Skip to content

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

fix(storage): lazily replay delta table during cold-start recovery (#5064) (#5225)

FranYestef6010a5a1e55
diff --git a/openviking/storage/vectordb/collection/local_collection.py b/openviking/storage/vectordb/collection/local_collection.py
index 06555b939..5f5cceb92 100644
--- a/openviking/storage/vectordb/collection/local_collection.py
+++ b/openviking/storage/vectordb/collection/local_collection.py
@@ -1349,17 +1349,18 @@ class PersistCollection(LocalCollection):
newest_version = index.get_newest_version()
if not self.store_mgr:
raise RuntimeError("Store manager is not initialized")
- delta_list = self.store_mgr.get_delta_data_after_ts(newest_version)
+ delta_records = self.store_mgr.get_delta_data_after_ts(newest_version)
logger.info(
- "Index '%s': replaying %d delta records to recover from last persistent snapshot",
+ "Index '%s': replaying delta records lazily to recover from last persistent snapshot",
index_name,
- len(delta_list),
)
upsert_list: List[DeltaRecord] = []
delete_list: List[DeltaRecord] = []
_processed = 0
+ _seen = 0
_last_log = 0.0
- for data in delta_list:
+ for data in delta_records:
+ _seen += 1
if data.type == OpType.PUT.value:
if delete_list:
_processed += self._replay_recovery_records(
@@ -1381,11 +1382,11 @@ class PersistCollection(LocalCollection):
upsert_list = []
delete_list.append(data)
now = time.time()
- if now - _last_log >= 5.0 and _processed > 0:
+ if now - _last_log >= 5.0 and _seen > 0:
logger.info(
"Delta replay progress: %d/%d records for index '%s'",
_processed,
- len(delta_list),
+ _seen,
index_name,
)
_last_log = now
diff --git a/openviking/storage/vectordb/store/local_store.py b/openviking/storage/vectordb/store/local_store.py
index 7c6b16183..c8213ebb8 100644
--- a/openviking/storage/vectordb/store/local_store.py
+++ b/openviking/storage/vectordb/store/local_store.py
@@ -201,6 +201,64 @@ class StoreEngineProxy(IMutiTableStore):
if data[0].startswith(table_name)
]
+ def iter_seek_to_end(
+ self,
+ start_key: str,
+ table_name: str,
+ page_size: int = STORE_SCAN_PAGE_SIZE,
+ page_bytes: int = STORE_SCAN_PAGE_BYTES,
+ ) -> Iterator[Tuple[str, bytes]]:
+ """Lazily scan a table from ``start_key`` to the end in bounded native pages.
+
+ Mirrors ``iter_all`` but starts the range at ``start_key`` instead of the
+ table head, so a large delta table can be replayed on memory-constrained
+ hosts without materializing the whole (key, value) list at once. Pages are
+ capped by row count and ``max(byte budget, one encoded row)`` so an
+ oversized row cannot cause a false end-of-scan. Each native page is
+ internally consistent, but separate page calls do not share a snapshot;
+ collection recovery invokes this while the store is quiescent.
+ """
+ if page_size <= 0:
+ raise ValueError("Store scan page size must be positive")
+ if page_bytes <= 0:
+ raise ValueError("Store scan page byte budget must be positive")
+
+ seek_page = getattr(self.storage_engine, "seek_range_page", None)
+ if not callable(seek_page):
+ raise RuntimeError(
+ "The native VectorDB engine does not support bounded store scans; "
+ "rebuild or reinstall the matching OpenViking engine package"
+ )
+
+ end_key = table_name + MAX_UNICODE_CHAR
+ cursor = table_name + start_key
+ start_exclusive = False
+ try:
+ page = seek_page(cursor, end_key, page_size, page_bytes, start_exclusive)
+ except NotImplementedError as exc:
+ raise RuntimeError(
+ "The native VectorDB engine does not support bounded store scans; "
+ "rebuild or reinstall the matching OpenViking engine package"
+ ) from exc
+
+ while page:
+ next_cursor = page[-1][0]
+ if next_cursor < cursor or (start_exclusive and next_cursor <= cursor):
+ raise RuntimeError(
+ "Native bounded store scan did not advance its continuation cursor"
+ )
+ for full_key, value in page:
+ if full_key.startswith(table_name):
+ yield full_key[len(table_name) :], value
+ # Drop the page before the next native call so two encoded-vector
+ # pages are not live at the same time during recovery.
+ page = None
+ full_key = None
+ value = None
+ cursor = next_cursor
+ start_exclusive = True
+ page = seek_page(cursor, end_key, page_size, page_bytes, start_exclusive)
+
def exec_sequence(self, op: List[Op], table_name: str):
"""Execute a sequence of operations on a specific table.
diff --git a/openviking/storage/vectordb/store/store.py b/openviking/storage/vectordb/store/store.py
index 54580b124..69b74bf61 100644
--- a/openviking/storage/vectordb/store/store.py
+++ b/openviking/storage/vectordb/store/store.py
@@ -198,6 +198,19 @@ class IMutiTableStore(ABC):
"""
yield from self.read_all(table_name)
+ def iter_seek_to_end(
+ self, start_key: str, table_name: str
+ ) -> Iterator[Tuple[str, bytes]]:
+ """Lazily iterate a table from ``start_key`` to the end, with a
+ materializing compatibility fallback.
+
+ Store implementations with a cursor or paged range API should override
+ this method. Keeping the default in terms of ``seek_to_end`` preserves
+ existing third-party and test-store behavior while still exposing the
+ materialization-free contract to callers.
+ """
+ yield from self.seek_to_end(start_key, table_name)
+
@abstractmethod
def seek_to_end(self, key: str, table_name: str) -> List[Tuple[str, bytes]]:
"""Retrieve all entries from a starting key to the end of the table.
diff --git a/openviking/storage/vectordb/store/store_manager.py b/openviking/storage/vectordb/store/store_manager.py
index b27dafac9..da4a9b1bc 100644
--- a/openviking/storage/vectordb/store/store_manager.py
+++ b/openviking/storage/vectordb/store/store_manager.py
@@ -249,21 +249,13 @@ class StoreManager:
"""Clear all data from the store."""
self.storage.clear()
- def get_delta_data_after_ts(self, ns_ts: int) -> List[DeltaRecord]:
- """Get delta records created after a specific timestamp.
-
- Args:
- ns_ts (int): Timestamp in nanoseconds.
-
- Returns:
- List[DeltaRecord]: List of delta records.
- """
- delta_kv_list = self.storage.seek_to_end(
- str(ns_ts),
- StoreManager.DeltaTable,
- )
- delta_list = [DeltaRecord.from_bytes(data=data[1]) for data in delta_kv_list]
- return delta_list
+ def get_delta_data_after_ts(self, ns_ts: int) -> Iterator[DeltaRecord]:
+ """Lazily deserialize delta records so a large delta table can be replayed on
+ memory-constrained hosts without materializing the whole list."""
+ for _, bytes_data in self.storage.iter_seek_to_end(
+ str(ns_ts), StoreManager.DeltaTable
+ ):
+ yield DeltaRecord.from_bytes(data=bytes_data)
def delete_delta_data_before_ts(self, ns_ts: int) -> List[DeltaRecord]:
"""Delete delta records created before a specific timestamp.