Closed
[Bug] Intent token usage store 冷启动并发消费必然 SQLite readonly #92
zhangzjAdd on  6 days agoClosed at  6 days ago
zhangzj
zhangzj
6 days ago Create

Paired: GitHub #210 ↔ GitCode #92

问题描述

SQLiteIntentTokenUsageStore.consume() 在数据库文件尚不存在且两个连接并发消费同一 token 时,必有一方抛 sqlite3.OperationalError: attempt to write a readonly database,该异常被统一包装成 IntentTokenUsageStoreError("Intent token usage store unavailable"),调用方只能按"存储服务不可用"处理。

问题现象

冷启动(首次部署、容器重启后数据卷为空)时并发请求消费同一 token:

[('ERR', 'IntentTokenUsageStoreError', "OperationalError('attempt to write a readonly database')"), (True, 1)]

一路成功记账,另一路被拒。修复前连续 3 轮 3/3 复现。

操作步骤

  1. 删除 usage 数据库文件(或使用全新目录):
    rm -f .a4p/intent_token_usage.sqlite3
    
  2. 启动两个进程/线程,用同一 token_id 同时调用 consume(max_executions=1):
import multiprocessing as mp, time
from a4p.intent.usage_store import SQLiteIntentTokenUsageStore

def worker(db, barrier, q):
    store = SQLiteIntentTokenUsageStore(db)
    barrier.wait()
    try:
        q.put(("OK", store.consume(token_id="tok", max_executions=1,
                                   expire_at_epoch=int(time.time()) + 600)))
    except Exception as e:
        q.put(("ERR", type(e).__name__, str(e)))
  1. 观察其中一路是否抛 IntentTokenUsageStoreError。

预期结果

两个并发消费都应正常返回,结果为 (True, 1) 与 (False, 1)(一个额度被消耗,另一个因额度用尽返回 False),不应出现异常。

实际结果

其中一路抛 IntentTokenUsageStoreError: Intent token usage store unavailable,根因是 attempt to write a readonly database。

原因定位

A4P-python-sdk/src/a4p/intent/usage_store.py:71-81:

connection.execute("BEGIN IMMEDIATE")          # 先开写事务
connection.execute("CREATE TABLE IF NOT EXISTS ...")  # 再建表

数据库文件不存在时,两个连接同时试图创建同一个文件,SQLite 在文件创建竞争下会给其中一个连接返回只读句柄,BEGIN IMMEDIATE 直接失败。仓库自带用例 tests/unit/test_stores.py::test_sqlite_usage_store_consumes_atomically_across_connections 在本机即为稳定失败状态。

修复建议

在开启写事务之前先执行幂等的 CREATE TABLE IF NOT EXISTS(autocommit 模式),再 BEGIN IMMEDIATE;同时对 readonly 类错误做一次短暂重试,其余 sqlite 错误仍统一包装为存储不可用。已提 PR:SQLite 侧 20/20 轮并发冷启动全部通过,test_stores.py 7 个用例通过。

likedislike
OopenJiuwen-botCollaborators
6 days ago Added label: sig/sig-agent-protocol
openJiuwen-botCollaborators
6 days ago Comments:

欢迎来到 openJiuwen 社区

Hey @gp1000 , 感谢你对社区的贡献.

机器人使用手册

有关指令的使用,可以点击 此处 查看详情。开发人员可以在每个PR或Issue下方评论特定指令来触发机器人任务。

联系指引

有疑问可以联系 SIG: sig-agent-protocol ,
维护者是: @YiyangShao, @xinyu-jiuwen ,
审核者是: @gcw_hx9prznZ, @mingo007 .

likedislike
Oopenjiuwen-syncCollaborators
6 days ago Modify description of issue
zhangzjzhangzj
6 days ago Associated pull request
OopenJiuwen-botCollaborators
6 days ago Close issue
OopenJiuwen-botCollaborators
6 days ago changed custom state from TODO to DONE