Skip to content

refactor: overhaul task executor with layered architecture and comprehensive test suite - #15471

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
xugangqiang:refactor/task-executor-overhaul
Jun 3, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
xugangqiang:refactor/task-executor-overhaul

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Decomposes the monolithic task_executor.py (1945 lines) into a 6-layer architecture with clear separation of concerns. The refactored code is functionally equivalent to the original, verified through 400 passing tests and a production-vs-dry-run comparison framework.

Architecture

entry (task_manager)
  └─ orchestration (task_handler)
       ├─ services (chunk_service, embedding_service, dataflow_service, raptor_service, post_processor)
       │    └─ utilities (chunk_builder, chunk_post_processor, embedding_utils)
       └─ infrastructure (task_context, recording_context, interceptor)

Key design decisions:

  • TaskContext — typed facade over raw task dict, injects rate limiters + callbacks via composition
  • RecordingContext + Comparator — enables side-by-side production vs dry-run execution for safe migration
  • NullRecordingContext — zero-allocation no-op for production, uses __slots__
  • WriteOperationInterceptor — FIFO replay of previous runs function returns for comparison mode

Migration Strategy

The original handle_task() in task_executor.py uses a 3-way switch via TE_RUN_MODE:

  • TE_RUN_MODE=0 (default) → runs refactored code
  • TE_RUN_MODE=1 → runs both original + refactored, compares all intermediate results
  • TE_RUN_MODE=2 → runs original code (fallback)

The comparison mode (TE_RUN_MODE=1) records ~40 intermediate values (chunks, vectors, token counts, func return values) from the production run and replays them during dry-run, then uses ContextComparator to report mismatches.

Functional Equivalence Fixes

All divergences between original and refactored code were identified and fixed:

  • Timeout decorators (handle/build_chunks/raptor/embedding)
  • NullRecordingContext leak in finally block causing RuntimeError
  • MinIO None-binary check with proper FileNotFoundError
  • Dataflow dispatch after embedding binding + init_kb
  • Memory task missing return after processing
  • RAPTOR checkpoint progress reporting
  • Tag cache (get_tags_from_cache/set_tags_to_cache) restoration
  • dataflow_id correction in _load_dsl
  • Language default Chinese, dead code guard removal
  • embed_chunks made async with proper thread_pool_exec
  • Full GraphRAG default configuration (10 parameters)
  • Hardcoded q_768_vec fallback removal in RAPTOR

Test Changes

  • 20 new tests covering table parser manual mode, tag cache, embedding edge cases, RAPTOR checkpoint, dataflow_id correction, storage binary None, cancel cleanup, metadata=None boundary
  • Unified make_task_context/make_task_dict factories eliminated 10+ duplicated helpers
  • DataflowService tests migrated from internal method mocks to IO boundary mocks (real orchestration code executes)
  • Parametrized duplicate build_chunks post-processor tests
  • 7 raptor tests modernized to @pytest.mark.asyncio
  • Mock count per test reduced through boundary-level mocking strategy

Test count: 400 passing, 0 warnings, 0 skips

Files Changed

