Skip to content

feat(server): add session auto commit scheduling - #2772

Open
zhoujh01 wants to merge 18 commits into
mainfrom
session-auto-commit-server
Open

zhoujh01 wants to merge 18 commits into
mainfrom
session-auto-commit-server

Conversation

@zhoujh01

@zhoujh01 zhoujh01 commented Jun 22, 2026 •

Copy link
Copy Markdown
Collaborator

OpenViking Session 自动 Commit 策略设计文档

Date: 2026-07-15
Status: 已实现

背景

记忆库存量客户迁移中,OV 需要对齐记忆库 StreamingWrite(POST /api/memory/session/streaming_write)的"边对话、边写入、自动抽取"能力。

记忆库的做法是:客户端每轮把 user / assistant 消息写入短期缓存,系统持续跟踪累积的 token 数和消息条数,当任一触发条件满足时自动执行长期记忆抽取,把对话压缩成事件记忆。触发条件包含 token_count、message_count、wait_timeout 三个阈值。

OV 在此之前的方案存在两个问题:

  • 易用性:客户期望"每个 session 每轮对话为单位高频抽取"(记忆库客户 A 场景),但 OV 只有手动 commit_session(session_id),需要接入方自己开发触发逻辑。
  • 性能:非标准 plugin 接入的客户,add_message 积攒大量 trace 后一次性 commit,容易因上下文过长导致抽取失败。

因此需要让 OV 支持按 session 配置的自动抽取策略,但默认保持关闭,避免对既有租户和既有 session 产生隐式抽取行为。开发者可以在创建 session 时显式开启并定制抽取频率;服务端也可以通过全局 memory.session_auto_commit.default_enabled 控制“未显式传策略的新 session 是否默认开启”。

目标与非目标

目标

  • 每个 session 可以携带一份 auto_commit_policy 配置;策略存在即启用,策略为 None 即关闭。
  • 服务端提供 memory.session_auto_commit.default_enabled,控制创建 session 时请求未显式传 config.auto_commit_policy 的默认行为;默认值为 false。
  • 支持在创建 session 时指定,并通过获取接口查看该配置;创建后配置不可变。
  • 消息写入后按"累积 token / 累积消息条数"阈值即时触发自动 commit,并支持节流。
  • 支持"空闲超时"强制抽取(服务端后台调度器扫描)。
  • 提供 Python SDK 的创建期配置能力;Rust CLI 目前可查看该配置,但不提供运行期修改命令。

非目标

  • 不提供单独的 enabled 字段。当前启停语义由 auto_commit_policy 是否存在表达:创建时未显式传策略且 default_enabled=false 时关闭;显式传 {} / 部分字段 / 完整字段时开启并按默认值补齐。创建后不提供运行期启停或修改语义。
  • 不改变既有手动 commit / commit_session 的语义。
  • 不再支持旧的"逐消息传 auto_commit_policy"配置语义;老客户端继续传该字段时会被请求模型静默忽略,策略不会被修改或启用。

总体架构

自动 commit 由三层协作完成:

                    ┌────────────────────────────────────────────────┐
   HTTP / SDK       │ POST /sessions   GET /sessions/{id}              │  配置面
                    └───────────────┬────────────────────────────────┘
                                    │  auto_commit_policy (dict)
                                    ▼
        ┌──────────────────────────────────────────────────────────┐
        │  AutoCommitPolicy(唯一合法化入口:clamp + 未知键拒绝)    │  策略模型
        └──────────────────────────────────────────────────────────┘
                                    │  持久化到 session .meta.json
                                    ▼
   触发面①  add_message / batch  ─────────────┐
            (inline, reason=message_write)   │
                                               ▼
   触发面②  SessionAutoCommitScheduler ──▶ maybe_schedule_auto_commit
            (后台扫描, reason=idle_timeout)        │ 去重 + 节流复核
                                                     ▼
                                            run_auto_commit
                                                     │
                                                     ▼
                                     Session.commit_async(两阶段归档+抽取)
  • 配置面:只在 create / GET 两处读写策略,绝不逐消息传入;PATCH /api/v1/sessions/{id} 不支持。
  • 策略模型 AutoCommitPolicy:所有取值合法化(clamp、未知键拒绝、默认填充)的唯一实现处。
  • 触发面:两条独立链路(消息写入即时触发、后台空闲超时触发)共用同一套判定/去重/执行逻辑。

策略模型 AutoCommitPolicy

代码位置:openviking/session/auto_commit_policy.py

这是一个 @dataclass,5 个 int 字段,配一组模块级常量(默认值、上限、合法键集合 _POLICY_KEYS)。它描述的是已启用时的有效策略;session meta 里的 auto_commit_policy=None 表示未启用自动 commit。

启用后,策略以 config.auto_commit_policy 的形式写入 session meta:

{
  "config": {
    "auto_commit_policy": {
      "pending_token_threshold": 10000,
      "message_count_threshold": 50,
      "idle_timeout_seconds": 86400,
      "keep_recent_count": 2,
      "min_commit_interval_seconds": 0
    }
  }
}
字段 类型 默认值 上限 语义
pending_token_threshold int 10000 50000 未提交 pending token 严格大于该值时,在消息写入后触发自动 commit
message_count_threshold int 50 500 未提交 live message 数严格大于该值时,在消息写入后触发自动 commit
idle_timeout_seconds int 86400(1 天) 604800(7 天) 有未提交内容的 session 空闲超过该秒数后,进入服务端 idle 调度器处理范围
keep_recent_count int 2 500 阈值触发的自动 commit 保留的最近 live message 数(作为原始 context);idle 超时触发忽略该值,提交全部积压
min_commit_interval_seconds int 0 604800 两次自动 commit 之间的最小间隔秒数(节流)

默认值对齐记忆库 streaming_write 的推荐值。所有字段最小值为 0;0 有"关闭该触发维度"的语义(见下文 get_* helper)。

校验与 clamp 规则(单一来源)

所有取值的合法化只在 AutoCommitPolicy 一处发生,保证 HTTP / SDK / 本地嵌入式入口行为一致。核心是 _coerce_int:

def _coerce_int(value, *, field, minimum, maximum):
    try:
        parsed = int(value)
    except (TypeError, ValueError):
        raise InvalidArgumentError(f"auto_commit_policy.{field} must be an integer")
    if parsed < minimum:
        parsed = minimum      # clamp 到下界(恒为 0)
    if parsed > maximum:
        parsed = maximum      # clamp 到上界(PRD 上限)
    return parsed

据此得到三条规则:

  • clamp 而非拒绝:超出上限的值被 clamp 到 [0, max],请求正常返回 200。例如 pending_token_threshold=10_000_000 会被 clamp 成 50000;负数被 clamp 成 0。
  • 未知字段拒绝:from_dict() 发现 _POLICY_KEYS 之外的键时抛 InvalidArgumentError(HTTP 映射为 400)。
  • 类型校验:非整数字符串/对象抛 InvalidArgumentError。

设计取舍:request 层(AutoCommitPolicyRequest)刻意不加 Pydantic 的 ge / le 数值边界,只保留 extra: "forbid" 用于拒绝未知键。数值边界交给 dataclass clamp,避免"request 层 422 拒绝 vs dataclass clamp 200"两套语义打架。而 request 层保留 forbid、dataclass 也再查一次未知键,是因为 SDK 本地直连路径不经过 Pydantic model,仍需 dataclass 兜底。

关键方法:

  • default() — 返回全默认策略。
  • from_dict(data) — 从 dict 构建:None → 默认;已是 AutoCommitPolicy → 原样返回;dict → 逐字段 _coerce_int(缺失填默认、越界 clamp)、未知键抛错。注意:这是模型层的解析行为;运行期调用方会先判断 session.meta.auto_commit_policy is None,将其视为关闭,不会把缺失策略自动解析成默认开启。
  • merge(patch) — 内部辅助方法:基于当前策略覆盖传入 dict 里的合法键,再走一遍 from_dict 完成 clamp。当前 HTTP / SDK 配置面不暴露运行期 merge 接口。
  • to_dict() — 序列化为固定 5 字段的 dict,写入 meta。

运行期 helper(session_auto_commit.py)

触发判定不直接读 dataclass 字段,而是经过一组 helper,把"None 表示整个自动 commit 关闭"和"0 表示关闭单个触发维度"的语义收敛在一处:

def get_token_threshold(policy):        # >0 才返回,否则 None(关闭该维度)
    if policy is None:
        return None
    t = resolve_policy(policy).pending_token_threshold
    return t if t > 0 else None
def get_message_count_threshold(policy): ...   # 同上
def get_idle_timeout_seconds(policy): ...      # >0 才返回,否则 None
def get_min_commit_interval_seconds(policy): return max(0, ...)  # 0 表示不节流
def get_keep_recent_count(policy): return max(0, ...)

resolve_policy 内部就是 AutoCommitPolicy.from_dict(...),因此 meta 里存的是 dict 时,即便是历史脏数据,也会在读取时被重新 clamp/补齐默认字段。policy is None 在 helper / service 层短路为关闭,不进入默认策略解析。

配置读写接口

创建:POST /api/v1/sessions

  • CreateSessionRequest 新增 config: Optional[SessionConfigRequest]。
  • 若请求显式传入 config.auto_commit_policy,路由用 model_dump(exclude_none=True) 提取(只保留用户显式给的字段),交给 SessionService.create(auto_commit_policy=...)。
  • create() 内部按如下顺序决定是否启用:
    • auto_commit_policy is not None:启用。AutoCommitPolicy.from_dict(payload).to_dict() 写入 session.meta.auto_commit_policy,即便用户只给一个字段,落库的也是填充默认后的完整 5 字段。
    • 请求未显式传策略,但服务端 memory.session_auto_commit.default_enabled=true:启用。用 AutoCommitPolicy.from_dict(None).to_dict() 写入完整默认策略。
    • 请求未显式传策略,且 default_enabled=false(默认):关闭。session.meta.auto_commit_policy = None。
  • 响应 result.config.auto_commit_policy 返回当前 session 的有效配置;关闭时为 null。

自动创建:首次写消息

单条与批量消息写入接口仍支持对不存在的 session 做自动创建(auto_create=True)。
这条路径必须和显式 POST /api/v1/sessions 保持同一套默认启用语义:

  • memory.session_auto_commit.default_enabled=false(默认)时,首次写消息创建出的 session
    保持关闭,auto_commit_policy=None。
  • memory.session_auto_commit.default_enabled=true 时,首次写消息创建出的 session
    写入完整默认策略,后续同一条消息写入完成后即可按 token/message 阈值进入自动
    commit 判定。
  • 消息写入请求本身不接受 per-message auto_commit_policy。旧客户端继续传该字段时,
    HTTP / embedded batch 路径都会忽略它,不能借首次写消息开启或修改 session 策略。

这样保证“先 create 再写消息”和“直接首次写消息创建 session”两条公开创建路径,在
全局默认开关下得到一致的自动 commit 行为。

查看:GET /api/v1/sessions/{session_id}

  • 响应在 session.meta.to_dict() 之外追加 result.config = effective_session_config(session)。
  • effective_session_config 只有在 meta.auto_commit_policy is not None 时才用 AutoCommitPolicy.from_dict(...).to_dict() 计算;若 meta 里没有策略或策略为 None,返回 {"auto_commit_policy": null}。
  • 同时单独回填 result.pending_tokens,方便调用方观察触发进度。

运行期编辑

Session config 创建后不可变;auto_commit_policy 只能在 POST /api/v1/sessions
时设置,之后通过 GET /api/v1/sessions/{session_id} 查看生效配置。

PATCH /api/v1/sessions/{session_id} 不支持,HTTP 路径返回 405 Method Not
Allowed。这样避免运行期配置写入与消息追加同时覆盖 .meta.json 的
read-modify-write 竞态,也让自动 commit 的启停边界保持在 session 创建期。

移除的旧入口

  • AddMessageRequest / BatchAddMessageRequest 移除了 auto_commit_policy 入参。这两个 model 不设 extra: "forbid",因此老客户端仍传该字段时会被 Pydantic 静默忽略(返回 200,策略保持不变),不报 422,降低迁移摩擦。

SessionMeta 数据模型

openviking/session/session.py:SessionMeta(dataclass,序列化进 .meta.json)。与本设计相关的字段:

字段 类型 用途
message_count int 当前 live 消息条数(每次 load 从 messages.jsonl 重新校准)
pending_tokens int 累积未提交 token 数,触发判据之一(见下节)
keep_recent_count int plugin 的 pending-token 记账窗口,决定滑动窗口哪些消息计入 pending_tokens
auto_commit_policy Optional[Dict] 持久化的策略;None 表示自动 commit 关闭
last_message_at str 最近消息时间(ISO),idle 计时基准
last_auto_commit_at str 最近一次自动 commit 时间,节流计时基准
auto_commit_last_error str 最近一次自动触发/一阶段 commit 的错误
auto_commit_last_error_at str 上述错误的时间

注意 keep_recent_count(meta 上的记账窗口)与 auto_commit_policy.keep_recent_count(策略的 commit 预留)是两个不同的东西,见后文"关键设计取舍"。

pending_tokens 记账原理

pending_tokens 是"累积 token"触发维度的数据基础,需要在高频 add_message 下保持 O(1) 维护,同时在 load / commit / 回滚时能被正确重建。

滑动窗口定义

给定 meta 里的记账窗口 keep = meta.keep_recent_count:

  • keep <= 0:所有 live 消息都算 pending(pending_tokens = Σ tokens)。
  • keep > 0:只有除最近 keep 条以外的消息算 pending(pending_tokens = Σ tokens[: total-keep])。
  • live 消息数 <= keep:pending_tokens = 0。

增量维护(add 路径,O(1))

_append_messages 每追加一条消息时增量更新,避免每次全量求和:

keep = int(meta.keep_recent_count or 0)
if keep <= 0:
    meta.pending_tokens += msg_tokens          # 全部计入
elif len(messages) > keep:
    pushed_out = messages[-(keep + 1)]          # 新消息把窗口最老的一条挤出 keep 窗
    meta.pending_tokens += pushed_out.tokens    # 被挤出者进入 pending

即:新消息进入"最近 keep 条"窗口,同时把窗口里最老的一条挤出成 pending,pending 只累加被挤出者的 token。

全量重建(load / 回滚,O(n))

_rebuild_pending_tokens() 按上面的滑动窗口定义整段重算,用于:

  • load():从 messages.jsonl 恢复 live 消息后重算,保证跨重启一致,并为 meta 早于本次改动的历史 session 补齐该字段。
  • commit 回滚等安全网场景。

commit 归档后,pending 部分已被写入 archive,故 commit_async 直接把 pending_tokens 重置为 0。

commit_async 两阶段流程

Session.commit_async(keep_recent_count=0, *, memory_policy=None, persist_keep_recent_count=True) 是所有 commit(手动/自动)的统一入口。

keep_recent_count 与 persist 两个入参

  • keep_recent_count:本次归档后 live 保留的最近条数。0 = 全量归档。
  • persist_keep_recent_count:是否把本次 keep_recent_count 回写进 meta.keep_recent_count(影响后续 add 的记账窗口)。
    • 默认 True:手动 commit / message_write 触发都回写。
    • idle 全量提交传 False:一次性全量归档不应把存量的 keep 偏好覆盖成 0。
stored_keep_recent_count = (
    keep_recent_count if persist_keep_recent_count
    else max(0, int(meta.keep_recent_count or 0))   # 保留原值
)

Phase 1(归档,路径锁保护)

  1. 空消息快速路径:self._messages 为空 → 只重置 pending_tokens=0、写 stored_keep_recent_count,返回 status=skipped, reason=no_messages,不进锁。
  2. 取文件系统分布式锁 LockContext(session_path, "exact"),跨 worker/进程串行化归档。
  3. 锁内二次空检查:处理两个并发调用都过了预检查、但只应有一个归档的竞态。
  4. 全在 keep 窗内:keep_recent_count > 0 且 total <= keep_recent_count → 无需归档,重置 pending_tokens=0、写 keep、返回 reason=all_within_keep_window。
  5. 计算切分点 split_idx = total - keep_recent_count(keep=0 时归档全部):
    • messages_to_archive = messages[:split_idx]
    • retained_messages = messages[split_idx:]
  6. 先写 archive 再裁剪 live:先把 messages_to_archive 写入 history/archive_NNN/messages.jsonl,成功后才把 live 替换成 retained tail 并回写 messages.jsonl。任一步失败则回滚 self._messages 与 compression_index 并抛错——保证归档写失败不会丢失 live 会话。
  7. 锁外收尾:更新 message_count、pending_tokens=0、keep_recent_count=stored、commit_count、last_commit_at,_save_meta()。

Phase 2(记忆抽取,后台)

通过 asyncio.create_task 异步做长期记忆抽取,返回 task_id 供轮询;二阶段失败通过后台 task 与 .failed.json 上报,不写 auto_commit_last_error。

触发链路

消息写入触发(inline,reason = message_write)

add_message / batch_add_messages 在写入消息后依次调用:

  1. SessionService.touch_last_message_at(session) — 写 meta.last_message_at(供 idle 计时),并 _save_meta。
  2. SessionService.maybe_schedule_auto_commit(session_id, ctx, reason_hint="message_write")。

判定见 _should_run_auto_commit(session, policy, "message_write"):

  1. policy is None → 自动 commit 未启用,不触发。
  2. 无未提交内容(_has_uncommitted_content)→ 不触发。
  3. 处于节流窗口内(_within_min_commit_interval)→ 不触发。
  4. 读 meta.pending_tokens / meta.message_count(异常转 int 失败则不触发)。
  5. token_threshold is not None 且 pending_tokens > token_threshold → 触发。
  6. message_threshold is not None 且 message_count > message_threshold → 触发。
  7. 否则不触发。

_has_uncommitted_content(helper has_uncommitted_content):pending_tokens > 0 或 message_count > meta.keep_recent_count 即视为有未提交内容。

阈值比较用严格大于(>),与 PRD "大于该值则触发" 一致。threshold is not None 的判断把"阈值=0(关闭该维度)"排除在触发之外。

空闲超时触发(后台调度,reason = idle_timeout)

SessionAutoCommitScheduler(openviking/service/session_auto_commit.py):

  • 仅当服务端全局开关 memory.session_auto_commit.idle_enabled = true 时才在 service/core.py 里被创建并 start();否则 _session_auto_commit_scheduler = None。
  • _run_loop:每 check_interval_seconds(默认 60s)await sleep 后,再判一次 idle_enabled 才 _scan_once();循环内任何异常都被 catch 记 error,不让调度器崩溃。
  • _scan_once 统计 scanned/due/scheduled,仅当 due>0 才打 info 日志,避免空扫刷屏。

扫描算法(_iter_session_meta_path_batches)

三层遍历 AGFS 树,产出 .meta.json 路径批次:

/local/{account_id}/user/{user_id}/sessions/{session_id}/.meta.json
  • 顶层 ls /local 得到 account 目录,跳过 _system 与非目录项。
  • 逐 account ls /local/{acc}/user,逐 user ls .../sessions。
  • 每个 session 目录拼出 meta_path,用 seen set 去重后进 batch。
  • 累计到 scan_batch_size(默认 16)就 yield 一批,批间可选 scan_batch_pause_seconds 暂停降存储压力。
  • 各级 ls 的 NotFound 记 debug、其他异常记 warning 后跳过,单个目录出错不影响整体扫描。

单条判定(_read_idle_candidate → _is_idle_policy_due)

  • 并发 asyncio.gather 读取一批 meta;JSON 解析失败/非 dict/NotFound 都返回 None 跳过。
  • _is_idle_policy_due(meta, now):
    1. auto_commit_policy is None → 自动 commit 未启用,不到期。
    2. get_idle_timeout_seconds(policy) 为 None(idle_timeout<=0)→ 不到期。
    3. has_uncommitted_content(meta) 为假 → 不到期。
    4. next_check_at = compute_next_check_at(last_message_at, idle_timeout)(= last_message_at + idle_timeout)。
    5. is_next_check_due(next_check_at, now) 为 True → 命中。
  • 命中后从 meta_path 反解 session_id/account_id/user_id,构造 RequestContext(Role.USER),调 maybe_schedule_auto_commit(..., reason_hint="idle_timeout")。

is_next_check_due 做了时区归一:next_check_at 带 tz 而 now 不带(或反之)时,会把两者对齐到同一 tz/naive 再比较,避免混用 aware/naive datetime 抛错。同样的归一逻辑也用在节流判断 _within_min_commit_interval。

调度、去重与并发

maybe_schedule_auto_commit

session = await self.get(session_id, ctx, auto_create=False)
if not self._should_run_auto_commit(session, policy, reason_hint):
    return False
claim = (account_id, user_id, session_id)
async with self._auto_commit_claims_lock:          # 进程内互斥
    if claim in self._auto_commit_claims:
        return False                               # 已在飞,跳过
    if await tracker.has_running("session_commit", session_id, ...):
        return False                               # 跨进程已有 commit 任务,跳过
    self._auto_commit_claims.add(claim)
asyncio.create_task(self.run_auto_commit(session_id, ctx, reason=reason_hint))
return True

两级去重:

  • 进程内:_auto_commit_claims(set[(account,user,session)])+ asyncio.Lock,防止同一进程内高频 add 反复排队 commit。claim 的增删都在锁内 / run_auto_commit 的 finally 里。
  • 跨进程/worker:task_tracker.has_running("session_commit", ...),已有运行中的 commit 任务则跳过。

执行体用 create_task 异步跑,不阻塞 add_message 的响应。

run_auto_commit

try:
    if await tracker.has_running("session_commit", ...): return   # 再查一次防竞态
    session = await self.get(session_id, ctx, auto_create=False)
    if not self._should_run_auto_commit(session, policy, reason): return  # 状态复核
    if reason == "idle_timeout":
        result = await session.commit_async(keep_recent_count=0,
                                             persist_keep_recent_count=False)
    else:
        result = await session.commit_async(keep_recent_count=get_keep_recent_count(policy))
    if result.get("archived"):
        meta.auto_commit_last_error = ""
        meta.auto_commit_last_error_at = ""
        meta.last_auto_commit_at = get_current_timestamp()   # 节流计时起点
    await session._save_meta()
except Exception as exc:
    # best-effort 记录错误,不影响主流程
    meta.auto_commit_last_error = str(exc); meta.auto_commit_last_error_at = now
finally:
    async with self._auto_commit_claims_lock:
        self._auto_commit_claims.discard(claim)   # 无论成败释放进程内 claim

要点:

  • 调度时判过一次、执行前再复核一次 has_running + _should_run_auto_commit,覆盖"排队期间状态已变"的竞态。
  • idle_timeout 走全量提交(keep_recent_count=0 且不持久化 keep),对应 PRD "超时将 session 内未被抽取的所有 message 都提交"。
  • message_write 按策略 keep_recent_count 保留最近若干条。
  • 只有真正 archived 才更新 last_auto_commit_at(节流基准)并清错误;skipped(无消息/全在 keep 窗内)不刷新节流时钟。
  • 错误记账是 best-effort,二次 get 也可能失败,失败只记 debug。

节流 _within_min_commit_interval

interval = get_min_commit_interval_seconds(policy);interval<=0 或无 last_auto_commit_at → 不节流。否则 now - last_auto_commit_at < interval 即处于节流窗口,_should_run_auto_commit 直接返回 False。节流只对 message_write 生效(idle 分支不查节流,但 idle 本身有 idle_timeout 天然间隔)。

关键设计取舍

keep_recent_count 与 meta.keep_recent_count 解耦

这是本次实现中最重要的一处修正。

  • meta.keep_recent_count 是 plugin 管理的 pending-token 记账窗口:决定 _rebuild_pending_tokens() / _append_messages() 时哪些消息计入 pending_tokens。
  • 策略里的 auto_commit_policy.keep_recent_count 是 commit 时的预留条数(PRD "每次自动抽取预留出最新的消息条数")。

早期实现曾在 load() / create() 时把 policy.keep_recent_count(默认 2)镜像进 meta.keep_recent_count,导致:session 加载后 pending 记账窗口被改成 2,≤2 条消息的 session 直接 pending_tokens=0,破坏了既有语义(test_get_session_pending_tokens_counts_tool_only_messages 失败)。

最终方案:两者完全解耦。

  • 策略的 keep_recent_count 只在自动 commit 触发那一刻作为 commit_async(keep_recent_count=...) 的实参使用。
  • load() 不会给缺失策略的 session 回填默认 auto_commit_policy;缺失或 None 保持关闭。只有当 meta 里已经存在策略 dict 时,运行期读取才会通过 AutoCommitPolicy.from_dict(...).to_dict() 做 clamp / 默认字段补齐。无论哪种情况,load() 都不再写 meta.keep_recent_count。
  • create 也不再镜像。
  • commit_async 的 persist_keep_recent_count=False(idle 全量路径)确保一次性全量归档不会把存量 keep 偏好写成 0。

这样 pending_tokens 保持"累积未提交 token 总数"语义(正好对应 PRD 的累积 token 触发口径),既有 plugin 行为不受影响。

幂等与"以最新一次调用为准"

PRD 要求触发抽取时"以最新一次调用为准"。OV 的实现是:策略在创建 session 时持久化到 session meta,创建后不可变;每次触发时(maybe_schedule_auto_commit / run_auto_commit)都会重新 get session 读取权威 meta,基于最新的消息计数、pending token、节流时间和任务状态做复核。而两级去重 + archived 才刷新节流时钟,保证同一时刻只有一次归档在飞,具备幂等性。

clamp 而非 422 拒绝

把越界值 clamp 成上限、返回 200,而不是拒绝请求,是为了对齐记忆库"设了个超大值也能用(按上限生效)"的宽松语义,降低迁移摩擦;同时把"什么是非法(未知字段/非整数)"与"什么只是越界"区分开——前者报 400,后者静默 clamp。

分布式部署的局限与扩展预留

当前实现主要面向**单实例(或单调度器实例)**部署,两条触发链路的分布式特性不同:

  • 消息写入触发(message_write):天然随请求分布到各实例,配合 commit_async 内的文件系统分布式锁 + task_tracker.has_running 跨进程去重,多实例并发写入同一 session 时不会重复归档,无额外假设。
  • 空闲超时触发(idle_timeout):由 SessionAutoCommitScheduler 后台全量扫描 AGFS 触发。即使 idle_enabled=true,也只会处理自身 auto_commit_policy 已存在且 idle_timeout_seconds>0 的 session。当前设计假定至多一个实例开启 idle_enabled 并承担扫描。若多实例同时开启 idle 调度器,会出现:
    • 每个实例都对全量 session 树做重复扫描,扫描成本随实例数线性放大;
    • 虽然 has_running + 进程内 claim 能兜住"重复归档",但重复扫描/重复排队仍是浪费,且缺乏跨实例的分片与故障接管机制。

扩展预留:本设计有意把 idle 触发与执行解耦——调度器只负责"发现到期的 session 并调用 maybe_schedule_auto_commit",真正的去重、节流、归档都收敛在 session_service 一侧且已具备跨进程语义。因此未来面向分布式的演进(例如:调度选主 / 租约、session 分片扫描、扫描任务下发到队列、独立的 idle-scan 服务等)可以只替换"谁来扫描、如何分片"这一层,而不必改动策略模型、触发判定与 commit 执行路径。具体分布式方案不在本文档范围内,此处仅保留扩展点。

服务端全局配置

openviking_cli/utils/config/memory_config.py:SessionAutoCommitConfig(memory.session_auto_commit),这是服务端全局控制面,不是 per-session 业务策略:

参数 默认 约束 说明
default_enabled false — 创建 session 时,如果请求未显式传 config.auto_commit_policy,是否默认写入完整默认策略并启用自动 commit
idle_enabled false — 是否启动 idle 调度器。关闭时,已启用策略的 session 仍可通过 token / message-count 做即时触发
check_interval_seconds 60.0 >0 idle 扫描周期
scan_batch_size 16 >0 每批并发读取的 meta 文件数
scan_batch_pause_seconds 0.0 >=0 批间暂停,降低扫描存储压力

(model_config = {"extra": "forbid"},未知配置项报错。)

service/core.py 启动流程:set_session_auto_commit_config(...) → 仅当 idle_enabled 才 SessionAutoCommitScheduler(...).start();关停时对应 stop()(cancel 循环 task 并等待)。default_enabled 只影响新 session 创建时的默认策略落库,不会启动后台调度器,也不会改写已有 session。

SDK 与 CLI

Python SDK

  • create_session(session_id=None, memory_policy=None, config=None) — config 形如 {"auto_commit_policy": {...}}。
  • 本地 client(client/local.py)从 config 里取 auto_commit_policy 直接下沉到 SessionService.create,不经过 HTTP/Pydantic,因此依赖 dataclass 兜底校验。
  • 当前嵌入式 / 本地 SDK 与 HTTP SDK 都支持 create 时传 config;不再提供 update_session_config / Session.update_config 这类运行期配置更新入口。

Rust CLI

Rust CLI 当前不提供 auto_commit_policy set 或运行期更新命令。ov session get
会展示服务端返回的 session config,用户需要通过 HTTP / SDK 在创建 session
时设置策略。

测试

  • tests/unit/session/test_auto_commit_policy.py(13)— dataclass 默认值、clamp(越界/负数)、未知键拒绝、非整数拒绝、merge 部分覆盖、to_dict。
  • tests/unit/service/test_session_auto_commit.py(17)— 触发判定(token/message 严格大于)、policy is None 跳过 message_write / idle_timeout、节流窗口、idle 全量提交、时区归一、commit_calls=(keep_recent_count, persist_keep_recent_count) 断言、去重。
  • tests/server/test_api_sessions.py(新增/改写多条)— 默认关闭时 create / GET 返回 auto_commit_policy=null、default_enabled=true 时 create 与首次写消息 auto-create 都写入默认策略、显式 {} / 部分字段启用并填充默认、clamp 返回 200、未知字段 400、PATCH /sessions/{id} 返回 405、keep_recent_count 与 pending_tokens 解耦、移除的逐消息入参被静默忽略。
  • Rust:cargo test -p ov_cli 覆盖 session 命令仍不会把移除的 message-level auto_commit_policy 写入消息请求体。

已知无关失败:test_tool_result_externalization_respects_server_config_disabled、test_commit_endpoint_returns_accepted_with_task_id 等在 HEAD 基线上也失败(这些用例自建 app 未接 dev auth plugin,返回 401),与本设计无关。

端到端时序

消息写入触发

client ── POST /sessions/{id}/messages ──▶ add_message()
                                              │ session.add_messages([...])   # O(1) 维护 pending_tokens
                                              │ touch_last_message_at()        # 写 last_message_at
                                              │ maybe_schedule_auto_commit(reason="message_write")
                                              │     ├─ _should_run_auto_commit? (policy 存在 & uncommitted & 未节流 & >阈值)
                                              │     ├─ 进程内 claim 去重 + task_tracker.has_running 去重
                                              │     └─ create_task(run_auto_commit)   # 异步,不阻塞响应
                                              ▼
                                        200 {session_id, message_count}

(后台)run_auto_commit ──▶ 复核 has_running + _should_run_auto_commit
                              └─▶ commit_async(keep_recent_count=policy.keep_recent_count)
                                    ├─ Phase 1:路径锁内归档 pending,保留最近 keep 条
                                    ├─ archived → 清 error,写 last_auto_commit_at(节流起点)
                                    └─ Phase 2:后台抽取记忆(task + .failed.json 上报)
                              finally: 释放进程内 claim

空闲超时触发

每 check_interval 秒(仅 idle_enabled=true):
  SessionAutoCommitScheduler._scan_once()
    └─ ls /local/*/user/*/sessions/*  分批(scan_batch_size)读 .meta.json
         └─ _is_idle_policy_due? (policy 存在 & 有未提交内容 & last_message_at + idle_timeout <= now)
              └─ maybe_schedule_auto_commit(reason="idle_timeout")
                   └─ run_auto_commit ──▶ commit_async(keep_recent_count=0, persist=False)  # 全量提交

相关代码入口

  • openviking/session/auto_commit_policy.py — 策略 dataclass、clamp、默认字段补齐。
  • openviking/service/session_auto_commit.py — 运行期 helper + idle 调度器(扫描/判定/时区归一)。
  • openviking/service/session_service.py — create / touch_last_message_at / effective_session_config / maybe_schedule_auto_commit / run_auto_commit / _should_run_auto_commit / _within_min_commit_interval。
  • openviking/session/session.py — SessionMeta 字段、load() 保持缺失策略为关闭、_append_messages() / _rebuild_pending_tokens() 记账、commit_async(persist_keep_recent_count=...) 两阶段。
  • openviking/server/routers/sessions.py — request models、create / get / messages 路由。
  • openviking_cli/utils/config/memory_config.py — SessionAutoCommitConfig。
  • openviking/service/core.py — 调度器 bootstrap / 关停。
  • crates/ov_cli/src/{main,commands/session}.rs — CLI 展示与消息请求体兼容逻辑。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch from bd10b0e to 798b0be Compare June 22, 2026 14:56
@zhoujh01
zhoujh01 marked this pull request as ready for review June 22, 2026 14:56
@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch 3 times, most recently from 0a5fefd to c4af314 Compare June 26, 2026 07:24

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

本次 review 发现 3 个 blocking 问题:batch API validator 调用不存在函数、CLI 测试编译失败、enabled 必填与 CLI/文档 contract 不一致。另有 1 个 non-blocking 建议关于 token_threshold=0 的边界语义。

Comment thread openviking/server/routers/sessions.py Outdated
def validate_content_or_parts(self) -> "BatchMessageRequest":
if self.content is None and self.parts is None:
raise ValueError("Either 'content' or 'parts' must be provided")
self.peer_id = normalize_peer_selector(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

normalize_peer_selector(...) 在仓库里不存在,当前文件也只 import 了 normalize_peer_id。因此任何 /messages/batch 请求都会在 BatchMessageRequest 的 Pydantic validator 里触发 NameError,批量写消息主路径直接不可用。

最小修法:不要新建这个只为禁用 per-message policy 的 BatchMessageRequest,继续复用已有的 AddMessageRequest;保留 batch 顶层的 before validator 拒绝 messages[*].auto_commit_policy 就够了。

Comment thread crates/ov_cli/src/commands/session.rs Outdated
None,
);

let body = message_body(&client, "user", "hello");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

message_body 的签名是 fn message_body(role: &str, content: &str),这里传入 &client 会让 Rust 测试编译失败。这个测试不需要构造 HttpClient。

最小修法:

let body = message_body("user", "hello");

同时删掉上面的 HttpClient import 和 client 变量。

Comment thread openviking/server/routers/sessions.py Outdated
class AutoCommitPolicyRequest(BaseModel):
"""Session-level server-side auto-commit policy."""

enabled: bool

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

服务端把 enabled 设成必填,但 CLI/文档都把各字段设计成可单独传入。比如用户运行 ov session add-message ... --token-threshold 512 时,CLI 会发送 { "auto_commit_policy": { "token_threshold": 512 } },这里会被 FastAPI 422 拒掉。

需要统一 contract:要么服务端给 enabled 一个默认值,要么 CLI 在任一 auto-commit 参数出现时自动补/强制要求 --auto-commit-enabled。

threshold = int(value)
except (TypeError, ValueError):
return None
return threshold if threshold >= 0 else None

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] (non-blocking)

token_threshold=0 会被视为有效阈值,后面 pending_tokens < threshold 的判断会让每次写消息都满足触发条件。除非明确要支持“每条消息都自动 commit”,这里建议只接受 > 0,并和 API 模型的校验保持一致。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch 2 times, most recently from 5df58f4 to 9f0abde Compare June 30, 2026 09:21

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

本次 review 主要 blocking 是自动提交与后续写消息并发时可能覆盖 live messages,存在数据丢失风险。另有两个需要一起修的契约/构建问题:API 文档与服务端 required 字段不一致,以及 setuptools-scm 只改了 lockfile 没改 pyproject 源约束。

return False
self._auto_commit_claims.add(claim)

asyncio.create_task(self.run_auto_commit(session_id, ctx, reason=reason_hint))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

这里异步启动 run_auto_commit() 后,自动 commit 会基于它加载到的 session 快照进入 Session.commit_async()。但普通 add_messages() 追加 messages.jsonl 不拿 commit 使用的 session path lock。真实场景是 token threshold 触发后台 commit 后,用户马上继续追加下一条消息;commit 可能用旧快照重写 live messages.jsonl,把刚追加的消息覆盖掉。

最小修法:让写消息路径和 commit 重写 live 文件路径共享现有 session lock;不需要新增调度状态机或持久化 in-flight 状态。

Comment thread docs/en/api/05-sessions.md Outdated

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `enabled` | bool | No | Enables or disables automatic commit for the session. Setting it to `false` turns off auto-triggering for that session |

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

这里写 enabled 非必填,但服务端 AutoCommitPolicyRequest.enabled 是 required。按这个文档传 {"token_threshold": 512} 会被 FastAPI 422 拒掉。CLI 现在已经强制用户传 --auto-commit-enabled,但 HTTP API/SDK 用户仍会被文档误导。

最小修法:要么把英文和中文 API 文档都改成 enabled required,要么服务端给 enabled 一个默认值;二选一即可。

def test_root_build_system_pins_setuptools_scm_below_v10_for_isolated_builds():
pyproject = _read_text("pyproject.toml")

assert '"setuptools-scm>=8.0,<10.0",' in pyproject

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

这个测试断言 pyproject.toml 里已经把 setuptools-scm pin 到 <10.0,但本 PR 实际只改了 uv.lock。当前 PR head 的 pyproject.toml 仍然有 setuptools-scm>=8.0 和 setuptools_scm>=10.0.0,既没有约束 isolated build,也会让这个测试在跑到时失败。

最小修法:同步修改 pyproject.toml 里的 build-system / dev / build extra 约束,再更新 lockfile。

Comment thread openviking/service/session_service.py Outdated
return

keep_recent_count = int((policy or {}).get("keep_recent_count", 0) or 0)
result = await session.commit_async(keep_recent_count=keep_recent_count)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] (non-blocking)

auto_commit_last_error 目前只覆盖 run_auto_commit() 自身异常。Session.commit_async() 返回时 phase1 已 accepted,但 phase2 memory extraction 还在后台 task 中继续执行;如果 phase2 失败,只会体现在 task failed / .failed.json,不会写到 auto_commit_last_error。

不建议为这个加新的重试状态机。最小处理是把字段说明收窄:它记录自动触发/phase1 调度错误,不代表 phase2 最终结果。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch 2 times, most recently from b1d0643 to 5b31c4d Compare July 1, 2026 14:13

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

本次只发布必须修复项。当前还有 3 个 blocking 问题:锁失败被当成成功会导致自动提交漏触发并清掉 pending token;setuptools-scm 只改了 lockfile 没改 pyproject 源约束;BaseClient 暴露了 auto_commit_policy 但 embedded client 路径没有实现,导致 HTTP/CLI 与 embedded mode 行为不一致。

Comment thread openviking/session/session.py Outdated
self._messages = list(messages_to_archive) + list(retained_messages)
self._compression.compression_index -= 1
raise
except LockAcquisitionError:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

这里把 LockAcquisitionError 当成一次成功的 commit 返回:status 是 accepted,但 task_id / archive_uri 都是 None,同时还把 pending_tokens 清成 0。

在当前项目里,锁获取失败是一个 retryable conflict,不是成功态;默认 transaction.lock_timeout=0 时,只要另一个请求正持有同一个 session path lock,就会立即触发。举例:session 已启用 auto commit,后台 commit 正在重写 live messages.jsonl,此时另一个 token-threshold commit 进来抢不到锁。修改后这条路径会返回 accepted,并清掉待提交 token 计数,但实际没有归档、没有后台 task,也没有错误暴露给调用方。后续 token-only session 可能因为 pending_tokens 已归零而不再自动提交,造成未提交内容静默滞留。

Comment thread uv.lock Outdated
{ name = "setuptools", marker = "extra == 'build'", specifier = ">=61.0" },
{ name = "setuptools-scm", marker = "extra == 'build'", specifier = ">=8.0" },
{ name = "setuptools-scm", marker = "extra == 'dev'", specifier = ">=10.0.0" },
{ name = "setuptools-scm", marker = "extra == 'build'", specifier = ">=8.0,<10.0" },

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

这里把 lockfile 里的 setuptools-scm 约束改成了 <10.0,但源约束没有同步改:当前 pyproject.toml 仍然有 build-system 的 setuptools-scm>=8.0,以及 dev extra 的 setuptools_scm>=10.0.0。

这意味着修复只存在于当前 lockfile 快照里,不存在于依赖真相源里。举例:用户做 isolated build 时,build backend 会按 pyproject.toml 的 requires 解析,仍然可以安装 setuptools-scm 10.x;下一次重新生成 lockfile 时,dev extra 甚至会继续要求 >=10.0.0,把这里的 <10.0 覆盖回去。之前 review 提过这个问题,目前当前 head 仍未解决。

Comment thread openviking_cli/client/base.py Outdated
parts: list[dict] | None = None,
created_at: str | None = None,
peer_id: str | None = None,
auto_commit_policy: dict[str, Any] | None = None,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

BaseClient.add_message() / batch_add_messages() 现在声明支持 auto_commit_policy,但 embedded Python client 路径没有实现这个新参数:openviking.AsyncOpenViking.add_message()、SyncOpenViking.add_message()、openviking.client.Session.add_message() 和 LocalClient.add_message() 都仍是旧签名,LocalClient 也没有调用 persist_auto_commit_policy_and_schedule() 或 maybe_schedule_auto_commit()。

具体例子:文档和接口让用户以为可以在 Python embedded mode 里调用 OpenViking(...).add_message(..., auto_commit_policy={"enabled": true, "token_threshold": 512}),但实际会在 wrapper 层直接 TypeError: got an unexpected keyword argument 'auto_commit_policy';即使绕到 LocalClient 当前实现,也只会追加消息,不会持久化 policy 或触发 token auto commit。这样 HTTP/CLI 可用,embedded mode 不可用,公共 API contract 不一致。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch from 5b31c4d to 3f053ef Compare July 2, 2026 06:13

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

本次 review 发布 3 个必须修复问题和 1 个非阻塞建议。主要 blocking 是自动提交任务执行前缺少 token/idle 最终复核,会在触发条件已失效后继续归档 live messages;另外 idle scanner 对合法但非对象的坏 meta 不容错,embedded batch path 与 HTTP 的 per-message auto_commit_policy 契约不一致。

Comment thread openviking/service/session_service.py Outdated
return

keep_recent_count = int((policy or {}).get("keep_recent_count", 0) or 0)
result = await session.commit_async(keep_recent_count=keep_recent_count)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

run_auto_commit() 收到了 reason,但真正执行前只重新检查了 should_enable_auto_commit(policy),没有按 token_threshold 或 idle_timeout 再做一次最终校验,然后就直接调用 session.commit_async(...)。

这会让已经过期的调度决策继续生效。具体例子:idle scheduler 在 12:00:00 扫到某个 session 已经 due,于是 maybe_schedule_auto_commit(..., reason_hint="idle_timeout") 创建后台任务;12:00:01 用户又发了一条新消息,last_message_at 已经刷新;12:00:02 这个后台任务才运行。当前代码会加载最新 session 后直接 commit,把刚活跃的 session 也归档掉,违反 idle timeout 语义。token path 也有类似窗口:任务排队后如果用户手动 commit 清掉 pending tokens,再写入一条低于阈值的新消息,旧任务仍可能提前 commit 这条新消息。

影响是自动 commit 会在触发条件已经不成立时归档 live messages,用户可见行为会从“空闲/达到阈值才自动提交”变成“曾经达到过条件的旧任务也能提交后续新内容”。

return None

try:
if not _is_idle_candidate(meta, now):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

这里假设 json.loads(raw) 一定返回 dict,但合法 JSON 也可能是 []、"bad"、123。这种情况下 _is_idle_candidate(meta, now) 会在内部执行 meta.get(...) 并抛 AttributeError,而当前只捕获 (TypeError, ValueError)。

具体例子:某个历史或损坏的 .meta.json 内容是 []。它不是 JSONDecodeError,会进入这里并让整次 _process_meta_batch() 的 asyncio.gather(...) 抛错;_run_loop() 只能记录 “scheduler loop failed”,这一轮后续 due session 不会被调度,下一轮扫到同一个坏 meta 还会重复失败。

这个路径和 PR 描述里的“坏 meta / 缺失 meta / 扫描异常做容错”不一致。一个坏 meta 不应该阻断同批或后续 session 的 idle auto commit。

Comment thread openviking/client/local.py Outdated
)

added = session.add_messages(specs)
await self._service.sessions.persist_auto_commit_policy_and_schedule(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

HTTP /messages/batch 明确拒绝 messages[*].auto_commit_policy,但 embedded LocalClient._batch_add_messages_impl() 没有做同样校验:循环里只读取 role/content/parts/peer_id/created_at,每条 message 上的 auto_commit_policy 会被静默忽略,最后只持久化顶层 auto_commit_policy。

具体例子:embedded 用户调用 batch_add_messages("s1", [{"role": "user", "content": "hello", "auto_commit_policy": {"enabled": true, "token_threshold": 1}}]) 会成功返回,但 policy 不会写入 meta,也不会触发 token auto commit;同样 payload 走 HTTP 会 400。这样 HTTP/SDK server path 和 embedded path 的公共 contract 不一致,而且 embedded 下是静默失败,用户很难发现自己配置没有生效。

assert '"console/static/**/*"' in setup_py


def test_build_workflow_invokes_maturin_via_python_module():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] (non-blocking)

这个 PR 删除了 packaging 相关断言,但当前 diff 没有对应的 packaging 实现变更:test_openviking_package_includes_console_static_assets() 被整体删掉,test_root_build_system_includes_maturin_for_isolated_builds() 里对 --features s3 的断言也被删掉。

这和 session auto commit 主题无关,会让 packaging 回归少一层保护。举例:如果后续 root 包漏掉 console static assets,或者 ragfs-python wheel 构建参数少了必要 feature,这个 PR 合并后测试就不再能发现。若这些断言已经过时,建议在 PR 里说明对应的实现/构建约束已经被替代;否则应恢复这些测试。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch from 3f053ef to 0ec5099 Compare July 2, 2026 11:55

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

本次只发布必须修复项。当前还剩 1 个 blocking:auto commit 仍可能在获取 session lock 前使用旧 session snapshot,覆盖锁期间已经成功追加的新消息。

# Use filesystem-based distributed lock so this works across workers/processes.
session_path = self._viking_fs._uri_to_path(self._session_uri, ctx=self.ctx)
async with LockContext(get_lock_manager(), [session_path], lock_mode="exact"):
async with LockContext(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

commit_async() 在进入 LockContext 之前已经基于当前 Session 实例的 self._messages 做了加载/快照,进锁后只检查这个内存列表是否为空,没有重新读取 messages.jsonl。这使得当前补的 append lock 只覆盖“commit 已持锁时 append 失败”的窗口,覆盖不了“commit 还没拿锁,append 先成功”的窗口。

具体例子:

  1. s1 已启用 auto_commit_policy={"enabled": true, "token_threshold": 100, "keep_recent_count": 0},磁盘 messages.jsonl 当前只有 m0。
  2. token threshold 触发自动 commit,run_auto_commit() 调 self.get() 加载出一个 Session 实例,此时 self._messages == [m0]。
  3. 这个 commit 任务准备进入 LockContext,但还没拿到 lock。
  4. 用户马上通过 add_message() 追加 m1。因为 commit 还没持锁,append 可以拿到同一把 session lock,并把 m1 成功写进 messages.jsonl,磁盘变成 [m0, m1]。
  5. auto commit 随后拿到 lock,但仍用旧的 self._messages == [m0] 计算 messages_to_archive=[m0]、retained_messages=[],然后调用 _write_to_agfs_async(messages=[]) 重写 live messages.jsonl。
  6. 结果是磁盘 live 文件从 [m0, m1] 被覆盖成空,m1 没进 archive,也不在 live session 里,用户刚写入的消息丢失。

影响:自动提交与正常写消息并发时仍有数据丢失风险,尤其 token threshold path 会频繁在消息写入后异步创建 commit 任务。这个问题是之前“写消息路径和 commit 重写路径共享 lock”review 的残留窗口;当前实现需要在持有 session lock 后再以存储中的最新 messages.jsonl / meta 作为权威状态,或者用等价方式保证 commit 计算和 live rewrite 基于锁内最新状态。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch from 0ec5099 to 8f3e966 Compare July 2, 2026 13:22

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

本次发布 2 个新的 blocking comments:Python 3.10 下 idle 时间解析会静默失效,以及 embedded client 未复用 HTTP 的 auto_commit_policy 校验。此前 openviking/session/session.py:1157 的并发数据丢失 thread 仍未解决,本次不重复发布同一条。

if not last_message_at:
return None
try:
base = datetime.fromisoformat(last_message_at)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

compute_next_check_at() 现在直接用 datetime.fromisoformat(last_message_at) 解析 session meta 中的 last_message_at。但写入路径 persist_auto_commit_policy_and_schedule() 用 get_current_timestamp() 写入的是 2026-06-20T10:00:00.000Z 这种 UTC Z 后缀格式。

为什么这是问题:
项目的 requires-python 仍是 >=3.10,Python 3.10 的 datetime.fromisoformat() 不能解析 Z 后缀;仓库已有 openviking.utils.time_utils.parse_iso_datetime() 专门处理这个格式。当前代码会捕获异常后返回 None,不是报错,所以 idle auto commit 会静默失效。

具体例子:

  1. Python 3.10 部署。
  2. 用户写入一条消息并设置 auto_commit_policy={"enabled": true, "idle_timeout_seconds": 60}。
  3. persist_auto_commit_policy_and_schedule() 写入 last_message_at="2026-06-20T10:00:00.000Z"。
  4. 60 秒后 scheduler 扫到这个 session。

执行过程:

  1. _read_idle_candidate() 调 _is_idle_candidate(meta, now)。
  2. _is_idle_policy_due() 调 compute_next_check_at(meta["last_message_at"], 60)。
  3. datetime.fromisoformat("2026-06-20T10:00:00.000Z") 在 Python 3.10 抛 ValueError。
  4. compute_next_check_at() 返回 None,_is_idle_policy_due() 返回 False。
  5. 这个 session 不会进入 maybe_schedule_auto_commit()。

影响:
Python 3.10 环境里,真实消息写入生成的 idle policy 永远算不出 deadline,idle auto commit 不会触发;用户看到的是 policy 已保存但服务端从不自动提交。

Comment thread openviking/client/local.py Outdated
peer_id=self._resolve_message_peer_id(role, peer_id),
created_at=created_at,
)
await self._service.sessions.persist_auto_commit_policy_and_schedule(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

LocalClient._add_message_impl() 现在把调用方传入的 auto_commit_policy 原样交给 persist_auto_commit_policy_and_schedule();_batch_add_messages_impl() 也走同样路径。这里没有复用 HTTP 路由里的 AutoCommitPolicyRequest 校验。

为什么这是问题:
HTTP API 明确要求 enabled 必填,token_threshold / idle_timeout_seconds 必须大于 0,并且禁止额外字段。embedded client 是同一个公开 client contract,但当前会接受同样无效的 policy 并写进 session meta。

具体例子:

  1. embedded 用户调用 await client.add_message("s1", "user", content="hello", auto_commit_policy={"token_threshold": 512})。
  2. 相同 payload 走 HTTP 会因为缺少 enabled 被 FastAPI 422 拒绝。
  3. embedded path 会成功返回并把 auto_commit_policy={"token_threshold": 512} 写进 .meta.json。

执行过程:

  1. _add_message_impl() 先调用 session.add_message(...) 写入消息。
  2. 这里调用 persist_auto_commit_policy_and_schedule(..., policy_provided=True) 持久化原始 dict。
  3. 随后的 maybe_schedule_auto_commit(..., reason_hint="token_threshold") 读取这个 policy。
  4. should_enable_auto_commit(policy) 因为没有 enabled: true 返回 False,所以不会调度 auto commit。

影响:
同一个 public API 在 HTTP 和 embedded mode 下行为不一致;embedded 用户得到成功返回,但配置实际不会生效,后续 token/idle 自动提交都不会触发。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch 3 times, most recently from 8bc8b9a to 42066b8 Compare July 17, 2026 09:43
@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch from 16eda80 to 518bd51 Compare July 20, 2026 15:53

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

结论:REQUEST_CHANGES。

自动提交总体复用了现有的 Session.commit_async(),但当前实现仍有 4 个阻塞问题:消息请求兼容性回归、独立 Python SDK 与服务端契约冲突、Phase 2 运行期间触发条件会被永久丢弃,以及 commit_async() 返回后用旧 Session 再次完整写 meta 导致并发更新丢失。当前集成 CI 中两个 metadata 用例已经因此失败。

此外,此前 review 在 openviking/session/session.py:1166 提出的旧消息快照问题仍未解决:消息在获取路径锁之前载入;若并发 append 先获得锁,随后 commit 会用旧的 self._messages 重写 live 文件并丢掉新消息。该问题已有未解决的历史 inline thread,本次不重复发同一条评论。

非阻塞项包括:embedded client 静默忽略错误配置键、全局默认开启后无法按 session 关闭、并发扫描测试依赖不稳定顺序,以及默认响应文档与实际返回不一致。PR 还混入了与自动提交无关的测试删除、reindex owner 测试、纯换行和重复 import,建议合并前清理提交范围。

Comment thread openviking/server/routers/sessions.py Outdated
raise ValueError("Either 'content' or 'parts' must be provided")
return self

model_config = {"extra": "forbid"}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

根因:这里把整个 AddMessageRequest 设置为 extra="forbid",因此不只是旧的 auto_commit_policy,所有此前由 Pydantic 忽略的额外消息字段都会变成请求校验错误。这直接改变了既有消息 API 的兼容契约,也与 PR 描述中的“静默忽略旧字段”不一致。

具体例子:

  1. 客户端发送 POST /api/v1/sessions/{id}/messages,请求体包含 role=user、content=hello、metadata.source=test。
  2. 修改前该请求返回 200;修改后在进入路由逻辑前就返回 400,错误为 body.metadata: Extra inputs are not permitted。
  3. BatchAddMessageRequest 复用了 AddMessageRequest,批量接口也会发生同样的回归。

影响:现有客户端的合法调用在升级后失败。当前 CI 已由此稳定失败:TestSessionMessages.test_add_message_with_metadata 和 TestSessionEdgeCases.test_session_add_message_with_metadata 都从预期 200 变成 400。请保留原有消息字段兼容行为,只处理本 PR 真正需要迁移的策略字段。

Comment thread sdk/python/openviking_sdk/client.py Outdated
if peer_id is not None:
payload["peer_id"] = peer_id
if auto_commit_policy is not None:
payload["auto_commit_policy"] = auto_commit_policy

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

根因:独立 Python SDK 仍把 auto_commit_policy 作为每条消息的字段发送,而同一 PR 的服务端把它视为未知字段并通过 extra="forbid" 拒绝;客户端与服务端定义了互相矛盾的公共契约。

具体例子:

  1. 用户调用 add_message(session_id, role="user", content="hi", auto_commit_policy={"enabled": true, "token_threshold": 100})。
  2. SDK 在这里把策略放进消息 POST payload。
  3. 服务端 AddMessageRequest 没有该字段,校验阶段直接返回 400,消息也不会写入。
  4. 这个独立 SDK 同时没有本 PR 对应的 create_session(config=...) / session config 更新入口,因此用户没有可用的替代路径。

影响:SDK 暴露并记录的自动提交功能实际不可用,mock 测试只验证了错误 payload 被组装出来,无法发现端到端失败。请统一 SDK 与服务端的唯一配置入口和字段 schema。

if claim in self._auto_commit_claims:
return False
tracker = get_task_tracker()
if await tracker.has_running(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

根因:达到阈值时如果已有 session_commit Phase 2 task,代码只返回 False,没有记录 pending trigger,也没有在现有 task 完成后重试。因此这次阈值触发会永久丢失。

具体例子(message_count_threshold=50、keep_recent_count=2、idle scheduler 关闭):

  1. 一次自动提交的 Phase 1 把 live messages 缩到 2 条,Phase 2 task 仍在运行。
  2. Phase 2 期间连续写入 49 条新消息,live count 变成 51。
  3. 第 49 条消息调用 maybe_schedule_auto_commit() 时已超过阈值,但这里发现 task 正在运行并直接返回。
  4. 随后流量停止,旧 task 完成;完成路径没有重新检查 51 条 backlog,idle scheduler 又已关闭。

影响:session 可以在超过配置阈值后无限期不再自动提交,直到恰好又收到一条消息。请保证被运行中 task 挡住的触发在 task 完成后仍会被重新检查或执行。

Comment thread openviking/service/session_service.py Outdated
session.meta.auto_commit_last_error = ""
session.meta.auto_commit_last_error_at = ""
session.meta.last_auto_commit_at = get_current_timestamp()
await session._save_meta()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

根因:session.commit_async() 已经持久化过 meta;本 PR 又在它返回后,用提交开始时加载的旧 Session 实例调用一次完整覆盖式 _save_meta()。这不是字段级更新,也不受消息路径锁保护,所以会覆盖并发消息请求刚写入的最新 meta。

具体时间线:

  1. 自动提交 A 的 Phase 1 保留 2 条消息,并保存 message_count=2、pending_tokens=0。
  2. A 在后续 enqueue/tracker 的 await 中尚未返回;请求 B 用另一个 Session 实例追加第 3 条消息,并保存 message_count=3、新的 pending_tokens 和 last_message_at。
  3. A 返回后只修改 last_auto_commit_at,但这里把 A 内存中的整份旧 meta 再写一遍。
  4. 磁盘最终退回 message_count=2、pending_tokens=0,而 messages.jsonl 实际已有 3 条。

影响:meta 与消息文件不一致,调度器可能据此跳过后续自动提交。请不要在正常 commit 之后再用旧快照完整写 meta;自动提交状态需要与 commit 的受保护 meta 更新合并,或使用不会覆盖并发字段的原子更新。

config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
await self._service.initialize_user_directories(self._ctx)
auto_commit_policy = (config or {}).get("auto_commit_policy")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Design] (non-blocking)

根因:embedded client 只用 .get("auto_commit_policy") 取值,没有像 HTTP 路径一样校验 config 的 shape 和未知字段,因此两个公开入口对同一配置的处理不同。

具体例子:调用 embedded client 时传 config={"auto_commmit_policy": {...}}(多写一个 m),这里得到 None,session 创建成功但自动提交静默关闭;同样的未知字段经 HTTP API 会明确报错。

影响:拼写错误看起来成功,直到 backlog 不提交时才被发现,也使 local/server 模式难以互换。建议复用同一套 AutoCommitPolicy 配置校验语义。

service = get_service()

auto_commit_policy_payload: Optional[Dict[str, Any]] = None
if request.config is not None and request.config.auto_commit_policy is not None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Design] (non-blocking)

根因:这里把“未提供 policy”和“显式提供 null”都折叠成 None;当 server.session_auto_commit.default_enabled=true 时,service 会把两者都解析成默认策略。因此当前 API 没有按 session 关闭自动提交的表达方式,PATCH 中的 null 也会被转成 {} 并启用默认策略。

具体例子:管理员全局开启默认策略后,用户发送 config.auto_commit_policy=null 想让某个高敏 session 保持手动提交,创建结果仍会持久化完整默认 policy。

影响:全局开关一旦开启便无法做单 session 例外,null 的直觉语义反而是“启用默认值”。如果不支持按 session 关闭是有意取舍,请明确说明业务约束并在 API 文档中写清;否则需要保留 omitted 与 explicit disable 的区别。

("/local/acct_a/user", "acct_a"),
("/local/acct_a/user/user_b/sessions", "acct_a"),
]
assert service.viking_fs.read_calls == [

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] (non-blocking)

根因:scheduler 并发读取多个 meta,但测试把 read_calls 的完成/追加顺序当成稳定契约。asyncio.gather 创建任务后,两个 read() 谁先追加不受保证,生产逻辑也不依赖该顺序。

具体例子:同一次 _scan_once() 可以先记录 session_due 再记录 session_skip,也可以相反;在 macOS / Python 3.14 的 targeted run 中该用例已因顺序反转失败,而两份 meta 都正确读取。

影响:测试会随事件循环调度产生假失败,掩盖真实回归。若这里只验证扫描集合,应比较无序结果;只有业务确实要求顺序时才应在生产代码中建立明确顺序。

Comment thread docs/en/api/05-sessions.md Outdated
"user_id": "alice"
},
"config": {
"auto_commit_policy": {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] (non-blocking)

根因:这个 response example 展示了完整默认策略,但本页前面的默认创建请求没有传 policy,且默认配置是 server.session_auto_commit.default_enabled=false。实际 create() 会把 session.meta.auto_commit_policy 设为 None,effective_session_config() 因而返回 "auto_commit_policy": null。

具体例子:按第 70 行的无 body curl 创建 session,实际响应不是这里列出的 1000/50/86400/2/60,而是 config.auto_commit_policy=null。

影响:用户会误以为不传配置也默认开启自动提交。请让示例与默认请求对应,或明确标注该响应仅适用于全局默认开启/显式提供策略的场景;中文文档中的对应示例也需要同步。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch from bbdc5b8 to 36329c5 Compare July 23, 2026 15:44

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

结论:REQUEST_CHANGES。

本次按要求只发布必须修复项。当前 head 仍有 2 个 blocking 问题:session config PATCH 会被并发消息写入用旧 meta 静默覆盖;default_enabled 没有应用到首次写消息时自动创建的 session。非阻塞建议和已有历史评论本次不重复发布。

Comment thread openviking/service/session_service.py Outdated
current = AutoCommitPolicy.from_dict(session.meta.auto_commit_policy)
merged = current.merge(config_patch.get("auto_commit_policy"))
session.meta.auto_commit_policy = merged.to_dict()
await session._save_meta()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

问题位置:update_session_config() 修改当前 Session 实例中的 policy 后,直接调用完整覆盖式 session._save_meta()。这个写入没有使用消息追加和 commit 共用的 session path lock,也没有在保存前重新读取持久化的最新 meta。

为什么这是问题:公开的 PATCH 和消息写入可以并发执行;两个请求各自持有独立的 Session 快照。只要消息请求在 PATCH 落盘前判断旧 policy 为 None,它就会走无锁追加路径,随后用旧快照覆盖 PATCH 已成功写入的整份 meta。

具体时间线:

  1. session 当前 auto_commit_policy=null,消息请求 A 和 PATCH 请求 B 都加载到这份旧 meta。
  2. A 的 _should_use_auto_commit_append_lock() 读取到持久化 policy 仍为 None,返回 False。
  3. B 合并 {"message_count_threshold": 1},这里调用 _save_meta() 写入新 policy,并向用户返回成功。
  4. A 完成消息追加后进入 if not use_session_lock,调用 _save_meta_sync(),把自身仍含 auto_commit_policy=None 的旧 meta 整体写回。
  5. 最终 GET session config 又返回 auto_commit_policy=null;B 的成功更新已经丢失。

影响:用户收到 PATCH 成功响应,但自动 commit 实际仍被关闭;同一类完整覆盖还可能回退并发更新的 message_count、pending_tokens 和 last_message_at。配置更新需要与现有 session path lock/权威 meta 合并机制共享同一个并发边界,并补充 PATCH 与 append 交错的回归测试。

set(MemoryTypeRegistry().list_names(include_disabled=False))
)
session.meta.memory_policy = policy.to_dict()
if auto_commit_policy is not None or self._session_auto_commit_config.default_enabled:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

问题位置:全局 default_enabled 只在 SessionService.create() 这条显式创建路径里应用;SessionService.get(..., auto_create=True) 发现 session 不存在时只调用 ensure_exists(),不会执行这里的默认 policy 初始化。

为什么这是问题:单条和批量消息路由都明确支持“首次写消息时自动创建 session”,embedded LocalClient 也走同一条 get(..., auto_create=True) 路径。这些都是创建新 session 的公开主路径,但它们绕过了全局默认开关的语义。

具体例子:

  1. 服务端配置 memory.session_auto_commit.default_enabled=true。
  2. 客户端不先调用 POST /sessions,直接向不存在的 s1 调用 POST /sessions/s1/messages。
  3. 消息路由调用 get("s1", auto_create=True);get() 只创建目录并保存初始 meta,auto_commit_policy 保持 None。
  4. 消息写入后的 maybe_schedule_auto_commit() 看到 policy 为 None,不会按 token/message threshold 调度;idle scanner 也会跳过这个 session。

影响:同一个全局配置下,显式 create 的 session 会自动 commit,而通过文档承诺的首次消息 auto-create 得到的 session 会永久保持关闭,行为取决于调用顺序。请让新 session 的默认 policy 初始化同时覆盖显式 create 和 auto-create,并补充 HTTP/embedded 首次写消息场景的测试。

@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch from 34e450a to 252777d Compare July 27, 2026 07:38
zhoujh01 added 14 commits July 28, 2026 11:46
feat(server): add session auto commit scheduling

fix: harden session auto commit e2e coverage

refactor: shorten session auto commit index path

docs: sync session auto commit design and api docs

feat: refine session auto commit idle indexing

feat: expose session auto commit in sdk and cli

fix: pin setuptools-scm for editable builds

fix: harden session auto commit index sync

refactor session idle auto commit scanning

fix session idle auto commit scheduling

fix(session): align auto-commit policy contract and fix batch validator

- Drop BatchMessageRequest which called a non-existent normalize_peer_selector
  and broke /messages/batch with NameError; reuse AddMessageRequest while
  keeping the top-level per-message policy rejection.
- Require --auto-commit-enabled in the CLI whenever any auto-commit option is
  set, so partial payloads no longer 422 or silently overwrite an enabled
  policy server-side.
- Treat token_threshold=0 as invalid (gt=0 in API model and service helper) to
  avoid auto-committing on every message.
- Fix ov_cli message_body test that passed an extra client argument and patch
  SkillCommands List/Remove pattern matches missing the new parent field.

fix session auto commit live message race

test: update core startup queue fake

update

chore: restore uv lockfile

fix: handle auto commit lock conflicts

fix session auto commit final validation
Rewrite the session auto-commit mechanism to strictly follow the PRD:

- Add AutoCommitPolicy dataclass (pending_token_threshold,
  message_count_threshold, idle_timeout_seconds, keep_recent_count,
  min_commit_interval_seconds) with recommended defaults, [0, max]
  clamping, and unknown-key rejection. The policy is a baseline config
  that applies to every session via defaults; there is no per-session
  on/off switch.
- Configure the policy via session config only: POST /sessions with a
  config object, PATCH /sessions/{id} with merge semantics, and view it
  via GET /sessions/{id} (result.config). Drop the per-message
  auto_commit_policy input from add_message / batch_add_messages.
- Trigger inline auto-commit after message writes when accumulated
  pending tokens or live message count exceed the configured thresholds,
  throttled by min_commit_interval_seconds. Idle-timeout commits (gated
  by the server-wide idle_enabled switch) archive the full backlog.
- Keep the policy keep_recent_count as a commit-time reservation only;
  it is decoupled from meta.keep_recent_count so pending-token
  accounting is unchanged.
- Update Python SDK (create/update_session), Rust CLI
  (session auto-commit-policy set), docs (en/zh), and tests.
@zhoujh01
zhoujh01 force-pushed the session-auto-commit-server branch from 61b8104 to d225018 Compare July 28, 2026 03:46

@qin-ctx qin-ctx left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

结论:REQUEST_CHANGES。

本次发布 4 条新的 inline comments:3 条 blocking、1 条 non-blocking。所有评论都只描述可达场景、当前执行路径和实际影响;具体业务保证、兼容性取舍与处理方式请由作者结合部署约束自行决定。

另外,以下已有 non-blocking review threads 在当前 head 仍然成立,本次不重复发布同一条 inline comment:

  • embedded create 对 config 未知键静默忽略,与 HTTP 校验语义不同;
  • default_enabled=true 时,省略 policy 与显式传 auto_commit_policy: null 无法区分;
  • scheduler 并发读取测试仍严格依赖 read_calls 顺序。

此前关于 append/commit 消息覆盖、首次写消息 auto-create、PATCH 并发更新、时间戳解析、坏 meta 和 SDK 契约等 blocking 问题,当前代码已经修复。


session = await self.get(session_id, ctx, auto_create=False)
policy = session.meta.auto_commit_policy
if not self._should_run_auto_commit(session, policy, reason):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

在多 worker 或多服务实例共同访问同一存储时,用户刚写入、已经不再满足 token/message/idle 条件的消息,仍可能被一个旧的自动提交任务提前归档。

run_auto_commit() 在这里用当前 Session 快照执行 _should_run_auto_commit(),但真正的权威消息和 meta 重载发生在后续 commit_async() 获取 session path lock 之后。_auto_commit_claims 只在单进程内去重,而 TaskTracker.has_running() 与 Phase 1 task 创建之间也不是跨 worker 的原子操作,因此两个 worker 可以同时通过这里的检查。

为什么这是问题:自动提交的公开语义是“当前 pending token / message count 超阈值,或当前 session 已空闲”才提交;这里的判定结果在等待 path lock 期间可以失效。

具体例子:

  1. idle_timeout_seconds=60,s1 有一条已经空闲两分钟的消息。
  2. worker A、B 同时扫描到 s1 到期;两者都在任何 Phase 1 task 创建前看到 has_running=False,并分别通过这里的 idle 检查。
  3. A 先获得 session lock,归档旧消息并释放锁。
  4. 用户随后获得同一把锁,写入一条新消息,将 last_message_at 更新为当前时间。
  5. B 已经通过旧快照的检查;它之后获得锁,commit_async() 虽然重载了这条新消息,却不会重新判断 idle 条件,于是把刚写入的消息归档。

影响:idle 和 message threshold 都可能归档不满足当前触发条件的新内容,用户看到的抽取时机与策略配置不一致。

请结合实际部署模型说明你希望保证的跨 worker 触发语义,并由你决定条件判定、权威快照和 path lock 之间应采用什么一致性取舍。

session_service=self._session_service,
)
try:
session_auto_commit_config = get_openviking_config().memory.session_auto_commit

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

通过 create_app(config=ServerConfig(...)) 程序化配置自动提交的服务,可能静默使用全局 singleton 中的另一份配置,导致 default_enabled 和 idle scheduler 都没有按传入配置生效。

OpenVikingService.__init__() 已经把服务使用的 OpenViking 配置保存为 self._config,但这里又调用 get_openviking_config() 读取全局状态;同时 create_app._configure_session_runtime() 会下沉其他 session runtime 配置,却没有下沉 config.memory.session_auto_commit。

为什么这是问题:create_app 明确接受 ServerConfig 和可注入的 service,同一份配置中的其他 session 字段会生效,auto-commit 配置却取决于 singleton 之前如何初始化。

具体例子:

  1. 调用方创建 ServerConfig(memory=MemoryConfig(session_auto_commit=SessionAutoCommitConfig(default_enabled=True, idle_enabled=True)))。
  2. 调用 create_app(config=config, service=service_built_with_default_config)。
  3. _configure_session_runtime() 不会把这份 auto-commit 配置写入 service。
  4. 这里读取 singleton 中默认的 false/false;未传 policy 的新 session 仍返回 auto_commit_policy=null,idle scheduler 也不会启动。

影响:配置对象看起来被应用成功,但运行时行为依赖初始化顺序和另一份全局状态,部署方无法从传入的 ServerConfig 判断实际行为。

请明确 ServerConfig.memory、OpenVikingService._config 和全局 singleton 中哪一个应是该配置的权威来源,并由你决定程序化创建、文件加载和注入 service 三条入口应如何保持一致。

specs: list[dict[str, Any]] = []

for index, message in enumerate(messages):
extra_keys = set(message) - _BATCH_ADD_MESSAGE_KEYS - _BATCH_ADD_MESSAGE_IGNORED_KEYS

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (blocking)

升级后的 embedded client 会拒绝过去能够成功处理、并且当前 HTTP 服务仍然接受的 batch message,造成 local/server 两种公开运行模式的兼容行为分叉。

这里新增的 extra_keys 检查只把旧的 auto_commit_policy 列为忽略项,却拒绝所有其他额外字段。PR 之前该方法只读取已知键,其余键会被忽略;HTTP 的 AddMessageRequest 当前也明确使用 extra="ignore"。

具体例子:

  1. embedded 用户调用 batch_add_messages("s1", [{"role": "user", "content": "hello", "metadata": {"source": "migration"}}])。
  2. 这里计算出 extra_keys={"metadata"},在构造任何消息前抛出 ValueError,整批消息均未写入。
  3. 相同 message object 走 HTTP /messages/batch 时,Pydantic 会忽略 metadata 并成功写入;PR 之前的 embedded 路径也会成功。

影响:既有 embedded 调用在升级后失败,而调用方仅切换 local/server 模式也会得到相反结果;这超出了本 PR“旧 per-message auto_commit_policy 静默忽略”的行为变化范围。

请说明 local 与 HTTP 是否有意采用不同的额外字段契约,并由你结合兼容性要求决定应保留哪种行为。

return False
self._auto_commit_claims.add(claim)

asyncio.create_task(self.run_auto_commit(session_id, ctx, reason=reason_hint))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Bug] (non-blocking)

embedded client 或服务关闭后,自动提交的后台 task 仍可能继续存活并访问已经关闭的 TaskTracker、VikingFS 或 queue,导致关闭流程没有真正释放本 PR 新增的后台工作。

这里创建的 run_auto_commit() task 没有保存可供 shutdown 取消或等待的引用;_schedule_auto_commit_recheck_locked() 创建的长期 recheck task 虽然保存在 _auto_commit_pending_tasks,但 OpenVikingService.close() 只停止 SessionAutoCommitScheduler,没有对应的 SessionService task 清理生命周期。

具体例子:

  1. policy 设置 min_commit_interval_seconds=604800,当前 session 已超过消息阈值但仍处于节流窗口。
  2. 一次消息写入创建 _run_auto_commit_when_not_running();该 task 会按 check_interval_seconds 循环等待,最长可持续七天。
  3. 用户随后执行 await client.close();service 关闭存储和 queue 后返回,但该 recheck task 未被取消或等待。
  4. task 下次醒来仍会调用 tracker.has_running() 和 self.get(),访问已关闭的 service 依赖。

影响:显式 close 后仍残留后台任务、对象引用和关闭后的 I/O;在长生命周期事件循环中会表现为资源泄漏或异步错误。

请明确 close() 对自动提交及延迟 recheck 的完成、取消或放任语义,并由你决定这些 task 应归哪个生命周期所有者管理。

zhoujh01 added a commit that referenced this pull request Aug 4, 2026
Re-implementation of the auto-commit feature (supersedes the overly complex
PR #2772). Commits are triggered on message write (token/message thresholds)
and by an optional background idle-timeout scan. The commit policy is set once
at session creation and is immutable afterwards; all bounds are clamped in
AutoCommitPolicy.from_dict. Server-wide switches live under
memory.session_auto_commit and default to disabled, so hot paths short-circuit
when no policy is stored.

Scheduling is best-effort: a missed cycle is re-triggered by the next write or
idle scan. maybe_schedule_auto_commit swallows scheduling errors so the task
store being unavailable never fails the caller's message write or aborts an
idle scan batch. Spawned commit tasks are kept in a strong-ref set so they are
not GC'd mid-await.

Config is threaded through the HTTP router, local/async/sync clients, the
Python/TypeScript/Go SDKs, and the CLI. Session GET returns the resolved
config.

Co-authored-by: TRAE CLI <noreply@bytedance.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Backlog

Development

Successfully merging this pull request may close these issues.

3 participants