Skip to main content

risingwave_frontend/session/
cursor_manager.rs

1// Copyright 2024 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 core::mem;
16use core::time::Duration;
17use std::collections::{HashMap, HashSet, VecDeque};
18use std::fmt::{Display, Formatter};
19use std::sync::Arc;
20use std::time::Instant;
21
22use anyhow::anyhow;
23use bytes::Bytes;
24use futures::StreamExt;
25use itertools::Itertools;
26use pgwire::pg_field_descriptor::PgFieldDescriptor;
27use pgwire::pg_response::StatementType;
28use pgwire::types::{Format, Row};
29use risingwave_batch::task::{ShutdownSender, ShutdownToken};
30use risingwave_common::catalog::{ColumnCatalog, Field};
31use risingwave_common::error::BoxedError;
32use risingwave_common::session_config::QueryMode;
33use risingwave_common::types::{DataType, ScalarImpl, StructType, StructValue};
34use risingwave_common::util::iter_util::ZipEqFast;
35use risingwave_hummock_sdk::HummockVersionId;
36
37use super::SessionImpl;
38use crate::catalog::TableId;
39use crate::catalog::subscription_catalog::SubscriptionCatalog;
40use crate::error::{ErrorCode, Result};
41use crate::expr::{ExprType, FunctionCall, InputRef, Literal};
42use crate::handler::HandlerArgs;
43use crate::handler::declare_cursor::create_chunk_stream_for_cursor;
44use crate::handler::query::{RwBatchQueryPlanResult, gen_batch_plan_fragmenter_with_snapshot};
45use crate::handler::util::{
46    DataChunkToRowSetAdapter, StaticSessionData, convert_logstore_u64_to_unix_millis,
47    pg_value_format, to_pg_field,
48};
49use crate::monitor::{CursorMetrics, PeriodicCursorMetrics};
50use crate::optimizer::PlanRoot;
51use crate::optimizer::plan_node::{BatchFilter, BatchLogSeqScan, BatchSeqScan, generic};
52use crate::optimizer::property::{Order, RequiredDist};
53use crate::scheduler::{DistributedQueryStream, LocalQueryStream, ReadSnapshot, SchedulerError};
54use crate::utils::Condition;
55use crate::{OptimizerContext, OptimizerContextRef, PgResponseStream, TableCatalog};
56
57pub enum CursorDataChunkStream {
58    LocalDataChunk(Option<LocalQueryStream>),
59    DistributedDataChunk(Option<DistributedQueryStream>),
60    PgResponse(PgResponseStream),
61}
62
63pub struct FetchCursorCancelHandle {
64    cancel_tx: ShutdownSender,
65    cancel_rx: ShutdownToken,
66}
67
68impl FetchCursorCancelHandle {
69    pub fn new() -> Self {
70        let (cancel_tx, cancel_rx) = ShutdownToken::new();
71        Self {
72            cancel_tx,
73            cancel_rx,
74        }
75    }
76
77    fn register(&self, session: &SessionImpl) {
78        session.set_cancel_query_flag(self.cancel_tx.clone());
79    }
80
81    async fn cancelled(&mut self) {
82        self.cancel_rx.cancelled().await;
83    }
84
85    fn is_cancelled(&self) -> bool {
86        self.cancel_rx.is_cancelled()
87    }
88}
89
90impl CursorDataChunkStream {
91    pub fn init_row_stream(
92        &mut self,
93        fields: &Vec<Field>,
94        formats: &Vec<Format>,
95        session: Arc<SessionImpl>,
96    ) {
97        let columns_type = fields.iter().map(|f| f.data_type()).collect();
98        match self {
99            CursorDataChunkStream::LocalDataChunk(data_chunk) => {
100                let data_chunk = mem::take(data_chunk).unwrap();
101                let row_stream = PgResponseStream::LocalQuery(DataChunkToRowSetAdapter::new(
102                    data_chunk,
103                    columns_type,
104                    formats.clone(),
105                    session,
106                ));
107                *self = CursorDataChunkStream::PgResponse(row_stream);
108            }
109            CursorDataChunkStream::DistributedDataChunk(data_chunk) => {
110                let data_chunk = mem::take(data_chunk).unwrap();
111                let row_stream = PgResponseStream::DistributedQuery(DataChunkToRowSetAdapter::new(
112                    data_chunk,
113                    columns_type,
114                    formats.clone(),
115                    session,
116                ));
117                *self = CursorDataChunkStream::PgResponse(row_stream);
118            }
119            _ => {}
120        }
121    }
122
123    pub async fn next(&mut self) -> Result<Option<std::result::Result<Vec<Row>, BoxedError>>> {
124        match self {
125            CursorDataChunkStream::PgResponse(row_stream) => Ok(row_stream.next().await),
126            _ => Err(ErrorCode::InternalError(
127                "Only 'CursorDataChunkStream' can call next and return rows".to_owned(),
128            )
129            .into()),
130        }
131    }
132}
133pub enum Cursor {
134    Subscription(SubscriptionCursor),
135    Query(QueryCursor),
136}
137impl Cursor {
138    pub async fn next(
139        &mut self,
140        count: u32,
141        handler_args: HandlerArgs,
142        formats: &Vec<Format>,
143        timeout_seconds: Option<u64>,
144        cancel_handle: &mut FetchCursorCancelHandle,
145    ) -> Result<(Vec<Row>, Vec<PgFieldDescriptor>)> {
146        match self {
147            Cursor::Subscription(cursor) => cursor
148                .next(count, handler_args, formats, timeout_seconds, cancel_handle)
149                .await
150                .inspect_err(|_| cursor.cursor_metrics.subscription_cursor_error_count.inc()),
151            Cursor::Query(cursor) => {
152                cursor
153                    .next(count, formats, handler_args, timeout_seconds)
154                    .await
155            }
156        }
157    }
158
159    pub fn get_fields(&mut self) -> Vec<Field> {
160        match self {
161            Cursor::Subscription(cursor) => cursor.fields_manager.get_output_fields(),
162            Cursor::Query(cursor) => cursor.fields.clone(),
163        }
164    }
165}
166
167pub struct QueryCursor {
168    chunk_stream: CursorDataChunkStream,
169    fields: Vec<Field>,
170    remaining_rows: VecDeque<Row>,
171}
172
173impl QueryCursor {
174    pub fn new(chunk_stream: CursorDataChunkStream, fields: Vec<Field>) -> Result<Self> {
175        Ok(Self {
176            chunk_stream,
177            fields,
178            remaining_rows: VecDeque::<Row>::new(),
179        })
180    }
181
182    pub async fn next_once(&mut self) -> Result<Option<Row>> {
183        while self.remaining_rows.is_empty() {
184            let rows = self.chunk_stream.next().await?;
185            let rows = match rows {
186                None => return Ok(None),
187                Some(row) => row?,
188            };
189            self.remaining_rows = rows.into_iter().collect();
190        }
191        let row = self.remaining_rows.pop_front().unwrap();
192        Ok(Some(row))
193    }
194
195    pub async fn next(
196        &mut self,
197        count: u32,
198        formats: &Vec<Format>,
199        handler_args: HandlerArgs,
200        timeout_seconds: Option<u64>,
201    ) -> Result<(Vec<Row>, Vec<PgFieldDescriptor>)> {
202        // `FETCH NEXT` is equivalent to `FETCH 1`.
203        // min with 100 to avoid allocating too many memory at once.
204        let timeout_instant = timeout_seconds.map(|s| Instant::now() + Duration::from_secs(s));
205        let session = handler_args.session;
206        let mut ans = Vec::with_capacity(std::cmp::min(100, count) as usize);
207        let mut cur = 0;
208        let desc = self.fields.iter().map(to_pg_field).collect();
209        self.chunk_stream
210            .init_row_stream(&self.fields, formats, session);
211        while cur < count
212            && let Some(row) = self.next_once().await?
213        {
214            cur += 1;
215            ans.push(row);
216            if let Some(timeout_instant) = timeout_instant
217                && Instant::now() > timeout_instant
218            {
219                break;
220            }
221        }
222        Ok((ans, desc))
223    }
224}
225
226enum State {
227    InitLogStoreQuery {
228        // The rw_timestamp used to initiate the query to read from subscription logstore.
229        seek_timestamp: u64,
230
231        // If specified, the expected_timestamp must be an exact match for the next rw_timestamp.
232        expected_timestamp: Option<u64>,
233    },
234    Fetch {
235        // Whether the query is reading from snapshot
236        // true: read from the upstream table snapshot
237        // false: read from subscription logstore
238        from_snapshot: bool,
239
240        // The rw_timestamp used to initiate the query to read from subscription logstore.
241        rw_timestamp: u64,
242
243        // The row stream to from the batch query read.
244        // It is returned from the batch execution.
245        chunk_stream: CursorDataChunkStream,
246
247        // A cache to store the remaining rows from the row stream.
248        remaining_rows: VecDeque<Row>,
249
250        expected_timestamp: Option<u64>,
251
252        init_query_timer: Instant,
253    },
254    Invalid,
255}
256
257impl Display for State {
258    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
259        match self {
260            State::InitLogStoreQuery {
261                seek_timestamp,
262                expected_timestamp,
263            } => write!(
264                f,
265                "InitLogStoreQuery {{ seek_timestamp: {}, expected_timestamp: {:?} }}",
266                seek_timestamp, expected_timestamp
267            ),
268            State::Fetch {
269                from_snapshot,
270                rw_timestamp,
271                expected_timestamp,
272                remaining_rows,
273                init_query_timer,
274                ..
275            } => write!(
276                f,
277                "Fetch {{ from_snapshot: {}, rw_timestamp: {}, expected_timestamp: {:?}, cached rows: {}, query init at {}ms before }}",
278                from_snapshot,
279                rw_timestamp,
280                expected_timestamp,
281                remaining_rows.len(),
282                init_query_timer.elapsed().as_millis()
283            ),
284            State::Invalid => write!(f, "Invalid"),
285        }
286    }
287}
288
289struct FieldsManager {
290    columns_catalog: Vec<ColumnCatalog>,
291    // All row fields, including hidden pk, op, rw_timestamp and all non-hidden columns in the upstream table.
292    row_fields: Vec<Field>,
293    // Row output column indices based on `row_fields`.
294    row_output_col_indices: Vec<usize>,
295    // Row pk indices based on `row_fields`.
296    row_pk_indices: Vec<usize>,
297    // Stream chunk row indices based on `row_fields`.
298    stream_chunk_row_indices: Vec<usize>,
299    // The op index based on `row_fields`.
300    op_index: usize,
301}
302
303impl FieldsManager {
304    // pub const OP_FIELD: Field = Field::with_name(DataType::Varchar, "op".to_owned());
305    // pub const RW_TIMESTAMP_FIELD: Field = Field::with_name(DataType::Int64, "rw_timestamp".to_owned());
306
307    pub fn new(catalog: &TableCatalog) -> Self {
308        let mut row_fields = Vec::new();
309        let mut row_output_col_indices = Vec::new();
310        let mut row_pk_indices = Vec::new();
311        let mut stream_chunk_row_indices = Vec::new();
312        let mut output_idx = 0_usize;
313        let pk_set: HashSet<usize> = catalog
314            .pk
315            .iter()
316            .map(|col_order| col_order.column_index)
317            .collect();
318
319        for (index, v) in catalog.columns.iter().enumerate() {
320            if pk_set.contains(&index) {
321                row_pk_indices.push(output_idx);
322                stream_chunk_row_indices.push(output_idx);
323                row_fields.push(Field::with_name(v.data_type().clone(), v.name()));
324                if !v.is_hidden {
325                    row_output_col_indices.push(output_idx);
326                }
327                output_idx += 1;
328            } else if !v.is_hidden {
329                row_output_col_indices.push(output_idx);
330                stream_chunk_row_indices.push(output_idx);
331                row_fields.push(Field::with_name(v.data_type().clone(), v.name()));
332                output_idx += 1;
333            }
334        }
335
336        row_fields.push(Field::with_name(DataType::Varchar, "op".to_owned()));
337        row_output_col_indices.push(output_idx);
338        let op_index = output_idx;
339        output_idx += 1;
340        row_fields.push(Field::with_name(DataType::Int64, "rw_timestamp".to_owned()));
341        row_output_col_indices.push(output_idx);
342        Self {
343            columns_catalog: catalog.columns.clone(),
344            row_fields,
345            row_output_col_indices,
346            row_pk_indices,
347            stream_chunk_row_indices,
348            op_index,
349        }
350    }
351
352    pub fn try_refill_fields(&mut self, catalog: &TableCatalog) -> bool {
353        if self.columns_catalog.ne(&catalog.columns) {
354            *self = Self::new(catalog);
355            true
356        } else {
357            false
358        }
359    }
360
361    pub fn process_output_desc_row(&self, mut rows: Vec<Row>) -> (Vec<Row>, Option<Row>) {
362        let last_row = rows.last_mut().map(|row| {
363            let mut row = row.clone();
364            row.project(&self.row_pk_indices)
365        });
366        let rows = rows
367            .iter_mut()
368            .map(|row| row.project(&self.row_output_col_indices))
369            .collect();
370        (rows, last_row)
371    }
372
373    pub fn get_output_fields(&self) -> Vec<Field> {
374        self.row_output_col_indices
375            .iter()
376            .map(|&idx| self.row_fields[idx].clone())
377            .collect()
378    }
379
380    // In the beginning (declare cur), we will give it an empty formats,
381    // this formats is not a real, when we fetch, We fill it with the formats returned from the pg client.
382    pub fn get_row_stream_fields_and_formats(
383        &self,
384        formats: &Vec<Format>,
385        from_snapshot: bool,
386    ) -> (Vec<Field>, Vec<Format>) {
387        let mut fields = Vec::new();
388        let need_format = !(formats.is_empty() || formats.len() == 1);
389        let mut new_formats = formats.clone();
390        let stream_chunk_row_indices_iter = if from_snapshot {
391            self.stream_chunk_row_indices.iter().chain(None)
392        } else {
393            self.stream_chunk_row_indices
394                .iter()
395                .chain(Some(&self.op_index))
396        };
397        for index in stream_chunk_row_indices_iter {
398            fields.push(self.row_fields[*index].clone());
399            if need_format && !self.row_output_col_indices.contains(index) {
400                new_formats.insert(*index, Format::Text);
401            }
402        }
403        (fields, new_formats)
404    }
405}
406
407pub struct SubscriptionCursor {
408    cursor_name: String,
409    subscription: Arc<SubscriptionCatalog>,
410    dependent_table_id: TableId,
411    cursor_need_drop_time: Instant,
412    state: State,
413    // fields will be set in the table's catalog when the cursor is created,
414    // and will be reset each time it is created chunk_stream, this is to avoid changes in the catalog due to alter.
415    fields_manager: FieldsManager,
416    cursor_metrics: Arc<CursorMetrics>,
417    last_fetch: Instant,
418    seek_pk_row: Option<Row>,
419}
420
421impl SubscriptionCursor {
422    pub async fn new(
423        cursor_name: String,
424        start_timestamp: Option<u64>,
425        subscription: Arc<SubscriptionCatalog>,
426        dependent_table_id: TableId,
427        handler_args: &HandlerArgs,
428        cursor_metrics: Arc<CursorMetrics>,
429    ) -> Result<Self> {
430        let (state, fields_manager) = if let Some(start_timestamp) = start_timestamp {
431            let table_catalog = handler_args.session.get_table_by_id(dependent_table_id)?;
432            (
433                State::InitLogStoreQuery {
434                    seek_timestamp: start_timestamp,
435                    expected_timestamp: None,
436                },
437                FieldsManager::new(&table_catalog),
438            )
439        } else {
440            // The query stream needs to initiated on cursor creation to make sure
441            // future fetch on the cursor starts from the snapshot when the cursor is declared.
442            //
443            // TODO: is this the right behavior? Should we delay the query stream initiation till the first fetch?
444            let snapshot = match handler_args.session.pinned_snapshot() {
445                ReadSnapshot::LatestCommitted { .. } => ReadSnapshot::FrontendPinned {
446                    snapshot: handler_args
447                        .session
448                        .env()
449                        .hummock_snapshot_manager()
450                        .acquire(),
451                },
452                snapshot => snapshot,
453            };
454            let pinned_epoch = match &snapshot {
455                ReadSnapshot::FrontendPinned { snapshot, .. } => {
456                    snapshot
457                        .version()
458                        .state_table_info
459                        .info()
460                        .get(&dependent_table_id)
461                        .ok_or_else(|| {
462                            anyhow!("dependent_table_id {dependent_table_id} not exists")
463                        })?
464                        .committed_epoch
465                }
466                ReadSnapshot::Other(_) => {
467                    return Err(ErrorCode::InternalError("Fetch Cursor can't start from specified query epoch. May run `set query_epoch = 0;`".to_owned()).into());
468                }
469                ReadSnapshot::LatestCommitted { .. } => {
470                    return Err(ErrorCode::InternalError(
471                        "Subscription snapshot must be frontend-pinned".to_owned(),
472                    )
473                    .into());
474                }
475                ReadSnapshot::ReadUncommitted => {
476                    return Err(ErrorCode::InternalError(
477                        "Fetch Cursor don't support read uncommitted".to_owned(),
478                    )
479                    .into());
480                }
481            };
482            // Execute against exactly the snapshot used for the transition to the change log.
483            let (chunk_stream, init_query_timer, table_catalog) = Self::initiate_query(
484                None,
485                dependent_table_id,
486                handler_args.clone(),
487                None,
488                Some(snapshot),
489            )
490            .await?;
491            let start_timestamp = pinned_epoch;
492
493            (
494                State::Fetch {
495                    from_snapshot: true,
496                    rw_timestamp: start_timestamp,
497                    chunk_stream,
498                    remaining_rows: VecDeque::new(),
499                    expected_timestamp: None,
500                    init_query_timer,
501                },
502                FieldsManager::new(&table_catalog),
503            )
504        };
505
506        let cursor_need_drop_time =
507            Instant::now() + Duration::from_secs(subscription.retention_seconds);
508        Ok(Self {
509            cursor_name,
510            subscription,
511            dependent_table_id,
512            cursor_need_drop_time,
513            state,
514            fields_manager,
515            cursor_metrics,
516            last_fetch: Instant::now(),
517            seek_pk_row: None,
518        })
519    }
520
521    async fn next_row(
522        &mut self,
523        handler_args: &HandlerArgs,
524        formats: &Vec<Format>,
525    ) -> Result<Option<Row>> {
526        loop {
527            match &mut self.state {
528                State::InitLogStoreQuery {
529                    seek_timestamp,
530                    expected_timestamp,
531                } => {
532                    let from_snapshot = false;
533
534                    // Initiate a new batch query to continue fetching
535                    match Self::get_next_rw_timestamp(
536                        *seek_timestamp,
537                        self.dependent_table_id,
538                        *expected_timestamp,
539                        handler_args.clone(),
540                        &self.subscription,
541                    )
542                    .await
543                    {
544                        Ok((Some(rw_timestamp), expected_timestamp)) => {
545                            let (mut chunk_stream, init_query_timer, catalog) =
546                                Self::initiate_query(
547                                    Some(rw_timestamp),
548                                    self.dependent_table_id,
549                                    handler_args.clone(),
550                                    None,
551                                    None,
552                                )
553                                .await?;
554                            let table_schema_changed =
555                                self.fields_manager.try_refill_fields(&catalog);
556                            let (fields, formats) = self
557                                .fields_manager
558                                .get_row_stream_fields_and_formats(formats, from_snapshot);
559                            chunk_stream.init_row_stream(
560                                &fields,
561                                &formats,
562                                handler_args.session.clone(),
563                            );
564
565                            self.cursor_need_drop_time = Instant::now()
566                                + Duration::from_secs(self.subscription.retention_seconds);
567                            let mut remaining_rows = VecDeque::new();
568                            Self::try_refill_remaining_rows(&mut chunk_stream, &mut remaining_rows)
569                                .await?;
570                            // Transition to the Fetch state
571                            self.state = State::Fetch {
572                                from_snapshot,
573                                rw_timestamp,
574                                chunk_stream,
575                                remaining_rows,
576                                expected_timestamp,
577                                init_query_timer,
578                            };
579                            if table_schema_changed {
580                                return Ok(None);
581                            }
582                        }
583                        Ok((None, _)) => return Ok(None),
584                        Err(e) => {
585                            self.state = State::Invalid;
586                            return Err(e);
587                        }
588                    }
589                }
590                State::Fetch {
591                    from_snapshot,
592                    rw_timestamp,
593                    chunk_stream,
594                    remaining_rows,
595                    expected_timestamp,
596                    init_query_timer,
597                } => {
598                    let session_data = StaticSessionData {
599                        timezone: handler_args.session.config().timezone(),
600                    };
601                    let from_snapshot = *from_snapshot;
602                    let rw_timestamp = *rw_timestamp;
603
604                    // Try refill remaining rows
605                    Self::try_refill_remaining_rows(chunk_stream, remaining_rows).await?;
606
607                    if let Some(row) = remaining_rows.pop_front() {
608                        // 1. Fetch the next row
609                        if from_snapshot {
610                            return Ok(Some(Self::build_row(
611                                row.take(),
612                                None,
613                                formats,
614                                &session_data,
615                            )?));
616                        } else {
617                            return Ok(Some(Self::build_row(
618                                row.take(),
619                                Some(rw_timestamp),
620                                formats,
621                                &session_data,
622                            )?));
623                        }
624                    } else {
625                        self.cursor_metrics
626                            .subscription_cursor_query_duration
627                            .with_label_values(&[&self.subscription.name])
628                            .observe(init_query_timer.elapsed().as_millis() as _);
629                        // 2. Reach EOF for the current query.
630                        if let Some(expected_timestamp) = expected_timestamp {
631                            self.state = State::InitLogStoreQuery {
632                                seek_timestamp: *expected_timestamp,
633                                expected_timestamp: Some(*expected_timestamp),
634                            };
635                        } else {
636                            self.state = State::InitLogStoreQuery {
637                                seek_timestamp: rw_timestamp + 1,
638                                expected_timestamp: None,
639                            };
640                        }
641                    }
642                }
643                State::Invalid => {
644                    // TODO: auto close invalid cursor?
645                    return Err(ErrorCode::InternalError(
646                        "Cursor is in invalid state. Please close and re-create the cursor."
647                            .to_owned(),
648                    )
649                    .into());
650                }
651            }
652        }
653    }
654
655    pub async fn next(
656        &mut self,
657        count: u32,
658        handler_args: HandlerArgs,
659        formats: &Vec<Format>,
660        timeout_seconds: Option<u64>,
661        cancel_handle: &mut FetchCursorCancelHandle,
662    ) -> Result<(Vec<Row>, Vec<PgFieldDescriptor>)> {
663        let timeout_instant = timeout_seconds.map(|s| Instant::now() + Duration::from_secs(s));
664        if Instant::now() > self.cursor_need_drop_time {
665            return Err(ErrorCode::InternalError(
666                "The cursor has exceeded its maximum lifetime, please recreate it (close then declare cursor).".to_owned(),
667            )
668            .into());
669        }
670
671        let session = &handler_args.session;
672        let mut ans = Vec::with_capacity(std::cmp::min(100, count) as usize);
673        let mut cur = 0;
674        if let State::Fetch {
675            from_snapshot,
676            chunk_stream,
677            ..
678        } = &mut self.state
679        {
680            let (fields, fotmats) = self
681                .fields_manager
682                .get_row_stream_fields_and_formats(formats, *from_snapshot);
683            chunk_stream.init_row_stream(&fields, &fotmats, session.clone());
684        }
685        while cur < count {
686            if cancel_handle.is_cancelled() {
687                return Err(SchedulerError::QueryCancelled("Cancelled by user".to_owned()).into());
688            }
689            let fetch_cursor_timer = Instant::now();
690            let row = self.next_row(&handler_args, formats).await?;
691            self.cursor_metrics
692                .subscription_cursor_fetch_duration
693                .with_label_values(&[&self.subscription.name])
694                .observe(fetch_cursor_timer.elapsed().as_millis() as _);
695            match row {
696                Some(row) => {
697                    cur += 1;
698                    ans.push(row);
699                }
700                None => {
701                    let timeout_seconds = timeout_seconds.unwrap_or(0);
702                    if cur > 0 || timeout_seconds == 0 {
703                        break;
704                    }
705                    let State::InitLogStoreQuery { seek_timestamp, .. } = &self.state else {
706                        // Triggered when previous next_row returns None while self.state is State::Fetch.
707                        continue;
708                    };
709                    // This is the only point where subscription cursor fetch waits without an
710                    // inner query. Register the FETCH-level cancel token so CancelRequest can
711                    // interrupt this wait. The token also marks the whole FETCH as cancelled, so
712                    // we won't start another inner query after a cancellation.
713                    cancel_handle.register(session);
714                    let timeout = tokio::time::sleep(Duration::from_secs(timeout_seconds));
715                    tokio::pin!(timeout);
716                    tokio::select! {
717                        biased;
718                        _ = cancel_handle.cancelled() => {
719                            return Err(SchedulerError::QueryCancelled(
720                                "Cancelled by user".to_owned(),
721                            )
722                            .into());
723                        }
724                        result = session
725                            .env
726                            .hummock_snapshot_manager()
727                            .wait_table_change_log_notification(
728                                self.dependent_table_id,
729                                *seek_timestamp,
730                            ) => {
731                            result?;
732                        }
733                        _ = &mut timeout => {
734                            tracing::debug!("Cursor wait next epoch timeout");
735                            break;
736                        }
737                    }
738                    if cancel_handle.is_cancelled() {
739                        return Err(
740                            SchedulerError::QueryCancelled("Cancelled by user".to_owned()).into(),
741                        );
742                    }
743                }
744            }
745            // Timeout, return with current value
746            if let Some(timeout_instant) = timeout_instant
747                && Instant::now() > timeout_instant
748            {
749                break;
750            }
751        }
752        self.last_fetch = Instant::now();
753        let (rows, seek_pk_row) = self.fields_manager.process_output_desc_row(ans);
754        if let Some(seek_pk_row) = seek_pk_row {
755            self.seek_pk_row = Some(seek_pk_row);
756        }
757        let desc = self
758            .fields_manager
759            .get_output_fields()
760            .iter()
761            .map(to_pg_field)
762            .collect();
763
764        Ok((rows, desc))
765    }
766
767    async fn get_next_rw_timestamp(
768        seek_timestamp: u64,
769        table_id: TableId,
770        expected_timestamp: Option<u64>,
771        handler_args: HandlerArgs,
772        dependent_subscription: &SubscriptionCatalog,
773    ) -> Result<(Option<u64>, Option<u64>)> {
774        let session = handler_args.session;
775        // Test subscription existence
776        session.get_subscription_by_schema_id_name(
777            dependent_subscription.schema_id,
778            &dependent_subscription.name,
779        )?;
780
781        // The epoch here must be pulled every time, otherwise there will be cache consistency issues
782        let Some(new_epochs) = session
783            .list_change_log_epochs(table_id, seek_timestamp, 2)
784            .await?
785        else {
786            return Ok((None, None));
787        };
788        if let Some(expected_timestamp) = expected_timestamp
789            && (new_epochs.is_empty() || &expected_timestamp != new_epochs.first().unwrap())
790        {
791            return Err(ErrorCode::CatalogError(
792                format!(
793                    " No data found for rw_timestamp {:?}, data may have been recycled, please recreate cursor",
794                    convert_logstore_u64_to_unix_millis(expected_timestamp)
795                )
796                .into(),
797            )
798            .into());
799        }
800        Ok((new_epochs.get(0).cloned(), new_epochs.get(1).cloned()))
801    }
802
803    pub fn gen_batch_plan_result(
804        &self,
805        handler_args: HandlerArgs,
806    ) -> Result<RwBatchQueryPlanResult> {
807        match self.state {
808            // Only used to return generated plans, so rw_timestamp are meaningless
809            State::InitLogStoreQuery { .. } => Self::init_batch_plan_for_subscription_cursor(
810                Some(0),
811                self.dependent_table_id,
812                handler_args,
813                self.seek_pk_row.clone(),
814            ),
815            State::Fetch {
816                from_snapshot,
817                rw_timestamp,
818                ..
819            } => {
820                if from_snapshot {
821                    Self::init_batch_plan_for_subscription_cursor(
822                        None,
823                        self.dependent_table_id,
824                        handler_args,
825                        self.seek_pk_row.clone(),
826                    )
827                } else {
828                    Self::init_batch_plan_for_subscription_cursor(
829                        Some(rw_timestamp),
830                        self.dependent_table_id,
831                        handler_args,
832                        self.seek_pk_row.clone(),
833                    )
834                }
835            }
836            State::Invalid => Err(ErrorCode::InternalError(
837                "Cursor is in invalid state. Please close and re-create the cursor.".to_owned(),
838            )
839            .into()),
840        }
841    }
842
843    fn init_batch_plan_for_subscription_cursor(
844        rw_timestamp: Option<u64>,
845        dependent_table_id: TableId,
846        handler_args: HandlerArgs,
847        seek_pk_row: Option<Row>,
848    ) -> Result<RwBatchQueryPlanResult> {
849        let session = handler_args.clone().session;
850        let table_catalog = session.get_table_by_id(dependent_table_id)?;
851        let context = OptimizerContext::from_handler_args(handler_args)?;
852        let version_id = {
853            let version = session.env.hummock_snapshot_manager.acquire();
854            let version = version.version();
855            if !version
856                .state_table_info
857                .info()
858                .contains_key(&dependent_table_id)
859            {
860                return Err(anyhow!("table id {dependent_table_id} has been dropped").into());
861            }
862            version.id
863        };
864        Self::create_batch_plan_for_cursor(
865            table_catalog,
866            &session,
867            context.into(),
868            rw_timestamp.map(|rw_timestamp| (rw_timestamp, rw_timestamp)),
869            version_id,
870            seek_pk_row,
871        )
872    }
873
874    async fn initiate_query(
875        rw_timestamp: Option<u64>,
876        dependent_table_id: TableId,
877        handler_args: HandlerArgs,
878        seek_pk_row: Option<Row>,
879        snapshot_override: Option<ReadSnapshot>,
880    ) -> Result<(CursorDataChunkStream, Instant, Arc<TableCatalog>)> {
881        let init_query_timer = Instant::now();
882        let session = handler_args.clone().session;
883        let table_catalog = session.get_table_by_id(dependent_table_id)?;
884        let plan_result = Self::init_batch_plan_for_subscription_cursor(
885            rw_timestamp,
886            dependent_table_id,
887            handler_args.clone(),
888            seek_pk_row,
889        )?;
890        let plan_fragmenter_result = gen_batch_plan_fragmenter_with_snapshot(
891            &handler_args.session,
892            plan_result,
893            snapshot_override,
894        )?;
895        let (chunk_stream, _) =
896            create_chunk_stream_for_cursor(handler_args.session, plan_fragmenter_result).await?;
897        Ok((chunk_stream, init_query_timer, table_catalog))
898    }
899
900    async fn try_refill_remaining_rows(
901        chunk_stream: &mut CursorDataChunkStream,
902        remaining_rows: &mut VecDeque<Row>,
903    ) -> Result<()> {
904        if remaining_rows.is_empty()
905            && let Some(row_set) = chunk_stream.next().await?
906        {
907            remaining_rows.extend(row_set?);
908        }
909        Ok(())
910    }
911
912    pub fn build_row(
913        mut row: Vec<Option<Bytes>>,
914        rw_timestamp: Option<u64>,
915        formats: &Vec<Format>,
916        session_data: &StaticSessionData,
917    ) -> Result<Row> {
918        let row_len = row.len();
919        let new_row = if let Some(rw_timestamp) = rw_timestamp {
920            let rw_timestamp_formats = formats.get(row_len).unwrap_or(&Format::Text);
921            let rw_timestamp = convert_logstore_u64_to_unix_millis(rw_timestamp);
922            let rw_timestamp = pg_value_format(
923                &DataType::Int64,
924                risingwave_common::types::ScalarRefImpl::Int64(rw_timestamp as i64),
925                *rw_timestamp_formats,
926                session_data,
927            )?;
928            vec![Some(rw_timestamp)]
929        } else {
930            let op_formats = formats.get(row_len).unwrap_or(&Format::Text);
931            let op = pg_value_format(
932                &DataType::Varchar,
933                risingwave_common::types::ScalarRefImpl::Utf8("Insert"),
934                *op_formats,
935                session_data,
936            )?;
937            vec![Some(op), None]
938        };
939        row.extend(new_row);
940        Ok(Row::new(row))
941    }
942
943    pub fn build_desc(mut descs: Vec<Field>, from_snapshot: bool) -> Vec<Field> {
944        if from_snapshot {
945            descs.push(Field::with_name(DataType::Varchar, "op"));
946        }
947        descs.push(Field::with_name(DataType::Int64, "rw_timestamp"));
948        descs
949    }
950
951    pub fn create_batch_plan_for_cursor(
952        table_catalog: Arc<TableCatalog>,
953        session: &SessionImpl,
954        context: OptimizerContextRef,
955        epoch_range: Option<(u64, u64)>,
956        version_id: HummockVersionId,
957        seek_pk_rows: Option<Row>,
958    ) -> Result<RwBatchQueryPlanResult> {
959        // pk + all column without hidden
960        let output_col_idx = table_catalog
961            .columns
962            .iter()
963            .enumerate()
964            .filter_map(|(index, v)| {
965                if !v.is_hidden || table_catalog.pk.iter().any(|pk| pk.column_index == index) {
966                    Some(index)
967                } else {
968                    None
969                }
970            })
971            .collect::<Vec<_>>();
972        let max_split_range_gap = context.session_ctx().config().max_split_range_gap() as u64;
973        let pks = table_catalog.pk();
974        let pks = pks
975            .iter()
976            .map(|f| {
977                let pk = table_catalog.columns.get(f.column_index).unwrap();
978                (pk.data_type(), f.column_index)
979            })
980            .collect_vec();
981        let (scan, predicate) = if let Some(seek_pk_rows) = seek_pk_rows {
982            let mut pk_rows = vec![];
983            let mut values = vec![];
984            for (seek_pk, (data_type, column_index)) in
985                seek_pk_rows.take().into_iter().zip_eq_fast(pks.into_iter())
986            {
987                if let Some(seek_pk) = seek_pk {
988                    pk_rows.push(InputRef {
989                        index: column_index,
990                        data_type: data_type.clone(),
991                    });
992                    let value_string = String::from_utf8(seek_pk.clone().into()).unwrap();
993                    let value_data = ScalarImpl::from_text(&value_string, data_type).unwrap();
994                    values.push((Some(value_data), data_type.clone()));
995                }
996            }
997            if pk_rows.is_empty() {
998                (None, None)
999            } else {
1000                let (right_data, right_types): (Vec<_>, Vec<_>) = values.into_iter().unzip();
1001                let right_data = ScalarImpl::Struct(StructValue::new(right_data));
1002                let right_type = DataType::Struct(StructType::row_expr_type(right_types));
1003                let left = FunctionCall::new_unchecked(
1004                    ExprType::Row,
1005                    pk_rows.into_iter().map(|pk| pk.into()).collect(),
1006                    right_type.clone(),
1007                );
1008                let right = Literal::new(Some(right_data), right_type);
1009                let (scan, predicate) = Condition {
1010                    conjunctions: vec![
1011                        FunctionCall::new(ExprType::GreaterThan, vec![left.into(), right.into()])?
1012                            .into(),
1013                    ],
1014                }
1015                .split_to_scan_ranges(&table_catalog, max_split_range_gap)?;
1016                if scan.len() > 1 {
1017                    return Err(ErrorCode::InternalError(
1018                        "Seek pk row should only generate one scan range".to_owned(),
1019                    )
1020                    .into());
1021                }
1022                (scan.first().cloned(), Some(predicate))
1023            }
1024        } else {
1025            (None, None)
1026        };
1027
1028        let (seq_scan, out_fields, out_names) = if let Some(epoch_range) = epoch_range {
1029            let core = generic::LogScan::new(
1030                table_catalog.name.clone(),
1031                output_col_idx,
1032                table_catalog.clone(),
1033                context,
1034                epoch_range,
1035                version_id,
1036            );
1037            let batch_log_seq_scan = BatchLogSeqScan::new(core, scan);
1038            let out_fields = batch_log_seq_scan.core().out_fields();
1039            let out_names = batch_log_seq_scan.core().column_names();
1040            (batch_log_seq_scan.into(), out_fields, out_names)
1041        } else {
1042            let core = generic::TableScan::new(
1043                output_col_idx,
1044                table_catalog.clone(),
1045                vec![],
1046                vec![],
1047                context,
1048                Condition {
1049                    conjunctions: vec![],
1050                },
1051                None,
1052            );
1053            let scans = match scan {
1054                Some(scan) => vec![scan],
1055                None => vec![],
1056            };
1057            let table_scan = BatchSeqScan::new(core, scans, None);
1058            let out_fields = table_scan.core().out_fields();
1059            let out_names = table_scan.core().column_names();
1060            (table_scan.into(), out_fields, out_names)
1061        };
1062
1063        let plan = if let Some(predicate) = predicate
1064            && !predicate.always_true()
1065        {
1066            BatchFilter::new(generic::Filter::new(predicate, seq_scan)).into()
1067        } else {
1068            seq_scan
1069        };
1070
1071        // order by pk, so don't need to sort
1072        let order = Order::new(table_catalog.pk().to_vec());
1073
1074        // Here we just need a plan_root to call the method, only out_fields and out_names will be used
1075        let plan_root = PlanRoot::new_with_batch_plan(
1076            plan,
1077            RequiredDist::single(),
1078            order,
1079            out_fields,
1080            out_names,
1081        );
1082        let schema = plan_root.schema();
1083        let (batch_log_seq_scan, query_mode) = match session.config().query_mode() {
1084            QueryMode::Auto | QueryMode::Local => {
1085                (plan_root.gen_batch_local_plan()?, QueryMode::Local)
1086            }
1087            QueryMode::Distributed => (
1088                plan_root.gen_batch_distributed_plan()?,
1089                QueryMode::Distributed,
1090            ),
1091        };
1092        Ok(RwBatchQueryPlanResult {
1093            plan: batch_log_seq_scan,
1094            query_mode,
1095            schema,
1096            stmt_type: StatementType::SELECT,
1097        })
1098    }
1099
1100    pub fn idle_duration(&self) -> Duration {
1101        self.last_fetch.elapsed()
1102    }
1103
1104    pub fn subscription_name(&self) -> &str {
1105        self.subscription.name.as_str()
1106    }
1107
1108    pub fn state_info_string(&self) -> String {
1109        format!("{}", self.state)
1110    }
1111}
1112
1113pub struct CursorManager {
1114    cursor_map: tokio::sync::Mutex<HashMap<String, Cursor>>,
1115    cursor_metrics: Arc<CursorMetrics>,
1116}
1117
1118impl CursorManager {
1119    pub fn new(cursor_metrics: Arc<CursorMetrics>) -> Self {
1120        Self {
1121            cursor_map: tokio::sync::Mutex::new(HashMap::new()),
1122            cursor_metrics,
1123        }
1124    }
1125
1126    pub async fn add_subscription_cursor(
1127        &self,
1128        cursor_name: String,
1129        start_timestamp: Option<u64>,
1130        dependent_table_id: TableId,
1131        subscription: Arc<SubscriptionCatalog>,
1132        handler_args: &HandlerArgs,
1133    ) -> Result<()> {
1134        let create_cursor_timer = Instant::now();
1135        let subscription_name = subscription.name.clone();
1136        let cursor = SubscriptionCursor::new(
1137            cursor_name,
1138            start_timestamp,
1139            subscription,
1140            dependent_table_id,
1141            handler_args,
1142            self.cursor_metrics.clone(),
1143        )
1144        .await?;
1145        let mut cursor_map = self.cursor_map.lock().await;
1146        self.cursor_metrics
1147            .subscription_cursor_declare_duration
1148            .with_label_values(&[&subscription_name])
1149            .observe(create_cursor_timer.elapsed().as_millis() as _);
1150
1151        cursor_map.retain(|_, v| {
1152            if let Cursor::Subscription(cursor) = v
1153                && matches!(cursor.state, State::Invalid)
1154            {
1155                false
1156            } else {
1157                true
1158            }
1159        });
1160
1161        cursor_map
1162            .try_insert(cursor.cursor_name.clone(), Cursor::Subscription(cursor))
1163            .map_err(|error| {
1164                ErrorCode::CatalogError(
1165                    format!("cursor `{}` already exists", error.entry.key()).into(),
1166                )
1167            })?;
1168        Ok(())
1169    }
1170
1171    pub async fn add_query_cursor(
1172        &self,
1173        cursor_name: String,
1174        chunk_stream: CursorDataChunkStream,
1175        fields: Vec<Field>,
1176    ) -> Result<()> {
1177        let cursor = QueryCursor::new(chunk_stream, fields)?;
1178        self.cursor_map
1179            .lock()
1180            .await
1181            .try_insert(cursor_name, Cursor::Query(cursor))
1182            .map_err(|error| {
1183                ErrorCode::CatalogError(
1184                    format!("cursor `{}` already exists", error.entry.key()).into(),
1185                )
1186            })?;
1187
1188        Ok(())
1189    }
1190
1191    pub async fn remove_cursor(&self, cursor_name: &str) -> Result<()> {
1192        self.cursor_map
1193            .lock()
1194            .await
1195            .remove(cursor_name)
1196            .ok_or_else(|| {
1197                ErrorCode::CatalogError(format!("cursor `{}` don't exists", cursor_name).into())
1198            })?;
1199        Ok(())
1200    }
1201
1202    pub async fn remove_all_cursor(&self) {
1203        self.cursor_map.lock().await.clear();
1204    }
1205
1206    pub async fn remove_all_query_cursor(&self) {
1207        self.cursor_map
1208            .lock()
1209            .await
1210            .retain(|_, v| matches!(v, Cursor::Subscription(_)));
1211    }
1212
1213    pub async fn get_rows_with_cursor(
1214        &self,
1215        cursor_name: &str,
1216        count: u32,
1217        handler_args: HandlerArgs,
1218        formats: &Vec<Format>,
1219        timeout_seconds: Option<u64>,
1220        cancel_handle: &mut FetchCursorCancelHandle,
1221    ) -> Result<(Vec<Row>, Vec<PgFieldDescriptor>)> {
1222        if let Some(cursor) = self.cursor_map.lock().await.get_mut(cursor_name) {
1223            cursor
1224                .next(count, handler_args, formats, timeout_seconds, cancel_handle)
1225                .await
1226        } else {
1227            Err(ErrorCode::InternalError(format!("Cannot find cursor `{}`", cursor_name)).into())
1228        }
1229    }
1230
1231    pub async fn get_fields_with_cursor(&self, cursor_name: &str) -> Result<Vec<Field>> {
1232        if let Some(cursor) = self.cursor_map.lock().await.get_mut(cursor_name) {
1233            Ok(cursor.get_fields())
1234        } else {
1235            Err(ErrorCode::InternalError(format!("Cannot find cursor `{}`", cursor_name)).into())
1236        }
1237    }
1238
1239    pub async fn get_periodic_cursor_metrics(&self) -> PeriodicCursorMetrics {
1240        let mut subscription_cursor_nums = 0;
1241        let mut invalid_subscription_cursor_nums = 0;
1242        let mut subscription_cursor_last_fetch_duration = HashMap::new();
1243        for cursor in self.cursor_map.lock().await.values() {
1244            if let Cursor::Subscription(subscription_cursor) = cursor {
1245                subscription_cursor_nums += 1;
1246                if matches!(subscription_cursor.state, State::Invalid) {
1247                    invalid_subscription_cursor_nums += 1;
1248                } else {
1249                    let fetch_duration =
1250                        subscription_cursor.last_fetch.elapsed().as_millis() as f64;
1251                    subscription_cursor_last_fetch_duration.insert(
1252                        subscription_cursor.subscription.name.clone(),
1253                        fetch_duration,
1254                    );
1255                }
1256            }
1257        }
1258        PeriodicCursorMetrics {
1259            subscription_cursor_nums,
1260            invalid_subscription_cursor_nums,
1261            subscription_cursor_last_fetch_duration,
1262        }
1263    }
1264
1265    pub async fn iter_query_cursors(&self, mut f: impl FnMut(&String, &QueryCursor)) {
1266        self.cursor_map
1267            .lock()
1268            .await
1269            .iter()
1270            .for_each(|(cursor_name, cursor)| {
1271                if let Cursor::Query(cursor) = cursor {
1272                    f(cursor_name, cursor)
1273                }
1274            });
1275    }
1276
1277    pub async fn iter_subscription_cursors(&self, mut f: impl FnMut(&String, &SubscriptionCursor)) {
1278        self.cursor_map
1279            .lock()
1280            .await
1281            .iter()
1282            .for_each(|(cursor_name, cursor)| {
1283                if let Cursor::Subscription(cursor) = cursor {
1284                    f(cursor_name, cursor)
1285                }
1286            });
1287    }
1288
1289    pub async fn gen_batch_plan_with_subscription_cursor(
1290        &self,
1291        cursor_name: &str,
1292        handler_args: HandlerArgs,
1293    ) -> Result<RwBatchQueryPlanResult> {
1294        match self.cursor_map.lock().await.get(cursor_name).ok_or_else(|| {
1295            ErrorCode::InternalError(format!("Cannot find cursor `{}`", cursor_name))
1296        })? {
1297            Cursor::Subscription(cursor) => {
1298                cursor.gen_batch_plan_result(handler_args.clone())
1299            },
1300            Cursor::Query(_) => Err(ErrorCode::InternalError("The plan of the cursor is the same as the query statement of the as when it was created.".to_owned()).into()),
1301        }
1302    }
1303}