Skip to content

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

fix(session): batch Phase 2 extraction by auto-commit policy (#4644)

agentacdbd704169e
diff --git a/openviking/session/extraction_batch.py b/openviking/session/extraction_batch.py
new file mode 100644
index 000000000..9694e89cf
--- /dev/null
+++ b/openviking/session/extraction_batch.py
@@ -0,0 +1,161 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Phase 2 extraction batches derived from a session's auto-commit policy."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any, Iterable, List, Optional
+
+from openviking.message import Message
+from openviking.session.auto_commit_policy import AutoCommitPolicy
+from openviking.session.retention import UserTurn, build_turns
+
+
+@dataclass(frozen=True)
+class ExtractionBatchLimits:
+ max_message_tokens: Optional[int] = None
+ max_messages: Optional[int] = None
+
+ @property
+ def enabled(self) -> bool:
+ return self.max_message_tokens is not None or self.max_messages is not None
+
+
+@dataclass(frozen=True)
+class ExtractionMessageBatch:
+ messages: tuple[Message, ...]
+ estimated_tokens: int
+ oversized: bool = False
+
+
+def resolve_extraction_batch_limits(auto_commit_policy: Any) -> ExtractionBatchLimits:
+ if not isinstance(auto_commit_policy, dict) or not auto_commit_policy:
+ return ExtractionBatchLimits()
+ policy = AutoCommitPolicy.from_dict(auto_commit_policy)
+ return ExtractionBatchLimits(
+ max_message_tokens=(
+ policy.pending_token_threshold if policy.pending_token_threshold > 0 else None
+ ),
+ max_messages=(
+ policy.message_count_threshold if policy.message_count_threshold > 0 else None
+ ),
+ )
+
+
+def estimate_extraction_message_tokens(messages: Iterable[Message]) -> int:
+ return sum(int(message.estimated_tokens or 0) for message in messages)
+
+
+def _exceeds_limits(
+ *,
+ message_count: int,
+ estimated_tokens: int,
+ limits: ExtractionBatchLimits,
+) -> bool:
+ return bool(
+ (limits.max_message_tokens is not None and estimated_tokens > limits.max_message_tokens)
+ or (limits.max_messages is not None and message_count > limits.max_messages)
+ )
+
+
+def _turn_units(turn: UserTurn, limits: ExtractionBatchLimits) -> List[List[Message]]:
+ messages = list(turn.messages)
+ if not _exceeds_limits(
+ message_count=len(messages),
+ estimated_tokens=estimate_extraction_message_tokens(messages),
+ limits=limits,
+ ):
+ return [messages]
+
+ units: List[List[Message]] = []
+ if turn.anchor is not None:
+ units.append([turn.anchor])
+ for step in turn.steps:
+ step_messages = list(step.messages)
+ if _exceeds_limits(
+ message_count=len(step_messages),
+ estimated_tokens=estimate_extraction_message_tokens(step_messages),
+ limits=limits,
+ ):
+ units.extend([[message] for message in step_messages])
+ elif step_messages:
+ units.append(step_messages)
+ return units or [messages]
+
+
+def plan_extraction_batches(
+ messages: List[Message],
+ limits: ExtractionBatchLimits,
+) -> List[ExtractionMessageBatch]:
+ if not messages:
+ return []
+ if not limits.enabled:
+ return [
+ ExtractionMessageBatch(
+ messages=tuple(messages),
+ estimated_tokens=estimate_extraction_message_tokens(messages),
+ )
+ ]
+
+ units = [unit for turn in build_turns(messages) for unit in _turn_units(turn, limits)]
+ batches: List[ExtractionMessageBatch] = []
+ current: List[Message] = []
+ current_tokens = 0
+
+ def flush() -> None:
+ nonlocal current, current_tokens
+ if not current:
+ return
+ batches.append(
+ ExtractionMessageBatch(
+ messages=tuple(current),
+ estimated_tokens=current_tokens,
+ oversized=_exceeds_limits(
+ message_count=len(current),
+ estimated_tokens=current_tokens,
+ limits=limits,
+ ),
+ )
+ )
+ current = []
+ current_tokens = 0
+
+ for unit in units:
+ if not unit:
+ continue
+ unit_tokens = estimate_extraction_message_tokens(unit)
+ if current and _exceeds_limits(
+ message_count=len(current) + len(unit),
+ estimated_tokens=current_tokens + unit_tokens,
+ limits=limits,
+ ):
+ flush()
+ if _exceeds_limits(
+ message_count=len(unit),
+ estimated_tokens=unit_tokens,
+ limits=limits,
+ ):
+ flush()
+ batches.append(
+ ExtractionMessageBatch(
+ messages=tuple(unit),
+ estimated_tokens=unit_tokens,
+ oversized=True,
+ )
+ )
+ continue
+ current.extend(unit)
+ current_tokens += unit_tokens
+
+ flush()
+ return batches
+
+
+__all__ = [
+ "ExtractionBatchLimits",
+ "ExtractionMessageBatch",
+ "estimate_extraction_message_tokens",
+ "plan_extraction_batches",
+ "resolve_extraction_batch_limits",
+]
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 972f3e89a..8776cdaaa 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -23,9 +23,16 @@ from openviking.pyagfs.exceptions import AGFSClientError, AGFSHTTPError, AGFSNot
from openviking.server.config import ToolOutputExternalizationConfig
from openviking.server.identity import RequestContext, Role
from openviking.session.auto_commit_policy import AutoCommitPolicy
+from openviking.session.extraction_batch import (
+ ExtractionBatchLimits,
+ ExtractionMessageBatch,
+ estimate_extraction_message_tokens,
+ plan_extraction_batches,
+ resolve_extraction_batch_limits,
+)
from openviking.session.memory.constants import AGENT_EVOLUTION_MEMORY_TYPES
-from openviking.session.memory_policy import MemoryPolicy
from openviking.session.memory.utils.language import resolve_output_language_from_conversation
+from openviking.session.memory_policy import MemoryPolicy
from openviking.session.retention import (
RETENTION_MODE_TURN_BUDGET,
RetentionPlan,
@@ -106,6 +113,12 @@ def _redact_inline_images(text: str) -> str:
return _B64_JSON_RE.sub(replace_b64_json, _INLINE_IMAGE_DATA_URL_RE.sub(replace_data_url, text))
+def _load_render_prompt() -> Callable[..., str]:
+ from openviking.prompts import render_prompt
+
+ return render_prompt
+
+
def _redact_inline_images_from_tool_outputs(messages: List[Message]) -> List[Message]:
for message in messages:
for part in message.parts:
@@ -2104,6 +2117,7 @@ class Session:
usage_uris=list(dict.fromkeys(u.uri for u in usage_snapshot if u.uri)),
record_auto_commit_success=record_auto_commit_success,
event_search_tags=list(effective_event_tags),
+ auto_commit_policy=dict(self._meta.auto_commit_policy or {}),
)
phase1_stage = "phase1_persist"
try:
@@ -2375,6 +2389,7 @@ class Session:
user_config_error=user_config_error,
record_auto_commit_success=msg.record_auto_commit_success,
event_search_tags=list(msg.event_search_tags or []),
+ auto_commit_policy=msg.auto_commit_policy,
)
return True
@@ -2400,6 +2415,95 @@ class Session:
)
return await reporter.extract_and_report(messages=messages, context=context)
+ async def _extract_long_term_memories_with_batching(
+ self,
+ *,
+ messages: List[Message],
+ limits: ExtractionBatchLimits,
+ archive_uri: str,
+ extract_batch: Callable[[List[Message]], Awaitable[Any]],
+ record_batch: Callable[
+ [str, str, List[Message], Callable[[], Awaitable[Any]]],
+ Awaitable[Any],
+ ],
+ ) -> Any:
+ batches = plan_extraction_batches(messages, limits)
+ if not batches:
+ return []
+
+ logger.info(
+ "Processing Phase 2 long-term memory extraction in %s planned batches "
+ "for %s estimated tokens",
+ len(batches),
+ estimate_extraction_message_tokens(messages),
+ )
+ contexts: List[Any] = []
+ skills: List[Dict[str, Any]] = []
+ memory_diffs: List[Dict[str, Any]] = []
+ previous_diff_raw = ""
+ if self._viking_fs:
+ try:
+ previous_diff_raw = await self._viking_fs.read_file(
+ f"{archive_uri}/memory_diff.json",
+ ctx=self.ctx,
+ )
+ previous_diff = json.loads(previous_diff_raw or "{}")
+ if isinstance(previous_diff, dict):
+ memory_diffs.append(previous_diff)
+ except Exception as exc:
+ if not _is_storage_not_found(exc):
+ raise
+ previous_diff_raw = ""
+
+ for batch_number, batch in enumerate(batches, start=1):
+ batch_messages = list(batch.messages)
+
+ async def _extract_and_merge(
+ batch_messages: List[Message] = batch_messages,
+ ) -> Any:
+ nonlocal previous_diff_raw
+ result = await extract_batch(batch_messages)
+ if not self._viking_fs:
+ return result
+ try:
+ current_diff_raw = await self._viking_fs.read_file(
+ f"{archive_uri}/memory_diff.json",
+ ctx=self.ctx,
+ )
+ if current_diff_raw != previous_diff_raw:
+ current_diff = json.loads(current_diff_raw or "{}")
+ if isinstance(current_diff, dict):
+ memory_diffs.append(current_diff)
+ await self._session_compressor._write_final_memory_diff(
+ archive_uri=archive_uri,
+ ctx=self.ctx,
+ memory_diffs=memory_diffs,
+ )
+ previous_diff_raw = await self._viking_fs.read_file(
+ f"{archive_uri}/memory_diff.json",
+ ctx=self.ctx,
+ )
+ except Exception as exc:
+ if not _is_storage_not_found(exc):
+ raise
+ return result
+
+ result = await record_batch(
+ f"long_term_memory_extraction_batch_{batch_number}",
+ "long_term",
+ batch_messages,
+ _extract_and_merge,
+ )
+ if isinstance(result, dict):
+ contexts.extend(result.get("contexts", []))
+ skills.extend(result.get("session_skills", []))
+ else:
+ contexts.extend(result or [])
+
+ if skills:
+ return {"contexts": contexts, "session_skills": skills}
+ return contexts
+
@tracer("session.commit.phase2", ignore_result=True, ignore_args=True)
async def _run_memory_extraction(
self,
@@ -2415,6 +2519,7 @@ class Session:
user_config_error: Optional[str] = None,
record_auto_commit_success: bool = False,
event_search_tags: Optional[List[str]] = None,
+ auto_commit_policy: Optional[Dict[str, Any]] = None,
) -> None:
"""Phase 2: Extract memories and enqueue semantic work in the background."""
from openviking.service.task_tracker import get_task_tracker
@@ -2458,6 +2563,7 @@ class Session:
with bind_telemetry(telemetry):
ov_config = get_openviking_config()
effective_policy = MemoryPolicy.from_dict(memory_policy)
+ extraction_batch_limits = resolve_extraction_batch_limits(auto_commit_policy)
working_memory_enabled = effective_policy.working_memory_enabled
checkpoint_requests = (
await self._collect_checkpoint_requests_for_phase2(
@@ -2497,10 +2603,21 @@ class Session:
}
if checkpoint_requests:
summary_kwargs["checkpoint_requests"] = checkpoint_requests
- generated = await self._generate_archive_summary_async(
+ summary_batches = plan_extraction_batches(
extraction_messages,
- **summary_kwargs,
+ extraction_batch_limits,
)
+ if checkpoint_requests or len(summary_batches) <= 1:
+ generated = await self._generate_archive_summary_async(
+ extraction_messages,
+ **summary_kwargs,
+ )
+ else:
+ generated = await self._generate_archive_summary_with_batching(
+ summary_batches,
+ limits=extraction_batch_limits,
+ **summary_kwargs,
+ )
summary_result = (
generated
if isinstance(generated, _ArchiveSummaryResult)
@@ -2644,13 +2761,15 @@ class Session:
if self._session_compressor and long_term_has_work:
- async def _run_long_term_memory_extraction() -> Any:
- # strict_extract_errors=True lets transient failures
- # surface so _run_retryable_phase2_step can retry them
- # (and so a final failure is recorded as a skipped
- # archive instead of silently dropping the memory).
+ async def _run_long_term_memory_extraction(
+ batch_messages: Optional[List[Message]] = None,
+ ) -> Any:
return await self._session_compressor.extract_long_term_memories(
- messages=long_term_messages,
+ messages=(
+ long_term_messages
+ if batch_messages is None
+ else batch_messages
+ ),
user=self.user,
session_id=self.session_id,
ctx=self.ctx,
@@ -2665,14 +2784,25 @@ class Session:
event_search_tags=event_search_tags,
)
- extraction_tasks.append(
- _run_recorded_memory_step(
- "long_term_memory_extraction",
- "long_term",
- long_term_messages,
- _run_long_term_memory_extraction,
+ if extraction_batch_limits.enabled:
+ extraction_tasks.append(
+ self._extract_long_term_memories_with_batching(
+ messages=long_term_messages,
+ limits=extraction_batch_limits,
+ archive_uri=archive_uri,
+ extract_batch=_run_long_term_memory_extraction,
+ record_batch=_run_recorded_memory_step,
+ )
+ )
+ else:
+ extraction_tasks.append(
+ _run_recorded_memory_step(
+ "long_term_memory_extraction",
+ "long_term",
+ long_term_messages,
+ _run_long_term_memory_extraction,
+ )
)
- )
extraction_labels.append("long_term")
_results = await asyncio.gather(
@@ -4210,6 +4340,50 @@ class Session:
)
return tuple(raw)
+ async def _generate_archive_summary_with_batching(
+ self,
+ batches: List[ExtractionMessageBatch],
+ *,
+ latest_archive_overview: str,
+ limits: ExtractionBatchLimits,
+ ) -> str:
+ messages = [message for batch in batches for message in batch.messages]
+ vlm = get_openviking_config().vlm
+ if not (vlm and vlm.is_available()):
+ return await self._generate_archive_summary_async(
+ messages,
+ latest_archive_overview=latest_archive_overview,
+ )
+ try:
+ _load_render_prompt()
+ except Exception:
+ return await self._generate_archive_summary_async(
+ messages,
+ latest_archive_overview=latest_archive_overview,
+ )
+
+ logger.info(
+ "Processing Phase 2 Working Memory extraction in %s planned batches "
+ "using auto-commit limits tokens=%s messages=%s",
+ len(batches),
+ limits.max_message_tokens,
+ limits.max_messages,
+ )
+ current_overview = latest_archive_overview
+
+ for batch in batches:
+ batch_messages = list(batch.messages)
+ generated = await self._generate_archive_summary_async(
+ batch_messages,
+ latest_archive_overview=current_overview,
+ )
+ current_overview = (
+ generated.overview
+ if isinstance(generated, _ArchiveSummaryResult)
+ else str(generated or "")
+ )
+ return current_overview
+
async def _generate_archive_summary_async(
self,
messages: List[Message],
@@ -4262,7 +4436,7 @@ class Session:
)
try:
- from openviking.prompts import render_prompt
+ render_prompt = _load_render_prompt()
except Exception as e:
if checkpoint_requests:
raise RuntimeError("Prompt module is required to generate checkpoints") from e
diff --git a/openviking/storage/queuefs/session_commit_msg.py b/openviking/storage/queuefs/session_commit_msg.py
index b4ab6170f..a68460398 100644
--- a/openviking/storage/queuefs/session_commit_msg.py
+++ b/openviking/storage/queuefs/session_commit_msg.py
@@ -21,6 +21,7 @@ class SessionCommitMsg:
# Resolved custom scalar tags to attach to event memories extracted in this
# commit. Already normalized by the producer; empty means "no tags".
event_search_tags: List[str] = field(default_factory=list)
+ auto_commit_policy: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
diff --git a/tests/session/test_session_commit.py b/tests/session/test_session_commit.py
index 640633d34..0ebe11fd1 100644
--- a/tests/session/test_session_commit.py
+++ b/tests/session/test_session_commit.py
@@ -115,6 +115,45 @@ class TestCommit:
# Wait for semantic/embedding queues
await service.resources.wait_processed(timeout=60.0)
+ async def test_phase2_splits_with_the_committed_auto_commit_policy(
+ self,
+ session_with_messages: Session,
+ monkeypatch,
+ ):
+ await session_with_messages.update_config(
+ auto_commit_policy={
+ "pending_token_threshold": 0,
+ "message_count_threshold": 1,
+ },
+ update_auto_commit_policy=True,
+ )
+ working_memory_batches = []
+
+ async def generate_summary(
+ _session,
+ messages,
+ latest_archive_overview="",
+ checkpoint_requests=None,
+ ):
+ del checkpoint_requests
+ working_memory_batches.append([message.id for message in messages])
+ return f"{latest_archive_overview}\n{messages[0].id}"
+
+ monkeypatch.setattr(Session, "_generate_archive_summary_async", generate_summary)
+ extract_long_term = AsyncMock(return_value=[])
+ session_with_messages._session_compressor.extract_long_term_memories = extract_long_term
+
+ result = await session_with_messages.commit_async()
+ task_result = await _wait_for_task(result["task_id"])
+
+ assert task_result["status"] == "completed"
+ assert len(working_memory_batches) == 4
+ assert all(len(batch) == 1 for batch in working_memory_batches)
+ assert extract_long_term.await_count == 4
+ assert all(len(call.kwargs["messages"]) == 1 for call in extract_long_term.await_args_list)
+ phase1 = await session_with_messages._read_phase1_meta(result["archive_uri"])
+ assert phase1["queue_message"]["auto_commit_policy"]["message_count_threshold"] == 1
+
async def test_commit_task_reports_intentionally_skipped_memory_operations(
self,
session_with_messages: Session,
diff --git a/tests/unit/session/test_extraction_batch.py b/tests/unit/session/test_extraction_batch.py
new file mode 100644
index 000000000..2a3dabc36
--- /dev/null
+++ b/tests/unit/session/test_extraction_batch.py
@@ -0,0 +1,186 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.message import Message, TextPart
+from openviking.session.extraction_batch import (
+ ExtractionBatchLimits,
+ plan_extraction_batches,
+ resolve_extraction_batch_limits,
+)
+from openviking.session.session import Session
+
+
+def _message(message_id: str, role: str = "user", text: str = "content") -> Message:
+ return Message(id=message_id, role=role, parts=[TextPart(text)])
+
+
+def test_auto_commit_policy_resolves_phase2_batch_limits():
+ limits = resolve_extraction_batch_limits(
+ {
+ "pending_token_threshold": 8000,
+ "message_count_threshold": 40,
+ }
+ )
+
+ assert limits == ExtractionBatchLimits(max_message_tokens=8000, max_messages=40)
+ assert resolve_extraction_batch_limits(None).enabled is False
+ assert resolve_extraction_batch_limits({}).enabled is False
+
+
+def test_phase2_batches_split_an_oversized_batch_by_message_count():
+ messages = [_message(f"m{index}") for index in range(5)]
+
+ batches = plan_extraction_batches(
+ messages,
+ ExtractionBatchLimits(max_messages=2),
+ )
+
+ assert [[message.id for message in batch.messages] for batch in batches] == [
+ ["m0", "m1"],
+ ["m2", "m3"],
+ ["m4"],
+ ]
+
+
+def test_phase2_batches_split_an_oversized_batch_by_token_count():
+ messages = [_message(f"m{index}", text="word " * 80) for index in range(3)]
+ one_message_tokens = messages[0].estimated_tokens
+
+ batches = plan_extraction_batches(
+ messages,
+ ExtractionBatchLimits(max_message_tokens=one_message_tokens),
+ )
+
+ assert [[message.id for message in batch.messages] for batch in batches] == [
+ ["m0"],
+ ["m1"],
+ ["m2"],
+ ]
+ assert all(batch.estimated_tokens <= one_message_tokens for batch in batches)
+
+
+def test_phase2_batches_keep_a_turn_together_when_it_fits():
+ messages = [
+ _message("u1", text="question"),
+ _message("a1", role="assistant", text="answer"),
+ _message("u2", text="next"),
+ _message("a2", role="assistant", text="done"),
+ ]
+
+ batches = plan_extraction_batches(
+ messages,
+ ExtractionBatchLimits(max_messages=2),
+ )
+
+ assert [[message.id for message in batch.messages] for batch in batches] == [
+ ["u1", "a1"],
+ ["u2", "a2"],
+ ]
+
+
+async def test_working_memory_batches_carry_the_previous_summary_forward():
+ session = Session(viking_fs=None)
+ messages = [_message("u1"), _message("u2"), _message("u3")]
+ calls = []
+
+ async def generate(batch, latest_archive_overview="", checkpoint_requests=None):
+ calls.append(
+ (
+ [message.id for message in batch],
+ latest_archive_overview,
+ list(checkpoint_requests or []),
+ )
+ )
+ return f"{latest_archive_overview}|{batch[0].id}"
+
+ session._generate_archive_summary_async = AsyncMock(side_effect=generate)
+
+ limits = ExtractionBatchLimits(max_messages=1)
+ result = await session._generate_archive_summary_with_batching(
+ plan_extraction_batches(messages, limits),
+ latest_archive_overview="previous",
+ limits=limits,
+ )
+
+ assert result == "previous|u1|u2|u3"
+ assert [(ids, previous) for ids, previous, _ in calls] == [
+ (["u1"], "previous"),
+ (["u2"], "previous|u1"),
+ (["u3"], "previous|u1|u2"),
+ ]
+
+
+async def test_working_memory_no_vlm_fallback_uses_all_messages(monkeypatch):
+ session = Session(viking_fs=None)
+ messages = [_message("u1"), _message("u2"), _message("u3")]
+ config = type("Config", (), {"vlm": None})()
+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)
+
+ limits = ExtractionBatchLimits(max_messages=1)
+ result = await session._generate_archive_summary_with_batching(
+ plan_extraction_batches(messages, limits),
+ latest_archive_overview="",
+ limits=limits,
+ )
+
+ assert result == "# Session Summary\n\n**Overview**: 3 turns, 3 messages"
+
+
+async def test_working_memory_prompt_fallback_uses_all_messages(monkeypatch):
+ session = Session(viking_fs=None)
+ messages = [_message("u1"), _message("u2"), _message("u3")]
+ vlm = type("VLM", (), {"is_available": lambda self: True})()
+ config = type("Config", (), {"vlm": vlm})()
+ monkeypatch.setattr("openviking.session.session.get_openviking_config", lambda: config)
+
+ def unavailable_prompt():
+ raise ImportError("prompt module unavailable")
+
+ monkeypatch.setattr("openviking.session.session._load_render_prompt", unavailable_prompt)
+
+ limits = ExtractionBatchLimits(max_messages=1)
+ result = await session._generate_archive_summary_with_batching(
+ plan_extraction_batches(messages, limits),
+ latest_archive_overview="",
+ limits=limits,
+ )
+
+ assert result == "# Session Summary\n\n**Overview**: 3 turns, 3 messages"
+
+
+async def test_long_term_memory_batches_follow_the_planned_limit():
+ session = Session(viking_fs=None)
+ messages = [_message("u1"), _message("u2"), _message("u3")]
+ recorded_batches = []
+
+ async def extract(batch):
+ return [batch[0].id]
+
+ async def record(operation_name, step, batch, fn):
+ result = await fn()
+ recorded_batches.append((operation_name, step, [message.id for message in batch]))
+ return result
+
+ result = await session._extract_long_term_memories_with_batching(
+ messages=messages,
+ limits=ExtractionBatchLimits(max_messages=1),
+ archive_uri="viking://user/default/sessions/s1/history/archive_001",
+ extract_batch=extract,
+ record_batch=record,
+ )
+
+ assert result == ["u1", "u2", "u3"]
+ assert [message_ids for _, _, message_ids in recorded_batches] == [
+ ["u1"],
+ ["u2"],
+ ["u3"],
+ ]
+ assert all(step == "long_term" for _, step, _ in recorded_batches)
diff --git a/tests/unit/session/test_session_commit_resume.py b/tests/unit/session/test_session_commit_resume.py
index a58a99c65..0aa929072 100644
--- a/tests/unit/session/test_session_commit_resume.py
+++ b/tests/unit/session/test_session_commit_resume.py
@@ -1,7 +1,9 @@
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
+import inspect
import json
+from dataclasses import fields
from unittest.mock import AsyncMock
import pytest
@@ -49,6 +51,13 @@ class _MemoryVikingFS:
self.files[uri] = content
+def test_phase2_auto_commit_policy_parameters_are_appended():
+ signature = inspect.signature(Session._run_memory_extraction)
+
+ assert list(signature.parameters)[-1] == "auto_commit_policy"
+ assert fields(SessionCommitMsg)[-1].name == "auto_commit_policy"
+
+
@pytest.mark.asyncio
async def test_resume_queued_commit_continues_phase2(monkeypatch):
session_uri = "viking://user/default/sessions/session-1"
@@ -74,6 +83,7 @@ async def test_resume_queued_commit_continues_phase2(monkeypatch):
archive_uri=archive_uri,
user={"account_id": "default", "user_id": "default"},
memory_policy={"memory_types": []},
+ auto_commit_policy={"pending_token_threshold": 8000},
)
try:
@@ -84,6 +94,9 @@ async def test_resume_queued_commit_continues_phase2(monkeypatch):
session._run_memory_extraction.assert_awaited_once()
assert session._run_memory_extraction.await_args.kwargs["task_id"] == "task-1"
assert session._run_memory_extraction.await_args.kwargs["agent_evolution_enabled"] is True
+ assert session._run_memory_extraction.await_args.kwargs["auto_commit_policy"] == {
+ "pending_token_threshold": 8000
+ }
assert [
item.id for item in session._run_memory_extraction.await_args.kwargs["messages"]
] == ["archived"]
@@ -210,4 +223,5 @@ def test_session_commit_message_ignores_unknown_fields():
)
assert message.task_id == "task-1"
+ assert message.auto_commit_policy == {}
assert "actor_peer_id" not in message.to_dict()