[Bug]: replace 模式文件不存在时抛出 NotFoundError 而非创建文件
Bug Description
调用 PUT /api/v1/content/write 并指定 mode=replace 时,如果目标 URI 对应的文件不存在,API 返回 404 NotFoundError,而不是创建该文件。
期望行为(也是 mode=create 的行为)是:文件不存在时应该创建文件,或者返回明确的 AlreadyExistsError,而不是 NotFoundError。
这导致 replace 模式无法实现常见的" upsert"(存在则更新,不存在则创建)模式。
Steps to Reproduce
from openviking.storage.content_write import ContentWriteCoordinator
生成一个确保不存在的 URI file_uri = f"viking://user/memories/test-note-{int(time.time())}.md"
result = await coordinator.write( uri=file_uri, content="# Hello\n\nWorld", ctx=ctx, mode="replace", # ❌ 抛出 404 NotFoundError # mode="create", # ✅ 正常创建 )
Expected Behavior
在 viking://user/memories/test-note-<时间戳>.md 创建文件
Actual Behavior
404 NotFoundError: viking://user/memories/test-note-<时间戳>.md
Minimal Reproducible Example
Error Logs
OpenViking Version
0.3.12
Python Version
3.1.3
Operating System
Linux
Model Backend
Volcengine (Doubao)
Additional Context
openviking/storage/content_write.py 第 67–69 行:
stat = await self._safe_stat(normalized_uri, ctx=ctx) if stat.get("isDir"): raise InvalidArgumentError(f"write only supports existing files, got directory: {uri}") ❌ 缺少: if stat.get("not_found"): ...处理创建逻辑...
对比 _create_and_write 方法(第 205–207 行),该方法正确处理了 not_found 的情况:
stat = await self._safe_stat(uri, ctx=ctx, allow_not_found=True) if not stat.get("not_found"): raise AlreadyExistsError(uri, "file") # 文件已存在 → 报错 ✅ not_found → 继续执行创建逻辑
replace 分支没有给 _safe_stat 传入 allow_not_found=True,所以当文件不存在时,第 186 行直接抛出 NotFoundError。
修复建议
在 replace 分支的 stat 调用之后添加 not_found 检查,逻辑与 _create_and_write 保持一致:
stat = await self._safe_stat(normalized_uri, ctx=ctx) if stat.get("isDir"): raise InvalidArgumentError(f"write only supports existing files, got directory: {uri}")
--- 新增这段 --- if stat.get("not_found"): # 文件不存在时,降级为 create 模式(实现 upsert 语义) return await self._create_and_write( uri=normalized_uri, content=content, ctx=ctx, wait=wait, timeout=timeout, ) --- 新增结束 ---
context_type = self._context_type_for_uri(normalized_uri)
这样既保留了对已存在文件的 replace 语义,又能为不存在的文件自动创建。
补充说明
NotFoundError 实际在 _safe_stat 第 186 行抛出:
raise NotFoundError(uri, "file") from exc
而调用处(第 67 行)未传入 allow_not_found=True 参数
python版本号是3.13,打错了
关闭原因:通过自动化脚本提了另一个issue