File Change
rag/svr/task_executor.py +1 line (NullRecordingContext fix)
rag/svr/task_executor_refactor/task_handler.py Orchestration layer, 8 logic fixes
rag/svr/task_executor_refactor/chunk_service.py +timeout + None-check
rag/svr/task_executor_refactor/embedding_service.py sync→async rewrite
rag/svr/task_executor_refactor/dataflow_service.py dataflow_id fix + timeout
rag/svr/task_executor_refactor/raptor_service.py checkpoint fix + assert
rag/svr/task_executor_refactor/chunk_post_processor.py tag cache restore
rag/svr/task_executor_refactor/task_context.py language default fix
test/.../conftest.py +294 lines shared helpers
test/.../*.py 15 test files refactored, 20 new tests

…hensive test suite

Architecture changes:
- Monolithic task_executor.py (1945 lines) decomposed into 6-layer architecture
  with clear separation of concerns and unidirectional dependencies
- New modules: task_handler (orchestration), chunk_service, embedding_service,
  dataflow_service, raptor_service, post_processor
- TaskContext encapsulates raw task dict, rate limiters, and callbacks via
  composition - all downstream services accept only TaskContext
- RecordingContext + Comparator enables production vs dry-run comparison for
  safe migration (TE_RUN_MODE=1)

Functional equivalence fixes:
- Added missing @timeout decorators on handle/build_chunks/raptor/embedding
- Fixed NullRecordingContext leak causing RuntimeError in finally block
- Added MinIO None-binary check with proper FileNotFoundError message
- Moved dataflow dispatch after embedding binding + init_kb (matching original)
- Added missing return after memory task in handle()
- Moved progress_cb/continue to outer if block in RAPTOR checkpoint
- Restored tag cache (get_tags_from_cache/set_tags_to_cache) in apply_tags
- Fixed dataflow_id correction in _load_dsl
- Changed language default from en to Chinese, removed dead code guard
- Made embed_chunks async with proper thread_pool_exec pattern
- Restored full GraphRAG default configuration (10 parameters)
- Added assert for empty chunks in RAPTOR _generate_raptor, removed dead
  hardcoded q_768_vec fallback

Test infrastructure:
- Unified make_task_context/make_task_dict factories in conftest, eliminated
  10+ duplicated _create_mock_context helpers across test files
- Added patch_embedding_binding, patch_pipeline_mocks context managers
- Extracted mock_thread_return_binary/mock_thread_return_none, eliminated
  15 inline mock_thread_impl definitions
- Consolidated 8 _create_*_task_dict definitions into make_task_dict

Test quality:
- 20 new tests: table parser manual mode, tag cache hit/miss,
  embedding edge cases, RAPTOR checkpoint progress, dataflow_id correction,
  storage binary None, cancel cleanup, metadata=None
- DataflowService tests migrated from internal method mocks to IO boundary
  mocks - _insert_chunks/_update_document_metadata/_record_pipeline_log now
  execute real code against mocked dependencies
- Parametrized 4 duplicate build_chunks post-processor tests
- Migrated 7 raptor tests from manual asyncio.new_event_loop to
  @pytest.mark.asyncio + await
- Flattened nested with blocks in dataflow_service tests
- Removed dead code (unused AsyncMock, empty with block)

All 400 tests pass with no warnings or skips.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code 🌈 python Pull requests that update Python code 🧪 test Pull requests that update test cases. labels Jun 1, 2026
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Converts EmbeddingService to async with thread-pool encoding, adds timeout decorators across chunking/dataflow/RAPTOR/handler, refactors TaskHandler orchestration and embedding binding, adds tag caching and DSL id correction, switches recording context for refactored executor, and consolidates test factories and many tests to async/shared helpers.

Changes

Task Executor Refactor and Async Embedding

Layer / File(s) Summary
Documentation
CLAUDE.md
Rewrote repository architecture doc with process- and component-level guidance.
Chunk service timeouts
rag/svr/task_executor_refactor/chunk_service.py
Import and apply timeout to build_chunks and per-upload upload_to_minio.
Async Embedding Service Implementation
rag/svr/task_executor_refactor/embedding_service.py
Converted embed_chunks to async def, moved encode calls into thread_pool_exec guarded by embed_limiter, added _batch_encode_wrapper, and removed prior sync helpers.
RAPTOR changes
rag/svr/task_executor_refactor/raptor_service.py
Applied @timeout(3600) to run_raptor_for_kb, assert non-empty chunks in _generate_raptor, and derive vector field from first chunk.
TaskContext default
rag/svr/task_executor_refactor/task_context.py
Changed default language fallback to "Chinese".
Recording context switch
rag/svr/task_executor.py
Set NullRecordingContext() for the refactored TE_RUN_MODE branch before running refactored executor.
Dataflow DSL & embedding timeout
rag/svr/task_executor_refactor/dataflow_service.py
_load_dsl returns (dsl, corrected_dataflow_id); run_dataflow uses corrected id and _embed_chunks is decorated with @timeout(60).
TaskHandler orchestration & binding
rag/svr/task_executor_refactor/task_handler.py
handle() decorated with 3-hour timeout, flow reordered (early cancel → bind embedding → init_kb → route), _bind_embedding_model returns (model, vector_size), GraphRAG defaults expanded, raise FileNotFoundError when storage binary missing, and unpack awaited embed_chunks results.
Chunk post-processor caching
rag/svr/task_executor_refactor/chunk_post_processor.py
Memoize all_tags via get_tags_from_cache/set_tags_to_cache and parse cached JSON on hits.
Test infrastructure (shared factories & patches)
test/unit_test/rag/svr/task_executor_refactor/conftest.py
Added make_task_context, make_task_dict, patch_embedding_binding, mock_thread_return_binary/none, patch_pipeline_mocks, and increased MockChatModel.max_length.
Tests: chunking, post-processing, embedding, raptor, dataflow, handler
test/unit_test/rag/svr/task_executor_refactor/*
Refactored many tests to use shared factories, converted suites to async where required, consolidated redundant tests into parameterized ones, added table-parser metadata/write_interceptor tests, and updated embedding/raptor tests to patch thread_pool_exec.

Sequence Diagram(s):

sequenceDiagram
  participant Caller
  participant TaskHandler
  participant TaskContext
  participant EmbeddingService
  participant ThreadPool
  participant EmbeddingModel
  Caller->>TaskHandler: invoke handle(task)
  TaskHandler->>TaskContext: bind embedding & check cancel
  TaskHandler->>EmbeddingService: await embed_chunks(docs)
  EmbeddingService->>TaskContext: acquire embed_limiter
  EmbeddingService->>ThreadPool: thread_pool_exec(_batch_encode_wrapper, txts, model)
  ThreadPool->>EmbeddingModel: encode(txts)
  EmbeddingModel-->>ThreadPool: vectors
  ThreadPool-->>EmbeddingService: vectors
  EmbeddingService-->>TaskHandler: (token_count, vector_size)
  TaskHandler->>TaskHandler: route to dataflow/chunking/raptor/graphrag
  TaskHandler-->>Caller: result/status
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

python

Suggested reviewers

  • yuzhichang
  • KevinHuSh

"🐰 I hopped through awaits and thread pools bright,
I wrapped long runs with timeouts tight,
I cached the tags to speed the race,
Tests now share a common place,
Async pipelines hum through the night."

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 79.75% 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 pull request title clearly summarizes the main change: refactoring the task executor with a new layered architecture and comprehensive test suite.
Description check ✅ Passed The pull request description is comprehensive and well-structured, covering the problem statement, architecture overview, migration strategy, functional equivalence fixes, test changes, and file changes.
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.

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

- Accept upstream rename get_model_config_by_type_and_name →
  get_model_config_from_provider_instance in production code
- Keep test refactoring (make_task_context, parametrized tests, etc.)
- Revert docker/.env and uv.lock changes

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py (1)

40-177: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Tag the new pytest coverage with priority markers.

The added/modified async tests are missing the required p1/p2/p3 markers, so they won’t participate cleanly in priority-based test selection.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

Also applies to: 358-397

🤖 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_dataflow_service.py`
around lines 40 - 177, Add the required pytest priority markers to each new
async test so they participate in priority-based selection: decorate
test_run_dataflow_dsl_not_found, test_run_dataflow_empty_chunks,
test_run_dataflow_with_output_type, test_run_dataflow_embedding_failure, and
test_run_dataflow_with_billing_hook_success with the appropriate marker (e.g.,
`@pytest.mark.p1` or the project’s chosen p2/p3) placed above the existing
`@pytest.mark.asyncio` decorator (for parametrized tests keep the marker alongside
`@pytest.mark.parametrize`), ensuring all five test functions include a priority
marker.
test/unit_test/rag/svr/task_executor_refactor/test_chunk_service.py (1)

49-125: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add p1/p2/p3 markers to the touched pytest cases.

These updated tests use pytest, but the new/modified cases are still unclassified. Please add the repo’s priority markers so they can be selected consistently in CI.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

Also applies to: 131-248

🤖 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_chunk_service.py` around
lines 49 - 125, The three pytest cases (test_build_chunks_file_size_exceeded,
test_build_chunks_file_size_ok, test_build_chunks_with_post_processing) lack the
repo priority markers; add the appropriate pytest priority marker decorator
(e.g., `@pytest.mark.p1`) above each test definition so CI can select them
consistently (place the decorator immediately above each async def). Ensure
imports/pytest usage remain unchanged and use `@pytest.mark.p1` (or p2/p3 per repo
classification) for each of these test functions.
rag/svr/task_executor_refactor/task_context.py (1)

217-227: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep the default language in the same format as the documented contract.

TaskContext.language is still documented as code-style values like 'en' / 'zh', but the new fallback returns "Chinese". That silently changes the value shape for every task missing language, which can break downstream checks or mappings that expect a locale/code rather than a display name.

💡 Proposed fix
-        "language": "Chinese",
+        "language": "zh",
🤖 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/task_context.py` around lines 217 - 227, The
default language value in the TaskContext defaults dict (_DEFAULTS) uses
"Chinese" which breaks the documented contract expecting code-style locales;
update the "language" entry in _DEFAULTS to the correct code-format value (e.g.,
"zh" or whatever the contract specifies) so TaskContext.language retains the
same shape for missing languages and downstream consumers continue to receive a
locale code.
rag/svr/task_executor_refactor/task_handler.py (2)

341-364: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Backfill new GraphRAG defaults into existing enabled configs.

This only seeds defaults when use_graphrag is false or missing. Existing KBs that already have use_graphrag=True but lack the newly added timeout/retry keys will skip this block entirely, so older parser configs won't receive the migration this PR introduces.

Suggested fix
-        kb_parser_config = kb.parser_config
-        if not kb_parser_config.get("graphrag", {}).get("use_graphrag", False):
-            kb_parser_config.update({
-                "graphrag": {
-                    "use_graphrag": True,
-                    "entity_types": [
-                        "organization",
-                        "person",
-                        "geo",
-                        "event",
-                        "category",
-                    ],
-                    "method": "light",
-                    "batch_chunk_token_size": 4096,
-                    "retry_attempts": 2,
-                    "retry_backoff_seconds": 2.0,
-                    "retry_backoff_max_seconds": 60.0,
-                    "build_subgraph_timeout_per_chunk_seconds": 300,
-                    "build_subgraph_min_timeout_seconds": 600,
-                    "merge_timeout_seconds": 180,
-                    "resolution_timeout_seconds": 1800,
-                    "community_timeout_seconds": 1800,
-                    "lock_acquire_timeout_seconds": 600,
-                }
-            })
+        kb_parser_config = kb.parser_config
+        graphrag_defaults = {
+            "use_graphrag": True,
+            "entity_types": ["organization", "person", "geo", "event", "category"],
+            "method": "light",
+            "batch_chunk_token_size": 4096,
+            "retry_attempts": 2,
+            "retry_backoff_seconds": 2.0,
+            "retry_backoff_max_seconds": 60.0,
+            "build_subgraph_timeout_per_chunk_seconds": 300,
+            "build_subgraph_min_timeout_seconds": 600,
+            "merge_timeout_seconds": 180,
+            "resolution_timeout_seconds": 1800,
+            "community_timeout_seconds": 1800,
+            "lock_acquire_timeout_seconds": 600,
+        }
+        merged_graphrag_config = {
+            **graphrag_defaults,
+            **kb_parser_config.get("graphrag", {}),
+        }
+        if merged_graphrag_config != kb_parser_config.get("graphrag", {}):
+            kb_parser_config.update({"graphrag": merged_graphrag_config})
             if ctx.write_interceptor:
                 update_result = ctx.write_interceptor.intercept("KnowledgebaseService.update_by_id")
             else:
                 update_result = KnowledgebaseService.update_by_id(kb.id, {"parser_config": kb_parser_config})
🤖 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/task_handler.py` around lines 341 - 364, The
current block only seeds GraphRAG defaults when kb_parser_config.get("graphrag",
{}).get("use_graphrag", False) is False, so configs that already have
use_graphrag=True won't receive newly added timeout/retry keys; update the logic
around kb_parser_config (the "graphrag" dict) to merge defaults into the
existing kb_parser_config["graphrag"] whenever use_graphrag is True or missing,
using a non-destructive merge (e.g., iterate over the default keys and set them
only if they are absent) so existing explicit values are preserved while adding
the new retry/backoff/timeout defaults like retry_attempts,
retry_backoff_seconds, build_subgraph_timeout_per_chunk_seconds, etc.

204-226: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid blocking the event loop in _bind_embedding_model embedding probe (rag/svr/task_executor_refactor/task_handler.py ~204-226)

_bind_embedding_model() is async, but it calls LLMBundle.encode(["ok"]) synchronously inline; LLMBundle.encode is a non-async def in api/db/services/llm_service.py. Offload the encode(["ok"]) probe to the existing thread-pool helper (used elsewhere for embedding batch encoding) so the event loop isn’t stalled; keep any ctx.embed_limiter throttling on the same offloaded path.

🤖 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/task_handler.py` around lines 204 - 226, The
_bind_embedding_model async function currently calls the synchronous
LLMBundle.encode(["ok"]) inline and will block the event loop; modify
_bind_embedding_model to offload the embedding probe to the project’s
thread-pool helper (the same helper used for batch embedding elsewhere) instead
of calling LLMBundle.encode directly, and ensure any ctx.embed_limiter
throttling is applied around/inside that offloaded call so the limiter is
honored on the worker thread; keep the existing model lookup logic
(get_model_config_by_type_and_name / get_tenant_default_model_by_type) and
LLMBundle instantiation, await the limiter if required, run
LLMBundle.encode(["ok"]) in the executor, extract vts and return
(embedding_model, len(vts[0])) as before.
🧹 Nitpick comments (9)
test/unit_test/rag/svr/task_executor_refactor/test_comparator.py (1)

141-142: 💤 Low value

Class name no longer matches scope.

TestContextComparatorCompareValue now tests both initialization and the compare_value method. Consider renaming to TestContextComparator for clarity, or keeping initialization tests in a separate class.

🤖 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_comparator.py` around
lines 141 - 142, The test class TestContextComparatorCompareValue name is
misleading because it covers both initialization and compare_value behavior;
rename the class to TestContextComparator (or split initialization tests into a
separate class) and update any references/imports accordingly so the class name
matches its scope and tests for both __init__ and compare_value methods.
rag/svr/task_executor_refactor/embedding_service.py (1)

58-117: ⚡ Quick win

Add logging around the new async embedding path.

This method now owns a new control flow boundary (embed_limiter + thread_pool_exec) but provides no breadcrumbs when a batch fails or stalls. Please add structured logs for task/chunk counts and batch failures so production incidents can be diagnosed from executor logs.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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/embedding_service.py` around lines 58 - 117,
Add structured logging around the new async embedding flow in embed_chunks: log
when entering and exiting the embed limiter (self._task_context.embed_limiter)
and include total docs count and batch size; log per-batch start/finish with
batch index and number of items, and call progress_cb as before; wrap the
thread_pool_exec calls (both titles and content batches) in try/except and log
failures with the batch index, any doc identifiers (from docs), and the
exception details before re-raising; also log the final token count and
vector_size returned by EmbeddingUtils.attach_vectors so executor logs show
task/chunk counts and outcomes.
test/unit_test/rag/svr/task_executor_refactor/test_task_context.py (1)

218-222: ⚡ Quick win

Mark this pytest case with a test priority.

This updated test still needs a p1/p2/p3 marker to match the backend test policy.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

🤖 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_task_context.py` around
lines 218 - 222, The test function test_language_default in this file needs a
pytest priority marker; add the appropriate marker (e.g., `@pytest.mark.p1` or
`@pytest.mark.p2/p3` per policy) directly above the test_language_default
definition and ensure pytest is imported (add "import pytest" at top if
missing); leave the test body and helper call (_make_ctx) unchanged so only the
marker and import are added.
test/unit_test/rag/svr/task_executor_refactor/test_chunk_post_processor.py (1)

42-57: ⚡ Quick win

Tag the new pytest coverage with test priorities.

The refactor keeps everything on pytest, but the added/updated cases still need p1/p2/p3 markers so they follow the backend test selection conventions.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

Also applies to: 63-297

🤖 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_chunk_post_processor.py`
around lines 42 - 57, Update the new/modified pytest tests to include the
backend test priority markers (p1/p2/p3) per convention: add the appropriate
pytest marker decorator (e.g., `@pytest.mark.p1` or
`@pytest.mark.p2/`@pytest.mark.p3) to the test classes or functions that live
under test/unit_test/rag/svr/task_executor_refactor/, and ensure any new helper
classes like _BasePostProcessorTest and its helpers (_mock_llm_binding,
_patch_prompt_func) are used by marked test cases so the test selection honors
the priority markers; apply the same marking pattern across the affected range
of tests (lines ~63-297) so all updated/added test cases follow the backend
priority convention.
test/unit_test/rag/svr/task_executor_refactor/test_chunk_builder.py (1)

53-95: ⚡ Quick win

Add p1/p2/p3 markers to the new pytest cases.

These refactored tests use pytest, but the new cases still lack the required priority markers, which makes them harder to target in CI/test selection.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

Also applies to: 101-163

🤖 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_chunk_builder.py` around
lines 53 - 95, Add the required pytest priority markers to the three new tests
by decorating test_run_chunking_success, test_run_chunking_with_parser_config,
and test_run_chunking_exception with the appropriate priority marker (e.g.,
`@pytest.mark.p1`) placed immediately above each async test definition; ensure
pytest is imported and use `@pytest.mark.p1/`@pytest.mark.p2/@pytest.mark.p3 as
your CI policy requires for these specific cases.
test/unit_test/rag/svr/task_executor_refactor/test_raptor_service.py (1)

220-392: ⚡ Quick win

Add backend priority markers to these async pytest tests.

The converted async cases and the new checkpoint test should carry p1/p2/p3 markers to stay consistent with the repository’s pytest conventions.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

Also applies to: 395-449

🤖 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_raptor_service.py` around
lines 220 - 392, These async pytest cases lack backend priority markers; add the
appropriate pytest markers (e.g., `@pytest.mark.p1` or
`@pytest.mark.p2/`@pytest.mark.p3 as per test importance) to each async test
function in this diff (examples:
test_run_raptor_for_kb_file_scope_delegates_to_file_level,
test_run_raptor_for_kb_dataset_scope_delegates_to_dataset_level,
test_run_raptor_for_kb_empty_doc_ids,
test_run_raptor_for_kb_returns_cleanup_list,
test_run_raptor_for_kb_defaults_to_file_scope_when_no_raptor_key,
test_run_raptor_for_kb_passes_vector_size_to_file_level,
test_run_raptor_for_kb_collects_doc_info) by adding the marker decorator
directly above the existing `@pytest.mark.asyncio` decorator for each test; apply
the same convention to the subsequent tests referenced in the comment (the block
around 395-449).
test/unit_test/rag/svr/task_executor_refactor/test_task_handler_integration.py (2)

800-857: ⚡ Quick win

Assert that the GraphRAG runner is actually invoked.

This test only checks the config passed to update_by_id(). It still passes if handle() stops after persisting defaults and never awaits run_graphrag_for_kb(), which is the main contract of this path.

Suggested assertion
             handler = TaskHandler(ctx=ctx)
             await handler.handle()
 
             # Verify update_by_id was called with full default config
             mock_kb_service.update_by_id.assert_called_once()
+            mock_run_graphrag.assert_awaited_once()
             call_args = mock_kb_service.update_by_id.call_args
             config = call_args[0][1]["parser_config"]["graphrag"]
🤖 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_task_handler_integration.py`
around lines 800 - 857, The test currently only asserts defaults saved via
KnowledgebaseService.update_by_id but doesn't verify the GraphRAG runner was
executed; after invoking TaskHandler.handle(), add an assertion that
run_graphrag_for_kb (mock_run_graphrag) was called (e.g.,
mock_run_graphrag.assert_called_once() or assert_called_once_with expected args)
to ensure TaskHandler.handle() proceeds to invoke run_graphrag_for_kb; reference
TaskHandler.handle, run_graphrag_for_kb, and the mock object mock_run_graphrag
when adding this assertion.

90-92: ⚡ Quick win

Turn the prose priorities into real pytest markers.

The P0/P1/P2 labels in docstrings don't help suite selection. Add @pytest.mark.p1/p2/p3 on these classes so the backend test split can target them consistently.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

Also applies to: 312-313, 415-417, 506-507, 546-547, 580-581, 705-706, 797-798

🤖 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_task_handler_integration.py`
around lines 90 - 92, The class docstring priority labels (e.g. "P0" in class
TestStandardChunkingPipelineIntegration) must be converted into pytest markers
so tests can be selected by priority; locate each test class whose docstring
contains "P0"/"P1"/"P2" (including TestStandardChunkingPipelineIntegration and
the other classes called out) and add the corresponding decorator
`@pytest.mark.p1` for P0, `@pytest.mark.p2` for P1, and `@pytest.mark.p3` for P2
immediately above the class definition, ensuring to import pytest if not already
imported.
test/unit_test/rag/svr/task_executor_refactor/test_task_handler.py (1)

43-319: ⚡ Quick win

Add pytest priority markers to the new unit tests.

These cases are now part of the orchestration coverage, but they still can't be selected via pytest -m because the priority only exists in comments/docstrings. Please add @pytest.mark.p1/p2/p3 at the class or test level.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

🤖 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_task_handler.py` around
lines 43 - 319, Add pytest priority markers so these tests can be selected via
-m: annotate the test classes or individual test functions with `@pytest.mark.p1`
/ `@pytest.mark.p2` / `@pytest.mark.p3` as appropriate; specifically add markers to
TestTaskHandlerHandleTask, TestTaskHandlerHandle, TestTaskHandlerBuildToc, and
TestTaskHandlerInit (or to their individual test_* methods) so pytest can filter
them by priority.
🤖 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.

Inline comments:
In `@rag/svr/task_executor_refactor/chunk_post_processor.py`:
- Around line 246-251: The tag-loading branch in apply_tags currently doesn't
log whether tags came from cache or were fetched, so add logging around
get_tags_from_cache(kb_ids) and the fallback
settings.retriever.all_tags_in_portion(tenant_id, kb_ids, S) +
set_tags_to_cache(kb_ids, all_tags): emit a debug/info log on cache hit (parsing
json and count of tags) and on cache miss (how many tags were loaded), include
identifying context like tenant_id and kb_ids in the message to help diagnose
stale-cache/invalidation issues.

In `@rag/svr/task_executor_refactor/dataflow_service.py`:
- Around line 106-109: Detect when _load_dsl returns a corrected_id different
from the requested dataflow_id and emit a clear debug/info log before replacing
the id and constructing Pipeline or persisting pipeline logs: log the original
dataflow_id and the corrected_id along with identifying context (e.g., pipeline
name or caller) so cross-service mismatches can be traced; apply the same change
at the other occurrence that uses _load_dsl (the block that then calls
Pipeline(...) and persists pipeline_log.pipeline_id). Use the service logger
(e.g., self.logger or the module logger) and include both IDs and a brief
message indicating the ID was corrected.

In `@test/unit_test/rag/svr/task_executor_refactor/conftest.py`:
- Around line 486-510: Update the test helpers so their default language matches
the new production default: change the "language" value from "en" to "zh" in the
shared defaults dict used by make_task_context() and make_task_dict(), and
ensure any other defaults blocks in the same file (the other occurrence
referenced around make_task_context/make_task_dict) are also updated to "zh" so
tests cannot accidentally bypass the new contract.
- Around line 521-535: The test fixture should assign ctx.raw_task to a real
dict rather than a MagicMock so code under test fails on missing keys; replace
the line setting ctx.raw_task with code that builds a plain dict (e.g., start
from a minimal/default task dict representing required TaskContext fields) and
then apply any relevant overrides from the overrides mapping to that dict before
assigning it to ctx.raw_task; keep the AsyncMockLimiter assignments
(chunk_limiter, chat_limiter, embed_limiter, kg_limiter, minio_limiter)
unchanged and ensure the same override loop updates both ctx attributes and keys
inside ctx.raw_task when appropriate.

In `@test/unit_test/rag/svr/task_executor_refactor/test_embedding_service.py`:
- Around line 63-260: Add the required pytest priority markers (p1/p2/p3) to
these new async tests so they are picked up by backend test-selection; for
example, decorate either the test class or each test function (e.g.,
test_embed_chunks_basic, test_embed_chunks_uses_embedding_utils,
test_embed_chunks_with_title_content_combination, etc.) with `@pytest.mark.p1` (or
the appropriate priority) or add `@pytest.mark.p2/`@pytest.mark.p3 as per test
importance; ensure the import of pytest.mark is present and apply the marker
consistently across all tests in this file so they adhere to the test-selection
policy.

In `@test/unit_test/rag/svr/task_executor_refactor/test_post_processor.py`:
- Around line 63-113: The two new async tests lack priority markers; add the
repo's pytest priority decorator (e.g., `@pytest.mark.p1`) to both test functions
test_processes_table_parser_manual_mode and
test_processes_table_parser_with_write_interceptor (place the decorator above
the existing `@pytest.mark.asyncio`), and ensure pytest is imported in the module
if not already so the p1 marker resolves.

---

Outside diff comments:
In `@rag/svr/task_executor_refactor/task_context.py`:
- Around line 217-227: The default language value in the TaskContext defaults
dict (_DEFAULTS) uses "Chinese" which breaks the documented contract expecting
code-style locales; update the "language" entry in _DEFAULTS to the correct
code-format value (e.g., "zh" or whatever the contract specifies) so
TaskContext.language retains the same shape for missing languages and downstream
consumers continue to receive a locale code.

In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 341-364: The current block only seeds GraphRAG defaults when
kb_parser_config.get("graphrag", {}).get("use_graphrag", False) is False, so
configs that already have use_graphrag=True won't receive newly added
timeout/retry keys; update the logic around kb_parser_config (the "graphrag"
dict) to merge defaults into the existing kb_parser_config["graphrag"] whenever
use_graphrag is True or missing, using a non-destructive merge (e.g., iterate
over the default keys and set them only if they are absent) so existing explicit
values are preserved while adding the new retry/backoff/timeout defaults like
retry_attempts, retry_backoff_seconds, build_subgraph_timeout_per_chunk_seconds,
etc.
- Around line 204-226: The _bind_embedding_model async function currently calls
the synchronous LLMBundle.encode(["ok"]) inline and will block the event loop;
modify _bind_embedding_model to offload the embedding probe to the project’s
thread-pool helper (the same helper used for batch embedding elsewhere) instead
of calling LLMBundle.encode directly, and ensure any ctx.embed_limiter
throttling is applied around/inside that offloaded call so the limiter is
honored on the worker thread; keep the existing model lookup logic
(get_model_config_by_type_and_name / get_tenant_default_model_by_type) and
LLMBundle instantiation, await the limiter if required, run
LLMBundle.encode(["ok"]) in the executor, extract vts and return
(embedding_model, len(vts[0])) as before.

In `@test/unit_test/rag/svr/task_executor_refactor/test_chunk_service.py`:
- Around line 49-125: The three pytest cases
(test_build_chunks_file_size_exceeded, test_build_chunks_file_size_ok,
test_build_chunks_with_post_processing) lack the repo priority markers; add the
appropriate pytest priority marker decorator (e.g., `@pytest.mark.p1`) above each
test definition so CI can select them consistently (place the decorator
immediately above each async def). Ensure imports/pytest usage remain unchanged
and use `@pytest.mark.p1` (or p2/p3 per repo classification) for each of these
test functions.

In `@test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py`:
- Around line 40-177: Add the required pytest priority markers to each new async
test so they participate in priority-based selection: decorate
test_run_dataflow_dsl_not_found, test_run_dataflow_empty_chunks,
test_run_dataflow_with_output_type, test_run_dataflow_embedding_failure, and
test_run_dataflow_with_billing_hook_success with the appropriate marker (e.g.,
`@pytest.mark.p1` or the project’s chosen p2/p3) placed above the existing
`@pytest.mark.asyncio` decorator (for parametrized tests keep the marker alongside
`@pytest.mark.parametrize`), ensuring all five test functions include a priority
marker.

---

Nitpick comments:
In `@rag/svr/task_executor_refactor/embedding_service.py`:
- Around line 58-117: Add structured logging around the new async embedding flow
in embed_chunks: log when entering and exiting the embed limiter
(self._task_context.embed_limiter) and include total docs count and batch size;
log per-batch start/finish with batch index and number of items, and call
progress_cb as before; wrap the thread_pool_exec calls (both titles and content
batches) in try/except and log failures with the batch index, any doc
identifiers (from docs), and the exception details before re-raising; also log
the final token count and vector_size returned by EmbeddingUtils.attach_vectors
so executor logs show task/chunk counts and outcomes.

In `@test/unit_test/rag/svr/task_executor_refactor/test_chunk_builder.py`:
- Around line 53-95: Add the required pytest priority markers to the three new
tests by decorating test_run_chunking_success,
test_run_chunking_with_parser_config, and test_run_chunking_exception with the
appropriate priority marker (e.g., `@pytest.mark.p1`) placed immediately above
each async test definition; ensure pytest is imported and use
`@pytest.mark.p1/`@pytest.mark.p2/@pytest.mark.p3 as your CI policy requires for
these specific cases.

In `@test/unit_test/rag/svr/task_executor_refactor/test_chunk_post_processor.py`:
- Around line 42-57: Update the new/modified pytest tests to include the backend
test priority markers (p1/p2/p3) per convention: add the appropriate pytest
marker decorator (e.g., `@pytest.mark.p1` or `@pytest.mark.p2/`@pytest.mark.p3) to
the test classes or functions that live under
test/unit_test/rag/svr/task_executor_refactor/, and ensure any new helper
classes like _BasePostProcessorTest and its helpers (_mock_llm_binding,
_patch_prompt_func) are used by marked test cases so the test selection honors
the priority markers; apply the same marking pattern across the affected range
of tests (lines ~63-297) so all updated/added test cases follow the backend
priority convention.

In `@test/unit_test/rag/svr/task_executor_refactor/test_comparator.py`:
- Around line 141-142: The test class TestContextComparatorCompareValue name is
misleading because it covers both initialization and compare_value behavior;
rename the class to TestContextComparator (or split initialization tests into a
separate class) and update any references/imports accordingly so the class name
matches its scope and tests for both __init__ and compare_value methods.

In `@test/unit_test/rag/svr/task_executor_refactor/test_raptor_service.py`:
- Around line 220-392: These async pytest cases lack backend priority markers;
add the appropriate pytest markers (e.g., `@pytest.mark.p1` or
`@pytest.mark.p2/`@pytest.mark.p3 as per test importance) to each async test
function in this diff (examples:
test_run_raptor_for_kb_file_scope_delegates_to_file_level,
test_run_raptor_for_kb_dataset_scope_delegates_to_dataset_level,
test_run_raptor_for_kb_empty_doc_ids,
test_run_raptor_for_kb_returns_cleanup_list,
test_run_raptor_for_kb_defaults_to_file_scope_when_no_raptor_key,
test_run_raptor_for_kb_passes_vector_size_to_file_level,
test_run_raptor_for_kb_collects_doc_info) by adding the marker decorator
directly above the existing `@pytest.mark.asyncio` decorator for each test; apply
the same convention to the subsequent tests referenced in the comment (the block
around 395-449).

In `@test/unit_test/rag/svr/task_executor_refactor/test_task_context.py`:
- Around line 218-222: The test function test_language_default in this file
needs a pytest priority marker; add the appropriate marker (e.g.,
`@pytest.mark.p1` or `@pytest.mark.p2/p3` per policy) directly above the
test_language_default definition and ensure pytest is imported (add "import
pytest" at top if missing); leave the test body and helper call (_make_ctx)
unchanged so only the marker and import are added.

In
`@test/unit_test/rag/svr/task_executor_refactor/test_task_handler_integration.py`:
- Around line 800-857: The test currently only asserts defaults saved via
KnowledgebaseService.update_by_id but doesn't verify the GraphRAG runner was
executed; after invoking TaskHandler.handle(), add an assertion that
run_graphrag_for_kb (mock_run_graphrag) was called (e.g.,
mock_run_graphrag.assert_called_once() or assert_called_once_with expected args)
to ensure TaskHandler.handle() proceeds to invoke run_graphrag_for_kb; reference
TaskHandler.handle, run_graphrag_for_kb, and the mock object mock_run_graphrag
when adding this assertion.
- Around line 90-92: The class docstring priority labels (e.g. "P0" in class
TestStandardChunkingPipelineIntegration) must be converted into pytest markers
so tests can be selected by priority; locate each test class whose docstring
contains "P0"/"P1"/"P2" (including TestStandardChunkingPipelineIntegration and
the other classes called out) and add the corresponding decorator
`@pytest.mark.p1` for P0, `@pytest.mark.p2` for P1, and `@pytest.mark.p3` for P2
immediately above the class definition, ensuring to import pytest if not already
imported.

In `@test/unit_test/rag/svr/task_executor_refactor/test_task_handler.py`:
- Around line 43-319: Add pytest priority markers so these tests can be selected
via -m: annotate the test classes or individual test functions with
`@pytest.mark.p1` / `@pytest.mark.p2` / `@pytest.mark.p3` as appropriate; specifically
add markers to TestTaskHandlerHandleTask, TestTaskHandlerHandle,
TestTaskHandlerBuildToc, and TestTaskHandlerInit (or to their individual test_*
methods) so pytest can filter them by priority.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0216fa77-a672-47ea-8620-8122e07affa4

📥 Commits

Reviewing files that changed from the base of the PR and between 10e8690 and 1453aec.

⛔ Files ignored due to path filters (1)
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (22)
  • CLAUDE.md
  • docker/.env
  • rag/svr/task_executor.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py
  • rag/svr/task_executor_refactor/chunk_service.py
  • rag/svr/task_executor_refactor/dataflow_service.py
  • rag/svr/task_executor_refactor/embedding_service.py
  • rag/svr/task_executor_refactor/raptor_service.py
  • rag/svr/task_executor_refactor/task_context.py
  • rag/svr/task_executor_refactor/task_handler.py
  • test/unit_test/rag/svr/task_executor_refactor/conftest.py
  • test/unit_test/rag/svr/task_executor_refactor/test_chunk_builder.py
  • test/unit_test/rag/svr/task_executor_refactor/test_chunk_post_processor.py
  • test/unit_test/rag/svr/task_executor_refactor/test_chunk_service.py
  • test/unit_test/rag/svr/task_executor_refactor/test_comparator.py
  • test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py
  • test/unit_test/rag/svr/task_executor_refactor/test_embedding_service.py
  • test/unit_test/rag/svr/task_executor_refactor/test_post_processor.py
  • test/unit_test/rag/svr/task_executor_refactor/test_raptor_service.py
  • test/unit_test/rag/svr/task_executor_refactor/test_task_context.py
  • test/unit_test/rag/svr/task_executor_refactor/test_task_handler.py
  • test/unit_test/rag/svr/task_executor_refactor/test_task_handler_integration.py

Comment on lines +246 to +251
all_tags = get_tags_from_cache(kb_ids)
if not all_tags:
all_tags = settings.retriever.all_tags_in_portion(tenant_id, kb_ids, S)
set_tags_to_cache(kb_ids, all_tags)
else:
all_tags = json.loads(all_tags)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Log the tag-cache branch.

This introduces a new cache hit/miss path in apply_tags, but it stays silent. Please log whether tags came from cache or all_tags_in_portion(...) and how many were loaded; otherwise stale-tag/cache-invalidation issues will be hard to diagnose in production.

Suggested patch
     examples = []
     all_tags = get_tags_from_cache(kb_ids)
     if not all_tags:
+        logging.debug("apply_tags: cache miss for kb_ids=%s", kb_ids)
         all_tags = settings.retriever.all_tags_in_portion(tenant_id, kb_ids, S)
         set_tags_to_cache(kb_ids, all_tags)
     else:
         all_tags = json.loads(all_tags)
+        logging.debug("apply_tags: cache hit for kb_ids=%s, tag_count=%d", kb_ids, len(all_tags))

As per coding guidelines, **/*.py: Add logging for new flows.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
all_tags = get_tags_from_cache(kb_ids)
if not all_tags:
all_tags = settings.retriever.all_tags_in_portion(tenant_id, kb_ids, S)
set_tags_to_cache(kb_ids, all_tags)
else:
all_tags = json.loads(all_tags)
all_tags = get_tags_from_cache(kb_ids)
if not all_tags:
logging.debug("apply_tags: cache miss for kb_ids=%s", kb_ids)
all_tags = settings.retriever.all_tags_in_portion(tenant_id, kb_ids, S)
set_tags_to_cache(kb_ids, all_tags)
else:
all_tags = json.loads(all_tags)
logging.debug("apply_tags: cache hit for kb_ids=%s, tag_count=%d", kb_ids, len(all_tags))
🤖 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/chunk_post_processor.py` around lines 246 -
251, The tag-loading branch in apply_tags currently doesn't log whether tags
came from cache or were fetched, so add logging around
get_tags_from_cache(kb_ids) and the fallback
settings.retriever.all_tags_in_portion(tenant_id, kb_ids, S) +
set_tags_to_cache(kb_ids, all_tags): emit a debug/info log on cache hit (parsing
json and count of tags) and on cache miss (how many tags were loaded), include
identifying context like tenant_id and kb_ids in the message to help diagnose
stale-cache/invalidation issues.

Comment on lines +106 to +109
dsl, corrected_id = await self._load_dsl(dataflow_id)
if dsl is None:
return
dataflow_id = corrected_id

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Log when the pipeline ID is corrected.

The new _load_dsl() contract can silently replace the requested dataflow_id with pipeline_log.pipeline_id, and that corrected value is then used for Pipeline(...) and pipeline-log persistence. Please emit a log when the ID changes so cross-service mismatches can be traced.

Suggested patch
             dsl, corrected_id = await self._load_dsl(dataflow_id)
             if dsl is None:
                 return
+            if corrected_id != dataflow_id:
+                logging.info(
+                    "run_dataflow: remapped dataflow_id from %s to %s for task_type=%s",
+                    dataflow_id,
+                    corrected_id,
+                    ctx.task_type,
+                )
             dataflow_id = corrected_id

As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 198-214

🤖 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/dataflow_service.py` around lines 106 - 109,
Detect when _load_dsl returns a corrected_id different from the requested
dataflow_id and emit a clear debug/info log before replacing the id and
constructing Pipeline or persisting pipeline logs: log the original dataflow_id
and the corrected_id along with identifying context (e.g., pipeline name or
caller) so cross-service mismatches can be traced; apply the same change at the
other occurrence that uses _load_dsl (the block that then calls Pipeline(...)
and persists pipeline_log.pipeline_id). Use the service logger (e.g.,
self.logger or the module logger) and include both IDs and a brief message
indicating the ID was corrected.

