* Skip applied WAL operations on shard load
* fixup! Skip applied WAL operations on shard load
- Skip WAL operation up to the *minimal* persisted version
- Add explanation comment
* fixup! Skip applied WAL operations on shard load
- "beautify" `skip_while` expression
- handle version `0` corner case (and add explanation)
* Update `Segment::handle_version` comment
* Simplify `Segment::handle_version` a bit
* Refactor `check_unprocessed_points`
* fixup! Refactor `check_unprocessed_points`
Optimized `check_unprocessed_points`
* Revert `LocalShard::load_from_wal` and `check_unprocessed_points` changes
* Downgrade failure in `check_unprocessed_points` to a warning
* Persist/track the first un-truncated index in `SerdeWal`...
...and use it as first index for WAL operations
* fixup! Downgrade failure in `check_unprocessed_points` to a warning
Downgrade failure in `check_unprocessed_points` to a warning *during `LocalShard::load_from_wal`* 🙈
* fixup! Persist/track the first un-truncated index in `SerdeWal`...
Words...
* Fix a bug in `SerdeWal::truncated_prefix_entries_num` and add explanation comment
* Fix a bug in `SerdeWal::ack`
* prevent unnesessary savings, use json, never decrease ack index
---------
Co-authored-by: Andrey Vasnetsov <andrey@vasnetsov.com>
This commit is contained in:
parent
77921a3a68
commit
291be89400
@ -2,7 +2,6 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use itertools::Itertools;
|
||||
use parking_lot::{RwLock, RwLockWriteGuard};
|
||||
use segment::data_types::named_vectors::NamedVectors;
|
||||
use segment::entry::entry_point::{OperationResult, SegmentEntry};
|
||||
@ -22,20 +21,11 @@ pub(crate) fn check_unprocessed_points(
|
||||
points: &[PointIdType],
|
||||
processed: &HashSet<PointIdType>,
|
||||
) -> CollectionResult<usize> {
|
||||
let unprocessed_points = points
|
||||
.iter()
|
||||
.cloned()
|
||||
.filter(|p| !processed.contains(p))
|
||||
.collect_vec();
|
||||
let missed_point = unprocessed_points.iter().cloned().next();
|
||||
let first_missed_point = points.iter().copied().find(|p| !processed.contains(p));
|
||||
|
||||
// ToDo: check pre-existing points
|
||||
|
||||
match missed_point {
|
||||
match first_missed_point {
|
||||
None => Ok(processed.len()),
|
||||
Some(missed_point) => Err(CollectionError::PointNotFound {
|
||||
missed_point_id: missed_point,
|
||||
}),
|
||||
Some(missed_point_id) => Err(CollectionError::PointNotFound { missed_point_id }),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -392,7 +392,20 @@ impl LocalShard {
|
||||
|
||||
bar.set_message(format!("Recovering collection {collection_id}"));
|
||||
let segments = self.segments();
|
||||
// ToDo: Start from minimal applied version
|
||||
|
||||
// When `Segment`s are flushed, WAL is truncated up to the index of the last operation
|
||||
// that has been applied and flushed.
|
||||
//
|
||||
// `SerdeWal` wrapper persists/keeps track of this index (in addition to any handling
|
||||
// in the `wal` crate itself).
|
||||
//
|
||||
// `SerdeWal::read_all` starts reading WAL from the first "un-truncated" index,
|
||||
// so no additional handling required to "skip" any potentially applied entries.
|
||||
//
|
||||
// Note, that it's not guaranted that some operation won't be re-applied to the storage.
|
||||
// (`SerdeWal::read_all` may even start reading WAL from some already truncated
|
||||
// index *occasionally*), but the storage can handle it.
|
||||
|
||||
for (op_num, update) in wal.read_all() {
|
||||
// Propagate `CollectionError::ServiceError`, but skip other error types.
|
||||
match &CollectionUpdater::update(segments, op_num, update) {
|
||||
@ -416,6 +429,7 @@ impl LocalShard {
|
||||
log::error!("{err}");
|
||||
return Err(err.clone());
|
||||
}
|
||||
Err(err @ CollectionError::NotFound { .. }) => log::warn!("{err}"),
|
||||
Err(err) => log::error!("{err}"),
|
||||
Ok(_) => (),
|
||||
}
|
||||
|
||||
@ -4,6 +4,7 @@ use std::path::Path;
|
||||
use std::result;
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use segment::common::file_operations::{atomic_save_json, read_json};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
@ -44,6 +45,17 @@ enum TestRecord {
|
||||
|
||||
type Result<T> = result::Result<T, WalError>;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
struct WalState {
|
||||
pub ack_index: u64,
|
||||
}
|
||||
|
||||
impl WalState {
|
||||
pub fn new(ack_index: u64) -> Self {
|
||||
Self { ack_index }
|
||||
}
|
||||
}
|
||||
|
||||
/// Write-Ahead-Log wrapper with built-in type parsing.
|
||||
/// Stores sequences of records of type `R` in binary files.
|
||||
///
|
||||
@ -54,16 +66,36 @@ pub struct SerdeWal<R> {
|
||||
record: PhantomData<R>,
|
||||
wal: Wal,
|
||||
options: WalOptions,
|
||||
first_index: Option<u64>,
|
||||
}
|
||||
|
||||
const FIRST_INDEX_FILE: &str = "first-index";
|
||||
|
||||
impl<'s, R: DeserializeOwned + Serialize + Debug> SerdeWal<R> {
|
||||
pub fn new(dir: &str, wal_options: WalOptions) -> Result<SerdeWal<R>> {
|
||||
let wal = Wal::with_options(dir, &wal_options)
|
||||
.map_err(|err| WalError::InitWalError(format!("{err:?}")))?;
|
||||
|
||||
let first_index_path = Path::new(dir).join(FIRST_INDEX_FILE);
|
||||
|
||||
let first_index = if first_index_path.exists() {
|
||||
let wal_state: WalState = read_json(&first_index_path).map_err(|err| {
|
||||
WalError::InitWalError(format!("failed to read first-index file: {err}"))
|
||||
})?;
|
||||
|
||||
let first_index = wal_state
|
||||
.ack_index
|
||||
.clamp(wal.first_index(), wal.last_index());
|
||||
Some(first_index)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(SerdeWal {
|
||||
record: PhantomData,
|
||||
wal,
|
||||
options: wal_options,
|
||||
first_index,
|
||||
})
|
||||
}
|
||||
|
||||
@ -77,7 +109,7 @@ impl<'s, R: DeserializeOwned + Serialize + Debug> SerdeWal<R> {
|
||||
}
|
||||
|
||||
pub fn read_all(&'s self) -> impl Iterator<Item = (u64, R)> + 's {
|
||||
self.read(self.wal.first_index())
|
||||
self.read(self.first_index())
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
@ -85,14 +117,36 @@ impl<'s, R: DeserializeOwned + Serialize + Debug> SerdeWal<R> {
|
||||
}
|
||||
|
||||
pub fn len(&self) -> u64 {
|
||||
self.wal.num_entries()
|
||||
self.wal
|
||||
.num_entries()
|
||||
.saturating_sub(self.truncated_prefix_entries_num())
|
||||
}
|
||||
|
||||
// WAL operates in *segments*, so when `Wal::prefix_truncate` is called (during `SerdeWal::ack`),
|
||||
// WAL is not truncated precisely up to the `until_index`, but up to the nearest segment with
|
||||
// `last_index` that is less-or-equal than `until_index`.
|
||||
//
|
||||
// Consider the pseudo-graphic illustration of the WAL that was truncated up to index 35:
|
||||
//
|
||||
// | -------- | -------- | ===='++++ | ++++++++ | ++++++++ | ++++++++ |
|
||||
// 10 20 30 35 40 50 60 70
|
||||
//
|
||||
// - ' marks the index 35 that has been truncated-to
|
||||
// - --- marks segments 10-30 that has been physically deleted
|
||||
// - +++ marks segments 35-70 that are still valid
|
||||
// - and === marks part of segment 30-35, that is still physically present on disk,
|
||||
// but that is "logically" deleted
|
||||
//
|
||||
// `truncated_prefix_entries_num` returns the length of the "logically deleted" part of the WAL.
|
||||
fn truncated_prefix_entries_num(&self) -> u64 {
|
||||
self.first_index().saturating_sub(self.wal.first_index())
|
||||
}
|
||||
|
||||
pub fn read(&'s self, start_from: u64) -> impl Iterator<Item = (u64, R)> + 's {
|
||||
let first_index = self.wal.first_index();
|
||||
let num_entries = self.wal.num_entries();
|
||||
let first_index = self.first_index();
|
||||
let len = self.len();
|
||||
|
||||
(start_from..(first_index + num_entries)).map(move |idx| {
|
||||
(start_from..(first_index + len)).map(move |idx| {
|
||||
let record_bin = self.wal.entry(idx).expect("Can't read entry from WAL");
|
||||
let record: R = serde_cbor::from_slice(&record_bin)
|
||||
.or_else(|_err| rmp_serde::from_slice(&record_bin))
|
||||
@ -109,9 +163,39 @@ impl<'s, R: DeserializeOwned + Serialize + Debug> SerdeWal<R> {
|
||||
/// * `until_index` - the newest no longer required record sequence number
|
||||
///
|
||||
pub fn ack(&mut self, until_index: u64) -> Result<()> {
|
||||
// Truncate WAL
|
||||
self.wal
|
||||
.prefix_truncate(until_index)
|
||||
.map_err(|err| WalError::TruncateWalError(format!("{err:?}")))
|
||||
.map_err(|err| WalError::TruncateWalError(format!("{err:?}")))?;
|
||||
|
||||
// Acknowledge index should not decrease
|
||||
let minimal_first_index = self.first_index.unwrap_or(self.wal.first_index());
|
||||
let new_first_index = Some(until_index.clamp(minimal_first_index, self.wal.last_index()));
|
||||
// Update current `first_index`
|
||||
if self.first_index != new_first_index {
|
||||
self.first_index = new_first_index;
|
||||
// Persist current `first_index` value on disk
|
||||
// TODO: Should we log this error and continue instead of failing?
|
||||
self.flush_first_index()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn flush_first_index(&self) -> Result<()> {
|
||||
let Some(first_index) = self.first_index else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
atomic_save_json(
|
||||
&self.path().join(FIRST_INDEX_FILE),
|
||||
&WalState::new(first_index),
|
||||
)
|
||||
.map_err(|err| {
|
||||
WalError::TruncateWalError(format!("failed to write first-index file: {err:?}"))
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn flush(&mut self) -> Result<()> {
|
||||
@ -128,6 +212,10 @@ impl<'s, R: DeserializeOwned + Serialize + Debug> SerdeWal<R> {
|
||||
self.wal.path()
|
||||
}
|
||||
|
||||
pub fn first_index(&self) -> u64 {
|
||||
self.first_index.unwrap_or_else(|| self.wal.first_index())
|
||||
}
|
||||
|
||||
pub fn last_index(&self) -> u64 {
|
||||
self.wal.last_index()
|
||||
}
|
||||
|
||||
@ -285,7 +285,8 @@ impl Segment {
|
||||
{
|
||||
match op_point_offset {
|
||||
None => {
|
||||
// Not a point operation, use global version to check if already applied
|
||||
// Not a point operation *or* point does not exist.
|
||||
// Use global version to check if operation has been already applied.
|
||||
if self.version.unwrap_or(0) > op_num {
|
||||
return Ok(false); // Skip without execution
|
||||
}
|
||||
@ -303,17 +304,17 @@ impl Segment {
|
||||
}
|
||||
}
|
||||
|
||||
let res = operation(self);
|
||||
let (applied, point_id) = operation(self)?;
|
||||
|
||||
if res.is_ok() {
|
||||
self.version = Some(max(op_num, self.version.unwrap_or(0)));
|
||||
if let Ok((_, Some(point_id))) = res {
|
||||
self.id_tracker
|
||||
.borrow_mut()
|
||||
.set_internal_version(point_id, op_num)?;
|
||||
}
|
||||
self.version = Some(max(op_num, self.version.unwrap_or(0)));
|
||||
|
||||
if let Some(point_id) = point_id {
|
||||
self.id_tracker
|
||||
.borrow_mut()
|
||||
.set_internal_version(point_id, op_num)?;
|
||||
}
|
||||
res.map(|(res, _)| res)
|
||||
|
||||
Ok(applied)
|
||||
}
|
||||
|
||||
fn lookup_internal_id(&self, point_id: PointIdType) -> OperationResult<PointOffsetType> {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user