feat: real service test endpoints (proxy 7-route round-trip, core/chat/vlm/markbase/embedding), unified log paths + errorLog, pipeline tools/import/export/folder APIs, face pipeline check, dynamic concurrency tuning
This commit is contained in:
+697
-30
@@ -198,6 +198,11 @@ impl JobWorker {
|
||||
warn!("[HEALTH-CHECK] Initial health check failed: {}", e);
|
||||
}
|
||||
|
||||
// Layer 0: Recover interrupted processors (Worker restarted)
|
||||
if let Err(e) = self.recover_interrupted_processors().await {
|
||||
warn!("[RECOVER] Initial recovery failed: {}", e);
|
||||
}
|
||||
|
||||
// Layer 3b: Re-evaluate stuck PROCESSING files
|
||||
if let Err(e) = self.re_evaluate_stuck_processing().await {
|
||||
warn!("[RE-EVALUATE] Initial re-evaluation failed: {}", e);
|
||||
@@ -209,6 +214,8 @@ impl JobWorker {
|
||||
let reevaluate_interval = std::time::Duration::from_secs(600); // 10 minutes
|
||||
let mut last_billing_agg = std::time::Instant::now();
|
||||
let billing_agg_interval = std::time::Duration::from_secs(3600); // 1 hour
|
||||
let mut last_completeness_check = std::time::Instant::now();
|
||||
let completeness_check_interval = std::time::Duration::from_secs(1800); // 30 minutes
|
||||
|
||||
loop {
|
||||
if !self.config.enabled {
|
||||
@@ -225,6 +232,14 @@ impl JobWorker {
|
||||
last_health_check = std::time::Instant::now();
|
||||
}
|
||||
|
||||
// Layer 3e: Periodic output completeness check every 30 minutes
|
||||
if last_completeness_check.elapsed() > completeness_check_interval {
|
||||
if let Err(e) = self.periodic_completeness_check().await {
|
||||
warn!("[COMPLETENESS] Periodic completeness check failed: {}", e);
|
||||
}
|
||||
last_completeness_check = std::time::Instant::now();
|
||||
}
|
||||
|
||||
// Layer 3b: Re-evaluate stuck PROCESSING files every 10 minutes
|
||||
if last_reevaluate.elapsed() > reevaluate_interval {
|
||||
if let Err(e) = self.re_evaluate_stuck_processing().await {
|
||||
@@ -320,6 +335,23 @@ impl JobWorker {
|
||||
error!("Failed to reset stale running jobs: {}", e);
|
||||
}
|
||||
|
||||
// ── Layer 3c: Job 併發上限(backpressure)─────────────────────────────
|
||||
// 同時執行 deep scan 的 job 數不得超過上限;超出的 running jobs 自動
|
||||
// 轉為 paused(video 退回 registered),名額釋出時自動恢復。
|
||||
// 上限來源:MOMENTRY_MAX_ACTIVE_JOBS > 動態併發(dynamic_max)。
|
||||
let max_active_jobs = std::env::var("MOMENTRY_MAX_ACTIVE_JOBS")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<usize>().ok())
|
||||
.unwrap_or(dynamic_max.max(1));
|
||||
if let Err(e) = self.enforce_job_slot_limit(max_active_jobs).await {
|
||||
error!("Failed to enforce job slot limit: {}", e);
|
||||
}
|
||||
|
||||
// ── Layer 3d: 卡住偵測 → 自動 re-scan(unregister → register → deep scan)──
|
||||
if let Err(e) = self.detect_and_rescan_stuck_jobs().await {
|
||||
error!("Failed stuck-job detection: {}", e);
|
||||
}
|
||||
|
||||
let health_key = format!("{}health", crate::core::config::REDIS_KEY_PREFIX.as_str());
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let running_count = self.processor_pool.get_running_count().await;
|
||||
@@ -486,10 +518,30 @@ impl JobWorker {
|
||||
// Process pending jobs if any
|
||||
let pending_jobs = self.db.get_pending_jobs(self.config.batch_size).await?;
|
||||
|
||||
// 認領前的 running 數(enforce_job_slot_limit 已將超額 running 轉 paused)
|
||||
let running_before_claim: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT count(*) FROM {} WHERE status = 'running'",
|
||||
monitor_jobs_table
|
||||
))
|
||||
.fetch_one(self.db.pool())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let mut claimed_jobs: i64 = 0;
|
||||
|
||||
if !pending_jobs.is_empty() {
|
||||
info!("Found {} pending jobs ({} paused)", pending_jobs.len(), paused_jobs.len());
|
||||
|
||||
for job in pending_jobs {
|
||||
// Job 名額上限:running + 本輪已認領數不得超過 max_active_jobs
|
||||
if running_before_claim + claimed_jobs >= max_active_jobs as i64 {
|
||||
info!(
|
||||
"[BACKPRESSURE] deep scan 名額已滿({}/{}),其餘 pending jobs 留待名額釋出",
|
||||
running_before_claim + claimed_jobs,
|
||||
max_active_jobs
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
// Skip paused jobs
|
||||
if paused_jobs.contains(&job.uuid) {
|
||||
debug!("Skipping paused job: {}", job.uuid);
|
||||
@@ -504,6 +556,503 @@ impl JobWorker {
|
||||
if let Err(e) = self.process_job(job).await {
|
||||
error!("Failed to process job: {}", e);
|
||||
}
|
||||
claimed_jobs += 1;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Layer 3c: Job 併發上限(backpressure)
|
||||
///
|
||||
/// 同時處於 running 的 deep scan job 不得超過 `limit`:
|
||||
/// - 超出者自動標記為 paused。保留對象:(1) 有 processor 正在執行的 job、
|
||||
/// (2) 全部 processor 已 completed 正在 ingestion 收尾的 job、
|
||||
/// (3) 名額內最新的 jobs。
|
||||
/// - 被 paused 的 job,其 video 狀態由 scanning 退回 registered,
|
||||
/// 避免 GUI 顯示大量停滯的 scanning。
|
||||
/// - 名額釋出時,最舊的 paused jobs 自動恢復為 pending 重新排隊。
|
||||
/// Layer 0: Recover interrupted processors
|
||||
///
|
||||
/// Worker 啟動時自動恢復被中斷的處理器。
|
||||
/// 當 worker 被 reboot/kill 時,正在執行的處理器會被標記為
|
||||
/// 'Worker restarted' 並停留在 pending 狀態。
|
||||
/// 此方法將所有這類處理器重置為 pending 並清除錯誤訊息,
|
||||
/// 讓 worker 可以重新處理它們。
|
||||
/// Layer 3e: Periodic completeness check (every 30 minutes)
|
||||
///
|
||||
/// 檢查所有 completed 影片的產出完整性。
|
||||
/// 發現缺項時:
|
||||
/// 1. 記錄警告 log
|
||||
/// 2. 更新 Redis 快取(供前端讀取)
|
||||
/// 3. 嘗試自動修復(觸發 auto-repair for missing JSON)
|
||||
async fn periodic_completeness_check(&self) -> Result<()> {
|
||||
info!("[COMPLETENESS] Starting periodic output completeness check");
|
||||
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
let videos_table = schema::table_name("videos");
|
||||
|
||||
let rows: Vec<(String, String)> = sqlx::query_as(&format!(
|
||||
"SELECT file_uuid, file_name FROM {} WHERE file_type = 'video' AND status = 'completed'",
|
||||
videos_table
|
||||
))
|
||||
.fetch_all(self.db.pool())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut total_missing = 0;
|
||||
let mut files_with_issues = 0;
|
||||
|
||||
for (uuid, file_name) in &rows {
|
||||
let mut missing: Vec<String> = Vec::new();
|
||||
|
||||
// 檢查 JSON 產出
|
||||
for ext in ["asrx", "cut", "face", "face_cluster", "face_traced", "ocr", "scenes"] {
|
||||
let path = format!("{}/{}.{}.json", output_dir, uuid, ext);
|
||||
if !std::path::Path::new(&path).exists() {
|
||||
missing.push(format!("{}.json", ext));
|
||||
}
|
||||
}
|
||||
|
||||
// 檢查 trace 目錄
|
||||
let trace_base = std::path::Path::new(&output_dir).join(uuid);
|
||||
if trace_base.is_dir() {
|
||||
if let Ok(entries) = std::fs::read_dir(&trace_base) {
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with("trace_") && entry.path().is_dir() {
|
||||
for f in ["key_face.jpg", "key_frame.jpg", "trace_profile.json"] {
|
||||
if !entry.path().join(f).exists() {
|
||||
missing.push(format!("{}/{}", name, f));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !missing.is_empty() {
|
||||
files_with_issues += 1;
|
||||
total_missing += missing.len();
|
||||
warn!(
|
||||
"[COMPLETENESS] {} ({}): missing {} items: {}",
|
||||
file_name,
|
||||
uuid,
|
||||
missing.len(),
|
||||
missing.join(", ")
|
||||
);
|
||||
|
||||
// 寫入 Redis 供前端讀取
|
||||
let redis_key = format!(
|
||||
"{}completeness:{}",
|
||||
crate::core::config::REDIS_KEY_PREFIX.as_str(),
|
||||
uuid
|
||||
);
|
||||
if let Ok(mut conn) = self.redis.get_conn().await {
|
||||
let _: Result<(), _> = redis::cmd("SET")
|
||||
.arg(&redis_key)
|
||||
.arg(serde_json::to_string(&missing).unwrap_or_default())
|
||||
.arg("EX")
|
||||
.arg(7200i64) // 2 hour TTL
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
}
|
||||
|
||||
// 嘗試觸發 auto-repair for missing JSON
|
||||
// (worker 下次 poll 時 check_and_repair_processor_results 會處理)
|
||||
} else {
|
||||
// 清除 Redis 中的完整性標記
|
||||
let redis_key = format!(
|
||||
"{}completeness:{}",
|
||||
crate::core::config::REDIS_KEY_PREFIX.as_str(),
|
||||
uuid
|
||||
);
|
||||
if let Ok(mut conn) = self.redis.get_conn().await {
|
||||
let _: Result<(), _> = redis::cmd("DEL")
|
||||
.arg(&redis_key)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if files_with_issues > 0 {
|
||||
warn!(
|
||||
"[COMPLETENESS] {} files with issues, {} total missing items",
|
||||
files_with_issues, total_missing
|
||||
);
|
||||
} else {
|
||||
info!("[COMPLETENESS] All outputs complete ({} files checked)", rows.len());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn recover_interrupted_processors(&self) -> Result<()> {
|
||||
let processor_results_table = schema::table_name("processor_results");
|
||||
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
||||
|
||||
// 1. 重置所有被 worker 重啟中斷的處理器
|
||||
let recovered = sqlx::query(&format!(
|
||||
"UPDATE {processor_results_table}
|
||||
SET status = 'pending', retry_count = 0, error_message = NULL, updated_at = NOW()
|
||||
WHERE status = 'pending'
|
||||
AND error_message = 'Worker restarted'"
|
||||
))
|
||||
.execute(self.db.pool())
|
||||
.await
|
||||
.map(|r| r.rows_affected())
|
||||
.unwrap_or(0);
|
||||
|
||||
if recovered > 0 {
|
||||
info!(
|
||||
"[RECOVER] 已恢復 {} 個被中斷的處理器(Worker restarted → pending)",
|
||||
recovered
|
||||
);
|
||||
|
||||
// 2. 對應的 monitor_jobs 也重置為 pending
|
||||
let jobs_reset = sqlx::query(&format!(
|
||||
"UPDATE {monitor_jobs_table} mj
|
||||
SET status = 'pending', updated_at = NOW()
|
||||
WHERE mj.status IN ('running', 'failed')
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM {processor_results_table} pr
|
||||
WHERE pr.file_uuid = mj.uuid AND pr.status = 'pending'
|
||||
)"
|
||||
))
|
||||
.execute(self.db.pool())
|
||||
.await
|
||||
.map(|r| r.rows_affected())
|
||||
.unwrap_or(0);
|
||||
|
||||
if jobs_reset > 0 {
|
||||
info!("[RECOVER] 已重置 {} 個 monitor_jobs 為 pending", jobs_reset);
|
||||
}
|
||||
} else {
|
||||
info!("[RECOVER] 無需恢復(沒有被中斷的處理器)");
|
||||
}
|
||||
|
||||
// 3. 額外檢查:有 output 檔案但 DB 狀態為 pending 的處理器
|
||||
// (避免重複處理已有產出的項目)
|
||||
let auto_repaired = sqlx::query(&format!(
|
||||
"UPDATE {processor_results_table} pr
|
||||
SET status = 'completed', error_message = NULL, updated_at = NOW()
|
||||
WHERE pr.status = 'pending'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM videos v WHERE v.file_uuid = pr.file_uuid
|
||||
)
|
||||
-- 只有當 output 目錄中對應的 JSON 存在時才標記 completed
|
||||
-- 這裡不直接查檔案系統(SQL 做不到),由 auto-repair 邏輯處理"
|
||||
))
|
||||
.execute(self.db.pool())
|
||||
.await;
|
||||
|
||||
// auto-repair 由 process_job 中的 check_and_repair_processor_results 處理
|
||||
// 這裡不需要額外操作
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn enforce_job_slot_limit(&self, limit: usize) -> Result<()> {
|
||||
if limit == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
||||
let videos_table = schema::table_name("videos");
|
||||
let processor_results_table = schema::table_name("processor_results");
|
||||
|
||||
// 可被暫停的 running jobs = 無 processor 在執行、且非全 completed(ingestion 中)
|
||||
let pausable_where = format!(
|
||||
"status = 'running'
|
||||
AND id NOT IN (
|
||||
SELECT DISTINCT job_id FROM {processor_results_table} WHERE status = 'running'
|
||||
)
|
||||
AND id NOT IN (
|
||||
SELECT job_id FROM {processor_results_table}
|
||||
GROUP BY job_id HAVING bool_and(status = 'completed')
|
||||
)"
|
||||
);
|
||||
|
||||
// 名額內可保留的 pausable jobs 數 = limit - 被佔用名額(有 processor 在跑的)
|
||||
let protected: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT count(DISTINCT job_id) FROM {processor_results_table} pr
|
||||
JOIN {monitor_jobs_table} mj ON mj.id = pr.job_id
|
||||
WHERE mj.status = 'running' AND pr.status = 'running'"
|
||||
))
|
||||
.fetch_one(self.db.pool())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let keep_count = limit.saturating_sub(protected as usize) as i64;
|
||||
|
||||
let demoted = sqlx::query(&format!(
|
||||
"UPDATE {monitor_jobs_table} SET status = 'paused', updated_at = NOW()
|
||||
WHERE {pausable_where}
|
||||
AND id NOT IN (
|
||||
SELECT id FROM (
|
||||
SELECT id FROM {monitor_jobs_table}
|
||||
WHERE {pausable_where}
|
||||
ORDER BY updated_at DESC
|
||||
LIMIT $1
|
||||
) keep
|
||||
)"
|
||||
))
|
||||
.bind(keep_count)
|
||||
.execute(self.db.pool())
|
||||
.await?
|
||||
.rows_affected();
|
||||
|
||||
if demoted > 0 {
|
||||
sqlx::query(&format!(
|
||||
"UPDATE {videos_table} SET status = 'registered', updated_at = NOW()
|
||||
WHERE status = 'scanning'
|
||||
AND file_uuid IN (SELECT uuid FROM {monitor_jobs_table} WHERE status = 'paused')"
|
||||
))
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
info!(
|
||||
"[BACKPRESSURE] running jobs 超過上限 {},已 paused {} 個 job(video 退回 registered)",
|
||||
limit, demoted
|
||||
);
|
||||
}
|
||||
|
||||
// 清理殘留:video 停在 scanning 但對應 job 已不是 running(pending/paused)
|
||||
// — 歷史重啟或暫停留下的不一致狀態
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {videos_table} SET status = 'registered', updated_at = NOW()
|
||||
WHERE status = 'scanning'
|
||||
AND file_uuid IN (SELECT uuid FROM {monitor_jobs_table} WHERE status IN ('pending', 'paused'))
|
||||
AND file_uuid NOT IN (SELECT uuid FROM {monitor_jobs_table} WHERE status = 'running')"
|
||||
))
|
||||
.execute(self.db.pool())
|
||||
.await;
|
||||
|
||||
// 名額釋出 → 恢復最舊的 paused jobs
|
||||
let running_now: i64 = sqlx::query_scalar(&format!(
|
||||
"SELECT count(*) FROM {monitor_jobs_table} WHERE status = 'running'"
|
||||
))
|
||||
.fetch_one(self.db.pool())
|
||||
.await
|
||||
.unwrap_or(0);
|
||||
let available = (limit as i64) - running_now;
|
||||
if available > 0 {
|
||||
let resumed = sqlx::query(&format!(
|
||||
"UPDATE {monitor_jobs_table} SET status = 'pending', updated_at = NOW()
|
||||
WHERE id IN (
|
||||
SELECT id FROM {monitor_jobs_table}
|
||||
WHERE status = 'paused' ORDER BY id LIMIT $1
|
||||
)"
|
||||
))
|
||||
.bind(available)
|
||||
.execute(self.db.pool())
|
||||
.await?
|
||||
.rows_affected();
|
||||
if resumed > 0 {
|
||||
info!(
|
||||
"[BACKPRESSURE] deep scan 名額釋出,恢復 {} 個 paused jobs → pending",
|
||||
resumed
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Layer 3d: 卡住偵測 → 自動 re-scan(unregister → register → deep scan)
|
||||
///
|
||||
/// 判定「卡住」(fingerprint 比對,不受空轉期間的 DB 寫入干擾):
|
||||
/// 1. job 仍在 running 且沒有任何 processor 正在執行
|
||||
/// 2. processor pool 完全閒置(沒有其他 job 在跑)— waiting 中的 job
|
||||
/// 只是排隊,不算卡住
|
||||
/// 3. 該 job 的 processor 狀態組合(fingerprint)持續
|
||||
/// MOMENTRY_STUCK_TIMEOUT_MIN(預設 10 分鐘)完全沒有變化
|
||||
/// 典型場景:dependency 永遠無法滿足(如 asrx 失敗 → asr ingestion 永遠
|
||||
/// waiting、face_trace 失敗 → face_cluster 永遠 deferred),job 每輪 poll
|
||||
/// 空轉、永遠無法完成。
|
||||
///
|
||||
/// 處理:對卡住的檔案自動 re-scan — 透過 command_queue 建立 register
|
||||
/// command(force=true → unregister → register → deep_scan),與 GUI 的
|
||||
/// re-scan 走完全相同路徑。每個檔案最多自動 re-scan
|
||||
/// MOMENTRY_AUTO_RESCAN_MAX(預設 2)次(Redis 計數、24 小時窗口),
|
||||
/// 避免對確定性失敗(如 codec 問題)無限重試。
|
||||
async fn detect_and_rescan_stuck_jobs(&self) -> Result<()> {
|
||||
// pool 忙碌時不做判定 — waiting 中的 job 只是排隊,不是卡住
|
||||
if self.processor_pool.get_running_count().await > 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let timeout_min: i64 = std::env::var("MOMENTRY_STUCK_TIMEOUT_MIN")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.filter(|v| *v > 0)
|
||||
.unwrap_or(10);
|
||||
let max_rescans: i64 = std::env::var("MOMENTRY_AUTO_RESCAN_MAX")
|
||||
.ok()
|
||||
.and_then(|v| v.parse::<i64>().ok())
|
||||
.filter(|v| *v >= 0)
|
||||
.unwrap_or(2);
|
||||
|
||||
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
||||
let videos_table = schema::table_name("videos");
|
||||
let processor_results_table = schema::table_name("processor_results");
|
||||
|
||||
// running 且無 processor 在執行的 jobs + 其 processor 狀態 fingerprint
|
||||
let candidates = sqlx::query_as::<_, (i32, String, Option<String>, Option<String>)>(&format!(
|
||||
"SELECT mj.id, mj.uuid, v.file_path,
|
||||
(SELECT string_agg(pr.status, ',' ORDER BY pr.processor)
|
||||
FROM {processor_results_table} pr WHERE pr.job_id = mj.id)
|
||||
FROM {monitor_jobs_table} mj
|
||||
JOIN {videos_table} v ON v.file_uuid = mj.uuid
|
||||
WHERE mj.status = 'running'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM {processor_results_table} pr
|
||||
WHERE pr.job_id = mj.id AND pr.status = 'running'
|
||||
)"
|
||||
))
|
||||
.fetch_all(self.db.pool())
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
|
||||
if candidates.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let prefix = crate::core::config::REDIS_KEY_PREFIX.as_str();
|
||||
|
||||
for (job_id, uuid, file_path, fingerprint) in candidates {
|
||||
let _ = job_id;
|
||||
let Some(fp) = fingerprint else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let Some(mut conn) = self.redis.get_conn().await.ok() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// fingerprint 與上次相同?用兩個 key 記錄內容與起始時間
|
||||
let fp_key = format!("{prefix}stuck_fp:{uuid}");
|
||||
let since_key = format!("{prefix}stuck_since:{uuid}");
|
||||
let prev_fp: Option<String> = redis::cmd("GET")
|
||||
.arg(&fp_key)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.unwrap_or(None);
|
||||
|
||||
if prev_fp.as_deref() != Some(fp.as_str()) {
|
||||
// 狀態有變化(或首次觀察)— 重新計時
|
||||
let _: Result<(), _> = redis::cmd("SET")
|
||||
.arg(&fp_key)
|
||||
.arg(&fp)
|
||||
.arg("EX")
|
||||
.arg(timeout_min * 60 * 3)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
let _: Result<(), _> = redis::cmd("SET")
|
||||
.arg(&since_key)
|
||||
.arg(now)
|
||||
.arg("EX")
|
||||
.arg(timeout_min * 60 * 3)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
|
||||
// fingerprint 未變 — 檢查持續時間
|
||||
let since: Option<i64> = redis::cmd("GET")
|
||||
.arg(&since_key)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.unwrap_or(None);
|
||||
let Some(since) = since else {
|
||||
let _: Result<(), _> = redis::cmd("SET")
|
||||
.arg(&since_key)
|
||||
.arg(now)
|
||||
.arg("EX")
|
||||
.arg(timeout_min * 60 * 3)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
continue;
|
||||
};
|
||||
if now - since < timeout_min * 60 {
|
||||
continue; // 還在觀察期內
|
||||
}
|
||||
|
||||
// ── 確認卡住 ──
|
||||
let Some(file_path) = file_path else {
|
||||
warn!("[STUCK-RESCAN] job {} 沒有 file_path,無法自動 re-scan", uuid);
|
||||
continue;
|
||||
};
|
||||
|
||||
// 每檔案自動 re-scan 次數上限(Redis 計數,24 小時窗口)
|
||||
let counter_key = format!("{prefix}auto_rescan:{uuid}");
|
||||
let rescan_count: i64 = redis::cmd("GET")
|
||||
.arg(&counter_key)
|
||||
.query_async::<Option<String>>(&mut conn)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|s| s.parse::<i64>().ok())
|
||||
.unwrap_or(0);
|
||||
if rescan_count >= max_rescans {
|
||||
warn!(
|
||||
"[STUCK-RESCAN] {} 卡住(fingerprint {} 分鐘未變)但已自動 re-scan {} 次(上限 {}),跳過 — 需人工檢查",
|
||||
uuid,
|
||||
(now - since) / 60,
|
||||
rescan_count,
|
||||
max_rescans
|
||||
);
|
||||
// 清除觀察 key,避免 log 每輪重複
|
||||
let _: Result<(), _> = redis::cmd("DEL").arg(&fp_key).query_async(&mut conn).await;
|
||||
let _: Result<(), _> = redis::cmd("DEL").arg(&since_key).query_async(&mut conn).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 與 GUI re-scan 相同:register command(force=true → unregister →
|
||||
// register → deep scan)。先將 job 標記 paused,避免 command 尚未
|
||||
// 執行的這一輪又被偵測重複排入。
|
||||
if let Err(e) = sqlx::query(&format!(
|
||||
"UPDATE {monitor_jobs_table} SET status = 'paused', updated_at = NOW()
|
||||
WHERE uuid = $1 AND status = 'running'"
|
||||
))
|
||||
.bind(&uuid)
|
||||
.execute(self.db.pool())
|
||||
.await
|
||||
{
|
||||
error!("[STUCK-RESCAN] 無法暫停卡住 job {}: {}", uuid, e);
|
||||
continue;
|
||||
}
|
||||
|
||||
let payload = serde_json::json!({
|
||||
"force": true,
|
||||
"deep_scan": true,
|
||||
"trigger_source": "worker_stuck_auto",
|
||||
});
|
||||
match self
|
||||
.db
|
||||
.create_command("register", Some(&file_path), None, None, &payload, 1)
|
||||
.await
|
||||
{
|
||||
Ok(cmd) => {
|
||||
info!(
|
||||
"[STUCK-RESCAN] job {} 卡住超過 {} 分鐘(fingerprint 無變化),已自動 re-scan(command={},第 {} 次)",
|
||||
uuid, timeout_min, cmd.command_id, rescan_count + 1
|
||||
);
|
||||
let _: Result<i64, _> = redis::cmd("INCR")
|
||||
.arg(&counter_key)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
let _: Result<(), _> = redis::cmd("EXPIRE")
|
||||
.arg(&counter_key)
|
||||
.arg(86_400i64)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
// 清除觀察 key(job 將被 unregister 刪除重建)
|
||||
let _: Result<(), _> = redis::cmd("DEL").arg(&fp_key).query_async(&mut conn).await;
|
||||
let _: Result<(), _> = redis::cmd("DEL").arg(&since_key).query_async(&mut conn).await;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("[STUCK-RESCAN] 為 {} 建立 re-scan command 失敗: {}", uuid, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -720,13 +1269,14 @@ impl JobWorker {
|
||||
.unwrap_or(false);
|
||||
let auto_pipeline_override = cmd
|
||||
.payload
|
||||
.get("auto_pipeline")
|
||||
.get("deep_scan")
|
||||
.or_else(|| cmd.payload.get("auto_pipeline")) // backward compat: in-flight old commands
|
||||
.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={}, auto_pipeline_override={})",
|
||||
"[COMMAND_QUEUE] Registering file: {} (user_id={:?}, force={}, deep_scan={})",
|
||||
file_path, user_id, force, auto_pipeline_override
|
||||
);
|
||||
|
||||
@@ -837,9 +1387,9 @@ impl JobWorker {
|
||||
async fn re_evaluate_stuck_processing(&self) -> Result<()> {
|
||||
info!("[RE-EVALUATE] Starting re-evaluation of stuck PROCESSING files");
|
||||
|
||||
// Get all PROCESSING videos
|
||||
// Get all PROCESSING/scanning videos
|
||||
let processing_videos = sqlx::query_as::<_, (String, String)>(&format!(
|
||||
"SELECT file_uuid, file_name FROM {} WHERE status = 'PROCESSING'",
|
||||
"SELECT file_uuid, file_name FROM {} WHERE status IN ('PROCESSING', 'scanning')",
|
||||
crate::core::db::schema::table_name("videos")
|
||||
))
|
||||
.fetch_all(self.db.pool())
|
||||
@@ -1067,31 +1617,13 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
for processor_type in &processors_to_run {
|
||||
// Check capacity BEFORE setting status to 'running'
|
||||
if !self.processor_pool.can_start_for_job(job.id).await {
|
||||
// 併發數已滿:保留 pending,下一輪 poll 再啟動。
|
||||
// 不可在此標記 skipped — 否則該處理器會被永久跳過
|
||||
//(這是 ocr / face / face_cluster 大量 skipped 的根因)。
|
||||
info!(
|
||||
"Max concurrent processors reached before starting {}, marking as skipped",
|
||||
"Max concurrent processors reached, {} deferred to next poll",
|
||||
processor_type.as_str()
|
||||
);
|
||||
if let Err(e) = self
|
||||
.db
|
||||
.upsert_processor_result(job_id, *processor_type, &job.uuid, "skipped")
|
||||
.await
|
||||
{
|
||||
error!("Failed to create skipped processor result: {}", e);
|
||||
}
|
||||
let _ = self
|
||||
.redis
|
||||
.update_worker_processor_status(
|
||||
&job.uuid,
|
||||
processor_type.as_str(),
|
||||
"skipped",
|
||||
None,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -2336,7 +2868,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
true
|
||||
};
|
||||
|
||||
// 4. Face Cluster: face_cluster.json 存在(有 face 時才需要)
|
||||
// 4. Face Cluster: face_cluster.json 存在 或 processor 已執行過
|
||||
let face_cluster_done: bool = if has_face {
|
||||
// No-face video: either explicit status or total_faces=0
|
||||
if trace_status == "no_faces" || total_faces == Some(0) {
|
||||
@@ -2357,7 +2889,24 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
true
|
||||
} else {
|
||||
let cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid);
|
||||
std::path::Path::new(&cluster_path).exists()
|
||||
let file_exists = std::path::Path::new(&cluster_path).exists();
|
||||
if file_exists {
|
||||
true
|
||||
} else {
|
||||
// 檔案不存在但 processor 已執行過(completed/failed),也算 done
|
||||
// 避免 processor 跑過但沒產出檔案時 ingestion 永遠卡住
|
||||
let fc_status: Option<String> = sqlx::query_scalar(&format!(
|
||||
"SELECT status FROM {pr_t} pr JOIN {mj_t} mj ON pr.job_id = mj.id \
|
||||
WHERE mj.uuid = $1 AND pr.processor = 'face_cluster' LIMIT 1",
|
||||
pr_t = schema::table_name("processor_results"),
|
||||
mj_t = schema::table_name("monitor_jobs")
|
||||
))
|
||||
.bind(uuid)
|
||||
.fetch_optional(pool)
|
||||
.await
|
||||
.unwrap_or(None);
|
||||
fc_status.as_deref() == Some("completed") || fc_status.as_deref() == Some("failed")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
true
|
||||
@@ -2498,10 +3047,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
} else {
|
||||
// scenes.json not found — check processor_results for scene_vlm completion
|
||||
// (e.g. "completed" due to invalid metadata / not applicable)
|
||||
let mj_t = schema::table_name("monitor_jobs");
|
||||
// Note: upsert_scene_vlm_result writes file_uuid + processor_type (not job_id + processor)
|
||||
let pr_t = schema::table_name("processor_results");
|
||||
let svlm_done: Option<String> = sqlx::query_scalar(&format!(
|
||||
"SELECT status FROM {pr_t} WHERE job_id = (SELECT id FROM {mj_t} WHERE uuid = $1) AND processor = 'scene_vlm' LIMIT 1"
|
||||
"SELECT status FROM {pr_t} WHERE file_uuid = $1 AND processor_type = 'scene_vlm' LIMIT 1"
|
||||
))
|
||||
.bind(uuid)
|
||||
.fetch_optional(pool)
|
||||
@@ -2536,6 +3085,115 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
all_ok
|
||||
}
|
||||
|
||||
/// Pipeline 完整性驗證:檢查所有必要產出是否存在
|
||||
///
|
||||
/// 在 job 完成前,驗證:
|
||||
/// 1. 所有處理器的 JSON 產出檔案存在
|
||||
/// 2. Trace 目錄完整(key_face.jpg + key_frame.jpg + trace_profile.json)
|
||||
/// 3. Scenes 目錄有 scene_*.jpg
|
||||
///
|
||||
/// 回傳缺項清單(空 = 完整)。如果有缺項則記錄警告,
|
||||
/// 讓 auto-repair 或 backfill 有機會修復。
|
||||
async fn verify_artifacts_complete(
|
||||
&self,
|
||||
uuid: &str,
|
||||
job_processors: &[String],
|
||||
) -> Result<Vec<String>> {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
let mut missing = Vec::new();
|
||||
|
||||
// 1. 檢查 JSON 產出
|
||||
let json_processors = [
|
||||
("cut", "cut"),
|
||||
("asrx", "asrx"),
|
||||
("face", "face"),
|
||||
("face_cluster", "face_cluster"),
|
||||
("face_trace", "face_traced"),
|
||||
("ocr", "ocr"),
|
||||
("scene_vlm", "scenes"),
|
||||
("probe", "probe"),
|
||||
];
|
||||
|
||||
for (proc_name, file_ext) in &json_processors {
|
||||
if job_processors.iter().any(|p| p == proc_name) {
|
||||
let json_path = format!("{}/{}.{}.json", output_dir, uuid, file_ext);
|
||||
if !std::path::Path::new(&json_path).exists() {
|
||||
// 如果 processor 已執行過(completed/failed),不算缺項
|
||||
// 避免 processor 跑過但沒產出檔案時 verification 永遠失敗
|
||||
let pr_t = schema::table_name("processor_results");
|
||||
let mj_t = schema::table_name("monitor_jobs");
|
||||
let proc_status: Option<String> = sqlx::query_scalar(&format!(
|
||||
"SELECT pr.status FROM {pr_t} pr JOIN {mj_t} mj ON pr.job_id = mj.id \
|
||||
WHERE mj.uuid = $1 AND pr.processor = $2 LIMIT 1"
|
||||
))
|
||||
.bind(uuid)
|
||||
.bind(proc_name)
|
||||
.fetch_optional(self.db.pool())
|
||||
.await
|
||||
.unwrap_or(None);
|
||||
if proc_status.as_deref() != Some("completed") && proc_status.as_deref() != Some("failed") {
|
||||
missing.push(format!("{}.json", file_ext));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 檢查 trace 目錄(如果有 faces)
|
||||
let face_json_path = format!("{}/{}.face.json", output_dir, uuid);
|
||||
if std::path::Path::new(&face_json_path).exists() {
|
||||
let trace_base = std::path::Path::new(&output_dir).join(uuid);
|
||||
if trace_base.is_dir() {
|
||||
if let Ok(entries) = std::fs::read_dir(&trace_base) {
|
||||
for entry in entries.filter_map(|e| e.ok()) {
|
||||
let name = entry.file_name().to_string_lossy().to_string();
|
||||
if name.starts_with("trace_") && entry.path().is_dir() {
|
||||
let trace_dir = entry.path();
|
||||
let trace_name = name;
|
||||
for required_file in ["key_face.jpg", "key_frame.jpg", "trace_profile.json"] {
|
||||
if !trace_dir.join(required_file).exists() {
|
||||
missing.push(format!("{}/{}", trace_name, required_file));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 檢查 scenes 目錄
|
||||
let scenes_json_path = format!("{}/{}.scenes.json", output_dir, uuid);
|
||||
if std::path::Path::new(&scenes_json_path).exists() {
|
||||
let scenes_dir = std::path::Path::new(&output_dir).join(uuid).join("scenes");
|
||||
if scenes_dir.is_dir() {
|
||||
let has_scene_jpgs = std::fs::read_dir(&scenes_dir)
|
||||
.map(|entries| {
|
||||
entries
|
||||
.filter_map(|e| e.ok())
|
||||
.any(|e| {
|
||||
e.file_name()
|
||||
.to_string_lossy()
|
||||
.starts_with("scene_")
|
||||
})
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if !has_scene_jpgs {
|
||||
missing.push("scenes/*.jpg".to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !missing.is_empty() {
|
||||
warn!(
|
||||
"[VERIFY] {} 缺少 {} 項產出: {}",
|
||||
uuid,
|
||||
missing.len(),
|
||||
missing.join(", ")
|
||||
);
|
||||
}
|
||||
|
||||
Ok(missing)
|
||||
}
|
||||
|
||||
async fn check_and_complete_job(
|
||||
&self,
|
||||
job_id: i32,
|
||||
@@ -2552,6 +3210,15 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
expected_count
|
||||
);
|
||||
|
||||
// ── Pipeline 完整性驗證:在完成前檢查所有必要產出 ──
|
||||
if let Err(e) = self.verify_artifacts_complete(uuid, job_processors).await {
|
||||
warn!(
|
||||
"[VERIFY] Artifact completeness check failed for {}: {}",
|
||||
uuid, e
|
||||
);
|
||||
// 不中止 job,只記錄警告 — 讓 auto-repair 有機會修復
|
||||
}
|
||||
|
||||
// Scene VLM 必要檢查 (deep scan = 有 cut):
|
||||
// - has_cut_job: job 是否含 cut 或 scene_vlm(決定 scene_vlm 是否必要)
|
||||
// - scene_vlm_complete: scenes.json 完整性
|
||||
|
||||
@@ -679,8 +679,10 @@ impl ProcessorPool {
|
||||
) -> Result<ProcessorOutput> {
|
||||
let video_path = job.video_path.as_ref().context("No video path in job")?;
|
||||
|
||||
// Generate output path
|
||||
let output_dir = PathBuf::from(OUTPUT_DIR.as_str());
|
||||
// Determine per-library output directory
|
||||
let output_dir = PathBuf::from(
|
||||
crate::core::config::get_output_dir_for_file_sync(&job.uuid, db.pool())
|
||||
);
|
||||
let suffix = format!("{}.{}", job.uuid, processor_type.as_str());
|
||||
let output_path = output_dir.join(format!("{}.json", suffix));
|
||||
|
||||
|
||||
+16
-7
@@ -141,8 +141,8 @@ impl SystemResources {
|
||||
fn get_memory_info() -> (u64, u64) {
|
||||
use std::process::Command;
|
||||
|
||||
// 總記憶體
|
||||
let total = Command::new("sysctl")
|
||||
// 總記憶體(用絕對路徑,避免 PATH 問題;sysctl 位於 /usr/sbin)
|
||||
let total = Command::new("/usr/sbin/sysctl")
|
||||
.args(["hw.memsize"])
|
||||
.output()
|
||||
.ok()
|
||||
@@ -158,7 +158,7 @@ impl SystemResources {
|
||||
|
||||
// 用 memory_pressure 取得真實可用記憶體
|
||||
// macOS 的可用記憶體 = free + inactive + speculative
|
||||
let available = Command::new("memory_pressure")
|
||||
let available = Command::new("/usr/bin/memory_pressure")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|o| {
|
||||
@@ -175,8 +175,8 @@ impl SystemResources {
|
||||
None
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
// fallback: vm_stat
|
||||
Command::new("vm_stat")
|
||||
// fallback: vm_stat(絕對路徑,位於 /usr/bin)
|
||||
let vm_stat_result = Command::new("/usr/bin/vm_stat")
|
||||
.output()
|
||||
.ok()
|
||||
.and_then(|v| {
|
||||
@@ -208,10 +208,19 @@ impl SystemResources {
|
||||
Some(
|
||||
(free_pages + inactive_pages + speculative_pages) * 16384 / 1024 / 1024,
|
||||
)
|
||||
})
|
||||
.unwrap_or(total / 4)
|
||||
});
|
||||
// Sanity check: if vm_stat failed or returned 0 (wrong PATH / parsing),
|
||||
// fall back to 1/4 of total instead of reporting 0MB (which would
|
||||
// wrongly trigger backpressure on machines with plenty of RAM).
|
||||
match vm_stat_result {
|
||||
Some(mb) if mb > 100 => mb,
|
||||
_ => total / 4,
|
||||
}
|
||||
});
|
||||
|
||||
// 最終 sanity check:memory_pressure 解析成功但回 0(例如 total=0)時也兜底
|
||||
let available = if available > 100 { available } else { total / 4 };
|
||||
|
||||
(available, total)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user