Skip to content

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

fix(session): preserve cumulative checkpoints across archives (#3647)

DuTao63626814109a
diff --git a/docs/images/session/cumulative-checkpoint-v2.png b/docs/images/session/cumulative-checkpoint-v2.png
new file mode 100644
index 000000000..2bbc9092b
Binary files /dev/null and b/docs/images/session/cumulative-checkpoint-v2.png differ
diff --git a/openviking/session/session.py b/openviking/session/session.py
index 383dfd6d2..3508dbf21 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -74,6 +74,7 @@ _MEMORY_EXTRACTION_RETRY_MAX_DELAY_SECONDS = 8.0
_AGENT_TRAINING_REQUIRED_MEMORY_TYPES = frozenset({"cases", "trajectories"})
_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS = 30.0
_MEMORY_STEP_NAMES = ("long_term", "execution")
+_CUMULATIVE_CHECKPOINT_VERSION = 2
class _ArchiveMessagesCorruptError(ValueError):
@@ -286,8 +287,9 @@ WM_UPDATE_TOOL: Dict[str, Any] = {
"type": "array",
"items": {"type": "string"},
"description": (
- "When checkpoint sources are present, one concise continuation "
- "summary per checkpoint_source index, in ascending index order."
+ "When checkpoint sources are present, one bounded cumulative "
+ "continuation summary per checkpoint_source index, in ascending "
+ "index order."
),
},
},
@@ -316,8 +318,8 @@ WM_CREATE_WITH_CHECKPOINTS_TOOL: Dict[str, Any] = {
"type": "array",
"items": {"type": "string"},
"description": (
- "One concise continuation summary per checkpoint_source index, "
- "in ascending index order."
+ "One bounded cumulative continuation summary per checkpoint_source "
+ "index, in ascending index order."
),
},
},
@@ -334,6 +336,19 @@ class _CheckpointRequest:
source_message_ids: tuple[str, ...]
retained_message_token_budget: int
estimated_active_tokens: int
+ previous_checkpoint_abstract: str = ""
+ previous_checkpoint_source_message_ids: tuple[str, ...] = ()
+
+
+@dataclass(frozen=True)
+class _CheckpointSnapshot:
+ """Effective completed checkpoint state for one retained User Turn."""
+
+ turn_anchor_message_id: str
+ source_message_ids: tuple[str, ...]
+ abstract: str
+ archive_id: str
+ archive_uri: str
@dataclass(frozen=True)
@@ -2854,9 +2869,9 @@ class Session:
async def _collect_session_context_components(self) -> Dict[str, Any]:
"""Collect overview and messages by stopping at the newest terminal archive.
- Archive history grows without bound, so this read path deliberately never
- walks the whole history. It scans newest → oldest and stops at the first
- terminal marker (``.done`` or ``.failed.json``):
+ Archive history grows without bound, so the current-format read path scans
+ newest → oldest and stops at the first terminal marker (``.done`` or
+ ``.failed.json``):
- newest terminal is ``completed``: inject that archive's overview when
readable, plus raw messages from the newer non-terminal archives;
@@ -2865,12 +2880,14 @@ class Session:
- no terminal at all: no overview, every archive is still non-terminal
so all of their raw messages are returned.
- Nothing at or older than that terminal is read, which is a deliberate
- deviation from the RFC #3330 recovery formula: an uncovered ``failed``
- archive no longer replays its raw messages, and only the terminal
- archive's checkpoints are restored. Phase 2 coverage bookkeeping is
- unaffected because it keeps using the full ``_scan_archive_states()``
- scan. Public ``pre_archive_abstracts`` stay empty; abstracts are not read.
+ Nothing at or older than that terminal is normally read, which is a
+ deliberate deviation from the RFC #3330 recovery formula: an uncovered
+ ``failed`` archive no longer replays its raw messages. Cumulative v2
+ checkpoints are restored from the terminal archive alone; only a
+ terminal legacy v1 delta checkpoint invokes an older-history compatibility
+ scan. Phase 2 coverage bookkeeping is unaffected because it keeps using
+ the full ``_scan_archive_states()`` scan. Public
+ ``pre_archive_abstracts`` stay empty; abstracts are not read.
"""
archive_refs = await self._list_archive_refs()
newer_pending: List[Dict[str, Any]] = []
@@ -2924,10 +2941,11 @@ class Session:
archive["archive_uri"],
)
- merged_messages = self._stable_deduplicate_messages(
- archive_messages + list(self._messages)
+ merged_messages = self._stable_deduplicate_messages(archive_messages + list(self._messages))
+ merged_messages = await self._insert_terminal_checkpoints(
+ merged_messages,
+ terminal if terminal_state == "completed" else None,
)
- merged_messages = await self._insert_terminal_checkpoints(merged_messages, terminal)
return {
"latest_archive": latest_archive,
@@ -3271,6 +3289,147 @@ class Session:
except Exception:
return {}
+ @staticmethod
+ def _checkpoint_records_for_anchors(
+ meta: Dict[str, Any],
+ anchor_ids: set[str],
+ ) -> Dict[str, List[Dict[str, Any]]]:
+ """Return structurally valid checkpoint records grouped by requested anchor."""
+ grouped: Dict[str, List[Dict[str, Any]]] = {}
+ checkpoints = meta.get("checkpoints")
+ if not isinstance(checkpoints, list):
+ return grouped
+
+ 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 anchor_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 = tuple(item for item in source_ids if isinstance(item, str) and item)
+ if not valid_source_ids:
+ continue
+ raw_version = checkpoint.get("checkpoint_version", 1)
+ try:
+ checkpoint_version = max(1, int(raw_version))
+ except (TypeError, ValueError):
+ checkpoint_version = 1
+ grouped.setdefault(anchor_id, []).append(
+ {
+ "source_message_ids": valid_source_ids,
+ "abstract": abstract.strip(),
+ "checkpoint_version": checkpoint_version,
+ }
+ )
+ return grouped
+
+ async def _get_effective_completed_checkpoints(
+ self,
+ anchor_ids: set[str],
+ *,
+ before_archive_index: Optional[int] = None,
+ ) -> Dict[str, _CheckpointSnapshot]:
+ """Resolve completed checkpoint history for the requested retained Turns.
+
+ Version 2 records are cumulative, so the first one found while scanning
+ newest to oldest is authoritative. Version 1 records are deltas; they are
+ collected until a v2 base (or the beginning of history) and merged in
+ chronological order. This keeps new sessions bounded while preserving
+ legacy histories during migration.
+ """
+ if not anchor_ids:
+ return {}
+
+ histories: Dict[str, Dict[str, Any]] = {
+ anchor_id: {
+ "base": None,
+ "legacy_chunks": [],
+ "resolved": False,
+ }
+ for anchor_id in anchor_ids
+ }
+ refs = await self._get_completed_archive_refs(before_archive_index=before_archive_index)
+ for archive in refs: # newest → oldest
+ unresolved = {
+ anchor_id for anchor_id, history in histories.items() if not history["resolved"]
+ }
+ if not unresolved:
+ break
+ grouped = self._checkpoint_records_for_anchors(
+ await self._read_archive_meta(archive["archive_uri"]),
+ unresolved,
+ )
+ for anchor_id, records in grouped.items():
+ history = histories[anchor_id]
+ cumulative = [
+ record
+ for record in records
+ if record["checkpoint_version"] >= _CUMULATIVE_CHECKPOINT_VERSION
+ ]
+ if cumulative:
+ # A v2 record already includes every older compressed prefix.
+ record = cumulative[-1]
+ history["base"] = {
+ **record,
+ "archive_id": archive["archive_id"],
+ "archive_uri": archive["archive_uri"],
+ }
+ history["resolved"] = True
+ continue
+
+ history["legacy_chunks"].append(
+ {
+ "source_message_ids": tuple(
+ dict.fromkeys(
+ source_id
+ for record in records
+ for source_id in record["source_message_ids"]
+ )
+ ),
+ "abstract": "\n\n".join(record["abstract"] for record in records),
+ "archive_id": archive["archive_id"],
+ "archive_uri": archive["archive_uri"],
+ }
+ )
+
+ snapshots: Dict[str, _CheckpointSnapshot] = {}
+ for anchor_id, history in histories.items():
+ base = history["base"]
+ legacy_chunks = list(reversed(history["legacy_chunks"]))
+ chronological_chunks = ([base] if base else []) + legacy_chunks
+ if not chronological_chunks:
+ continue
+
+ source_message_ids: List[str] = []
+ abstracts: List[str] = []
+ for chunk in chronological_chunks:
+ seen = set(source_message_ids)
+ new_source_ids = [
+ source_id for source_id in chunk["source_message_ids"] if source_id not in seen
+ ]
+ if not new_source_ids:
+ continue
+ source_message_ids.extend(new_source_ids)
+ abstracts.append(chunk["abstract"])
+ if not source_message_ids or not abstracts:
+ continue
+
+ newest = history["legacy_chunks"][0] if history["legacy_chunks"] else base
+ snapshots[anchor_id] = _CheckpointSnapshot(
+ turn_anchor_message_id=anchor_id,
+ source_message_ids=tuple(source_message_ids),
+ abstract="\n\n".join(abstracts),
+ archive_id=newest["archive_id"],
+ archive_uri=newest["archive_uri"],
+ )
+ return snapshots
+
async def _collect_checkpoint_requests_for_phase2(
self,
archive_uri: str,
@@ -3386,7 +3545,29 @@ class Session:
message_order[source_id] for source_id in request.source_message_ids
)
)
- return requests
+ previous_by_anchor = await self._get_effective_completed_checkpoints(
+ {request.turn_anchor_message_id for request in requests},
+ before_archive_index=self._archive_index_from_uri(archive_uri),
+ )
+ return [
+ _CheckpointRequest(
+ turn_anchor_message_id=request.turn_anchor_message_id,
+ source_message_ids=request.source_message_ids,
+ retained_message_token_budget=request.retained_message_token_budget,
+ estimated_active_tokens=request.estimated_active_tokens,
+ previous_checkpoint_abstract=(
+ previous_by_anchor[request.turn_anchor_message_id].abstract
+ if request.turn_anchor_message_id in previous_by_anchor
+ else ""
+ ),
+ previous_checkpoint_source_message_ids=(
+ previous_by_anchor[request.turn_anchor_message_id].source_message_ids
+ if request.turn_anchor_message_id in previous_by_anchor
+ else ()
+ ),
+ )
+ for request in requests
+ ]
@staticmethod
def _build_checkpoint_records(
@@ -3419,8 +3600,16 @@ class Session:
raise ValueError("Checkpoint summary is empty after local token truncation")
records.append(
{
+ "checkpoint_version": _CUMULATIVE_CHECKPOINT_VERSION,
"turn_anchor_message_id": request.turn_anchor_message_id,
- "source_message_ids": list(request.source_message_ids),
+ "source_message_ids": list(
+ dict.fromkeys(
+ [
+ *request.previous_checkpoint_source_message_ids,
+ *request.source_message_ids,
+ ]
+ )
+ ),
"abstract": abstract,
"estimated_tokens": estimate_text_tokens(abstract),
}
@@ -3432,13 +3621,12 @@ class Session:
messages: List[Message],
terminal: Optional[Dict[str, Any]],
) -> List[Message]:
- """Insert the newest terminal archive's checkpoints after retained anchors.
+ """Insert completed checkpoints after their retained User anchors.
- Only that one archive is read so the cost stays independent of history
- length. A long User Turn committed partially more than once therefore
- keeps just its newest compressed prefix; earlier disjoint prefixes from
- older archives are not restored. Legacy archives without a
- ``checkpoints`` metadata field do not synthesize one from their overview.
+ New v2 checkpoints are cumulative, so the newest terminal archive is a
+ constant-cost first hit. A terminal v1 checkpoint triggers the legacy
+ compatibility scan and merges its older delta records chronologically.
+ Pending or failed terminal archives are never passed to this method.
"""
if not messages or terminal is None:
return messages
@@ -3446,41 +3634,37 @@ class Session:
message_ids = {message.id for message in messages}
candidates: Dict[str, Dict[str, Any]] = {}
meta = await self._read_archive_meta(terminal["archive_uri"])
- checkpoints = meta.get("checkpoints")
- if isinstance(checkpoints, list):
- 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
+ grouped = self._checkpoint_records_for_anchors(meta, message_ids)
+ legacy_anchor_ids: set[str] = set()
+ for anchor_id, records in grouped.items():
+ cumulative = [
+ record
+ for record in records
+ if record["checkpoint_version"] >= _CUMULATIVE_CHECKPOINT_VERSION
+ ]
+ if not cumulative:
+ legacy_anchor_ids.add(anchor_id)
+ continue
+ record = cumulative[-1]
+ candidates[anchor_id] = {
+ "archive_id": terminal["archive_id"],
+ "archive_uri": terminal["archive_uri"],
+ "source_message_ids": list(record["source_message_ids"]),
+ "abstract": record["abstract"],
+ }
- candidate = candidates.setdefault(
- anchor_id,
- {
- "archive_id": terminal["archive_id"],
- "archive_uri": terminal["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["source_message_ids"].extend(new_source_ids)
- candidate["abstracts"].append(abstract.strip())
+ if legacy_anchor_ids:
+ legacy = await self._get_effective_completed_checkpoints(
+ legacy_anchor_ids,
+ before_archive_index=terminal["index"] + 1,
+ )
+ for anchor_id, snapshot in legacy.items():
+ candidates[anchor_id] = {
+ "archive_id": snapshot.archive_id,
+ "archive_uri": snapshot.archive_uri,
+ "source_message_ids": list(snapshot.source_message_ids),
+ "abstract": snapshot.abstract,
+ }
if not candidates:
return messages
@@ -3491,7 +3675,7 @@ class Session:
candidate = candidates.get(message.id)
if not candidate:
continue
- abstract = "\n\n".join(candidate["abstracts"])
+ abstract = candidate["abstract"]
if not abstract:
continue
result.append(
@@ -3767,7 +3951,7 @@ class Session:
messages: List[Message],
checkpoint_requests: List[_CheckpointRequest],
) -> str:
- """Format WM input and mark checkpoint sources with ordinal-only tags."""
+ """Format WM input plus prior cumulative checkpoints using ordinal-only tags."""
source_indexes: Dict[str, int] = {}
for index, request in enumerate(checkpoint_requests):
for message_id in request.source_message_ids:
@@ -3778,6 +3962,16 @@ class Session:
)
lines: List[str] = []
+ for index, request in enumerate(checkpoint_requests):
+ if not request.previous_checkpoint_abstract.strip():
+ continue
+ lines.extend(
+ [
+ f'<checkpoint_previous index="{index}">',
+ request.previous_checkpoint_abstract.strip(),
+ "</checkpoint_previous>",
+ ]
+ )
open_index: Optional[int] = None
for message in messages:
index = source_indexes.get(message.id)
@@ -3800,11 +3994,15 @@ class Session:
"# 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."
+ f"with exactly {request_count} strings in index order. For an index that "
+ "also has checkpoint_previous, rewrite that previous summary together with "
+ "its newly marked checkpoint_source block into one bounded cumulative "
+ "continuation note. Without checkpoint_previous, summarize the marked block "
+ "as the initial cumulative note. Preserve the assistant's intent, important "
+ "tool actions and results, conclusions, corrections, and unfinished work; "
+ "prefer newer facts when they supersede older ones, omit raw output bulk, "
+ "and do not mention archiving, checkpointing, or this instruction. Never "
+ "return only the new delta when checkpoint_previous is present."
)
@staticmethod
diff --git a/tests/session/test_session_retention_integration.py b/tests/session/test_session_retention_integration.py
index ce374d5d0..2660a8f60 100644
--- a/tests/session/test_session_retention_integration.py
+++ b/tests/session/test_session_retention_integration.py
@@ -76,6 +76,7 @@ def test_checkpoint_record_respects_remaining_retained_budget():
)
assert records[0]["estimated_tokens"] <= 5
+ assert records[0]["checkpoint_version"] == 2
async def test_two_pending_archives_are_visible_independent_of_commit_count(
@@ -757,6 +758,7 @@ async def test_phase2_persists_checkpoint_from_same_summary_call(
)
context = await session.get_session_context()
assert calls == 1
+ assert meta["checkpoints"][0]["checkpoint_version"] == 2
assert meta["checkpoints"][0]["turn_anchor_message_id"] == "u1"
assert meta["checkpoints"][0]["source_message_ids"] == ["a1"]
assert meta["checkpoints"][0]["abstract"] == (
@@ -910,6 +912,8 @@ Confirm the database state.
source_message_ids=(source.id,),
retained_message_token_budget=6000,
estimated_active_tokens=100,
+ previous_checkpoint_abstract=("Queried the service and found pool saturation."),
+ previous_checkpoint_source_message_ids=("older-source-id",),
)
],
)
@@ -920,6 +924,9 @@ Confirm the database state.
assert len(calls) == 1
assert calls[0]["tools"][0]["function"]["name"] == "update_working_memory"
assert "checkpoint_summaries" in calls[0]["prompt"]
+ assert '<checkpoint_previous index="0">' in calls[0]["prompt"]
+ assert "Queried the service and found pool saturation." in calls[0]["prompt"]
+ assert "Never return only the new delta" in calls[0]["prompt"]
async def test_roll_forward_collects_multiple_checkpoint_requests(
@@ -978,6 +985,135 @@ async def test_roll_forward_collects_multiple_checkpoint_requests(
assert formatted.count('<checkpoint_source index="1">') == 1
+async def test_phase2_rolls_previous_cumulative_checkpoint_into_v2_record(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="cumulative_checkpoint_roll_forward_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ await _write_archive(
+ session,
+ 1,
+ [anchor, _text_message("a1", "assistant", "first archived step")],
+ overview="# Working Memory\n\n## Current State\nFirst prefix covered.",
+ meta={
+ "checkpoints": [
+ {
+ "checkpoint_version": 2,
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a1"],
+ "abstract": "Pool saturation was confirmed.",
+ "estimated_tokens": 7,
+ }
+ ]
+ },
+ done={"starting_message_id": "u1", "ending_message_id": "a1"},
+ )
+ current_source = _text_message("a2", "assistant", "second archived step")
+ current_uri = await _write_archive(
+ session,
+ 2,
+ [anchor, current_source],
+ meta={
+ "retention_plan": {
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a2"],
+ "retained_message_token_budget": 6000,
+ "estimated_active_tokens": 100,
+ }
+ },
+ )
+
+ requests = await session._collect_checkpoint_requests_for_phase2(
+ current_uri,
+ [],
+ [anchor, current_source],
+ )
+
+ assert len(requests) == 1
+ assert requests[0].source_message_ids == ("a2",)
+ assert requests[0].previous_checkpoint_source_message_ids == ("a1",)
+ assert requests[0].previous_checkpoint_abstract == "Pool saturation was confirmed."
+ records = session._build_checkpoint_records(
+ requests,
+ ("Pool saturation was confirmed; the network path was ruled out.",),
+ )
+ assert records == [
+ {
+ "checkpoint_version": 2,
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a1", "a2"],
+ "abstract": ("Pool saturation was confirmed; the network path was ruled out."),
+ "estimated_tokens": records[0]["estimated_tokens"],
+ }
+ ]
+
+
+async def test_phase2_migrates_legacy_checkpoint_deltas_to_cumulative_v2(
+ client: AsyncOpenViking,
+):
+ session = client.session(session_id="legacy_checkpoint_migration_test")
+ await session.ensure_exists()
+ anchor = _text_message("u1", "user", "investigate the outage")
+ for index, source_id, abstract in (
+ (1, "a1", "Pool saturation was confirmed."),
+ (2, "a2", "The network path was ruled out."),
+ ):
+ await _write_archive(
+ session,
+ index,
+ [anchor, _text_message(source_id, "assistant", f"archived step {index}")],
+ overview=f"# Working Memory\n\n## Current State\nPrefix {index} covered.",
+ meta={
+ "checkpoints": [
+ {
+ # Missing checkpoint_version means legacy delta semantics.
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": [source_id],
+ "abstract": abstract,
+ }
+ ]
+ },
+ done={"starting_message_id": "u1", "ending_message_id": source_id},
+ )
+ current_source = _text_message("a3", "assistant", "third archived step")
+ current_uri = await _write_archive(
+ session,
+ 3,
+ [anchor, current_source],
+ meta={
+ "retention_plan": {
+ "partial_turn": True,
+ "turn_anchor_message_id": "u1",
+ "checkpoint_source_message_ids": ["a3"],
+ "retained_message_token_budget": 6000,
+ "estimated_active_tokens": 100,
+ }
+ },
+ )
+
+ requests = await session._collect_checkpoint_requests_for_phase2(
+ current_uri,
+ [],
+ [anchor, current_source],
+ )
+
+ assert requests[0].previous_checkpoint_source_message_ids == ("a1", "a2")
+ assert requests[0].previous_checkpoint_abstract == (
+ "Pool saturation was confirmed.\n\nThe network path was ruled out."
+ )
+ record = session._build_checkpoint_records(
+ requests,
+ (
+ "Pool saturation was confirmed, the network was ruled out, "
+ "and the database remains under investigation.",
+ ),
+ )[0]
+ assert record["checkpoint_version"] == 2
+ assert record["source_message_ids"] == ["a1", "a2", "a3"]
+
+
async def test_checkpoint_request_rejects_user_or_cross_turn_sources(
client: AsyncOpenViking,
):
@@ -1203,14 +1339,59 @@ async def test_covered_failed_partial_turn_checkpoint_points_to_covering_overvie
assert checkpoint["source_message_ids"] == ["a1"]
-async def test_repeated_partial_commits_restore_only_newest_checkpoint(
+async def test_failed_terminal_checkpoint_metadata_is_never_restored(
client: AsyncOpenViking,
):
- """Terminal-stop keeps checkpoint reads O(1), so only archive_002 is restored.
+ session = client.session(session_id="failed_terminal_checkpoint_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", "completed prefix")],
+ overview="# Working Memory\n\n## Current State\nCompleted prefix.",
+ meta={
+ "checkpoints": [
+ {
+ "checkpoint_version": 2,
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a1"],
+ "abstract": "Completed prefix.",
+ }
+ ]
+ },
+ done={"starting_message_id": "u1", "ending_message_id": "a1"},
+ )
+ await _write_archive(
+ session,
+ 2,
+ [anchor, _text_message("a2", "assistant", "failed prefix")],
+ failed=True,
+ meta={
+ "checkpoints": [
+ {
+ "checkpoint_version": 2,
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a1", "a2"],
+ "abstract": "This incomplete checkpoint must not be visible.",
+ }
+ ]
+ },
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
- The earlier disjoint prefix from archive_001 is intentionally not merged
- anymore; restoring it would require walking the whole archive history.
- """
+ context = await session.get_session_context()
+
+ assert [message["id"] for message in context["messages"]] == ["u1", "a3"]
+ assert not any(message.get("message_kind") == "checkpoint" for message in context["messages"])
+
+
+async def test_repeated_legacy_partial_commits_merge_checkpoint_deltas(
+ client: AsyncOpenViking,
+):
+ """Legacy records have no version marker, so older deltas remain readable."""
session = client.session(session_id="repeated_partial_checkpoint_merge_test")
await session.ensure_exists()
anchor = _text_message("u1", "user", "investigate the outage")
@@ -1260,9 +1441,79 @@ async def test_repeated_partial_commits_restore_only_newest_checkpoint(
"a3",
]
checkpoint = context["messages"][1]
- assert checkpoint["source_message_ids"] == ["a2"]
+ assert checkpoint["source_message_ids"] == ["a1", "a2"]
assert checkpoint["parts"][0]["uri"] == second_uri
- assert checkpoint["parts"][0]["abstract"] == "Second prefix ruled out the network path."
+ assert checkpoint["parts"][0]["abstract"] == (
+ "First prefix found pool saturation.\n\nSecond prefix ruled out the network path."
+ )
+
+
+async def test_repeated_v2_partial_commits_restore_newest_cumulative_checkpoint_only(
+ client: AsyncOpenViking,
+ monkeypatch,
+):
+ """The newest v2 record is complete, so context does not read older archives."""
+ session = client.session(session_id="repeated_cumulative_checkpoint_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": [
+ {
+ "checkpoint_version": 2,
+ "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": [
+ {
+ "checkpoint_version": 2,
+ "turn_anchor_message_id": "u1",
+ "source_message_ids": ["a1", "a2"],
+ "abstract": ("Pool saturation was found, then the network path was ruled out."),
+ "estimated_tokens": 15,
+ }
+ ]
+ },
+ done={"starting_message_id": "u1", "ending_message_id": "a2"},
+ )
+ session._messages = [anchor, tail]
+ await session._write_to_agfs_async(messages=session._messages)
+
+ touched: list[str] = []
+ original_read_file = session._viking_fs.read_file
+
+ async def tracking_read_file(*args, **kwargs):
+ uri = args[0] if args else kwargs.get("uri")
+ touched.append(uri)
+ return await original_read_file(*args, **kwargs)
+
+ monkeypatch.setattr(session._viking_fs, "read_file", tracking_read_file)
+ context = await session.get_session_context()
+
+ checkpoint = context["messages"][1]
+ assert checkpoint["source_message_ids"] == ["a1", "a2"]
+ assert checkpoint["parts"][0]["uri"] == second_uri
+ assert checkpoint["parts"][0]["abstract"] == (
+ "Pool saturation was found, then the network path was ruled out."
+ )
+ assert not any(isinstance(uri, str) and "archive_001" in uri for uri in touched)
async def test_commit_externalizes_tool_outputs_across_the_whole_turn(