Skip to content

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

fix(storage): 恢复 cp/mv 精确条目查询,避免同级索引并发干扰 (#5119)

Kchen149b8637876f
diff --git a/openviking/storage/viking_vector_index_backend.py b/openviking/storage/viking_vector_index_backend.py
index 5211b2bc8..7d079bb69 100644
--- a/openviking/storage/viking_vector_index_backend.py
+++ b/openviking/storage/viking_vector_index_backend.py
@@ -43,7 +43,6 @@ from openviking.utils.time_utils import get_current_timestamp
from openviking_cli.exceptions import InvalidArgumentError
from openviking_cli.utils import get_logger
from openviking_cli.utils.config.vectordb_config import DEFAULT_INDEX_NAME, VectorDBBackendConfig
-from openviking_cli.utils.uri import VikingURI
logger = get_logger(__name__)
@@ -202,6 +201,7 @@ class _AsyncVectorAdapter:
await asyncio.to_thread(_update)
+
class _SingleAccountBackend:
"""绑定单个 account 的后端实现(内部类)"""
@@ -1757,11 +1757,8 @@ class VikingVectorIndexBackend:
scopes: List[FilterExpr] = [Eq("uri", uri)]
if recursive:
scopes.append(PathScope("uri", uri, depth=-1))
- # Chunk URIs are siblings in the path index. Scan one parent level and
- # filter exact transfer entries below, without backend-specific operators.
- parent = VikingURI(uri).parent
- if parent is not None and parent.uri != "viking://":
- scopes.append(PathScope("uri", parent.uri, depth=1))
+ # Never include the parent: unrelated siblings are outside transfer locks
+ # and may change between the count and paginated reads.
return And([Eq("account_id", ctx.account_id), Or(scopes)])
async def _scan_uri_transfer_scope(
@@ -1822,9 +1819,10 @@ class VikingVectorIndexBackend:
for record in page
if isinstance(record.get("uri"), str)
and (
- self._vector_entry_uri(record["uri"], selected_entries) in selected_entries
+ record["uri"] in selected_entries
if selected_entries is not None
- else uri_in_transfer_scope(record["uri"], uri, recursive=recursive)
+ else record["uri"] == uri
+ or (recursive and record["uri"].startswith(uri.rstrip("/") + "/"))
)
]
if include_full_records and scoped:
@@ -1914,24 +1912,30 @@ class VikingVectorIndexBackend:
target_entry_exists: Callable[[str], Awaitable[bool]] | None = None,
) -> tuple[List[Dict[str, Any]], int, Dict[str, Dict[str, Any]]]:
"""Read selected source records and remove affected target records."""
- source_records, batches = await self._scan_uri_transfer_scope(
- ctx,
- source_uri,
- recursive=recursive,
- include_full_records=True,
- )
-
selected_source_uris = {
resolve_uri(uri).uri
for uri in (source_uris if source_uris is not None else [source_uri])
}
- if source_uris is not None:
- source_records = [
- record
- for record in source_records
- if self._vector_entry_uri(str(record["uri"]), selected_source_uris)
- in selected_source_uris
- ]
+ if source_uris is None:
+ 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
# Match legacy mv: unindexed source entries leave old target records intact.
if not source_records:
diff --git a/tests/storage/test_transfer_merge_binding.py b/tests/storage/test_transfer_merge_binding.py
index 2631eaa80..5ebbef5df 100644
--- a/tests/storage/test_transfer_merge_binding.py
+++ b/tests/storage/test_transfer_merge_binding.py
@@ -74,35 +74,121 @@ async def seed_vector(backend, uri, content):
@pytest.mark.asyncio
[email protected]("operation", ["copy_uri_mapping", "update_uri_mapping"])
[email protected]("operation", ["cp", "mv"])
[email protected]("directory", [False, True])
[email protected]("phase", ["source", "target"])
[email protected]("mutation", ["add", "delete"])
+async def test_transfer_ignores_concurrent_sibling_index_changes(
+ indexed_fs, monkeypatch, operation, directory, phase, mutation
+):
+ fs, backend = indexed_fs
+ ctx = root_ctx()
+ source, target = "viking://resources/source", "viking://resources/target"
+ source_file = source + "/file.md" if directory else source
+ target_file = target + "/file.md" if directory else target
+ sibling = "viking://resources/unrelated.md"
+ 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")
+ if directory:
+ await seed_vector(backend, source, "source summary")
+ await seed_vector(backend, target, "target summary")
+ await fs.write_file_bytes(target + "/keep.md", b"keep", ctx=ctx)
+ if mutation == "delete":
+ 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
+
+ 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):
+ # 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
+
+ monkeypatch.setattr(backend, "_strict_transfer_count", count_with_sibling_change)
+ await getattr(fs, operation)(
+ source, target, ctx=ctx, **({"recursive": directory} if operation == "cp" else {})
+ )
+
+ assert 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)
+ assert [record["abstract"] for record in copied] == ["new"]
+ assert await fs.exists(source, ctx=ctx) == (operation == "cp")
+ assert await fs.exists(sibling, ctx=ctx) == (mutation == "add")
+ if directory:
+ assert await fs.read_file_bytes(target + "/keep.md", ctx=ctx) == b"keep"
+
+
[email protected]("operation", ["cp", "mv"])
@pytest.mark.parametrize("directory", [False, True])
-async def test_path_transfer_scans_native_chunks_without_unrelated_subtrees(
- indexed_fs, monkeypatch, operation, directory
+async def test_transfer_preserves_legacy_independent_chunk_records(
+ indexed_fs, operation, directory
):
- _, backend = indexed_fs
+ fs, backend = indexed_fs
ctx = root_ctx()
- source_file = "viking://resources/source/file.md"
- target_file = "viking://resources/target/file.md"
- source = "viking://resources/source" if directory else source_file
- target = "viking://resources/target" if directory else target_file
- source_uris = [source_file] + [f"{source_file}#chunk_{i:04d}" for i in range(205)]
- old_targets = [target_file] + [f"{target_file}#chunk_{i:04d}" for i in range(206)]
+ source, target = "viking://resources/source", "viking://resources/target"
+ source_file = source + "/file.md" if directory else source
+ target_file = target + "/file.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")
+ source_chunk = source_file + "#chunk_0001"
+ target_chunk = target_file + "#chunk_old"
+ await seed_vector(backend, source_chunk, "source chunk")
+ await seed_vector(backend, target_chunk, "old target chunk")
+
+ await getattr(fs, operation)(
+ source, target, ctx=ctx, **({"recursive": directory} if operation == "cp" else {})
+ )
+
+ assert await fs.read_file_bytes(target_file, ctx=ctx) == b"new"
+ assert await backend.get_context_by_uri(source_chunk, ctx=ctx)
+ assert await backend.get_context_by_uri(target_chunk, ctx=ctx)
+ assert not await backend.get_context_by_uri(target_file + "#chunk_0001", ctx=ctx)
+
+
[email protected]("operation", ["cp", "mv"])
+async def test_directory_transfer_batches_exact_entries_with_native_storage(
+ indexed_fs, monkeypatch, operation
+):
+ fs, backend = indexed_fs
+ ctx = root_ctx()
+ source, target = "viking://resources/source", "viking://resources/target"
+ names = [f"file-{i:03d}.md" for i in range(205)] + ["literal.md#chunk_0001"]
+ for name in names:
+ await fs.write_file_bytes(f"{source}/{name}", b"new", ctx=ctx)
+ await fs.write_file_bytes(f"{target}/keep.md", b"keep", ctx=ctx)
+ source_uris = [f"{source}/{name}" for name in names]
+ old_targets = [f"{target}/{name}" for name in names]
untouched = [
- "viking://resources/target/keep.md",
- "viking://resources/target/unrelated/deep.md",
+ f"{source}/missing.md", # Orphan index, absent from the filesystem manifest.
+ f"{source}/file-000.md#chunk_0001",
+ f"{target}/file-000.md#chunk_old",
+ f"{target}/keep.md",
+ f"{target}/unrelated/deep.md",
]
- records = [
- {
- "id": uri,
- "uri": uri,
- "level": 2,
- "vector": [0.1, 0.2, 0.3, 0.4],
- "account_id": ctx.account_id,
- }
- for uri in source_uris + old_targets + untouched
- ]
- await backend._upsert_many_raw(records, ctx=ctx)
- read_ids = set()
+ await backend._upsert_many_raw(
+ [
+ {"id": uri, "uri": uri, "level": 2, "vector": [0.1] * 4, "account_id": ctx.account_id}
+ for uri in source_uris + old_targets + untouched
+ ],
+ ctx=ctx,
+ )
+ read_ids: set[str] = set()
original_page = backend._strict_transfer_page
async def tracked_page(*args, **kwargs):
@@ -111,26 +197,21 @@ async def test_path_transfer_scans_native_chunks_without_unrelated_subtrees(
return page, cursor
monkeypatch.setattr(backend, "_strict_transfer_page", tracked_page)
- result = await getattr(backend, operation)(
- ctx,
- source,
- target,
- recursive=directory,
- **({"source_uris": [source, source_file]} if directory else {}),
+ result = await getattr(fs, operation)(
+ source, target, ctx=ctx, **({"recursive": True} if operation == "cp" else {})
)
- assert result.scanned == result.written == 206
- assert result.batches >= 3
+ assert result["vectors"]["scanned"] == result["vectors"]["written"] == len(names)
+ assert result["vectors"]["batches"] >= 3
assert set(source_uris + old_targets).issubset(read_ids)
- assert untouched[1] not in read_ids
- expected_targets = [target_file] + [f"{target_file}#chunk_{i:04d}" for i in range(205)]
- target_ids = [vector_record_id(ctx.account_id, uri, 2) for uri in expected_targets]
- copied = await backend.get(target_ids, ctx=ctx)
- assert {record["uri"] for record in copied} == set(expected_targets)
+ assert not set(untouched).intersection(read_ids)
+ target_ids = [vector_record_id(ctx.account_id, uri, 2) for uri in old_targets]
+ assert {record["uri"] for record in await backend.get(target_ids, ctx=ctx)} == set(old_targets)
assert not await backend.get(old_targets, ctx=ctx)
assert {record["uri"] for record in await backend.get(untouched, ctx=ctx)} == set(untouched)
- remaining_source = await backend.get(source_uris, ctx=ctx)
- assert len(remaining_source) == (206 if operation == "copy_uri_mapping" else 0)
+ assert len(await backend.get(source_uris, ctx=ctx)) == (len(names) if operation == "cp" else 0)
+ assert await fs.read_file_bytes(f"{target}/keep.md", ctx=ctx) == b"keep"
+ assert await fs.read_file_bytes(f"{target}/literal.md#chunk_0001", ctx=ctx) == b"new"
@pytest.mark.asyncio
@@ -218,8 +299,8 @@ async def test_chunk_only_copy_preserves_private_target_main_record(indexed_fs):
main = await backend.get(["private-target"], ctx=ctx)
assert main[0]["abstract"] == "old"
assert main[0]["acl_direct_grants"] == old_main["acl_direct_grants"]
- assert await backend.get_context_by_uri(f"{target_file}#chunk_0000", ctx=ctx)
- assert not await backend.get_context_by_uri(f"{target_file}#chunk_old", ctx=ctx)
+ assert not await backend.get_context_by_uri(f"{target_file}#chunk_0000", ctx=ctx)
+ assert await backend.get_context_by_uri(f"{target_file}#chunk_old", ctx=ctx)
@pytest.mark.asyncio
@@ -294,20 +375,11 @@ async def test_transfer_protects_chunk_shaped_target_file(
with pytest.raises(PermissionDeniedError):
await fs.read_file_bytes(sibling, ctx=outsider)
kwargs = {"recursive": directory} if operation == "cp" else {}
- if incoming_chunk:
- with pytest.raises(InvalidArgumentError, match="chunk.*existing filesystem entry"):
- await getattr(fs, operation)(source, target, ctx=ctx, **kwargs)
- assert await fs.read_file_bytes(source_file, ctx=ctx) == b"new"
- assert await backend.get_context_by_uri(source_file, ctx=ctx)
- # Keep the approved weak rollback: vector failure removes the target
- # filesystem subtree, but must not delete or overwrite the sibling ACL.
- assert not await fs.exists(target, ctx=ctx)
- else:
- await getattr(fs, operation)(source, target, ctx=ctx, **kwargs)
- assert await fs.read_file_bytes(target_file, ctx=ctx) == b"new"
- assert await fs.read_file_bytes(sibling, ctx=ctx) == b"private sibling"
- with pytest.raises(PermissionDeniedError):
- await fs.read_file_bytes(sibling, ctx=outsider)
+ await getattr(fs, operation)(source, target, ctx=ctx, **kwargs)
+ assert await fs.read_file_bytes(target_file, ctx=ctx) == b"new"
+ assert await fs.read_file_bytes(sibling, ctx=ctx) == b"private sibling"
+ with pytest.raises(PermissionDeniedError):
+ await fs.read_file_bytes(sibling, ctx=outsider)
saved = await backend.get([sibling_id], ctx=ctx)
assert saved[0]["abstract"] == "private sibling"
assert saved[0]["acl_direct_grants"] == [f"7:user:{ctx.user.user_id}"]
@@ -350,8 +422,7 @@ async def test_directory_merge_replaces_only_affected_file_vectors(
kwargs = {"recursive": True} if operation == "cp" else {}
await getattr(fs, operation)(source, target, ctx=ctx, **kwargs)
- # Path queries may scan sibling IDs/URIs, but discard unrelated entries
- # before loading their full vector records.
+ # Exact entry queries must not load vectors for destination-only files.
assert f"{target}/only.txt" not in fetched_ids
assert f"{target}/unindexed.txt" not in fetched_ids
copied = await backend.get_context_by_uri(f"{target}/indexed.txt", ctx=ctx)
@@ -360,7 +431,7 @@ async def test_directory_merge_replaces_only_affected_file_vectors(
tasks = await backend.get_context_by_uri(f"{target}/tasks/indexed.txt", ctx=ctx)
tasks = await backend.get([record["id"] for record in tasks], ctx=ctx)
assert [record["abstract"] for record in tasks] == ["new task"]
- assert not await backend.get_context_by_uri(f"{target}/indexed.txt#chunk-9", ctx=ctx)
+ assert await backend.get_context_by_uri(f"{target}/indexed.txt#chunk-9", ctx=ctx)
stale = await backend.get_context_by_uri(f"{target}/unindexed.txt", ctx=ctx)
stale = await backend.get([record["id"] for record in stale], ctx=ctx)
assert [record["abstract"] for record in stale] == ["old raw"]
diff --git a/tests/storage/test_vector_transfer.py b/tests/storage/test_vector_transfer.py
index 85bbe97c0..6b26ee4e5 100644
--- a/tests/storage/test_vector_transfer.py
+++ b/tests/storage/test_vector_transfer.py
@@ -411,12 +411,12 @@ async def test_transfer_scan_fails_closed_on_repeated_record_page():
@pytest.mark.asyncio
-async def test_copy_uri_mapping_preserves_dense_sparse_and_chunk_payloads():
+async def test_copy_uri_mapping_preserves_dense_and_sparse_payloads():
source = "viking://resources/src.md"
backend = _MemoryTransferBackend(
[
_record("source-file", source, sparse_vector={}),
- _record("source-chunk", f"{source}#chunk_0001", vector=[]),
+ _record("source-l0", source, level=0, vector=[]),
_record("outside", "viking://resources/other.md"),
]
)
@@ -429,7 +429,6 @@ async def test_copy_uri_mapping_preserves_dense_sparse_and_chunk_payloads():
assert result.written == 2
assert {record["uri"] for record in copied} == {
"viking://resources/dst.md",
- "viking://resources/dst.md#chunk_0001",
}
assert {tuple(record["vector"]) for record in copied} == {(), (0.1, 0.2)}
assert {tuple(record["sparse_vector"].items()) for record in copied} == {
@@ -451,10 +450,7 @@ async def test_remote_transfer_scope_avoids_unsupported_contains_filter(mode):
for filter_expr in backend.scroll_filters:
assert isinstance(filter_expr, And)
scopes = next(cond for cond in filter_expr.conds if isinstance(cond, Or)).conds
- assert not any(isinstance(scope, Contains) for scope in scopes)
- assert any(
- isinstance(scope, PathScope) and scope.path == "viking://resources" for scope in scopes
- )
+ assert all(isinstance(scope, Eq) and scope.field == "uri" for scope in scopes)
@pytest.mark.asyncio
@@ -497,7 +493,7 @@ async def test_transfer_scan_emits_supported_aggregate_request(
validate_dsl(child)
elif node["field"] == "uri":
assert all(value.startswith("/") for value in node["conds"])
- assert node["para"] in {"-d=0", "-d=1", "-d=-1"}
+ assert node["para"] in {"-d=0", "-d=-1"}
async def count(ctx, filter):
def data_post(path, data):
@@ -522,12 +518,14 @@ async def test_transfer_scan_emits_supported_aggregate_request(
entry_uris=[entry] if selected_entries else None,
)
assert requests
- assert {record["id"] for record in found} == {"file", "chunk"}
+ assert {record["id"] for record in found} == (
+ {"file", "chunk"} if recursive and not selected_entries else {"file"}
+ )
@pytest.mark.asyncio
@pytest.mark.parametrize("transfer_method", ["copy_uri_mapping", "update_uri_mapping"])
-async def test_uri_mapping_overwrites_affected_target_and_removes_obsolete_chunks(
+async def test_uri_mapping_overwrites_exact_target_and_leaves_independent_chunks(
transfer_method,
):
source = "viking://resources/src.md"
@@ -545,12 +543,13 @@ async def test_uri_mapping_overwrites_affected_target_and_removes_obsolete_chunk
result = await getattr(backend, transfer_method)(_ctx(), source, target, recursive=False)
targets = sorted(_records_under(backend, target), key=lambda record: record["uri"])
- assert result.scanned == 2
- assert result.written == 2
+ assert result.scanned == result.written == 1
assert [(record["uri"], record["content"]) for record in targets] == [
(target, "new-file"),
- (f"{target}#chunk_0001", "new-chunk"),
+ (f"{target}#chunk_0001", "old-chunk"),
+ (f"{target}#chunk_0002", "obsolete"),
]
+ assert backend.records["source-chunk"]["content"] == "new-chunk"
@pytest.mark.asyncio
@@ -591,10 +590,8 @@ async def test_merge_target_scan_excludes_unrelated_subtrees(
source, target = "viking://resources/source", "viking://resources/target"
affected = f"{target}/a.md"
source_records = [_record("source-root", source), _record("source-file", f"{source}/a.md")]
- old_records = [_record("old-root", target), _record("old-file", affected)] + [
- _record(f"old-chunk-{i}", f"{affected}#chunk_{i}") for i in range(205)
- ]
- unique_records = [
+ old_records = [_record("old-root", target), _record("old-file", affected)]
+ unique_records = [_record(f"old-chunk-{i}", f"{affected}#chunk_{i}") for i in range(205)] + [
_record(f"unique-{i}", f"{target}/unrelated/file-{i}.md") for i in range(1000)
]
backend = _RealAclMemoryTransferBackend(source_records + old_records + unique_records)
@@ -622,18 +619,18 @@ async def test_merge_target_scan_excludes_unrelated_subtrees(
@pytest.mark.asyncio
@pytest.mark.parametrize("transfer_method", ["copy_uri_mapping", "update_uri_mapping"])
-async def test_target_replacement_cleans_chunks_across_entry_batches(transfer_method):
+async def test_target_replacement_cleans_exact_entries_across_batches(transfer_method):
source, target = "viking://resources/source", "viking://resources/target"
source_records = [_record(f"source-{i}", f"{source}/file-{i}.md") for i in range(101)]
- old_chunks = [_record(f"old-{i}", f"{target}/file-{i}.md#chunk_old") for i in range(101)]
- backend = _RealAclMemoryTransferBackend(source_records + old_chunks)
+ old_records = [_record(f"old-{i}", f"{target}/file-{i}.md") for i in range(101)]
+ backend = _RealAclMemoryTransferBackend(source_records + old_records)
backend.acl_manager = None
result = await getattr(backend, transfer_method)(_ctx(), source, target, recursive=True)
assert result.written == 101
assert len(_records_under(backend, target)) == 101
- assert not set(backend.records).intersection(record["id"] for record in old_chunks)
+ assert not set(backend.records).intersection(record["id"] for record in old_records)
@pytest.mark.asyncio
@@ -670,9 +667,9 @@ async def test_uri_mapping_write_failure_keeps_source_without_restoring_old_targ
backend = _MemoryTransferBackend(
[
_record("source-file", source),
- _record("source-chunk", f"{source}#chunk_0001"),
+ _record("source-l0", source, level=0),
_record("old-target-file", target, content="do-not-restore"),
- _record("old-target-chunk", f"{target}#chunk_0009", content="do-not-restore"),
+ _record("old-target-l0", target, level=0, content="do-not-restore"),
]
)
backend.fail_upsert_at = 2
@@ -724,7 +721,7 @@ async def test_uri_mapping_source_uris_limits_source_and_target_replacement_scop
@pytest.mark.asyncio
-async def test_copy_over_private_target_preserves_target_acl_for_new_chunks():
+async def test_copy_over_private_target_preserves_target_acl():
source = "viking://resources/src.md"
target = "viking://resources/dst.md"
backend = _RealAclMemoryTransferBackend(
@@ -744,10 +741,8 @@ async def test_copy_over_private_target_preserves_target_acl_for_new_chunks():
await backend.copy_uri_mapping(_ctx(), source, target, recursive=False)
targets = _records_under(backend, target, recursive=False)
- assert {record["uri"] for record in targets} == {
- target,
- f"{target}#chunk_0001",
- }
+ assert {record["uri"] for record in targets} == {target}
+ assert "source-chunk" in backend.records
assert all(record["acl_direct_grants"] == ["7:user:bob"] for record in targets)
assert all(record["acl_inherited_grants"] == [] for record in targets)
@@ -1139,28 +1134,24 @@ async def test_target_chunk_candidate_respects_filesystem_entry(operation, mode,
backend = _MemoryTransferBackend(records)
backend.backend_mode = mode
exists = AsyncMock(return_value=True)
- if incoming_chunk:
- with pytest.raises(InvalidArgumentError, match="chunk.*existing filesystem entry"):
- await getattr(backend, operation)(_ctx(), source, target, target_entry_exists=exists)
- assert backend.delete_calls == backend.upsert_calls == 0
- else:
- await getattr(backend, operation)(_ctx(), source, target, target_entry_exists=exists)
- assert any(record["uri"] == target for record in backend.records.values())
+ await getattr(backend, operation)(_ctx(), source, target, target_entry_exists=exists)
+ assert any(record["uri"] == target for record in backend.records.values())
assert backend.records["private"] == records[1]
- exists.assert_awaited_once_with(sibling)
+ if incoming_chunk:
+ assert backend.records["source-chunk"] == records[2]
@pytest.mark.asyncio
-async def test_target_entry_lookup_failure_precedes_vector_mutation():
+async def test_transfer_does_not_inspect_unrelated_chunk_shaped_entry():
source, target = "viking://resources/source.md", "viking://resources/target.md"
backend = _MemoryTransferBackend(
[_record("source", source), _record("old", target + "#chunk-1")]
)
- with pytest.raises(RuntimeError, match="stat failed"):
- await backend.copy_uri_mapping(
- _ctx(),
- source,
- target,
- target_entry_exists=AsyncMock(side_effect=RuntimeError("stat failed")),
- )
- assert backend.delete_calls == backend.upsert_calls == 0
+ result = await backend.copy_uri_mapping(
+ _ctx(),
+ source,
+ target,
+ target_entry_exists=AsyncMock(side_effect=RuntimeError("unrelated stat failed")),
+ )
+ assert result.written == 1
+ assert backend.records["old"]["uri"] == target + "#chunk-1"