Skip to content

fix: clear task queue when index is disabled - #295

Merged
Johnson-zs merged 1 commit into
linuxdeepin:develop/snipefrom
Johnson-zs:agent/bugfix/f2d0d7670338
Nov 19, 2026
Merged

Johnson-zs merged 1 commit into
linuxdeepin:develop/snipefrom
Johnson-zs:agent/bugfix/f2d0d7670338

Conversation

@Johnson-zs

@Johnson-zs Johnson-zs commented Nov 18, 2026 •

Copy link
Copy Markdown

修复:关闭 OCR 索引开关后队列中的任务继续执行

问题

关闭文件管理器设置中的 OCR 索引开关(SetEnabled(false))后,FSEventController::setEnabled(false) 仅停止新事件收集,不触及 TaskManager 的任务队列。schedule() 不检查 m_enabled,导致数万级 OCR 任务继续执行,长时间占用 CPU 和内存。

根因

OcrIndexDBus::SetEnabled(false)(ocrindexdbus.cpp:200-203)只调用 FSEventController::setEnabled(false),后者仅设置 m_enabled = false 并停止监控定时器,完全不触及 TaskManager:

  • 不调用 stopCurrentTask() → 正在运行的 OCR 任务继续执行
  • 不清除 taskQueue → schedule() 持续从队列出队执行

修复方案

  1. FSEventController 新增 enabledChanged(bool) 信号,在 setEnabled() 中 emit
  2. TaskManager 新增 onEnabledChanged(bool) 私有槽,禁用时清空 taskQueue(不调 stopCurrentTask 避免与文管层重复)
  3. IndexRuntime 构造函数中连接信号槽

改动文件

  • src/index/fsmonitor/fseventcontroller.h — 新增 enabledChanged(bool) 信号
  • src/index/fsmonitor/fseventcontroller.cpp — setEnabled() 中 emit 信号
  • src/index/task/taskmanager.h — 新增 onEnabledChanged(bool) 槽声明
  • src/index/task/taskmanager.cpp — 实现槽函数,禁用时清空队列
  • src/index/core/indexruntime.cpp — 构造函数中连接信号槽
  • autotests/index/test_taskmanager_private.cpp — 新增单元测试

测试

新增单元测试 OnEnabledChanged_DisableClearsQueue 验证禁用时队列被清空。

PMS: TASK-395529

Summary by Sourcery

Clear queued indexing work when the OCR index is disabled.

Bug Fixes:

  • Clear pending OCR index tasks when indexing is disabled so queued work no longer continues consuming CPU and memory.

Enhancements:

  • Connect index enablement changes to task management while leaving cancellation of the currently running task to the file-manager layer.

Tests:

  • Add coverage verifying that disabling indexing empties the task queue.

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: Johnson-zs

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Declare the enablement-change signal and TaskManager slot that form the interface between index runtime and task management.

  • src/index/fsmonitor/fseventcontroller.h L58-61
  • src/index/task/taskmanager.h L83-85

Uses of the API

Connect FSEventController enablement changes to the TaskManager slot in IndexRuntime.

  • src/index/core/indexruntime.cpp L20-27

Implementation

Emit the enablement signal from setEnabled() and clear pending tasks when indexing is disabled.

  • src/index/fsmonitor/fseventcontroller.cpp L185-186
  • src/index/task/taskmanager.cpp L1163-1171

Tests

Verify that disabling the index clears queued tasks.

  • autotests/index/test_taskmanager_private.cpp L193-208

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 7 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/index/core/indexruntime.cpp" line_range="26" />
<code_context>
+    // The file-manager layer already calls StopCurrentTask to halt the
+    // running task; here we only clear the queue to avoid duplicate stops.
+    connect(m_fsEventController, &FSEventController::enabledChanged,
+            m_taskManager, &TaskManager::onEnabledChanged);
+
     EnvDetector::instance().setDataPath(m_profile.indexDirectory());
</code_context>
<issue_to_address>
**Index target fails to compile**

When the `indexruntime.cpp` target is compiled, `IndexRuntime` takes the address of `TaskManager::onEnabledChanged` outside `TaskManager`, but the method is declared under `private Q_SLOTS`, so C++ access control rejects the reference and the target fails to compile.

Make `onEnabledChanged` accessible to `IndexRuntime` or change the connection so it does not take the address of a private method.

Also at `src/index/core/indexruntime.cpp:27`.
</issue_to_address>

### Comment 2
<location path="src/index/fsmonitor/fseventcontroller.h" line_range="60" />
<code_context>

+    // Emitted when setEnabled() changes the enabled state.
+    // Runtimes connect this to TaskManager to clear queued tasks on disable.
+    void enabledChanged(bool enabled);
+
 private:
