fix(kb): replace fragile error string matching with pre-check for duplicate kb_name#9121
Conversation
There was a problem hiding this comment.
Code Review
This pull request improves the knowledge base creation logic in kb_mgr.py by proactively checking if a knowledge base name already exists before attempting creation, replacing a fragile exception string-matching check. It also adds error logging when creation fails. There are no review comments, so I have no feedback to provide.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Hey - I've found 1 issue, and left some high level feedback:
- The pre-check for existing
kb_namereduces reliance on error string parsing but still leaves a race window; consider also handling the specific database unique constraint violation on insert to cover concurrent creation attempts robustly. - In the broad
except Exceptionblock,logger.exceptionmay be preferable tologger.errorso that the full traceback is captured in logs while re-raising the original exception.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The pre-check for existing `kb_name` reduces reliance on error string parsing but still leaves a race window; consider also handling the specific database unique constraint violation on insert to cover concurrent creation attempts robustly.
- In the broad `except Exception` block, `logger.exception` may be preferable to `logger.error` so that the full traceback is captured in logs while re-raising the original exception.
## Individual Comments
### Comment 1
<location path="astrbot/core/knowledge_base/kb_mgr.py" line_range="134" />
<code_context>
self.kb_insts[kb.kb_id] = kb_helper
return kb_helper
except Exception as e:
- if "kb_name" in str(e):
- raise ValueError(f"知识库名称 '{kb_name}' 已存在")
+ logger.error(f"创建知识库失败: {e}")
raise
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Reintroduce targeted handling for unique-name violations rather than fully generic error propagation
This change removes the specific mapping of name-uniqueness violations to a clear `ValueError`, so callers will now see a generic exception when a DB uniqueness constraint is hit. To avoid regressing the public behavior, please still detect this known case (ideally via driver-specific error types/codes rather than string matching) and translate it into the same `ValueError` used in the pre-check, so both the pre-check and DB constraint paths remain consistent and user-friendly.
```suggestion
except Exception as e:
logger.error(f"创建知识库失败: {e}")
# 尝试识别数据库层面的唯一约束冲突(例如名称重复)
unique_violation = False
# 优先使用 SQLAlchemy 的 IntegrityError 等驱动特定异常
try:
from sqlalchemy.exc import IntegrityError # type: ignore
except Exception: # pragma: no cover - 兼容未使用 SQLAlchemy 的情况
IntegrityError = () # type: ignore
if isinstance(e, IntegrityError):
# PostgreSQL: 通过 pgcode 判断唯一约束冲突
orig = getattr(e, "orig", None)
pgcode = getattr(orig, "pgcode", None)
if pgcode == "23505":
unique_violation = True
# 兜底:通过错误信息中是否包含 unique/constraint 等关键词判断
msg = str(e).lower()
if "unique constraint" in msg or "unique violation" in msg:
unique_violation = True
else:
# 非特定驱动时,保留原有的基于错误信息的判断逻辑
if "kb_name" in str(e):
unique_violation = True
if unique_violation:
# 保持与前置名称检查相同的对外行为
raise ValueError(f"知识库名称 '{kb_name}' 已存在") from e
# 非唯一约束错误继续向外抛出
raise
```
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
…licate kb_name (AstrBotDevs#9121) * fix(kb): replace fragile error string matching with pre-check for duplicate kb_name * fix(kb): handle IntegrityError race condition on duplicate kb_name
创建知识库时,原有的重复名称检测依赖于捕获所有异常后检查
"kb_name" in str(e),这种字符串匹配方式脆弱且不可靠。Modifications / 改动点
astrbot/core/knowledge_base/kb_mgr.py: 在创建知识库前预先查询名称是否已存在,如果存在直接抛出明确的ValueError异常。避免依赖异常字符串匹配合法性检查This is NOT a breaking change. / 这不是一个破坏性变更。
Screenshots or Test Results / 运行截图或测试结果
Checklist / 检查清单
😊 If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
/ 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。
👀 My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
/ 我的更改经过了良好的测试,并已在上方提供了"验证步骤"和"运行截图"。
🤓 I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in
requirements.txtandpyproject.toml./ 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到
requirements.txt和pyproject.toml文件相应位置。😮 My changes do not introduce malicious code.
/ 我的更改没有引入恶意代码。
Summary by Sourcery
Improve robustness of knowledge base creation error handling by explicitly checking for duplicate names before creation and logging unexpected failures.
Bug Fixes:
Enhancements: