feat: implement Re-scan API (partial)

實現內容:
1. 新增 ReScanRequest 和 ReScanResponse 結構體
2. 實現 re_scan API 函數
3. 添加路由 POST /api/v1/re-scan
4. 修改 process_register_command 添加 auto_pipeline_override 支持

測試結果:
- ✅ Re-scan API 可用
- ✅ Command 創建成功
- ✅ Force unregister 正確執行
- ❌ Monitor Job 未自動創建(需要進一步修復)

已知問題:
- register_single_file 在 force unregister 後仍返回 already_exists=true
- 導致 auto_pipeline 條件判斷失敗

下一步:
- 修改 register_single_file 修復 already_exists 標志
- 或在 process_register_command 中添加 force_unregister_executed 標志
This commit is contained in:
Accusys
2026-09-27 14:29:23 +08:00
parent 9cd3e20e48
commit ecb209633a
3 changed files with 240 additions and 4 deletions
@@ -0,0 +1,116 @@
---
title: Processor Test Stuck - Worker Not Executing Processors
version: 1.0
date: 2026-09-27
author: OpenCode
status: blocked
---
## 測試目標
測試 020.mp4 的所有處理器是否正常運行。
---
## 測試結果
### ✅ 成功部分
1. **創建 monitor_job**: 成功創建 ID 958
2. **Worker 檢測**: Worker 正確檢測到 job
3. **狀態更新**: Job 狀態更新為 "running"
4. **處理器識別**: Worker 正確識別所有待運行處理器
### ❌ 失敗部分
**Worker 不執行處理器**
---
## 問題詳情
### 現象
```
[INFO] Processing job: b496a68800f90770aa7246c877f38985 (958)
[INFO] Processors specified: ["ASR", "FACE", "OCR", "POSE", ...]
[INFO] check_and_complete_job: results=1, expected=10
[INFO] check_and_complete_job: missing processor results: ["ASR", "FACE", ...]
```
**循環重複,但沒有實際執行處理器**
---
## 根本原因
### Worker 處理流程缺陷
1. **只檢查不執行**: Worker 的 `check_and_complete_job` 只檢查結果,不執行處理器
2. **缺少執行邏輯**: 沒有找到實際運行處理器的代碼調用
3. **設計問題**: Worker 可能設計為只檢查已完成的工作,不自動執行
---
## 發現的問題鏈
```
註冊函數缺陷
└─ 只執行 CUT,不觸發 pipeline
auto_pipeline 未觸發
└─ file_type 是 null,條件不滿足
monitor_job 創建成功
└─ 手動創建繞過了前兩個問題
Worker 不執行處理器 ❌
└─ 發現新的設計問題
```
---
## 測試進度
| 處理器 | 狀態 | 問題 |
|--------|------|------|
| CUT | ✅ 完成 | 註冊時完成 |
| ASR | ❌ 未運行 | Worker 不執行 |
| Face | ❌ 未運行 | Worker 不執行 |
| OCR | ❌ 未運行 | Worker 不執行 |
| Pose | ❌ 未運行 | Worker 不執行 |
| Scene VLM | ❌ 未運行 | Worker 不執行 |
| Phase 2 | ❌ 未運行 | 依賴 Phase 1 |
| Phase 3 | ❌ 未運行 | 依賴 Phase 1 |
---
## 建議的解決方案
### 短期
1. **手動運行處理器**: 直接調用 Python 腳本
2. **繞過 Worker**: 不使用 monitor_job 機制
3. **測試每個處理器**: 獨立測試每個處理器
### 長期
1. **修復 Worker 執行邏輯**: 添加實際運行處理器的代碼
2. **改進註冊流程**: 註冊時正確設置 file_type
3. **統一 Pipeline 觸發**: 確保 auto_pipeline 正確工作
---
## 下一步
**選項 A**: 繼續分析 Worker 代碼,找出為什麼不執行
**選項 B**: 手動運行處理器,測試每個處理器
**選項 C**: 其他方法
---
## 相關文件
- `docs_v1.0/M4_workspace/2026-09-27_session_summary.md`
- `docs_v1.0/M4_workspace/2026-09-27_pipeline_architecture_flaws.md`
- `docs_v1.0/M4_workspace/2026-09-27_worker_data_integrity_fix.md`
+112
View File
@@ -1053,6 +1053,29 @@ struct UnregisterRequest {
reason: Option<String>,
}
#[derive(Debug, Deserialize)]
struct ReScanRequest {
file_uuid: String,
#[serde(default)]
processors: Option<Vec<String>>,
#[serde(default)]
face_settings: Option<FaceSettings>,
#[serde(default)]
trigger_source: Option<String>,
#[serde(default)]
reason: Option<String>,
}
#[derive(Debug, Serialize)]
struct ReScanResponse {
success: bool,
message: String,
file_uuid: String,
unregister_command_id: Option<String>,
register_command_id: Option<String>,
process_command_id: Option<String>,
}
fn delete_output_files(uuid: &str) -> u64 {
let mut deleted_count = 0u64;
let output_dirs = [
@@ -1174,6 +1197,94 @@ async fn unregister(
}))
}
async fn re_scan(
State(state): State<AppState>,
Json(req): Json<ReScanRequest>,
) -> Result<Json<ReScanResponse>, StatusCode> {
let file_uuid = req.file_uuid.clone();
let source = req.trigger_source.as_deref().unwrap_or("api_re_scan");
let reason = req.reason.as_deref().unwrap_or("re_scan");
tracing::info!(
"[RE-SCAN] Starting re-scan for {} (source={}, reason={})",
file_uuid,
source,
reason
);
// Step 1: Get file path from database
let videos_table = schema::table_name("videos");
let file_path: Option<String> = sqlx::query_scalar(&format!(
"SELECT file_path FROM {} WHERE file_uuid = $1",
videos_table
))
.bind(&file_uuid)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[RE-SCAN] Failed to query file path for {}: {:?}", file_uuid, e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let file_path = match file_path {
Some(p) => p,
None => {
tracing::error!("[RE-SCAN] File not found: {}", file_uuid);
return Err(StatusCode::NOT_FOUND);
}
};
// Step 2: Create register command with force=true
// Note: force=true will automatically unregister existing file if needed
let register_payload = serde_json::json!({
"force": true,
"auto_pipeline": true, // Flag to force auto-pipeline
"content_hash": null,
"face_settings": req.face_settings.as_ref().map(|fs| {
serde_json::json!({
"min_confidence": fs.min_confidence,
"min_size": fs.min_size
})
}),
});
let register_cmd = state
.db
.create_command("register", Some(&file_path), None, None, &register_payload, 1)
.await
.map_err(|e| {
tracing::error!(
"[RE-SCAN] Failed to enqueue register command for {}: {:?}",
file_path,
e
);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tracing::info!(
"[RE-SCAN] Register command {} enqueued for {} (with force=true)",
register_cmd.command_id,
file_path
);
// Note: Register command with force=true will:
// 1. Unregister existing file if needed
// 2. Register the file
// 3. Trigger auto-pipeline if auto_pipeline flag is set
Ok(Json(ReScanResponse {
success: true,
message: format!(
"Re-scan queued: register={}",
register_cmd.command_id
),
file_uuid,
unregister_command_id: None,
register_command_id: Some(register_cmd.command_id),
process_command_id: None,
}))
}
/// Internal unregister function - can be called from both API and register
pub(crate) async fn unregister_internal(db: &PostgresDb, uuid: &str) -> Result<(), StatusCode> {
let videos_table = schema::table_name("videos");
@@ -1487,6 +1598,7 @@ pub fn file_routes() -> Router<AppState> {
.route("/api/v1/files/register", post(register_file))
.route("/api/v1/files/lookup", get(lookup_file_by_name))
.route("/api/v1/unregister", post(unregister))
.route("/api/v1/re-scan", post(re_scan))
.route("/api/v1/command/:command_id", get(get_command_status))
.route("/api/v1/file/:file_uuid/probe", get(probe_by_uuid))
.route(
+12 -4
View File
@@ -530,11 +530,16 @@ impl JobWorker {
.get("force")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let auto_pipeline_override = cmd
.payload
.get("auto_pipeline")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let face_settings = cmd.payload.get("face_settings").cloned();
info!(
"[COMMAND_QUEUE] Registering file: {} (user_id={:?}, force={})",
file_path, user_id, force
"[COMMAND_QUEUE] Registering file: {} (user_id={:?}, force={}, auto_pipeline_override={})",
file_path, user_id, force, auto_pipeline_override
);
let resp = register_single_file(&self.db, file_path, user_id, content_hash, force).await;
@@ -543,8 +548,11 @@ impl JobWorker {
anyhow::bail!("Register failed: {}", resp.message);
}
if resp.success
&& !resp.already_exists
// Trigger auto-pipeline if:
// 1. auto_pipeline_override flag is set, OR
// 2. (force || !already_exists) AND file is video AND auto_pipeline is enabled globally
if (auto_pipeline_override || (force || !resp.already_exists))
&& resp.success
&& resp.file_type.as_deref() == Some("video")
&& crate::core::config::get_auto_pipeline_enabled()
{