Skip to content

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

feat(session): add turn-aware retention and reliable archive recovery (#3380)

DuTao0ab85f450a9d
diff --git a/bot/docs/en/concepts/04-openviking-integration.md b/bot/docs/en/concepts/04-openviking-integration.md
index c38287847..56fbb0c2f 100644
--- a/bot/docs/en/concepts/04-openviking-integration.md
+++ b/bot/docs/en/concepts/04-openviking-integration.md
@@ -188,9 +188,23 @@ The `message.compact` Hook performs this synchronization. Important settings inc
| Setting | Purpose |
|---------|---------|
| `agents.commit_token_threshold` | Commit when pending tokens reach this value |
-| `agents.commit_keep_recent_count` | Number of recent messages retained after commit |
+| `agents.commit_keep_recent_turn_count` | Maximum number of recent logical Turns retained after commit; default: `3` |
+| `agents.commit_retained_message_token_budget` | Token budget for retained messages and the checkpoint after commit; default: `6000` |
+| `agents.commit_min_raw_tail_steps` | Minimum number of trailing assistant Steps kept verbatim when the newest Turn exceeds the budget; default: `1` |
+| `agents.commit_keep_recent_count` | Deprecated physical-message setting, retained only for compatibility with existing configuration files |
| `agents.memory_window` | Local history window, also used as a message-count commit threshold |
+A logical Turn starts with a real user query and includes every assistant Step before the next real user query. Each Step keeps the assistant text, tool calls, and corresponding tool results as an indivisible unit. The system first selects recent Turns using `commit_keep_recent_turn_count`, then applies `commit_retained_message_token_budget` to the retained content. If the newest Turn alone exceeds the budget, its user query and at least `commit_min_raw_tail_steps` latest Steps remain verbatim while earlier Steps are represented by the checkpoint generated during the same archive operation.
+
+For migration, `commit_keep_recent_count` is not automatically converted from a physical-message count to a Turn count, and the current VikingBot Turn-aware commit path no longer reads it. The configuration model still accepts the field, so an existing `ov.conf` does not fail because of an unknown setting. If only the deprecated field is present, the three new settings use their defaults. Configure the new fields explicitly to preserve a customized retention policy:
+
+```yaml
+agents:
+ commit_keep_recent_turn_count: 3
+ commit_retained_message_token_budget: 6000
+ commit_min_raw_tail_steps: 1
+```
+
Messages use local indexes for incremental synchronization, avoiding repeated appends on every turn. A synchronization failure is stored in metadata and logged, but optional memory functionality does not block basic chat.
## Compressed Session Context
diff --git a/bot/docs/zh/concepts/04-openviking-integration.md b/bot/docs/zh/concepts/04-openviking-integration.md
index 8572424fe..216c2837f 100644
--- a/bot/docs/zh/concepts/04-openviking-integration.md
+++ b/bot/docs/zh/concepts/04-openviking-integration.md
@@ -188,9 +188,23 @@ VikingBot Session metadata 记录 OpenViking 同步状态:
| 配置 | 作用 |
|------|------|
| `agents.commit_token_threshold` | pending token 达到该值后 commit |
-| `agents.commit_keep_recent_count` | commit 后保留的最近消息数 |
+| `agents.commit_keep_recent_turn_count` | commit 后最多保留的最近逻辑 Turn 数;默认 `3` |
+| `agents.commit_retained_message_token_budget` | commit 后 retained messages 与 checkpoint 的 token 预算;默认 `6000` |
+| `agents.commit_min_raw_tail_steps` | 最新 Turn 超出预算时,至少原样保留的末尾 assistant Step 数;默认 `1` |
+| `agents.commit_keep_recent_count` | 已废弃的物理消息数配置,仅为兼容旧配置文件而保留 |
| `agents.memory_window` | 本地历史窗口,也可触发消息数阈值提交 |
+一个逻辑 Turn 从真实 user query 开始,包含下一条真实 user query 之前的全部 assistant Step;每个 Step 会将 assistant 文本、工具调用和对应工具结果作为不可拆分的整体处理。系统先按 `commit_keep_recent_turn_count` 选择最近 Turn,再用 `commit_retained_message_token_budget` 约束 retained 内容。如果最新 Turn 本身超出预算,则保留 user query 和至少 `commit_min_raw_tail_steps` 个最新 Step,较早 Step 进入同一次归档生成的 checkpoint。
+
+迁移旧配置时,`commit_keep_recent_count` 不会自动换算为 Turn 数,当前 VikingBot 的 Turn-aware commit 也不再读取它。该字段仍被配置模型接受,因此已有 `ov.conf` 不会因未知字段而加载失败。如果只保留旧字段,系统会使用三个新字段的默认值;需要保持自定义保留策略时,应显式配置新字段,例如:
+
+```yaml
+agents:
+ commit_keep_recent_turn_count: 3
+ commit_retained_message_token_budget: 6000
+ commit_min_raw_tail_steps: 1
+```
+
消息使用本地索引增量同步,避免每轮重复 append。同步失败会写入 metadata 并记录日志,但不会让可选记忆能力阻断基础对话。
## 压缩会话上下文
diff --git a/bot/tests/test_agent_loop_outcome.py b/bot/tests/test_agent_loop_outcome.py
index f2be2b363..03fbad040 100644
--- a/bot/tests/test_agent_loop_outcome.py
+++ b/bot/tests/test_agent_loop_outcome.py
@@ -549,6 +549,71 @@ async def test_agent_loop_build_prompt_history_enforces_token_budget_for_live_to
assert any("History truncated" in str(message.get("content", "")) for message in history)
+async def test_agent_loop_build_prompt_history_preserves_anchor_when_final_needs_truncation(
+ temp_dir: Path, monkeypatch
+):
+ monkeypatch.setattr(AgentLoop, "_register_builtin_hooks", lambda self: None)
+ monkeypatch.setattr(AgentLoop, "_register_default_tools", lambda self: None)
+ monkeypatch.setattr("vikingbot.agent.loop.SubagentManager", _FakeSubagentManager)
+
+ fake_ov_client = _FakeOVClient(
+ context_payload={
+ "messages": [
+ {"role": "user", "parts": [{"type": "text", "text": "u" * 400}]},
+ {"role": "assistant", "parts": [{"type": "text", "text": "a" * 7600}]},
+ ]
+ }
+ )
+
+ async def fake_get_ov_client(self, session_key, openviking_connection=None, actor_peer_id=None):
+ del self, session_key, openviking_connection, actor_peer_id
+ return fake_ov_client
+
+ monkeypatch.setattr(AgentLoop, "_get_ov_client", fake_get_ov_client)
+
+ loop = AgentLoop(
+ bus=MessageBus(),
+ provider=_FakeProvider(),
+ workspace=temp_dir / "workspace",
+ config=Config(
+ storage_workspace=str(temp_dir),
+ ov_server={"server_url": "http://127.0.0.1:1933"},
+ agents={"session_context_enabled": True, "session_context_token_budget": 3000},
+ ),
+ )
+ session = loop.sessions.get_or_create(
+ SessionKey(type="cli", channel_id="default", chat_id="session-long-final"),
+ skip_heartbeat=True,
+ )
+ session.metadata["openviking"] = {
+ "session_id": "ov-session-long-final",
+ "last_synced_local_index": -1,
+ }
+
+ history = await loop._build_prompt_history(session)
+
+ assert fake_ov_client.context_calls == [("ov-session-long-final", 3000)]
+ assert [message["role"] for message in history] == ["user", "assistant"]
+ assert history[0]["content"] == "u" * 400
+ assert "History truncated" in history[1]["content"]
+ assert sum(loop._history_message_tokens(message) for message in history) <= 3000
+
+
+def test_agent_loop_turn_aware_trim_reserves_space_for_short_final():
+ history = [
+ {"role": "user", "content": "u" * 20},
+ {"role": "assistant", "content": "a"},
+ ]
+
+ trimmed = AgentLoop._trim_history_to_token_budget(history, 10)
+
+ assert [message["role"] for message in trimmed] == ["user", "assistant"]
+ assert trimmed[0]["content"]
+ assert trimmed[1]["content"] == "a"
+ assert sum(AgentLoop._history_message_tokens(message) for message in trimmed) <= 10
+
+
@pytest.mark.asyncio
async def test_agent_loop_submits_openviking_session_through_compact_hook(
temp_dir: Path, monkeypatch
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.py
index 19d47e2b1..596948943 100644
--- a/bot/vikingbot/agent/loop.py
+++ b/bot/vikingbot/agent/loop.py
@@ -493,7 +493,10 @@ class AgentLoop:
# Very small budgets may not fit the marker. Preserve as much raw text
# as possible while still honoring the hard limit.
if not best:
- low = 0
+ # Empty content is not a valid candidate and breaks the monotonic
+ # assumption of this binary search: "" is rejected while a
+ # one-character prefix may fit.
+ low = 1
high = len(content)
while low <= high:
mid = (low + high) // 2
@@ -521,7 +524,7 @@ class AgentLoop:
messages: list[dict[str, Any]],
token_budget: int,
) -> list[dict[str, Any]]:
- """Keep the newest contiguous history tail within a hard token budget."""
+ """Fit history to a hard budget without dropping the latest User anchor."""
if token_budget <= 0 or not messages:
return []
@@ -529,21 +532,152 @@ class AgentLoop:
if total_tokens <= token_budget:
return messages
- remaining = token_budget
- retained_reversed: list[dict[str, Any]] = []
- for message in reversed(messages):
+ latest_anchor_index = next(
+ (
+ index
+ for index in range(len(messages) - 1, -1, -1)
+ if messages[index].get("role") == "user"
+ ),
+ None,
+ )
+ if latest_anchor_index is None:
+ # Legacy assistant-only history has no Turn boundary to preserve.
+ remaining = token_budget
+ retained_reversed: list[dict[str, Any]] = []
+ for message in reversed(messages):
+ message_tokens = cls._history_message_tokens(message)
+ if message_tokens <= remaining:
+ retained_reversed.append(message)
+ remaining -= message_tokens
+ continue
+
+ clipped = cls._truncate_history_message(message, remaining)
+ if clipped is not None:
+ retained_reversed.append(clipped)
+ break
+ return list(reversed(retained_reversed))
+
+ final_index = next(
+ (
+ index
+ for index in range(len(messages) - 1, latest_anchor_index, -1)
+ if messages[index].get("role") == "assistant"
+ ),
+ None,
+ )
+
+ selected: dict[int, dict[str, Any]] = {}
+ used_tokens = 0
+
+ def _select_message(
+ index: int,
+ *,
+ allow_truncate: bool,
+ max_budget: int | None = None,
+ ) -> tuple[bool, bool]:
+ nonlocal used_tokens
+ remaining = max(0, token_budget - used_tokens)
+ if max_budget is not None:
+ remaining = min(remaining, max(0, int(max_budget)))
+
+ message = messages[index]
message_tokens = cls._history_message_tokens(message)
- if message_tokens <= remaining:
- retained_reversed.append(message)
- remaining -= message_tokens
- continue
+ chosen = message
+ truncated = False
+ if message_tokens > remaining:
+ if not allow_truncate or remaining <= 0:
+ return False, False
+ clipped = cls._truncate_history_message(message, remaining)
+ if clipped is None:
+ return False, False
+ chosen = clipped
+ truncated = True
+
+ selected[index] = chosen
+ used_tokens += cls._history_message_tokens(chosen)
+ return True, truncated
+
+ def _minimum_message_budget(index: int) -> int | None:
+ message = messages[index]
+ message_tokens = cls._history_message_tokens(message)
+ if message_tokens == 0:
+ return 0
- clipped = cls._truncate_history_message(message, remaining)
- if clipped is not None:
- retained_reversed.append(clipped)
- break
+ low = 1
+ high = min(message_tokens, token_budget)
+ minimum: int | None = None
+ while low <= high:
+ candidate = (low + high) // 2
+ if cls._truncate_history_message(message, candidate) is not None:
+ minimum = candidate
+ high = candidate - 1
+ else:
+ low = candidate + 1
+ return minimum
+
+ # OpenViking already returns Turn-aware context, but VikingBot applies a
+ # second budget with a different estimator after adding the local tail.
+ # Jointly reserve room for the latest User anchor and final Assistant so
+ # this final boundary cannot turn the prompt back into a half Turn.
+ final_reserve = 0
+ if final_index is not None:
+ anchor_minimum = _minimum_message_budget(latest_anchor_index)
+ final_minimum = _minimum_message_budget(final_index)
+ if (
+ anchor_minimum is not None
+ and final_minimum is not None
+ and anchor_minimum + final_minimum <= token_budget
+ ):
+ final_reserve = min(
+ cls._history_message_tokens(messages[final_index]),
+ max(final_minimum, token_budget // 2),
+ token_budget - anchor_minimum,
+ )
+
+ _select_message(
+ latest_anchor_index,
+ allow_truncate=True,
+ max_budget=token_budget - final_reserve,
+ )
+ if final_index is not None:
+ _select_message(final_index, allow_truncate=True)
+
+ # Prefer the newest remaining Steps in the latest Turn. At most one Step
+ # is clipped; older material is useful only while this suffix remains
+ # lossless.
+ latest_turn_end = final_index if final_index is not None else len(messages)
+ for index in range(latest_turn_end - 1, latest_anchor_index, -1):
+ kept, truncated = _select_message(index, allow_truncate=True)
+ if not kept or truncated:
+ break
- return list(reversed(retained_reversed))
+ # Add older Turns only as complete units so the final prompt never starts
+ # from the assistant half of an earlier Turn. An assistant-only prefix
+ # such as the archive overview is treated as one conservative unit.
+ older_turns: list[list[int]] = []
+ current_turn: list[int] = []
+ for index in range(latest_anchor_index):
+ if messages[index].get("role") == "user" and current_turn:
+ older_turns.append(current_turn)
+ current_turn = []
+ current_turn.append(index)
+ if current_turn:
+ older_turns.append(current_turn)
+
+ remaining = token_budget
+ remaining -= used_tokens
+ for turn_indexes in reversed(older_turns):
+ turn_tokens = sum(
+ cls._history_message_tokens(messages[index]) for index in turn_indexes
+ )
+ if turn_tokens > remaining:
+ break
+ for index in turn_indexes:
+ selected[index] = messages[index]
+ used_tokens += turn_tokens
+ remaining -= turn_tokens
+
+ return [selected[index] for index in sorted(selected)]
async def _build_prompt_history(
self,
@@ -616,7 +750,7 @@ class AgentLoop:
session: Session,
*,
force_commit: bool = False,
- keep_recent_count: int | None = None,
+ keep_recent_turn_count: int | None = None,
commit_message_threshold: int | None = None,
openviking_connection: dict[str, Any] | None = None,
) -> bool:
@@ -629,8 +763,8 @@ class AgentLoop:
"session": session,
"force_commit": force_commit,
}
- if keep_recent_count is not None:
- kwargs["keep_recent_count"] = keep_recent_count
+ if keep_recent_turn_count is not None:
+ kwargs["keep_recent_turn_count"] = keep_recent_turn_count
if commit_message_threshold is not None:
kwargs["commit_message_threshold"] = commit_message_threshold
if openviking_connection:
@@ -655,14 +789,14 @@ class AgentLoop:
session: Session,
*,
force_commit: bool = False,
- keep_recent_count: int | None = None,
+ keep_recent_turn_count: int | None = None,
commit_message_threshold: int | None = None,
openviking_connection: dict[str, Any] | None = None,
) -> bool:
success = await self._submit_openviking_session(
session,
force_commit=force_commit,
- keep_recent_count=keep_recent_count,
+ keep_recent_turn_count=keep_recent_turn_count,
commit_message_threshold=commit_message_threshold,
openviking_connection=openviking_connection,
)
@@ -708,7 +842,9 @@ class AgentLoop:
await self._submit_openviking_session_and_clear_if_committed(
session,
force_commit=True,
- keep_recent_count=int(getattr(agents_config, "commit_keep_recent_count", 10) or 0),
+ keep_recent_turn_count=int(
+ getattr(agents_config, "commit_keep_recent_turn_count", 3) or 0
+ ),
commit_message_threshold=self.memory_window,
openviking_connection=getattr(msg, "openviking_connection", None),
)
@@ -717,7 +853,7 @@ class AgentLoop:
self,
session: Session,
*,
- keep_recent_count: int = 0,
+ keep_recent_turn_count: int = 0,
clear_local_session: bool = False,
rotate_session_id: bool = False,
openviking_connection: dict[str, Any] | None = None,
@@ -725,7 +861,7 @@ class AgentLoop:
success = await self._submit_openviking_session(
session,
force_commit=True,
- keep_recent_count=keep_recent_count,
+ keep_recent_turn_count=keep_recent_turn_count,
openviking_connection=openviking_connection,
)
if not success:
@@ -1252,7 +1388,7 @@ class AgentLoop:
if self._ov_session_context_enabled():
committed = await self._commit_openviking_session(
session,
- keep_recent_count=0,
+ keep_recent_turn_count=0,
clear_local_session=True,
openviking_connection=openviking_connection,
)
@@ -1287,7 +1423,7 @@ class AgentLoop:
if self._ov_session_context_enabled():
remembered = await self._commit_openviking_session(
session,
- keep_recent_count=self.config.agents.commit_keep_recent_count,
+ keep_recent_turn_count=self.config.agents.commit_keep_recent_turn_count,
openviking_connection=openviking_connection,
)
if not remembered:
diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.py
index 657319629..a9b8c54cf 100644
--- a/bot/vikingbot/config/schema.py
+++ b/bot/vikingbot/config/schema.py
@@ -459,7 +459,28 @@ class AgentsConfig(BaseModel):
session_context_enabled: bool = True
session_context_token_budget: int = 3000
commit_token_threshold: int = 200000
- commit_keep_recent_count: int = 10
+ commit_keep_recent_count: int = Field(
+ default=10,
+ description=(
+ "Deprecated physical-message retention setting. VikingBot session context "
+ "commits now use logical Turn retention."
+ ),
+ )
+ commit_keep_recent_turn_count: int = Field(
+ default=3,
+ ge=0,
+ description="Number of newest logical user Turns retained after an OpenViking commit.",
+ )
+ commit_retained_message_token_budget: int = Field(
+ default=6_000,
+ gt=0,
+ description="Token budget for retained raw OpenViking session messages and checkpoints.",
+ )
+ commit_min_raw_tail_steps: int = Field(
+ default=1,
+ ge=0,
+ description="Minimum number of latest assistant Steps retained without compaction.",
+ )
gen_image_model: str = "openai/doubao-seedream-4-5-251128"
thinking: bool = Field(
default=True,
diff --git a/bot/vikingbot/hooks/builtins/openviking_hooks.py b/bot/vikingbot/hooks/builtins/openviking_hooks.py
index 261eb64f4..201f07f03 100644
--- a/bot/vikingbot/hooks/builtins/openviking_hooks.py
+++ b/bot/vikingbot/hooks/builtins/openviking_hooks.py
@@ -83,7 +83,9 @@ class OpenVikingCompactHook(Hook):
admin_user_id: str,
*,
force_commit: bool,
- keep_recent_count: int,
+ keep_recent_turn_count: int,
+ retained_message_token_budget: int,
+ min_raw_tail_steps: int,
commit_message_threshold: int | None,
) -> dict[str, Any]:
state = get_openviking_state(session)
@@ -139,7 +141,11 @@ class OpenVikingCompactHook(Hook):
if should_commit:
admin_commit_result = await client.commit_session(
session_id=session_id,
- keep_recent_count=keep_recent_count,
+ keep_recent_count=0,
+ retention_mode="turn_budget",
+ keep_recent_turn_count=keep_recent_turn_count,
+ retained_message_token_budget=retained_message_token_budget,
+ min_raw_tail_steps=min_raw_tail_steps,
user_id=session_user_id,
)
logger.info(
@@ -182,10 +188,24 @@ class OpenVikingCompactHook(Hook):
if not isinstance(openviking_connection, dict):
openviking_connection = None
force_commit = bool(kwargs.get("force_commit", False))
- keep_recent_count = int(
+ keep_recent_turn_count = int(
kwargs.get(
- "keep_recent_count",
- getattr(agents_config, "commit_keep_recent_count", 10),
+ "keep_recent_turn_count",
+ getattr(agents_config, "commit_keep_recent_turn_count", 3),
+ )
+ or 0
+ )
+ retained_message_token_budget = int(
+ kwargs.get(
+ "retained_message_token_budget",
+ getattr(agents_config, "commit_retained_message_token_budget", 6_000),
+ )
+ or 6_000
+ )
+ min_raw_tail_steps = int(
+ kwargs.get(
+ "min_raw_tail_steps",
+ getattr(agents_config, "commit_min_raw_tail_steps", 1),
)
or 0
)
@@ -226,7 +246,9 @@ class OpenVikingCompactHook(Hook):
agents_config,
admin_user_id,
force_commit=force_commit,
- keep_recent_count=keep_recent_count,
+ keep_recent_turn_count=keep_recent_turn_count,
+ retained_message_token_budget=retained_message_token_budget,
+ min_raw_tail_steps=min_raw_tail_steps,
commit_message_threshold=commit_message_threshold,
)
diff --git a/bot/vikingbot/openviking_mount/ov_server.py b/bot/vikingbot/openviking_mount/ov_server.py
index 5f5beba8b..511b326b6 100644
--- a/bot/vikingbot/openviking_mount/ov_server.py
+++ b/bot/vikingbot/openviking_mount/ov_server.py
@@ -1124,6 +1124,10 @@ class VikingClient:
keep_recent_count: int = 0,
user_id: Optional[str] = None,
memory_policy: Optional[Dict[str, Any]] = None,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
) -> Dict[str, Any]:
await self.ensure_session(
session_id,
@@ -1133,9 +1137,20 @@ class VikingClient:
else self.default_memory_policy(),
)
client = await self._session_client_for_user(user_id)
+ retention_kwargs = {
+ key: value
+ for key, value in {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }.items()
+ if value is not None
+ }
return await client.commit_session(
session_id,
keep_recent_count=keep_recent_count,
+ **retention_kwargs,
)
async def commit(
@@ -1146,6 +1161,10 @@ class VikingClient:
keep_recent_count: int = 0,
peer_id: Optional[str] = None,
memory_policy: Optional[Dict[str, Any]] = None,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
):
"""Append messages to a stable session and commit it."""
session_user_id = self._effective_session_user_id(user_id)
@@ -1163,11 +1182,22 @@ class VikingClient:
default_user_peer_id=self._peer_id(peer_id),
session_user_id=session_user_id,
)
+ retention_kwargs = {
+ key: value
+ for key, value in {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }.items()
+ if value is not None
+ }
commit_result = await self.commit_session(
session_id,
keep_recent_count=keep_recent_count,
user_id=session_user_id,
memory_policy=session_memory_policy,
+ **retention_kwargs,
)
logger.debug(
f"Committed OpenViking session {session_id}, "
diff --git a/bot/vikingbot/tests/unit/test_bot_provider_thinking.py b/bot/vikingbot/tests/unit/test_bot_provider_thinking.py
index 53525665f..9c34ef897 100644
--- a/bot/vikingbot/tests/unit/test_bot_provider_thinking.py
+++ b/bot/vikingbot/tests/unit/test_bot_provider_thinking.py
@@ -14,6 +14,16 @@ def test_agents_config_defaults_thinking_enabled():
assert AgentsConfig(thinking=False).thinking is False
+def test_agents_openviking_retention_defaults_to_turn_budget_values():
+ config = AgentsConfig()
+
+ assert config.commit_keep_recent_count == 10
+ assert AgentsConfig(commit_keep_recent_count=7).commit_keep_recent_count == 7
+ assert config.commit_keep_recent_turn_count == 3
+ assert config.commit_retained_message_token_budget == 6_000
+ assert config.commit_min_raw_tail_steps == 1
+
+
def test_make_provider_passes_default_thinking_to_vlm_adapter(monkeypatch):
monkeypatch.setitem(
sys.modules,
@@ -23,7 +33,7 @@ def test_make_provider_passes_default_thinking_to_vlm_adapter(monkeypatch):
monkeypatch.setitem(
sys.modules,
"prompt_toolkit.formatted_text",
- SimpleNamespace(HTML=lambda value: value),
+ SimpleNamespace(HTML=lambda value: value, FormattedText=lambda value: value),
)
monkeypatch.setitem(
sys.modules,
@@ -35,6 +45,13 @@ def test_make_provider_passes_default_thinking_to_vlm_adapter(monkeypatch):
"prompt_toolkit.patch_stdout",
SimpleNamespace(patch_stdout=lambda: contextlib.nullcontext()),
)
+ monkeypatch.setitem(
+ sys.modules,
+ "prompt_toolkit.styles",
+ SimpleNamespace(
+ Style=SimpleNamespace(from_dict=lambda value: value),
+ ),
+ )
from vikingbot.cli.commands import _make_provider
diff --git a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py b/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
index 90533a9a6..feed35b6e 100644
--- a/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
+++ b/bot/vikingbot/tests/unit/test_openviking_peer_identity.py
@@ -107,12 +107,14 @@ def test_normalize_session_messages_preserves_assistant_turn_tool_relationship()
{
"role": "assistant",
"content": "final answer",
+ "reasoning_content": "private final reasoning",
"timestamp": "2026-07-14T10:00:03Z",
"tools_used": [{"tool_name": "legacy", "result": "must not duplicate"}],
"agent_turns": [
{
"role": "assistant",
"content": "Let me check these.",
+ "reasoning_content": "private intermediate reasoning",
"timestamp": "2026-07-14T10:00:01Z",
"tool_calls": [
{
@@ -164,6 +166,8 @@ def test_normalize_session_messages_preserves_assistant_turn_tool_relationship()
for message in normalized
for part in message.get("parts", [])
)
+ assert "private final reasoning" not in str(normalized)
+ assert "private intermediate reasoning" not in str(normalized)
def test_normalize_session_messages_excludes_auto_memory_search():
@@ -401,6 +405,47 @@ async def test_commit_session_defaults_to_peer_only_memory(monkeypatch):
}
+async def test_commit_session_forwards_turn_budget_retention(monkeypatch):
+ client = _client(api_key_type="user")
+ calls = {}
+
+ async def fake_ensure_session(session_id, user_id=None, memory_policy=None):
+ return {"session_id": session_id}
+
+ class FakeSessionClient:
+ async def commit_session(self, session_id, keep_recent_count=0, **kwargs):
+ calls["commit"] = {
+ "session_id": session_id,
+ "keep_recent_count": keep_recent_count,
+ **kwargs,
+ }
+ return {"archived": True}
+
+ async def fake_session_client_for_user(user_id=None):
+ return FakeSessionClient()
+
+ monkeypatch.setattr(client, "ensure_session", fake_ensure_session)
+ monkeypatch.setattr(client, "_session_client_for_user", fake_session_client_for_user)
+
+ await client.commit_session(
+ "session-1",
+ retention_mode="turn_budget",
+ keep_recent_turn_count=3,
+ retained_message_token_budget=12_000,
+ min_raw_tail_steps=1,
+ )
+
+ assert calls["commit"] == {
+ "session_id": "session-1",
+ "keep_recent_count": 0,
+ "retention_mode": "turn_budget",
+ "keep_recent_turn_count": 3,
+ "retained_message_token_budget": 12_000,
+ "min_raw_tail_steps": 1,
+ }
+
+
@pytest.mark.asyncio
async def test_search_with_peer_id_uses_peer_target_uri_without_forwarding_peer_id():
client = _client(api_key_type="user")
diff --git a/bot/vikingbot/tests/unit/test_openviking_session_retention.py b/bot/vikingbot/tests/unit/test_openviking_session_retention.py
new file mode 100644
index 000000000..1703a66f1
--- /dev/null
+++ b/bot/vikingbot/tests/unit/test_openviking_session_retention.py
@@ -0,0 +1,122 @@
+from types import SimpleNamespace
+
+import pytest
+
+from vikingbot.agent.loop import AgentLoop
+from vikingbot.config.schema import SessionKey
+from vikingbot.hooks.base import HookContext
+from vikingbot.hooks.builtins.openviking_hooks import OpenVikingCompactHook
+from vikingbot.session.manager import Session
+
+
+async def test_session_context_commit_uses_turn_budget_retention():
+ session_key = SessionKey(type="test", channel_id="channel", chat_id="chat")
+ session = Session(key=session_key)
+ session.add_message("user", "question")
+ session.add_message("assistant", "answer")
+ commit_calls: list[dict] = []
+
+ class FakeClient:
+ @staticmethod
+ def session_owner_user_id():
+ return None
+
+ @staticmethod
+ async def append_messages(**kwargs):
+ return {"added": len(kwargs["messages"])}
+
+ @staticmethod
+ async def get_session(session_id, user_id=None):
+ return {"session_id": session_id, "pending_tokens": 0}
+
+ @staticmethod
+ async def commit_session(**kwargs):
+ commit_calls.append(kwargs)
+ return {"archived": True}
+
+ result = await OpenVikingCompactHook()._execute_session_context_commit(
+ HookContext(event_type="message.compact", session_key=session_key),
+ session,
+ FakeClient(),
+ SimpleNamespace(commit_token_threshold=200_000),
+ "admin",
+ force_commit=True,
+ keep_recent_turn_count=3,
+ retained_message_token_budget=12_000,
+ min_raw_tail_steps=1,
+ commit_message_threshold=None,
+ )
+
+ assert result["success"] is True
+ assert commit_calls == [
+ {
+ "session_id": session_key.safe_name(),
+ "keep_recent_count": 0,
+ "retention_mode": "turn_budget",
+ "keep_recent_turn_count": 3,
+ "retained_message_token_budget": 12_000,
+ "min_raw_tail_steps": 1,
+ "user_id": None,
+ }
+ ]
+
+
+def test_prompt_history_consumes_overview_checkpoint_and_raw_tail_in_order():
+ session_key = SessionKey(type="test", channel_id="channel", chat_id="chat")
+ session = Session(key=session_key)
+ context_payload = {
+ "latest_archive_overview": "Earlier turns were compacted.",
+ "messages": [
+ {
+ "role": "user",
+ "message_kind": "user_query",
+ "parts": [{"type": "text", "text": "Investigate the outage"}],
+ },
+ {
+ "role": "assistant",
+ "message_kind": "checkpoint",
+ "parts": [
+ {
+ "type": "context",
+ "context_type": "memory",
+ "uri": "viking://user/default/sessions/s/history/archive_001",
+ "abstract": "Checked early signals and confirmed pool saturation.",
+ }
+ ],
+ },
+ {
+ "role": "assistant",
+ "message_kind": "assistant_step",
+ "parts": [
+ {"type": "text", "text": "I will verify the recovery setting."},
+ {
+ "type": "tool",
+ "tool_id": "call-2",
+ "tool_name": "read_config",
+ "tool_output": "recovery_timeout=30",
+ },
+ ],
+ },
+ ],
+ }
+
+ loop = AgentLoop.__new__(AgentLoop)
+ history = loop._build_ov_history_messages(session, context_payload)
+
+ assert [message["role"] for message in history] == [
+ "assistant",
+ "user",
+ "assistant",
+ "assistant",
+ ]
+ assert history[0]["content"] == (
+ "[Earlier conversation summary]\nEarlier turns were compacted."
+ )
+ assert history[1]["content"] == "Investigate the outage"
+ assert history[2]["content"] == (
+ "Checked early signals and confirmed pool saturation."
+ )
+ assert history[3]["content"] == (
+ "I will verify the recovery setting.\nrecovery_timeout=30"
+ )
diff --git a/openviking/async_client.py b/openviking/async_client.py
index 9e6f11361..8580dbd33 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -196,6 +196,9 @@ class AsyncOpenViking:
created_at: str | None = None,
peer_id: str | None = None,
telemetry: TelemetryRequest = False,
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
) -> Dict[str, Any]:
"""Add a message to a session.
@@ -210,6 +213,15 @@ class AsyncOpenViking:
If both content and parts are provided, parts takes precedence.
"""
await self._ensure_initialized()
+ semantic_kwargs = {
+ key: value
+ for key, value in {
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }.items()
+ if value is not None
+ }
return await self._client.add_message(
session_id=session_id,
role=role,
@@ -218,6 +230,7 @@ class AsyncOpenViking:
created_at=created_at,
peer_id=peer_id,
telemetry=telemetry,
+ **semantic_kwargs,
)
async def batch_add_messages(
@@ -240,13 +253,28 @@ class AsyncOpenViking:
telemetry: TelemetryRequest = False,
*,
keep_recent_count: int = 0,
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
) -> Dict[str, Any]:
"""Commit a session (archive and extract memories)."""
await self._ensure_initialized()
+ optional_retention = {
+ key: value
+ for key, value in {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }.items()
+ if value is not None
+ }
return await self._client.commit_session(
session_id,
telemetry=telemetry,
keep_recent_count=keep_recent_count,
+ **optional_retention,
)
async def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:
diff --git a/openviking/client/local.py b/openviking/client/local.py
index aecce6b78..0233b28d0 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -890,15 +890,29 @@ class LocalClient(BaseClient):
telemetry: TelemetryRequest = False,
*,
keep_recent_count: int = 0,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
) -> Dict[str, Any]:
"""Commit a session (archive and extract memories)."""
+ commit_kwargs: Dict[str, Any] = {"keep_recent_count": keep_recent_count}
+ optional_retention = {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }
+ commit_kwargs.update(
+ {key: value for key, value in optional_retention.items() if value is not None}
+ )
execution = await run_with_telemetry(
operation="session.commit",
telemetry=telemetry,
fn=lambda: self._service.sessions.commit(
session_id,
self._ctx,
- keep_recent_count=keep_recent_count,
+ **commit_kwargs,
),
)
return attach_telemetry_payload(
@@ -937,6 +951,9 @@ class LocalClient(BaseClient):
created_at: Optional[str] = None,
peer_id: Optional[str] = None,
telemetry: TelemetryRequest = False,
+ turn_id: Optional[str] = None,
+ message_kind: Optional[str] = None,
+ source_message_ids: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Add a message to a session.
@@ -960,6 +977,9 @@ class LocalClient(BaseClient):
parts,
created_at,
peer_id,
+ turn_id,
+ message_kind,
+ source_message_ids,
),
)
return attach_telemetry_payload(
@@ -975,6 +995,9 @@ class LocalClient(BaseClient):
parts: Optional[List[Dict[str, Any]]],
created_at: Optional[str],
peer_id: Optional[str],
+ turn_id: Optional[str],
+ message_kind: Optional[str],
+ source_message_ids: Optional[List[str]],
) -> Dict[str, Any]:
from openviking.message.part import Part, TextPart, part_from_dict
@@ -988,12 +1011,25 @@ class LocalClient(BaseClient):
else:
raise ValueError("Either content or parts must be provided")
- session.add_message(
- role,
- message_parts,
- peer_id=self._resolve_message_peer_id(role, peer_id),
- created_at=created_at,
- )
+ semantic_kwargs = {
+ key: value
+ for key, value in {
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }.items()
+ if value is not None
+ }
+ add_async = getattr(session, "add_message_async", None)
+ add_kwargs = {
+ "peer_id": self._resolve_message_peer_id(role, peer_id),
+ "created_at": created_at,
+ **semantic_kwargs,
+ }
+ if callable(add_async):
+ await add_async(role, message_parts, **add_kwargs)
+ else:
+ session.add_message(role, message_parts, **add_kwargs)
return {
"session_id": session_id,
"message_count": len(session.messages),
@@ -1045,10 +1081,17 @@ class LocalClient(BaseClient):
"parts": message_parts,
"peer_id": self._resolve_message_peer_id(role, message.get("peer_id")),
"created_at": message.get("created_at"),
+ "turn_id": message.get("turn_id"),
+ "message_kind": message.get("message_kind"),
+ "source_message_ids": message.get("source_message_ids"),
}
)
- added = session.add_messages(specs)
+ add_many_async = getattr(session, "add_messages_async", None)
+ if callable(add_many_async):
+ added = await add_many_async(specs)
+ else:
+ added = session.add_messages(specs)
return {
"session_id": session_id,
"message_count": len(session.messages),
diff --git a/openviking/client/session.py b/openviking/client/session.py
index b659aaff2..5286bfb69 100644
--- a/openviking/client/session.py
+++ b/openviking/client/session.py
@@ -42,6 +42,9 @@ class Session:
parts: Optional[List[Part]] = None,
created_at: Optional[str] = None,
peer_id: Optional[str] = None,
+ turn_id: Optional[str] = None,
+ message_kind: Optional[str] = None,
+ source_message_ids: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Add a message to the session.
@@ -57,6 +60,15 @@ class Session:
Returns:
Result dict with session_id and message_count
"""
+ semantic_kwargs = {
+ key: value
+ for key, value in {
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }.items()
+ if value is not None
+ }
if parts is not None:
parts_dicts = [asdict(p) for p in parts]
return await self._client.add_message(
@@ -65,6 +77,7 @@ class Session:
parts=parts_dicts,
created_at=created_at,
peer_id=peer_id,
+ **semantic_kwargs,
)
return await self._client.add_message(
self.session_id,
@@ -72,6 +85,7 @@ class Session:
content=content,
created_at=created_at,
peer_id=peer_id,
+ **semantic_kwargs,
)
async def batch_add_messages(
@@ -97,23 +111,38 @@ class Session:
telemetry: TelemetryRequest = False,
*,
keep_recent_count: int = 0,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
) -> Dict[str, Any]:
"""Commit the session (archive messages and extract memories).
Returns:
Commit result
"""
- return await self._client.commit_session(
- self.session_id,
- telemetry=telemetry,
- keep_recent_count=keep_recent_count,
- )
+ kwargs: Dict[str, Any] = {
+ "telemetry": telemetry,
+ "keep_recent_count": keep_recent_count,
+ }
+ optional = {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }
+ kwargs.update({key: value for key, value in optional.items() if value is not None})
+ return await self._client.commit_session(self.session_id, **kwargs)
async def commit_async(
self,
telemetry: TelemetryRequest = False,
*,
keep_recent_count: int = 0,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
) -> Dict[str, Any]:
"""Commit the session asynchronously (archive messages and extract memories).
Used in viking bot for committing.
@@ -124,6 +153,10 @@ class Session:
return await self.commit(
telemetry=telemetry,
keep_recent_count=keep_recent_count,
+ retention_mode=retention_mode,
+ keep_recent_turn_count=keep_recent_turn_count,
+ retained_message_token_budget=retained_message_token_budget,
+ min_raw_tail_steps=min_raw_tail_steps,
)
async def delete(self) -> None:
diff --git a/openviking/message/message.py b/openviking/message/message.py
index 7d119e1ad..3f2aa230f 100644
--- a/openviking/message/message.py
+++ b/openviking/message/message.py
@@ -24,6 +24,11 @@ class Message:
parts: List[Part]
peer_id: Optional[str] = None
created_at: str = None
+ turn_id: Optional[str] = None
+ message_kind: Optional[
+ Literal["user_query", "assistant_step", "tool_transport", "checkpoint"]
+ ] = None
+ source_message_ids: Optional[List[str]] = None
@property
def content(self) -> str:
@@ -83,6 +88,12 @@ class Message:
}
if self.peer_id is not None:
data["peer_id"] = self.peer_id
+ if self.turn_id is not None:
+ data["turn_id"] = self.turn_id
+ if self.message_kind is not None:
+ data["message_kind"] = self.message_kind
+ if self.source_message_ids is not None:
+ data["source_message_ids"] = list(self.source_message_ids)
return data
def _part_to_dict(self, part: Part) -> dict:
@@ -180,6 +191,13 @@ class Message:
parts=parts,
peer_id=peer_id,
created_at=data.get("created_at"),
+ turn_id=data.get("turn_id"),
+ message_kind=data.get("message_kind"),
+ source_message_ids=(
+ list(data.get("source_message_ids"))
+ if isinstance(data.get("source_message_ids"), list)
+ else None
+ ),
)
def to_jsonl(self) -> str:
diff --git a/openviking/prompts/templates/compression/ov_wm_v2.yaml b/openviking/prompts/templates/compression/ov_wm_v2.yaml
index 61172aad8..cf13c0729 100644
--- a/openviking/prompts/templates/compression/ov_wm_v2.yaml
+++ b/openviking/prompts/templates/compression/ov_wm_v2.yaml
@@ -2,7 +2,7 @@ metadata:
id: "compression.ov_wm_v2"
name: "Working Memory v2 - Creation"
description: "Produce a structured Working Memory document for a session archive (no prior WM)."
- version: "2.2.0"
+ version: "2.3.0"
language: "en"
category: "compression"
@@ -16,6 +16,11 @@ variables:
description: "Optional prior Working Memory. When provided, still-valid info should be carried forward."
required: false
default: ""
+ - name: "checkpoint_instructions"
+ type: "string"
+ description: "Optional instructions for checkpoint summaries produced by the same call."
+ required: false
+ default: ""
template: |
You are a session note-taker. Produce a structured Working Memory document
@@ -35,6 +40,10 @@ template: |
{{ messages }}
</session_content>
+ {% if checkpoint_instructions %}
+ {{ checkpoint_instructions }}
+ {% endif %}
+
Output a complete Working Memory using the 7-section structure below.
RULES:
@@ -83,5 +92,11 @@ template: |
## Open Issues
_Unresolved questions, blockers, follow-ups, risks, or topics to revisit._
+ {% if checkpoint_instructions %}
+ Put the complete document above in the `working_memory` field, satisfy the
+ checkpoint instructions in `checkpoint_summaries`, and call
+ `create_working_memory` exactly once. Do not emit freeform text.
+ {% endif %}
+
llm_config:
temperature: 0.0
diff --git a/openviking/prompts/templates/compression/ov_wm_v2_update.yaml b/openviking/prompts/templates/compression/ov_wm_v2_update.yaml
index 08aa15e06..d6679b5f9 100644
--- a/openviking/prompts/templates/compression/ov_wm_v2_update.yaml
+++ b/openviking/prompts/templates/compression/ov_wm_v2_update.yaml
@@ -2,7 +2,7 @@ metadata:
id: "compression.ov_wm_v2_update"
name: "Working Memory v2 - Incremental Update (tool_call)"
description: "Incrementally update an existing Working Memory by emitting per-section decisions via the `update_working_memory` tool."
- version: "2.4.0"
+ version: "2.5.0"
language: "en"
category: "compression"
@@ -20,12 +20,18 @@ variables:
description: "Dynamic section-size warnings generated from the current Working Memory."
required: false
default: ""
+ - name: "checkpoint_instructions"
+ type: "string"
+ description: "Optional instructions for checkpoint summaries produced by the same call."
+ required: false
+ default: ""
template: |
- You are the Working Memory maintainer for a long-running session. Your one and
- only job is to produce a per-section decision via the `update_working_memory`
- tool. The session will keep going for many more rounds, so information you
- drop now is GONE — nobody else will put it back.
+ You are the Working Memory maintainer for a long-running session. Produce a
+ per-section decision via the `update_working_memory` tool{% if checkpoint_instructions %}
+ and the explicitly requested checkpoint summaries in that same tool call{% endif %}.
+ The session will keep going for many more rounds, so information you drop now
+ is GONE — nobody else will put it back.
<current_wm>
{{ latest_archive_overview }}
@@ -35,6 +41,10 @@ template: |
{{ messages }}
</new_content>
+ {% if checkpoint_instructions %}
+ {{ checkpoint_instructions }}
+ {% endif %}
+
{% if wm_section_reminders %}
{{ wm_section_reminders }}
{% endif %}
@@ -193,7 +203,12 @@ template: |
URL lists instead of preserving each raw URL.
- Do not fabricate information not grounded in <new_content> or <current_wm>.
- You MUST call `update_working_memory` exactly once. No freeform text
- outside the tool call.
+ outside the tool call.
+ {% if checkpoint_instructions %}
+ - The same tool call MUST also include `checkpoint_summaries` exactly as
+ requested. Do not add message IDs, archive IDs, token budgets, or storage
+ metadata; the server owns that mapping.
+ {% endif %}
llm_config:
temperature: 0.0
diff --git a/openviking/server/mcp_endpoint.py b/openviking/server/mcp_endpoint.py
index be3f79ed7..88fb8a7d4 100644
--- a/openviking/server/mcp_endpoint.py
+++ b/openviking/server/mcp_endpoint.py
@@ -438,10 +438,11 @@ async def remember(messages: list[StoreMessage]) -> str:
session = await service.sessions.get(session_id, ctx, auto_create=True)
for msg in messages:
if msg.content:
- session.add_message(
- msg.role,
- [TextPart(text=msg.content)],
- )
+ add_async = getattr(session, "add_message_async", None)
+ if callable(add_async):
+ await add_async(msg.role, [TextPart(text=msg.content)])
+ else:
+ session.add_message(msg.role, [TextPart(text=msg.content)])
await service.sessions.commit_async(session_id, ctx)
return f"Stored {len(messages)} message(s) and committed for memory extraction."
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index 37afab144..562b9e3a1 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -90,6 +90,11 @@ class AddMessageRequest(BaseModel):
content: Optional[str] = None
parts: Optional[List[Dict[str, Any]]] = None
created_at: Optional[str] = None
+ turn_id: Optional[str] = None
+ message_kind: Optional[
+ Literal["user_query", "assistant_step", "tool_transport", "checkpoint"]
+ ] = None
+ source_message_ids: Optional[List[str]] = None
telemetry: TelemetryRequest = False
@field_validator("peer_id")
@@ -180,7 +185,6 @@ def _to_jsonable(value: Any) -> Any:
return value
-
@router.post("")
async def create_session(
request: CreateSessionRequest = Body(default_factory=CreateSessionRequest),
@@ -378,8 +382,46 @@ class CommitRequest(BaseModel):
"(default 10); compact path passes 0 to archive everything."
),
)
+ retention_mode: Optional[Literal["turn_budget"]] = Field(
+ default=None,
+ description=(
+ "Opt in to logical Turn retention. Omit to preserve keep_recent_count semantics."
+ ),
+ )
+ keep_recent_turn_count: Optional[int] = Field(
+ default=None,
+ ge=0,
+ le=10_000,
+ description="Maximum number of newest logical user Turns to retain.",
+ )
+ retained_message_token_budget: Optional[int] = Field(
+ default=None,
+ ge=1,
+ description="Token budget for retained raw messages and checkpoint.",
+ )
+ min_raw_tail_steps: Optional[int] = Field(
+ default=None,
+ ge=0,
+ le=10_000,
+ description="Minimum number of latest atomic assistant Steps kept raw.",
+ )
telemetry: TelemetryRequest = False
+ @model_validator(mode="after")
+ def validate_turn_retention_opt_in(self) -> "CommitRequest":
+ if self.retention_mode is None and any(
+ value is not None
+ for value in (
+ self.keep_recent_turn_count,
+ self.retained_message_token_budget,
+ self.min_raw_tail_steps,
+ )
+ ):
+ raise ValueError(
+ "retention_mode='turn_budget' is required when Turn retention fields are set"
+ )
+ return self
+
@router.post("/{session_id}/commit")
async def commit_session(
@@ -394,13 +436,23 @@ async def commit_session(
polling progress via ``GET /tasks/{task_id}``.
"""
service = get_service()
+ commit_kwargs: Dict[str, Any] = {"keep_recent_count": body.keep_recent_count}
+ optional_retention = {
+ "retention_mode": body.retention_mode,
+ "keep_recent_turn_count": body.keep_recent_turn_count,
+ "retained_message_token_budget": body.retained_message_token_budget,
+ "min_raw_tail_steps": body.min_raw_tail_steps,
+ }
+ commit_kwargs.update(
+ {key: value for key, value in optional_retention.items() if value is not None}
+ )
execution = await run_operation(
operation="session.commit",
telemetry=body.telemetry,
fn=lambda: service.sessions.commit_async(
session_id,
_ctx,
- keep_recent_count=body.keep_recent_count,
+ **commit_kwargs,
),
)
return Response(
@@ -448,16 +500,22 @@ async def add_message(
session = await service.sessions.get(session_id, _ctx, auto_create=True)
parts = _resolve_message_parts(request)
- session.add_messages(
- [
- {
- "role": request.role,
- "parts": parts,
- "peer_id": _resolve_message_peer_id(request, _ctx),
- "created_at": request.created_at,
- }
- ]
- )
+ specs = [
+ {
+ "role": request.role,
+ "parts": parts,
+ "peer_id": _resolve_message_peer_id(request, _ctx),
+ "created_at": request.created_at,
+ "turn_id": request.turn_id,
+ "message_kind": request.message_kind,
+ "source_message_ids": request.source_message_ids,
+ }
+ ]
+ add_many_async = getattr(session, "add_messages_async", None)
+ if callable(add_many_async):
+ await add_many_async(specs)
+ else:
+ session.add_messages(specs)
return {
"session_id": session_id,
"message_count": len(session.messages),
@@ -495,9 +553,16 @@ async def batch_add_messages(
"parts": parts,
"peer_id": _resolve_message_peer_id(msg_request, _ctx),
"created_at": msg_request.created_at,
+ "turn_id": msg_request.turn_id,
+ "message_kind": msg_request.message_kind,
+ "source_message_ids": msg_request.source_message_ids,
}
)
- msgs = session.add_messages(specs)
+ add_many_async = getattr(session, "add_messages_async", None)
+ if callable(add_many_async):
+ msgs = await add_many_async(specs)
+ else:
+ msgs = session.add_messages(specs)
return {
"session_id": session_id,
"message_count": len(session.messages),
diff --git a/openviking/service/resource_memory_link_service.py b/openviking/service/resource_memory_link_service.py
index 5280f1ede..89efed9b9 100644
--- a/openviking/service/resource_memory_link_service.py
+++ b/openviking/service/resource_memory_link_service.py
@@ -193,7 +193,11 @@ class ResourceMemoryLinkService:
}
if target_peer_id:
message_spec["peer_id"] = target_peer_id
- session.add_messages([message_spec])
+ add_many_async = getattr(session, "add_messages_async", None)
+ if callable(add_many_async):
+ await add_many_async([message_spec])
+ else:
+ session.add_messages([message_spec])
commit_result = await self._session_service.commit_async(
session_id,
ctx,
@@ -259,7 +263,11 @@ class ResourceMemoryLinkService:
}
if target_peer_id:
message_spec["peer_id"] = target_peer_id
- session.add_messages([message_spec])
+ add_many_async = getattr(session, "add_messages_async", None)
+ if callable(add_many_async):
+ await add_many_async([message_spec])
+ else:
+ session.add_messages([message_spec])
commit_result = await self._session_service.commit_async(
session_id,
ctx,
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index 867ecaf48..241903add 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -268,6 +268,11 @@ class SessionService:
session_id: str,
ctx: RequestContext,
keep_recent_count: int = 0,
+ *,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
) -> Dict[str, Any]:
"""Commit a session (archive messages and extract memories).
@@ -284,6 +289,10 @@ class SessionService:
session_id,
ctx,
keep_recent_count=keep_recent_count,
+ retention_mode=retention_mode,
+ keep_recent_turn_count=keep_recent_turn_count,
+ retained_message_token_budget=retained_message_token_budget,
+ min_raw_tail_steps=min_raw_tail_steps,
)
async def commit_async(
@@ -291,6 +300,11 @@ class SessionService:
session_id: str,
ctx: RequestContext,
keep_recent_count: int = 0,
+ *,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
) -> Dict[str, Any]:
"""Async commit a session.
@@ -308,7 +322,17 @@ class SessionService:
"""
self._ensure_initialized()
session = await self.get(session_id, ctx)
- result = await session.commit_async(keep_recent_count=keep_recent_count)
+ commit_kwargs: Dict[str, Any] = {"keep_recent_count": keep_recent_count}
+ optional_retention = {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }
+ commit_kwargs.update(
+ {key: value for key, value in optional_retention.items() if value is not None}
+ )
+ result = await session.commit_async(**commit_kwargs)
self._record_lifecycle_metric("commit", "ok" if result.get("status") else "error")
self._record_archive_metric("ok" if result.get("archived") else "skip")
return result
diff --git a/openviking/session/retention.py b/openviking/session/retention.py
new file mode 100644
index 000000000..ff18f383a
--- /dev/null
+++ b/openviking/session/retention.py
@@ -0,0 +1,509 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Pure planning for turn-aware session retention.
+
+The planner deliberately has no filesystem or model dependencies. It groups
+physical messages into logical user turns and atomic assistant steps, then
+chooses the archive/live boundary under a token budget.
+"""
+
+from __future__ import annotations
+
+import copy
+from dataclasses import dataclass, field
+from typing import Dict, Iterable, List, Optional
+
+from openviking.message import Message
+from openviking.message.part import ContextPart, TextPart, ToolPart
+from openviking.utils.token_estimation import truncate_text_to_token_budget
+
+RETENTION_MODE_TURN_BUDGET = "turn_budget"
+_CHECKPOINT_TOKEN_RESERVE = 1024
+
+
+def is_tool_transport(message: Message) -> bool:
+ """Return whether a user-role message only transports tool results."""
+ if message.message_kind == "tool_transport":
+ return True
+ if message.message_kind == "user_query":
+ return False
+ return (
+ bool(message.parts)
+ and message.role == "user"
+ and all(isinstance(part, ToolPart) for part in message.parts)
+ )
+
+
+def is_user_query(message: Message) -> bool:
+ """Return whether a message starts a real logical user turn."""
+ if message.message_kind == "user_query":
+ return True
+ if message.message_kind == "tool_transport":
+ return False
+ return message.role == "user" and not is_tool_transport(message)
+
+
+@dataclass
+class AssistantStep:
+ """One assistant response plus any following tool-transport messages."""
+
+ messages: List[Message] = field(default_factory=list)
+
+ @property
+ def estimated_tokens(self) -> int:
+ return sum(int(message.estimated_tokens or 0) for message in self.messages)
+
+
+@dataclass
+class UserTurn:
+ """A real user query and everything before the next real user query."""
+
+ anchor: Optional[Message] = None
+ steps: List[AssistantStep] = field(default_factory=list)
+
+ @property
+ def messages(self) -> List[Message]:
+ result: List[Message] = []
+ if self.anchor is not None:
+ result.append(self.anchor)
+ for step in self.steps:
+ result.extend(step.messages)
+ return result
+
+ @property
+ def estimated_tokens(self) -> int:
+ return sum(int(message.estimated_tokens or 0) for message in self.messages)
+
+
+@dataclass
+class RetentionPlan:
+ """The complete, deterministic output of a retention decision."""
+
+ archive_messages: List[Message]
+ retained_messages: List[Message]
+ turn_anchor: Optional[Message] = None
+ checkpoint_source_message_ids: List[str] = field(default_factory=list)
+ raw_tail_start_message_id: Optional[str] = None
+ estimated_active_tokens: int = 0
+ budget_exceeded: bool = False
+ partial_turn: bool = False
+
+ @property
+ def has_archive_work(self) -> bool:
+ return bool(self.archive_messages)
+
+
+@dataclass
+class ActiveMessageBudgetPlan:
+ """A non-destructive, budgeted view of active messages."""
+
+ messages: List[Message]
+ estimated_tokens: int
+ dropped_message_ids: List[str] = field(default_factory=list)
+ truncated_message_ids: List[str] = field(default_factory=list)
+
+
+def _append_to_turn(turn: UserTurn, message: Message) -> None:
+ """Append a message without splitting assistant/tool-result relationships."""
+ if is_tool_transport(message) and turn.steps:
+ turn.steps[-1].messages.append(message)
+ return
+
+ if message.role == "assistant":
+ turn.steps.append(AssistantStep(messages=[message]))
+ return
+
+ # Malformed/legacy input can contain transport messages before an assistant
+ # response. Keep those physical messages atomic in a conservative step.
+ turn.steps.append(AssistantStep(messages=[message]))
+
+
+def build_turns(messages: Iterable[Message]) -> List[UserTurn]:
+ """Group messages into logical turns while preserving their original order."""
+ turns: List[UserTurn] = []
+ current: Optional[UserTurn] = None
+
+ for message in messages:
+ if is_user_query(message):
+ current = UserTurn(anchor=message)
+ turns.append(current)
+ continue
+
+ if current is None:
+ # Preserve a legacy assistant-only prefix as one conservative turn.
+ current = UserTurn()
+ turns.append(current)
+ _append_to_turn(current, message)
+
+ return turns
+
+
+def _flatten_turns(turns: Iterable[UserTurn]) -> List[Message]:
+ return [message for turn in turns for message in turn.messages]
+
+
+def _message_tokens(messages: Iterable[Message]) -> int:
+ return sum(int(message.estimated_tokens or 0) for message in messages)
+
+
+def _truncate_message_group(
+ messages: List[Message],
+ token_budget: int,
+) -> tuple[List[Message], List[str]]:
+ """Return a virtual atomic group that fits ``token_budget``.
+
+ Durable messages are never mutated. Text/context bodies and tool outputs are
+ the only fields shortened. Tool IDs, names and result pairing remain intact;
+ oversized tool inputs are replaced only when their fixed serialized cost
+ would otherwise make the whole atomic Step impossible to return.
+ """
+ if token_budget <= 0 or not messages:
+ return [], []
+ if _message_tokens(messages) <= token_budget:
+ return list(messages), []
+
+ cloned = copy.deepcopy(messages)
+ slots: List[tuple[Message, object, str, str]] = []
+ truncated_ids: set[str] = set()
+
+ # Prefer the most recent material when an atomic Step itself is oversized.
+ for message in reversed(cloned):
+ for part in reversed(message.parts):
+ if isinstance(part, TextPart):
+ slots.append((message, part, "text", part.text or ""))
+ part.text = ""
+ elif isinstance(part, ContextPart):
+ slots.append((message, part, "abstract", part.abstract or ""))
+ part.abstract = ""
+ elif isinstance(part, ToolPart):
+ slots.append((message, part, "tool_output", part.tool_output or ""))
+ part.tool_output = ""
+
+ # Tool inputs are structured and cannot be text-truncated safely. Preserve
+ # them whenever possible, then remove oldest inputs until fixed metadata fits.
+ if _message_tokens(cloned) > token_budget:
+ for message in cloned:
+ for part in message.parts:
+ if not isinstance(part, ToolPart) or not part.tool_input:
+ continue
+ part.tool_input = {}
+ truncated_ids.add(message.id)
+ if _message_tokens(cloned) <= token_budget:
+ break
+ if _message_tokens(cloned) <= token_budget:
+ break
+
+ if _message_tokens(cloned) > token_budget:
+ return [], []
+
+ for _message, part, attribute, original in slots:
+ if not original:
+ continue
+ used = _message_tokens(cloned)
+ remaining = max(0, token_budget - used)
+ if remaining <= 0:
+ break
+ fitted = truncate_text_to_token_budget(original, remaining)
+ setattr(part, attribute, fitted)
+
+ # Record every cleared/shortened slot, including older fields that received
+ # no remaining budget at all. Keep enough tool metadata for callers to know
+ # that the returned body is only a preview of the durable raw output.
+ for message, part, attribute, original in slots:
+ fitted = getattr(part, attribute)
+ if fitted == original:
+ continue
+ truncated_ids.add(message.id)
+ if isinstance(part, ToolPart):
+ part.tool_output_truncated = True
+ if part.tool_output_original_chars is None:
+ part.tool_output_original_chars = len(original)
+ part.tool_output_preview_chars = len(fitted)
+
+ # The estimator and truncation helper share the same accounting, but keep a
+ # defensive final guard so this function is a strict budget boundary.
+ if _message_tokens(cloned) > token_budget:
+ return [], []
+ return cloned, sorted(truncated_ids)
+
+
+def fit_active_messages_to_budget(
+ messages: List[Message],
+ *,
+ token_budget: int,
+) -> ActiveMessageBudgetPlan:
+ """Build a strict, non-destructive active-message view under a token budget.
+
+ Selection order follows the retention RFC: newest User anchor, final
+ Assistant Step, checkpoint, recent Steps, then older complete Turns. An
+ Assistant Step is selected or truncated atomically, so call/result transport
+ messages never land on opposite sides of the returned boundary.
+ """
+ token_budget = max(0, int(token_budget or 0))
+ if not messages or token_budget == 0:
+ return ActiveMessageBudgetPlan(
+ messages=[],
+ estimated_tokens=0,
+ dropped_message_ids=[message.id for message in messages],
+ )
+
+ total_tokens = _message_tokens(messages)
+ if total_tokens <= token_budget:
+ return ActiveMessageBudgetPlan(messages=list(messages), estimated_tokens=total_tokens)
+
+ turns = build_turns(messages)
+ message_indexes: Dict[int, int] = {id(message): index for index, message in enumerate(messages)}
+ selected: Dict[int, Message] = {}
+ truncated_ids: set[str] = set()
+ used_tokens = 0
+
+ def _select_group(
+ group: List[Message],
+ *,
+ allow_truncate: bool,
+ max_budget: Optional[int] = None,
+ ) -> bool:
+ nonlocal used_tokens
+ if not group:
+ return True
+ remaining = max(0, token_budget - used_tokens)
+ if max_budget is not None:
+ remaining = min(remaining, max(0, int(max_budget)))
+ group_tokens = _message_tokens(group)
+ chosen = list(group)
+ group_truncated: List[str] = []
+ if group_tokens > remaining:
+ if not allow_truncate or remaining <= 0:
+ return False
+ chosen, group_truncated = _truncate_message_group(group, remaining)
+ if not chosen:
+ return False
+
+ for original, returned in zip(group, chosen, strict=True):
+ selected[message_indexes[id(original)]] = returned
+ used_tokens += _message_tokens(chosen)
+ truncated_ids.update(group_truncated)
+ return True
+
+ latest = turns[-1]
+ final_step = latest.steps[-1] if latest.steps else None
+ anchor_group = [latest.anchor] if latest.anchor is not None else []
+ final_group = final_step.messages if final_step is not None else []
+
+ def _minimum_group_budget(group: List[Message]) -> Optional[int]:
+ """Return the smallest budget for which a truncated group is selectable."""
+ group_tokens = _message_tokens(group)
+ if not group or group_tokens == 0:
+ return 0
+
+ low = 1
+ high = min(group_tokens, token_budget)
+ minimum: Optional[int] = None
+ while low <= high:
+ candidate = (low + high) // 2
+ chosen, _ = _truncate_message_group(group, candidate)
+ if chosen:
+ minimum = candidate
+ high = candidate - 1
+ else:
+ low = candidate + 1
+ return minimum
+
+ # Anchor and final Step are both mandatory. Reserve part of the hard budget
+ # for the final Step before truncating the anchor; otherwise a long user
+ # query can consume the entire budget and silently drop the latest answer.
+ final_reserve = 0
+ if anchor_group and final_group:
+ anchor_minimum = _minimum_group_budget(anchor_group)
+ final_minimum = _minimum_group_budget(final_group)
+ if (
+ anchor_minimum is not None
+ and final_minimum is not None
+ and anchor_minimum + final_minimum <= token_budget
+ ):
+ final_reserve = min(
+ _message_tokens(final_group),
+ max(final_minimum, token_budget // 2),
+ token_budget - anchor_minimum,
+ )
+
+ if anchor_group:
+ _select_group(
+ anchor_group,
+ allow_truncate=True,
+ max_budget=token_budget - final_reserve,
+ )
+ if final_group:
+ _select_group(final_group, allow_truncate=True)
+
+ checkpoint_steps = [
+ step
+ for step in latest.steps[:-1]
+ if any(message.message_kind == "checkpoint" for message in step.messages)
+ ]
+ for step in checkpoint_steps:
+ if not _select_group(step.messages, allow_truncate=True):
+ break
+
+ checkpoint_ids = {id(step) for step in checkpoint_steps}
+ for step in reversed(latest.steps[:-1]):
+ if id(step) in checkpoint_ids:
+ continue
+ if not _select_group(step.messages, allow_truncate=False):
+ break
+
+ # Older Turns are useful only as a contiguous newest suffix and remain raw.
+ for turn in reversed(turns[:-1]):
+ if not _select_group(turn.messages, allow_truncate=False):
+ break
+
+ returned_messages = [selected[index] for index in sorted(selected)]
+ returned_ids = set(selected)
+ return ActiveMessageBudgetPlan(
+ messages=returned_messages,
+ estimated_tokens=_message_tokens(returned_messages),
+ dropped_message_ids=[
+ message.id for index, message in enumerate(messages) if index not in returned_ids
+ ],
+ truncated_message_ids=sorted(truncated_ids),
+ )
+
+
+def _partial_latest_turn_plan(
+ older_turns: List[UserTurn],
+ latest_turn: UserTurn,
+ *,
+ token_budget: int,
+ min_raw_tail_steps: int,
+) -> RetentionPlan:
+ """Keep the latest user anchor and an atomic suffix of assistant steps."""
+ anchor = latest_turn.anchor
+ steps = latest_turn.steps
+ min_tail = max(1, int(min_raw_tail_steps or 0)) if steps else 0
+
+ retained_steps: List[AssistantStep] = list(steps[-min_tail:]) if min_tail else []
+ retained_tokens = int(anchor.estimated_tokens or 0) if anchor is not None else 0
+ retained_tokens += sum(step.estimated_tokens for step in retained_steps)
+
+ # Leave room for the dedicated checkpoint summary generated alongside the
+ # existing Working Memory output during Phase 2.
+ # Mandatory anchor/final/tail messages are never dropped merely to satisfy
+ # the budget; in that case budget_exceeded reports the lossless overflow.
+ checkpoint_reserve = min(
+ _CHECKPOINT_TOKEN_RESERVE,
+ max(0, token_budget // 4),
+ )
+ raw_budget = max(0, token_budget - checkpoint_reserve)
+
+ first_retained_step = len(steps) - len(retained_steps)
+ for index in range(first_retained_step - 1, -1, -1):
+ candidate = steps[index]
+ if retained_tokens + candidate.estimated_tokens > raw_budget:
+ break
+ retained_steps.insert(0, candidate)
+ retained_tokens += candidate.estimated_tokens
+ first_retained_step = index
+
+ archived_prefix = steps[:first_retained_step]
+ archived_source_messages = [message for step in archived_prefix for message in step.messages]
+ retained_messages: List[Message] = []
+ if anchor is not None:
+ retained_messages.append(anchor)
+ retained_messages.extend(message for step in retained_steps for message in step.messages)
+
+ archive_messages = _flatten_turns(older_turns)
+ if archived_source_messages:
+ # A copy of the anchor (same message id) makes the partial archive
+ # understandable during Phase 2. Context assembly stable-deduplicates it
+ # against the retained live anchor while the archive is pending/failed.
+ if anchor is not None:
+ archive_messages.append(anchor)
+ archive_messages.extend(archived_source_messages)
+
+ source_ids = [message.id for message in archived_source_messages]
+ active_tokens = _message_tokens(retained_messages)
+ return RetentionPlan(
+ archive_messages=archive_messages,
+ retained_messages=retained_messages,
+ turn_anchor=anchor,
+ checkpoint_source_message_ids=source_ids,
+ raw_tail_start_message_id=(
+ retained_steps[0].messages[0].id
+ if retained_steps and retained_steps[0].messages
+ else None
+ ),
+ estimated_active_tokens=active_tokens,
+ budget_exceeded=active_tokens > token_budget,
+ partial_turn=bool(archived_source_messages),
+ )
+
+
+def plan_retention(
+ messages: List[Message],
+ *,
+ keep_recent_turn_count: int,
+ token_budget: int,
+ min_raw_tail_steps: int = 1,
+) -> RetentionPlan:
+ """Plan Turn-aware retention under both a turn count and token budget.
+
+ Oldest complete turns are archived first. If the newest turn alone exceeds
+ the budget, its user anchor and an atomic suffix of assistant steps remain
+ live while early steps become checkpoint sources.
+ """
+ keep_recent_turn_count = max(0, int(keep_recent_turn_count or 0))
+ token_budget = max(0, int(token_budget or 0))
+ turns = build_turns(messages)
+
+ if not turns or keep_recent_turn_count == 0:
+ return RetentionPlan(archive_messages=list(messages), retained_messages=[])
+
+ selected_start = max(0, len(turns) - keep_recent_turn_count)
+ retained_turns = turns[selected_start:]
+
+ # Enforce the token budget by evicting complete oldest turns. Never evict
+ # the newest turn here; it is handled by the partial-turn fallback below.
+ while (
+ len(retained_turns) > 1 and sum(t.estimated_tokens for t in retained_turns) > token_budget
+ ):
+ selected_start += 1
+ retained_turns = turns[selected_start:]
+
+ older_turns = turns[:selected_start]
+ latest_turn = retained_turns[-1]
+ if latest_turn.estimated_tokens > token_budget:
+ if latest_turn.anchor is None:
+ # A legacy assistant-only prefix has no stable User anchor for a
+ # partial-Turn checkpoint. Archive it as a complete unit so Phase 2
+ # can summarize it without producing an invalid checkpoint plan.
+ return RetentionPlan(
+ archive_messages=_flatten_turns([*older_turns, latest_turn]),
+ retained_messages=[],
+ )
+ return _partial_latest_turn_plan(
+ older_turns,
+ latest_turn,
+ token_budget=token_budget,
+ min_raw_tail_steps=min_raw_tail_steps,
+ )
+
+ retained_messages = _flatten_turns(retained_turns)
+ return RetentionPlan(
+ archive_messages=_flatten_turns(older_turns),
+ retained_messages=retained_messages,
+ estimated_active_tokens=_message_tokens(retained_messages),
+ )
+
+
+__all__ = [
+ "AssistantStep",
+ "ActiveMessageBudgetPlan",
+ "RETENTION_MODE_TURN_BUDGET",
+ "RetentionPlan",
+ "UserTurn",
+ "build_turns",
+ "fit_active_messages_to_budget",
+ "is_tool_transport",
+ "is_user_query",
+ "plan_retention",
+]
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 5c9b6ccff..51f0f8c30 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -10,7 +10,7 @@ import json
import re
from dataclasses import dataclass, field
from datetime import datetime, timezone
-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Optional
+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, Literal, Optional
from uuid import uuid4
from openviking.core.namespace import canonical_session_uri
@@ -21,6 +21,14 @@ 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_policy import MemoryPolicy
+from openviking.session.retention import (
+ RETENTION_MODE_TURN_BUDGET,
+ RetentionPlan,
+ build_turns,
+ fit_active_messages_to_budget,
+ is_user_query,
+ plan_retention,
+)
from openviking.session.tool_result_store import (
ToolResultStore,
build_tool_result_id,
@@ -36,7 +44,7 @@ from openviking.telemetry import get_current_telemetry, tracer
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
+from openviking.utils.token_estimation import estimate_text_tokens, truncate_text_to_token_budget
from openviking_cli.exceptions import FailedPreconditionError
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import get_logger, run_async
@@ -56,6 +64,8 @@ _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
+_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS = 30.0
+_MEMORY_STEP_NAMES = ("long_term", "execution")
def _wm_debug(msg: str) -> None:
@@ -128,10 +138,13 @@ def _resolve_memory_extraction_scope(
# Phase 2 of a commit generates / updates a structured 7-section Working
# Memory document stored at archive_NNN/.overview.md.
#
-# First commit: call `compression.ov_wm_v2` with a plain completion.
+# First commit: call `compression.ov_wm_v2` with a plain completion unless
+# partial-Turn retention also needs checkpoint summaries. In that case the
+# same call uses `create_working_memory` and returns both products.
# Subsequent commits: call `compression.ov_wm_v2_update` with the
-# `update_working_memory` tool to get a per-section decision, then let
-# the server do section-level merge against the previous WM.
+# `update_working_memory` tool to get a per-section decision plus any requested
+# checkpoint summaries, then let the server do section-level merge against the
+# previous WM.
# =====================================================================
WM_SEVEN_SECTIONS: List[str] = [
@@ -205,13 +218,69 @@ WM_UPDATE_TOOL: Dict[str, Any] = {
"required": list(WM_SEVEN_SECTIONS),
"additionalProperties": False,
"properties": dict.fromkeys(WM_SEVEN_SECTIONS, _WM_SECTION_OP_SCHEMA),
- }
+ },
+ "checkpoint_summaries": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "When checkpoint sources are present, one concise continuation "
+ "summary per checkpoint_source index, in ascending index order."
+ ),
+ },
+ },
+ },
+ },
+}
+
+WM_CREATE_WITH_CHECKPOINTS_TOOL: Dict[str, Any] = {
+ "type": "function",
+ "function": {
+ "name": "create_working_memory",
+ "description": (
+ "Create the complete Working Memory and the requested checkpoint summaries "
+ "from the same model pass."
+ ),
+ "parameters": {
+ "type": "object",
+ "required": ["working_memory", "checkpoint_summaries"],
+ "additionalProperties": False,
+ "properties": {
+ "working_memory": {
+ "type": "string",
+ "description": "Complete 7-section Working Memory markdown.",
+ },
+ "checkpoint_summaries": {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "One concise continuation summary per checkpoint_source index, "
+ "in ascending index order."
+ ),
+ },
},
},
},
}
+@dataclass(frozen=True)
+class _CheckpointRequest:
+ """Server-owned mapping for one checkpoint summary requested from Phase 2."""
+
+ turn_anchor_message_id: str
+ source_message_ids: tuple[str, ...]
+ retained_message_token_budget: int
+ estimated_active_tokens: int
+
+
+@dataclass(frozen=True)
+class _ArchiveSummaryResult:
+ """The two products emitted by the existing Working-Memory model call."""
+
+ overview: str
+ checkpoint_summaries: tuple[str, ...] = ()
+
+
@dataclass
class SessionCompression:
"""Session compression information."""
@@ -234,6 +303,37 @@ class SessionStats:
memories_extracted: int = 0
+@dataclass
+class ArchiveState:
+ """Filesystem-derived state for one archive directory."""
+
+ archive_id: str
+ archive_uri: str
+ index: int
+ state: Literal["pending", "completed", "failed"]
+ overview: str = ""
+ done: Dict[str, Any] = field(default_factory=dict)
+ failed: Dict[str, Any] = field(default_factory=dict)
+
+ @property
+ def coverage_start_index(self) -> int:
+ raw = self.done.get("coverage_start_archive")
+ if isinstance(raw, str):
+ match = re.fullmatch(r"archive_(\d+)", raw)
+ if match:
+ return int(match.group(1))
+ return self.index
+
+ @property
+ def coverage_end_index(self) -> int:
+ raw = self.done.get("coverage_end_archive")
+ if isinstance(raw, str):
+ match = re.fullmatch(r"archive_(\d+)", raw)
+ if match:
+ return int(match.group(1))
+ return self.index
+
+
@dataclass
class SessionMeta:
"""Session metadata persisted in .meta.json."""
@@ -272,6 +372,12 @@ class SessionMeta:
# add_message calls can maintain pending_tokens consistently across
# process restarts.
keep_recent_count: int = 0
+ # Opt-in Turn-aware retention. Empty mode preserves the physical-message
+ # keep_recent_count behavior for existing integrations.
+ retention_mode: str = ""
+ keep_recent_turn_count: int = 0
+ retained_message_token_budget: int = 0
+ min_raw_tail_steps: int = 1
memory_policy: Optional[Dict[str, Any]] = None
def to_dict(self) -> Dict[str, Any]:
@@ -289,6 +395,10 @@ class SessionMeta:
"embedding_token_usage": dict(self.embedding_token_usage),
"pending_tokens": self.pending_tokens,
"keep_recent_count": self.keep_recent_count,
+ "retention_mode": self.retention_mode,
+ "keep_recent_turn_count": self.keep_recent_turn_count,
+ "retained_message_token_budget": self.retained_message_token_budget,
+ "min_raw_tail_steps": self.min_raw_tail_steps,
"memory_policy": dict(self.memory_policy) if self.memory_policy is not None else None,
}
if self.total_message_count is not None:
@@ -332,6 +442,12 @@ class SessionMeta:
},
pending_tokens=max(0, int(data.get("pending_tokens", 0) or 0)),
keep_recent_count=max(0, int(data.get("keep_recent_count", 0) or 0)),
+ retention_mode=str(data.get("retention_mode", "") or ""),
+ keep_recent_turn_count=max(0, int(data.get("keep_recent_turn_count", 0) or 0)),
+ retained_message_token_budget=max(
+ 0, int(data.get("retained_message_token_budget", 0) or 0)
+ ),
+ min_raw_tail_steps=max(0, int(data.get("min_raw_tail_steps", 1) or 0)),
memory_policy=data.get("memory_policy"),
)
@@ -379,6 +495,7 @@ class Session:
self._messages: List[Message] = []
self._usage_records: List[Usage] = []
+ self._archive_meta_merge_lock = asyncio.Lock()
self._compression: SessionCompression = SessionCompression()
self._stats: SessionStats = SessionStats()
self._meta = SessionMeta(
@@ -459,6 +576,26 @@ class Session:
Used on load and as a safety net after rollbacks. Respects the
currently remembered ``keep_recent_count`` from meta.
"""
+ if (
+ self._meta.retention_mode == RETENTION_MODE_TURN_BUDGET
+ and self._meta.keep_recent_turn_count > 0
+ and self._meta.retained_message_token_budget > 0
+ ):
+ plan = plan_retention(
+ self._messages,
+ keep_recent_turn_count=self._meta.keep_recent_turn_count,
+ token_budget=self._meta.retained_message_token_budget,
+ min_raw_tail_steps=self._meta.min_raw_tail_steps,
+ )
+ retained_ids = {message.id for message in plan.retained_messages}
+ self._meta.pending_tokens = sum(
+ int(message.estimated_tokens or 0)
+ for message in plan.archive_messages
+ if message.id not in retained_ids
+ )
+ self._meta.pending_tokens = max(0, self._meta.pending_tokens)
+ return
+
keep = max(0, int(self._meta.keep_recent_count or 0))
total = len(self._messages)
if keep <= 0:
@@ -498,12 +635,6 @@ class Session:
ctx=self.ctx,
)
- def _save_meta_sync(self) -> None:
- """Sync wrapper for _save_meta()."""
- if not self._viking_fs:
- return
- run_async(self._save_meta())
-
@property
def messages(self) -> List[Message]:
"""Get message list."""
@@ -771,7 +902,16 @@ class Session:
return
group_id = messages[0].id
- group_original_chars = sum(len(p.tool_output or "") for _, p in tool_parts)
+ group_original_chars = sum(
+ (
+ int(p.tool_output_original_chars)
+ if p.tool_output_ref
+ and p.tool_output_truncated
+ and p.tool_output_original_chars is not None
+ else len(p.tool_output or "")
+ )
+ for _, p in tool_parts
+ )
normal_indices: List[int] = []
selected: set[int] = set()
externalized_preview_cache: Dict[tuple[int, int, str], tuple[ToolResultSynopsis, int]] = {}
@@ -844,7 +984,7 @@ class Session:
reverse=True,
)
while (
- projected_inline_chars(selected) > cfg.assistant_turn_inline_budget_chars and remaining
+ projected_inline_chars(selected) >= cfg.assistant_turn_inline_budget_chars and remaining
):
baseline = projected_inline_chars(selected)
chosen_pos = None
@@ -887,38 +1027,127 @@ class Session:
)
def _append_messages(self, messages: List[Message]) -> None:
- """Append multiple messages: update lists, stats, JSONL, meta."""
+ """Append messages through the same authoritative lock as commit Phase 1."""
+ run_async(self._append_messages_authoritatively(messages))
+
+ async def _append_messages_authoritatively(self, messages: List[Message]) -> None:
+ """Reload and append under the session path lock.
+
+ Different workers can hold stale Session objects. Without sharing the
+ commit lock, an append between commit's root read and root rewrite can
+ be overwritten even though add_message already returned successfully.
+ """
+ if not messages:
+ return
+ if not self._viking_fs:
+ self._apply_appended_messages_to_state(messages)
+ return
+
+ uri_to_path = getattr(self._viking_fs, "_uri_to_path", None)
+ if not callable(uri_to_path):
+ # Minimal/embedded VikingFS implementations predate transaction
+ # locks. Preserve their existing append contract; production
+ # VikingFS always takes the authoritative path-lock branch below.
+ await self._append_messages_without_path_lock(messages)
+ return
+
+ from openviking.storage.transaction import LockContext, get_lock_manager
+
+ session_path = uri_to_path(self._session_uri, ctx=self.ctx)
+ async with LockContext(
+ get_lock_manager(),
+ [session_path],
+ lock_mode="exact",
+ timeout=_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS,
+ ):
+ self._messages = await self._read_live_messages_strict()
+ in_memory_meta = self._meta
+ try:
+ meta_content = await self._viking_fs.read_file(
+ f"{self._session_uri}/.meta.json",
+ ctx=self.ctx,
+ )
+ self._meta = SessionMeta.from_dict(json.loads(meta_content))
+ except Exception:
+ # Legacy/malformed metadata must not prevent an otherwise safe
+ # append. Message correctness remains rooted in messages.jsonl.
+ self._meta = in_memory_meta
+
+ self._apply_appended_messages_to_state(messages)
+ batch_content = "".join(message.to_jsonl() + "\n" for message in messages)
+ await self._viking_fs.append_file(
+ f"{self._session_uri}/messages.jsonl",
+ batch_content,
+ ctx=self.ctx,
+ )
+ await self._save_meta()
+
+ async def _append_messages_without_path_lock(self, messages: List[Message]) -> None:
+ """Compatibility append for storage adapters without path locking."""
+ from openviking_cli.exceptions import NotFoundError
+
+ try:
+ self._messages = await self._read_live_messages_strict()
+ except (FileNotFoundError, NotFoundError):
+ # A fresh lightweight adapter may not materialize messages.jsonl
+ # until its first append.
+ pass
+
+ in_memory_meta = self._meta
+ try:
+ meta_content = await self._viking_fs.read_file(
+ f"{self._session_uri}/.meta.json",
+ ctx=self.ctx,
+ )
+ self._meta = SessionMeta.from_dict(json.loads(meta_content))
+ except Exception:
+ # Keep the in-memory legacy metadata if the lightweight adapter
+ # has no metadata file or cannot decode an older one.
+ self._meta = in_memory_meta
+
+ self._apply_appended_messages_to_state(messages)
+ batch_content = "".join(message.to_jsonl() + "\n" for message in messages)
+ await self._viking_fs.append_file(
+ f"{self._session_uri}/messages.jsonl",
+ batch_content,
+ ctx=self.ctx,
+ )
+ await self._save_meta()
+
+ def _apply_appended_messages_to_state(self, messages: List[Message]) -> None:
+ """Update in-memory counters after an authoritative root reload."""
for msg in messages:
self._messages.append(msg)
- if msg.role == "user":
+ if is_user_query(msg):
self._stats.total_turns += 1
msg_tokens = int(msg.estimated_tokens or 0)
self._stats.total_tokens += msg_tokens
- keep = int(self._meta.keep_recent_count or 0)
- if keep <= 0:
- self._meta.pending_tokens += msg_tokens
- elif len(self._messages) > keep:
- pushed_out = self._messages[-(keep + 1)]
- self._meta.pending_tokens += int(pushed_out.estimated_tokens or 0)
+ if self._meta.retention_mode != RETENTION_MODE_TURN_BUDGET:
+ keep = int(self._meta.keep_recent_count or 0)
+ if keep <= 0:
+ self._meta.pending_tokens += msg_tokens
+ elif len(self._messages) > keep:
+ pushed_out = self._messages[-(keep + 1)]
+ self._meta.pending_tokens += int(pushed_out.estimated_tokens or 0)
- self._append_messages_to_jsonl_batch(messages)
+ if self._meta.retention_mode == RETENTION_MODE_TURN_BUDGET:
+ self._rebuild_pending_tokens()
self._meta.message_count = len(self._messages)
if self._meta.total_message_count is not None:
self._meta.total_message_count += len(messages)
- self._save_meta_sync()
- def add_messages(
+ def _build_messages(
self,
messages_spec: List[dict],
) -> List[Message]:
- """Add multiple messages in a single batch.
+ """Validate message specs and build their durable Message objects.
Args:
messages_spec: List of dicts, each with keys:
- role, parts, peer_id (optional), created_at (optional)
+ role, parts, peer_id/created_at and optional semantic fields.
"""
all_messages = []
for i, spec in enumerate(messages_spec):
@@ -929,6 +1158,9 @@ class Session:
role = spec["role"]
parts = spec["parts"]
created_at = spec.get("created_at") or datetime.now(timezone.utc).isoformat()
+ turn_id = spec.get("turn_id")
+ message_kind = spec.get("message_kind")
+ source_message_ids = spec.get("source_message_ids")
try:
peer_id = normalize_peer_id(spec.get("peer_id"))
@@ -945,6 +1177,11 @@ class Session:
parts=[part],
peer_id=peer_id,
created_at=created_at,
+ turn_id=turn_id,
+ message_kind=message_kind or "tool_transport",
+ source_message_ids=(
+ list(source_message_ids) if source_message_ids is not None else None
+ ),
)
for part in parts
]
@@ -957,19 +1194,44 @@ class Session:
parts=parts,
peer_id=peer_id,
created_at=created_at,
+ turn_id=turn_id,
+ message_kind=message_kind,
+ source_message_ids=(
+ list(source_message_ids) if source_message_ids is not None else None
+ ),
)
self._externalize_large_tool_outputs(msg)
all_messages.append(msg)
- self._append_messages(all_messages)
return all_messages
+ def add_messages(
+ self,
+ messages_spec: List[dict],
+ ) -> List[Message]:
+ """Synchronously add multiple messages in one authoritative batch."""
+ messages = self._build_messages(messages_spec)
+ self._append_messages(messages)
+ return messages
+
+ async def add_messages_async(
+ self,
+ messages_spec: List[dict],
+ ) -> List[Message]:
+ """Asynchronously add multiple messages without blocking the caller loop."""
+ messages = self._build_messages(messages_spec)
+ await self._append_messages_authoritatively(messages)
+ return messages
+
def add_message(
self,
role: str,
parts: List[Part],
peer_id: Optional[str] = None,
created_at: str = None,
+ turn_id: Optional[str] = None,
+ message_kind: Optional[str] = None,
+ source_message_ids: Optional[List[str]] = None,
) -> Message:
"""Add a message.
@@ -983,6 +1245,35 @@ class Session:
"parts": parts,
"peer_id": peer_id,
"created_at": created_at,
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }
+ ]
+ )
+ return msgs[0]
+
+ async def add_message_async(
+ self,
+ role: str,
+ parts: List[Part],
+ peer_id: Optional[str] = None,
+ created_at: str = None,
+ turn_id: Optional[str] = None,
+ message_kind: Optional[str] = None,
+ source_message_ids: Optional[List[str]] = None,
+ ) -> Message:
+ """Asynchronously add one message through the authoritative path lock."""
+ msgs = await self.add_messages_async(
+ [
+ {
+ "role": role,
+ "parts": parts,
+ "peer_id": peer_id,
+ "created_at": created_at,
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
}
]
)
@@ -1039,17 +1330,235 @@ class Session:
return {"tool_results": []}
return await store.list(tool_name=tool_name, limit=limit)
+ def _remember_retention_policy(
+ self,
+ *,
+ keep_recent_count: int,
+ retention_mode: Optional[str],
+ keep_recent_turn_count: int,
+ retained_message_token_budget: int,
+ min_raw_tail_steps: int,
+ ) -> None:
+ """Persist the policy used by the latest Phase 1 decision."""
+ self._meta.keep_recent_count = keep_recent_count
+ self._meta.retention_mode = retention_mode or ""
+ self._meta.keep_recent_turn_count = keep_recent_turn_count
+ self._meta.retained_message_token_budget = retained_message_token_budget
+ self._meta.min_raw_tail_steps = min_raw_tail_steps
+
+ async def _merge_archive_meta(self, archive_uri: str, updates: Dict[str, Any]) -> None:
+ """Merge archive metadata so Phase 2 cannot erase Phase 1 planning data."""
+ if not self._viking_fs:
+ return
+ # Summary generation and memory extraction run concurrently. Serialize
+ # their read/merge/write cycles so overview token metadata, retention
+ # planning and extraction progress cannot overwrite one another.
+ async with self._archive_meta_merge_lock:
+ meta: Dict[str, Any] = {}
+ try:
+ content = await self._viking_fs.read_file(f"{archive_uri}/.meta.json", ctx=self.ctx)
+ parsed = json.loads(content)
+ if isinstance(parsed, dict):
+ meta = parsed
+ except Exception:
+ pass
+ meta.update(updates)
+ await self._viking_fs.write_file(
+ uri=f"{archive_uri}/.meta.json",
+ content=json.dumps(meta, ensure_ascii=False),
+ ctx=self.ctx,
+ )
+
+ @staticmethod
+ def _retention_plan_meta(
+ plan: RetentionPlan,
+ *,
+ keep_recent_turn_count: int,
+ retained_message_token_budget: int,
+ min_raw_tail_steps: int,
+ ) -> Dict[str, Any]:
+ return {
+ "mode": RETENTION_MODE_TURN_BUDGET,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ "partial_turn": plan.partial_turn,
+ "turn_anchor_message_id": plan.turn_anchor.id if plan.turn_anchor else None,
+ "checkpoint_source_message_ids": list(plan.checkpoint_source_message_ids),
+ "raw_tail_start_message_id": plan.raw_tail_start_message_id,
+ "estimated_active_tokens": plan.estimated_active_tokens,
+ "budget_exceeded": plan.budget_exceeded,
+ }
+
+ async def _write_phase1_marker(
+ self,
+ archive_uri: str,
+ *,
+ queue_message: Dict[str, Any],
+ original_messages: List[Message],
+ archived_messages: List[Message],
+ retained_messages: List[Message],
+ keep_recent_count: int,
+ retention_mode: Optional[str],
+ keep_recent_turn_count: int,
+ retained_message_token_budget: int,
+ min_raw_tail_steps: int,
+ ) -> None:
+ """Persist the Phase 1 intent before any destructive root rewrite."""
+ payload = {
+ "version": 1,
+ "status": "preparing",
+ "created_at": get_current_timestamp(),
+ "queue_message": queue_message,
+ "original_message_ids": [message.id for message in original_messages],
+ "archived_message_ids": [message.id for message in archived_messages],
+ "retained_message_ids": [message.id for message in retained_messages],
+ "keep_recent_count": keep_recent_count,
+ "retention_mode": retention_mode or "",
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "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})
+
+ async def _write_phase1_ready_marker(self, archive_uri: str) -> None:
+ phase1 = await self._read_phase1_meta(archive_uri)
+ phase1.update(
+ {
+ "status": "ready",
+ "ready_at": get_current_timestamp(),
+ }
+ )
+ await self._merge_archive_meta(archive_uri, {"phase1": phase1})
+
+ async def _archive_file_exists(self, archive_uri: str, file_name: str) -> bool:
+ try:
+ return await self._viking_fs.exists(f"{archive_uri}/{file_name}", ctx=self.ctx)
+ except Exception:
+ return False
+
+ async def _read_phase1_meta(self, archive_uri: str) -> Dict[str, Any]:
+ phase1 = (await self._read_archive_meta(archive_uri)).get("phase1")
+ return dict(phase1) if isinstance(phase1, dict) else {}
+
+ async def _ensure_phase1_ready(self, archive_uri: str) -> bool:
+ """Verify or recover a queued Phase 1 before Phase 2 consumes it.
+
+ New commits enqueue while holding the session lock and before rewriting
+ root messages. A consumer therefore acquires the same lock, then either
+ observes ``phase1.status=ready`` in archive metadata or
+ deterministically reconciles a process crash from the persisted intent.
+ """
+ marker = await self._read_phase1_meta(archive_uri)
+ if not marker:
+ # Archives created by older OpenViking versions have no Phase 1
+ # metadata and keep their previous processing contract.
+ return True
+ if marker.get("status") == "ready":
+ return True
+ if await self._archive_file_exists(archive_uri, ".failed.json"):
+ return False
+
+ from openviking.storage.transaction import LockContext, get_lock_manager
+
+ session_path = self._viking_fs._uri_to_path(self._session_uri, ctx=self.ctx)
+ async with LockContext(
+ get_lock_manager(),
+ [session_path],
+ lock_mode="exact",
+ timeout=_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS,
+ ):
+ marker = await self._read_phase1_meta(archive_uri)
+ if marker.get("status") == "ready":
+ return True
+ if await self._archive_file_exists(archive_uri, ".failed.json"):
+ return False
+
+ try:
+ if not marker:
+ raise ValueError("Phase 1 metadata is missing")
+ retained_ids = marker.get("retained_message_ids")
+ archived_ids = marker.get("archived_message_ids")
+ if not isinstance(retained_ids, list) or not isinstance(archived_ids, list):
+ raise ValueError("Phase 1 metadata has invalid message ID lists")
+ retained_ids = [item for item in retained_ids if isinstance(item, str)]
+ archived_ids = [item for item in archived_ids if isinstance(item, str)]
+ live_messages = await self._read_live_messages_strict()
+ except Exception as exc:
+ await self._write_failed_marker(
+ archive_uri,
+ stage="phase1_recovery",
+ error=f"Cannot verify Phase 1 state: {exc}",
+ )
+ return False
+
+ live_ids = [message.id for message in live_messages]
+ archived_only_ids = set(archived_ids) - set(retained_ids)
+ phase1_applied = (
+ live_ids[: len(retained_ids)] == retained_ids
+ and not archived_only_ids.intersection(live_ids)
+ )
+ if not phase1_applied:
+ await self._write_failed_marker(
+ archive_uri,
+ stage="phase1_recovery",
+ error="Root rewrite was not durably completed before process interruption",
+ )
+ return False
+
+ # Root is authoritative and proves the rewrite completed. Reconcile
+ # metadata that may have been interrupted immediately afterwards.
+ try:
+ meta_content = await self._viking_fs.read_file(
+ f"{self._session_uri}/.meta.json",
+ ctx=self.ctx,
+ )
+ self._meta = SessionMeta.from_dict(json.loads(meta_content))
+ except Exception:
+ pass
+ self._messages = live_messages
+ self._remember_retention_policy(
+ keep_recent_count=max(0, int(marker.get("keep_recent_count", 0) or 0)),
+ retention_mode=str(marker.get("retention_mode", "") or "") or None,
+ keep_recent_turn_count=max(
+ 0, int(marker.get("keep_recent_turn_count", 0) or 0)
+ ),
+ retained_message_token_budget=max(
+ 0, int(marker.get("retained_message_token_budget", 0) or 0)
+ ),
+ min_raw_tail_steps=max(0, int(marker.get("min_raw_tail_steps", 1) or 0)),
+ )
+ self._meta.message_count = len(live_messages)
+ self._meta.commit_count = max(
+ self._meta.commit_count,
+ self._archive_index_from_uri(archive_uri),
+ )
+ self._meta.last_commit_at = get_current_timestamp()
+ self._rebuild_pending_tokens()
+ await self._save_meta()
+ await self._write_phase1_ready_marker(archive_uri)
+ logger.warning("Recovered interrupted Session Phase 1: %s", archive_uri)
+ return True
+
def commit(
self,
keep_recent_count: int = 0,
*,
memory_policy: Optional[Dict[str, Any]] = None,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
) -> Dict[str, Any]:
"""Sync wrapper for commit_async()."""
return run_async(
self.commit_async(
keep_recent_count=keep_recent_count,
memory_policy=memory_policy,
+ retention_mode=retention_mode,
+ keep_recent_turn_count=keep_recent_turn_count,
+ retained_message_token_budget=retained_message_token_budget,
+ min_raw_tail_steps=min_raw_tail_steps,
)
)
@@ -1059,13 +1568,18 @@ class Session:
keep_recent_count: int = 0,
*,
memory_policy: Optional[Dict[str, Any]] = None,
+ retention_mode: Optional[str] = None,
+ keep_recent_turn_count: Optional[int] = None,
+ retained_message_token_budget: Optional[int] = None,
+ min_raw_tail_steps: Optional[int] = None,
) -> Dict[str, Any]:
"""Archive immediately and enqueue restart-safe Phase 2 processing.
Phase 1 (Archive prep, path-lock protected): Split messages into
- archive/retain parts, write the retained tail back to messages.jsonl,
- then persist the archive. Uses a distributed filesystem lock
- so this works across workers and processes.
+ archive/retain parts, persist a recoverable intent and archive raw,
+ enqueue Phase 2, then atomically publish the retained root state with
+ ``phase1.status=ready``. Uses a distributed filesystem lock across
+ workers and processes.
Phase 2 (Memory extraction): Runs through the persistent QueueFS queue.
Args:
@@ -1084,6 +1598,31 @@ class Session:
trace_id = tracer.get_trace_id()
keep_recent_count = max(0, int(keep_recent_count or 0))
+ if retention_mode not in (None, RETENTION_MODE_TURN_BUDGET):
+ raise ValueError(f"Unsupported retention_mode: {retention_mode}")
+ if retention_mode is None and any(
+ value is not None
+ for value in (
+ keep_recent_turn_count,
+ retained_message_token_budget,
+ min_raw_tail_steps,
+ )
+ ):
+ raise ValueError(
+ "retention_mode='turn_budget' is required when Turn retention fields are set"
+ )
+ turn_mode = retention_mode == RETENTION_MODE_TURN_BUDGET
+ effective_keep_turns = max(
+ 0, int(3 if keep_recent_turn_count is None else keep_recent_turn_count)
+ )
+ effective_token_budget = max(
+ 0,
+ int(12_000 if retained_message_token_budget is None else retained_message_token_budget),
+ )
+ effective_min_tail = max(0, int(1 if min_raw_tail_steps is None else min_raw_tail_steps))
+ if turn_mode and effective_token_budget <= 0:
+ raise ValueError("retained_message_token_budget must be greater than 0")
+ in_memory_default_memory_policy = self._meta.memory_policy
effective_policy = MemoryPolicy.from_dict(
memory_policy if memory_policy is not None else self._meta.memory_policy
)
@@ -1091,35 +1630,64 @@ class Session:
effective_memory_policy = effective_policy.to_dict()
logger.info(
f"[TRACER] session_commit started, trace_id={trace_id}, "
- f"keep_recent_count={keep_recent_count}"
+ f"keep_recent_count={keep_recent_count}, retention_mode={retention_mode}, "
+ f"keep_recent_turn_count={effective_keep_turns}, "
+ f"retained_message_token_budget={effective_token_budget}"
)
- # ===== Phase 1: Snapshot + clear (path-lock protected) =====
- # Fast pre-check: skip lock entirely if no messages (common case avoids
- # unnecessary filesystem lock acquisition).
- if not self._messages:
- self._meta.pending_tokens = 0
- self._meta.keep_recent_count = keep_recent_count
- await self._save_meta()
- get_current_telemetry().set("memory.extracted", 0)
- return {
- "session_id": self.session_id,
- "status": "skipped",
- "task_id": None,
- "archive_uri": None,
- "archived": False,
- "reason": "no_messages",
- "trace_id": trace_id,
- }
-
- # Use filesystem-based distributed lock so this works across workers/processes.
+ # ===== Phase 1: authoritative snapshot + split (path-lock protected) =====
+ # Use a waiting filesystem lock and reload inside it. Different workers
+ # can hold stale Session objects, so in-memory emptiness is never a
+ # correctness boundary.
session_path = self._viking_fs._uri_to_path(self._session_uri, ctx=self.ctx)
- async with LockContext(get_lock_manager(), [session_path], lock_mode="exact"):
- # Authoritative check under lock: handles the race where two concurrent
- # callers both passed the pre-check but only the first should archive.
+ async with LockContext(
+ get_lock_manager(),
+ [session_path],
+ lock_mode="exact",
+ timeout=_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS,
+ ):
+ self._messages = await self._read_live_messages_strict()
+ try:
+ meta_content = await self._viking_fs.read_file(
+ f"{self._session_uri}/.meta.json",
+ ctx=self.ctx,
+ )
+ self._meta = SessionMeta.from_dict(json.loads(meta_content))
+ if (
+ memory_policy is None
+ and self._meta.memory_policy is None
+ and in_memory_default_memory_policy is not None
+ ):
+ self._meta.memory_policy = in_memory_default_memory_policy
+ except Exception:
+ # The root JSONL remains authoritative for message correctness;
+ # legacy sessions may not have metadata yet.
+ pass
+
+ # A Session object may have been loaded by another worker before a
+ # different worker updated the persisted default policy. Phase 2
+ # must use the policy from the same lock-protected snapshot as the
+ # messages being archived, unless this commit supplied an explicit
+ # override.
+ if memory_policy is None:
+ effective_policy = MemoryPolicy.from_dict(self._meta.memory_policy)
+ _validate_memory_policy_types(effective_policy)
+ effective_memory_policy = effective_policy.to_dict()
+
+ archive_refs = await self._list_archive_refs()
+ self._compression.compression_index = max(
+ [archive["index"] for archive in archive_refs],
+ default=0,
+ )
if not self._messages:
self._meta.pending_tokens = 0
- self._meta.keep_recent_count = keep_recent_count
+ self._remember_retention_policy(
+ keep_recent_count=keep_recent_count,
+ retention_mode=retention_mode,
+ keep_recent_turn_count=effective_keep_turns if turn_mode else 0,
+ retained_message_token_budget=effective_token_budget if turn_mode else 0,
+ min_raw_tail_steps=effective_min_tail,
+ )
await self._save_meta()
get_current_telemetry().set("memory.extracted", 0)
return {
@@ -1132,15 +1700,44 @@ class Session:
"trace_id": trace_id,
}
- # WM v2 boundary: if all live messages already fit inside the keep
- # window, there is nothing to archive — just remember the new
- # keep_recent_count and reset pending_tokens so the next
- # add_message uses the sliding-window path.
total = len(self._messages)
- if keep_recent_count > 0 and total <= keep_recent_count:
+ retention_plan: Optional[RetentionPlan] = None
+ if turn_mode:
+ # The externalization budget belongs to a logical Turn, not one
+ # physical assistant message. This catches N small tool outputs
+ # whose aggregate exceeds the configured inline budget.
+ for turn in build_turns(self._messages):
+ self._externalize_large_tool_output_group(turn.messages)
+ retention_plan = plan_retention(
+ self._messages,
+ keep_recent_turn_count=effective_keep_turns,
+ token_budget=effective_token_budget,
+ min_raw_tail_steps=effective_min_tail,
+ )
+ messages_to_archive = retention_plan.archive_messages
+ retained_messages = retention_plan.retained_messages
+ elif keep_recent_count > 0:
+ split_idx = max(0, total - keep_recent_count)
+ messages_to_archive = self._messages[:split_idx]
+ retained_messages = self._messages[split_idx:]
+ else:
+ messages_to_archive = self._messages.copy()
+ retained_messages = []
+
+ # No archive work: persist possible Turn-wide externalization and
+ # remember the policy for subsequent add_message accounting.
+ if not messages_to_archive:
+ self._messages = retained_messages
+ await self._write_to_agfs_async(messages=self._messages)
self._meta.pending_tokens = 0
- self._meta.keep_recent_count = keep_recent_count
self._meta.message_count = total
+ self._remember_retention_policy(
+ keep_recent_count=keep_recent_count,
+ retention_mode=retention_mode,
+ keep_recent_turn_count=effective_keep_turns if turn_mode else 0,
+ retained_message_token_budget=effective_token_budget if turn_mode else 0,
+ min_raw_tail_steps=effective_min_tail,
+ )
await self._save_meta()
get_current_telemetry().set("memory.extracted", 0)
return {
@@ -1151,23 +1748,49 @@ class Session:
"archived": False,
"reason": "all_within_keep_window",
"trace_id": trace_id,
+ "estimated_active_tokens": (
+ retention_plan.estimated_active_tokens if retention_plan else 0
+ ),
+ "budget_exceeded": retention_plan.budget_exceeded if retention_plan else False,
}
self._compression.compression_index += 1
archive_uri = (
f"{self._session_uri}/history/archive_{self._compression.compression_index:03d}"
)
- if keep_recent_count > 0:
- split_idx = total - keep_recent_count
- messages_to_archive = self._messages[:split_idx]
- retained_messages = self._messages[split_idx:]
- else:
- messages_to_archive = self._messages.copy()
- retained_messages = []
-
+ original_messages = list(self._messages)
+ usage_snapshot = self._usage_records.copy()
+ task_id = str(uuid4())
+ queue_msg = SessionCommitMsg(
+ task_id=task_id,
+ session_id=self.session_id,
+ session_uri=self._session_uri,
+ archive_uri=archive_uri,
+ user=self.ctx.user.to_dict(),
+ actor_peer_id=self.ctx.actor_peer_id,
+ memory_policy=effective_memory_policy,
+ usage_uris=list(dict.fromkeys(u.uri for u in usage_snapshot if u.uri)),
+ )
+ phase1_stage = "phase1_persist"
try:
- # Persist archive raw messages before trimming live messages so
- # an archive write failure cannot drop live conversation history.
+ # Persist the full intent before any root rewrite. Queueing while
+ # holding the same session lock lets a consumer either observe
+ # final ready metadata or recover the exact interrupted state.
+ await self._write_phase1_marker(
+ archive_uri,
+ queue_message=queue_msg.to_dict(),
+ original_messages=original_messages,
+ archived_messages=messages_to_archive,
+ retained_messages=retained_messages,
+ keep_recent_count=keep_recent_count,
+ retention_mode=retention_mode,
+ keep_recent_turn_count=effective_keep_turns if turn_mode else 0,
+ retained_message_token_budget=effective_token_budget if turn_mode else 0,
+ min_raw_tail_steps=effective_min_tail,
+ )
+
+ # Archive raw remains durable and recoverable before any live
+ # conversation history is removed from the root JSONL.
if self._viking_fs:
lines = [m.to_jsonl() for m in messages_to_archive]
await self._viking_fs.write_file(
@@ -1175,26 +1798,79 @@ class Session:
content="\n".join(lines) + "\n",
ctx=self.ctx,
)
+ if retention_plan is not None:
+ await self._merge_archive_meta(
+ archive_uri,
+ {
+ "retention_plan": self._retention_plan_meta(
+ retention_plan,
+ keep_recent_turn_count=effective_keep_turns,
+ retained_message_token_budget=effective_token_budget,
+ min_raw_tail_steps=effective_min_tail,
+ )
+ },
+ )
+
+ phase1_stage = "queue_enqueue"
+ await get_queue_manager().enqueue(
+ QueueManager.SESSION_COMMIT,
+ queue_msg.to_dict(),
+ )
+
+ # Register after the durable queue write but before publishing
+ # ready. The consumer is blocked by this session lock until
+ # ready, so it cannot complete the task before registration;
+ # if registration fails, the queued consumer will observe the
+ # Phase 1 failure marker and create/fail the task itself.
+ phase1_stage = "task_tracker_create"
+ await get_task_tracker().create(
+ "session_commit",
+ resource_id=self.session_id,
+ account_id=self.ctx.account_id,
+ user_id=self.ctx.user.user_id,
+ task_id=task_id,
+ )
+
+ phase1_stage = "phase1_persist"
self._messages = retained_messages
await self._write_to_agfs_async(messages=self._messages)
+ self._meta.message_count = len(self._messages)
+ self._meta.pending_tokens = 0
+ self._remember_retention_policy(
+ keep_recent_count=keep_recent_count,
+ retention_mode=retention_mode,
+ keep_recent_turn_count=effective_keep_turns if turn_mode else 0,
+ retained_message_token_budget=effective_token_budget if turn_mode else 0,
+ min_raw_tail_steps=effective_min_tail,
+ )
+ self._meta.commit_count = max(
+ self._meta.commit_count,
+ self._compression.compression_index,
+ )
+ self._meta.last_commit_at = get_current_timestamp()
+ await self._save_meta()
+ await self._write_phase1_ready_marker(archive_uri)
except Exception as e:
- logger.error(f"[commit] Failed to persist archive/live messages: {e}")
- self._messages = list(messages_to_archive) + list(retained_messages)
+ logger.error(f"[commit] Failed during {phase1_stage}: {e}")
+ # Whether the queue write failed or a queued Phase 1 stopped
+ # before publication, a terminal marker makes archive raw
+ # logically live and prevents a permanent pending directory.
+ try:
+ await self._write_failed_marker(
+ archive_uri,
+ stage=phase1_stage,
+ error=str(e),
+ )
+ except Exception:
+ logger.exception(
+ "Failed to mark archive after Phase 1 persistence failure: %s",
+ archive_uri,
+ )
+ self._messages = original_messages
self._compression.compression_index -= 1
raise
- # Lock released; live session now contains only the retained tail.
-
- # WM v2: live session is now the retained tail; pending_tokens resets
- # because anything that was pending has been archived.
- self._meta.message_count = len(self._messages)
- self._meta.pending_tokens = 0
- self._meta.keep_recent_count = keep_recent_count
- self._meta.commit_count = max(
- self._meta.commit_count,
- self._compression.compression_index,
- )
- self._meta.last_commit_at = get_current_timestamp()
- await self._save_meta()
+ # Lock released; Phase 1 intent, queue item, retained root, metadata and
+ # ready metadata are all durable.
self._compression.original_count += len(messages_to_archive)
logger.info(
@@ -1202,28 +1878,6 @@ class Session:
f"history/archive_{self._compression.compression_index:03d}/"
)
- # Snapshot mutable state for Phase 2.
- usage_snapshot = self._usage_records.copy()
- task_id = str(uuid4())
- queue_msg = SessionCommitMsg(
- task_id=task_id,
- session_id=self.session_id,
- session_uri=self._session_uri,
- archive_uri=archive_uri,
- user=self.ctx.user.to_dict(),
- actor_peer_id=self.ctx.actor_peer_id,
- memory_policy=effective_memory_policy,
- usage_uris=list(dict.fromkeys(u.uri for u in usage_snapshot if u.uri)),
- )
- await get_queue_manager().enqueue(QueueManager.SESSION_COMMIT, queue_msg.to_dict())
- await get_task_tracker().create(
- "session_commit",
- resource_id=self.session_id,
- account_id=self.ctx.account_id,
- user_id=self.ctx.user.user_id,
- task_id=task_id,
- )
-
return {
"session_id": self.session_id,
"status": "accepted",
@@ -1231,6 +1885,10 @@ class Session:
"archive_uri": archive_uri,
"archived": True,
"trace_id": trace_id,
+ "estimated_active_tokens": (
+ retention_plan.estimated_active_tokens if retention_plan else 0
+ ),
+ "budget_exceeded": retention_plan.budget_exceeded if retention_plan else False,
}
async def resume_queued_commit(self, msg: "SessionCommitMsg") -> None:
@@ -1276,6 +1934,25 @@ class Session:
)
return
+ if not await self._ensure_phase1_ready(msg.archive_uri):
+ try:
+ failed = json.loads(
+ await self._viking_fs.read_file(
+ f"{msg.archive_uri}/.failed.json",
+ ctx=self.ctx,
+ )
+ )
+ error = str(failed.get("error") or "session commit Phase 1 is not ready")
+ except Exception:
+ error = "session commit Phase 1 is not ready"
+ await tracker.fail(
+ msg.task_id,
+ error,
+ account_id=self.ctx.account_id,
+ user_id=self.ctx.user.user_id,
+ )
+ return
+
archive_messages = await self._read_archive_messages(msg.archive_uri)
if not archive_messages:
error = "session commit archive has no messages"
@@ -1348,11 +2025,23 @@ class Session:
extracted_skill_results: list[dict] = []
active_count_updated = 0
memory_diff_uri: Optional[str] = None
+ completed_memory_steps: Dict[str, set[str]] = {}
telemetry = OperationTelemetry(operation="session_commit_phase2", enabled=True)
archive_index = self._archive_index_from_uri(archive_uri)
try:
await self._wait_for_previous_archive_done(archive_index)
+ (
+ messages,
+ coverage_start_archive,
+ coverage_end_archive,
+ covered_failed_archives,
+ completed_memory_steps,
+ ) = await self._prepare_phase2_archive_messages(archive_uri, messages)
+ if not messages:
+ raise ValueError("session commit archive has no recoverable messages")
+ first_message_id = messages[0].id
+ last_message_id = messages[-1].id
await tracker.start(
task_id,
@@ -1366,9 +2055,19 @@ class Session:
ov_config = get_openviking_config()
effective_policy = MemoryPolicy.from_dict(memory_policy)
working_memory_enabled = effective_policy.working_memory_enabled
+ checkpoint_requests = (
+ await self._collect_checkpoint_requests_for_phase2(
+ archive_uri,
+ covered_failed_archives,
+ messages,
+ )
+ if working_memory_enabled
+ else []
+ )
latest_archive_overview = (
await self._get_latest_completed_archive_overview(
- exclude_archive_uri=archive_uri
+ exclude_archive_uri=archive_uri,
+ before_archive_index=archive_index,
)
if working_memory_enabled
else ""
@@ -1389,10 +2088,29 @@ class Session:
"(memory_policy.working_memory.enabled=false)"
)
return
- summary = await self._generate_archive_summary_async(
+ summary_kwargs: Dict[str, Any] = {
+ "latest_archive_overview": latest_archive_overview,
+ }
+ if checkpoint_requests:
+ summary_kwargs["checkpoint_requests"] = checkpoint_requests
+ generated = await self._generate_archive_summary_async(
extraction_messages,
- latest_archive_overview=latest_archive_overview,
+ **summary_kwargs,
+ )
+ summary_result = (
+ generated
+ if isinstance(generated, _ArchiveSummaryResult)
+ else _ArchiveSummaryResult(overview=str(generated or ""))
+ )
+ checkpoint_records = self._build_checkpoint_records(
+ checkpoint_requests,
+ summary_result.checkpoint_summaries,
)
+ summary = summary_result.overview
+ if checkpoint_requests and not summary.strip():
+ raise ValueError(
+ "Working Memory output is empty for a required checkpoint"
+ )
if self._viking_fs and summary:
abstract = self._extract_abstract_from_summary(summary)
await self._viking_fs.write_file(
@@ -1405,15 +2123,13 @@ class Session:
content=summary,
ctx=self.ctx,
)
- await self._viking_fs.write_file(
- uri=f"{archive_uri}/.meta.json",
- content=json.dumps(
- {
- "overview_tokens": estimate_text_tokens(summary),
- "abstract_tokens": estimate_text_tokens(abstract),
- }
- ),
- ctx=self.ctx,
+ await self._merge_archive_meta(
+ archive_uri,
+ {
+ "overview_tokens": estimate_text_tokens(summary),
+ "abstract_tokens": estimate_text_tokens(abstract),
+ "checkpoints": checkpoint_records,
+ },
)
async def _run_retryable_phase2_step(
@@ -1435,6 +2151,29 @@ class Session:
operation_name=operation_name,
)
+ async def _run_recorded_memory_step(
+ operation_name: str,
+ step: str,
+ step_messages: List[Message],
+ fn: Callable[[], Awaitable[Any]],
+ ) -> Any:
+ result = await _run_retryable_phase2_step(operation_name, fn)
+ completed_memory_steps.setdefault(step, set()).update(
+ message.id for message in step_messages
+ )
+ # Persist progress before waiting for sibling Phase 2
+ # tasks. A process restart or a sibling failure can then
+ # resume without applying this memory step twice.
+ await self._merge_archive_meta(
+ archive_uri,
+ {
+ "completed_memory_steps": (
+ self._serialize_completed_memory_steps(completed_memory_steps)
+ )
+ },
+ )
+ return result
+
# Summary, long-term memory, and execution-derived memory run concurrently.
memory_extraction_enabled = ov_config.memory.extraction_enabled
config_session_skill_extraction_enabled = (
@@ -1456,15 +2195,28 @@ class Session:
memory_type_filter
)
+ long_term_messages = [
+ message
+ for message in extraction_messages
+ if message.id not in completed_memory_steps.get("long_term", set())
+ ]
+ execution_messages = [
+ message
+ for message in extraction_messages
+ if message.id not in completed_memory_steps.get("execution", set())
+ ]
+
long_term_has_work = (
memory_extraction_enabled
and (self_memory_enabled or allowed_peer_ids)
and (long_term_memory_types is None or bool(long_term_memory_types))
+ and bool(long_term_messages)
)
execution_memory_has_work = (
self_memory_enabled
and memory_extraction_enabled
and (execution_memory_types is None or bool(execution_memory_types))
+ and bool(execution_messages)
)
session_skill_extraction_enabled = (
session_skill_extraction_enabled and execution_memory_has_work
@@ -1496,7 +2248,7 @@ class Session:
# (and so a final failure is recorded as a skipped
# archive instead of silently dropping the memory).
return await self._session_compressor.extract_long_term_memories(
- messages=extraction_messages,
+ messages=long_term_messages,
user=self.user,
session_id=self.session_id,
ctx=self.ctx,
@@ -1509,8 +2261,10 @@ class Session:
)
extraction_tasks.append(
- _run_retryable_phase2_step(
+ _run_recorded_memory_step(
"long_term_memory_extraction",
+ "long_term",
+ long_term_messages,
_run_long_term_memory_extraction,
)
)
@@ -1522,7 +2276,7 @@ class Session:
# See _run_long_term_memory_extraction: surface errors
# so retries can engage and final failures are visible.
return await self._session_compressor.extract_execution_memories(
- messages=extraction_messages,
+ messages=execution_messages,
ctx=self.ctx,
strict_extract_errors=True,
latest_archive_overview=latest_archive_overview,
@@ -1532,8 +2286,10 @@ class Session:
)
extraction_tasks.append(
- _run_retryable_phase2_step(
+ _run_recorded_memory_step(
"execution_memory_extraction",
+ "execution",
+ execution_messages,
_run_execution_memory_extraction,
)
)
@@ -1543,10 +2299,11 @@ class Session:
*extraction_tasks,
return_exceptions=True,
)
- # Binary archive outcome: if ANY Phase 2 step (Working
- # Memory summary, long-term, or execution memory) still
- # fails after retries, the whole archive is marked
- # .failed.json and skipped. There is no partial state.
+ # The archive outcome is binary: if ANY Phase 2 step
+ # still fails after retries, no .done coverage is
+ # published. Successful memory steps keep a message-ID
+ # progress marker solely to make later raw replay
+ # idempotent.
extraction_error: Optional[BaseException] = None
for label, result in zip(extraction_labels, _results, strict=True):
if isinstance(result, Exception):
@@ -1667,7 +2424,18 @@ class Session:
)
# Write .done last so a recovered queue item can skip completed work.
- await self._write_done_file(archive_uri, first_message_id, last_message_id)
+ await self._write_done_file(
+ archive_uri,
+ first_message_id,
+ last_message_id,
+ working_memory_enabled=working_memory_enabled,
+ coverage_start_archive=coverage_start_archive,
+ coverage_end_archive=coverage_end_archive,
+ covered_failed_archives=covered_failed_archives,
+ completed_memory_steps=self._serialize_completed_memory_steps(
+ completed_memory_steps
+ ),
+ )
result_payload = {
"session_id": self.session_id,
@@ -1709,6 +2477,9 @@ class Session:
archive_uri,
stage="memory_extraction",
error=str(e),
+ completed_memory_steps=self._serialize_completed_memory_steps(
+ completed_memory_steps
+ ),
)
await tracker.fail(
task_id, str(e), account_id=self.ctx.account_id, user_id=self.ctx.user.user_id
@@ -1720,14 +2491,26 @@ class Session:
archive_uri: str,
first_message_id: str,
last_message_id: str,
+ *,
+ working_memory_enabled: Optional[bool] = None,
+ coverage_start_archive: Optional[str] = None,
+ coverage_end_archive: Optional[str] = None,
+ covered_failed_archives: Optional[List[str]] = None,
+ completed_memory_steps: Optional[Dict[str, List[str]]] = None,
) -> None:
"""Write .done marker file to the archive directory."""
if not self._viking_fs:
return
+ archive_id = archive_uri.rstrip("/").split("/")[-1]
content = json.dumps(
{
"starting_message_id": first_message_id,
"ending_message_id": last_message_id,
+ "working_memory_enabled": working_memory_enabled,
+ "coverage_start_archive": coverage_start_archive or archive_id,
+ "coverage_end_archive": coverage_end_archive or archive_id,
+ "covered_failed_archives": list(covered_failed_archives or []),
+ "completed_memory_steps": dict(completed_memory_steps or {}),
},
ensure_ascii=False,
)
@@ -1744,6 +2527,7 @@ class Session:
error: str,
blocked_by: str = "",
skipped: bool = True,
+ completed_memory_steps: Optional[Dict[str, List[str]]] = None,
) -> None:
"""Persist a terminal failure marker for the archive."""
if not self._viking_fs:
@@ -1753,6 +2537,7 @@ class Session:
"error": error,
"failed_at": get_current_timestamp(),
"skipped": skipped,
+ "completed_memory_steps": dict(completed_memory_steps or {}),
}
if blocked_by:
payload["blocked_by"] = blocked_by
@@ -1769,8 +2554,21 @@ class Session:
context = await self._collect_session_context_components()
merged_messages = context["messages"]
-
- message_tokens = sum(m.estimated_tokens for m in merged_messages)
+ budgeted = fit_active_messages_to_budget(
+ merged_messages,
+ token_budget=token_budget,
+ )
+ merged_messages = budgeted.messages
+ message_tokens = budgeted.estimated_tokens
+ if budgeted.dropped_message_ids or budgeted.truncated_message_ids:
+ logger.info(
+ "[get_session_context] active budget applied: session_id=%s, "
+ "budget=%s, dropped=%s, truncated=%s",
+ self.session_id,
+ token_budget,
+ len(budgeted.dropped_message_ids),
+ len(budgeted.truncated_message_ids),
+ )
# 精简日志:只打印关键信息
logger.info(
@@ -1861,49 +2659,60 @@ class Session:
async def _collect_session_context_components(self) -> Dict[str, Any]:
"""Collect the latest summary archive and merged pending/live messages."""
- completed_archives = await self._get_completed_archive_refs()
+ archive_states = await self._scan_archive_states()
+ completed_archives = [
+ state for state in reversed(archive_states) if state.state == "completed"
+ ]
latest_archive = None
pre_archive_abstracts: List[Dict[str, Any]] = []
- failed_archives = 0
+ covered_archive_ids = self._covered_archive_ids(archive_states)
+ failed_archives = sum(
+ state.state == "failed" and state.archive_id not in covered_archive_ids
+ for state in archive_states
+ )
for archive in completed_archives:
- if latest_archive is None:
- overview = await self._read_archive_overview(archive["archive_uri"])
- if not overview:
- failed_archives += 1
- continue
-
+ # ``.done`` is the authoritative completion marker. A completed
+ # archive may intentionally have no overview when Working Memory is
+ # disabled, so keep looking for the newest completed archive that
+ # actually has a readable overview.
+ if latest_archive is None and archive.overview.strip():
latest_archive = {
- "archive_id": archive["archive_id"],
- "archive_uri": archive["archive_uri"],
- "overview": overview,
+ "archive_id": archive.archive_id,
+ "archive_uri": archive.archive_uri,
+ "overview": archive.overview,
"overview_tokens": await self._read_archive_overview_tokens(
- archive["archive_uri"], overview
+ archive.archive_uri, archive.overview
),
}
- abstract = await self._read_archive_abstract(archive["archive_uri"])
+ abstract = await self._read_archive_abstract(archive.archive_uri, archive.overview)
if abstract:
pre_archive_abstracts.append(
{
- "archive_id": archive["archive_id"],
+ "archive_id": archive.archive_id,
"abstract": abstract,
"tokens": estimate_text_tokens(abstract),
}
)
- else:
- failed_archives += 1
+
+ uncovered = await self._get_uncovered_archive_messages(archive_states)
+ merged_messages = self._stable_deduplicate_messages(uncovered + list(self._messages))
+ merged_messages = await self._insert_checkpoint_if_needed(
+ merged_messages,
+ archive_states,
+ )
return {
"latest_archive": latest_archive,
"pre_archive_abstracts": pre_archive_abstracts,
- "total_archives": len(completed_archives),
+ "total_archives": len(archive_states),
"failed_archives": failed_archives,
- "messages": await self._get_pending_archive_messages() + list(self._messages),
+ "messages": merged_messages,
}
async def _list_archive_refs(self) -> List[Dict[str, Any]]:
"""List archive refs sorted by archive index descending."""
- if not self._viking_fs or self.compression.compression_index <= 0:
+ if not self._viking_fs:
return []
try:
@@ -1931,22 +2740,192 @@ class Session:
return sorted(refs, key=lambda item: item["index"], reverse=True)
+ async def _scan_archive_states(self) -> List[ArchiveState]:
+ """Derive every archive state exclusively from its directory markers."""
+ states: List[ArchiveState] = []
+ refs = sorted(await self._list_archive_refs(), key=lambda item: item["index"])
+ for archive in refs:
+ done_uri = f"{archive['archive_uri']}/.done"
+ try:
+ done_exists = await self._viking_fs.exists(done_uri, ctx=self.ctx)
+ except Exception:
+ done_exists = False
+ done: Dict[str, Any] = {}
+ if done_exists:
+ try:
+ raw_done = await self._viking_fs.read_file(done_uri, ctx=self.ctx)
+ parsed_done = json.loads(raw_done or "{}")
+ if isinstance(parsed_done, dict):
+ done = parsed_done
+ except Exception as exc:
+ # Marker existence still means completion, but unreadable
+ # contents cannot extend coverage to earlier archives.
+ logger.warning(
+ "Unreadable archive done marker %s: %s", archive["archive_uri"], exc
+ )
+
+ if done_exists:
+ overview = await self._read_archive_overview(archive["archive_uri"])
+ if done.get("working_memory_enabled") is True and not overview.strip():
+ # New markers distinguish an intentionally overview-less
+ # working_memory=false commit from a missing/corrupt
+ # required overview. The latter remains logically live and
+ # can be rolled forward by a later successful archive.
+ logger.warning(
+ "Completed archive has no readable required overview: %s",
+ archive["archive_uri"],
+ )
+ states.append(
+ ArchiveState(
+ archive_id=archive["archive_id"],
+ archive_uri=archive["archive_uri"],
+ index=archive["index"],
+ state="failed",
+ done=done,
+ failed={
+ "stage": "archive_overview",
+ "error": "required overview is missing or unreadable",
+ },
+ )
+ )
+ continue
+
+ # working_memory=false legitimately writes .done without an
+ # overview. Legacy markers lack the explicit flag, so retain
+ # their established completed semantics for compatibility.
+ states.append(
+ ArchiveState(
+ archive_id=archive["archive_id"],
+ archive_uri=archive["archive_uri"],
+ index=archive["index"],
+ state="completed",
+ overview=overview,
+ done=done,
+ )
+ )
+ continue
+
+ failed: Dict[str, Any] = {}
+ failed_uri = f"{archive['archive_uri']}/.failed.json"
+ try:
+ failed_exists = await self._viking_fs.exists(failed_uri, ctx=self.ctx)
+ except Exception:
+ failed_exists = False
+ if failed_exists:
+ try:
+ parsed_failed = json.loads(
+ await self._viking_fs.read_file(failed_uri, ctx=self.ctx) or "{}"
+ )
+ if isinstance(parsed_failed, dict):
+ failed = parsed_failed
+ except Exception as exc:
+ logger.warning("Unreadable archive failed marker %s: %s", failed_uri, exc)
+ states.append(
+ ArchiveState(
+ archive_id=archive["archive_id"],
+ archive_uri=archive["archive_uri"],
+ index=archive["index"],
+ state="failed" if failed_exists else "pending",
+ failed=failed,
+ )
+ )
+ return states
+
+ @staticmethod
+ def _covered_archive_ids(states: List[ArchiveState]) -> set[str]:
+ """Return archives covered by an authoritative completion marker."""
+ existing = {state.archive_id: state for state in states}
+ covered: set[str] = set()
+ for state in states:
+ if state.state != "completed":
+ continue
+ start = max(
+ 1,
+ min(state.coverage_start_index, state.coverage_end_index, state.index),
+ )
+ end = min(
+ state.index,
+ max(state.coverage_start_index, state.coverage_end_index),
+ )
+ for candidate in states:
+ # A pending archive still has a live Phase 2 owner and is never
+ # valid coverage input. Even malformed/manual range metadata
+ # must not make its raw messages disappear.
+ if start <= candidate.index <= end and candidate.state != "pending":
+ covered.add(candidate.archive_id)
+ explicit = state.done.get("covered_failed_archives", [])
+ if isinstance(explicit, list):
+ covered.update(
+ archive_id
+ for archive_id in explicit
+ if isinstance(archive_id, str)
+ and archive_id in existing
+ and existing[archive_id].index <= state.index
+ and existing[archive_id].state == "failed"
+ )
+ return covered
+
+ @staticmethod
+ def _stable_deduplicate_messages(messages: List[Message]) -> List[Message]:
+ """Stable-deduplicate crash/recovery overlaps by durable message id."""
+ seen: set[str] = set()
+ result: List[Message] = []
+ for message in messages:
+ if message.id in seen:
+ continue
+ seen.add(message.id)
+ result.append(message)
+ return result
+
+ @staticmethod
+ def _merge_completed_memory_steps(
+ target: Dict[str, set[str]],
+ raw: Any,
+ ) -> None:
+ """Merge durable per-step message coverage from archive metadata."""
+ if not isinstance(raw, dict):
+ return
+ for step in _MEMORY_STEP_NAMES:
+ message_ids = raw.get(step)
+ if not isinstance(message_ids, list):
+ continue
+ target.setdefault(step, set()).update(
+ item for item in message_ids if isinstance(item, str) and item
+ )
+
+ @staticmethod
+ def _serialize_completed_memory_steps(
+ completed: Dict[str, set[str]],
+ ) -> Dict[str, List[str]]:
+ return {
+ step: sorted(completed.get(step, set()))
+ for step in _MEMORY_STEP_NAMES
+ if completed.get(step)
+ }
+
async def _get_completed_archive_refs(
self,
exclude_archive_uri: Optional[str] = None,
+ before_archive_index: Optional[int] = None,
) -> List[Dict[str, Any]]:
"""Return completed archive refs sorted by archive index descending."""
completed: List[Dict[str, Any]] = []
exclude = exclude_archive_uri.rstrip("/") if exclude_archive_uri else None
- for archive in await self._list_archive_refs():
- if exclude and archive["archive_uri"] == exclude:
+ for state in reversed(await self._scan_archive_states()):
+ if exclude and state.archive_uri == exclude:
continue
- try:
- await self._viking_fs.read_file(f"{archive['archive_uri']}/.done", ctx=self.ctx)
- except Exception:
+ if before_archive_index is not None and state.index >= before_archive_index:
+ continue
+ if state.state != "completed":
continue
- completed.append(archive)
+ completed.append(
+ {
+ "archive_id": state.archive_id,
+ "archive_uri": state.archive_uri,
+ "index": state.index,
+ }
+ )
return completed
@@ -2006,9 +2985,13 @@ class Session:
async def _get_latest_completed_archive_summary(
self,
exclude_archive_uri: Optional[str] = None,
+ before_archive_index: Optional[int] = None,
) -> Optional[Dict[str, Any]]:
"""Return the newest readable completed archive summary."""
- for archive in await self._get_completed_archive_refs(exclude_archive_uri):
+ for archive in await self._get_completed_archive_refs(
+ exclude_archive_uri,
+ before_archive_index,
+ ):
overview = await self._read_archive_overview(archive["archive_uri"])
if not overview:
continue
@@ -2028,48 +3011,295 @@ class Session:
async def _get_latest_completed_archive_overview(
self,
exclude_archive_uri: Optional[str] = None,
+ before_archive_index: Optional[int] = None,
) -> str:
"""Return the newest completed archive overview, skipping incomplete archives."""
- summary = await self._get_latest_completed_archive_summary(exclude_archive_uri)
+ summary = await self._get_latest_completed_archive_summary(
+ exclude_archive_uri,
+ before_archive_index,
+ )
return summary["overview"] if summary else ""
- async def _get_pending_archive_messages(self) -> List[Message]:
- """Return messages from in-progress archives newer than the latest completed archive."""
- # Seed from 0 rather than ``commit_count``: Phase 1 bumps ``commit_count``
- # as soon as an archive's messages are written, before its Phase 2 memory
- # extraction finishes and the ``.done`` marker is written. The in-flight
- # archive's index therefore equals ``commit_count``, so seeding from
- # ``commit_count`` would treat that still-pending archive as already
- # completed and drop its messages from the assembled context (issue #3129).
- # Completed archives are detected below via their ``.done`` marker.
- latest_completed_index = 0
- pending_archives: List[Dict[str, Any]] = []
- for archive in sorted(await self._list_archive_refs(), key=lambda item: item["index"]):
- try:
- await self._viking_fs.read_file(f"{archive['archive_uri']}/.done", ctx=self.ctx)
- latest_completed_index = max(latest_completed_index, archive["index"])
+ async def _read_archive_meta(self, archive_uri: str) -> Dict[str, Any]:
+ try:
+ content = await self._viking_fs.read_file(f"{archive_uri}/.meta.json", ctx=self.ctx)
+ parsed = json.loads(content)
+ return parsed if isinstance(parsed, dict) else {}
+ except Exception:
+ return {}
+
+ async def _collect_checkpoint_requests_for_phase2(
+ self,
+ archive_uri: str,
+ covered_failed_archives: List[str],
+ messages: List[Message],
+ ) -> List[_CheckpointRequest]:
+ """Collect and validate partial-Turn checkpoint work owned by this Phase 2.
+
+ Failed archives rolled into the current commit contribute their pending
+ checkpoint sources. Requests sharing one retained user anchor are merged
+ before the LLM call, so context assembly inserts one checkpoint per Turn.
+ """
+ archive_root = archive_uri.rstrip("/").rsplit("/", 1)[0]
+ current_archive_id = archive_uri.rstrip("/").split("/")[-1]
+ archive_ids = list(
+ dict.fromkeys(
+ [
+ archive_id
+ for archive_id in [*covered_failed_archives, current_archive_id]
+ if isinstance(archive_id, str) and re.fullmatch(r"archive_\d+", archive_id)
+ ]
+ )
+ )
+ archive_ids.sort(key=lambda item: int(item.split("_")[1]))
+
+ message_by_id = {message.id: message for message in messages}
+ message_ids = set(message_by_id)
+ message_order = {message.id: index for index, message in enumerate(messages)}
+ turn_anchor_by_message_id: Dict[str, Optional[str]] = {}
+ for turn in build_turns(messages):
+ owner_anchor_id = turn.anchor.id if turn.anchor is not None else None
+ for message in turn.messages:
+ turn_anchor_by_message_id[message.id] = owner_anchor_id
+ merged: Dict[str, Dict[str, Any]] = {}
+ for archive_id in archive_ids:
+ meta = await self._read_archive_meta(f"{archive_root}/{archive_id}")
+ plan = meta.get("retention_plan")
+ if not isinstance(plan, dict) or not plan.get("partial_turn"):
continue
- except Exception:
- pass
- try:
- await self._viking_fs.read_file(
- f"{archive['archive_uri']}/.failed.json",
- ctx=self.ctx,
+ anchor_id = plan.get("turn_anchor_message_id")
+ raw_source_ids = plan.get("checkpoint_source_message_ids")
+ if not isinstance(anchor_id, str) or not anchor_id:
+ raise ValueError(f"{archive_id} has a partial Turn without a valid anchor")
+ if not isinstance(raw_source_ids, list) or not raw_source_ids:
+ raise ValueError(
+ f"{archive_id} has a partial Turn without checkpoint source messages"
+ )
+ source_ids = [
+ source_id
+ for source_id in raw_source_ids
+ if isinstance(source_id, str) and source_id
+ ]
+ if len(source_ids) != len(raw_source_ids):
+ raise ValueError(f"{archive_id} has invalid checkpoint source message IDs")
+
+ missing_ids = [
+ message_id
+ for message_id in [anchor_id, *source_ids]
+ if message_id not in message_ids
+ ]
+ if missing_ids:
+ raise ValueError(
+ f"{archive_id} checkpoint source is missing messages: {missing_ids}"
+ )
+ invalid_source_ids = [
+ source_id
+ for source_id in source_ids
+ if is_user_query(message_by_id[source_id])
+ or turn_anchor_by_message_id.get(source_id) != anchor_id
+ ]
+ if invalid_source_ids:
+ raise ValueError(
+ f"{archive_id} checkpoint source is outside its Assistant/Tool prefix: "
+ f"{invalid_source_ids}"
+ )
+
+ request = merged.setdefault(
+ anchor_id,
+ {
+ "source_message_ids": [],
+ "retained_message_token_budget": 0,
+ "estimated_active_tokens": 0,
+ },
+ )
+ request["source_message_ids"] = list(
+ dict.fromkeys([*request["source_message_ids"], *source_ids])
+ )
+ # The newest plan for the same still-active Turn is authoritative.
+ request["retained_message_token_budget"] = max(
+ 0, int(plan.get("retained_message_token_budget", 0) or 0)
+ )
+ request["estimated_active_tokens"] = max(
+ 0, int(plan.get("estimated_active_tokens", 0) or 0)
+ )
+
+ requests: List[_CheckpointRequest] = []
+ for anchor_id, request in merged.items():
+ source_ids = sorted(
+ request["source_message_ids"],
+ key=lambda message_id: message_order[message_id],
+ )
+ requests.append(
+ _CheckpointRequest(
+ turn_anchor_message_id=anchor_id,
+ source_message_ids=tuple(source_ids),
+ retained_message_token_budget=request["retained_message_token_budget"],
+ estimated_active_tokens=request["estimated_active_tokens"],
+ )
+ )
+ requests.sort(
+ key=lambda request: min(
+ message_order[source_id] for source_id in request.source_message_ids
+ )
+ )
+ return requests
+
+ @staticmethod
+ def _build_checkpoint_records(
+ requests: List[_CheckpointRequest],
+ summaries: tuple[str, ...],
+ ) -> List[Dict[str, Any]]:
+ """Bind ordinal LLM outputs to server-owned IDs and enforce local budgets."""
+ if len(summaries) != len(requests):
+ raise ValueError(
+ "Working Memory output returned "
+ f"{len(summaries)} checkpoint summaries for {len(requests)} requests"
+ )
+
+ records: List[Dict[str, Any]] = []
+ for request, raw_summary in zip(requests, summaries, strict=True):
+ summary = raw_summary.strip() if isinstance(raw_summary, str) else ""
+ if not summary:
+ raise ValueError("Working Memory output contains an empty checkpoint summary")
+
+ configured_budget = request.retained_message_token_budget
+ if configured_budget > 0:
+ available = configured_budget - request.estimated_active_tokens
+ checkpoint_budget = (
+ min(1024, available) if available > 0 else min(256, configured_budget)
)
+ else:
+ checkpoint_budget = 1024
+ abstract = truncate_text_to_token_budget(summary, max(1, checkpoint_budget))
+ if not abstract:
+ raise ValueError("Checkpoint summary is empty after local token truncation")
+ records.append(
+ {
+ "turn_anchor_message_id": request.turn_anchor_message_id,
+ "source_message_ids": list(request.source_message_ids),
+ "abstract": abstract,
+ "estimated_tokens": estimate_text_tokens(abstract),
+ }
+ )
+ return records
+
+ async def _insert_checkpoint_if_needed(
+ self,
+ messages: List[Message],
+ states: List[ArchiveState],
+ ) -> List[Message]:
+ """Insert persisted checkpoint products after retained anchors.
+
+ Only completed archives are authoritative. Legacy archives without a
+ ``checkpoints`` metadata field do not synthesize one from their overview.
+ """
+ if not messages:
+ return messages
+
+ message_ids = {message.id for message in messages}
+ candidates: Dict[str, Dict[str, Any]] = {}
+ for state in states:
+ if state.state != "completed":
continue
- except Exception:
- pass
+ meta = await self._read_archive_meta(state.archive_uri)
+ checkpoints = meta.get("checkpoints")
+ if not isinstance(checkpoints, list):
+ continue
+ for checkpoint in checkpoints:
+ if not isinstance(checkpoint, dict):
+ continue
+ anchor_id = checkpoint.get("turn_anchor_message_id")
+ source_ids = checkpoint.get("source_message_ids")
+ abstract = checkpoint.get("abstract")
+ if not isinstance(anchor_id, str) or anchor_id not in message_ids:
+ continue
+ if not isinstance(source_ids, list) or not source_ids:
+ continue
+ if not isinstance(abstract, str) or not abstract.strip():
+ continue
+ valid_source_ids = [
+ item for item in source_ids if isinstance(item, str) and item
+ ]
+ if not valid_source_ids:
+ continue
- pending_archives.append(archive)
+ # One long-running User Turn may be partially committed more
+ # than once. Keep every disjoint completed prefix instead of
+ # letting the newest checkpoint erase earlier compressed Steps.
+ candidate = candidates.setdefault(
+ anchor_id,
+ {
+ "archive_id": state.archive_id,
+ "archive_uri": state.archive_uri,
+ "source_message_ids": [],
+ "abstracts": [],
+ },
+ )
+ seen_source_ids = set(candidate["source_message_ids"])
+ new_source_ids = [
+ source_id
+ for source_id in valid_source_ids
+ if source_id not in seen_source_ids
+ ]
+ if not new_source_ids:
+ continue
+ candidate["archive_id"] = state.archive_id
+ candidate["archive_uri"] = state.archive_uri
+ candidate["source_message_ids"].extend(new_source_ids)
+ candidate["abstracts"].append(abstract.strip())
+
+ if not candidates:
+ return messages
+
+ result: List[Message] = []
+ for message in messages:
+ result.append(message)
+ candidate = candidates.get(message.id)
+ if not candidate:
+ continue
+ abstract = "\n\n".join(candidate["abstracts"])
+ if not abstract:
+ continue
+ result.append(
+ Message(
+ id=f"checkpoint_{candidate['archive_id']}_{message.id}",
+ role="assistant",
+ parts=[
+ ContextPart(
+ uri=candidate["archive_uri"],
+ context_type="memory",
+ abstract=abstract,
+ )
+ ],
+ # The checkpoint is synthesized by OpenViking, not authored
+ # by the user who owns the retained anchor.
+ peer_id=None,
+ created_at=message.created_at,
+ turn_id=message.turn_id,
+ message_kind="checkpoint",
+ source_message_ids=candidate["source_message_ids"],
+ )
+ )
+ return result
- pending_messages: List[Message] = []
- for archive in pending_archives:
- if archive["index"] <= latest_completed_index:
+ async def _get_uncovered_archive_messages(
+ self,
+ states: Optional[List[ArchiveState]] = None,
+ ) -> List[Message]:
+ """Return pending/failed raw messages not covered by a completed archive."""
+ states = states if states is not None else await self._scan_archive_states()
+ covered = self._covered_archive_ids(states)
+ messages: List[Message] = []
+ for state in states:
+ if state.archive_id in covered or state.state == "completed":
continue
- pending_messages.extend(await self._read_archive_messages(archive["archive_uri"]))
+ messages.extend(await self._read_archive_messages(state.archive_uri))
+ return self._stable_deduplicate_messages(messages)
- return pending_messages
+ async def _get_pending_archive_messages(self) -> List[Message]:
+ """Compatibility wrapper; uncovered includes pending and failed archives."""
+ return await self._get_uncovered_archive_messages()
@staticmethod
def _archive_index_from_uri(archive_uri: str) -> int:
@@ -2080,70 +3310,148 @@ class Session:
return int(match.group(1))
async def _wait_for_previous_archive_done(self, archive_index: int) -> bool:
- """Wait until the previous archive reaches a terminal state."""
+ """Wait until every earlier archive reaches a terminal state."""
if archive_index <= 1 or not self._viking_fs:
return True
- previous_archive_uri = f"{self._session_uri}/history/archive_{archive_index - 1:03d}"
while True:
- try:
- await self._viking_fs.read_file(f"{previous_archive_uri}/.done", ctx=self.ctx)
- return True
- except Exception:
- pass
-
- try:
- await self._viking_fs.read_file(
- f"{previous_archive_uri}/.failed.json",
- ctx=self.ctx,
- )
- logger.info(
- "Previous archive %s failed and is skipped; continuing",
- previous_archive_uri,
- )
+ earlier_states = [
+ state
+ for state in await self._scan_archive_states()
+ if state.index < archive_index
+ ]
+ pending_states = [state for state in earlier_states if state.state == "pending"]
+ if not pending_states:
+ non_completed = [state for state in earlier_states if state.state == "failed"]
+ if non_completed:
+ logger.info(
+ "Earlier archives reached terminal non-completed states; "
+ "continuing with raw replay: %s",
+ [state.archive_id for state in non_completed],
+ )
return True
- except Exception:
- pass
+ # A new-format intent without ready status may be left by a
+ # process interruption. Reconcile it under the session lock rather
+ # than waiting forever for a queue item that may never have existed.
+ reconciled = False
+ for state in pending_states:
+ phase1 = await self._read_phase1_meta(state.archive_uri)
+ if not phase1 or phase1.get("status") == "ready":
+ continue
+ await self._ensure_phase1_ready(state.archive_uri)
+ reconciled = True
+ if reconciled:
+ continue
await asyncio.sleep(_ARCHIVE_WAIT_POLL_SECONDS)
+ async def _prepare_phase2_archive_messages(
+ self,
+ archive_uri: str,
+ current_messages: List[Message],
+ ) -> tuple[List[Message], str, str, List[str], Dict[str, set[str]]]:
+ """Roll earlier failed raw archives into current Phase 2 input.
+
+ Pending archives are never replayed: their own Phase 2 job still owns
+ them, and this method is called only after all earlier directories have
+ reached a terminal state.
+ """
+ current_index = self._archive_index_from_uri(archive_uri)
+ states = await self._scan_archive_states()
+ covered = self._covered_archive_ids(states)
+ replay_states = [
+ state
+ for state in states
+ if state.index < current_index
+ and state.archive_id not in covered
+ and state.state == "failed"
+ ]
+
+ combined: List[Message] = []
+ completed_memory_steps: Dict[str, set[str]] = {}
+ for state in replay_states:
+ combined.extend(await self._read_archive_messages(state.archive_uri))
+ marker = state.failed
+ self._merge_completed_memory_steps(
+ completed_memory_steps,
+ marker.get("completed_memory_steps") if marker else None,
+ )
+ state_meta = await self._read_archive_meta(state.archive_uri)
+ self._merge_completed_memory_steps(
+ completed_memory_steps,
+ state_meta.get("completed_memory_steps"),
+ )
+ combined.extend(current_messages)
+ combined = self._stable_deduplicate_messages(combined)
+
+ # A restarted queue item can resume the current archive after a process
+ # died between a successful memory step and the final .done write.
+ current_meta = await self._read_archive_meta(archive_uri)
+ self._merge_completed_memory_steps(
+ completed_memory_steps,
+ current_meta.get("completed_memory_steps"),
+ )
+
+ coverage_start_index = min([current_index] + [state.index for state in replay_states])
+ covered_failed = [state.archive_id for state in replay_states if state.state == "failed"]
+ return (
+ combined,
+ f"archive_{coverage_start_index:03d}",
+ f"archive_{current_index:03d}",
+ covered_failed,
+ completed_memory_steps,
+ )
+
async def _merge_and_save_commit_meta(
self,
archive_index: int,
memories_extracted: Dict[str, int],
telemetry_snapshot: Any,
) -> None:
- """Reload and merge latest meta state before persisting commit results."""
- latest_meta = self._meta
- try:
- meta_content = await self._viking_fs.read_file(
- f"{self._session_uri}/.meta.json",
- ctx=self.ctx,
- )
- latest_meta = SessionMeta.from_dict(json.loads(meta_content))
- except Exception:
+ """Merge Phase 2 results without overwriting concurrent root updates."""
+ from openviking.storage.transaction import LockContext, get_lock_manager
+
+ session_path = self._viking_fs._uri_to_path(self._session_uri, ctx=self.ctx)
+ async with LockContext(
+ get_lock_manager(),
+ [session_path],
+ lock_mode="exact",
+ timeout=_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS,
+ ):
latest_meta = self._meta
+ try:
+ meta_content = await self._viking_fs.read_file(
+ f"{self._session_uri}/.meta.json",
+ ctx=self.ctx,
+ )
+ latest_meta = SessionMeta.from_dict(json.loads(meta_content))
+ except Exception:
+ latest_meta = self._meta
+
+ if telemetry_snapshot:
+ llm = telemetry_snapshot.summary.get("tokens", {}).get("llm", {})
+ latest_meta.llm_token_usage["prompt_tokens"] += llm.get("input", 0)
+ latest_meta.llm_token_usage["completion_tokens"] += llm.get("output", 0)
+ latest_meta.llm_token_usage["total_tokens"] += llm.get("total", 0)
+ latest_meta.llm_token_usage["cached_tokens"] += llm.get("prompt_cached", 0)
+ latest_meta.llm_token_usage["reasoning_tokens"] += llm.get(
+ "completion_reasoning", 0
+ )
+ embedding = telemetry_snapshot.summary.get("tokens", {}).get("embedding", {})
+ latest_meta.embedding_token_usage["total_tokens"] += embedding.get("total", 0)
- if telemetry_snapshot:
- llm = telemetry_snapshot.summary.get("tokens", {}).get("llm", {})
- latest_meta.llm_token_usage["prompt_tokens"] += llm.get("input", 0)
- latest_meta.llm_token_usage["completion_tokens"] += llm.get("output", 0)
- latest_meta.llm_token_usage["total_tokens"] += llm.get("total", 0)
- latest_meta.llm_token_usage["cached_tokens"] += llm.get("prompt_cached", 0)
- latest_meta.llm_token_usage["reasoning_tokens"] += llm.get("completion_reasoning", 0)
- embedding = telemetry_snapshot.summary.get("tokens", {}).get("embedding", {})
- latest_meta.embedding_token_usage["total_tokens"] += embedding.get("total", 0)
-
- latest_meta.commit_count = max(latest_meta.commit_count, archive_index)
- for cat, count in memories_extracted.items():
- latest_meta.memories_extracted[cat] = latest_meta.memories_extracted.get(cat, 0) + count
- latest_meta.memories_extracted["total"] = (
- latest_meta.memories_extracted.get("total", 0) + count
- )
- latest_meta.last_commit_at = get_current_timestamp()
- latest_meta.message_count = await self._read_live_message_count()
- self._meta = latest_meta
- await self._save_meta()
+ latest_meta.commit_count = max(latest_meta.commit_count, archive_index)
+ for cat, count in memories_extracted.items():
+ latest_meta.memories_extracted[cat] = (
+ latest_meta.memories_extracted.get(cat, 0) + count
+ )
+ latest_meta.memories_extracted["total"] = (
+ latest_meta.memories_extracted.get("total", 0) + count
+ )
+ latest_meta.last_commit_at = get_current_timestamp()
+ latest_meta.message_count = await self._read_live_message_count()
+ self._meta = latest_meta
+ await self._save_meta()
async def _read_live_message_count(self) -> int:
"""Count current live session messages from persisted storage."""
@@ -2158,6 +3466,26 @@ class Session:
return len(self._messages)
return len([line for line in content.strip().split("\n") if line.strip()])
+ async def _read_live_messages_strict(self) -> List[Message]:
+ """Read the authoritative root JSONL without silently dropping corrupt rows."""
+ if not self._viking_fs:
+ return list(self._messages)
+ content = await self._viking_fs.read_file(
+ f"{self._session_uri}/messages.jsonl",
+ ctx=self.ctx,
+ )
+ messages: List[Message] = []
+ for line_number, line in enumerate(content.splitlines(), start=1):
+ if not line.strip():
+ continue
+ try:
+ messages.append(Message.from_dict(json.loads(line)))
+ except Exception as exc:
+ raise ValueError(
+ f"Invalid live message JSONL at line {line_number}: {exc}"
+ ) from exc
+ return messages
+
def _extract_abstract_from_summary(self, summary: str) -> str:
"""Extract one-sentence overview from structured summary."""
if not summary:
@@ -2190,11 +3518,72 @@ class Session:
body = "\n".join(lines) if lines else "(no content)"
return f"[{m.role}]: {body}"
+ @classmethod
+ def _format_messages_for_wm(
+ cls,
+ messages: List[Message],
+ checkpoint_requests: List[_CheckpointRequest],
+ ) -> str:
+ """Format WM input and mark checkpoint sources with ordinal-only tags."""
+ source_indexes: Dict[str, int] = {}
+ for index, request in enumerate(checkpoint_requests):
+ for message_id in request.source_message_ids:
+ previous = source_indexes.setdefault(message_id, index)
+ if previous != index:
+ raise ValueError(
+ f"Checkpoint source message {message_id} belongs to multiple requests"
+ )
+
+ lines: List[str] = []
+ open_index: Optional[int] = None
+ for message in messages:
+ index = source_indexes.get(message.id)
+ if index != open_index:
+ if open_index is not None:
+ lines.append("</checkpoint_source>")
+ if index is not None:
+ lines.append(f'<checkpoint_source index="{index}">')
+ open_index = index
+ lines.append(cls._format_message_for_wm(message))
+ if open_index is not None:
+ lines.append("</checkpoint_source>")
+ return "\n".join(lines)
+
+ @staticmethod
+ def _checkpoint_prompt_instructions(request_count: int) -> str:
+ if request_count <= 0:
+ return ""
+ return (
+ "# CHECKPOINT OUTPUT\n\n"
+ f"The session content contains checkpoint_source blocks indexed 0 through "
+ f"{request_count - 1}. In the SAME tool call, return checkpoint_summaries "
+ f"with exactly {request_count} strings in index order. Each string must "
+ "summarize only its marked block as a compact continuation note: preserve "
+ "the assistant's intent, important tool actions and results, conclusions, "
+ "and unfinished work; omit raw output bulk and do not mention archiving, "
+ "checkpointing, or this instruction."
+ )
+
+ @staticmethod
+ def _parse_required_checkpoint_summaries(
+ args: Dict[str, Any],
+ request_count: int,
+ ) -> tuple[str, ...]:
+ raw = args.get("checkpoint_summaries")
+ if not isinstance(raw, list):
+ raise ValueError("tool_call arguments.checkpoint_summaries missing")
+ if len(raw) != request_count or not all(isinstance(item, str) for item in raw):
+ raise ValueError(
+ f"tool_call checkpoint_summaries must contain exactly {request_count} strings"
+ )
+ return tuple(raw)
+
async def _generate_archive_summary_async(
self,
messages: List[Message],
latest_archive_overview: str = "",
- ) -> str:
+ checkpoint_requests: Optional[List[_CheckpointRequest]] = None,
+ ) -> str | _ArchiveSummaryResult:
"""Generate Working Memory document for the current archive (async).
Two paths:
@@ -2211,14 +3600,20 @@ class Session:
f"_generate_archive_summary_async called "
f"messages={len(messages)} prior_wm={len(latest_archive_overview)}B"
)
+ checkpoint_requests = list(checkpoint_requests or [])
if not messages:
+ if checkpoint_requests:
+ raise ValueError("Cannot generate checkpoints without archive messages")
return ""
- formatted = "\n".join(self._format_message_for_wm(m) for m in messages)
+ formatted = self._format_messages_for_wm(messages, checkpoint_requests)
+ checkpoint_instructions = self._checkpoint_prompt_instructions(len(checkpoint_requests))
vlm = get_openviking_config().vlm
if not (vlm and vlm.is_available()):
- turn_count = len([m for m in messages if m.role == "user"])
+ if checkpoint_requests:
+ raise ValueError("A configured VLM is required to generate checkpoint summaries")
+ turn_count = len([m for m in messages if is_user_query(m)])
return (
f"# Session Summary\n\n**Overview**: {turn_count} turns, {len(messages)} messages"
)
@@ -2226,8 +3621,10 @@ class Session:
try:
from openviking.prompts import render_prompt
except Exception as e:
+ if checkpoint_requests:
+ raise RuntimeError("Prompt module is required to generate checkpoints") from e
logger.warning(f"Prompt module unavailable: {e}")
- turn_count = len([m for m in messages if m.role == "user"])
+ turn_count = len([m for m in messages if is_user_query(m)])
return (
f"# Session Summary\n\n**Overview**: {turn_count} turns, {len(messages)} messages"
)
@@ -2249,13 +3646,47 @@ class Session:
{
"messages": formatted,
"latest_archive_overview": latest_archive_overview or "",
+ "checkpoint_instructions": checkpoint_instructions,
},
)
+ if checkpoint_requests:
+ response = await vlm.get_completion_async(
+ prompt=prompt,
+ tools=[WM_CREATE_WITH_CHECKPOINTS_TOOL],
+ tool_choice={
+ "type": "function",
+ "function": {"name": "create_working_memory"},
+ },
+ )
+ if not (
+ getattr(response, "has_tool_calls", False)
+ and getattr(response, "tool_calls", None)
+ ):
+ raise ValueError(
+ "Working Memory creation returned no create_working_memory tool call"
+ )
+ args = response.tool_calls[0].arguments
+ if isinstance(args, str):
+ args = json.loads(args)
+ if not isinstance(args, dict):
+ raise ValueError("create_working_memory arguments must be an object")
+ working_memory = args.get("working_memory")
+ if not isinstance(working_memory, str) or not working_memory.strip():
+ raise ValueError("create_working_memory.working_memory is empty")
+ return _ArchiveSummaryResult(
+ overview=working_memory,
+ checkpoint_summaries=self._parse_required_checkpoint_summaries(
+ args,
+ len(checkpoint_requests),
+ ),
+ )
return await vlm.get_completion_async(prompt)
except Exception as e:
_wm_debug(f"creation failed: {e}")
logger.warning(f"WM creation failed: {e}")
- turn_count = len([m for m in messages if m.role == "user"])
+ if checkpoint_requests:
+ raise
+ turn_count = len([m for m in messages if is_user_query(m)])
return (
f"# Session Summary\n\n"
f"**Overview**: {turn_count} turns, {len(messages)} messages"
@@ -2273,6 +3704,7 @@ class Session:
"messages": formatted,
"latest_archive_overview": latest_archive_overview,
"wm_section_reminders": reminders,
+ "checkpoint_instructions": checkpoint_instructions,
},
)
resp = await vlm.get_completion_async(
@@ -2287,6 +3719,8 @@ class Session:
import traceback as _tb
_wm_debug(f"tool_call raised: {type(e).__name__}: {e} tb={_tb.format_exc()[-400:]}")
+ if checkpoint_requests:
+ raise
logger.warning("WM update tool_call failed (%s); falling back to creation prompt", e)
return await self._fallback_generate_wm_creation(
formatted, messages, latest_archive_overview
@@ -2302,11 +3736,14 @@ class Session:
)
if not has_tc:
+ if checkpoint_requests:
+ raise ValueError("Working Memory update returned no tool call for checkpoints")
logger.warning("WM update: LLM returned no tool_call; falling back to creation prompt")
return await self._fallback_generate_wm_creation(
formatted, messages, latest_archive_overview
)
+ checkpoint_summaries: tuple[str, ...] = ()
try:
raw_args = resp.tool_calls[0].arguments
_wm_debug(f"raw_args type={type(raw_args).__name__} preview={str(raw_args)[:400]!r}")
@@ -2344,6 +3781,11 @@ class Session:
_wm_debug(f"recovered args keys={list(args.keys())}")
_wm_debug(f"args keys={list(args.keys())}")
+ if checkpoint_requests:
+ checkpoint_summaries = self._parse_required_checkpoint_summaries(
+ args,
+ len(checkpoint_requests),
+ )
# Tolerant: if LLM returned {"Session Title": {...}, ...} without
# the outer "sections" wrapper, treat the top-level as ops.
if "sections" in args and isinstance(args["sections"], dict):
@@ -2356,6 +3798,8 @@ class Session:
if not isinstance(ops, dict):
raise ValueError("ops is not a dict")
except Exception as e:
+ if checkpoint_requests:
+ raise
_wm_debug(
f"args parse failed: {type(e).__name__}: {e}; attempting regex recovery from raw"
)
@@ -2404,7 +3848,13 @@ class Session:
f"ops keys={list(ops.keys())[:7]} "
f"ops_summary={[(k, v.get('op') if isinstance(v, dict) else type(v).__name__) for k, v in ops.items()][:7]}"
)
- return self._merge_wm_sections(latest_archive_overview, ops)
+ overview = self._merge_wm_sections(latest_archive_overview, ops)
+ if checkpoint_requests:
+ return _ArchiveSummaryResult(
+ overview=overview,
+ checkpoint_summaries=checkpoint_summaries,
+ )
+ return overview
async def _fallback_generate_wm_creation(
self,
@@ -2426,12 +3876,16 @@ class Session:
prompt = render_prompt(
"compression.ov_wm_v2",
- {"messages": formatted_messages, "latest_archive_overview": prior_overview},
+ {
+ "messages": formatted_messages,
+ "latest_archive_overview": prior_overview,
+ "checkpoint_instructions": "",
+ },
)
return await get_openviking_config().vlm.get_completion_async(prompt)
except Exception as e:
logger.warning(f"WM creation fallback failed: {e}")
- turn_count = len([m for m in messages if m.role == "user"])
+ turn_count = len([m for m in messages if is_user_query(m)])
return (
f"# Session Summary\n\n**Overview**: {turn_count} turns, {len(messages)} messages"
)
@@ -3190,7 +4644,7 @@ class Session:
return
viking_fs = self._viking_fs
- turn_count = len([m for m in messages if m.role == "user"])
+ turn_count = len([m for m in messages if is_user_query(m)])
abstract = self._generate_abstract()
overview = self._generate_overview(turn_count)
@@ -3214,19 +4668,6 @@ class Session:
ctx=self.ctx,
)
- def _append_messages_to_jsonl_batch(self, messages: List[Message]) -> None:
- """Append multiple messages to messages.jsonl in a single write."""
- if not self._viking_fs:
- return
- batch_content = "".join(msg.to_jsonl() + "\n" for msg in messages)
- run_async(
- self._viking_fs.append_file(
- f"{self._session_uri}/messages.jsonl",
- batch_content,
- ctx=self.ctx,
- )
- )
-
def _generate_abstract(self) -> str:
"""Generate one-sentence summary for session."""
if not self._messages:
diff --git a/openviking/sync_client.py b/openviking/sync_client.py
index d686865e4..7c36ad3bf 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -102,6 +102,9 @@ class SyncOpenViking:
created_at: str | None = None,
peer_id: str | None = None,
telemetry: TelemetryRequest = False,
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
) -> Dict[str, Any]:
"""Add a message to a session.
@@ -115,6 +118,15 @@ class SyncOpenViking:
If both content and parts are provided, parts takes precedence.
"""
+ semantic_kwargs = {
+ key: value
+ for key, value in {
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }.items()
+ if value is not None
+ }
return run_async(
self._async_client.add_message(
session_id=session_id,
@@ -124,6 +136,7 @@ class SyncOpenViking:
created_at=created_at,
peer_id=peer_id,
telemetry=telemetry,
+ **semantic_kwargs,
)
)
@@ -148,13 +161,28 @@ class SyncOpenViking:
telemetry: TelemetryRequest = False,
*,
keep_recent_count: int = 0,
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
) -> Dict[str, Any]:
"""Commit a session (archive and extract memories)."""
+ optional_retention = {
+ key: value
+ for key, value in {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }.items()
+ if value is not None
+ }
return run_async(
self._async_client.commit_session(
session_id,
telemetry=telemetry,
keep_recent_count=keep_recent_count,
+ **optional_retention,
)
)
diff --git a/openviking/usage_reporter/models.py b/openviking/usage_reporter/models.py
index c82105740..390dd9050 100644
--- a/openviking/usage_reporter/models.py
+++ b/openviking/usage_reporter/models.py
@@ -48,8 +48,7 @@ class UsageEvent:
self.account_id,
self.user_id,
self.session_id,
- self.task_id or "",
- str(self.evidence.get("archive_uri") or ""),
+ str(self.evidence.get("message_id") or ""),
str(self.evidence.get("tool_call_id") or ""),
self.resource_uri,
]
diff --git a/openviking_cli/client/_http_compat.py b/openviking_cli/client/_http_compat.py
index a523f0269..1190b60a2 100644
--- a/openviking_cli/client/_http_compat.py
+++ b/openviking_cli/client/_http_compat.py
@@ -34,6 +34,7 @@ from openviking_cli.exceptions import (
UnimplementedError,
VLMFailedError,
)
+from openviking_cli.utils.async_utils import run_async
ERROR_CODE_TO_EXCEPTION = {
"INVALID_ARGUMENT": InvalidArgumentError,
@@ -165,8 +166,126 @@ class AsyncHTTPClient(import_openviking_sdk().AsyncHTTPClient):
def _raise_exception(self, error: Dict[str, Any]) -> None:
_raise_legacy_exception(error)
+ async def add_message(
+ self,
+ session_id: str,
+ role: str,
+ content: str | None = None,
+ parts: list[dict] | None = None,
+ created_at: str | None = None,
+ peer_id: str | None = None,
+ telemetry: Any = False,
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
+ ) -> Dict[str, Any]:
+ payload: Dict[str, Any] = {"role": role}
+ if parts is not None:
+ payload["parts"] = parts
+ elif content is not None:
+ payload["content"] = content
+ else:
+ raise ValueError("Either content or parts must be provided")
+ optional = {
+ "created_at": created_at,
+ "peer_id": peer_id,
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }
+ payload.update({key: value for key, value in optional.items() if value is not None})
+ if telemetry is not False:
+ payload["telemetry"] = telemetry
+ session_path = self._path_segment(session_id)
+ response = await self._request(
+ "POST", f"/api/v1/sessions/{session_path}/messages", json=payload
+ )
+ return self._handle_response_data(response).get("result", {})
+
+ async def commit_session(
+ self,
+ session_id: str,
+ telemetry: Any = False,
+ *,
+ keep_recent_count: int = 0,
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
+ ) -> Dict[str, Any]:
+ """Commit with optional Turn-aware retention fields understood by the server."""
+ payload: Dict[str, Any] = {
+ "keep_recent_count": keep_recent_count,
+ "telemetry": telemetry,
+ }
+ optional = {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }
+ payload.update({key: value for key, value in optional.items() if value is not None})
+ session_path = self._path_segment(session_id)
+ response = await self._request(
+ "POST",
+ f"/api/v1/sessions/{session_path}/commit",
+ json=payload,
+ )
+ return self._handle_response_data(response).get("result", {})
+
class SyncHTTPClient(import_openviking_sdk().SyncHTTPClient):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._async_client = AsyncHTTPClient(*args, **kwargs)
+
+ def add_message(
+ self,
+ session_id: str,
+ role: str,
+ content: str | None = None,
+ parts: list[dict] | None = None,
+ created_at: str | None = None,
+ peer_id: str | None = None,
+ telemetry: Any = False,
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.add_message(
+ session_id,
+ role,
+ content=content,
+ parts=parts,
+ created_at=created_at,
+ peer_id=peer_id,
+ telemetry=telemetry,
+ turn_id=turn_id,
+ message_kind=message_kind,
+ source_message_ids=source_message_ids,
+ )
+ )
+
+ def commit_session(
+ self,
+ session_id: str,
+ telemetry: Any = False,
+ *,
+ keep_recent_count: int = 0,
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
+ ) -> Dict[str, Any]:
+ return run_async(
+ self._async_client.commit_session(
+ session_id,
+ telemetry=telemetry,
+ keep_recent_count=keep_recent_count,
+ retention_mode=retention_mode,
+ keep_recent_turn_count=keep_recent_turn_count,
+ retained_message_token_budget=retained_message_token_budget,
+ min_raw_tail_steps=min_raw_tail_steps,
+ )
+ )
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index 9db81a80c..f7f3efd1e 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -374,6 +374,10 @@ class BaseClient(ABC):
telemetry: TelemetryRequest = False,
*,
keep_recent_count: int = 0,
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
) -> Dict[str, Any]:
"""Commit a session (archive and extract memories).
@@ -394,6 +398,9 @@ class BaseClient(ABC):
created_at: str | None = None,
peer_id: str | None = None,
telemetry: TelemetryRequest = False,
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
) -> Dict[str, Any]:
"""Add a message to a session.
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index 87ae76dcc..5168e9643 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -138,7 +138,19 @@ class Session:
parts: list[dict] | None = None,
created_at: str | None = None,
peer_id: str | None = None,
- ) -> Dict[str, Any]:
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
+ ) -> Dict[str, Any]:
+ semantic_kwargs = {
+ key: value
+ for key, value in {
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }.items()
+ if value is not None
+ }
return await self._client.add_message(
self.session_id,
role=role,
@@ -146,14 +158,35 @@ class Session:
parts=parts,
created_at=created_at,
peer_id=peer_id,
+ **semantic_kwargs,
)
async def batch_add_messages(self, messages: list[dict]) -> Dict[str, Any]:
return await self._client.batch_add_messages(self.session_id, messages)
- async def commit(self, keep_recent_count: int = 0) -> Dict[str, Any]:
+ async def commit(
+ self,
+ keep_recent_count: int = 0,
+ *,
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
+ ) -> Dict[str, Any]:
+ optional_retention = {
+ key: value
+ for key, value in {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }.items()
+ if value is not None
+ }
return await self._client.commit_session(
- self.session_id, keep_recent_count=keep_recent_count
+ self.session_id,
+ keep_recent_count=keep_recent_count,
+ **optional_retention,
)
async def delete(self) -> None:
@@ -181,7 +214,19 @@ class SyncSession:
parts: list[dict] | None = None,
created_at: str | None = None,
peer_id: str | None = None,
- ) -> Dict[str, Any]:
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
+ ) -> Dict[str, Any]:
+ semantic_kwargs = {
+ key: value
+ for key, value in {
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }.items()
+ if value is not None
+ }
return self._client.add_message(
self.session_id,
role=role,
@@ -189,6 +234,7 @@ class SyncSession:
parts=parts,
created_at=created_at,
peer_id=peer_id,
+ **semantic_kwargs,
)
def batch_add_messages(self, messages: list[dict]) -> Dict[str, Any]:
@@ -199,11 +245,26 @@ class SyncSession:
telemetry: Any = False,
*,
keep_recent_count: int = 0,
- ) -> Dict[str, Any]:
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
+ ) -> Dict[str, Any]:
+ optional_retention = {
+ key: value
+ for key, value in {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }.items()
+ if value is not None
+ }
return self._client.commit_session(
self.session_id,
telemetry=telemetry,
keep_recent_count=keep_recent_count,
+ **optional_retention,
)
def commit_async(
@@ -211,8 +272,26 @@ class SyncSession:
telemetry: Any = False,
*,
keep_recent_count: int = 0,
- ) -> Dict[str, Any]:
- return self.commit(telemetry=telemetry, keep_recent_count=keep_recent_count)
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
+ ) -> Dict[str, Any]:
+ optional_retention = {
+ key: value
+ for key, value in {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }.items()
+ if value is not None
+ }
+ return self.commit(
+ telemetry=telemetry,
+ keep_recent_count=keep_recent_count,
+ **optional_retention,
+ )
def delete(self) -> None:
self._client.delete_session(self.session_id)
@@ -1244,12 +1323,27 @@ class AsyncHTTPClient:
telemetry: Any = False,
*,
keep_recent_count: int = 0,
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
) -> Dict[str, Any]:
+ payload: Dict[str, Any] = {
+ "keep_recent_count": keep_recent_count,
+ "telemetry": telemetry,
+ }
+ optional = {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }
+ payload.update({key: value for key, value in optional.items() if value is not None})
session_path = self._path_segment(session_id)
response = await self._request(
"POST",
f"/api/v1/sessions/{session_path}/commit",
- json={"keep_recent_count": keep_recent_count, "telemetry": telemetry},
+ json=payload,
)
return self._handle_response_data(response).get("result", {})
@@ -1262,6 +1356,9 @@ class AsyncHTTPClient:
created_at: str | None = None,
peer_id: str | None = None,
telemetry: Any = False,
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
) -> Dict[str, Any]:
payload: Dict[str, Any] = {"role": role}
if parts is not None:
@@ -1270,10 +1367,14 @@ class AsyncHTTPClient:
payload["content"] = content
else:
raise ValueError("Either content or parts must be provided")
- if created_at is not None:
- payload["created_at"] = created_at
- if peer_id is not None:
- payload["peer_id"] = peer_id
+ optional = {
+ "created_at": created_at,
+ "peer_id": peer_id,
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }
+ payload.update({key: value for key, value in optional.items() if value is not None})
if telemetry is not False:
payload["telemetry"] = telemetry
session_path = self._path_segment(session_id)
@@ -2147,19 +2248,36 @@ class SyncHTTPClient:
telemetry: Any = False,
*,
keep_recent_count: int = 0,
- ) -> Dict[str, Any]:
+ retention_mode: str | None = None,
+ keep_recent_turn_count: int | None = None,
+ retained_message_token_budget: int | None = None,
+ min_raw_tail_steps: int | None = None,
+ ) -> Dict[str, Any]:
+ kwargs = {"keep_recent_count": keep_recent_count}
+ kwargs.update(
+ {
+ key: value
+ for key, value in {
+ "retention_mode": retention_mode,
+ "keep_recent_turn_count": keep_recent_turn_count,
+ "retained_message_token_budget": retained_message_token_budget,
+ "min_raw_tail_steps": min_raw_tail_steps,
+ }.items()
+ if value is not None
+ }
+ )
if telemetry is False:
return run_async(
self._async_client.commit_session(
session_id,
- keep_recent_count=keep_recent_count,
+ **kwargs,
)
)
return run_async(
self._async_client.commit_session(
session_id,
telemetry=telemetry,
- keep_recent_count=keep_recent_count,
+ **kwargs,
)
)
@@ -2172,6 +2290,9 @@ class SyncHTTPClient:
created_at: str | None = None,
peer_id: str | None = None,
telemetry: Any = False,
+ turn_id: str | None = None,
+ message_kind: str | None = None,
+ source_message_ids: list[str] | None = None,
) -> Dict[str, Any]:
kwargs = {
"role": role,
@@ -2180,6 +2301,17 @@ class SyncHTTPClient:
"created_at": created_at,
"peer_id": peer_id,
}
+ kwargs.update(
+ {
+ key: value
+ for key, value in {
+ "turn_id": turn_id,
+ "message_kind": message_kind,
+ "source_message_ids": source_message_ids,
+ }.items()
+ if value is not None
+ }
+ )
if telemetry is not False:
kwargs["telemetry"] = telemetry
return run_async(
diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.py
index 514e61a7e..89f840d22 100644
--- a/sdk/python/tests/test_async_client_behaviors.py
+++ b/sdk/python/tests/test_async_client_behaviors.py
@@ -88,6 +88,46 @@ async def test_async_http_client_batch_add_messages_url_encodes_session_id():
)
+async def test_async_http_client_sends_message_semantics_and_turn_retention():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
+ client._http = fake_http
+ client._handle_response_data = lambda _response: {"result": {"status": "ok"}}
+
+ await client.add_message(
+ "demo-session",
+ "assistant",
+ parts=[{"type": "text", "text": "checking"}],
+ turn_id="turn-1",
+ message_kind="assistant_step",
+ source_message_ids=["u1"],
+ )
+ await client.commit_session(
+ "demo-session",
+ retention_mode="turn_budget",
+ keep_recent_turn_count=3,
+ retained_message_token_budget=12_000,
+ min_raw_tail_steps=1,
+ )
+
+ assert fake_http.post.await_args_list[0].kwargs["json"] == {
+ "role": "assistant",
+ "parts": [{"type": "text", "text": "checking"}],
+ "turn_id": "turn-1",
+ "message_kind": "assistant_step",
+ "source_message_ids": ["u1"],
+ }
+ assert fake_http.post.await_args_list[1].kwargs["json"] == {
+ "keep_recent_count": 0,
+ "telemetry": False,
+ "retention_mode": "turn_budget",
+ "keep_recent_turn_count": 3,
+ "retained_message_token_budget": 12_000,
+ "min_raw_tail_steps": 1,
+ }
+
+
@pytest.mark.asyncio
async def test_async_http_client_reindex_posts_content_reindex():
client = AsyncHTTPClient(url="http://localhost:1933")
@@ -764,16 +804,12 @@ async def test_export_and_backup_ovpack_append_default_suffixes(tmp_path):
async def test_backup_ovpack_preserves_existing_file_when_replace_fails(tmp_path):
client = AsyncHTTPClient(url="http://localhost:1933")
client._http = SimpleNamespace(
- post=AsyncMock(
- return_value=SimpleNamespace(is_success=True, content=b"new-backup")
- )
+ post=AsyncMock(return_value=SimpleNamespace(is_success=True, content=b"new-backup"))
)
output = tmp_path / "backup.ovpack"
output.write_bytes(b"known-good-backup")
- with patch(
- "openviking_sdk.client.os.replace", side_effect=OSError("replace failed")
- ):
+ with patch("openviking_sdk.client.os.replace", side_effect=OSError("replace failed")):
with pytest.raises(OSError, match="replace failed"):
await client.backup_ovpack(str(output))
diff --git a/tests/client/test_rebuild_clients.py b/tests/client/test_rebuild_clients.py
index 55f41351d..cc803b6c6 100644
--- a/tests/client/test_rebuild_clients.py
+++ b/tests/client/test_rebuild_clients.py
@@ -101,6 +101,60 @@ async def test_async_openviking_reindex_forwards_to_local_client(tmp_path):
)
+async def test_async_openviking_forwards_turn_retention_and_message_semantics(tmp_path):
+ client = AsyncOpenViking(path=str(tmp_path))
+ with patch.object(client, "_ensure_initialized", new_callable=AsyncMock):
+ with patch.object(
+ client._client,
+ "add_message",
+ new_callable=AsyncMock,
+ return_value={"message_count": 1},
+ ) as mock_add:
+ with patch.object(
+ client._client,
+ "commit_session",
+ new_callable=AsyncMock,
+ return_value={"status": "accepted"},
+ ) as mock_commit:
+ await client.add_message(
+ "session-1",
+ "assistant",
+ parts=[{"type": "text", "text": "checking"}],
+ turn_id="turn-1",
+ message_kind="assistant_step",
+ source_message_ids=["u1"],
+ )
+ await client.commit_session(
+ "session-1",
+ retention_mode="turn_budget",
+ keep_recent_turn_count=3,
+ retained_message_token_budget=12_000,
+ min_raw_tail_steps=1,
+ )
+
+ mock_add.assert_awaited_once_with(
+ session_id="session-1",
+ role="assistant",
+ content=None,
+ parts=[{"type": "text", "text": "checking"}],
+ created_at=None,
+ peer_id=None,
+ telemetry=False,
+ turn_id="turn-1",
+ message_kind="assistant_step",
+ source_message_ids=["u1"],
+ )
+ mock_commit.assert_awaited_once_with(
+ "session-1",
+ telemetry=False,
+ keep_recent_count=0,
+ retention_mode="turn_budget",
+ keep_recent_turn_count=3,
+ retained_message_token_budget=12_000,
+ min_raw_tail_steps=1,
+ )
+
+
def test_sync_openviking_reindex_forwards_to_async_client():
client = SyncOpenViking()
with patch.object(
diff --git a/tests/server/conftest.py b/tests/server/conftest.py
index d1672587a..0904c3638 100644
--- a/tests/server/conftest.py
+++ b/tests/server/conftest.py
@@ -3,6 +3,7 @@
"""Shared fixtures for OpenViking server tests."""
+import asyncio
import shutil
import socket
import threading
@@ -22,6 +23,7 @@ from openviking.server.app import create_app
from openviking.server.config import ServerConfig
from openviking.server.identity import RequestContext, Role
from openviking.service.core import OpenVikingService
+from openviking.storage.queuefs import QueueManager, SessionCommitMsg, get_queue_manager
from openviking.storage.transaction import reset_lock_manager
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils.config.embedding_config import EmbeddingConfig
@@ -85,6 +87,37 @@ def _install_fake_vlm(monkeypatch):
monkeypatch.setattr(VLMConfig, "get_vision_completion_async", _fake_get_vision_completion)
+def _install_session_commit_queue_fallback(service: OpenVikingService, monkeypatch) -> None:
+ """Execute SessionCommit jobs when MockLocalAGFS cannot dequeue QueueFS entries."""
+ queue_manager = get_queue_manager()
+ original_enqueue = queue_manager.enqueue
+
+ async def enqueue_with_session_commit_fallback(queue_name, data):
+ if queue_name != QueueManager.SESSION_COMMIT:
+ return await original_enqueue(queue_name, data)
+
+ async def process_commit() -> None:
+ await asyncio.sleep(0)
+ msg = SessionCommitMsg(**data)
+ ctx = RequestContext(
+ user=UserIdentifier.from_dict(msg.user),
+ role=Role.USER,
+ actor_peer_id=msg.actor_peer_id,
+ )
+ queued_session = service.sessions.session(
+ ctx,
+ msg.session_id,
+ session_uri=msg.session_uri,
+ )
+ await queued_session.load()
+ await queued_session.resume_queued_commit(msg)
+
+ asyncio.create_task(process_commit())
+ return data["task_id"]
+
+ monkeypatch.setattr(queue_manager, "enqueue", enqueue_with_session_commit_fallback)
+
+
# ---------------------------------------------------------------------------
# Core fixtures: service + app + async client (HTTP API tests, in-process)
# ---------------------------------------------------------------------------
@@ -143,6 +176,7 @@ async def service(temp_dir: Path, monkeypatch):
)
await svc.initialize()
svc.viking_fs.query_embedder = fake_embedder_cls()
+ _install_session_commit_queue_fallback(svc, monkeypatch)
yield svc
await svc.close()
reset_lock_manager()
@@ -214,6 +248,7 @@ async def running_server(temp_dir: Path, monkeypatch):
)
await svc.initialize()
svc.viking_fs.query_embedder = fake_embedder_cls()
+ _install_session_commit_queue_fallback(svc, monkeypatch)
config = ServerConfig(root_api_key=SDK_ROOT_API_KEY)
fastapi_app = create_app(config=config, service=svc)
diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.py
index 8fe4ecba0..51d7d8c9d 100644
--- a/tests/server/test_api_sessions.py
+++ b/tests/server/test_api_sessions.py
@@ -272,6 +272,8 @@ async def test_tool_result_externalization_read_and_search(client: httpx.AsyncCl
async def test_tool_result_externalization_respects_server_config_disabled(service):
+ from openviking.server.auth.plugins import DevAuthPlugin
+
app = create_app(
config=ServerConfig(
tool_output_externalization=ToolOutputExternalizationConfig(enabled=False)
@@ -279,6 +281,9 @@ async def test_tool_result_externalization_respects_server_config_disabled(servi
service=service,
)
set_service(service)
+ # ASGITransport does not run the application lifespan that normally
+ # initializes the configured auth plugin.
+ app.state.auth_plugin = DevAuthPlugin()
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
@@ -355,13 +360,14 @@ async def test_get_session_context_includes_incomplete_archive_messages(
assert resp.status_code == 200
body = resp.json()
assert [m["parts"][0]["text"] for m in body["result"]["messages"]] == [
+ "Archived seed",
"Pending user message",
"Pending assistant response",
"Current live message",
]
-async def test_get_session_context_skips_failed_archive_messages(
+async def test_get_session_context_restores_failed_archive_messages(
client: httpx.AsyncClient, service
):
create_resp = await client.post("/api/v1/sessions", json={})
@@ -406,6 +412,8 @@ async def test_get_session_context_skips_failed_archive_messages(
assert resp.status_code == 200
body = resp.json()
assert [m["parts"][0]["text"] for m in body["result"]["messages"]] == [
+ "Archived seed",
+ "Failed archive message",
"Current live message",
]
@@ -903,17 +911,26 @@ async def test_get_session_context_endpoint_returns_trimmed_latest_archive_and_m
result = body["result"]
assert result["latest_archive_overview"] == ""
assert result["pre_archive_abstracts"] == []
- assert len(result["messages"]) == 1
- assert result["messages"][0]["role"] == "assistant"
- assert any(
- part["type"] == "tool" and part["tool_id"] == "tool_123"
- for part in result["messages"][0]["parts"]
- )
+ assert result["messages"] == []
+ assert result["estimatedTokens"] <= 1
+ assert result["stats"]["activeTokens"] <= 1
assert result["stats"]["totalArchives"] == 1
assert result["stats"]["includedArchives"] == 0
assert result["stats"]["droppedArchives"] == 1
assert result["stats"]["failedArchives"] == 0
+ # Budget fitting is a virtual view and must not mutate the durable live row.
+ full_resp = await client.get(
+ f"/api/v1/sessions/{session_id}/context?token_budget=128000"
+ )
+ full_result = full_resp.json()["result"]
+ assert len(full_result["messages"]) == 1
+ assert full_result["messages"][0]["role"] == "assistant"
+ assert any(
+ part["type"] == "tool" and part["tool_id"] == "tool_123"
+ for part in full_result["messages"][0]["parts"]
+ )
+
async def test_get_session_archive_endpoint_returns_archive_details(
client: httpx.AsyncClient,
diff --git a/tests/server/test_http_client_sdk.py b/tests/server/test_http_client_sdk.py
index facb0e799..4665abb4a 100644
--- a/tests/server/test_http_client_sdk.py
+++ b/tests/server/test_http_client_sdk.py
@@ -289,6 +289,44 @@ async def test_sdk_commit_session_keeps_telemetry_as_second_positional_argument(
]
+async def test_sdk_commit_session_sends_turn_budget_retention_fields():
+ calls = []
+
+ class _FakeHTTP:
+ async def post(self, path, json):
+ calls.append((path, json))
+ return httpx.Response(
+ 200,
+ json={"status": "success", "result": {"task_id": "task-turn"}},
+ )
+
+ client = AsyncHTTPClient(url="http://127.0.0.1:1933")
+ client._http = _FakeHTTP()
+
+ result = await client.commit_session(
+ "s1",
+ retention_mode="turn_budget",
+ keep_recent_turn_count=3,
+ retained_message_token_budget=12_000,
+ min_raw_tail_steps=1,
+ )
+
+ assert result == {"task_id": "task-turn"}
+ assert calls == [
+ (
+ "/api/v1/sessions/s1/commit",
+ {
+ "keep_recent_count": 0,
+ "telemetry": False,
+ "retention_mode": "turn_budget",
+ "keep_recent_turn_count": 3,
+ "retained_message_token_budget": 12_000,
+ "min_raw_tail_steps": 1,
+ },
+ )
+ ]
+
+
async def test_sdk_get_session_archive(http_client):
client, svc = http_client
diff --git a/tests/server/test_mcp_endpoint.py b/tests/server/test_mcp_endpoint.py
index 988e1b1fa..94a91a8f5 100644
--- a/tests/server/test_mcp_endpoint.py
+++ b/tests/server/test_mcp_endpoint.py
@@ -455,13 +455,13 @@ async def test_store_does_not_autofill_peer_id_from_ctx(service, monkeypatch):
from openviking.session.session import Session
captured: list[tuple[str, str | None]] = []
- original = Session.add_message
+ original = Session.add_message_async
- def _spy(self, role, parts, peer_id=None, created_at=None):
+ async def _spy(self, role, parts, peer_id=None, created_at=None):
captured.append((role, peer_id))
- return original(self, role, parts, peer_id=peer_id, created_at=created_at)
+ return await original(self, role, parts, peer_id=peer_id, created_at=created_at)
- monkeypatch.setattr(Session, "add_message", _spy)
+ monkeypatch.setattr(Session, "add_message_async", _spy)
await remember(
messages=[
diff --git a/tests/session/test_retention.py b/tests/session/test_retention.py
new file mode 100644
index 000000000..5d09e10cf
--- /dev/null
+++ b/tests/session/test_retention.py
@@ -0,0 +1,271 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import pytest
+
+from openviking.message import Message, TextPart, ToolPart
+from openviking.server.routers.sessions import CommitRequest
+from openviking.session.retention import (
+ build_turns,
+ fit_active_messages_to_budget,
+ plan_retention,
+)
+
+
+def _message(message_id: str, role: str, text: str) -> Message:
+ return Message(id=message_id, role=role, parts=[TextPart(text)])
+
+
+def test_build_turns_does_not_treat_tool_transport_as_user_query():
+ messages = [
+ _message("u1", "user", "find the issue"),
+ Message(
+ id="a1",
+ role="assistant",
+ parts=[TextPart("I will inspect it"), ToolPart(tool_id="t1", tool_name="read")],
+ ),
+ Message(
+ id="tr1",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="t1",
+ tool_name="read",
+ tool_output="result",
+ tool_status="completed",
+ )
+ ],
+ ),
+ _message("a2", "assistant", "done"),
+ ]
+
+ turns = build_turns(messages)
+
+ assert len(turns) == 1
+ assert turns[0].anchor.id == "u1"
+ assert [[message.id for message in step.messages] for step in turns[0].steps] == [
+ ["a1", "tr1"],
+ ["a2"],
+ ]
+
+
+def test_explicit_assistant_role_tool_transport_stays_with_previous_step():
+ messages = [
+ _message("u1", "user", "find the issue"),
+ Message(
+ id="a1",
+ role="assistant",
+ parts=[TextPart("I will inspect it"), ToolPart(tool_id="t1", tool_name="read")],
+ ),
+ Message(
+ id="tr1",
+ role="assistant",
+ message_kind="tool_transport",
+ parts=[
+ ToolPart(
+ tool_id="t1",
+ tool_name="read",
+ tool_output="result",
+ tool_status="completed",
+ )
+ ],
+ ),
+ ]
+
+ turns = build_turns(messages)
+
+ assert [[message.id for message in step.messages] for step in turns[0].steps] == [
+ ["a1", "tr1"]
+ ]
+
+
+def test_message_semantic_fields_round_trip_without_affecting_legacy_rows():
+ message = Message(
+ id="checkpoint-1",
+ role="assistant",
+ parts=[TextPart("state")],
+ turn_id="turn-1",
+ message_kind="checkpoint",
+ source_message_ids=["a1", "a2"],
+ )
+
+ restored = Message.from_dict(message.to_dict())
+ legacy = Message.from_dict({"id": "legacy", "role": "user", "content": "hello"})
+
+ assert restored.turn_id == "turn-1"
+ assert restored.message_kind == "checkpoint"
+ assert restored.source_message_ids == ["a1", "a2"]
+ assert legacy.message_kind is None
+
+
+def test_one_user_and_ten_assistant_steps_retains_the_user_anchor():
+ messages = [_message("u1", "user", "investigate")]
+ messages.extend(_message(f"a{i}", "assistant", f"step {i}") for i in range(10))
+
+ plan = plan_retention(
+ messages,
+ keep_recent_turn_count=1,
+ token_budget=12_000,
+ )
+
+ assert plan.archive_messages == []
+ assert [message.id for message in plan.retained_messages] == [
+ "u1",
+ *(f"a{i}" for i in range(10)),
+ ]
+
+
+def test_oversized_latest_turn_keeps_anchor_and_atomic_raw_tail():
+ messages = [_message("u1", "user", "investigate")]
+ for index in range(6):
+ messages.append(_message(f"a{index}", "assistant", str(index) * 1000))
+ messages.append(
+ Message(
+ id=f"tr{index}",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id=f"t{index}",
+ tool_name="read",
+ tool_output=f"result-{index}",
+ tool_status="completed",
+ )
+ ],
+ )
+ )
+
+ plan = plan_retention(
+ messages,
+ keep_recent_turn_count=1,
+ token_budget=700,
+ min_raw_tail_steps=1,
+ )
+
+ retained_ids = [message.id for message in plan.retained_messages]
+ archived_ids = [message.id for message in plan.archive_messages]
+ assert plan.partial_turn is True
+ assert retained_ids[0] == "u1"
+ assert retained_ids[-2:] == ["a5", "tr5"]
+ assert archived_ids[0] == "u1" # duplicate anchor makes Phase 2 self-contained
+ assert ("a4" in archived_ids) == ("tr4" in archived_ids)
+ assert ("a4" in retained_ids) == ("tr4" in retained_ids)
+ assert plan.checkpoint_source_message_ids == archived_ids[1:]
+
+
+def test_oversized_legacy_assistant_only_turn_archives_without_checkpoint():
+ messages = [
+ _message("a1", "assistant", "A" * 1000),
+ _message("a2", "assistant", "B" * 1000),
+ _message("a3", "assistant", "C" * 1000),
+ ]
+
+ plan = plan_retention(
+ messages,
+ keep_recent_turn_count=1,
+ token_budget=150,
+ min_raw_tail_steps=1,
+ )
+
+ assert [message.id for message in plan.archive_messages] == ["a1", "a2", "a3"]
+ assert plan.retained_messages == []
+ assert plan.turn_anchor is None
+ assert plan.checkpoint_source_message_ids == []
+ assert plan.partial_turn is False
+ assert plan.budget_exceeded is False
+
+
+def test_complete_old_turns_are_archived_before_splitting_latest_turn():
+ messages = [
+ _message("u1", "user", "first"),
+ _message("a1", "assistant", "answer one"),
+ _message("u2", "user", "second"),
+ _message("a2", "assistant", "answer two"),
+ _message("u3", "user", "third"),
+ _message("a3", "assistant", "answer three"),
+ ]
+
+ plan = plan_retention(
+ messages,
+ keep_recent_turn_count=2,
+ token_budget=20,
+ )
+
+ assert [message.id for message in plan.archive_messages] == ["u1", "a1"]
+ assert [message.id for message in plan.retained_messages] == ["u2", "a2", "u3", "a3"]
+
+
+def test_turn_retention_fields_require_explicit_mode_opt_in():
+ with pytest.raises(ValueError, match="retention_mode='turn_budget'"):
+ CommitRequest(keep_recent_turn_count=3)
+
+ request = CommitRequest(
+ retention_mode="turn_budget",
+ keep_recent_turn_count=3,
+ )
+ assert request.retention_mode == "turn_budget"
+
+
+def test_active_budget_keeps_latest_anchor_and_final_without_mutating_raw():
+ user_text = "latest query"
+ final_text = "F" * 1200
+ messages = [
+ _message("u1", "user", user_text),
+ _message("a1", "assistant", "intermediate" * 200),
+ _message("a2", "assistant", final_text),
+ ]
+
+ plan = fit_active_messages_to_budget(messages, token_budget=120)
+
+ assert [message.id for message in plan.messages] == ["u1", "a2"]
+ assert plan.estimated_tokens <= 120
+ assert plan.truncated_message_ids == ["a2"]
+ assert messages[0].content == user_text
+ assert messages[-1].content == final_text
+
+
+def test_active_budget_reserves_space_for_long_anchor_and_final():
+ messages = [
+ _message("u1", "user", "U" * 100),
+ _message("a1", "assistant", "done"),
+ ]
+
+ plan = fit_active_messages_to_budget(messages, token_budget=5)
+
+ assert [message.id for message in plan.messages] == ["u1", "a1"]
+ assert plan.messages[0].content
+ assert plan.messages[1].content == "done"
+ assert plan.estimated_tokens <= 5
+ assert plan.dropped_message_ids == []
+ assert plan.truncated_message_ids == ["u1"]
+
+
+def test_active_budget_never_splits_an_assistant_tool_step():
+ assistant = Message(
+ id="a1",
+ role="assistant",
+ parts=[TextPart("inspect"), ToolPart(tool_id="t1", tool_name="read")],
+ )
+ transport = Message(
+ id="tr1",
+ role="user",
+ parts=[
+ ToolPart(
+ tool_id="t1",
+ tool_name="read",
+ tool_output="result" * 1000,
+ tool_status="completed",
+ )
+ ],
+ )
+ messages = [
+ _message("u1", "user", "query"),
+ assistant,
+ transport,
+ _message("a2", "assistant", "final"),
+ ]
+
+ plan = fit_active_messages_to_budget(messages, token_budget=40)
+ returned_ids = {message.id for message in plan.messages}
+
+ assert plan.estimated_tokens <= 40
+ assert ("a1" in returned_ids) == ("tr1" in returned_ids)
diff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.py
index 97e8703f5..42a64d936 100644
--- a/tests/session/test_session_commit.py
+++ b/tests/session/test_session_commit.py
@@ -229,6 +229,9 @@ class TestCommit:
archive_uri = task_result["result"]["archive_uri"]
assert not await _marker_exists(session_with_messages, archive_uri, ".overview.md")
assert not await _marker_exists(session_with_messages, archive_uri, ".abstract.md")
+ context = await session_with_messages.get_session_context()
+ assert context["latest_archive_overview"] == ""
+ assert context["messages"] == []
session_with_messages._session_compressor.extract_long_term_memories.assert_awaited_once()
async def test_commit_routes_peer_memory_with_single_full_context_pass(
@@ -499,19 +502,22 @@ class TestCommit:
)
seen: dict[str, str] = {}
- original_generate = session._generate_archive_summary_async
+ session_type = type(session)
+ original_generate = session_type._generate_archive_summary_async
- async def capture_generate(messages, latest_archive_overview=""):
+ async def capture_generate(self, messages, latest_archive_overview=""):
seen["summary"] = latest_archive_overview
return await original_generate(
- messages, latest_archive_overview=latest_archive_overview
+ self,
+ messages,
+ latest_archive_overview=latest_archive_overview,
)
async def capture_extract(*args, **kwargs):
seen["extract"] = kwargs.get("latest_archive_overview", "")
return []
- session._generate_archive_summary_async = capture_generate
+ monkeypatch.setattr(session_type, "_generate_archive_summary_async", capture_generate)
session._session_compressor.extract_long_term_memories = capture_extract
session.add_message("user", [TextPart("Second round message")])
diff --git a/tests/session/test_session_commit_race.py b/tests/session/test_session_commit_race.py
index ede9754a4..25e2ab44f 100644
--- a/tests/session/test_session_commit_race.py
+++ b/tests/session/test_session_commit_race.py
@@ -32,26 +32,32 @@ class TestCommitRace:
# Compression index should have incremented exactly once
assert session._compression.compression_index == 1
- async def test_message_added_during_commit_not_lost(self, client: AsyncOpenViking):
+ async def test_message_added_during_commit_not_lost(
+ self,
+ client: AsyncOpenViking,
+ monkeypatch,
+ ):
"""Messages added while commit is running should not be lost."""
session = client.session(session_id="race_test_msg_safety")
session.add_message("user", [TextPart("Original message")])
# Use an Event for deterministic synchronization instead of sleeps
phase1_done = asyncio.Event()
- original_generate = session._generate_archive_summary_async
+ session_type = type(session)
+ original_generate = session_type._generate_archive_summary_async
- async def slow_generate(messages, latest_archive_overview=""):
+ async def slow_generate(self, messages, latest_archive_overview=""):
# Signal that Phase 1 is complete (lock released, messages cleared)
phase1_done.set()
# Yield control so add_message can run before archive completes
await asyncio.sleep(0)
return await original_generate(
+ self,
messages,
latest_archive_overview=latest_archive_overview,
)
- session._generate_archive_summary_async = slow_generate
+ monkeypatch.setattr(session_type, "_generate_archive_summary_async", slow_generate)
async def commit_and_add():
"""Start commit, then add a message after Phase 1 completes."""
diff --git a/tests/session/test_session_context.py b/tests/session/test_session_context.py
index 043d81e29..dbcca26e6 100644
--- a/tests/session/test_session_context.py
+++ b/tests/session/test_session_context.py
@@ -15,6 +15,7 @@ from openviking.message import Message, TextPart
from openviking.models.embedder.base import DenseEmbedderBase, EmbedResult
from openviking.service.task_tracker import get_task_tracker
from openviking.session import Session
+from openviking.storage.queuefs import QueueManager, SessionCommitMsg, get_queue_manager
from openviking_cli.utils.config import OPENVIKING_CONFIG_ENV
from openviking_cli.utils.config.embedding_config import EmbeddingConfig
from openviking_cli.utils.config.open_viking_config import OpenVikingConfigSingleton
@@ -67,6 +68,7 @@ def _write_test_config(tmp_path):
}
},
"encryption": {"enabled": False},
+ "memory": {"extraction_enabled": False},
}
),
encoding="utf-8",
@@ -88,6 +90,28 @@ async def client(test_data_dir, monkeypatch, tmp_path):
with patch("openviking.utils.agfs_utils.create_agfs_client", return_value=mock_agfs):
client = AsyncOpenViking(path=str(test_data_dir))
await client.initialize()
+
+ # MockLocalAGFS provides ordinary file operations but not QueueFS's
+ # virtual enqueue/dequeue endpoints. Execute SessionCommit jobs through
+ # the real resume path so these context tests remain about context
+ # assembly rather than the storage mock's missing queue protocol.
+ queue_manager = get_queue_manager()
+ original_enqueue = queue_manager.enqueue
+
+ async def enqueue_with_session_commit_fallback(queue_name, data):
+ if queue_name != QueueManager.SESSION_COMMIT:
+ return await original_enqueue(queue_name, data)
+
+ async def process_commit():
+ await asyncio.sleep(0)
+ queued_session = client.session(session_id=data["session_id"])
+ await queued_session.load()
+ await queued_session.resume_queued_commit(SessionCommitMsg(**data))
+
+ asyncio.create_task(process_commit())
+ return data["task_id"]
+
+ monkeypatch.setattr(queue_manager, "enqueue", enqueue_with_session_commit_fallback)
yield client
await client.close()
@@ -109,6 +133,36 @@ async def _wait_for_task(task_id: str, timeout: float = 30.0) -> dict:
raise TimeoutError(f"Task {task_id} did not complete within {timeout}s")
+async def test_oversized_legacy_assistant_only_commit_completes_without_checkpoint(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="legacy_assistant_only_turn_test")
+ for index in range(3):
+ session.add_message("assistant", [TextPart(str(index) * 1000)])
+
+ result = await session.commit_async(
+ retention_mode="turn_budget",
+ keep_recent_turn_count=1,
+ retained_message_token_budget=150,
+ min_raw_tail_steps=1,
+ )
+ task = await _wait_for_task(result["task_id"])
+ context = await session.get_session_context()
+
+ assert task["status"] == "completed"
+ assert context["latest_archive_overview"]
+ assert context["messages"] == []
+ archive_meta = json.loads(
+ await session._viking_fs.read_file(
+ f"{result['archive_uri']}/.meta.json",
+ ctx=session.ctx,
+ )
+ )
+ assert archive_meta["retention_plan"]["partial_turn"] is False
+ assert archive_meta["retention_plan"]["turn_anchor_message_id"] is None
+ assert archive_meta.get("checkpoints", []) == []
+
+
class TestGetContextForSearch:
"""Test get_context_for_search"""
@@ -265,7 +319,7 @@ class TestGetContextForSearch:
assert len(context["current_messages"]) == 1
async def test_get_context_tracks_multiple_rapid_commits_by_done_boundary(
- self, client: AsyncOpenViking
+ self, client: AsyncOpenViking, monkeypatch
):
"""Context should only advance latest overview when the earlier archive is .done."""
session = client.session(session_id="archive_context_done_boundary_test")
@@ -273,17 +327,16 @@ class TestGetContextForSearch:
second_gate = asyncio.Event()
second_started = asyncio.Event()
- async def gated_extract(messages, **kwargs):
- del kwargs
- contents = " ".join(m.content for m in messages)
- if "First round" in contents:
+ async def gated_summary(self, prompt, **kwargs):
+ del self, kwargs
+ if "First round" in prompt:
await first_gate.wait()
- return []
+ return "# First Summary\n\nFirst archive completed."
second_started.set()
await second_gate.wait()
- return []
+ return "# Second Summary\n\nSecond archive completed."
- session._session_compressor.extract_long_term_memories = gated_extract
+ monkeypatch.setattr(VLMConfig, "get_completion_async", gated_summary)
session.add_message("user", [TextPart("First round user")])
session.add_message("assistant", [TextPart("First round assistant")])
@@ -341,11 +394,11 @@ class TestGetSessionContext:
"# Session Summary\n\n" + ("B" * 20),
]
- async def fake_generate(_messages, latest_archive_overview=""):
- del latest_archive_overview
+ async def fake_generate(self, _messages, latest_archive_overview="", **kwargs):
+ del self, latest_archive_overview, kwargs
return summaries.pop(0)
- monkeypatch.setattr(session, "_generate_archive_summary_async", fake_generate)
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", fake_generate)
session.add_message("user", [TextPart("first turn")])
session.add_message("assistant", [TextPart("first reply")])
@@ -392,10 +445,10 @@ class TestGetSessionContext:
assert context["stats"]["activeTokens"] == session.messages[0].estimated_tokens
assert context["stats"]["activeTokens"] > _estimate_tokens("Executing tool...")
- async def test_get_session_context_reads_latest_overview_and_all_archive_abstracts(
+ async def test_get_session_context_validates_overviews_and_keeps_public_abstracts_empty(
self, client: AsyncOpenViking, monkeypatch
):
- """Overview is only read for the latest archive; abstracts are returned for all archives."""
+ """Completed archives are validated, while the public abstracts field stays empty."""
session = client.session(session_id="assemble_lazy_read_test")
summaries = [
"# Summary\n\n" + ("A" * 80),
@@ -403,11 +456,11 @@ class TestGetSessionContext:
"# Summary\n\n" + ("C" * 80),
]
- async def fake_generate(_messages, latest_archive_overview=""):
- del latest_archive_overview
+ async def fake_generate(self, _messages, latest_archive_overview="", **kwargs):
+ del self, latest_archive_overview, kwargs
return summaries.pop(0)
- monkeypatch.setattr(session, "_generate_archive_summary_async", fake_generate)
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", fake_generate)
for word in ("first", "second", "third"):
session.add_message("user", [TextPart(f"{word} turn")])
@@ -439,25 +492,21 @@ class TestGetSessionContext:
context = await session.get_session_context(token_budget=token_budget)
assert context["latest_archive_overview"] == newest_summary
- assert context["pre_archive_abstracts"] == [
- {"archive_id": "archive_003", "abstract": "# Summary"},
- {"archive_id": "archive_002", "abstract": "# Summary"},
- {"archive_id": "archive_001", "abstract": "# Summary"},
- ]
- assert context["stats"]["includedArchives"] == 3
- assert context["stats"]["droppedArchives"] == 0
+ # The public field is retained for compatibility but intentionally
+ # remains empty; only the latest overview participates in context.
+ assert context["pre_archive_abstracts"] == []
+ assert context["stats"]["includedArchives"] == 0
+ assert context["stats"]["droppedArchives"] == 3
overview_reads = [u for u in read_uris if u.endswith(".overview.md")]
abstract_reads = [u for u in read_uris if u.endswith(".abstract.md")]
- assert all("archive_003" in u for u in overview_reads), (
- f"Only newest archive overview should be read, got: {overview_reads}"
- )
+ assert all(
+ any(f"archive_{index:03d}" in uri for uri in overview_reads)
+ for index in (1, 2, 3)
+ ), f"Every completed archive overview should be validated, got: {overview_reads}"
assert all(
"archive_003" in u or "archive_002" in u or "archive_001" in u for u in abstract_reads
), f"Archive abstracts should be read for every returned archive, got: {abstract_reads}"
- assert not any("archive_001/.overview.md" in u for u in overview_reads), (
- "Oldest archive overview should not be read"
- )
async def test_get_session_context_drops_oldest_pre_archive_abstracts_first(
self, client: AsyncOpenViking, monkeypatch
@@ -469,11 +518,11 @@ class TestGetSessionContext:
"# Summary\n\n" + ("C" * 80),
]
- async def fake_generate(_messages, latest_archive_overview=""):
- del latest_archive_overview
+ async def fake_generate(self, _messages, latest_archive_overview="", **kwargs):
+ del self, latest_archive_overview, kwargs
return summaries.pop(0)
- monkeypatch.setattr(session, "_generate_archive_summary_async", fake_generate)
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", fake_generate)
for word in ("first", "second", "third"):
session.add_message("user", [TextPart(f"{word} turn")])
@@ -493,13 +542,13 @@ class TestGetSessionContext:
context = await session.get_session_context(token_budget=token_budget)
assert context["latest_archive_overview"] == newest_summary
- assert context["pre_archive_abstracts"] == [
- {"archive_id": "archive_003", "abstract": "# Summary"}
- ]
- assert context["estimatedTokens"] == token_budget
+ assert context["pre_archive_abstracts"] == []
+ assert context["estimatedTokens"] == (
+ active_tokens + _estimate_tokens(newest_summary)
+ )
assert context["stats"]["totalArchives"] == 3
- assert context["stats"]["includedArchives"] == 1
- assert context["stats"]["droppedArchives"] == 2
+ assert context["stats"]["includedArchives"] == 0
+ assert context["stats"]["droppedArchives"] == 3
async def test_get_session_context_falls_back_to_older_completed_archive(
self, client: AsyncOpenViking, monkeypatch
@@ -510,11 +559,11 @@ class TestGetSessionContext:
"# Session Summary\n\narchive two",
]
- async def fake_generate(_messages, latest_archive_overview=""):
- del latest_archive_overview
+ async def fake_generate(self, _messages, latest_archive_overview="", **kwargs):
+ del self, latest_archive_overview, kwargs
return summaries.pop(0)
- monkeypatch.setattr(session, "_generate_archive_summary_async", fake_generate)
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", fake_generate)
session.add_message("user", [TextPart("turn one")])
result = await session.commit_async()
@@ -537,12 +586,10 @@ class TestGetSessionContext:
context = await session.get_session_context(token_budget=128_000)
assert context["latest_archive_overview"] == "# Session Summary\n\narchive one"
- assert context["pre_archive_abstracts"] == [
- {"archive_id": "archive_001", "abstract": "# Session Summary"}
- ]
+ assert context["pre_archive_abstracts"] == []
assert context["stats"]["totalArchives"] == 2
- assert context["stats"]["includedArchives"] == 1
- assert context["stats"]["droppedArchives"] == 0
+ assert context["stats"]["includedArchives"] == 0
+ assert context["stats"]["droppedArchives"] == 1
assert context["stats"]["failedArchives"] == 1
async def test_get_session_context_budget_trim_drops_latest_archive_abstract(
@@ -550,11 +597,11 @@ class TestGetSessionContext:
):
session = client.session(session_id="assemble_trim_id_test")
- async def fake_generate(_messages, latest_archive_overview=""):
- del latest_archive_overview
+ async def fake_generate(self, _messages, latest_archive_overview="", **kwargs):
+ del self, latest_archive_overview, kwargs
return "# Session Summary\n\n" + ("Z" * 80)
- monkeypatch.setattr(session, "_generate_archive_summary_async", fake_generate)
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", fake_generate)
session.add_message("user", [TextPart("turn one")])
result = await session.commit_async()
@@ -642,11 +689,11 @@ class TestGetSessionArchive:
"# Session Summary\n\narchive two",
]
- async def fake_generate(_messages, latest_archive_overview=""):
- del latest_archive_overview
+ async def fake_generate(self, _messages, latest_archive_overview="", **kwargs):
+ del self, latest_archive_overview, kwargs
return summaries.pop(0)
- monkeypatch.setattr(session, "_generate_archive_summary_async", fake_generate)
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", fake_generate)
session.add_message("user", [TextPart("turn one")])
session.add_message("assistant", [TextPart("reply one")])
diff --git a/tests/session/test_session_retention_integration.py b/tests/session/test_session_retention_integration.py
new file mode 100644
index 000000000..f11ddd0e1
--- /dev/null
+++ b/tests/session/test_session_retention_integration.py
@@ -0,0 +1,1623 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import asyncio
+import json
+from types import SimpleNamespace
+from uuid import uuid4
+
+import pytest
+
+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.session import Session, _ArchiveSummaryResult, _CheckpointRequest
+
+
+async def _write_archive(
+ session,
+ index: int,
+ messages: list[Message],
+ *,
+ overview: str = "",
+ done: dict | None = None,
+ failed: bool = False,
+ meta: dict | None = None,
+) -> str:
+ archive_id = f"archive_{index:03d}"
+ archive_uri = f"{session.uri}/history/{archive_id}"
+ await session._viking_fs.write_file(
+ f"{archive_uri}/messages.jsonl",
+ "\n".join(message.to_jsonl() for message in messages) + "\n",
+ ctx=session.ctx,
+ )
+ if overview:
+ await session._viking_fs.write_file(
+ f"{archive_uri}/.overview.md", overview, ctx=session.ctx
+ )
+ if meta is not None:
+ await session._viking_fs.write_file(
+ f"{archive_uri}/.meta.json",
+ json.dumps(meta),
+ ctx=session.ctx,
+ )
+ if failed:
+ await session._viking_fs.write_file(
+ f"{archive_uri}/.failed.json",
+ json.dumps({"error": "synthetic failure"}),
+ ctx=session.ctx,
+ )
+ if done is not None:
+ await session._viking_fs.write_file(
+ f"{archive_uri}/.done",
+ json.dumps(done),
+ ctx=session.ctx,
+ )
+ return archive_uri
+
+
+def _text_message(message_id: str, role: str, text: str) -> Message:
+ return Message(id=message_id, role=role, parts=[TextPart(text)])
+
+
+def test_checkpoint_record_respects_remaining_retained_budget():
+ records = Session._build_checkpoint_records(
+ [
+ _CheckpointRequest(
+ turn_anchor_message_id="u1",
+ source_message_ids=("a1",),
+ retained_message_token_budget=20,
+ estimated_active_tokens=15,
+ )
+ ],
+ ("A" * 400,),
+ )
+
+ assert records[0]["estimated_tokens"] <= 5
+
+
+async def test_two_pending_archives_are_visible_independent_of_commit_count(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="two_pending_directory_state_test")
+ await session.ensure_exists()
+ await _write_archive(session, 1, [_text_message("u1", "user", "one")])
+ await _write_archive(session, 2, [_text_message("u2", "user", "two")])
+ session.meta.commit_count = 99
+ await session._save_meta()
+
+ context = await session.get_session_context()
+
+ assert [message["id"] for message in context["messages"]] == ["u1", "u2"]
+ assert context["latest_archive_overview"] == ""
+
+
+async def test_session_context_enforces_hard_budget_without_mutating_archive_raw(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="session_context_hard_budget_test")
+ await session.ensure_exists()
+ archived = _text_message("u1", "user", "A" * 4000)
+ await _write_archive(session, 1, [archived])
+ live = _text_message("a1", "assistant", "B" * 4000)
+ session._messages = [live]
+ await session._write_to_agfs_async(messages=[live])
+
+ context = await session.get_session_context(token_budget=100)
+ raw = await session._read_archive_messages(f"{session.uri}/history/archive_001")
+
+ assert context["estimatedTokens"] <= 100
+ assert context["stats"]["activeTokens"] <= 100
+ assert raw[0].content == "A" * 4000
+ assert live.content == "B" * 4000
+
+
+async def test_failed_archive_returns_raw_but_done_without_overview_stays_archived(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="failed_and_wm_disabled_archive_test")
+ await session.ensure_exists()
+ await _write_archive(
+ session,
+ 1,
+ [_text_message("u1", "user", "failed raw")],
+ failed=True,
+ )
+ await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "completed without overview")],
+ done={"starting_message_id": "u2", "ending_message_id": "u2"},
+ )
+
+ context = await session.get_session_context()
+
+ assert [message["id"] for message in context["messages"]] == ["u1"]
+ assert context["stats"]["failedArchives"] == 1
+
+
+async def test_done_with_missing_required_overview_remains_uncovered(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="missing_required_overview_test")
+ await session.ensure_exists()
+ await _write_archive(
+ session,
+ 1,
+ [_text_message("u1", "user", "required overview raw")],
+ done={
+ "starting_message_id": "u1",
+ "ending_message_id": "u1",
+ "working_memory_enabled": True,
+ },
+ )
+
+ context = await session.get_session_context()
+
+ assert [message["id"] for message in context["messages"]] == ["u1"]
+ assert context["stats"]["failedArchives"] == 1
+
+
+async def test_legacy_done_marker_covers_only_its_own_archive(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="legacy_done_self_coverage_test")
+ await session.ensure_exists()
+ await _write_archive(
+ session,
+ 1,
+ [_text_message("u1", "user", "failed raw remains active")],
+ failed=True,
+ )
+ await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "legacy completed raw")],
+ overview="# Session Summary\n\nlegacy archive two only",
+ done={"starting_message_id": "u2", "ending_message_id": "u2"},
+ )
+
+ context = await session.get_session_context()
+
+ assert context["latest_archive_overview"].endswith("legacy archive two only")
+ assert [message["id"] for message in context["messages"]] == ["u1"]
+
+
+async def test_coverage_metadata_cannot_hide_a_pending_archive(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="pending_not_explicitly_covered_test")
+ await session.ensure_exists()
+ await _write_archive(
+ session,
+ 1,
+ [_text_message("u1", "user", "still pending")],
+ )
+ await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "completed two")],
+ overview="# Session Summary\n\narchive two",
+ done={
+ "starting_message_id": "u2",
+ "ending_message_id": "u2",
+ "coverage_start_archive": "archive_001",
+ "coverage_end_archive": "archive_002",
+ "covered_failed_archives": ["archive_001"],
+ },
+ )
+
+ context = await session.get_session_context()
+
+ assert [message["id"] for message in context["messages"]] == ["u1"]
+
+
+async def test_later_coverage_absorbs_failed_raw_and_stable_deduplicates_root(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="failed_coverage_roll_forward_test")
+ await session.ensure_exists()
+ duplicate = _text_message("u1", "user", "failed raw")
+ await _write_archive(session, 1, [duplicate], failed=True)
+ await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "current raw")],
+ overview="# Session Summary\n\ncovered one and two",
+ done={
+ "starting_message_id": "u1",
+ "ending_message_id": "u2",
+ "coverage_start_archive": "archive_001",
+ "coverage_end_archive": "archive_002",
+ "covered_failed_archives": ["archive_001"],
+ },
+ )
+ session._messages = [duplicate]
+ await session._write_to_agfs_async(messages=session._messages)
+
+ context = await session.get_session_context()
+
+ assert context["latest_archive_overview"] == "# Session Summary\n\ncovered one and two"
+ assert [message["id"] for message in context["messages"]] == ["u1"]
+
+
+async def test_phase2_replays_failed_but_not_completed_without_overview(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="phase2_failed_replay_test")
+ await session.ensure_exists()
+ await _write_archive(
+ session,
+ 1,
+ [_text_message("u1", "user", "failed one")],
+ failed=True,
+ )
+ await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "completed without overview")],
+ done={"starting_message_id": "u2", "ending_message_id": "u2"},
+ )
+ current_uri = await _write_archive(
+ session,
+ 3,
+ [_text_message("u3", "user", "current three")],
+ )
+
+ messages, start, end, failed, completed_steps = await session._prepare_phase2_archive_messages(
+ current_uri,
+ [_text_message("u3", "user", "current three")],
+ )
+
+ assert [message.id for message in messages] == ["u1", "u3"]
+ assert start == "archive_001"
+ assert end == "archive_003"
+ assert failed == ["archive_001"]
+ assert completed_steps == {}
+
+
+async def test_phase2_never_replays_an_earlier_pending_archive(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="phase2_pending_not_replayed_test")
+ await session.ensure_exists()
+ await _write_archive(session, 1, [_text_message("u1", "user", "pending one")])
+ await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "failed two")],
+ failed=True,
+ )
+ current_uri = await _write_archive(
+ session,
+ 3,
+ [_text_message("u3", "user", "current three")],
+ )
+
+ messages, start, end, failed, _completed_steps = await session._prepare_phase2_archive_messages(
+ current_uri,
+ [_text_message("u3", "user", "current three")],
+ )
+
+ assert [message.id for message in messages] == ["u2", "u3"]
+ assert start == "archive_002"
+ assert end == "archive_003"
+ assert failed == ["archive_002"]
+
+
+async def test_phase2_waits_for_all_earlier_pending_archives(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="phase2_wait_all_pending_test")
+ await session.ensure_exists()
+ first_uri = await _write_archive(
+ session,
+ 1,
+ [_text_message("u1", "user", "pending one")],
+ )
+ await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "completed two")],
+ overview="# Summary\n\ncomplete",
+ done={"starting_message_id": "u2", "ending_message_id": "u2"},
+ )
+ monkeypatch.setattr("openviking.session.session._ARCHIVE_WAIT_POLL_SECONDS", 0.01)
+
+ waiter = asyncio.create_task(session._wait_for_previous_archive_done(3))
+ await asyncio.sleep(0.03)
+ assert not waiter.done()
+
+ await session._viking_fs.write_file(
+ f"{first_uri}/.failed.json",
+ json.dumps({"error": "synthetic terminal failure"}),
+ ctx=session.ctx,
+ )
+ assert await asyncio.wait_for(waiter, timeout=0.5)
+
+
+async def test_missing_previous_archive_directory_does_not_block_phase2(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="missing_previous_archive_test")
+ await session.ensure_exists()
+ await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "archive two")],
+ )
+
+ assert await asyncio.wait_for(
+ session._wait_for_previous_archive_done(2),
+ timeout=0.5,
+ )
+
+
+async def test_phase2_roll_forward_writes_coverage_and_calls_existing_summary_once(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="phase2_roll_forward_end_to_end_test")
+ await session.ensure_exists()
+ await _write_archive(
+ session,
+ 1,
+ [_text_message("u1", "user", "failed one")],
+ failed=True,
+ )
+ current = _text_message("u2", "user", "current two")
+ current_uri = await _write_archive(session, 2, [current])
+ seen_message_ids: list[list[str]] = []
+
+ async def fake_summary(messages, latest_archive_overview=""):
+ assert latest_archive_overview == ""
+ seen_message_ids.append([message.id for message in messages])
+ return "# Session Summary\n\n## Current State\nBoth rounds are covered."
+
+ config = SimpleNamespace(
+ memory=SimpleNamespace(
+ extraction_enabled=False,
+ session_skill_extraction_enabled=False,
+ )
+ )
+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)
+ monkeypatch.setattr(session, "_generate_archive_summary_async", fake_summary)
+
+ task_id = str(uuid4())
+ await get_task_tracker().create(
+ "session_commit",
+ resource_id=session.session_id,
+ account_id=session.ctx.account_id,
+ user_id=session.ctx.user.user_id,
+ task_id=task_id,
+ )
+ await session._run_memory_extraction(
+ task_id=task_id,
+ archive_uri=current_uri,
+ messages=[current],
+ usage_records=[],
+ first_message_id=current.id,
+ last_message_id=current.id,
+ memory_policy={"working_memory": {"enabled": True}},
+ )
+
+ done = json.loads(await session._viking_fs.read_file(f"{current_uri}/.done", ctx=session.ctx))
+ context = await session.get_session_context()
+ assert seen_message_ids == [["u1", "u2"]]
+ assert done["coverage_start_archive"] == "archive_001"
+ assert done["coverage_end_archive"] == "archive_002"
+ assert done["covered_failed_archives"] == ["archive_001"]
+ assert context["latest_archive_overview"].endswith("Both rounds are covered.")
+ assert context["messages"] == []
+
+
+async def test_phase2_rolls_forward_done_archive_with_missing_required_overview(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="invalid_done_roll_forward_test")
+ await session.ensure_exists()
+ await _write_archive(
+ session,
+ 1,
+ [_text_message("u1", "user", "raw from invalid completed archive")],
+ done={
+ "starting_message_id": "u1",
+ "ending_message_id": "u1",
+ "working_memory_enabled": True,
+ },
+ )
+ current = _text_message("u2", "user", "current archive")
+ current_uri = await _write_archive(session, 2, [current])
+ seen_message_ids: list[list[str]] = []
+
+ async def fake_summary(messages, latest_archive_overview=""):
+ assert latest_archive_overview == ""
+ seen_message_ids.append([message.id for message in messages])
+ return "# Session Summary\n\n## Current State\nInvalid archive was recovered."
+
+ config = SimpleNamespace(
+ memory=SimpleNamespace(
+ extraction_enabled=False,
+ session_skill_extraction_enabled=False,
+ )
+ )
+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)
+ monkeypatch.setattr(session, "_generate_archive_summary_async", fake_summary)
+
+ task_id = str(uuid4())
+ await get_task_tracker().create(
+ "session_commit",
+ resource_id=session.session_id,
+ account_id=session.ctx.account_id,
+ user_id=session.ctx.user.user_id,
+ task_id=task_id,
+ )
+ await session._run_memory_extraction(
+ task_id=task_id,
+ archive_uri=current_uri,
+ messages=[current],
+ usage_records=[],
+ first_message_id=current.id,
+ last_message_id=current.id,
+ memory_policy={"working_memory": {"enabled": True}},
+ )
+
+ done = json.loads(await session._viking_fs.read_file(f"{current_uri}/.done", ctx=session.ctx))
+ context = await session.get_session_context()
+ assert seen_message_ids == [["u1", "u2"]]
+ assert done["coverage_start_archive"] == "archive_001"
+ assert done["covered_failed_archives"] == ["archive_001"]
+ assert context["latest_archive_overview"].endswith("Invalid archive was recovered.")
+ assert context["messages"] == []
+
+
+async def test_roll_forward_does_not_repeat_completed_memory_step_messages(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="phase2_memory_step_idempotency_test")
+ await session.ensure_exists()
+ first = _text_message("u1", "user", "already extracted")
+ await _write_archive(
+ session,
+ 1,
+ [first],
+ failed=True,
+ meta={"completed_memory_steps": {"long_term": ["u1"]}},
+ )
+ current = _text_message("u2", "user", "extract this once")
+ current_uri = await _write_archive(session, 2, [current])
+ summary_inputs: list[list[str]] = []
+ long_term_inputs: list[list[str]] = []
+
+ async def fake_summary(messages, latest_archive_overview=""):
+ assert latest_archive_overview == ""
+ summary_inputs.append([message.id for message in messages])
+ return "# Session Summary\n\n## Current State\nBoth messages are summarized."
+
+ async def fake_long_term(*, messages, **_kwargs):
+ long_term_inputs.append([message.id for message in messages])
+ return []
+
+ config = SimpleNamespace(
+ memory=SimpleNamespace(
+ extraction_enabled=True,
+ session_skill_extraction_enabled=False,
+ )
+ )
+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)
+ monkeypatch.setattr(session, "_generate_archive_summary_async", fake_summary)
+ monkeypatch.setattr(
+ session._session_compressor,
+ "extract_long_term_memories",
+ fake_long_term,
+ )
+
+ task_id = str(uuid4())
+ await get_task_tracker().create(
+ "session_commit",
+ resource_id=session.session_id,
+ account_id=session.ctx.account_id,
+ user_id=session.ctx.user.user_id,
+ task_id=task_id,
+ )
+ await session._run_memory_extraction(
+ task_id=task_id,
+ archive_uri=current_uri,
+ messages=[current],
+ usage_records=[],
+ first_message_id=current.id,
+ last_message_id=current.id,
+ memory_policy={
+ "self": {"enabled": True},
+ "peer": {"enabled": False},
+ "memory_types": ["profile"],
+ "working_memory": {"enabled": True},
+ },
+ )
+
+ done = json.loads(await session._viking_fs.read_file(f"{current_uri}/.done", ctx=session.ctx))
+ assert summary_inputs == [["u1", "u2"]]
+ assert long_term_inputs == [["u2"]]
+ assert done["completed_memory_steps"]["long_term"] == ["u1", "u2"]
+
+
+async def test_completed_partial_turn_inserts_checkpoint_after_user_anchor(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="partial_turn_checkpoint_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ early = _text_message("a1", "assistant", "checking the first signal")
+ tail = _text_message("a2", "assistant", "the latest raw step")
+ overview = """# Session Summary
+
+## Current State
+Connection pool exhaustion is confirmed.
+
+## Key Facts & Decisions
+- Keep the user query as the Turn anchor.
+
+## Open Issues
+- Validate the recycle configuration.
+"""
+ archive_uri = await _write_archive(
+ session,
+ 1,
+ [anchor, early],
+ overview=overview,
+ meta={
+ "retention_plan": {
+ "mode": "turn_budget",
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a1"],
+ "raw_tail_start_message_id": "a2",
+ "retained_message_token_budget": 12_000,
+ },
+ "checkpoints": [
+ {
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a1"],
+ "abstract": "Checked the first signal and found pool saturation.",
+ "estimated_tokens": 12,
+ }
+ ],
+ },
+ done={
+ "starting_message_id": "u1",
+ "ending_message_id": "a1",
+ "coverage_start_archive": "archive_001",
+ "coverage_end_archive": "archive_001",
+ "covered_failed_archives": [],
+ },
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
+ # The retained-message budget belongs to commit planning. Context reads
+ # must use their own request budget instead of silently reusing this value.
+ session.meta.retention_mode = "turn_budget"
+ session.meta.retained_message_token_budget = 1
+
+ context = await session.get_session_context(token_budget=128_000)
+
+ assert [message["id"] for message in context["messages"]] == [
+ "u1",
+ "checkpoint_archive_001_u1",
+ "a2",
+ ]
+ checkpoint = context["messages"][1]
+ assert checkpoint["message_kind"] == "checkpoint"
+ assert "peer_id" not in checkpoint
+ assert checkpoint["source_message_ids"] == ["a1"]
+ assert checkpoint["parts"][0]["uri"] == archive_uri
+ assert checkpoint["parts"][0]["abstract"] == (
+ "Checked the first signal and found pool saturation."
+ )
+
+
+async def test_legacy_partial_turn_does_not_derive_checkpoint_from_overview(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="legacy_partial_turn_without_checkpoint_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ early = _text_message("a1", "assistant", "checking the first signal")
+ tail = _text_message("a2", "assistant", "the latest raw step")
+ await _write_archive(
+ session,
+ 1,
+ [anchor, early],
+ overview="# Working Memory\n\n## Current State\nPool exhaustion was found.",
+ meta={
+ "retention_plan": {
+ "mode": "turn_budget",
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a1"],
+ "retained_message_token_budget": 12_000,
+ }
+ },
+ done={"starting_message_id": "u1", "ending_message_id": "a1"},
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
+
+ context = await session.get_session_context()
+
+ assert [message["id"] for message in context["messages"]] == ["u1", "a2"]
+
+
+async def test_phase2_persists_checkpoint_from_same_summary_call(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="phase2_checkpoint_product_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ early = _text_message("a1", "assistant", "checking the first signal")
+ tail = _text_message("a2", "assistant", "the latest raw step")
+ archive_uri = await _write_archive(
+ session,
+ 1,
+ [anchor, early],
+ meta={
+ "retention_plan": {
+ "mode": "turn_budget",
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a1"],
+ "raw_tail_start_message_id": "a2",
+ "retained_message_token_budget": 6000,
+ "estimated_active_tokens": 100,
+ }
+ },
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
+ calls = 0
+
+ async def fake_summary(
+ messages,
+ latest_archive_overview="",
+ checkpoint_requests=None,
+ ):
+ nonlocal calls
+ calls += 1
+ assert latest_archive_overview == ""
+ assert [message.id for message in messages] == ["u1", "a1"]
+ assert checkpoint_requests is not None
+ assert len(checkpoint_requests) == 1
+ assert checkpoint_requests[0].turn_anchor_message_id == "u1"
+ assert checkpoint_requests[0].source_message_ids == ("a1",)
+ return _ArchiveSummaryResult(
+ overview="# Working Memory\n\n## Current State\nPool saturation confirmed.",
+ checkpoint_summaries=("Checked the first signal; pool saturation was confirmed.",),
+ )
+
+ config = SimpleNamespace(
+ memory=SimpleNamespace(
+ extraction_enabled=False,
+ session_skill_extraction_enabled=False,
+ )
+ )
+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)
+ monkeypatch.setattr(session, "_generate_archive_summary_async", fake_summary)
+
+ task_id = str(uuid4())
+ await get_task_tracker().create(
+ "session_commit",
+ resource_id=session.session_id,
+ account_id=session.ctx.account_id,
+ user_id=session.ctx.user.user_id,
+ task_id=task_id,
+ )
+ await session._run_memory_extraction(
+ task_id=task_id,
+ archive_uri=archive_uri,
+ messages=[anchor, early],
+ usage_records=[],
+ first_message_id="u1",
+ last_message_id="a1",
+ memory_policy={"working_memory": {"enabled": True}},
+ )
+
+ meta = json.loads(
+ await session._viking_fs.read_file(f"{archive_uri}/.meta.json", ctx=session.ctx)
+ )
+ context = await session.get_session_context()
+ assert calls == 1
+ assert meta["checkpoints"][0]["turn_anchor_message_id"] == "u1"
+ assert meta["checkpoints"][0]["source_message_ids"] == ["a1"]
+ assert meta["checkpoints"][0]["abstract"] == (
+ "Checked the first signal; pool saturation was confirmed."
+ )
+ assert meta["checkpoints"][0]["estimated_tokens"] > 0
+ assert [message["id"] for message in context["messages"]] == [
+ "u1",
+ "checkpoint_archive_001_u1",
+ "a2",
+ ]
+
+
+async def test_wm_creation_returns_two_products_in_one_model_call(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="single_call_checkpoint_generation_test")
+ calls: list[dict] = []
+
+ class FakeVLM:
+ @staticmethod
+ def is_available() -> bool:
+ return True
+
+ async def get_completion_async(self, **kwargs):
+ calls.append(kwargs)
+ return VLMResponse(
+ tool_calls=[
+ ToolCall(
+ id="tool-call-1",
+ name="create_working_memory",
+ arguments={
+ "working_memory": (
+ "# Working Memory\n\n## Current State\nInvestigation continues."
+ ),
+ "checkpoint_summaries": [
+ "Queried the service and found pool saturation."
+ ],
+ },
+ )
+ ],
+ finish_reason="tool_calls",
+ )
+
+ vlm = FakeVLM()
+ monkeypatch.setattr(
+ "openviking.session.session.get_openviking_config",
+ lambda: SimpleNamespace(vlm=vlm),
+ )
+ anchor = _text_message("secret-anchor-id", "user", "investigate the outage")
+ source = _text_message("secret-source-id", "assistant", "queried the service")
+ result = await session._generate_archive_summary_async(
+ [anchor, source],
+ checkpoint_requests=[
+ _CheckpointRequest(
+ turn_anchor_message_id=anchor.id,
+ source_message_ids=(source.id,),
+ retained_message_token_budget=6000,
+ estimated_active_tokens=100,
+ )
+ ],
+ )
+
+ assert isinstance(result, _ArchiveSummaryResult)
+ assert result.checkpoint_summaries == ("Queried the service and found pool saturation.",)
+ assert len(calls) == 1
+ assert calls[0]["tools"][0]["function"]["name"] == "create_working_memory"
+ assert '<checkpoint_source index="0">' in calls[0]["prompt"]
+ assert calls[0]["prompt"].count("queried the service") == 1
+ assert "secret-anchor-id" not in calls[0]["prompt"]
+ assert "secret-source-id" not in calls[0]["prompt"]
+
+
+async def test_wm_update_returns_two_products_in_one_model_call(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="single_call_checkpoint_update_test")
+ calls: list[dict] = []
+
+ class FakeVLM:
+ @staticmethod
+ def is_available() -> bool:
+ return True
+
+ async def get_completion_async(self, **kwargs):
+ calls.append(kwargs)
+ return VLMResponse(
+ tool_calls=[
+ ToolCall(
+ id="tool-call-1",
+ name="update_working_memory",
+ arguments={
+ "sections": {
+ name: {"op": "KEEP"}
+ for name in (
+ "Session Title",
+ "Current State",
+ "Task & Goals",
+ "Key Facts & Decisions",
+ "Files & Context",
+ "Errors & Corrections",
+ "Open Issues",
+ )
+ },
+ "checkpoint_summaries": [
+ "Compared logs and ruled out the network path."
+ ],
+ },
+ )
+ ],
+ finish_reason="tool_calls",
+ )
+
+ vlm = FakeVLM()
+ monkeypatch.setattr(
+ "openviking.session.session.get_openviking_config",
+ lambda: SimpleNamespace(vlm=vlm),
+ )
+ source = _text_message("source-id", "assistant", "compared the logs")
+ prior = """# Working Memory
+
+## Session Title
+Outage investigation
+
+## Current State
+Investigation continues.
+
+## Task & Goals
+Find the outage cause.
+
+## Key Facts & Decisions
+None.
+
+## Files & Context
+None.
+
+## Errors & Corrections
+None.
+
+## Open Issues
+Confirm the database state.
+"""
+ result = await session._generate_archive_summary_async(
+ [source],
+ latest_archive_overview=prior,
+ checkpoint_requests=[
+ _CheckpointRequest(
+ turn_anchor_message_id="anchor-id",
+ source_message_ids=(source.id,),
+ retained_message_token_budget=6000,
+ estimated_active_tokens=100,
+ )
+ ],
+ )
+
+ assert isinstance(result, _ArchiveSummaryResult)
+ assert result.checkpoint_summaries == ("Compared logs and ruled out the network path.",)
+ assert "Investigation continues." in result.overview
+ assert len(calls) == 1
+ assert calls[0]["tools"][0]["function"]["name"] == "update_working_memory"
+ assert "checkpoint_summaries" in calls[0]["prompt"]
+
+
+async def test_roll_forward_collects_multiple_checkpoint_requests(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="multiple_roll_forward_checkpoint_test")
+ await session.ensure_exists()
+ first_anchor = _text_message("u1", "user", "first investigation")
+ first_source = _text_message("a1", "assistant", "first archived step")
+ second_anchor = _text_message("u2", "user", "second investigation")
+ second_source = _text_message("a2", "assistant", "second archived step")
+ await _write_archive(
+ session,
+ 1,
+ [first_anchor, first_source],
+ failed=True,
+ meta={
+ "retention_plan": {
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a1"],
+ "retained_message_token_budget": 6000,
+ "estimated_active_tokens": 100,
+ }
+ },
+ )
+ await _write_archive(
+ session,
+ 2,
+ [second_anchor, second_source],
+ failed=True,
+ meta={
+ "retention_plan": {
+ "partial_turn": True,
+ "turn_anchor_message_id": "u2",
+ "checkpoint_source_message_ids": ["a2"],
+ "retained_message_token_budget": 6000,
+ "estimated_active_tokens": 120,
+ }
+ },
+ )
+ current = _text_message("u3", "user", "current work")
+ current_uri = await _write_archive(session, 3, [current], meta={})
+ combined = [first_anchor, first_source, second_anchor, second_source, current]
+
+ requests = await session._collect_checkpoint_requests_for_phase2(
+ current_uri,
+ ["archive_001", "archive_002"],
+ combined,
+ )
+ formatted = session._format_messages_for_wm(combined, requests)
+
+ assert [request.turn_anchor_message_id for request in requests] == ["u1", "u2"]
+ assert [request.source_message_ids for request in requests] == [("a1",), ("a2",)]
+ assert formatted.count('<checkpoint_source index="0">') == 1
+ assert formatted.count('<checkpoint_source index="1">') == 1
+
+
+async def test_checkpoint_request_rejects_user_or_cross_turn_sources(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="invalid_checkpoint_source_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "first query")
+ assistant = _text_message("a1", "assistant", "first response")
+ archive_uri = await _write_archive(
+ session,
+ 1,
+ [anchor, assistant],
+ meta={
+ "retention_plan": {
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["u1"],
+ "retained_message_token_budget": 6000,
+ "estimated_active_tokens": 100,
+ }
+ },
+ )
+
+ with pytest.raises(ValueError, match="outside its Assistant/Tool prefix"):
+ await session._collect_checkpoint_requests_for_phase2(
+ archive_uri,
+ [],
+ [anchor, assistant],
+ )
+
+
+async def test_missing_required_checkpoint_keeps_archive_raw_uncovered(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="missing_required_checkpoint_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ early = _text_message("a1", "assistant", "checking the first signal")
+ tail = _text_message("a2", "assistant", "the latest raw step")
+ archive_uri = await _write_archive(
+ session,
+ 1,
+ [anchor, early],
+ meta={
+ "retention_plan": {
+ "mode": "turn_budget",
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a1"],
+ "retained_message_token_budget": 6000,
+ "estimated_active_tokens": 100,
+ }
+ },
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
+
+ async def fake_summary(*_args, **_kwargs):
+ # Simulate an old/malformed implementation that returns only overview.
+ return "# Working Memory\n\n## Current State\nPool saturation confirmed."
+
+ config = SimpleNamespace(
+ memory=SimpleNamespace(
+ extraction_enabled=False,
+ session_skill_extraction_enabled=False,
+ )
+ )
+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)
+ monkeypatch.setattr(session, "_generate_archive_summary_async", fake_summary)
+
+ task_id = str(uuid4())
+ await get_task_tracker().create(
+ "session_commit",
+ resource_id=session.session_id,
+ account_id=session.ctx.account_id,
+ user_id=session.ctx.user.user_id,
+ task_id=task_id,
+ )
+ await session._run_memory_extraction(
+ task_id=task_id,
+ archive_uri=archive_uri,
+ messages=[anchor, early],
+ usage_records=[],
+ first_message_id="u1",
+ last_message_id="a1",
+ memory_policy={"working_memory": {"enabled": True}},
+ )
+
+ assert not await session._viking_fs.exists(f"{archive_uri}/.done", ctx=session.ctx)
+ assert await session._viking_fs.exists(f"{archive_uri}/.failed.json", ctx=session.ctx)
+ context = await session.get_session_context()
+ assert [message["id"] for message in context["messages"]] == ["u1", "a1", "a2"]
+ assert not any(message.get("message_kind") == "checkpoint" for message in context["messages"])
+
+
+async def test_working_memory_disabled_does_not_generate_or_restore_checkpoint(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="wm_disabled_partial_checkpoint_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ early = _text_message("a1", "assistant", "checking the first signal")
+ tail = _text_message("a2", "assistant", "the latest raw step")
+ archive_uri = await _write_archive(
+ session,
+ 1,
+ [anchor, early],
+ meta={
+ "retention_plan": {
+ "mode": "turn_budget",
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a1"],
+ "retained_message_token_budget": 6000,
+ "estimated_active_tokens": 100,
+ }
+ },
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
+
+ async def unexpected_summary(*_args, **_kwargs):
+ raise AssertionError("Working Memory generation must stay disabled")
+
+ config = SimpleNamespace(
+ memory=SimpleNamespace(
+ extraction_enabled=False,
+ session_skill_extraction_enabled=False,
+ )
+ )
+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)
+ monkeypatch.setattr(session, "_generate_archive_summary_async", unexpected_summary)
+
+ task_id = str(uuid4())
+ await get_task_tracker().create(
+ "session_commit",
+ resource_id=session.session_id,
+ account_id=session.ctx.account_id,
+ user_id=session.ctx.user.user_id,
+ task_id=task_id,
+ )
+ await session._run_memory_extraction(
+ task_id=task_id,
+ archive_uri=archive_uri,
+ messages=[anchor, early],
+ usage_records=[],
+ first_message_id="u1",
+ last_message_id="a1",
+ memory_policy={
+ "working_memory": {"enabled": False},
+ "self": {"enabled": False},
+ "peer": {"enabled": False},
+ },
+ )
+
+ assert await session._viking_fs.exists(f"{archive_uri}/.done", ctx=session.ctx)
+ context = await session.get_session_context()
+ assert [message["id"] for message in context["messages"]] == ["u1", "a2"]
+
+
+async def test_covered_failed_partial_turn_checkpoint_points_to_covering_overview(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="covered_failed_partial_checkpoint_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ early = _text_message("a1", "assistant", "checking an early signal")
+ tail = _text_message("a2", "assistant", "the latest raw step")
+ await _write_archive(
+ session,
+ 1,
+ [anchor, early],
+ failed=True,
+ meta={
+ "retention_plan": {
+ "mode": "turn_budget",
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a1"],
+ "raw_tail_start_message_id": "a2",
+ "retained_message_token_budget": 12_000,
+ }
+ },
+ )
+ covering_uri = await _write_archive(
+ session,
+ 2,
+ [_text_message("u2", "user", "a later query")],
+ overview="# Session Summary\n\n## Current State\nThe early signal is covered.",
+ meta={
+ "checkpoints": [
+ {
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a1"],
+ "abstract": "The early signal ruled out a network failure.",
+ "estimated_tokens": 11,
+ }
+ ]
+ },
+ done={
+ "starting_message_id": "u1",
+ "ending_message_id": "u2",
+ "coverage_start_archive": "archive_001",
+ "coverage_end_archive": "archive_002",
+ "covered_failed_archives": ["archive_001"],
+ },
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
+
+ context = await session.get_session_context()
+
+ checkpoint = context["messages"][1]
+ assert checkpoint["id"] == "checkpoint_archive_002_u1"
+ assert checkpoint["parts"][0]["uri"] == covering_uri
+ assert checkpoint["source_message_ids"] == ["a1"]
+
+
+async def test_repeated_partial_commits_merge_checkpoints_for_same_turn_anchor(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="repeated_partial_checkpoint_merge_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ tail = _text_message("a3", "assistant", "latest raw step")
+ await _write_archive(
+ session,
+ 1,
+ [anchor, _text_message("a1", "assistant", "first old step")],
+ overview="# Working Memory\n\n## Current State\nFirst prefix covered.",
+ meta={
+ "checkpoints": [
+ {
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a1"],
+ "abstract": "First prefix found pool saturation.",
+ "estimated_tokens": 9,
+ }
+ ]
+ },
+ done={"starting_message_id": "u1", "ending_message_id": "a1"},
+ )
+ second_uri = await _write_archive(
+ session,
+ 2,
+ [anchor, _text_message("a2", "assistant", "second old step")],
+ overview="# Working Memory\n\n## Current State\nSecond prefix covered.",
+ meta={
+ "checkpoints": [
+ {
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a2"],
+ "abstract": "Second prefix ruled out the network path.",
+ "estimated_tokens": 11,
+ }
+ ]
+ },
+ done={"starting_message_id": "u1", "ending_message_id": "a2"},
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
+
+ context = await session.get_session_context()
+
+ assert [message["id"] for message in context["messages"]] == [
+ "u1",
+ "checkpoint_archive_002_u1",
+ "a3",
+ ]
+ checkpoint = context["messages"][1]
+ assert checkpoint["source_message_ids"] == ["a1", "a2"]
+ assert checkpoint["parts"][0]["uri"] == second_uri
+ assert checkpoint["parts"][0]["abstract"] == (
+ "First prefix found pool saturation.\n\n"
+ "Second prefix ruled out the network path."
+ )
+
+
+async def test_commit_externalizes_tool_outputs_across_the_whole_turn(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="turn_wide_externalization_test")
+ session.add_message("user", [TextPart("inspect all files")])
+ for index in range(10):
+ session.add_message(
+ "assistant",
+ [
+ TextPart(f"step {index}"),
+ ToolPart(
+ tool_id=f"tool-{index}",
+ tool_name="read",
+ tool_output=str(index) * 10_000,
+ tool_status="completed",
+ ),
+ ],
+ )
+
+ result = await session.commit_async(
+ retention_mode="turn_budget",
+ keep_recent_turn_count=1,
+ retained_message_token_budget=50_000,
+ )
+
+ tool_parts = [
+ part for message in session.messages for part in message.parts if isinstance(part, ToolPart)
+ ]
+ assert result["archived"] is False
+ assert any(part.tool_output_ref for part in tool_parts)
+ assert all(part.tool_output_group_original_chars == 100_000 for part in tool_parts)
+ assert any(part.tool_output_externalized_reason == "turn_budget" for part in tool_parts)
+
+
+async def test_turn_budget_commit_archives_complete_old_turn_and_keeps_latest_user(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="turn_budget_phase1_boundary_test")
+ session.add_message("user", [TextPart("first query")])
+ session.add_message("assistant", [TextPart("first answer")])
+ session.add_message("user", [TextPart("latest query")])
+ session.add_message("assistant", [TextPart("latest answer")])
+
+ result = await session.commit_async(
+ retention_mode="turn_budget",
+ keep_recent_turn_count=1,
+ retained_message_token_budget=12_000,
+ memory_policy={
+ "working_memory": {"enabled": False},
+ "self": {"enabled": False},
+ "peer": {"enabled": False},
+ },
+ )
+ archived = await session._read_archive_messages(result["archive_uri"])
+
+ assert [message.content for message in archived] == ["first query", "first answer"]
+ assert [message.content for message in session.messages] == ["latest query", "latest answer"]
+ assert result["estimated_active_tokens"] > 0
+ assert result["budget_exceeded"] is False
+
+
+async def test_concurrent_stale_session_instances_use_one_authoritative_phase1_snapshot(
+ client: AsyncOpenViking,
+):
+ session_a = client.session(session_id="multi_worker_phase1_snapshot_test")
+ session_a.add_message("user", [TextPart("only once")])
+ session_b = client.session(session_id=session_a.session_id)
+ await session_b.load()
+ disabled_policy = {
+ "working_memory": {"enabled": False},
+ "self": {"enabled": False},
+ "peer": {"enabled": False},
+ }
+
+ results = await asyncio.gather(
+ session_a.commit_async(memory_policy=disabled_policy),
+ session_b.commit_async(memory_policy=disabled_policy),
+ )
+
+ assert sum(result["archived"] is True for result in results) == 1
+ assert len(await session_a._list_archive_refs()) == 1
+ assert await session_a._read_live_messages_strict() == []
+
+
+async def test_concurrent_stale_workers_append_without_losing_messages(
+ client: AsyncOpenViking,
+):
+ session_a = client.session(session_id="multi_worker_append_lock_test")
+ await session_a.ensure_exists()
+ session_b = client.session(session_id=session_a.session_id)
+ await session_b.load()
+
+ await asyncio.gather(
+ asyncio.to_thread(session_a.add_message, "user", [TextPart("from worker a")]),
+ asyncio.to_thread(session_b.add_message, "user", [TextPart("from worker b")]),
+ )
+
+ fresh = client.session(session_id=session_a.session_id)
+ await fresh.load()
+ assert sorted(message.content for message in fresh.messages) == [
+ "from worker a",
+ "from worker b",
+ ]
+
+
+async def test_phase2_meta_merge_serializes_with_concurrent_append(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ initial = client.session(session_id="phase2_meta_append_lock_test")
+ await initial.add_message_async("user", [TextPart("first")])
+
+ phase2 = client.session(session_id=initial.session_id)
+ appending = client.session(session_id=initial.session_id)
+ await phase2.load()
+ await appending.load()
+
+ phase2_inside_save = asyncio.Event()
+ allow_phase2_save = asyncio.Event()
+ original_save_meta = phase2._save_meta
+
+ async def delayed_save_meta():
+ phase2_inside_save.set()
+ await allow_phase2_save.wait()
+ await original_save_meta()
+
+ monkeypatch.setattr(phase2, "_save_meta", delayed_save_meta)
+ merge_task = asyncio.create_task(
+ phase2._merge_and_save_commit_meta(
+ archive_index=1,
+ memories_extracted={},
+ telemetry_snapshot=None,
+ )
+ )
+ await phase2_inside_save.wait()
+
+ append_task = asyncio.create_task(
+ appending.add_message_async("assistant", [TextPart("second")])
+ )
+ await asyncio.sleep(0.05)
+ assert not append_task.done()
+
+ allow_phase2_save.set()
+ await asyncio.gather(merge_task, append_task)
+
+ fresh = client.session(session_id=initial.session_id)
+ await fresh.load()
+ assert [message.content for message in fresh.messages] == ["first", "second"]
+ assert fresh.meta.message_count == 2
+ assert fresh.meta.total_message_count == 2
+ assert fresh.meta.commit_count == 1
+
+
+async def test_add_waits_for_commit_root_rewrite_and_remains_live(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ committing = client.session(session_id="add_during_commit_lock_test")
+ committing.add_message("user", [TextPart("archive me")])
+ adding = client.session(session_id=committing.session_id)
+ await adding.load()
+ commit_inside_rewrite = asyncio.Event()
+ allow_commit_rewrite = asyncio.Event()
+ original_write = committing._write_to_agfs_async
+
+ async def delayed_root_write(messages):
+ commit_inside_rewrite.set()
+ await allow_commit_rewrite.wait()
+ await original_write(messages)
+
+ class CapturingQueueManager:
+ async def enqueue(self, *_args, **_kwargs):
+ return None
+
+ monkeypatch.setattr(committing, "_write_to_agfs_async", delayed_root_write)
+ monkeypatch.setattr(
+ "openviking.storage.queuefs.get_queue_manager",
+ lambda: CapturingQueueManager(),
+ )
+ disabled_policy = {
+ "working_memory": {"enabled": False},
+ "self": {"enabled": False},
+ "peer": {"enabled": False},
+ }
+
+ commit_task = asyncio.create_task(committing.commit_async(memory_policy=disabled_policy))
+ await commit_inside_rewrite.wait()
+ add_task = asyncio.create_task(
+ asyncio.to_thread(adding.add_message, "assistant", [TextPart("keep me live")])
+ )
+ await asyncio.sleep(0.05)
+ assert not add_task.done()
+ allow_commit_rewrite.set()
+ await asyncio.gather(commit_task, add_task)
+
+ fresh = client.session(session_id=committing.session_id)
+ await fresh.load()
+ context = await fresh.get_session_context()
+ assert [message.content for message in fresh.messages] == ["keep me live"]
+ assert [message["parts"][0]["text"] for message in context["messages"]] == [
+ "archive me",
+ "keep me live",
+ ]
+
+
+async def test_queue_enqueue_failure_marks_archive_failed_and_keeps_raw_logically_live(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="queue_enqueue_failure_recovery_test")
+ session.add_message("user", [TextPart("do not lose me")])
+
+ class FailingQueueManager:
+ async def enqueue(self, *_args, **_kwargs):
+ raise RuntimeError("queue unavailable")
+
+ monkeypatch.setattr(
+ "openviking.storage.queuefs.get_queue_manager",
+ lambda: FailingQueueManager(),
+ )
+
+ with pytest.raises(RuntimeError, match="queue unavailable"):
+ await session.commit_async()
+
+ states = await session._scan_archive_states()
+ context = await session.get_session_context()
+ failed = json.loads(
+ await session._viking_fs.read_file(
+ f"{states[0].archive_uri}/.failed.json",
+ ctx=session.ctx,
+ )
+ )
+ assert states[0].state == "failed"
+ assert failed["stage"] == "queue_enqueue"
+ assert [message["parts"][0]["text"] for message in context["messages"]] == ["do not lose me"]
+
+
+async def test_phase1_root_rewrite_failure_marks_orphan_archive_failed(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="phase1_root_failure_recovery_test")
+ session.add_message("user", [TextPart("archive candidate")])
+ session.add_message("assistant", [TextPart("retained tail")])
+ original_write = session._write_to_agfs_async
+
+ async def write_then_fail(messages):
+ await original_write(messages)
+ raise RuntimeError("synthetic root rewrite failure")
+
+ monkeypatch.setattr(session, "_write_to_agfs_async", write_then_fail)
+
+ with pytest.raises(RuntimeError, match="synthetic root rewrite failure"):
+ await session.commit_async(keep_recent_count=1)
+
+ states = await session._scan_archive_states()
+ failed = json.loads(
+ await session._viking_fs.read_file(
+ f"{states[0].archive_uri}/.failed.json",
+ ctx=session.ctx,
+ )
+ )
+ fresh = client.session(session_id=session.session_id)
+ await fresh.load()
+ context = await fresh.get_session_context()
+ assert states[0].state == "failed"
+ assert failed["stage"] == "phase1_persist"
+ assert [message["parts"][0]["text"] for message in context["messages"]] == [
+ "archive candidate",
+ "retained tail",
+ ]
+
+
+async def test_phase1_enqueues_before_root_rewrite_and_publishes_ready_last(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ session = client.session(session_id="phase1_publish_order_test")
+ session.add_message("user", [TextPart("archive me")])
+ observations: list[tuple[list[str], str]] = []
+
+ class InspectingQueueManager:
+ async def enqueue(self, _queue_name, data):
+ root = await session._read_live_messages_strict()
+ archive_uri = data["archive_uri"]
+ observations.append(
+ (
+ [message.content for message in root],
+ (await session._read_phase1_meta(archive_uri)).get("status", ""),
+ )
+ )
+
+ monkeypatch.setattr(
+ "openviking.storage.queuefs.get_queue_manager",
+ lambda: InspectingQueueManager(),
+ )
+
+ result = await session.commit_async()
+
+ assert observations == [(["archive me"], "preparing")]
+ assert (await session._read_phase1_meta(result["archive_uri"]))["status"] == "ready"
+ assert await session._read_live_messages_strict() == []
+
+
+async def test_interrupted_phase1_recovers_when_root_rewrite_is_durable(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="phase1_reconcile_durable_root_test")
+ original = [
+ _text_message("u1", "user", "archive me"),
+ _text_message("a1", "assistant", "retain me"),
+ ]
+ session._messages = original
+ await session._write_to_agfs_async(messages=original)
+ archive_uri = await _write_archive(session, 1, [original[0]])
+ await session._write_phase1_marker(
+ archive_uri,
+ queue_message={"task_id": "synthetic"},
+ original_messages=original,
+ archived_messages=[original[0]],
+ retained_messages=[original[1]],
+ keep_recent_count=1,
+ retention_mode=None,
+ keep_recent_turn_count=0,
+ retained_message_token_budget=0,
+ min_raw_tail_steps=1,
+ )
+ await session._write_to_agfs_async(messages=[original[1]])
+
+ assert await session._ensure_phase1_ready(archive_uri)
+ assert (await session._read_phase1_meta(archive_uri))["status"] == "ready"
+ assert session.meta.message_count == 1
+
+
+async def test_interrupted_phase1_before_root_rewrite_becomes_failed(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="phase1_reconcile_original_root_test")
+ original = [_text_message("u1", "user", "still live")]
+ session._messages = original
+ await session._write_to_agfs_async(messages=original)
+ archive_uri = await _write_archive(session, 1, original)
+ await session._write_phase1_marker(
+ archive_uri,
+ queue_message={"task_id": "synthetic"},
+ original_messages=original,
+ archived_messages=original,
+ retained_messages=[],
+ keep_recent_count=0,
+ retention_mode=None,
+ keep_recent_turn_count=0,
+ retained_message_token_budget=0,
+ min_raw_tail_steps=1,
+ )
+
+ assert not await session._ensure_phase1_ready(archive_uri)
+ states = await session._scan_archive_states()
+ context = await session.get_session_context()
+ assert states[0].state == "failed"
+ assert [message["id"] for message in context["messages"]] == ["u1"]
+
+
+async def test_stale_worker_uses_lock_snapshot_memory_policy_for_queue_message(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ stale_session = client.session(session_id="stale_memory_policy_snapshot_test")
+ stale_session.add_message("user", [TextPart("archive with persisted policy")])
+ updater = client.session(session_id=stale_session.session_id)
+ await updater.load()
+ updater.meta.memory_policy = {
+ "working_memory": {"enabled": False},
+ "self": {"enabled": False},
+ "peer": {"enabled": False},
+ }
+ await updater._save_meta()
+ queued: list[dict] = []
+
+ class CapturingQueueManager:
+ async def enqueue(self, _queue_name, data):
+ queued.append(data)
+
+ monkeypatch.setattr(
+ "openviking.storage.queuefs.get_queue_manager",
+ lambda: CapturingQueueManager(),
+ )
+
+ result = await stale_session.commit_async()
+
+ assert result["archived"] is True
+ assert queued[0]["memory_policy"] == updater.meta.memory_policy
diff --git a/tests/unit/usage_reporter/test_memory_usage_extractor.py b/tests/unit/usage_reporter/test_memory_usage_extractor.py
index ae21a7f69..8f46a49f3 100644
--- a/tests/unit/usage_reporter/test_memory_usage_extractor.py
+++ b/tests/unit/usage_reporter/test_memory_usage_extractor.py
@@ -301,10 +301,21 @@ async def test_memory_usage_extractor_replay_uses_stable_event_id():
extractor = MemoryUsageExtractor()
first = await extractor.extract(messages=messages, context=_context())
- replay = await extractor.extract(messages=messages, context=_context())
+ replay = await extractor.extract(
+ messages=messages,
+ context=UsageContext(
+ account_id="new",
+ user_id="test",
+ session_id="session-1",
+ archive_uri="viking://user/test/sessions/session-1/history/archive_002",
+ task_id="task-2",
+ ),
+ )
assert first[0].event_id
assert replay[0].event_id == first[0].event_id
+ assert replay[0].task_id == "task-2"
+ assert replay[0].evidence["archive_uri"].endswith("archive_002")
@pytest.mark.asyncio
diff --git a/web-studio/src/gen/ov-client/types.gen.ts b/web-studio/src/gen/ov-client/types.gen.ts
index a0e69785f..f044706ac 100644
--- a/web-studio/src/gen/ov-client/types.gen.ts
+++ b/web-studio/src/gen/ov-client/types.gen.ts
@@ -48,6 +48,18 @@ export type AddMessageRequest = {
* Created At
*/
created_at?: string | null;
+ /**
+ * Turn Id
+ */
+ turn_id?: string | null;
+ /**
+ * Message Kind
+ */
+ message_kind?: 'user_query' | 'assistant_step' | 'tool_transport' | 'checkpoint' | null;
+ /**
+ * Source Message Ids
+ */
+ source_message_ids?: Array<string> | null;
/**
* Telemetry
*/
@@ -257,6 +269,30 @@ export type CommitRequest = {
* Number of most-recent messages to keep live after commit. Plugin's afterTurn path typically passes its configured value (default 10); compact path passes 0 to archive everything.
*/
keep_recent_count?: number;
+ /**
+ * Retention Mode
+ *
+ * Opt in to logical Turn retention. Omit to preserve keep_recent_count semantics.
+ */
+ retention_mode?: 'turn_budget' | null;
+ /**
+ * Keep Recent Turn Count
+ *
+ * Maximum number of newest logical user Turns to retain.
+ */
+ keep_recent_turn_count?: number | null;
+ /**
+ * Retained Message Token Budget
+ *
+ * Token budget for retained raw messages and checkpoint.
+ */
+ retained_message_token_budget?: number | null;
+ /**
+ * Min Raw Tail Steps
+ *
+ * Minimum number of latest atomic assistant Steps kept raw.
+ */
+ min_raw_tail_steps?: number | null;
/**
* Telemetry
*/