Comment on lines +486 to +510
defaults = {
"id": "task_1",
"tenant_id": "tenant_1",
"kb_id": "kb_1",
"doc_id": "doc_1",
"name": "test.pdf",
"location": "/path/to/test.pdf",
"language": "en",
"parser_id": "naive",
"parser_config": {},
"kb_parser_config": {},
"llm_id": "llm_1",
"embd_id": "embd_1",
"from_page": 0,
"to_page": -1,
"size": 1000,
"pagerank": 0,
"task_type": "standard",
"dataflow_id": "",
"doc_ids": [],
"file": None,
"memory_id": "",
"source_id": "",
"message_dict": {},
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Align shared helper defaults with the new language default.

Both make_task_context() and make_task_dict() still default language to "en", but this PR changes the production default to Chinese. Keeping the old default here lets tests bypass the new contract and can keep regressions hidden unless every caller overrides language explicitly.

Also applies to: 645-674

🤖 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/conftest.py` around lines 486 -
510, Update the test helpers so their default language matches the new
production default: change the "language" value from "en" to "zh" in the shared
defaults dict used by make_task_context() and make_task_dict(), and ensure any
other defaults blocks in the same file (the other occurrence referenced around
make_task_context/make_task_dict) are also updated to "zh" so tests cannot
accidentally bypass the new contract.

Comment on lines +521 to +535
# Raw task dict — derive from context attributes
ctx.raw_task = MagicMock()

# Limiters — all use AsyncMockLimiter so services that acquire them work
limiter = AsyncMockLimiter()
ctx.chunk_limiter = limiter
ctx.chat_limiter = limiter
ctx.embed_limiter = limiter
ctx.kg_limiter = limiter
ctx.minio_limiter = limiter

# Apply remaining overrides
for k, v in overrides.items():
setattr(ctx, k, v)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Build raw_task as a real dict, not a MagicMock.

This shared factory is supposed to mimic TaskContext, but ctx.raw_task = MagicMock() means code under test can read arbitrary keys/attributes without failing, which can mask real branching bugs across the suite.

Suggested fix
-    # Raw task dict — derive from context attributes
-    ctx.raw_task = MagicMock()
-
     # Limiters — all use AsyncMockLimiter so services that acquire them work
     limiter = AsyncMockLimiter()
     ctx.chunk_limiter = limiter
     ctx.chat_limiter = limiter
     ctx.embed_limiter = limiter
@@
     # Apply remaining overrides
     for k, v in overrides.items():
         setattr(ctx, k, v)
+
+    # Raw task dict — derive from context attributes
+    ctx.raw_task = {k: getattr(ctx, k) for k in defaults}
🤖 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/conftest.py` around lines 521 -
535, The test fixture should assign ctx.raw_task to a real dict rather than a
MagicMock so code under test fails on missing keys; replace the line setting
ctx.raw_task with code that builds a plain dict (e.g., start from a
minimal/default task dict representing required TaskContext fields) and then
apply any relevant overrides from the overrides mapping to that dict before
assigning it to ctx.raw_task; keep the AsyncMockLimiter assignments
(chunk_limiter, chat_limiter, embed_limiter, kg_limiter, minio_limiter)
unchanged and ensure the same override loop updates both ctx attributes and keys
inside ctx.raw_task when appropriate.

Comment on lines +63 to +260
@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_basic(self, mock_thread_pool):
"""Test basic chunk embedding."""
mock_run_encode.return_value = (np.array([[1.0, 2.0]]), 10)
mock_thread_pool.return_value = (np.array([[1.0, 2.0]]), 10)
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx, embedding_batch_size=10)
model = MagicMock()
model.max_length = 100

