Skip to content

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

fix: auto-rename on duplicate filename conflict (#178) (#197)

Ethon14795ffa9aa1
diff --git a/openviking/parse/tree_builder.py b/openviking/parse/tree_builder.py
index 353590442..903e822d2 100644
--- a/openviking/parse/tree_builder.py
+++ b/openviking/parse/tree_builder.py
@@ -119,8 +119,11 @@ class TreeBuilder:
logger.info(f"Finalizing from temp: {temp_uri} -> {base_uri}")
- # 3. Build final URI using VikingURI.join to handle slashes correctly
- final_uri = VikingURI(base_uri).join(doc_name).uri
+ # 3. Build final URI, auto-renaming on conflict (e.g. doc_1, doc_2, ...)
+ candidate_uri = VikingURI(base_uri).join(doc_name).uri
+ final_uri = await self._resolve_unique_uri(candidate_uri)
+ if final_uri != candidate_uri:
+ logger.info(f"Resolved name conflict: {candidate_uri} -> {final_uri}")
# 4. Move directory tree from temp to final location in AGFS
await self._move_directory_in_agfs(doc_uri, final_uri)
@@ -152,6 +155,34 @@ class TreeBuilder:
return tree
+ async def _resolve_unique_uri(self, uri: str, max_attempts: int = 100) -> str:
+ """Return a URI that does not collide with an existing resource.
+
+ If *uri* is free, return it unchanged. Otherwise append ``_1``,
+ ``_2``, … until a free name is found (like macOS Finder / Windows
+ Explorer).
+ """
+ viking_fs = get_viking_fs()
+
+ async def _exists(u: str) -> bool:
+ try:
+ await viking_fs.stat(u)
+ return True
+ except Exception:
+ return False
+
+ if not await _exists(uri):
+ return uri
+
+ for i in range(1, max_attempts + 1):
+ candidate = f"{uri}_{i}"
+ if not await _exists(candidate):
+ return candidate
+
+ raise FileExistsError(
+ f"Cannot resolve unique name for {uri} after {max_attempts} attempts"
+ )
+
async def _move_directory_in_agfs(self, src_uri: str, dst_uri: str) -> None:
"""Recursively move AGFS directory tree (copy + delete)."""
viking_fs = get_viking_fs()
diff --git a/tests/misc/test_tree_builder_dedup.py b/tests/misc/test_tree_builder_dedup.py
new file mode 100644
index 000000000..52f15de86
--- /dev/null
+++ b/tests/misc/test_tree_builder_dedup.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for TreeBuilder._resolve_unique_uri — duplicate filename auto-rename."""
+
+import os
+import sys
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+
+def _make_viking_fs_mock(existing_uris: set[str]):
+ """Create a mock VikingFS whose stat() raises for non-existing URIs."""
+ fs = MagicMock()
+
+ async def _stat(uri):
+ if uri in existing_uris:
+ return {"name": uri.split("/")[-1], "isDir": True}
+ raise FileNotFoundError(f"Not found: {uri}")
+
+ fs.stat = AsyncMock(side_effect=_stat)
+ return fs
+
+
+class TestResolveUniqueUri:
+
+ @pytest.mark.asyncio
+ async def test_no_conflict(self):
+ """When the URI is free, return it unchanged."""
+ from openviking.parse.tree_builder import TreeBuilder
+
+ fs = _make_viking_fs_mock(set())
+ builder = TreeBuilder()
+
+ with patch("openviking.parse.tree_builder.get_viking_fs", return_value=fs):
+ result = await builder._resolve_unique_uri("viking://resources/report")
+
+ assert result == "viking://resources/report"
+
+ @pytest.mark.asyncio
+ async def test_single_conflict(self):
+ """When base name exists, should return name_1."""
+ from openviking.parse.tree_builder import TreeBuilder
+
+ existing = {"viking://resources/report"}
+ fs = _make_viking_fs_mock(existing)
+ builder = TreeBuilder()
+
+ with patch("openviking.parse.tree_builder.get_viking_fs", return_value=fs):
+ result = await builder._resolve_unique_uri("viking://resources/report")
+
+ assert result == "viking://resources/report_1"
+
+ @pytest.mark.asyncio
+ async def test_multiple_conflicts(self):
+ """When _1 and _2 also exist, should return _3."""
+ from openviking.parse.tree_builder import TreeBuilder
+
+ existing = {
+ "viking://resources/report",
+ "viking://resources/report_1",
+ "viking://resources/report_2",
+ }
+ fs = _make_viking_fs_mock(existing)
+ builder = TreeBuilder()
+
+ with patch("openviking.parse.tree_builder.get_viking_fs", return_value=fs):
+ result = await builder._resolve_unique_uri("viking://resources/report")
+
+ assert result == "viking://resources/report_3"
+
+ @pytest.mark.asyncio
+ async def test_max_attempts_exceeded(self):
+ """When all candidate names are taken, raise FileExistsError."""
+ from openviking.parse.tree_builder import TreeBuilder
+
+ existing = {"viking://resources/report"} | {
+ f"viking://resources/report_{i}" for i in range(1, 6)
+ }
+ fs = _make_viking_fs_mock(existing)
+ builder = TreeBuilder()
+
+ with patch("openviking.parse.tree_builder.get_viking_fs", return_value=fs):
+ with pytest.raises(FileExistsError, match="Cannot resolve unique name"):
+ await builder._resolve_unique_uri(
+ "viking://resources/report", max_attempts=5
+ )
+
+ @pytest.mark.asyncio
+ async def test_gap_in_sequence(self):
+ """If _1 exists but _2 does not, should return _2 (not skip to _3)."""
+ from openviking.parse.tree_builder import TreeBuilder
+
+ existing = {
+ "viking://resources/report",
+ "viking://resources/report_1",
+ }
+ fs = _make_viking_fs_mock(existing)
+ builder = TreeBuilder()
+
+ with patch("openviking.parse.tree_builder.get_viking_fs", return_value=fs):
+ result = await builder._resolve_unique_uri("viking://resources/report")
+
+ assert result == "viking://resources/report_2"