Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat: add global Agent Evolution switch and HTTP usage sink (#3223)

agent8391d3a75823
diff --git a/docs/design/agent-evolution-global-switch-design.md b/docs/design/agent-evolution-global-switch-design.md
new file mode 100644
index 000000000..c1a8746d2
--- /dev/null
+++ b/docs/design/agent-evolution-global-switch-design.md
@@ -0,0 +1,112 @@
+# Global Agent Evolution Switch Design
+
+## Scope
+
+Agent Evolution is controlled by one deployment-level switch for the entire
+OpenViking server instance. All accounts and users served by the same process
+share the same effective value.
+
+The switch controls whether session commits may generate or update these memory
+types:
+
+- `cases`
+- `trajectories`
+- `experiences`
+
+Disabling the switch does not delete existing files and does not prevent
+existing experiences from being searched or read.
+
+## Configuration
+
+Add the switch directly to `ServerConfig`:
+
+```json
+{
+ "server": {
+ "agent_evolution": {
+ "enabled": false
+ }
+ }
+}
+```
+
+The default is `false`.
+
+`server.user_config_defaults` remains responsible only for existing per-user
+defaults such as add targets. Agent Evolution is no longer part of active
+`UserConfig` resolution.
+
+This setting belongs to the HTTP server deployment surface. Embedded/local SDK
+clients do not load `ServerConfig`, so they preserve the historical enabled
+behavior instead of becoming permanently unable to produce Agent memory.
+
+## Commit Behavior
+
+`SessionService` passes the deployment-level Agent Evolution configuration into
+each `Session`. A commit applies the global value after validating the
+session-level `memory_policy`:
+
+- When enabled, the session policy remains authoritative. A session may still
+ exclude `cases`, `trajectories`, or `experiences`.
+- When disabled, the commit removes all three Agent Evolution memory types from
+ the effective policy. A session cannot enable them through `memory_policy`.
+
+Phase 1 stores the effective boolean and skip reason in archive metadata.
+Asynchronous Phase 2 reads that snapshot, so normal queue processing and direct
+recovery of that archive use the value accepted at commit time.
+
+When a later commit rolls earlier failed archives into one recovery batch, the
+entire batch uses the triggering archive's snapshot. OpenViking keeps one
+extraction policy per batch instead of splitting the merged conversation across
+different Agent Evolution settings. Therefore, changing the deployment setting
+before a later recovery commit can affect replayed messages from earlier failed
+archives.
+
+Archives created before the snapshot field existed preserve the historical
+enabled behavior during recovery.
+
+## Removed User-Level Surface
+
+Remove Agent Evolution from the active per-user configuration and resolution
+logic. Retain a deprecated parse-only schema field so existing
+`user_config.json` files remain loadable; its value is ignored.
+
+Remove the user-level management surfaces introduced by the current branch:
+
+- `GET /api/v1/user-settings/memory`
+- `PATCH /api/v1/user-settings/memory`
+- Python SDK memory-setting methods
+- Embedded client memory-setting methods
+- `ov user-settings memory`
+- `ov user-settings set-memory`
+- Agent Evolution fields accepted during account or user creation
+
+Existing stored `agent_evolution` fields are ignored after upgrade. They do not
+override the deployment-level setting.
+
+## Compatibility
+
+- Existing experiences remain readable and searchable.
+- Embedded/local SDK clients preserve their historical enabled behavior because
+ they do not have the HTTP server configuration surface.
+- Existing user config files containing `agent_evolution` continue to parse,
+ preventing an upgrade from breaking users that already wrote the branch-era
+ configuration.
+- Session-level `memory_policy` remains supported as an allow-list below the
+ global switch.
+- Queue payload structure remains unchanged; the commit-time decision stays in
+ archive metadata.
+
+## Verification
+
+Tests cover:
+
+- Default global value is disabled.
+- Explicit global enablement produces Agent Evolution memory when the session
+ policy permits it.
+- Global disablement cannot be bypassed by session `memory_policy`.
+- Different users in one server receive the same effective value.
+- Existing user config with the deprecated field loads but does not affect the
+ result.
+- Phase 2 uses the archived commit-time value.
+- Existing experiences remain readable while production is disabled.
diff --git a/docs/design/agent-evolution-global-switch-implementation-plan.md b/docs/design/agent-evolution-global-switch-implementation-plan.md
new file mode 100644
index 000000000..0f7481cbf
--- /dev/null
+++ b/docs/design/agent-evolution-global-switch-implementation-plan.md
@@ -0,0 +1,397 @@
+# Global Agent Evolution Switch Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Replace the per-user Agent Evolution setting with one deployment-level switch shared by every account and user in an OpenViking server instance.
+
+**Architecture:** `ServerConfig.agent_evolution.enabled` is the only active Agent Evolution setting for HTTP server deployments. `SessionService` snapshots it into each `Session`; commit Phase 1 stores the effective value in archive metadata and Phase 2 consumes that snapshot. Embedded/local SDK clients preserve the historical enabled behavior because they do not load `ServerConfig`. The former user field remains parse-only for compatibility, while user-facing management APIs, clients, and CLI commands are removed.
+
+**Tech Stack:** Python 3.10+, Pydantic v2, FastAPI, pytest, Rust/clap CLI.
+
+---
+
+### Task 1: Define the global configuration contract
+
+**Files:**
+- Modify: `openviking/server/config.py`
+- Modify: `openviking/server/user_config.py`
+- Test: `tests/server/test_agent_evolution_global_setting.py`
+
+- [ ] **Step 1: Replace user-resolution tests with global configuration tests**
+
+Add tests that assert:
+
+```python
+def test_agent_evolution_is_disabled_by_default():
+ assert ServerConfig().agent_evolution.enabled is False
+
+
+def test_agent_evolution_can_be_enabled_for_the_server():
+ config = ServerConfig.model_validate(
+ {"agent_evolution": {"enabled": True}}
+ )
+ assert config.agent_evolution.enabled is True
+
+
+def test_deprecated_user_agent_evolution_value_is_ignored():
+ user_config = UserConfig.model_validate(
+ {"agent_evolution": {"enabled": True}}
+ )
+ assert user_config.agent_evolution.enabled is True
+ assert "agent_evolution" not in user_config.model_dump(exclude_none=True)
+```
+
+- [ ] **Step 2: Run the tests and verify they fail**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov --tb=short tests/server/test_agent_evolution_global_setting.py
+```
+
+Expected: failures because `ServerConfig.agent_evolution` does not exist and the user field is still active.
+
+- [ ] **Step 3: Add the global model and make the old user field parse-only**
+
+Implement:
+
+```python
+class AgentEvolutionConfig(BaseModel):
+ enabled: bool = False
+
+ model_config = {"extra": "forbid"}
+
+
+class DeprecatedUserAgentEvolutionConfig(BaseModel):
+ enabled: Optional[bool] = None
+
+ model_config = {"extra": "forbid"}
+
+
+class UserConfig(BaseModel):
+ add_targets: AddTargetsConfig = Field(default_factory=AddTargetsConfig)
+ agent_evolution: DeprecatedUserAgentEvolutionConfig = Field(
+ default_factory=DeprecatedUserAgentEvolutionConfig,
+ exclude=True,
+ )
+
+
+class ServerConfig(BaseModel):
+ agent_evolution: AgentEvolutionConfig = Field(default_factory=AgentEvolutionConfig)
+```
+
+Remove `ResolvedMemorySettings`, `write_user_memory_settings()`,
+`resolve_memory_settings()`, and `public_memory_settings()` from
+`openviking/server/user_config.py`.
+
+- [ ] **Step 4: Run the configuration tests**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov --tb=short tests/server/test_agent_evolution_global_setting.py
+```
+
+Expected: all remaining global configuration and compatibility tests pass.
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add openviking/server/config.py openviking/server/user_config.py tests/server/test_agent_evolution_global_setting.py
+git commit -m "refactor(agent-evolution): use global configuration"
+```
+
+### Task 2: Apply the global switch to session commit
+
+**Files:**
+- Modify: `openviking/server/app.py`
+- Modify: `openviking/service/session_service.py`
+- Modify: `openviking/session/session.py`
+- Modify: `tests/unit/session/test_agent_evolution_policy.py`
+- Modify: `tests/unit/session/test_session_commit_resume.py`
+- Modify: `tests/session/test_session_commit.py`
+
+- [ ] **Step 1: Add failing global-switch session tests**
+
+Cover these behaviors:
+
+```python
+def test_disabled_global_switch_removes_agent_memory_types():
+ policy = _apply_agent_evolution_setting(
+ MemoryPolicy.default(),
+ agent_evolution_enabled=False,
+ )
+ assert AGENT_EVOLUTION_MEMORY_TYPES.isdisjoint(policy.memory_types)
+
+
+async def test_commit_uses_global_enabled_value(session_with_messages):
+ session_with_messages._agent_evolution_enabled = True
+ result = await session_with_messages.commit_async()
+ task = await _wait_for_task(result["task_id"])
+ assert task["result"]["agent_evolution_enabled"] is True
+
+
+async def test_phase2_uses_archived_global_value(session):
+ archive_meta = {
+ "agent_evolution": {
+ "enabled": True,
+ "skip_reason": None,
+ }
+ }
+ session._agent_evolution_enabled = False
+ await session.resume_queued_commit(
+ _queued_commit_with_archive_meta(archive_meta)
+ )
+ assert (
+ session._run_memory_extraction.await_args.kwargs[
+ "agent_evolution_enabled"
+ ]
+ is True
+ )
+```
+
+- [ ] **Step 2: Run the focused tests and verify they fail**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov --tb=short \
+ tests/unit/session/test_agent_evolution_policy.py \
+ tests/unit/session/test_session_commit_resume.py \
+ tests/session/test_session_commit.py
+```
+
+Expected: failures because sessions still resolve per-user settings.
+
+- [ ] **Step 3: Pass the deployment value into sessions**
+
+In `SessionService`, replace `_user_config_defaults` with:
+
+```python
+# Embedded/local compatibility default. HTTP app setup overrides it from
+# ServerConfig, whose default is false.
+self._agent_evolution_enabled = True
+
+def set_agent_evolution_config(self, config: AgentEvolutionConfig) -> None:
+ self._agent_evolution_enabled = config.enabled
+```
+
+Pass `agent_evolution_enabled=self._agent_evolution_enabled` when constructing
+`Session`, and pass the same value to manual extraction.
+
+In `openviking/server/app.py`, configure the service with:
+
+```python
+sessions.set_agent_evolution_config(config.agent_evolution)
+```
+
+- [ ] **Step 4: Remove per-user resolution from commit**
+
+In `Session.__init__`, store:
+
+```python
+self._agent_evolution_enabled = bool(agent_evolution_enabled)
+```
+
+In `commit_async`, derive the effective policy directly from that value:
+
+```python
+agent_evolution_enabled = self._agent_evolution_enabled
+effective_policy = _apply_agent_evolution_setting(
+ effective_policy,
+ agent_evolution_enabled=agent_evolution_enabled,
+)
+```
+
+Remove the user-config exception path and `user_config_error` from new archive
+metadata and task results. Keep Phase 2 compatibility reads for old archive
+metadata, but do not consult current configuration during resume.
+
+- [ ] **Step 5: Run the focused session tests**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov --tb=short \
+ tests/unit/session/test_agent_evolution_policy.py \
+ tests/unit/session/test_session_commit_resume.py \
+ tests/session/test_session_commit.py
+```
+
+Expected: all tests pass.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add openviking/server/app.py openviking/service/session_service.py \
+ openviking/session/session.py tests/unit/session/test_agent_evolution_policy.py \
+ tests/unit/session/test_session_commit_resume.py tests/session/test_session_commit.py
+git commit -m "feat(agent-evolution): apply global commit switch"
+```
+
+### Task 3: Remove user-level management surfaces
+
+**Files:**
+- Modify: `openviking/server/routers/admin.py`
+- Modify: `openviking/server/routers/user_settings.py`
+- Modify: `openviking/async_client.py`
+- Modify: `openviking/sync_client.py`
+- Modify: `openviking/client/local.py`
+- Modify: `openviking_cli/client/base.py`
+- Modify: `sdk/python/openviking_sdk/client.py`
+- Modify: `crates/ov_cli/src/commands/mod.rs`
+- Delete: `crates/ov_cli/src/commands/user_settings.rs`
+- Modify: `crates/ov_cli/src/main.rs`
+- Modify: `crates/ov_cli/src/help_ui.rs`
+- Delete: `tests/client/test_user_memory_settings.py`
+- Modify: `tests/client/test_base_client_compatibility.py`
+- Modify: `sdk/python/tests/test_async_client_behaviors.py`
+- Modify: `tests/server/test_admin_api.py`
+
+- [ ] **Step 1: Change API tests to assert the user-level endpoint is absent**
+
+Add:
+
+```python
+async def test_agent_evolution_user_endpoint_is_not_registered(client):
+ response = await client.get("/api/v1/user-settings/memory")
+ assert response.status_code == 404
+```
+
+Remove tests that patch or retrieve the former user-level setting.
+
+- [ ] **Step 2: Run API/client tests and verify they fail**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov --tb=short \
+ tests/server/test_agent_evolution_global_setting.py \
+ tests/client/test_base_client_compatibility.py \
+ sdk/python/tests/test_async_client_behaviors.py
+```
+
+Expected: the endpoint and client methods still exist.
+
+- [ ] **Step 3: Remove the Python and HTTP surfaces**
+
+Delete the memory request model and `/user-settings/memory` routes. Remove
+`get_memory_settings()` and `patch_memory_settings()` from embedded, async,
+sync, CLI-base, and SDK clients. Remove Agent Evolution handling from account
+and user creation; deprecated user input remains accepted by `UserConfig` but
+is ignored.
+
+- [ ] **Step 4: Remove the Rust CLI commands**
+
+Delete the `user-settings` command group, dispatcher, help entries, parser
+tests, and `commands/user_settings.rs`.
+
+- [ ] **Step 5: Run Python and Rust tests**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov --tb=short \
+ tests/server/test_agent_evolution_global_setting.py \
+ tests/client/test_base_client_compatibility.py \
+ sdk/python/tests/test_async_client_behaviors.py
+cargo test --manifest-path crates/ov_cli/Cargo.toml user_settings
+cargo test --manifest-path crates/ov_cli/Cargo.toml plain_help
+```
+
+Expected: Python tests pass; the filtered Rust suites complete without a
+failure.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add -A crates/ov_cli openviking sdk/python tests
+git commit -m "refactor(agent-evolution): remove user settings surface"
+```
+
+### Task 4: Update public configuration documentation
+
+**Files:**
+- Delete: `docs/design/agent-evolution-user-configuration.md`
+- Modify: `docs/en/guides/01-configuration.md`
+- Modify: `docs/zh/guides/01-configuration.md`
+- Modify or delete: `docs/en/api/12-user-settings.md`
+- Modify or delete: `docs/zh/api/12-user-settings.md`
+- Modify: `docs/en/api/01-overview.md`
+- Modify: `docs/zh/api/01-overview.md`
+- Modify: `docs/.vitepress/config.ts`
+- Modify: `docs/scripts/check-api-reference.mjs`
+
+- [ ] **Step 1: Replace user-setting examples with global server configuration**
+
+Document:
+
+```json
+{
+ "server": {
+ "agent_evolution": {
+ "enabled": false
+ }
+ }
+}
+```
+
+State that the value applies to every account and user served by the process,
+controls only future production, and does not hide or delete existing files.
+
+- [ ] **Step 2: Remove API references for `/user-settings/memory`**
+
+Keep existing add-location documentation only where it existed independently
+of this branch. Remove navigation entries introduced solely for the deleted
+memory-setting API.
+
+- [ ] **Step 3: Run documentation checks**
+
+Run:
+
+```bash
+npm --prefix docs run docs:check-api-reference
+git diff --check
+```
+
+Expected: documentation validation and whitespace checks pass.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add -A docs
+git commit -m "docs(agent-evolution): document global switch"
+```
+
+### Task 5: Full regression and PR review
+
+**Files:**
+- Test only
+
+- [ ] **Step 1: Run the focused Python suite**
+
+```bash
+uv run pytest -q --no-cov --tb=short \
+ tests/unit/session/test_session_commit_resume.py \
+ tests/storage/test_session_commit_processor_identity.py \
+ tests/server/test_agent_evolution_global_setting.py \
+ tests/unit/session/test_agent_evolution_policy.py \
+ tests/unit/usage_reporter \
+ tests/session/test_compressor_v3.py \
+ tests/session/test_session_commit.py
+```
+
+- [ ] **Step 2: Run formatting and static checks**
+
+```bash
+uv run ruff check openviking tests sdk/python
+uv run ruff format --check openviking tests sdk/python
+cargo fmt --manifest-path crates/ov_cli/Cargo.toml --check
+git diff --check
+```
+
+- [ ] **Step 3: Push and run `review-pr`**
+
+Push the branch, review PR #3223 against `main`, fix every blocking finding
+with a failing regression test first, and repeat until the current HEAD has no
+blocking findings.
diff --git a/docs/design/openviking-usage-count-record-implementation-plan.md b/docs/design/openviking-usage-count-record-implementation-plan.md
new file mode 100644
index 000000000..d0f96894d
--- /dev/null
+++ b/docs/design/openviking-usage-count-record-implementation-plan.md
@@ -0,0 +1,228 @@
+# HTTP Usage CountRecord Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** 将内置 HTTP Usage Sink 上报的事件元素改为 `CountRecord`,同时保持内部 `UsageEvent`、自定义 Sink 和 outbox 可靠性语义不变。
+
+**Architecture:** `MemoryUsageExtractor` 继续生成 `UsageEvent`。`HttpUsageSink` 在持久化批次前执行单向转换,HTTP 批次中的 `events` 改为 `CountRecord`;`uniqueId` 继续承担重放去重键,并用于计算稳定 `batch_id`。
+
+**Tech Stack:** Python 3.10+、dataclasses、标准库 datetime/json、pytest、Ruff。
+
+---
+
+## 文件结构
+
+- Modify: `openviking/usage_reporter/http_sink.py`
+ - 定义 `UsageEvent -> CountRecord` 私有转换。
+ - 调整批次 ID 从 `uniqueId` 计算。
+- Modify: `tests/unit/usage_reporter/test_http_sink.py`
+ - 固定 recall/inject 字段映射、毫秒时间戳、扩展字段和未知事件行为。
+- Modify: `docs/design/openviking-usage-reporter-sink-design.md`
+ - 补充 `attributes -> extra.attributes` 的无损映射说明。
+
+### Task 1: 固定 CountRecord 映射契约
+
+**Files:**
+- Test: `tests/unit/usage_reporter/test_http_sink.py`
+
+- [ ] **Step 1: 扩展测试事件构造器**
+
+让 `FakeUsageEvent` 支持 `event_type`、`occurred_at`、`resource_uri`、
+`resource_type`、`task_id`、`evidence` 和 `attributes`,并继续通过
+`to_dict()` 模拟真实 `UsageEvent`。
+
+- [ ] **Step 2: 写 recall 映射失败测试**
+
+构造 `memory.recalled` 事件并调用 `sink.write()`,读取 pending JSON,断言:
+
+```python
+assert payload["events"] == [
+ {
+ "CountName": "experience.recall.count",
+ "OpType": "add",
+ "amount": 1.0,
+ "timestamp": 1785124800000,
+ "uniqueId": "ue_recall",
+ "tags": {
+ "account_id": "2101858484",
+ "user_id": "user-1",
+ "resource_uri": "viking://user/user-1/memories/experiences/exchange.md",
+ "resource_type": "experience",
+ },
+ "extra": {
+ "session_id": "session-1",
+ "task_id": "task-1",
+ "archive_uri": "viking://user/user-1/sessions/session-1/history/archive_001",
+ "message_id": "msg-1",
+ "tool_call_id": "call-1",
+ "tool_name": "search_experience",
+ "attributes": {"rank": 1},
+ },
+ }
+]
+```
+
+- [ ] **Step 3: 运行测试并确认 RED**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov tests/unit/usage_reporter/test_http_sink.py::TestHttpUsageSink::test_write_persists_recall_as_count_record
+```
+
+Expected: FAIL,当前 payload 仍包含 `event_type` 等 `UsageEvent` 字段。
+
+- [ ] **Step 4: 写 inject、空字段和未知事件失败测试**
+
+分别断言:
+
+- `memory.injected -> experience.inject.count`
+- `task_id=None`、空 `evidence`、空 `attributes` 不产生对应 `extra` 字段
+- 未知 `event_type` 在 `sink.write()` 时抛出 `ValueError`
+
+- [ ] **Step 5: 运行新增测试并确认 RED**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov tests/unit/usage_reporter/test_http_sink.py -k "count_record or unknown_event_type"
+```
+
+Expected: FAIL,CountRecord 转换尚不存在。
+
+### Task 2: 实现 HTTP 边界转换
+
+**Files:**
+- Modify: `openviking/usage_reporter/http_sink.py`
+
+- [ ] **Step 1: 增加事件类型映射和毫秒时间转换**
+
+```python
+_COUNT_NAMES = {
+ "memory.recalled": "experience.recall.count",
+ "memory.injected": "experience.inject.count",
+}
+
+
+def _timestamp_millis(value: str) -> int:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return int(parsed.timestamp() * 1000)
+```
+
+- [ ] **Step 2: 增加 CountRecord 转换**
+
+```python
+def _to_count_record(event: UsageEvent) -> dict[str, Any]:
+ record = event.to_dict()
+ event_type = str(record.get("event_type") or "")
+ try:
+ count_name = _COUNT_NAMES[event_type]
+ except KeyError as exc:
+ raise ValueError(f"unsupported usage event type: {event_type}") from exc
+
+ evidence = record.get("evidence")
+ evidence = evidence if isinstance(evidence, dict) else {}
+ attributes = record.get("attributes")
+ attributes = attributes if isinstance(attributes, dict) else {}
+ extra = {
+ "session_id": str(record.get("session_id") or ""),
+ **{key: value for key, value in evidence.items() if value not in (None, "")},
+ }
+ if record.get("task_id") not in (None, ""):
+ extra["task_id"] = record["task_id"]
+ if attributes:
+ extra["attributes"] = attributes
+
+ return {
+ "CountName": count_name,
+ "OpType": "add",
+ "amount": 1.0,
+ "timestamp": _timestamp_millis(str(record["occurred_at"])),
+ "uniqueId": str(record["event_id"]),
+ "tags": {
+ "account_id": str(record.get("account_id") or ""),
+ "user_id": str(record.get("user_id") or ""),
+ "resource_uri": str(record.get("resource_uri") or ""),
+ "resource_type": str(record.get("resource_type") or ""),
+ },
+ "extra": extra,
+ }
+```
+
+- [ ] **Step 3: 在持久化入口使用转换**
+
+`_persist_events()` 先校验 `event_id`,再调用 `_to_count_record()`。移除旧的
+逐事件 `prefix` 字段;资源归属继续由批次 `resource_id` 和
+`V-Resource-Id` header 表达。
+
+- [ ] **Step 4: 改用 uniqueId 生成 batch_id**
+
+```python
+unique_ids = "\n".join(str(event["uniqueId"]) for event in events)
+batch_id = f"ub_{hashlib.sha256(unique_ids.encode('utf-8')).hexdigest()}"
+```
+
+- [ ] **Step 5: 运行新增测试并确认 GREEN**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov tests/unit/usage_reporter/test_http_sink.py -k "count_record or unknown_event_type"
+```
+
+Expected: PASS。
+
+### Task 3: 回归可靠性与文档
+
+**Files:**
+- Modify: `docs/design/openviking-usage-reporter-sink-design.md`
+- Test: `tests/unit/usage_reporter/test_http_sink.py`
+
+- [ ] **Step 1: 补充 attributes 映射说明**
+
+在 CountRecord 字段映射中明确:非空 `UsageEvent.attributes` 写入
+`extra.attributes`,避免事件类型扩展字段丢失。
+
+- [ ] **Step 2: 运行 HTTP Sink 全量测试**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov --tb=short tests/unit/usage_reporter/test_http_sink.py
+```
+
+Expected: 全部 PASS,覆盖 outbox、重试、拆包、dead-letter 和 destination
+隔离。
+
+- [ ] **Step 3: 运行 Usage Reporter 回归**
+
+Run:
+
+```bash
+uv run pytest -q --no-cov --tb=short tests/unit/usage_reporter
+```
+
+Expected: 全部 PASS。
+
+- [ ] **Step 4: 运行静态检查**
+
+Run:
+
+```bash
+uv run ruff check openviking/usage_reporter/http_sink.py tests/unit/usage_reporter/test_http_sink.py
+uv run ruff format --check openviking/usage_reporter/http_sink.py tests/unit/usage_reporter/test_http_sink.py
+git diff --check
+```
+
+Expected: 全部通过。
+
+- [ ] **Step 5: 提交实现**
+
+```bash
+git add openviking/usage_reporter/http_sink.py \
+ tests/unit/usage_reporter/test_http_sink.py \
+ docs/design/openviking-usage-reporter-sink-design.md
+git commit -m "feat(usage): emit CountRecord over HTTP"
+```
diff --git a/docs/design/openviking-usage-reporter-sink-design.md b/docs/design/openviking-usage-reporter-sink-design.md
index 0989383d4..9b7e3fb16 100644
--- a/docs/design/openviking-usage-reporter-sink-design.md
+++ b/docs/design/openviking-usage-reporter-sink-design.md
@@ -92,7 +92,7 @@ UsageEvent 是可独立传输和消费的完整事件。`UsageContext` 只用于
## 6. UsageSink 机制
-OpenViking 开源包只定义 Sink 抽象:
+OpenViking 开源包定义统一的 Sink 抽象:
```python
class UsageSink:
@@ -100,7 +100,7 @@ class UsageSink:
...
```
-具体 Sink 作为外部扩展,通过 `class_path` 动态加载。
+具体 Sink 可以作为外部扩展通过 `class_path` 动态加载。开源包同时提供不依赖第三方消息队列 SDK 的内置 HTTP Sink,用于需要本地持久化重试的部署。
配置示例:
@@ -130,6 +130,59 @@ def load_class(class_path: str):
每个 Sink 的 `write()` 调用最多等待 5 秒。超时或异常只记录日志,不影响其他 Sink。Reporter 在应用生命周期内只创建一次,应用退出时调用 Sink 可选的 `close()` 方法。同步和异步 `close()` 均受同一超时限制;同步 hook 在独立 daemon 线程中执行,超时后不会阻塞事件循环、后续 Sink 清理或进程退出。
+内置 HTTP Sink 在 `write()` 返回前把事件批次写入本地 outbox,再由后台线程发送。它只依赖 Python 标准库,不引入 Kafka 等厂商依赖。HTTP Sink 支持指数退避、`413` 拆包、不可恢复批次转入 dead-letter,以及有界磁盘容量。
+
+### 6.1 HTTP CountRecord 协议
+
+`UsageEvent` 继续作为 OpenViking 内部抽取结果和自定义 Sink 的稳定协议。内置
+HTTP Sink 在写入 outbox 前,将 `UsageEvent` 转换为计量接收端使用的
+`CountRecord`。这样计量平台协议不会侵入 Extractor,也不会改变自定义 Sink
+的输入。
+
+HTTP 批次外层继续保留 `schema_version`、`resource_id`、`batch_id`、
+`created_at`、`attempt`、`next_retry_at` 和 `events`。`events` 数组中的元素
+采用以下格式:
+
+```json
+{
+ "CountName": "experience.recall.count",
+ "OpType": "add",
+ "amount": 1.0,
+ "timestamp": 1785124800000,
+ "uniqueId": "ue_<sha256>",
+ "tags": {
+ "account_id": "new",
+ "user_id": "test",
+ "resource_uri": "viking://user/test/memories/experiences/example.md",
+ "resource_type": "experience"
+ },
+ "extra": {
+ "session_id": "session-id",
+ "task_id": "task-id",
+ "archive_uri": "viking://user/test/sessions/session-id/history/archive_001",
+ "message_id": "message-id",
+ "tool_call_id": "tool-call-id",
+ "tool_name": "search_experience"
+ }
+}
+```
+
+字段映射:
+
+- `memory.recalled` 映射为 `CountName=experience.recall.count`。
+- `memory.injected` 映射为 `CountName=experience.inject.count`。
+- `OpType` 固定为 `add`。
+- `amount` 固定为 `1.0`。
+- `timestamp` 由 `occurred_at` 转换为 Unix 毫秒时间戳。
+- `uniqueId` 使用稳定的 `event_id`。
+- `tags` 保存 `account_id`、`user_id`、`resource_uri` 和 `resource_type`。
+- `extra` 保存 `session_id`、可选的 `task_id` 以及 `evidence` 中的审计字段。
+- 非空的 `UsageEvent.attributes` 原样写入 `extra.attributes`。
+- 空的可选字段不写入 `extra`。
+
+无法识别的 `event_type` 不生成含义不明确的计量记录,转换时抛出错误并由
+Reporter 的 best-effort 隔离机制处理。
+
## 7. 配置设计
默认关闭:
@@ -153,6 +206,21 @@ server:
endpoint: https://usage.example.com/events
```
+内置 HTTP Sink:
+
+```yaml
+server:
+ usage_reporter:
+ enabled: true
+ sinks:
+ - type: http
+ config:
+ endpoint: https://usage.example.com/events
+ resource_id_env: OV_RESOURCE_ID
+ outbox_dir: /var/lib/openviking/.usage_outbox
+ max_outbox_bytes: 268435456
+```
+
## 8. 对 OpenViking 的侵入
侵入点控制在 4 个地方。
@@ -197,7 +265,7 @@ archive session success
Usage Reporter 采用 best-effort 投递语义:
- Sink 成功:正常返回。
-- Sink 失败或超时:记录日志,不影响 session commit,也不自动重试。
+- Sink 失败或超时:记录日志,不影响 session commit。自定义 Sink 是否重试由其实现决定。
- 多个 Sink 相互隔离,某个 Sink 失败不影响其他 Sink。
- Sink 失败时事件可能丢失,因此本机制不保证 at-least-once。
- 如果 Sink 已写入成功,但进程在 phase2 写入完成标记前退出,phase2 恢复执行时可能重复发送同一事件。
@@ -212,12 +280,15 @@ schema_version
+ account_id
+ user_id
+ session_id
-+ task_id
-+ evidence.archive_uri
++ evidence.message_id
+ evidence.tool_call_id
+ resource_uri
```
-`occurred_at`、`message_id` 和 `attributes` 不参与计算,避免重放时间差或附加属性变化破坏幂等性。同一 archive 中同一 tool call 对同一资源产生的事件,在 phase2 重放后仍得到相同 `event_id`。
+`occurred_at`、`task_id`、`archive_uri` 和 `attributes` 不参与计算,避免重放时间差、
+任务恢复或附加属性变化破坏幂等性。同一 session message 中同一 tool call
+对同一资源产生的事件,在 phase2 重放后仍得到相同 `event_id`。
+
+内置 HTTP Sink 提供持久化 outbox、失败重试和发送确认。所有 `2xx` 响应视为确认,瞬时错误进入指数退避重试,`400` / `422` 进入 dead-letter。HTTP Sink 可能重复发送同一事件,消费端需按由内部 `event_id` 映射得到的 `CountRecord.uniqueId` 去重。
-如果后续需要可靠投递,需要增加持久化 outbox、失败重试和发送确认机制。
+HTTP outbox 使用 `max_outbox_bytes` 限制磁盘占用。达到上限时先淘汰最旧的 dead-letter,再淘汰最旧的 pending;inflight 不被淘汰。因此即使启用 HTTP Sink,长期下游故障和容量压力下仍可能丢失事件,整体机制保持 best-effort,不承诺端到端 at-least-once。
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 287f21de2..e338108a6 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -1475,6 +1475,9 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:
"resource_uri": "viking://user/resources",
"skill_uri": "viking://user/skills"
}
+ },
+ "agent_evolution": {
+ "enabled": false
}
}
}
@@ -1495,12 +1498,50 @@ When running OpenViking as an HTTP service, add a `server` section to `ov.conf`:
| `temp_upload.shared_prefix` | str | URI prefix used when allocating shared `temp_file_id` objects. | `"viking://upload"` |
| `user_config_defaults.add_targets.resource_uri` | str | Deployment default resource add directory used when `add_resource` omits both `to` and `parent`. `viking://user/...` resolves per request user. | `null` |
| `user_config_defaults.add_targets.skill_uri` | str | Deployment default skill add root used when `add_skill` omits `target_uri`. Only `viking://user/skills` and `viking://agent/skills` are accepted. | `null` |
+| `agent_evolution.enabled` | bool | Instance-wide Agent Evolution switch. When enabled, session commits may generate or update cases, trajectories, and experiences according to the session `memory_policy`. When disabled, production of these memory types stops for every account and user. Existing memories remain readable and searchable. | `false` |
`api_key` mode uses API keys and is the default. `trusted` mode trusts `X-OpenViking-Account` / `X-OpenViking-User` headers from a trusted gateway or internal caller.
When `root_api_key` is configured in `api_key` mode, the server enables multi-tenant authentication. Use the Admin API to create accounts and user keys. In `trusted` mode, ordinary requests do not require user registration first; each request is resolved as `USER` from the injected identity headers. However, skipping `root_api_key` in `trusted` mode is allowed only on localhost. Development mode only applies when `auth_mode = "api_key"` and `root_api_key` is not set.
-`user_config_defaults` sets defaults for new and existing users when they have no per-user override. For add operations, explicit request targets still win: `add_resource.to` / `add_resource.parent` take precedence over user defaults, and `add_skill.target_uri` takes precedence over user defaults. Per-user overrides are stored in `viking://user/{user_id}/settings/user_config.json`.
+`user_config_defaults` only provides per-user defaults for add targets. For add operations, explicit request targets still win: `add_resource.to` / `add_resource.parent` take precedence over user defaults, and `add_skill.target_uri` takes precedence over user defaults. `agent_evolution.enabled` is shared by the entire OpenViking instance and has no per-user override; restart the server after changing it.
+
+### Usage Reporter
+
+The optional Usage Reporter extracts memory usage events from committed session tool parts. The built-in HTTP sink persists batches to a local outbox before delivering them to a collector:
+
+```json
+{
+ "server": {
+ "usage_reporter": {
+ "enabled": true,
+ "extractors": ["memory_usage"],
+ "sinks": [
+ {
+ "type": "http",
+ "config": {
+ "endpoint": "https://collector.example.com/openviking/usage",
+ "resource_id_env": "OV_RESOURCE_ID",
+ "outbox_dir": "/var/lib/openviking/.usage_outbox",
+ "request_timeout_seconds": 10,
+ "inflight_lease_seconds": 60,
+ "retry_base_seconds": 1,
+ "retry_max_seconds": 300,
+ "max_batch_bytes": 1048576,
+ "max_outbox_bytes": 268435456
+ }
+ }
+ ]
+ }
+ }
+}
+```
+
+Set the environment variable named by `resource_id_env` before starting the server. If `outbox_dir` is omitted, it defaults to `~/.openviking/data/.usage_outbox` for the operating-system user running OpenViking.
+
+HTTP delivery uses a durable local retry queue and may deliver the same event more than once. Collectors should deduplicate `CountRecord` entries by `uniqueId`. Every `2xx` response acknowledges a batch; transient failures are retried with exponential backoff. `400` and `422` responses move a batch to `dead_letter`, while `413` splits multi-event batches. The outbox is bounded by `max_outbox_bytes`; when the limit is reached, the oldest dead-letter batches are removed first, followed by the oldest pending batches. In-flight batches are not evicted. Because capacity pressure can discard pending data, reporting remains best-effort and does not provide an end-to-end at-least-once guarantee.
+
+`inflight_lease_seconds` must be greater than `request_timeout_seconds`. The lease is refreshed whenever a worker claims a batch, preventing another worker from recovering an active delivery.
Supported add target URIs:
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 86327b784..1f8303de3 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -1441,6 +1441,9 @@ openviking add-resource ./docs --exclude "*.tmp"
"resource_uri": "viking://user/resources",
"skill_uri": "viking://user/skills"
}
+ },
+ "agent_evolution": {
+ "enabled": false
}
}
}
@@ -1461,12 +1464,50 @@ openviking add-resource ./docs --exclude "*.tmp"
| `temp_upload.shared_prefix` | str | 分配 shared `temp_file_id` 对象时使用的 URI 前缀。 | `"viking://upload"` |
| `user_config_defaults.add_targets.resource_uri` | str | `add_resource` 未传 `to` 和 `parent` 时使用的部署级默认资源添加目录。`viking://user/...` 会按请求用户解析。 | `null` |
| `user_config_defaults.add_targets.skill_uri` | str | `add_skill` 未传 `target_uri` 时使用的部署级默认技能添加根目录。仅允许 `viking://user/skills` 和 `viking://agent/skills`。 | `null` |
+| `agent_evolution.enabled` | bool | 实例级 Agent 进化开关。开启时,session commit 可按 session `memory_policy` 生成或更新 cases、trajectories 和 experiences;关闭时,所有账号和用户均停止生产这三类记忆。已有记忆仍可读取和检索。 | `false` |
`api_key` 模式使用 API Key 认证,也是默认模式;`trusted` 模式信任上游网关或受信调用方注入的 `X-OpenViking-Account` / `X-OpenViking-User` 请求头。
在 `api_key` 模式下配置 `root_api_key` 后,服务端启用正式多租户认证,并通过 Admin API 创建工作区和用户 key。在 `trusted` 模式下,普通请求不需要先注册 user key;每个请求都会根据注入的身份头解析成 `USER`。只有在 `auth_mode = "api_key"` 且未配置 `root_api_key` 时,服务端才会进入开发模式。
-`user_config_defaults` 用于给没有个人覆盖配置的新老用户提供默认用户配置。添加操作中,显式请求目标仍然优先:`add_resource.to` / `add_resource.parent` 优先于用户默认值,`add_skill.target_uri` 优先于用户默认值。个人覆盖配置存储在 `viking://user/{user_id}/settings/user_config.json`。
+`user_config_defaults` 仅用于添加目标的用户级默认配置。添加操作中,显式请求目标仍然优先:`add_resource.to` / `add_resource.parent` 优先于用户默认值,`add_skill.target_uri` 优先于用户默认值。`agent_evolution.enabled` 是当前 OpenViking 实例的统一开关,不支持用户级覆盖;修改后需重启服务加载配置。
+
+### Usage Reporter
+
+可选的 Usage Reporter 从已 commit session 的 tool parts 中抽取记忆使用事件。内置 HTTP Sink 会先把事件批次持久化到本地 outbox,再发送给采集服务:
+
+```json
+{
+ "server": {
+ "usage_reporter": {
+ "enabled": true,
+ "extractors": ["memory_usage"],
+ "sinks": [
+ {
+ "type": "http",
+ "config": {
+ "endpoint": "https://collector.example.com/openviking/usage",
+ "resource_id_env": "OV_RESOURCE_ID",
+ "outbox_dir": "/var/lib/openviking/.usage_outbox",
+ "request_timeout_seconds": 10,
+ "inflight_lease_seconds": 60,
+ "retry_base_seconds": 1,
+ "retry_max_seconds": 300,
+ "max_batch_bytes": 1048576,
+ "max_outbox_bytes": 268435456
+ }
+ }
+ ]
+ }
+ }
+}
+```
+
+启动服务前,需要设置 `resource_id_env` 指定的环境变量。未配置 `outbox_dir` 时,默认使用 OpenViking 运行用户的 `~/.openviking/data/.usage_outbox`。
+
+HTTP Sink 使用本地持久化队列重试,同一事件可能被重复发送,采集端需要按 `CountRecord.uniqueId` 去重。所有 `2xx` 响应都表示批次已确认;瞬时失败使用指数退避重试;`400` 和 `422` 会将批次移入 `dead_letter`;`413` 会拆分包含多条事件的批次。outbox 总量受 `max_outbox_bytes` 限制,达到上限后先删除最旧的 dead-letter 批次,再删除最旧的 pending 批次,正在发送的批次不会被淘汰。由于容量压力可能丢弃 pending 数据,整体上报仍是 best-effort,不提供端到端 at-least-once 保证。
+
+`inflight_lease_seconds` 必须大于 `request_timeout_seconds`。worker 领取批次时会刷新 lease,避免其他 worker 把正在发送的批次误判为过期任务。
支持的 add target URI:
diff --git a/examples/ov.conf.example b/examples/ov.conf.example
index 2ec4b9565..f1efe9fb8 100644
--- a/examples/ov.conf.example
+++ b/examples/ov.conf.example
@@ -4,6 +4,9 @@
"port": 1933,
"root_api_key": null,
"cors_origins": ["*"],
+ "agent_evolution": {
+ "enabled": false,
+ },
"observability": {
"metrics": {
"enabled": true,
diff --git a/openviking/async_client.py b/openviking/async_client.py
index 8580dbd33..ae71027bd 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -24,7 +24,6 @@ if TYPE_CHECKING:
logger = get_logger(__name__)
-
if TYPE_CHECKING:
from openviking.snapshot_namespace import AsyncSnapshotNamespace
diff --git a/openviking/server/app.py b/openviking/server/app.py
index 7dd62e12a..8e171495e 100644
--- a/openviking/server/app.py
+++ b/openviking/server/app.py
@@ -223,6 +223,10 @@ def create_app(
if callable(usage_reporter_setter):
usage_reporter_setter(_get_usage_reporter())
+ agent_evolution_setter = getattr(sessions, "set_agent_evolution_config", None)
+ if callable(agent_evolution_setter):
+ agent_evolution_setter(config.agent_evolution)
+
if service is not None:
_configure_session_runtime(service)
diff --git a/openviking/server/config.py b/openviking/server/config.py
index d158eb2d6..6757b423c 100644
--- a/openviking/server/config.py
+++ b/openviking/server/config.py
@@ -81,10 +81,30 @@ class AddTargetsConfig(BaseModel):
raise ValueError("skill_uri must be viking://user/skills or viking://agent/skills")
+class AgentEvolutionConfig(BaseModel):
+ """Server-wide Agent Evolution production switch."""
+
+ enabled: bool = False
+
+ model_config = {"extra": "forbid"}
+
+
+class DeprecatedUserAgentEvolutionConfig(BaseModel):
+ """Parse-only compatibility for legacy per-user configuration files."""
+
+ enabled: Optional[bool] = None
+
+ model_config = {"extra": "forbid"}
+
+
class UserConfig(BaseModel):
"""User configuration values that can be defaulted or initialized."""
add_targets: AddTargetsConfig = Field(default_factory=AddTargetsConfig)
+ agent_evolution: DeprecatedUserAgentEvolutionConfig = Field(
+ default_factory=DeprecatedUserAgentEvolutionConfig,
+ exclude=True,
+ )
model_config = {"extra": "forbid"}
@@ -176,7 +196,7 @@ class UsageAuditConfig(BaseModel):
class UsageReporterSinkConfig(BaseModel):
"""Usage reporter sink configuration."""
- type: Literal["custom"] = "custom"
+ type: Literal["custom", "http"] = "custom"
class_path: Optional[str] = None
config: Dict[str, object] = Field(default_factory=dict)
@@ -267,6 +287,7 @@ class ServerConfig(BaseModel):
upload_signed_ttl_seconds: int = 600
temp_upload: TempUploadConfig = Field(default_factory=TempUploadConfig)
user_config_defaults: UserConfig = Field(default_factory=UserConfig)
+ agent_evolution: AgentEvolutionConfig = Field(default_factory=AgentEvolutionConfig)
tool_output_externalization: ToolOutputExternalizationConfig = Field(
default_factory=ToolOutputExternalizationConfig
)
diff --git a/openviking/server/routers/admin.py b/openviking/server/routers/admin.py
index 0e08ed3a8..56c686ad9 100644
--- a/openviking/server/routers/admin.py
+++ b/openviking/server/routers/admin.py
@@ -90,6 +90,10 @@ def _has_add_targets(user_config: UserConfig | None) -> bool:
)
+def _has_initial_user_config(user_config: UserConfig | None) -> bool:
+ return _has_add_targets(user_config)
+
+
def _validate_initial_user_config(
service,
user_ctx: RequestContext,
@@ -111,7 +115,7 @@ async def _write_initial_user_config(
user_ctx: RequestContext,
user_config: UserConfig | None,
) -> None:
- if not _has_add_targets(user_config):
+ if not _has_initial_user_config(user_config):
return
await write_user_config(service.viking_fs, user_ctx, user_config)
diff --git a/openviking/server/user_config.py b/openviking/server/user_config.py
index e384c9aff..4a93fc776 100644
--- a/openviking/server/user_config.py
+++ b/openviking/server/user_config.py
@@ -5,17 +5,20 @@
from __future__ import annotations
import json
+from contextlib import asynccontextmanager
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, Optional, TypeVar
from openviking.core.namespace import canonical_user_root
from openviking.core.uri_validation import validate_content_target_uri
from openviking.server.config import AddTargetsConfig, UserConfig
+from openviking.storage.transaction import LockContext, get_lock_manager
from openviking_cli.exceptions import InvalidArgumentError, NotFoundError
if TYPE_CHECKING:
from openviking.server.config import ServerConfig
from openviking.server.identity import RequestContext
+ from openviking.storage.transaction import LockHandle
from openviking.storage.viking_fs import VikingFS
@@ -25,10 +28,28 @@ class ResolvedAddTargets:
skill_uri: Optional[str] = None
+_UpdateResult = TypeVar("_UpdateResult")
+
+
def user_config_uri(ctx: RequestContext) -> str:
return f"{canonical_user_root(ctx)}/settings/user_config.json"
+@asynccontextmanager
+async def _user_config_lock(
+ viking_fs: VikingFS,
+ uri: str,
+ ctx: RequestContext,
+) -> AsyncIterator[Optional[LockHandle]]:
+ uri_to_path = getattr(viking_fs, "_uri_to_path", None)
+ if not callable(uri_to_path):
+ yield None
+ return
+ path = uri_to_path(uri, ctx=ctx)
+ async with LockContext(get_lock_manager(), [path], lock_mode="exact") as handle:
+ yield handle
+
+
def _user_config_from_payload(payload: Any) -> UserConfig:
if not isinstance(payload, dict):
raise InvalidArgumentError("user config must be an object")
@@ -114,6 +135,32 @@ async def read_user_config(
return _user_config_from_payload(payload)
+async def update_user_config(
+ viking_fs: VikingFS,
+ ctx: RequestContext,
+ updater: Callable[[UserConfig], _UpdateResult],
+) -> _UpdateResult:
+ """Apply a locked read-modify-write update to the current user's config."""
+ uri = user_config_uri(ctx)
+ async with _user_config_lock(viking_fs, uri, ctx) as handle:
+ current = await read_user_config(viking_fs, ctx)
+ before = current.model_dump()
+ result = updater(current)
+ validate_add_targets(current.add_targets, ctx=ctx, viking_fs=viking_fs)
+ if current.model_dump() != before:
+ await viking_fs.write_file(
+ uri,
+ json.dumps(
+ current.model_dump(exclude_none=True),
+ ensure_ascii=False,
+ sort_keys=True,
+ ),
+ ctx=ctx,
+ lock_handle=handle,
+ )
+ return result
+
+
async def write_user_config(
viking_fs: VikingFS,
ctx: RequestContext,
@@ -121,11 +168,17 @@ async def write_user_config(
) -> ResolvedAddTargets:
runtime = validate_add_targets(user_config.add_targets, ctx=ctx, viking_fs=viking_fs)
uri = user_config_uri(ctx)
- await viking_fs.write_file(
- uri,
- json.dumps(user_config.model_dump(exclude_none=True), ensure_ascii=False, sort_keys=True),
- ctx=ctx,
- )
+ async with _user_config_lock(viking_fs, uri, ctx) as handle:
+ await viking_fs.write_file(
+ uri,
+ json.dumps(
+ user_config.model_dump(exclude_none=True),
+ ensure_ascii=False,
+ sort_keys=True,
+ ),
+ ctx=ctx,
+ lock_handle=handle,
+ )
return runtime
@@ -148,13 +201,20 @@ async def write_user_add_targets(
ctx: RequestContext,
settings: AddTargetsConfig,
) -> ResolvedAddTargets:
- user_config = await read_user_config(viking_fs, ctx)
- user_config.add_targets = settings
- return await write_user_config(viking_fs, ctx, user_config)
+ runtime = validate_add_targets(settings, ctx=ctx, viking_fs=viking_fs)
+
+ def _set(user_config: UserConfig) -> None:
+ user_config.add_targets = settings
+
+ await update_user_config(viking_fs, ctx, _set)
+ return runtime
async def delete_user_add_targets(viking_fs: VikingFS, ctx: RequestContext) -> None:
- await delete_user_config(viking_fs, ctx)
+ def _clear(user_config: UserConfig) -> None:
+ user_config.add_targets = AddTargetsConfig()
+
+ await update_user_config(viking_fs, ctx, _clear)
async def effective_resource_add_target(
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 241903add..25b8704cf 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -9,7 +9,7 @@ Provides session management operations: session, sessions, add_message, commit,
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from openviking.core.namespace import canonical_session_uri
-from openviking.server.config import ToolOutputExternalizationConfig
+from openviking.server.config import AgentEvolutionConfig, ToolOutputExternalizationConfig
from openviking.server.identity import RequestContext
from openviking.service.task_tracker import get_task_tracker
from openviking.session import Session
@@ -44,6 +44,10 @@ class SessionService:
self._viking_fs = viking_fs
self._session_compressor = session_compressor
self._tool_output_externalization_config = ToolOutputExternalizationConfig()
+ # Embedded clients do not load ServerConfig. Preserve their historical
+ # Agent memory behavior; HTTP servers always override this from
+ # server.agent_evolution during app setup.
+ self._agent_evolution_enabled = True
self._usage_reporter: Optional["UsageReporter"] = None
def set_dependencies(
@@ -63,6 +67,10 @@ class SessionService:
"""Set tool output externalization controls for newly created sessions."""
self._tool_output_externalization_config = config.model_copy(deep=True)
+ def set_agent_evolution_config(self, config: AgentEvolutionConfig) -> None:
+ """Set the instance-wide Agent Evolution switch."""
+ self._agent_evolution_enabled = config.enabled
+
def set_usage_reporter(self, usage_reporter: Optional["UsageReporter"]) -> None:
"""Set the usage reporter for newly created sessions."""
self._usage_reporter = usage_reporter
@@ -126,6 +134,7 @@ class SessionService:
session_id=session_id,
session_uri=session_uri,
tool_output_externalization_config=self._tool_output_externalization_config,
+ agent_evolution_enabled=self._agent_evolution_enabled,
usage_reporter=self._usage_reporter,
)
@@ -368,6 +377,7 @@ class SessionService:
session_id=session_id,
ctx=ctx,
archive_uri=archive_uri,
+ agent_evolution_enabled=self._agent_evolution_enabled,
)
self._record_lifecycle_metric("extract", "ok")
return memories
diff --git a/openviking/session/compressor_v3.py b/openviking/session/compressor_v3.py
index a007ce8af..95e611a5a 100644
--- a/openviking/session/compressor_v3.py
+++ b/openviking/session/compressor_v3.py
@@ -23,6 +23,13 @@ from openviking.core.context import Context
from openviking.message import Message
from openviking.server.identity import RequestContext
from openviking.session.memory import ExtractLoop, MemoryUpdater, StreamingMemoryUpdaterConfig
+from openviking.session.memory.constants import (
+ AGENT_EVOLUTION_MEMORY_TYPES,
+ CASE_MEMORY_TYPE,
+ EXECUTION_MEMORY_TYPES,
+ EXPERIENCE_MEMORY_TYPE,
+ TRAJECTORY_MEMORY_TYPE,
+)
from openviking.session.memory.dataclass import (
MemoryFile,
MemoryOperationSource,
@@ -77,7 +84,10 @@ from openviking_cli.utils.config import get_openviking_config
logger = get_logger(__name__)
-_CASES_MEMORY_TYPE = "cases"
+_CASES_MEMORY_TYPE = CASE_MEMORY_TYPE
+_TRAJECTORIES_MEMORY_TYPE = TRAJECTORY_MEMORY_TYPE
+_EXPERIENCES_MEMORY_TYPE = EXPERIENCE_MEMORY_TYPE
+_AGENT_MEMORY_TYPES = EXECUTION_MEMORY_TYPES
_TRAINING_CASE_SPEC_PROTOCOL = "openviking.batch_train.case_spec.v1"
_TRAINING_CASE_SPEC_HEADER = "# OpenViking Batch Training CaseSpec v1"
_TRAINING_FAST_PATH_MEMORY_TYPES = frozenset({"cases", "trajectories", "experiences"})
@@ -289,9 +299,18 @@ class SessionCompressorV3:
latest_archive_overview: str = "",
archive_uri: Optional[str] = None,
allowed_memory_types: Optional[set[str]] = None,
+ agent_evolution_enabled: bool = True,
allow_self_memory: bool = True,
allowed_peer_ids: Optional[set[str]] = None,
):
+ if not agent_evolution_enabled:
+ effective_types = (
+ set(create_default_registry().list_names(include_disabled=False))
+ if allowed_memory_types is None
+ else set(allowed_memory_types)
+ )
+ allowed_memory_types = effective_types - AGENT_EVOLUTION_MEMORY_TYPES
+
message_list = list(messages)
fast_path_case = _training_case_from_first_message(message_list, allowed_memory_types)
if fast_path_case is not None:
@@ -302,6 +321,8 @@ class SessionCompressorV3:
session_id=session_id,
archive_uri=archive_uri or "",
strict_extract_errors=strict_extract_errors,
+ agent_evolution_enabled=agent_evolution_enabled,
+ allowed_memory_types=allowed_memory_types,
)
result = await self._extract_user_memories(
@@ -316,16 +337,42 @@ class SessionCompressorV3:
allow_self_memory=allow_self_memory,
allowed_peer_ids=allowed_peer_ids,
)
- train_result = await self.train_from_extracted_cases(
- cases=result.cases,
- messages=message_list,
- ctx=ctx,
- case_uri_by_name=getattr(result, "case_uri_by_name", {}),
- session_id=session_id,
- archive_uri=archive_uri or "",
- strict_extract_errors=strict_extract_errors,
- collect_memory_diff=True,
- )
+ agent_memory_types = _allowed_agent_memory_types(allowed_memory_types)
+ cases_allowed = allowed_memory_types is None or _CASES_MEMORY_TYPE in allowed_memory_types
+ session_skills_enabled = self._session_skill_extraction_enabled()
+ if (
+ agent_evolution_enabled
+ and cases_allowed
+ and _TRAJECTORIES_MEMORY_TYPE in agent_memory_types
+ ):
+ train_result = await self.train_from_extracted_cases(
+ cases=result.cases,
+ messages=message_list,
+ ctx=ctx,
+ case_uri_by_name=getattr(result, "case_uri_by_name", {}),
+ session_id=session_id,
+ archive_uri=archive_uri or "",
+ strict_extract_errors=strict_extract_errors,
+ collect_memory_diff=True,
+ allowed_memory_types=agent_memory_types,
+ )
+ elif not agent_evolution_enabled and allow_self_memory and session_skills_enabled:
+ train_result = await self.extract_session_skills(
+ messages=message_list,
+ ctx=ctx,
+ archive_uri=archive_uri or "",
+ strict_extract_errors=strict_extract_errors,
+ )
+ else:
+ train_result = {
+ "case_count": len(result.cases),
+ "submitted": 0,
+ "reason": (
+ "agent_evolution_disabled"
+ if not agent_evolution_enabled
+ else "memory_types_filtered"
+ ),
+ }
await self._write_final_memory_diff(
archive_uri=archive_uri or "",
ctx=ctx,
@@ -349,6 +396,8 @@ class SessionCompressorV3:
session_id: Optional[str],
archive_uri: str,
strict_extract_errors: bool,
+ agent_evolution_enabled: bool,
+ allowed_memory_types: Optional[set[str]],
) -> dict[str, Any]:
if ctx is None:
logger.warning("No RequestContext provided, skipping training case fast path")
@@ -360,16 +409,25 @@ class SessionCompressorV3:
)
case_result = _applied_memory_result(case_write)
contexts = _contexts_from_update_result(case_result)
- train_result = await self.train_from_extracted_cases(
- cases=[case],
- messages=_training_messages_after_case_spec(messages),
- ctx=ctx,
- case_uri_by_name={case.name: _first_context_uri(contexts)},
- session_id=session_id,
- archive_uri=archive_uri,
- strict_extract_errors=strict_extract_errors,
- collect_memory_diff=True,
- )
+ agent_memory_types = _allowed_agent_memory_types(allowed_memory_types)
+ if agent_evolution_enabled and _TRAJECTORIES_MEMORY_TYPE in agent_memory_types:
+ train_result = await self.train_from_extracted_cases(
+ cases=[case],
+ messages=_training_messages_after_case_spec(messages),
+ ctx=ctx,
+ case_uri_by_name={case.name: _first_context_uri(contexts)},
+ session_id=session_id,
+ archive_uri=archive_uri,
+ strict_extract_errors=strict_extract_errors,
+ collect_memory_diff=True,
+ allowed_memory_types=agent_memory_types,
+ )
+ else:
+ train_result = {
+ "case_count": 1,
+ "submitted": 0,
+ "reason": "agent_evolution_disabled",
+ }
await self._write_final_memory_diff(
archive_uri=archive_uri,
ctx=ctx,
@@ -487,7 +545,10 @@ class SessionCompressorV3:
registry = create_default_registry()
if allow_self_memory:
- await registry.initialize_memory_files(ctx)
+ await registry.initialize_memory_files(
+ ctx,
+ allowed_memory_types=allowed_memory_types,
+ )
extract_context = ExtractContext(messages)
isolation_handler = MemoryIsolationHandler(
@@ -568,6 +629,131 @@ class SessionCompressorV3:
case_uri_by_name=_case_uri_by_name(canonical_cases, patch_operations, result),
)
+ def _session_skill_extraction_enabled(self) -> bool:
+ config = get_openviking_config()
+ return bool(
+ config.memory.session_skill_extraction_enabled and self.skill_processor is not None
+ )
+
+ async def extract_session_skills(
+ self,
+ *,
+ messages: list[Message],
+ ctx: Optional[RequestContext],
+ archive_uri: str = "",
+ strict_extract_errors: bool = False,
+ ) -> dict[str, Any]:
+ """Extract reusable skills without producing Agent Evolution memories."""
+ if not messages or ctx is None:
+ return {"case_count": 0, "submitted": 0, "reason": "missing_messages_or_ctx"}
+ if not self._session_skill_extraction_enabled():
+ return {"case_count": 0, "submitted": 0, "reason": "session_skills_disabled"}
+
+ extract = getattr(self.rollout_analyzer, "extract_trajectory_memories", None)
+ if not callable(extract):
+ return {
+ "case_count": 0,
+ "submitted": 0,
+ "reason": "session_skill_extractor_unavailable",
+ }
+
+ try:
+ result = await extract(
+ messages=list(messages),
+ ctx=ctx,
+ strict_extract_errors=strict_extract_errors,
+ include_trajectories=False,
+ include_session_skills=True,
+ source_archive_uri=archive_uri,
+ )
+ skill_gradients = [
+ gradient
+ for gradient in list((result or {}).get("skill_gradients", []))
+ if _gradient_memory_type(gradient) == "skills"
+ ]
+ if not skill_gradients:
+ return {
+ "case_count": 0,
+ "submitted": 0,
+ "skill_submitted": 0,
+ "skill_uris": [],
+ }
+
+ viking_fs = get_viking_fs()
+ skill_trainer = await self._get_session_skill_trainer(
+ viking_fs=viking_fs,
+ ctx=ctx,
+ messages=messages,
+ strict_extract_errors=strict_extract_errors,
+ archive_uri=archive_uri,
+ )
+ training_result = await skill_trainer.submit_gradients(skill_gradients)
+ apply_result = getattr(training_result, "apply_result", None)
+ skill_uris = [
+ str(uri) for uri in list(getattr(apply_result, "written_uris", []) or []) if uri
+ ]
+ return {
+ "case_count": 0,
+ "submitted": 0,
+ "skill_submitted": 1,
+ "skill_uris": skill_uris,
+ }
+ except Exception as exc:
+ logger.warning("Session skill extraction failed: %s", exc, exc_info=True)
+ if strict_extract_errors:
+ raise
+ return {"case_count": 0, "submitted": 0, "error": str(exc)}
+
+ async def _get_session_skill_trainer(
+ self,
+ *,
+ viking_fs: Any,
+ ctx: RequestContext,
+ messages: list[Message],
+ strict_extract_errors: bool,
+ archive_uri: str,
+ ) -> Any:
+ skill_root_uri = _skill_root_uri(ctx)
+ skill_policy_set = await SkillSetLoader(viking_fs=viking_fs).load(
+ skill_root_uri,
+ ctx=ctx,
+ )
+ analysis_context = TrajectoryAnalyzerContext(
+ request_context=ctx,
+ strict_extract_errors=strict_extract_errors,
+ include_session_skills=True,
+ source_archive_uri=archive_uri,
+ )
+ return await get_streaming_policy_trainer(
+ key=_skill_trainer_key(ctx),
+ policy_set=skill_policy_set,
+ rollout_analyzer=self.rollout_analyzer,
+ gradient_estimator=_NoopGradientEstimator(),
+ policy_optimizer=PatchMergePolicyOptimizer(
+ viking_fs=viking_fs,
+ memory_type="skills",
+ ),
+ policy_updater=SkillPolicyUpdater(
+ skill_processor=self.skill_processor,
+ viking_fs=viking_fs,
+ vikingdb=self.vikingdb,
+ memory_type="skills",
+ ),
+ context=PipelineContext(
+ analysis_context=analysis_context,
+ gradient_context=ExperienceGradientContext(
+ request_context=ctx,
+ messages=list(messages),
+ strict_extract_errors=strict_extract_errors,
+ ),
+ optimization_context=PatchMergePolicyOptimizerContext(
+ request_context=ctx,
+ ),
+ apply_context=ctx,
+ ),
+ config=self.streaming_trainer_config,
+ )
+
@tracer("train.compressor_v3.train_from_extracted_cases", ignore_result=True, ignore_args=True)
async def train_from_extracted_cases(
self,
@@ -580,6 +766,7 @@ class SessionCompressorV3:
archive_uri: str = "",
strict_extract_errors: bool = False,
collect_memory_diff: bool = False,
+ allowed_memory_types: Optional[set[str]] = None,
) -> dict[str, Any]:
if not messages or ctx is None:
return {"case_count": 0, "submitted": 0, "reason": "missing_messages_or_ctx"}
@@ -587,10 +774,16 @@ class SessionCompressorV3:
tracer.info("No commit training case memories extracted; skipping streaming train")
return {"case_count": 0, "submitted": 0}
- config = get_openviking_config()
- skill_enabled = (
- config.memory.session_skill_extraction_enabled and self.skill_processor is not None
- )
+ agent_memory_types = _allowed_agent_memory_types(allowed_memory_types)
+ if _TRAJECTORIES_MEMORY_TYPE not in agent_memory_types:
+ return {
+ "case_count": len(cases),
+ "submitted": 0,
+ "reason": "memory_types_filtered",
+ }
+ experiences_allowed = _EXPERIENCES_MEMORY_TYPE in agent_memory_types
+
+ skill_enabled = self._session_skill_extraction_enabled()
try:
viking_fs = get_viking_fs()
@@ -640,33 +833,12 @@ class SessionCompressorV3:
# --- Skill streaming trainer ---
skill_trainer = None
if skill_enabled:
- skill_root_uri = _skill_root_uri(ctx)
- skill_policy_set = await SkillSetLoader(viking_fs=viking_fs).load(
- skill_root_uri,
+ skill_trainer = await self._get_session_skill_trainer(
+ viking_fs=viking_fs,
ctx=ctx,
- )
- skill_trainer = await get_streaming_policy_trainer(
- key=_skill_trainer_key(ctx),
- policy_set=skill_policy_set,
- rollout_analyzer=self.rollout_analyzer,
- gradient_estimator=_NoopGradientEstimator(),
- policy_optimizer=PatchMergePolicyOptimizer(
- viking_fs=viking_fs,
- memory_type="skills",
- ),
- policy_updater=SkillPolicyUpdater(
- skill_processor=self.skill_processor,
- viking_fs=viking_fs,
- vikingdb=self.vikingdb,
- memory_type="skills",
- ),
- context=PipelineContext(
- analysis_context=analysis_context,
- gradient_context=gradient_context,
- optimization_context=optimizer_context,
- apply_context=ctx,
- ),
- config=self.streaming_trainer_config,
+ messages=messages,
+ strict_extract_errors=strict_extract_errors,
+ archive_uri=archive_uri,
)
submitted = 0
@@ -692,9 +864,11 @@ class SessionCompressorV3:
analysis = await self.rollout_analyzer.analyze(rollout, analysis_context)
# Experience path: estimate gradients, then submit to exp trainer
- exp_gradients = await ExperienceGradientEstimator(
- viking_fs=viking_fs,
- ).estimate(analysis, exp_trainer.policy_set, gradient_context)
+ exp_gradients = []
+ if experiences_allowed:
+ exp_gradients = await ExperienceGradientEstimator(
+ viking_fs=viking_fs,
+ ).estimate(analysis, exp_trainer.policy_set, gradient_context)
exp_training_result = _trajectory_only_training_result(
analysis=analysis,
rollout=rollout,
@@ -969,6 +1143,8 @@ def _training_case_from_first_message(
"""
if not messages or allowed_memory_types is None:
return None
+ if not {_CASES_MEMORY_TYPE, _TRAJECTORIES_MEMORY_TYPE}.issubset(allowed_memory_types):
+ return None
if not set(allowed_memory_types).issubset(_TRAINING_FAST_PATH_MEMORY_TYPES):
return None
@@ -978,6 +1154,12 @@ def _training_case_from_first_message(
return _case_from_payload(payload)
+def _allowed_agent_memory_types(allowed_memory_types: Optional[set[str]]) -> set[str]:
+ if allowed_memory_types is None:
+ return set(_AGENT_MEMORY_TYPES)
+ return set(allowed_memory_types) & _AGENT_MEMORY_TYPES
+
+
def _training_case_spec_payload_from_message(message: Message) -> dict[str, Any] | None:
text = _message_text(message).strip()
if not text.startswith(_TRAINING_CASE_SPEC_HEADER):
@@ -1127,7 +1309,6 @@ def _case_evidence(case: Case) -> str:
return "Structured batch training CaseSpec supplied by the training pipeline."
-
async def _canonical_cases_from_update_result(
*,
operations: ResolvedOperations,
diff --git a/openviking/session/memory/constants.py b/openviking/session/memory/constants.py
index b8959de95..b5c60dca2 100644
--- a/openviking/session/memory/constants.py
+++ b/openviking/session/memory/constants.py
@@ -1,6 +1,8 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+CASE_MEMORY_TYPE = "cases"
TRAJECTORY_MEMORY_TYPE = "trajectories"
EXPERIENCE_MEMORY_TYPE = "experiences"
EXECUTION_MEMORY_TYPES = frozenset({TRAJECTORY_MEMORY_TYPE, EXPERIENCE_MEMORY_TYPE})
+AGENT_EVOLUTION_MEMORY_TYPES = frozenset({CASE_MEMORY_TYPE, *EXECUTION_MEMORY_TYPES})
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 63ea40fac..b28a8745e 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -20,7 +20,10 @@ from openviking.message.part import ContextPart, TextPart, ToolPart
from openviking.pyagfs.exceptions import AGFSClientError, AGFSHTTPError, AGFSNotFoundError
from openviking.server.config import ToolOutputExternalizationConfig
from openviking.server.identity import RequestContext, Role
-from openviking.session.memory.constants import EXECUTION_MEMORY_TYPES
+from openviking.session.memory.constants import (
+ AGENT_EVOLUTION_MEMORY_TYPES,
+ EXECUTION_MEMORY_TYPES,
+)
from openviking.session.memory_policy import MemoryPolicy
from openviking.session.retention import (
RETENTION_MODE_TURN_BUDGET,
@@ -46,7 +49,10 @@ from openviking.telemetry.request_wait_tracker import get_request_wait_tracker
from openviking.utils.model_retry import is_retryable_api_error, retry_async
from openviking.utils.time_utils import get_current_timestamp
from openviking.utils.token_estimation import estimate_text_tokens, truncate_text_to_token_budget
-from openviking_cli.exceptions import FailedPreconditionError, NotFoundError
+from openviking_cli.exceptions import (
+ FailedPreconditionError,
+ NotFoundError,
+)
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import get_logger, run_async
from openviking_cli.utils.config import get_openviking_config
@@ -65,6 +71,7 @@ _PHASE2_QUEUE_WAIT_TIMEOUT_SECONDS = 1800.0
_MEMORY_EXTRACTION_MAX_RETRIES = 3
_MEMORY_EXTRACTION_RETRY_BASE_DELAY_SECONDS = 1.0
_MEMORY_EXTRACTION_RETRY_MAX_DELAY_SECONDS = 8.0
+_AGENT_TRAINING_REQUIRED_MEMORY_TYPES = frozenset({"cases", "trajectories"})
_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS = 30.0
_MEMORY_STEP_NAMES = ("long_term", "execution")
@@ -102,6 +109,46 @@ def _validate_memory_policy_types(policy: MemoryPolicy) -> None:
policy.validate_memory_types(_enabled_memory_types())
+def _apply_agent_evolution_setting(
+ policy: MemoryPolicy,
+ *,
+ agent_evolution_enabled: bool,
+) -> MemoryPolicy:
+ if agent_evolution_enabled:
+ return policy
+ effective_types = (
+ _enabled_memory_types() if policy.memory_types is None else set(policy.memory_types)
+ )
+ effective_types -= AGENT_EVOLUTION_MEMORY_TYPES
+ return MemoryPolicy(
+ self_enabled=policy.self_enabled,
+ peer_enabled=policy.peer_enabled,
+ memory_types=effective_types,
+ working_memory_enabled=policy.working_memory_enabled,
+ )
+
+
+def _effective_memory_types(policy: MemoryPolicy) -> set[str]:
+ if policy.memory_types is None:
+ return _enabled_memory_types()
+ return set(policy.memory_types)
+
+
+def _agent_memory_skip_reason(
+ *,
+ agent_evolution_enabled: bool,
+ effective_memory_types: set[str],
+ user_config_error: Optional[str] = None,
+) -> Optional[str]:
+ if user_config_error:
+ return "invalid_user_config"
+ if not agent_evolution_enabled:
+ return "agent_evolution_disabled"
+ if not _AGENT_TRAINING_REQUIRED_MEMORY_TYPES.issubset(effective_memory_types):
+ return "memory_types_filtered"
+ return None
+
+
def _split_policy_memory_types(
memory_types: Optional[set[str]],
) -> tuple[Optional[set[str]], Optional[set[str]]]:
@@ -495,6 +542,7 @@ class Session:
session_uri: Optional[str] = None,
auto_commit_threshold: int = 8000,
tool_output_externalization_config: Optional[ToolOutputExternalizationConfig] = None,
+ agent_evolution_enabled: bool = True,
usage_reporter: Optional["UsageReporter"] = None,
):
self._viking_fs = viking_fs
@@ -526,6 +574,7 @@ class Session:
if tool_output_externalization_config is not None
else ToolOutputExternalizationConfig()
)
+ self._agent_evolution_enabled = agent_evolution_enabled
self._usage_reporter = usage_reporter
logger.info(f"Session created: {self.session_id} for user {self.user}")
@@ -1426,6 +1475,8 @@ class Session:
keep_recent_turn_count: int,
retained_message_token_budget: int,
min_raw_tail_steps: int,
+ agent_evolution_enabled: bool = True,
+ agent_memory_skip_reason: Optional[str] = None,
) -> None:
"""Persist the Phase 1 intent before any destructive root rewrite."""
payload = {
@@ -1442,7 +1493,16 @@ class Session:
"retained_message_token_budget": retained_message_token_budget,
"min_raw_tail_steps": min_raw_tail_steps,
}
- await self._merge_archive_meta(archive_uri, {"phase1": payload})
+ await self._merge_archive_meta(
+ archive_uri,
+ {
+ "phase1": payload,
+ "agent_evolution": {
+ "enabled": agent_evolution_enabled,
+ "skip_reason": agent_memory_skip_reason,
+ },
+ },
+ )
async def _write_phase1_ready_marker(self, archive_uri: str) -> None:
phase1 = await self._read_phase1_meta(archive_uri)
@@ -1650,7 +1710,17 @@ class Session:
memory_policy if memory_policy is not None else self._meta.memory_policy
)
_validate_memory_policy_types(effective_policy)
+ agent_evolution_enabled = self._agent_evolution_enabled
+ effective_policy = _apply_agent_evolution_setting(
+ effective_policy,
+ agent_evolution_enabled=agent_evolution_enabled,
+ )
effective_memory_policy = effective_policy.to_dict()
+ effective_memory_types = sorted(_effective_memory_types(effective_policy))
+ agent_memory_skip_reason = _agent_memory_skip_reason(
+ agent_evolution_enabled=agent_evolution_enabled,
+ effective_memory_types=set(effective_memory_types),
+ )
logger.info(
f"[TRACER] session_commit started, trace_id={trace_id}, "
f"keep_recent_count={keep_recent_count}, retention_mode={retention_mode}, "
@@ -1695,7 +1765,16 @@ class Session:
if memory_policy is None:
effective_policy = MemoryPolicy.from_dict(self._meta.memory_policy)
_validate_memory_policy_types(effective_policy)
+ effective_policy = _apply_agent_evolution_setting(
+ effective_policy,
+ agent_evolution_enabled=agent_evolution_enabled,
+ )
effective_memory_policy = effective_policy.to_dict()
+ effective_memory_types = sorted(_effective_memory_types(effective_policy))
+ agent_memory_skip_reason = _agent_memory_skip_reason(
+ agent_evolution_enabled=agent_evolution_enabled,
+ effective_memory_types=set(effective_memory_types),
+ )
archive_refs = await self._list_archive_refs()
self._compression.compression_index = max(
@@ -1810,6 +1889,8 @@ class Session:
keep_recent_turn_count=effective_keep_turns if turn_mode else 0,
retained_message_token_budget=effective_token_budget if turn_mode else 0,
min_raw_tail_steps=effective_min_tail,
+ agent_evolution_enabled=agent_evolution_enabled,
+ agent_memory_skip_reason=agent_memory_skip_reason,
)
# Archive raw remains durable and recoverable before any live
@@ -2003,6 +2084,40 @@ class Session:
)
return
+ queued_policy = MemoryPolicy.from_dict(msg.memory_policy)
+ archive_meta = await self._read_archive_meta(msg.archive_uri)
+ agent_evolution_snapshot = archive_meta.get("agent_evolution")
+ if not isinstance(agent_evolution_snapshot, dict):
+ # Compatibility with jobs created by pre-merge development builds
+ # that temporarily stored this snapshot in the queue payload.
+ phase1 = archive_meta.get("phase1")
+ queue_snapshot = phase1.get("queue_message") if isinstance(phase1, dict) else None
+ agent_evolution_snapshot = (
+ queue_snapshot if isinstance(queue_snapshot, dict) else {}
+ )
+
+ snapshot_enabled = agent_evolution_snapshot.get("enabled")
+ if snapshot_enabled is None:
+ snapshot_enabled = agent_evolution_snapshot.get("agent_evolution_enabled")
+ # Archives created before this setting existed preserve their original
+ # behavior, where Agent memory extraction was enabled by default.
+ agent_evolution_enabled = (
+ snapshot_enabled if isinstance(snapshot_enabled, bool) else True
+ )
+ agent_memory_skip_reason = agent_evolution_snapshot.get("skip_reason")
+ if agent_memory_skip_reason is None:
+ agent_memory_skip_reason = agent_evolution_snapshot.get(
+ "agent_memory_skip_reason"
+ )
+ if agent_memory_skip_reason is None:
+ agent_memory_skip_reason = _agent_memory_skip_reason(
+ agent_evolution_enabled=agent_evolution_enabled,
+ effective_memory_types=_effective_memory_types(queued_policy),
+ )
+ user_config_error = agent_evolution_snapshot.get("user_config_error")
+ if user_config_error is not None:
+ user_config_error = str(user_config_error)
+
await self._run_memory_extraction(
task_id=msg.task_id,
archive_uri=msg.archive_uri,
@@ -2011,6 +2126,9 @@ class Session:
first_message_id=archive_messages[0].id,
last_message_id=archive_messages[-1].id,
memory_policy=msg.memory_policy,
+ agent_evolution_enabled=agent_evolution_enabled,
+ agent_memory_skip_reason=agent_memory_skip_reason,
+ user_config_error=user_config_error,
)
async def _run_usage_reporting(
@@ -2045,6 +2163,9 @@ class Session:
first_message_id: str,
last_message_id: str,
memory_policy: Optional[Dict[str, Any]],
+ agent_evolution_enabled: bool = True,
+ agent_memory_skip_reason: Optional[str] = None,
+ user_config_error: Optional[str] = None,
) -> None:
"""Phase 2: Extract memories, write relations, enqueue — runs in background."""
from openviking.service.task_tracker import get_task_tracker
@@ -2225,9 +2346,16 @@ class Session:
allowed_peer_ids = extraction_scope.allowed_peer_ids
session_skill_extraction_enabled = extraction_scope.include_session_skills
memory_type_filter = extraction_scope.memory_types
- long_term_memory_types, execution_memory_types = _split_policy_memory_types(
- memory_type_filter
+ has_execution_memory = hasattr(
+ self._session_compressor, "extract_execution_memories"
)
+ if has_execution_memory:
+ long_term_memory_types, execution_memory_types = _split_policy_memory_types(
+ memory_type_filter
+ )
+ else:
+ long_term_memory_types = memory_type_filter
+ execution_memory_types = set()
long_term_messages = [
message
@@ -2262,10 +2390,6 @@ class Session:
len(messages),
)
- has_execution_memory = hasattr(
- self._session_compressor, "extract_execution_memories"
- )
-
extraction_tasks: List[Any] = []
extraction_labels: List[str] = []
if working_memory_enabled:
@@ -2290,6 +2414,7 @@ class Session:
latest_archive_overview=latest_archive_overview,
archive_uri=archive_uri,
allowed_memory_types=long_term_memory_types,
+ agent_evolution_enabled=agent_evolution_enabled,
allow_self_memory=self_memory_enabled,
allowed_peer_ids=allowed_peer_ids,
)
@@ -2483,6 +2608,11 @@ class Session:
],
"usage_events_extracted": usage_events_extracted,
"active_count_updated": active_count_updated,
+ "effective_memory_types": sorted(
+ _effective_memory_types(MemoryPolicy.from_dict(memory_policy))
+ ),
+ "agent_evolution_enabled": agent_evolution_enabled,
+ "agent_memory_skip_reason": agent_memory_skip_reason,
"token_usage": {
"llm": dict(self._meta.llm_token_usage),
"embedding": dict(self._meta.embedding_token_usage),
@@ -2496,6 +2626,8 @@ class Session:
}
if memory_diff_uri:
result_payload["memory_diff_uri"] = memory_diff_uri
+ if user_config_error:
+ result_payload["user_config_error"] = user_config_error
await tracker.complete(
task_id,
diff --git a/openviking/session/train/components/trajectory_analyzer.py b/openviking/session/train/components/trajectory_analyzer.py
index 50631837d..3f2252a13 100644
--- a/openviking/session/train/components/trajectory_analyzer.py
+++ b/openviking/session/train/components/trajectory_analyzer.py
@@ -139,17 +139,20 @@ class TrajectoryRolloutAnalyzer:
ctx: RequestContext | None,
strict_extract_errors: bool = False,
latest_archive_overview: str = "",
+ include_trajectories: bool = True,
include_session_skills: bool = False,
case_name: str = "",
source_archive_uri: str = "",
) -> dict[str, list[Any]]:
- """Extract and persist trajectory memories from rollout messages.
+ """Extract trajectory and/or reusable skill operations from rollout messages.
When ``include_session_skills`` is True, session skill patches are
co-extracted in the same ExtractLoop pass and returned as
``PatchSemanticGradient`` instances in the ``"skill_gradients"`` key.
Skill patches are *not* applied to disk by this method — they are
- returned as gradient signals for downstream policy training.
+ returned as gradient signals for downstream policy training. Setting
+ ``include_trajectories`` to False keeps the pass skill-only and prevents
+ trajectory operations from being persisted.
"""
empty_result: dict[str, list[Any]] = {"contexts": [], "skill_gradients": []}
if not messages or ctx is None:
@@ -158,7 +161,7 @@ class TrajectoryRolloutAnalyzer:
provider = AgentTrajectoryContextProvider(
messages=messages,
latest_archive_overview=latest_archive_overview,
- include_trajectories=True,
+ include_trajectories=include_trajectories,
include_session_skills=include_session_skills,
)
phase_result = await self._run_trajectory_extract_phase(
@@ -166,6 +169,7 @@ class TrajectoryRolloutAnalyzer:
messages=messages,
ctx=ctx,
strict_extract_errors=strict_extract_errors,
+ include_trajectories=include_trajectories,
include_session_skills=include_session_skills,
case_name=case_name,
source_archive_uri=source_archive_uri,
@@ -183,6 +187,7 @@ class TrajectoryRolloutAnalyzer:
messages: list[Message],
ctx: RequestContext,
strict_extract_errors: bool,
+ include_trajectories: bool = True,
include_session_skills: bool = False,
case_name: str = "",
source_archive_uri: str = "",
@@ -194,7 +199,9 @@ class TrajectoryRolloutAnalyzer:
raise RuntimeError("VikingFS is required to extract trajectory memories")
extract_context = provider.get_extract_context()
- allowed_types: set[str] = {_TRAJECTORY_MEMORY_TYPE}
+ allowed_types: set[str] = set()
+ if include_trajectories:
+ allowed_types.add(_TRAJECTORY_MEMORY_TYPE)
if include_session_skills:
allowed_types.add(SESSION_SKILL_MEMORY_TYPE)
isolation_handler = MemoryIsolationHandler(
@@ -242,13 +249,15 @@ class TrajectoryRolloutAnalyzer:
_ensure_trajectory_case_name(traj_ops, case_name=case_name)
_apply_trajectory_source_archive_uri(traj_ops, source_archive_uri)
- memory_result = await self._apply_trajectory_operations(
- operations=traj_ops,
- provider=provider,
- ctx=ctx,
- extract_context=extract_context,
- isolation_handler=isolation_handler,
- )
+ memory_result = MemoryUpdateResult()
+ if include_trajectories:
+ memory_result = await self._apply_trajectory_operations(
+ operations=traj_ops,
+ provider=provider,
+ ctx=ctx,
+ extract_context=extract_context,
+ isolation_handler=isolation_handler,
+ )
tracer.info(
"[trajectory] Applied memory ops: "
f"written={len(memory_result.written_uris)}, "
diff --git a/openviking/storage/queuefs/session_commit_msg.py b/openviking/storage/queuefs/session_commit_msg.py
index 7f6ba0da1..8d223b775 100644
--- a/openviking/storage/queuefs/session_commit_msg.py
+++ b/openviking/storage/queuefs/session_commit_msg.py
@@ -2,7 +2,7 @@
# SPDX-License-Identifier: AGPL-3.0
"""Persistent Session Phase 2 queue message."""
-from dataclasses import asdict, dataclass, field
+from dataclasses import asdict, dataclass, field, fields
from typing import Any, Dict, List, Optional
@@ -19,3 +19,11 @@ class SessionCommitMsg:
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
+
+ @classmethod
+ def from_dict(cls, payload: Dict[str, Any]) -> "SessionCommitMsg":
+ """Load a queue message while ignoring fields from newer producers."""
+ if not isinstance(payload, dict):
+ raise ValueError("session commit queue payload must be an object")
+ known_fields = {item.name for item in fields(cls)}
+ return cls(**{key: value for key, value in payload.items() if key in known_fields})
diff --git a/openviking/storage/queuefs/session_commit_processor.py b/openviking/storage/queuefs/session_commit_processor.py
index 6b370cd38..03b98dc42 100644
--- a/openviking/storage/queuefs/session_commit_processor.py
+++ b/openviking/storage/queuefs/session_commit_processor.py
@@ -82,7 +82,7 @@ class SessionCommitProcessor(DequeueHandlerBase):
payload = data.get("data", data)
if isinstance(payload, str):
payload = json.loads(payload)
- msg = SessionCommitMsg(**payload)
+ msg = SessionCommitMsg.from_dict(payload)
ctx = RequestContext(
user=UserIdentifier.from_dict(msg.user),
role=Role.USER,
diff --git a/openviking/usage_reporter/__init__.py b/openviking/usage_reporter/__init__.py
index 7382cbbb4..d38f5d585 100644
--- a/openviking/usage_reporter/__init__.py
+++ b/openviking/usage_reporter/__init__.py
@@ -3,12 +3,14 @@
"""Usage reporting extension points for OpenViking."""
from .extractors import MemoryUsageExtractor, UsageExtractor
+from .http_sink import HttpUsageSink
from .models import UsageContext, UsageEvent
from .reporter import UsageReporter
from .sinks import UsageSink
__all__ = [
"MemoryUsageExtractor",
+ "HttpUsageSink",
"UsageContext",
"UsageEvent",
"UsageExtractor",
diff --git a/openviking/usage_reporter/config.py b/openviking/usage_reporter/config.py
index f1ea78cdc..f6d0ecf05 100644
--- a/openviking/usage_reporter/config.py
+++ b/openviking/usage_reporter/config.py
@@ -10,6 +10,7 @@ from typing import Any
from openviking.server.config import UsageReporterConfig, UsageReporterSinkConfig
from .extractors import MemoryUsageExtractor
+from .http_sink import HttpUsageSink
from .reporter import UsageReporter
from .sinks import UsageSink
@@ -24,6 +25,9 @@ def _load_class(class_path: str) -> type:
def _build_sink(config: UsageReporterSinkConfig) -> UsageSink:
+ if config.type == "http":
+ return HttpUsageSink(**dict(config.config))
+
if config.type == "custom":
if not config.class_path:
raise ValueError("custom usage sink requires class_path")
diff --git a/openviking/usage_reporter/http_sink.py b/openviking/usage_reporter/http_sink.py
new file mode 100644
index 000000000..ead3e0c85
--- /dev/null
+++ b/openviking/usage_reporter/http_sink.py
@@ -0,0 +1,524 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Durable HTTP usage event sink."""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import logging
+import os
+import random
+import threading
+import time
+import urllib.error
+import urllib.request
+from collections.abc import Iterator
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ from .models import UsageEvent
+
+logger = logging.getLogger(__name__)
+
+_COUNT_NAMES = {
+ "memory.recalled": "experience.recall.count",
+ "memory.injected": "experience.inject.count",
+}
+
+
+def _timestamp_millis(value: str) -> int:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return int(parsed.timestamp() * 1000)
+
+
+def _to_count_record(event: UsageEvent) -> dict[str, Any]:
+ record = event.to_dict()
+ event_type = str(record.get("event_type") or "")
+ try:
+ count_name = _COUNT_NAMES[event_type]
+ except KeyError as exc:
+ raise ValueError(f"unsupported usage event type: {event_type}") from exc
+
+ evidence = record.get("evidence")
+ evidence = evidence if isinstance(evidence, dict) else {}
+ attributes = record.get("attributes")
+ attributes = attributes if isinstance(attributes, dict) else {}
+
+ extra = {key: value for key, value in evidence.items() if value not in (None, "")}
+ session_id = str(record.get("session_id") or "")
+ if session_id:
+ extra["session_id"] = session_id
+ task_id = record.get("task_id")
+ if task_id not in (None, ""):
+ extra["task_id"] = task_id
+ if attributes:
+ extra["attributes"] = attributes
+
+ return {
+ "CountName": count_name,
+ "OpType": "add",
+ "amount": 1.0,
+ "timestamp": _timestamp_millis(str(record.get("occurred_at") or "")),
+ "uniqueId": str(record.get("event_id") or ""),
+ "tags": {
+ "account_id": str(record.get("account_id") or ""),
+ "user_id": str(record.get("user_id") or ""),
+ "resource_uri": str(record.get("resource_uri") or ""),
+ "resource_type": str(record.get("resource_type") or ""),
+ },
+ "extra": extra,
+ }
+
+
+class HttpUsageSink:
+ """Persist usage events before delivering them to an HTTP collector."""
+
+ def __init__(
+ self,
+ *,
+ endpoint: str,
+ resource_id_env: str = "OV_RESOURCE_ID",
+ outbox_dir: str | os.PathLike[str] | None = None,
+ request_timeout_seconds: float = 10.0,
+ inflight_lease_seconds: float = 60.0,
+ retry_base_seconds: float = 1.0,
+ retry_max_seconds: float = 300.0,
+ max_batch_bytes: int = 1024 * 1024,
+ max_outbox_bytes: int = 256 * 1024 * 1024,
+ ) -> None:
+ self._endpoint = endpoint.strip()
+ self._resource_id = os.environ.get(resource_id_env, "").strip()
+ if not self._endpoint:
+ raise ValueError("endpoint is required")
+ if not self._resource_id:
+ raise ValueError(f"{resource_id_env} is required")
+ self._outbox_scope = hashlib.sha256(
+ f"{self._endpoint}\0{self._resource_id}".encode("utf-8")
+ ).hexdigest()[:24]
+
+ self._outbox_dir = (
+ Path(outbox_dir)
+ if outbox_dir is not None
+ else Path.home() / ".openviking" / "data" / ".usage_outbox"
+ )
+ self._pending_dir = self._outbox_dir / "pending"
+ self._inflight_dir = self._outbox_dir / "inflight"
+ self._dead_letter_dir = self._outbox_dir / "dead_letter"
+ self._metadata_dir = self._outbox_dir / "metadata"
+ for directory in (
+ self._pending_dir,
+ self._inflight_dir,
+ self._dead_letter_dir,
+ self._metadata_dir,
+ ):
+ directory.mkdir(parents=True, exist_ok=True)
+
+ self._request_timeout_seconds = float(request_timeout_seconds)
+ self._inflight_lease_seconds = float(inflight_lease_seconds)
+ self._retry_base_seconds = float(retry_base_seconds)
+ self._retry_max_seconds = float(retry_max_seconds)
+ self._max_batch_bytes = int(max_batch_bytes)
+ self._max_outbox_bytes = int(max_outbox_bytes)
+ if self._request_timeout_seconds <= 0:
+ raise ValueError("request_timeout_seconds must be positive")
+ if self._inflight_lease_seconds <= 0:
+ raise ValueError("inflight_lease_seconds must be positive")
+ if self._inflight_lease_seconds <= self._request_timeout_seconds:
+ raise ValueError("inflight_lease_seconds must be greater than request_timeout_seconds")
+ if self._retry_base_seconds < 0:
+ raise ValueError("retry_base_seconds must be non-negative")
+ if self._retry_max_seconds < 0:
+ raise ValueError("retry_max_seconds must be non-negative")
+ if self._max_batch_bytes <= 0:
+ raise ValueError("max_batch_bytes must be positive")
+ if self._max_outbox_bytes <= 0:
+ raise ValueError("max_outbox_bytes must be positive")
+ self._outbox_lock = threading.Lock()
+ self._wake_event = threading.Event()
+ self._stop_event = threading.Event()
+ self._worker: threading.Thread | None = None
+ self._start_worker()
+
+ async def write(self, *, events: list[UsageEvent]) -> None:
+ if not events:
+ return
+ await asyncio.to_thread(self._persist_events, events)
+
+ def close(self) -> None:
+ self._stop_event.set()
+ self._wake_event.set()
+ if self._worker is not None:
+ self._worker.join(timeout=self._request_timeout_seconds + 1)
+
+ def _persist_events(self, events: list[UsageEvent]) -> None:
+ records: list[dict[str, Any]] = []
+ for event in events:
+ event_id = str(event.to_dict().get("event_id") or "").strip()
+ if not event_id:
+ raise ValueError("event_id is required")
+ records.append(_to_count_record(event))
+
+ batch: list[dict[str, Any]] = []
+ for record in records:
+ candidate = [*batch, record]
+ if batch and (
+ len(candidate) > 100
+ or self._encoded_payload_size(candidate) > self._max_batch_bytes
+ ):
+ self._persist_batch(batch)
+ batch = [record]
+ else:
+ batch = candidate
+ if batch:
+ self._persist_batch(batch)
+ self._wake_event.set()
+
+ def _persist_batch(self, events: list[dict[str, Any]]) -> bool:
+ return self._persist_batches([events])
+
+ def _persist_batches(
+ self,
+ event_batches: list[list[dict[str, Any]]],
+ *,
+ replace_path: Path | None = None,
+ ) -> bool:
+ encoded_batches: list[tuple[dict[str, Any], bytes, Path, Path]] = []
+ for index, events in enumerate(event_batches):
+ payload = self._build_payload(events)
+ encoded = json.dumps(
+ payload,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ file_stem = f"{self._outbox_scope}_{time.time_ns()}_{index}_{payload['batch_id']}"
+ encoded_batches.append(
+ (
+ payload,
+ encoded,
+ self._pending_dir / f".{file_stem}.tmp",
+ self._pending_dir / f"{file_stem}.json",
+ )
+ )
+
+ incoming_bytes = sum(len(encoded) for _, encoded, _, _ in encoded_batches)
+ with self._outbox_lock:
+ reclaimable_bytes = 0
+ if replace_path is not None:
+ try:
+ reclaimable_bytes = replace_path.stat().st_size
+ except FileNotFoundError:
+ return False
+ if not self._ensure_outbox_capacity(
+ incoming_bytes,
+ reclaimable_bytes=reclaimable_bytes,
+ ):
+ batch_ids = [payload["batch_id"] for payload, _, _, _ in encoded_batches]
+ logger.warning(
+ "Dropping OpenViking usage batch because the outbox is full, "
+ "batch_ids=%s size=%s max_outbox_bytes=%s",
+ batch_ids,
+ incoming_bytes,
+ self._max_outbox_bytes,
+ )
+ return False
+ temporary_paths: list[Path] = []
+ try:
+ for _payload, encoded, temporary_path, pending_path in encoded_batches:
+ temporary_paths.append(temporary_path)
+ with temporary_path.open("wb") as output:
+ output.write(encoded)
+ output.flush()
+ os.fsync(output.fileno())
+ os.replace(temporary_path, pending_path)
+ self._fsync_directory(self._pending_dir)
+ if replace_path is not None:
+ replace_path.unlink()
+ self._fsync_directory(replace_path.parent)
+ finally:
+ for temporary_path in temporary_paths:
+ try:
+ temporary_path.unlink()
+ except FileNotFoundError:
+ pass
+ return True
+
+ def _ensure_outbox_capacity(
+ self,
+ incoming_bytes: int,
+ *,
+ reclaimable_bytes: int = 0,
+ ) -> bool:
+ if incoming_bytes > self._max_outbox_bytes:
+ return False
+
+ eviction_candidates: list[Path] = []
+ total_bytes = 0
+ for directory in (
+ self._dead_letter_dir,
+ self._pending_dir,
+ self._inflight_dir,
+ ):
+ for path in self._owned_batches(directory):
+ try:
+ total_bytes += path.stat().st_size
+ except FileNotFoundError:
+ continue
+ if directory != self._inflight_dir:
+ eviction_candidates.append(path)
+
+ effective_total_bytes = max(0, total_bytes - reclaimable_bytes)
+ if effective_total_bytes + incoming_bytes <= self._max_outbox_bytes:
+ return True
+
+ def _eviction_order(path: Path) -> tuple[int, int, str]:
+ try:
+ modified_at = path.stat().st_mtime_ns
+ except FileNotFoundError:
+ modified_at = 0
+ directory_priority = 0 if path.parent == self._dead_letter_dir else 1
+ return directory_priority, modified_at, path.name
+
+ for path in sorted(eviction_candidates, key=_eviction_order):
+ try:
+ size = path.stat().st_size
+ path.unlink()
+ except FileNotFoundError:
+ continue
+ effective_total_bytes -= size
+ logger.warning("Evicted OpenViking usage outbox batch: %s", path)
+ if effective_total_bytes + incoming_bytes <= self._max_outbox_bytes:
+ return True
+ return effective_total_bytes + incoming_bytes <= self._max_outbox_bytes
+
+ def _build_payload(self, events: list[dict[str, Any]]) -> dict[str, Any]:
+ unique_ids = "\n".join(str(event["uniqueId"]) for event in events)
+ batch_id = f"ub_{hashlib.sha256(unique_ids.encode('utf-8')).hexdigest()}"
+ created_at = (
+ datetime.now(timezone.utc)
+ .isoformat(timespec="milliseconds")
+ .replace(
+ "+00:00",
+ "Z",
+ )
+ )
+ return {
+ "schema_version": "v1",
+ "resource_id": self._resource_id,
+ "batch_id": batch_id,
+ "created_at": created_at,
+ "attempt": 0,
+ "next_retry_at": created_at,
+ "events": events,
+ }
+
+ def _encoded_payload_size(self, events: list[dict[str, Any]]) -> int:
+ return len(
+ json.dumps(
+ self._build_payload(events),
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ )
+
+ @staticmethod
+ def _fsync_directory(directory: Path) -> None:
+ if os.name == "nt":
+ return
+ descriptor = os.open(directory, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+
+ def _start_worker(self) -> None:
+ self._recover_stale_inflight()
+ with self._outbox_lock:
+ self._ensure_outbox_capacity(0)
+ self._worker = threading.Thread(
+ target=self._worker_loop,
+ name="openviking-usage-http-sink",
+ daemon=True,
+ )
+ self._worker.start()
+
+ def _worker_loop(self) -> None:
+ while not self._stop_event.is_set():
+ try:
+ self._recover_stale_inflight()
+ handled_batch = self._handle_next_batch()
+ except Exception:
+ logger.exception("OpenViking usage outbox worker failed")
+ handled_batch = False
+ if handled_batch:
+ continue
+ self._wake_event.wait(timeout=0.05)
+ self._wake_event.clear()
+
+ def _handle_next_batch(self) -> bool:
+ now = datetime.now(timezone.utc)
+ for pending_path in sorted(self._owned_batches(self._pending_dir)):
+ try:
+ payload = self._read_payload(pending_path)
+ except (OSError, ValueError, json.JSONDecodeError):
+ self._move_to_dead_letter(pending_path)
+ continue
+ next_retry_at = self._parse_datetime(str(payload.get("next_retry_at") or ""))
+ if next_retry_at is not None and next_retry_at > now:
+ continue
+
+ inflight_path = self._inflight_dir / pending_path.name
+ try:
+ os.replace(pending_path, inflight_path)
+ os.utime(inflight_path, None)
+ except FileNotFoundError:
+ continue
+
+ try:
+ status = self._post_payload(payload)
+ except Exception:
+ logger.exception(
+ "OpenViking usage delivery failed unexpectedly, batch_id=%s",
+ payload.get("batch_id"),
+ )
+ self._schedule_retry(inflight_path, payload)
+ return True
+ if 200 <= status < 300:
+ try:
+ inflight_path.unlink()
+ except FileNotFoundError:
+ pass
+ return True
+ if status == 413:
+ self._split_batch(inflight_path, payload)
+ return True
+ if status in (400, 422):
+ self._move_to_dead_letter(inflight_path)
+ return True
+
+ self._schedule_retry(inflight_path, payload)
+ return True
+ return False
+
+ def _split_batch(self, inflight_path: Path, payload: dict[str, Any]) -> None:
+ events = payload.get("events")
+ if not isinstance(events, list) or len(events) < 2:
+ self._move_to_dead_letter(inflight_path)
+ return
+ midpoint = len(events) // 2
+ if not self._persist_batches(
+ [events[:midpoint], events[midpoint:]],
+ replace_path=inflight_path,
+ ):
+ self._move_to_dead_letter(inflight_path)
+ self._wake_event.set()
+
+ def _post_payload(self, payload: dict[str, Any]) -> int:
+ request = urllib.request.Request(
+ self._endpoint,
+ data=json.dumps(
+ payload,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode("utf-8"),
+ headers={
+ "Content-Type": "application/json",
+ "V-Resource-Id": self._resource_id,
+ },
+ method="POST",
+ )
+ try:
+ with urllib.request.urlopen(
+ request,
+ timeout=self._request_timeout_seconds,
+ ) as response:
+ response.read()
+ return response.status
+ except urllib.error.HTTPError as error:
+ error.read()
+ return error.code
+ except (OSError, TimeoutError, urllib.error.URLError):
+ return 0
+
+ def _schedule_retry(self, inflight_path: Path, payload: dict[str, Any]) -> None:
+ attempt = int(payload.get("attempt") or 0) + 1
+ delay = min(
+ self._retry_max_seconds,
+ self._retry_base_seconds * (2 ** max(0, attempt - 1)),
+ )
+ if delay > 0:
+ delay *= random.uniform(0.8, 1.2)
+ payload["attempt"] = attempt
+ payload["next_retry_at"] = (
+ datetime.fromtimestamp(time.time() + delay, tz=timezone.utc)
+ .isoformat(timespec="milliseconds")
+ .replace("+00:00", "Z")
+ )
+ try:
+ self._replace_payload(inflight_path, payload)
+ os.replace(inflight_path, self._pending_dir / inflight_path.name)
+ except FileNotFoundError:
+ return
+ self._wake_event.set()
+
+ def _replace_payload(self, path: Path, payload: dict[str, Any]) -> None:
+ temporary_path = path.with_name(f".{path.name}.tmp")
+ encoded = json.dumps(
+ payload,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ ).encode("utf-8")
+ try:
+ with temporary_path.open("wb") as output:
+ output.write(encoded)
+ output.flush()
+ os.fsync(output.fileno())
+ os.replace(temporary_path, path)
+ self._fsync_directory(path.parent)
+ finally:
+ try:
+ temporary_path.unlink()
+ except FileNotFoundError:
+ pass
+
+ @staticmethod
+ def _read_payload(path: Path) -> dict[str, Any]:
+ with path.open("r", encoding="utf-8") as source:
+ payload = json.load(source)
+ if not isinstance(payload, dict):
+ raise ValueError("outbox payload must be an object")
+ return payload
+
+ @staticmethod
+ def _parse_datetime(value: str) -> datetime | None:
+ if not value:
+ return None
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+ def _move_to_dead_letter(self, path: Path) -> None:
+ try:
+ os.replace(path, self._dead_letter_dir / path.name)
+ except FileNotFoundError:
+ return
+
+ def _recover_stale_inflight(self) -> None:
+ stale_before = time.time() - self._inflight_lease_seconds
+ with self._outbox_lock:
+ for inflight_path in self._owned_batches(self._inflight_dir):
+ try:
+ if inflight_path.stat().st_mtime > stale_before:
+ continue
+ os.replace(inflight_path, self._pending_dir / inflight_path.name)
+ except FileNotFoundError:
+ continue
+
+ def _owned_batches(self, directory: Path) -> Iterator[Path]:
+ return directory.glob(f"{self._outbox_scope}_*.json")
diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.py
index 89f840d22..6ff733efd 100644
--- a/sdk/python/tests/test_async_client_behaviors.py
+++ b/sdk/python/tests/test_async_client_behaviors.py
@@ -7,6 +7,7 @@ from openviking_sdk import AsyncHTTPClient, SyncHTTPClient
from openviking_sdk.client import Session, SyncSession
from openviking_sdk.errors import NotFoundError
+
@pytest.mark.asyncio
async def test_async_http_client_initialize_forwards_event_hooks():
async def request_hook(_request):
diff --git a/tests/server/test_admin_api.py b/tests/server/test_admin_api.py
index 53f99c57e..7f7695d49 100644
--- a/tests/server/test_admin_api.py
+++ b/tests/server/test_admin_api.py
@@ -22,7 +22,7 @@ from openviking.server.config import ServerConfig
from openviking.server.dependencies import set_service
from openviking.server.identity import RequestContext, Role
from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
-from openviking.server.user_config import read_user_add_targets
+from openviking.server.user_config import read_user_add_targets, read_user_config
from openviking.service.core import OpenVikingService
from openviking.service.task_store import (
SYSTEM_TASK_ACCOUNT_ID,
@@ -331,6 +331,48 @@ async def test_create_user_paths_accept_initial_user_config(
assert bob_settings.resource_uri == "viking://user/resources/bob"
+async def test_create_user_paths_ignore_deprecated_agent_evolution_config(
+ lightweight_admin_client: httpx.AsyncClient,
+ lightweight_admin_app: FastAPI,
+):
+ acct = _uid()
+ viking_fs = lightweight_admin_app.state.fake_service.viking_fs
+
+ resp = await lightweight_admin_client.post(
+ "/api/v1/admin/accounts",
+ json={
+ "account_id": acct,
+ "admin_user_id": "alice",
+ "user_config": {"agent_evolution": {"enabled": True}},
+ },
+ headers=root_headers(),
+ )
+ assert resp.status_code == 200, resp.text
+
+ alice_config = await read_user_config(
+ viking_fs,
+ RequestContext(user=UserIdentifier(acct, "alice"), role=Role.ADMIN),
+ )
+ assert alice_config.agent_evolution.enabled is None
+
+ resp = await lightweight_admin_client.post(
+ f"/api/v1/admin/accounts/{acct}/users",
+ json={
+ "user_id": "bob",
+ "role": "user",
+ "user_config": {"agent_evolution": {"enabled": False}},
+ },
+ headers=root_headers(),
+ )
+ assert resp.status_code == 200, resp.text
+
+ bob_config = await read_user_config(
+ viking_fs,
+ RequestContext(user=UserIdentifier(acct, "bob"), role=Role.USER),
+ )
+ assert bob_config.agent_evolution.enabled is None
+
+
async def test_list_accounts(admin_client: httpx.AsyncClient):
"""ROOT can list all accounts."""
acct = _uid()
diff --git a/tests/server/test_agent_evolution_global_setting.py b/tests/server/test_agent_evolution_global_setting.py
new file mode 100644
index 000000000..ec0c9b7e5
--- /dev/null
+++ b/tests/server/test_agent_evolution_global_setting.py
@@ -0,0 +1,83 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from unittest.mock import AsyncMock
+
+import httpx
+
+from openviking.server.config import AgentEvolutionConfig, ServerConfig, UserConfig
+from openviking.service.session_service import SessionService
+
+
+def test_agent_evolution_is_disabled_by_default():
+ assert ServerConfig().agent_evolution.enabled is False
+
+
+def test_agent_evolution_can_be_enabled_for_the_server():
+ config = ServerConfig.model_validate({"agent_evolution": {"enabled": True}})
+
+ assert config.agent_evolution.enabled is True
+
+
+def test_embedded_session_service_preserves_agent_evolution_default():
+ service = SessionService()
+
+ assert service._agent_evolution_enabled is True
+
+
+def test_deprecated_user_agent_evolution_config_is_not_persisted():
+ config = UserConfig.model_validate({"agent_evolution": {"enabled": True}})
+
+ assert config.agent_evolution.enabled is True
+ assert "agent_evolution" not in config.model_dump(exclude_none=True)
+
+
+async def test_agent_evolution_user_endpoint_is_not_registered(
+ client: httpx.AsyncClient,
+):
+ response = await client.get("/api/v1/user-settings/memory")
+
+ assert response.status_code == 404
+
+
+async def test_manual_extract_respects_disabled_agent_evolution(
+ service,
+ client: httpx.AsyncClient,
+):
+ create_response = await client.post("/api/v1/sessions", json={})
+ session_id = create_response.json()["result"]["session_id"]
+ add_response = await client.post(
+ f"/api/v1/sessions/{session_id}/messages",
+ json={"role": "user", "content": "请处理一次换货任务"},
+ )
+ assert add_response.status_code == 200, add_response.text
+
+ extract = AsyncMock(return_value=[])
+ service.sessions._session_compressor.extract_long_term_memories = extract
+
+ response = await client.post(f"/api/v1/sessions/{session_id}/extract")
+
+ assert response.status_code == 200, response.text
+ assert extract.await_args.kwargs["agent_evolution_enabled"] is False
+
+
+async def test_manual_extract_respects_enabled_agent_evolution(
+ service,
+ client: httpx.AsyncClient,
+):
+ service.sessions.set_agent_evolution_config(AgentEvolutionConfig(enabled=True))
+ create_response = await client.post("/api/v1/sessions", json={})
+ session_id = create_response.json()["result"]["session_id"]
+ add_response = await client.post(
+ f"/api/v1/sessions/{session_id}/messages",
+ json={"role": "user", "content": "请处理一次换货任务"},
+ )
+ assert add_response.status_code == 200, add_response.text
+
+ extract = AsyncMock(return_value=[])
+ service.sessions._session_compressor.extract_long_term_memories = extract
+
+ response = await client.post(f"/api/v1/sessions/{session_id}/extract")
+
+ assert response.status_code == 200, response.text
+ assert extract.await_args.kwargs["agent_evolution_enabled"] is True
diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.py
index 51d7d8c9d..97ef38585 100644
--- a/tests/server/test_api_sessions.py
+++ b/tests/server/test_api_sessions.py
@@ -14,7 +14,11 @@ from starlette.requests import Request
from openviking.message import ImagePart, Message, TextPart
from openviking.server.app import create_app
-from openviking.server.config import ServerConfig, ToolOutputExternalizationConfig
+from openviking.server.config import (
+ AgentEvolutionConfig,
+ ServerConfig,
+ ToolOutputExternalizationConfig,
+)
from openviking.server.dependencies import set_service
from openviking.server.identity import RequestContext, Role
from openviking.server.routers import sessions as sessions_router
@@ -1035,6 +1039,8 @@ async def test_commit_failed_when_execution_extraction_fails_does_not_block_next
retries), the whole archive is marked .failed.json and skipped — there is
no partial state — but a failed archive must not block the next commit.
"""
+ service.sessions.set_agent_evolution_config(AgentEvolutionConfig(enabled=True))
+
create_resp = await client.post("/api/v1/sessions", json={})
session_id = create_resp.json()["result"]["session_id"]
diff --git a/tests/session/test_compressor_v3.py b/tests/session/test_compressor_v3.py
index 0bfabbd08..dfce4eb70 100644
--- a/tests/session/test_compressor_v3.py
+++ b/tests/session/test_compressor_v3.py
@@ -88,6 +88,240 @@ def test_factory_ignores_deprecated_memory_version():
)
+async def test_v3_skips_agent_training_when_agent_evolution_is_disabled(monkeypatch):
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_viking_fs",
+ lambda: SimpleNamespace(),
+ )
+ compressor = SessionCompressorV3(vikingdb=None)
+ compressor._extract_user_memories = AsyncMock(
+ return_value=SimpleNamespace(
+ contexts=[],
+ cases=[_training_case()],
+ memory_diff={"operations": {}},
+ case_uri_by_name={},
+ )
+ )
+ compressor.train_from_extracted_cases = AsyncMock()
+ compressor._write_final_memory_diff = AsyncMock()
+
+ await compressor.extract_long_term_memories(
+ messages=_messages(),
+ ctx=_ctx(),
+ allowed_memory_types={"cases", "profile"},
+ agent_evolution_enabled=False,
+ )
+
+ compressor.train_from_extracted_cases.assert_not_awaited()
+
+
+async def test_v3_extracts_session_skills_when_agent_evolution_is_disabled(monkeypatch):
+ config = SimpleNamespace(
+ memory=SimpleNamespace(session_skill_extraction_enabled=True),
+ )
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_openviking_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_viking_fs",
+ lambda: SimpleNamespace(),
+ )
+ compressor = SessionCompressorV3(
+ vikingdb=None,
+ skill_processor=SimpleNamespace(),
+ )
+ compressor._extract_user_memories = AsyncMock(
+ return_value=SimpleNamespace(
+ contexts=[],
+ cases=[],
+ memory_diff={"operations": {}},
+ case_uri_by_name={},
+ )
+ )
+ compressor.train_from_extracted_cases = AsyncMock()
+ compressor.extract_session_skills = AsyncMock(
+ return_value={
+ "case_count": 0,
+ "submitted": 0,
+ "skill_submitted": 1,
+ "skill_uris": ["viking://user/u/skills/code-review/SKILL.md"],
+ }
+ )
+ compressor._write_final_memory_diff = AsyncMock()
+
+ result = await compressor.extract_long_term_memories(
+ messages=_messages(),
+ ctx=_ctx(),
+ allowed_memory_types={"profile", "preferences"},
+ agent_evolution_enabled=False,
+ )
+
+ compressor.train_from_extracted_cases.assert_not_awaited()
+ compressor.extract_session_skills.assert_awaited_once()
+ assert result["session_skills"] == [
+ {
+ "uri": "viking://user/u/skills/code-review/SKILL.md",
+ "archive_uri": "",
+ }
+ ]
+
+
+async def test_v3_skill_only_extraction_submits_gradients_without_agent_memories(monkeypatch):
+ from openviking.session.train import PatchSemanticGradient
+
+ skill_uri = "viking://user/u/skills/code-review/SKILL.md"
+ gradient = PatchSemanticGradient(
+ before_file=None,
+ after_file=MemoryFile(
+ uri=skill_uri,
+ content="## Workflow\n- Read changed files first.",
+ memory_type="skills",
+ extra_fields={"skill_name": "code-review"},
+ ),
+ base_version=None,
+ rationale="test",
+ links=[],
+ confidence=0.9,
+ metadata={},
+ )
+ analyzer = SimpleNamespace(
+ extract_trajectory_memories=AsyncMock(
+ return_value={"contexts": [], "skill_gradients": [gradient]}
+ )
+ )
+ trainer = SimpleNamespace(
+ submit_gradients=AsyncMock(
+ return_value=SimpleNamespace(apply_result=SimpleNamespace(written_uris=[skill_uri]))
+ )
+ )
+ compressor = SessionCompressorV3(
+ vikingdb=None,
+ rollout_analyzer=analyzer,
+ skill_processor=SimpleNamespace(),
+ )
+ compressor._session_skill_extraction_enabled = lambda: True
+ compressor._get_session_skill_trainer = AsyncMock(return_value=trainer)
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_viking_fs",
+ lambda: SimpleNamespace(),
+ )
+
+ result = await compressor.extract_session_skills(
+ messages=_messages(),
+ ctx=_ctx(),
+ archive_uri="viking://user/u/sessions/s1/history/archive_001",
+ )
+
+ analyzer.extract_trajectory_memories.assert_awaited_once()
+ assert analyzer.extract_trajectory_memories.await_args.kwargs["include_trajectories"] is False
+ trainer.submit_gradients.assert_awaited_once_with([gradient])
+ assert result == {
+ "case_count": 0,
+ "submitted": 0,
+ "skill_submitted": 1,
+ "skill_uris": [skill_uri],
+ }
+
+
+async def test_v3_skips_agent_training_when_execution_memory_types_are_filtered(monkeypatch):
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_viking_fs",
+ lambda: SimpleNamespace(),
+ )
+ compressor = SessionCompressorV3(vikingdb=None)
+ compressor._extract_user_memories = AsyncMock(
+ return_value=SimpleNamespace(
+ contexts=[],
+ cases=[_training_case()],
+ memory_diff={"operations": {}},
+ case_uri_by_name={},
+ )
+ )
+ compressor.train_from_extracted_cases = AsyncMock()
+ compressor._write_final_memory_diff = AsyncMock()
+
+ await compressor.extract_long_term_memories(
+ messages=_messages(),
+ ctx=_ctx(),
+ allowed_memory_types={"cases", "profile"},
+ agent_evolution_enabled=True,
+ )
+
+ compressor.train_from_extracted_cases.assert_not_awaited()
+
+
+async def test_v3_passes_allowed_execution_types_to_agent_training(monkeypatch):
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_viking_fs",
+ lambda: SimpleNamespace(),
+ )
+ compressor = SessionCompressorV3(vikingdb=None)
+ compressor._extract_user_memories = AsyncMock(
+ return_value=SimpleNamespace(
+ contexts=[],
+ cases=[_training_case()],
+ memory_diff={"operations": {}},
+ case_uri_by_name={},
+ )
+ )
+ compressor.train_from_extracted_cases = AsyncMock(
+ return_value={"case_count": 1, "submitted": 1}
+ )
+ compressor._write_final_memory_diff = AsyncMock()
+
+ await compressor.extract_long_term_memories(
+ messages=_messages(),
+ ctx=_ctx(),
+ allowed_memory_types={"cases", "trajectories"},
+ agent_evolution_enabled=True,
+ )
+
+ assert compressor.train_from_extracted_cases.await_args.kwargs["allowed_memory_types"] == {
+ "trajectories"
+ }
+
+
+async def test_v3_initializes_only_allowed_memory_files(monkeypatch):
+ initialized_with = []
+
+ class DummyRegistry:
+ async def initialize_memory_files(self, ctx, allowed_memory_types=None):
+ del ctx
+ initialized_with.append(allowed_memory_types)
+
+ class DummyOrchestrator:
+ async def run(self):
+ return None, []
+
+ compressor = SessionCompressorV3(vikingdb=None)
+ compressor._get_or_create_react = lambda **kwargs: DummyOrchestrator()
+ compressor._write_final_memory_diff = AsyncMock()
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_viking_fs",
+ lambda: SimpleNamespace(),
+ )
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.create_default_registry",
+ lambda: DummyRegistry(),
+ )
+
+ await compressor.extract_long_term_memories(
+ messages=_messages(),
+ ctx=_ctx(),
+ allowed_memory_types={"profile"},
+ agent_evolution_enabled=False,
+ )
+
+ assert initialized_with == [{"profile"}]
+
+
def test_experience_root_uri_requires_request_user():
with pytest.raises(ValueError, match="RequestContext.user.user_id is required"):
_experience_root_uri(SimpleNamespace(user=None))
@@ -284,6 +518,67 @@ async def test_train_from_extracted_cases_submits_streaming_rollout(monkeypatch)
assert cases[0].name == "duplicate_booking"
+async def test_train_from_extracted_cases_skips_experience_updates_when_not_allowed(monkeypatch):
+ analyzed = []
+
+ class FakeTrainer:
+ policy_set = ExperienceSet(
+ root_uri="viking://user/u/memories/experiences",
+ policies=[],
+ )
+
+ class FakeAnalyzer:
+ async def analyze(self, rollout, context):
+ del context
+ analyzed.append(rollout)
+ return RolloutAnalysis(
+ evaluation=RubricEvaluation(
+ passed=True,
+ score=1.0,
+ criterion_results=[],
+ feedback=[],
+ ),
+ trajectories=[
+ Trajectory(
+ name="duplicate_booking",
+ uri="viking://user/u/memories/trajectories/t1.md",
+ content="trajectory content",
+ outcome="success",
+ retrieval_anchor="",
+ )
+ ],
+ gradients=[],
+ )
+
+ estimate = AsyncMock(side_effect=AssertionError("experience estimation must be skipped"))
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_viking_fs",
+ lambda: SimpleNamespace(ls=AsyncMock(return_value=[])),
+ )
+ monkeypatch.setattr(
+ "openviking.session.compressor_v3.get_streaming_policy_trainer",
+ AsyncMock(return_value=FakeTrainer()),
+ )
+ monkeypatch.setattr(
+ "openviking.session.train.components.gradient_estimator.ExperienceGradientEstimator.estimate",
+ estimate,
+ )
+
+ compressor = SessionCompressorV3(vikingdb=None, rollout_analyzer=FakeAnalyzer())
+ result = await compressor.train_from_extracted_cases(
+ cases=[_training_case()],
+ messages=_messages(),
+ ctx=_ctx(),
+ session_id="s1",
+ allowed_memory_types={"trajectories"},
+ )
+
+ assert len(analyzed) == 1
+ assert result["submitted"] == 1
+ estimate.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_train_from_extracted_multiple_case_memories_analyzes_bound_rollouts(monkeypatch):
seen_rollouts = []
@@ -368,7 +663,8 @@ async def test_v3_extract_uses_patch_merge_without_directory_lock(monkeypatch):
trained_cases = []
class DummyRegistry:
- async def initialize_memory_files(self, ctx):
+ async def initialize_memory_files(self, ctx, allowed_memory_types=None):
+ del ctx, allowed_memory_types
return None
class DummyOrchestrator:
@@ -414,7 +710,7 @@ async def test_v3_extract_uses_patch_merge_without_directory_lock(monkeypatch):
contexts = await compressor.extract_long_term_memories(
messages=_messages(),
ctx=_ctx(),
- allowed_memory_types={"cases", "profile"},
+ allowed_memory_types={"cases", "profile", "trajectories", "experiences"},
)
assert len(applied_operations) == 1
@@ -451,7 +747,8 @@ async def test_v3_extract_trains_only_canonical_case_after_patch_merge(monkeypat
)
class DummyRegistry:
- async def initialize_memory_files(self, ctx):
+ async def initialize_memory_files(self, ctx, allowed_memory_types=None):
+ del ctx, allowed_memory_types
return None
class DummyOrchestrator:
@@ -521,7 +818,7 @@ async def test_v3_extract_trains_only_canonical_case_after_patch_merge(monkeypat
contexts = await compressor.extract_long_term_memories(
messages=_messages(),
ctx=_ctx(),
- allowed_memory_types={"cases", "profile"},
+ allowed_memory_types={"cases", "profile", "trajectories", "experiences"},
)
assert [context.uri for context in contexts] == [canonical_uri]
@@ -591,6 +888,7 @@ async def test_v3_training_case_spec_fast_path_skips_user_memory_extraction_and_
compressor._extract_user_memories = fail_extract_user_memories
compressor._write_training_case_memory = fake_write_training_case_memory
compressor.train_from_extracted_cases = fake_train_from_extracted_cases
+ compressor._write_final_memory_diff = AsyncMock()
contexts = await compressor.extract_long_term_memories(
messages=[case_spec, *rollout_messages],
@@ -606,6 +904,36 @@ async def test_v3_training_case_spec_fast_path_skips_user_memory_extraction_and_
assert contexts[0].uri == "viking://user/u/memories/cases/duplicate_booking.md"
+async def test_v3_training_case_spec_does_not_write_case_when_evolution_disabled():
+ compressor = SessionCompressorV3(vikingdb=None, rollout_analyzer=SimpleNamespace())
+ compressor._extract_user_memories = AsyncMock(
+ return_value=SimpleNamespace(
+ contexts=[],
+ cases=[],
+ memory_diff=None,
+ case_uri_by_name={},
+ )
+ )
+ compressor._write_training_case_memory = AsyncMock()
+ compressor.train_from_extracted_cases = AsyncMock()
+ compressor._write_final_memory_diff = AsyncMock()
+
+ contexts = await compressor.extract_long_term_memories(
+ messages=[_case_spec_message(), *_messages()],
+ ctx=_ctx(),
+ session_id="s1",
+ archive_uri="viking://user/u/sessions/s1/history/archive_001",
+ allowed_memory_types={"cases", "trajectories", "experiences"},
+ agent_evolution_enabled=False,
+ )
+
+ assert contexts == []
+ compressor._write_training_case_memory.assert_not_awaited()
+ compressor.train_from_extracted_cases.assert_not_awaited()
+ assert compressor._extract_user_memories.await_args.kwargs["allowed_memory_types"] == set()
+
+
@pytest.mark.asyncio
async def test_v3_training_case_spec_fast_path_not_used_with_user_memory_policy():
extracted = False
@@ -633,7 +961,7 @@ async def test_v3_training_case_spec_fast_path_not_used_with_user_memory_policy(
assert contexts == []
assert extracted is True
- assert trained and trained[0]["messages"][0].id == "case-spec"
+ assert trained == []
@pytest.mark.asyncio
diff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.py
index 42a64d936..9ed194543 100644
--- a/tests/session/test_session_commit.py
+++ b/tests/session/test_session_commit.py
@@ -79,6 +79,91 @@ class TestCommit:
# Wait for semantic/embedding queues
await client.wait_processed(timeout=60.0)
+ async def test_commit_default_disables_agent_memory_but_keeps_archive(
+ self, session_with_messages: Session
+ ):
+ session_with_messages._agent_evolution_enabled = False
+ session_with_messages._session_compressor.extract_long_term_memories = AsyncMock(
+ return_value=[]
+ )
+
+ result = await session_with_messages.commit_async()
+ task_result = await _wait_for_task(result["task_id"])
+
+ assert result["archived"] is True
+ assert task_result["status"] == "completed"
+ assert task_result["result"]["agent_evolution_enabled"] is False
+ assert "cases" not in task_result["result"]["effective_memory_types"]
+ assert "trajectories" not in task_result["result"]["effective_memory_types"]
+ assert "experiences" not in task_result["result"]["effective_memory_types"]
+ assert task_result["result"]["agent_memory_skip_reason"] == ("agent_evolution_disabled")
+ call_kwargs = (
+ session_with_messages._session_compressor.extract_long_term_memories.call_args.kwargs
+ )
+ assert call_kwargs["agent_evolution_enabled"] is False
+ assert "cases" not in call_kwargs["allowed_memory_types"]
+ assert "trajectories" not in call_kwargs["allowed_memory_types"]
+ assert "experiences" not in call_kwargs["allowed_memory_types"]
+
+ async def test_commit_uses_global_setting_and_enables_agent_memory(
+ self, session_with_messages: Session
+ ):
+ session_with_messages._agent_evolution_enabled = True
+ session_with_messages._session_compressor.extract_long_term_memories = AsyncMock(
+ return_value=[]
+ )
+
+ result = await session_with_messages.commit_async()
+ task_result = await _wait_for_task(result["task_id"])
+
+ assert task_result["status"] == "completed"
+ assert task_result["result"]["agent_evolution_enabled"] is True
+ assert "cases" in task_result["result"]["effective_memory_types"]
+ assert "trajectories" in task_result["result"]["effective_memory_types"]
+ assert "experiences" in task_result["result"]["effective_memory_types"]
+ call_kwargs = (
+ session_with_messages._session_compressor.extract_long_term_memories.call_args.kwargs
+ )
+ assert call_kwargs["agent_evolution_enabled"] is True
+ assert call_kwargs["allowed_memory_types"] is None
+
+ async def test_disabled_agent_evolution_keeps_working_memory(
+ self, session_with_messages: Session, monkeypatch
+ ):
+ session_with_messages._agent_evolution_enabled = False
+ summary_called = False
+
+ async def fake_summary(_session, messages, latest_archive_overview=""):
+ nonlocal summary_called
+ del messages, latest_archive_overview
+ summary_called = True
+ return "# Working Memory\n\nAgent memory production is disabled."
+
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", fake_summary)
+ session_with_messages._session_compressor.extract_long_term_memories = AsyncMock(
+ return_value=[]
+ )
+ if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):
+ session_with_messages._session_compressor.extract_execution_memories = AsyncMock(
+ return_value={"contexts": [], "session_skills": []}
+ )
+
+ result = await session_with_messages.commit_async(
+ memory_policy={
+ "memory_types": ["cases", "trajectories", "experiences"],
+ "working_memory": {"enabled": True},
+ }
+ )
+ task_result = await _wait_for_task(result["task_id"])
+
+ assert task_result["status"] == "completed"
+ assert summary_called is True
+ archive_uri = task_result["result"]["archive_uri"]
+ assert await _marker_exists(session_with_messages, archive_uri, ".overview.md")
+ session_with_messages._session_compressor.extract_long_term_memories.assert_not_awaited()
+ if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):
+ session_with_messages._session_compressor.extract_execution_memories.assert_not_awaited()
+
async def test_commit_reports_session_skills_separately(
self, session_with_messages: Session, monkeypatch
):
@@ -120,9 +205,7 @@ class TestCommit:
session_with_messages._session_compressor.extract_long_term_memories.assert_not_awaited()
if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):
session_with_messages._session_compressor.extract_execution_memories.assert_awaited_once()
- call_kwargs = (
- session_with_messages._session_compressor.extract_execution_memories.call_args.kwargs
- )
+ call_kwargs = session_with_messages._session_compressor.extract_execution_memories.call_args.kwargs
assert call_kwargs["allowed_memory_types"] == {"trajectories"}
assert call_kwargs["include_session_skills"] is True
@@ -184,9 +267,7 @@ class TestCommit:
session_with_messages._session_compressor.extract_long_term_memories.assert_awaited_once()
if hasattr(session_with_messages._session_compressor, "extract_execution_memories"):
session_with_messages._session_compressor.extract_execution_memories.assert_awaited_once()
- call_kwargs = (
- session_with_messages._session_compressor.extract_execution_memories.call_args.kwargs
- )
+ call_kwargs = session_with_messages._session_compressor.extract_execution_memories.call_args.kwargs
assert call_kwargs["include_session_skills"] is False
async def test_commit_can_skip_working_memory_summary(
diff --git a/tests/session/test_session_retention_integration.py b/tests/session/test_session_retention_integration.py
index f11ddd0e1..31148136b 100644
--- a/tests/session/test_session_retention_integration.py
+++ b/tests/session/test_session_retention_integration.py
@@ -12,6 +12,7 @@ from openviking import AsyncOpenViking
from openviking.message import Message, TextPart, ToolPart
from openviking.models.vlm.base import ToolCall, VLMResponse
from openviking.service.task_tracker import get_task_tracker
+from openviking.session.memory.constants import AGENT_EVOLUTION_MEMORY_TYPES
from openviking.session.session import Session, _ArchiveSummaryResult, _CheckpointRequest
@@ -366,9 +367,15 @@ async def test_phase2_roll_forward_writes_coverage_and_calls_existing_summary_on
1,
[_text_message("u1", "user", "failed one")],
failed=True,
+ meta={"agent_evolution": {"enabled": False}},
)
current = _text_message("u2", "user", "current two")
- current_uri = await _write_archive(session, 2, [current])
+ current_uri = await _write_archive(
+ session,
+ 2,
+ [current],
+ meta={"agent_evolution": {"enabled": True}},
+ )
seen_message_ids: list[list[str]] = []
async def fake_summary(messages, latest_archive_overview=""):
@@ -401,11 +408,14 @@ async def test_phase2_roll_forward_writes_coverage_and_calls_existing_summary_on
first_message_id=current.id,
last_message_id=current.id,
memory_policy={"working_memory": {"enabled": True}},
+ agent_evolution_enabled=True,
)
done = json.loads(await session._viking_fs.read_file(f"{current_uri}/.done", ctx=session.ctx))
+ task = await get_task_tracker().get(task_id)
context = await session.get_session_context()
assert seen_message_ids == [["u1", "u2"]]
+ assert task.result["agent_evolution_enabled"] is True
assert done["coverage_start_archive"] == "archive_001"
assert done["coverage_end_archive"] == "archive_002"
assert done["covered_failed_archives"] == ["archive_001"]
@@ -1620,4 +1630,16 @@ async def test_stale_worker_uses_lock_snapshot_memory_policy_for_queue_message(
result = await stale_session.commit_async()
assert result["archived"] is True
- assert queued[0]["memory_policy"] == updater.meta.memory_policy
+ queued_policy = queued[0]["memory_policy"]
+ assert {
+ key: queued_policy[key] for key in updater.meta.memory_policy
+ } == updater.meta.memory_policy
+ assert set(queued_policy["memory_types"]).isdisjoint(AGENT_EVOLUTION_MEMORY_TYPES)
+ assert "agent_evolution_enabled" not in queued[0]
+ archive_meta = json.loads(
+ await stale_session._viking_fs.read_file(
+ f"{result['archive_uri']}/.meta.json",
+ ctx=stale_session.ctx,
+ )
+ )
+ assert archive_meta["agent_evolution"]["enabled"] is False
diff --git a/tests/session/train/test_trajectory_analyzer_component.py b/tests/session/train/test_trajectory_analyzer_component.py
index 32b8cc4c5..fb924d035 100644
--- a/tests/session/train/test_trajectory_analyzer_component.py
+++ b/tests/session/train/test_trajectory_analyzer_component.py
@@ -55,6 +55,31 @@ class FakeExtractLoop:
)
+class FakeSkillOnlyExtractLoop(FakeExtractLoop):
+ async def run(self):
+ return (
+ ResolvedOperations(
+ upsert_operations=[
+ ResolvedOperation(
+ old_memory_file_content=None,
+ memory_fields={
+ "skill_name": "code-review",
+ "description": "Review code carefully",
+ "content": "## Workflow\n- Read the changed files first.",
+ },
+ memory_type="session_skills",
+ uris=["viking://user/u/skills/code-review/SKILL.md"],
+ page_id=100,
+ )
+ ],
+ delete_file_contents=[],
+ errors=[],
+ resolved_links=[],
+ ),
+ [],
+ )
+
+
class FakeVikingFS:
agfs = None
@@ -65,7 +90,8 @@ class FakeVikingFS:
async def read_file(self, uri, ctx=None):
return self.files[uri]
- async def write_file(self, uri, content, ctx=None):
+ async def write_file(self, uri, content, ctx=None, lock_handle=None):
+ del lock_handle
self.files[uri] = content
self.writes.append((uri, content, ctx))
@@ -161,6 +187,41 @@ async def test_trajectory_rollout_analyzer_extracts_and_persists_trajectory(monk
assert analysis.metadata["policy_snapshot_id"] == "snapshot"
+async def test_trajectory_rollout_analyzer_extracts_skill_without_persisting_trajectory(
+ monkeypatch,
+):
+ from openviking.session.train.components import trajectory_analyzer as module
+
+ FakeExtractLoop.created.clear()
+ fs = FakeVikingFS()
+ monkeypatch.setattr(module, "ExtractLoop", FakeSkillOnlyExtractLoop)
+ monkeypatch.setattr(module, "get_viking_fs", lambda: fs)
+
+ analyzer = TrajectoryRolloutAnalyzer(viking_fs=fs, vlm=SimpleNamespace(model="fake"))
+ result = await analyzer.extract_trajectory_memories(
+ messages=_rollout().messages,
+ ctx=SimpleNamespace(
+ user=SimpleNamespace(account_id="default", user_id="u"),
+ account_id="default",
+ ),
+ include_trajectories=False,
+ include_session_skills=True,
+ )
+
+ provider = FakeExtractLoop.created[0].kwargs["context_provider"]
+ assert [
+ schema.memory_type
+ for schema in provider.get_memory_schemas(
+ SimpleNamespace(user=SimpleNamespace(account_id="default", user_id="u"))
+ )
+ ] == ["session_skills"]
+ assert result["contexts"] == []
+ assert len(result["skill_gradients"]) == 1
+ assert result["skill_gradients"][0].after_file.memory_type == "skills"
+ assert fs.writes == []
+
+
@pytest.mark.asyncio
async def test_trajectory_rollout_analyzer_evaluates_before_extracting_trajectory(monkeypatch):
from openviking.session.train.components import trajectory_analyzer as module
diff --git a/tests/unit/session/test_agent_evolution_policy.py b/tests/unit/session/test_agent_evolution_policy.py
new file mode 100644
index 000000000..0bd16c0ed
--- /dev/null
+++ b/tests/unit/session/test_agent_evolution_policy.py
@@ -0,0 +1,70 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from openviking.session import session as session_module
+from openviking.session.memory_policy import MemoryPolicy
+
+
+def test_global_enabled_agent_evolution_preserves_session_memory_types():
+ policy = MemoryPolicy.from_dict(
+ {"memory_types": ["profile", "events", "cases", "trajectories", "experiences"]}
+ )
+
+ effective = session_module._apply_agent_evolution_setting(
+ policy,
+ agent_evolution_enabled=True,
+ )
+
+ assert effective.memory_types == {
+ "profile",
+ "events",
+ "cases",
+ "trajectories",
+ "experiences",
+ }
+ assert effective.self_enabled is True
+ assert effective.peer_enabled is True
+ assert effective.working_memory_enabled is True
+
+
+def test_disabled_agent_evolution_cannot_be_bypassed_by_session_policy():
+ policy = MemoryPolicy.from_dict(
+ {"memory_types": ["profile", "cases", "trajectories", "experiences"]}
+ )
+
+ effective = session_module._apply_agent_evolution_setting(
+ policy,
+ agent_evolution_enabled=False,
+ )
+
+ assert effective.memory_types == {"profile"}
+
+
+def test_disabled_agent_evolution_removes_agent_memory_types_from_default_policy():
+ effective = session_module._apply_agent_evolution_setting(
+ MemoryPolicy.default(),
+ agent_evolution_enabled=False,
+ )
+
+ assert effective.memory_types is not None
+ assert "profile" in effective.memory_types
+ assert "cases" not in effective.memory_types
+ assert "trajectories" not in effective.memory_types
+ assert "experiences" not in effective.memory_types
+
+
+def test_agent_memory_skip_reason_requires_case_and_trajectory_types():
+ assert (
+ session_module._agent_memory_skip_reason(
+ agent_evolution_enabled=True,
+ effective_memory_types={"cases", "experiences"},
+ )
+ == "memory_types_filtered"
+ )
+ assert (
+ session_module._agent_memory_skip_reason(
+ agent_evolution_enabled=True,
+ effective_memory_types={"cases", "trajectories"},
+ )
+ is None
+ )
diff --git a/tests/unit/session/test_session_commit_resume.py b/tests/unit/session/test_session_commit_resume.py
index 549e38abf..240f4c410 100644
--- a/tests/unit/session/test_session_commit_resume.py
+++ b/tests/unit/session/test_session_commit_resume.py
@@ -81,6 +81,7 @@ async def test_resume_queued_commit_continues_phase2(monkeypatch):
session._run_memory_extraction.assert_awaited_once()
assert session._run_memory_extraction.await_args.kwargs["task_id"] == "task-1"
+ assert session._run_memory_extraction.await_args.kwargs["agent_evolution_enabled"] is True
assert [
item.id for item in session._run_memory_extraction.await_args.kwargs["messages"]
] == ["archived"]
@@ -143,3 +144,68 @@ async def test_session_context_skips_pending_archive_with_missing_messages(monke
context = await session.get_context_for_search(query="test")
assert context == {"latest_archive_overview": "", "current_messages": []}
+
+
+async def test_resume_queued_commit_uses_agent_evolution_archive_snapshot(monkeypatch):
+ session_uri = "viking://user/sessions/session-1"
+ archive_uri = f"{session_uri}/history/archive_001"
+ archived = Message(id="archived", role="user", parts=[TextPart("old")])
+ files = {
+ f"{session_uri}/messages.jsonl": "",
+ f"{session_uri}/.meta.json": json.dumps(
+ {"session_id": "session-1", "message_count": 0, "commit_count": 1}
+ ),
+ f"{archive_uri}/messages.jsonl": f"{archived.to_jsonl()}\n",
+ f"{archive_uri}/.meta.json": json.dumps(
+ {
+ "agent_evolution": {
+ "enabled": False,
+ "skip_reason": "agent_evolution_disabled",
+ "user_config_error": None,
+ }
+ }
+ ),
+ }
+ session = Session(
+ viking_fs=_MemoryVikingFS(files),
+ session_id="session-1",
+ session_uri=session_uri,
+ )
+ tracker = TaskTracker(_TaskStore())
+ set_task_tracker(tracker)
+ monkeypatch.setattr(session, "_run_memory_extraction", AsyncMock())
+ message = SessionCommitMsg(
+ task_id="task-1",
+ session_id="session-1",
+ session_uri=session_uri,
+ archive_uri=archive_uri,
+ user={"account_id": "default", "user_id": "default"},
+ memory_policy={"memory_types": ["profile"]},
+ )
+
+ try:
+ await session.resume_queued_commit(message)
+ finally:
+ set_task_tracker(None)
+
+ kwargs = session._run_memory_extraction.await_args.kwargs
+ assert kwargs["agent_evolution_enabled"] is False
+ assert kwargs["agent_memory_skip_reason"] == "agent_evolution_disabled"
+ assert kwargs["user_config_error"] is None
+
+
+def test_session_commit_message_ignores_unknown_fields():
+ message = SessionCommitMsg.from_dict(
+ {
+ "task_id": "task-1",
+ "session_id": "session-1",
+ "session_uri": "viking://user/sessions/session-1",
+ "archive_uri": "viking://user/sessions/session-1/history/archive_001",
+ "user": {"account_id": "default", "user_id": "default"},
+ "future_field": "ignored",
+ }
+ )
+
+ assert message.task_id == "task-1"
+ assert "future_field" not in message.to_dict()
diff --git a/tests/unit/usage_reporter/test_http_sink.py b/tests/unit/usage_reporter/test_http_sink.py
new file mode 100644
index 000000000..90449ec01
--- /dev/null
+++ b/tests/unit/usage_reporter/test_http_sink.py
@@ -0,0 +1,692 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import json
+import os
+import tempfile
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from unittest import mock
+
+import pytest
+
+from openviking.usage_reporter.http_sink import HttpUsageSink
+
+
+class FakeUsageEvent:
+ def __init__(
+ self,
+ event_id: str,
+ session_id: str,
+ attributes: dict[str, object] | None = None,
+ *,
+ event_type: str = "memory.recalled",
+ occurred_at: str = "2026-07-27T04:00:00Z",
+ resource_uri: str = "viking://user/user-1/memories/experiences/exchange.md",
+ resource_type: str = "experience",
+ task_id: str | None = None,
+ evidence: dict[str, object] | None = None,
+ ) -> None:
+ self._record = {
+ "schema_version": "v1",
+ "event_id": event_id,
+ "event_type": event_type,
+ "account_id": "2101858484",
+ "user_id": "user-1",
+ "session_id": session_id,
+ "task_id": task_id,
+ "occurred_at": occurred_at,
+ "resource_uri": resource_uri,
+ "resource_type": resource_type,
+ "evidence": evidence or {},
+ "attributes": attributes or {},
+ }
+
+ def to_dict(self) -> dict[str, object]:
+ return dict(self._record)
+
+
+class UsageRequestHandler(BaseHTTPRequestHandler):
+ def do_POST(self) -> None:
+ content_length = int(self.headers["Content-Length"])
+ body = json.loads(self.rfile.read(content_length))
+ self.server.requests.append(body)
+ self.server.resource_ids.append(self.headers["V-Resource-Id"])
+ response_status = self.server.response_statuses.pop(0)
+ self.send_response(response_status)
+ self.end_headers()
+ self.wfile.write(b"{}")
+
+ def log_message(self, format: str, *args: object) -> None:
+ return
+
+
+class UsageHTTPServer(ThreadingHTTPServer):
+ requests: list[dict[str, object]]
+ resource_ids: list[str]
+ response_statuses: list[int]
+
+
+def wait_until(predicate: object, timeout: float = 3.0) -> None:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if predicate():
+ return
+ time.sleep(0.01)
+ raise AssertionError("condition was not met before timeout")
+
+
+class TestHttpUsageSink:
+ def test_write_persists_recall_as_count_record(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ )
+ asyncio.run(
+ sink.write(
+ events=[
+ FakeUsageEvent(
+ "ue_recall",
+ "session-1",
+ {"rank": 1},
+ task_id="task-1",
+ evidence={
+ "archive_uri": (
+ "viking://user/user-1/sessions/session-1/"
+ "history/archive_001"
+ ),
+ "message_id": "msg-1",
+ "tool_call_id": "call-1",
+ "tool_name": "search_experience",
+ },
+ )
+ ]
+ )
+ )
+
+ pending_path = next((outbox_dir / "pending").glob("*.json"))
+ payload = json.loads(pending_path.read_text(encoding="utf-8"))
+ assert payload["events"] == [
+ {
+ "CountName": "experience.recall.count",
+ "OpType": "add",
+ "amount": 1.0,
+ "timestamp": 1785124800000,
+ "uniqueId": "ue_recall",
+ "tags": {
+ "account_id": "2101858484",
+ "user_id": "user-1",
+ "resource_uri": ("viking://user/user-1/memories/experiences/exchange.md"),
+ "resource_type": "experience",
+ },
+ "extra": {
+ "session_id": "session-1",
+ "task_id": "task-1",
+ "archive_uri": (
+ "viking://user/user-1/sessions/session-1/history/archive_001"
+ ),
+ "message_id": "msg-1",
+ "tool_call_id": "call-1",
+ "tool_name": "search_experience",
+ "attributes": {"rank": 1},
+ },
+ }
+ ]
+
+ def test_write_maps_injected_event_to_count_record(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ )
+ asyncio.run(
+ sink.write(
+ events=[
+ FakeUsageEvent(
+ "ue_inject",
+ "session-1",
+ event_type="memory.injected",
+ )
+ ]
+ )
+ )
+
+ pending_path = next((outbox_dir / "pending").glob("*.json"))
+ payload = json.loads(pending_path.read_text(encoding="utf-8"))
+ assert payload["events"][0]["CountName"] == "experience.inject.count"
+
+ def test_write_omits_empty_optional_count_record_extra_fields(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ )
+ asyncio.run(sink.write(events=[FakeUsageEvent("ue_minimal", "session-1")]))
+
+ pending_path = next((outbox_dir / "pending").glob("*.json"))
+ payload = json.loads(pending_path.read_text(encoding="utf-8"))
+ assert payload["events"][0]["extra"] == {"session_id": "session-1"}
+
+ def test_write_rejects_unknown_usage_event_type(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(Path(data_dir) / ".usage_outbox"),
+ )
+ with pytest.raises(
+ ValueError,
+ match="unsupported usage event type: memory.unknown",
+ ):
+ asyncio.run(
+ sink.write(
+ events=[
+ FakeUsageEvent(
+ "ue_unknown",
+ "session-1",
+ event_type="memory.unknown",
+ )
+ ]
+ )
+ )
+
+ def test_write_atomically_persists_stable_batch(self) -> None:
+ events = [
+ FakeUsageEvent("ue_1", "session-1"),
+ FakeUsageEvent("ue_2", "session-1"),
+ ]
+ expected_digest = hashlib.sha256(b"ue_1\nue_2").hexdigest()
+
+ with tempfile.TemporaryDirectory() as data_dir:
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/api/openviking/ReportOpenVikingUsage",
+ outbox_dir=str(Path(data_dir) / ".usage_outbox"),
+ )
+ asyncio.run(sink.write(events=events))
+
+ pending_files = list((Path(data_dir) / ".usage_outbox" / "pending").glob("*.json"))
+ temporary_files = list((Path(data_dir) / ".usage_outbox" / "pending").glob("*.tmp"))
+
+ assert len(pending_files) == 1
+ assert temporary_files == []
+ payload = json.loads(pending_files[0].read_text(encoding="utf-8"))
+ assert payload["schema_version"] == "v1"
+ assert payload["resource_id"] == "ov-test"
+ assert payload["batch_id"] == f"ub_{expected_digest}"
+ assert [event["uniqueId"] for event in payload["events"]] == [
+ "ue_1",
+ "ue_2",
+ ]
+ assert all("prefix" not in event for event in payload["events"])
+
+ def test_write_splits_batches_before_http_limit(self) -> None:
+ events = [
+ FakeUsageEvent("ue_large_1", "session-large", {"text": "a" * 700}),
+ FakeUsageEvent("ue_large_2", "session-large", {"text": "b" * 700}),
+ ]
+
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ max_batch_bytes=1024,
+ )
+ asyncio.run(sink.write(events=events))
+
+ batches = [
+ json.loads(path.read_text(encoding="utf-8"))
+ for path in (outbox_dir / "pending").glob("*.json")
+ ]
+ assert len(batches) == 2
+ assert sorted(len(batch["events"]) for batch in batches) == [1, 1]
+
+ def test_worker_retries_then_deletes_acknowledged_batch(self) -> None:
+ server = UsageHTTPServer(("127.0.0.1", 0), UsageRequestHandler)
+ server.requests = []
+ server.resource_ids = []
+ server.response_statuses = [503, 200]
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+
+ try:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ sink = HttpUsageSink(
+ endpoint=f"http://127.0.0.1:{server.server_port}/usage",
+ outbox_dir=str(outbox_dir),
+ request_timeout_seconds=0.5,
+ retry_base_seconds=0.01,
+ retry_max_seconds=0.02,
+ )
+ asyncio.run(sink.write(events=[FakeUsageEvent("ue_retry", "session-retry")]))
+ wait_until(lambda: len(server.requests) == 2)
+ wait_until(
+ lambda: (
+ not list((outbox_dir / "pending").glob("*.json"))
+ and not list((outbox_dir / "inflight").glob("*.json"))
+ )
+ )
+ sink.close()
+
+ assert [request["batch_id"] for request in server.requests] == [
+ server.requests[0]["batch_id"],
+ server.requests[0]["batch_id"],
+ ]
+ assert server.resource_ids == ["ov-test", "ov-test"]
+ finally:
+ server.shutdown()
+ server.server_close()
+ server_thread.join(timeout=1)
+
+ def test_worker_accepts_any_successful_http_status(self) -> None:
+ server = UsageHTTPServer(("127.0.0.1", 0), UsageRequestHandler)
+ server.requests = []
+ server.resource_ids = []
+ server.response_statuses = [204]
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+
+ try:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ sink = HttpUsageSink(
+ endpoint=f"http://127.0.0.1:{server.server_port}/usage",
+ outbox_dir=str(outbox_dir),
+ request_timeout_seconds=0.5,
+ )
+ asyncio.run(sink.write(events=[FakeUsageEvent("ue_204", "session-success")]))
+ wait_until(lambda: len(server.requests) == 1)
+ wait_until(
+ lambda: (
+ not list((outbox_dir / "pending").glob("*.json"))
+ and not list((outbox_dir / "inflight").glob("*.json"))
+ )
+ )
+ sink.close()
+ finally:
+ server.shutdown()
+ server.server_close()
+ server_thread.join(timeout=1)
+
+ def test_outbox_capacity_evicts_oldest_pending_batches(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ max_outbox_bytes=1800,
+ )
+ for index in range(4):
+ asyncio.run(
+ sink.write(
+ events=[
+ FakeUsageEvent(
+ f"ue_capacity_{index}",
+ "session-capacity",
+ {"text": str(index) * 600},
+ )
+ ]
+ )
+ )
+
+ pending_files = list((outbox_dir / "pending").glob("*.json"))
+ total_bytes = sum(path.stat().st_size for path in pending_files)
+ persisted_ids = {
+ event["uniqueId"]
+ for path in pending_files
+ for event in json.loads(path.read_text(encoding="utf-8"))["events"]
+ }
+ assert total_bytes <= 1800
+ assert "ue_capacity_0" not in persisted_ids
+ assert "ue_capacity_3" in persisted_ids
+
+ def test_outbox_capacity_counts_inflight_without_evicting_it(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ max_outbox_bytes=1800,
+ )
+ inflight_path = outbox_dir / "inflight" / f"{sink._outbox_scope}_active.json"
+ inflight_path.write_bytes(b"x" * 1000)
+ asyncio.run(
+ sink.write(
+ events=[
+ FakeUsageEvent(
+ "ue_while_inflight",
+ "session-capacity",
+ {"text": "x" * 900},
+ )
+ ]
+ )
+ )
+
+ assert inflight_path.exists()
+ assert list((outbox_dir / "pending").glob("*.json")) == []
+
+ def test_default_outbox_directory_uses_current_user_home(self) -> None:
+ with tempfile.TemporaryDirectory() as home_dir:
+ expected = Path(home_dir) / ".openviking" / "data" / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(Path, "home", return_value=Path(home_dir)):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(endpoint="http://127.0.0.1:1/usage")
+
+ assert sink._outbox_dir == expected
+ assert expected.is_dir()
+
+ def test_shared_outbox_root_isolated_by_endpoint_and_resource(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_root = Path(data_dir) / ".usage_outbox"
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "resource-a"}, clear=False):
+ sink_a = HttpUsageSink(
+ endpoint="http://collector-a.example/usage",
+ outbox_dir=str(outbox_root),
+ )
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "resource-b"}, clear=False):
+ other_resource_sink = HttpUsageSink(
+ endpoint="http://collector-a.example/usage",
+ outbox_dir=str(outbox_root),
+ )
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "resource-a"}, clear=False):
+ other_endpoint_sink = HttpUsageSink(
+ endpoint="http://collector-b.example/usage",
+ outbox_dir=str(outbox_root),
+ )
+
+ asyncio.run(sink_a.write(events=[FakeUsageEvent("ue_a", "session-a")]))
+ sink_a._post_payload = mock.Mock(return_value=200)
+ other_resource_sink._post_payload = mock.Mock(return_value=200)
+ other_endpoint_sink._post_payload = mock.Mock(return_value=200)
+
+ assert other_resource_sink._handle_next_batch() is False
+ other_resource_sink._post_payload.assert_not_called()
+ assert other_endpoint_sink._handle_next_batch() is False
+ other_endpoint_sink._post_payload.assert_not_called()
+ assert sink_a._handle_next_batch() is True
+ sink_a._post_payload.assert_called_once()
+
+ def test_worker_splits_payload_rejected_as_too_large(self) -> None:
+ server = UsageHTTPServer(("127.0.0.1", 0), UsageRequestHandler)
+ server.requests = []
+ server.resource_ids = []
+ server.response_statuses = [413, 200, 200]
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+
+ try:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ sink = HttpUsageSink(
+ endpoint=f"http://127.0.0.1:{server.server_port}/usage",
+ outbox_dir=str(outbox_dir),
+ request_timeout_seconds=0.5,
+ )
+ asyncio.run(
+ sink.write(
+ events=[
+ FakeUsageEvent("ue_left", "session-split"),
+ FakeUsageEvent("ue_right", "session-split"),
+ ]
+ )
+ )
+ wait_until(lambda: len(server.requests) == 3)
+ wait_until(
+ lambda: (
+ not list((outbox_dir / "pending").glob("*.json"))
+ and not list((outbox_dir / "inflight").glob("*.json"))
+ )
+ )
+ sink.close()
+
+ original_batch_id = server.requests[0]["batch_id"]
+ child_batch_ids = {request["batch_id"] for request in server.requests[1:]}
+ assert [len(request["events"]) for request in server.requests] == [2, 1, 1]
+ assert original_batch_id not in child_batch_ids
+ assert len(child_batch_ids) == 2
+ finally:
+ server.shutdown()
+ server.server_close()
+ server_thread.join(timeout=1)
+
+ def test_split_replaces_parent_without_evicting_child_batches(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ events = [
+ FakeUsageEvent("ue_split_left", "session-split", {"text": "a" * 500}),
+ FakeUsageEvent("ue_split_right", "session-split", {"text": "b" * 500}),
+ ]
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ max_outbox_bytes=10_000,
+ )
+ asyncio.run(sink.write(events=events))
+
+ parent_path = next((outbox_dir / "pending").glob("*.json"))
+ payload = json.loads(parent_path.read_text(encoding="utf-8"))
+ inflight_path = outbox_dir / "inflight" / parent_path.name
+ os.replace(parent_path, inflight_path)
+ child_size = sum(
+ sink._encoded_payload_size([event]) for event in payload["events"]
+ )
+ sink._max_outbox_bytes = child_size + 50
+
+ sink._split_batch(inflight_path, payload)
+
+ children = [
+ json.loads(path.read_text(encoding="utf-8"))
+ for path in (outbox_dir / "pending").glob("*.json")
+ ]
+ assert not inflight_path.exists()
+ assert len(children) == 2
+ assert {event["uniqueId"] for child in children for event in child["events"]} == {
+ "ue_split_left",
+ "ue_split_right",
+ }
+
+ def test_worker_moves_unrecoverable_payload_to_dead_letter(self) -> None:
+ server = UsageHTTPServer(("127.0.0.1", 0), UsageRequestHandler)
+ server.requests = []
+ server.resource_ids = []
+ server.response_statuses = [422]
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+
+ try:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ sink = HttpUsageSink(
+ endpoint=f"http://127.0.0.1:{server.server_port}/usage",
+ outbox_dir=str(outbox_dir),
+ )
+ asyncio.run(sink.write(events=[FakeUsageEvent("ue_bad", "session-bad")]))
+ wait_until(lambda: len(list((outbox_dir / "dead_letter").glob("*.json"))) == 1)
+ sink.close()
+
+ assert len(server.requests) == 1
+ assert not list((outbox_dir / "pending").glob("*.json"))
+ finally:
+ server.shutdown()
+ server.server_close()
+ server_thread.join(timeout=1)
+
+ def test_startup_recovers_only_stale_inflight_batch(self) -> None:
+ server = UsageHTTPServer(("127.0.0.1", 0), UsageRequestHandler)
+ server.requests = []
+ server.resource_ids = []
+ server.response_statuses = [200]
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+
+ try:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ first_sink = HttpUsageSink(
+ endpoint=f"http://127.0.0.1:{server.server_port}/usage",
+ outbox_dir=str(outbox_dir),
+ )
+ asyncio.run(
+ first_sink.write(events=[FakeUsageEvent("ue_stale", "session-stale")])
+ )
+ pending_path = next((outbox_dir / "pending").glob("*.json"))
+ inflight_path = outbox_dir / "inflight" / pending_path.name
+ os.replace(pending_path, inflight_path)
+ stale_time = time.time() - 10
+ os.utime(inflight_path, (stale_time, stale_time))
+
+ second_sink = HttpUsageSink(
+ endpoint=f"http://127.0.0.1:{server.server_port}/usage",
+ outbox_dir=str(outbox_dir),
+ request_timeout_seconds=0.5,
+ inflight_lease_seconds=1,
+ )
+ wait_until(lambda: len(server.requests) == 1)
+ wait_until(lambda: not inflight_path.exists())
+ second_sink.close()
+ finally:
+ server.shutdown()
+ server.server_close()
+ server_thread.join(timeout=1)
+
+ def test_worker_recovers_inflight_batch_when_lease_expires_after_startup(self) -> None:
+ server = UsageHTTPServer(("127.0.0.1", 0), UsageRequestHandler)
+ server.requests = []
+ server.resource_ids = []
+ server.response_statuses = [200]
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+
+ try:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ first_sink = HttpUsageSink(
+ endpoint=f"http://127.0.0.1:{server.server_port}/usage",
+ outbox_dir=str(outbox_dir),
+ )
+ asyncio.run(
+ first_sink.write(events=[FakeUsageEvent("ue_fresh", "session-fresh")])
+ )
+ pending_path = next((outbox_dir / "pending").glob("*.json"))
+ inflight_path = outbox_dir / "inflight" / pending_path.name
+ os.replace(pending_path, inflight_path)
+
+ second_sink = HttpUsageSink(
+ endpoint=f"http://127.0.0.1:{server.server_port}/usage",
+ outbox_dir=str(outbox_dir),
+ request_timeout_seconds=0.01,
+ inflight_lease_seconds=0.05,
+ )
+ wait_until(lambda: len(server.requests) == 1)
+ wait_until(lambda: not inflight_path.exists())
+ second_sink.close()
+ finally:
+ server.shutdown()
+ server.server_close()
+ server_thread.join(timeout=1)
+
+ def test_worker_keeps_batch_after_unexpected_delivery_exception(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ retry_base_seconds=0.01,
+ retry_max_seconds=0.02,
+ )
+ attempts = 0
+
+ def flaky_post(payload: dict[str, object]) -> int:
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise RuntimeError("unexpected delivery failure")
+ return 200
+
+ sink._post_payload = flaky_post
+ with mock.patch(
+ "openviking.usage_reporter.http_sink.logger.exception"
+ ) as log_exception:
+ asyncio.run(
+ sink.write(events=[FakeUsageEvent("ue_exception", "session-exception")])
+ )
+ wait_until(lambda: attempts == 2)
+ wait_until(
+ lambda: (
+ not list((outbox_dir / "pending").glob("*.json"))
+ and not list((outbox_dir / "inflight").glob("*.json"))
+ )
+ )
+ sink.close()
+ assert log_exception.call_count == 1
+ assert (
+ "usage delivery failed unexpectedly"
+ in log_exception.call_args.args[0].lower()
+ )
+
+ def test_claiming_pending_batch_refreshes_inflight_lease(self) -> None:
+ with tempfile.TemporaryDirectory() as data_dir:
+ outbox_dir = Path(data_dir) / ".usage_outbox"
+ with mock.patch.dict(os.environ, {"OV_RESOURCE_ID": "ov-test"}, clear=False):
+ with mock.patch.object(HttpUsageSink, "_start_worker"):
+ sink = HttpUsageSink(
+ endpoint="http://127.0.0.1:1/usage",
+ outbox_dir=str(outbox_dir),
+ request_timeout_seconds=0.01,
+ inflight_lease_seconds=0.05,
+ )
+ asyncio.run(sink.write(events=[FakeUsageEvent("ue_claim", "session-claim")]))
+ pending_path = next((outbox_dir / "pending").glob("*.json"))
+ stale_time = time.time() - 60
+ os.utime(pending_path, (stale_time, stale_time))
+ claimed_mtime = 0.0
+
+ def record_claim(_payload: dict[str, object]) -> int:
+ nonlocal claimed_mtime
+ inflight_path = outbox_dir / "inflight" / pending_path.name
+ claimed_mtime = inflight_path.stat().st_mtime
+ return 200
+
+ sink._post_payload = record_claim
+ assert sink._handle_next_batch() is True
+
+ assert claimed_mtime >= time.time() - 1
diff --git a/tests/unit/usage_reporter/test_usage_reporter_config.py b/tests/unit/usage_reporter/test_usage_reporter_config.py
index 46b7715a8..8b631407e 100644
--- a/tests/unit/usage_reporter/test_usage_reporter_config.py
+++ b/tests/unit/usage_reporter/test_usage_reporter_config.py
@@ -11,6 +11,7 @@ from openviking.server.app import create_app
from openviking.server.config import ServerConfig, UsageReporterConfig
from openviking.usage_reporter import UsageContext, UsageEvent
from openviking.usage_reporter.config import build_usage_reporter
+from openviking.usage_reporter.http_sink import HttpUsageSink
@pytest.mark.asyncio
@@ -79,9 +80,35 @@ class CustomUsageSink:
assert "source" not in payload
+def test_builtin_http_sink_is_built_from_config(tmp_path, monkeypatch):
+ monkeypatch.setenv("OV_RESOURCE_ID", "ov-test")
+
+ reporter = build_usage_reporter(
+ UsageReporterConfig(
+ enabled=True,
+ extractors=["memory_usage"],
+ sinks=[
+ {
+ "type": "http",
+ "config": {
+ "endpoint": "http://127.0.0.1:1/usage",
+ "outbox_dir": str(tmp_path / ".usage_outbox"),
+ },
+ }
+ ],
+ )
+ )
+
+ assert reporter is not None
+ assert len(reporter.sinks) == 1
+ assert isinstance(reporter.sinks[0], HttpUsageSink)
+ reporter.sinks[0].close()
+
+
async def test_app_reuses_and_closes_usage_reporter(monkeypatch):
built_reporters = []
assigned_reporters = []
+ assigned_agent_evolution_configs = []
class Reporter:
closed = False
@@ -103,6 +130,9 @@ async def test_app_reuses_and_closes_usage_reporter(monkeypatch):
def set_usage_reporter(self, value):
assigned_reporters.append(value)
+ def set_agent_evolution_config(self, config):
+ assigned_agent_evolution_configs.append(config)
+
class Service:
sessions = Sessions()
@@ -131,10 +161,12 @@ async def test_app_reuses_and_closes_usage_reporter(monkeypatch):
monkeypatch.setattr("openviking.server.app.get_task_tracker", lambda: TaskTracker())
monkeypatch.setattr("openviking.server.mcp_endpoint.mcp_lifespan", mcp_lifespan)
- app = create_app(config=ServerConfig(), service=Service())
+ config = ServerConfig.model_validate({"agent_evolution": {"enabled": True}})
+ app = create_app(config=config, service=Service())
async with app.router.lifespan_context(app):
pass
assert built_reporters == [reporter]
assert assigned_reporters == [reporter, reporter]
+ assert [config.enabled for config in assigned_agent_evolution_configs] == [True, True]
assert reporter.closed is True