Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(storage): 恢复 cp/mv 旧版逐 URI 向量读取 (#5151)
Kchen936ceaab9f5b
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.pyindex 7d079bb69..61b9931f0 100644--- a/openviking/storage/viking_vector_index_backend.py+++ b/openviking/storage/viking_vector_index_backend.py@@ -1761,6 +1761,42 @@ class VikingVectorIndexBackend:# and may change between the count and paginated reads.return And([Eq("account_id", ctx.account_id), Or(scopes)])+ async def _read_uri_transfer_entries(+ self,+ ctx: RequestContext,+ entry_uris: List[str],+ *,+ include_full_records: bool,+ ) -> tuple[List[Dict[str, Any]], int]:+ """Use legacy per-entry reads; concurrent misses do not abort a transfer.++ Each URI has the pre-transaction limit of 100 records. Do not count or+ sort: separate aggregate and search requests need not share a snapshot.+ Backend failures still propagate, unlike the legacy fail-open query API.+ """+ backend = self._get_backend_for_context(ctx)+ records: Dict[str, Dict[str, Any]] = {}+ entries = sorted(set(entry_uris))+ for uri in entries:+ page = await backend.strict_query(+ filter=self._uri_transfer_filter(ctx, uri, recursive=False),+ limit=100,+ output_fields=["id", "uri"],+ )+ ids = [+ str(record["id"])+ for record in page+ if record.get("id") and record.get("uri") == uri+ ]+ if include_full_records and ids:+ page = await self._strict_transfer_get(ctx, ids)+ records.update(+ (str(record["id"]), record)+ for record in page+ if record.get("uri") == uri and str(record.get("id")) in ids+ )+ return list(records.values()), len(entries)+async def _scan_uri_transfer_scope(self,ctx: RequestContext,@@ -1916,26 +1952,18 @@ class VikingVectorIndexBackend:resolve_uri(uri).urifor uri in (source_uris if source_uris is not None else [source_uri])}- if source_uris is None:+ use_entry_queries = source_uris is not None or not recursive+ if not use_entry_queries:+ # Direct vector callers without a filesystem manifest retain subtree scans.source_records, batches = await self._scan_uri_transfer_scope(ctx, source_uri, recursive=recursive, include_full_records=True)else:# Filesystem transfers supply the actual entries under their locks.# Match legacy mv: do not discover independent #chunk_* records.- source_records = []- batches = 0- source_entries = sorted(selected_source_uris)- for offset in range(0, len(source_entries), 100):- records, scanned_batches = await self._scan_uri_transfer_scope(- ctx,- source_uri,- recursive=False,- include_full_records=True,- entry_uris=source_entries[offset : offset + 100],- )- source_records.extend(records)- batches += scanned_batches+ source_records, batches = await self._read_uri_transfer_entries(+ ctx, list(selected_source_uris), include_full_records=True+ )# Match legacy mv: unindexed source entries leave old target records intact.if not source_records:@@ -1982,22 +2010,29 @@ class VikingVectorIndexBackend:preserved_acl_uris = {uri for uri in replacement_target_uris - written_uris if is_acl_uri(uri)}- # Bound the query expression and avoid scanning destination-only subtrees.- target_entries = sorted(replacement_target_uris)+ # Query only overwritten entries, never destination-only subtrees.affected_target_ids: List[str] = []- for offset in range(0, len(target_entries), 100):- target_records, _ = await self._scan_uri_transfer_scope(- ctx,- target_uri,- recursive=False,- include_full_records=False,- entry_uris=target_entries[offset : offset + 100],+ if use_entry_queries:+ target_records, _ = await self._read_uri_transfer_entries(+ ctx, list(replacement_target_uris), include_full_records=False)- for record in target_records:- if record["uri"] not in preserved_acl_uris and not await is_independent_target(- str(record["uri"])- ):- affected_target_ids.append(str(record["id"]))+ else:+ target_records = []+ target_entries = sorted(replacement_target_uris)+ for offset in range(0, len(target_entries), 100):+ records, _ = await self._scan_uri_transfer_scope(+ ctx,+ target_uri,+ recursive=False,+ include_full_records=False,+ entry_uris=target_entries[offset : offset + 100],+ )+ target_records.extend(records)+ for record in target_records:+ if record["uri"] not in preserved_acl_uris and not await is_independent_target(+ str(record["uri"])+ ):+ affected_target_ids.append(str(record["id"]))target_acl_fields: Dict[str, Dict[str, Any]] = {}if preserve_target_acl and self._acl_enabled(ctx) and replacement_target_uris:assert self.acl_manager is not Nonediff --git a/tests/storage/test_transfer_merge_binding.py b/tests/storage/test_transfer_merge_binding.pyindex 5ebbef5df..9d4399e95 100644--- a/tests/storage/test_transfer_merge_binding.py+++ b/tests/storage/test_transfer_merge_binding.py@@ -73,6 +73,120 @@ async def seed_vector(backend, uri, content):)[email protected]("operation", ["cp", "mv"])[email protected]("directory", [False, True])[email protected]("phase", ["source", "target"])+async def test_transfer_uses_queries_without_count_or_sort(+ indexed_fs, monkeypatch, operation, directory, phase+):+ fs, backend = indexed_fs+ ctx = root_ctx()+ source, target = "viking://resources/source", "viking://resources/target"+ source_file = source + "/a.md" if directory else source+ target_file = target + "/a.md" if directory else target+ await fs.write_file_bytes(source_file, b"new", ctx=ctx)+ await fs.write_file_bytes(target_file, b"old", ctx=ctx)+ await seed_vector(backend, source_file, "new")+ await seed_vector(backend, target_file, "old")+ adapter = backend._get_backend_for_context(ctx)._adapter+ original_count, original_query = adapter.count, adapter.query+ count_calls, queries = [], []++ def stale_count(*args, **kwargs):+ count_calls.append(True)+ count = original_count(*args, **kwargs)+ return count + (len(count_calls) == (1 if phase == "source" else 2))++ def query(**kwargs):+ queries.append(kwargs)+ return original_query(**kwargs)++ monkeypatch.setattr(adapter, "count", stale_count)+ monkeypatch.setattr(adapter, "query", query)+ await getattr(fs, operation)(+ source, target, ctx=ctx, **({"recursive": directory} if operation == "cp" else {})+ )++ assert not count_calls+ assert len(queries) >= 2 # Both source reads and target replacement use this path.+ assert all(+ q.get("order_by") is None and q["offset"] == 0 and q["limit"] == 100 for q in queries+ )+ assert await fs.read_file_bytes(target_file, ctx=ctx) == b"new"+ records = await backend.get([vector_record_id(ctx.account_id, target_file, 2)], ctx=ctx)+ assert [record["abstract"] for record in records] == ["new"]+ assert await fs.exists(source, ctx=ctx) == (operation == "cp")++[email protected]("operation", ["cp", "mv"])[email protected]("disappear_all", [False, True])+async def test_transfer_skips_source_record_disappearing_before_fetch(+ indexed_fs, monkeypatch, operation, disappear_all+):+ fs, backend = indexed_fs+ ctx = root_ctx()+ source, target = "viking://resources/source", "viking://resources/target"+ a, b = source + "/a.md", source + "/b.md"+ for uri in [a, b]:+ await fs.write_file_bytes(uri, b"new", ctx=ctx)+ await seed_vector(backend, uri, "new")+ await seed_vector(backend, target + "/b.md", "old target index")+ original_get = backend._strict_transfer_get++ async def get_after_delete(ctx, ids):+ missing = [uri for uri in ids if uri == b or (disappear_all and uri == a)]+ if missing:+ await backend._get_backend_for_context(ctx).strict_delete(missing)+ return await original_get(ctx, ids)++ monkeypatch.setattr(backend, "_strict_transfer_get", get_after_delete)+ result = await getattr(fs, operation)(+ source, target, ctx=ctx, **({"recursive": True} if operation == "cp" else {})+ )+ assert result["vectors"]["written"] == (0 if disappear_all else 1)+ assert await fs.read_file_bytes(target + "/b.md", ctx=ctx) == b"new"+ records = await backend.get([target + "/b.md"], ctx=ctx)+ assert [record["abstract"] for record in records] == ["old target index"]+ assert bool(+ await backend.get([vector_record_id(ctx.account_id, target + "/a.md", 2)], ctx=ctx)+ ) == (not disappear_all)++[email protected]("operation", ["cp", "mv"])[email protected]("failure", ["source_query", "target_query", "source_fetch"])+async def test_transfer_propagates_legacy_read_errors(indexed_fs, monkeypatch, operation, failure):+ fs, backend = indexed_fs+ ctx = root_ctx()+ source, target = "viking://resources/source.md", "viking://resources/target.md"+ await fs.write_file_bytes(source, b"new", ctx=ctx)+ await fs.write_file_bytes(target, b"old", ctx=ctx)+ await seed_vector(backend, source, "new")+ await seed_vector(backend, target, "old")+ adapter = backend._get_backend_for_context(ctx)._adapter+ original_query, original_get = adapter.query, adapter.get++ def query(**kwargs):+ records = original_query(**kwargs)+ failed_uri = target if failure == "target_query" else source+ if failure.endswith("query") and any(r["uri"] == failed_uri for r in records):+ raise RuntimeError("backend unavailable")+ return records++ def get(ids):+ if failure == "source_fetch" and source in ids:+ raise RuntimeError("backend unavailable")+ return original_get(ids)++ monkeypatch.setattr(adapter, "query", query)+ monkeypatch.setattr(adapter, "get", get)+ with pytest.raises(RuntimeError, match="backend unavailable"):+ await getattr(fs, operation)(source, target, ctx=ctx)+ assert await fs.read_file_bytes(source, ctx=ctx) == b"new"++@pytest.mark.asyncio@pytest.mark.parametrize("operation", ["cp", "mv"])@pytest.mark.parametrize("directory", [False, True])@@ -99,27 +213,30 @@ async def test_transfer_ignores_concurrent_sibling_index_changes(await fs.write_file_bytes(sibling, b"unrelated", ctx=ctx)await seed_vector(backend, sibling, "unrelated")- original_count = backend._strict_transfer_count- count_calls = 0+ account_backend = backend._get_backend_for_context(ctx)+ original_query = account_backend.strict_query+ trigger_uri = source_file if phase == "source" else target_file+ changed = False- async def count_with_sibling_change(*args, **kwargs):- nonlocal count_calls- count = await original_count(*args, **kwargs)- count_calls += 1- if count_calls == (1 if phase == "source" else 2):+ async def query_with_sibling_change(*args, **kwargs):+ nonlocal changed+ records = await original_query(*args, **kwargs)+ if not changed and any(record["uri"] == trigger_uri for record in records):+ changed = True# No transfer lease is supplied: this is an independent writer.if mutation == "add":await fs.write_file_bytes(sibling, b"unrelated", ctx=ctx)await seed_vector(backend, sibling, "unrelated")else:await fs.rm(sibling, ctx=ctx)- return count+ return records- monkeypatch.setattr(backend, "_strict_transfer_count", count_with_sibling_change)+ monkeypatch.setattr(account_backend, "strict_query", query_with_sibling_change)await getattr(fs, operation)(source, target, ctx=ctx, **({"recursive": directory} if operation == "cp" else {}))+ assert changedassert await fs.read_file_bytes(target_file, ctx=ctx) == b"new"copied = await backend.get_context_by_uri(target_file, ctx=ctx)copied = await backend.get([record["id"] for record in copied], ctx=ctx)@@ -162,7 +279,7 @@ async def test_transfer_preserves_legacy_independent_chunk_records(@pytest.mark.asyncio@pytest.mark.parametrize("operation", ["cp", "mv"])-async def test_directory_transfer_batches_exact_entries_with_native_storage(+async def test_directory_transfer_reads_all_exact_entries_with_native_storage(indexed_fs, monkeypatch, operation):fs, backend = indexed_fs@@ -189,14 +306,15 @@ async def test_directory_transfer_batches_exact_entries_with_native_storage(ctx=ctx,)read_ids: set[str] = set()- original_page = backend._strict_transfer_page+ account_backend = backend._get_backend_for_context(ctx)+ original_query = account_backend.strict_query- async def tracked_page(*args, **kwargs):- page, cursor = await original_page(*args, **kwargs)+ async def tracked_query(*args, **kwargs):+ page = await original_query(*args, **kwargs)read_ids.update(record["id"] for record in page)- return page, cursor+ return page- monkeypatch.setattr(backend, "_strict_transfer_page", tracked_page)+ monkeypatch.setattr(account_backend, "strict_query", tracked_query)result = await getattr(fs, operation)(source, target, ctx=ctx, **({"recursive": True} if operation == "cp" else {}))diff --git a/tests/storage/test_vector_transfer.py b/tests/storage/test_vector_transfer.pyindex 6b26ee4e5..791a78747 100644--- a/tests/storage/test_vector_transfer.py+++ b/tests/storage/test_vector_transfer.py@@ -70,6 +70,17 @@ class _MemoryTransferBackend(VikingVectorIndexBackend):def mode(self) -> str:return self.backend_mode+ def _get_backend_for_context(self, ctx):+ del ctx+ return SimpleNamespace(strict_query=self._query)++ async def _query(self, *, filter, limit=10, offset=0, output_fields=None):+ del output_fields+ self.scroll_filters.append(filter)+ return [+ dict(record) for record in self.records.values() if _matches_filter(filter, record)+ ][offset : offset + limit]+async def scroll(self,filter=None,@@ -523,6 +534,89 @@ async def test_transfer_scan_emits_supported_aggregate_request()+async def test_legacy_transfer_reads_use_private_adapter_query_and_fetch(monkeypatch):+ source = "viking://resources/source.md"+ backend = _MemoryTransferBackend([])+ adapter = VikingDBPrivateCollectionAdapter(+ host="unused.invalid",+ headers=None,+ project_name="test",+ collection_name="context",+ index_name="default",+ )+ collection = VikingDBCollection(+ host="unused.invalid", meta_data={"ProjectName": "test", "CollectionName": "context"}+ )+ adapter._collection = Collection(collection)+ account_backend = _SingleAccountBackend(VectorDBBackendConfig(), "acct", shared_adapter=adapter)+ monkeypatch.setattr(backend, "_get_backend_for_context", lambda ctx: account_backend)+ monkeypatch.setattr(+ backend,+ "_strict_transfer_get",+ VikingVectorIndexBackend._strict_transfer_get.__get__(backend),+ )+ monkeypatch.setattr(+ "openviking.storage.vectordb_adapters.base.get_openviking_config",+ lambda: SimpleNamespace(embedding=SimpleNamespace(dimension=2)),+ )+ paths = []++ def data_post(path, data):+ paths.append(path)+ if path == "/api/vikingdb/data/search/vector":+ assert data["limit"] == 100 and data["offset"] == 0+ assert len(data["dense_vector"]) == 2+ assert "field" not in data and "order" not in data+ assert data["filter"] == {+ "op": "and",+ "conds": [+ {"op": "must", "field": "account_id", "conds": ["acct"]},+ {+ "op": "and",+ "conds": [+ {"op": "must", "field": "account_id", "conds": ["acct"]},+ {+ "op": "must",+ "field": "uri",+ "conds": ["/resources/source.md"],+ "para": "-d=0",+ },+ ],+ },+ ],+ }+ return {+ "data": [+ {"id": "file", "fields": {"uri": "/resources/source.md"}},+ {"id": "gone", "fields": {"uri": "/resources/source.md"}},+ ]+ }+ if path == "/api/vikingdb/data/fetch_in_collection":+ assert data["ids"] == ["file", "gone"]+ return {+ "fetch": [+ {+ "id": "file",+ "fields": {+ "uri": "/resources/source.md",+ "account_id": "acct",+ "vector": [0.1, 0.2],+ },+ }+ ],+ "ids_not_exist": ["gone"],+ }+ raise AssertionError(f"Legacy reads must not use aggregate or scalar search: {path}")++ monkeypatch.setattr(collection, "_data_post", data_post)+ records, _ = await backend._read_uri_transfer_entries(+ _ctx(), [source], include_full_records=True+ )+ assert [(r["id"], r["uri"], r["vector"]) for r in records] == [("file", source, [0.1, 0.2])]+ assert paths == ["/api/vikingdb/data/search/vector", "/api/vikingdb/data/fetch_in_collection"]++@pytest.mark.asyncio@pytest.mark.parametrize("transfer_method", ["copy_uri_mapping", "update_uri_mapping"])async def test_uri_mapping_overwrites_exact_target_and_leaves_independent_chunks(@@ -597,15 +691,15 @@ async def test_merge_target_scan_excludes_unrelated_subtrees(backend = _RealAclMemoryTransferBackend(source_records + old_records + unique_records)backend.acl_manager = Nonebackend.backend_mode = backend_mode- original_page = backend._strict_transfer_page+ original_query = backend._queryread_ids: list[str] = []- async def counted_page(*args, **kwargs):- page, cursor = await original_page(*args, **kwargs)+ async def counted_query(*args, **kwargs):+ page = await original_query(*args, **kwargs)read_ids.extend(str(record["id"]) for record in page)- return page, cursor+ return page- monkeypatch.setattr(backend, "_strict_transfer_page", counted_page)+ monkeypatch.setattr(backend, "_query", counted_query)result = await getattr(backend, transfer_method)(_ctx(), source, target, recursive=True, source_uris=[source, f"{source}/a.md"])@@ -617,6 +711,22 @@ async def test_merge_target_scan_excludes_unrelated_subtrees(assert all(backend.records[record["id"]] == record for record in unique_records)[email protected]("transfer_method", ["copy_uri_mapping", "update_uri_mapping"])+async def test_direct_recursive_transfer_keeps_complete_target_scan(transfer_method):+ source, target = "viking://resources/source", "viking://resources/target"+ old_ids = [f"old-{i}" for i in range(101)]+ backend = _RealAclMemoryTransferBackend(+ [_record("source", source)] + [_record(record_id, target) for record_id in old_ids]+ )+ backend.acl_manager = None++ await getattr(backend, transfer_method)(_ctx(), source, target, recursive=True)++ assert not set(old_ids).intersection(backend.records)+ assert len(_records_under(backend, target)) == 1++@pytest.mark.asyncio@pytest.mark.parametrize("transfer_method", ["copy_uri_mapping", "update_uri_mapping"])async def test_target_replacement_cleans_exact_entries_across_batches(transfer_method):