Spaces:
Build error
Build error
File size: 11,009 Bytes
84d2a97 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 |
use std::collections::HashSet;
use std::path::Path;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use common::counter::hardware_accumulator::HwMeasurementAcc;
use common::tar_ext;
use common::types::TelemetryDetail;
use segment::data_types::facets::{FacetParams, FacetResponse};
use segment::data_types::order_by::OrderBy;
use segment::types::{
ExtendedPointId, Filter, PointIdType, ScoredPoint, SnapshotFormat, WithPayload,
WithPayloadInterface, WithVector,
};
use tokio::runtime::Handle;
use tokio::sync::{oneshot, RwLock};
use tokio::time::timeout;
use super::update_tracker::UpdateTracker;
use crate::operations::operation_effect::{
EstimateOperationEffectArea, OperationEffectArea, PointsOperationEffect,
};
use crate::operations::types::{
CollectionError, CollectionInfo, CollectionResult, CoreSearchRequestBatch,
CountRequestInternal, CountResult, PointRequestInternal, RecordInternal, UpdateResult,
};
use crate::operations::universal_query::shard_query::{ShardQueryRequest, ShardQueryResponse};
use crate::operations::OperationWithClockTag;
use crate::shards::local_shard::LocalShard;
use crate::shards::shard_trait::ShardOperation;
use crate::shards::telemetry::LocalShardTelemetry;
use crate::update_handler::UpdateSignal;
type ChangedPointsSet = Arc<RwLock<HashSet<PointIdType>>>;
/// ProxyShard
///
/// ProxyShard is a wrapper type for a LocalShard.
///
/// It can be used to provide all read and write operations while the wrapped shard is being transferred to another node.
/// It keeps track of changed points during the shard transfer to assure consistency.
pub struct ProxyShard {
wrapped_shard: LocalShard,
changed_points: ChangedPointsSet,
pub changed_alot: AtomicBool,
}
/// Max number of updates tracked to synchronize after the transfer.
const MAX_CHANGES_TRACKED_COUNT: usize = 10_000;
/// How much time can we wait for the update queue to be empty.
/// We don't want false positive here, so it should be large.
/// If the queue stuck - it means something wrong with application logic.
const UPDATE_QUEUE_CLEAR_TIMEOUT: Duration = Duration::from_secs(1);
const UPDATE_QUEUE_CLEAR_MAX_TIMEOUT: Duration = Duration::from_secs(128);
impl ProxyShard {
#[allow(unused)]
pub async fn new(wrapped_shard: LocalShard) -> Self {
let res = Self {
wrapped_shard,
changed_points: Default::default(),
changed_alot: Default::default(),
};
res.reinit_changelog().await;
res
}
/// Forward `create_snapshot` to `wrapped_shard`
pub async fn create_snapshot(
&self,
temp_path: &Path,
tar: &tar_ext::BuilderExt,
format: SnapshotFormat,
save_wal: bool,
) -> CollectionResult<()> {
self.wrapped_shard
.create_snapshot(temp_path, tar, format, save_wal)
.await
}
pub async fn on_optimizer_config_update(&self) -> CollectionResult<()> {
self.wrapped_shard.on_optimizer_config_update().await
}
pub fn trigger_optimizers(&self) {
// TODO: we might want to defer this trigger until we unproxy
self.wrapped_shard.trigger_optimizers();
}
pub async fn reinit_changelog(&self) -> CollectionResult<()> {
// Blocks updates in the wrapped shard.
let mut changed_points_guard = self.changed_points.write().await;
// Clear the update queue
let mut attempt = 1;
loop {
let (tx, rx) = oneshot::channel();
let plunger = UpdateSignal::Plunger(tx);
self.wrapped_shard
.update_sender
.load()
.send(plunger)
.await?;
let attempt_timeout = UPDATE_QUEUE_CLEAR_TIMEOUT * (2_u32).pow(attempt);
// It is possible, that the queue is recreated while we are waiting for plunger.
// So we will timeout and try again
if timeout(attempt_timeout, rx).await.is_err() {
log::warn!("Timeout {} while waiting for the wrapped shard to finish the update queue, retrying", attempt_timeout.as_secs());
attempt += 1;
if attempt_timeout > UPDATE_QUEUE_CLEAR_MAX_TIMEOUT {
return Err(CollectionError::service_error(
"Timeout while waiting for the wrapped shard to finish the update queue"
.to_string(),
));
}
continue;
}
break;
}
// Update queue is clear now
// Clear the changed_points set
changed_points_guard.clear();
// Clear changed_alot flag
self.changed_alot
.store(false, std::sync::atomic::Ordering::Relaxed);
Ok(())
}
pub fn get_telemetry_data(&self, detail: TelemetryDetail) -> LocalShardTelemetry {
self.wrapped_shard.get_telemetry_data(detail)
}
pub fn update_tracker(&self) -> &UpdateTracker {
self.wrapped_shard.update_tracker()
}
}
#[async_trait]
impl ShardOperation for ProxyShard {
/// Update `wrapped_shard` while keeping track of the changed points
///
/// # Cancel safety
///
/// This method is *not* cancel safe.
async fn update(
&self,
operation: OperationWithClockTag,
wait: bool,
) -> CollectionResult<UpdateResult> {
// If we modify `self.changed_points`, we *have to* (?) execute `local_shard` update
// to completion, so this method is not cancel safe.
let local_shard = &self.wrapped_shard;
let estimate_effect = operation.operation.estimate_effect_area();
let points_operation_effect: PointsOperationEffect = match estimate_effect {
OperationEffectArea::Empty => PointsOperationEffect::Empty,
OperationEffectArea::Points(points) => PointsOperationEffect::Some(points),
OperationEffectArea::Filter(filter) => {
let cardinality = local_shard.estimate_cardinality(Some(&filter))?;
// validate the size of the change set before retrieving it
if cardinality.max > MAX_CHANGES_TRACKED_COUNT {
PointsOperationEffect::Many
} else {
let runtime_handle = self.wrapped_shard.search_runtime.clone();
let points = local_shard
.read_filtered(Some(&filter), &runtime_handle)
.await?;
PointsOperationEffect::Some(points.into_iter().collect())
}
}
};
{
let mut changed_points_guard = self.changed_points.write().await;
match points_operation_effect {
PointsOperationEffect::Empty => {}
PointsOperationEffect::Some(points) => {
for point in points {
// points updates are recorded but never trigger in `changed_alot`
changed_points_guard.insert(point);
}
}
PointsOperationEffect::Many => {
self.changed_alot
.store(true, std::sync::atomic::Ordering::Relaxed);
}
}
// Shard update is within a write lock scope, because we need a way to block the shard updates
// during the transfer restart and finalization.
local_shard.update(operation, wait).await
}
}
/// Forward read-only `scroll_by` to `wrapped_shard`
async fn scroll_by(
&self,
offset: Option<ExtendedPointId>,
limit: usize,
with_payload_interface: &WithPayloadInterface,
with_vector: &WithVector,
filter: Option<&Filter>,
search_runtime_handle: &Handle,
order_by: Option<&OrderBy>,
timeout: Option<Duration>,
) -> CollectionResult<Vec<RecordInternal>> {
let local_shard = &self.wrapped_shard;
local_shard
.scroll_by(
offset,
limit,
with_payload_interface,
with_vector,
filter,
search_runtime_handle,
order_by,
timeout,
)
.await
}
/// Forward read-only `info` to `wrapped_shard`
async fn info(&self) -> CollectionResult<CollectionInfo> {
let local_shard = &self.wrapped_shard;
local_shard.info().await
}
/// Forward read-only `search` to `wrapped_shard`
async fn core_search(
&self,
request: Arc<CoreSearchRequestBatch>,
search_runtime_handle: &Handle,
timeout: Option<Duration>,
hw_measurement_acc: &HwMeasurementAcc,
) -> CollectionResult<Vec<Vec<ScoredPoint>>> {
let local_shard = &self.wrapped_shard;
local_shard
.core_search(request, search_runtime_handle, timeout, hw_measurement_acc)
.await
}
/// Forward read-only `count` to `wrapped_shard`
async fn count(
&self,
request: Arc<CountRequestInternal>,
search_runtime_handle: &Handle,
timeout: Option<Duration>,
hw_measurement_acc: &HwMeasurementAcc,
) -> CollectionResult<CountResult> {
let local_shard = &self.wrapped_shard;
local_shard
.count(request, search_runtime_handle, timeout, hw_measurement_acc)
.await
}
/// Forward read-only `retrieve` to `wrapped_shard`
async fn retrieve(
&self,
request: Arc<PointRequestInternal>,
with_payload: &WithPayload,
with_vector: &WithVector,
search_runtime_handle: &Handle,
timeout: Option<Duration>,
) -> CollectionResult<Vec<RecordInternal>> {
let local_shard = &self.wrapped_shard;
local_shard
.retrieve(
request,
with_payload,
with_vector,
search_runtime_handle,
timeout,
)
.await
}
/// Forward read-only `query` to `wrapped_shard`
async fn query_batch(
&self,
request: Arc<Vec<ShardQueryRequest>>,
search_runtime_handle: &Handle,
timeout: Option<Duration>,
hw_measurement_acc: &HwMeasurementAcc,
) -> CollectionResult<Vec<ShardQueryResponse>> {
let local_shard = &self.wrapped_shard;
local_shard
.query_batch(request, search_runtime_handle, timeout, hw_measurement_acc)
.await
}
async fn facet(
&self,
request: Arc<FacetParams>,
search_runtime_handle: &Handle,
timeout: Option<Duration>,
) -> CollectionResult<FacetResponse> {
let local_shard = &self.wrapped_shard;
local_shard
.facet(request, search_runtime_handle, timeout)
.await
}
}
|