Skip to main content

risingwave_meta/controller/
session_params.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 std::collections::HashMap;
16use std::sync::Arc;
17
18use itertools::Itertools;
19use risingwave_common::config::SessionInitConfig;
20use risingwave_common::session_config::{SessionConfig, SessionConfigError};
21use risingwave_meta_model::prelude::SessionParameter;
22use risingwave_meta_model::session_parameter;
23use risingwave_pb::meta::SetSessionParamRequest;
24use risingwave_pb::meta::subscribe_response::{Info, Operation};
25use sea_orm::ActiveValue::Set;
26use sea_orm::{DatabaseConnection, EntityTrait, TransactionTrait};
27use thiserror_ext::AsReport;
28use tokio::sync::{RwLock, RwLockReadGuard};
29use tracing::info;
30
31use crate::controller::SqlMetaStore;
32use crate::manager::{LocalNotification, NotificationManagerRef};
33use crate::{MetaError, MetaResult};
34
35pub type SessionParamsControllerRef = Arc<SessionParamsController>;
36
37const ENABLE_LOCALITY_BACKFILL_PARAM: &str = "enable_locality_backfill";
38const LOCALITY_BACKFILL_MODE_PARAM: &str = "locality_backfill_mode";
39
40/// Manages the global default session params on meta.
41/// Note that the session params in each session will be initialized from the default value here.
42pub struct SessionParamsController {
43    db: DatabaseConnection,
44    // Cached parameters.
45    params: RwLock<SessionConfig>,
46    notification_manager: NotificationManagerRef,
47}
48
49impl SessionParamsController {
50    pub async fn new(
51        sql_meta_store: SqlMetaStore,
52        notification_manager: NotificationManagerRef,
53        session_init: SessionInitConfig,
54    ) -> MetaResult<Self> {
55        let db = sql_meta_store.conn;
56
57        // Precedence (high to low):
58        // 1. Persisted value in Meta store (`session_parameter`)
59        // 2. Explicit value in `[session_init]`
60        // 3. Built-in `SessionConfig::default()`
61        let mut init_params = SessionConfig::default();
62
63        // Apply the explicitly-configured `[session_init]` values onto the built-in defaults.
64        // Record the normalized value of each so we can later detect when a persisted value
65        // takes precedence and warn the operator.
66        let mut session_init_values: HashMap<String, String> = HashMap::new();
67        for (name, value) in session_init.entries() {
68            let normalized = init_params.set(name, value.to_owned(), &mut ())?;
69            session_init_values.insert(name.to_owned(), normalized);
70        }
71        if !session_init_values.is_empty() {
72            info!(
73                "[session_init] seeds session parameters during cluster bootstrap only; \
74                 persisted values in the meta store take precedence on existing clusters"
75            );
76        }
77
78        // Persisted values take precedence over `[session_init]`.
79        let params = SessionParameter::find().all(&db).await?;
80        let has_locality_backfill_mode = params
81            .iter()
82            .any(|param| param.name == LOCALITY_BACKFILL_MODE_PARAM);
83        let has_legacy_locality_backfill = params
84            .iter()
85            .any(|param| param.name == ENABLE_LOCALITY_BACKFILL_PARAM);
86        for param in params {
87            if let Some(configured) = session_init_values.get(&param.name)
88                && *configured != param.value
89            {
90                tracing::warn!(
91                    parameter = %param.name,
92                    session_init_value = %configured,
93                    persisted_value = %param.value,
94                    "session_init value differs from persisted session parameter, using persisted value"
95                );
96            }
97            if let Err(e) = init_params.set(&param.name, param.value, &mut ()) {
98                match e {
99                    SessionConfigError::InvalidValue { .. } => {
100                        tracing::error!(error = %e.as_report(), "failed to set parameter from meta database, using default value {}", init_params.get(&param.name)?)
101                    }
102                    SessionConfigError::UnrecognizedEntry(_) => {
103                        tracing::error!(error = %e.as_report(), "failed to set parameter from meta database")
104                    }
105                }
106            }
107        }
108        // Before the mode existed, enabling locality backfill always skipped the size check.
109        if !has_locality_backfill_mode && has_legacy_locality_backfill {
110            init_params.set(LOCALITY_BACKFILL_MODE_PARAM, "always".to_owned(), &mut ())?;
111        }
112
113        info!(?init_params, "session parameters");
114
115        let ctl = Self {
116            db,
117            params: RwLock::new(init_params.clone()),
118            notification_manager,
119        };
120        // flush to db.
121        ctl.flush_params().await?;
122
123        Ok(ctl)
124    }
125
126    pub async fn get_params(&self) -> SessionConfig {
127        self.params.read().await.clone()
128    }
129
130    /// Retain the read guard through reading the session snapshot and sending its marker.
131    pub async fn get_params_read_guard(&self) -> RwLockReadGuard<'_, SessionConfig> {
132        self.params.read().await
133    }
134
135    async fn flush_params(&self) -> MetaResult<()> {
136        let params = self.params.read().await.list_all();
137        let models = params
138            .into_iter()
139            .map(|param| session_parameter::ActiveModel {
140                name: Set(param.name),
141                value: Set(param.setting),
142                description: Set(Some(param.description)),
143            })
144            .collect_vec();
145        let txn = self.db.begin().await?;
146        // delete all params first and then insert all params. It follows the same logic
147        // as the old code, we'd better change it to another way later to keep consistency.
148        SessionParameter::delete_many().exec(&txn).await?;
149        SessionParameter::insert_many(models).exec(&txn).await?;
150        txn.commit().await?;
151        Ok(())
152    }
153
154    pub async fn set_param(&self, name: &str, value: Option<String>) -> MetaResult<String> {
155        let mut params_guard = self.params.write().await;
156        let name = SessionConfig::alias_to_entry_name(name);
157        let Some(param) = SessionParameter::find_by_id(name.clone())
158            .one(&self.db)
159            .await?
160        else {
161            return Err(MetaError::system_params(format!(
162                "unrecognized session parameter {:?}",
163                name
164            )));
165        };
166        let old_batch_parallelism = params_guard.batch_parallelism();
167        // FIXME: use a real reporter
168        let reporter = &mut ();
169        let new_param = if let Some(value) = value {
170            params_guard.set(&name, value, reporter)?
171        } else {
172            params_guard.reset(&name, reporter)?
173        };
174
175        let mut param: session_parameter::ActiveModel = param.into();
176        param.value = Set(new_param.clone());
177        SessionParameter::update(param).exec(&self.db).await?;
178        let new_batch_parallelism = params_guard.batch_parallelism();
179        self.notify_workers(name.clone(), new_param.clone());
180        if old_batch_parallelism != new_batch_parallelism {
181            self.notification_manager
182                .notify_local_subscribers(LocalNotification::BatchParallelismChange);
183        }
184
185        Ok(new_param)
186    }
187
188    pub fn notify_workers(&self, name: String, value: String) {
189        self.notification_manager.notify_frontend_without_version(
190            Operation::Update,
191            Info::SessionParam(SetSessionParamRequest {
192                param: name,
193                value: Some(value),
194            }),
195        );
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use sea_orm::ColumnTrait;
202
203    use super::*;
204    use crate::manager::MetaSrvEnv;
205
206    #[tokio::test]
207    async fn test_session_params() {
208        use sea_orm::QueryFilter;
209
210        let env = MetaSrvEnv::for_test().await;
211        let meta_store = env.meta_store_ref();
212        let init_params = SessionConfig::default();
213
214        // init system parameter controller as first launch.
215        let session_param_ctl = SessionParamsController::new(
216            meta_store.clone(),
217            env.notification_manager_ref(),
218            SessionInitConfig::default(),
219        )
220        .await
221        .unwrap();
222        let params = session_param_ctl.get_params().await;
223        assert_eq!(params, init_params);
224
225        // set parameter.
226        let new_params = session_param_ctl
227            .set_param("rw_implicit_flush", Some("true".into()))
228            .await
229            .unwrap();
230
231        // insert deprecated params.
232        let deprecated_param = session_parameter::ActiveModel {
233            name: Set("deprecated_param".into()),
234            value: Set("foo".into()),
235            description: Set(None),
236        };
237        SessionParameter::insert(deprecated_param)
238            .exec(&session_param_ctl.db)
239            .await
240            .unwrap();
241
242        // init system parameter controller as not first launch.
243        let session_param_ctl = SessionParamsController::new(
244            meta_store.clone(),
245            env.notification_manager_ref(),
246            SessionInitConfig::default(),
247        )
248        .await
249        .unwrap();
250        // check deprecated params are cleaned up.
251        assert!(
252            SessionParameter::find_by_id("deprecated_param".to_owned())
253                .one(&session_param_ctl.db)
254                .await
255                .unwrap()
256                .is_none()
257        );
258        // check new params are set.
259        let params = session_param_ctl.get_params().await;
260        assert_eq!(params.get("rw_implicit_flush").unwrap(), new_params);
261        assert_eq!(
262            params.get("rw_implicit_flush").unwrap(),
263            params.get("implicit_flush").unwrap()
264        );
265        // check db consistency.
266        // rw_implicit_flush is alias to implicit_flush <https://github.com/risingwavelabs/risingwave/pull/18769>
267        let models = SessionParameter::find()
268            .filter(session_parameter::Column::Name.eq("rw_implicit_flush"))
269            .one(&session_param_ctl.db)
270            .await
271            .unwrap();
272        assert!(models.is_none());
273        let models = SessionParameter::find()
274            .filter(session_parameter::Column::Name.eq("implicit_flush"))
275            .one(&session_param_ctl.db)
276            .await
277            .unwrap()
278            .unwrap();
279        assert_eq!(models.value, params.get("rw_implicit_flush").unwrap());
280    }
281
282    /// Scenario 1: on a new cluster, `[session_init]` seeds values into the meta store, including
283    /// the `default` placeholder which must be persisted verbatim.
284    #[tokio::test]
285    async fn test_session_init_bootstrap() {
286        let env = MetaSrvEnv::for_test().await;
287        let meta_store = env.meta_store_ref().clone();
288        // Simulate an empty store: drop the rows seeded while constructing the test env.
289        SessionParameter::delete_many()
290            .exec(&meta_store.conn)
291            .await
292            .unwrap();
293
294        let session_init = SessionInitConfig {
295            streaming_parallelism: Some("bounded(8)".to_owned()),
296            streaming_parallelism_for_table: Some("default".to_owned()),
297            ..Default::default()
298        };
299        let ctl = SessionParamsController::new(
300            meta_store.clone(),
301            env.notification_manager_ref(),
302            session_init,
303        )
304        .await
305        .unwrap();
306
307        let params = ctl.get_params().await;
308        assert_eq!(params.get("streaming_parallelism").unwrap(), "bounded(8)");
309        // `default` must be persisted as-is, not materialized into a concrete value.
310        assert_eq!(
311            params.get("streaming_parallelism_for_table").unwrap(),
312            "default"
313        );
314
315        // Values are persisted to the meta store.
316        let persisted = SessionParameter::find_by_id("streaming_parallelism".to_owned())
317            .one(&meta_store.conn)
318            .await
319            .unwrap()
320            .unwrap();
321        assert_eq!(persisted.value, "bounded(8)");
322    }
323
324    /// Scenario 2: on an existing cluster, a persisted value takes precedence over `[session_init]`.
325    #[tokio::test]
326    async fn test_session_init_persisted_takes_precedence() {
327        let env = MetaSrvEnv::for_test().await;
328        let meta_store = env.meta_store_ref().clone();
329
330        // First launch: seed the store and then mimic an `ALTER SYSTEM SET`.
331        let ctl = SessionParamsController::new(
332            meta_store.clone(),
333            env.notification_manager_ref(),
334            SessionInitConfig::default(),
335        )
336        .await
337        .unwrap();
338        ctl.set_param("streaming_parallelism", Some("ratio(0.5)".to_owned()))
339            .await
340            .unwrap();
341
342        // Restart with a conflicting `[session_init]`: the persisted value must win.
343        let session_init = SessionInitConfig {
344            streaming_parallelism: Some("bounded(8)".to_owned()),
345            ..Default::default()
346        };
347        let ctl = SessionParamsController::new(
348            meta_store.clone(),
349            env.notification_manager_ref(),
350            session_init,
351        )
352        .await
353        .unwrap();
354        let params = ctl.get_params().await;
355        assert_eq!(params.get("streaming_parallelism").unwrap(), "ratio(0.5)");
356    }
357
358    /// Scenario 3: a newly supported field missing from the persisted `session_parameter` table is
359    /// seeded from `[session_init]` on restart.
360    #[tokio::test]
361    async fn test_session_init_seeds_missing_field() {
362        let env = MetaSrvEnv::for_test().await;
363        let meta_store = env.meta_store_ref().clone();
364
365        // First launch seeds and persists defaults for all fields.
366        SessionParamsController::new(
367            meta_store.clone(),
368            env.notification_manager_ref(),
369            SessionInitConfig::default(),
370        )
371        .await
372        .unwrap();
373        // Simulate an older cluster that has no row for this field.
374        SessionParameter::delete_by_id("streaming_parallelism_for_materialized_view".to_owned())
375            .exec(&meta_store.conn)
376            .await
377            .unwrap();
378
379        let session_init = SessionInitConfig {
380            streaming_parallelism_for_materialized_view: Some("bounded(4)".to_owned()),
381            ..Default::default()
382        };
383        let ctl = SessionParamsController::new(
384            meta_store.clone(),
385            env.notification_manager_ref(),
386            session_init,
387        )
388        .await
389        .unwrap();
390        let params = ctl.get_params().await;
391        assert_eq!(
392            params
393                .get("streaming_parallelism_for_materialized_view")
394                .unwrap(),
395            "bounded(4)"
396        );
397    }
398
399    #[tokio::test]
400    async fn test_session_init_invalid_value_fails_without_persisting() {
401        let env = MetaSrvEnv::for_test().await;
402        let meta_store = env.meta_store_ref().clone();
403        // Simulate an empty store: drop the rows seeded while constructing the test env.
404        SessionParameter::delete_many()
405            .exec(&meta_store.conn)
406            .await
407            .unwrap();
408
409        let session_init = SessionInitConfig {
410            streaming_parallelism_for_backfill: Some("bounded(2)".to_owned()),
411            ..Default::default()
412        };
413        let err = match SessionParamsController::new(
414            meta_store.clone(),
415            env.notification_manager_ref(),
416            session_init,
417        )
418        .await
419        {
420            Ok(_) => panic!("invalid [session_init] should fail"),
421            Err(err) => err,
422        };
423        assert!(err
424            .to_string()
425            .contains("Session parameters error: Invalid value `bounded(2)` for `streaming_parallelism_for_backfill`"));
426
427        let persisted = SessionParameter::find()
428            .all(&meta_store.conn)
429            .await
430            .unwrap();
431        assert!(persisted.is_empty());
432    }
433}