Skip to main content

risingwave_stream/common/
change_buffer.rs

1// Copyright 2025 RisingWave Labs
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
15use std::sync::LazyLock;
16
17use risingwave_common::array::stream_record::Record;
18use risingwave_common::array::{Op, StreamChunk, StreamChunkBuilder};
19use risingwave_common::log::LogSuppressor;
20use risingwave_common::row::{Row, RowExt as _};
21use risingwave_common::types::DataType;
22
23use crate::consistency::consistency_panic;
24
25mod insertion_ordered_map;
26use insertion_ordered_map::{Entry, InsertionOrderedMap};
27
28/// Behavior when inconsistency is detected when aggregating changes to [`ChangeBuffer`].
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum InconsistencyBehavior {
31    Panic,
32    Warn,
33    Tolerate,
34}
35
36impl InconsistencyBehavior {
37    /// Report an inconsistency.
38    #[track_caller]
39    pub fn report(self, msg: &str) {
40        match self {
41            InconsistencyBehavior::Panic => consistency_panic!("{}", msg),
42            InconsistencyBehavior::Warn => {
43                static LOG_SUPPRESSOR: LazyLock<LogSuppressor> =
44                    LazyLock::new(LogSuppressor::default);
45
46                if let Ok(suppressed_count) = LOG_SUPPRESSOR.check() {
47                    tracing::warn!(suppressed_count, "{}", msg);
48                }
49            }
50            InconsistencyBehavior::Tolerate => {}
51        }
52    }
53}
54
55mod private {
56    pub trait Key: Eq + std::hash::Hash {}
57    impl<K> Key for K where K: Eq + std::hash::Hash {}
58
59    pub trait Row: Eq {}
60    impl<R> Row for R where R: Eq {}
61}
62
63/// The accumulated change of a key, with each side in an [`Option`] so that state
64/// transitions can take one side out in place. `(None, None)` entries are removed eagerly.
65#[derive(Debug)]
66struct Slot<R> {
67    old: Option<R>,
68    new: Option<R>,
69}
70
71/// A buffer that accumulates changes and produce compacted changes.
72#[derive(Debug)]
73pub struct ChangeBuffer<K, R> {
74    // `InsertionOrderedMap` preserves the original order of the changes as much as possible.
75    buffer: InsertionOrderedMap<K, Slot<R>>,
76    ib: InconsistencyBehavior,
77}
78
79impl<K, R> ChangeBuffer<K, R>
80where
81    K: private::Key,
82    R: private::Row,
83{
84    /// Apply an insertion of a row with the given key.
85    pub fn insert(&mut self, key: K, new_row: R) {
86        let entry = self.buffer.entry(key);
87        match entry {
88            Entry::Vacant(e) => {
89                e.insert(Slot {
90                    old: None,
91                    new: Some(new_row),
92                });
93            }
94            Entry::Occupied(mut e) => {
95                let slot = e.get_mut();
96                if slot.new.is_some() {
97                    self.ib.report("inconsistent changes: double-inserting");
98                }
99                slot.new = Some(new_row);
100            }
101        }
102    }
103
104    /// Apply a deletion of a row with the given key.
105    pub fn delete(&mut self, key: K, old_row: R) {
106        let entry = self.buffer.entry(key);
107        match entry {
108            Entry::Vacant(e) => {
109                e.insert(Slot {
110                    old: Some(old_row),
111                    new: None,
112                });
113            }
114            Entry::Occupied(mut e) => {
115                let slot = e.get_mut();
116                if slot.new.take().is_some() {
117                    if slot.old.is_none() {
118                        // The previous `Insert` is fully cancelled by this deletion.
119                        e.remove();
120                    }
121                } else {
122                    self.ib.report("inconsistent changes: double-deleting");
123                    slot.old = Some(old_row);
124                }
125            }
126        }
127    }
128
129    /// Apply an update of a row with the given key.
130    pub fn update(&mut self, key: K, old_row: R, new_row: R) {
131        let entry = self.buffer.entry(key);
132        match entry {
133            Entry::Vacant(e) => {
134                e.insert(Slot {
135                    old: Some(old_row),
136                    new: Some(new_row),
137                });
138            }
139            Entry::Occupied(mut e) => {
140                let slot = e.get_mut();
141                if slot.new.is_some() {
142                    slot.new = Some(new_row);
143                } else {
144                    self.ib.report("inconsistent changes: update after delete");
145                    slot.old = Some(old_row);
146                    slot.new = Some(new_row);
147                }
148            }
149        }
150    }
151
152    /// Apply a change record, with the key extracted by the given function.
153    ///
154    /// For `Record::Update`, inconsistency is reported if the old key and the new key are different.
155    /// Further behavior is determined by the `InconsistencyBehavior`.
156    pub fn apply_record(&mut self, record: Record<R>, key_fn: impl Fn(&R) -> K) {
157        match record {
158            Record::Insert { new_row } => self.insert(key_fn(&new_row), new_row),
159            Record::Delete { old_row } => self.delete(key_fn(&old_row), old_row),
160            Record::Update { old_row, new_row } => {
161                let old_key = key_fn(&old_row);
162                let new_key = key_fn(&new_row);
163
164                // As long as `ib` is not `Panic`, we still gracefully handle the mismatched key.
165                if old_key != new_key {
166                    self.ib
167                        .report("inconsistent changes: mismatched key in update");
168                    self.delete(old_key, old_row);
169                    self.insert(new_key, new_row);
170                } else {
171                    self.update(old_key, old_row, new_row);
172                }
173            }
174        }
175    }
176
177    /// Apply an `Op` of a row with the given key.
178    pub fn apply_op_row(&mut self, op: Op, key: K, row: R) {
179        match op {
180            Op::Insert | Op::UpdateInsert => self.insert(key, row),
181            Op::Delete | Op::UpdateDelete => self.delete(key, row),
182        }
183    }
184
185    /// Apply an operation from an upsert stream, retaining only the final operation per key.
186    /// Unlike retract input, an insertion can overwrite a row from an earlier batch, so a
187    /// subsequent deletion must retain its tombstone even if no earlier deletion was buffered.
188    pub fn apply_upsert_op_row(&mut self, op: Op, key: K, row: R) {
189        let slot = match op {
190            Op::Insert | Op::UpdateInsert => Slot {
191                old: None,
192                new: Some(row),
193            },
194            Op::Delete | Op::UpdateDelete => Slot {
195                old: Some(row),
196                new: None,
197            },
198        };
199        self.buffer.insert(key, slot);
200    }
201
202    /// Consume the buffer and produce a list of change records.
203    ///
204    /// No-op updates are filtered out.
205    pub fn into_records(self) -> impl Iterator<Item = Record<R>> {
206        self.buffer
207            .into_values()
208            .filter_map(|slot| match (slot.old, slot.new) {
209                (None, Some(new_row)) => Some(Record::Insert { new_row }),
210                (Some(old_row), None) => Some(Record::Delete { old_row }),
211                (Some(old_row), Some(new_row)) => {
212                    (old_row != new_row).then(|| Record::Update { old_row, new_row })
213                }
214                (None, None) => unreachable!("empty slot should have been removed"),
215            })
216    }
217}
218
219impl<K, R> Default for ChangeBuffer<K, R> {
220    fn default() -> Self {
221        Self::new()
222    }
223}
224
225impl<K, R> ChangeBuffer<K, R> {
226    /// Create a new `ChangeBuffer` that panics on inconsistency.
227    pub fn new() -> Self {
228        Self::with_capacity(0)
229    }
230
231    /// Create a new `ChangeBuffer` with the given capacity that panics on inconsistency.
232    pub fn with_capacity(capacity: usize) -> Self {
233        Self {
234            buffer: InsertionOrderedMap::with_capacity(capacity),
235            ib: InconsistencyBehavior::Panic,
236        }
237    }
238
239    /// Set the inconsistency behavior.
240    pub fn with_inconsistency_behavior(mut self, ib: InconsistencyBehavior) -> Self {
241        self.ib = ib;
242        self
243    }
244
245    /// Get the number of keys that have pending changes in the buffer.
246    pub fn len(&self) -> usize {
247        self.buffer.len()
248    }
249
250    /// Check if the buffer is empty.
251    pub fn is_empty(&self) -> bool {
252        self.buffer.is_empty()
253    }
254}
255
256/// The kind of output for [`ChangeBuffer::into_chunk`] and [`ChangeBuffer::into_chunks`].
257/// Can be [`UPSERT`] or [`RETRACT`].
258pub type OutputKind = bool;
259pub mod output_kind {
260    use super::OutputKind;
261    /// For updates, only keep the new row with `Insert` operation.
262    ///
263    /// The output chunk can only be used in streams with `StreamKind::Upsert`. Refer to it for
264    /// more details.
265    pub const UPSERT: OutputKind = true;
266    /// For updates, keep both the old and new row with `UpdateDelete` and `UpdateInsert` operation.
267    pub const RETRACT: OutputKind = false;
268}
269use output_kind::*;
270
271impl<K, R> ChangeBuffer<K, R>
272where
273    K: private::Key,
274    R: private::Row + Row,
275{
276    /// Consume the buffer and produce a single compacted chunk.
277    pub fn into_chunk<const KIND: OutputKind>(
278        self,
279        data_types: Vec<DataType>,
280    ) -> Option<StreamChunk> {
281        let mut builder = StreamChunkBuilder::unlimited(data_types, Some(self.buffer.len()));
282        for record in self.into_records() {
283            let record = match KIND {
284                UPSERT => record.into_upsert(),
285                RETRACT => record,
286            };
287            let none = builder.append_record(record);
288            debug_assert!(none.is_none());
289        }
290        builder.take()
291    }
292
293    /// Consume the buffer and produce a single compacted chunk, with the given new key indices.
294    ///
295    /// The key must be a superset of the old key to ensure uniqueness. Otherwise, changes to the
296    /// same key might be written multiple times so that the correct ordering of the operations cannot
297    /// be guaranteed.
298    pub fn into_chunk_with_key(
299        self,
300        data_types: Vec<DataType>,
301        key_indices: &[usize],
302    ) -> Option<StreamChunk> {
303        let mut builder = StreamChunkBuilder::unlimited(data_types, Some(self.buffer.len()));
304        for record in self.into_records() {
305            macro_rules! append_record {
306                ($record:expr) => {
307                    let none = builder.append_record($record);
308                    debug_assert!(none.is_none());
309                };
310            }
311
312            if let Record::Update { old_row, new_row } = &record
313                && !Row::eq(&old_row.project(key_indices), new_row.project(key_indices))
314            {
315                append_record!(Record::Delete { old_row });
316                append_record!(Record::Insert { new_row });
317            } else {
318                append_record!(record);
319            }
320        }
321        builder.take()
322    }
323
324    /// Consume the buffer and produce a list of compacted chunks with the given size at most.
325    pub fn into_chunks<const KIND: OutputKind>(
326        self,
327        data_types: Vec<DataType>,
328        chunk_size: usize,
329    ) -> Vec<StreamChunk> {
330        let mut res = Vec::new();
331        let mut builder = StreamChunkBuilder::new(chunk_size, data_types);
332        for record in self.into_records() {
333            let record = match KIND {
334                UPSERT => record.into_upsert(),
335                RETRACT => record,
336            };
337            if let Some(chunk) = builder.append_record(record) {
338                res.push(chunk);
339            }
340        }
341        res.extend(builder.take());
342        res
343    }
344}