docs = [
{"docnm_kwd": "Title1", "content_with_weight": "Content1"},
]
tk_count, vector_size = service.embed_chunks(docs, model)
tk_count, vector_size = await service.embed_chunks(docs, model)

assert tk_count > 0
assert vector_size == 2
assert "q_2_vec" in docs[0]

@patch.object(EmbeddingService, '_run_encode')
def test_embed_chunks_uses_embedding_utils(self, mock_run_encode):
"""Test that embed_chunks uses EmbeddingUtils internally.

The internal path runs _encode_batch -> EmbeddingUtils.truncate_texts
-> _run_encode. We verify via the public embed_chunks that the chain
is wired correctly without asserting on individual private method calls.
"""
mock_run_encode.return_value = (np.array([[1.0, 2.0]]), 10)
@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_uses_embedding_utils(self, mock_thread_pool):
"""Test that embed_chunks uses thread_pool_exec for encoding."""
mock_thread_pool.return_value = (np.array([[1.0, 2.0]]), 10)
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx, embedding_batch_size=10)
model = MagicMock()
model.max_length = 100

docs = [
{"docnm_kwd": "Title1", "content_with_weight": "Content1"},
]
service.embed_chunks(docs, model)
await service.embed_chunks(docs, model)

mock_run_encode.assert_called()
# thread_pool_exec should be called at least once for encoding
mock_thread_pool.assert_called()

