Skip to content

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

fix(memory): reject ambiguous search replacements (#3386)

teacup80d63f508d82
diff --git a/openviking/session/memory/extract_loop.py b/openviking/session/memory/extract_loop.py
index 27c57f971..e4c08ec11 100644
--- a/openviking/session/memory/extract_loop.py
+++ b/openviking/session/memory/extract_loop.py
@@ -922,6 +922,8 @@ The final output of the model must strictly follow the JSON Schema format shown
return (
"SEARCH/REPLACE patch could not be applied to the target memory file. "
"The SEARCH text must be copied exactly from the read result of the file bound to that operation's page_id. "
+ "The SEARCH text must occur exactly once in the target file. "
+ "If it occurs more than once, include enough contiguous surrounding context to make the SEARCH text unique. "
"Do not use SEARCH text from the conversation or from another page. "
"If you copy from numbered read output, exclude the `line_number<TAB>` prefix from SEARCH and REPLACE text. "
"If found_in_other_uris is non-empty, diagnose this as a possible page_id mismatch and choose the correct target page_id or rewrite the patch for the current page_id; do not silently move the patch. "
diff --git a/openviking/session/memory/merge_op/patch.py b/openviking/session/memory/merge_op/patch.py
index 06b46c95f..f10e808ba 100644
--- a/openviking/session/memory/merge_op/patch.py
+++ b/openviking/session/memory/merge_op/patch.py
@@ -75,8 +75,8 @@ class PatchOp(MergeOpBase):
# Case 2: dict form of StrPatch (from JSON parsing)
if isinstance(patch_value, dict):
- try:
- if "blocks" in patch_value:
+ if "blocks" in patch_value:
+ try:
blocks = []
for block_dict in patch_value["blocks"]:
if isinstance(block_dict, dict):
@@ -85,13 +85,15 @@ class PatchOp(MergeOpBase):
blocks.append(block_dict)
# Filter out empty-search blocks when there's existing content
valid_blocks = [b for b in blocks if b.search]
- if valid_blocks:
- return apply_str_patch(current_str, StrPatch(blocks=valid_blocks))
- # All blocks have empty search → keep original
- return current_value
- except Exception:
- # If conversion fails, treat as simple replacement
- return str(patch_value) if patch_value is not None else ""
+ converted_patch = StrPatch(blocks=valid_blocks) if valid_blocks else None
+ except Exception:
+ # If conversion fails, treat as simple replacement
+ return str(patch_value) if patch_value is not None else ""
+
+ if converted_patch is not None:
+ return apply_str_patch(current_str, converted_patch)
+ # All blocks have empty search → keep original
+ return current_value
# Case 3: Simple full replacement
# 空字符串和 None 都保持原值
diff --git a/openviking/session/memory/merge_op/patch_handler.py b/openviking/session/memory/merge_op/patch_handler.py
index 88b6ad04a..13bb4b97d 100644
--- a/openviking/session/memory/merge_op/patch_handler.py
+++ b/openviking/session/memory/merge_op/patch_handler.py
@@ -880,7 +880,15 @@ def apply_str_patch(original_content: str, patch: StrPatch) -> str:
all_applied = False
break
- result_content = result_content.replace(search_content, replace_content)
+ match_count = result_content.count(search_content)
+ if match_count > 1:
+ raise PatchParseError(
+ f"SEARCH content matched {match_count} locations; "
+ "The re-generated SEARCH string may contain additional lines "
+ "to make sure it is unique."
+ )
+
+ result_content = result_content.replace(search_content, replace_content, 1)
if all_applied:
return result_content
diff --git a/tests/session/memory/test_compressor_v2.py b/tests/session/memory/test_compressor_v2.py
index 68c6340e1..c17f0e9dd 100644
--- a/tests/session/memory/test_compressor_v2.py
+++ b/tests/session/memory/test_compressor_v2.py
@@ -899,6 +899,8 @@ class TestExtractLoopPatchRepair:
assert len(vlm.messages) == 2
second_call_content = "\n".join(message["content"] for message in vlm.messages[1])
assert "SEARCH/REPLACE patch could not be applied" in second_call_content
+ assert "The SEARCH text must occur exactly once" in second_call_content
+ assert "include enough contiguous surrounding context" in second_call_content
assert "Regenerate the complete operations JSON" in second_call_content
assert target_uri in second_call_content
assert other_uri in second_call_content
diff --git a/tests/session/memory/test_merge_ops.py b/tests/session/memory/test_merge_ops.py
index a74f9d44c..865b21b5d 100644
--- a/tests/session/memory/test_merge_ops.py
+++ b/tests/session/memory/test_merge_ops.py
@@ -4,6 +4,8 @@
Tests for MergeOp architecture - type-safe merge operations.
"""
+import pytest
+
from openviking.session.memory.dataclass import (
MemoryField,
)
@@ -12,6 +14,7 @@ from openviking.session.memory.merge_op import (
MergeOp,
MergeOpFactory,
PatchOp,
+ PatchParseError,
SearchReplaceBlock,
StrPatch,
SumOp,
@@ -81,6 +84,30 @@ class TestPatchOp:
op_int = PatchOp(FieldType.INT64)
assert op_int.apply(100, 200) == 200
+ def test_apply_dict_patch(self):
+ """Dict-form string patches should be converted and applied."""
+ op = PatchOp(FieldType.STRING)
+ patch = {"blocks": [{"search": "hello world", "replace": "hello there"}]}
+
+ assert op.apply("hello world", patch) == "hello there"
+
+ def test_apply_invalid_dict_patch_falls_back_to_string_replacement(self):
+ """Invalid dict-form patches should preserve the compatibility fallback."""
+ op = PatchOp(FieldType.STRING)
+ patch = {"blocks": [{"search": "hello world"}]}
+
+ assert op.apply("hello world", patch) == str(patch)
+
+ def test_apply_dict_patch_propagates_patch_parse_error(self):
+ """Patch errors raised after dict conversion must reach the caller."""
+ op = PatchOp(FieldType.STRING)
+ patch = {
+ "blocks": [{"search": "status: pending", "replace": "status: done"}]
+ }
+
+ with pytest.raises(PatchParseError, match="matched 2 locations"):
+ op.apply("status: pending\nstatus: pending", patch)
+
class TestSumOp:
"""Tests for SumOp."""
@@ -269,6 +296,32 @@ class TestApplyStrPatch:
# Directly test apply_str_patch
assert result == "hello there"
+ def test_duplicate_search_is_rejected(self):
+ """Ambiguous SEARCH content must fail instead of replacing globally."""
+ original = "status: pending\nstatus: pending"
+ patch = StrPatch(
+ blocks=[SearchReplaceBlock(search="status: pending", replace="status: done")]
+ )
+
+ with pytest.raises(
+ PatchParseError,
+ match="additional lines to make sure it is unique",
+ ):
+ apply_str_patch(original, patch)
+
+ def test_duplicate_search_after_prior_block_is_rejected(self):
+ """A later ambiguous block must not return a partially applied patch."""
+ original = "title\nstatus: pending\nstatus: pending"
+ patch = StrPatch(
+ blocks=[
+ SearchReplaceBlock(search="title", replace="updated title"),
+ SearchReplaceBlock(search="status: pending", replace="status: done"),
+ ]
+ )
+
+ with pytest.raises(PatchParseError, match="matched 2 locations"):
+ apply_str_patch(original, patch)
+
def test_numbered_multiline_patch_uses_inferred_start_line(self):
"""Tab-prefixed read output should target the numbered range."""
original = "keep\nsame\nkeep\nsame"