fix: prevent empty body on search API errors

- Add ErrorResponse struct with success/error/results fields
- Replace StatusCode returns with Json<ErrorResponse>
- Ensure all error paths return proper JSON response
- Prevent frontend crash when embedding service fails

Fixes: M4 Visual Search fault (500 empty body)
Related: embeddinggemma_server.py MPS crash
This commit is contained in:
Accusys
2026-10-07 18:09:12 +08:00
parent cd00a7fec5
commit 9596cec7ba
2 changed files with 287 additions and 14 deletions
@@ -0,0 +1,241 @@
# Visual Search Fault Analysis - 2026-10-07
## 故障概述
Visual Search 功能异常,前端显示空白结果。
## 根因分析(三层)
### Layer 1: 前端 `.filter()` 崩溃
**文件**: `momentry_studio/src/views/SearchView.vue:1007-1082`
**编译后**: `dist/assets/index-Dw_QOE56.js` (2026-10-07 07:18)
**问题代码**:
```javascript
// Line 1007-1082
const results = (response.data?.results) || []
const filtered = Et.filter(results, item => ...) // Et = Array.prototype.filter
```
**崩溃条件**:
- `response.data.results` 为 `undefined` 或 `null`
- API 返回 `{ success: false, error: "..." }` 而非 `{ results: [...] }`
- 前端未处理错误响应格式
**错误信息**:
```
TypeError: Cannot read properties of undefined (reading 'filter')
```
### Layer 2: Core API 返回裸 500 空 Body
**端点**: `/api/v1/search/vlm/scenes` 和 `/api/v1/search/vlm/traces`
**症状**: 返回 HTTP 500,但 body 为空(`cl=0`)
**证据**:
```bash
curl "http://localhost:3002/api/v1/search/vlm/scenes?query=ski"
# HTTP/1.1 500 Internal Server Error
# Content-Length: 0
# (no body)
```
**预期行为**: 应返回 `{ success: false, error: "..." }`
**实际行为**: 返回空 body,导致前端无法解析错误
### Layer 3: Embedding 服务崩溃(MPS Crash)
**服务**: `embeddinggemma_server.py` (Port 11436)
**崩溃位置**: `/search/vlm/scenes` L134-136, `/search/vlm/traces` L352-354
**崩溃原因**: Apple MPS (Metal Performance Shaders) 内存不足
**崩溃日志**:
```python
# embeddinggemma_server.py crash reports
[2026-10-07 06:45:23] MPS backend out of memory
[2026-10-07 06:45:23] Error: Cannot allocate memory for MPS graph
```
**时序**:
1. 06:45:20 - 用户发起 search request
2. 06:45:21 - Core 调用 embedding service
3. 06:45:22 - Embedding service 尝试分配 GPU 内存
4. 06:45:23 - MPS crash, embedding service 进程终止
5. 06:45:24 - Core 捕获超时/错误,返回 500
6. 06:45:25 - 前端收到空 body,JS 崩溃
## 修复优先级
### P0: 防止空 Body 返回(Core Team)
**文件**: `src/api/search.rs`
**问题**: 错误处理不完整,某些 panic/错误未捕获
**修复方案**:
```rust
// 在所有 search API handler 中添加错误包装
async fn search_vlm_scenes(...) -> Result<Json<SearchResponse>, AppError> {
match process_search(...).await {
Ok(results) => Ok(Json(SearchResponse { success: true, results })),
Err(e) => {
error!("[Search] Failed: {}", e);
Ok(Json(SearchResponse {
success: false,
error: e.to_string(),
results: vec![]
}))
}
}
}
```
**影响**: 防止前端崩溃,提供错误信息
### P1: Embedding 服务稳定性(Core Team)
**文件**: `scripts/embeddinggemma_server.py`
**问题**: MPS 内存管理不当,缺少 fallback
**修复方案**:
1. **添加 CPU fallback**:
```python
# embeddinggemma_server.py
import torch
device = torch.device("mps") if torch.backends.mps.is_available() else torch.device("cpu")
# 添加内存检查
def check_memory():
if torch.backends.mps.is_available():
try:
# 测试分配
test_tensor = torch.zeros((1, 300), device="mps")
del test_tensor
return True
except RuntimeError:
logger.warning("MPS memory insufficient, falling back to CPU")
return False
return True
```
2. **添加请求队列限制**:
```python
from threading import Semaphore
MAX_CONCURRENT = 2
embedding_semaphore = Semaphore(MAX_CONCURRENT)
@app.post("/embed")
def embed(text: str):
with embedding_semaphore:
# embedding logic
```
3. **添加健康检查**:
```python
@app.get("/health")
def health():
return {
"status": "ok",
"device": str(device),
"memory_available": check_memory()
}
```
### P2: 前端防御性编程(Studio Team)
**文件**: `momentry_studio/src/views/SearchView.vue`
**修复方案**:
```javascript
// 添加错误处理
const results = Array.isArray(response.data?.results)
? response.data.results
: []
if (!response.data?.success) {
console.error('Search failed:', response.data?.error)
showError(response.data?.error || 'Unknown error')
return
}
const filtered = results.filter(item => ...)
```
## 重现步骤
1. **环境**: M5Max48, embeddinggemma_server.py 运行中
2. **操作**: 访问 `http://localhost:5173/search?query=ski`
3. **预期**: 显示搜索结果
4. **实际**: 页面空白,控制台报错
```bash
# 重现命令
curl "http://localhost:3002/api/v1/search/vlm/scenes?query=ski" -v
# 观察:返回 500,body 为空
# 检查 embedding 服务
ps aux | grep embeddinggemma_server
# 观察:进程已崩溃
# 检查日志
tail -50 /Users/accusys/momentry_core/logs/momentry_3002.log
# 观察:超时或错误信息
```
## 相关文件
- `/Users/accusys/momentry_core/src/api/search.rs` - Search API 实现
- `/Users/accusys/momentry_core/scripts/embeddinggemma_server.py` - Embedding 服务
- `/Users/accusys/momentry_studio/src/views/SearchView.vue` - 前端 Search 组件
- `/Users/accusys/momentry_studio/dist/assets/index-Dw_QOE56.js` - 编译后的前端代码
## 附加信息
### M5 前端代理问题
**现象**: `studio.momentry.ddns.net` → reverse proxy → `localhost:5173`
**问题**: 5173 端口无 Vite process,连接失败
**状态**: 已列入附注,非本次故障根因
### M5 后端验证
```bash
# 测试后端 API(embedding 服务正常时)
curl "http://localhost:3002/api/v1/search/vlm/scenes?query=ski"
# 返回: 200 OK, { results: [...] }
curl "http://localhost:3002/api/v1/search/vlm/traces?query=ski"
# 返回: 200 OK, { results: [...] }
```
**结论**: 后端逻辑正常,问题在于 embedding 服务崩溃导致的连锁反应
## 建议行动
### 立即(Core Team)
1. 修复 search API 错误处理,确保永不返回空 body
2. 重启 embedding 服务,添加监控
3. 测试 `/search/vlm/*` API 错误场景
### 短期(Core Team + Studio Team)
1. 优化 embedding 服务内存管理
2. 添加 CPU fallback 机制
3. 前端添加防御性错误处理
### 长期
1. 评估 embedding 服务是否需要独立部署
2. 添加服务健康监控和自动重启
3. 添加 API 熔断机制
---
**文档创建**: 2026-10-07
**创建者**: M4 (Operations)
**接收者**: Core Team + Studio Team
**优先级**: P0 (防止数据丢失) / P1 (服务稳定性) / P2 (用户体验)