@patch.object(EmbeddingService, '_run_encode')
def test_embed_chunks_with_title_content_combination(self, mock_run_encode):
@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_with_title_content_combination(self, mock_thread_pool):
"""Test that title and content vectors are combined."""
mock_run_encode.return_value = (np.array([[1.0, 2.0]]), 10)
mock_thread_pool.return_value = (np.array([[1.0, 2.0]]), 10)
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx, embedding_batch_size=10)
model = MagicMock()
model.max_length = 100

docs = [
{"docnm_kwd": "Title1", "content_with_weight": "Content1"},
]
_, vector_size = service.embed_chunks(docs, model, parser_config={"filename_embd_weight": 0.5})
_, vector_size = await service.embed_chunks(docs, model, parser_config={"filename_embd_weight": 0.5})

assert vector_size == 2

@patch.object(EmbeddingService, '_run_encode')
def test_embed_chunks_handles_long_text(self, mock_run_encode):
@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_handles_long_text(self, mock_thread_pool):
"""Test that long texts are handled by embedding pipeline.

Even with content exceeding model.max_length, embed_chunks produces
valid vectors, meaning truncation (via EmbeddingUtils) is wired
correctly in the encode path.
"""
mock_run_encode.return_value = (np.array([[1.0, 2.0]]), 10)
mock_thread_pool.return_value = (np.array([[1.0, 2.0]]), 10)
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx, embedding_batch_size=10)
model = MagicMock()
model.max_length = 100

