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
105 changes: 75 additions & 30 deletions python/packages/core/agent_framework/_harness/_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import logging
import re
import threading
import uuid
import weakref
from abc import ABC, abstractmethod
from base64 import b32decode
Expand Down Expand Up @@ -222,7 +223,25 @@ def _coerce_summary(summary: str, memories: Sequence[str]) -> str:


def _default_state() -> dict[str, Any]:
return {"last_consolidated_at": None, "sessions_since_consolidation": []}
# ``sessions_since_consolidation`` lists the distinct sessions with turns not yet covered by a
# consolidation pass. ``pending_turn_ids`` maps each of them to a unique id of its latest finished
# turn, so a pass only retires a session whose latest turn finished before the pass took its snapshot.
return {"last_consolidated_at": None, "sessions_since_consolidation": [], "pending_turn_ids": {}}


def _normalize_state(state: Mapping[str, Any]) -> dict[str, Any]:
"""Return ``state`` with every maintenance field present and of the expected type.

Stores may return state saved before a field existed, such as state without ``pending_turn_ids``.
"""
normalized = {**_default_state(), **state}
if not isinstance(normalized.get("sessions_since_consolidation"), list):
normalized["sessions_since_consolidation"] = []
if not isinstance(normalized.get("pending_turn_ids"), dict):
normalized["pending_turn_ids"] = {}
if not isinstance(normalized.get("last_consolidated_at"), (str, type(None))):
normalized["last_consolidated_at"] = None
return normalized


def _format_search_results(results: Sequence[Mapping[str, Any]]) -> str:
Expand Down Expand Up @@ -893,12 +912,7 @@ def read_state(self, session: AgentSession, *, source_id: str) -> dict[str, Any]
raw_state = self.loads(state_path.read_text(encoding="utf-8"))
if not isinstance(raw_state, dict):
raise ValueError("Memory state file must contain a JSON object.")
state = {**_default_state(), **cast(dict[str, Any], raw_state)}
if not isinstance(state.get("sessions_since_consolidation"), list):
state["sessions_since_consolidation"] = []
if not isinstance(state.get("last_consolidated_at"), (str, type(None))):
state["last_consolidated_at"] = None
return state
return _normalize_state(cast(dict[str, Any], raw_state))

def write_state(self, session: AgentSession, state: Mapping[str, Any], *, source_id: str) -> None:
"""Persist the maintenance state for the current owner."""
Expand Down Expand Up @@ -1084,6 +1098,10 @@ def _topic_async_lock(self, session: AgentSession, topic: str) -> asyncio.Lock:
def _state_async_lock(self, session: AgentSession) -> asyncio.Lock:
return self._store_async_lock(session, kind="state", key="maintenance")

def _read_maintenance_state(self, session: AgentSession) -> dict[str, Any]:
# Custom stores may return state saved before newer fields existed, so fill them in here.
return _normalize_state(self.store.read_state(session, source_id=self.source_id))

