release: v1.3.1 - Pipeline Queue Integration, OCR Fix, Worker Compatibility

Major Changes:
- Pipeline Queue integration completed (internal.file + pipeline.commands)
- Fixed old job_worker database compatibility with new command_queue table
- Compiled Swift OCR binary (was missing, causing empty OCR results)
- Added deep scan functionality through re-scan API

Fixes:
- Changed CommandJob.id from i32 to i64 for database compatibility
- Added UUID generation in create_command (message_id field)
- Fixed claim_pending_commands to query queue_name = 'internal.file'
- Fixed field mappings: command_id → message_id, job_type → command_type
- Added support for 'processing' status in CommandJobStatus

Queue System:
- internal.file queue: for register/unregister/re-scan commands (job_worker)
- pipeline.commands queue: for vectorize/store_asrx/etc commands (pipeline_worker)

Documentation:
- Added comprehensive queue system documentation
- Created M4 workspace status reports
- Updated AGENTS.md with queue system details
This commit is contained in:
Accusys
2026-10-12 10:00:51 +08:00
parent 0a18e70639
commit 63fbbe1225
418 changed files with 44084 additions and 4280 deletions
@@ -0,0 +1,764 @@
# Momentry Core 新队列架构系统说明
**版本**: V1.0
**日期**: 2026-10-11
**状态**: 生产就绪
---
## 🎯 系统概述
Momentry Core 现在包含三个队列系统:
| 队列系统 | 用途 | 数据存储 | 状态 |
|---------|------|---------|------|
| **命令队列** | 文件注册/注销 | PostgreSQL `command_queue` | ✅ 运行中 |
| **任务队列** | 文件处理流水线 | PostgreSQL `monitor_jobs` | ✅ 运行中 |
| **VLM 队列** | VLM 请求调度 | PostgreSQL `vlm_requests` | ✅ 已实施 |
---
## 🏗️ 系统架构图
```
┌─────────────────────────────────────────────────────────────────┐
│ Momentry Core 系统 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────┐ ┌──────────────────┐ ┌────────────────┐│
│ │ 命令队列 │ │ 任务队列 │ │ VLM 队列 ││
│ │ │ │ │ │ ││
│ │ command_queue │ │ monitor_jobs │ │ vlm_requests ││
│ │ ├─ register │ │ ├─ ASR │ │ ├─ Agent VLM ││
│ │ └─ unregister │ │ ├─ Face │ │ ├─ Scene VLM ││
│ │ │ │ ├─ OCR │ │ └─ Face VLM ││
│ │ 优先级: P2 │ │ └─ ... │ │ ││
│ │ │ │ 优先级: P3 │ │ 优先级: P0-P1 ││
│ └──────────────────┘ └──────────────────┘ └────────────────┘│
│ │
│ ┌──────────────────────────────────────────────────────────────┐│
│ │ Job Worker (主进程) ││
│ │ ├─ 轮询命令队列 (每 5 秒) ││
│ │ ├─ 轮询任务队列 (每 5 秒) ││
│ │ ├─ 初始化 VLM Workers ││
│ │ └─ 管理 ProcessorPool ││
│ └──────────────────────────────────────────────────────────────┘│
│ │
│ ┌──────────────────────────────────────────────────────────────┐│
│ │ VLM Workers (独立线程) ││
│ │ ├─ Worker 0: Agent VLM (P0 - 最高优先级) ││
│ │ ├─ Worker 1: Scene/Face VLM (P1) ││
│ │ └─ Worker 2: Scene/Face VLM (P1) ││
│ └──────────────────────────────────────────────────────────────┘│
│ │
│ ┌──────────────────────────────────────────────────────────────┐│
│ │ API Server (HTTP) ││
│ │ ├─ REST API (port 3002) ││
│ │ ├─ 文件注册 API ││
│ │ ├─ 搜索 API ││
│ │ └─ VLM 队列状态 API ││
│ └──────────────────────────────────────────────────────────────┘│
│ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ 数据存储层 │
├─────────────────────────────────────────────────────────────────┤
│ PostgreSQL │ Redis │ Qdrant │
│ ├─ command_queue │ ├─ 进度缓存 │ ├─ 向量索引 │
│ ├─ monitor_jobs │ ├─ Pub/Sub │ └─ Face embeddings │
│ ├─ vlm_requests │ └─ 健康检查 │ │
│ ├─ vlm_dlq │ │ │
│ └─ videos │ │ │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ 外部服务 │
├─────────────────────────────────────────────────────────────────┤
│ LLM Services │ File Storage │ Processors │
│ ├─ Chat (8080) │ ├─ 输出目录 │ ├─ FFmpeg │
│ └─ VLM (8080) │ └─ MarkBase │ ├─ Python scripts │
│ │ │ └─ Swift CLI │
└─────────────────────────────────────────────────────────────────┘
```
---
## 👥 系统角色与职责
### 1. API Server (HTTP Server)
**角色**: HTTP API 端点服务
**职责**:
- ✅ 提供 REST API
- ✅ 处理文件注册请求
- ✅ 提交命令到命令队列
- ✅ 提供搜索服务
- ✅ 提供 VLM 队列状态查询
**启动方式**:
```bash
# 方式 1: launchd (生产环境)
launchctl start gui/$(id -u)/com.momentry.server
# 方式 2: 手动启动
cargo run --release -- server --port 3002
# 方式 3: 后台运行
./target/release/momentry server > logs/momentry_3002.log 2>&1 &
```
**端口**: 3002
**日志**: `logs/momentry_3002.log`
---
### 2. Job Worker (主进程)
**角色**: 队列消费者与任务调度器
**职责**:
- ✅ 轮询 `command_queue` 处理注册/注销命令
- ✅ 轮询 `monitor_jobs` 处理文件处理任务
- ✅ 初始化 VLM Workers
- ✅ 管理 ProcessorPool 并发控制
- ✅ 健康检查与错误恢复
**启动方式**:
```bash
# 方式 1: launchd (生产环境)
launchctl start gui/$(id -u)/com.momentry.worker
# 方式 2: 与 API Server 一起启动
cargo run --release -- server
# 注意: API Server 和 Worker 是同一个进程
```
**配置**:
```bash
# 环境变量
MOMENTRY_MAX_CONCURRENT=6 # 最大并发任务数
MOMENTRY_POLL_INTERVAL_SECS=5 # 轮询间隔(秒)
```
**并发控制**:
```
全局并发限制: 6 个任务
├─ Frame Pipeline: 最多 4 个
├─ Time Pipeline: 最多 2 个
└─ 动态调整: 根据 CPU/内存/GPU 自动调整
```
**启动流程**:
```rust
// src/worker/job_worker.rs
pub async fn run(&self) {
// 1. 健康检查
self.health_check_incomplete_jobs().await;
// 2. 初始化 VLM Workers
let num_vlm_workers = 3; // 可配置
crate::core::vlm::init_producer(self.db.pool().clone());
crate::core::vlm::worker::start_workers(self.db.pool().clone(), num_vlm_workers, 2).await;
// 3. 主循环
loop {
// 3.1 轮询命令队列
self.poll_and_process_commands().await;
// 3.2 轮询任务队列
self.poll_and_process_jobs().await;
// 3.3 等待
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
```
---
### 3. VLM Workers (独立线程)
**角色**: VLM 请求处理者
**职责**:
- ✅ 处理 VLM 请求(Agent, Scene, Face)
- ✅ 优先级调度(P0 > P1)
- ✅ 调用 llama.cpp VLM API
- ✅ 结果对比与错误处理
- ✅ 死信队列管理
**启动方式**:
```rust
// 自动启动(在 Job Worker 初始化时)
// src/worker/job_worker.rs
crate::core::vlm::worker::start_workers(self.db.pool().clone(), 3, 2).await;
```
**Worker 配置**:
```
Worker 0: 处理 Agent VLM (P0 - 最高优先级)
Worker 1: 处理 Scene/Face VLM (P1)
Worker 2: 处理 Scene/Face VLM (P1)
最大重试次数: 2 次
超时时间: 60 秒
```
**工作流程**:
```rust
// src/core/vlm/worker.rs
loop {
// 1. 从队列取请求(优先级调度)
let messages = consumer.poll().await;
for message in messages {
// 2. 调用 VLM API
let result = client.generate(
&message.image_path,
&message.prompt,
message.max_tokens
).await;
// 3. 处理结果
match result {
Ok(text) => {
consumer.complete(message.offset, text, processing_time_ms).await?;
}
Err(e) => {
consumer.fail(message.offset, e.to_string(), max_retries).await?;
}
}
}
}
```
---
### 4. VLM Producer (全局单例)
**角色**: VLM 请求生产者
**职责**:
- ✅ 提交 VLM 请求到队列
- ✅ 支持批量提交
- ✅ 提供便捷方法(`submit_agent_vlm`, `submit_scene_vlm`)
- ✅ 等待结果(`wait_for_result`)
**初始化**:
```rust
// src/core/vlm/mod.rs
pub fn init_producer(db: PgPool) {
let producer = Arc::new(VLMProducer::new(db));
VLM_PRODUCER.set(producer).unwrap();
}
```
**使用方式**:
```rust
// 方式 1: 获取全局 Producer
if let Some(producer) = crate::core::vlm::get_producer() {
let offset = producer.submit_scene_vlm(
image_path,
prompt,
max_tokens,
file_uuid,
scene_index
).await?;
let result = producer.wait_for_result(offset, 60).await?;
}
// 方式 2: 便捷方法
let producer = crate::core::vlm::get_producer().unwrap();
let offset = producer.submit_agent_vlm(image_path, prompt, 300).await?;
let result = producer.wait_for_result(offset, 30).await?;
```
---
### 5. VLM Consumer (每个 Worker 一个)
**角色**: VLM 队列消费者
**职责**:
- ✅ 从队列拉取请求(`poll`)
- ✅ 标记请求完成(`complete`)
- ✅ 标记请求失败(`fail`)
- ✅ 更新统计信息
- ✅ 死信队列管理
**创建方式**:
```rust
// src/core/vlm/consumer.rs
let consumer = VLMConsumer::new(
db_pool,
"worker_0".to_string(), // consumer_id
1 // max_batch_size (每次处理 1 条)
);
```
---
## 🔄 运作流程
### 流程 1: 文件注册
```
用户请求
↓
API Server (POST /api/v1/register)
↓
写入 command_queue (status='pending')
↓
Job Worker 轮询 (每 5 秒)
↓
claim_pending_commands(5)
↓
更新 status='running'
↓
执行 register 逻辑
├─ 检查文件是否存在
├─ 提取元数据
├─ 写入 videos 表
└─ 触发 Pipeline (可选)
↓
更新 status='completed' 或 'failed'
```
**关键点**:
- ✅ 使用 `FOR UPDATE SKIP LOCKED` 避免并发冲突
- ✅ 每次最多处理 5 个命令
- ✅ 支持自动 Pipeline 触发
---
### 流程 2: 文件处理 Pipeline
```
Job Worker 轮询 monitor_jobs
↓
找到 status='pending' 的任务
↓
检查依赖关系 (Processor 依赖图)
↓
ProcessorPool.can_start_for_job(job_id)
↓
执行 Processor
├─ ASR (音频转录)
├─ Face (人脸检测)
├─ OCR (文字识别)
├─ Cut (场景切割)
└─ ...
↓
更新 monitor_jobs 状态
↓
Scene VLM (如果 cut.json 存在)
↓
提交 VLM 请求到 vlm_requests
↓
VLM Worker 处理
↓
更新 scenes.json
↓
完成 Pipeline
```
**Pipeline 阶段**:
```
1. ASR - 音频转录
2. ASRX - 说话人分离
3. OCR - 文字识别
4. Face - 人脸检测
5. Cut - 场景切割
6. Pose - 姿态估计
7. TKG - 知识图谱
8. Chunk - 句子分块
9. Scene VLM - 场景描述
10. Vector - 向量化
```
---
### 流程 3: Scene VLM 处理
```
Pipeline 检测到 cut.json
↓
触发 Scene VLM 处理
↓
SceneProfile.generate_vlm_descriptions()
↓
对于每个场景:
├─ 读取 JPEG 帧
├─ 构建请求 payload
└─ 提交到 VLM 队列
↓
VLM Producer.append()
├─ 写入 vlm_requests 表
└─ 返回 offset
↓
VLM Producer.wait_for_result(offset, 60)
├─ 轮询数据库
├─ 检查 status
└─ 返回结果
↓
更新 scenes.json
```
**关键点**:
- ✅ 优先级调度:Agent VLM (P0) > Scene VLM (P1)
- ✅ 并发限制:最多 3 个 VLM 请求并行
- ✅ 超时保护:60 秒超时
- ✅ 死信队列:失败请求隔离
---
### 流程 4: Agent VLM 处理
```
Agent 接收用户请求
↓
analyze_frame 工具
↓
VLM Producer.submit_agent_vlm()
├─ priority = 0 (最高)
├─ request_type = 'agent_vlm'
└─ 返回 offset
↓
VLM Producer.wait_for_result(offset, 30)
├─ 轮询数据库
└─ 返回结果
↓
返回给用户
```
**优先级保证**:
```
P0 (Agent VLM):
- 插队到高优先级队列
- VLM Worker 优先处理
- 用户体验:5-15 秒响应
P1 (Scene/Face VLM):
- 普通优先级队列
- 后台批处理
- 响应时间:10-60 秒
```
---
## 🚀 启动与停止
### 启动所有服务
#### 方式 1: launchd (生产环境)
```bash
# 1. 启动 API Server + Worker
launchctl start gui/$(id -u)/com.momentry.server
# 2. 启动独立的 Worker (如果需要)
launchctl start gui/$(id -u)/com.momentry.worker
# 3. 启动 LLM 服务
launchctl start gui/$(id -u)/com.momentry.chat-llamacpp
# 4. 检查状态
launchctl list | grep momentry
```
#### 方式 2: 手动启动
```bash
# 1. 启动 API Server + Worker
cargo run --release -- server --port 3002 > logs/momentry_3002.log 2>&1 &
# 2. 或者使用脚本
./run-server-3002.sh
# 3. 检查日志
tail -f logs/momentry_3002.log
```
#### 方式 3: 开发模式
```bash
# 使用 debug binary (更快编译,适合开发)
cargo run -- server --port 3002
# 或者 Playground (port 3003)
cargo run --bin momentry_playground -- server
```
---
### 停止服务
#### 方式 1: launchd
```bash
# 停止所有 Momentry 服务
launchctl stop gui/$(id -u)/com.momentry.server
launchctl stop gui/$(id -u)/com.momentry.worker
```
#### 方式 2: 手动停止
```bash
# 查找进程
ps aux | grep momentry
# 停止进程
pkill -f "momentry server"
```
---
### 重启服务
```bash
# launchd 方式
launchctl stop gui/$(id -u)/com.momentry.server
sleep 2
launchctl start gui/$(id -u)/com.momentry.server
# 手动方式
pkill -f "momentry server"
sleep 2
cargo run --release -- server --port 3002 > logs/momentry_3002.log 2>&1 &
```
---
## 🔧 配置
### 环境变量
```bash
# .env 文件
# Server
MOMENTRY_SERVER_PORT=3002
# Worker
MOMENTRY_MAX_CONCURRENT=6
MOMENTRY_POLL_INTERVAL_SECS=5
# VLM Queue
MOMENTRY_VLM_MAX_CONCURRENT=3
MOMENTRY_VLM_TIMEOUT_SECONDS=60
# LLM Services
MOMENTRY_LLM_CHAT_URL=http://localhost:8080/v1/chat/completions
MOMENTRY_LLM_CHAT_MODEL=gemma-4-12b-it
MOMENTRY_LLM_VISION_URL=http://localhost:8080/v1/chat/completions
MOMENTRY_LLM_VISION_MODEL=gemma-4-12b-it
# Database
DATABASE_URL=postgres://accusys@localhost:5432/momentry
# Redis
REDIS_URL=redis://:accusys@localhost:6379
MOMENTRY_REDIS_PREFIX=momentry:
# Storage
MOMENTRY_OUTPUT_DIR=/Users/accusys/momentry/output
```
---
### 队列配置
| 队列 | 并发限制 | 轮询间隔 | 超时 |
|------|---------|---------|------|
| **命令队列** | 5 个/次 | 5 秒 | 无 |
| **任务队列** | 6 个并发 | 5 秒 | 动态 |
| **VLM 队列** | 3 个并发 | 100ms | 60s |
---
## 📊 监控与日志
### 日志位置
```bash
logs/
├── momentry_3002.log # API Server + Worker 日志
├── momentry_3003.log # Playground 日志
└── worker_3002.log # 独立 Worker 日志
```
### 查看日志
```bash
# 实时查看
tail -f logs/momentry_3002.log
# 查看最近错误
grep -i "error\|panic\|FAIL" logs/momentry_3002.log | tail -20
# 查看队列状态
curl http://localhost:3002/api/v1/vlm/queue/status \
-H "Authorization: Bearer $API_KEY"
```
### 队列状态 API
```bash
# VLM 队列状态
GET /api/v1/vlm/queue/status
# 响应示例
{
"high_priority_count": 2,
"normal_priority_count": 15,
"current_request": {
"id": "vlm_abc123",
"request_type": "scene_vlm",
...
},
"current_concurrent": 3,
"max_concurrent": 3,
"is_healthy": true,
"avg_processing_time_ms": 12500.5
}
```
---
## 🛠️ 故障排除
### 问题 1: VLM 队列卡住
**症状**: VLM 请求一直处于 `pending` 或 `running` 状态
**排查**:
```bash
# 1. 检查 VLM 服务是否运行
curl http://localhost:8080/v1/models
# 2. 检查队列状态
curl http://localhost:3002/api/v1/vlm/queue/status
# 3. 检查日志
grep -i "vlm" logs/momentry_3002.log | tail -20
# 4. 检查 GPU 使用
nvidia-smi # 如果有 NVIDIA GPU
```
**解决**:
```bash
# 重启 Worker
launchctl stop gui/$(id -u)/com.momentry.server
sleep 2
launchctl start gui/$(id -u)/com.momentry.server
```
---
### 问题 2: 命令队列不处理
**症状**: `command_queue` 中有大量 `pending` 命令
**排查**:
```bash
# 1. 检查 Worker 是否运行
ps aux | grep momentry
# 2. 检查数据库连接
psql -U accusys -d momentry -c "SELECT COUNT(*) FROM command_queue WHERE status='pending'"
# 3. 检查日志
grep -i "COMMAND_QUEUE" logs/momentry_3002.log | tail -20
```
**解决**:
```bash
# 重启服务
pkill -f "momentry server"
sleep 2
cargo run --release -- server --port 3002 > logs/momentry_3002.log 2>&1 &
```
---
### 问题 3: GPU 过载
**症状**: VLM 响应极慢,GPU 利用率 > 90%
**排查**:
```bash
# 检查 GPU 状态
# macOS: 使用 Activity Monitor
# Linux: nvidia-smi
# 检查 VLM 并发数
curl http://localhost:3002/api/v1/vlm/queue/status | jq '.current_concurrent'
```
**解决**:
```bash
# 降低并发数
export MOMENTRY_VLM_MAX_CONCURRENT=2
# 重启服务
```
---
## 📚 相关文档
| 文档 | 路径 | 说明 |
|------|------|------|
| VLM 队列设计 | `docs_v1.0/DESIGN/VLM_Queue_Design.md` | 详细设计文档 |
| Pipeline 设计 | `docs_v1.0/DESIGN/FILE_PROCESSING_PIPELINE_V3.md` | Pipeline 阶段说明 |
| 并发控制 | `docs_v1.0/OPERATIONS/PIPELINE_CONCURRENCY_FIX.md` | 并发控制策略 |
| 部署指南 | `docs_v1.0/OPERATIONS/DELIVERY_PROCEDURE.md` | 部署流程 |
---
## 🎯 总结
### 系统角色总览
| 角色 | 类型 | 数量 | 职责 |
|------|------|:----:|------|
| **API Server** | 进程 | 1 | HTTP API 端点 |
| **Job Worker** | 进程 | 1 | 队列消费、任务调度 |
| **VLM Workers** | 线程 | 3 | VLM 请求处理 |
| **VLM Producer** | 单例 | 1 | VLM 请求提交 |
| **VLM Consumers** | 实例 | 3 | VLM 队列消费 |
### 启动顺序
```
1. 数据库服务 (PostgreSQL, Redis, Qdrant)
↓
2. LLM 服务 (llama.cpp on port 8080)
↓
3. Momentry Server (API + Worker)
↓
├─ 初始化 VLM Producer
└─ 启动 VLM Workers (3 个线程)
↓
4. 系统就绪
```
### 关键配置
```
生产环境:
├─ API Server: port 3002
├─ Worker: max_concurrent=6
├─ VLM Workers: 3 个线程
└─ 日志: logs/momentry_3002.log
```
---
**文档完成,系统架构清晰!**