AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug] faiss_memory_index.py 顶层 import faiss 导致 faiss-cpu 1.14.2 下进程挂死

Open Blueteemo opened this issue 5 months ago • 3 comments

What happened / 发生了什么

astrbot/core/db/vec_db/faiss_impl/faiss_memory_index.py 第 10 行顶层执行 import faiss,在 faiss-cpu 1.14.2 环境下,C 库的 CPU 指令集检测会永久阻塞(死锁),导致 Python 进程挂死。

该问题无法被 Python try/except 捕获,也无法被 asyncio.wait_for 取消(因为是同步 C 调用,不释放 GIL)。表现为空 Docker 容器以 exit code 0 反复重启(restart policy: always),无任何错误日志输出。

回退到 faiss-cpu 1.13.2 后问题消失。

Reproduce / 如何复现?

  1. 使用 AstrBot 最新 Docker 镜像(内置 faiss-cpu 1.14.2)
  2. 安装 astrbot_plugin_angel_memory 插件(该插件导入链会触发 faiss 加载)
  3. 启动 AstrBot → 进程挂死 → Docker 重启 → 循环崩溃

AstrBot version / 版本信息

  • AstrBot 版本:v4.25.5(Docker 镜像 soulter/astrbot:latest)
  • faiss-cpu 版本:1.14.2(镜像内置)→ 回退到 1.13.2 后正常
  • 部署方式:Docker Compose,restart: always

OS

Linux (Docker)

Logs / 报错日志

关键特征:无任何日志输出。 进程在 import faiss 处永久阻塞,不会产生 Python 层面的异常或日志。

Docker 日志仅显示反复 restart:

2026-06-09 03:xx:xx ⚡ AstrBot v4.25.5
... (启动到加载插件阶段后卡死,无后续输出)

通过 stderr 调试确认卡在:

[DEBUG] Before import faiss
(进程挂死,无 "After import faiss" 输出)

根因分析

  1. faiss-cpu 1.14.2 的 C 库在 CPU 特性检测阶段死锁(可能与特定 CPU 架构/虚拟化环境相关)
  2. faiss_memory_index.py:10 顶层 import faiss 在模块加载时就触发 C 库初始化
  3. 同步 C 调用无法被 Python 取消:asyncio.wait_for() 无法中断不释放 GIL 的 C 调用
  4. 异常链上游无保护:component_factory.py 的导入链(FaissVectorStore → faiss_memory_index → import faiss)无超时或懒加载机制

建议修复方案

  1. 将 import faiss 改为懒加载:在 FaissVectorStore 实例化或首次调用时才 import,而非模块顶层
  2. 或在 requirements 中 pin faiss-cpu 版本:faiss-cpu>=1.12.0,<1.14.0
  3. 或在 Dockerfile 中固定版本:确保镜像使用已知稳定的 faiss-cpu 版本

相关文件

  • astrbot/core/db/vec_db/faiss_impl/faiss_memory_index.py:10
  • astrbot/core/knowledge_base/kb_helper.py(_ensure_vec_db() 触发导入)

Are you willing to submit a PR? / 你愿意提交 PR 吗?

Yes!

Blueteemo avatar Jun 09 '26 03:06 Blueteemo

@dosubot 你怎么看?

Blueteemo avatar Jun 09 '26 03:06 Blueteemo

我认为你的分析是正确的,这个问题确实存在。补充几点:

  1. 之前已有类似修复: PR #7400 在 2026 年 4 月已经对 kb_helper.py 等多个文件做了懒加载改造 [1],但 embedding_storage.py 的顶层 import faiss 仍然保留了 [2]——这正是你遇到的问题入口。

  2. 版本 pin 的情况: 项目依赖中 faiss-cpu 曾被 pin 到 ==1.10.0 [3],但看起来 Docker 镜像中实际安装了 1.14.2,说明版本约束可能被覆盖或更新了。

  3. 建议的 PR 方向: 将 embedding_storage.py 中的 import faiss 移到类方法内部(如 __init__ 或首次使用时),与 PR #7400 的懒加载策略保持一致。这是最彻底的修复,能同时防住死锁、段错误、非法指令等各种 faiss C 库初始化问题。

期待你的 PR 👍

To reply, just mention @dosu.


Docs are dead. Just use Dosu.

Leave Feedback Ask Dosu about AstrBot Share Dosu with your team

dosubot[bot] avatar Jun 09 '26 03:06 dosubot[bot]

PR 提交了:AstrBotDevs/AstrBot#8696

改动:

  1. embedding_storage.py - import faiss 从顶层移至 __init__() 内
  2. vec_db.py - EmbeddingStorage 导入改为局部导入
  3. faiss_impl/__init__.py - 使用 __getattr__ 懒加载

是 PR #7400 的延续,处理 faiss 模块自身的顶层导入。

Blueteemo avatar Jun 09 '26 04:06 Blueteemo