4 Commits

Author SHA1 Message Date
Accusys 8ff77d7dba fix: rust_asr_asrx extracts audio into ~/momentry/temp, auto-cleans
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
The extracted wav used to be written next to the source video
(<video>.wav), polluting the /library listing (002.wav, 025.wav leftovers).
- extract_audio now writes into MOMENTRY_TEMP_DIR (default ~/momentry/temp)
  with a unique per-run name (<stem>_asr_<millis>.wav) so concurrent jobs
  with the same basename cannot collide and mlx_whisper sidecar JSON is
  unique as well.
- TempAudioGuard removes the temp wav + /tmp/<stem>.json sidecar on every
  exit path (success, early bail, error).
- Verified: /library source dir stays clean, temp dir empty after run.
2026-11-09 12:15:30 +08:00
Accusys c1ede4ade8 fix: rust_asr_asrx handles MLX Whisper non-finite JSON literals
- MLX Whisper emits 'avg_logprob: NaN' / 'compression_ratio: Infinity' when a
  clip has no intelligible audio (e.g. near-silent test clips). serde_json
  strictly refuses those literals, so rust_asr_asrx failed with
  'expected value at line 1 column 151' and asrx never completed.
- Sanitize NaN / Infinity / -Infinity literals outside strings into null
  before parsing (sanitize_json_nonfinite).
- Add no-audio-track early-out. Clean up .wav byproduct after success.

Verified on dev (m5max48): 002.mp4 asrx re-scan now completes and produces
output/df6376c8....asrx.json; processor_results asrx = completed.
2026-11-09 12:02:19 +08:00
Accusys 5caecb887f fix: rebuild binary without MongoDB health check dependency
- Removed check_mongodb() from health.rs
- Health endpoint now depends only on PostgreSQL + Redis + Qdrant
- Regenerated .sqlx offline query cache (was incomplete, only 3 files)
- Binary rebuilt: target/release/momentry (47M, arm64)
- Deployed to 203 (m4promini)

Full clean-install + sample data install verified:
- clean-install.sh: ✅ (23 PASS / 0 FAIL)
- sample data: ✅ 100 videos, 899 processor_results, 100 monitor_jobs
- Health endpoint: status=ok (no MongoDB hang)
2026-11-08 23:39:53 +08:00
Accusys 4f4aa27da8 refactor: remove MongoDB from health check
- Removed check_mongodb() function from health.rs
- Health endpoint no longer requires MongoDB (status depends on PG+Redis+Qdrant only)
- ServiceHealth struct: mongodb field commented out
- Both health() and health_detailed() updated
- Removed MongoCache import

Note: Binary rebuild blocked by missing .sqlx cache files for
command/queue.rs and vlm/consumer.rs. Once build env is fixed:
  cd momentry_core && SQLX_OFFLINE=true cargo build --release
  cp target/release/momentry ../momentry/bin/momentry