</code_context>
<issue_to_address>
**Build fails at link time**

`emit enabledChanged(m_enabled)` calls a method declared as a slot but never defined, leaving an unresolved symbol when the index target links. The new signal-to-slot connection also cannot use this declaration as a Qt signal.

Declare `enabledChanged(bool)` under `Q_SIGNALS:` instead of `private Q_SLOTS:`.
</issue_to_address>

### Comment 3
<location path="src/index/task/taskmanager.cpp" line_range="1168" />
<code_context>
+    if (!enabled && !taskQueue.isEmpty()) {
+        qInfo() << "[TaskManager::onEnabledChanged] Index disabled, clearing"
+                 << taskQueue.size() << "queued tasks";
+        taskQueue.clear();
+    }
+}
</code_context>
<issue_to_address>
**Queued file changes disappear**

When queued file-change tasks are cleared on disable after the initial silent refresh has been consumed, and indexing is later re-enabled, `taskQueue.clear()` discards pending changes, including queued OCR removals, and `setEnabled(true)` does not schedule another silent refresh; the affected files remain stale or absent from the index, and deleted OCR entries can remain searchable.

Preserve the queued changes or schedule a recovery refresh when indexing is re-enabled.
</issue_to_address>

### Comment 4
<location path="src/index/task/taskmanager.cpp" line_range="1168" />
<code_context>
+    if (!enabled && !taskQueue.isEmpty()) {
+        qInfo() << "[TaskManager::onEnabledChanged] Index disabled, clearing"
+                 << taskQueue.size() << "queued tasks";
+        taskQueue.clear();
+    }
+}
</code_context>
<issue_to_address>
**Indexing resumes while disabled**

When indexing is disabled while a task is running and the file-manager layer stops it, `onTaskPaused()` re-enqueues the unfinished work and calls `schedule()` without checking the enabled state, so the queue is repopulated and indexing continues while disabled.

Prevent `onTaskPaused()` from re-enqueuing or scheduling work while indexing is disabled.
</issue_to_address>

### Comment 5
<location path="src/index/task/taskmanager.cpp" line_range="1168" />
<code_context>
+    if (!enabled && !taskQueue.isEmpty()) {
+        qInfo() << "[TaskManager::onEnabledChanged] Index disabled, clearing"
+                 << taskQueue.size() << "queued tasks";
+        taskQueue.clear();
+    }
+}
</code_context>
<issue_to_address>
**Backlog and status stay stale**

When queued work is cleared on disable after clients have received a waiting status or the filename backlog threshold has been crossed, `onEnabledChanged()` clears `taskQueue` without refreshing the backlog tracker or emitting `indexStatusChanged`, so the backlog can remain set and clients can continue displaying the old queued status.

Refresh the backlog state and emit `indexStatusChanged` after clearing the queue.
</issue_to_address>

