Skip to main content

risingwave_stream/executor/mview/
cache.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::collections::HashSet;
16use std::ops::Deref as _;
17
18use bytes::Bytes;
19use futures::{StreamExt as _, stream};
20use itertools::Itertools as _;
21use risingwave_common::array::{Op, StreamChunk};
22use risingwave_common::catalog::{ConflictBehavior, checked_conflict_behaviors};
23use risingwave_common::row::{CompactedRow, OwnedRow, Row, RowExt as _};
24use risingwave_common::types::ScalarImpl;
25use risingwave_common::util::iter_util::ZipEqFast as _;
26use risingwave_common::util::sort_util::{OrderType, cmp_datum};
27use risingwave_common::util::value_encoding::{BasicSerde, ValueRowSerializer as _};
28use risingwave_storage::StateStore;
29use risingwave_storage::row_serde::value_serde::ValueRowSerde;
30
31use crate::cache::ManagedLruCache;
32use crate::common::metrics::MetricsInfo;
33use crate::common::table::state_table::StateTableInner;
34use crate::executor::StreamExecutorResult;
35use crate::executor::monitor::MaterializeCacheMetrics;
36use crate::task::AtomicU64Ref;
37
38/// A cache for materialize executors.
39pub struct MaterializeCache {
40    lru_cache: ManagedLruCache<Vec<u8>, CacheValue>,
41    row_serde: BasicSerde,
42    version_column_indices: Vec<u32>,
43    conflict_behavior: ConflictBehavior,
44    placeholder_column_indices: Option<Vec<usize>>,
45    metrics: MaterializeCacheMetrics,
46}
47
48type CacheValue = Option<CompactedRow>;
49type ChangeBuffer = crate::common::change_buffer::ChangeBuffer<Vec<u8>, OwnedRow>;
50
51/// Check whether the given row is below the latest watermark of the table. If so, we may want to
52/// treat them as non-existent. This extra step is necessary for TTL-ed tables because:
53///
54/// - the storage may clean expired rows asynchronously
55/// - an expired row may still be in the cache while we expect a consistent view
56///
57/// The watermark is forwarded downstream once it is fed into the table, so the rows below it are
58/// expired before the commit.
59fn row_below_watermark<S: StateStore, SD: ValueRowSerde>(
60    row_serde: &BasicSerde,
61    table: &StateTableInner<S, SD>,
62    row: &CompactedRow,
63) -> StreamExecutorResult<bool> {
64    let Some(clean_watermark_index) = table.clean_watermark_index else {
65        return Ok(false);
66    };
67    let Some(watermark) = table
68        .get_pending_watermark()
69        .or(table.get_committed_watermark())
70    else {
71        return Ok(false);
72    };
73    let deserialized = row_serde.deserializer.deserialize(row.row.clone())?;
74    Ok(cmp_datum(
75        deserialized.datum_at(clean_watermark_index),
76        Some(watermark.as_scalar_ref_impl()),
77        OrderType::ascending(),
78    ) == std::cmp::Ordering::Less)
79}
80
81impl MaterializeCache {
82    /// Create a new `MaterializeCache`.
83    ///
84    /// Returns `None` if the conflict behavior is `NoCheck`.
85    pub fn new(
86        watermark_sequence: AtomicU64Ref,
87        metrics_info: MetricsInfo,
88        row_serde: BasicSerde,
89        version_column_indices: Vec<u32>,
90        conflict_behavior: ConflictBehavior,
91        placeholder_column_indices: Option<Vec<usize>>,
92        materialize_cache_metrics: MaterializeCacheMetrics,
93    ) -> Option<Self> {
94        match conflict_behavior {
95            checked_conflict_behaviors!() => {}
96            ConflictBehavior::NoCheck => {
97                assert!(
98                    placeholder_column_indices.is_none(),
99                    "when there are placeholder columns, conflict handling must be enabled"
100                );
101                return None;
102            }
103        }
104
105        let lru_cache: ManagedLruCache<Vec<u8>, CacheValue> =
106            ManagedLruCache::unbounded(watermark_sequence, metrics_info);
107        Some(Self {
108            lru_cache,
109            row_serde,
110            version_column_indices,
111            conflict_behavior,
112            placeholder_column_indices,
113            metrics: materialize_cache_metrics,
114        })
115    }
116
117    /// First populate the cache from `table`, and then calculate a [`ChangeBuffer`].
118    /// `table` will not be written in this method.
119    pub async fn handle_new<S: StateStore, SD: ValueRowSerde>(
120        &mut self,
121        chunk: StreamChunk,
122        table: &StateTableInner<S, SD>,
123    ) -> StreamExecutorResult<ChangeBuffer> {
124        if table.value_indices().is_some() {
125            // TODO(st1page): when materialize partial columns(), we should
126            // construct some columns in the pk
127            unimplemented!("materialize cache cannot handle conflicts with partial table values");
128        };
129
130        let (data_chunk, ops) = chunk.clone().into_parts();
131        let values = data_chunk.serialize();
132
133        let key_chunk = data_chunk.project(table.pk_indices());
134
135        let pks = {
136            let mut pks = vec![vec![]; data_chunk.capacity()];
137            key_chunk
138                .rows_with_holes()
139                .zip_eq_fast(pks.iter_mut())
140                .for_each(|(r, vnode_and_pk)| {
141                    if let Some(r) = r {
142                        table.pk_serde().serialize(r, vnode_and_pk);
143                    }
144                });
145            pks
146        };
147        let (_, vis) = key_chunk.into_parts();
148        let row_ops = ops
149            .iter()
150            .zip_eq_fast(pks.into_iter())
151            .zip_eq_fast(values.into_iter())
152            .zip_eq_fast(vis.iter())
153            .filter_map(|(((op, k), v), vis)| vis.then_some((*op, k, v)))
154            .collect_vec();
155
156        self.handle_inner(row_ops, table).await
157    }
158
159    async fn handle_inner<S: StateStore, SD: ValueRowSerde>(
160        &mut self,
161        row_ops: Vec<(Op, Vec<u8>, Bytes)>,
162        table: &StateTableInner<S, SD>,
163    ) -> StreamExecutorResult<ChangeBuffer> {
164        let key_set: HashSet<Box<[u8]>> = row_ops
165            .iter()
166            .map(|(_, k, _)| k.as_slice().into())
167            .collect();
168
169        // Populate the LRU cache with the keys in input chunk.
170        // For new keys, row values are set to None.
171        self.fetch_keys(key_set.iter().map(|v| v.deref()), table)
172            .await?;
173
174        let mut change_buffer = ChangeBuffer::new();
175        let row_serde = self.row_serde.clone();
176        let version_column_indices = self.version_column_indices.clone();
177        for (op, key, row) in row_ops {
178            // Use a macro instead of method to workaround partial borrow.
179            macro_rules! get_expected {
180                () => {
181                    self.lru_cache.get(&key).unwrap_or_else(|| {
182                        panic!(
183                            "the key {:?} has not been fetched in the materialize executor's cache",
184                            key
185                        )
186                    })
187                };
188            }
189
190            match op {
191                Op::Insert | Op::UpdateInsert => {
192                    let Some(old_row) = get_expected!() else {
193                        // not exists before, meaning no conflict, simply insert
194                        let new_row_deserialized =
195                            row_serde.deserializer.deserialize(row.clone())?;
196                        change_buffer.insert(key.clone(), new_row_deserialized);
197                        self.lru_cache.put(key, Some(CompactedRow { row }));
198                        continue;
199                    };
200
201                    // now conflict happens, handle it according to the specified behavior
202                    match self.conflict_behavior {
203                        ConflictBehavior::Overwrite => {
204                            let old_row_deserialized =
205                                row_serde.deserializer.deserialize(old_row.row.clone())?;
206                            let new_row_deserialized =
207                                row_serde.deserializer.deserialize(row.clone())?;
208
209                            let need_overwrite = if !version_column_indices.is_empty() {
210                                versions_are_newer_or_equal(
211                                    &old_row_deserialized,
212                                    &new_row_deserialized,
213                                    &version_column_indices,
214                                )
215                            } else {
216                                // no version column specified, just overwrite
217                                true
218                            };
219
220                            if need_overwrite {
221                                if let Some(placeholder_column_indices) =
222                                    &self.placeholder_column_indices
223                                {
224                                    // Replace Debezium's placeholder with old row values.
225                                    let final_row = placeholder::restore_placeholder_columns(
226                                        &old_row_deserialized,
227                                        &new_row_deserialized,
228                                        placeholder_column_indices,
229                                    );
230
231                                    change_buffer.update(
232                                        key.clone(),
233                                        old_row_deserialized,
234                                        final_row.clone(),
235                                    );
236                                    let final_row_bytes =
237                                        Bytes::from(row_serde.serializer.serialize(final_row));
238                                    self.lru_cache.put(
239                                        key.clone(),
240                                        Some(CompactedRow {
241                                            row: final_row_bytes,
242                                        }),
243                                    );
244                                } else {
245                                    // No placeholder columns, use the original row bytes directly to avoid unnecessary serialization
246                                    change_buffer.update(
247                                        key.clone(),
248                                        old_row_deserialized,
249                                        new_row_deserialized,
250                                    );
251                                    self.lru_cache
252                                        .put(key.clone(), Some(CompactedRow { row: row.clone() }));
253                                }
254                            };
255                        }
256                        ConflictBehavior::IgnoreConflict => {
257                            // ignore conflict, do nothing
258                        }
259                        ConflictBehavior::DoUpdateIfNotNull => {
260                            // In this section, we compare the new row and old row column by column and perform `DoUpdateIfNotNull` replacement.
261
262                            let old_row_deserialized =
263                                row_serde.deserializer.deserialize(old_row.row.clone())?;
264                            let new_row_deserialized =
265                                row_serde.deserializer.deserialize(row.clone())?;
266                            let need_overwrite = if !version_column_indices.is_empty() {
267                                versions_are_newer_or_equal(
268                                    &old_row_deserialized,
269                                    &new_row_deserialized,
270                                    &version_column_indices,
271                                )
272                            } else {
273                                true
274                            };
275
276                            if need_overwrite {
277                                let mut row_deserialized_vec =
278                                    old_row_deserialized.clone().into_inner().into_vec();
279                                replace_if_not_null(
280                                    &mut row_deserialized_vec,
281                                    new_row_deserialized.clone(),
282                                );
283                                let mut updated_row = OwnedRow::new(row_deserialized_vec);
284
285                                // Replace Debezium's placeholder with old row values.
286                                if let Some(placeholder_column_indices) =
287                                    &self.placeholder_column_indices
288                                {
289                                    // Note: we need to use old_row_deserialized again, but it was moved above
290                                    // So we re-deserialize the old row
291                                    let old_row_deserialized_again =
292                                        row_serde.deserializer.deserialize(old_row.row.clone())?;
293                                    updated_row = placeholder::restore_placeholder_columns(
294                                        &old_row_deserialized_again,
295                                        &updated_row,
296                                        placeholder_column_indices,
297                                    );
298                                }
299
300                                change_buffer.update(
301                                    key.clone(),
302                                    old_row_deserialized,
303                                    updated_row.clone(),
304                                );
305                                let updated_row_bytes =
306                                    Bytes::from(row_serde.serializer.serialize(updated_row));
307                                self.lru_cache.put(
308                                    key.clone(),
309                                    Some(CompactedRow {
310                                        row: updated_row_bytes,
311                                    }),
312                                );
313                            }
314                        }
315                        ConflictBehavior::NoCheck => unreachable!(),
316                    };
317                }
318
319                Op::UpdateDelete
320                    if matches!(
321                        self.conflict_behavior,
322                        ConflictBehavior::Overwrite | ConflictBehavior::DoUpdateIfNotNull
323                    ) =>
324                {
325                    // For `UpdateDelete`s, we skip processing them but directly handle the following `UpdateInsert`
326                    // instead. This is because...
327                    //
328                    // - For `Overwrite`, we only care about the new row.
329                    // - For `DoUpdateIfNotNull`, we don't want the whole row to be deleted, but instead perform
330                    //   column-wise replacement when handling the `UpdateInsert`.
331                    //
332                    // However, for `IgnoreConflict`, we still need to delete the old row first, otherwise the row
333                    // cannot be updated at all.
334                }
335
336                Op::Delete | Op::UpdateDelete => {
337                    if let Some(old_row) = get_expected!() {
338                        let old_row_deserialized =
339                            row_serde.deserializer.deserialize(old_row.row.clone())?;
340                        change_buffer.delete(key.clone(), old_row_deserialized);
341                        // put a None into the cache to represent deletion
342                        self.lru_cache.put(key, None);
343                    } else {
344                        // delete a non-existent value
345                        // this is allowed in the case of mview conflict, so ignore
346                    }
347                }
348            }
349        }
350        Ok(change_buffer)
351    }
352
353    async fn fetch_keys<'a, S: StateStore, SD: ValueRowSerde>(
354        &mut self,
355        keys: impl Iterator<Item = &'a [u8]>,
356        table: &StateTableInner<S, SD>,
357    ) -> StreamExecutorResult<()> {
358        let mut futures = vec![];
359        for key in keys {
360            self.metrics.materialize_cache_total_count.inc();
361
362            if let Some(cached) = self.lru_cache.get(key) {
363                self.metrics.materialize_cache_hit_count.inc();
364                if let Some(row) = cached {
365                    if row_below_watermark(&self.row_serde, table, row)? {
366                        self.lru_cache.put(key.to_vec(), None);
367                    } else {
368                        self.metrics.materialize_data_exist_count.inc();
369                    }
370                }
371                continue;
372            }
373
374            let row_serde = self.row_serde.clone();
375            futures.push(async move {
376                let key_row = table.pk_serde().deserialize(key).unwrap();
377                let row = table.get_row(key_row).await?.map(CompactedRow::from);
378                let row = match row {
379                    Some(row) if row_below_watermark(&row_serde, table, &row)? => None,
380                    other => other,
381                };
382                StreamExecutorResult::Ok((key.to_vec(), row))
383            });
384        }
385
386        let mut buffered = stream::iter(futures).buffer_unordered(10).fuse();
387        while let Some(result) = buffered.next().await {
388            let (key, row) = result?;
389            if row.is_some() {
390                self.metrics.materialize_data_exist_count.inc();
391            }
392            // for keys that are not in the table, `value` is None
393            match self.conflict_behavior {
394                checked_conflict_behaviors!() => self.lru_cache.put(key, row),
395                _ => unreachable!(),
396            };
397        }
398
399        Ok(())
400    }
401
402    /// Drop the entries of rows deleted from `table` without going through [`Self::handle_new`].
403    /// Entries are removed instead of set to `None` so mass deletes leave no tombstones behind.
404    pub fn invalidate_rows<S: StateStore, SD: ValueRowSerde>(
405        &mut self,
406        rows: impl IntoIterator<Item = impl Row>,
407        table: &StateTableInner<S, SD>,
408    ) {
409        for row in rows {
410            let key = row
411                .project(table.pk_indices())
412                .memcmp_serialize(table.pk_serde());
413            self.lru_cache.remove(&key);
414        }
415    }
416
417    /// Write the rows of a chunk applied to `table` without going through [`Self::handle_new`].
418    pub fn write_through<S: StateStore, SD: ValueRowSerde>(
419        &mut self,
420        chunk: &StreamChunk,
421        table: &StateTableInner<S, SD>,
422    ) {
423        for (op, row) in chunk.rows() {
424            let key = row
425                .project(table.pk_indices())
426                .memcmp_serialize(table.pk_serde());
427            let value = match op {
428                Op::Insert | Op::UpdateInsert => Some(CompactedRow {
429                    row: Bytes::from(self.row_serde.serializer.serialize(row)),
430                }),
431                Op::Delete | Op::UpdateDelete => None,
432            };
433            self.lru_cache.put(key, value);
434        }
435    }
436
437    /// Evict the LRU cache entries that are lower than the watermark.
438    pub fn evict(&mut self) {
439        self.lru_cache.evict()
440    }
441
442    /// Clear the LRU cache.
443    pub fn clear(&mut self) {
444        self.lru_cache.clear()
445    }
446}
447
448/// Replace columns in an existing row with the corresponding columns in a replacement row, if the
449/// column value in the replacement row is not null.
450///
451/// # Example
452///
453/// ```ignore
454/// let mut row = vec![Some(1), None, Some(3)];
455/// let replacement = vec![Some(10), Some(20), None];
456/// replace_if_not_null(&mut row, replacement);
457/// ```
458///
459/// After the call, `row` will be `[Some(10), Some(20), Some(3)]`.
460fn replace_if_not_null(row: &mut Vec<Option<ScalarImpl>>, replacement: OwnedRow) {
461    for (old_col, new_col) in row.iter_mut().zip_eq_fast(replacement) {
462        if let Some(new_value) = new_col {
463            *old_col = Some(new_value);
464        }
465    }
466}
467
468/// Compare multiple version columns lexicographically.
469/// Returns true if `new_row` has a newer or equal version compared to `old_row`.
470fn versions_are_newer_or_equal(
471    old_row: &OwnedRow,
472    new_row: &OwnedRow,
473    version_column_indices: &[u32],
474) -> bool {
475    if version_column_indices.is_empty() {
476        // No version columns specified, always consider new version as newer
477        return true;
478    }
479
480    for &idx in version_column_indices {
481        let old_value = old_row.datum_at(idx as usize);
482        let new_value = new_row.datum_at(idx as usize);
483
484        match cmp_datum(old_value, new_value, OrderType::ascending_nulls_first()) {
485            std::cmp::Ordering::Less => return true,     // new is newer
486            std::cmp::Ordering::Greater => return false, // old is newer
487            std::cmp::Ordering::Equal => continue,       // equal, check next column
488        }
489    }
490
491    // All version columns are equal, consider new version as equal (should overwrite)
492    true
493}
494
495/// Handling of Debezium's placeholder for column values that an UPDATE left unchanged and the
496/// upstream did not log, such as PostgreSQL TOAST values and Oracle LOB, XML and extended string
497/// values.
498pub(super) mod placeholder {
499    use risingwave_common::types::{DEBEZIUM_UNAVAILABLE_VALUE, DEBEZIUM_UNAVAILABLE_VECTOR_ELEM};
500
501    use super::*;
502
503    /// Fast string comparison to check if a string equals `DEBEZIUM_UNAVAILABLE_VALUE`.
504    /// Optimized by checking length first to avoid expensive string comparison.
505    fn is_placeholder_str(s: &str) -> bool {
506        s.len() == DEBEZIUM_UNAVAILABLE_VALUE.len() && s == DEBEZIUM_UNAVAILABLE_VALUE
507    }
508
509    /// Check if a datum represents Debezium's placeholder.
510    /// This function handles both scalar types and one-dimensional arrays.
511    fn is_debezium_placeholder(
512        datum: &Option<risingwave_common::types::ScalarRefImpl<'_>>,
513    ) -> bool {
514        match datum {
515            Some(risingwave_common::types::ScalarRefImpl::Utf8(val)) => is_placeholder_str(val),
516            Some(risingwave_common::types::ScalarRefImpl::Jsonb(jsonb_ref)) => {
517                // For jsonb type, check if it's a string containing the placeholder
518                jsonb_ref.as_str().map(is_placeholder_str).unwrap_or(false)
519            }
520            Some(risingwave_common::types::ScalarRefImpl::Bytea(bytea)) => {
521                // For bytea type, we need to check if it contains the string bytes of DEBEZIUM_UNAVAILABLE_VALUE
522                // This is because when processing bytea from Debezium, we convert the base64-encoded string
523                // to `DEBEZIUM_UNAVAILABLE_VALUE` in the json.rs parser to maintain consistency
524                if let Ok(bytea_str) = std::str::from_utf8(bytea) {
525                    is_placeholder_str(bytea_str)
526                } else {
527                    false
528                }
529            }
530            Some(risingwave_common::types::ScalarRefImpl::Vector(vec_ref)) => {
531                // pgvector unchanged-TOAST sentinel: the JSON parser materialises an N-d
532                // vector whose every element equals `DEBEZIUM_UNAVAILABLE_VECTOR_ELEM`
533                // (currently `f32::MAX`). N matches the column's declared dimension so the
534                // value survives `check_datum_type` on its way in; the chance of a real
535                // embedding having every element simultaneously equal to that value is
536                // effectively zero.
537                let slice = vec_ref.as_slice();
538                !slice.is_empty()
539                    && slice
540                        .iter()
541                        .all(|f| f.0 == DEBEZIUM_UNAVAILABLE_VECTOR_ELEM)
542            }
543            // For list type, check if it contains exactly one element with the placeholder.
544            // This is because when any element in an array triggers TOAST, Debezium treats the
545            // entire array as unchanged and sends a placeholder array with only one element.
546            Some(risingwave_common::types::ScalarRefImpl::List(list_ref))
547                if list_ref.len() == 1 =>
548            {
549                if let Some(Some(element)) = list_ref.get(0) {
550                    // Recursively check the array element
551                    is_debezium_placeholder(&Some(element))
552                } else {
553                    false
554                }
555            }
556            _ => false,
557        }
558    }
559
560    /// Whether any row in the chunk carries Debezium's placeholder in one of the given columns.
561    pub fn chunk_has_placeholder(
562        chunk: &StreamChunk,
563        placeholder_column_indices: &[usize],
564    ) -> bool {
565        chunk.rows().any(|(_, row)| {
566            placeholder_column_indices
567                .iter()
568                .any(|&idx| is_debezium_placeholder(&row.datum_at(idx)))
569        })
570    }
571
572    /// Replace Debezium's placeholder in the given columns of `new_row` with the values from
573    /// `old_row`.
574    pub fn restore_placeholder_columns(
575        old_row: &OwnedRow,
576        new_row: &OwnedRow,
577        placeholder_column_indices: &[usize],
578    ) -> OwnedRow {
579        let mut fixed_row_data = new_row.as_inner().to_vec();
580
581        for &placeholder_column_idx in placeholder_column_indices {
582            // Check if the new value is Debezium's placeholder
583            let is_placeholder = is_debezium_placeholder(&new_row.datum_at(placeholder_column_idx));
584            if is_placeholder {
585                fixed_row_data[placeholder_column_idx] = old_row
586                    .datum_at(placeholder_column_idx)
587                    .map(|old_datum_ref| old_datum_ref.into_scalar_impl());
588            }
589        }
590
591        OwnedRow::new(fixed_row_data)
592    }
593}