docs = [
{"docnm_kwd": "Title1", "content_with_weight": "a" * 200},
]
tk_count, vector_size = service.embed_chunks(docs, model)
tk_count, vector_size = await service.embed_chunks(docs, model)

# Public contract: embed_chunks returns valid token counts and vectors
assert tk_count > 0
assert vector_size == 2
assert "q_2_vec" in docs[0]


@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_empty_docs(self, mock_thread_pool):
"""Test embedding with empty docs list returns zero results."""
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx)
model = MagicMock()
model.max_length = 100

tk_count, vector_size = await service.embed_chunks([], model)

assert tk_count == 0
assert vector_size == 0

@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_no_title(self, mock_thread_pool):
"""Test embedding when chunks have no title — content vectors used directly."""
mock_thread_pool.return_value = (np.array([[3.0, 4.0]]), 5)
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx, embedding_batch_size=10)
model = MagicMock()
model.max_length = 100

docs = [{"content_with_weight": "Content only, no title"}]
tk_count, vector_size = await service.embed_chunks(docs, model)

# With no title, only content is encoded (1 call); vector_size comes from content vec
assert vector_size == 2
assert "q_2_vec" in docs[0]

@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_title_weight_zero(self, mock_thread_pool):
"""Test embedding with filename_embd_weight=0.0 — no title contribution."""
mock_thread_pool.return_value = (np.array([[1.0, 2.0]]), 5)
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx, embedding_batch_size=10)
model = MagicMock()
model.max_length = 100

