diff --git a/pyproject.toml b/pyproject.toml index baa423ba..c33af5ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -62,7 +62,7 @@ Changelog = "https://github.com/nustackdev/virtuals/releases" virtuals-binary-codec = { path = "lib/binary-codec", editable = true } [project.optional-dependencies] -rocksdb = ["rdbpython>=0.2.7"] +rocksdb = ["rdbpython>=0.3.0,<0.4"] lmdb = ["lmdb"] redis = [ "redis>=5.0", diff --git a/src/virtuals/_backends/storages/rocksdb/__init__.py b/src/virtuals/_backends/storages/rocksdb/__init__.py index bd4ee42f..d5e17560 100644 --- a/src/virtuals/_backends/storages/rocksdb/__init__.py +++ b/src/virtuals/_backends/storages/rocksdb/__init__.py @@ -1,16 +1,24 @@ -"""RocksDB storage adapter for nu.""" +"""RocksDB storage adapter for nu. + +``RocksDBStorage`` is the serial variant (one writer at a time per storage, +snapshot reads); ``RocksDBSerialStorage`` names it explicitly. +""" from .scan import RocksDBScan from .snapshot import RocksDBSnapshot -from .storage import RocksDBStorage +from .storage import RocksDBStorage, RocksDBWriteSlot from .transaction import RocksDBTransaction from .write_batch import RocksDBWriteBatch +RocksDBSerialStorage = RocksDBStorage + __all__ = [ "RocksDBScan", + "RocksDBSerialStorage", "RocksDBSnapshot", "RocksDBStorage", "RocksDBTransaction", "RocksDBWriteBatch", + "RocksDBWriteSlot", ] diff --git a/src/virtuals/_backends/storages/rocksdb/context.py b/src/virtuals/_backends/storages/rocksdb/context.py index cab3652a..8d309975 100644 --- a/src/virtuals/_backends/storages/rocksdb/context.py +++ b/src/virtuals/_backends/storages/rocksdb/context.py @@ -4,9 +4,12 @@ from typing import TYPE_CHECKING +import rdbpy + from virtuals.tkv.storage import ( ScanProtocol, StorageClosedError, + StorageError, StorageLockTimeoutError, StorageOperationError, StorageScanOptions, @@ -28,23 +31,40 @@ "ContextBase", "ReadOperationsMixin", "WriteOperationsMixin", + "classify_rdbpy", + "is_missing_file_error", ] -def _classify_rdbpy(key: Key, action: str, e: Exception) -> StorageOperationError: - """Map an rdbpy exception to the right storage exception. +# Conflicts rocksdb reports on a write or a commit: the key moved after the +# transaction's snapshot (Busy, Deadlock is a Busy), the memtable history +# was too short to validate (TryAgain), or the transaction expired. +_CONFLICT = (rdbpy.Busy, rdbpy.TryAgain, rdbpy.Expired) +# A lock wait exceeded its timeout, or the lock table is full. +_LOCK_TIMEOUT = (rdbpy.TimedOut, rdbpy.LockLimit) + +# rocksdb::Status::SubCode::kPathNotFound: an IO error on a file that is gone. +_SUBCODE_PATH_NOT_FOUND = 9 + + +def classify_rdbpy(e: BaseException, message: str) -> StorageError: + """Map an rdbpy exception onto the storage exception hierarchy. - rdbpy surfaces RocksDB statuses as plain `Exception` with a bytes - message; we sniff for the canonical status strings and map to - typed errors so policy spans (e.g. RetryOnConflict) can target them. + Mapping is by exception class (rdbpy types every rocksdb status), so + the retryable classes ``RetryOnConflict`` targets are exact: + Busy / Deadlock / TryAgain / Expired become + ``StorageTransactionConflictError``, TimedOut / LockLimit become + ``StorageLockTimeoutError``. rdbpy raises ``RuntimeError`` for a handle + whose parent ended (transaction committed, storage closed), which is + ``StorageClosedError`` here. Everything else is an operation error. """ - msg = str(e) - lower = msg.lower() - if "timeout waiting to lock" in lower or "lock timeout" in lower: - return StorageLockTimeoutError(f"Failed to {action} key {key}: {e}") - if "busy" in lower or "conflict" in lower or "deadlock" in lower: - return StorageTransactionConflictError(f"Failed to {action} key {key}: {e}") - return StorageOperationError(f"Failed to {action} key {key}: {e}") + if isinstance(e, _CONFLICT): + return StorageTransactionConflictError(f"{message}: {e}") + if isinstance(e, _LOCK_TIMEOUT): + return StorageLockTimeoutError(f"{message}: {e}") + if isinstance(e, RuntimeError): + return StorageClosedError(f"{message}: {e}") + return StorageOperationError(f"{message}: {e}") # Bounded retries for a read-only secondary whose manifest version still @@ -53,39 +73,38 @@ def _classify_rdbpy(key: Key, action: str, e: Exception) -> StorageOperationErro _SECONDARY_STALE_RETRIES = 6 -def _is_missing_file_error(e: Exception) -> bool: +def is_missing_file_error(e: BaseException) -> bool: """True if a read failed because it touched a now-deleted SST file. This is the signature of a read-only secondary pinned to a manifest version older than the primary's current one: the primary compacted and deleted the file, but the secondary's view still references it. A - catch-up to the current manifest drops the reference. + catch-up to the current manifest drops the reference. rocksdb reports + it as an IO error with the path-not-found subcode. """ - return "no such file or directory" in str(e).lower() + return isinstance(e, rdbpy.RocksIOError) and e.subcode == _SUBCODE_PATH_NOT_FOUND class ContextBase: - """Base class for RocksDB transaction/snapshot contexts. + """Base class for RocksDB transaction, snapshot and batch contexts. - Provides common functionality for state management, validation, and - resource cleanup. All contexts wrap a RocksDB transaction handle. + Tracks open/closed state and, for write contexts, the storage's writer + slot, which is given back when the context closes. Subclasses own + their rdbpy handles and drop them in ``_drop_handles``. """ - __slots__ = ("_closed", "_rdbpy_txn", "_storage") + __slots__ = ("_closed", "_holds_write_slot", "_storage") - def __init__( - self, - storage: RocksDBStorage, - rdbpy_txn: Any, # noqa: ANN401 - ) -> None: - """Initialize context with storage reference and RocksDB transaction. + def __init__(self, storage: RocksDBStorage, *, holds_write_slot: bool = False) -> None: + """Initialize context. Args: storage: Parent storage instance - rdbpy_txn: RocksDB transaction handle + holds_write_slot: True if this context holds the storage's + in-process writer slot and must release it on close. """ self._storage = storage - self._rdbpy_txn: Any | None = rdbpy_txn + self._holds_write_slot = holds_write_slot self._closed = False @property @@ -97,25 +116,25 @@ def storage(self) -> RocksDBStorage: """ return self._storage - def _require_active(self) -> object: - """Validate context is active and return transaction handle. - - Returns: - Active RocksDB transaction handle + def _require_active(self) -> None: + """Validate context is active. Raises: - StorageClosedError: If context is closed or invalid + StorageClosedError: If context is closed """ if self._closed: raise StorageClosedError("Context is closed") - if self._rdbpy_txn is None: - raise StorageClosedError("Context handle is invalid") - return self._rdbpy_txn + + def _drop_handles(self) -> None: + """Forget the rdbpy handles. Overridden by subclasses.""" def _mark_closed(self) -> None: - """Mark context as closed and clear handle.""" + """Mark context as closed, drop its handles, and give back the writer slot.""" self._closed = True - self._rdbpy_txn = None + self._drop_handles() + if self._holds_write_slot: + self._holds_write_slot = False + self._storage._release_write_slot() @property def is_closed(self) -> bool: @@ -140,7 +159,10 @@ class ReadOperationsMixin: """Mixin providing read operations for RocksDB contexts. Implements point access (get, exists), batch access (multiget), - and range access (scan) operations. + and range access (scan) operations over two hooks the context + provides: ``_get_raw(encoded_key)`` and ``_iterator(keys_only, reverse)``. + Both read at the context's snapshot: a transaction's own snapshot + merged with its pending writes, or a Snapshot's DB snapshot. """ __slots__ = () @@ -148,27 +170,32 @@ class ReadOperationsMixin: # Type hints for mixed-in attributes _storage: RocksDBStorage _require_active: Any # Method from ContextBase + _get_raw: Callable[[bytes], bytes | None] + _iterator: Callable[..., Any] - def _read_with_catchup(self, key: Key, action: str, op: Callable[[], object]) -> object: - """Run a read `op`, surviving a stale-manifest secondary. + def _read_raw(self, key: Key, action: str, encoded_key: bytes) -> bytes | None: + """Point read at the context's snapshot, surviving a stale-manifest secondary. - On a read-only secondary, `op` can fail because the secondary's + On a read-only secondary, the read can fail because the secondary's manifest version references an SST the primary already compacted away. That is recoverable: force a catch-up to the current manifest - and retry. Any other failure -- and any failure at all on a primary - -- is classified and raised immediately, exactly as before. + and retry. Any other failure, and any failure at all on a primary, + is classified and raised immediately. """ + try: + return self._get_raw(encoded_key) + except Exception as e: + last = e storage = self._storage - last: Exception | None = None for _ in range(_SECONDARY_STALE_RETRIES): + if not (storage._is_secondary and is_missing_file_error(last)): + break + storage.force_catch_up_with_primary() try: - return op() + return self._get_raw(encoded_key) except Exception as e: - if not (storage._is_secondary and _is_missing_file_error(e)): - raise _classify_rdbpy(key, action, e) from e last = e - storage.force_catch_up_with_primary() - raise _classify_rdbpy(key, action, last) from last # type: ignore[arg-type] + raise classify_rdbpy(last, f"Failed to {action} key {key}") from last def get(self, key: Key) -> Value | Empty: """Get value by key. @@ -184,24 +211,19 @@ def get(self, key: Key) -> Value | Empty: StorageOperationError: If operation fails StorageClosedError: If context is closed """ - txn = self._require_active() + self._require_active() codec = self._storage.codec - # Encode key for RocksDB try: encoded_key = codec.encode_key(key) except Exception as e: raise StorageOperationError(f"Failed to encode key {key}: {e}") from e - # Retrieve from RocksDB. `_read_with_catchup` absorbs a stale-manifest - # secondary (an SST the primary compacted away) by catching up + retrying. - encoded_value = self._read_with_catchup(key, "get", lambda: txn.get(encoded_key)) + encoded_value = self._read_raw(key, "get", encoded_key) - # Handle not found - return EMPTY instead of raising if encoded_value is None: return EMPTY - # Decode value try: return codec.decode_value(encoded_value) except Exception as e: @@ -220,7 +242,7 @@ def exists(self, key: Key) -> bool: StorageOperationError: If check fails StorageClosedError: If context is closed """ - txn = self._require_active() + self._require_active() codec = self._storage.codec try: @@ -228,7 +250,7 @@ def exists(self, key: Key) -> bool: except Exception as e: raise StorageOperationError(f"Failed to encode key {key}: {e}") from e - return self._read_with_catchup(key, "check", lambda: txn.get(encoded_key) is not None) + return self._read_raw(key, "check", encoded_key) is not None def multiget(self, keys: list[Key]) -> dict[Key, Value]: """Get multiple keys. @@ -267,16 +289,15 @@ def scan(self, options: StorageScanOptions) -> ScanProtocol: """ from .scan import RocksDBScan - # Validate context is active before creating scan self._require_active() return RocksDBScan(self, options) # type: ignore[arg-type] class WriteOperationsMixin: - """Mixin providing write operations for RocksDB contexts. + """Mixin providing write operations for RocksDB transactions. - Implements point writes (put, delete). + Implements point writes (put, delete) on the rdbpy transaction. Tracks modified keys for notification on commit. """ @@ -285,6 +306,7 @@ class WriteOperationsMixin: # Type hints for mixed-in attributes _storage: RocksDBStorage _require_active: Any # Method from ContextBase + _rdbpy_txn: Any _modified_keys: set[Key] # Initialized in __init__ def put(self, key: Key, value: Value) -> None: @@ -296,31 +318,31 @@ def put(self, key: Key, value: Value) -> None: Raises: StorageOperationError: If write fails + StorageTransactionConflictError: If the key moved after the + transaction's snapshot (another writer bypassed the slot) StorageClosedError: If context is closed """ - txn = self._require_active() + self._require_active() codec = self._storage.codec - # Encode key and value try: encoded_key = codec.encode_key(key) encoded_value = codec.encode_value(value) except Exception as e: raise StorageOperationError(f"Failed to encode key/value for {key}: {e}") from e - # Write to RocksDB try: - txn.put(encoded_key, encoded_value) + self._rdbpy_txn.put(encoded_key, encoded_value) except Exception as e: - raise _classify_rdbpy(key, "put", e) from e + raise classify_rdbpy(e, f"Failed to put key {key}") from e - # Track modification for notifications self._modified_keys.add(key) def delete(self, key: Key) -> None: """Delete key (idempotent). - Silent if key doesn't exist (never raises for missing keys). + Silent if key doesn't exist (never raises for missing keys), and + notifies only when something was there to delete. Args: key: Key to delete @@ -329,7 +351,7 @@ def delete(self, key: Key) -> None: StorageOperationError: If deletion fails StorageClosedError: If context is closed """ - txn = self._require_active() + self._require_active() codec = self._storage.codec try: @@ -337,18 +359,11 @@ def delete(self, key: Key) -> None: except Exception as e: raise StorageOperationError(f"Failed to encode key {key}: {e}") from e - # Check if key exists try: - exists = txn.get(encoded_key) is not None - - if not exists: - # Key doesn't exist, silently do nothing + if self._rdbpy_txn.get(encoded_key) is None: return - - # Delete the key - txn.delete_single(encoded_key) + self._rdbpy_txn.delete(encoded_key) except Exception as e: - raise _classify_rdbpy(key, "delete", e) from e + raise classify_rdbpy(e, f"Failed to delete key {key}") from e - # Track modification for notifications self._modified_keys.add(key) diff --git a/src/virtuals/_backends/storages/rocksdb/scan.py b/src/virtuals/_backends/storages/rocksdb/scan.py index 172f469e..d21d58e5 100644 --- a/src/virtuals/_backends/storages/rocksdb/scan.py +++ b/src/virtuals/_backends/storages/rocksdb/scan.py @@ -12,13 +12,19 @@ StorageScanOptions, ) -from .context import _is_missing_file_error +from .context import classify_rdbpy, is_missing_file_error # Bounded restarts when a secondary scan touches an SST the primary # compacted away. Mirrors the point-read retry budget in `context.py`. _SCAN_STALE_RETRIES = 6 +# Rows fetched per native call. The first batch is small so a scan that +# stops early (limit, break filter) reads little past its end; later +# batches grow so a long scan pays one native call per hundreds of rows. +_BATCH_FIRST = 8 +_BATCH_MAX = 1024 + if TYPE_CHECKING: from collections.abc import Generator @@ -41,15 +47,17 @@ class _IteratorType(Enum): class RocksDBScan(ScanProtocol): - """Optimized scan iterator implementation conforming to ScanProtocol. + """Scan iterator implementation conforming to ScanProtocol. - Provides Pythonic iteration interface over a range of keys. + Provides Pythonic iteration interface over a range of keys, read at the + context's snapshot (a transaction's own, merged with its pending + writes, or a Snapshot's). Key optimizations: - 1. Uses iterkeys() when only keys needed (no value I/O from disk), in - both directions - 2. Uses iteritems() when values needed - 3. Seeks straight to the start bound (seek / seek_for_prev) + 1. Key-only cursors when only keys are needed (no value I/O from disk), + in both directions + 2. Seeks straight to the start bound (seek / seek_for_prev) + 3. Rows come in native batches, so Python pays per batch, not per row 4. Uses filter/break_filter for flexible key filtering """ @@ -98,7 +106,10 @@ def _iterate_impl(self, iterator_type: _IteratorType) -> Generator[object, None, yield item return except Exception as e: - if not (storage._is_secondary and _is_missing_file_error(e)): + cause = e.__cause__ + if not ( + storage._is_secondary and cause is not None and is_missing_file_error(cause) + ): raise attempt += 1 if attempt > _SCAN_STALE_RETRIES: @@ -121,7 +132,8 @@ def _scan_once(self, iterator_type: _IteratorType) -> Generator[object, None, No Yields: Keys, values, or (key, value) tuples based on iterator_type """ - txn = self._context._require_active() + context = self._context + context._require_active() codec = self._storage.codec options = self._options @@ -140,70 +152,73 @@ def _scan_once(self, iterator_type: _IteratorType) -> Generator[object, None, No raise StorageOperationError(f"Failed to encode start key: {e}") from e try: - iterator = txn.iteritems() if need_values else txn.iterkeys() - except RuntimeError as e: - raise StorageClosedError(f"Scan context is closed: {e}") from e + iterator = context._iterator(keys_only=not need_values, reverse=options.reverse) # type: ignore[attr-defined] except Exception as e: - raise StorageOperationError(f"Failed to create iterator: {e}") from e + raise classify_rdbpy(e, "Failed to create iterator") from e - self._seek(iterator, options.reverse, start_key_encoded) + try: + self._seek(iterator, options.reverse, start_key_encoded) + + count = 0 + max_depth = options.max_depth + first_batch = _BATCH_FIRST + if options.limit is not None: + first_batch = max(1, min(first_batch, options.limit)) + batch_size = first_batch + while True: + rows = self._next_batch(iterator, batch_size) + if not rows: + return + batch_size = min(batch_size * 4, _BATCH_MAX) + for row in rows: + # Rows already fetched outlive the context (and on a + # secondary the shared DB handle outlives the snapshot), + # so check the context before every row, not the cursor. + if context.is_closed: + raise StorageClosedError("Scan used after its context ended") + if need_values: + encoded_key, encoded_value = row + else: + encoded_key, encoded_value = row, None + + try: + key = codec.decode_key(encoded_key) + except Exception as e: + raise StorageOperationError(f"Failed to decode key: {e}") from e + + if options.break_filter is not None and not options.break_filter.matches(key): + return + + if max_depth is not None and len(key) > max_depth: + # Below the walked depth: one seek over the whole subtree, + # dropping the rest of this batch. + self._seek(iterator, options.reverse, options.skip_bound(codec, key)) + batch_size = first_batch + break + + if options.filter is not None and not options.filter.matches(key): + continue - count = 0 - max_depth = options.max_depth - context = self._context + if options.limit is not None and count >= options.limit: + return - while True: - # A secondary's snapshot wraps the shared DB handle, so closing the - # snapshot does not invalidate the iterator; check the context. - if context.is_closed: - raise StorageClosedError("Scan used after its context ended") - entry = self._read(iterator) - if entry is None: - break - if need_values: - encoded_key, encoded_value = entry - else: - encoded_key, encoded_value = entry, None + value = None + if need_values and encoded_value is not None: + try: + value = codec.decode_value(encoded_value) + except Exception as e: + raise StorageOperationError(f"Failed to decode value: {e}") from e - try: - key = codec.decode_key(encoded_key) - except Exception as e: - raise StorageOperationError(f"Failed to decode key: {e}") from e - - if options.break_filter is not None and not options.break_filter.matches(key): - break - - if max_depth is not None and len(key) > max_depth: - # Below the walked depth: one seek over the whole subtree. - self._seek(iterator, options.reverse, options.skip_bound(codec, key)) - continue - - if options.filter is not None and not options.filter.matches(key): - if not self._advance(iterator, options.reverse): - break - continue - - if options.limit is not None and count >= options.limit: - break - - value = None - if need_values and encoded_value is not None: - try: - value = codec.decode_value(encoded_value) - except Exception as e: - raise StorageOperationError(f"Failed to decode value: {e}") from e - - if iterator_type == _IteratorType.KEYS: - yield key - elif iterator_type == _IteratorType.VALUES: - yield value - else: - yield (key, value) - - count += 1 + if iterator_type == _IteratorType.KEYS: + yield key + elif iterator_type == _IteratorType.VALUES: + yield value + else: + yield (key, value) - if not self._advance(iterator, options.reverse): - break + count += 1 + finally: + iterator.close() @staticmethod def _seek(iterator: Any, reverse: bool, start_key_encoded: bytes | None) -> None: # noqa: ANN401 @@ -211,7 +226,7 @@ def _seek(iterator: Any, reverse: bool, start_key_encoded: bytes | None) -> None Forward lands on the first key >= start, reverse on the last key <= start (`seek_for_prev`). An empty range leaves the iterator - invalid, which `_read` reports as exhausted. + invalid, which the first batch reports as exhausted. """ try: if reverse: @@ -223,41 +238,19 @@ def _seek(iterator: Any, reverse: bool, start_key_encoded: bytes | None) -> None iterator.seek(start_key_encoded) else: iterator.seek_to_first() - except RuntimeError as e: - raise StorageClosedError(f"Scan used after its context ended: {e}") from e - except Exception as e: - raise StorageOperationError(f"Failed during scan: {e}") from e - - @staticmethod - def _read(iterator: Any) -> Any: # noqa: ANN401 - """Current entry (key, or (key, value)), or None when exhausted.""" - try: - return iterator.get() - except ValueError: - return None - except RuntimeError as e: - raise StorageClosedError(f"Scan used after its context ended: {e}") from e except Exception as e: - raise StorageOperationError(f"Failed during scan: {e}") from e + raise classify_rdbpy(e, "Failed during scan") from e @staticmethod - def _advance(iterator: Any, reverse: bool) -> bool: # noqa: ANN401 - """Step forward or backward. Returns False on exhaustion.""" + def _next_batch(iterator: Any, n: int) -> list: # noqa: ANN401 + """Up to ``n`` rows from the cursor in its direction; empty when exhausted.""" try: - if reverse: - iterator.skip_back() - else: - iterator.skip() - except ValueError: - return False - except RuntimeError as e: - raise StorageClosedError(f"Scan used after its context ended: {e}") from e + return iterator.next_batch(n) except Exception as e: - raise StorageOperationError(f"Failed during scan: {e}") from e - return True + raise classify_rdbpy(e, "Failed during scan") from e def keys(self) -> Generator[Key, None, None]: - """Iterate over keys only - uses iterkeys() for minimal I/O. + """Iterate over keys only - a key-only cursor for minimal I/O. Yields: Keys in scan range @@ -270,7 +263,7 @@ def keys(self) -> Generator[Key, None, None]: ) def values(self) -> Generator[Value, None, None]: - """Iterate over values only - must use iteritems(). + """Iterate over values only. Yields: Values in scan range @@ -283,7 +276,7 @@ def values(self) -> Generator[Value, None, None]: ) def items(self) -> Generator[tuple[Key, Value], None, None]: - """Iterate over (key, value) tuples - uses iteritems(). + """Iterate over (key, value) tuples. Yields: Tuples of (key, value) for each item in scan range diff --git a/src/virtuals/_backends/storages/rocksdb/snapshot.py b/src/virtuals/_backends/storages/rocksdb/snapshot.py index fe2488dd..c13c0d97 100644 --- a/src/virtuals/_backends/storages/rocksdb/snapshot.py +++ b/src/virtuals/_backends/storages/rocksdb/snapshot.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from virtuals.tkv.storage import ( StorageError, @@ -21,30 +21,53 @@ class RocksDBSnapshot(ContextBase, ReadOperationsMixin): - """Read-only snapshot implementation. + """Read-only snapshot: a rocksdb DB snapshot taken when it begins. - Provides consistent read-only view of the database at a point in time. - Composed from base context and read operations. + Every get and scan reads at that snapshot, so the view is repeatable + and never shows half of a commit. It takes no lock and never waits on + a writer. + + On a read-only secondary rocksdb does not support snapshots: reads + there see the secondary's state as of its last catch-up with the + primary, which the storage runs when the snapshot begins (throttled by + ``secondary_refresh_interval``). """ - __slots__ = () + __slots__ = ("_db", "_snapshot") - def __init__(self, storage: RocksDBStorage, rdbpy_txn: object) -> None: + def __init__(self, storage: RocksDBStorage, db: Any, snapshot: Any) -> None: # noqa: ANN401 """Initialize snapshot. Args: storage: Parent storage instance - rdbpy_txn: RocksDB transaction handle with snapshot + db: rdbpy DB handle to read through + snapshot: rdbpy Snapshot pinning the view, or None on a secondary """ - super().__init__(storage, rdbpy_txn) + super().__init__(storage) + self._db: Any | None = db + self._snapshot: Any | None = snapshot @property def writable(self) -> bool: """Always False for snapshots.""" return False + def _drop_handles(self) -> None: + self._db = None + self._snapshot = None + + def _get_raw(self, encoded_key: bytes) -> bytes | None: + """Read at the pinned snapshot.""" + return self._db.get(encoded_key, snapshot=self._snapshot) # type: ignore[union-attr] + + def _iterator(self, *, keys_only: bool, reverse: bool) -> Any: # noqa: ANN401 + """Cursor at the pinned snapshot.""" + return self._db.iterator( # type: ignore[union-attr] + snapshot=self._snapshot, keys_only=keys_only, reverse=reverse + ) + def close(self) -> None: - """Close snapshot and release resources. + """Close snapshot and release the rocksdb snapshot. Raises: StorageError: If close fails @@ -52,24 +75,15 @@ def close(self) -> None: if self._closed: return - if self._storage._is_secondary: - # Secondary snapshots wrap the shared DB handle; no rollback needed. - self._mark_closed() - self._storage._remove_snapshot(self) - return - - if self._rdbpy_txn is not None: - try: - # Rollback to release the snapshot - self._rdbpy_txn.rollback() - except Exception as e: - raise StorageError(f"Failed to close snapshot: {e}") from e - finally: - self._mark_closed() - self._storage._remove_snapshot(self) - else: + snapshot = self._snapshot + try: + if snapshot is not None: + snapshot.release() + except Exception as e: + raise StorageError(f"Failed to close snapshot: {e}") from e + finally: self._mark_closed() - self._storage._remove_snapshot(self) + self._storage._untrack_snapshot(self) def __enter__(self) -> RocksDBSnapshot: """Enter context manager.""" diff --git a/src/virtuals/_backends/storages/rocksdb/storage.py b/src/virtuals/_backends/storages/rocksdb/storage.py index dae995a8..14eb5d67 100644 --- a/src/virtuals/_backends/storages/rocksdb/storage.py +++ b/src/virtuals/_backends/storages/rocksdb/storage.py @@ -1,26 +1,30 @@ """RocksDB storage backend implementation. -Provides persistent key-value storage with transactions, snapshots, -and optional change notifications via a publisher. +Provides persistent key-value storage with serializable transactions, +point-in-time snapshots, and optional change notifications via a publisher. """ from __future__ import annotations +import os import threading import time from contextlib import contextmanager from logging import getLogger from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal, overload +from typing import TYPE_CHECKING, Any, ClassVar, Literal, overload from virtuals.tkv.storage import ( SnapshotProtocol, StorageClosedError, StorageError, + StorageTransactionError, TransactionProtocol, WriteBatchProtocol, ) +from .._write_slot import WriterLock, WriteSlot +from .context import classify_rdbpy from .snapshot import RocksDBSnapshot from .transaction import RocksDBTransaction from .write_batch import RocksDBWriteBatch @@ -43,22 +47,77 @@ ) from e -__all__ = ["RocksDBStorage"] +__all__ = ["RocksDBStorage", "RocksDBWriteSlot"] logger = getLogger(__name__) +DEFAULT_BUSY_TIMEOUT = 60.0 # seconds + +# Native handles a forked child inherited and was asked to close. Freeing +# them there would run rocksdb teardown (a memtable flush, waits on +# background jobs, lock manager mutexes) against threads and locks that only +# exist in the parent: it can hang or write into the parent's directory. The +# child keeps them referenced instead, until it exits. +_INHERITED_HANDLES: list[Any] = [] + +RocksDBWriteSlot = WriteSlot +"""Returned by ``RocksDBStorage.areserve_write_slot``; see ``WriteSlot``.""" + +# Keys of the ``txn_db_options`` dict, as rdbpy.TransactionDB spells them, +# plus the names rdbpy 0.2 used (values in milliseconds either way). +_TXN_DB_OPTION_ALIASES = { + "transaction_lock_timeout": "lock_timeout_ms", + "default_lock_timeout": "default_lock_timeout_ms", +} +# Keys of the ``txn_options`` dict, as rdbpy ``TransactionDB.begin`` spells +# them, plus the rdbpy 0.2 names. +_TXN_OPTION_ALIASES = { + "lock_timeout": "lock_timeout_ms", + "expiration": "expiration_ms", +} + + class RocksDBStorage: """RocksDB storage implementation conforming to StorageProtocol. - Provides persistent key-value storage with transactions, snapshots, - and optional change notifications via a publisher. + The serial variant: one writer at a time per storage, real snapshots + for every read. + + Transactions: a write transaction holds the storage's in-process writer + slot from begin until commit or abort. With one writer at a time and + every read inside the transaction at its own begin snapshot (merged + with its pending writes), committed transactions are serializable, + scans included: no lost update, write skew or phantom is possible. + Underneath, a pessimistic rocksdb transaction with snapshot validation + turns any writer that bypassed the slot into a retryable conflict. + + Snapshots: a rocksdb DB snapshot, taken when the Snapshot begins, pins + every get and scan in it. They never wait on a writer. + + Coroutines: the slot belongs to a thread and, on an event loop, to the + task that took it. Coroutines sharing one loop wait for it with + ``areserve_write_slot``, which polls without blocking the loop, and + hand it to ``begin_transaction(write_slot=...)``. A second writer from + the task or thread that already holds the slot raises + ``StorageNestedTransactionError``; a sync begin while another task on + the same loop holds it raises ``StorageLockTimeoutError`` at once. A + sync writer on another thread blocks for up to ``busy_timeout``. + Write batches take the slot for the duration of ``write``. + + Process model: single-process. RocksDB locks its directory, so one + process opens a storage read-write; others open it as a read-only + secondary (``read_only=True, secondary_path=...``) or go through the + owning process. A storage handle must not be used in a forked child. A transaction, snapshot or scan belongs to one thread: do not share it between threads, and close the storage only once every thread is done. """ + process_model: ClassVar[Literal["single", "multi"]] = "single" + """Contract section 4: one process opens the storage read-write.""" + def __init__( self, path: Path | str, @@ -75,6 +134,7 @@ def __init__( create_if_missing: bool = True, sync_writes: bool = False, disable_wal: bool = False, + busy_timeout: float = DEFAULT_BUSY_TIMEOUT, ) -> None: """Initialize RocksDB storage. @@ -91,12 +151,21 @@ def __init__( older than this. Set to 0 to catch up on every snapshot, or None to never catch up (callers drive freshness manually). wal_path: Optional separate WAL directory - options: RocksDB options dict - txn_db_options: TransactionDB options dict - txn_options: Transaction options dict + options: ``rdbpy.Options`` kwargs. ``block_cache_mb`` (an int) + and ``block_table`` (a dict of block table kwargs) are also + accepted and folded in. + txn_db_options: ``rdbpy.TransactionDB`` kwargs: ``lock_timeout_ms``, + ``default_lock_timeout_ms``, ``max_num_locks``, ``num_stripes``, + ``max_num_deadlocks``. Row locks only matter for a writer that + bypassed the writer slot. + txn_options: ``rdbpy.TransactionDB.begin`` kwargs: ``lock_timeout_ms``, + ``deadlock_detect``, ``deadlock_detect_depth``, ``expiration_ms``. + Transactions always begin with a snapshot. create_if_missing: Create database if it doesn't exist - sync_writes: Sync writes to disk + sync_writes: fsync every commit and batch write disable_wal: Disable write-ahead log + busy_timeout: Seconds a sync writer waits for the writer slot + before ``StorageLockTimeoutError``. """ # Core dependencies self._codec = codec @@ -128,14 +197,18 @@ def __init__( self._create_if_missing = create_if_missing self._sync_writes = sync_writes self._disable_wal = disable_wal + self._busy_timeout = busy_timeout + self._begin_kwargs = self._build_begin_kwargs() # State self._db: rdbpy.TransactionDB | rdbpy.DB | None = None - self._db_lock = threading.RLock() + self._state_lock = threading.Lock() + self._writer = WriterLock("RocksDB") self._active_transactions: set[RocksDBTransaction] = set() self._active_write_batches: set[RocksDBWriteBatch] = set() self._active_snapshots: set[RocksDBSnapshot] = set() self._opened = False + self._pid = os.getpid() @property def read_only(self) -> bool: @@ -147,6 +220,11 @@ def codec(self) -> CodecProtocol[bytes, bytes]: """Get codec for key/value encoding.""" return self._codec + @property + def path(self) -> Path: + """The database directory.""" + return self._path + # ========================================================================= # Lifecycle # ========================================================================= @@ -154,13 +232,6 @@ def codec(self) -> CodecProtocol[bytes, bytes]: def _build_options(self) -> rdbpy.Options: """Build RocksDB options from configuration. - Recognized non-rocksdb keys in options dict: - block_table: dict of kwargs for rdbpy.BlockBasedTableFactory - (e.g. cache_index_and_filter_blocks, pin_l0_filter_and_index_blocks_in_cache, - partition_filters, format_version, ...) - block_cache_mb: int — convenience, builds a shared LRU and passes it as - block_cache into BlockBasedTableFactory - Returns: Configured Options object @@ -172,26 +243,32 @@ def _build_options(self) -> rdbpy.Options: options_dict["create_if_missing"] = self._create_if_missing block_table_kwargs = options_dict.pop("block_table", None) + if block_table_kwargs: + options_dict.update(block_table_kwargs) block_cache_mb = options_dict.pop("block_cache_mb", None) + if block_cache_mb is not None and "block_cache_size" not in options_dict: + options_dict["block_cache_size"] = int(block_cache_mb) * 1024 * 1024 + + if self._wal_path is not None: + options_dict["wal_dir"] = str(self._wal_path) try: - options = rdbpy.Options(**options_dict) + return rdbpy.Options(**options_dict) except Exception as e: raise StorageError(f"Invalid RocksDB options: {e}") from e - if block_table_kwargs is not None or block_cache_mb is not None: - tf_kwargs = dict(block_table_kwargs or {}) - if block_cache_mb is not None and "block_cache" not in tf_kwargs: - tf_kwargs["block_cache"] = rdbpy.PyLRUCache(int(block_cache_mb) * 1024 * 1024) - try: - options.table_factory = rdbpy.BlockBasedTableFactory(**tf_kwargs) - except Exception as e: - raise StorageError(f"Invalid block-table options: {e}") from e - - if self._wal_path is not None: - options.wal_dir = str(self._wal_path) + def _build_txn_db_kwargs(self) -> dict[str, Any]: + """Translate ``txn_db_options`` into ``rdbpy.TransactionDB`` kwargs.""" + return {_TXN_DB_OPTION_ALIASES.get(k, k): v for k, v in self._txn_db_options_dict.items()} - return options + def _build_begin_kwargs(self) -> dict[str, Any]: + """Translate ``txn_options`` into ``TransactionDB.begin`` kwargs.""" + kwargs = {_TXN_OPTION_ALIASES.get(k, k): v for k, v in self._txn_options_dict.items()} + kwargs.pop("set_snapshot", None) # always on + kwargs["set_snapshot"] = True + kwargs["sync"] = self._sync_writes + kwargs["disable_wal"] = self._disable_wal + return kwargs def _open_transaction_db(self, options: rdbpy.Options) -> None: """Open database as TransactionDB for read-write access. @@ -202,22 +279,27 @@ def _open_transaction_db(self, options: rdbpy.Options) -> None: Raises: StorageError: If database cannot be opened """ - txn_db_options = None - if self._txn_db_options_dict: - try: - txn_db_options = rdbpy.TransactionDBOptions(**self._txn_db_options_dict) - except Exception as e: - raise StorageError(f"Invalid TransactionDB options: {e}") from e - try: - self._db = rdbpy.TransactionDB( - str(self._path), - options, - txn_db_opts=txn_db_options, - ) + self._db = rdbpy.TransactionDB(str(self._path), options, **self._build_txn_db_kwargs()) + except TypeError as e: + raise StorageError(f"Invalid TransactionDB options: {e}") from e except Exception as e: raise StorageError(f"Failed to open RocksDB TransactionDB: {e}") from e + def _open_read_only_db(self, options: rdbpy.Options) -> None: + """Open an existing database read-only (no secondary instance). + + Args: + options: RocksDB options + + Raises: + StorageError: If database cannot be opened + """ + try: + self._db = rdbpy.DB(str(self._path), options, read_only=True) + except Exception as e: + raise StorageError(f"Failed to open RocksDB read-only: {e}") from e + def _open_secondary_db(self, options: rdbpy.Options) -> None: """Open database as secondary for parallel reads. @@ -255,72 +337,104 @@ def open(self) -> None: if self._opened: return - with self._db_lock: - # Create directories - try: - self._path.mkdir(parents=True, exist_ok=True) - if self._wal_path is not None: - self._wal_path.mkdir(parents=True, exist_ok=True) - except Exception as e: - raise StorageError(f"Failed to create database directories: {e}") from e + # Create directories + try: + self._path.mkdir(parents=True, exist_ok=True) + if self._wal_path is not None: + self._wal_path.mkdir(parents=True, exist_ok=True) + except Exception as e: + raise StorageError(f"Failed to create database directories: {e}") from e - options = self._build_options() + options = self._build_options() - # Open in appropriate mode - if self._is_secondary: - self._open_secondary_db(options) - else: - self._open_transaction_db(options) + # Open in appropriate mode + if self._is_secondary: + self._open_secondary_db(options) + elif self._read_only: + self._open_read_only_db(options) + else: + self._open_transaction_db(options) + with self._state_lock: + self._pid = os.getpid() self._opened = True def close(self) -> None: """Close database and release all resources. + Closes the database first: rdbpy refuses while another thread is + inside a call on it or on one of its transactions, snapshots or + iterators, and then nothing is touched and the storage stays open. + Once the database is closed (rdbpy rolls back its transactions and + releases its snapshots), open transactions, snapshots and batches + are marked ended and the writer slot is given back. + Raises: - StorageError: If close fails + StorageError: If close fails, e.g. a call is still in flight on + another thread """ if not self._opened: return + if self._pid != os.getpid(): + self._forget_inherited() + return + + db = self._db + if db is not None: + try: + db.close() + except Exception as e: + raise StorageError(f"Failed to close database: {e}") from e - with self._db_lock: - # Abort all active transactions - for transaction in list(self._active_transactions): - try: - transaction.abort() - except Exception as e: - logger.error(f"Transaction abort failed during close: {e}") - - # Close all active snapshots - for snapshot in list(self._active_snapshots): - try: - snapshot.close() - except Exception as e: - logger.error(f"Snapshot close failed during close: {e}") - - # Abort all active write batches - for write_batch in list(self._active_write_batches): - try: - write_batch.abort() - except Exception as e: - logger.error(f"Write batch abort failed during close: {e}") - - # Clear tracking sets + with self._state_lock: + transactions = list(self._active_transactions) + snapshots = list(self._active_snapshots) + write_batches = list(self._active_write_batches) self._active_transactions.clear() self._active_write_batches.clear() self._active_snapshots.clear() + self._db = None + self._opened = False + + # Native state is gone; these only mark the contexts ended and give + # back the writer slot. A waiter woken by that sees a closed storage. + for transaction in transactions: + try: + transaction.abort() + except Exception as e: + logger.error(f"Transaction abort failed during close: {e}") - # Close database. Any rdbpy iterator still referenced (e.g. by a - # suspended scan generator) is invalidated by rdbpy, not freed. - if self._db is not None: - try: - self._db.close() - except Exception as e: - raise StorageError(f"Failed to close database: {e}") from e - finally: - self._db = None + for snapshot in snapshots: + try: + snapshot.close() + except Exception as e: + logger.error(f"Snapshot close failed during close: {e}") + for write_batch in write_batches: + try: + write_batch.abort() + except Exception as e: + logger.error(f"Write batch abort failed during close: {e}") + + def _forget_inherited(self) -> None: + """Close in a forked child: forget the parent's handles, free nothing native.""" + with self._state_lock: + contexts = [ + *self._active_transactions, + *self._active_snapshots, + *self._active_write_batches, + ] + self._active_transactions.clear() + self._active_write_batches.clear() + self._active_snapshots.clear() + _INHERITED_HANDLES.append((self._db, contexts)) + self._db = None self._opened = False + self._writer.reset() + for context in contexts: + # Ended without touching its rdbpy handle, which stays referenced. + context._holds_write_slot = False + context._closed = True def __enter__(self) -> RocksDBStorage: """Enter context manager - open storage.""" @@ -380,7 +494,7 @@ def begin( return self.begin_transaction() def begin_snapshot(self) -> RocksDBSnapshot: - """Begin read-only snapshot. + """Begin read-only snapshot, pinned at this moment. Returns: New snapshot instance @@ -390,168 +504,177 @@ def begin_snapshot(self) -> RocksDBSnapshot: StorageClosedError: If storage is not open """ self._require_open() + db = self._db if self._is_secondary: - return self._begin_snapshot_on_secdb() + self._catch_up_if_due() + rdbpy_snapshot = None # rocksdb: snapshots not supported in secondary mode else: - return self._begin_snapshot_on_txdb() - - def _begin_snapshot_on_secdb(self) -> RocksDBSnapshot: - """Begin read-only snapshot on a secondary db instance. - - Returns: - New snapshot instance - - Raises: - StorageError: If snapshot creation fails - """ - self._require_open() - - if not self._is_secondary: - raise StorageError("Invalid snapshot creation") - - with self._db_lock: - interval = self._secondary_refresh_interval - if interval is not None: - now = time.monotonic() - if now - self._last_catchup_monotonic >= interval: - try: - self._db.try_catch_up_with_primary() - except Exception as e: - raise StorageError(f"Failed to catch up with primary: {e}") from e - self._last_catchup_monotonic = now - try: - snapshot = RocksDBSnapshot(self, self._db) + rdbpy_snapshot = db.snapshot() except Exception as e: - raise StorageError(f"Failed to begin snapshot: {e}") from e + raise classify_rdbpy(e, "Failed to begin snapshot") from e + + snapshot = RocksDBSnapshot(self, db, rdbpy_snapshot) + with self._state_lock: self._active_snapshots.add(snapshot) - return snapshot + return snapshot + + def _catch_up_if_due(self) -> None: + """Throttled catch-up of a secondary with the primary, before a snapshot.""" + interval = self._secondary_refresh_interval + if interval is None: + return + now = time.monotonic() + if now - self._last_catchup_monotonic < interval: + return + try: + self._db.try_catch_up_with_primary() + except Exception as e: + raise StorageError(f"Failed to catch up with primary: {e}") from e + self._last_catchup_monotonic = now def force_catch_up_with_primary(self) -> None: """Catch up to the primary's current manifest immediately. - Unlike the throttled catch-up in `_begin_snapshot_on_secdb`, this - bypasses `secondary_refresh_interval`. It exists to recover from a - read that hit an SST file the primary compacted away: the secondary - is pinned to an old manifest version that still references the - deleted file, and catching up to the current manifest drops that - reference. No-op on a primary (non-secondary) storage. + Unlike the throttled catch-up in `begin_snapshot`, this bypasses + `secondary_refresh_interval`. It exists to recover from a read that + hit an SST file the primary compacted away: the secondary is pinned + to an old manifest version that still references the deleted file, + and catching up to the current manifest drops that reference. No-op + on a primary (non-secondary) storage. """ if not self._is_secondary: return - with self._db_lock: - try: - self._db.try_catch_up_with_primary() - except Exception as e: - raise StorageError(f"Failed to catch up with primary: {e}") from e - self._last_catchup_monotonic = time.monotonic() + self._require_open() + try: + self._db.try_catch_up_with_primary() + except Exception as e: + raise StorageError(f"Failed to catch up with primary: {e}") from e + self._last_catchup_monotonic = time.monotonic() - def _begin_snapshot_on_txdb(self) -> RocksDBSnapshot: - """Begin read-only snapshot on TransactionDB instance. + def begin_transaction(self, *, write_slot: WriteSlot | None = None) -> RocksDBTransaction: + """Begin read-write transaction, taking the writer slot now. + + Args: + write_slot: A slot from ``areserve_write_slot``. The transaction + takes it over instead of acquiring the slot itself, then + releases it on commit or abort. None acquires as usual. Returns: - New snapshot instance + New transaction instance Raises: - StorageError: If snapshot creation fails + StorageNestedTransactionError: If this task or thread already + holds the writer slot + StorageLockTimeoutError: If the slot is not free within + ``busy_timeout``, or is held by another task on this loop + StorageError: If transaction creation fails + StorageClosedError: If storage is not open """ + if self._read_only: + raise StorageError("Cannot start transaction in read only mode.") self._require_open() - if self._is_secondary: - raise StorageError("Invalid snapshot creation") - - with self._db_lock: - # Create transaction options with snapshot - txn_options_dict = dict(self._txn_options_dict) - txn_options_dict["set_snapshot"] = True + give_back_slot = self._writer.take(self, write_slot, self._busy_timeout) + try: + db = self._db + if db is None: + raise StorageClosedError("Storage is not open") + rdbpy_txn = db.begin(**self._begin_kwargs) + except StorageClosedError: + give_back_slot() + raise + except TypeError as e: + give_back_slot() + raise StorageError(f"Invalid transaction options: {e}") from e + except Exception as e: + give_back_slot() + raise StorageError(f"Failed to begin transaction: {e}") from e - try: - txn_options = rdbpy.TransactionOptions(**txn_options_dict) - except Exception as e: - raise StorageError(f"Invalid snapshot options: {e}") from e + transaction = RocksDBTransaction(self, rdbpy_txn) + with self._state_lock: + self._active_transactions.add(transaction) + return transaction - # Begin transaction with snapshot - try: - rdbpy_txn = self._db.begin_transaction(txn_options) - rdbpy_txn.set_snapshot() - except Exception as e: - raise StorageError(f"Failed to begin snapshot: {e}") from e + async def areserve_write_slot(self) -> WriteSlot: + """Wait for the writer slot without blocking the event loop. - snapshot = RocksDBSnapshot(self, rdbpy_txn) - self._active_snapshots.add(snapshot) - return snapshot - - def begin_transaction(self) -> RocksDBTransaction: - """Begin read-write transaction. + Polls the slot with a short, growing sleep between tries, so other + coroutines on the loop keep running, including the one that holds + it. Waits behind other threads too. Returns: - New transaction instance + The held slot, for ``begin_transaction(write_slot=...)``. Call + its ``release`` if no transaction takes it. Raises: - StorageError: If transaction creation fails - StorageClosedError: If storage is not open + StorageNestedTransactionError: If this task already holds the + slot. + StorageLockTimeoutError: If it is not free within + ``busy_timeout``. """ if self._read_only: - raise StorageError("Cannot start transaction in read only mode.") - + raise StorageError("Cannot reserve the write slot in read only mode.") self._require_open() - - with self._db_lock: - # Create transaction options - txn_options = None - if self._txn_options_dict: - try: - txn_options = rdbpy.TransactionOptions(**self._txn_options_dict) - except Exception as e: - raise StorageError(f"Invalid transaction options: {e}") from e - - # Write options (e.g. disable WAL for bulk writes) - write_options = None - if self._disable_wal: - write_options = {"disable_wal": True} - - # Begin transaction - try: - if txn_options is not None: - rdbpy_txn = self._db.begin_transaction(txn_options, write_options=write_options) - else: - rdbpy_txn = self._db.begin_transaction(write_options=write_options) - except Exception as e: - raise StorageError(f"Failed to begin transaction: {e}") from e - - transaction = RocksDBTransaction(self, rdbpy_txn) - self._active_transactions.add(transaction) - return transaction + lock = await self._writer.areserve(self._busy_timeout) + return RocksDBWriteSlot(self, lock) def begin_write_batch(self) -> RocksDBWriteBatch: - """Begin write-only batch. + """Begin write-only batch. Takes the writer slot only in ``write``. Returns: New write batch instance Raises: - StorageOperationError: If batch creation fails + StorageError: If batch creation fails in read only mode StorageClosedError: If storage is closed """ if self._read_only: raise StorageError("Cannot start write batch in read only mode.") - self._require_open() - with self._db_lock: - rdbpy_batch = rdbpy.WriteBatch() - write_batch = RocksDBWriteBatch(self, rdbpy_batch) + write_batch = RocksDBWriteBatch(self, rdbpy.WriteBatch()) + with self._state_lock: self._active_write_batches.add(write_batch) - return write_batch + return write_batch + + def _write_batch(self, batch: Any) -> None: # noqa: ANN401 + """Apply an rdbpy write batch atomically, under the writer slot. + + Raises: + StorageNestedTransactionError: If this task or thread holds a + write transaction on the storage + StorageLockTimeoutError: If the slot is not free in time, or + rocksdb timed out on a row lock + StorageTransactionConflictError: If rocksdb refused the write + StorageTransactionError: If the write fails otherwise + """ + give_back_slot = self._writer.take(self, None, self._busy_timeout) + try: + self._require_open() + self._db.write(batch, sync=self._sync_writes, disable_wal=self._disable_wal) + except StorageError: + raise + except Exception as e: + mapped = classify_rdbpy(e, "Failed to write batch") + if isinstance(mapped, (StorageTransactionError, StorageClosedError)): + raise mapped from e # retryable (conflict, lock timeout) or closed + raise StorageTransactionError(f"Failed to write batch: {e}") from e + finally: + give_back_slot() + + def _release_write_slot(self, lock: Any = None) -> None: # noqa: ANN401 + """Release the in-process writer slot.""" + self._writer.release(lock) @contextmanager def transaction(self) -> Iterator[RocksDBTransaction]: """Context manager for a read-write transaction. Commits on successful exit, aborts on any exception (including - KeyboardInterrupt, cancellation and GeneratorExit) so row locks are - never left held. + KeyboardInterrupt, cancellation and GeneratorExit) so the writer + slot is never left held. """ txn = self.begin_transaction() try: @@ -619,41 +742,38 @@ def _notify_batch(self, keys: set[Key]) -> None: except Exception as e: logger.error(f"Publisher notification failed: {e}") - def _remove_transaction(self, transaction: RocksDBTransaction) -> None: - """Remove transaction from active set. - - Args: - transaction: Transaction to remove - """ - with self._db_lock: + def _untrack_transaction(self, transaction: RocksDBTransaction) -> None: + """Remove transaction from active set.""" + with self._state_lock: self._active_transactions.discard(transaction) - def _remove_snapshot(self, snapshot: RocksDBSnapshot) -> None: - """Remove snapshot from active set. - - Args: - snapshot: Snapshot to remove - """ - with self._db_lock: + def _untrack_snapshot(self, snapshot: RocksDBSnapshot) -> None: + """Remove snapshot from active set.""" + with self._state_lock: self._active_snapshots.discard(snapshot) - def _remove_write_batch(self, write_batch: RocksDBWriteBatch) -> None: - """Remove write batch from active set. - - Args: - write_batch: Write batch to remove - """ - with self._db_lock: + def _untrack_write_batch(self, write_batch: RocksDBWriteBatch) -> None: + """Remove write batch from active set.""" + with self._state_lock: self._active_write_batches.discard(write_batch) def _require_open(self) -> None: - """Validate storage is open. + """Validate storage is open, in the process that opened it. Raises: StorageClosedError: If storage is not open + StorageError: If this is a forked child of the opening process: + the rocksdb handle (background threads, directory lock) + does not survive a fork, so the child must open its own """ if not self._opened or self._db is None: raise StorageClosedError("Storage is not open") + if self._pid != os.getpid(): + raise StorageError( + "RocksDB storage was opened in another process; a forked child " + "cannot use its handle. RocksDB is single-process: open the " + "storage in this process instead" + ) if TYPE_CHECKING: diff --git a/src/virtuals/_backends/storages/rocksdb/transaction.py b/src/virtuals/_backends/storages/rocksdb/transaction.py index e6cc936a..820b06b2 100644 --- a/src/virtuals/_backends/storages/rocksdb/transaction.py +++ b/src/virtuals/_backends/storages/rocksdb/transaction.py @@ -3,16 +3,18 @@ from __future__ import annotations from logging import getLogger -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from virtuals.tkv.storage import ( StorageClosedError, + StorageLockTimeoutError, StorageTransactionAbortedError, + StorageTransactionConflictError, StorageTransactionError, TransactionProtocol, ) -from .context import ContextBase, ReadOperationsMixin, WriteOperationsMixin +from .context import ContextBase, ReadOperationsMixin, WriteOperationsMixin, classify_rdbpy if TYPE_CHECKING: @@ -28,31 +30,38 @@ logger = getLogger(__name__) +# Commit failures that keep their class: the retryable ones, and a handle +# whose storage closed underneath it. Anything else is a transaction error. +_RAISE_AS_IS = (StorageTransactionConflictError, StorageLockTimeoutError, StorageClosedError) + class RocksDBTransaction( ContextBase, ReadOperationsMixin, WriteOperationsMixin, TransactionProtocol ): - """Read-write transaction implementation. + """Read-write transaction backed by a pessimistic rdbpy transaction. + + The transaction holds the storage's writer slot from begin until commit + or abort, so it is the only writer on the storage while it runs: what + it reads cannot move under it, point reads and scans alike. Reads go + through the transaction's own snapshot, taken at begin, merged with its + pending writes. - Provides full read-write access with ACID guarantees. - Composed from base context, read operations, write operations, - and transaction control. + The rocksdb row locks and snapshot validation underneath are a second + line of defence: a writer that somehow bypasses the slot surfaces as a + retryable conflict or lock timeout, never as a silent lost update. """ - __slots__ = ("_aborted", "_committed", "_modified_keys") + __slots__ = ("_aborted", "_committed", "_modified_keys", "_rdbpy_txn") - def __init__( - self, - storage: RocksDBStorage, - rdbpy_txn: object, - ) -> None: + def __init__(self, storage: RocksDBStorage, rdbpy_txn: Any) -> None: # noqa: ANN401 """Initialize transaction. Args: storage: Parent storage instance - rdbpy_txn: RocksDB transaction handle + rdbpy_txn: rdbpy transaction handle, begun with a snapshot """ - super().__init__(storage, rdbpy_txn) + super().__init__(storage, holds_write_slot=True) + self._rdbpy_txn: Any | None = rdbpy_txn self._modified_keys: set[Key] = set() self._committed = False self._aborted = False @@ -62,12 +71,28 @@ def writable(self) -> bool: """Always True for transactions.""" return True + def _drop_handles(self) -> None: + self._rdbpy_txn = None + + def _get_raw(self, encoded_key: bytes) -> bytes | None: + """Read at the transaction snapshot, merging pending writes.""" + return self._rdbpy_txn.get(encoded_key) # type: ignore[union-attr] + + def _iterator(self, *, keys_only: bool, reverse: bool) -> Any: # noqa: ANN401 + """Cursor at the transaction snapshot, merging pending writes.""" + return self._rdbpy_txn.iterator(keys_only=keys_only, reverse=reverse) # type: ignore[union-attr] + def commit(self) -> None: """Commit all changes in the transaction. Sends notifications for all modified keys after successful commit. + A failed commit ends the transaction (rdbpy rolls it back) and gives + back the writer slot. Raises: + StorageTransactionConflictError: If rocksdb refused the commit + as a conflict (retryable) + StorageLockTimeoutError: If rocksdb timed out on a lock (retryable) StorageTransactionError: If commit fails or transaction is invalid StorageClosedError: If context is closed """ @@ -81,52 +106,47 @@ def commit(self) -> None: logger.error("Cannot commit, transaction already aborted") raise StorageTransactionError("Transaction already aborted") - txn = self._require_active() - - # Commit to RocksDB + txn = self._rdbpy_txn try: - txn.commit() + txn.commit() # type: ignore[union-attr] except Exception as e: + self._aborted = True + self._mark_closed() + self._storage._untrack_transaction(self) logger.error("Transaction commit failed") + mapped = classify_rdbpy(e, "Failed to commit transaction") + if isinstance(mapped, _RAISE_AS_IS): + raise mapped from e raise StorageTransactionError(f"Failed to commit transaction: {e}") from e - logger.info("Transaction committed") + logger.debug("Transaction committed") - # Mark as committed before notifications self._committed = True self._mark_closed() - - # Notify observers (batch) self._storage._notify_batch(self._modified_keys) - - # Remove from active transactions - self._storage._remove_transaction(self) + self._storage._untrack_transaction(self) def abort(self) -> None: """Abort transaction and discard all changes. Raises: StorageTransactionAbortedError: If abort fails - StorageClosedError: If context is closed """ if self._closed: - # Already closed, nothing to do logger.debug("Abort called on closed transaction") return - txn = self._require_active() - + txn = self._rdbpy_txn try: - txn.rollback() - - logger.info("Transaction aborted") + txn.rollback() # type: ignore[union-attr] + logger.debug("Transaction aborted") except Exception as e: logger.error("Transaction abort failed") raise StorageTransactionAbortedError(f"Failed to abort transaction: {e}") from e finally: self._aborted = True self._mark_closed() - self._storage._remove_transaction(self) + self._storage._untrack_transaction(self) def __enter__(self) -> RocksDBTransaction: """Enter context manager.""" @@ -144,12 +164,9 @@ def __exit__( Otherwise, commit the transaction. """ if exc_type is not None: - # Exception occurred - abort try: self.abort() except Exception: logger.error("Transaction abort failed") - else: - # No exception - commit if not already done - if not self._committed and not self._aborted: - self.commit() + elif not self._committed and not self._aborted: + self.commit() diff --git a/src/virtuals/_backends/storages/rocksdb/write_batch.py b/src/virtuals/_backends/storages/rocksdb/write_batch.py index 150cc0c9..47a0add1 100644 --- a/src/virtuals/_backends/storages/rocksdb/write_batch.py +++ b/src/virtuals/_backends/storages/rocksdb/write_batch.py @@ -3,7 +3,7 @@ from __future__ import annotations from logging import getLogger -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from virtuals.tkv.storage import ( StorageClosedError, @@ -32,24 +32,23 @@ class RocksDBWriteBatch(ContextBase, WriteBatchProtocol): """Write-only batch implementation for RocksDB. - Provides efficient bulk write operations using rdbpy.WriteBatch. - Does not support read operations - optimized for write-heavy workloads. + Buffers puts and deletes in an rdbpy.WriteBatch and applies them in one + atomic write. The batch takes the storage's writer slot only for the + duration of ``write``, so it queues behind transactions and never + lands in the middle of one. """ - __slots__ = ("_aborted", "_modified_keys", "_written") + __slots__ = ("_aborted", "_modified_keys", "_rdbpy_batch", "_written") - def __init__( - self, - storage: RocksDBStorage, - rdbpy_batch: object, - ) -> None: + def __init__(self, storage: RocksDBStorage, rdbpy_batch: Any) -> None: # noqa: ANN401 """Initialize write batch. Args: storage: Parent storage instance rdbpy_batch: RocksDB write batch handle """ - super().__init__(storage, rdbpy_batch) + super().__init__(storage) + self._rdbpy_batch: Any | None = rdbpy_batch self._modified_keys: set[Key] = set() self._written = False self._aborted = False @@ -59,6 +58,9 @@ def writable(self) -> bool: """Always True for write batches.""" return True + def _drop_handles(self) -> None: + self._rdbpy_batch = None + def put(self, key: Key, value: Value) -> None: """Put key-value pair into batch. @@ -70,23 +72,20 @@ def put(self, key: Key, value: Value) -> None: StorageOperationError: If write fails StorageClosedError: If batch is closed """ - batch = self._require_active() + self._require_active() codec = self._storage.codec - # Encode key and value try: encoded_key = codec.encode_key(key) encoded_value = codec.encode_value(value) except Exception as e: raise StorageOperationError(f"Failed to encode key/value for {key}: {e}") from e - # Add to batch try: - batch.put(encoded_key, encoded_value) + self._rdbpy_batch.put(encoded_key, encoded_value) # type: ignore[union-attr] except Exception as e: raise StorageOperationError(f"Failed to put key {key}: {e}") from e - # Track modification for notifications self._modified_keys.add(key) def delete(self, key: Key) -> None: @@ -101,7 +100,7 @@ def delete(self, key: Key) -> None: StorageOperationError: If deletion fails StorageClosedError: If batch is closed """ - batch = self._require_active() + self._require_active() codec = self._storage.codec try: @@ -110,21 +109,24 @@ def delete(self, key: Key) -> None: raise StorageOperationError(f"Failed to encode key {key}: {e}") from e try: - # Add delete to batch - batch.delete(encoded_key) + self._rdbpy_batch.delete(encoded_key) # type: ignore[union-attr] except Exception as e: raise StorageOperationError(f"Failed to delete key {key}: {e}") from e - # Track modification for notifications self._modified_keys.add(key) def write(self) -> None: """Write batch and make changes permanent. - Sends notifications for all modified keys after successful write. + Takes the writer slot, applies the batch atomically, releases the + slot. Sends notifications for all modified keys after a successful + write. Raises: - StorageTransactionError: If write fails + StorageLockTimeoutError: If the writer slot is not free in time + StorageNestedTransactionError: If this task or thread already + holds a write transaction on the storage + StorageTransactionError: If the write fails StorageClosedError: If already written or aborted """ if self._closed: @@ -137,49 +139,32 @@ def write(self) -> None: logger.error("Cannot write, batch already aborted") raise StorageTransactionError("Write batch already aborted") - batch = self._require_active() + batch = self._rdbpy_batch self._storage._require_open() - # Write to RocksDB try: - self._storage._db.write(batch, disable_wal=self._storage._disable_wal) - except Exception as e: + self._storage._write_batch(batch) + except Exception: logger.error("Write batch write failed") - raise StorageTransactionError(f"Failed to write batch: {e}") from e + raise - logger.info("Write batch written") + logger.debug("Write batch written") - # Mark as written before notifications self._written = True self._mark_closed() - - # Notify observers (batch) self._storage._notify_batch(self._modified_keys) - - # Remove from active batches - self._storage._remove_write_batch(self) + self._storage._untrack_write_batch(self) def abort(self) -> None: - """Abort write batch and discard changes. - - Raises: - StorageTransactionError: If abort fails - StorageClosedError: If batch is closed - """ + """Abort write batch and discard changes.""" if self._closed: - # Already closed, nothing to do logger.debug("Abort called on closed write batch") return - try: - logger.info("Write batch aborted") - - self._aborted = True - self._mark_closed() - self._storage._remove_write_batch(self) - except Exception as e: - logger.error("Write batch abort failed") - raise StorageTransactionError(f"Failed to abort write batch: {e}") from e + self._aborted = True + self._mark_closed() + self._storage._untrack_write_batch(self) + logger.debug("Write batch aborted") def __enter__(self) -> RocksDBWriteBatch: """Enter context manager.""" @@ -197,12 +182,9 @@ def __exit__( Otherwise, write the batch. """ if exc_type is not None: - # Exception occurred - abort try: self.abort() except Exception: logger.error("Write batch abort failed") - else: - # No exception - write if not already done - if not self._written and not self._aborted: - self.write() + elif not self._written and not self._aborted: + self.write() diff --git a/src/virtuals/storages/rocksdb.py b/src/virtuals/storages/rocksdb.py index 75a6b3c7..124a70d2 100644 --- a/src/virtuals/storages/rocksdb.py +++ b/src/virtuals/storages/rocksdb.py @@ -1,10 +1,16 @@ -"""RocksDB storage backend implementation.""" +"""RocksDB storage backend implementation. + +``RocksDBStorage`` is the serial variant: one writer at a time per storage, +every read at a real snapshot. ``RocksDBSerialStorage`` is the same class +under its variant name. +""" from __future__ import annotations -from virtuals._backends.storages.rocksdb import RocksDBStorage +from virtuals._backends.storages.rocksdb import RocksDBSerialStorage, RocksDBStorage __all__ = [ + "RocksDBSerialStorage", "RocksDBStorage", ] diff --git a/tests/_backends/storages/test_rocksdb_contract.py b/tests/_backends/storages/test_rocksdb_contract.py new file mode 100644 index 00000000..bfb89156 --- /dev/null +++ b/tests/_backends/storages/test_rocksdb_contract.py @@ -0,0 +1,817 @@ +"""The kv contract on the RocksDB serial variant. + +Sections 1-4 of the contract as point tests: serializable transactions +(lost update, write skew, insert race, phantom on scan), read your own +writes, point-in-time snapshots (repeatable, never torn), the nested +transaction error, retryable error classes, and coroutine writers that +queue on the writer slot without stalling the event loop. +""" + +from __future__ import annotations + +import asyncio +import os +import threading +import time +from typing import TYPE_CHECKING, Any + +import pytest +import rdbpy + +from virtuals._backends.storages.rocksdb import RocksDBSerialStorage, RocksDBStorage +from virtuals._backends.storages.rocksdb.context import classify_rdbpy +from virtuals.codecs import BinaryCodec +from virtuals.tkv import StorageScanOptions +from virtuals.tkv.filter import PrefixFilter +from virtuals.tkv.storage import ( + StorageClosedError, + StorageError, + StorageLockTimeoutError, + StorageNestedTransactionError, + StorageOperationError, + StorageTransactionConflictError, +) +from virtuals.tkv.types import EMPTY + + +if TYPE_CHECKING: + from pathlib import Path + + +RETRYABLE = (StorageTransactionConflictError, StorageLockTimeoutError) + +K = ("counter",) +X, Y = ("x",), ("y",) + +ROUNDS = 20 +PAUSE = 0.001 # between a read and its dependent write, so a race can happen +BARRIER = 0.05 # how long a racer waits for its peer after reading + + +@pytest.fixture +def storage(tmp_path: Path): + s = RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec(), busy_timeout=5.0) + s.open() + yield s + s.close() + + +def _retrying(fn, attempts: int = 200): + for i in range(attempts): + try: + return fn() + except RETRYABLE: + time.sleep(min(0.0005 * (i + 1), 0.005)) + raise AssertionError("still conflicting") + + +def _put(storage, items: dict) -> None: + def body() -> None: + with storage.transaction() as t: + for k, v in items.items(): + t.put(k, v) + + _retrying(body) + + +def _read(storage, key): + with storage.snapshot() as s: + return s.get(key) + + +def _threads(*targets, timeout: float = 10.0) -> list: + results: list = [None] * len(targets) + errors: list[BaseException] = [] + + def wrap(i, fn): + try: + results[i] = fn() + except BaseException as e: + errors.append(e) + + threads = [ + threading.Thread(target=wrap, args=(i, fn), daemon=True) for i, fn in enumerate(targets) + ] + for t in threads: + t.start() + for t in threads: + t.join(timeout) + assert not any(t.is_alive() for t in threads), "stalled" + if errors: + raise errors[0] + return results + + +def _wait(barrier: threading.Barrier) -> None: + try: + barrier.wait(timeout=BARRIER) + except threading.BrokenBarrierError: + pass + + +# ============================================================================= +# Section 1: serializable transactions +# ============================================================================= + + +def test_variant_naming_and_process_model() -> None: + assert RocksDBSerialStorage is RocksDBStorage + assert RocksDBStorage.process_model == "single" + + +def test_lost_update_threads(storage: RocksDBStorage) -> None: + _put(storage, {K: 0}) + threads, iters = 4, 25 + + def worker() -> None: + for _ in range(iters): + + def body() -> None: + with storage.transaction() as t: + v = t.get(K) + time.sleep(PAUSE) + t.put(K, v + 1) + + _retrying(body) + + _threads(*[worker] * threads) + assert _read(storage, K) == threads * iters + + +def test_write_skew_disjoint_keys(storage: RocksDBStorage) -> None: + """At most one of x, y is on: each claimer sets its own only if the other read off.""" + barrier = threading.Barrier(2) + violations = 0 + for _ in range(ROUNDS): + _put(storage, {X: False, Y: False}) + barrier.reset() + + def claim(mine, other): + def body() -> None: + with storage.transaction() as t: + seen = t.get(other) + _wait(barrier) + if not seen: + t.put(mine, True) + + return lambda: _retrying(body) + + _threads(claim(X, Y), claim(Y, X)) + if _read(storage, X) and _read(storage, Y): + violations += 1 + assert violations == 0 + + +def test_insert_race(storage: RocksDBStorage) -> None: + """Create-if-absent on one key: exactly one creator wins.""" + barrier = threading.Barrier(2) + doubles = 0 + for r in range(ROUNDS): + key = ("slot", r) + barrier.reset() + + def create(me, key=key): + def body() -> bool: + with storage.transaction() as t: + present = t.get(key) + _wait(barrier) + if present is EMPTY: + t.put(key, me) + return True + return False + + return lambda: _retrying(body) + + if sum(_threads(create("a"), create("b"))) != 1: + doubles += 1 + assert doubles == 0 + + +def test_scan_write_skew_no_phantom(storage: RocksDBStorage) -> None: + """A decision from a scanned range is not skewed by a concurrent insert into it.""" + barrier = threading.Barrier(2) + violations = 0 + for r in range(ROUNDS): + prefix = ("seat", r) + barrier.reset() + options = StorageScanOptions(start=prefix, break_filter=PrefixFilter(prefix=prefix)) + + def take(me, prefix=prefix, options=options): + def body() -> None: + with storage.transaction() as t: + taken = list(t.scan(options).keys()) + _wait(barrier) + if not taken: + t.put((*prefix, me), True) + + return lambda: _retrying(body) + + _threads(take("a"), take("b")) + with storage.snapshot() as s: + if len(list(s.scan(options).keys())) > 1: + violations += 1 + assert violations == 0 + + +def test_read_your_own_writes(storage: RocksDBStorage) -> None: + _put(storage, {("r", 1): "old", ("r", 2): "gone"}) + options = StorageScanOptions(start=("r",), break_filter=PrefixFilter(prefix=("r",))) + with storage.transaction() as t: + t.put(("r", 1), "new") + t.put(("r", 3), "added") + t.delete(("r", 2)) + assert t.get(("r", 1)) == "new" + assert t.get(("r", 3)) == "added" + assert t.get(("r", 2)) is EMPTY + assert not t.exists(("r", 2)) + assert dict(t.scan(options).items()) == {("r", 1): "new", ("r", 3): "added"} + assert list(t.scan(StorageScanOptions(start=("r", 9), reverse=True)).keys())[:2] == [ + ("r", 3), + ("r", 1), + ] + t.abort() + with storage.snapshot() as s: + assert dict(s.scan(options).items()) == {("r", 1): "old", ("r", 2): "gone"} + + +def test_transaction_reads_are_pinned_while_it_runs(storage: RocksDBStorage) -> None: + """A read-only transaction is never torn: it holds the slot, writers wait.""" + _put(storage, {X: 1, Y: -1}) + t = storage.begin_transaction() + try: + first = t.get(X) + done = threading.Event() + + def writer() -> None: + _put(storage, {X: 2, Y: -2}) # blocks on the slot until t ends + done.set() + + th = threading.Thread(target=writer, daemon=True) + th.start() + time.sleep(0.05) + assert not done.is_set(), "writer committed under an open transaction" + assert t.get(X) == first + assert t.get(X) + t.get(Y) == 0 + finally: + t.abort() + assert done.wait(5.0) + assert _read(storage, X) == 2 + + +def test_nested_transaction_raises_distinct_error(storage: RocksDBStorage) -> None: + assert not issubclass(StorageNestedTransactionError, RETRYABLE) + outer = storage.begin_transaction() + try: + outer.put(K, 1) + t0 = time.monotonic() + with pytest.raises(StorageNestedTransactionError): + storage.begin_transaction() + with pytest.raises(StorageNestedTransactionError): + with storage.batch_write() as batch: + batch.put(K, 2) + assert time.monotonic() - t0 < 0.5 + finally: + outer.abort() + storage.begin_transaction().commit() # the slot came back with the abort + assert _read(storage, K) is EMPTY + + +def test_nested_transaction_in_same_task_raises(storage: RocksDBStorage) -> None: + async def main() -> None: + slot = await storage.areserve_write_slot() + tx = storage.begin_transaction(write_slot=slot) + with pytest.raises(StorageNestedTransactionError): + await storage.areserve_write_slot() + with pytest.raises(StorageNestedTransactionError): + storage.begin_transaction() + tx.abort() + storage.begin_transaction().commit() + + asyncio.run(main()) + + +# ============================================================================= +# Section 2: snapshots +# ============================================================================= + + +def test_snapshot_repeatable_read(storage: RocksDBStorage) -> None: + _put(storage, {X: 0}) + for i in range(1, ROUNDS + 1): + with storage.snapshot() as s: + first = s.get(X) + _threads(lambda i=i: _put(storage, {X: i})) + assert s.get(X) == first + assert dict(s.scan(StorageScanOptions()).items())[X] == first + assert _read(storage, X) == i + + +def test_snapshot_never_torn(storage: RocksDBStorage) -> None: + """The writer keeps x + y == 0; a snapshot reads x, a commit lands, it reads y.""" + _put(storage, {X: 0, Y: 0}) + torn = [] + for i in range(1, ROUNDS + 1): + with storage.snapshot() as s: + x = s.get(X) + _threads(lambda i=i: _put(storage, {X: i, Y: -i})) + y = s.get(Y) + if x + y != 0: + torn.append((x, y)) + assert not torn + + +def test_snapshot_not_torn_under_continuous_writer(storage: RocksDBStorage) -> None: + _put(storage, {X: 0, Y: 0}) + stop = threading.Event() + + def writer() -> None: + i = 0 + while not stop.is_set(): + i += 1 + _put(storage, {X: i, Y: -i}) + + th = threading.Thread(target=writer, daemon=True) + th.start() + reads = torn = 0 + end = time.monotonic() + 0.3 + try: + while time.monotonic() < end: + with storage.snapshot() as s: + a = s.get(X) + time.sleep(0.0002) + b = s.get(Y) + reads += 1 + torn += a + b != 0 + finally: + stop.set() + th.join(5.0) + assert reads > 10 + assert torn == 0 + + +def test_snapshot_never_waits_on_writer(storage: RocksDBStorage) -> None: + _put(storage, {X: 0}) + wrote, release = threading.Event(), threading.Event() + + def writer() -> None: + t = storage.begin_transaction() + try: + t.put(X, 1) + wrote.set() + release.wait(5.0) + finally: + t.abort() + + th = threading.Thread(target=writer, daemon=True) + th.start() + try: + assert wrote.wait(5.0) + t0 = time.monotonic() + with storage.snapshot() as s: + seen = s.get(X) + elapsed = time.monotonic() - t0 + finally: + release.set() + th.join(5.0) + assert seen == 0 + assert elapsed < 0.1 + + +def test_read_only_open_serves_snapshots(tmp_path: Path) -> None: + with RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec()) as rw: + _put(rw, {X: 1}) + ro = RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec(), read_only=True) + ro.open() + try: + assert _read(ro, X) == 1 + with pytest.raises(StorageError): + ro.begin_transaction() + with pytest.raises(StorageError): + ro.begin_write_batch() + finally: + ro.close() + + +# ============================================================================= +# Section 3: errors and retry +# ============================================================================= + + +@pytest.mark.parametrize( + ("error", "expected"), + [ + (rdbpy.Busy("busy", 11, 0), StorageTransactionConflictError), + (rdbpy.Deadlock("deadlock", 11, 5), StorageTransactionConflictError), + (rdbpy.TryAgain("history", 13, 0), StorageTransactionConflictError), + (rdbpy.Expired("expired", 12, 0), StorageTransactionConflictError), + (rdbpy.TimedOut("lock", 9, 2), StorageLockTimeoutError), + (rdbpy.LockLimit("locks", 11, 3), StorageLockTimeoutError), + (rdbpy.Corruption("bad", 2, 0), StorageOperationError), + (RuntimeError("iterator is closed or its parent has ended"), StorageClosedError), + ], +) +def test_rdbpy_errors_map_by_class(error: Exception, expected: type) -> None: + mapped = classify_rdbpy(error, "op") + assert type(mapped) is expected + assert isinstance(mapped, RETRYABLE) == issubclass(expected, RETRYABLE) + + +def test_row_lock_held_outside_the_slot_is_a_lock_timeout(tmp_path: Path) -> None: + """A writer that bypasses the slot (a raw rdbpy txn) surfaces as retryable, fast.""" + s = RocksDBStorage( + path=tmp_path / "db", + codec=BinaryCodec(), + txn_db_options={"transaction_lock_timeout": 20, "default_lock_timeout": 20}, + ) + s.open() + try: + raw = s._db.begin() + raw.put(s.codec.encode_key(K), b"raw") + t0 = time.monotonic() + with pytest.raises(StorageLockTimeoutError), s.transaction() as t: + t.put(K, 1) + assert time.monotonic() - t0 < 1.0 + raw.rollback() + _put(s, {K: 1}) + finally: + s.close() + + +def test_key_moved_after_snapshot_is_a_conflict(storage: RocksDBStorage) -> None: + """A write that bypasses the slot after the txn snapshot surfaces as a conflict.""" + _put(storage, {K: 0}) + with pytest.raises(StorageTransactionConflictError), storage.transaction() as t: + assert t.get(K) == 0 + storage._db.put(storage.codec.encode_key(K), b"\x00") # behind the slot's back + t.put(K, 1) + _put(storage, {K: 2}) + assert _read(storage, K) == 2 + + +def test_lock_timeout_between_threads(tmp_path: Path) -> None: + s = RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec(), busy_timeout=0.05) + s.open() + try: + holding, release = threading.Event(), threading.Event() + + def holder() -> None: + with s.transaction() as t: + t.put(K, 1) + holding.set() + release.wait(5.0) + + th = threading.Thread(target=holder, daemon=True) + th.start() + assert holding.wait(5.0) + t0 = time.monotonic() + with pytest.raises(StorageLockTimeoutError): + s.begin_transaction() + with pytest.raises(StorageLockTimeoutError): + with s.batch_write() as b: + b.put(K, 2) + assert 0.05 <= time.monotonic() - t0 < 1.0 + release.set() + th.join(5.0) + assert _read(s, K) == 1 + finally: + s.close() + + +def test_closed_storage_error_is_not_retryable(tmp_path: Path) -> None: + s = RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec()) + s.open() + s.close() + with pytest.raises(StorageError) as info: + with s.transaction() as t: + t.put(K, 1) + assert not isinstance(info.value, RETRYABLE) + + +def test_close_refuses_while_a_thread_is_inside_a_call(tmp_path: Path) -> None: + """close() during another thread's native call raises and frees nothing. + + It used to abort that thread's transaction under it (a segfault). + """ + s = RocksDBStorage( + path=tmp_path / "db", + codec=BinaryCodec(), + txn_db_options={"transaction_lock_timeout": 1000, "default_lock_timeout": 1000}, + ) + s.open() + raw = s._db.begin() + raw.put(s.codec.encode_key(K), b"raw") # row lock outside the slot + entered = threading.Event() + outcome: list = [] + + def worker() -> None: + t = s.begin_transaction() + entered.set() + try: + t.put(K, 1) # waits nogil on the row lock + except RETRYABLE as e: + outcome.append(e) + t.abort() + + th = threading.Thread(target=worker, daemon=True) + th.start() + entered.wait(5) + time.sleep(0.2) + with pytest.raises(StorageError, match="in use"): + s.close() + th.join(5) + assert outcome and isinstance(outcome[0], StorageLockTimeoutError) + raw.rollback() + _put(s, {K: 2}) + assert _read(s, K) == 2 + s.close() + + +def test_close_wakes_slot_waiter_with_closed_error(tmp_path: Path) -> None: + """A sync writer queued on the slot sees a closed storage once close() ends.""" + s = RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec(), busy_timeout=5.0) + s.open() + held = s.begin_transaction() + errors: list[BaseException] = [] + + def waiter() -> None: + try: + s.begin_transaction() + except BaseException as e: + errors.append(e) + + th = threading.Thread(target=waiter, daemon=True) + th.start() + time.sleep(0.05) + s.close() + th.join(5) + assert not th.is_alive() + assert held.is_closed + assert errors and isinstance(errors[0], StorageClosedError) + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +def test_close_in_forked_child_frees_nothing(tmp_path: Path) -> None: + """A forked child's close() forgets the parent's handle instead of tearing it down. + + Tearing it down in the child hung (no-WAL memtable flush waits on a + background thread only the parent has). + """ + s = RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec(), disable_wal=True) + s.open() + _put(s, {K: 1}) + txn = s.begin_transaction() + snap = s.begin_snapshot() + before = sorted(p.name for p in (tmp_path / "db").iterdir()) + pid = os.fork() + if pid == 0: # pragma: no cover - child + code = 1 + try: + s.close() + code = 0 if txn.is_closed and snap.is_closed and not s._opened else 2 + finally: + os._exit(code) + deadline = time.monotonic() + 10 + while (done := os.waitpid(pid, os.WNOHANG))[0] == 0 and time.monotonic() < deadline: + time.sleep(0.02) + if done[0] == 0: + os.kill(pid, 9) + os.waitpid(pid, 0) + pytest.fail("close hung in the forked child") + assert os.waitstatus_to_exitcode(done[1]) == 0 + assert sorted(p.name for p in (tmp_path / "db").iterdir()) == before + assert snap.get(K) == 1 + txn.put(K, 2) + txn.commit() + snap.close() + assert _read(s, K) == 2 + s.close() + + +def test_write_batch_queues_behind_transaction(storage: RocksDBStorage) -> None: + """A batch never lands inside a transaction: it waits for the slot.""" + _put(storage, {K: 0}) + order: list[str] = [] + holding = threading.Event() + + def holder() -> None: + with storage.transaction() as t: + holding.set() + v = t.get(K) + time.sleep(0.1) + t.put(K, v + 1) + order.append("txn") + + th = threading.Thread(target=holder, daemon=True) + th.start() + assert holding.wait(5.0) + with storage.batch_write() as b: + b.put(K, 100) + order.append("batch") + th.join(5.0) + assert order == ["txn", "batch"] + assert _read(storage, K) == 100 + + +# ============================================================================= +# Section 4: coroutines and the event loop +# ============================================================================= + + +async def _increment(storage: RocksDBStorage, key: tuple, pause: float) -> None: + slot = await storage.areserve_write_slot() + try: + tx = storage.begin_transaction(write_slot=slot) + try: + cur = tx.get(key) + tx.put(key, (cur if cur is not EMPTY else 0) + 1) + await asyncio.sleep(pause) + except BaseException: + tx.abort() + raise + tx.commit() + finally: + slot.release() + + +def test_concurrent_incs_do_not_stall_the_loop(storage: RocksDBStorage) -> None: + """10 coroutines inc one key with an await inside the txn: all land, fast, loop alive.""" + n, step, tick = 10, 0.005, 0.002 + + async def main() -> tuple[float, float]: + stop = asyncio.Event() + last = time.perf_counter() + gap = 0.0 + + async def ticker() -> None: + nonlocal last, gap + while not stop.is_set(): + await asyncio.sleep(tick) + now = time.perf_counter() + gap = max(gap, now - last) + last = now + + t = asyncio.create_task(ticker()) + t0 = time.perf_counter() + await asyncio.gather(*(_increment(storage, K, step) for _ in range(n))) + wall = time.perf_counter() - t0 + stop.set() + await t + return wall, gap + + wall, gap = asyncio.run(main()) + assert _read(storage, K) == n + assert wall < 1.0, f"{n} incs took {wall:.2f}s" + assert gap < 0.1, f"event loop blocked for {gap * 1000:.0f}ms" + + +def test_coroutine_holding_slot_blocks_peer_until_commit(storage: RocksDBStorage) -> None: + order: list[str] = [] + + async def a() -> None: + slot = await storage.areserve_write_slot() + tx = storage.begin_transaction(write_slot=slot) + tx.put(("a",), 1) + order.append("a holds") + await asyncio.sleep(0.05) + order.append("a commits") + tx.commit() + slot.release() # no-op: the transaction owned the slot + + async def b() -> None: + await asyncio.sleep(0.01) + slot = await storage.areserve_write_slot() + order.append("b holds") + with storage.begin_transaction(write_slot=slot) as tx: + assert tx.get(("a",)) == 1 + tx.put(("b",), 2) + + async def main() -> None: + await asyncio.gather(a(), b()) + + asyncio.run(main()) + assert order == ["a holds", "a commits", "b holds"] + assert _read(storage, ("b",)) == 2 + + +def test_sync_begin_behind_loop_peer_fails_fast(storage: RocksDBStorage) -> None: + async def holder(ready: asyncio.Event, done: asyncio.Event) -> None: + slot = await storage.areserve_write_slot() + ready.set() + await done.wait() + slot.release() + + async def main() -> None: + ready, done = asyncio.Event(), asyncio.Event() + task = asyncio.create_task(holder(ready, done)) + await ready.wait() + t0 = time.monotonic() + with pytest.raises(StorageLockTimeoutError, match="areserve_write_slot"): + storage.begin_transaction() + assert time.monotonic() - t0 < 0.5 + done.set() + await task + + asyncio.run(main()) + storage.begin_transaction().commit() + + +def test_unused_slot_is_released(storage: RocksDBStorage) -> None: + async def main() -> None: + slot = await storage.areserve_write_slot() + assert slot.held + slot.release() + slot.release() + assert not slot.held + with pytest.raises(StorageError): + storage.begin_transaction(write_slot=slot) + + asyncio.run(main()) + storage.begin_transaction().commit() + + +def test_failed_begin_returns_slot_to_holder(storage: RocksDBStorage) -> None: + async def main() -> None: + slot = await storage.areserve_write_slot() + db = storage._db + + class Broken: + def __getattr__(self, name: str) -> Any: + return getattr(db, name) + + def begin(self, **kwargs: Any) -> Any: + raise rdbpy.RocksIOError("no begin", 5, 0) + + storage._db = Broken() + try: + with pytest.raises(StorageError, match="no begin"): + storage.begin_transaction(write_slot=slot) + finally: + storage._db = db + assert slot.held + storage.begin_transaction(write_slot=slot).commit() + assert not slot.held + + asyncio.run(main()) + storage.begin_transaction().commit() + + +def test_async_waiter_times_out_without_blocking_loop(tmp_path: Path) -> None: + with RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec(), busy_timeout=0.2) as s: + + async def main() -> int: + held = await s.areserve_write_slot() + ticks = 0 + stop = asyncio.Event() + + async def ticker() -> None: + nonlocal ticks + while not stop.is_set(): + ticks += 1 + await asyncio.sleep(0.005) + + tick_task = asyncio.create_task(ticker()) + t0 = time.monotonic() + + async def waiter() -> None: + await s.areserve_write_slot() + + with pytest.raises(StorageLockTimeoutError, match="Timed out"): + await asyncio.create_task(waiter()) + elapsed = time.monotonic() - t0 + stop.set() + await tick_task + held.release() + assert 0.15 < elapsed < 1.0 + return ticks + + assert asyncio.run(main()) >= 10 + + +# ============================================================================= +# Options compatibility +# ============================================================================= + + +def test_option_dicts_translate(tmp_path: Path) -> None: + s = RocksDBStorage( + path=tmp_path / "db", + codec=BinaryCodec(), + options={"block_cache_mb": 4, "block_table": {"cache_index_and_filter_blocks": True}}, + txn_db_options={"lock_timeout_ms": 10, "max_num_deadlocks": 2}, + txn_options={"deadlock_detect": True, "lock_timeout": 10}, + ) + s.open() + try: + _put(s, {K: 1}) + assert _read(s, K) == 1 + finally: + s.close() + + +def test_unknown_option_is_a_storage_error(tmp_path: Path) -> None: + s = RocksDBStorage(path=tmp_path / "db", codec=BinaryCodec(), options={"nope": 1}) + with pytest.raises(StorageError, match="options"): + s.open() + s = RocksDBStorage(path=tmp_path / "db2", codec=BinaryCodec(), txn_db_options={"nope": 1}) + with pytest.raises(StorageError, match="options"): + s.open() diff --git a/tests/_backends/storages/test_rocksdb_storage.py b/tests/_backends/storages/test_rocksdb_storage.py index 66d49eb8..20d3525c 100644 --- a/tests/_backends/storages/test_rocksdb_storage.py +++ b/tests/_backends/storages/test_rocksdb_storage.py @@ -3,7 +3,7 @@ Covers what compliance cannot: scans that outlive their transaction or the storage (a use-after-free in rdbpy before 0.2.7), reverse scans with start bounds, secondary instances, TransactionDB options and aborting on -BaseException. +BaseException. The kv contract cases live in ``test_rocksdb_contract.py``. """ from __future__ import annotations @@ -170,49 +170,47 @@ def test_reverse_prefix_scan_from_upper_bound(storage: RocksDBStorage) -> None: class _CountingIterator: def __init__(self, it: Any) -> None: self._it = it - self.steps = 0 + self.rows = 0 def __getattr__(self, name: str) -> Any: return getattr(self._it, name) - def skip(self) -> None: - self.steps += 1 - self._it.skip() + def next_batch(self, n: int) -> list: + rows = self._it.next_batch(n) + self.rows += len(rows) + return rows - def skip_back(self) -> None: - self.steps += 1 - self._it.skip_back() - -class _CountingTxn: - def __init__(self, txn: Any) -> None: - self._txn = txn +class _CountingDB: + def __init__(self, db: Any) -> None: + self._db = db self.iterators: list[_CountingIterator] = [] def __getattr__(self, name: str) -> Any: - return getattr(self._txn, name) + return getattr(self._db, name) - def iterkeys(self) -> _CountingIterator: - it = _CountingIterator(self._txn.iterkeys()) + def iterator(self, **kwargs: Any) -> _CountingIterator: + it = _CountingIterator(self._db.iterator(**kwargs)) self.iterators.append(it) return it def test_reverse_prefix_scan_seeks_instead_of_walking(storage: RocksDBStorage) -> None: _fill(storage, KEYS) - snap = storage.begin_snapshot() - counting = _CountingTxn(snap._rdbpy_txn) - snap._rdbpy_txn = counting - options = StorageScanOptions( - start=("a", 10), reverse=True, break_filter=PrefixFilter(prefix=("a",)) - ) - keys = list(snap.scan(options).keys()) - snap._rdbpy_txn = counting._txn - snap.close() + counting = _CountingDB(storage._db) + storage._db = counting + try: + options = StorageScanOptions( + start=("a", 10), reverse=True, break_filter=PrefixFilter(prefix=("a",)) + ) + with storage.snapshot() as snap: + keys = list(snap.scan(options).keys()) + finally: + storage._db = counting._db assert keys == [("a", i) for i in range(10, -1, -1)] - # 11 yielded keys, then one step off the start of the keyspace; no walk - # over the 100 keys after the start bound. - assert counting.iterators[0].steps == 11 + # 11 yielded keys from the seek down to the start of the keyspace; no + # walk over the 100 keys after the start bound. + assert counting.iterators[0].rows == 11 # ============================================================================= diff --git a/tests/conformance/backends.py b/tests/conformance/backends.py index 522b1ee1..c7ba3da0 100644 --- a/tests/conformance/backends.py +++ b/tests/conformance/backends.py @@ -63,6 +63,7 @@ def _rocksdb(root: Path, lock_timeout: float | None, codec: Any): if lock_timeout is not None: ms = max(1, int(lock_timeout * 1000)) kwargs["txn_db_options"] = {"transaction_lock_timeout": ms, "default_lock_timeout": ms} + kwargs["busy_timeout"] = lock_timeout # in-process slot, see contract section 4 return RocksDBStorage(path=root / "rocks", codec=codec, **kwargs) diff --git a/tests/conformance/known_failures.py b/tests/conformance/known_failures.py index 9759fef0..9b0b2460 100644 --- a/tests/conformance/known_failures.py +++ b/tests/conformance/known_failures.py @@ -7,53 +7,13 @@ from __future__ import annotations -LANE_K = "fixed by lane K (rocksdb rewrite)" LMDB_XPROC = ( "lmdb cross-process writer wait is unbounded; contract §4; owner: lmdb writer slot follow-up" ) # case name -> backend -> (strict, reason) KNOWN_FAILURES: dict[str, dict[str, tuple[bool, str]]] = { - "test_s1_lost_update_threads": { - "rocksdb": (True, f"reads ignore concurrent commits, last writer wins; {LANE_K}"), - }, - "test_s1_write_skew_disjoint_keys": { - "rocksdb": (True, f"read-committed, no read validation; {LANE_K}"), - }, - "test_s1_insert_race": { - "rocksdb": (True, f"absent read not validated; {LANE_K}"), - }, - "test_s1_scan_write_skew": { - "rocksdb": (True, f"scanned range not protected from inserts; {LANE_K}"), - }, - "test_s1_nested_transaction_raises_distinct_error": { - "rocksdb": (True, f"inner write waits on its own lock, then lock timeout; {LANE_K}"), - }, - "test_s1_nested_batch_write_raises_distinct_error": { - "rocksdb": (True, f"batch waits on the txn's key lock, then a generic txn error; {LANE_K}"), - }, - "test_s2_repeatable_read_in_snapshot": { - "rocksdb": (True, f"snapshot reads see later commits; {LANE_K}"), - }, - "test_s2_snapshot_never_torn": { - "rocksdb": (True, f"snapshot reads see later commits; {LANE_K}"), - }, - "test_s2_snapshot_binds_at_open_get": { - "rocksdb": (True, f"snapshot reads see commits after open; {LANE_K}"), - }, - "test_s2_snapshot_binds_at_open_scan": { - "rocksdb": (True, f"snapshot scans see commits after open; {LANE_K}"), - }, - "test_s2_commit_atomic_to_concurrent_snapshots": { - "rocksdb": (True, f"snapshot reads see commits landing between its reads; {LANE_K}"), - }, "test_s3_cross_process_contention_raises_retryable": { "lmdb": (True, LMDB_XPROC), }, - "test_s4_coroutine_writers_serialize": { - "rocksdb": (True, f"no writer slot, coroutines lose updates; {LANE_K}"), - }, - "test_s4_coroutine_writers_do_not_block_loop": { - "rocksdb": (True, f"lock wait blocks the event loop thread; {LANE_K}"), - }, } diff --git a/tests/views/test_fractional_indexed_dict_view.py b/tests/views/test_fractional_indexed_dict_view.py index d47a0b21..aa0c4ed8 100644 --- a/tests/views/test_fractional_indexed_dict_view.py +++ b/tests/views/test_fractional_indexed_dict_view.py @@ -1001,61 +1001,6 @@ def test_two_writers_appending(fdict): _assert_consistent(view) -@pytest.mark.parametrize("backend", ["rocksdb"]) -def test_window_respace_vs_concurrent_insert_inside_window(backend, tmp_path): - """A respace can displace a concurrent insert next to a row in its window. - - T1 inserts at a hot gap until a window respace fires; T2 inserts after - a row inside T1's window. T2 writes none of the rows T1 rewrites, so - both commit on every multi-writer backend (sqlite, lmdb and mem - are single-writer and never see this). The documented outcome: T2's item - is present exactly once and the rest of the order is intact; only its - position may have shifted into the rewritten range. - """ - storage = _open_storage(backend, tmp_path) - try: - with storage.transaction() as tx: - view = Navigator(storage).root(tx).open_child("lst", _CountingRespaceView) - view.store([f"r{i}" for i in range(20)] + ["h"] + [f"s{i}" for i in range(20)]) - # Fill the gap after h until the next fresh key would pass the cap. - i = 0 - while True: - view.insert_after("h", f"c{i}") - if len(view.position(f"c{i}")) >= view.MAX_KEY_LENGTH - 3: - break - i += 1 - t1 = storage.begin_transaction() - t2 = storage.begin_transaction() - try: - v1 = Navigator(storage).root(t1).open_child("lst", _CountingRespaceView) - v2 = Navigator(storage).root(t2).open_child("lst", _CountingRespaceView) - _CountingRespaceView.respaces = [] - n = 0 - while not _CountingRespaceView.respaces: - v1.insert_after("h", f"y{n}") - n += 1 - order_t1 = list(v1) - ref = order_t1[order_t1.index("h") - 2] # inside T1's window below h - v2.insert_after(ref, "Z") - t1.commit() - t2.commit() - except BaseException: - for t in (t1, t2): - t.abort() - raise - with storage.snapshot() as sn: - view = Navigator(storage).root(sn).open_child("lst", _CountingRespaceView) - got = list(view) - assert got.count("Z") == 1 - assert len(view) == len(got) - assert [x for x in got if x != "Z"] == order_t1 - assert view["Z"] is True - assert view.position("Z") == next(ok for ok, a in view.positions() if a == "Z") - _assert_consistent(view) - finally: - storage.close() - - # ============================================================================ # HOOKS (mem with the in-memory transport) # ============================================================================