From bb8f7cc5d6f85ea30b1e5d43cd7042b3ff345711 Mon Sep 17 00:00:00 2001 From: N7766 <181212062+N7766@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:22:32 +0800 Subject: [PATCH 1/2] fix: remove stale raw vectors when overwriting snapshots --- tests/test_snapshot_overwrite.py | 103 +++++++++++++++++++++++++++++++ vicinity/vicinity.py | 10 ++- 2 files changed, 111 insertions(+), 2 deletions(-) create mode 100644 tests/test_snapshot_overwrite.py diff --git a/tests/test_snapshot_overwrite.py b/tests/test_snapshot_overwrite.py new file mode 100644 index 0000000..512bf1d --- /dev/null +++ b/tests/test_snapshot_overwrite.py @@ -0,0 +1,103 @@ +from pathlib import Path + +import numpy as np +import pytest + +from vicinity import Metric, Vicinity + + +@pytest.mark.parametrize("metric", [Metric.COSINE, Metric.EUCLIDEAN]) +@pytest.mark.parametrize("old_store,new_store", [(False, False), (False, True), (True, False), (True, True)]) +def test_overwrite_preserves_current_vector_store( + tmp_path: Path, metric: Metric, old_store: bool, new_store: bool +) -> None: + """Overwriting a snapshot preserves only the current instance's raw vectors.""" + folder = tmp_path / "snapshot" + old = Vicinity.from_vectors_and_items( + np.array([[10.0, 0.0]]), ["old-document"], metric=metric, store_vectors=old_store + ) + vectors = np.array([[0.0, 20.0]]) + current = Vicinity.from_vectors_and_items(vectors, ["new-document"], metric=metric, store_vectors=new_store) + old.save(folder) + current.save(folder, overwrite=True) + + loaded = Vicinity.load(folder) + assert loaded.items == current.items + assert loaded.query(vectors, k=1) == current.query(vectors, k=1) + if new_store: + assert loaded.vector_store is not None + np.testing.assert_array_equal(loaded.get_vector_by_index(0), vectors) + else: + assert loaded.vector_store is None + assert not (folder / "store").exists() + with pytest.raises(ValueError, match="No vector store was provided"): + loaded.get_vector_by_index(0) + + +@pytest.mark.parametrize("metric", [Metric.COSINE, Metric.EUCLIDEAN]) +def test_overwrite_without_store_can_change_dimensions(tmp_path: Path, metric: Metric) -> None: + """Replacing a snapshot cannot attach raw vectors with the previous dimensionality.""" + folder = tmp_path / "snapshot" + old = Vicinity.from_vectors_and_items(np.array([[10.0, 0.0]]), ["old-document"], metric=metric, store_vectors=True) + vectors = np.array([[0.0, 20.0, 0.0]]) + current = Vicinity.from_vectors_and_items(vectors, ["new-document"], metric=metric) + old.save(folder) + current.save(folder, overwrite=True) + + loaded = Vicinity.load(folder) + assert loaded.dim == 3 + assert loaded.query(vectors, k=1) == current.query(vectors, k=1) + assert loaded.vector_store is None + + +@pytest.mark.parametrize("store_vectors", [False, True]) +def test_save_without_overwrite_preserves_existing_snapshot(tmp_path: Path, store_vectors: bool) -> None: + """A rejected overwrite leaves the original persisted snapshot intact.""" + folder = tmp_path / "snapshot" + vectors = np.array([[10.0, 0.0]]) + old = Vicinity.from_vectors_and_items(vectors, ["old-document"], store_vectors=store_vectors) + current = Vicinity.from_vectors_and_items(np.array([[0.0, 20.0]]), ["new-document"]) + old.save(folder) + with pytest.raises(FileExistsError): + current.save(folder) + + loaded = Vicinity.load(folder) + assert loaded.items == old.items + assert loaded.query(vectors, k=1) == old.query(vectors, k=1) + assert (loaded.vector_store is not None) == store_vectors + if store_vectors: + np.testing.assert_array_equal(loaded.get_vector_by_index(0), vectors) + + +def test_fresh_snapshot_without_raw_vectors(tmp_path: Path) -> None: + """A fresh snapshot without stored raw vectors keeps vector lookup unavailable.""" + folder = tmp_path / "snapshot" + vectors = np.array([[0.0, 20.0]]) + current = Vicinity.from_vectors_and_items(vectors, ["new-document"]) + current.save(folder) + + loaded = Vicinity.load(folder) + assert loaded.query(vectors, k=1) == current.query(vectors, k=1) + assert loaded.vector_store is None + with pytest.raises(ValueError, match="No vector store was provided"): + loaded.get_vector_by_index(0) + + +def test_overwrite_preserves_unrelated_store_files(tmp_path: Path) -> None: + """Replacing optional raw vectors leaves unrelated files in the snapshot untouched.""" + folder = tmp_path / "snapshot" + old = Vicinity.from_vectors_and_items(np.array([[10.0, 0.0]]), ["old-document"], store_vectors=True) + current = Vicinity.from_vectors_and_items(np.array([[0.0, 20.0]]), ["new-document"]) + old.save(folder) + note = folder / "store" / "notes.txt" + note.write_text("keep this note") + root_note = folder / "notes.txt" + root_note.write_text("keep root note") + current.save(folder, overwrite=True) + + loaded = Vicinity.load(folder) + assert loaded.items == current.items + assert loaded.vector_store is None + assert not (folder / "store" / "vectors.npy").exists() + assert note.read_text() == "keep this note" + assert root_note.read_text() == "keep root note" diff --git a/vicinity/vicinity.py b/vicinity/vicinity.py index 6c1fd9e..3b8bc68 100644 --- a/vicinity/vicinity.py +++ b/vicinity/vicinity.py @@ -177,6 +177,7 @@ def save( :param folder: The path to which to save the JSON file. The vectors are saved separately. The JSON contains a path to the numpy file. :param overwrite: Whether to overwrite the JSON and numpy files if they already exist. + Raw vectors from an earlier save are removed if this instance has no vector store. :raises ValueError: If the path is not a directory. :raises JSONEncodeError: If the items are not JSON-serializable. ``save()`` and ``load()`` only support item types that orjson can encode (e.g. strings, numbers, dicts). @@ -196,10 +197,15 @@ def save( raise JSONEncodeError(f"Items could not be encoded to JSON because they are not serializable: {e}") self.backend.save(path) + store_path = path / "store" if self.vector_store is not None: - store_path = path / "store" store_path.mkdir(exist_ok=overwrite) self.vector_store.save(store_path) + elif store_path.is_dir(): + # Remove only the library-owned raw vectors, preserving unrelated files. + (store_path / "vectors.npy").unlink(missing_ok=True) + if not any(store_path.iterdir()): + store_path.rmdir() @classmethod def load(cls, filename: PathLike) -> Vicinity[Any]: @@ -224,7 +230,7 @@ def load(cls, filename: PathLike) -> Vicinity[Any]: backend_cls: type[AbstractBackend] = get_backend_class(backend_type) backend = backend_cls.load(folder_path) - if Path(folder_path / "store").exists(): + if (folder_path / "store" / "vectors.npy").is_file(): vector_store = BasicVectorStore.load(folder_path / "store") else: vector_store = None From 51da04035b23e54fdf9ca75d5e4a18fa3cb4b15d Mon Sep 17 00:00:00 2001 From: N7766 <181212062+N7766@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:24:23 +0800 Subject: [PATCH 2/2] Simplify snapshot overwrite cleanup per review --- tests/test_snapshot_overwrite.py | 103 ------------------------------- tests/test_vicinity.py | 19 ++++++ vicinity/vicinity.py | 11 ++-- 3 files changed, 23 insertions(+), 110 deletions(-) delete mode 100644 tests/test_snapshot_overwrite.py diff --git a/tests/test_snapshot_overwrite.py b/tests/test_snapshot_overwrite.py deleted file mode 100644 index 512bf1d..0000000 --- a/tests/test_snapshot_overwrite.py +++ /dev/null @@ -1,103 +0,0 @@ -from pathlib import Path - -import numpy as np -import pytest - -from vicinity import Metric, Vicinity - - -@pytest.mark.parametrize("metric", [Metric.COSINE, Metric.EUCLIDEAN]) -@pytest.mark.parametrize("old_store,new_store", [(False, False), (False, True), (True, False), (True, True)]) -def test_overwrite_preserves_current_vector_store( - tmp_path: Path, metric: Metric, old_store: bool, new_store: bool -) -> None: - """Overwriting a snapshot preserves only the current instance's raw vectors.""" - folder = tmp_path / "snapshot" - old = Vicinity.from_vectors_and_items( - np.array([[10.0, 0.0]]), ["old-document"], metric=metric, store_vectors=old_store - ) - vectors = np.array([[0.0, 20.0]]) - current = Vicinity.from_vectors_and_items(vectors, ["new-document"], metric=metric, store_vectors=new_store) - old.save(folder) - current.save(folder, overwrite=True) - - loaded = Vicinity.load(folder) - assert loaded.items == current.items - assert loaded.query(vectors, k=1) == current.query(vectors, k=1) - if new_store: - assert loaded.vector_store is not None - np.testing.assert_array_equal(loaded.get_vector_by_index(0), vectors) - else: - assert loaded.vector_store is None - assert not (folder / "store").exists() - with pytest.raises(ValueError, match="No vector store was provided"): - loaded.get_vector_by_index(0) - - -@pytest.mark.parametrize("metric", [Metric.COSINE, Metric.EUCLIDEAN]) -def test_overwrite_without_store_can_change_dimensions(tmp_path: Path, metric: Metric) -> None: - """Replacing a snapshot cannot attach raw vectors with the previous dimensionality.""" - folder = tmp_path / "snapshot" - old = Vicinity.from_vectors_and_items(np.array([[10.0, 0.0]]), ["old-document"], metric=metric, store_vectors=True) - vectors = np.array([[0.0, 20.0, 0.0]]) - current = Vicinity.from_vectors_and_items(vectors, ["new-document"], metric=metric) - old.save(folder) - current.save(folder, overwrite=True) - - loaded = Vicinity.load(folder) - assert loaded.dim == 3 - assert loaded.query(vectors, k=1) == current.query(vectors, k=1) - assert loaded.vector_store is None - - -@pytest.mark.parametrize("store_vectors", [False, True]) -def test_save_without_overwrite_preserves_existing_snapshot(tmp_path: Path, store_vectors: bool) -> None: - """A rejected overwrite leaves the original persisted snapshot intact.""" - folder = tmp_path / "snapshot" - vectors = np.array([[10.0, 0.0]]) - old = Vicinity.from_vectors_and_items(vectors, ["old-document"], store_vectors=store_vectors) - current = Vicinity.from_vectors_and_items(np.array([[0.0, 20.0]]), ["new-document"]) - old.save(folder) - with pytest.raises(FileExistsError): - current.save(folder) - - loaded = Vicinity.load(folder) - assert loaded.items == old.items - assert loaded.query(vectors, k=1) == old.query(vectors, k=1) - assert (loaded.vector_store is not None) == store_vectors - if store_vectors: - np.testing.assert_array_equal(loaded.get_vector_by_index(0), vectors) - - -def test_fresh_snapshot_without_raw_vectors(tmp_path: Path) -> None: - """A fresh snapshot without stored raw vectors keeps vector lookup unavailable.""" - folder = tmp_path / "snapshot" - vectors = np.array([[0.0, 20.0]]) - current = Vicinity.from_vectors_and_items(vectors, ["new-document"]) - current.save(folder) - - loaded = Vicinity.load(folder) - assert loaded.query(vectors, k=1) == current.query(vectors, k=1) - assert loaded.vector_store is None - with pytest.raises(ValueError, match="No vector store was provided"): - loaded.get_vector_by_index(0) - - -def test_overwrite_preserves_unrelated_store_files(tmp_path: Path) -> None: - """Replacing optional raw vectors leaves unrelated files in the snapshot untouched.""" - folder = tmp_path / "snapshot" - old = Vicinity.from_vectors_and_items(np.array([[10.0, 0.0]]), ["old-document"], store_vectors=True) - current = Vicinity.from_vectors_and_items(np.array([[0.0, 20.0]]), ["new-document"]) - old.save(folder) - note = folder / "store" / "notes.txt" - note.write_text("keep this note") - root_note = folder / "notes.txt" - root_note.write_text("keep root note") - current.save(folder, overwrite=True) - - loaded = Vicinity.load(folder) - assert loaded.items == current.items - assert loaded.vector_store is None - assert not (folder / "store" / "vectors.npy").exists() - assert note.read_text() == "keep this note" - assert root_note.read_text() == "keep root note" diff --git a/tests/test_vicinity.py b/tests/test_vicinity.py index 1a24ac2..bbd8a39 100644 --- a/tests/test_vicinity.py +++ b/tests/test_vicinity.py @@ -167,6 +167,25 @@ def test_vicinity_save_and_load_vector_store(tmp_path: Path, vicinity_instance_w assert v.vector_store is not None +def test_vicinity_overwrite_without_vector_store(tmp_path: Path) -> None: + """Overwriting a stored-vector snapshot removes the previous vector store.""" + save_path = tmp_path / "vicinity_data" + original = Vicinity.from_vectors_and_items(np.array([[1.0, 0.0]]), ["old"], store_vectors=True) + original.save(save_path) + + vectors = np.array([[0.0, 1.0]]) + replacement = Vicinity.from_vectors_and_items(vectors, ["new"], store_vectors=False) + replacement.save(save_path, overwrite=True) + + loaded = Vicinity.load(save_path) + assert loaded.items == ["new"] + assert loaded.query(vectors, k=1) == replacement.query(vectors, k=1) + assert loaded.vector_store is None + assert not (save_path / "store").exists() + with pytest.raises(ValueError, match="No vector store was provided"): + loaded.get_vector_by_index(0) + + def test_vicinity_save_and_load_non_serializable_items( tmp_path: Path, non_serializable_items: list[str], vectors: np.ndarray ) -> None: diff --git a/vicinity/vicinity.py b/vicinity/vicinity.py index 3b8bc68..de16d1b 100644 --- a/vicinity/vicinity.py +++ b/vicinity/vicinity.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import shutil from collections.abc import Iterable, Sequence from pathlib import Path from time import perf_counter @@ -177,7 +178,6 @@ def save( :param folder: The path to which to save the JSON file. The vectors are saved separately. The JSON contains a path to the numpy file. :param overwrite: Whether to overwrite the JSON and numpy files if they already exist. - Raw vectors from an earlier save are removed if this instance has no vector store. :raises ValueError: If the path is not a directory. :raises JSONEncodeError: If the items are not JSON-serializable. ``save()`` and ``load()`` only support item types that orjson can encode (e.g. strings, numbers, dicts). @@ -201,11 +201,8 @@ def save( if self.vector_store is not None: store_path.mkdir(exist_ok=overwrite) self.vector_store.save(store_path) - elif store_path.is_dir(): - # Remove only the library-owned raw vectors, preserving unrelated files. - (store_path / "vectors.npy").unlink(missing_ok=True) - if not any(store_path.iterdir()): - store_path.rmdir() + elif store_path.exists(): + shutil.rmtree(store_path) @classmethod def load(cls, filename: PathLike) -> Vicinity[Any]: @@ -230,7 +227,7 @@ def load(cls, filename: PathLike) -> Vicinity[Any]: backend_cls: type[AbstractBackend] = get_backend_class(backend_type) backend = backend_cls.load(folder_path) - if (folder_path / "store" / "vectors.npy").is_file(): + if Path(folder_path / "store").exists(): vector_store = BasicVectorStore.load(folder_path / "store") else: vector_store = None