2026-11-08 23:24:02 +08:00
26 changed files with 1046 additions and 82 deletions
@@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_requests\n SET \n status = 'completed',\n result = $1,\n processing_time_ms = $2,\n completed_at = NOW()\n WHERE id = $3\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Int8",
"Int8"
]
},
"nullable": []
},
"hash": "0373b02cc8de069f6e964bc023c4e29497cb66f8b0a181bafa73f175454e6903"
}
@@ -0,0 +1,27 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO command_queue (\n message_id, queue_name, queue_type,\n command_type, command_category,\n key, value, priority,\n request_id, key_id, billing_context,\n scheduled_at, max_retries,\n created_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Jsonb",
"Int2",
"Varchar",
"Varchar",
"Jsonb",
"Timestamptz",
"Int4",
"Timestamptz"
]
},
"nullable": []
},
"hash": "08adb7aafb3214ab7740baabcb6db8901c80dc5357008cd984f50d497fd416a2"
}
@@ -0,0 +1,34 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT status, result, error\n FROM vlm_requests\n WHERE id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "status",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "result",
"type_info": "Text"
},
{
"ordinal": 2,
"name": "error",
"type_info": "Text"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
true,
true
]
},
"hash": "1083cb140d49eed76e1f5081b88cbdca34f59052571490635dc8b1fdca3b1bd3"
}
@@ -1,15 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE dev.videos SET processing_status = $1 WHERE uuid = $2",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Jsonb",
"Text"
]
},
"nullable": []
},
"hash": "2d61eacd106ad5144c99a85c84f070924af9b29103a507e115674d1b14b77181"
}
@@ -1,14 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE dev.jobs SET status = 'COMPLETED', processed_frames = total_frames, updated_at = NOW() WHERE id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid"
]
},
"nullable": []
},
"hash": "345d912734b063a7b30d52c066045553964d0a55453a7e26a4d8b8d758be3857"
}
@@ -0,0 +1,50 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT command_type, command_category, queue_name, handler, priority, billing_required\n FROM queue_routes\n WHERE active = true\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "command_type",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "command_category",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "queue_name",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "handler",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "priority",
"type_info": "Int2"
},
{
"ordinal": 5,
"name": "billing_required",
"type_info": "Bool"
}
],
"parameters": {
"Left": []
},
"nullable": [
false,
true,
false,
false,
true,
true
]
},
"hash": "392a5b8ec9b3f9cf1736d47eeecaa1fe87ffa62024146c3d2c37bf028d954b3f"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_consumer_offsets\n SET current_offset = $1, last_poll_at = NOW()\n WHERE consumer_id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "3d7027dffb815b8a40e5525c9065bdd3173ff567cf8b7b299ad56f5b4cfb49de"
}
@@ -0,0 +1,18 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE command_queue\n SET status = $2,\n processing_completed_at = $3,\n token_usage = $4,\n cost_usd = $5\n WHERE message_id = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Varchar",
"Timestamptz",
"Jsonb",
"Float8"
]
},
"nullable": []
},
"hash": "4580e475bf8395911bbf9b36660094cf4483a4d4dcbe3dc7b5437904aeb86780"
}
@@ -0,0 +1,24 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO vlm_requests (request_type, priority, payload, status)\n VALUES ($1, $2, $3, 'pending')\n RETURNING id\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Varchar",
"Int4",
"Jsonb"
]
},
"nullable": [
false
]
},
"hash": "5bc08af47af66dc518afee2939f2fb33ea3384c63226fc474043346225923fcc"
}
@@ -0,0 +1,164 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE command_queue\n SET status = 'processing',\n consumer_group = $1,\n consumer_id = $2,\n processing_started_at = NOW(),\n timeout_at = NOW() + ($5::bigint * INTERVAL '1 second')\n WHERE message_id IN (\n SELECT message_id\n FROM command_queue\n WHERE queue_name = $3\n AND status = 'pending'\n AND (scheduled_at IS NULL OR scheduled_at <= NOW())\n ORDER BY priority ASC, created_at ASC\n LIMIT $4\n FOR UPDATE SKIP LOCKED\n )\n RETURNING\n message_id, queue_name, queue_type,\n command_type, command_category, command_action,\n key, value, priority,\n request_id, key_id, billing_context, token_usage, cost_usd,\n status, consumer_group, consumer_id,\n retry_count, max_retries, last_error,\n created_at, scheduled_at, processing_started_at, processing_completed_at\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "message_id",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "queue_name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "queue_type",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "command_type",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "command_category",
"type_info": "Varchar"
},
{
"ordinal": 5,
"name": "command_action",
"type_info": "Varchar"
},
{
"ordinal": 6,
"name": "key",
"type_info": "Varchar"
},
{
"ordinal": 7,
"name": "value",
"type_info": "Jsonb"
},
{
"ordinal": 8,
"name": "priority",
"type_info": "Int2"
},
{
"ordinal": 9,
"name": "request_id",
"type_info": "Varchar"
},
{
"ordinal": 10,
"name": "key_id",
"type_info": "Varchar"
},
{
"ordinal": 11,
"name": "billing_context",
"type_info": "Jsonb"
},
{
"ordinal": 12,
"name": "token_usage",
"type_info": "Jsonb"
},
{
"ordinal": 13,
"name": "cost_usd",
"type_info": "Float8"
},
{
"ordinal": 14,
"name": "status",
"type_info": "Varchar"
},
{
"ordinal": 15,
"name": "consumer_group",
"type_info": "Varchar"
},
{
"ordinal": 16,
"name": "consumer_id",
"type_info": "Varchar"
},
{
"ordinal": 17,
"name": "retry_count",
"type_info": "Int4"
},
{
"ordinal": 18,
"name": "max_retries",
"type_info": "Int4"
},
{
"ordinal": 19,
"name": "last_error",
"type_info": "Text"
},
{
"ordinal": 20,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 21,
"name": "scheduled_at",
"type_info": "Timestamptz"
},
{
"ordinal": 22,
"name": "processing_started_at",
"type_info": "Timestamptz"
},
{
"ordinal": 23,
"name": "processing_completed_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Text",
"Int8",
"Int8"
]
},
"nullable": [
false,
false,
false,
false,
true,
true,
true,
false,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true
]
},
"hash": "5f27ef47fc166a0bb8f8a26ccbd7418710e3bbb280af10935ffb2eddffcd33e4"
}
@@ -1,15 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE dev.jobs SET status = 'FAILED', error_message = $2, updated_at = NOW() WHERE id = $1",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Uuid",
"Text"
]
},
"nullable": []
},
"hash": "60cc008705cfea3a4532b9496db8f6ed0e3023436660bdf8ee81fe78fe270971"
}
@@ -0,0 +1,14 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_requests\n SET status = 'processing', started_at = NOW()\n WHERE id = ANY($1)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8Array"
]
},
"nullable": []
},
"hash": "66ef83b7ad3fe95922fb2aa9a083ed55b14c5b4d7dd6b9ada1659d6060780533"
}
@@ -0,0 +1,24 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO vlm_requests (request_type, priority, payload, status)\n VALUES ($1, $2, $3, 'pending')\n RETURNING id\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
}
],
"parameters": {
"Left": [
"Varchar",
"Int4",
"Jsonb"
]
},
"nullable": [
false
]
},
"hash": "748de226872459680cdd121b4b27369b73ae2edfeb9c75c03f1b8e240cb55f0c"
}
@@ -0,0 +1,23 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO command_execution_log (\n message_id, handler, action, status,\n result, error_message,\n duration_ms, tokens_used, cost_usd,\n executed_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Varchar",
"Varchar",
"Varchar",
"Varchar",
"Jsonb",
"Text",
"Int4",
"Int4",
"Float8",
"Timestamptz"
]
},
"nullable": []
},
"hash": "7b3d7e7af47f2f91193229925454e22e1ef1a8fec81174092b926880ca36a118"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_requests\n SET status = 'failed', error = $1, completed_at = NOW()\n WHERE id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Int8"
]
},
"nullable": []
},
"hash": "7d4e34cc4505455b678b45b2f884021a6cf786e0e86d8f15f1b324e6a8bcfac9"
}
@@ -0,0 +1,16 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE command_queue\n SET status = 'failed',\n processing_completed_at = $3,\n last_error = $2,\n retry_count = retry_count + 1\n WHERE message_id = $1\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text",
"Timestamptz"
]
},
"nullable": []
},
"hash": "89d0f71757cf23b1a02923e97ed0c1921cafbdd69844e43c41c00222d5595f18"
}
@@ -0,0 +1,17 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_consumer_offsets\n SET \n total_processed = total_processed + $1,\n total_succeeded = total_succeeded + $2,\n total_failed = total_failed + $3\n WHERE consumer_id = $4\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Int8",
"Int8",
"Text"
]
},
"nullable": []
},
"hash": "8fb9ba962eb0fc70bca83f7523afe081285a79aacaf5821d2e41f7539c57ced6"
}
@@ -0,0 +1,19 @@
{
"db_name": "PostgreSQL",
"query": "\n INSERT INTO vlm_dlq (original_id, original_request_type, original_priority, original_payload, error, retry_count)\n VALUES ($1, $2, $3, $4, $5, $6)\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Int8",
"Varchar",
"Int4",
"Jsonb",
"Text",
"Int4"
]
},
"nullable": []
},
"hash": "961e59ccb11c4e1674573d1e55e61dea1aa9eb9c78e506ba42aa1a42b891bf27"
}
@@ -0,0 +1,160 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT\n message_id, queue_name, queue_type,\n command_type, command_category, command_action,\n key, value, priority,\n request_id, key_id, billing_context, token_usage, cost_usd,\n status, consumer_group, consumer_id,\n retry_count, max_retries, last_error,\n created_at, scheduled_at, processing_started_at, processing_completed_at\n FROM command_queue\n WHERE message_id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "message_id",
"type_info": "Varchar"
},
{
"ordinal": 1,
"name": "queue_name",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "queue_type",
"type_info": "Varchar"
},
{
"ordinal": 3,
"name": "command_type",
"type_info": "Varchar"
},
{
"ordinal": 4,
"name": "command_category",
"type_info": "Varchar"
},
{
"ordinal": 5,
"name": "command_action",
"type_info": "Varchar"
},
{
"ordinal": 6,
"name": "key",
"type_info": "Varchar"
},
{
"ordinal": 7,
"name": "value",
"type_info": "Jsonb"
},
{
"ordinal": 8,
"name": "priority",
"type_info": "Int2"
},
{
"ordinal": 9,
"name": "request_id",
"type_info": "Varchar"
},
{
"ordinal": 10,
"name": "key_id",
"type_info": "Varchar"
},
{
"ordinal": 11,
"name": "billing_context",
"type_info": "Jsonb"
},
{
"ordinal": 12,
"name": "token_usage",
"type_info": "Jsonb"
},
{
"ordinal": 13,
"name": "cost_usd",
"type_info": "Float8"
},
{
"ordinal": 14,
"name": "status",
"type_info": "Varchar"
},
{
"ordinal": 15,
"name": "consumer_group",
"type_info": "Varchar"
},
{
"ordinal": 16,
"name": "consumer_id",
"type_info": "Varchar"
},
{
"ordinal": 17,
"name": "retry_count",
"type_info": "Int4"
},
{
"ordinal": 18,
"name": "max_retries",
"type_info": "Int4"
},
{
"ordinal": 19,
"name": "last_error",
"type_info": "Text"
},
{
"ordinal": 20,
"name": "created_at",
"type_info": "Timestamptz"
},
{
"ordinal": 21,
"name": "scheduled_at",
"type_info": "Timestamptz"
},
{
"ordinal": 22,
"name": "processing_started_at",
"type_info": "Timestamptz"
},
{
"ordinal": 23,
"name": "processing_completed_at",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false,
false,
false,
false,
true,
true,
true,
false,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true
]
},
"hash": "a09f617a37776df57c4e711b25e62075db983095764bb5f2bae1e3dfddc3b243"
}
@@ -0,0 +1,40 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT \n id as offset,\n request_type,\n priority,\n payload\n FROM vlm_requests\n WHERE status = 'pending'\n ORDER BY priority ASC, created_at ASC\n LIMIT $1\n FOR UPDATE SKIP LOCKED\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "offset",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "request_type",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "priority",
"type_info": "Int4"
},
{
"ordinal": 3,
"name": "payload",
"type_info": "Jsonb"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
true,
false
]
},
"hash": "ab09a5b7e35daf5fa5085ce9a986c9d58de60f4b9ffc0a127a7d17694d42277a"
}
@@ -0,0 +1,46 @@
{
"db_name": "PostgreSQL",
"query": "\n SELECT id, request_type, payload, retry_count, priority\n FROM vlm_requests\n WHERE id = $1\n ",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "id",
"type_info": "Int8"
},
{
"ordinal": 1,
"name": "request_type",
"type_info": "Varchar"
},
{
"ordinal": 2,
"name": "payload",
"type_info": "Jsonb"
},
{
"ordinal": 3,
"name": "retry_count",
"type_info": "Int4"
},
{
"ordinal": 4,
"name": "priority",
"type_info": "Int4"
}
],
"parameters": {
"Left": [
"Int8"
]
},
"nullable": [
false,
false,
false,
true,
true
]
},
"hash": "ec65769979d98dae69f4bb8ef280bb55ec401b86eaa01e80e63833654125733d"
}
@@ -0,0 +1,15 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE vlm_requests\n SET \n status = 'pending',\n retry_count = retry_count + 1,\n error = $1\n WHERE id = $2\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Int8"
]
},
"nullable": []
},
"hash": "fff0adae6b82b647111a1d27ac7c0a9e15311a8bacd4c1a5b7229e511df45954"
}
+59
View File
@@ -0,0 +1,59 @@
# 移除 MongoDB 依賴 — 變更說明
## 問題
m5max128 (192.168.110.200) 的 `/api/v1/health` 端點掛住,因為 health check
等待 MongoDB 連線回應,但該機器未安裝 MongoDB。
## 修改內容
### `src/api/health.rs`
| 變更 | 說明 |
|---|---|
| 移除 `MongoCache` import | 不再需要 MongoDB 型別 |
| 移除 `check_mongodb()` 函數 | 不再檢查 MongoDB 健康狀態 |
| `health()` 函數 | `all_ok` 條件改為只檢查 PostgreSQL + Redis + Qdrant |
| `health_detailed()` 函數 | 同上,移除 MongoDB 檢查 |
| `ServiceHealth` struct | `mongodb` 欄位註解化 |
### 影響範圍
- Health 端點不再依賴 MongoDB
- `AppState` 中的 `mongo_cache` 欄位仍保留(供其他功能使用)
- server.rs 中的 MongoDB 初始化(5 秒 timeout → disabled fallback)維持原樣
## 重新編譯
### 目前阻礙
`.sqlx/` 目錄只有 3 個查詢快取檔案,缺少:
- `command/queue.rs` 的查詢快取
- `vlm/consumer.rs` 的查詢快取
### 解決步驟
```bash
# 方法 1: 完整 .sqlx 快取(需要連線到 DB)
cd /Users/accusys/momentry_core
export DATABASE_URL="postgres://accusys@localhost:5432/momentry"
cargo sqlx prepare
SQLX_OFFLINE=true cargo build --release
# 方法 2: 修復現有查詢錯誤後再編譯
# 檢查 src/core/command/queue.rs 和 src/core/vlm/consumer.rs 的 sqlx 巨集
# 編譯完成後替換 binary
cp target/release/momentry ../momentry/bin/momentry
```
### 部署到 203 (m4promini)
```bash
scp target/release/momentry accusys@192.168.110.203:~/momentry/bin/momentry
ssh accusys@192.168.110.203 'launchctl stop com.momentry.server && launchctl start com.momentry.server'
```
## 驗證
重啟後測試:
```bash
curl -s -m 10 http://localhost:3002/api/v1/health
# 應回傳: {"status":"ok", ...} 而不是超時
```
## Git commit
`4f4aa27d` on branch `feature/dynamic-concurrency-v1.3.4`
+15 -32
View File
@@ -4,7 +4,6 @@ use serde::Serialize;
use std::time::Instant;
use super::types::AppState;
use crate::core::cache::MongoCache;
use crate::core::config;
use crate::core::db::{Database, PostgresDb, RedisClient};
use crate::core::db::qdrant_db::new_http_client;
@@ -181,7 +180,7 @@ struct ServiceHealth {
postgres: ServiceStatus,
redis: ServiceStatus,
qdrant: ServiceStatus,
mongodb: ServiceStatus,
// mongodb: ServiceStatus, // Removed - now using Redis only
}
#[derive(Debug, Serialize)]
@@ -195,12 +194,11 @@ pub async fn health(State(state): State<AppState>) -> Json<HealthResponse> {
let postgres = check_postgres().await;
let redis = check_redis().await;
let qdrant = check_qdrant().await;
let mongodb = check_mongodb(&state.mongo_cache).await;
// MongoDB removed — no longer required
let all_ok = postgres.status == "ok"
&& redis.status == "ok"
&& qdrant.status == "ok"
&& mongodb.status == "ok";
&& qdrant.status == "ok";
let status = if all_ok { "ok" } else { "degraded" };
@@ -228,12 +226,11 @@ pub async fn health_detailed(State(state): State<AppState>) -> Json<DetailedHeal
let postgres = check_postgres().await;
let redis = check_redis().await;
let qdrant = check_qdrant().await;
let mongodb = check_mongodb(&state.mongo_cache).await;
// MongoDB removed — no longer required
let overall_status = if postgres.status == "ok"
&& redis.status == "ok"
&& qdrant.status == "ok"
&& mongodb.status == "ok"
{
"ok"
} else {
@@ -339,7 +336,7 @@ pub async fn health_detailed(State(state): State<AppState>) -> Json<DetailedHeal
postgres,
redis,
qdrant,
mongodb,
// mongodb, // Removed
},
resources: ResourceStatus {
cpu_used_percent: sys.cpu_used_percent,
@@ -532,22 +529,6 @@ async fn check_qdrant() -> ServiceStatus {
}
}
async fn check_mongodb(cache: &MongoCache) -> ServiceStatus {
let start = Instant::now();
match cache.health_check().await {
Ok(_) => ServiceStatus {
status: "ok".to_string(),
latency_ms: Some(start.elapsed().as_millis() as u64),
error: None,
},
Err(e) => ServiceStatus {
status: "error".to_string(),
latency_ms: Some(start.elapsed().as_millis() as u64),
error: Some(e.to_string()),
},
}
}
fn parse_required_migrations() -> Vec<MigrationInfo> {
let raw = env!("REQUIRED_MIGRATIONS");
if raw.is_empty() {
@@ -631,19 +612,21 @@ async fn check_rsync() -> ServiceStatus {
/// Check worker liveness via Redis health key TTL.
/// Returns true if the Worker's Redis health key exists and has remaining TTL > 0.
pub async fn check_worker_alive(state: &AppState) -> bool {
pub async fn check_worker_alive(_state: &AppState) -> bool {
let health_key = format!("{}health", crate::core::config::REDIS_KEY_PREFIX.as_str());
let client = state.redis_cache.get_client().await;
let guard = client.write().await;
if let Ok(mut conn) = guard.get_conn().await {
// Use a fresh client (same pattern as check_redis) instead of the shared
// redis_cache client: the shared client's RwLock can be held indefinitely
// by a task stalled on redis reconnect, deadlocking every health check.
let client = match RedisClient::new() {
Ok(c) => c,
Err(_) => return false,
};
if let Ok(mut conn) = client.get_conn().await {
let ttl: Result<i64, _> = redis::cmd("TTL")
.arg(&[health_key.as_str()])
.query_async(&mut conn)
.await;
match ttl {
Ok(ttl) if ttl > 0 => return true,
_ => return false,
}
return matches!(ttl, Ok(ttl) if ttl > 0);
}
false
}
+17
View File
@@ -76,9 +76,26 @@ pub async fn process_asr_asrx(
})
.unwrap_or_default();
// Clean up wav byproduct after successful processing.
cleanup_wav_byproduct(video_path);
Ok(AsrAsrxResult {
language,
segments,
recovery,
})
}
/// Clean up the .wav audio byproduct left by rust_asr_asrx.
/// The wav file is created next to the video with the same base name.
fn cleanup_wav_byproduct(video_path: &str) {
let mut wav_path = std::path::PathBuf::from(video_path);
wav_path.set_extension("wav");
if wav_path.exists() {
if let Err(e) = std::fs::remove_file(&wav_path) {
tracing::warn!("[ASR_ASRX] Failed to cleanup {}: {}", wav_path.display(), e);
} else {
tracing::info!("[ASR_ASRX] Cleaned up wav byproduct: {}", wav_path.display());
}
}
}
+218 -6
View File
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
use serde_json::json;
use std::collections::BTreeMap;
use std::io::Write;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;
@@ -571,10 +571,54 @@ fn main() -> Result<()> {
anyhow::bail!("Input file not found: {}", cli.input);
}
// Step 1: Extract audio (if video)
// Step 1: Check for audio track and extract (if video)
if is_video_file(&cli.input) {
println!("[1/7] Checking for audio track...");
if !has_audio_track(&cli.input) {
println!("[ASR-ASRX] No audio track found in video, skipping ASR");
// Write empty output with no_audio_track status
let empty_output = serde_json::json!({
"status": "no_audio_track",
"language": null,
"n_speakers": 0,
"segments": [],
"speaker_stats": {},
"processing_time": {
"total": 0.0
},
"garbled_fallback": false,
"recovery": {
"triggered": false,
"final_result": "no_audio_track",
"attempts": [],
"garbled_check_enabled": false,
"language_candidates": [],
"no_intelligible_speech": false
},
"processor": "rust_asr_asrx",
"model": cli.model,
"source": cli.input
});
let output_path = Path::new(&cli.output);
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent).ok();
}
std::fs::write(&cli.output, serde_json::to_string_pretty(&empty_output)?)
.context("Failed to write output")?;
println!("[ASR-ASRX] Output: {}", cli.output);
println!("[ASR-ASRX] Done in 0.0s (no audio track)");
return Ok(());
}
}
println!("[1/7] Extracting audio...");
let temp_guard = TempAudioGuard::default();
let audio_path = if is_video_file(&cli.input) {
extract_audio(&cli.input)?
let p = extract_audio(&cli.input)?;
temp_guard.set(&p);
p
} else {
cli.input.clone()
};
@@ -730,6 +774,64 @@ fn print_recovery_summary(kind: &str, attempts: &[serde_json::Value], garbled_fa
}
}
/// Get ffmpeg path from environment variable or default to "ffmpeg"
fn get_ffmpeg_path() -> String {
std::env::var("MOMENTRY_FFMPEG")
.unwrap_or_else(|_| "ffmpeg".to_string())
}
/// Check if a video file has an audio track
/// Tries ffprobe first, then falls back to ffmpeg metadata check
fn has_audio_track(input: &str) -> bool {
// Try ffprobe first (preferred)
let ffprobe_result = std::process::Command::new("ffprobe")
.args(&[
"-v", "error",
"-select_streams", "a",
"-show_entries", "stream=codec_type",
"-of", "csv=p=0",
input,
])
.output();
if let Ok(out) = ffprobe_result {
let stdout = String::from_utf8_lossy(&out.stdout);
if !stdout.trim().is_empty() {
return stdout.trim().contains("audio");
}
}
// Fallback: try ffmpeg to extract audio and check if it succeeds
// Use a temp file and check if ffmpeg can extract audio
let temp_audio = format!("/tmp/asr_audio_check_{}.wav", std::process::id());
let ffmpeg_result = std::process::Command::new(get_ffmpeg_path())
.args(&[
"-y",
"-i", input,
"-vn",
"-acodec", "pcm_s16le",
"-ar", "16000",
"-ac", "1",
"-t", "1", // Just extract 1 second to check
&temp_audio,
])
.output();
// Clean up temp file
let _ = std::fs::remove_file(&temp_audio);
match ffmpeg_result {
Ok(out) => out.status.success(),
Err(_) => {
// If both fail, assume there might be audio
// The extraction step will handle the actual error
true
}
}
}
fn is_video_file(path: &str) -> bool {
let ext = Path::new(path)
.extension()
@@ -739,10 +841,68 @@ fn is_video_file(path: &str) -> bool {
matches!(ext.to_lowercase().as_str(), "mp4" | "mkv" | "avi" | "mov")
}
fn extract_audio(input: &str) -> Result<String> {
let output = input.replace(".mp4", ".wav").replace(".mkv", ".wav");
/// Resolve the processor temp dir: `MOMENTRY_TEMP_DIR` env override, default
/// `~/momentry/temp`. Process artifacts (extracted wav etc.) must never be
/// written next to the source file — that pollutes the library listing.
fn process_temp_dir() -> PathBuf {
let dir = std::env::var("MOMENTRY_TEMP_DIR")
.map(PathBuf::from)
.unwrap_or_else(|_| {
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home).join("momentry/temp")
});
if !dir.exists() {
let _ = std::fs::create_dir_all(&dir);
}
dir
}
let status = Command::new("ffmpeg")
/// RAII guard: removes the extracted temp audio (and the mlx_whisper JSON
/// sidecar derived from its stem) when it goes out of scope — success, early
/// bail, or error all end the function, and Drop fires either way.
#[derive(Default)]
struct TempAudioGuard {
audio_path: std::cell::Cell<Option<String>>,
}
impl TempAudioGuard {
fn set(&self, path: &str) {
self.audio_path.set(Some(path.to_string()));
}
}
impl Drop for TempAudioGuard {
fn drop(&mut self) {
if let Some(audio) = self.audio_path.take() {
let _ = std::fs::remove_file(&audio);
if let Some(stem) = Path::new(&audio).file_stem().and_then(|s| s.to_str()) {
let sidecar = format!("/tmp/{}.json", stem);
let _ = std::fs::remove_file(&sidecar);
}
println!("[ASR-ASRX] cleaned temp audio: {}", audio);
}
}
}
fn extract_audio(input: &str) -> Result<String> {
let temp_dir = process_temp_dir();
let stem = Path::new(input)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("audio")
.to_string();
// Unique per run: concurrent jobs with the same basename won't collide,
// and no stray wav ever appears in the source directory.
let millis = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis())
.unwrap_or(0);
let output = temp_dir
.join(format!("{}_asr_{}.wav", stem, millis))
.to_string_lossy()
.to_string();
let status = Command::new(get_ffmpeg_path())
.args(&[
"-y",
"-i",
@@ -804,6 +964,53 @@ fn run_vad(audio_path: &str, vad_model: &str) -> Result<Vec<(f64, f64)>> {
.collect())
}
/// Replace JSON non-finite literals (`NaN`, `Infinity`, `-Infinity`) with `null`
/// when they appear outside string literals. Python's `json` module emits these
/// (allow_nan=True), but serde_json strictly refuses to parse them.
fn sanitize_json_nonfinite(input: &str) -> String {
let mut out = String::with_capacity(input.len() + 16);
let mut in_string = false;
let mut escaped = false;
let mut chars = input.char_indices().peekable();
while let Some((idx, ch)) = chars.next() {
if in_string {
out.push(ch);
if escaped {
escaped = false;
} else if ch == '\\' {
escaped = true;
} else if ch == '"' {
in_string = false;
}
continue;
}
let rest = &input[idx..];
if rest.starts_with("NaN") {
out.push_str("null");
// skip "aN"
for _ in 0..2 {
chars.next();
}
} else if rest.starts_with("Infinity") {
out.push_str("null");
// skip "nfinity"
for _ in 0..7 {
chars.next();
}
} else if rest.starts_with("-Infinity") {
out.push_str("null");
// skip "Infinity"
for _ in 0..8 {
chars.next();
}
} else {
out.push(ch);
}
}
out
}
fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Result<AsrResult> {
let mut args = vec![
audio_path.to_string(),
@@ -847,6 +1054,11 @@ fn run_mlx_whisper(audio_path: &str, model: &str, language: Option<&str>) -> Res
let json_content =
std::fs::read_to_string(&json_path).context("Failed to read MLX Whisper output")?;
// MLX Whisper emits non-strict JSON (avg_logprob: NaN, compression_ratio:
// Infinity, ...) whenever a run has no meaningful audio, so serde fails with
// "expected value". Sanitize non-finite literals outside strings → null.
let json_content = sanitize_json_nonfinite(&json_content);
let json: serde_json::Value = serde_json::from_str(&json_content)?;
let segments = json["segments"]