### Comment 6
<location path="autotests/index/test_taskmanager_private.cpp" line_range="199" />
<code_context>
+TEST_F(TaskManagerPrivateTest, OnEnabledChanged_DisableClearsQueue)
+{
+    // Enable the index so that the enabledChanged signal fires on toggle.
+    runtime->fsEventController()->setEnabled(true);
+
+    // Enqueue a compensation task so the queue is non-empty.
</code_context>
<issue_to_address>
**New test dereferences null timer**

The test calls `setEnabled(true)` on a controller whose monitoring timers have not been initialized; `setEnabled()` calls `m_stopTimer->stop()`, so the test crashes instead of verifying queue clearing.

Initialize the event collector before toggling enabled state in the test, or test the slot without calling `setEnabled()`.
</issue_to_address>

### Comment 7
<location path="src/index/fsmonitor/fseventcontroller.h" line_range="60" />
<code_context>

+    // Emitted when setEnabled() changes the enabled state.
+    // Runtimes connect this to TaskManager to clear queued tasks on disable.
+    void enabledChanged(bool enabled);
+
 private:
</code_context>
<issue_to_address>
**New methods use camelCase**

The new `enabledChanged` signal and `onEnabledChanged` slot use camelCase instead of snake_case, violating the repository's required naming convention for C++ methods.

Rename the new methods to snake_case and update their references.

Also at `src/index/task/taskmanager.h:94`, `src/index/task/taskmanager.cpp:1163`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/index/core/indexruntime.cpp Resolved
Comment thread src/index/fsmonitor/fseventcontroller.h Resolved
if (!enabled && !taskQueue.isEmpty()) {
qInfo() << "[TaskManager::onEnabledChanged] Index disabled, clearing"
<< taskQueue.size() << "queued tasks";
taskQueue.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Queued file changes disappear

When queued file-change tasks are cleared on disable after the initial silent refresh has been consumed, and indexing is later re-enabled, taskQueue.clear() discards pending changes, including queued OCR removals, and setEnabled(true) does not schedule another silent refresh; the affected files remain stale or absent from the index, and deleted OCR entries can remain searchable.

Preserve the queued changes or schedule a recovery refresh when indexing is re-enabled.

Prompt for AI agents
In `src/index/task/taskmanager.cpp` at line 1168:

**Queued file changes disappear**

When queued file-change tasks are cleared on disable after the initial silent refresh has been consumed, and indexing is later re-enabled, `taskQueue.clear()` discards pending changes, including queued OCR removals, and `setEnabled(true)` does not schedule another silent refresh; the affected files remain stale or absent from the index, and deleted OCR entries can remain searchable.

Preserve the queued changes or schedule a recovery refresh when indexing is re-enabled.

if (!enabled && !taskQueue.isEmpty()) {
qInfo() << "[TaskManager::onEnabledChanged] Index disabled, clearing"
<< taskQueue.size() << "queued tasks";
taskQueue.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟠 High · Indexing resumes while disabled

When indexing is disabled while a task is running and the file-manager layer stops it, onTaskPaused() re-enqueues the unfinished work and calls schedule() without checking the enabled state, so the queue is repopulated and indexing continues while disabled.

Prevent onTaskPaused() from re-enqueuing or scheduling work while indexing is disabled.

Prompt for AI agents
In `src/index/task/taskmanager.cpp` at line 1168:

**Indexing resumes while disabled**

When indexing is disabled while a task is running and the file-manager layer stops it, `onTaskPaused()` re-enqueues the unfinished work and calls `schedule()` without checking the enabled state, so the queue is repopulated and indexing continues while disabled.

Prevent `onTaskPaused()` from re-enqueuing or scheduling work while indexing is disabled.

if (!enabled && !taskQueue.isEmpty()) {
qInfo() << "[TaskManager::onEnabledChanged] Index disabled, clearing"
<< taskQueue.size() << "queued tasks";
taskQueue.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Backlog and status stay stale

When queued work is cleared on disable after clients have received a waiting status or the filename backlog threshold has been crossed, onEnabledChanged() clears taskQueue without refreshing the backlog tracker or emitting indexStatusChanged, so the backlog can remain set and clients can continue displaying the old queued status.

Refresh the backlog state and emit indexStatusChanged after clearing the queue.

Prompt for AI agents
In `src/index/task/taskmanager.cpp` at line 1168:

**Backlog and status stay stale**

When queued work is cleared on disable after clients have received a waiting status or the filename backlog threshold has been crossed, `onEnabledChanged()` clears `taskQueue` without refreshing the backlog tracker or emitting `indexStatusChanged`, so the backlog can remain set and clients can continue displaying the old queued status.

Refresh the backlog state and emit `indexStatusChanged` after clearing the queue.


// Emitted when setEnabled() changes the enabled state.
// Runtimes connect this to TaskManager to clear queued tasks on disable.
void enabledChanged(bool enabled);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚪ Low · New methods use camelCase

The new enabledChanged signal and onEnabledChanged slot use camelCase instead of snake_case, violating the repository's required naming convention for C++ methods.

Rename the new methods to snake_case and update their references.

Also at src/index/task/taskmanager.h:94, src/index/task/taskmanager.cpp:1163.

Prompt for AI agents
In `src/index/fsmonitor/fseventcontroller.h` at line 60:

**New methods use camelCase**

The new `enabledChanged` signal and `onEnabledChanged` slot use camelCase instead of snake_case, violating the repository's required naming convention for C++ methods.

Rename the new methods to snake_case and update their references.

Also at `src/index/task/taskmanager.h:94`, `src/index/task/taskmanager.cpp:1163`.

From AGENTS.md L57:

- Functions: `snake_case` (C functions, C++ methods)

@Johnson-zs
Johnson-zs force-pushed the agent/bugfix/f2d0d7670338 branch from 84eb2c2 to 98b4fd0 Compare November 18, 2026 05:08
@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

🤖 AI 代码审查报告

总体评分: 89 分 (通过阈值: 70分)

Pass


📊 总体评价

项目 结果
审查结论 代码审查通过
评分详情 本次提交目的是在索引被禁用时清空任务队列,避免挂起任务继续消耗 CPU/内存。新增的 enabledChanged 信号与 TaskManager::onEnabledChanged 槽在 setEnabled() 路径上逻辑正确,注释清晰,并通过单元测试覆盖;代码安全维度无漏洞。但发现一个逻辑缺陷:D-Bus 禁用索引的实际路径调用的是 setEnabledNow(false),该方法直接置 m_enabled=false 并停止监控,未调用 setEnabled(),因此不会发射 enabledChanged 信号,任务队列不会被清空——与本提交的修复目标相悖。建议在 setEnabledNow(false) 分支也发射 enabledChanged 或统一走 setEnabled()。其余维度均为轻微建议,总体通过。

🔍 详细分析

1. 语法逻辑 ❌

评价: 存在逻辑缺陷 ❌ 不通过

潜在问题:
✅ 未发现明显问题

建议: ['在 setEnabledNow(bool) 的 else 分支也发射 enabledChanged(m_enabled),或将其重构为统一调用 setEnabled(),确保所有禁用路径都能清空任务队列']


2. 代码质量 ✅

评价: 代码结构清晰,注释完整 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['在 setEnabled() 开头记录 oldEnabled,仅当 oldEnabled != m_enabled 时才发射 enabledChanged,避免无意义信号']


3. 代码性能 ✅

评价: 性能良好,资源使用合理 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: []


4. 代码安全 🔒

评价: 存在0个安全漏洞 ✅ 通过

🔐 发现 0 个安全漏洞

安全漏洞详情:
✅ 未发现安全漏洞

建议: []


💡 改进建议代码示例

// src/index/fsmonitor/fseventcontroller.cpp
// 方案一:在 setEnabledNow 的 else 分支补发信号
void FSEventController::setEnabledNow(bool enabled)
{
    if (enabled) {
        setEnabled(enabled);
    } else {
        m_enabled = false;
        stopFSMonitoring();
        emit enabledChanged(m_enabled);   // 补发,确保禁用路径清空队列
    }
}

// 方案二(更稳妥):在 setEnabled() 中仅当状态变化时才发射信号
void FSEventController::setEnabled(bool enabled)
{
    bool oldEnabled = m_enabled;
    m_enabled = enabled;
    // ... 原有逻辑 ...
    if (oldEnabled != m_enabled) {
        emit enabledChanged(m_enabled);
    }
}

本报告由 AI 代码审查工具自动生成

1. Root cause: SetEnabled(false) only called FSEventController::setEnabled
   which sets m_enabled=false and stops monitor timer, but never touched
   TaskManager's taskQueue. schedule() did not check m_enabled, so queued
   OCR tasks continued executing after the user disabled the index
2. Fix: add enabledChanged(bool) signal to FSEventController, emit it in
   setEnabled(); add onEnabledChanged(bool) public slot to TaskManager
   that clears taskQueue when disabled; connect them in IndexRuntime ctor
3. Impact: when user disables OCR index, pending queued tasks are cleared
   immediately instead of continuing to consume CPU/memory; file-manager
   layer's existing StopCurrentTask handles the running task; no duplicate
   stop calls since server-side only clears the queue

Log: Disabling OCR index now clears pending queued tasks to stop unnecessary CPU and memory usage

Influence:
1. Test disabling OCR index while tasks are queued — verify queue is cleared
2. Test re-enabling OCR index after disable — verify silentlyRefreshStarted
   recovery still works
3. Test filename index enable/disable — verify same signal-slot connection
   does not affect filename index behavior

fix: 关闭索引开关时清空任务队列

1. 根因:SetEnabled(false) 仅调用 FSEventController::setEnabled 设置
   m_enabled=false 并停止监控定时器,完全不触及 TaskManager 的 taskQueue。
   schedule() 不检查 m_enabled,导致用户关闭 OCR 索引开关后队列中的任务
   继续执行消耗 CPU 和内存
2. 方案:FSEventController 新增 enabledChanged(bool) 信号并在 setEnabled()
   中 emit;TaskManager 新增 onEnabledChanged(bool) 公有槽(函数指针式
   connect 要求跨类可见),禁用时清空 taskQueue(不调 stopCurrentTask
   避免与文管层重复);IndexRuntime 构造函数中连接信号槽
3. 影响:用户关闭 OCR 索引开关后待执行任务立即被清除,不再消耗资源;
   文管层已有 StopCurrentTask 机制处理当前运行任务;服务端仅清队列不
   调 stopCurrentTask,不会产生重复调用

Log: 关闭 OCR 索引开关后立即清空待执行任务队列,停止不必要的 CPU 和内存占用

Influence:
1. 测试关闭 OCR 索引开关时队列中有任务——验证队列被清空
2. 测试关闭后重新打开 OCR 索引开关——验证 silentlyRefreshStarted 恢复正常
3. 测试文件名索引的启用/禁用——验证相同的信号槽连接不影响文件名索引行为

PMS: TASK-395529
@Johnson-zs
Johnson-zs force-pushed the agent/bugfix/f2d0d7670338 branch from 98b4fd0 to 90f20ba Compare November 18, 2026 10:48
@Johnson-zs
Johnson-zs merged commit 148b748 into linuxdeepin:develop/snipe Nov 19, 2026
17 of 20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants