Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
Feat/session auto commit v2 (#3736)
Jiahui Zhoud2056e971d20
diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex a2f28878f..d94e65b22 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -31,6 +31,7 @@ Create a new session. Sessions are containers for conversations, storing message**Code Entries:**- `openviking/session/session.py:Session.__init__()` - Core Session class+- `openviking/session/auto_commit_policy.py:AutoCommitPolicy` - Auto-commit policy defaults and validation- `openviking/server/routers/sessions.py:create_session()` - HTTP route- `openviking_cli/client/base.py:BaseClient.create_session()` - Python SDK- `crates/ov_cli/src/commands/session.rs:new_session()` - CLI command@@ -43,6 +44,19 @@ Create a new session. Sessions are containers for conversations, storing message|-----------|------|----------|---------|-------------|| session_id | str | No | None | Session ID. Creates new session with auto-generated ID if None || memory_policy | object | No | None | Default memory extraction policy for the session. Optional `self` and `peer` switches control write targets, optional `working_memory.enabled=false` skips archive summaries, and optional top-level `memory_types` limits extraction to specific enabled memory schemas. Use JSON booleans for every `enabled` value. Legacy boolean-like values remain accepted temporarily (including string `"false"`, which is parsed as false) but emit a deprecation warning. When `memory_types` is omitted or `null`, all enabled memory schemas are allowed. Invalid shapes or unknown memory types are rejected with `InvalidArgumentError`. |+| auto_commit_policy | object | No | None | Optional auto-commit policy (see table below). Any provided fields are validated, clamped to their bounds, and merged over the defaults; the effective policy is returned in the response `result.auto_commit_policy` and persisted into session metadata. If no policy is provided, auto commit is disabled unless `memory.session_auto_commit.default_enabled=true`. The policy is immutable after creation. |++`auto_commit_policy` fields (all optional; omitted fields fall back to the defaults when a policy is present):++| Field | Type | Default | Max | Description |+|-------|------|---------|-----|-------------|+| `pending_token_threshold` | int | 10000 | 50000 | When uncommitted pending tokens exceed this value (strictly greater-than), an auto commit is triggered after a message write. |+| `message_count_threshold` | int | 50 | 500 | When the uncommitted live message count exceeds this value (strictly greater-than), an auto commit is triggered after a message write. |+| `idle_timeout_seconds` | int | 86400 | 604800 | After this many idle seconds, a session with uncommitted content becomes eligible for the server-side idle scheduler. An idle-timeout commit archives the full backlog and ignores `keep_recent_count`. |+| `keep_recent_count` | int | 2 | 500 | Number of recent live messages to keep (not archived) on a threshold-triggered auto commit. Idle-timeout commits ignore this and commit everything. |+| `min_commit_interval_seconds` | int | 0 | 604800 | Minimum seconds between two automatic commits (throttle). |++All fields have a minimum of `0` and are clamped into `[0, max]`. Unknown keys are rejected with `InvalidArgumentError`.#### 3. Usage Examples@@ -63,6 +77,20 @@ curl -X POST http://localhost:1933/api/v1/sessions \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{"session_id": "my-custom-session-id"}'++# Create new session with a custom auto-commit policy+curl -X POST http://localhost:1933/api/v1/sessions \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "auto_commit_policy": {+ "pending_token_threshold": 8000,+ "message_count_threshold": 40,+ "idle_timeout_seconds": 600,+ "keep_recent_count": 10,+ "min_commit_interval_seconds": 0+ }+ }'```**Python SDK**@@ -80,6 +108,18 @@ print(f"Session ID: {result['session_id']}")# Create new session with specified IDresult = await client.create_session(session_id="my-custom-session-id")print(f"Session ID: {result['session_id']}")++# Create new session with a custom auto-commit policy+result = await client.create_session(+ auto_commit_policy={+ "pending_token_threshold": 8000,+ "message_count_threshold": 40,+ "idle_timeout_seconds": 600,+ "keep_recent_count": 10,+ "min_commit_interval_seconds": 0,+ }+)+print(result["auto_commit_policy"])```**TypeScript SDK**@@ -118,7 +158,8 @@ ov session new"user": {"account_id": "default","user_id": "alice"- }+ },+ "auto_commit_policy": null},"time": 0.1}@@ -227,6 +268,7 @@ Get session details including metadata, message statistics, commit history, etc.- `commit_count`: Number of successful commits- `memories_extracted`: Count statistics of extracted memories by category- `last_commit_at`: Time of last commit+- `auto_commit_policy`: Effective auto-commit policy with defaults filled in; `null` when not enabled**Code Entries:**- `openviking/session/session.py:Session.load()` - Session loading@@ -343,13 +385,29 @@ ov session get a1b2c3d4"account_id": "default","user_id": "alice"},- "pending_tokens": 450+ "pending_tokens": 450,+ "auto_commit_policy": {+ "pending_token_threshold": 10000,+ "message_count_threshold": 50,+ "idle_timeout_seconds": 86400,+ "keep_recent_count": 2,+ "min_commit_interval_seconds": 0+ }}}```---+### Updating Session Config++The auto-commit policy is immutable after creation. Set `auto_commit_policy` when+creating the session, then use `GET /api/v1/sessions/{session_id}` to inspect the+effective config. Runtime session-config updates are not exposed by the Sessions+API.++---+### list_tool_results()List large tool results externalized from a session.diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.mdindex da906ca90..ac83acf12 100644--- a/docs/en/guides/01-configuration.md+++ b/docs/en/guides/01-configuration.md@@ -1179,6 +1179,59 @@ Legacy compatibility example:}```+##### Session Auto Commit Configuration++`memory.session_auto_commit` controls server-wide automatic session commit behavior.++```json+{+ "memory": {+ "session_auto_commit": {+ "default_enabled": false,+ "idle_enabled": false,+ "check_interval_seconds": 60.0,+ "scan_batch_size": 16,+ "scan_batch_pause_seconds": 0.0+ }+ }+}+```++| Parameter | Type | Description | Default |+|-----------|------|-------------|---------|+| `default_enabled` | bool | Enables auto commit by default for newly created sessions that do not explicitly provide `auto_commit_policy`. When `false`, those sessions keep auto commit disabled | `false` |+| `idle_enabled` | bool | Enables the server-side idle-timeout auto-commit scheduler. When disabled, the idle scheduler is not started. Token- and message-count immediate triggering still works | `false` |+| `check_interval_seconds` | float | Poll interval for the idle scheduler in seconds. Must be greater than `0` | `60.0` |+| `scan_batch_size` | int | Maximum number of session meta files read concurrently in each idle scan batch. Must be greater than `0` | `16` |+| `scan_batch_pause_seconds` | float | Optional pause between idle scan batches, in seconds. Use this to reduce storage pressure during large scans | `0.0` |++Notes:++- `memory.session_auto_commit` is a server-wide control surface, not a per-session business policy.+- Per-session auto-commit behavior is configured through the session-level `auto_commit_policy` (see the table below). It is set only when creating a session (`POST /api/v1/sessions` with a top-level `auto_commit_policy` field) and viewed via `GET /api/v1/sessions/{session_id}`; runtime config PATCH is not supported.+- When `default_enabled=false`, sessions created without `auto_commit_policy` keep auto commit disabled and return `auto_commit_policy: null`. Providing `{}` or any policy field explicitly enables auto commit for that session and fills missing fields from the defaults below.+- When `default_enabled=true`, sessions created without `auto_commit_policy` get the default policy below.+- When `idle_enabled=false`:+ - `SessionAutoCommitScheduler` is not started+- When `idle_enabled=true`:+ - `SessionAutoCommitScheduler` wakes up periodically and scans session `.meta.json` files under AGFS `/local/{account}/user/{user}/sessions`+ - It does not perform a dedicated startup recovery sweep; idle detection happens only on periodic scans+- Token- and message-count auto commit run inline after message writes, do not depend on the scheduler, and are unaffected by this switch.++###### Per-session Auto Commit Policy++When a session carries an `auto_commit_policy`, any field you omit falls back to the recommended default below. Sessions without a stored policy keep auto commit disabled. Values are clamped into `[0, max]`, and unknown keys are rejected with `InvalidArgumentError`. See [Sessions API](../api/05-sessions.md#create_session) for how to set and view it.++| Field | Type | Default | Max | Description |+|-------|------|---------|-----|-------------|+| `pending_token_threshold` | int | 10000 | 50000 | When uncommitted pending tokens exceed this value (strictly greater-than), an auto commit is triggered after a message write. |+| `message_count_threshold` | int | 50 | 500 | When the uncommitted live message count exceeds this value (strictly greater-than), an auto commit is triggered after a message write. |+| `idle_timeout_seconds` | int | 86400 | 604800 | After this many idle seconds, a session with uncommitted content becomes eligible for the server-side idle scheduler. Idle-timeout commits archive the full backlog and ignore `keep_recent_count`. |+| `keep_recent_count` | int | 2 | 500 | Number of recent live messages to keep (not archived) on a threshold-triggered auto commit. Idle-timeout commits ignore this and commit everything. |+| `min_commit_interval_seconds` | int | 0 | 604800 | Minimum seconds between two automatic commits (throttle). |++Code entry: `openviking/session/auto_commit_policy.py:AutoCommitPolicy`.+##### S3 Backend Configuration@@ -1439,6 +1492,7 @@ For memory-related settings, add a `memory` section in `ov.conf`:| `extraction_enabled` | Whether session commit runs long-term memory extraction. | `true` || `session_skill_extraction_enabled` | Whether session commit also extracts reusable skills into the current user's skill directory. | `false` || `link_enabled` | Whether memory extraction writes and resolves memory links. | `false` |+| `session_auto_commit` | Server-wide automatic session commit controls. This belongs under `memory`, not under `server`; see [Session Auto Commit Configuration](#session-auto-commit-configuration). | See section above |### ovcli.confdiff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex 2c4c94572..4cd34877d 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -31,6 +31,7 @@ Session API 按认证用户作用域访问会话,并返回 canonical user sess**代码入口**:- `openviking/session/session.py:Session.__init__()` - Session 核心类+- `openviking/session/auto_commit_policy.py:AutoCommitPolicy` - 自动 commit 策略的默认值与校验- `openviking/server/routers/sessions.py:create_session()` - HTTP 路由- `openviking_cli/client/base.py:BaseClient.create_session()` - Python SDK- `crates/ov_cli/src/commands/session.rs:new_session()` - CLI 命令@@ -43,6 +44,19 @@ Session API 按认证用户作用域访问会话,并返回 canonical user sess|------|------|------|--------|------|| session_id | str | 否 | None | 会话 ID。如果为 None,则创建一个自动生成 ID 的新会话 || memory_policy | object | 否 | None | 会话默认的记忆抽取策略。可选的 `self` 和 `peer` 开关控制写入目标;可选的 `working_memory.enabled=false` 跳过 archive summary;可选的顶层 `memory_types` 将抽取限制为指定的 enabled memory schema。所有 `enabled` 值都应使用 JSON 布尔值。旧版 boolean-like 值暂时仍兼容(字符串 `"false"` 会正确解析为 false),但会产生弃用警告。未传或为 `null` 时允许所有 enabled memory schema。非法结构或未知 memory type 会以 `InvalidArgumentError` 拒绝。 |+| auto_commit_policy | object | 否 | None | 可选的自动 commit 策略(见下表)。传入的字段会被校验并 clamp 到取值范围,然后合并到默认值之上;最终生效的策略会在响应的 `result.auto_commit_policy` 中返回,并持久化到 session meta。未传 policy 时 auto commit 关闭,除非 `memory.session_auto_commit.default_enabled=true`。该策略创建后不可变。 |++`auto_commit_policy` 字段(均为可选;存在 policy 时,未传字段回退到默认值):++| 字段 | 类型 | 默认值 | 上限 | 说明 |+|------|------|--------|------|------|+| `pending_token_threshold` | int | 10000 | 50000 | 当未提交的 pending token 超过该值(严格大于)时,会在消息写入后触发一次自动 commit。 |+| `message_count_threshold` | int | 50 | 500 | 当未提交的 live message 数量超过该值(严格大于)时,会在消息写入后触发一次自动 commit。 |+| `idle_timeout_seconds` | int | 86400 | 604800 | 有未提交内容的 session 在空闲这么多秒后,进入服务端 idle scheduler 的处理范围。idle 触发的 commit 会归档全部积压消息,并忽略 `keep_recent_count`。 |+| `keep_recent_count` | int | 2 | 500 | 阈值触发的自动 commit 后保留(不归档)的最近 live message 数量。idle 超时触发的 commit 会忽略该值并归档所有消息。 |+| `min_commit_interval_seconds` | int | 0 | 604800 | 两次自动 commit 之间的最小间隔秒数(节流)。 |++所有字段最小值为 `0`,会被 clamp 到 `[0, 上限]`。未知字段会以 `InvalidArgumentError` 拒绝。#### 3. 使用示例@@ -63,6 +77,20 @@ curl -X POST http://localhost:1933/api/v1/sessions \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{"session_id": "my-custom-session-id"}'++# 创建带自定义自动 commit 策略的新会话+curl -X POST http://localhost:1933/api/v1/sessions \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{+ "auto_commit_policy": {+ "pending_token_threshold": 8000,+ "message_count_threshold": 40,+ "idle_timeout_seconds": 600,+ "keep_recent_count": 10,+ "min_commit_interval_seconds": 0+ }+ }'```**Python SDK**@@ -80,6 +108,18 @@ print(f"Session ID: {result['session_id']}")# 创建指定 ID 的新会话result = await client.create_session(session_id="my-custom-session-id")print(f"Session ID: {result['session_id']}")++# 创建带自定义自动 commit 策略的新会话+result = await client.create_session(+ auto_commit_policy={+ "pending_token_threshold": 8000,+ "message_count_threshold": 40,+ "idle_timeout_seconds": 600,+ "keep_recent_count": 10,+ "min_commit_interval_seconds": 0,+ }+)+print(result["auto_commit_policy"])```**TypeScript SDK**@@ -118,7 +158,8 @@ ov session new"user": {"account_id": "default","user_id": "alice"- }+ },+ "auto_commit_policy": null},"time": 0.1}@@ -227,6 +268,7 @@ ov session list- `commit_count`: 成功提交的次数- `memories_extracted`: 各类记忆的提取数量统计- `last_commit_at`: 最后一次提交的时间+- `auto_commit_policy`: 填充默认值后的生效自动 commit 策略;未启用时为 `null`**代码入口**:- `openviking/session/session.py:Session.load()` - 会话加载@@ -343,13 +385,28 @@ ov session get a1b2c3d4"account_id": "default","user_id": "alice"},- "pending_tokens": 450+ "pending_tokens": 450,+ "auto_commit_policy": {+ "pending_token_threshold": 10000,+ "message_count_threshold": 50,+ "idle_timeout_seconds": 86400,+ "keep_recent_count": 2,+ "min_commit_interval_seconds": 0+ }}}```---+### 更新 Session 配置++自动 commit 策略创建后不可变。请在创建 session 时设置+`auto_commit_policy`,之后通过 `GET /api/v1/sessions/{session_id}` 查看生效配置。+Sessions API 不提供运行期 session 配置更新接口。++---+### list_tool_results()列出会话中因体积较大而外置保存的工具结果。diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.mdindex b6785dc5a..be71b720f 100644--- a/docs/zh/guides/01-configuration.md+++ b/docs/zh/guides/01-configuration.md@@ -1148,6 +1148,59 @@ RAGFS 默认使用 Rust binding 模式,通过 Rust 实现直接访问文件系}```+##### Session Auto Commit 配置++`memory.session_auto_commit` 用于控制服务端 session 自动 commit 的全局行为。++```json+{+ "memory": {+ "session_auto_commit": {+ "default_enabled": false,+ "idle_enabled": false,+ "check_interval_seconds": 60.0,+ "scan_batch_size": 16,+ "scan_batch_pause_seconds": 0.0+ }+ }+}+```++| 参数 | 类型 | 说明 | 默认值 |+|------|------|------|--------|+| `default_enabled` | bool | 对未显式传入 `auto_commit_policy` 的新 session,是否默认开启 auto commit。为 `false` 时,这类 session 保持关闭 | `false` |+| `idle_enabled` | bool | 是否启用服务端 idle timeout 自动 commit 调度器。关闭后,不会启动 idle scheduler;但 token / message-count 的即时触发仍然生效 | `false` |+| `check_interval_seconds` | float | idle scheduler 的检查周期,单位秒,必须大于 `0` | `60.0` |+| `scan_batch_size` | int | 每个 idle 扫描批次最多并发读取的 session meta 文件数量,必须大于 `0` | `16` |+| `scan_batch_pause_seconds` | float | idle 扫描批次之间的可选暂停时间,单位秒,用于降低大量 session 扫描时的存储压力 | `0.0` |++说明:++- `memory.session_auto_commit` 是服务端全局配置,不是单个 session 的业务 policy。+- session 级别的自动触发参数通过 session 级 `auto_commit_policy` 设置(见下表)。它只能在创建 session 时通过 `POST /api/v1/sessions` 的顶层 `auto_commit_policy` 字段设置,之后通过 `GET /api/v1/sessions/{session_id}` 查看;不支持运行期 PATCH 修改。+- `default_enabled=false` 时,未传 `auto_commit_policy` 创建的 session 保持 auto commit 关闭,返回 `auto_commit_policy: null`。显式传 `{}` 或任意 policy 字段会为该 session 开启 auto commit,并用下方默认值补齐缺失字段。+- `default_enabled=true` 时,未传 `auto_commit_policy` 创建的 session 会带上下方默认 policy。+- `idle_enabled=false` 时:+ - 不会启动 `SessionAutoCommitScheduler`+- `idle_enabled=true` 时:+ - `SessionAutoCommitScheduler` 会按固定周期扫描 AGFS `/local/{account}/user/{user}/sessions` 下的 session `.meta.json`+ - 不会做单独的启动恢复扫描,idle 检查只发生在周期扫描时+- token 和 message-count 自动触发在消息写入后内联执行,不依赖 scheduler,也不受这个开关影响。++###### 单 session 自动 commit 策略++当 session 带有 `auto_commit_policy` 时,未传的字段会回退到下方推荐默认值。没有存储 policy 的 session 保持 auto commit 关闭。取值会被 clamp 到 `[0, 上限]`,未知字段会以 `InvalidArgumentError` 拒绝。设置和查看方式见 [Sessions API](../api/05-sessions.md#create_session)。++| 字段 | 类型 | 默认值 | 上限 | 说明 |+|------|------|--------|------|------|+| `pending_token_threshold` | int | 10000 | 50000 | 当未提交的 pending token 超过该值(严格大于)时,会在消息写入后触发一次自动 commit。 |+| `message_count_threshold` | int | 50 | 500 | 当未提交的 live message 数量超过该值(严格大于)时,会在消息写入后触发一次自动 commit。 |+| `idle_timeout_seconds` | int | 86400 | 604800 | 有未提交内容的 session 在空闲这么多秒后,进入服务端 idle scheduler 的处理范围。idle 触发的 commit 会归档全部积压消息,并忽略 `keep_recent_count`。 |+| `keep_recent_count` | int | 2 | 500 | 阈值触发的自动 commit 后保留(不归档)的最近 live message 数量。idle 超时触发的 commit 会忽略该值并归档所有消息。 |+| `min_commit_interval_seconds` | int | 0 | 604800 | 两次自动 commit 之间的最小间隔秒数(节流)。 |++代码入口:`openviking/session/auto_commit_policy.py:AutoCommitPolicy`。+##### S3 后端配置@@ -1405,6 +1458,7 @@ openviking-server --config /path/to/ov.conf| `extraction_enabled` | session commit 时是否执行长期记忆抽取。 | `true` || `session_skill_extraction_enabled` | session commit 时是否同时抽取可复用 skill 到当前用户的 skill 目录。 | `false` || `link_enabled` | 记忆抽取是否写入和解析 memory links。 | `false` |+| `session_auto_commit` | 服务端 session 自动 commit 的全局控制项。该配置属于 `memory` 段,不属于 `server` 段;详见 [Session Auto Commit 配置](#session-auto-commit-配置)。 | 见上文 |### ovcli.confdiff --git a/openviking/async_client.py b/openviking/async_client.pyindex 7b09a6a6f..ecd40d925 100644--- a/openviking/async_client.py+++ b/openviking/async_client.py@@ -140,18 +140,22 @@ class AsyncOpenViking:session_id: Optional[str] = None,telemetry: TelemetryRequest = False,memory_policy: Optional[Dict[str, Any]] = None,+ auto_commit_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.Args:session_id: Optional session ID. If provided, creates a session with the given ID.If None, creates a new session with auto-generated ID.+ memory_policy: Optional default extraction policy for future commits.+ auto_commit_policy: Optional automatic-commit policy overrides."""await self._ensure_initialized()return await self._client.create_session(session_id,telemetry=telemetry,memory_policy=memory_policy,+ auto_commit_policy=auto_commit_policy,)async def list_sessions(self) -> List[Any]:diff --git a/openviking/client/local.py b/openviking/client/local.pyindex 8a50c8ff6..8729c96a1 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -842,17 +842,20 @@ class LocalClient(BaseClient):session_id: Optional[str] = None,telemetry: TelemetryRequest = False,memory_policy: Optional[Dict[str, Any]] = None,+ auto_commit_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.Args:session_id: Optional session ID. If provided, creates a session with the given ID.If None, creates a new session with auto-generated ID.+ memory_policy: Optional default extraction policy for future commits.+ auto_commit_policy: Optional automatic-commit policy overrides."""execution = await run_with_telemetry(operation="session.create",telemetry=telemetry,- fn=lambda: self._create_session_impl(session_id, memory_policy),+ fn=lambda: self._create_session_impl(session_id, memory_policy, auto_commit_policy),)return attach_telemetry_payload(execution.result,@@ -863,17 +866,20 @@ class LocalClient(BaseClient):self,session_id: Optional[str],memory_policy: Optional[Dict[str, Any]],+ auto_commit_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:await self._service.initialize_user_directories(self._ctx)session = await self._service.sessions.create(self._ctx,session_id,memory_policy=memory_policy,+ auto_commit_policy=auto_commit_policy,)return {"session_id": session.session_id,"uri": session.uri,"user": session.user.to_dict(),+ "auto_commit_policy": self._service.sessions.effective_auto_commit_policy(session),}async def list_sessions(self) -> List[Any]:@@ -886,6 +892,7 @@ class LocalClient(BaseClient):result = session.meta.to_dict()result["uri"] = session.uriresult["user"] = session.user.to_dict()+ result["auto_commit_policy"] = self._service.sessions.effective_auto_commit_policy(session)return resultasync def get_session_context(@@ -1063,6 +1070,12 @@ class LocalClient(BaseClient):await add_async(role, message_parts, **add_kwargs)else:session.add_message(role, message_parts, **add_kwargs)+ await self._service.sessions.maybe_schedule_auto_commit(+ session_id,+ self._ctx,+ reason_hint="message_write",+ session=session,+ )return {"session_id": session_id,"message_count": len(session.messages),@@ -1128,6 +1141,12 @@ class LocalClient(BaseClient):added = await add_many_async(specs)else:added = session.add_messages(specs)+ await self._service.sessions.maybe_schedule_auto_commit(+ session_id,+ self._ctx,+ reason_hint="message_write",+ session=session,+ )return {"session_id": session_id,"message_count": len(session.messages),diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.pyindex aeacaedc4..a0bee9774 100644--- a/openviking/server/routers/sessions.py+++ b/openviking/server/routers/sessions.py@@ -73,6 +73,23 @@ class ToolPartRequest(BaseModel):PartRequest = TextPartRequest | ContextPartRequest | ToolPartRequest+class AutoCommitPolicyRequest(BaseModel):+ """Session-level auto-commit policy overrides.++ All fields are optional. Bounds are not enforced here: ``AutoCommitPolicy``+ clamps every value into ``[0, max]`` so clamping lives in one place across+ the HTTP, SDK, and CLI entrypoints.+ """++ pending_token_threshold: Optional[int] = None+ message_count_threshold: Optional[int] = None+ idle_timeout_seconds: Optional[int] = None+ keep_recent_count: Optional[int] = None+ min_commit_interval_seconds: Optional[int] = None++ model_config = {"extra": "forbid"}++class AddMessageRequest(BaseModel):"""Request model for adding a message.@@ -126,6 +143,7 @@ class CreateSessionRequest(BaseModel):session_id: Optional[str] = Nonememory_policy: Optional[Dict[str, Any]] = None+ auto_commit_policy: Optional[AutoCommitPolicyRequest] = Nonetelemetry: TelemetryRequest = False@@ -200,17 +218,23 @@ async def create_session("""service = get_service()+ auto_commit_policy_payload: Optional[Dict[str, Any]] = None+ if request.auto_commit_policy is not None:+ auto_commit_policy_payload = request.auto_commit_policy.model_dump(exclude_none=True)+async def _create() -> dict[str, Any]:await service.initialize_user_directories(_ctx)session = await service.sessions.create(_ctx,request.session_id,memory_policy=request.memory_policy,+ auto_commit_policy=auto_commit_policy_payload,)return {"session_id": session.session_id,"uri": session.uri,"user": session.user.to_dict(),+ "auto_commit_policy": service.sessions.effective_auto_commit_policy(session),}execution = await run_operation(@@ -249,6 +273,7 @@ async def get_session(result["uri"] = session.uriresult["user"] = session.user.to_dict()result["pending_tokens"] = int(session.meta.pending_tokens or 0)+ result["auto_commit_policy"] = service.sessions.effective_auto_commit_policy(session)return Response(status="ok", result=result)@@ -519,6 +544,12 @@ async def add_message(await add_many_async(specs)else:session.add_messages(specs)+ await service.sessions.maybe_schedule_auto_commit(+ session_id,+ _ctx,+ reason_hint="message_write",+ session=session,+ )return {"session_id": session_id,"message_count": len(session.messages),@@ -569,6 +600,12 @@ async def batch_add_messages(msgs = await add_many_async(specs)else:msgs = session.add_messages(specs)+ await service.sessions.maybe_schedule_auto_commit(+ session_id,+ _ctx,+ reason_hint="message_write",+ session=session,+ )return {"session_id": session_id,"message_count": len(session.messages),diff --git a/openviking/service/core.py b/openviking/service/core.pyindex dc1ab27a8..88b6800a5 100644--- a/openviking/service/core.py+++ b/openviking/service/core.py@@ -24,6 +24,7 @@ from openviking.service.resource_memory_link_service import ResourceMemoryLinkSefrom openviking.service.resource_service import ResourceServicefrom openviking.service.search_service import SearchServicefrom openviking.service.session_service import SessionService+from openviking.service.session_auto_commit import SessionAutoCommitSchedulerfrom openviking.service.task_tracker import get_task_tracker, set_task_trackerfrom openviking.session import create_session_compressorfrom openviking.storage.collection_schemas import init_context_collection@@ -44,6 +45,7 @@ from openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils import get_loggerfrom openviking_cli.utils.config import OPENVIKING_ENABLE_RECORDER_ENV, get_openviking_configfrom openviking_cli.utils.config.git_config import GitConfig+from openviking_cli.utils.config.memory_config import SessionAutoCommitConfigfrom openviking_cli.utils.config.open_viking_config import initialize_openviking_configfrom openviking_cli.utils.config.storage_config import StorageConfig@@ -91,6 +93,7 @@ class OpenVikingService:self._directory_initializer: Optional[DirectoryInitializer] = Noneself._watch_scheduler: Optional[WatchScheduler] = None+ self._session_auto_commit_scheduler: Optional[SessionAutoCommitScheduler] = Noneself._encryptor: Optional[Any] = Noneself._privacy_config_service: Optional[UserPrivacyConfigService] = Noneself._data_dir_lock_acquired = False@@ -411,6 +414,20 @@ class OpenVikingService:viking_fs=self._viking_fs,session_service=self._session_service,)+ try:+ session_auto_commit_config = get_openviking_config().memory.session_auto_commit+ except Exception:+ session_auto_commit_config = SessionAutoCommitConfig()+ self._session_service.set_session_auto_commit_config(session_auto_commit_config)+ if session_auto_commit_config.idle_enabled:+ self._session_auto_commit_scheduler = SessionAutoCommitScheduler(+ self._session_service,+ session_auto_commit_config,+ check_interval=session_auto_commit_config.check_interval_seconds,+ )+ await self._session_auto_commit_scheduler.start()+ else:+ self._session_auto_commit_scheduler = Noneself._debug_service.set_dependencies(vikingdb=self._vikingdb_manager,config=self._config,@@ -476,6 +493,11 @@ class OpenVikingService:self._watch_scheduler = Nonelogger.info("WatchScheduler stopped")+ if self._session_auto_commit_scheduler:+ await self._session_auto_commit_scheduler.stop()+ self._session_auto_commit_scheduler = None+ logger.info("SessionAutoCommitScheduler stopped")+if self._queue_manager:await asyncio.to_thread(self._queue_manager.stop)self._queue_manager = Nonediff --git a/openviking/service/session_auto_commit.py b/openviking/service/session_auto_commit.pynew file mode 100644index 000000000..922f145a4--- /dev/null+++ b/openviking/service/session_auto_commit.py@@ -0,0 +1,393 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Runtime helpers for server-side automatic session commits."""++from __future__ import annotations++import asyncio+import json+from collections.abc import AsyncIterator+from datetime import datetime, timedelta, timezone+from typing import Any, Dict, Optional++from openviking.pyagfs import AsyncAGFSClient+from openviking.server.error_mapping import is_not_found_error+from openviking.server.identity import RequestContext, Role+from openviking.session.auto_commit_policy import AutoCommitPolicy+from openviking.utils.time_utils import parse_iso_datetime+from openviking_cli.session.user_id import UserIdentifier+from openviking_cli.utils import get_logger++logger = get_logger(__name__)++SESSION_META_SUFFIX = "/.meta.json"+AGFS_SESSION_SCAN_ROOT = "/local"+++class SessionAutoCommitScheduler:+ """Scheduler for idle-based automatic session commits."""++ DEFAULT_CHECK_INTERVAL = 60.0++ def __init__(+ self,+ session_service: Any,+ config: Any,+ *,+ check_interval: Optional[float] = None,+ sleep: Any = asyncio.sleep,+ ):+ self._session_service = session_service+ self._config = config+ self._check_interval = (+ self.DEFAULT_CHECK_INTERVAL if check_interval is None else float(check_interval)+ )+ self._scan_batch_size = max(1, int(getattr(config, "scan_batch_size", 16) or 16))+ self._scan_batch_pause_seconds = max(+ 0.0,+ float(getattr(config, "scan_batch_pause_seconds", 0.0) or 0.0),+ )+ self._sleep = sleep+ self._running = False+ self._task: Optional[asyncio.Task] = None+ self._agfs_client: Optional[AsyncAGFSClient] = None++ async def start(self) -> None:+ if self._running:+ return+ self._running = True+ logger.info(+ "SessionAutoCommitScheduler started with check interval %.3fs", self._check_interval+ )+ self._task = asyncio.create_task(self._run_loop())++ async def stop(self) -> None:+ self._running = False+ if self._task is not None:+ self._task.cancel()+ try:+ await self._task+ except asyncio.CancelledError:+ pass+ self._task = None++ async def _run_loop(self) -> None:+ while self._running:+ try:+ await self._sleep(self._check_interval)+ except asyncio.CancelledError:+ break++ try:+ if self._config.idle_enabled:+ await self._scan_once()+ except Exception as exc:+ logger.error("Session auto-commit scheduler loop failed: %s", exc, exc_info=True)++ async def _scan_once(self) -> None:+ now = datetime.now(timezone.utc)+ scanned = 0+ due = 0+ scheduled = 0+ agfs = self._get_agfs_client()+ async for batch in self._iter_session_meta_path_batches(agfs):+ batch_scanned, batch_due, batch_scheduled = await self._process_meta_batch(+ agfs, batch, now+ )+ scanned += batch_scanned+ due += batch_due+ scheduled += batch_scheduled++ if due > 0:+ logger.info(+ "SessionAutoCommitScheduler scanned=%d due=%d scheduled=%d",+ scanned,+ due,+ scheduled,+ )++ def _get_agfs_client(self) -> AsyncAGFSClient:+ if self._agfs_client is None:+ self._agfs_client = AsyncAGFSClient(self._session_service.viking_fs.agfs)+ return self._agfs_client++ async def _process_meta_batch(+ self,+ agfs: AsyncAGFSClient,+ batch: list[str],+ now: datetime,+ ) -> tuple[int, int, int]:+ results = await asyncio.gather(+ *(self._read_idle_candidate(agfs, meta_path, now) for meta_path in batch)+ )+ due = 0+ scheduled = 0+ for item in results:+ if item is None:+ continue+ session_id, account_id, user_id = item+ due += 1+ ctx = RequestContext(+ user=UserIdentifier(account_id=account_id, user_id=user_id),+ role=Role.USER,+ )+ did_schedule = await self._session_service.maybe_schedule_auto_commit(+ session_id,+ ctx,+ reason_hint="idle_timeout",+ )+ if did_schedule:+ scheduled += 1+ return len(batch), due, scheduled++ async def _read_idle_candidate(+ self,+ agfs: AsyncAGFSClient,+ meta_path: str,+ now: datetime,+ ) -> Optional[tuple[str, str, str]]:+ try:+ content = await agfs.read(meta_path)+ raw = content.decode("utf-8") if isinstance(content, bytes) else str(content)+ meta = json.loads(raw)+ if not isinstance(meta, dict):+ logger.warning(+ "Invalid session meta object for idle auto-commit: %s (%s)",+ meta_path,+ type(meta).__name__,+ )+ return None+ except json.JSONDecodeError as exc:+ logger.warning(+ "Invalid session meta JSON for idle auto-commit: %s (%s)",+ meta_path,+ exc,+ )+ return None+ except Exception as exc:+ if is_not_found_error(exc):+ logger.debug(+ "Session meta disappeared during idle auto-commit scan: %s",+ meta_path,+ )+ return None+ logger.warning(+ "Failed to read session meta for idle auto-commit: %s",+ meta_path,+ exc_info=True,+ )+ return None++ try:+ if not _is_idle_candidate(meta, now):+ return None+ except (TypeError, ValueError) as exc:+ logger.warning(+ "Invalid session meta fields for idle auto-commit: %s (%s)",+ meta_path,+ exc,+ )+ return None++ session_id = _session_id_from_meta_path(meta_path)+ account_id = _account_id_from_meta_path(meta_path)+ user_id = _user_id_from_meta_path(meta_path)+ if not session_id or not account_id or not user_id:+ return None+ return session_id, account_id, user_id++ async def _iter_session_meta_path_batches(+ self, agfs: AsyncAGFSClient+ ) -> AsyncIterator[list[str]]:+ try:+ account_entries = await agfs.ls(AGFS_SESSION_SCAN_ROOT)+ except Exception:+ logger.warning("Failed to scan AGFS tree for idle auto-commit", exc_info=True)+ return++ batch: list[str] = []+ seen: set[str] = set()+ for account_entry in account_entries:+ account_id = str(account_entry.get("name") or "").strip()+ if not account_id or account_id == "_system":+ continue+ if not account_entry.get("isDir", False):+ continue++ try:+ user_entries = await agfs.ls(f"/local/{account_id}/user")+ except Exception as exc:+ if is_not_found_error(exc):+ logger.debug(+ "Account user directory missing during idle auto-commit scan: %s",+ account_id,+ )+ else:+ logger.warning(+ "Failed to scan users for idle auto-commit: /local/%s/user",+ account_id,+ exc_info=True,+ )+ continue++ for user_entry in user_entries:+ user_id = str(user_entry.get("name") or "").strip()+ if not user_id or not user_entry.get("isDir", False):+ continue+ sessions_root = f"/local/{account_id}/user/{user_id}/sessions"+ try:+ session_entries = await agfs.ls(sessions_root)+ except Exception as exc:+ if is_not_found_error(exc):+ logger.debug(+ "User sessions directory missing during idle auto-commit scan: %s",+ sessions_root,+ )+ else:+ logger.warning(+ "Failed to scan sessions for idle auto-commit: %s",+ sessions_root,+ exc_info=True,+ )+ continue++ for session_entry in session_entries:+ session_id = str(session_entry.get("name") or "").strip()+ if not session_id or not session_entry.get("isDir", False):+ continue+ meta_path = f"{sessions_root}/{session_id}{SESSION_META_SUFFIX}"+ if meta_path not in seen:+ seen.add(meta_path)+ batch.append(meta_path)+ if len(batch) >= self._scan_batch_size:+ yield batch+ batch = []+ if self._scan_batch_pause_seconds > 0:+ await self._sleep(self._scan_batch_pause_seconds)+ if batch:+ yield batch+++def resolve_policy(policy: Optional[Dict[str, Any]]) -> AutoCommitPolicy:+ """Resolve a stored policy dict into an effective policy (defaults filled)."""+ return AutoCommitPolicy.from_dict(policy if isinstance(policy, dict) else None)+++def get_idle_timeout_seconds(policy: Optional[Dict[str, Any]]) -> Optional[int]:+ if policy is None:+ return None+ seconds = resolve_policy(policy).idle_timeout_seconds+ return seconds if seconds > 0 else None+++def get_token_threshold(policy: Optional[Dict[str, Any]]) -> Optional[int]:+ if policy is None:+ return None+ threshold = resolve_policy(policy).pending_token_threshold+ return threshold if threshold > 0 else None+++def get_message_count_threshold(policy: Optional[Dict[str, Any]]) -> Optional[int]:+ if policy is None:+ return None+ threshold = resolve_policy(policy).message_count_threshold+ return threshold if threshold > 0 else None+++def get_min_commit_interval_seconds(policy: Optional[Dict[str, Any]]) -> int:+ if policy is None:+ return 0+ return max(0, resolve_policy(policy).min_commit_interval_seconds)+++def get_keep_recent_count(policy: Optional[Dict[str, Any]]) -> int:+ if policy is None:+ return 0+ return max(0, resolve_policy(policy).keep_recent_count)+++def compute_next_check_at(last_message_at: str, idle_timeout_seconds: int) -> Optional[str]:+ if not last_message_at:+ return None+ try:+ base = parse_iso_datetime(last_message_at)+ except Exception:+ return None+ return (base + timedelta(seconds=idle_timeout_seconds)).isoformat()+++def is_next_check_due(next_check_at: str, now: datetime) -> Optional[bool]:+ try:+ next_dt = parse_iso_datetime(next_check_at)+ except Exception:+ return None++ compare_now = now+ if next_dt.tzinfo is not None:+ if compare_now.tzinfo is None:+ compare_now = datetime.fromtimestamp(compare_now.timestamp(), tz=next_dt.tzinfo)+ else:+ compare_now = compare_now.astimezone(next_dt.tzinfo)+ elif compare_now.tzinfo is not None:+ compare_now = compare_now.replace(tzinfo=None)++ return next_dt <= compare_now+++def has_uncommitted_content(meta: Dict[str, Any]) -> bool:+ keep_recent_count = _coerce_non_negative_int(meta.get("keep_recent_count", 0))+ return bool(+ _coerce_non_negative_int(meta.get("pending_tokens", 0)) > 0+ or _coerce_non_negative_int(meta.get("message_count", 0)) > keep_recent_count+ )+++def has_idle_uncommitted_content(meta: Dict[str, Any]) -> bool:+ return bool(+ _coerce_non_negative_int(meta.get("pending_tokens", 0)) > 0+ or _coerce_non_negative_int(meta.get("message_count", 0)) > 0+ )+++def _is_idle_policy_due(meta: Dict[str, Any], now: datetime) -> bool:+ idle_timeout = get_idle_timeout_seconds(meta.get("auto_commit_policy"))+ if idle_timeout is None:+ return False+ if not has_idle_uncommitted_content(meta):+ return False+ next_check_at = compute_next_check_at(meta.get("last_message_at", ""), idle_timeout)+ if not next_check_at:+ return False+ return is_next_check_due(next_check_at, now) is True+++def _coerce_non_negative_int(value: Any) -> int:+ parsed = int(value or 0)+ return max(0, parsed)+++def _is_idle_candidate(meta: Dict[str, Any], now: datetime) -> bool:+ return _is_idle_policy_due(meta, now)+++def _session_id_from_meta_path(meta_path: str) -> str:+ if not meta_path.endswith(SESSION_META_SUFFIX):+ return ""+ parts = [part for part in meta_path.split("/") if part]+ if len(parts) >= 6 and parts[0] == "local" and parts[2] == "user" and parts[4] == "sessions":+ return parts[5]+ return ""+++def _account_id_from_meta_path(meta_path: str) -> str:+ parts = [part for part in meta_path.split("/") if part]+ if len(parts) >= 2 and parts[0] == "local":+ return parts[1]+ return ""+++def _user_id_from_meta_path(meta_path: str) -> str:+ parts = [part for part in meta_path.split("/") if part]+ if len(parts) >= 6 and parts[0] == "local" and parts[2] == "user" and parts[4] == "sessions":+ return parts[3]+ return ""diff --git a/openviking/service/session_service.py b/openviking/service/session_service.pyindex 3d2bd9394..c1ad3d464 100644--- a/openviking/service/session_service.py+++ b/openviking/service/session_service.py@@ -7,24 +7,41 @@ Provides session management operations: session, sessions, add_message, commit,"""from dataclasses import replace+from datetime import datetimefrom typing import TYPE_CHECKING, Any, Dict, List, Optional+import asyncio+from openviking.core.namespace import canonical_session_urifrom openviking.server.agent_evolution_config import AgentEvolutionConfigProviderfrom openviking.server.config import AgentEvolutionConfig, ToolOutputExternalizationConfigfrom openviking.server.identity import RequestContext+from openviking.service.session_auto_commit import (+ compute_next_check_at,+ get_idle_timeout_seconds,+ get_keep_recent_count,+ get_message_count_threshold,+ get_min_commit_interval_seconds,+ get_token_threshold,+ has_idle_uncommitted_content,+ has_uncommitted_content,+ is_next_check_due,+)from openviking.service.task_tracker import get_task_trackerfrom openviking.session import Session+from openviking.session.auto_commit_policy import AutoCommitPolicyfrom openviking.session.memory.memory_type_registry import MemoryTypeRegistryfrom openviking.session.memory_policy import MemoryPolicyfrom openviking.storage.viking_fs import VikingFSfrom openviking.storage.vikingdb_manager import VikingDBManager+from openviking.utils.time_utils import parse_iso_datetimefrom openviking_cli.exceptions import (AlreadyExistsError,NotFoundError,NotInitializedError,)from openviking_cli.utils import get_logger+from openviking_cli.utils.config.memory_config import SessionAutoCommitConfiglogger = get_logger(__name__)@@ -53,6 +70,15 @@ class SessionService:self._agent_evolution_config_provider: Optional[AgentEvolutionConfigProvider] = Noneself._agent_evolution_config_path: Optional[str] = Noneself._usage_reporter: Optional["UsageReporter"] = None+ # Server-wide controls; embedded clients keep the disabled defaults+ # unless set_session_auto_commit_config() pushes a config in.+ self._session_auto_commit_config = SessionAutoCommitConfig()+ # Per-worker in-flight guard so bursts don't spawn duplicate commit+ # tasks. Cross-worker correctness relies on has_running(), not this set.+ self._auto_commit_inflight: set[tuple[str, str, str]] = set()+ self._auto_commit_inflight_lock = asyncio.Lock()+ # Strong refs so spawned tasks aren't GC'd mid-await.+ self._auto_commit_tasks: set[asyncio.Task] = set()def set_dependencies(self,@@ -103,11 +129,21 @@ class SessionService:"""Set the usage reporter for newly created sessions."""self._usage_reporter = usage_reporter+ def set_session_auto_commit_config(self, config: SessionAutoCommitConfig) -> None:+ """Set server-wide controls for automatic session commits."""+ self._session_auto_commit_config = config.model_copy(deep=True)+def _ensure_initialized(self) -> None:"""Ensure all dependencies are initialized."""if not self._viking_fs:raise NotInitializedError("VikingFS")+ @property+ def viking_fs(self) -> VikingFS:+ """Expose VikingFS for the idle auto-commit scheduler's AGFS scan."""+ self._ensure_initialized()+ return self._viking_fs+@staticmethoddef _record_lifecycle_metric(action: str, status: str) -> None:"""Best-effort session lifecycle metrics should never break the main flow."""@@ -175,6 +211,7 @@ class SessionService:ctx: RequestContext,session_id: Optional[str] = None,memory_policy: Optional[Dict[str, Any]] = None,+ auto_commit_policy: Optional[Dict[str, Any]] = None,) -> Session:"""Create a session and persist its root path.@@ -183,6 +220,8 @@ class SessionService:session_id: Optional session ID. If provided, creates a session with the given ID.If None, creates a new session with auto-generated ID.memory_policy: Optional default extraction policy for future commits.+ auto_commit_policy: Optional automatic-commit policy overrides. Missing+ fields fall back to the recommended defaults. Immutable after creation.Raises:AlreadyExistsError: If a session with the given ID already exists@@ -200,6 +239,14 @@ class SessionService:set(MemoryTypeRegistry().list_names(include_disabled=False)))session.meta.memory_policy = policy.to_dict()+ # Auto-commit is enabled when the caller supplies a policy, or when+ # the server default turns it on. Absent both, it stays disabled.+ if auto_commit_policy is not None or self._session_auto_commit_config.default_enabled:+ session.meta.auto_commit_policy = AutoCommitPolicy.from_dict(+ auto_commit_policy+ ).to_dict()+ else:+ session.meta.auto_commit_policy = Noneawait session.ensure_exists()self._record_lifecycle_metric("create", "ok")return session@@ -223,6 +270,8 @@ class SessionService:if not await session.exists():if not auto_create:raise NotFoundError(session_id, "session")+ if self._session_auto_commit_config.default_enabled:+ session.meta.auto_commit_policy = AutoCommitPolicy.from_dict(None).to_dict()await session.ensure_exists()await session.load()self._record_lifecycle_metric("get", "ok")@@ -413,3 +462,161 @@ class SessionService:)self._record_lifecycle_metric("extract", "ok")return memories++ @staticmethod+ def effective_auto_commit_policy(session: Session) -> Optional[Dict[str, Any]]:+ """Return the resolved auto-commit policy (defaults filled), or None when disabled."""+ if session.meta.auto_commit_policy is None:+ return None+ return AutoCommitPolicy.from_dict(session.meta.auto_commit_policy).to_dict()++ async def maybe_schedule_auto_commit(+ self,+ session_id: str,+ ctx: RequestContext,+ *,+ reason_hint: str,+ session: Optional[Session] = None,+ ) -> bool:+ """Best-effort automatic commit scheduler entrypoint.++ Returns True when a commit task was spawned. Misses are acceptable: the+ next message write or the next idle scan re-triggers naturally, so there+ is no recheck/polling machinery here. Scheduling never propagates errors+ to the caller's message write or the idle scan batch.+ """+ claim = (ctx.account_id, ctx.user.user_id, session_id)+ try:+ if session is None:+ 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_hint):+ return False++ async with self._auto_commit_inflight_lock:+ if claim in self._auto_commit_inflight:+ return False+ if await get_task_tracker().has_running(+ "session_commit",+ session_id,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ ):+ return False+ self._auto_commit_inflight.add(claim)+ except Exception:+ logger.debug(+ "Skipped auto-commit scheduling for %s", session_id, exc_info=True+ )+ return False++ task = asyncio.create_task(self.run_auto_commit(session_id, ctx, reason=reason_hint))+ self._auto_commit_tasks.add(task)+ task.add_done_callback(self._auto_commit_tasks.discard)+ return True++ async def run_auto_commit(self, session_id: str, ctx: RequestContext, *, reason: str) -> None:+ """Run one best-effort automatic commit and release the in-flight claim."""+ claim = (ctx.account_id, ctx.user.user_id, session_id)+ try:+ tracker = get_task_tracker()+ if await tracker.has_running(+ "session_commit",+ session_id,+ account_id=ctx.account_id,+ user_id=ctx.user.user_id,+ ):+ return++ # Reload so a stale in-memory session can't drive the decision;+ # commit_async re-reads again under its own path lock.+ 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):+ return++ # Idle timeout commits the whole backlog but must not persist a+ # keep_recent_count of 0, which would wipe the stored preference.+ if reason == "idle_timeout":+ await session.commit_async(+ keep_recent_count=0,+ persist_keep_recent_count=False,+ record_auto_commit_success=True,+ )+ else:+ await session.commit_async(+ keep_recent_count=get_keep_recent_count(policy),+ record_auto_commit_success=True,+ )+ except Exception as exc:+ logger.warning("Automatic session commit failed for %s: %s", session_id, exc)+ finally:+ async with self._auto_commit_inflight_lock:+ self._auto_commit_inflight.discard(claim)++ @staticmethod+ def _has_uncommitted_content(session: Session) -> bool:+ return has_uncommitted_content(session.meta.to_dict())++ def _within_min_commit_interval(self, session: Session, policy: Any) -> bool:+ """Return True when the throttle window has not yet elapsed."""+ interval = get_min_commit_interval_seconds(policy)+ if interval <= 0:+ return False+ last_auto_commit_at = session.meta.last_auto_commit_at+ if not last_auto_commit_at:+ return False+ try:+ last_dt = parse_iso_datetime(last_auto_commit_at)+ except (TypeError, ValueError):+ return False+ now = datetime.now()+ if last_dt.tzinfo is not None:+ if now.tzinfo is None:+ now = datetime.fromtimestamp(now.timestamp(), tz=last_dt.tzinfo)+ else:+ now = now.astimezone(last_dt.tzinfo)+ elif now.tzinfo is not None:+ now = now.replace(tzinfo=None)+ return (now - last_dt).total_seconds() < interval++ def _should_run_auto_commit(self, session: Session, policy: Any, reason: str) -> bool:+ """Validate the current session state still satisfies the trigger reason."""+ if policy is None:+ return False+ if reason == "message_write":+ if not self._has_uncommitted_content(session):+ return False+ if self._within_min_commit_interval(session, policy):+ return False+ return self._message_write_threshold_exceeded(session, policy)++ if reason == "idle_timeout":+ if not self._session_auto_commit_config.idle_enabled:+ return False+ idle_timeout = get_idle_timeout_seconds(policy)+ if idle_timeout is None or not has_idle_uncommitted_content(session.meta.to_dict()):+ return False+ if self._within_min_commit_interval(session, policy):+ return False+ next_check_at = compute_next_check_at(session.meta.last_message_at, idle_timeout)+ if not next_check_at:+ return False+ return is_next_check_due(next_check_at, datetime.now()) is True++ return False++ @staticmethod+ def _message_write_threshold_exceeded(session: Session, policy: Any) -> bool:+ try:+ pending_tokens = int(session.meta.pending_tokens or 0)+ message_count = int(session.meta.message_count or 0)+ except (TypeError, ValueError):+ return False+ token_threshold = get_token_threshold(policy)+ if token_threshold is not None and pending_tokens > token_threshold:+ return True+ message_threshold = get_message_count_threshold(policy)+ if message_threshold is not None and message_count > message_threshold:+ return True+ return Falsediff --git a/openviking/session/auto_commit_policy.py b/openviking/session/auto_commit_policy.pynew file mode 100644index 000000000..ad6c2505a--- /dev/null+++ b/openviking/session/auto_commit_policy.py@@ -0,0 +1,122 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Automatic session-commit policy.++Sessions without a stored policy keep automatic commits disabled. When a policy+object is present, missing fields fall back to the recommended defaults below.+The policy is set once at session creation and inspected via session GET; it is+immutable afterwards, so there is no per-message or patch handling here.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from openviking_cli.exceptions import InvalidArgumentError++# Recommended defaults, aligned with the memory-bank streaming_write behavior.+DEFAULT_PENDING_TOKEN_THRESHOLD = 10000+DEFAULT_MESSAGE_COUNT_THRESHOLD = 50+DEFAULT_IDLE_TIMEOUT_SECONDS = 86400 # 1 day+DEFAULT_KEEP_RECENT_COUNT = 2+DEFAULT_MIN_COMMIT_INTERVAL_SECONDS = 0++# PRD upper bounds.+MAX_PENDING_TOKEN_THRESHOLD = 50000+MAX_MESSAGE_COUNT_THRESHOLD = 500+MAX_IDLE_TIMEOUT_SECONDS = 604800 # 7 days++_POLICY_KEYS = {+ "pending_token_threshold",+ "message_count_threshold",+ "idle_timeout_seconds",+ "keep_recent_count",+ "min_commit_interval_seconds",+}+++def _coerce_int(value: Any, *, field: str, minimum: int, maximum: int) -> int:+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ raise InvalidArgumentError(f"auto_commit_policy.{field} must be an integer")+ if parsed < minimum:+ parsed = minimum+ if parsed > maximum:+ parsed = maximum+ return parsed+++@dataclass+class AutoCommitPolicy:+ """Effective automatic-commit policy for one session."""++ pending_token_threshold: int = DEFAULT_PENDING_TOKEN_THRESHOLD+ message_count_threshold: int = DEFAULT_MESSAGE_COUNT_THRESHOLD+ idle_timeout_seconds: int = DEFAULT_IDLE_TIMEOUT_SECONDS+ keep_recent_count: int = DEFAULT_KEEP_RECENT_COUNT+ min_commit_interval_seconds: int = DEFAULT_MIN_COMMIT_INTERVAL_SECONDS++ @classmethod+ def default(cls) -> "AutoCommitPolicy":+ return cls()++ @classmethod+ def from_dict(cls, data: Any) -> "AutoCommitPolicy":+ """Build a policy from a dict, clamping to PRD bounds and filling defaults."""+ if data is None:+ return cls.default()+ if isinstance(data, AutoCommitPolicy):+ return data+ if not isinstance(data, dict):+ raise InvalidArgumentError("auto_commit_policy must be an object")+ extra_keys = set(data) - _POLICY_KEYS+ if extra_keys:+ raise InvalidArgumentError(+ "auto_commit_policy supports only: " + ", ".join(sorted(_POLICY_KEYS))+ )+ default = cls.default()+ return cls(+ pending_token_threshold=_coerce_int(+ data.get("pending_token_threshold", default.pending_token_threshold),+ field="pending_token_threshold",+ minimum=0,+ maximum=MAX_PENDING_TOKEN_THRESHOLD,+ ),+ message_count_threshold=_coerce_int(+ data.get("message_count_threshold", default.message_count_threshold),+ field="message_count_threshold",+ minimum=0,+ maximum=MAX_MESSAGE_COUNT_THRESHOLD,+ ),+ idle_timeout_seconds=_coerce_int(+ data.get("idle_timeout_seconds", default.idle_timeout_seconds),+ field="idle_timeout_seconds",+ minimum=0,+ maximum=MAX_IDLE_TIMEOUT_SECONDS,+ ),+ keep_recent_count=_coerce_int(+ data.get("keep_recent_count", default.keep_recent_count),+ field="keep_recent_count",+ minimum=0,+ maximum=MAX_MESSAGE_COUNT_THRESHOLD,+ ),+ min_commit_interval_seconds=_coerce_int(+ data.get(+ "min_commit_interval_seconds", default.min_commit_interval_seconds+ ),+ field="min_commit_interval_seconds",+ minimum=0,+ maximum=MAX_IDLE_TIMEOUT_SECONDS,+ ),+ )++ def to_dict(self) -> dict[str, Any]:+ return {+ "pending_token_threshold": self.pending_token_threshold,+ "message_count_threshold": self.message_count_threshold,+ "idle_timeout_seconds": self.idle_timeout_seconds,+ "keep_recent_count": self.keep_recent_count,+ "min_commit_interval_seconds": self.min_commit_interval_seconds,+ }diff --git a/openviking/session/session.py b/openviking/session/session.pyindex bc6e6a77c..72c718b2a 100644--- a/openviking/session/session.py+++ b/openviking/session/session.py@@ -21,6 +21,7 @@ from openviking.message.part import ContextPart, TextPart, ToolPartfrom openviking.pyagfs.exceptions import AGFSClientError, AGFSHTTPError, AGFSNotFoundErrorfrom openviking.server.config import ToolOutputExternalizationConfigfrom openviking.server.identity import RequestContext, Role+from openviking.session.auto_commit_policy import AutoCommitPolicyfrom openviking.session.memory.constants import (AGENT_EVOLUTION_MEMORY_TYPES,EXECUTION_MEMORY_TYPES,@@ -458,6 +459,15 @@ class SessionMeta:retained_message_token_budget: int = 0min_raw_tail_steps: int = 1memory_policy: Optional[Dict[str, Any]] = None+ # Automatic-commit policy, set once at session creation and immutable after.+ # None keeps auto-commit disabled; a dict enables it with the stored bounds.+ auto_commit_policy: Optional[Dict[str, Any]] = None+ # Timestamp of the most recent add_message, used by the idle scan to decide+ # whether an idle-timeout commit is due.+ last_message_at: str = ""+ # Timestamp of the most recent successful auto-commit, surfaced via session+ # GET and used to throttle auto-commit frequency.+ last_auto_commit_at: str = ""def to_dict(self) -> Dict[str, Any]:data = {@@ -479,6 +489,11 @@ class SessionMeta:"retained_message_token_budget": self.retained_message_token_budget,"min_raw_tail_steps": self.min_raw_tail_steps,"memory_policy": dict(self.memory_policy) if self.memory_policy is not None else None,+ "auto_commit_policy": (+ dict(self.auto_commit_policy) if self.auto_commit_policy is not None else None+ ),+ "last_message_at": self.last_message_at,+ "last_auto_commit_at": self.last_auto_commit_at,}if self.total_message_count is not None:data["total_message_count"] = self.total_message_count@@ -528,6 +543,9 @@ class SessionMeta:),min_raw_tail_steps=max(0, int(data.get("min_raw_tail_steps", 1) or 0)),memory_policy=data.get("memory_policy"),+ auto_commit_policy=data.get("auto_commit_policy"),+ last_message_at=data.get("last_message_at", ""),+ last_auto_commit_at=data.get("last_auto_commit_at", ""),)@@ -642,14 +660,26 @@ class Session:if not _is_storage_not_found(exc):raise# Old session without meta — derive from existing data- self._meta.message_count = len(self._messages)self._meta.commit_count = self._compression.compression_indexself._meta.total_message_count = None+ # message_count mirrors the live message list, maintained by every write+ # path. Recompute on load so a stale persisted value can't drift.+ self._meta.message_count = len(self._messages)+if not self._meta.created_by_account_id:self._meta.created_by_account_id = self.ctx.account_idif not self._meta.created_by_user_id:self._meta.created_by_user_id = self.ctx.user.user_id+ # Auto-commit stays disabled when no policy is stored. When present,+ # normalize the stored policy so missing fields are filled and bounds+ # are clamped. The policy's keep_recent_count is a commit-time+ # reservation only and is intentionally NOT mirrored onto+ # meta.keep_recent_count.+ if self._meta.auto_commit_policy is not None:+ self._meta.auto_commit_policy = AutoCommitPolicy.from_dict(+ self._meta.auto_commit_policy+ ).to_dict()# WM v2: always rebuild pending_tokens from current messages so the# counter stays consistent across restarts and is also backfilled for# legacy sessions whose .meta.json predates these fields. O(n) once,@@ -1228,6 +1258,11 @@ class Session:self._meta.message_count = len(self._messages)if self._meta.total_message_count is not None:self._meta.total_message_count += len(messages)+ if messages:+ # Track the newest activity so the idle scan can decide when an+ # idle-timeout auto-commit is due. Written under the same append+ # path lock as the counters above.+ self._meta.last_message_at = get_current_timestamp()def _build_messages(self,@@ -1683,6 +1718,8 @@ class Session:keep_recent_turn_count: Optional[int] = None,retained_message_token_budget: Optional[int] = None,min_raw_tail_steps: Optional[int] = None,+ persist_keep_recent_count: bool = True,+ record_auto_commit_success: bool = False,) -> Dict[str, Any]:"""Archive immediately and enqueue restart-safe Phase 2 processing.@@ -1699,6 +1736,14 @@ class Session:behavior of archiving everything. The plugin's afterTurn pathtypically passes its configured value (default 10); the compactpath passes ``0``.+ persist_keep_recent_count: When ``True`` (default), ``keep_recent_count``+ is remembered in meta for subsequent add_message() accounting.+ The idle full-commit path passes ``False`` with+ ``keep_recent_count=0`` so a one-off full archive does not wipe+ the stored keep preference.+ record_auto_commit_success: When ``True``, clear the auto-commit+ error fields and stamp ``last_auto_commit_at`` in the same+ lock-protected meta update as the commit boundary.Returns a task_id for tracking Phase 2 progress."""@@ -1789,6 +1834,18 @@ class Session:# legacy sessions may not have metadata yet.pass+ # keep_recent_count controls how many live messages survive this+ # commit. stored_keep_recent_count is what we persist for future+ # add_message accounting: the idle full-commit path archives+ # everything once (keep_recent_count=0) without discarding the+ # caller's stored keep preference. Read it from the freshly reloaded+ # meta so a concurrent manual commit's value is not reverted.+ stored_keep_recent_count = (+ keep_recent_count+ if persist_keep_recent_count+ else max(0, int(self._meta.keep_recent_count or 0))+ )+# A Session object may have been loaded by another worker before a# different worker updated the persisted default policy. Phase 2# must use the policy from the same lock-protected snapshot as the@@ -1816,7 +1873,7 @@ class Session:if not self._messages:self._meta.pending_tokens = 0self._remember_retention_policy(- keep_recent_count=keep_recent_count,+ keep_recent_count=stored_keep_recent_count,retention_mode=retention_mode,keep_recent_turn_count=effective_keep_turns if turn_mode else 0,retained_message_token_budget=effective_token_budget if turn_mode else 0,@@ -1866,7 +1923,7 @@ class Session:self._meta.pending_tokens = 0self._meta.message_count = totalself._remember_retention_policy(- keep_recent_count=keep_recent_count,+ keep_recent_count=stored_keep_recent_count,retention_mode=retention_mode,keep_recent_turn_count=effective_keep_turns if turn_mode else 0,retained_message_token_budget=effective_token_budget if turn_mode else 0,@@ -1903,6 +1960,7 @@ class Session:user=self.ctx.user.to_dict(),memory_policy=effective_memory_policy,usage_uris=list(dict.fromkeys(u.uri for u in usage_snapshot if u.uri)),+ record_auto_commit_success=record_auto_commit_success,)phase1_stage = "phase1_persist"try:@@ -1975,7 +2033,7 @@ class Session:self._meta.message_count = len(self._messages)self._meta.pending_tokens = 0self._remember_retention_policy(- keep_recent_count=keep_recent_count,+ keep_recent_count=stored_keep_recent_count,retention_mode=retention_mode,keep_recent_turn_count=effective_keep_turns if turn_mode else 0,retained_message_token_budget=effective_token_budget if turn_mode else 0,@@ -1986,6 +2044,11 @@ class Session:self._compression.compression_index,)self._meta.last_commit_at = get_current_timestamp()+ if record_auto_commit_success:+ # Stamp success in the same lock-protected meta write as the+ # commit boundary, so an idle scan and a concurrent worker+ # never see a stale state.+ self._meta.last_auto_commit_at = get_current_timestamp()await self._save_meta(lease_ref=lease)await self._write_phase1_ready_marker(archive_uri, lease_ref=lease)except Exception as e:@@ -2168,6 +2231,7 @@ class Session:agent_evolution_enabled=agent_evolution_enabled,agent_memory_skip_reason=agent_memory_skip_reason,user_config_error=user_config_error,+ record_auto_commit_success=msg.record_auto_commit_success,)async def _run_usage_reporting(@@ -2205,6 +2269,7 @@ class Session:agent_evolution_enabled: bool = True,agent_memory_skip_reason: Optional[str] = None,user_config_error: Optional[str] = None,+ record_auto_commit_success: bool = False,) -> None:"""Phase 2: Extract memories, write relations, enqueue — runs in background."""from openviking.service.task_tracker import get_task_tracker@@ -2619,6 +2684,7 @@ class Session:archive_index=archive_index,memories_extracted=memories_extracted,telemetry_snapshot=snapshot,+ record_auto_commit_success=record_auto_commit_success,)# Write .done last so a recovered queue item can skip completed work.@@ -3861,6 +3927,8 @@ class Session:archive_index: int,memories_extracted: Dict[str, int],telemetry_snapshot: Any,+ *,+ record_auto_commit_success: bool = False,) -> None:"""Merge Phase 2 results without overwriting concurrent root updates."""session_path = self._viking_fs._uri_to_path(self._session_uri, ctx=self.ctx)@@ -3900,6 +3968,10 @@ class Session:)latest_meta.last_commit_at = get_current_timestamp()latest_meta.message_count = await self._read_live_message_count()+ if record_auto_commit_success:+ # Mirror the Phase 1 success stamp so the persisted meta reflects+ # a clean auto-commit even after Phase 2 reloads the latest meta.+ latest_meta.last_auto_commit_at = get_current_timestamp()self._meta = latest_metaawait self._save_meta(lease_ref=lease)finally:diff --git a/openviking/storage/queuefs/session_commit_msg.py b/openviking/storage/queuefs/session_commit_msg.pyindex 9a0efe31e..a2c8d8317 100644--- a/openviking/storage/queuefs/session_commit_msg.py+++ b/openviking/storage/queuefs/session_commit_msg.py@@ -15,6 +15,9 @@ class SessionCommitMsg:user: Dict[str, str]memory_policy: Dict[str, Any] = field(default_factory=dict)usage_uris: List[str] = field(default_factory=list)+ # When True, Phase 2's final meta merge also clears the auto-commit error+ # fields and stamps last_auto_commit_at. Defaults keep old producers working.+ record_auto_commit_success: bool = Falsedef to_dict(self) -> Dict[str, Any]:return asdict(self)diff --git a/openviking/sync_client.py b/openviking/sync_client.pyindex a2a060443..50b7dcd30 100644--- a/openviking/sync_client.py+++ b/openviking/sync_client.py@@ -56,18 +56,22 @@ class SyncOpenViking:session_id: Optional[str] = None,telemetry: TelemetryRequest = False,memory_policy: Optional[Dict[str, Any]] = None,+ auto_commit_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.Args:session_id: Optional session ID. If provided, creates a session with the given ID.If None, creates a new session with auto-generated ID.+ memory_policy: Optional default extraction policy for future commits.+ auto_commit_policy: Optional automatic-commit policy overrides."""return run_async(self._async_client.create_session(session_id,telemetry=telemetry,memory_policy=memory_policy,+ auto_commit_policy=auto_commit_policy,))diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.pyindex 1f2568f51..68e570d19 100644--- a/openviking_cli/client/base.py+++ b/openviking_cli/client/base.py@@ -337,6 +337,7 @@ class BaseClient(ABC):session_id: Optional[str] = None,telemetry: TelemetryRequest = False,memory_policy: Optional[Dict[str, Any]] = None,+ auto_commit_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:"""Create a new session.@@ -345,6 +346,7 @@ class BaseClient(ABC):If None, creates a new session with auto-generated ID.telemetry: Whether to attach operation telemetry data to the result.memory_policy: Optional default memory extraction policy.+ auto_commit_policy: Optional automatic-commit policy overrides."""...diff --git a/openviking_cli/utils/config/memory_config.py b/openviking_cli/utils/config/memory_config.pyindex c1caca226..82dff294b 100644--- a/openviking_cli/utils/config/memory_config.py+++ b/openviking_cli/utils/config/memory_config.py@@ -9,6 +9,18 @@ from openviking_cli.utils.logger import get_loggerlogger = get_logger(__name__)+class SessionAutoCommitConfig(BaseModel):+ """Server-wide controls for automatic session commits."""++ default_enabled: bool = False+ idle_enabled: bool = False+ check_interval_seconds: float = Field(default=60.0, gt=0)+ scan_batch_size: int = Field(default=16, gt=0)+ scan_batch_pause_seconds: float = Field(default=0.0, ge=0)++ model_config = {"extra": "forbid"}++class MemoryConfig(BaseModel):"""Memory configuration for OpenViking."""@@ -85,6 +97,10 @@ class MemoryConfig(BaseModel):"no page_id or link fields are generated, and link resolution is skipped."),)+ session_auto_commit: SessionAutoCommitConfig = Field(+ default_factory=SessionAutoCommitConfig,+ description="Server-wide controls for automatic session commits.",+ )model_config = {"extra": "forbid"}diff --git a/sdk/go/sessions.go b/sdk/go/sessions.goindex ec4b625d4..ed0b10ddf 100644--- a/sdk/go/sessions.go+++ b/sdk/go/sessions.go@@ -16,6 +16,7 @@ func (c *Client) CreateSession(ctx context.Context, opts *CreateSessionOptions)payload := map[string]any{}setString(payload, "session_id", opts.SessionID)setAny(payload, "memory_policy", opts.MemoryPolicy)+ setAny(payload, "auto_commit_policy", opts.AutoCommitPolicy)setAny(payload, "telemetry", opts.Telemetry)var result map[string]anyerr := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions", nil, payload, &result)diff --git a/sdk/go/types.go b/sdk/go/types.goindex 765ff967d..14677c834 100644--- a/sdk/go/types.go+++ b/sdk/go/types.go@@ -241,9 +241,10 @@ type GlobOptions struct {// CreateSessionOptions controls CreateSession.type CreateSessionOptions struct {- SessionID string- MemoryPolicy map[string]any- Telemetry any+ SessionID string+ MemoryPolicy map[string]any+ AutoCommitPolicy map[string]any+ Telemetry any}// GetSessionOptions controls GetSession.diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex 1d22abfac..6407be5ac 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -1322,12 +1322,15 @@ class AsyncHTTPClient:session_id: Optional[str] = None,telemetry: Any = False,memory_policy: Optional[Dict[str, Any]] = None,+ auto_commit_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:json_body: Dict[str, Any] = {}if session_id is not None:json_body["session_id"] = session_idif memory_policy is not None:json_body["memory_policy"] = memory_policy+ if auto_commit_policy is not None:+ json_body["auto_commit_policy"] = auto_commit_policyif telemetry is not False:json_body["telemetry"] = telemetryresponse = await self._request("POST", "/api/v1/sessions", json=json_body)@@ -2311,12 +2314,14 @@ class SyncHTTPClient:session_id: Optional[str] = None,telemetry: Any = False,memory_policy: Optional[Dict[str, Any]] = None,+ auto_commit_policy: Optional[Dict[str, Any]] = None,) -> Dict[str, Any]:return run_async(self._async_client.create_session(session_id=session_id,telemetry=telemetry,memory_policy=memory_policy,+ auto_commit_policy=auto_commit_policy,))diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsindex 10f43d326..f4de8976b 100644--- a/sdk/typescript/src/client.ts+++ b/sdk/typescript/src/client.ts@@ -552,6 +552,7 @@ export class OpenVikingClient {body: compact({session_id: options.sessionId,memory_policy: options.memoryPolicy,+ auto_commit_policy: options.autoCommitPolicy,telemetry: options.telemetry,}),});diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex ea9ecf8a7..6305c5aad 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -145,6 +145,7 @@ export interface Message {export interface CreateSessionOptions {sessionId?: string;memoryPolicy?: JsonObject;+ autoCommitPolicy?: JsonObject;telemetry?: unknown;}/** Background task filters. */diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.pyindex 29f3c39ce..72fc33443 100644--- a/tests/server/test_api_sessions.py+++ b/tests/server/test_api_sessions.py@@ -22,8 +22,10 @@ from openviking.server.config import (from openviking.server.dependencies import set_servicefrom openviking.server.identity import RequestContext, Rolefrom openviking.server.routers import sessions as sessions_router+from openviking.session.session import Sessionfrom openviking_cli.session.user_id import UserIdentifierfrom openviking_cli.utils.config import OPENVIKING_CONFIG_ENV+from openviking_cli.utils.config.memory_config import SessionAutoCommitConfigfrom openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingletonfrom tests.utils.mock_agfs import MockLocalAGFS@@ -447,6 +449,222 @@ async def test_add_message(client: httpx.AsyncClient):assert body["result"]["message_count"] == 1+async def test_add_message_records_last_message_at(client: httpx.AsyncClient):+ create_resp = await client.post("/api/v1/sessions", json={})+ session_id = create_resp.json()["result"]["session_id"]++ resp = await client.post(+ f"/api/v1/sessions/{session_id}/messages",+ json={"role": "user", "content": "Hello, world!"},+ )+ assert resp.status_code == 200++ session_resp = await client.get(f"/api/v1/sessions/{session_id}")+ assert session_resp.status_code == 200+ assert session_resp.json()["result"]["last_message_at"]+++async def test_direct_session_add_message_records_last_message_at(service):+ session = await service.sessions.get(+ "direct-last-message-at-session",+ RequestContext(user=DEFAULT_USER, role=Role.ROOT),+ auto_create=True,+ )+ assert session.meta.last_message_at == ""++ session.add_message("user", [TextPart("Hello, world!")])++ assert session.meta.last_message_at+++async def test_add_message_records_last_message_at_with_single_meta_save(+ client: httpx.AsyncClient,+ monkeypatch,+):+ create_resp = await client.post("/api/v1/sessions", json={})+ session_id = create_resp.json()["result"]["session_id"]+ save_session_ids = []+ original_save_meta = Session._save_meta++ async def counting_save_meta(self, *args, **kwargs):+ save_session_ids.append(self.session_id)+ await original_save_meta(self, *args, **kwargs)++ monkeypatch.setattr(Session, "_save_meta", counting_save_meta)++ resp = await client.post(+ f"/api/v1/sessions/{session_id}/messages",+ json={"role": "user", "content": "Hello, world!"},+ )+ assert resp.status_code == 200++ assert save_session_ids == [session_id]++ session_resp = await client.get(f"/api/v1/sessions/{session_id}")+ assert session_resp.status_code == 200+ assert session_resp.json()["result"]["last_message_at"]+++async def test_add_message_ignores_extra_metadata_fields(client: httpx.AsyncClient):+ create_resp = await client.post("/api/v1/sessions", json={})+ session_id = create_resp.json()["result"]["session_id"]++ resp = await client.post(+ f"/api/v1/sessions/{session_id}/messages",+ json={+ "role": "user",+ "content": "Hello, world!",+ "metadata": {"source": "test"},+ "auto_commit_policy": {"pending_token_threshold": 123},+ },+ )+ assert resp.status_code == 200+ assert resp.json()["result"]["message_count"] == 1+++async def test_create_session_defaults_auto_commit_policy_to_disabled(+ client: httpx.AsyncClient,+):+ resp = await client.post("/api/v1/sessions", json={})+ assert resp.status_code == 200+ assert resp.json()["result"]["auto_commit_policy"] is None+++async def test_create_session_uses_default_policy_when_server_default_enabled(+ client: httpx.AsyncClient,+ service,+):+ service.sessions.set_session_auto_commit_config(+ SessionAutoCommitConfig(default_enabled=True)+ )++ resp = await client.post("/api/v1/sessions", json={})+ assert resp.status_code == 200+ assert resp.json()["result"]["auto_commit_policy"] == {+ "pending_token_threshold": 10000,+ "message_count_threshold": 50,+ "idle_timeout_seconds": 86400,+ "keep_recent_count": 2,+ "min_commit_interval_seconds": 0,+ }+++async def test_auto_created_session_uses_default_policy_when_server_default_enabled(+ client: httpx.AsyncClient,+ service,+):+ service.sessions.set_session_auto_commit_config(+ SessionAutoCommitConfig(default_enabled=True)+ )+ session_id = "auto-created-default-policy"++ add_resp = await client.post(+ f"/api/v1/sessions/{session_id}/messages",+ json={"role": "user", "content": "create this session by writing first"},+ )+ assert add_resp.status_code == 200++ session_resp = await client.get(f"/api/v1/sessions/{session_id}")+ assert session_resp.status_code == 200+ assert session_resp.json()["result"]["auto_commit_policy"] == {+ "pending_token_threshold": 10000,+ "message_count_threshold": 50,+ "idle_timeout_seconds": 86400,+ "keep_recent_count": 2,+ "min_commit_interval_seconds": 0,+ }+++async def test_create_session_applies_config_and_fills_defaults(client: httpx.AsyncClient):+ resp = await client.post(+ "/api/v1/sessions",+ json={+ "auto_commit_policy": {+ "pending_token_threshold": 8000,+ "keep_recent_count": 10,+ }+ },+ )+ assert resp.status_code == 200+ result = resp.json()["result"]+ assert result["auto_commit_policy"] == {+ "pending_token_threshold": 8000,+ "message_count_threshold": 50,+ "idle_timeout_seconds": 86400,+ "keep_recent_count": 10,+ "min_commit_interval_seconds": 0,+ }++ session_resp = await client.get(f"/api/v1/sessions/{result['session_id']}")+ session_result = session_resp.json()["result"]+ assert session_result["auto_commit_policy"]["pending_token_threshold"] == 8000+ assert session_result["auto_commit_policy"]["keep_recent_count"] == 10+++async def test_create_session_clamps_config_above_bounds(client: httpx.AsyncClient):+ resp = await client.post(+ "/api/v1/sessions",+ json={"auto_commit_policy": {"pending_token_threshold": 10_000_000}},+ )+ assert resp.status_code == 200+ policy = resp.json()["result"]["auto_commit_policy"]+ assert policy["pending_token_threshold"] == 50000+++async def test_get_session_returns_effective_config(client: httpx.AsyncClient):+ create_resp = await client.post("/api/v1/sessions", json={})+ session_id = create_resp.json()["result"]["session_id"]++ resp = await client.get(f"/api/v1/sessions/{session_id}")+ assert resp.status_code == 200+ assert resp.json()["result"]["auto_commit_policy"] is None+++async def test_patch_session_config_is_not_supported(client: httpx.AsyncClient):+ create_resp = await client.post(+ "/api/v1/sessions",+ json={+ "auto_commit_policy": {+ "pending_token_threshold": 8000,+ "message_count_threshold": 40,+ "keep_recent_count": 10,+ }+ },+ )+ session_id = create_resp.json()["result"]["session_id"]++ patch_resp = await client.patch(+ f"/api/v1/sessions/{session_id}",+ json={"auto_commit_policy": {"message_count_threshold": 25}},+ )+ assert patch_resp.status_code == 405++ session_resp = await client.get(f"/api/v1/sessions/{session_id}")+ session_config = session_resp.json()["result"]["auto_commit_policy"]+ assert session_config["message_count_threshold"] == 40+ assert session_config["pending_token_threshold"] == 8000+++async def test_session_load_recovers_message_count_from_live_messages(service):+ ctx = RequestContext(user=UserIdentifier("acct_a", "user_b"), role=Role.ADMIN)+ await service.initialize_account_directories(ctx)+ await service.initialize_user_directories(ctx)++ session = await service.sessions.create(ctx)+ session.add_message("user", [TextPart("我爱吃西瓜")])++ session = await service.sessions.get(session.session_id, ctx, auto_create=False)+ session.meta.message_count = 0+ session.meta.pending_tokens = 0+ await session._save_meta()++ reloaded = service.sessions.session(ctx, session.session_id)+ await reloaded.load()++ assert len(reloaded.messages) == 1+ assert reloaded.meta.message_count == 1++async def test_write_responses_return_pending_tokens_for_commit_policy(client: httpx.AsyncClient,):@@ -648,6 +866,22 @@ async def test_batch_add_message_accepts_mixed_parts(client: httpx.AsyncClient,assert isinstance(session.messages[0].parts[1], ImagePart)+async def test_batch_add_message_ignores_removed_auto_commit_policy(client: httpx.AsyncClient):+ create_resp = await client.post("/api/v1/sessions", json={})+ session_id = create_resp.json()["result"]["session_id"]++ resp = await client.post(+ f"/api/v1/sessions/{session_id}/messages/batch",+ json={+ "messages": [{"role": "user", "content": "hello"}],+ "auto_commit_policy": {"pending_token_threshold": 1},+ },+ )++ assert resp.status_code == 200+ assert resp.json()["result"]["message_count"] == 1++async def test_add_message_splits_tool_result_aggregate(client: httpx.AsyncClient):create_resp = await client.post("/api/v1/sessions", json={})session_id = create_resp.json()["result"]["session_id"]diff --git a/tests/unit/service/test_core_encryption_startup.py b/tests/unit/service/test_core_encryption_startup.pyindex f1cf7a7d8..e34684806 100644--- a/tests/unit/service/test_core_encryption_startup.py+++ b/tests/unit/service/test_core_encryption_startup.py@@ -188,6 +188,7 @@ async def test_close_releases_data_dir_lock_after_successful_cleanup(monkeypatchservice = OpenVikingService.__new__(OpenVikingService)service._resource_service = _ResourceService()service._watch_scheduler = None+ service._session_auto_commit_scheduler = Noneservice._queue_manager = Noneservice._lock_manager = Noneservice._vikingdb_manager = Nonediff --git a/tests/unit/service/test_session_auto_commit.py b/tests/unit/service/test_session_auto_commit.pynew file mode 100644index 000000000..1b3d066c6--- /dev/null+++ b/tests/unit/service/test_session_auto_commit.py@@ -0,0 +1,839 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from __future__ import annotations++import json+import logging+import threading+import time+from datetime import datetime, timedelta, timezone+from types import SimpleNamespace++import pytest++import openviking.service.session_auto_commit as auto_commit_module+import openviking.service.session_service as session_service_module+from openviking.server.identity import RequestContext+from openviking.service.session_auto_commit import (+ SessionAutoCommitScheduler,+ compute_next_check_at,+)+from openviking.service.session_service import SessionService+from openviking_cli.session.user_id import UserIdentifier+from openviking_cli.utils.config.memory_config import SessionAutoCommitConfig+++_REAL_DATETIME = datetime+++class _Python310LikeDateTime:+ @classmethod+ def fromisoformat(cls, value: str):+ if isinstance(value, str) and value.endswith("Z"):+ raise ValueError("Invalid isoformat string")+ return _REAL_DATETIME.fromisoformat(value)++ @classmethod+ def now(cls):+ return _REAL_DATETIME.now()++ @classmethod+ def fromtimestamp(cls, timestamp: float, tz=None):+ return _REAL_DATETIME.fromtimestamp(timestamp, tz=tz)+++class _FakeVikingFS:+ def __init__(+ self,+ tree_entries: list[dict[str, str]],+ metas: dict[str, object],+ *,+ users_by_account: dict[str, list[str]] | None = None,+ tree_entries_by_user: dict[tuple[str, str], list[dict[str, str]]] | None = None,+ ls_errors: dict[str, BaseException] | None = None,+ read_delay_seconds: float = 0.0,+ ) -> None:+ self._tree_entries = tree_entries+ self._metas = metas+ self._users_by_account = users_by_account or {"acct_a": ["user_b"]}+ self._tree_entries_by_user = tree_entries_by_user or {}+ self._ls_errors = ls_errors or {}+ self._read_delay_seconds = read_delay_seconds+ self.agfs = self+ self.ls_calls: list[tuple[str, str]] = []+ self.read_calls: list[str] = []+ self.active_reads = 0+ self.max_active_reads = 0+ self._read_lock = threading.Lock()++ def ls(self, path: str, ctx=None):+ account_id = ""+ if isinstance(ctx, dict):+ account_id = str(ctx.get("account_id", ""))+ elif ctx is not None:+ account_id = str(getattr(ctx, "account_id", ""))+ self.ls_calls.append((path, account_id))+ if path in self._ls_errors:+ raise self._ls_errors[path]+ if path == "/local":+ return [{"name": account, "isDir": True} for account in self._users_by_account] + [+ {"name": "_system", "isDir": True},+ ]+ parts = [part for part in path.split("/") if part]+ if len(parts) == 3 and parts[0] == "local" and parts[2] == "user":+ return [+ {"name": user, "isDir": True} for user in self._users_by_account.get(parts[1], [])+ ]+ if (+ len(parts) == 5+ and parts[0] == "local"+ and parts[2] == "user"+ and parts[4] == "sessions"+ ):+ return list(self._tree_entries_by_user.get((parts[1], parts[3]), self._tree_entries))+ raise AssertionError(path)++ def read(self, path: str):+ with self._read_lock:+ self.read_calls.append(path)+ self.active_reads += 1+ self.max_active_reads = max(self.max_active_reads, self.active_reads)+ try:+ if self._read_delay_seconds:+ time.sleep(self._read_delay_seconds)+ value = self._metas[path]+ if isinstance(value, BaseException):+ raise value+ if isinstance(value, bytes):+ return value+ if isinstance(value, str):+ return value.encode("utf-8")+ return json.dumps(value).encode("utf-8")+ finally:+ with self._read_lock:+ self.active_reads -= 1+++class _FakeSessionService:+ def __init__(+ self,+ tree_entries: list[dict[str, str]],+ metas: dict[str, object],+ *,+ users_by_account: dict[str, list[str]] | None = None,+ tree_entries_by_user: dict[tuple[str, str], list[dict[str, str]]] | None = None,+ ls_errors: dict[str, BaseException] | None = None,+ read_delay_seconds: float = 0.0,+ ) -> None:+ self.viking_fs = _FakeVikingFS(+ tree_entries,+ metas,+ users_by_account=users_by_account,+ tree_entries_by_user=tree_entries_by_user,+ ls_errors=ls_errors,+ read_delay_seconds=read_delay_seconds,+ )+ self.calls: list[tuple[str, str, str]] = []+ self.schedule_results: list[bool] = []++ async def maybe_schedule_auto_commit(+ self,+ session_id: str,+ ctx: RequestContext,+ *,+ reason_hint: str,+ ):+ self.calls.append((session_id, reason_hint, ctx.user.user_id))+ if self.schedule_results:+ return self.schedule_results.pop(0)+ return True+++class _FakeSessionMeta:+ def __init__(+ self,+ *,+ auto_commit_policy: dict | None,+ pending_tokens: int = 0,+ message_count: int = 0,+ keep_recent_count: int = 0,+ last_message_at: str = "",+ last_auto_commit_at: str = "",+ ) -> None:+ self.auto_commit_policy = auto_commit_policy+ self.pending_tokens = pending_tokens+ self.message_count = message_count+ self.keep_recent_count = keep_recent_count+ self.last_message_at = last_message_at+ self.last_auto_commit_at = last_auto_commit_at++ def to_dict(self) -> dict:+ return {+ "auto_commit_policy": self.auto_commit_policy,+ "pending_tokens": self.pending_tokens,+ "message_count": self.message_count,+ "keep_recent_count": self.keep_recent_count,+ "last_message_at": self.last_message_at,+ "last_auto_commit_at": self.last_auto_commit_at,+ }+++class _FakeAutoCommitSession:+ def __init__(self, meta: _FakeSessionMeta) -> None:+ self.meta = meta+ self.commit_calls: list[tuple[int, bool, bool]] = []+ self.save_calls = 0++ async def commit_async(+ self,+ *,+ keep_recent_count: int = 0,+ persist_keep_recent_count: bool = True,+ record_auto_commit_success: bool = False,+ ):+ self.commit_calls.append(+ (keep_recent_count, persist_keep_recent_count, record_auto_commit_success)+ )+ return {"archived": True}++ async def _save_meta(self):+ self.save_calls += 1+++class _FakeTaskTracker:+ async def has_running(self, *args, **kwargs) -> bool:+ return False+++def _auto_commit_ctx() -> RequestContext:+ return RequestContext(+ user=UserIdentifier(account_id="acct_a", user_id="user_b"),+ role="user",+ )+++def _session_service_for_auto_commit_test(+ monkeypatch: pytest.MonkeyPatch,+ session: _FakeAutoCommitSession,+) -> SessionService:+ service = SessionService()+ service.set_session_auto_commit_config(+ SessionAutoCommitConfig(idle_enabled=True, check_interval_seconds=60.0)+ )++ async def fake_get(session_id, ctx, auto_create=False):+ return session++ monkeypatch.setattr(service, "get", fake_get)+ monkeypatch.setattr(session_service_module, "get_task_tracker", lambda: _FakeTaskTracker())+ return service+++def _meta(+ *,+ account_id: str = "acct_a",+ user_id: str = "user_b",+ idle_timeout_seconds: int | None = 60,+ pending_tokens: int = 1,+ message_count: int = 1,+ keep_recent_count: int = 0,+ last_message_at: str | None = None,+) -> dict:+ if last_message_at is None:+ last_message_at = (datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat()+ policy: dict = {"keep_recent_count": keep_recent_count}+ if idle_timeout_seconds is not None:+ policy["idle_timeout_seconds"] = idle_timeout_seconds+ return {+ "auto_commit_policy": policy,+ "created_by_account_id": account_id,+ "created_by_user_id": user_id,+ "pending_tokens": pending_tokens,+ "message_count": message_count,+ "keep_recent_count": keep_recent_count,+ "last_message_at": last_message_at,+ }+++def _session_entry(session_id: str) -> dict[str, object]:+ return {"name": session_id, "isDir": True}+++def test_compute_next_check_at_parses_utc_z_timestamps_on_python310(monkeypatch):+ monkeypatch.setattr(auto_commit_module, "datetime", _Python310LikeDateTime)++ assert (+ compute_next_check_at("2026-06-20T10:00:00.000Z", 60)+ == "2026-06-20T10:01:00+00:00"+ )+++async def test_run_auto_commit_skips_when_below_token_threshold(monkeypatch):+ session = _FakeAutoCommitSession(+ _FakeSessionMeta(+ auto_commit_policy={+ "pending_token_threshold": 100,+ "message_count_threshold": 50,+ "keep_recent_count": 0,+ "min_commit_interval_seconds": 0,+ },+ pending_tokens=10,+ message_count=1,+ )+ )+ service = _session_service_for_auto_commit_test(monkeypatch, session)++ await service.run_auto_commit("session_a", _auto_commit_ctx(), reason="message_write")++ assert session.commit_calls == []+ assert session.save_calls == 0+++async def test_run_auto_commit_skips_when_policy_is_disabled(monkeypatch):+ session = _FakeAutoCommitSession(+ _FakeSessionMeta(+ auto_commit_policy=None,+ pending_tokens=10_000,+ message_count=1_000,+ )+ )+ service = _session_service_for_auto_commit_test(monkeypatch, session)++ await service.run_auto_commit("session_a", _auto_commit_ctx(), reason="message_write")++ assert session.commit_calls == []+ assert session.save_calls == 0+++async def test_maybe_schedule_auto_commit_reuses_loaded_session(monkeypatch):+ session = _FakeAutoCommitSession(+ _FakeSessionMeta(+ auto_commit_policy=None,+ pending_tokens=10_000,+ message_count=1_000,+ )+ )+ service = SessionService()++ async def fail_get(*args, **kwargs):+ raise AssertionError("session should be reused instead of reloaded")++ monkeypatch.setattr(service, "get", fail_get)++ did_schedule = await service.maybe_schedule_auto_commit(+ "session_a",+ _auto_commit_ctx(),+ reason_hint="message_write",+ session=session,+ )++ assert did_schedule is False+++async def test_maybe_schedule_auto_commit_swallows_scheduling_errors(monkeypatch):+ session = _FakeAutoCommitSession(+ _FakeSessionMeta(+ auto_commit_policy={+ "pending_token_threshold": 100,+ "message_count_threshold": 500,+ },+ pending_tokens=101,+ message_count=5,+ )+ )+ service = SessionService()+ service.set_session_auto_commit_config(SessionAutoCommitConfig())++ class _FailingTaskTracker:+ async def has_running(self, *args, **kwargs) -> bool:+ raise RuntimeError("task store unavailable")++ monkeypatch.setattr(+ session_service_module, "get_task_tracker", lambda: _FailingTaskTracker()+ )++ did_schedule = await service.maybe_schedule_auto_commit(+ "session_a",+ _auto_commit_ctx(),+ reason_hint="message_write",+ session=session,+ )++ assert did_schedule is False+ assert session.commit_calls == []+ session = _FakeAutoCommitSession(+ _FakeSessionMeta(+ auto_commit_policy={+ "pending_token_threshold": 100,+ "message_count_threshold": 500,+ "keep_recent_count": 3,+ "min_commit_interval_seconds": 0,+ },+ pending_tokens=101,+ message_count=5,+ )+ )+ service = _session_service_for_auto_commit_test(monkeypatch, session)++ await service.run_auto_commit("session_a", _auto_commit_ctx(), reason="message_write")++ # message_write reserves the configured keep_recent tail and persists it.+ assert session.commit_calls == [(3, True, True)]+ assert session.save_calls == 0+ assert session.meta.last_auto_commit_at == ""+++async def test_run_auto_commit_throttles_with_utc_z_last_auto_commit_at_on_python310(monkeypatch):+ monkeypatch.setattr(session_service_module, "datetime", _Python310LikeDateTime)+ session = _FakeAutoCommitSession(+ _FakeSessionMeta(+ auto_commit_policy={+ "pending_token_threshold": 100,+ "message_count_threshold": 500,+ "keep_recent_count": 0,+ "min_commit_interval_seconds": 60,+ },+ pending_tokens=101,+ message_count=5,+ last_auto_commit_at="2099-01-01T00:00:00.000Z",+ )+ )+ service = _session_service_for_auto_commit_test(monkeypatch, session)++ await service.run_auto_commit("session_a", _auto_commit_ctx(), reason="message_write")++ assert session.commit_calls == []+ assert session.save_calls == 0+++async def test_run_auto_commit_rechecks_idle_timeout_before_committing(monkeypatch):+ session = _FakeAutoCommitSession(+ _FakeSessionMeta(+ auto_commit_policy={+ "idle_timeout_seconds": 300,+ "keep_recent_count": 0,+ },+ pending_tokens=1,+ message_count=1,+ last_message_at=datetime.now(timezone.utc).isoformat(),+ )+ )+ service = _session_service_for_auto_commit_test(monkeypatch, session)++ await service.run_auto_commit("session_a", _auto_commit_ctx(), reason="idle_timeout")++ assert session.commit_calls == []+ assert session.save_calls == 0+++async def test_run_auto_commit_idle_commits_full_backlog_without_persisting_keep_recent(monkeypatch):+ session = _FakeAutoCommitSession(+ _FakeSessionMeta(+ auto_commit_policy={+ "idle_timeout_seconds": 60,+ "keep_recent_count": 5,+ },+ pending_tokens=10,+ message_count=8,+ last_message_at=(datetime.now(timezone.utc) - timedelta(minutes=5)).isoformat(),+ )+ )+ service = _session_service_for_auto_commit_test(monkeypatch, session)++ await service.run_auto_commit("session_a", _auto_commit_ctx(), reason="idle_timeout")++ # Idle commits the full backlog and must not overwrite the stored keep pref.+ assert session.commit_calls == [(0, False, True)]+ assert session.save_calls == 0+++async def test_scheduler_scans_agfs_paths_directly_without_account_user_indices():+ tree_entries = [+ _session_entry("session_due"),+ _session_entry("session_skip"),+ ]+ metas = {+ "/local/acct_a/user/user_b/sessions/session_due/.meta.json": _meta(),+ "/local/acct_a/user/user_b/sessions/session_skip/.meta.json": _meta(+ pending_tokens=0,+ message_count=0,+ ),+ }+ service = _FakeSessionService(tree_entries, metas)+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ await scheduler._scan_once()++ assert service.viking_fs.ls_calls == [+ ("/local", "_system"),+ ("/local/acct_a/user", "acct_a"),+ ("/local/acct_a/user/user_b/sessions", "acct_a"),+ ]+ assert service.viking_fs.read_calls == [+ "/local/acct_a/user/user_b/sessions/session_due/.meta.json",+ "/local/acct_a/user/user_b/sessions/session_skip/.meta.json",+ ]+ # session_skip has no uncommitted content and is filtered at scan time.+ assert service.calls == [+ ("session_due", "idle_timeout", "user_b"),+ ]+++async def test_scheduler_skips_sessions_without_uncommitted_content():+ service = _FakeSessionService(+ [_session_entry("session_empty")],+ {+ "/local/acct_a/user/user_b/sessions/session_empty/.meta.json": _meta(+ pending_tokens=0,+ message_count=0,+ ),+ },+ )+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ await scheduler._scan_once()++ assert service.calls == []+++async def test_scheduler_skips_sessions_without_auto_commit_policy():+ service = _FakeSessionService(+ [_session_entry("session_disabled")],+ {+ "/local/acct_a/user/user_b/sessions/session_disabled/.meta.json": _meta()+ | {"auto_commit_policy": None},+ },+ )+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ await scheduler._scan_once()++ assert service.calls == []+++async def test_scheduler_schedules_idle_sessions_still_within_keep_recent_window():+ service = _FakeSessionService(+ [_session_entry("session_within_keep")],+ {+ "/local/acct_a/user/user_b/sessions/session_within_keep/.meta.json": _meta(+ pending_tokens=0,+ message_count=2,+ keep_recent_count=2,+ ),+ },+ )+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ await scheduler._scan_once()++ assert service.calls == [+ ("session_within_keep", "idle_timeout", "user_b"),+ ]+++async def test_scheduler_logs_scheduled_count_separately_from_due_candidates(caplog):+ service = _FakeSessionService(+ [_session_entry("session_due_1"), _session_entry("session_due_2")],+ {+ "/local/acct_a/user/user_b/sessions/session_due_1/.meta.json": _meta(),+ "/local/acct_a/user/user_b/sessions/session_due_2/.meta.json": _meta(),+ },+ )+ service.schedule_results = [True, False]+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ openviking_logger = logging.getLogger("openviking")+ old_propagate = openviking_logger.propagate+ openviking_logger.propagate = True+ try:+ with caplog.at_level(logging.INFO, logger="openviking.service.session_auto_commit"):+ await scheduler._scan_once()+ finally:+ openviking_logger.propagate = old_propagate++ assert "SessionAutoCommitScheduler scanned=2 due=2 scheduled=1" in caplog.text+++async def test_scheduler_reads_session_meta_with_bounded_concurrency():+ tree_entries = [_session_entry(f"session_{index}") for index in range(6)]+ metas = {+ f"/local/acct_a/user/user_b/sessions/session_{index}/.meta.json": _meta()+ for index in range(6)+ }+ service = _FakeSessionService(tree_entries, metas, read_delay_seconds=0.01)+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(+ idle_enabled=True,+ check_interval_seconds=60.0,+ scan_batch_size=2,+ scan_batch_pause_seconds=0.0,+ ),+ check_interval=60.0,+ )++ await scheduler._scan_once()++ assert service.viking_fs.max_active_reads == 2+ assert len(service.viking_fs.read_calls) == 6+ assert len(service.calls) == 6+++async def test_scheduler_pauses_between_scan_batches():+ tree_entries = [_session_entry(f"session_{index}") for index in range(5)]+ metas = {+ f"/local/acct_a/user/user_b/sessions/session_{index}/.meta.json": _meta()+ for index in range(5)+ }+ service = _FakeSessionService(tree_entries, metas)+ sleep_calls: list[float] = []++ async def fake_sleep(seconds: float) -> None:+ sleep_calls.append(seconds)++ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(+ idle_enabled=True,+ check_interval_seconds=60.0,+ scan_batch_size=2,+ scan_batch_pause_seconds=0.25,+ ),+ check_interval=60.0,+ sleep=fake_sleep,+ )++ await scheduler._scan_once()++ assert sleep_calls == [0.25, 0.25]+++async def test_scheduler_applies_batch_pause_while_enumerating_sessions():+ users_by_account = {"acct_a": ["user_1", "user_2", "user_3"]}+ tree_entries_by_user = {+ ("acct_a", "user_1"): [_session_entry("session_1")],+ ("acct_a", "user_2"): [_session_entry("session_2")],+ ("acct_a", "user_3"): [_session_entry("session_3")],+ }+ metas = {+ "/local/acct_a/user/user_1/sessions/session_1/.meta.json": _meta(user_id="user_1"),+ "/local/acct_a/user/user_2/sessions/session_2/.meta.json": _meta(user_id="user_2"),+ "/local/acct_a/user/user_3/sessions/session_3/.meta.json": _meta(user_id="user_3"),+ }+ service = _FakeSessionService(+ [],+ metas,+ users_by_account=users_by_account,+ tree_entries_by_user=tree_entries_by_user,+ )+ sleep_calls: list[float] = []++ async def fake_sleep(seconds: float) -> None:+ sleep_calls.append(seconds)++ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(+ idle_enabled=True,+ check_interval_seconds=60.0,+ scan_batch_size=2,+ scan_batch_pause_seconds=0.25,+ ),+ check_interval=60.0,+ sleep=fake_sleep,+ )++ await scheduler._scan_once()++ assert sleep_calls == [0.25]+ assert service.calls == [+ ("session_1", "idle_timeout", "user_1"),+ ("session_2", "idle_timeout", "user_2"),+ ("session_3", "idle_timeout", "user_3"),+ ]+++async def test_scheduler_does_not_warn_for_missing_meta(caplog):+ service = _FakeSessionService(+ [_session_entry("deleted_session")],+ {+ "/local/acct_a/user/user_b/sessions/deleted_session/.meta.json": FileNotFoundError(+ "missing"+ )+ },+ )+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ await scheduler._scan_once()++ assert not [record for record in caplog.records if record.levelname == "WARNING"]+ assert service.calls == []+++async def test_scheduler_warns_for_invalid_meta_json(caplog):+ service = _FakeSessionService(+ [_session_entry("bad_session")],+ {+ "/local/acct_a/user/user_b/sessions/bad_session/.meta.json": "{not-json",+ },+ )+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ openviking_logger = logging.getLogger("openviking")+ old_propagate = openviking_logger.propagate+ openviking_logger.propagate = True+ try:+ with caplog.at_level(logging.WARNING, logger="openviking.service.session_auto_commit"):+ await scheduler._scan_once()+ finally:+ openviking_logger.propagate = old_propagate++ assert "Invalid session meta JSON for idle auto-commit" in caplog.text+ assert service.calls == []+++async def test_scheduler_skips_non_object_meta_without_aborting_batch(caplog):+ service = _FakeSessionService(+ [_session_entry("bad_session"), _session_entry("good_session")],+ {+ "/local/acct_a/user/user_b/sessions/bad_session/.meta.json": [],+ "/local/acct_a/user/user_b/sessions/good_session/.meta.json": _meta(),+ },+ )+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ with caplog.at_level(logging.WARNING, logger="openviking.service.session_auto_commit"):+ await scheduler._scan_once()++ assert "Session auto-commit scheduler loop failed" not in caplog.text+ assert service.calls == [("good_session", "idle_timeout", "user_b")]+++async def test_scheduler_skips_malformed_due_fields_without_aborting_batch(caplog):+ service = _FakeSessionService(+ [_session_entry("bad_session"), _session_entry("good_session")],+ {+ "/local/acct_a/user/user_b/sessions/bad_session/.meta.json": _meta()+ | {"last_message_at": []},+ "/local/acct_a/user/user_b/sessions/good_session/.meta.json": _meta(),+ },+ )+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ with caplog.at_level(logging.WARNING, logger="openviking.service.session_auto_commit"):+ await scheduler._scan_once()++ assert "Session auto-commit scheduler loop failed" not in caplog.text+ assert service.calls == [("good_session", "idle_timeout", "user_b")]+++async def test_scheduler_warns_for_non_missing_session_scan_errors(caplog):+ service = _FakeSessionService(+ [],+ {},+ ls_errors={"/local/acct_a/user/user_b/sessions": RuntimeError("backend down")},+ )+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ openviking_logger = logging.getLogger("openviking")+ old_propagate = openviking_logger.propagate+ openviking_logger.propagate = True+ try:+ with caplog.at_level(logging.WARNING, logger="openviking.service.session_auto_commit"):+ await scheduler._scan_once()+ finally:+ openviking_logger.propagate = old_propagate++ assert "Failed to scan sessions for idle auto-commit" in caplog.text+ assert service.calls == []+++async def test_scheduler_reuses_async_agfs_client_between_scans(monkeypatch):+ service = _FakeSessionService(+ [_session_entry("session_due")],+ {+ "/local/acct_a/user/user_b/sessions/session_due/.meta.json": _meta(),+ },+ )+ created_clients = 0+ real_client = auto_commit_module.AsyncAGFSClient++ class _CountingAsyncAGFSClient(real_client):+ def __init__(self, client):+ nonlocal created_clients+ created_clients += 1+ super().__init__(client)++ monkeypatch.setattr(auto_commit_module, "AsyncAGFSClient", _CountingAsyncAGFSClient)+ scheduler = SessionAutoCommitScheduler(+ service,+ SimpleNamespace(idle_enabled=True, check_interval_seconds=60.0),+ check_interval=60.0,+ )++ await scheduler._scan_once()+ await scheduler._scan_once()++ assert created_clients == 1diff --git a/tests/unit/session/test_auto_commit_policy.py b/tests/unit/session/test_auto_commit_policy.pynew file mode 100644index 000000000..84e8f08b4--- /dev/null+++ b/tests/unit/session/test_auto_commit_policy.py@@ -0,0 +1,117 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0++from __future__ import annotations++import pytest++from openviking.session.auto_commit_policy import (+ DEFAULT_IDLE_TIMEOUT_SECONDS,+ DEFAULT_KEEP_RECENT_COUNT,+ DEFAULT_MESSAGE_COUNT_THRESHOLD,+ DEFAULT_MIN_COMMIT_INTERVAL_SECONDS,+ DEFAULT_PENDING_TOKEN_THRESHOLD,+ MAX_IDLE_TIMEOUT_SECONDS,+ MAX_MESSAGE_COUNT_THRESHOLD,+ MAX_PENDING_TOKEN_THRESHOLD,+ AutoCommitPolicy,+)+from openviking_cli.exceptions import InvalidArgumentError+++def test_default_matches_prd_recommended_values():+ policy = AutoCommitPolicy.default()++ assert policy.pending_token_threshold == DEFAULT_PENDING_TOKEN_THRESHOLD == 10000+ assert policy.message_count_threshold == DEFAULT_MESSAGE_COUNT_THRESHOLD == 50+ assert policy.idle_timeout_seconds == DEFAULT_IDLE_TIMEOUT_SECONDS == 86400+ assert policy.keep_recent_count == DEFAULT_KEEP_RECENT_COUNT == 2+ assert policy.min_commit_interval_seconds == DEFAULT_MIN_COMMIT_INTERVAL_SECONDS == 0+++def test_from_dict_none_returns_defaults():+ assert AutoCommitPolicy.from_dict(None).to_dict() == AutoCommitPolicy.default().to_dict()+++def test_from_dict_fills_missing_fields_with_defaults():+ policy = AutoCommitPolicy.from_dict({"pending_token_threshold": 8000})++ assert policy.pending_token_threshold == 8000+ assert policy.message_count_threshold == DEFAULT_MESSAGE_COUNT_THRESHOLD+ assert policy.idle_timeout_seconds == DEFAULT_IDLE_TIMEOUT_SECONDS+ assert policy.keep_recent_count == DEFAULT_KEEP_RECENT_COUNT+ assert policy.min_commit_interval_seconds == DEFAULT_MIN_COMMIT_INTERVAL_SECONDS+++def test_from_dict_clamps_to_upper_bounds():+ policy = AutoCommitPolicy.from_dict(+ {+ "pending_token_threshold": 10_000_000,+ "message_count_threshold": 10_000,+ "idle_timeout_seconds": 999_999_999,+ "keep_recent_count": 10_000,+ "min_commit_interval_seconds": 999_999_999,+ }+ )++ assert policy.pending_token_threshold == MAX_PENDING_TOKEN_THRESHOLD+ assert policy.message_count_threshold == MAX_MESSAGE_COUNT_THRESHOLD+ assert policy.idle_timeout_seconds == MAX_IDLE_TIMEOUT_SECONDS+ assert policy.keep_recent_count == MAX_MESSAGE_COUNT_THRESHOLD+ assert policy.min_commit_interval_seconds == MAX_IDLE_TIMEOUT_SECONDS+++def test_from_dict_clamps_negatives_to_zero():+ policy = AutoCommitPolicy.from_dict(+ {+ "pending_token_threshold": -5,+ "message_count_threshold": -1,+ "idle_timeout_seconds": -100,+ "keep_recent_count": -3,+ "min_commit_interval_seconds": -9,+ }+ )++ assert policy.to_dict() == {+ "pending_token_threshold": 0,+ "message_count_threshold": 0,+ "idle_timeout_seconds": 0,+ "keep_recent_count": 0,+ "min_commit_interval_seconds": 0,+ }+++def test_from_dict_rejects_unknown_keys():+ with pytest.raises(InvalidArgumentError):+ AutoCommitPolicy.from_dict({"enabled": True})++ with pytest.raises(InvalidArgumentError):+ AutoCommitPolicy.from_dict({"token_threshold": 500})+++def test_from_dict_rejects_non_object():+ with pytest.raises(InvalidArgumentError):+ AutoCommitPolicy.from_dict(42)+++def test_from_dict_rejects_non_integer_values():+ with pytest.raises(InvalidArgumentError):+ AutoCommitPolicy.from_dict({"pending_token_threshold": "abc"})+++def test_from_dict_accepts_existing_policy_instance():+ original = AutoCommitPolicy.from_dict({"keep_recent_count": 7})++ assert AutoCommitPolicy.from_dict(original) is original+++def test_to_dict_round_trips():+ payload = {+ "pending_token_threshold": 8000,+ "message_count_threshold": 40,+ "idle_timeout_seconds": 600,+ "keep_recent_count": 10,+ "min_commit_interval_seconds": 30,+ }++ assert AutoCommitPolicy.from_dict(payload).to_dict() == payloaddiff --git a/tests/utils/mock_agfs.py b/tests/utils/mock_agfs.pyindex f73ad121f..6e7479682 100644--- a/tests/utils/mock_agfs.py+++ b/tests/utils/mock_agfs.py@@ -99,3 +99,12 @@ class MockLocalAGFS:def bind_request_context(self, ctx):return MagicMock(__enter__=lambda x: None, __exit__=lambda x, y, z: None)++ def pathlock_acquire_tree(self, *args, **kwargs):+ return {"lease_ref": "mock-lease"}++ def pathlock_acquire_exact(self, *args, **kwargs):+ return {"lease_ref": "mock-lease"}++ def pathlock_release(self, *args, **kwargs):+ return None