Skip to content

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

25.0 KB
Raw Blame
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
import multiprocessing
import os
import shutil
import sys
import tempfile
import time
import unittest
import weakref
from contextlib import ExitStack
from pathlib import Path
from unittest.mock import patch

from openviking.storage.vectordb import engine
from openviking.storage.vectordb.collection.local_collection import get_or_create_local_collection
from openviking.storage.vectordb.store.data import CandidateData, DeltaRecord
from openviking.storage.vectordb.store.store_manager import StoreManager

DB_PATH_CRASH = "./test_data/test_db_crash_recovery"
DB_PATH_ROBUST = "./test_data/test_db_robust_crash"
DB_PATH_TORN = "./test_data/test_db_torn_snapshot"
LARGE_TEXT = "旧数据升级后的长文本" * 4000


def worker_write_and_crash(path, start_id, count, event_ready):
    """
    Subprocess function:
    1. Opens/Creates collection
    2. Writes data
    3. Signals readiness
    4. Waits to be killed (simulating crash without close())
    """
    try:
        # Setup collection
        meta_data = {
            "CollectionName": "crash_test_col",
            "Fields": [
                {"FieldName": "id", "FieldType": "int64", "IsPrimaryKey": True},
                {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
                {"FieldName": "data", "FieldType": "string"},
            ],
        }
        # Force a fresh instance in this process
        col = get_or_create_local_collection(meta_data=meta_data, path=path)

        if not col.has_index("idx_crash"):
            col.create_index(
                "idx_crash",
                {"IndexName": "idx_crash", "VectorIndex": {"IndexType": "flat", "Distance": "l2"}},
            )

        # Write data
        data = []
        for i in range(count):
            uid = start_id + i
            data.append(
                {
                    "id": uid,
                    "vector": [0.1] * 4,  # Use constant vector for easier search verification
                    "data": f"crash_data_{uid}",
                }
            )

        # Seed real unversioned candidate and delta rows as an older writer did.
        # Keep one legacy row untouched; update the other after switching writers.
        legacy_fields = [
            ("label", "uint64"),
            ("vector", "list_float32"),
            ("sparse_raw_terms", "list_string"),
            ("sparse_values", "list_float32"),
            ("fields", "string"),
        ]
        with ExitStack() as legacy_writer:
            for record_type, definitions in (
                (CandidateData, [*legacy_fields, ("expire_ns_ts", "uint64")]),
                (DeltaRecord, [("type", "uint64"), *legacy_fields, ("old_fields", "string")]),
            ):
                legacy_schema = engine.Schema(
                    [
                        {
                            "name": name,
                            "id": index,
                            "data_type": getattr(engine.FieldType, field_type),
                        }
                        for index, (name, field_type) in enumerate(definitions)
                    ]
                )
                legacy_writer.enter_context(
                    patch.object(record_type, "bytes_row", engine.BytesRow(legacy_schema))
                )
            col.upsert_data(data[:2])

        print(f"[Subprocess] Upserting {count} mixed-format items...")
        col.upsert_data(data[2:])
        col.update_data([{"id": start_id, "data": LARGE_TEXT}])
        col.update_data([{"id": start_id, "data": LARGE_TEXT + " updated"}])
        # Replay long PUT and DEL runs, including a large deletion, without
        # changing the final count.
        transient_ids = list(range(start_id + count, start_id + 2 * count))
        col.upsert_data(
            [
                {"id": uid, "vector": [0.1] * 4, "data": LARGE_TEXT if i == 0 else "temporary"}
                for i, uid in enumerate(transient_ids)
            ]
        )
        col.delete_data(transient_ids)
        print("[Subprocess] Upsert done. Not closing.")

        # Notify main process that write is done
        event_ready.set()

        # Simulate work or wait to be killed
        # DO NOT close collection
        # We sleep long enough for parent to kill us
        time.sleep(60)
    except Exception as e:
        print(f"[Subprocess] Error: {e}")
        sys.exit(1)


def setup_robust_collection(path):
    """Helper to setup collection config for robust test"""
    meta_data = {
        "CollectionName": "robust_crash_col",
        "Fields": [
            {"FieldName": "id", "FieldType": "int64", "IsPrimaryKey": True},
            {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
            {"FieldName": "data", "FieldType": "string"},
            {"FieldName": "tag", "FieldType": "string"},
        ],
    }
    col = get_or_create_local_collection(meta_data=meta_data, path=path)
    if not col.has_index("idx_main"):
        col.create_index(
            "idx_main",
            {"IndexName": "idx_main", "VectorIndex": {"IndexType": "flat", "Distance": "l2"}},
        )
    return col


def setup_torn_snapshot_collection(path):
    """Helper to setup collection config for torn-snapshot tests"""
    meta_data = {
        "CollectionName": "torn_snapshot_col",
        "Fields": [
            {"FieldName": "id", "FieldType": "int64", "IsPrimaryKey": True},
            {"FieldName": "vector", "FieldType": "vector", "Dim": 4},
            {"FieldName": "data", "FieldType": "string"},
        ],
    }
    col = get_or_create_local_collection(meta_data=meta_data, path=path)
    if not col.has_index("idx_torn"):
        col.create_index(
            "idx_torn",
            {"IndexName": "idx_torn", "VectorIndex": {"IndexType": "flat", "Distance": "l2"}},
        )
    return col


def list_version_numbers(version_dir):
    """Return the snapshot version numbers currently on disk, sorted."""
    return sorted(
        int(name)
        for name in os.listdir(version_dir)
        if name.isdigit() and (Path(version_dir) / name).is_dir()
    )


def make_torn_version(version_dir, version):
    """Create a marker-complete but payload-less (torn) snapshot version."""
    os.makedirs(str(Path(version_dir, str(version))))
    Path(version_dir, f"{version}.write_done").touch()


def worker_cycle_1_write(path, event_ready):
    """
    Cycle 1: Write 500 items (ID 0-499).
    Crash immediately after.
    """
    try:
        col = setup_robust_collection(path)

        data = []
        for i in range(500):
            data.append({"id": i, "vector": [0.1] * 4, "data": f"cycle1_{i}", "tag": "c1"})

        print("[Cycle 1] Upserting 500 items...")
        col.upsert_data(data)
        print("[Cycle 1] Upsert done.")

        event_ready.set()
        time.sleep(60)  # Wait to be killed
    except Exception as e:
        print(f"[Cycle 1] Error: {e}")
        sys.exit(1)


def worker_cycle_2_mix(path, event_ready):
    """
    Cycle 2:
    - Recover collection (happens automatically on open)
    - Delete first 100 items (ID 0-99)
    - Write 300 new items (ID 1000-1299)
    Crash immediately after.
    """
    try:
        col = setup_robust_collection(path)

        # Verify Cycle 1 data exists before modification
        res = col.fetch_data([0, 499])
        if len(res.items) != 2:
            print("[Cycle 2] Critical: Cycle 1 data missing on startup!")
            sys.exit(1)

        # Delete 0-99
        print("[Cycle 2] Deleting 100 items (0-99)...")
        col.delete_data(list(range(100)))

        # Upsert 1000-1299
        print("[Cycle 2] Upserting 300 items (1000-1299)...")
        data = []
        for i in range(300):
            uid = 1000 + i
            data.append({"id": uid, "vector": [0.2] * 4, "data": f"cycle2_{uid}", "tag": "c2"})
        col.upsert_data(data)
        print("[Cycle 2] Operations done.")

        event_ready.set()
        time.sleep(60)  # Wait to be killed
    except Exception as e:
        print(f"[Cycle 2] Error: {e}")
        sys.exit(1)


class TestCrashRecovery(unittest.TestCase):
    def setUp(self):
        if os.path.exists(DB_PATH_CRASH):
            shutil.rmtree(DB_PATH_CRASH)
        if os.path.exists(DB_PATH_ROBUST):
            shutil.rmtree(DB_PATH_ROBUST)

    def tearDown(self):
        self.doCleanups()
        if os.path.exists(DB_PATH_CRASH):
            shutil.rmtree(DB_PATH_CRASH)
        if os.path.exists(DB_PATH_ROBUST):
            shutil.rmtree(DB_PATH_ROBUST)

    def test_simple_crash_recovery(self):
        """
        Test that data and indexes are recovered correctly after a process crash
        (where close() was not called).
        """
        print("\n=== Test Simple Crash Recovery ===")

        # Use 'spawn' to ensure clean process state (especially important for RocksDB/LevelDB locks)
        ctx = multiprocessing.get_context("spawn")
        event = ctx.Event()

        data_count = 2050
        p = ctx.Process(target=worker_write_and_crash, args=(DB_PATH_CRASH, 0, data_count, event))
        p.start()

        # Wait for write to complete in subprocess
        print("[Main] Waiting for subprocess to write data...")
        is_set = event.wait(timeout=30)
        self.assertTrue(is_set, "Subprocess timed out writing data")

        # Give it a tiny moment to ensure the OS flush might happen (though we want to test robustness)
        # But immediate kill is what we want to test.
        # However, Python's LevelDB binding might be sync or async. Usually writes go to OS cache.
        time.sleep(0.5)

        # KILL the process immediately to simulate crash (no cleanup, no flush)
        print("[Main] Terminating subprocess (Simulating Crash)...")
        p.terminate()
        p.join()
        print(f"[Main] Subprocess terminated with exit code: {p.exitcode}")

        # Recover
        print("[Main] Recovering collection in main process...")
        # Re-opening the collection should trigger recovery logic (PersistentIndex should rebuild/catchup from Store)
        live_deltas: weakref.WeakValueDictionary[int, DeltaRecord] = weakref.WeakValueDictionary()
        peak_live_deltas = 0
        read_deltas = StoreManager.get_delta_data_after_ts

        def tracked_deltas(manager, version):
            nonlocal peak_live_deltas
            for number, record in enumerate(read_deltas(manager, version)):
                live_deltas[number] = record
                peak_live_deltas = max(peak_live_deltas, len(live_deltas))
                yield record

        with patch.object(StoreManager, "get_delta_data_after_ts", tracked_deltas):
            col = get_or_create_local_collection(path=DB_PATH_CRASH)
        self.addCleanup(col.close)
        self.assertGreater(peak_live_deltas, 0, "Recovery must exercise the persisted delta log")
        self.assertLessEqual(
            peak_live_deltas, 1025, "Recovery must release replayed deltas during long PUT/DEL runs"
        )

        # 1. Verify Data Persistence (Store)
        print(f"[Main] Verifying data fetch (All {data_count} items)...")
        # Check all IDs
        all_ids = list(range(data_count))
        res = col.fetch_data(all_ids)

        print(f"[Main] Fetch retrieved {len(res.items)} items. Missing: {len(res.ids_not_exist)}")

        self.assertEqual(
            len(res.items), data_count, f"Should find all {data_count} items in KV Store"
        )
        payloads = {item.id: item.fields["data"] for item in res.items}
        self.assertEqual(payloads[0], LARGE_TEXT + " updated")
        self.assertEqual(payloads[1], "crash_data_1")
        self.assertEqual(col.fetch_data([data_count]).ids_not_exist, [data_count])

        print("[Main] Data fetch verified.")

        # 2. Verify Index Recovery
        # Since we killed the process, the Index (which might be in memory or partially written)
        # needs to be reconstructed from the KV Store delta during initialization.
        print("[Main] Verifying vector search (Index Recovery)...")

        # Searching for vector [0.1, 0.1, 0.1, 0.1] should return our data
        search_res = col.search_by_vector("idx_crash", dense_vector=[0.1] * 4, limit=data_count)

        found_ids = [item.id for item in search_res.data]
        print(f"[Main] Search returned {len(found_ids)} items.")

        # We expect all items to be found if index recovery works
        self.assertEqual(
            len(found_ids), data_count, "Index should contain all items after recovery"
        )
        self.assertEqual(set(found_ids), set(all_ids))

        print("[Main] Simple recovery test passed.")

    def run_process_and_crash(self, target_func):
        ctx = multiprocessing.get_context("spawn")
        event = ctx.Event()
        p = ctx.Process(target=target_func, args=(DB_PATH_ROBUST, event))
        p.start()

        # Wait for work done
        is_set = event.wait(timeout=30)
        self.assertTrue(is_set, "Subprocess timed out")

        # Give a split second for OS buffers (simulate sudden power loss/crash)
        time.sleep(0.5)

        print(f"[Main] Crashing process {p.pid}...")
        p.terminate()
        p.join()
        print(f"[Main] Process {p.pid} crashed.")

    def test_multi_cycle_crash(self):
        print("\n=== Test Robust Multi-Cycle Crash Recovery ===")

        # --- Cycle 1: Write & Crash ---
        print("\n--- Starting Cycle 1 ---")
        self.run_process_and_crash(worker_cycle_1_write)

        # Verify Cycle 1 Recovery
        print("[Main] Verifying Cycle 1 recovery...")
        col = setup_robust_collection(DB_PATH_ROBUST)

        # Check counts
        res_search = col.search_by_vector("idx_main", [0.1] * 4, limit=1000)
        self.assertEqual(len(res_search.data), 500, "Should have 500 items after Cycle 1")
        col.close()

        # --- Cycle 2: Mix Ops & Crash ---
        print("\n--- Starting Cycle 2 ---")
        self.run_process_and_crash(worker_cycle_2_mix)

        # Verify Cycle 2 Recovery
        print("[Main] Verifying Cycle 2 recovery...")
        col = setup_robust_collection(DB_PATH_ROBUST)

        # 1. Verify Deletions (0-99 should be gone)
        print("[Main] Verifying deletions (0-99)...")
        res_deleted = col.fetch_data(list(range(10)))
        self.assertEqual(len(res_deleted.items), 0, "IDs 0-9 should be deleted")

        # Search check for deleted items
        # IDs 0-99 had vector [0.1]*4.
        # IDs 100-499 still have [0.1]*4.
        # So searching [0.1]*4 should return 400 items that match perfectly (score ~0)
        # But vector search returns all items up to limit.
        res_search_old = col.search_by_vector("idx_main", [0.1] * 4, limit=1000)

        # Verify total count is 700 (400 old + 300 new)
        self.assertEqual(len(res_search_old.data), 700, "Total index items should be 700")

        # Verify IDs 0-99 are GONE
        found_ids = {item.id for item in res_search_old.data}
        for i in range(100):
            self.assertNotIn(i, found_ids, f"ID {i} should have been deleted")

        # Verify IDs 100-499 EXIST
        for i in range(100, 500):
            self.assertIn(i, found_ids, f"ID {i} should exist")

        # 2. Verify New Inserts (1000-1299 should exist)
        print("[Main] Verifying new inserts (1000-1299)...")
        res_new = col.fetch_data([1000, 1299])
        self.assertEqual(len(res_new.items), 2, "New items 1000 and 1299 should exist")

        # Search check for new items ([0.2]*4)
        # Should also return all 700 items, but sorted differently
        res_search_new = col.search_by_vector("idx_main", [0.2] * 4, limit=1000)
        self.assertEqual(len(res_search_new.data), 700, "Should return all 700 items")

        # Verify IDs 1000-1299 EXIST in the result
        found_ids_new = {item.id for item in res_search_new.data}
        for i in range(1000, 1300):
            self.assertIn(i, found_ids_new, f"ID {i} should exist")

        print("[Main] Total items verified via index: 700")

        col.close()
        print("\n[Main] Robust recovery test passed.")


class TestTornSnapshotSelection(unittest.TestCase):
    """A snapshot marked .write_done but missing its payload must never be selected.

    A crash between the native dump and the payload blocks reaching disk can
    leave behind a version directory that carries a .write_done marker but no
    loadable payload. Selecting it as the newest version makes the next open
    hard-fail on the native loader before any recovery path runs, even though
    the previous complete snapshot is still on disk and loadable.
    """

    def setUp(self):
        if os.path.exists(DB_PATH_TORN):
            shutil.rmtree(DB_PATH_TORN)

    def tearDown(self):
        if os.path.exists(DB_PATH_TORN):
            shutil.rmtree(DB_PATH_TORN)

    def test_torn_newest_snapshot_is_skipped_on_reopen(self):
        print("\n=== Test Torn Newest Snapshot Is Skipped On Reopen ===")

        col = setup_torn_snapshot_collection(DB_PATH_TORN)
        data = [{"id": i, "vector": [0.1] * 4, "data": f"torn_{i}"} for i in range(10)]
        col.upsert_data(data)
        version_dir = col.get_index("idx_torn").version_dir
        col.close()

        # After close() only the newest complete version remains on disk.
        valid_versions = list_version_numbers(version_dir)
        self.assertEqual(len(valid_versions), 1)
        valid_version = valid_versions[0]
        self.assertTrue(Path(version_dir, str(valid_version), "manager_meta.json").is_file())

        # Crash artifact: a newer, marker-complete but payload-less version.
        torn_version = valid_version + 1
        make_torn_version(version_dir, torn_version)

        # Reopening must succeed and fall back to the previous complete
        # snapshot instead of hard-failing on the empty newest one.
        reopened = setup_torn_snapshot_collection(DB_PATH_TORN)
        reopened_index = reopened.get_index("idx_torn")
        self.assertEqual(int(reopened_index.now_version), valid_version)
        self.assertEqual(int(reopened_index.get_newest_version()), valid_version)

        res = reopened.fetch_data(list(range(10)))
        self.assertEqual(len(res.items), 10)
        self.assertEqual(
            {item.id for item in res.items}, set(range(10)), "All ids should be recovered"
        )
        search_res = reopened.search_by_vector("idx_torn", dense_vector=[0.1] * 4, limit=10)
        self.assertEqual({item.id for item in search_res.data}, set(range(10)))

        reopened.close()
        print("[Main] Torn snapshot skipped, previous complete snapshot reloaded.")

    def test_get_newest_version_ignores_missing_or_empty_meta(self):
        print("\n=== Test get_newest_version Ignores Torn Snapshots ===")

        col = setup_torn_snapshot_collection(DB_PATH_TORN)
        try:
            col.upsert_data([{"id": 1, "vector": [0.1] * 4, "data": "torn_1"}])
            index = col.get_index("idx_torn")
            version_dir = index.version_dir
            index.persist()
            valid_version = index.get_newest_version()
            self.assertGreater(valid_version, 0)

            # Torn variants: marker present, payload missing or 0 bytes.
            make_torn_version(version_dir, valid_version + 1)
            empty_meta_version = valid_version + 2
            os.makedirs(str(Path(version_dir, str(empty_meta_version))))
            Path(version_dir, str(empty_meta_version), "manager_meta.json").touch()
            Path(version_dir, f"{empty_meta_version}.write_done").touch()

            self.assertEqual(index.get_newest_version(), valid_version)
        finally:
            col.close()
        print("[Main] get_newest_version rejected torn snapshots.")


def worker_failed_snapshot(path, scalar, connection):
    import resource
    import signal

    exit_code = 0
    try:
        dim = 4 if scalar else 128
        meta = {
            "CollectionName": "failed_snapshot",
            "Fields": [
                {"FieldName": "id", "FieldType": "int64", "IsPrimaryKey": True},
                {"FieldName": "vector", "FieldType": "vector", "Dim": dim},
                {"FieldName": "text", "FieldType": "string"},
            ],
        }
        col = get_or_create_local_collection(
            meta_data=meta,
            path=path,
            config={"ttl_cleanup_seconds": 0, "index_maintenance_seconds": 3600},
        )
        rows = [
            {"id": i, "vector": [0.25] * dim, "text": f"record-{i}" + "x" * 512}
            for i in range(1, 3002)
        ]
        col.upsert_data(rows[:1])
        col.create_index(
            "idx",
            {
                "IndexName": "idx",
                "VectorIndex": {"IndexType": "flat", "Distance": "l2"},
                "ScalarIndex": ["text"] if scalar else [],
            },
        )
        index = col.get_index("idx")
        version_before = index.get_newest_version()
        markers_before = sorted(Path(index.version_dir).glob("*.write_done"))
        col.upsert_data(rows[1:])
        local = col._Collection__collection
        delta_before = len(list(local.store_mgr.get_delta_data_after_ts(0)))
        real_dump = index.engine_proxy.dump
        failed_file_size = None

        def limited_dump(directory):
            nonlocal failed_file_size
            payload = "scalar_index/scalar_index.data" if scalar else "vector_index/index_flat.data"
            failed_file = Path(directory) / payload
            old_limit = resource.getrlimit(resource.RLIMIT_FSIZE)
            old_handler = signal.signal(signal.SIGXFSZ, signal.SIG_IGN)
            try:
                resource.setrlimit(resource.RLIMIT_FSIZE, (131072, old_limit[1]))
                return real_dump(directory)
            finally:
                resource.setrlimit(resource.RLIMIT_FSIZE, old_limit)
                signal.signal(signal.SIGXFSZ, old_handler)
                failed_file_size = failed_file.stat().st_size

        with patch.object(index.engine_proxy, "dump", side_effect=limited_dump):
            flushed = local.flush_all_indexes()
        connection.send(
            {
                "flushed": flushed,
                "delta_before": delta_before,
                "delta_after": len(list(local.store_mgr.get_delta_data_after_ts(0))),
                "version_before": version_before,
                "version_after": index.get_newest_version(),
                "markers_unchanged": markers_before
                == sorted(Path(index.version_dir).glob("*.write_done")),
                "failed_file_size": failed_file_size,
            }
        )
    except Exception as exc:
        connection.send({"error": repr(exc)})
        exit_code = 1
    finally:
        connection.close()
        # A normal close would retry persistence and overwrite the failure evidence.
        os._exit(exit_code)


@unittest.skipUnless(sys.platform in {"darwin", "linux"}, "Requires RLIMIT_FSIZE and SIGXFSZ")
class TestFailedSnapshotWrite(unittest.TestCase):
    def check_failed_snapshot(self, scalar):
        with tempfile.TemporaryDirectory() as path:
            ctx = multiprocessing.get_context("spawn")
            receiver, sender = ctx.Pipe(duplex=False)
            worker = ctx.Process(target=worker_failed_snapshot, args=(path, scalar, sender))
            worker.start()
            sender.close()
            try:
                self.assertTrue(receiver.poll(60), "Snapshot writer timed out")
                report = receiver.recv()
                worker.join(10)
                self.assertEqual(worker.exitcode, 0, report)
            finally:
                receiver.close()
                if worker.is_alive():
                    worker.terminate()
                worker.join()
            self.assertEqual(report["failed_file_size"], 131072, "Real write failure must occur")
            self.assertEqual(report["delta_before"], 3000)
            self.assertEqual(report["flushed"], 0, "Failed snapshot must not count as saved")
            self.assertEqual(report["version_after"], report["version_before"])
            self.assertTrue(report["markers_unchanged"])
            self.assertEqual(report["delta_after"], 3000, "Recovery deltas must survive")
            col = get_or_create_local_collection(path=path)
            try:
                self.assertEqual(col.fetch_data(list(range(1, 3002))).ids_not_exist, [])
                result = col.search_by_vector(
                    "idx", dense_vector=[0.25] * (4 if scalar else 128), limit=3101
                )
                self.assertEqual({item.id for item in result.data}, set(range(1, 3002)))
                if scalar:
                    filtered = col.search_by_vector(
                        "idx",
                        dense_vector=[0.25] * 4,
                        limit=10,
                        filters={
                            "op": "must",
                            "field": "text",
                            "conds": ["record-3001" + "x" * 512],
                        },
                    )
                    self.assertEqual([item.id for item in filtered.data], [3001])
            finally:
                col.close()

    def test_failed_vector_write_preserves_recovery(self):
        self.check_failed_snapshot(scalar=False)

    def test_failed_scalar_write_preserves_recovery(self):
        self.check_failed_snapshot(scalar=True)


if __name__ == "__main__":
    unittest.main()