def _create_history_provider(self, session: AgentSession) -> FileHistoryProvider:
return FileHistoryProvider(
self.store.get_transcripts_directory(session, source_id=self.source_id),
Expand Down Expand Up @@ -1401,27 +1419,34 @@ async def after_run(
await self.save_messages(session.session_id, messages_to_store, state=state)

current_time = datetime.now(timezone.utc).replace(microsecond=0)
async with self._state_async_lock(session):
maintenance_state = self.store.read_state(session, source_id=self.source_id)
session_ids_since_consolidation = cast(list[str], maintenance_state["sessions_since_consolidation"])
if session.session_id not in session_ids_since_consolidation:
session_ids_since_consolidation.append(session.session_id)
maintenance_state["sessions_since_consolidation"] = session_ids_since_consolidation
self.store.write_state(session, maintenance_state, source_id=self.source_id)

extracted_topics = await self._extract_memories(
client=self._chat_client(agent),
session=session,
context=context,
now=current_time,
)
if extracted_topics:
self.store.rebuild_index(
session,
source_id=self.source_id,
line_limit=self.index_line_limit,
line_length=self.index_line_length,
try:
extracted_topics = await self._extract_memories(
client=self._chat_client(agent),
session=session,
context=context,
now=current_time,
)
if extracted_topics:
self.store.rebuild_index(
session,
source_id=self.source_id,
line_limit=self.index_line_limit,
line_length=self.index_line_length,
)
finally:
# Register the session only once its extraction is over, so a consolidation pass that sees
# this session as pending has also seen the memories it extracted. Registering in `finally`
# keeps topics already written by a run that then failed or was cancelled pending too.
# A fresh turn id is recorded even when the session is already pending: runs on the same
# session can overlap, and a pass that snapshotted an earlier turn must not retire this one.
async with self._state_async_lock(session):
maintenance_state = self._read_maintenance_state(session)
session_ids_since_consolidation = cast(list[str], maintenance_state["sessions_since_consolidation"])
if session.session_id not in session_ids_since_consolidation:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shivam Sharma (@ShivamSharma43) this still uses a de-duplicated session.session_id as the only pending-work marker. If a consolidation pass snapshots covered_session_ids while session-1 is already pending, then a second overlapping agent.run(..., session=AgentSession(session_id="session-1")) can finish extraction and reach this block while session-1 is still in the list, so line 1435 records no new marker. When the older pass succeeds, lines 1599-1603 remove session-1 because it was in the snapshot, leaving the later turn’s newly written topic out of the pending window even though it was not in that snapshot. Agent.run does not serialize callers per AgentSession, so the marker needs to distinguish completions rather than just membership by session id.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, thanks. Fixed in 069de84. The marker now changes with every finished turn, so it no longer depends on the session id alone.

  • Every finished turn stores a new uuid4 id for its session in a new state field, pending_turn_ids ({session_id: id of the latest finished turn}). This happens in the same finally block, under the state lock, even when the session is already pending.
  • A pass records each pending session's id when it takes its snapshot. When the pass succeeds, it retires a session only if that id hasn't changed. In your interleaving, the second session-1 turn replaces the id, so the older pass leaves session-1 pending. Ids are never reused, so this also holds when two passes overlap and the other one retires and re-adds the session in between.
  • sessions_since_consolidation keeps its format: a de-duplicated list of session ids. consolidation_min_sessions still counts distinct sessions, matching its docstring ("Number of sessions required") and the de-duplication the provider already did. Overlapping turns of one session don't move the threshold forward any faster.
  • Existing state still loads. read_state fills in pending_turn_ids as {} when it's missing. A session that's pending without an id is retired by a pass that saw it, unless a newer turn has recorded an id by the time the pass finishes.

Tests:

  • test_automatic_consolidation_keeps_overlapping_turn_of_covered_session_pending follows your interleaving. Two overlapping agent.run(..., session=AgentSession(session_id="session-1")) calls run through the real automatic passes. The first pass, which snapshotted session-1, finishes after the second turn wrote and registered its topic, and session-1 stays pending. The second pass then covers the new topic and retires it. On 480eea4 the pending list ends up [] at that point.
  • test_memory_consolidation_retires_only_turns_in_its_snapshot is now parametrized. A turn registered during the pass is kept in each case: for a new session, for a pending session without an id (older state), and for a pending session with an id.

Memory, file-memory, sessions and background-agents tests: 302 passed, 1 skipped. The 1 failure is the Windows path-length case (test_opaque_session_id_round_trips_through_safe_filename), which also fails on main. Ruff, pyright (source) and mypy, ty, pyrefly (tests) are clean on the changed files.

session_ids_since_consolidation.append(session.session_id)
maintenance_state["sessions_since_consolidation"] = session_ids_since_consolidation
cast(dict[str, str], maintenance_state["pending_turn_ids"])[session.session_id] = uuid.uuid4().hex

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shivam Sharma (@ShivamSharma43), MemoryContextProvider also accepts custom implementations of the exported MemoryStore abstraction, but the new field is backfilled only by MemoryFileStore.read_state(). An existing store returning the previously valid state {"last_consolidated_at": null, "sessions_since_consolidation": []} now raises KeyError: 'pending_turn_ids' here on every run, even when extraction returns no memories. Please initialize the missing map at the provider boundary and make the consolidation reads tolerate legacy state too, so custom backends can continue loading their existing maintenance state.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c92fc7d. MemoryContextProvider now passes every state read from the store through a shared _normalize_state helper. The helper fills in a missing pending_turn_ids map (and the other maintenance fields), so the registration step and both reads in the consolidation pass accept legacy state. MemoryFileStore.read_state() now uses the same helper.

With legacy state, a pass still retires the sessions it saw, as before. A turn registered while the pass is running still gets its own id, so it stays pending.

Added two regression tests built on a custom store that only persists last_consolidated_at and sessions_since_consolidation. They cover a run whose extraction returns no memories and a consolidation pass over the legacy state. Both raised KeyError: 'pending_turn_ids' before this change.

self.store.write_state(session, maintenance_state, source_id=self.source_id)

await self._run_consolidation(
client=self._chat_client(agent, override=self.consolidation_client),
Expand Down Expand Up @@ -1549,15 +1574,23 @@ async def _run_consolidation(
# making LLM calls so concurrent before/after_run invocations don't have to wait through
# multi-second consolidation calls.
async with self._state_async_lock(session):
maintenance_state = self.store.read_state(session, source_id=self.source_id)
maintenance_state = self._read_maintenance_state(session)
if not force and not self._should_consolidate(maintenance_state, now=now):
return 0
topic_records = self.store.list_topics(session, source_id=self.source_id)
if not topic_records:
maintenance_state["last_consolidated_at"] = _timestamp(now)
maintenance_state["sessions_since_consolidation"] = []
maintenance_state["pending_turn_ids"] = {}
self.store.write_state(session, maintenance_state, source_id=self.source_id)
return 0
# Turns registered after this snapshot are not covered by this pass and stay pending, even
# when their session was already pending at snapshot time.
pending_turn_ids = cast(dict[str, str], maintenance_state["pending_turn_ids"])
covered_turn_ids = {
session_id: pending_turn_ids.get(session_id)
for session_id in cast(list[str], maintenance_state["sessions_since_consolidation"])
}

success_count = 0
for record in topic_records:
Expand All @@ -1578,9 +1611,21 @@ async def _run_consolidation(
# session IDs so the next after_run will retry instead of silently sliding the window.
if success_count > 0:
async with self._state_async_lock(session):
maintenance_state = self.store.read_state(session, source_id=self.source_id)
maintenance_state = self._read_maintenance_state(session)
maintenance_state["last_consolidated_at"] = _timestamp(now)
maintenance_state["sessions_since_consolidation"] = []
pending_turn_ids = cast(dict[str, str], maintenance_state["pending_turn_ids"])
remaining_session_ids = [
session_id
for session_id in cast(list[str], maintenance_state["sessions_since_consolidation"])
if session_id not in covered_turn_ids
or pending_turn_ids.get(session_id) != covered_turn_ids[session_id]
]
maintenance_state["sessions_since_consolidation"] = remaining_session_ids
maintenance_state["pending_turn_ids"] = {
session_id: pending_turn_ids[session_id]
for session_id in remaining_session_ids
if session_id in pending_turn_ids
}
self.store.write_state(session, maintenance_state, source_id=self.source_id)
self.store.rebuild_index(
session,
Expand Down
Loading
Loading