From 6b1460281d8e6a881f29e1874af58d9b03b9088b Mon Sep 17 00:00:00 2001 From: AsherDLL Date: Thu, 27 Aug 2026 17:25:09 -0700 Subject: [PATCH 1/4] fix(context): persist budget checkpoint under the canonical state key enforce_context_budget wrote the hard-limit checkpoint under "context_budget:checkpoint", but make_checkpoint_recorder reads SessionKeys.CONTEXT_CHECKPOINT ("_runtime:context_checkpoint"), so the after-agent recorder never saw a real budget checkpoint and it was never persisted. Bind CHECKPOINT_STATE_KEY to the canonical session key so the writer and reader agree; the payload shape was already compatible. Adds a writer->reader regression test. --- src/arema/runtime/context/budget.py | 7 ++- tests/unit/runtime/test_context_budget.py | 53 +++++++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/arema/runtime/context/budget.py b/src/arema/runtime/context/budget.py index 9554ace..d27161c 100644 --- a/src/arema/runtime/context/budget.py +++ b/src/arema/runtime/context/budget.py @@ -28,6 +28,7 @@ from arema.core.config import Settings, get_settings from arema.core.logging import get_logger +from arema.runtime.sessions import SessionKeys if TYPE_CHECKING: from collections.abc import Sequence @@ -51,8 +52,10 @@ _TEXT_TRUNCATE_MIN_LENGTH = 500 _TEXT_TRUNCATE_PREFIX_CHARS = 200 -# Session-state key under which a hard-limit checkpoint is recorded. -CHECKPOINT_STATE_KEY = "context_budget:checkpoint" +# Session-state key under which a hard-limit checkpoint is recorded. Must be the +# canonical key the after-agent recorder reads, or the checkpoint is never +# persisted (see runtime/services.py:make_checkpoint_recorder). +CHECKPOINT_STATE_KEY = SessionKeys.CONTEXT_CHECKPOINT class ContextPressure(StrEnum): diff --git a/tests/unit/runtime/test_context_budget.py b/tests/unit/runtime/test_context_budget.py index 42977dd..2cd510f 100644 --- a/tests/unit/runtime/test_context_budget.py +++ b/tests/unit/runtime/test_context_budget.py @@ -11,6 +11,7 @@ from google.genai.types import Content, FunctionCall, FunctionResponse, Part from arema.core.config import Settings +from arema.memory.models import CheckpointRecord from arema.runtime.context.budget import ( CHECKPOINT_STATE_KEY, ContextPressure, @@ -20,6 +21,8 @@ enforce_context_budget, estimate_tokens, ) +from arema.runtime.services import make_checkpoint_recorder +from arema.runtime.sessions import SessionKeys # --------------------------------------------------------------------------- # Helpers @@ -54,6 +57,19 @@ def _settings(**overrides: object) -> Settings: _LONG_TEXT = "A" * 600 +class _RecordingCheckpointSink: + """Capture ``append_checkpoint`` calls for the writer->reader regression.""" + + def __init__(self) -> None: + self.calls: list[tuple[str, CheckpointRecord]] = [] + + def append_checkpoint( + self, scope_id: str, checkpoint: CheckpointRecord, *, source: str + ) -> None: + del source + self.calls.append((scope_id, checkpoint)) + + # --------------------------------------------------------------------------- # estimate_tokens # --------------------------------------------------------------------------- @@ -445,3 +461,40 @@ async def test_checkpoint_still_terminates_when_state_write_is_unavailable(self) result = await enforce_context_budget(callback_context, llm_request) assert isinstance(result, LlmResponse) + + async def test_budget_checkpoint_reaches_the_after_agent_recorder(self) -> None: + """Regression: the key budget writes is the key the recorder reads. + + Before the fix the writer used ``context_budget:checkpoint`` while the + recorder read ``SessionKeys.CONTEXT_CHECKPOINT``, so no budget checkpoint + was ever persisted. + """ + settings = _settings(context_budget_tokens=10_000) + contents = [ + _make_content( + [ + _make_func_response_part( + {"result": "[Compacted] search completed. done."}, name="search" + ) + ] + ) + ] + llm_request = SimpleNamespace(contents=contents) + state: dict[str, object] = {SessionKeys.MEMORY_SCOPE_ID: "scope-1"} + callback_context = SimpleNamespace(state=state) + + with ( + mock.patch("arema.runtime.context.budget.get_settings", return_value=settings), + mock.patch("arema.runtime.context.budget.estimate_tokens", return_value=9_500), + ): + await enforce_context_budget(callback_context, llm_request) + + sink = _RecordingCheckpointSink() + make_checkpoint_recorder(sink)(callback_context) + + assert len(sink.calls) == 1 + scope_id, checkpoint = sink.calls[0] + assert scope_id == "scope-1" + assert isinstance(checkpoint, CheckpointRecord) + assert checkpoint.state["tokens"] == 9_500 + assert checkpoint.state["budget"] == 10_000 From 38e44964fe6c704f62a5c734b9065fde49591055 Mon Sep 17 00:00:00 2001 From: AsherDLL Date: Thu, 27 Aug 2026 17:26:04 -0700 Subject: [PATCH 2/4] fix(memory): clear the degraded flag when a write recovers MemoryService._degraded was set on a failed safe_append_event but never reset, so a single transient store failure marked health() (and /status) degraded for the whole process lifetime even after the store recovered. Clear the flag on a successful write so health reflects current writability. Adds a fail-then-recover regression test. --- src/arema/memory/service.py | 7 ++++++- tests/unit/memory/test_service.py | 33 +++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/arema/memory/service.py b/src/arema/memory/service.py index 3cf1611..f4abf02 100644 --- a/src/arema/memory/service.py +++ b/src/arema/memory/service.py @@ -215,13 +215,18 @@ def append_event(self, scope_id: str, event: EventRecord, *, source: str) -> Mem ) def safe_append_event(self, scope_id: str, event: EventRecord, *, source: str) -> bool: - """Persist an event fail-open: return ``False`` and degrade on failure.""" + """Persist an event fail-open: return ``False`` and degrade on failure. + + ``health()`` reflects current writability, so a successful write clears a + prior degraded flag rather than latching it for the process lifetime. + """ try: self.append_event(scope_id, event, source=source) except MemoryStoreError as exc: logger.warning("memory event write failed", error_type=type(exc).__name__) self._degraded = True return False + self._degraded = False return True def append_checkpoint( diff --git a/tests/unit/memory/test_service.py b/tests/unit/memory/test_service.py index c35bc58..622ddfd 100644 --- a/tests/unit/memory/test_service.py +++ b/tests/unit/memory/test_service.py @@ -60,6 +60,27 @@ def health(self) -> StoreHealth: return StoreHealth(healthy=True) +class _FlakyStore: + """A store that fails its first write, then delegates successfully.""" + + def __init__(self) -> None: + self._delegate = InMemoryStore() + self._delegate.initialize() + self._remaining_failures = 1 + + def insert_record(self, record: MemoryEnvelope) -> MemoryEnvelope: + if self._remaining_failures > 0: + self._remaining_failures -= 1 + raise MemoryStoreError("write failed") + return self._delegate.insert_record(record) + + def create_scope(self, scope: MemoryScope) -> MemoryScope: + return self._delegate.create_scope(scope) + + def health(self) -> StoreHealth: + return StoreHealth(healthy=True) + + def build_service() -> MemoryService: store = InMemoryStore() store.initialize() @@ -187,6 +208,18 @@ def test_safe_append_event_returns_false_and_degrades_on_failure() -> None: assert service.health().healthy is False +def test_safe_append_event_clears_degraded_after_recovery() -> None: + store: MemoryStore = _FlakyStore() # type: ignore[assignment] + service = MemoryService(store=store, codecs=default_core_codec_registry()) + scope = service.create_scope(MemoryScope(scope_type="run")) + + assert service.safe_append_event(scope.id, EventRecord(name="boom"), source="unit") is False + assert service.health().healthy is False + + assert service.safe_append_event(scope.id, EventRecord(name="ok"), source="unit") is True + assert service.health().healthy is True + + def test_append_event_raises_strictly_on_failure() -> None: store: MemoryStore = _FailingStore() # type: ignore[assignment] service = MemoryService(store=store, codecs=default_core_codec_registry()) From d71f907de0245671ae31b20078f2f994fff06150 Mon Sep 17 00:00:00 2001 From: AsherDLL Date: Thu, 27 Aug 2026 17:26:37 -0700 Subject: [PATCH 3/4] docs(config): mark memory_enabled and context_max_list_items as inert Both settings are documented in .env.example but read nowhere in src: composition always builds a store keyed off memory_backend, and list truncation uses the per-tool OutputPolicy.max_list_items. Note that they are currently inert so the knobs are not mistaken for live controls. --- .env.example | 4 ++-- src/arema/core/config.py | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.env.example b/.env.example index 7a7e5b9..4ebe55e 100644 --- a/.env.example +++ b/.env.example @@ -144,7 +144,7 @@ AREMA_CONTEXT_BUDGET_TOKENS=80000 # AREMA_CONTEXT_WARNING_RATIO=0.60 # Compaction begins at this occupancy # AREMA_CONTEXT_HARD_RATIO=0.75 # Tighter preservation past this tier # AREMA_CONTEXT_CRITICAL_RATIO=0.85 # Run stops cleanly above this tier -# AREMA_CONTEXT_MAX_LIST_ITEMS=30 +# AREMA_CONTEXT_MAX_LIST_ITEMS=30 # currently inert (per-tool OutputPolicy is used) # AREMA_CONTEXT_PRESERVE_RECENT_TOOLS=3 # AREMA_CONTEXT_PRESERVE_RECENT_MODEL_TURNS=4 @@ -165,7 +165,7 @@ AREMA_LOG_LEVEL=INFO # ============================================================================== # Backend-neutral structured storage. Default backend is SQLite on local disk; # set AREMA_MEMORY_BACKEND=memory for ephemeral, in-process runs and tests. -AREMA_MEMORY_ENABLED=true +AREMA_MEMORY_ENABLED=true # currently inert; the store is always built AREMA_MEMORY_BACKEND=sqlite AREMA_MEMORY_PATH=~/.arema/memory/arema.db # AREMA_MEMORY_RETRIEVAL_MAX_RECORDS=20 diff --git a/src/arema/core/config.py b/src/arema/core/config.py index c193fa8..7f4cafe 100644 --- a/src/arema/core/config.py +++ b/src/arema/core/config.py @@ -162,6 +162,7 @@ class Settings(BaseSettings): context_warning_ratio: float = Field(default=0.60, gt=0.0, lt=1.0) context_hard_ratio: float = Field(default=0.75, gt=0.0, lt=1.0) context_critical_ratio: float = Field(default=0.85, gt=0.0, lt=1.0) + # Currently inert: per-tool OutputPolicy.max_list_items drives list truncation. context_max_list_items: int = Field(default=30, ge=5, le=200) context_preserve_recent_tools: int = Field(default=3, ge=1, le=10) context_preserve_recent_model_turns: int = Field(default=4, ge=1, le=20) @@ -169,6 +170,7 @@ class Settings(BaseSettings): default_turn_limit: int = Field(default=100, ge=1, le=1000) agent_turn_limits: dict[str, int] = Field(default_factory=dict) + # Currently inert: composition always builds a store, keyed off memory_backend. memory_enabled: bool = True memory_backend: Literal["sqlite", "memory"] = "sqlite" memory_path: Path = Field( From 2887a8c85bc89a32b90e2f7879a6da91e731b65a Mon Sep 17 00:00:00 2001 From: AsherDLL Date: Thu, 27 Aug 2026 17:26:55 -0700 Subject: [PATCH 4/4] docs: note the recovery tag is absent from the public mirror The plan references pre-arema-domain-reset-2026-07-21, but this mirror's history is squashed from Initial Commit so the tag isn't present here. Add a note so the reference isn't read as a live, resolvable pointer. --- .../plans/2026-07-21-arema-domain-neutral-shell.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/superpowers/plans/2026-07-21-arema-domain-neutral-shell.md b/docs/superpowers/plans/2026-07-21-arema-domain-neutral-shell.md index 3247ed4..86d6056 100644 --- a/docs/superpowers/plans/2026-07-21-arema-domain-neutral-shell.md +++ b/docs/superpowers/plans/2026-07-21-arema-domain-neutral-shell.md @@ -77,6 +77,11 @@ During Tasks 1–12 these files live under `tests_arema/`; Task 13 renames that - [ ] **Step 1: Verify the execution worktree and create the recovery tag** +> Note: the `pre-arema-domain-reset-2026-07-21` tag lives in the private +> development history and is **not present in the public mirror** (published +> history is squashed from `Initial Commit`), so `git tag -l` here is empty by +> design. The steps below reflect the original private-repo execution. + Run: ```bash