Skip to content

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

fix(semantic): reuse overview summary cache (#4307)

MaojiaSheng42c0ee1363d0
diff --git a/openviking/storage/queuefs/semantic_processor.py b/openviking/storage/queuefs/semantic_processor.py
index 829fb25b7..5d4126c53 100644
--- a/openviking/storage/queuefs/semantic_processor.py
+++ b/openviking/storage/queuefs/semantic_processor.py
@@ -7,6 +7,7 @@ import re
import threading
from contextlib import nullcontext
from typing import Any, Dict, List, Optional, Set, Tuple
+from urllib.parse import quote, unquote, urlsplit
from openviking.observability.context import (
bind_root_observability_context,
@@ -1069,12 +1070,16 @@ class SemanticProcessor(DequeueHandlerBase):
) -> str:
"""Render a subdirectory summary line with a collision-free link placeholder."""
placeholder = f"viking://input_sample_c{idx}"
- link_map[placeholder] = f"{dir_uri}/{item['name']}"
+ link_map[placeholder] = self._markdown_link_target(dir_uri, item["name"])
return f"- {item['name']}/ (link: {placeholder}): {item['abstract']}"
- def _replace_link_references(
- self, generated_content: str, link_map: Dict[str, str]
- ) -> str:
+ @staticmethod
+ def _markdown_link_target(dir_uri: str, entry_name: str) -> str:
+ """Build a Markdown-safe target without changing the stored Viking URI."""
+ entry_uri = VikingURI(dir_uri).join(entry_name).uri
+ return quote(entry_uri, safe=":/")
+
+ def _replace_link_references(self, generated_content: str, link_map: Dict[str, str]) -> str:
"""Resolve link placeholders (viking://input_sample_fN / cN) to real URIs.
The model is fed compact, collision-free placeholders and asked to emit
@@ -1183,7 +1188,7 @@ class SemanticProcessor(DequeueHandlerBase):
if current_file and current_summary_lines:
summaries[current_file] = " ".join(current_summary_lines).strip()
- file_name = header_match.group(1).strip()
+ file_name = self._overview_heading_cache_key(header_match.group(1).strip())
parts = file_name.split()
if len(parts) >= 2 and parts[0] == parts[1]:
file_name = parts[0]
@@ -1210,6 +1215,21 @@ class SemanticProcessor(DequeueHandlerBase):
return summaries
+ @staticmethod
+ def _overview_heading_cache_key(heading: str) -> str:
+ """Return the entry name represented by a plain or linked H3 heading."""
+ if heading.startswith("[") and heading.endswith(")"):
+ destination_start = heading.rfind("](")
+ if destination_start > 0:
+ target = heading[destination_start + 2 : -1].strip()
+ if target.startswith("<") and target.endswith(">"):
+ target = target[1:-1].strip()
+ if target.startswith("viking://"):
+ path = unquote(urlsplit(target).path).rstrip("/")
+ if path:
+ return path.rsplit("/", 1)[-1]
+ return heading
+
async def _generate_overview(
self,
dir_uri: str,
@@ -1280,7 +1300,7 @@ class SemanticProcessor(DequeueHandlerBase):
file_summaries_lines = []
for idx, item in enumerate(file_summaries, 1):
placeholder = f"viking://input_sample_f{idx}"
- link_map[placeholder] = f"{dir_uri}/{item['name']}"
+ link_map[placeholder] = self._markdown_link_target(dir_uri, item["name"])
file_summaries_lines.append(
f"- {item['name']} (link: {placeholder}): {item['summary']}"
)
@@ -1446,11 +1466,9 @@ class SemanticProcessor(DequeueHandlerBase):
if entry_kind == "file":
placeholder = f"viking://input_sample_f{global_idx}"
batch_link_map[placeholder] = link_map.get(
- placeholder, f"{dir_uri}/{item['name']}"
- )
- batch_lines.append(
- f"- {item['name']} (link: {placeholder}): {item['summary']}"
+ placeholder, self._markdown_link_target(dir_uri, item["name"])
)
+ batch_lines.append(f"- {item['name']} (link: {placeholder}): {item['summary']}")
else:
child_lines.append(
self._child_summary_line(dir_uri, global_idx, item, batch_link_map)
@@ -1468,9 +1486,7 @@ class SemanticProcessor(DequeueHandlerBase):
)
batch_prompts.append((batch_idx, prompt, batch_link_map))
- async def _run_batch(
- batch_idx: int, prompt: str, batch_link_map: Dict[str, str]
- ) -> None:
+ async def _run_batch(batch_idx: int, prompt: str, batch_link_map: Dict[str, str]) -> None:
try:
async with llm_sem:
with bind_telemetry_stage("resource_summarize"):
@@ -1494,8 +1510,9 @@ class SemanticProcessor(DequeueHandlerBase):
return partial_overviews[0]
# Merge partials only; each child abstract is already represented once.
- # Placeholders were already resolved to real URIs in each partial, so no
- # further link substitution is needed after the merge.
+ # Partials already contain real URIs, but the shared generation prompt can
+ # make the merge model emit placeholders again. Resolve the merged output
+ # with the complete map before persisting it.
combined = "\n\n---\n\n".join(partial_overviews)
try:
prompt = render_prompt(
@@ -1510,6 +1527,7 @@ class SemanticProcessor(DequeueHandlerBase):
)
with bind_telemetry_stage("resource_summarize"):
overview = await vlm.get_completion_async(prompt)
+ overview = self._replace_link_references(overview, link_map)
return overview.strip()
except Exception as e:
logger.error(
diff --git a/tests/storage/test_semantic_processor_l0_l1.py b/tests/storage/test_semantic_processor_l0_l1.py
index bbbb43e02..1603d4adb 100644
--- a/tests/storage/test_semantic_processor_l0_l1.py
+++ b/tests/storage/test_semantic_processor_l0_l1.py
@@ -99,6 +99,38 @@ def test_link_references_are_replaced_inside_markdown_overview(monkeypatch):
)
+def test_parse_overview_uses_decoded_link_target_name_as_cache_key(monkeypatch):
+ _patch_semantic_limits(monkeypatch)
+ processor = SemanticProcessor()
+ overview = (
+ "# docs\n\n"
+ "## Detailed Description\n\n"
+ "### [Friendly title](viking://resources/docs/README%20guide%23intro.md)\n"
+ "Reusable summary.\n"
+ )
+
+ assert processor._parse_overview_md(overview) == {"README guide#intro.md": "Reusable summary."}
+
+
+def test_parse_overview_keeps_plain_heading_cache_key(monkeypatch):
+ _patch_semantic_limits(monkeypatch)
+ processor = SemanticProcessor()
+ overview = "# docs\n\n## Detailed Description\n\n### README.md\nLegacy summary.\n"
+
+ assert processor._parse_overview_md(overview) == {"README.md": "Legacy summary."}
+
+
+def test_markdown_link_target_percent_encodes_uri_path_characters(monkeypatch):
+ _patch_semantic_limits(monkeypatch)
+ processor = SemanticProcessor()
+
+ target = processor._markdown_link_target(
+ "viking://resources/product docs", "file #1(approved).md"
+ )
+
+ assert target == ("viking://resources/product%20docs/file%20%231%28approved%29.md")
+
+
def test_abstract_truncation_prefers_complete_sentence(monkeypatch):
_patch_semantic_limits(monkeypatch, abstract_max_chars=80)
processor = SemanticProcessor()
diff --git a/tests/storage/test_semantic_processor_overview_batching.py b/tests/storage/test_semantic_processor_overview_batching.py
index 96244756f..8b5212e3b 100644
--- a/tests/storage/test_semantic_processor_overview_batching.py
+++ b/tests/storage/test_semantic_processor_overview_batching.py
@@ -21,6 +21,16 @@ class RecordingVLM:
return f"overview-{len(self.prompts)}"
+class MergePlaceholderVLM(RecordingVLM):
+ async def get_completion_async(self, prompt):
+ self.prompts.append(prompt)
+ if len(self.prompts) == 1:
+ return "[first](viking://input_sample_f1)"
+ if len(self.prompts) == 2:
+ return "[second](viking://input_sample_f2)"
+ return "[first](viking://input_sample_f1) and [second](viking://input_sample_f2)"
+
+
@pytest.mark.asyncio
async def test_children_only_oversized_overview_is_batched(monkeypatch):
vlm = RecordingVLM()
@@ -98,3 +108,41 @@ async def test_sampled_overview_prompt_describes_full_directory_coverage(monkeyp
assert "Summaries provided for this aggregation: 1" in coverage
assert "Direct entries not individually shown: 512" in coverage
assert "Coverage: sampled" in coverage
+
+
+async def test_batched_merge_resolves_placeholders_from_merge_output(monkeypatch):
+ vlm = MergePlaceholderVLM()
+ config = SimpleNamespace(
+ vlm=vlm,
+ semantic=SimpleNamespace(
+ max_overview_prompt_chars=1,
+ overview_batch_size=1,
+ ),
+ output_language_override="en",
+ )
+ monkeypatch.setattr(
+ semantic_processor_module,
+ "get_openviking_config",
+ lambda: config,
+ )
+ monkeypatch.setattr(
+ semantic_processor_module,
+ "render_prompt",
+ lambda _name, values: values["file_summaries"],
+ )
+
+ overview = await SemanticProcessor()._generate_overview(
+ "viking://resources/product docs",
+ file_summaries=[
+ {"name": "first file.md", "summary": "first summary"},
+ {"name": "second#file.md", "summary": "second summary"},
+ ],
+ children_abstracts=[],
+ )
+
+ assert overview == (
+ "[first](viking://resources/product%20docs/first%20file.md) and "
+ "[second](viking://resources/product%20docs/second%23file.md)"
+ )
+ assert "viking://input_sample_" not in overview