flow/
utils.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! utilities for managing state of dataflow execution
16
17use std::collections::{BTreeMap, BTreeSet};
18use std::ops::Bound;
19use std::sync::Arc;
20
21use common_meta::key::flow::flow_state::FlowStat;
22use common_telemetry::trace;
23use datatypes::value::Value;
24use get_size2::GetSize;
25use smallvec::{SmallVec, smallvec};
26use tokio::sync::{RwLock, mpsc, oneshot};
27use tokio::time::Instant;
28
29use crate::error::InternalSnafu;
30use crate::expr::{EvalError, ScalarExpr};
31use crate::repr::{DiffRow, Duration, KeyValDiffRow, Row, Timestamp, value_to_internal_ts};
32
33/// A batch of updates, arranged by key
34pub type Batch = BTreeMap<Row, SmallVec<[DiffRow; 2]>>;
35
36/// Get a estimate of heap size of a value
37pub fn get_value_heap_size(v: &Value) -> usize {
38    match v {
39        Value::Binary(bin) => bin.len(),
40        Value::String(s) => s.len(),
41        Value::List(list) => list.items().iter().map(get_value_heap_size).sum(),
42        _ => 0,
43    }
44}
45
46#[derive(Clone)]
47pub struct SizeReportSender {
48    inner: mpsc::Sender<oneshot::Sender<FlowStat>>,
49}
50
51impl SizeReportSender {
52    pub fn new() -> (Self, StateReportHandler) {
53        let (tx, rx) = mpsc::channel(1);
54        let zelf = Self { inner: tx };
55        (zelf, rx)
56    }
57
58    /// Query the size report, will timeout after one second if no response
59    pub async fn query(&self, timeout: std::time::Duration) -> crate::Result<FlowStat> {
60        let (tx, rx) = oneshot::channel();
61        self.inner.send(tx).await.map_err(|_| {
62            InternalSnafu {
63                reason: "failed to send size report request due to receiver dropped",
64            }
65            .build()
66        })?;
67        let timeout = tokio::time::timeout(timeout, rx);
68        timeout
69            .await
70            .map_err(|_elapsed| {
71                InternalSnafu {
72                    reason: "failed to receive size report after one second timeout",
73                }
74                .build()
75            })?
76            .map_err(|_| {
77                InternalSnafu {
78                    reason: "failed to receive size report due to sender dropped",
79                }
80                .build()
81            })
82    }
83}
84
85/// Handle the size report request, and send the report back
86pub type StateReportHandler = mpsc::Receiver<oneshot::Sender<FlowStat>>;
87
88/// A spine of batches, arranged by timestamp
89/// TODO(discord9): consider internally index by key, value, and timestamp for faster lookup
90pub type Spine = BTreeMap<Timestamp, Batch>;
91
92/// Determine when should a key expire according to it's event timestamp in key.
93///
94/// If a key is expired, any future updates to it should be ignored.
95///
96/// Note that key is expired by it's event timestamp (contained in the key), not by the time it's inserted (system timestamp).
97#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
98pub struct KeyExpiryManager {
99    /// A map from event timestamp to key, used for expire keys.
100    event_ts_to_key: BTreeMap<Timestamp, BTreeSet<Row>>,
101
102    /// Duration after which a key is considered expired, and will be removed from state
103    key_expiration_duration: Option<Duration>,
104
105    /// Expression to get timestamp from key row
106    event_timestamp_from_row: Option<ScalarExpr>,
107}
108
109impl GetSize for KeyExpiryManager {
110    fn get_heap_size(&self) -> usize {
111        let row_size = if let Some(row_size) = &self
112            .event_ts_to_key
113            .first_key_value()
114            .map(|(_, v)| v.first().get_heap_size())
115        {
116            *row_size
117        } else {
118            0
119        };
120        self.event_ts_to_key
121            .values()
122            .map(|v| v.len() * row_size + std::mem::size_of::<i64>())
123            .sum::<usize>()
124    }
125}
126
127impl KeyExpiryManager {
128    pub fn new(
129        key_expiration_duration: Option<Duration>,
130        event_timestamp_from_row: Option<ScalarExpr>,
131    ) -> Self {
132        Self {
133            event_ts_to_key: Default::default(),
134            key_expiration_duration,
135            event_timestamp_from_row,
136        }
137    }
138
139    /// Extract event timestamp from key row.
140    ///
141    /// If no expire state is set, return None.
142    pub fn extract_event_ts(&self, row: &Row) -> Result<Option<Timestamp>, EvalError> {
143        let ts = self
144            .event_timestamp_from_row
145            .as_ref()
146            .map(|e| e.eval(&row.inner))
147            .transpose()?
148            .map(value_to_internal_ts)
149            .transpose()?;
150        Ok(ts)
151    }
152
153    /// Return timestamp that should be expired by the time `now` by compute `now - expiration_duration`
154    pub fn compute_expiration_timestamp(&self, now: Timestamp) -> Option<Timestamp> {
155        self.key_expiration_duration.map(|d| now - d)
156    }
157
158    /// Update the event timestamp to key mapping.
159    ///
160    /// - If given key is expired by now (that is less than `now - expiry_duration`), return the amount of time it's expired.
161    /// - If it's not expired, return None
162    pub fn get_expire_duration_and_update_event_ts(
163        &mut self,
164        now: Timestamp,
165        row: &Row,
166    ) -> Result<Option<Duration>, EvalError> {
167        let Some(event_ts) = self.extract_event_ts(row)? else {
168            return Ok(None);
169        };
170
171        self.event_ts_to_key
172            .entry(event_ts)
173            .or_default()
174            .insert(row.clone());
175
176        if let Some(expire_time) = self.compute_expiration_timestamp(now)
177            && expire_time > event_ts
178        {
179            // return how much time it's expired
180            return Ok(Some(expire_time - event_ts));
181        }
182
183        Ok(None)
184    }
185
186    /// Get the expire duration of a key, if it's expired by now.
187    ///
188    /// Return None if the key is not expired
189    pub fn get_expire_duration(
190        &self,
191        now: Timestamp,
192        row: &Row,
193    ) -> Result<Option<Duration>, EvalError> {
194        let Some(event_ts) = self.extract_event_ts(row)? else {
195            return Ok(None);
196        };
197
198        if let Some(expire_time) = self.compute_expiration_timestamp(now)
199            && expire_time > event_ts
200        {
201            // return how much time it's expired
202            return Ok(Some(expire_time - event_ts));
203        }
204
205        Ok(None)
206    }
207
208    /// Remove expired keys from the state, and return an iterator of removed keys with
209    /// event_ts less than expire time (i.e. now - key_expiration_duration).
210    pub fn remove_expired_keys(&mut self, now: Timestamp) -> Option<impl Iterator<Item = Row>> {
211        let expire_time = self.compute_expiration_timestamp(now)?;
212
213        let mut before = self.event_ts_to_key.split_off(&expire_time);
214        std::mem::swap(&mut before, &mut self.event_ts_to_key);
215
216        Some(before.into_iter().flat_map(|(_ts, keys)| keys.into_iter()))
217    }
218}
219
220/// A shared state of key-value pair for various state in dataflow execution.
221///
222/// i.e: Mfp operator with temporal filter need to store it's future output so that it can add now, and delete later.
223/// To get all needed updates in a time span, use [`get_updates_in_range`].
224///
225/// And reduce operator need full state of it's output, so that it can query (and modify by calling [`apply_updates`])
226/// existing state, also need a way to expire keys. To get a key's current value, use [`get`] with time being `now`
227/// so it's like:
228/// `mfp operator -> arrange(store futures only, no expire) -> reduce operator <-> arrange(full, with key expiring time) -> output`
229///
230/// Note the two way arrow between reduce operator and arrange, it's because reduce operator need to query existing state
231/// and also need to update existing state.
232#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
233pub struct Arrangement {
234    /// A name or identifier for the arrangement which can be used for debugging or logging purposes.
235    /// This field is not critical to the functionality but aids in monitoring and management of arrangements.
236    name: Vec<String>,
237
238    /// Manages a collection of pending updates in a `BTreeMap` where each key is a timestamp and each value is a `Batch` of updates.
239    /// Updates are grouped into batched based on their timestamps.
240    /// Each batch covers a range of time from the last key (exclusive) to the current key (inclusive).
241    ///
242    /// - Updates with a timestamp (`update_ts`) that falls between two keys are placed in the batch of the higher key.
243    ///   For example, if the keys are `1, 5, 7, 9` and `update_ts` is `6`, the update goes into the batch with key `7`.
244    /// - Updates with a timestamp before the first key are categorized under the first key.
245    /// - Updates with a timestamp greater than the highest key result in a new batch being created with that timestamp as the key.
246    ///
247    /// The first key represents the current state and includes consolidated updates from the past. It is always set to `now`.
248    /// Each key should have only one update per batch with a `diff=1` for the batch representing the current time (`now`).
249    ///
250    /// Since updates typically occur as a delete followed by an insert, a small vector of size 2 is used to store updates for efficiency.
251    ///
252    /// TODO(discord9): Consider balancing the batch size?
253    spine: Spine,
254
255    /// Indicates whether the arrangement maintains a complete history of updates.
256    /// - `true`: Maintains all past and future updates, necessary for full state reconstruction at any point in time.
257    /// - `false`: Only future updates are retained, optimizing for scenarios where past state is irrelevant and conserving resources.
258    ///            Useful for case like `map -> arrange -> reduce`.
259    full_arrangement: bool,
260
261    /// Indicates whether the arrangement has been modified since its creation.
262    /// - `true`: The arrangement has been written to, meaning it has received updates.
263    ///           Cloning this arrangement is generally unsafe as it may lead to inconsistencies if the clone is modified independently.
264    ///           However, cloning is safe when both the original and the clone require a full arrangement, as this ensures consistency.
265    /// - `false`: The arrangement is in its initial state and has not been modified. It can be safely cloned and shared
266    ///            without concerns of carrying over unintended state changes.
267    is_written: bool,
268
269    /// Manage the expire state of the arrangement.
270    expire_state: Option<KeyExpiryManager>,
271
272    /// The time that the last compaction happened, also known as the current time.
273    last_compaction_time: Option<Timestamp>,
274
275    /// Estimated size of the arrangement in heap size.
276    estimated_size: usize,
277    last_size_update: Instant,
278    size_update_interval: tokio::time::Duration,
279}
280
281impl Arrangement {
282    fn compute_size(&self) -> usize {
283        self.spine
284            .values()
285            .map(|v| {
286                let per_entry_size = v
287                    .first_key_value()
288                    .map(|(k, v)| {
289                        k.get_heap_size()
290                            + v.len() * v.first().map(|r| r.get_heap_size()).unwrap_or(0)
291                    })
292                    .unwrap_or(0);
293                std::mem::size_of::<i64>() + v.len() * per_entry_size
294            })
295            .sum::<usize>()
296            + self.expire_state.get_heap_size()
297            + self.name.get_heap_size()
298    }
299
300    fn update_and_fetch_size(&mut self) -> usize {
301        if self.last_size_update.elapsed() > self.size_update_interval {
302            self.estimated_size = self.compute_size();
303            self.last_size_update = Instant::now();
304        }
305        self.estimated_size
306    }
307}
308
309impl GetSize for Arrangement {
310    fn get_heap_size(&self) -> usize {
311        self.estimated_size
312    }
313}
314
315impl Default for Arrangement {
316    fn default() -> Self {
317        Self {
318            spine: Default::default(),
319            full_arrangement: false,
320            is_written: false,
321            expire_state: None,
322            last_compaction_time: None,
323            name: Vec::new(),
324            estimated_size: 0,
325            last_size_update: Instant::now(),
326            size_update_interval: tokio::time::Duration::from_secs(3),
327        }
328    }
329}
330
331impl Arrangement {
332    pub fn new_with_name(name: Vec<String>) -> Self {
333        Self {
334            spine: Default::default(),
335            full_arrangement: false,
336            is_written: false,
337            expire_state: None,
338            last_compaction_time: None,
339            name,
340            estimated_size: 0,
341            last_size_update: Instant::now(),
342            size_update_interval: tokio::time::Duration::from_secs(3),
343        }
344    }
345
346    pub fn get_expire_state(&self) -> Option<&KeyExpiryManager> {
347        self.expire_state.as_ref()
348    }
349
350    pub fn set_expire_state(&mut self, expire_state: KeyExpiryManager) {
351        self.expire_state = Some(expire_state);
352    }
353
354    /// Apply updates into spine, with no respect of whether the updates are in futures, past, or now.
355    ///
356    /// Return the maximum expire time (already expire by how much time) of all updates if any keys is already expired.
357    pub fn apply_updates(
358        &mut self,
359        now: Timestamp,
360        updates: Vec<KeyValDiffRow>,
361    ) -> Result<Option<Duration>, EvalError> {
362        self.is_written = true;
363
364        let mut max_expired_by: Option<Duration> = None;
365
366        for ((key, val), update_ts, diff) in updates {
367            // check if the key is expired
368            if let Some(s) = &mut self.expire_state
369                && let Some(expired_by) = s.get_expire_duration_and_update_event_ts(now, &key)?
370            {
371                max_expired_by = max_expired_by.max(Some(expired_by));
372                trace!(
373                    "Expired key: {:?}, expired by: {:?} with time being now={}",
374                    key, expired_by, now
375                );
376                continue;
377            }
378
379            // If the `highest_ts` is less than `update_ts`, we need to create a new batch with key being `update_ts`.
380            if self
381                .spine
382                .last_key_value()
383                .map(|(highest_ts, _)| *highest_ts < update_ts)
384                .unwrap_or(true)
385            {
386                self.spine.insert(update_ts, Default::default());
387            }
388
389            // Get the first batch with key that's greater or equal to `update_ts`.
390            let (_, batch) = self
391                .spine
392                .range_mut(update_ts..)
393                .next()
394                .expect("Previous insert should have created the batch");
395
396            let key_updates = batch.entry(key).or_default();
397            key_updates.push((val, update_ts, diff));
398
399            // a stable sort make updates sort in order of insertion
400            // without changing the order of updates within same tick
401            key_updates.sort_by_key(|(_val, ts, _diff)| *ts);
402        }
403        self.update_and_fetch_size();
404        Ok(max_expired_by)
405    }
406
407    /// Find out the time of next update in the future that is the next update with `timestamp > now`.
408    pub fn get_next_update_time(&self, now: &Timestamp) -> Option<Timestamp> {
409        // iter over batches that only have updates of `timestamp>now` and find the first non empty batch, then get the minimum timestamp in that batch
410        for (_ts, batch) in self.spine.range((Bound::Excluded(now), Bound::Unbounded)) {
411            let min_ts = batch
412                .iter()
413                .flat_map(|(_k, v)| v.iter().map(|(_, ts, _)| *ts).min())
414                .min();
415
416            if min_ts.is_some() {
417                return min_ts;
418            }
419        }
420
421        None
422    }
423
424    /// Get the last compaction time.
425    pub fn last_compaction_time(&self) -> Option<Timestamp> {
426        self.last_compaction_time
427    }
428
429    /// Split spine off at `split_ts`, and return the spine that's before `split_ts` (including `split_ts`).
430    fn split_spine_le(&mut self, split_ts: &Timestamp) -> Spine {
431        self.split_batch_at(split_ts);
432        let mut before = self.spine.split_off(&(split_ts + 1));
433        std::mem::swap(&mut before, &mut self.spine);
434        before
435    }
436
437    /// Split the batch at `split_ts` into two parts.
438    fn split_batch_at(&mut self, split_ts: &Timestamp) {
439        // FAST PATH:
440        //
441        // The `split_ts` hit the boundary of a batch, nothing to do.
442        if self.spine.contains_key(split_ts) {
443            return;
444        }
445
446        let Some((_, batch_to_split)) = self.spine.range_mut(split_ts..).next() else {
447            return; // No batch to split, nothing to do.
448        };
449
450        // SLOW PATH:
451        //
452        // The `split_ts` is in the middle of a batch, we need to split the batch into two parts.
453        let mut new_batch = Batch::default();
454
455        batch_to_split.retain(|key, updates| {
456            let mut new_updates = SmallVec::default();
457
458            updates.retain(|(val, ts, diff)| {
459                if *ts <= *split_ts {
460                    // Move the updates that are less than or equal to `split_ts` to the new batch.
461                    new_updates.push((val.clone(), *ts, *diff));
462                }
463                // Keep the updates that are greater than `split_ts` in the current batch.
464                *ts > *split_ts
465            });
466
467            if !new_updates.is_empty() {
468                new_batch.insert(key.clone(), new_updates);
469            }
470
471            // Keep the key in the current batch if it still has updates.
472            !updates.is_empty()
473        });
474
475        if !new_batch.is_empty() {
476            self.spine.insert(*split_ts, new_batch);
477        }
478    }
479
480    /// Advance time to `now` and consolidate all older (`now` included) updates to the first key.
481    ///
482    /// Return the maximum expire time(already expire by how much time) of all updates if any keys is already expired.
483    pub fn compact_to(&mut self, now: Timestamp) -> Result<Option<Duration>, EvalError> {
484        let mut max_expired_by: Option<Duration> = None;
485
486        let batches_to_compact = self.split_spine_le(&now);
487        self.last_compaction_time = Some(now);
488
489        // If a full arrangement is not needed, we can just discard everything before and including now,
490        if !self.full_arrangement {
491            return Ok(None);
492        }
493
494        // else we update them into current state.
495        let mut compacting_batch = Batch::default();
496
497        for (_, batch) in batches_to_compact {
498            for (key, updates) in batch {
499                // check if the key is expired
500                if let Some(s) = &mut self.expire_state
501                    && let Some(expired_by) =
502                        s.get_expire_duration_and_update_event_ts(now, &key)?
503                {
504                    max_expired_by = max_expired_by.max(Some(expired_by));
505                    continue;
506                }
507
508                let mut row = compacting_batch
509                    .remove(&key)
510                    // only one row in the updates during compaction
511                    .and_then(|mut updates| updates.pop());
512
513                for update in updates {
514                    row = compact_diff_row(row, &update);
515                }
516                if let Some(compacted_update) = row {
517                    compacting_batch.insert(key, smallvec![compacted_update]);
518                }
519            }
520        }
521
522        // insert the compacted batch into spine with key being `now`
523        self.spine.insert(now, compacting_batch);
524        self.update_and_fetch_size();
525        Ok(max_expired_by)
526    }
527
528    /// Get the updates of the arrangement from the given range of time.
529    pub fn get_updates_in_range<R: std::ops::RangeBounds<Timestamp> + Clone>(
530        &self,
531        range: R,
532    ) -> Vec<KeyValDiffRow> {
533        // Include the next batch in case the range is not aligned with the boundary of a batch.
534        let batches = match range.end_bound() {
535            Bound::Included(t) => self.spine.range(range.clone()).chain(
536                self.spine
537                    .range((Bound::Excluded(t), Bound::Unbounded))
538                    .next(),
539            ),
540            Bound::Excluded(t) => self.spine.range(range.clone()).chain(
541                self.spine
542                    .range((Bound::Included(t), Bound::Unbounded))
543                    .next(),
544            ),
545            _ => self.spine.range(range.clone()).chain(None),
546        };
547
548        let mut res = vec![];
549        for (_, batch) in batches {
550            for (key, updates) in batch {
551                for (val, ts, diff) in updates {
552                    if range.contains(ts) {
553                        res.push(((key.clone(), val.clone()), *ts, *diff));
554                    }
555                }
556            }
557        }
558        res
559    }
560
561    /// Expire keys in now that are older than expire_time, intended for reducing memory usage and limit late data arrive
562    pub fn truncate_expired_keys(&mut self, now: Timestamp) {
563        if let Some(s) = &mut self.expire_state
564            && let Some(expired_keys) = s.remove_expired_keys(now)
565        {
566            for key in expired_keys {
567                for (_, batch) in self.spine.iter_mut() {
568                    batch.remove(&key);
569                }
570            }
571        }
572    }
573
574    /// Get current state of things.
575    ///
576    /// Useful for query existing keys (i.e. reduce and join operator need to query existing state)
577    pub fn get(&self, now: Timestamp, key: &Row) -> Option<DiffRow> {
578        // FAST PATH:
579        //
580        // If `now <= last_compaction_time`, and it's full arrangement, we can directly return the value
581        // from the current state (which should be the first batch in the spine if it exist).
582        if let Some(last_compaction_time) = self.last_compaction_time()
583            && now <= last_compaction_time
584            && self.full_arrangement
585        {
586            // if the last compaction time's batch is not exist, it means the spine doesn't have it's first batch as current value
587            return self
588                .spine
589                .get(&last_compaction_time)
590                .and_then(|batch| batch.get(key))
591                .and_then(|updates| updates.first().cloned());
592        }
593
594        // SLOW PATH:
595        //
596        // Accumulate updates from the oldest batch to the batch containing `now`.
597
598        let batches = if self.spine.contains_key(&now) {
599            // hit the boundary of a batch
600            self.spine.range(..=now).chain(None)
601        } else {
602            // not hit the boundary of a batch, should include the next batch
603            self.spine.range(..=now).chain(
604                self.spine
605                    .range((Bound::Excluded(now), Bound::Unbounded))
606                    .next(),
607            )
608        };
609
610        let mut final_val = None;
611        for (ts, batch) in batches {
612            if let Some(updates) = batch.get(key) {
613                if *ts <= now {
614                    for update in updates {
615                        final_val = compact_diff_row(final_val, update);
616                    }
617                } else {
618                    for update in updates.iter().filter(|(_, ts, _)| *ts <= now) {
619                        final_val = compact_diff_row(final_val, update);
620                    }
621                }
622            }
623        }
624        final_val
625    }
626}
627
628fn compact_diff_row(old_row: Option<DiffRow>, new_row: &DiffRow) -> Option<DiffRow> {
629    let (val, ts, diff) = new_row;
630    match (old_row, diff) {
631        (Some((row, _old_ts, old_diff)), diff) if row == *val && old_diff + diff == 0 => {
632            // the key is deleted now
633            None
634        }
635        (Some((row, _old_ts, old_diff)), diff) if row == *val && old_diff + diff != 0 => {
636            Some((row, *ts, old_diff + *diff))
637        }
638        // if old val not equal new val, simple consider it as being overwritten, for each key can only have one value
639        // so it make sense to just replace the old value with new value
640        _ => Some((val.clone(), *ts, *diff)),
641    }
642}
643
644/// Simply a type alias for ReadGuard of Arrangement
645pub type ArrangeReader<'a> = tokio::sync::RwLockReadGuard<'a, Arrangement>;
646/// Simply a type alias for WriteGuard of Arrangement
647pub type ArrangeWriter<'a> = tokio::sync::RwLockWriteGuard<'a, Arrangement>;
648
649/// A handler to the inner Arrangement, can be cloned and shared, useful for query it's inner state
650#[derive(Debug, Clone)]
651pub struct ArrangeHandler {
652    inner: Arc<RwLock<Arrangement>>,
653}
654
655impl ArrangeHandler {
656    /// create a new handler from arrangement
657    pub fn from(arr: Arrangement) -> Self {
658        Self {
659            inner: Arc::new(RwLock::new(arr)),
660        }
661    }
662
663    /// write lock the arrangement
664    pub fn write(&self) -> ArrangeWriter<'_> {
665        self.inner.blocking_write()
666    }
667
668    /// read lock the arrangement
669    pub fn read(&self) -> ArrangeReader<'_> {
670        self.inner.blocking_read()
671    }
672
673    /// Clone the handler, but only keep the future updates.
674    ///
675    /// It's a cheap operation, since it's `Arc-ed` and only clone the `Arc`.
676    pub fn clone_future_only(&self) -> Option<Self> {
677        if self.read().is_written {
678            return None;
679        }
680        Some(Self {
681            inner: self.inner.clone(),
682        })
683    }
684
685    /// Clone the handler, but keep all updates.
686    ///
687    /// Prevent illegal clone after the arrange have been written,
688    /// because that will cause loss of data before clone.
689    ///
690    /// It's a cheap operation, since it's `Arc-ed` and only clone the `Arc`.
691    pub fn clone_full_arrange(&self) -> Option<Self> {
692        {
693            let zelf = self.read();
694            if !zelf.full_arrangement && zelf.is_written {
695                return None;
696            }
697        }
698
699        self.write().full_arrangement = true;
700        Some(Self {
701            inner: self.inner.clone(),
702        })
703    }
704
705    pub fn set_full_arrangement(&self, full: bool) {
706        self.write().full_arrangement = full;
707    }
708
709    pub fn is_full_arrangement(&self) -> bool {
710        self.read().full_arrangement
711    }
712}
713
714#[cfg(test)]
715mod test {
716    use std::borrow::Borrow;
717
718    use datatypes::value::Value;
719    use itertools::Itertools;
720
721    use super::*;
722
723    fn lit(v: impl Into<Value>) -> Row {
724        Row::new(vec![v.into()])
725    }
726
727    fn kv(key: impl Borrow<Row>, value: impl Borrow<Row>) -> (Row, Row) {
728        (key.borrow().clone(), value.borrow().clone())
729    }
730
731    #[test]
732    fn test_future_get() {
733        // test if apply only future updates, whether get(future_time) can operate correctly
734        let arr = ArrangeHandler::from(Arrangement::default());
735
736        let mut arr = arr.write();
737
738        let key = lit("a");
739        let updates: Vec<KeyValDiffRow> = vec![
740            (kv(&key, lit("b")), 1 /* ts */, 1 /* diff */),
741            (kv(&key, lit("c")), 2 /* ts */, 1 /* diff */),
742            (kv(&key, lit("d")), 3 /* ts */, 1 /* diff */),
743        ];
744
745        // all updates above are future updates
746        arr.apply_updates(0, updates).unwrap();
747
748        assert_eq!(arr.get(1, &key), Some((lit("b"), 1 /* ts */, 1 /* diff */)));
749        assert_eq!(arr.get(2, &key), Some((lit("c"), 2 /* ts */, 1 /* diff */)));
750        assert_eq!(arr.get(3, &key), Some((lit("d"), 3 /* ts */, 1 /* diff */)));
751    }
752
753    #[test]
754    fn only_save_future_updates() {
755        // mfp operator's temporal filter need to record future updates so that it can delete on time
756        // i.e. insert a record now, delete this record 5 minutes later
757        // they will only need to keep future updates(if downstream don't need full arrangement that is)
758        let arr = ArrangeHandler::from(Arrangement::default());
759
760        {
761            let arr1 = arr.clone_full_arrange();
762            assert!(arr1.is_some());
763            let arr2 = arr.clone_future_only();
764            assert!(arr2.is_some());
765        }
766
767        {
768            let mut arr = arr.write();
769            let updates: Vec<KeyValDiffRow> = vec![
770                (kv(lit("a"), lit("x")), 1 /* ts */, 1 /* diff */),
771                (kv(lit("b"), lit("y")), 2 /* ts */, 1 /* diff */),
772                (kv(lit("c"), lit("z")), 3 /* ts */, 1 /* diff */),
773            ];
774            // all updates above are future updates
775            arr.apply_updates(0, updates).unwrap();
776
777            assert_eq!(
778                arr.get_updates_in_range(1..=1),
779                vec![(kv(lit("a"), lit("x")), 1 /* ts */, 1 /* diff */)]
780            );
781            assert_eq!(arr.spine.len(), 3);
782
783            arr.compact_to(1).unwrap();
784            assert_eq!(arr.spine.len(), 3);
785
786            let key = &lit("a");
787            assert_eq!(arr.get(3, key), Some((lit("x"), 1 /* ts */, 1 /* diff */)));
788            let key = &lit("b");
789            assert_eq!(arr.get(3, key), Some((lit("y"), 2 /* ts */, 1 /* diff */)));
790            let key = &lit("c");
791            assert_eq!(arr.get(3, key), Some((lit("z"), 3 /* ts */, 1 /* diff */)));
792        }
793
794        assert!(arr.clone_future_only().is_none());
795        {
796            let arr2 = arr.clone_full_arrange().unwrap();
797            let mut arr = arr2.write();
798            assert_eq!(arr.spine.len(), 3);
799
800            arr.compact_to(2).unwrap();
801            assert_eq!(arr.spine.len(), 2);
802            let key = &lit("a");
803            assert_eq!(arr.get(3, key), Some((lit("x"), 1 /* ts */, 1 /* diff */)));
804            let key = &lit("b");
805            assert_eq!(arr.get(3, key), Some((lit("y"), 2 /* ts */, 1 /* diff */)));
806            let key = &lit("c");
807            assert_eq!(arr.get(3, key), Some((lit("z"), 3 /* ts */, 1 /* diff */)));
808        }
809    }
810
811    #[test]
812    fn test_reduce_expire_keys() {
813        let mut arr = Arrangement::default();
814        let expire_state = KeyExpiryManager {
815            event_ts_to_key: Default::default(),
816            key_expiration_duration: Some(10),
817            event_timestamp_from_row: Some(ScalarExpr::Column(0)),
818        };
819        arr.expire_state = Some(expire_state);
820        arr.full_arrangement = true;
821
822        let arr = ArrangeHandler::from(arr);
823
824        let updates: Vec<KeyValDiffRow> = vec![
825            (kv(lit(1i64), lit("x")), 1 /* ts */, 1 /* diff */),
826            (kv(lit(2i64), lit("y")), 2 /* ts */, 1 /* diff */),
827            (kv(lit(3i64), lit("z")), 3 /* ts */, 1 /* diff */),
828        ];
829        {
830            let mut arr = arr.write();
831            arr.apply_updates(0, updates.clone()).unwrap();
832            // repeat the same updates means having multiple updates for the same key
833            arr.apply_updates(0, updates).unwrap();
834
835            assert_eq!(
836                arr.get_updates_in_range(1..=1),
837                vec![
838                    (kv(lit(1i64), lit("x")), 1 /* ts */, 1 /* diff */),
839                    (kv(lit(1i64), lit("x")), 1 /* ts */, 1 /* diff */)
840                ]
841            );
842            assert_eq!(arr.spine.len(), 3);
843            arr.compact_to(1).unwrap();
844            assert_eq!(arr.spine.len(), 3);
845        }
846
847        {
848            let mut arr = arr.write();
849            assert_eq!(arr.spine.len(), 3);
850
851            arr.truncate_expired_keys(11);
852            assert_eq!(arr.spine.len(), 3);
853            let key = &lit(1i64);
854            assert_eq!(arr.get(11, key), Some((lit("x"), 1 /* ts */, 2 /* diff */)));
855            let key = &lit(2i64);
856            assert_eq!(arr.get(11, key), Some((lit("y"), 2 /* ts */, 2 /* diff */)));
857            let key = &lit(3i64);
858            assert_eq!(arr.get(11, key), Some((lit("z"), 3 /* ts */, 2 /* diff */)));
859
860            arr.truncate_expired_keys(12);
861            assert_eq!(arr.spine.len(), 3);
862            let key = &lit(1i64);
863            assert_eq!(arr.get(12, key), None);
864            let key = &lit(2i64);
865            assert_eq!(arr.get(12, key), Some((lit("y"), 2 /* ts */, 2 /* diff */)));
866            let key = &lit(3i64);
867            assert_eq!(arr.get(12, key), Some((lit("z"), 3 /* ts */, 2 /* diff */)));
868            assert_eq!(arr.expire_state.as_ref().unwrap().event_ts_to_key.len(), 2);
869
870            arr.truncate_expired_keys(13);
871            assert_eq!(arr.spine.len(), 3);
872            let key = &lit(1i64);
873            assert_eq!(arr.get(13, key), None);
874            let key = &lit(2i64);
875            assert_eq!(arr.get(13, key), None);
876            let key = &lit(3i64);
877            assert_eq!(arr.get(13, key), Some((lit("z"), 3 /* ts */, 2 /* diff */)));
878            assert_eq!(arr.expire_state.as_ref().unwrap().event_ts_to_key.len(), 1);
879        }
880    }
881
882    #[test]
883    fn test_apply_expired_keys() {
884        // apply updates with a expired key
885        let mut arr = Arrangement::default();
886        let expire_state = KeyExpiryManager {
887            event_ts_to_key: Default::default(),
888            key_expiration_duration: Some(10),
889            event_timestamp_from_row: Some(ScalarExpr::Column(0)),
890        };
891        arr.expire_state = Some(expire_state);
892
893        let arr = ArrangeHandler::from(arr);
894
895        let updates: Vec<KeyValDiffRow> = vec![
896            (kv(lit(1i64), lit("x")), 1 /* ts */, 1 /* diff */),
897            (kv(lit(2i64), lit("y")), 2 /* ts */, 1 /* diff */),
898        ];
899        {
900            let mut arr = arr.write();
901            let expired_by = arr.apply_updates(12, updates).unwrap();
902            assert_eq!(expired_by, Some(1));
903
904            let key = &lit(1i64);
905            assert_eq!(arr.get(12, key), None);
906            let key = &lit(2i64);
907            assert_eq!(arr.get(12, key), Some((lit("y"), 2 /* ts */, 1 /* diff */)));
908        }
909    }
910
911    /// test if split_spine_le get ranges that are not aligned with batch boundaries
912    /// this split_spine_le can correctly retrieve all updates in the range, including updates that are in the batches
913    /// near the boundary of input range
914    #[test]
915    fn test_split_off() {
916        let mut arr = Arrangement::default();
917        // manually create batch ..=1 and 2..=3
918        arr.spine.insert(1, Batch::default());
919        arr.spine.insert(3, Batch::default());
920
921        let updates = vec![(kv(lit("a"), lit("x")), 2 /* ts */, 1 /* diff */)];
922        // updates falls into the range of 2..=3
923        arr.apply_updates(2, updates).unwrap();
924
925        let mut arr1 = arr.clone();
926        {
927            assert_eq!(arr.get_next_update_time(&1), Some(2));
928            // split expect to take batch ..=1 and create a new batch 2..=2 (which contains update)
929            let split = &arr.split_spine_le(&2);
930            assert_eq!(split.len(), 2);
931            assert_eq!(split[&2].len(), 1);
932
933            assert_eq!(arr.get_next_update_time(&1), None);
934        }
935
936        {
937            // take all updates with timestamp <=1, will get no updates
938            let split = &arr1.split_spine_le(&1);
939            assert_eq!(split.len(), 1);
940            assert_eq!(split[&1].len(), 0);
941        }
942    }
943
944    /// test if get ranges is not aligned with boundary of batch,
945    /// whether can get correct result
946    #[test]
947    fn test_get_by_range() {
948        let mut arr = Arrangement::default();
949
950        // will form {2: [2, 1], 4: [4,3], 6: [6,5]} three batch
951        // TODO(discord9): manually set batch
952        let updates: Vec<KeyValDiffRow> = vec![
953            (kv(lit("a"), lit("")), 2 /* ts */, 1 /* diff */),
954            (kv(lit("a"), lit("")), 1 /* ts */, 1 /* diff */),
955            (kv(lit("b"), lit("")), 4 /* ts */, 1 /* diff */),
956            (kv(lit("c"), lit("")), 3 /* ts */, 1 /* diff */),
957            (kv(lit("c"), lit("")), 6 /* ts */, 1 /* diff */),
958            (kv(lit("a"), lit("")), 5 /* ts */, 1 /* diff */),
959        ];
960        arr.apply_updates(0, updates).unwrap();
961        assert_eq!(
962            arr.get_updates_in_range(2..=5),
963            vec![
964                (kv(lit("a"), lit("")), 2 /* ts */, 1 /* diff */),
965                (kv(lit("b"), lit("")), 4 /* ts */, 1 /* diff */),
966                (kv(lit("c"), lit("")), 3 /* ts */, 1 /* diff */),
967                (kv(lit("a"), lit("")), 5 /* ts */, 1 /* diff */),
968            ]
969        );
970    }
971
972    /// test if get with range unaligned with batch boundary
973    /// can get correct result
974    #[test]
975    fn test_get_unaligned() {
976        let mut arr = Arrangement::default();
977
978        // will form {2: [2, 1], 4: [4,3], 6: [6,5]} three batch
979        // TODO(discord9): manually set batch
980        let key = &lit("a");
981        let updates: Vec<KeyValDiffRow> = vec![
982            (kv(key, lit(1)), 2 /* ts */, 1 /* diff */),
983            (kv(key, lit(2)), 1 /* ts */, 1 /* diff */),
984            (kv(key, lit(3)), 4 /* ts */, 1 /* diff */),
985            (kv(key, lit(4)), 3 /* ts */, 1 /* diff */),
986            (kv(key, lit(5)), 6 /* ts */, 1 /* diff */),
987            (kv(key, lit(6)), 5 /* ts */, 1 /* diff */),
988        ];
989        arr.apply_updates(0, updates).unwrap();
990        // aligned with batch boundary
991        assert_eq!(arr.get(2, key), Some((lit(1), 2 /* ts */, 1 /* diff */)));
992        // unaligned with batch boundary
993        assert_eq!(arr.get(3, key), Some((lit(4), 3 /* ts */, 1 /* diff */)));
994    }
995
996    /// test if out of order updates can be sorted correctly
997    #[test]
998    fn test_out_of_order_apply_updates() {
999        let mut arr = Arrangement::default();
1000
1001        let key = &lit("a");
1002        let updates: Vec<KeyValDiffRow> = vec![
1003            (kv(key, lit(5)), 6 /* ts */, 1 /* diff */),
1004            (kv(key, lit(2)), 2 /* ts */, -1 /* diff */),
1005            (kv(key, lit(1)), 2 /* ts */, 1 /* diff */),
1006            (kv(key, lit(2)), 1 /* ts */, 1 /* diff */),
1007            (kv(key, lit(3)), 4 /* ts */, 1 /* diff */),
1008            (kv(key, lit(4)), 3 /* ts */, 1 /* diff */),
1009            (kv(key, lit(6)), 5 /* ts */, 1 /* diff */),
1010        ];
1011        arr.apply_updates(0, updates.clone()).unwrap();
1012        let sorted = updates
1013            .iter()
1014            .sorted_by_key(|(_, ts, _)| *ts)
1015            .cloned()
1016            .collect_vec();
1017        assert_eq!(arr.get_updates_in_range(1..7), sorted);
1018    }
1019
1020    #[test]
1021    fn test_full_arrangement_get_from_first_entry() {
1022        let mut arr = Arrangement::default();
1023        // will form {3: [1, 2, 3]}
1024        let updates = vec![
1025            (kv(lit("a"), lit("x")), 3 /* ts */, 1 /* diff */),
1026            (kv(lit("b"), lit("y")), 1 /* ts */, 1 /* diff */),
1027            (kv(lit("b"), lit("y")), 2 /* ts */, -1 /* diff */),
1028        ];
1029        arr.apply_updates(0, updates).unwrap();
1030        assert_eq!(arr.get(2, &lit("b")), None /* deleted */);
1031        arr.full_arrangement = true;
1032        assert_eq!(arr.get(2, &lit("b")), None /* still deleted */);
1033
1034        arr.compact_to(1).unwrap();
1035
1036        assert_eq!(
1037            arr.get(1, &lit("b")),
1038            Some((lit("y"), 1, 1)) /* fast path */
1039        );
1040    }
1041}