Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(middleware): clear invalid compaction state

xf gong9dd8c392561b
diff --git a/cubepi/middleware/compaction/__init__.py b/cubepi/middleware/compaction/__init__.py
index 3a54b9b..8ac0eba 100644
--- a/cubepi/middleware/compaction/__init__.py
+++ b/cubepi/middleware/compaction/__init__.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import logging
from typing import Any
+from pydantic import ValidationError
+
from cubepi.agent.types import AgentContext
from cubepi.middleware.base import Middleware
from cubepi.middleware.compaction.boundary import safe_boundary
@@ -34,7 +36,10 @@ def _load_state(value: Any) -> CompactionState | None:
if isinstance(value, CompactionState):
return value
if isinstance(value, dict):
- return CompactionState.model_validate(value)
+ try:
+ return CompactionState.model_validate(value)
+ except ValidationError:
+ return None
return None
@@ -85,6 +90,9 @@ class CompactionMiddleware(Middleware):
) -> list[Message]:
state = _load_state(ctx.extra.get("compaction"))
boundary = int(ctx.extra.get("compaction_until_msg_index") or 0)
+ if state is None and ("compaction" in ctx.extra or boundary > 0):
+ boundary = 0
+ _clear_state(ctx)
if boundary >= len(messages) or not _state_matches_history(
messages, state, boundary
):
diff --git a/tests/middleware/test_compaction.py b/tests/middleware/test_compaction.py
index ed498a6..2616494 100644
--- a/tests/middleware/test_compaction.py
+++ b/tests/middleware/test_compaction.py
@@ -227,3 +227,23 @@ async def test_stale_boundary_from_replaced_history_is_ignored() -> None:
assert result == new_messages
assert "compaction" not in ctx.extra
assert "compaction_until_msg_index" not in ctx.extra
+
+
+async def test_malformed_persisted_state_is_cleared() -> None:
+ provider = _FakeSummaryProvider()
+ middleware = _make_middleware(provider, max_tokens_before=100_000)
+ messages: list[Message] = [_user("new question")]
+ ctx = AgentContext(
+ system_prompt="",
+ messages=messages,
+ extra={
+ "compaction": {},
+ "compaction_until_msg_index": 1,
+ },
+ )
+
+ result = await middleware.transform_context(messages, ctx=ctx)
+
+ assert result == messages
+ assert "compaction" not in ctx.extra
+ assert "compaction_until_msg_index" not in ctx.extra