docs = [{"docnm_kwd": "Title1", "content_with_weight": "Content1"}]
_, vector_size = await service.embed_chunks(docs, model,
parser_config={"filename_embd_weight": 0.0})

assert vector_size == 2

@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_title_weight_one(self, mock_thread_pool):
"""Test embedding with filename_embd_weight=1.0 — full title contribution."""
mock_thread_pool.return_value = (np.array([[1.0, 2.0]]), 5)
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx, embedding_batch_size=10)
model = MagicMock()
model.max_length = 100

docs = [{"docnm_kwd": "Title1", "content_with_weight": "Content1"}]
_, vector_size = await service.embed_chunks(docs, model,
parser_config={"filename_embd_weight": 1.0})

assert vector_size == 2

@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_encode_failure_propagates(self, mock_thread_pool):
"""Test that model.encode exceptions are propagated to caller."""
mock_thread_pool.side_effect = RuntimeError("embedding service unavailable")
ctx = MagicMock()
ctx.progress_cb = None
ctx.embed_limiter = AsyncMockLimiter()
service = EmbeddingService(ctx=ctx, embedding_batch_size=10)
model = MagicMock()
model.max_length = 100

docs = [{"docnm_kwd": "Title1", "content_with_weight": "Content1"}]
with pytest.raises(RuntimeError, match="embedding service unavailable"):
await service.embed_chunks(docs, model)

@pytest.mark.asyncio
@patch("rag.svr.task_executor_refactor.embedding_service.thread_pool_exec", new_callable=AsyncMock)
async def test_embed_chunks_multiple_batches(self, mock_thread_pool):
"""Test embedding with more chunks than batch size — multiple encode calls."""
# Each call returns vectors matching input count
def side_effect(func, texts, *args, **kw):
n = len(texts) if isinstance(texts, list) else 1
return np.random.rand(n, 2).astype(np.float32), 10 * n

mock_thread_pool.side_effect = side_effect
ctx = MagicMock()
ctx.progress_cb = MagicMock()
ctx.embed_limiter = AsyncMockLimiter()
# batch_size=2, 5 chunks with titles → 1 title + ceil(5/2)=3 content = 4 calls
service = EmbeddingService(ctx=ctx, embedding_batch_size=2)
model = MagicMock()
model.max_length = 100

docs = [{"docnm_kwd": f"Title{i}", "content_with_weight": f"Content{i}"} for i in range(5)]
_, vector_size = await service.embed_chunks(docs, model)

assert mock_thread_pool.call_count == 4
assert vector_size > 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add pytest priority markers to the new async tests.

These tests switched to pytest-style async cases, but they still lack the required p1/p2/p3 markers. Please tag the class or each test so they participate correctly in the backend test-selection policy.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

🤖 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_embedding_service.py`
around lines 63 - 260, Add the required pytest priority markers (p1/p2/p3) to
these new async tests so they are picked up by backend test-selection; for
example, decorate either the test class or each test function (e.g.,
test_embed_chunks_basic, test_embed_chunks_uses_embedding_utils,
test_embed_chunks_with_title_content_combination, etc.) with `@pytest.mark.p1` (or
the appropriate priority) or add `@pytest.mark.p2/`@pytest.mark.p3 as per test
importance; ensure the import of pytest.mark is present and apply the marker
consistently across all tests in this file so they adhere to the test-selection
policy.

Comment on lines +63 to +113
@pytest.mark.asyncio
async def test_processes_table_parser_manual_mode(self):
"""Test that table parser in manual mode aggregates and persists metadata."""
ctx = MagicMock()
ctx.parser_id = "table"
ctx.raw_task = {"parser_config": {}}
ctx.write_interceptor = None
chunks = [{"col_key": "val"}]

with patch("rag.svr.task_executor_refactor.post_processor.merge_table_parser_config_from_kb") as mock_merge, \
patch("rag.svr.task_executor_refactor.post_processor.aggregate_table_manual_doc_metadata") as mock_agg, \
patch("rag.svr.task_executor_refactor.post_processor.table_parser_strip_doc_metadata_keys") as mock_strip, \
patch("rag.svr.task_executor_refactor.post_processor.update_metadata_to") as mock_update, \
patch("rag.svr.task_executor_refactor.post_processor.DocMetadataService") as mock_meta:

mock_merge.return_value = {"table_column_mode": "manual"}
mock_agg.return_value = {"col_key": ["val1", "val2"]}
mock_strip.return_value = set()
mock_meta.get_document_metadata.return_value = {}
mock_update.return_value = {"col_key": ["val1", "val2"]}

service = PostProcessor(ctx=ctx)
await service.process_table_parser_metadata("doc_1", chunks)

mock_agg.assert_called_once_with(chunks, ctx.raw_task)
mock_meta.update_document_metadata.assert_called_once()

@pytest.mark.asyncio
async def test_processes_table_parser_with_write_interceptor(self):
"""Test table parser with write interceptor bypasses DB."""
ctx = MagicMock()
ctx.parser_id = "table"
ctx.raw_task = {}
ctx.write_interceptor = MagicMock()

with patch("rag.svr.task_executor_refactor.post_processor.merge_table_parser_config_from_kb") as mock_merge, \
patch("rag.svr.task_executor_refactor.post_processor.aggregate_table_manual_doc_metadata") as mock_agg, \
patch("rag.svr.task_executor_refactor.post_processor.table_parser_strip_doc_metadata_keys") as mock_strip, \
patch("rag.svr.task_executor_refactor.post_processor.DocMetadataService") as mock_meta:

mock_merge.return_value = {"table_column_mode": "manual"}
mock_agg.return_value = {"key": ["v"]}
mock_strip.return_value = set()
mock_meta.get_document_metadata.return_value = {}

service = PostProcessor(ctx=ctx)
await service.process_table_parser_metadata("doc_1", [])

ctx.write_interceptor.intercept.assert_called_once_with(
"DocMetadataService.update_document_metadata"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add priority markers to the new async tests.

These new pytest cases should carry the repo’s p1/p2/p3 markers so they slot into the expected backend test buckets.

As per coding guidelines, test/**/*.py: Use pytest for Python backend testing with priority level markers (p1/p2/p3).

🤖 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 63 - 113, The two new async tests lack priority markers; add the repo's
pytest priority decorator (e.g., `@pytest.mark.p1`) to both test functions
test_processes_table_parser_manual_mode and
test_processes_table_parser_with_write_interceptor (place the decorator above
the existing `@pytest.mark.asyncio`), and ensure pytest is imported in the module
if not already so the p1 marker resolves.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
rag/svr/task_executor_refactor/task_handler.py (1)

215-226: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Offload the embedding vector-size probe (and add logging for missing storage).

  • rag/svr/task_executor_refactor/task_handler.py _bind_embedding_model() calls embedding_model.encode(["ok"]) synchronously inside an async def, and LLMBundle.encode is a normal (non-async) def encode(...), so this blocks/bypasses the embed_limiter + thread_pool_exec pattern used by EmbeddingService.
  • rag/svr/task_executor_refactor/task_handler.py _run_standard_chunking() raises FileNotFoundError when binary is None without any local logging.*, so the failed MinIO lookup is hard to diagnose.
Suggested fix
             embedding_model = LLMBundle(task_tenant_id, embd_model_config, lang=task_language)
-            vts, _ = embedding_model.encode(["ok"])
+            async with ctx.embed_limiter:
+                vts, _ = await thread_pool_exec(embedding_model.encode, ["ok"])
             return embedding_model, len(vts[0])
🤖 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/task_handler.py` around lines 215 - 226, The
embedding probe in _bind_embedding_model currently calls the synchronous
LLMBundle.encode(["ok"]) inside an async function, bypassing
embed_limiter/thread_pool_exec; change _bind_embedding_model to offload the
probe to the executor using the same embed_limiter + thread_pool_exec pattern
(or call into EmbeddingService helper) so the blocking encode runs on the thread
pool and is rate-limited, then return embedding_model and vector length;
additionally, in _run_standard_chunking add a logging.error/logging.warning when
binary is None before raising FileNotFoundError so a failed MinIO/storage lookup
is recorded (reference symbols: _bind_embedding_model, LLMBundle.encode,
embed_limiter, thread_pool_exec, _run_standard_chunking).
🧹 Nitpick comments (1)
rag/svr/task_executor_refactor/task_handler.py (1)

