Skip to content

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

fix(memory): skip unfixable event resolution retries (#6429)

Danny Ward3266cd865e32
diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.py
index b6451a3d6..9ebe459cc 100644
--- a/openviking/session/memory/extract_loop.py
+++ b/openviking/session/memory/extract_loop.py
@@ -522,10 +522,11 @@ class ExtractLoop:
or resolution_skip.reason_code not in _EVENT_RETRYABLE_RESOLUTION_SKIP_CODES
):
continue
- if resolution_skip.reason_code == MemoryOperationSkipCode.NO_WRITABLE_TARGET and (
- not self.ctx or not self.ctx.user
- ):
- continue
+ if resolution_skip.reason_code == MemoryOperationSkipCode.NO_WRITABLE_TARGET:
+ if not self.ctx or not self.ctx.user:
+ continue
+ if not self._has_writable_message_target():
+ continue
issue = {
"memory_type": operation.memory_type,
"page_id": operation.page_id,
@@ -536,6 +537,21 @@ class ExtractLoop:
issues.append(issue)
return issues
+ def _has_writable_message_target(self) -> bool:
+ """Preserve legacy retries if the isolation handler cannot answer the check."""
+ handler = self._isolation_handler
+ has_writable_target = getattr(handler, "has_writable_message_target", None)
+ if not callable(has_writable_target):
+ return True
+ try:
+ return bool(has_writable_target())
+ except Exception:
+ logger.warning(
+ "Unable to determine writable message targets; preserving resolution repair",
+ exc_info=True,
+ )
+ return True
+
def _build_resolution_repair_instruction(self, issues: List[Dict[str, Any]]) -> str:
return self._output_protocol.render_resolution_repair(issues)
diff --git a/openviking/session/memory/memory_isolation_handler.py b/openviking/session/memory/memory_isolation_handler.py
index 13d38527f..f5f753e16 100644
--- a/openviking/session/memory/memory_isolation_handler.py
+++ b/openviking/session/memory/memory_isolation_handler.py
@@ -211,6 +211,10 @@ class MemoryIsolationHandler:
]
return list(dict.fromkeys(targets))
+ def has_writable_message_target(self) -> bool:
+ """Whether any message in the current window resolves to a writable owner."""
+ return bool(self._target_ids_in_messages())
+
def _range_is_fully_in_bounds(self, ranges: Any) -> bool:
parts = str(ranges).split(",")
if not parts or any(not part.strip() for part in parts):
diff --git a/tests/session/memory/test_memory_isolation_handler.py b/tests/session/memory/test_memory_isolation_handler.py
index 8e2186dad..3d2669d2b 100644
--- a/tests/session/memory/test_memory_isolation_handler.py
+++ b/tests/session/memory/test_memory_isolation_handler.py
@@ -92,6 +92,20 @@ class TestGetReadScope:
assert handler._message_target_id(message) is None
+ def test_writable_message_target_requires_a_resolvable_owner_message(self):
+ ctx = create_ctx()
+ assistant_only = MemoryIsolationHandler(
+ ctx,
+ create_mock_extract_context([create_message("assistant")]),
+ )
+ with_user_message = MemoryIsolationHandler(
+ ctx,
+ create_mock_extract_context([create_message("user")]),
+ )
+
+ assert not assistant_only.has_writable_message_target()
+ assert with_user_message.has_writable_message_target()
+
def test_deduplicate_users(self):
"""Test that duplicate users are deduplicated."""
ctx = create_ctx()
diff --git a/tests/unit/session/memory/test_extract_loop_match_text.py b/tests/unit/session/memory/test_extract_loop_match_text.py
index 18a529499..0b6446751 100644
--- a/tests/unit/session/memory/test_extract_loop_match_text.py
+++ b/tests/unit/session/memory/test_extract_loop_match_text.py
@@ -807,8 +807,47 @@ class TestResolutionRepair:
assert self._loop(ctx=None)._retryable_resolution_issues(operations) == []
+ def test_missing_or_failing_isolation_handler_preserves_legacy_retry(self):
+ operations = ResolvedOperations(
+ upsert_operations=[
+ ResolvedOperation(
+ memory_fields={"ranges": "0"},
+ memory_type="events",
+ uris=[],
+ page_id=100,
+ resolution_skip=MemoryOperationSkip(
+ reason_code=MemoryOperationSkipCode.NO_WRITABLE_TARGET,
+ reason="No writable memory target could be resolved",
+ ),
+ )
+ ],
+ delete_file_contents=[],
+ errors=[],
+ )
+ ctx = SimpleNamespace(user=SimpleNamespace(user_id="alice"))
+
+ missing_handler = self._loop(ctx=ctx)
+ missing_handler._isolation_handler = None
+ assert len(missing_handler._retryable_resolution_issues(operations)) == 1
+
+ failing_handler = self._loop(ctx=ctx)
+ failing_handler._isolation_handler.has_writable_message_target.side_effect = RuntimeError(
+ "target lookup failed"
+ )
+ assert len(failing_handler._retryable_resolution_issues(operations)) == 1
+
+ @pytest.mark.parametrize(
+ ("resolution_skip_code", "has_writable_target", "expected_llm_calls"),
+ [
+ (MemoryOperationSkipCode.INVALID_RANGES, False, 2),
+ (MemoryOperationSkipCode.NO_WRITABLE_TARGET, False, 1),
+ (MemoryOperationSkipCode.NO_WRITABLE_TARGET, True, 2),
+ ],
+ )
@pytest.mark.asyncio
- async def test_run_repairs_only_failed_event_and_preserves_successful_profile(self):
+ async def test_run_repairs_only_actionable_event_and_preserves_successful_profile(
+ self, resolution_skip_code, has_writable_target, expected_llm_calls
+ ):
schema = TestResolveOperations._event_schema()
profile_schema = MemoryTypeSchema(
memory_type="profile",
@@ -830,6 +869,7 @@ class TestResolutionRepair:
isolation_handler = Mock()
isolation_handler.get_read_scope.return_value = None
isolation_handler.fill_identity_fields.side_effect = lambda item, **kwargs: item
+ isolation_handler.has_writable_message_target.return_value = has_writable_target
event_resolution_attempts = 0
def calculate_memory_uris(*, memory_type_schema, operation, **kwargs):
@@ -839,8 +879,12 @@ class TestResolutionRepair:
event_resolution_attempts += 1
if event_resolution_attempts == 1:
operation.resolution_skip = MemoryOperationSkip(
- reason_code=MemoryOperationSkipCode.INVALID_RANGES,
- reason="Message ranges are malformed or out of bounds",
+ reason_code=resolution_skip_code,
+ reason=(
+ "Message ranges are malformed or out of bounds"
+ if resolution_skip_code == MemoryOperationSkipCode.INVALID_RANGES
+ else "No writable memory target could be resolved"
+ ),
)
return []
operation.resolution_skip = None
@@ -853,6 +897,7 @@ class TestResolutionRepair:
viking_fs=Mock(),
context_provider=context_provider,
isolation_handler=isolation_handler,
+ ctx=SimpleNamespace(user=SimpleNamespace(user_id="alice")),
)
loop._call_llm = AsyncMock(
side_effect=[
@@ -890,10 +935,12 @@ class TestResolutionRepair:
final_operations, _ = await loop.run()
- assert loop._call_llm.await_count == 2
- assert event_resolution_attempts == 2
+ assert loop._call_llm.await_count == expected_llm_calls
+ assert event_resolution_attempts == expected_llm_calls
assert len(final_operations.upsert_operations) == 2
- assert final_operations.upsert_operations[0].uris == [event_uri]
+ assert final_operations.upsert_operations[0].uris == (
+ [event_uri] if expected_llm_calls == 2 else []
+ )
assert final_operations.upsert_operations[0].page_id == 100
assert final_operations.upsert_operations[1].memory_type == "profile"
assert final_operations.upsert_operations[1].uris == [profile_uri]
@@ -903,9 +950,12 @@ class TestResolutionRepair:
for message in loop._call_llm.await_args_list[-1].args[0]
if message["role"] == "user" and "Resolution issues:" in message["content"]
]
- assert len(repair_messages) == 1
- assert '"reason_code": "invalid_ranges"' in repair_messages[0]
- assert '"event_name": "demo"' in repair_messages[0]
+ if expected_llm_calls == 2:
+ assert len(repair_messages) == 1
+ assert f'"reason_code": "{resolution_skip_code.value}"' in repair_messages[0]
+ assert '"event_name": "demo"' in repair_messages[0]
+ else:
+ assert repair_messages == []
def test_merge_event_repair_ignores_unrequested_memory_types(self):
original_profile = ResolvedOperation(