Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/arema/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,13 +162,15 @@ 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)

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(
Expand Down
7 changes: 6 additions & 1 deletion src/arema/memory/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
7 changes: 5 additions & 2 deletions src/arema/runtime/context/budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down
33 changes: 33 additions & 0 deletions tests/unit/memory/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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())
Expand Down
53 changes: 53 additions & 0 deletions tests/unit/runtime/test_context_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -20,6 +21,8 @@
enforce_context_budget,
estimate_tokens,
)
from arema.runtime.services import make_checkpoint_recorder
from arema.runtime.sessions import SessionKeys

# ---------------------------------------------------------------------------
# Helpers
Expand Down Expand Up @@ -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
# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -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
Loading