Skip to main content

risingwave_stream/executor/source/batch_source/
batch_adbc_snowflake_fetch.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::VecDeque;
16
17use arrow::RecordBatch;
18use either::Either;
19use futures::stream;
20use itertools::Itertools;
21use parking_lot::RwLock;
22use risingwave_common::array::Op;
23use risingwave_common::array::arrow::{arrow_array_58 as arrow, from_arrow58_record_batch};
24use risingwave_common::id::TableId;
25use risingwave_common::types::{JsonbVal, Scalar, ScalarRef};
26use risingwave_connector::source::ConnectorProperties;
27use risingwave_connector::source::adbc_snowflake::AdbcSnowflakeProperties;
28use risingwave_connector::source::reader::desc::SourceDesc;
29use thiserror_ext::AsReport;
30
31use super::batch_adbc_snowflake_list::AdbcSnowflakeSplit;
32use crate::executor::prelude::*;
33use crate::executor::source::StreamSourceCore;
34use crate::executor::stream_reader::StreamReaderWithPause;
35use crate::task::LocalBarrierManager;
36
37pub struct BatchAdbcSnowflakeFetchExecutor<S: StateStore> {
38    actor_ctx: ActorContextRef,
39
40    /// Core component for managing external streaming source state
41    stream_source_core: Option<StreamSourceCore<S>>,
42
43    /// Upstream list executor that provides the splits to read.
44    upstream: Option<Executor>,
45
46    // barrier manager for reporting load finished
47    barrier_manager: LocalBarrierManager,
48
49    associated_table_id: TableId,
50}
51
52impl<S: StateStore> BatchAdbcSnowflakeFetchExecutor<S> {
53    pub fn new(
54        actor_ctx: ActorContextRef,
55        stream_source_core: StreamSourceCore<S>,
56        upstream: Executor,
57        barrier_manager: LocalBarrierManager,
58        associated_table_id: Option<TableId>,
59    ) -> Self {
60        assert!(associated_table_id.is_some());
61        Self {
62            actor_ctx,
63            stream_source_core: Some(stream_source_core),
64            upstream: Some(upstream),
65            barrier_manager,
66            associated_table_id: associated_table_id.unwrap(),
67        }
68    }
69}
70
71impl<S: StateStore> BatchAdbcSnowflakeFetchExecutor<S> {
72    #[try_stream(ok = Message, error = StreamExecutorError)]
73    async fn into_stream(mut self) {
74        let mut upstream = self.upstream.take().unwrap().execute();
75        let barrier = expect_first_barrier(&mut upstream).await?;
76        yield Message::Barrier(barrier);
77
78        let mut is_refreshing = false;
79        let mut is_list_finished = false;
80        let mut splits_on_fetch: usize = 0;
81        let is_load_finished = Arc::new(RwLock::new(false));
82        let mut split_queue = VecDeque::new();
83
84        let mut core = self.stream_source_core.take().unwrap();
85        let source_desc_builder = core.source_desc_builder.take().unwrap();
86        let source_desc = source_desc_builder
87            .build()
88            .map_err(StreamExecutorError::connector_error)?;
89
90        // Get column names from the source schema, filtering out additional columns and hidden columns.
91        // These columns are derived from the fetch executor's schema and represent the actual
92        // Snowflake table columns that should be queried.
93        let column_names: Vec<String> = source_desc
94            .columns
95            .iter()
96            .filter(|c| c.is_visible() && c.additional_column.column_type.is_none())
97            .map(|c| c.name.clone())
98            .collect();
99        tracing::debug!("[adbc snowflake fetch] column_names: {:?}", column_names);
100
101        let mut stream =
102            StreamReaderWithPause::<true, StreamChunk>::new(upstream, stream::pending().boxed());
103
104        while let Some(msg) = stream.next().await {
105            match msg {
106                Err(e) => {
107                    tracing::error!(error = %e.as_report(), "Fetch Error");
108                    split_queue.clear();
109                    *is_load_finished.write() = false;
110                    return Err(e);
111                }
112                Ok(msg) => match msg {
113                    Either::Left(msg) => match msg {
114                        Message::Barrier(barrier) => {
115                            let mut need_rebuild_reader = false;
116                            if let Some(mutation) = barrier.mutation.as_deref() {
117                                match mutation {
118                                    Mutation::Pause => stream.pause_stream(),
119                                    Mutation::Resume => stream.resume_stream(),
120                                    Mutation::RefreshStart {
121                                        associated_source_id,
122                                        ..
123                                    } if associated_source_id == &core.source_id => {
124                                        tracing::info!(
125                                            ?barrier.epoch,
126                                            actor_id = %self.actor_ctx.id,
127                                            source_id = %core.source_id,
128                                            table_id = %self.associated_table_id,
129                                            "RefreshStart:"
130                                        );
131
132                                        // reset states and abort current workload
133                                        split_queue.clear();
134                                        splits_on_fetch = 0;
135                                        is_refreshing = true;
136                                        is_list_finished = false;
137                                        *is_load_finished.write() = false;
138
139                                        need_rebuild_reader = true;
140                                    }
141                                    Mutation::ListFinish {
142                                        associated_source_id,
143                                    } if associated_source_id == &core.source_id => {
144                                        tracing::info!(
145                                            ?barrier.epoch,
146                                            actor_id = %self.actor_ctx.id,
147                                            source_id = %core.source_id,
148                                            table_id = %self.associated_table_id,
149                                            "ListFinish:"
150                                        );
151                                        is_list_finished = true;
152                                    }
153                                    _ => {
154                                        // ignore other mutations
155                                    }
156                                }
157                            }
158
159                            if splits_on_fetch == 0
160                                && split_queue.is_empty()
161                                && is_list_finished
162                                && is_refreshing
163                                && barrier.is_checkpoint()
164                            {
165                                tracing::info!(
166                                    ?barrier.epoch,
167                                    actor_id = %self.actor_ctx.id,
168                                    source_id = %core.source_id,
169                                    table_id = %self.associated_table_id,
170                                    "Reporting load finished"
171                                );
172                                self.barrier_manager.report_source_load_finished(
173                                    barrier.epoch,
174                                    self.actor_ctx.id,
175                                    self.associated_table_id,
176                                    core.source_id,
177                                );
178
179                                // reset flags
180                                is_list_finished = false;
181                                is_refreshing = false;
182                            }
183
184                            yield Message::Barrier(barrier);
185
186                            if need_rebuild_reader
187                                || (splits_on_fetch == 0
188                                    && !split_queue.is_empty()
189                                    && is_refreshing)
190                            {
191                                Self::replace_with_new_reader(
192                                    &mut split_queue,
193                                    &mut stream,
194                                    &mut splits_on_fetch,
195                                    source_desc.clone(),
196                                    &column_names,
197                                    is_load_finished.clone(),
198                                )?;
199                            }
200                        }
201                        Message::Chunk(chunk) => {
202                            let split_values: Vec<(String, JsonbVal)> = chunk
203                                .data_chunk()
204                                .rows()
205                                .map(|row| {
206                                    let split_id = row.datum_at(0).unwrap().into_utf8();
207                                    let split = row.datum_at(1).unwrap().into_jsonb();
208                                    (split_id.to_owned(), split.to_owned_scalar())
209                                })
210                                .collect();
211                            tracing::debug!("received split assignments: {:?}", split_values);
212                            split_queue.extend(split_values);
213                        }
214                        Message::Watermark(_) => unreachable!(),
215                    },
216                    Either::Right(chunk) => {
217                        // Check if the reader is finished after yielding
218                        if *is_load_finished.read() {
219                            splits_on_fetch -= 1;
220                            tracing::debug!(
221                                "split read finished, remaining splits_on_fetch: {}",
222                                splits_on_fetch
223                            );
224                        }
225                        yield Message::Chunk(chunk);
226                    }
227                },
228            }
229        }
230    }
231
232    fn replace_with_new_reader<const BIASED: bool>(
233        split_queue: &mut VecDeque<(String, JsonbVal)>,
234        stream: &mut StreamReaderWithPause<BIASED, StreamChunk>,
235        splits_on_fetch: &mut usize,
236        source_desc: SourceDesc,
237        column_names: &[String],
238        read_finished: Arc<RwLock<bool>>,
239    ) -> StreamExecutorResult<()> {
240        // For ADBC Snowflake, we process one split at a time to manage connection resources
241        // In the future, this could be extended to batch multiple splits
242
243        if let Some((split_id, split_json)) = split_queue.pop_front() {
244            tracing::debug!("building reader for split: {}", split_id);
245            *splits_on_fetch = 1;
246            *read_finished.write() = false;
247
248            let split = AdbcSnowflakeSplit::decode(split_json.as_scalar_ref())?;
249            let reader =
250                Self::build_split_reader(source_desc, split, column_names.to_vec(), read_finished);
251            stream.replace_data_stream(reader.boxed());
252        } else {
253            stream.replace_data_stream(stream::pending().boxed());
254        }
255
256        Ok(())
257    }
258
259    /// Build and execute a data reader for a single split.
260    /// The reader yields chunks from the split until all data is exhausted,
261    /// then sets the `read_finished` flag.
262    /// Chunks are split to respect the configured `chunk_size` for rate limiting.
263    #[try_stream(ok = StreamChunk, error = StreamExecutorError)]
264    async fn build_split_reader(
265        source_desc: SourceDesc,
266        split: AdbcSnowflakeSplit,
267        column_names: Vec<String>,
268        read_finished: Arc<RwLock<bool>>,
269    ) {
270        let properties = source_desc.source.config.clone();
271        let properties = match properties {
272            ConnectorProperties::AdbcSnowflake(props) => Box::new(*props),
273            _ => unreachable!(),
274        };
275
276        let max_chunk_size = crate::config::chunk_size();
277        let chunks = Self::read_split(properties, split, &column_names)?;
278        for chunk in chunks {
279            // Split large chunks to respect the configured chunk_size for rate limiting
280            if chunk.capacity() > max_chunk_size {
281                for small_chunk in chunk.split(max_chunk_size) {
282                    yield small_chunk;
283                }
284            } else {
285                yield chunk;
286            }
287        }
288
289        *read_finished.write() = true;
290    }
291
292    /// Read data from a single split by executing the Snowflake query.
293    /// Returns all chunks for the split. The query is built from the source schema,
294    /// `table_ref`, optional snapshot timestamp (AT clause), and optional WHERE clause.
295    /// Column names are derived from the fetch executor's schema, filtering out additional
296    /// columns and hidden columns.
297    /// If time travel query fails, falls back to querying without snapshot.
298    fn read_split(
299        properties: Box<AdbcSnowflakeProperties>,
300        split: AdbcSnowflakeSplit,
301        column_names: &[String],
302    ) -> StreamExecutorResult<Vec<StreamChunk>> {
303        let select_list = column_names
304            .iter()
305            .map(|c| format!(r#""{}""#, c))
306            .collect::<Vec<_>>()
307            .join(", ");
308
309        // Try with snapshot first if available
310        if let Some(ref ts) = split.snapshot_timestamp {
311            let table_expr_with_snapshot = format!("{} AT(TIMESTAMP => '{}')", split.table_ref, ts);
312            let mut final_query = format!("SELECT {select_list} FROM {}", table_expr_with_snapshot);
313            if let Some(ref where_clause) = split.where_clause {
314                final_query = format!("{final_query} WHERE {where_clause}");
315            }
316
317            tracing::debug!(
318                split_id = %split.split_id,
319                query = %final_query,
320                "executing query for split with time travel"
321            );
322
323            match properties.execute_query(&final_query) {
324                Ok(batches) => {
325                    return Self::convert_batches_to_chunks(&split.split_id, batches);
326                }
327                Err(e) => {
328                    // Time travel may have failed, log and fall back to current data
329                    tracing::warn!(
330                        split_id = %split.split_id,
331                        error = %e.as_report(),
332                        "Time travel query failed, falling back to current data"
333                    );
334                }
335            }
336        }
337
338        // Fall back to querying without snapshot
339        let mut final_query = format!("SELECT {select_list} FROM {}", split.table_ref);
340        if let Some(ref where_clause) = split.where_clause {
341            final_query = format!("{final_query} WHERE {where_clause}");
342        }
343
344        tracing::debug!(
345            split_id = %split.split_id,
346            query = %final_query,
347            "executing query for split without time travel"
348        );
349
350        let batches = properties.execute_query(&final_query)?;
351        Self::convert_batches_to_chunks(&split.split_id, batches)
352    }
353
354    /// Convert Arrow `RecordBatch`es to `StreamChunk`s
355    fn convert_batches_to_chunks(
356        split_id: &str,
357        batches: Vec<RecordBatch>,
358    ) -> StreamExecutorResult<Vec<StreamChunk>> {
359        let mut chunks = Vec::new();
360
361        for batch in batches {
362            // Convert Arrow RecordBatch to RisingWave DataChunk
363            // The column order in the RecordBatch matches the Snowflake query result,
364            // which is consistent with the schema inferred by get_arrow_schema() in the connector.
365            let data_chunk = from_arrow58_record_batch(&batch)?;
366
367            // Convert DataChunk to StreamChunk (all inserts)
368            let stream_chunk = StreamChunk::from_parts(
369                itertools::repeat_n(Op::Insert, data_chunk.capacity()).collect_vec(),
370                data_chunk,
371            );
372
373            chunks.push(stream_chunk);
374        }
375
376        tracing::debug!(
377            split_id = %split_id,
378            num_chunks = chunks.len(),
379            "finished reading split"
380        );
381
382        Ok(chunks)
383    }
384}
385
386impl<S: StateStore> Execute for BatchAdbcSnowflakeFetchExecutor<S> {
387    fn execute(self: Box<Self>) -> BoxedMessageStream {
388        self.into_stream().boxed()
389    }
390}
391
392impl<S: StateStore> Debug for BatchAdbcSnowflakeFetchExecutor<S> {
393    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
394        if let Some(core) = &self.stream_source_core {
395            f.debug_struct("BatchAdbcSnowflakeFetchExecutor")
396                .field("source_id", &core.source_id)
397                .field("column_ids", &core.column_ids)
398                .finish()
399        } else {
400            f.debug_struct("BatchAdbcSnowflakeFetchExecutor").finish()
401        }
402    }
403}