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,598 @@
# Pipeline Queue 集成分析报告
**日期**: 2026-10-11
**分析范围**: Pipeline 处理流程 + Queue 系统集成
**状态**: 分析报告
---
## 📊 当前 Pipeline 架构
### 1. Pipeline 端点
| 端点 | 功能 | 处理时间 | 状态 |
|------|------|:---------:|:----:|
| `/api/v1/file/:uuid/store-asrx` | 存储 ASRX chunks | ~1s | ✅ 同步 |
| `/api/v1/file/:uuid/rule1` | Rule 1 切片 | ~2s | ✅ 同步 |
| `/api/v1/file/:uuid/vectorize` | 向量化 | ~10-60s | ✅ 同步 |
| `/api/v1/file/:uuid/phase1` | Phase 1 打包 | ~2s | ✅ 同步 |
| `/api/v1/file/:uuid/complete` | 标记完成 | ~1s | ✅ 同步 |
---
### 2. 处理流程
```
Video Registration
↓
ASR Processing (外部,~10-30min)
↓
ASRX Processing (~1-2min)
↓
store_asrx_chunks (同步,~1s)
↓
execute_rule1 (同步,~2s)
↓
vectorize_chunks (同步,~10-60s)
↓
phase1_pack (同步,~2s)
↓
mark_complete (同步,~1s)
```
---
## 🚨 当前问题
### 1. 同步阻塞
**问题**:
- 所有 pipeline 操作都是同步的
- 长时间操作(如 vectorize)会阻塞 API
- 用户等待时间长
- 无法处理大量并发请求
**影响**:
- API 响应时间慢(最长 60 秒)
- 用户体验差
- 系统吞吐量低
---
### 2. 无重试机制
**问题**:
- 失败后无法自动重试
- 需要手动重新执行
- 无错误追踪
**影响**:
- 运维成本高
- 数据不一致
---
### 3. 无进度追踪
**问题**:
- 无法追踪处理进度
- 用户不知道任务状态
**影响**:
- 用户体验差
- 无法调试
---
## 🎯 Queue 集成方案
### 方案 1: 将 Pipeline 操作转为 Command Queue
**架构**:
```
┌─────────────────────────────────────────────────┐
│ Pipeline Command Queue │
├─────────────────────────────────────────────────┤
│ Queue: pipeline.commands (P1 - High) │
│ │
│ Commands: │
│ ├─ StoreASRX (P1, ~1s) │
│ ├─ ExecuteRule1 (P2, ~2s) │
│ ├─ VectorizeChunks (P3, ~10-60s) │
│ ├─ Phase1Pack (P2, ~2s) │
│ └─ MarkComplete (P1, ~1s) │
└─────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────┐
│ Pipeline Workers │
├─────────────────────────────────────────────────┤
│ Worker Pool: 3-5 workers │
│ - 每个文件独立处理 │
│ - 支持并行处理多个文件 │
│ - 自动重试 (max 3) │
└─────────────────────────────────────────────────┘
```
---
### 方案 2: 具体实现
#### 2.1 Command Types
```typescript
// 新增 Pipeline Command Types
pub enum PipelineCommandType {
StoreASRX,
ExecuteRule1,
VectorizeChunks,
Phase1Pack,
MarkComplete,
ExecuteRule3, // 新增
ReindexEmbeddings, // 新增
}
impl PipelineCommandType {
pub fn default_priority(&self) -> CommandPriority {
match self {
Self::MarkComplete => CommandPriority::Critical,
Self::StoreASRX => CommandPriority::High,
Self::ExecuteRule1 => CommandPriority::Normal,
Self::VectorizeChunks => CommandPriority::Low, // 长时间任务
Self::Phase1Pack => CommandPriority::Normal,
Self::ExecuteRule3 => CommandPriority::Normal,
Self::ReindexEmbeddings => CommandPriority::Low,
}
}
pub fn estimated_duration(&self) -> std::time::Duration {
match self {
Self::StoreASRX => std::time::Duration::from_secs(5),
Self::ExecuteRule1 => std::time::Duration::from_secs(10),
Self::VectorizeChunks => std::time::Duration::from_secs(120), // 2 分钟
Self::Phase1Pack => std::time::Duration::from_secs(10),
Self::MarkComplete => std::time::Duration::from_secs(5),
Self::ExecuteRule3 => std::time::Duration::from_secs(30),
Self::ReindexEmbeddings => std::time::Duration::from_secs(120),
}
}
}
```
---
#### 2.2 Pipeline Service
```rust
// src/core/command/pipeline/mod.rs
use crate::core::command::error::{CommandError, CommandResult};
use crate::core::command::queue::CommandQueue;
use crate::core::command::types::{Command, CommandType, CommandPriority};
use serde_json::json;
pub struct PipelineService {
queue: CommandQueue,
}
impl PipelineService {
pub fn new(db: sqlx::PgPool) -> Self {
Self {
queue: CommandQueue::new(db),
}
}
/// 提交 ASRX 存储命令
pub async fn store_asrx(&self, file_uuid: &str) -> CommandResult<String> {
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineStoreASRX,
},
json!({
"file_uuid": file_uuid,
}),
)
.with_priority(CommandPriority::High);
self.queue.produce(
"pipeline.commands",
command,
Default::default(),
).await
}
/// 提交 Rule1 执行命令
pub async fn execute_rule1(&self, file_uuid: &str) -> CommandResult<String> {
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineExecuteRule1,
},
json!({
"file_uuid": file_uuid,
}),
)
.with_priority(CommandPriority::Normal);
self.queue.produce(
"pipeline.commands",
command,
Default::default(),
).await
}
/// 提交向量化命令
pub async fn vectorize_chunks(&self, file_uuid: &str) -> CommandResult<String> {
let command = Command::new(
CommandType::Internal {
category: InternalCommandCategory::PipelineVectorize,
},
json!({
"file_uuid": file_uuid,
}),
)
.with_priority(CommandPriority::Low); // 长时间任务,低优先级
self.queue.produce(
"pipeline.commands",
command,
Default::default(),
).await
}
/// 提交完整 pipeline 流程
pub async fn submit_full_pipeline(&self, file_uuid: &str) -> CommandResult<Vec<String>> {
let mut command_ids = Vec::new();
// 按顺序提交命令(后续会按 file_uuid 分组处理)
command_ids.push(self.store_asrx(file_uuid).await?);
command_ids.push(self.execute_rule1(file_uuid).await?);
command_ids.push(self.vectorize_chunks(file_uuid).await?);
command_ids.push(self.phase1_pack(file_uuid).await?);
command_ids.push(self.mark_complete(file_uuid).await?);
Ok(command_ids)
}
}
```
---
#### 2.3 Pipeline Worker
```rust
// src/core/command/pipeline/worker.rs
use super::*;
use crate::core::pipeline;
use crate::core::db::postgres_db::PostgresDb;
use tracing::{debug, error, info};
pub struct PipelineWorker {
worker_id: String,
db: sqlx::PgPool,
}
impl PipelineWorker {
pub fn new(db: sqlx::PgPool) -> Self {
Self {
worker_id: uuid::Uuid::new_v4().to_string(),
db,
}
}
pub async fn start(&self) -> CommandResult<()> {
info!(worker_id = %self.worker_id, "Pipeline worker started");
loop {
match self.process_commands().await {
Ok(count) => {
debug!(count = count, "Processed pipeline commands");
}
Err(e) => {
error!(error = ?e, "Error processing pipeline commands");
}
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
}
async fn process_commands(&self) -> CommandResult<usize> {
let queue = CommandQueue::new(self.db.clone());
let messages = queue.consume(
"pipeline.commands",
crate::core::command::types::ConsumeOptions {
consumer_group: "pipeline_workers".to_string(),
consumer_id: self.worker_id.clone(),
max_messages: 5,
..Default::default()
},
).await?;
let count = messages.len();
for message in messages {
if let Err(e) = self.handle_command(&message).await {
error!(error = ?e, "Pipeline command failed");
// 记录错误但继续处理其他命令
}
}
Ok(count)
}
async fn handle_command(&self, message: &crate::core::command::types::CommandMessage) -> CommandResult<()> {
let command = &message.command;
// 提取 file_uuid
let file_uuid = command.payload.get("file_uuid")
.and_then(|v| v.as_str())
.ok_or_else(|| CommandError::MissingPayload("file_uuid".to_string()))?;
info!(
command_id = %message.message_id,
file_uuid = %file_uuid,
"Processing pipeline command"
);
let start = std::time::Instant::now();
// 根据命令类型执行操作
let result = match command.command_type {
CommandType::Internal { category: InternalCommandCategory::PipelineStoreASRX } => {
self.execute_store_asrx(file_uuid).await
}
CommandType::Internal { category: InternalCommandCategory::PipelineExecuteRule1 } => {
self.execute_rule1(file_uuid).await
}
CommandType::Internal { category: InternalCommandCategory::PipelineVectorize } => {
self.execute_vectorize(file_uuid).await
}
CommandType::Internal { category: InternalCommandCategory::PipelinePhase1Pack } => {
self.execute_phase1(file_uuid).await
}
CommandType::Internal { category: InternalCommandCategory::PipelineMarkComplete } => {
self.execute_mark_complete(file_uuid).await
}
_ => {
Err(CommandError::InvalidCommandType(format!("{:?}", command.command_type)))
}
};
let duration_ms = start.elapsed().as_millis() as i64;
// 记录结果
match result {
Ok(_) => {
info!(
command_id = %message.message_id,
file_uuid = %file_uuid,
duration_ms = duration_ms,
"Pipeline command completed"
);
}
Err(ref e) => {
error!(
command_id = %message.message_id,
file_uuid = %file_uuid,
duration_ms = duration_ms,
error = ?e,
"Pipeline command failed"
);
}
}
result
}
async fn execute_store_asrx(&self, file_uuid: &str) -> CommandResult<()> {
let db = PostgresDb::new(&crate::core::config::DATABASE_URL).await?;
pipeline::store_asrx_chunks(&db, file_uuid).await?;
Ok(())
}
async fn execute_rule1(&self, file_uuid: &str) -> CommandResult<()> {
let db = PostgresDb::new(&crate::core::config::DATABASE_URL).await?;
pipeline::execute_rule1(&db, file_uuid).await?;
Ok(())
}
async fn execute_vectorize(&self, file_uuid: &str) -> CommandResult<()> {
pipeline::vectorize_chunks(file_uuid).await?;
Ok(())
}
async fn execute_phase1(&self, file_uuid: &str) -> CommandResult<()> {
pipeline::run_phase1(file_uuid).await?;
Ok(())
}
async fn execute_mark_complete(&self, file_uuid: &str) -> CommandResult<()> {
let db = PostgresDb::new(&crate::core::config::DATABASE_URL).await?;
pipeline::mark_complete(&db, file_uuid).await?;
Ok(())
}
}
```
---
#### 2.4 更新 API 端点
```rust
// src/api/pipeline.rs (修改)
use crate::core::command::pipeline::PipelineService;
async fn handle_store_asrx(
Path(uuid): Path<String>,
Extension(pipeline_service): Extension<Arc<PipelineService>>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
// 提交到队列,立即返回
let command_id = pipeline_service.store_asrx(&uuid).await.map_err(|e| {
tracing::error!("Submit store_asrx error: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
Ok(Json(json!({
"success": true,
"message": "ASRX store command queued",
"file_uuid": uuid,
"command_id": command_id,
"status": "queued"
})))
}
async fn handle_vectorize(
Path(uuid): Path<String>,
Extension(pipeline_service): Extension<Arc<PipelineService>>,
) -> Result<Json<Value>, (axum::http::StatusCode, Json<Value>)> {
// 提交到队列,立即返回
let command_id = pipeline_service.vectorize_chunks(&uuid).await.map_err(|e| {
tracing::error!("Submit vectorize error: {}", e);
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({"error": e.to_string()})),
)
})?;
Ok(Json(json!({
"success": true,
"message": "Vectorization command queued (long-running task)",
"file_uuid": uuid,
"command_id": command_id,
"status": "queued",
"estimated_duration_sec": 120
})))
}
```
---
## 📊 对比分析
### 性能对比
| 操作 | 之前(同步) | 之后(队列) | 改进 |
|------|:-----------:|:-----------:|:----:|
| StoreASRX | ~1s | ~50ms | 20x |
| Rule1 | ~2s | ~50ms | 40x |
| Vectorize | ~60s | ~50ms | 1200x |
| Phase1 | ~2s | ~50ms | 40x |
| Complete | ~1s | ~50ms | 20x |
---
### 用户体验对比
**之前**:
```
POST /api/v1/file/xxx/vectorize
↓
等待 60 秒
↓
返回结果
```
**之后**:
```
POST /api/v1/file/xxx/vectorize
↓
立即返回(50ms)
↓
后台处理(120s)
↓
用户可继续其他操作
```
---
## 🎯 实施计划
### Phase 1: 基础队列集成(2 天)
- [ ] 创建 `InternalCommandCategory` 枚举(Pipeline 相关)
- [ ] 实现 `PipelineService`
- [ ] 实现 `PipelineWorker`
- [ ] 修改 API 端点
- [ ] 测试单个命令
---
### Phase 2: 完整流程(2 天)
- [ ] 实现命令链式调用
- [ ] 添加进度追踪
- [ ] 添加错误通知
- [ ] 测试完整 pipeline
---
### Phase 3: 优化(1 天)
- [ ] 性能测试
- [ ] 并发测试
- [ ] 监控配置
- [ ] 文档更新
---
## 📝 数据库更新
### 新增 InternalCommandCategory
```sql
-- 更新 queue_routes 表
INSERT INTO queue_routes (command_type, command_category, queue_name, handler, priority, billing_required) VALUES
('internal', 'pipeline_store_asrx', 'pipeline.commands', 'pipeline_worker', 1, false),
('internal', 'pipeline_execute_rule1', 'pipeline.commands', 'pipeline_worker', 2, false),
('internal', 'pipeline_vectorize', 'pipeline.commands', 'pipeline_worker', 3, false),
('internal', 'pipeline_phase1_pack', 'pipeline.commands', 'pipeline_worker', 2, false),
('internal', 'pipeline_mark_complete', 'pipeline.commands', 'pipeline_worker', 1, false),
('internal', 'pipeline_execute_rule3', 'pipeline.commands', 'pipeline_worker', 2, false),
('internal', 'pipeline_reindex_embeddings', 'pipeline.commands', 'pipeline_worker', 3, false)
ON CONFLICT (command_type, command_category) DO NOTHING;
```
---
## ✅ 预期效果
### 系统吞吐量
- **之前**: 1-2 个文件/分钟(同步)
- **之后**: 10-20 个文件/分钟(并行)
---
### API 响应时间
- **之前**: 平均 10-60 秒
- **之后**: 平均 50 毫秒
---
### 用户体验
- ✅ 立即反馈
- ✅ 后台处理
- ✅ 进度可追踪
- ✅ 错误可恢复
---
## 🚀 下一步
1. **立即实施**: Phase 1 - 基础队列集成
2. **测试验证**: 确保所有 pipeline 命令正常工作
3. **性能测试**: 验证吞吐量提升
4. **监控配置**: 添加 Prometheus 指标
---
**Pipeline Queue 集成分析完成!可立即开始实施。**