419-424: ⚡ Quick win

Log the missing-storage failure path.

This is a new branch, but it raises without emitting task-executor context locally. A log with task_id, doc_id, bucket, and name will make storage misses diagnosable in production. Based on learnings, this module runs in the Task Executors process, so local executor logs are the right place to surface this failure. As per coding guidelines, **/*.py: Add logging for new flows.

Suggested fix
         bucket, name = File2DocumentService.get_storage_address(doc_id=ctx.doc_id)
         binary = await self._get_storage_binary(bucket, name)
         if binary is None:
+            logging.error(
+                "Missing storage object for task_id=%s doc_id=%s bucket=%s name=%s",
+                task_id,
+                task_doc_id,
+                bucket,
+                name,
+            )
             raise FileNotFoundError(
                 f"Can not find file <{ctx.name}> from minio. Could you try it again."
             )
🤖 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/task_handler.py` around lines 419 - 424,
Before raising in the storage-miss branch of TaskHandler, emit a local
task-executor log containing task context and storage keys: when
File2DocumentService.get_storage_address(...) and await
self._get_storage_binary(bucket, name) return None, call the executor logger
(e.g., self._logger or the module-level logger) to log task_id (ctx.task_id),
doc_id (ctx.doc_id), bucket and name plus a brief message indicating storage
miss, then raise the same FileNotFoundError; update the block around
File2DocumentService.get_storage_address and _get_storage_binary to add that log
call immediately before the raise.
🤖 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/task_handler.py`:
- Around line 215-226: The embedding probe in _bind_embedding_model currently
calls the synchronous LLMBundle.encode(["ok"]) inside an async function,
bypassing embed_limiter/thread_pool_exec; change _bind_embedding_model to
offload the probe to the executor using the same embed_limiter +
thread_pool_exec pattern (or call into EmbeddingService helper) so the blocking
encode runs on the thread pool and is rate-limited, then return embedding_model
and vector length; additionally, in _run_standard_chunking add a
logging.error/logging.warning when binary is None before raising
FileNotFoundError so a failed MinIO/storage lookup is recorded (reference
symbols: _bind_embedding_model, LLMBundle.encode, embed_limiter,
thread_pool_exec, _run_standard_chunking).

---

Nitpick comments:
In `@rag/svr/task_executor_refactor/task_handler.py`:
- Around line 419-424: Before raising in the storage-miss branch of TaskHandler,
emit a local task-executor log containing task context and storage keys: when
File2DocumentService.get_storage_address(...) and await
self._get_storage_binary(bucket, name) return None, call the executor logger
(e.g., self._logger or the module-level logger) to log task_id (ctx.task_id),
doc_id (ctx.doc_id), bucket and name plus a brief message indicating storage
miss, then raise the same FileNotFoundError; update the block around
File2DocumentService.get_storage_address and _get_storage_binary to add that log
call immediately before the raise.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e2564796-c635-474f-896f-3138df93fd4b

📥 Commits

Reviewing files that changed from the base of the PR and between 1453aec and 914bf8d.

📒 Files selected for processing (9)
  • rag/svr/task_executor.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py
  • rag/svr/task_executor_refactor/dataflow_service.py
  • rag/svr/task_executor_refactor/task_handler.py
  • test/unit_test/rag/svr/task_executor_refactor/conftest.py
  • test/unit_test/rag/svr/task_executor_refactor/test_chunk_post_processor.py
  • test/unit_test/rag/svr/task_executor_refactor/test_task_handler.py
  • test/unit_test/rag/svr/task_executor_refactor/test_task_handler_integration.py
  • web/src/locales/zh.ts
✅ Files skipped from review due to trivial changes (1)
  • web/src/locales/zh.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • rag/svr/task_executor_refactor/dataflow_service.py
  • test/unit_test/rag/svr/task_executor_refactor/test_task_handler.py
  • rag/svr/task_executor_refactor/chunk_post_processor.py
  • test/unit_test/rag/svr/task_executor_refactor/conftest.py
  • test/unit_test/rag/svr/task_executor_refactor/test_task_handler_integration.py
  • test/unit_test/rag/svr/task_executor_refactor/test_chunk_post_processor.py

@xugangqiang xugangqiang self-assigned this Jun 1, 2026
@xugangqiang xugangqiang added the ci Continue Integration label Jun 1, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 1, 2026 06:59
@xugangqiang
xugangqiang marked this pull request as ready for review June 1, 2026 06:59
@xugangqiang
xugangqiang force-pushed the refactor/task-executor-overhaul branch from d521106 to 211f736 Compare June 1, 2026 07:41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py (1)

27-27: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Remove unused import.

The settings import is unused and causes a ruff linting failure (F401). The tests that reference settings use @patch decorators to mock it, so the import is not needed.

🔧 Proposed fix
-from common import settings
🤖 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_dataflow_service.py` at
line 27, The file contains an unused import "settings" (from common import
settings) which causes a lint F401; remove that import line so the tests rely on
their `@patch` decorators to provide mocked settings instead—locate the import
statement in test_dataflow_service.py and delete the "settings" import.
🧹 Nitpick comments (1)
test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py (1)

347-386: 💤 Low value

Consider adding pytest priority markers.

The new test class validates the _load_dsl id correction behavior comprehensively. However, per coding guidelines, tests should use pytest priority level markers (p1/p2/p3).

Example with priority markers
+@pytest.mark.p1
 `@pytest.mark.asyncio`
 async def test_load_dsl_for_dataflow_task_type_returns_unchanged_id(self):

As per coding guidelines: Use pytest for Python tests with priority level markers (p1/p2/p3).

🤖 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_dataflow_service.py`
around lines 347 - 386, The tests in TestDataflowServiceLoadDsl are missing the
required pytest priority markers; add the appropriate priority marker (e.g.,
`@pytest.mark.p1` or the project's chosen level) to the test class
TestDataflowServiceLoadDsl or to each test method
(test_load_dsl_for_dataflow_task_type_returns_unchanged_id and
test_load_dsl_for_pipeline_log_task_type_returns_corrected_id) so they comply
with the coding guideline requiring p1/p2/p3 markers.
🤖 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 `@test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py`:
- Line 27: The file contains an unused import "settings" (from common import
settings) which causes a lint F401; remove that import line so the tests rely on
their `@patch` decorators to provide mocked settings instead—locate the import
statement in test_dataflow_service.py and delete the "settings" import.

---

Nitpick comments:
In `@test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py`:
- Around line 347-386: The tests in TestDataflowServiceLoadDsl are missing the
required pytest priority markers; add the appropriate priority marker (e.g.,
`@pytest.mark.p1` or the project's chosen level) to the test class
TestDataflowServiceLoadDsl or to each test method
(test_load_dsl_for_dataflow_task_type_returns_unchanged_id and
test_load_dsl_for_pipeline_log_task_type_returns_corrected_id) so they comply
with the coding guideline requiring p1/p2/p3 markers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1112673b-6a18-4307-a15d-1126017524ac

📥 Commits

Reviewing files that changed from the base of the PR and between a507d5c and d61ee8b.

📒 Files selected for processing (1)
  • test/unit_test/rag/svr/task_executor_refactor/test_dataflow_service.py

@xugangqiang
xugangqiang force-pushed the refactor/task-executor-overhaul branch from d61ee8b to 5cc6913 Compare June 1, 2026 10:42
@codecov

codecov Bot commented Jun 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (12579db) to head (5cc6913).
⚠️ Report is 4 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15471   +/-   ##
=======================================
  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 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.

@xugangqiang

Copy link
Copy Markdown
Contributor Author

@KevinHuSh @yuzhichang
Main changes:

  1. find the logical diff between pre-refactor & post-refactor and fix
  2. refactor unit test to reduce mock

@wangq8
wangq8 merged commit b363146 into infiniflow:main Jun 3, 2026
1 check passed
@xugangqiang
xugangqiang deleted the refactor/task-executor-overhaul branch July 29, 2026 02:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 🌈 python Pull requests that update Python code ☯️ refactor Pull request that refactor/refine code size:L This PR changes 100-499 lines, ignoring generated files. 🧪 test Pull requests that update test cases.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants