AstrBot icon indicating copy to clipboard operation
AstrBot copied to clipboard

[Bug] 创建新的知识库实例时,存在创建了kb数据库,但是没有创建kb_helper的情况

Open Li-shi-ling opened this issue 10 months ago • 1 comments

What happened / 发生了什么

创建新的知识库实例时,如果没有输入编码器变量,会导致创建了kb数据库但是没有创建kb_helper,从而导致在下一次创建同一个名称时出现SQLite 唯一约束冲突,但是实际上这个数据库并没有被完整创建

QQ运行界面 Image

我认为的错误是 class KnowledgeBaseManager:类别的create_kb方法,存在问题 先执行了

            session.add(kb)
            await session.commit()
            await session.refresh(kb)

创建数据库,然后在创建KBHelper时报错,导致创建了对应的数据库,但是没有创建KBHelper

    async def create_kb(
        self,
        kb_name: str,
        description: str | None = None,
        emoji: str | None = None,
        embedding_provider_id: str | None = None,
        rerank_provider_id: str | None = None,
        chunk_size: int | None = None,
        chunk_overlap: int | None = None,
        top_k_dense: int | None = None,
        top_k_sparse: int | None = None,
        top_m_final: int | None = None,
    ) -> KBHelper:
        """创建新的知识库实例"""
        kb = KnowledgeBase(
            kb_name=kb_name,
            description=description,
            emoji=emoji or "📚",
            embedding_provider_id=embedding_provider_id,
            rerank_provider_id=rerank_provider_id,
            chunk_size=chunk_size if chunk_size is not None else 512,
            chunk_overlap=chunk_overlap if chunk_overlap is not None else 50,
            top_k_dense=top_k_dense if top_k_dense is not None else 50,
            top_k_sparse=top_k_sparse if top_k_sparse is not None else 50,
            top_m_final=top_m_final if top_m_final is not None else 5,
        )
        async with self.kb_db.get_db() as session:
            session.add(kb)
            await session.commit()
            await session.refresh(kb)

            kb_helper = KBHelper(
                kb_db=self.kb_db,
                kb=kb,
                provider_manager=self.provider_manager,
                kb_root_dir=FILES_PATH,
                chunker=CHUNKER,
            )
            await kb_helper.initialize()
        self.kb_insts[kb.kb_id] = kb_helper
        return kb_helper

Reproduce / 如何复现?

以下kb_name是同一个值

第一次使用

self.context.kb_manager.create_kb(
            kb_name = kb_name,
        )

创建数据库正常报错,未配置 Embedding Provider

在第二次使用

self.context.kb_manager.create_kb(
            kb_name = kb_name,
            embedding_provider_id = ep_names
        )

报错 (sqlite3.IntegrityError) UNIQUE constraint failed: knowledge_bases.kb_name [SQL: INSERT INTO knowledge_bases (kb_id, kb_name, description, emoji, embedding_provider_id, rerank_provider_id, chunk_size, chunk_overlap, top_k_dense, top_k_sparse, top_m_final, created_at, updated_at, doc_count, chunk_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)] [parameters: ('11cea1c0-ba0c-4e67-abb1-65b54e1ac2b3', '群127097993记忆链', None, '📚', 'STEmbedding', None, 512, 50, 50, 50, 5, '2026-01-10 08:00:55.977504', '2026-01-10 08:00:55.977547', 0, 0)] (Background on this error at: https://sqlalche.me/e/20/gkpj) 这个错误是SQLite 唯一约束冲突 但是使用其他其他名称不会出现该问题

AstrBot version, deployment method (e.g., Windows Docker Desktop deployment), provider used, and messaging platform used. / AstrBot 版本、部署方式(如 Windows Docker Desktop 部署)、使用的提供商、使用的消息平台适配器

Ubuntu 22.04 LST python 3.10 AstrBot v4.8.0

OS

Linux

Logs / 报错日志

[16:00:55] [Core] [INFO] [core.event_bus:59]: [default] [Li(aiocqhttp)] 四/3527679745: /li memorychain kbcr 群127097993记忆链 STEmbedding
[16:00:56] [Core] [ERRO] [pipeline.context_utils:63]: Previous Error: None [16:00:56] [Core] [ERRO] [method.star_request:51]: Traceback (most recent call last): File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1967, in _exec_single_context self.dialect.do_execute( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 952, in do_execute cursor.execute(statement, parameters) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py", line 180, in execute self._adapt_connection._handle_exception(error) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py", line 340, in handle_exception raise error File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py", line 162, in execute self.await(_cursor.execute(operation, parameters)) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 132, in await_only return current.parent.switch(awaitable) # type: ignore[no-any-return,attr-defined] # noqa: E501 File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 196, in greenlet_spawn value = await result File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/aiosqlite/cursor.py", line 40, in execute await self._execute(self._cursor.execute, sql, parameters) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/aiosqlite/cursor.py", line 32, in _execute return await self._conn._execute(fn, *args, **kwargs) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/aiosqlite/core.py", line 122, in _execute return await future File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/aiosqlite/core.py", line 105, in run result = function() sqlite3.IntegrityError: UNIQUE constraint failed: knowledge_bases.kb_name

The above exception was the direct cause of the following exception:

Traceback (most recent call last): File "/home/orangepi/pythonDma/AstrBot/astrbot/core/pipeline/process_stage/method/star_request.py", line 47, in process async for ret in wrapper: File "/home/orangepi/pythonDma/AstrBot/astrbot/core/pipeline/context_utils.py", line 64, in call_handler raise e File "/home/orangepi/pythonDma/AstrBot/astrbot/core/pipeline/context_utils.py", line 47, in call_handler async for ret in ready_to_call: File "/home/orangepi/pythonDma/AstrBot/data/plugins/astrbot_plugin_memorychain/main.py", line 75, in kb_create await self.context.kb_manager.create_kb( File "/home/orangepi/pythonDma/AstrBot/astrbot/core/knowledge_base/kb_mgr.py", line 109, in create_kb await session.commit() File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/ext/asyncio/session.py", line 1000, in commit await greenlet_spawn(self.sync_session.commit) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 203, in greenlet_spawn result = context.switch(value) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 2030, in commit trans.commit(_to_root=True) File "", line 2, in commit File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/state_changes.py", line 137, in _go ret_value = fn(self, *arg, **kw) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 1311, in commit self._prepare_impl() File "", line 2, in _prepare_impl File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/state_changes.py", line 137, in _go ret_value = fn(self, *arg, **kw) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 1286, in _prepare_impl self.session.flush() File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 4331, in flush self._flush(objects) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 4466, in _flush with util.safe_reraise(): File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/util/langhelpers.py", line 224, in exit raise exc_value.with_traceback(exc_tb) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 4427, in _flush flush_context.execute() File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/unitofwork.py", line 466, in execute rec.execute(self) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/unitofwork.py", line 642, in execute util.preloaded.orm_persistence.save_obj( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/persistence.py", line 93, in save_obj _emit_insert_statements( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/orm/persistence.py", line 1233, in _emit_insert_statements result = connection.execute( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1419, in execute return meth( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/sql/elements.py", line 527, in _execute_on_connection return connection._execute_clauseelement( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1641, in _execute_clauseelement ret = self._execute_context( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1846, in _execute_context return self._exec_single_context( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1986, in _exec_single_context self._handle_dbapi_exception( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2363, in _handle_dbapi_exception raise sqlalchemy_exception.with_traceback(exc_info[2]) from e File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1967, in _exec_single_context self.dialect.do_execute( File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 952, in do_execute cursor.execute(statement, parameters) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py", line 180, in execute self._adapt_connection._handle_exception(error) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py", line 340, in handle_exception raise error File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/dialects/sqlite/aiosqlite.py", line 162, in execute self.await(_cursor.execute(operation, parameters)) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 132, in await_only return current.parent.switch(awaitable) # type: ignore[no-any-return,attr-defined] # noqa: E501 File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/sqlalchemy/util/_concurrency_py3k.py", line 196, in greenlet_spawn value = await result File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/aiosqlite/cursor.py", line 40, in execute await self._execute(self._cursor.execute, sql, parameters) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/aiosqlite/cursor.py", line 32, in _execute return await self._conn._execute(fn, *args, **kwargs) File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/aiosqlite/core.py", line 122, in _execute return await future File "/home/orangepi/pythonDma/AstrBot/.venv/lib/python3.10/site-packages/aiosqlite/core.py", line 105, in run result = function() sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) UNIQUE constraint failed: knowledge_bases.kb_name [SQL: INSERT INTO knowledge_bases (kb_id, kb_name, description, emoji, embedding_provider_id, rerank_provider_id, chunk_size, chunk_overlap, top_k_dense, top_k_sparse, top_m_final, created_at, updated_at, doc_count, chunk_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)] [parameters: ('11cea1c0-ba0c-4e67-abb1-65b54e1ac2b3', '群127097993记忆链', None, '📚', 'STEmbedding', None, 512, 50, 50, 50, 5, '2026-01-10 08:00:55.977504', '2026-01-10 08:00:55.977547', 0, 0)] (Background on this error at: https://sqlalche.me/e/20/gkpj)

[16:00:56] [Core] [ERRO] [method.star_request:52]: Star data.plugins.astrbot_plugin_memorychain.main_kb_create handle error: (sqlite3.IntegrityError) UNIQUE constraint failed: knowledge_bases.kb_name [SQL: INSERT INTO knowledge_bases (kb_id, kb_name, description, emoji, embedding_provider_id, rerank_provider_id, chunk_size, chunk_overlap, top_k_dense, top_k_sparse, top_m_final, created_at, updated_at, doc_count, chunk_count) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)] [parameters: ('11cea1c0-ba0c-4e67-abb1-65b54e1ac2b3', '群127097993记忆链', None, '📚', 'STEmbedding', None, 512, 50, 50, 50, 5, '2026-01-10 08:00:55.977504', '2026-01-10 08:00:55.977547', 0, 0)] (Background on this error at: https://sqlalche.me/e/20/gkpj)

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

  • [x] Yes!

Code of Conduct

Li-shi-ling avatar Jan 10 '26 08:01 Li-shi-ling

Hi @Li-shi-ling! I'm Dosu and I’m helping the AstrBot team.

你的分析完全正确,问题出在 create_kb 方法的事务原子性不足:

  • 当前实现是先把 KnowledgeBase 写入数据库并 commit,然后再初始化 KBHelper。如果 KBHelper 初始化(比如 embedding_provider_id 缺失)失败,数据库里已经有了这条 KnowledgeBase 记录,但没有对应的 KBHelper 实例,下次用同名创建就会遇到 SQLite 唯一约束冲突(kb_name 重复)源码参考。

可行的改进方案:

  1. 参数预校验
    在写入数据库前,先校验 embedding_provider_id 等关键参数是否齐全,提前 fail fast,避免无效写入。

  2. 异常补偿/回滚
    如果 KBHelper 初始化失败,可以在 except 块里补偿删除刚刚写入的 KnowledgeBase 记录(用 session.delete + commit 或直接 SQL 删除),保证数据库和内存状态一致。

  3. 全流程事务包裹
    理想情况下,整个创建流程(包括 KBHelper 初始化)都应在一个数据库事务内,只有全部成功才 commit,否则 rollback。但由于 KBHelper 初始化涉及外部资源(如文件系统、向量库),实现全流程原子性较复杂,通常用补偿机制更实际。

推荐方案
最简单有效的是方案 1+2:

  • 先校验 embedding_provider_id,缺失直接 raise,不写库。
  • 如果 KBHelper 初始化失败,捕获异常并删除已写入的 KnowledgeBase 记录。

伪代码示例:

async def create_kb(...):
    if not embedding_provider_id:
        raise ValueError("未配置 Embedding Provider")
    kb = KnowledgeBase(...)
    async with self.kb_db.get_db() as session:
        session.add(kb)
        await session.commit()
        await session.refresh(kb)
        try:
            kb_helper = KBHelper(...)
            await kb_helper.initialize()
        except Exception as e:
            await session.delete(kb)
            await session.commit()
            raise e
    self.kb_insts[kb.kb_id] = kb_helper
    return kb_helper

这样可以避免部分创建导致的唯一约束冲突。

相关源码位置

目前社区和文档中未发现已有类似问题的讨论或官方修复。你的优化建议很有价值,欢迎提交 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 Jan 10 '26 08:01 dosubot[bot]