From bd77b599cc25caf7980d3a1627cdd7727c888778 Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 28 Oct 2026 07:27:04 +0000 Subject: [PATCH 1/7] refactor(flow): remove tracked-write protocol (#9992) Signed-off-by: discord9 <55937128+discord9@users.noreply.github.com> --- Cargo.lock | 1 - licenserc-enterprise.toml | 5 - licenserc.toml | 5 - src/common/grpc/Cargo.toml | 4 - src/common/grpc/src/flow_write.rs | 477 --------- src/common/grpc/src/lib.rs | 2 - src/datanode/Cargo.toml | 2 +- src/datanode/src/region_server.rs | 19 - src/datanode/src/region_server/flow_write.rs | 969 ------------------ src/flow/Cargo.toml | 2 +- src/flow/src/batching_mode/frontend_client.rs | 98 -- .../frontend_client/flow_write.rs | 758 -------------- src/frontend/Cargo.toml | 2 - src/frontend/src/instance.rs | 31 - src/frontend/src/instance/builder.rs | 2 - src/frontend/src/instance/flow_write.rs | 227 ---- src/frontend/src/instance/grpc.rs | 14 - src/operator/Cargo.toml | 1 - src/operator/src/insert.rs | 43 - src/operator/src/insert/flow_write.rs | 391 ------- src/session/Cargo.toml | 3 - src/session/src/context.rs | 5 - 22 files changed, 2 insertions(+), 3059 deletions(-) delete mode 100644 src/common/grpc/src/flow_write.rs delete mode 100644 src/datanode/src/region_server/flow_write.rs delete mode 100644 src/flow/src/batching_mode/frontend_client/flow_write.rs delete mode 100644 src/frontend/src/instance/flow_write.rs delete mode 100644 src/operator/src/insert/flow_write.rs diff --git a/Cargo.lock b/Cargo.lock index 639a771816a..6ada3b0a295 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2588,7 +2588,6 @@ dependencies = [ "tokio-util", "tonic 0.14.2", "tower 0.5.2", - "uuid", "vec1", ] diff --git a/licenserc-enterprise.toml b/licenserc-enterprise.toml index 805358f1f1e..d11d344b64d 100644 --- a/licenserc-enterprise.toml +++ b/licenserc-enterprise.toml @@ -15,11 +15,6 @@ headerPath = "licenses/enterprise-header.txt" # with the "# enterprise" block in `licenserc.toml`'s `excludes` — both are # enforced by `make check-enterprise-license`. includes = [ - "src/common/grpc/src/flow_write.rs", - "src/frontend/src/instance/flow_write.rs", - "src/datanode/src/region_server/flow_write.rs", - "src/operator/src/insert/flow_write.rs", - "src/flow/src/batching_mode/frontend_client/flow_write.rs", "src/common/meta/src/rpc/ddl/trigger.rs", "src/operator/src/expr_helper/trigger.rs", "src/sql/src/statements/alter/trigger.rs", diff --git a/licenserc.toml b/licenserc.toml index e84d3a1f8ff..42e6464017c 100644 --- a/licenserc.toml +++ b/licenserc.toml @@ -31,11 +31,6 @@ excludes = [ # Keep this list in sync with that file's `includes`; enforced by # `make check-enterprise-license`. # enterprise:start - "src/common/grpc/src/flow_write.rs", - "src/frontend/src/instance/flow_write.rs", - "src/datanode/src/region_server/flow_write.rs", - "src/operator/src/insert/flow_write.rs", - "src/flow/src/batching_mode/frontend_client/flow_write.rs", "src/common/meta/src/rpc/ddl/trigger.rs", "src/operator/src/expr_helper/trigger.rs", "src/sql/src/statements/alter/trigger.rs", diff --git a/src/common/grpc/Cargo.toml b/src/common/grpc/Cargo.toml index fbfab1b6318..58bd04db093 100644 --- a/src/common/grpc/Cargo.toml +++ b/src/common/grpc/Cargo.toml @@ -7,9 +7,6 @@ license.workspace = true [lints] workspace = true -[features] -enterprise = [] - [dependencies] api.workspace = true arrow-flight.workspace = true @@ -35,7 +32,6 @@ tokio.workspace = true tokio-util.workspace = true tonic.workspace = true tower.workspace = true -uuid.workspace = true vec1 = "1.12" [dev-dependencies] diff --git a/src/common/grpc/src/flow_write.rs b/src/common/grpc/src/flow_write.rs deleted file mode 100644 index 6d085a500bd..00000000000 --- a/src/common/grpc/src/flow_write.rs +++ /dev/null @@ -1,477 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -use std::collections::HashMap; -use std::sync::{Arc, Mutex}; - -use common_error::ext::{ErrorExt, StackError}; -use common_error::status_code::StatusCode; - -use common_recordbatch::{RecordBatch, RecordBatches}; -use datatypes::arrow::array::{Array, StringArray}; -use datatypes::prelude::{ConcreteDataType, VectorRef}; -use datatypes::schema::{ColumnSchema, Schema}; -use datatypes::vectors::StringVector; -use serde::{Deserialize, Serialize}; -use tokio::sync::watch; -use uuid::Uuid; - -pub const COMMAND_KEY: &str = "flow_write_command"; -pub const CHILD_KEY: &str = "flow_write_child"; - -/// The control command carried by a Flow write request. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub enum Command { - Open { nonce: String }, - Write { capability: String }, - Close { capability: String }, -} - -impl Command { - /// Serializes this command as JSON. - pub fn encode(&self) -> serde_json::Result { - serde_json::to_string(self) - } - - /// Parses a serialized command. - pub fn decode(value: &str) -> serde_json::Result { - serde_json::from_str(value) - } -} - -/// A safe terminal application error. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct TerminalError { - pub code: u32, - pub message: String, -} - -impl std::fmt::Display for TerminalError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.message) - } -} - -impl std::error::Error for TerminalError {} - -impl StackError for TerminalError { - fn debug_fmt(&self, layer: usize, buf: &mut Vec) { - buf.push(format!("{layer}: {self:?}")); - } - - fn next(&self) -> Option<&dyn StackError> { - None - } -} - -impl ErrorExt for TerminalError { - fn status_code(&self) -> StatusCode { - StatusCode::from_u32(self.code).unwrap_or(StatusCode::Internal) - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } -} - -/// A finite response for a tracked Flow write. -#[derive(Debug, Clone, Serialize, Deserialize)] -pub enum Reply { - Opened { - capability: String, - }, - Closed, - Complete { - rows: usize, - cost: usize, - metrics: Option, - error: Option, - }, -} - -fn envelope_schema() -> Arc { - Arc::new(Schema::new(vec![ColumnSchema::new( - "envelope", - ConcreteDataType::string_datatype(), - false, - )])) -} - -fn response_error(reason: impl Into) -> common_recordbatch::error::Error { - common_recordbatch::error::Error::CreateRecordBatches { - reason: reason.into(), - location: snafu::Location::new(file!(), line!(), column!()), - } -} - -/// Encodes a reply in the finite one-string-column record-batch envelope. -pub fn reply_batches(reply: &Reply) -> common_recordbatch::error::Result { - let value = serde_json::to_string(reply).map_err(|e| response_error(e.to_string()))?; - let batch = RecordBatch::new( - envelope_schema(), - vec![Arc::new(StringVector::from(vec![value])) as VectorRef], - )?; - RecordBatches::try_new(batch.schema.clone(), vec![batch]) -} - -/// Decodes a reply from its finite one-string-column record-batch envelope. -pub fn decode_reply(batches: &RecordBatches) -> common_recordbatch::error::Result { - let batch = batches - .iter() - .next() - .ok_or_else(|| response_error("missing reply batch"))?; - if batches.iter().count() != 1 || batch.num_columns() != 1 || batch.num_rows() != 1 { - return Err(response_error("reply must be exactly one string value")); - } - let values = batch.columns()[0] - .as_any() - .downcast_ref::() - .ok_or_else(|| response_error("reply value is not a string"))?; - if values.is_null(0) { - return Err(response_error("reply value is null")); - } - let value = values.value(0); - serde_json::from_str(value).map_err(|e| response_error(e.to_string())) -} - -/// Errors that reject admission or indicate that an admitted writer was lost. -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum RegistryError { - UnknownCapability, - Closing, - WriterLost, - PayloadMismatch, -} - -impl std::fmt::Display for RegistryError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "{self:?}") - } -} - -impl std::error::Error for RegistryError {} - -impl StackError for RegistryError { - fn debug_fmt(&self, layer: usize, buf: &mut Vec) { - buf.push(format!("{layer}: {self:?}")); - } - - fn next(&self) -> Option<&dyn StackError> { - None - } -} - -impl ErrorExt for RegistryError { - fn status_code(&self) -> StatusCode { - StatusCode::InvalidArguments - } - - fn as_any(&self) -> &dyn std::any::Any { - self - } -} - -/// Result of atomically admitting or joining a payload. -#[derive(Debug)] -pub enum Admission { - Start(watch::Sender>>), - Join(watch::Receiver>>), -} - -#[derive(Debug)] -struct Entry { - payload: Option

, - sender: Option>>>, - receiver: watch::Receiver>>, - closing: bool, -} - -#[derive(Debug)] -struct State { - openers: HashMap, - entries: HashMap>, -} - -/// Receiver-issued capabilities for single-write admission and completion sharing. -#[derive(Debug)] -pub struct FlowWriteRegistry { - state: Mutex>, -} - -impl Default for FlowWriteRegistry { - fn default() -> Self { - Self { - state: Mutex::new(State { - openers: HashMap::new(), - entries: HashMap::new(), - }), - } - } -} - -impl FlowWriteRegistry { - /// Returns the active capability for this opener nonce, creating one if needed. - pub fn open(&self, nonce: &str) -> Result { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - if let Some(capability) = state.openers.get(nonce) { - if state - .entries - .get(capability) - .is_some_and(|entry| entry.closing) - { - return Err(RegistryError::Closing); - } - return Ok(capability.clone()); - } - let capability = Uuid::new_v4().to_string(); - let (sender, receiver) = watch::channel(None); - state.openers.insert(nonce.to_string(), capability.clone()); - state.entries.insert( - capability.clone(), - Entry { - payload: None, - sender: Some(sender), - receiver, - closing: false, - }, - ); - Ok(capability) - } - - /// Atomically starts one payload or joins its identical in-flight completion. - pub fn admit(&self, capability: &str, payload: P) -> Result, RegistryError> { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let entry = state - .entries - .get_mut(capability) - .ok_or(RegistryError::UnknownCapability)?; - if entry.closing { - return Err(RegistryError::Closing); - } - match &entry.payload { - Some(existing) if existing != &payload => Err(RegistryError::PayloadMismatch), - Some(_) => Ok(Admission::Join(entry.receiver.clone())), - None => { - entry.payload = Some(payload); - let sender = entry.sender.take().ok_or(RegistryError::Closing)?; - Ok(Admission::Start(sender)) - } - } - } - - /// Closes admission, drains an admitted writer, then deletes the capability. - pub async fn close(&self, capability: &str) -> Result<(), RegistryError> { - let receiver = { - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - let Some(entry) = state.entries.get_mut(capability) else { - return Ok(()); - }; - entry.closing = true; - if entry.payload.is_none() { - state.entries.remove(capability); - state.openers.retain(|_, value| value != capability); - return Ok(()); - } - entry.receiver.clone() - }; - wait_completion(receiver).await?; - let mut state = self - .state - .lock() - .unwrap_or_else(std::sync::PoisonError::into_inner); - state.entries.remove(capability); - state.openers.retain(|_, value| value != capability); - Ok(()) - } -} - -/// Waits for an admitted writer's positive terminal completion. -pub async fn wait_completion( - mut receiver: watch::Receiver>>, -) -> Result, RegistryError> { - loop { - if let Some(value) = receiver.borrow().clone() { - return Ok(value); - } - if receiver.changed().await.is_err() { - return Err(RegistryError::WriterLost); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Barrier; - use std::thread; - - #[tokio::test] - async fn concurrent_admission_has_one_owner_and_same_payload_joins() { - let registry = Arc::new(FlowWriteRegistry::::default()); - let cap = registry.open("nonce").unwrap(); - let barrier = Arc::new(Barrier::new(8)); - let mut workers = Vec::new(); - for _ in 0..8 { - let registry = registry.clone(); - let cap = cap.clone(); - let barrier = barrier.clone(); - workers.push(thread::spawn(move || { - barrier.wait(); - registry.admit(&cap, "payload".into()).unwrap() - })); - } - let admissions: Vec<_> = workers.into_iter().map(|w| w.join().unwrap()).collect(); - assert_eq!( - admissions - .iter() - .filter(|a| matches!(a, Admission::Start(_))) - .count(), - 1 - ); - let sender = admissions - .into_iter() - .find_map(|a| match a { - Admission::Start(s) => Some(s), - _ => None, - }) - .unwrap(); - sender.send(Some(Arc::new(7))).unwrap(); - registry.close(&cap).await.unwrap(); - } - - #[tokio::test] - async fn close_drains_active_writer_and_deletes_old_capability() { - let registry = Arc::new(FlowWriteRegistry::::default()); - let cap = registry.open("first").unwrap(); - let Admission::Start(sender) = registry.admit(&cap, "payload".into()).unwrap() else { - panic!() - }; - let close_registry = registry.clone(); - let close_cap = cap.clone(); - let close = tokio::spawn(async move { close_registry.close(&close_cap).await }); - tokio::task::yield_now().await; - assert!(matches!( - registry.admit(&cap, "payload".into()), - Err(RegistryError::Closing) - )); - assert!(!close.is_finished()); - sender.send(Some(Arc::new(9))).unwrap(); - close.await.unwrap().unwrap(); - assert!(matches!( - registry.admit(&cap, "payload".into()), - Err(RegistryError::UnknownCapability) - )); - registry.close(&cap).await.unwrap(); - let new_cap = registry.open("first").unwrap(); - assert_ne!(cap, new_cap); - assert!(matches!( - registry.admit(&cap, "late".into()), - Err(RegistryError::UnknownCapability) - )); - assert!(matches!( - registry.admit(&new_cap, "new".into()).unwrap(), - Admission::Start(_) - )); - } - - #[tokio::test] - async fn writer_loss_is_not_completion() { - let registry = FlowWriteRegistry::::default(); - let cap = registry.open("nonce").unwrap(); - let Admission::Start(sender) = registry.admit(&cap, "payload".into()).unwrap() else { - panic!() - }; - let Admission::Join(receiver) = registry.admit(&cap, "payload".into()).unwrap() else { - panic!() - }; - drop(sender); - assert_eq!( - wait_completion(receiver).await.unwrap_err(), - RegistryError::WriterLost - ); - assert_eq!( - registry.close(&cap).await.unwrap_err(), - RegistryError::WriterLost - ); - } - - #[test] - fn command_and_reply_envelope_round_trip_and_malformed_envelopes() { - let command = Command::Open { nonce: "n".into() }; - assert_eq!( - Command::decode(&command.encode().unwrap()).unwrap(), - command - ); - let reply = Reply::Complete { - rows: 2, - cost: 3, - metrics: Some(common_recordbatch::adapter::RecordBatchMetrics::default()), - error: Some(TerminalError { - code: 4, - message: "terminal".into(), - }), - }; - let batches = reply_batches(&reply).unwrap(); - let decoded = decode_reply(&batches).unwrap(); - assert!(matches!( - decoded, - Reply::Complete { - rows: 2, - cost: 3, - error: Some(_), - .. - } - )); - - let schema = envelope_schema(); - let two_rows = RecordBatch::new( - schema.clone(), - vec![Arc::new(StringVector::from(vec!["a", "b"])) as VectorRef], - ) - .unwrap(); - assert!( - decode_reply(&RecordBatches::try_new(schema.clone(), vec![two_rows]).unwrap()).is_err() - ); - let int_schema = Arc::new(Schema::new(vec![ColumnSchema::new( - "envelope", - ConcreteDataType::int32_datatype(), - false, - )])); - let non_string = RecordBatch::new( - int_schema.clone(), - vec![Arc::new(datatypes::vectors::Int32Vector::from(vec![Some(1)])) as VectorRef], - ) - .unwrap(); - assert!( - decode_reply(&RecordBatches::try_new(int_schema, vec![non_string]).unwrap()).is_err() - ); - let invalid_json = RecordBatch::new( - envelope_schema(), - vec![Arc::new(StringVector::from(vec!["not json"])) as VectorRef], - ) - .unwrap(); - assert!( - decode_reply( - &RecordBatches::try_new(invalid_json.schema.clone(), vec![invalid_json]).unwrap() - ) - .is_err() - ); - } -} diff --git a/src/common/grpc/src/lib.rs b/src/common/grpc/src/lib.rs index 0ac05863f3e..8527dd079b8 100644 --- a/src/common/grpc/src/lib.rs +++ b/src/common/grpc/src/lib.rs @@ -15,8 +15,6 @@ pub mod channel_manager; pub mod error; pub mod flight; -#[cfg(feature = "enterprise")] -pub mod flow_write; pub mod precision; pub mod reloadable_tls; pub mod select; diff --git a/src/datanode/Cargo.toml b/src/datanode/Cargo.toml index bef2641415e..0720a576b9c 100644 --- a/src/datanode/Cargo.toml +++ b/src/datanode/Cargo.toml @@ -6,7 +6,7 @@ license.workspace = true [features] testing = [] -enterprise = ["mito2/enterprise", "common-grpc/enterprise"] +enterprise = ["mito2/enterprise"] [lints] workspace = true diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 06b9d42fd00..6055b07dbf6 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -13,10 +13,6 @@ // limitations under the License. mod catalog; -#[cfg(feature = "enterprise")] -mod flow_write; -#[cfg(feature = "enterprise")] -use flow_write::TrackedPayload; mod registrations; mod remote_dyn_filter; @@ -42,8 +38,6 @@ use async_trait::async_trait; use bytes::Bytes; use common_error::ext::{BoxedError, ErrorExt}; use common_error::status_code::StatusCode; -#[cfg(feature = "enterprise")] -use common_grpc::flow_write::{COMMAND_KEY, FlowWriteRegistry, Reply}; use common_meta::datanode::TopicStatsReporter; use common_query::OutputData; use common_query::request::QueryRequest; @@ -122,8 +116,6 @@ pub struct RegionServer { inner: Arc, flight_compression: FlightCompression, suspend: Arc, - #[cfg(feature = "enterprise")] - flow_write_registry: Arc>, } pub struct RegionStat { @@ -172,8 +164,6 @@ impl RegionServer { )), flight_compression, suspend: Arc::new(AtomicBool::new(false)), - #[cfg(feature = "enterprise")] - flow_write_registry: Arc::new(FlowWriteRegistry::default()), } } @@ -1069,15 +1059,6 @@ impl RegionServerHandler for RegionServer { &self, request: RegionRequestV1, ) -> ServerResult { - #[cfg(feature = "enterprise")] - if request - .header - .as_ref() - .and_then(|header| header.query_context.as_ref()) - .is_some_and(|context| context.extensions.contains_key(COMMAND_KEY)) - { - return self.handle_flow_write_request(request).await; - } let accept_partial_result = request .header .as_ref() diff --git a/src/datanode/src/region_server/flow_write.rs b/src/datanode/src/region_server/flow_write.rs deleted file mode 100644 index bc9bf65d69d..00000000000 --- a/src/datanode/src/region_server/flow_write.rs +++ /dev/null @@ -1,969 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -//! Datanode receiver for tracked Flow writes. -//! -//! A single immutable operation per receiver-issued capability: the first -//! admitted `Write` becomes the owner and executes the Inserts exactly once on -//! the region engines; concurrent or retried identical writers join the -//! owner's completion. Dropping a waiter (for example a lost RPC response) -//! never cancels the engine work, and closing a capability rejects later -//! writes with that capability. If the owner's outcome becomes unknown (a -//! child ingest worker was lost), no positive terminal completion is -//! published: waiters observe `WriterLost`; the capability admits no second -//! owner, so no overlapping engine write can be produced. - -use std::sync::Arc; - -use api::v1::region::RegionRequest as RegionRequestV1; -use api::v1::region::region_request; -use common_error::ext::ErrorExt; -use common_grpc::flow_write::{Admission, COMMAND_KEY, Command, Reply, TerminalError}; -use common_runtime::runtime::RuntimeTrait; -use common_telemetry::tracing_context::{FutureExt, TracingContext}; -use futures_util::future::join_all; -use prost::Message; -use servers::error::{InvalidQuerySnafu, Result as ServerResult}; -use snafu::OptionExt; - -use crate::region_server::RegionServer; - -/// Payload of a tracked write: encoded Inserts rows (exact bytes, so floats -/// keep bit equality even for NaN), schemas compared by protobuf equality, and -/// semantic header identity (dbname and command-free query context). Retrying -/// with different business data or context is rejected instead of joining. -pub(crate) type TrackedPayload = ( - Vec, - Vec>>, - String, - Option, -); - -fn tracked_payload(request: &RegionRequestV1) -> ServerResult { - let body = request.body.as_ref().context(InvalidQuerySnafu { - reason: "Expecting non-empty region request body.", - })?; - if !matches!(body, region_request::Body::Inserts(_)) { - return Err(servers::error::Error::InvalidQuery { - reason: "Tracked Flow write supports Inserts requests only.".to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - // Oneof is not `prost::Message`; the variant message itself is. Schema - // options contain unordered maps, so compare schemas separately rather than - // letting their wire ordering affect retries; retain encoded rows for NaN. - let (bytes, schemas) = match body { - region_request::Body::Inserts(inserts) => { - let mut inserts = inserts.clone(); - let schemas = inserts - .requests - .iter_mut() - .map(|request| { - request - .rows - .as_mut() - .map(|rows| std::mem::take(&mut rows.schema)) - }) - .collect(); - (inserts.encode_to_vec(), schemas) - } - _ => unreachable!("checked above"), - }; - let header = request.header.as_ref(); - let mut query_context = header.and_then(|header| header.query_context.clone()); - if let Some(context) = query_context.as_mut() { - // The command extension differs per control request, not per business. - context.extensions.remove(COMMAND_KEY); - } - Ok(( - bytes, - schemas, - header - .map(|header| header.dbname.clone()) - .unwrap_or_default(), - query_context, - )) -} - -fn ensure_empty_control_body(request: &RegionRequestV1) -> ServerResult<()> { - match request.body.as_ref() { - Some(region_request::Body::Inserts(inserts)) if inserts.requests.is_empty() => Ok(()), - _ => Err(servers::error::Error::InvalidQuery { - reason: "Tracked Flow write control requests must carry an empty Inserts body." - .to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - }), - } -} - -fn registry_error(error: common_grpc::flow_write::RegistryError) -> servers::error::Error { - servers::error::Error::UnexpectedResult { - reason: format!("Tracked Flow write registry rejected request: {error:?}"), - location: snafu::Location::new(file!(), line!(), column!()), - } -} - -fn response(reply: Reply) -> ServerResult { - let encoded = - serde_json::to_vec(&reply).map_err(|error| servers::error::Error::UnexpectedResult { - reason: format!("Failed to encode tracked Flow write reply: {error}"), - location: snafu::Location::new(file!(), line!(), column!()), - })?; - let mut extensions = std::collections::HashMap::new(); - extensions.insert(COMMAND_KEY.to_string(), encoded); - Ok(api::v1::region::RegionResponse { - header: Some(api::v1::ResponseHeader { - status: Some(api::v1::Status { - status_code: common_error::status_code::StatusCode::Success as _, - ..Default::default() - }), - }), - affected_rows: 0, - extensions, - metadata: Vec::new(), - failures: Vec::new(), - }) -} - -impl RegionServer { - pub(crate) async fn handle_flow_write_request( - &self, - request: RegionRequestV1, - ) -> ServerResult { - let command = request - .header - .as_ref() - .and_then(|header| header.query_context.as_ref()) - .and_then(|context| context.extensions.get(COMMAND_KEY)) - .and_then(|value| Command::decode(value).ok()); - let command = match command { - Some(command) => command, - None => { - // The extension exists but is not a decodable command: reject - // before any ordinary DML dispatch. - return Err(InvalidQuerySnafu { - reason: "Malformed tracked Flow write command.", - } - .build()); - } - }; - - match command { - Command::Open { nonce } => { - ensure_empty_control_body(&request)?; - let capability = self - .flow_write_registry - .open(&nonce) - .map_err(registry_error)?; - response(Reply::Opened { capability }) - } - Command::Close { capability } => { - ensure_empty_control_body(&request)?; - self.flow_write_registry - .close(&capability) - .await - .map_err(registry_error)?; - response(Reply::Closed) - } - Command::Write { capability } => { - let payload = tracked_payload(&request)?; - let admission = self - .flow_write_registry - .admit(&capability, payload) - .map_err(registry_error)?; - let reply = match admission { - Admission::Start(owner) => { - // Subscribe before the owner sender moves into the - // spawned task: this caller stays a plain waiter whose - // drop cannot cancel the engine work. - let receiver = owner.subscribe(); - let server = self.clone(); - let body = request.body; - let header = request.header; - self.inner.runtime.spawn(async move { - let completion = server - .run_tracked_write(header, body) - .trace(TracingContext::from_current_span().attach( - common_telemetry::tracing::info_span!( - "RegionServer::tracked_flow_write" - ), - )) - .await; - match completion { - Some(reply) => { - let _ = owner.send(Some(Arc::new(reply))); - } - None => { - // Unknown worker outcome: no positive terminal - // result is published. Dropping the sender lets - // waiters observe `WriterLost`. - drop(owner); - } - } - }); - common_grpc::flow_write::wait_completion(receiver) - .await - .map_err(registry_error)? - } - Admission::Join(waiter) => common_grpc::flow_write::wait_completion(waiter) - .await - .map_err(registry_error)?, - }; - response((*reply).clone()) - } - } - } - - /// Executes one admitted tracked write. Returns `None` only when the - /// outcome is unknown (a child worker was lost); malformed request bodies - /// are terminal because no child was ever dispatched. - async fn run_tracked_write( - &self, - header: Option, - body: Option, - ) -> Option { - let requests = - match body.map(store_api::region_request::RegionRequest::try_from_request_body) { - Some(Ok(requests)) => requests, - Some(Err(error)) => { - return Some(Reply::Complete { - rows: 0, - cost: 0, - metrics: None, - error: Some(TerminalError { - code: error.status_code() as u32, - message: error.output_msg(), - }), - }); - } - // `None` is unreachable here: the Write path already rejected an - // empty body before admission. Treat it as unknown rather than - // inventing a terminal result. - None => return None, - }; - let tracing = header - .as_ref() - .map(|header| TracingContext::from_w3c(&header.tracing_context)) - .unwrap_or_default(); - - let mut unknown_worker = false; - let mut first_error: Option = None; - let mut affected_rows = 0usize; - - let tasks = requests.into_iter().map(|(region_id, request)| { - let span = tracing.attach(common_telemetry::tracing::info_span!( - "RegionServer::tracked_region_write", - region_id = region_id.to_string() - )); - async move { self.handle_request(region_id, request).trace(span).await } - }); - // Drain every per-region child before any terminal decision. A lost - // ingest worker (`RuntimeJoin`) is unknown and outranks any ordinary - // application error observed during the same drain. - for result in join_all(tasks).await { - match result { - Ok(response) => affected_rows += response.affected_rows, - Err(crate::error::Error::RuntimeJoin { .. }) => { - unknown_worker = true; - } - Err(error) if first_error.is_none() => first_error = Some(error), - Err(_) => {} - } - } - - if unknown_worker { - return None; - } - - Some(match first_error { - None => Reply::Complete { - rows: affected_rows, - cost: affected_rows, - metrics: None, - error: None, - }, - Some(error) => Reply::Complete { - rows: 0, - cost: 0, - metrics: None, - error: Some(TerminalError { - code: error.status_code() as u32, - message: error.output_msg(), - }), - }, - }) - } -} - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - use std::sync::Arc; - use std::sync::atomic::{AtomicUsize, Ordering}; - - use api::region::RegionResponse; - use api::v1::region::region_request::Body; - use api::v1::region::{ - InsertRequest, InsertRequests, RegionRequest as Request, RegionRequestHeader, - }; - use api::v1::{ColumnDataType, ColumnSchema, QueryContext, Row, Rows, SemanticType, Value}; - use common_grpc::flow_write::{self, Command, Reply}; - use servers::grpc::region_server::RegionServerHandler; - use store_api::region_engine::{RegionEngine, RegionEngineRef}; - use store_api::storage::RegionId; - use tokio::sync::Notify; - use tokio::time::{Duration, timeout}; - - use super::*; - use crate::tests::{MockRegionEngine, mock_region_server}; - - #[derive(Clone, Default)] - struct Gate { - entered: Arc, - notified: Arc, - open: Arc, - fail: bool, - } - - impl Gate { - async fn wait_entered(&self, count: usize) { - timeout(Duration::from_secs(5), async { - loop { - let notified = self.notified.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if self.entered.load(Ordering::SeqCst) >= count { - break; - } - notified.await; - } - }) - .await - .unwrap(); - } - fn release(&self) { - self.open.store(1, Ordering::SeqCst); - self.notified.notify_waiters(); - } - async fn wait_open(&self) { - loop { - let notified = self.notified.notified(); - tokio::pin!(notified); - notified.as_mut().enable(); - if self.open.load(Ordering::SeqCst) != 0 { - break; - } - notified.await; - } - } - } - - struct GatedEngine { - gate: Gate, - inner: Arc, - panic_id: Option, - } - #[async_trait::async_trait] - impl RegionEngine for GatedEngine { - fn name(&self) -> &str { - self.inner.name() - } - async fn handle_request( - &self, - id: RegionId, - _request: store_api::region_request::RegionRequest, - ) -> Result { - self.gate.entered.fetch_add(1, Ordering::SeqCst); - self.gate.notified.notify_waiters(); - if self.panic_id == Some(id.as_u64()) { - panic!("test ingest panic"); - } - if self.gate.fail && id.as_u64() == 1 { - return Err(common_error::ext::BoxedError::new( - crate::error::RegionNotFoundSnafu { region_id: id }.build(), - )); - } - self.gate.wait_open().await; - Ok(RegionResponse::new(1)) - } - async fn handle_query( - &self, - id: RegionId, - req: store_api::storage::ScanRequest, - ) -> Result - { - self.inner.handle_query(id, req).await - } - async fn get_committed_sequence( - &self, - id: RegionId, - ) -> Result { - self.inner.get_committed_sequence(id).await - } - async fn get_metadata( - &self, - id: RegionId, - ) -> Result { - self.inner.get_metadata(id).await - } - fn region_statistic( - &self, - id: RegionId, - ) -> Option { - self.inner.region_statistic(id) - } - async fn stop(&self) -> Result<(), common_error::ext::BoxedError> { - self.inner.stop().await - } - fn set_region_role( - &self, - id: RegionId, - role: store_api::region_engine::RegionRole, - ) -> Result<(), common_error::ext::BoxedError> { - self.inner.set_region_role(id, role) - } - - fn set_region_role_with_lease( - &self, - id: RegionId, - role: store_api::region_engine::RegionRole, - deadline: std::time::Instant, - ) -> Result<(), common_error::ext::BoxedError> { - self.inner.set_region_role_with_lease(id, role, deadline) - } - async fn sync_region( - &self, - id: RegionId, - req: store_api::region_engine::SyncRegionFromRequest, - ) -> Result - { - self.inner.sync_region(id, req).await - } - async fn remap_manifests( - &self, - req: store_api::region_engine::RemapManifestsRequest, - ) -> Result - { - self.inner.remap_manifests(req).await - } - async fn set_region_role_state_gracefully( - &self, - id: RegionId, - state: store_api::region_engine::SettableRegionRoleState, - ) -> Result< - store_api::region_engine::SetRegionRoleStateResponse, - common_error::ext::BoxedError, - > { - self.inner.set_region_role_state_gracefully(id, state).await - } - fn role(&self, id: RegionId) -> Option { - self.inner.role(id) - } - fn as_any(&self) -> &dyn std::any::Any { - self - } - } - - fn body(ids: &[u64], nan: bool) -> Body { - Body::Inserts(InsertRequests { - requests: ids - .iter() - .map(|id| InsertRequest { - region_id: *id, - rows: Some(Rows { - schema: vec![ - ColumnSchema { - column_name: "ts".into(), - datatype: ColumnDataType::TimestampMillisecond as i32, - semantic_type: SemanticType::Timestamp as i32, - datatype_extension: None, - options: None, - }, - ColumnSchema { - column_name: "v".into(), - datatype: ColumnDataType::Float64 as i32, - semantic_type: SemanticType::Field as i32, - datatype_extension: None, - options: None, - }, - ], - rows: vec![Row { - values: vec![ - Value { - value_data: Some( - api::v1::value::ValueData::TimestampMillisecondValue(1), - ), - }, - Value { - value_data: Some(api::v1::value::ValueData::F64Value(if nan { - f64::NAN - } else { - 7. - })), - }, - ], - }], - }), - partition_expr_version: None, - skip_wal: false, - }) - .collect(), - }) - } - - fn request(cmd: Command, body: Option) -> Request { - let mut extensions = HashMap::new(); - extensions.insert(flow_write::COMMAND_KEY.into(), cmd.encode().unwrap()); - Request { - header: Some(RegionRequestHeader { - dbname: "db".into(), - tracing_context: Default::default(), - query_context: Some(QueryContext { - extensions, - ..Default::default() - }), - }), - body, - } - } - fn decode(resp: &api::v1::region::RegionResponse) -> Reply { - assert_eq!( - resp.header - .as_ref() - .unwrap() - .status - .as_ref() - .unwrap() - .status_code, - common_error::status_code::StatusCode::Success as u32 - ); - serde_json::from_slice(resp.extensions.get(flow_write::COMMAND_KEY).unwrap()).unwrap() - } - async fn open(s: &RegionServer) -> String { - match decode( - &s.handle_region_request(request( - Command::Open { nonce: "n".into() }, - Some(Body::Inserts(InsertRequests { requests: vec![] })), - )) - .await - .unwrap(), - ) { - Reply::Opened { capability } => capability, - x => panic!("{x:?}"), - } - } - fn setup(gate: Gate, panic_id: Option, ids: &[u64]) -> RegionServer { - let s = mock_region_server(); - let (inner, _) = MockRegionEngine::new("mock"); - let engine: RegionEngineRef = Arc::new(GatedEngine { - gate, - inner, - panic_id, - }); - for id in ids { - s.inner.region_map.insert( - RegionId::from_u64(*id), - super::super::RegionEngineWithStatus::Ready(engine.clone()), - ); - } - s - } - fn write(cap: &str, ids: &[u64], nan: bool) -> Request { - request( - Command::Write { - capability: cap.into(), - }, - Some(body(ids, nan)), - ) - } - - #[tokio::test] - async fn dropped_rpc_retry_and_close_drain_exactly_once() { - let gate = Gate::default(); - let s = setup(gate.clone(), None, &[1, 2]); - let cap = open(&s).await; - let w = write(&cap, &[1, 2], false); - let first = tokio::spawn({ - let s = s.clone(); - let w = w.clone(); - async move { s.handle_region_request(w).await } - }); - gate.wait_entered(2).await; - first.abort(); - // Exercise the same actual registry admission used by retry, before release. - let payload = tracked_payload(&w).unwrap(); - let Admission::Join(waiter) = s.flow_write_registry.admit(&cap, payload).unwrap() else { - panic!("retry did not join") - }; - let mut retry_waiter = tokio::spawn(common_grpc::flow_write::wait_completion(waiter)); - assert!( - timeout(Duration::from_millis(20), &mut retry_waiter) - .await - .is_err() - ); - let mut closer = tokio::spawn({ - let s = s.clone(); - let cap = cap.clone(); - async move { - s.handle_region_request(request( - Command::Close { capability: cap }, - Some(Body::Inserts(InsertRequests { requests: vec![] })), - )) - .await - } - }); - assert!( - timeout(Duration::from_millis(20), &mut closer) - .await - .is_err() - ); - gate.release(); - let joined = timeout(Duration::from_secs(5), &mut retry_waiter) - .await - .unwrap() - .unwrap() - .unwrap(); - assert!(matches!( - *joined, - Reply::Complete { - rows: 2, - error: None, - .. - } - )); - assert!(matches!( - decode( - &timeout(Duration::from_secs(5), &mut closer) - .await - .unwrap() - .unwrap() - .unwrap() - ), - Reply::Closed - )); - assert!( - s.handle_region_request(write(&cap, &[1], false)) - .await - .is_err() - ); - let cap2 = open(&s).await; - gate.release(); - let r = s - .handle_region_request(write(&cap2, &[1], false)) - .await - .unwrap(); - assert!(matches!(decode(&r), Reply::Complete { rows: 1, .. })); - assert!( - s.handle_region_request(write(&cap, &[1], false)) - .await - .is_err() - ); - assert_eq!(gate.entered.load(Ordering::SeqCst), 3); - let close2 = request( - Command::Close { capability: cap2 }, - Some(Body::Inserts(InsertRequests { requests: vec![] })), - ); - assert!(matches!( - decode(&s.handle_region_request(close2).await.unwrap()), - Reply::Closed - )); - } - - #[tokio::test] - async fn application_error_waits_for_sibling_and_panic_overrides_it() { - let gate = Gate { - fail: true, - ..Default::default() - }; - let s = setup(gate.clone(), None, &[1, 2]); - let cap = open(&s).await; - let task = tokio::spawn({ - let s = s.clone(); - async move { s.handle_region_request(write(&cap, &[1, 2], false)).await } - }); - gate.wait_entered(2).await; - // The ordinary error is immediate for region 1, but region 2 remains gated. - assert!(!task.is_finished()); - gate.release(); - let r = timeout(Duration::from_secs(5), task) - .await - .unwrap() - .unwrap() - .unwrap(); - assert!(matches!(decode(&r), Reply::Complete { error: Some(_), .. })); - - let gate = Gate { - fail: true, - ..Default::default() - }; - let s = setup(gate.clone(), Some(2), &[1, 2, 3]); - let cap = open(&s).await; - let task = tokio::spawn({ - let s = s.clone(); - let cap = cap.clone(); - async move { - s.handle_region_request(write(&cap, &[1, 2, 3], false)) - .await - } - }); - gate.wait_entered(3).await; - assert!(!task.is_finished()); - gate.release(); - assert!( - timeout(Duration::from_secs(5), task) - .await - .unwrap() - .unwrap() - .is_err() - ); - assert!( - s.handle_region_request(write(&cap, &[1, 2, 3], false)) - .await - .is_err() - ); - assert_eq!(gate.entered.load(Ordering::SeqCst), 3); - } - - #[tokio::test] - async fn decoded_schema_option_maps_join_live_nan_write() { - let gate = Gate::default(); - let s = setup(gate.clone(), None, &[1]); - let cap = open(&s).await; - let mut original = write(&cap, &[1], true); - let Body::Inserts(inserts) = original.body.as_mut().unwrap() else { - unreachable!() - }; - inserts.requests[0].rows.as_mut().unwrap().schema[1].options = - Some(api::v1::ColumnOptions { - options: [ - ("alpha".to_string(), "one".to_string()), - ("beta".to_string(), "two".to_string()), - ("gamma".to_string(), "three".to_string()), - ] - .into_iter() - .collect(), - }); - let encoded = original.encode_to_vec(); - let Body::Inserts(original_inserts) = original.body.as_ref().unwrap() else { - unreachable!() - }; - let original_rows = original_inserts.requests[0].rows.clone(); - let original_body_bytes = original_inserts.encode_to_vec(); - let mut retries = Vec::new(); - let mut found_different_wire_order = false; - for _ in 0..128 { - let decoded = Request::decode(encoded.as_slice()).unwrap(); - let Body::Inserts(decoded_inserts) = decoded.body.as_ref().unwrap() else { - unreachable!() - }; - assert_eq!( - decoded_inserts.requests[0].rows.as_ref().unwrap().schema, - original_rows.as_ref().unwrap().schema - ); - assert_eq!( - tracked_payload(&decoded).unwrap(), - tracked_payload(&original).unwrap() - ); - found_different_wire_order |= decoded_inserts.encode_to_vec() != original_body_bytes; - retries.push(decoded); - if found_different_wire_order && retries.len() >= 16 { - break; - } - } - assert!(found_different_wire_order); - - let owner = tokio::spawn({ - let s = s.clone(); - async move { s.handle_region_request(original).await } - }); - gate.wait_entered(1).await; - let retry_tasks: Vec<_> = retries - .into_iter() - .map(|retry| { - let s = s.clone(); - tokio::spawn(async move { s.handle_region_request(retry).await }) - }) - .collect(); - tokio::task::yield_now().await; - assert!(retry_tasks.iter().all(|retry| !retry.is_finished())); - assert_eq!(gate.entered.load(Ordering::SeqCst), 1); - gate.release(); - let owner_reply = decode( - &timeout(Duration::from_secs(5), owner) - .await - .unwrap() - .unwrap() - .unwrap(), - ); - assert!(matches!( - &owner_reply, - Reply::Complete { - rows: 1, - error: None, - .. - } - )); - let owner_reply_json = serde_json::to_string(&owner_reply).unwrap(); - for retry in retry_tasks { - let retry_reply = decode( - &timeout(Duration::from_secs(5), retry) - .await - .unwrap() - .unwrap() - .unwrap(), - ); - assert!(matches!( - &retry_reply, - Reply::Complete { - rows: 1, - error: None, - .. - } - )); - assert_eq!( - serde_json::to_string(&retry_reply).unwrap(), - owner_reply_json - ); - } - assert_eq!(gate.entered.load(Ordering::SeqCst), 1); - - let replay = Request::decode(encoded.as_slice()).unwrap(); - assert!(matches!( - decode(&s.handle_region_request(replay.clone()).await.unwrap()), - Reply::Complete { rows: 1, .. } - )); - let mut changed_schema = replay.clone(); - let Body::Inserts(inserts) = changed_schema.body.as_mut().unwrap() else { - unreachable!() - }; - inserts.requests[0].rows.as_mut().unwrap().schema[1] - .options - .as_mut() - .unwrap() - .options - .insert("gamma".into(), "changed".into()); - assert!(s.handle_region_request(changed_schema).await.is_err()); - let close = request( - Command::Close { - capability: cap.clone(), - }, - Some(Body::Inserts(InsertRequests { requests: vec![] })), - ); - assert!(matches!( - decode(&s.handle_region_request(close).await.unwrap()), - Reply::Closed - )); - assert!(s.handle_region_request(replay).await.is_err()); - assert_eq!(gate.entered.load(Ordering::SeqCst), 1); - } - - #[tokio::test] - async fn payload_identity_nan_semantics_and_pre_admission_rejection() { - let s = mock_region_server(); - let cap = open(&s).await; - let a = write(&cap, &[1], true); - let b = write(&cap, &[1], true); - assert_eq!(tracked_payload(&a).unwrap(), tracked_payload(&b).unwrap()); - let owner = match s - .flow_write_registry - .admit(&cap, tracked_payload(&a).unwrap()) - .unwrap() - { - Admission::Start(owner) => owner, - _ => panic!(), - }; - let mut semantic_mismatch = b.clone(); - semantic_mismatch.header.as_mut().unwrap().dbname = "other_db".into(); - assert_eq!( - s.flow_write_registry - .admit(&cap, tracked_payload(&semantic_mismatch).unwrap()) - .unwrap_err(), - flow_write::RegistryError::PayloadMismatch - ); - semantic_mismatch = b.clone(); - semantic_mismatch - .header - .as_mut() - .unwrap() - .query_context - .as_mut() - .unwrap() - .extensions - .insert("flow_lane".into(), "changed".into()); - assert_eq!( - s.flow_write_registry - .admit(&cap, tracked_payload(&semantic_mismatch).unwrap()) - .unwrap_err(), - flow_write::RegistryError::PayloadMismatch - ); - let Admission::Join(waiter) = s - .flow_write_registry - .admit(&cap, tracked_payload(&b).unwrap()) - .unwrap() - else { - panic!() - }; - let mut joined = tokio::spawn(common_grpc::flow_write::wait_completion(waiter)); - assert!( - timeout(Duration::from_millis(20), &mut joined) - .await - .is_err() - ); - owner - .send(Some(Arc::new(Reply::Complete { - rows: 1, - cost: 1, - metrics: None, - error: None, - }))) - .unwrap(); - assert!(matches!( - *timeout(Duration::from_secs(5), &mut joined) - .await - .unwrap() - .unwrap() - .unwrap(), - Reply::Complete { rows: 1, .. } - )); - s.flow_write_registry.close(&cap).await.unwrap(); - assert_ne!( - tracked_payload(&a).unwrap(), - tracked_payload(&write(&cap, &[1], false)).unwrap() - ); - assert!( - s.handle_region_request(request( - Command::Write { - capability: cap.clone() - }, - Some(Body::Deletes(Default::default())) - )) - .await - .is_err() - ); - let fresh = open(&s).await; - let mut bad = request( - Command::Write { - capability: fresh.clone(), - }, - Some(body(&[1], false)), - ); - bad.header - .as_mut() - .unwrap() - .query_context - .as_mut() - .unwrap() - .extensions - .insert(flow_write::COMMAND_KEY.into(), "not-json".into()); - assert!(s.handle_region_request(bad).await.is_err()); - s.flow_write_registry.close(&fresh).await.unwrap(); - } -} diff --git a/src/flow/Cargo.toml b/src/flow/Cargo.toml index 2cf316ad245..2d9ff283aa2 100644 --- a/src/flow/Cargo.toml +++ b/src/flow/Cargo.toml @@ -5,7 +5,7 @@ edition.workspace = true license.workspace = true [features] -enterprise = ["common-grpc/enterprise", "session/enterprise"] +enterprise = [] [lints] workspace = true diff --git a/src/flow/src/batching_mode/frontend_client.rs b/src/flow/src/batching_mode/frontend_client.rs index 8c74c6897f0..1a354c55e42 100644 --- a/src/flow/src/batching_mode/frontend_client.rs +++ b/src/flow/src/batching_mode/frontend_client.rs @@ -95,12 +95,8 @@ pub enum FrontendClient { control_channel_manager: ChannelManager, query: QueryOptions, batch_opts: BatchingModeOptions, - #[cfg(feature = "enterprise")] - tracked_writes: bool, }, Standalone { - #[cfg(feature = "enterprise")] - tracked_writes: bool, /// for the sake of simplicity still use grpc even in standalone mode /// notice the client here should all be lazy, so that can wait after frontend is booted then make conn database_client: HandlerMutable, @@ -109,26 +105,6 @@ pub enum FrontendClient { } impl FrontendClient { - #[cfg(feature = "enterprise")] - pub fn with_tracked_writes(&self) -> Self { - let mut client = self.clone(); - match &mut client { - Self::Distributed { tracked_writes, .. } | Self::Standalone { tracked_writes, .. } => { - *tracked_writes = true; - } - } - client - } - - #[cfg(feature = "enterprise")] - fn tracked_writes_enabled(&self) -> bool { - match self { - Self::Distributed { tracked_writes, .. } | Self::Standalone { tracked_writes, .. } => { - *tracked_writes - } - } - } - /// Create a new empty frontend client, with a `HandlerMutable` to set the grpc handler later pub fn from_empty_grpc_handler(query: QueryOptions) -> (Self, HandlerMutable) { let is_initialized = Arc::new(SetOnce::new()); @@ -140,8 +116,6 @@ impl FrontendClient { Self::Standalone { database_client: handler.clone(), query, - #[cfg(feature = "enterprise")] - tracked_writes: false, }, handler, ) @@ -178,8 +152,6 @@ impl FrontendClient { control_channel_manager, query, batch_opts, - #[cfg(feature = "enterprise")] - tracked_writes: false, }) } @@ -196,8 +168,6 @@ impl FrontendClient { Self::Standalone { database_client: handler, query, - #[cfg(feature = "enterprise")] - tracked_writes: false, } } } @@ -235,39 +205,7 @@ impl DatabaseWithPeer { } } -#[cfg(feature = "enterprise")] -pub(crate) mod flow_write; - impl FrontendClient { - /// Preflight tracked-write support by opening and closing a capability without writing. - #[cfg(feature = "enterprise")] - pub async fn check_tracked_writes(&self, catalog: &str, schema: &str) -> Result<(), Error> { - if !self.tracked_writes_enabled() { - return UnexpectedSnafu { - reason: "Tracked writes are not enabled on this frontend client", - } - .fail(); - } - flow_write::check_tracked_writes(self, catalog, schema).await - } - - /// Execute a finite SQL write with receiver-issued completion tracking. - #[cfg(feature = "enterprise")] - pub async fn tracked_sql_write( - &self, - catalog: &str, - schema: &str, - sql: &str, - ) -> Result { - if !self.tracked_writes_enabled() { - return UnexpectedSnafu { - reason: "Tracked writes are not enabled on this frontend client", - } - .fail(); - } - flow_write::tracked_sql_write(self, catalog, schema, sql).await - } - /// scan for available frontend from metadata pub(crate) async fn scan_for_frontend(&self) -> Result, Error> { let Self::Distributed { meta_client, .. } = self else { @@ -558,33 +496,6 @@ impl FrontendClient { peer_desc: &mut Option, ) -> Result { let flow_extensions = build_flow_extensions(extensions)?; - #[cfg(feature = "enterprise")] - if self.tracked_writes_enabled() && is_tracked_insert_request(&request) { - let effective_extensions: HashMap = extensions - .iter() - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) - .collect(); - if effective_extensions.contains_key(common_grpc::flow_write::COMMAND_KEY) { - return UnexpectedSnafu { - reason: "Client-supplied tracked Flow command is forbidden", - } - .fail(); - } - let effective_extension_refs: Vec<(&str, &str)> = effective_extensions - .iter() - .map(|(key, value)| (key.as_str(), value.as_str())) - .collect(); - return flow_write::tracked_query( - self, - catalog, - schema, - Some(request), - &effective_extension_refs, - snapshot_seqs, - peer_desc, - ) - .await; - } match self { FrontendClient::Distributed { query, batch_opts, .. @@ -835,15 +746,6 @@ impl FrontendClient { } } -#[cfg(feature = "enterprise")] -fn is_tracked_insert_request(request: &QueryRequest) -> bool { - match request.query.as_ref() { - Some(Query::InsertIntoPlan(_)) => true, - Some(Query::Sql(sql)) => sql.trim_start().to_ascii_uppercase().starts_with("INSERT "), - _ => false, - } -} - fn build_flow_extensions(extensions: &[(&str, &str)]) -> Result { let flow_extensions = HashMap::from_iter( extensions diff --git a/src/flow/src/batching_mode/frontend_client/flow_write.rs b/src/flow/src/batching_mode/frontend_client/flow_write.rs deleted file mode 100644 index 0d7663ccd4d..00000000000 --- a/src/flow/src/batching_mode/frontend_client/flow_write.rs +++ /dev/null @@ -1,758 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -use std::collections::HashMap; -use std::sync::Arc; -use std::time::Duration; - -use api::v1::query_request::Query; -use api::v1::{QueryRequest, greptime_request::Request}; -use client::OutputWithMetrics; -use common_error::ext::{BoxedError, ErrorExt}; -use common_error::status_code::StatusCode; -use common_grpc::flow_write::{self, COMMAND_KEY, Command, Reply, TerminalError}; -use common_query::{Output, OutputData, OutputMeta}; -use common_telemetry::warn; -use session::context::{Channel, QueryContextBuilder, generate_remote_query_id}; -use snafu::OptionExt; -use tokio::time::sleep; - -use crate::Error; -use crate::batching_mode::frontend_client::{DatabaseWithPeer, FrontendClient, PeerDesc}; -use crate::error::UnexpectedSnafu; - -const RETRY_PACE: Duration = Duration::from_secs(1); - -pub(crate) async fn tracked_sql_write( - frontend: &FrontendClient, - catalog: &str, - schema: &str, - sql: &str, -) -> Result { - tracked_query( - frontend, - catalog, - schema, - Some(QueryRequest { - query: Some(Query::Sql(sql.to_string())), - }), - &[], - &HashMap::new(), - &mut None, - ) - .await -} - -pub(crate) async fn check_tracked_writes( - frontend: &FrontendClient, - catalog: &str, - schema: &str, -) -> Result<(), Error> { - tracked_query( - frontend, - catalog, - schema, - None, - &[], - &HashMap::new(), - &mut None, - ) - .await - .map(|_| ()) -} - -pub(crate) async fn tracked_query( - frontend: &FrontendClient, - catalog: &str, - schema: &str, - request: Option, - extensions: &[(&str, &str)], - snapshot_seqs: &HashMap, - peer_desc: &mut Option, -) -> Result { - let (selected, handler, parallelism, read_preference, timeout) = match frontend { - FrontendClient::Distributed { - query, batch_opts, .. - } => ( - Some( - frontend - .get_random_active_frontend(catalog, schema) - .await - .map_err(prewrite_error)?, - ), - None, - query.parallelism.to_string(), - Some(batch_opts.read_preference.as_ref().to_string()), - batch_opts.experimental_flight_do_get_timeout, - ), - FrontendClient::Standalone { - database_client, - query, - .. - } => { - let handler = database_client - .handler - .lock() - .map_err(|e| { - prewrite_reason( - format!("Failed to lock database client: {e}"), - StatusCode::Internal, - ) - })? - .as_ref() - .context(UnexpectedSnafu { - reason: "Standalone's frontend instance is not set", - }) - .map_err(prewrite_error)? - .upgrade() - .context(UnexpectedSnafu { - reason: "Failed to upgrade database client", - }) - .map_err(prewrite_error)?; - ( - None, - Some(handler), - query.parallelism.to_string(), - None, - RETRY_PACE, - ) - } - }; - *peer_desc = Some(match &selected { - Some(DatabaseWithPeer { peer, .. }) => PeerDesc::Dist { peer: peer.clone() }, - None => PeerDesc::Standalone, - }); - - let nonce = generate_remote_query_id(); - let mut command = Command::Open { nonce }; - let mut completion: Option<( - usize, - usize, - Option, - Option, - )> = None; - - loop { - let encoded = command.encode().map_err(|error| { - UnexpectedSnafu { - reason: format!("Failed to encode tracked Flow command: {error}"), - } - .build() - })?; - let mut operation_extensions: Vec<(String, String)> = extensions - .iter() - .filter(|(key, _)| *key != COMMAND_KEY) - .map(|(key, value)| ((*key).to_string(), (*value).to_string())) - .collect(); - operation_extensions.push((COMMAND_KEY.to_string(), encoded)); - let extension_refs: Vec<(&str, &str)> = operation_extensions - .iter() - .map(|(k, v)| (k.as_str(), v.as_str())) - .collect(); - let phase_request = match &command { - Command::Write { .. } => request - .as_ref() - .context(UnexpectedSnafu { - reason: "Tracked Flow write command has no request", - })? - .clone(), - Command::Open { .. } | Command::Close { .. } => QueryRequest { - query: Some(Query::Sql(String::new())), - }, - }; - let response = if let Some(DatabaseWithPeer { database, .. }) = &selected { - let mut hints = vec![( - query::datafusion::QUERY_PARALLELISM_HINT, - parallelism.as_str(), - )]; - if let Some(preference) = read_preference.as_deref() { - hints.push((session::hints::READ_PREFERENCE_HINT, preference)); - } - database - .flight_request() - .with_hints(&hints) - .with_flow_extensions(&extension_refs) - .with_snapshot_seqs(snapshot_seqs) - .with_timeout(timeout) - .query_with_terminal_metrics(phase_request) - .await - .map(|output| output.output) - .map_err(|e| (e.status_code(), e.to_string())) - } else { - let mut ctx_extensions: HashMap = - operation_extensions.into_iter().collect(); - ctx_extensions.insert( - query::datafusion::QUERY_PARALLELISM_HINT.to_string(), - parallelism.clone(), - ); - let ctx = QueryContextBuilder::default() - .current_catalog(catalog.to_string()) - .current_schema(schema.to_string()) - .channel(Channel::Internal) - .extensions(ctx_extensions) - .snapshot_seqs(Arc::new(std::sync::RwLock::new(snapshot_seqs.clone()))) - .build(); - let handler = handler.as_ref().ok_or_else(|| { - UnexpectedSnafu { - reason: "Standalone handler was not pinned", - } - .build() - })?; - handler - .do_query(Request::Query(phase_request), Arc::new(ctx)) - .await - .map_err(|e| (e.status_code(), e.to_string())) - }; - let reply = match response { - Ok(output) => match decode_output(output).await { - Ok(reply) => Some(reply), - Err(e) if matches!(&command, Command::Open { .. }) => { - return Err(prewrite_reason( - format!("Frontend does not support tracked Flow writes: {e}"), - StatusCode::Unsupported, - )); - } - Err(e) => { - warn!("Malformed tracked Flow {:?} reply: {}", command, e); - None - } - }, - Err((code, msg)) => { - // Only Open is pre-admission; definitive rejection there is safe to surface. - if matches!(&command, Command::Open { .. }) && is_definitive_rejection(code) { - return Err(prewrite_reason( - format!("Frontend rejected tracked Flow open: {msg}"), - code, - )); - } - warn!( - "Tracked Flow {:?} transport failure (code={:?}): {}", - command, code, msg - ); - None - } - }; - match (command.clone(), reply) { - (Command::Open { .. }, Some(Reply::Opened { capability: cap })) if !cap.is_empty() => { - command = if request.is_some() { - Command::Write { capability: cap } - } else { - Command::Close { capability: cap } - }; - continue; - } - (Command::Open { .. }, Some(other)) => { - return Err(prewrite_reason( - format!("Invalid tracked Flow open reply: {other:?}"), - StatusCode::InvalidArguments, - )); - } - ( - Command::Write { capability }, - Some(Reply::Complete { - rows, - cost, - metrics, - error, - }), - ) => { - completion = Some((rows, cost, metrics, error)); - command = Command::Close { capability }; - continue; - } - (Command::Write { .. }, Some(other)) => { - warn!("Unexpected tracked Flow write reply: {other:?}") - } - (Command::Close { .. }, Some(Reply::Closed)) => { - let Some((rows, cost, metrics, error)) = completion.take() else { - if request.is_none() { - return Ok(OutputWithMetrics::from_output(Output::new( - OutputData::AffectedRows(0), - OutputMeta::default(), - ))); - } - return UnexpectedSnafu { - reason: "Close completed without positive write result", - } - .fail(); - }; - if let Some(error) = error { - return Err(Error::External { - source: BoxedError::new(error), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - let output = OutputWithMetrics::from_output(Output::new( - OutputData::AffectedRows(rows), - OutputMeta { - cost, - ..Default::default() - }, - )); - output.metrics.update(metrics); - return Ok(output); - } - (Command::Close { .. }, Some(other)) => { - warn!("Unexpected tracked Flow close reply: {other:?}") - } - (_, None) => {} - } - sleep(RETRY_PACE).await; - } -} - -fn prewrite_error(error: Error) -> Error { - let status = error.status_code(); - prewrite_reason(error.to_string(), status) -} - -/// Returns true when a tracked Flow command error is a definitive, non-retryable -/// rejection from the frontend rather than an ambiguous transport failure. These -/// codes indicate the frontend itself refused the command (unsupported protocol, -/// malformed/empty command, or wrong channel), so retrying the same pinned -/// frontend can never succeed; the caller must fail fast instead of looping. -fn is_definitive_rejection(code: StatusCode) -> bool { - matches!( - code, - StatusCode::Unsupported | StatusCode::InvalidArguments | StatusCode::PermissionDenied - ) -} - -fn prewrite_reason(message: String, status: StatusCode) -> Error { - Error::External { - source: BoxedError::new(TerminalError { - code: status as u32, - message, - }), - location: snafu::Location::new(file!(), line!(), column!()), - } -} - -async fn decode_output(output: Output) -> Result { - let batches = match output.data { - OutputData::RecordBatches(batches) => batches, - OutputData::Stream(stream) => common_recordbatch::util::collect_batches(stream) - .await - .map_err(|e| e.to_string())?, - _ => return Err("tracked control request returned a non-record-batch result".to_string()), - }; - flow_write::decode_reply(&batches).map_err(|e| e.to_string()) -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicUsize, Ordering}; - - use common_error::ext::{BoxedError, PlainError}; - use common_error::status_code::StatusCode; - use session::context::QueryContextRef; - - #[derive(Debug, Default)] - struct LostReplyHandler { - opens: AtomicUsize, - writes: AtomicUsize, - closes: AtomicUsize, - executions: AtomicUsize, - registry: common_grpc::flow_write::FlowWriteRegistry, - capabilities: std::sync::Mutex>, - } - - #[async_trait::async_trait] - impl super::super::GrpcQueryHandlerWithBoxedError for LostReplyHandler { - async fn do_query( - &self, - request: Request, - ctx: QueryContextRef, - ) -> Result { - let encoded = ctx.extensions().get(COMMAND_KEY).cloned().ok_or_else(|| { - BoxedError::new(PlainError::new( - "missing command".into(), - StatusCode::Unexpected, - )) - })?; - match Command::decode(&encoded).map_err(|error| { - BoxedError::new(PlainError::new( - error.to_string(), - StatusCode::InvalidArguments, - )) - })? { - Command::Open { nonce } => { - let call = self.opens.fetch_add(1, Ordering::SeqCst); - let capability = self.registry.open(&nonce).unwrap(); - let previous = self - .capabilities - .lock() - .unwrap() - .insert(nonce, capability.clone()); - if let Some(previous) = previous { - assert_eq!(previous, capability); - } - if call == 0 { - return Err(transport_error("lost Open reply")); - } - assert_empty_sql(&request); - response(Reply::Opened { capability }) - } - Command::Write { capability } => { - let sql = request_sql(&request); - let call = self.writes.fetch_add(1, Ordering::SeqCst); - let admission = self.registry.admit(&capability, sql.clone()).unwrap(); - let result = match admission { - common_grpc::flow_write::Admission::Start(sender) => { - self.executions.fetch_add(1, Ordering::SeqCst); - let reply = Reply::Complete { - rows: 1, - cost: 9, - metrics: Some(common_recordbatch::adapter::RecordBatchMetrics { - region_watermarks: vec![ - common_recordbatch::adapter::RegionWatermarkEntry { - region_id: 41, - watermark: Some(17), - }, - ], - ..Default::default() - }), - error: None, - }; - sender.send(Some(Arc::new(reply.clone()))).unwrap(); - reply - } - common_grpc::flow_write::Admission::Join(receiver) => { - common_grpc::flow_write::wait_completion(receiver) - .await - .unwrap() - .as_ref() - .clone() - } - }; - if call == 0 { - return Err(transport_error("lost Write reply")); - } - response(result) - } - Command::Close { capability } => { - let call = self.closes.fetch_add(1, Ordering::SeqCst); - self.registry.close(&capability).await.unwrap(); - if call == 0 { - return Err(transport_error("lost Close reply")); - } - response(Reply::Closed) - } - } - } - } - - fn request_sql(request: &Request) -> String { - match request { - Request::Query(query) => match query.query.as_ref() { - Some(Query::Sql(sql)) => sql.clone(), - other => panic!("expected SQL INSERT, got {other:?}"), - }, - other => panic!("expected Query request, got {other:?}"), - } - } - - fn assert_empty_sql(request: &Request) { - assert!( - matches!(request, Request::Query(QueryRequest { query: Some(Query::Sql(sql)) }) if sql.is_empty()) - ); - } - - fn transport_error(message: &str) -> BoxedError { - BoxedError::new(PlainError::new( - message.to_string(), - StatusCode::StorageUnavailable, - )) - } - - fn response(reply: Reply) -> Result { - let batches = flow_write::reply_batches(&reply).map_err(BoxedError::new)?; - Ok(Output::new_with_record_batches(batches)) - } - - #[tokio::test] - async fn retries_same_open_write_and_close_capability_and_executes_once() { - let handler = Arc::new(LostReplyHandler::default()); - let trait_handler: Arc = handler.clone(); - let weak = Arc::downgrade(&trait_handler); - let frontend = - FrontendClient::from_grpc_handler(weak, query::options::QueryOptions::default()) - .with_tracked_writes(); - let output = frontend - .tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (7)") - .await - .unwrap(); - assert!(matches!(output.output.data, OutputData::AffectedRows(1))); - assert_eq!(output.output.meta.cost, 9); - assert_eq!( - output.metrics.region_watermark_map(), - Some(HashMap::from([(41, 17)])) - ); - assert_eq!(handler.opens.load(Ordering::SeqCst), 2); - assert_eq!(handler.writes.load(Ordering::SeqCst), 2); - assert_eq!(handler.closes.load(Ordering::SeqCst), 2); - assert_eq!(handler.executions.load(Ordering::SeqCst), 1); - let second = frontend - .tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (8)") - .await - .unwrap(); - assert!(matches!(second.output.data, OutputData::AffectedRows(1))); - assert_eq!(handler.executions.load(Ordering::SeqCst), 2); - } - - /// A legacy frontend that does not understand the tracked-write extension - /// processes `Open` as an ordinary empty-SQL query and rejects it with - /// `InvalidArguments`. That is a definitive application rejection, not an - /// ambiguous transport failure: the client must fail fast instead of - /// retrying the same pinned frontend forever. - #[derive(Debug, Default)] - struct LegacyRejectHandler { - opens: AtomicUsize, - } - - #[async_trait::async_trait] - impl super::super::GrpcQueryHandlerWithBoxedError for LegacyRejectHandler { - async fn do_query( - &self, - _request: Request, - _ctx: QueryContextRef, - ) -> Result { - self.opens.fetch_add(1, Ordering::SeqCst); - Err(BoxedError::new(PlainError::new( - "empty statements".to_string(), - StatusCode::InvalidArguments, - ))) - } - } - - #[derive(Debug)] - struct PreflightHandler { - opens: AtomicUsize, - closes: AtomicUsize, - reject_open: bool, - } - - #[async_trait::async_trait] - impl super::super::GrpcQueryHandlerWithBoxedError for PreflightHandler { - async fn do_query( - &self, - request: Request, - ctx: QueryContextRef, - ) -> Result { - let encoded = ctx.extensions().get(COMMAND_KEY).cloned().unwrap(); - assert_empty_sql(&request); - match Command::decode(&encoded).unwrap() { - Command::Open { .. } => { - self.opens.fetch_add(1, Ordering::SeqCst); - if self.reject_open { - Err(BoxedError::new(PlainError::new( - "preflight rejected".into(), - StatusCode::PermissionDenied, - ))) - } else { - response(Reply::Opened { - capability: "preflight-capability".into(), - }) - } - } - Command::Close { capability } => { - assert_eq!(capability, "preflight-capability"); - self.closes.fetch_add(1, Ordering::SeqCst); - response(Reply::Closed) - } - Command::Write { .. } => panic!("preflight must not write"), - } - } - } - - #[tokio::test] - async fn preflight_opens_and_closes_without_writing() { - let handler = Arc::new(PreflightHandler { - opens: AtomicUsize::default(), - closes: AtomicUsize::default(), - reject_open: false, - }); - let trait_handler: Arc = handler.clone(); - let frontend = FrontendClient::from_grpc_handler( - Arc::downgrade(&trait_handler), - query::options::QueryOptions::default(), - ) - .with_tracked_writes(); - tokio::time::timeout( - Duration::from_secs(10), - frontend.check_tracked_writes("greptime", "public"), - ) - .await - .expect("tracked-write preflight should finish within 10 seconds") - .unwrap(); - assert_eq!(handler.opens.load(Ordering::SeqCst), 1); - assert_eq!(handler.closes.load(Ordering::SeqCst), 1); - } - - #[tokio::test] - async fn preflight_preserves_definitive_open_error() { - let handler = Arc::new(PreflightHandler { - opens: AtomicUsize::default(), - closes: AtomicUsize::default(), - reject_open: true, - }); - let trait_handler: Arc = handler.clone(); - let frontend = FrontendClient::from_grpc_handler( - Arc::downgrade(&trait_handler), - query::options::QueryOptions::default(), - ) - .with_tracked_writes(); - let error = tokio::time::timeout( - Duration::from_secs(10), - frontend.check_tracked_writes("greptime", "public"), - ) - .await - .expect("tracked-write preflight rejection should finish within 10 seconds") - .unwrap_err(); - assert_eq!(error.status_code(), StatusCode::PermissionDenied); - assert!(matches!( - &error, - Error::External { source, .. } - if source.as_any().downcast_ref::().is_some_and(|terminal| { - terminal.code == StatusCode::PermissionDenied as u32 - && terminal.message.contains("preflight rejected") - }) - )); - assert_eq!(handler.opens.load(Ordering::SeqCst), 1); - assert_eq!(handler.closes.load(Ordering::SeqCst), 0); - } - - #[derive(Debug)] - struct RejectionRetryHandler { - status: StatusCode, - opens: AtomicUsize, - writes: AtomicUsize, - closes: AtomicUsize, - capability: std::sync::Mutex>, - } - - #[async_trait::async_trait] - impl super::super::GrpcQueryHandlerWithBoxedError for RejectionRetryHandler { - async fn do_query( - &self, - request: Request, - ctx: QueryContextRef, - ) -> Result { - let encoded = ctx.extensions().get(COMMAND_KEY).cloned().unwrap(); - match Command::decode(&encoded).unwrap() { - Command::Open { nonce } => { - assert_empty_sql(&request); - self.opens.fetch_add(1, Ordering::SeqCst); - let mut capability = self.capability.lock().unwrap(); - let value = capability.get_or_insert_with(|| nonce); - response(Reply::Opened { - capability: value.clone(), - }) - } - Command::Write { capability } => { - assert_eq!(request_sql(&request), "INSERT INTO t VALUES (11)"); - assert_eq!(self.capability.lock().unwrap().as_ref(), Some(&capability)); - if self.writes.fetch_add(1, Ordering::SeqCst) == 0 { - Err(BoxedError::new(PlainError::new( - "write rejection".into(), - self.status, - ))) - } else { - response(Reply::Complete { - rows: 2, - cost: 0, - metrics: None, - error: None, - }) - } - } - Command::Close { capability } => { - assert_empty_sql(&request); - assert_eq!(self.capability.lock().unwrap().as_ref(), Some(&capability)); - if self.closes.fetch_add(1, Ordering::SeqCst) == 0 { - Err(BoxedError::new(PlainError::new( - "close rejection".into(), - self.status, - ))) - } else { - response(Reply::Closed) - } - } - } - } - } - - #[tokio::test] - async fn post_admission_rejections_retry_same_capability_until_close() { - for status in [ - StatusCode::Unsupported, - StatusCode::InvalidArguments, - StatusCode::PermissionDenied, - ] { - let handler = Arc::new(RejectionRetryHandler { - status, - opens: AtomicUsize::default(), - writes: AtomicUsize::default(), - closes: AtomicUsize::default(), - capability: std::sync::Mutex::new(None), - }); - let trait_handler: Arc = - handler.clone(); - let frontend = FrontendClient::from_grpc_handler( - Arc::downgrade(&trait_handler), - query::options::QueryOptions::default(), - ) - .with_tracked_writes(); - let output = tokio::time::timeout( - Duration::from_secs(10), - frontend.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (11)"), - ) - .await - .expect("post-admission retries should finish within 10 seconds") - .unwrap(); - assert!(matches!(output.output.data, OutputData::AffectedRows(2))); - assert_eq!(handler.opens.load(Ordering::SeqCst), 1); - assert_eq!(handler.writes.load(Ordering::SeqCst), 2); - assert_eq!(handler.closes.load(Ordering::SeqCst), 2); - } - } - - #[tokio::test] - async fn fails_fast_on_definitive_open_rejection() { - let handler = Arc::new(LegacyRejectHandler::default()); - let trait_handler: Arc = handler.clone(); - let weak = Arc::downgrade(&trait_handler); - let frontend = - FrontendClient::from_grpc_handler(weak, query::options::QueryOptions::default()) - .with_tracked_writes(); - let result = tokio::time::timeout( - Duration::from_secs(10), - frontend.tracked_sql_write("greptime", "public", "INSERT INTO t VALUES (7)"), - ) - .await - .expect("definitive Open rejection should finish within 10 seconds"); - let err = result.expect_err("definitive Open rejection must not be retried forever"); - assert_eq!(err.status_code(), StatusCode::InvalidArguments); - // The durable-execution layer keys repair off a TerminalError inside - // Error::External; pin that exact shape so a refactor cannot silently - // downgrade the rejection to an unresolved (permanently stalled) error. - assert!( - matches!(&err, Error::External { source, .. } if source.as_any().is::()), - "expected Error::External carrying TerminalError, got {err:?}" - ); - assert_eq!( - handler.opens.load(Ordering::SeqCst), - 1, - "Open must not be retried after a definitive rejection" - ); - } -} diff --git a/src/frontend/Cargo.toml b/src/frontend/Cargo.toml index 1fd347c68e9..0e4a15e5d97 100644 --- a/src/frontend/Cargo.toml +++ b/src/frontend/Cargo.toml @@ -7,8 +7,6 @@ license.workspace = true [features] testing = [] enterprise = [ - "common-grpc/enterprise", - "session/enterprise", "common-meta/enterprise", "operator/enterprise", "sql/enterprise", diff --git a/src/frontend/src/instance.rs b/src/frontend/src/instance.rs index 67f1e6003a0..554a9677af7 100644 --- a/src/frontend/src/instance.rs +++ b/src/frontend/src/instance.rs @@ -17,8 +17,6 @@ mod copy_in; mod dashboard; mod entity_graph; mod export_database; -#[cfg(feature = "enterprise")] -mod flow_write; mod grpc; mod import_packed; mod influxdb; @@ -136,13 +134,6 @@ pub struct Instance { trace_aux_limiter: Option, otlp_resource_info: bool, suspend: Arc, - #[cfg(feature = "enterprise")] - flow_write_registry: Arc< - common_grpc::flow_write::FlowWriteRegistry< - flow_write::WritePayload, - common_grpc::flow_write::Reply, - >, - >, } impl Instance { @@ -332,17 +323,6 @@ impl Instance { timeout_recorder, ); - #[cfg(feature = "enterprise")] - let result = if query_ctx.channel() == Channel::Internal - && query_ctx.extension(common_grpc::flow_write::CHILD_KEY) == Some("1") - { - query_fut.await - } else { - CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) - .await - .map_err(|_| error::CancelledSnafu.build())? - }; - #[cfg(not(feature = "enterprise"))] let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) .await .map_err(|_| error::CancelledSnafu.build())?; @@ -913,17 +893,6 @@ impl Instance { let query_fut = self.exec_plan_with_timeout(plan, query_ctx.clone(), timeout_recorder); - #[cfg(feature = "enterprise")] - let result = if query_ctx.channel() == Channel::Internal - && query_ctx.extension(common_grpc::flow_write::CHILD_KEY) == Some("1") - { - query_fut.await - } else { - CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) - .await - .map_err(|_| error::CancelledSnafu.build())? - }; - #[cfg(not(feature = "enterprise"))] let result = CancellableFuture::new(query_fut, ticket.cancellation_handle.clone()) .await .map_err(|_| error::CancelledSnafu.build())?; diff --git a/src/frontend/src/instance/builder.rs b/src/frontend/src/instance/builder.rs index 732c587e07b..05efd38d28a 100644 --- a/src/frontend/src/instance/builder.rs +++ b/src/frontend/src/instance/builder.rs @@ -438,8 +438,6 @@ impl FrontendBuilder { trace_aux_limiter, otlp_resource_info: self.options.otlp.experimental_enable_resource_info, suspend: Arc::new(AtomicBool::new(false)), - #[cfg(feature = "enterprise")] - flow_write_registry: Default::default(), }) } } diff --git a/src/frontend/src/instance/flow_write.rs b/src/frontend/src/instance/flow_write.rs deleted file mode 100644 index f908d438d4e..00000000000 --- a/src/frontend/src/instance/flow_write.rs +++ /dev/null @@ -1,227 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -use std::sync::Arc; - -use api::v1::{greptime_request::Request, query_request::Query}; -use common_error::ext::ErrorExt; -use common_grpc::flow_write::{ - Admission, CHILD_KEY, COMMAND_KEY, Command, Reply, TerminalError, wait_completion, -}; -use common_query::{Output, OutputData}; -use servers::error::{self as server_error, Error as ServerError}; -use servers::interceptor::GrpcQueryInterceptor; -use servers::query_handler::grpc::GrpcQueryHandler; -use session::context::QueryContextRef; - -use crate::instance::Instance; - -#[derive(Clone, Debug, PartialEq)] -pub(crate) struct WritePayload { - request: Request, - catalog: String, - schema: String, - snapshots: Vec<(u64, u64)>, - sst_min_sequences: Vec<(u64, u64)>, - extensions: Vec<(String, String)>, -} - -impl WritePayload { - fn new(request: &Request, ctx: &QueryContextRef) -> Result { - if !is_finite_insert(request) { - return Err("tracked flow writes require INSERT or InsertIntoPlan".to_string()); - } - let mut snapshots: Vec<_> = ctx.snapshots().into_iter().collect(); - snapshots.sort_unstable(); - let mut sst_min_sequences: Vec<_> = ctx.sst_min_sequences().into_iter().collect(); - sst_min_sequences.sort_unstable(); - let mut extensions: Vec<_> = ctx - .extensions() - .into_iter() - .filter(|(key, _)| { - key != COMMAND_KEY - && key != CHILD_KEY - && key != session::context::REMOTE_QUERY_ID_EXTENSION_KEY - }) - .collect(); - extensions.sort_unstable(); - Ok(Self { - request: request.clone(), - catalog: ctx.current_catalog().to_string(), - schema: ctx.current_schema(), - snapshots, - sst_min_sequences, - extensions, - }) - } -} - -fn is_finite_insert(request: &Request) -> bool { - match request { - Request::Query(query) => match query.query.as_ref() { - Some(Query::InsertIntoPlan(_)) => true, - Some(Query::Sql(sql)) => sql.split_whitespace().next().is_some_and(|statement| { - statement - .trim_end_matches(';') - .eq_ignore_ascii_case("INSERT") - }), - _ => false, - }, - _ => false, - } -} - -impl Instance { - fn intercept_control( - &self, - request: &Request, - ctx: &QueryContextRef, - ) -> server_error::Result<()> { - let interceptor = self - .plugins - .get::>(); - interceptor - .as_ref() - .pre_execute(request, ctx.clone()) - .map_err(|error| ServerError::ExecuteQuery { - source: common_error::ext::BoxedError::new(error), - location: snafu::Location::new(file!(), line!(), column!()), - }) - } - - pub(crate) async fn handle_flow_write_request( - &self, - request: Request, - ctx: QueryContextRef, - encoded_command: String, - ) -> server_error::Result { - let command = Command::decode(&encoded_command).map_err(|e| ServerError::InvalidQuery { - reason: e.to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - })?; - let reply = match command { - Command::Open { nonce } => { - self.intercept_control(&request, &ctx)?; - if !is_empty_control(&request) { - return Err(ServerError::InvalidQuery { - reason: "Open requires an empty SQL request".into(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - Reply::Opened { - capability: self - .flow_write_registry - .open(&nonce) - .map_err(registry_error)?, - } - } - Command::Close { capability } => { - self.intercept_control(&request, &ctx)?; - if !is_empty_control(&request) { - return Err(ServerError::InvalidQuery { - reason: "Close requires an empty SQL request".into(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - self.flow_write_registry - .close(&capability) - .await - .map_err(registry_error)?; - Reply::Closed - } - Command::Write { capability } => { - let payload = WritePayload::new(&request, &ctx).map_err(|reason| { - ServerError::InvalidQuery { - reason, - location: snafu::Location::new(file!(), line!(), column!()), - } - })?; - match self - .flow_write_registry - .admit(&capability, payload) - .map_err(registry_error)? - { - Admission::Join(receiver) => { - (*wait_completion(receiver).await.map_err(registry_error)?).clone() - } - Admission::Start(sender) => { - let receiver = sender.subscribe(); - let instance = self.clone(); - let mut child_ctx = (*ctx).clone(); - child_ctx.remove_extension(COMMAND_KEY); - child_ctx.set_extension(CHILD_KEY, "1"); - let child_ctx = Arc::new(child_ctx); - common_runtime::spawn_global(async move { - let terminal = match instance.do_query(request, child_ctx).await { - Ok(output) => terminal_reply(output), - Err(error) => Reply::Complete { - rows: 0, - cost: 0, - metrics: None, - error: Some(TerminalError { - code: error.status_code() as u32, - message: error.output_msg(), - }), - }, - }; - let _ = sender.send(Some(Arc::new(terminal))); - }); - (*wait_completion(receiver).await.map_err(registry_error)?).clone() - } - } - } - }; - let batches = common_grpc::flow_write::reply_batches(&reply).map_err(|e| { - ServerError::InvalidQuery { - reason: e.to_string(), - location: snafu::Location::new(file!(), line!(), column!()), - } - })?; - Ok(Output::new_with_record_batches(batches)) - } -} - -fn is_empty_control(request: &Request) -> bool { - matches!(request, Request::Query(query) if matches!(&query.query, Some(Query::Sql(sql)) if sql.trim().is_empty())) -} - -fn terminal_reply(output: Output) -> Reply { - let (rows, cost) = output.extract_rows_and_cost(); - let metrics = output - .meta - .plan - .clone() - .and_then(query::metrics::terminal_recordbatch_metrics_from_plan); - match output.data { - OutputData::AffectedRows(_) => Reply::Complete { - rows, - cost, - metrics, - error: None, - }, - _ => Reply::Complete { - rows: 0, - cost, - metrics, - error: Some(TerminalError { - code: 1001, - message: "tracked INSERT did not produce finite affected rows".into(), - }), - }, - } -} - -fn registry_error(error: common_grpc::flow_write::RegistryError) -> ServerError { - ServerError::InvalidQuery { - reason: format!("flow write capability rejected: {error:?}"), - location: snafu::Location::new(file!(), line!(), column!()), - } -} diff --git a/src/frontend/src/instance/grpc.rs b/src/frontend/src/instance/grpc.rs index 3fb8a6feef8..7dfd97cd69d 100644 --- a/src/frontend/src/instance/grpc.rs +++ b/src/frontend/src/instance/grpc.rs @@ -66,20 +66,6 @@ impl GrpcQueryHandler for Instance { request: Request, ctx: QueryContextRef, ) -> server_error::Result { - #[cfg(feature = "enterprise")] - if let Some(command) = ctx - .extension(common_grpc::flow_write::COMMAND_KEY) - .map(str::to_string) - { - if ctx.channel() != session::context::Channel::Internal { - return Err(server_error::Error::InvalidQuery { - reason: "flow write commands are only accepted on the internal channel".into(), - location: snafu::Location::new(file!(), line!(), column!()), - }); - } - return self.handle_flow_write_request(request, ctx, command).await; - } - let result: Result = async { let interceptor_ref = self.plugins.get::>(); let interceptor = interceptor_ref.as_ref(); diff --git a/src/operator/Cargo.toml b/src/operator/Cargo.toml index 225f1bb6dec..b89bf4b13d3 100644 --- a/src/operator/Cargo.toml +++ b/src/operator/Cargo.toml @@ -7,7 +7,6 @@ license.workspace = true [features] testing = [] enterprise = [ - "common-grpc/enterprise", "common-meta/enterprise", "sql/enterprise", "query/enterprise", diff --git a/src/operator/src/insert.rs b/src/operator/src/insert.rs index 9a0cd64a828..88cb565c779 100644 --- a/src/operator/src/insert.rs +++ b/src/operator/src/insert.rs @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -#[cfg(feature = "enterprise")] -mod flow_write; mod otlp; pub use otlp::MetricInsertPreflight; @@ -857,47 +855,6 @@ impl Inserter { has_instant_rows, )?; - // Tracked Flow children use a same-capability write protocol. Keep the - // ordinary dispatch path unchanged for every other request. - #[cfg(feature = "enterprise")] - if flow_write::is_child(ctx) { - let dispatcher = self.write_dispatcher.clone(); - let request = request_factory.build_insert(normal_requests); - let writes = dispatcher.prepare(vec![request]).await?; - let tracked_tasks = writes.into_iter().map(|(peer, mut request)| { - let mut query_context = crate::utils::to_meta_query_context(ctx.clone()); - query_context.extensions.insert( - common_grpc::flow_write::CHILD_KEY.to_string(), - "1".to_string(), - ); - if let Some(header) = request.header.as_mut() { - header.query_context = Some(query_context.into()); - } - let node_manager = self.node_manager.clone(); - async move { flow_write::dispatch(&node_manager, &peer, request).await } - }); - let results = future::join_all(tracked_tasks).await; - let mut affected_rows = 0; - let mut first_error = None; - for result in results { - match result { - Ok(response) => affected_rows += response.affected_rows, - Err(error) if first_error.is_none() => first_error = Some(error), - Err(_) => {} - } - } - if let Some(error) = first_error { - return Err(error); - } - crate::metrics::DIST_INGEST_ROW_COUNT - .with_label_values(&[ctx.get_db_string().as_str()]) - .inc_by(affected_rows as u64); - return Ok(Output::new( - OutputData::AffectedRows(affected_rows), - OutputMeta::new_with_cost(write_cost as _), - )); - } - let dispatcher = self.write_dispatcher.clone(); let request = request_factory.build_insert(normal_requests); let writes = dispatcher.prepare(vec![request]).await?; diff --git a/src/operator/src/insert/flow_write.rs b/src/operator/src/insert/flow_write.rs deleted file mode 100644 index 62935e46981..00000000000 --- a/src/operator/src/insert/flow_write.rs +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright 2023-2026 GrepTime Inc. -// -// This file is part of the GreptimeDB Enterprise Edition and is licensed under -// the GreptimeDB Enterprise License. You may not use this file except in -// compliance with that license. A copy of the license is available at the root -// of this repository in the file LICENSE-ENTERPRISE. -// -// Unless required by applicable law or agreed to in writing, this software is -// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, -// either express or implied. - -use std::time::Duration; - -use api::v1::region::RegionRequest; -use common_error::ext::BoxedError; -use common_grpc::flow_write::{self, Command, Reply}; -use common_meta::node_manager::{DatanodeRef, NodeManagerRef}; -use common_meta::peer::Peer; -use session::context::generate_remote_query_id; - -use crate::error::{Error, Result}; - -const RETRY_DELAY: Duration = Duration::from_secs(1); - -fn error(message: impl Into) -> Error { - Error::Unexpected { - violated: message.into(), - location: snafu::Location::new(file!(), line!(), column!()), - } -} - -fn command_request( - request: &RegionRequest, - command: &Command, - control: bool, -) -> Result { - let mut request = request.clone(); - if control { - request.body = Some(api::v1::region::region_request::Body::Inserts( - Default::default(), - )); - } - let header = request.header.get_or_insert_with(Default::default); - let query_context = header - .query_context - .get_or_insert_with(api::v1::QueryContext::default); - query_context.extensions.insert( - flow_write::COMMAND_KEY.to_string(), - command.encode().map_err(|e| error(e.to_string()))?, - ); - Ok(request) -} - -fn reply(response: &api::region::RegionResponse) -> Option { - response - .extensions - .get(flow_write::COMMAND_KEY) - .and_then(|value| std::str::from_utf8(value).ok()) - .and_then(|value| serde_json::from_str(value).ok()) -} - -pub(crate) async fn dispatch( - node_manager: &NodeManagerRef, - peer: &Peer, - request: RegionRequest, -) -> Result { - dispatch_datanode(node_manager.datanode(peer).await, request).await -} - -async fn dispatch_datanode( - datanode: DatanodeRef, - request: RegionRequest, -) -> Result { - let nonce = generate_remote_query_id(); - let open = command_request(&request, &Command::Open { nonce }, true)?; - let capability = loop { - match datanode.handle(open.clone()).await { - Ok(response) => match reply(&response) { - Some(Reply::Opened { capability }) if !capability.is_empty() => break capability, - _ => return Err(error("Datanode does not support tracked Flow writes")), - }, - Err(_) => tokio::time::sleep(RETRY_DELAY).await, - } - }; - - let write = command_request( - &request, - &Command::Write { - capability: capability.clone(), - }, - false, - )?; - let complete = loop { - match datanode.handle(write.clone()).await { - Ok(response) => match reply(&response) { - Some(Reply::Complete { - rows, - cost: _, - metrics: _, - error, - }) => break (response, rows, error), - _ => tokio::time::sleep(RETRY_DELAY).await, - }, - Err(_) => tokio::time::sleep(RETRY_DELAY).await, - } - }; - - let close = command_request( - &request, - &Command::Close { - capability: capability.clone(), - }, - true, - )?; - loop { - match datanode.handle(close.clone()).await { - Ok(response) if matches!(reply(&response), Some(Reply::Closed)) => break, - _ => tokio::time::sleep(RETRY_DELAY).await, - } - } - - let (mut response, rows, terminal_error) = complete; - if let Some(terminal_error) = terminal_error { - return Err(Error::External { - source: BoxedError::new(terminal_error), - location: snafu::location!(), - }); - } - response.affected_rows = rows as _; - Ok(response) -} - -pub(crate) fn is_child(ctx: &session::context::QueryContextRef) -> bool { - ctx.channel() == common_base::protocol::Channel::Internal - && ctx.extension(flow_write::CHILD_KEY) == Some("1") -} - -#[cfg(test)] -mod tests { - use std::collections::HashMap; - use std::sync::atomic::{AtomicUsize, Ordering}; - use std::sync::{Arc, Mutex}; - - use api::region::RegionResponse; - use api::v1::region::{RegionRequest, region_request::Body}; - use common_error::ext::BoxedError; - use common_error::ext::ErrorExt; - use common_grpc::flow_write::{self, Command, Reply}; - use common_meta::node_manager::{Datanode, DatanodeRef}; - use common_query::request::QueryRequest; - use common_recordbatch::SendableRecordBatchStream; - use futures_util::future::join_all; - use tokio::sync::Notify; - - use super::dispatch_datanode; - - #[derive(Default)] - struct MockDatanode { - capabilities: Mutex>, - business_write_attempts: AtomicUsize, - write_commands: Mutex>, - requests: Mutex>, - drop_open_reply: AtomicUsize, - drop_write_reply: AtomicUsize, - drop_close_reply: AtomicUsize, - latch_write: bool, - terminal_error: bool, - write_started: Notify, - release_write: Notify, - close_started: Notify, - } - - impl MockDatanode { - fn response(reply: Reply) -> RegionResponse { - let mut response = RegionResponse::new(0); - response.extensions.insert( - flow_write::COMMAND_KEY.to_string(), - serde_json::to_vec(&reply).unwrap(), - ); - response - } - - fn command(request: &RegionRequest) -> Command { - let serialized = request - .header - .as_ref() - .and_then(|header| header.query_context.as_ref()) - .and_then(|context| context.extensions.get(flow_write::COMMAND_KEY)) - .unwrap(); - Command::decode(serialized).unwrap() - } - } - - #[async_trait::async_trait] - impl Datanode for MockDatanode { - async fn handle_request( - &self, - request: Arc, - ) -> common_meta::error::Result { - self.requests.lock().unwrap().push(request.as_ref().clone()); - match Self::command(&request) { - Command::Open { nonce } => { - if !matches!(request.body, Some(Body::Inserts(ref inserts)) if inserts.requests.is_empty()) - { - return Err(common_meta::error::Error::External { - source: BoxedError::new(common_error::mock::MockError::new( - common_error::status_code::StatusCode::InvalidArguments, - )), - location: snafu::location!(), - }); - } - let mut capabilities = self.capabilities.lock().unwrap(); - let capability = capabilities - .entry(nonce) - .or_insert_with(|| "cap-1".into()) - .clone(); - if self - .drop_open_reply - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) - .is_ok() - { - return Err(common_meta::error::Error::External { - source: BoxedError::new(common_error::mock::MockError::new( - common_error::status_code::StatusCode::TableUnavailable, - )), - location: snafu::location!(), - }); - } - Ok(Self::response(Reply::Opened { capability })) - } - Command::Write { capability } => { - self.write_commands.lock().unwrap().push(capability.clone()); - if matches!(request.body, Some(Body::Inserts(ref inserts)) if !inserts.requests.is_empty()) - && self.business_write_attempts.fetch_add(1, Ordering::SeqCst) == 0 - && self.latch_write - { - self.write_started.notify_one(); - self.release_write.notified().await; - } - if self - .drop_write_reply - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) - .is_ok() - { - return Err(common_meta::error::Error::External { - source: BoxedError::new(common_error::mock::MockError::new( - common_error::status_code::StatusCode::TableUnavailable, - )), - location: snafu::location!(), - }); - } - Ok(Self::response(Reply::Complete { - rows: 7, - cost: 0, - metrics: None, - error: self.terminal_error.then(|| flow_write::TerminalError { - code: common_error::status_code::StatusCode::TableNotFound as u32, - message: "terminal child error".to_string(), - }), - })) - } - Command::Close { .. } => { - self.close_started.notify_one(); - if self - .drop_close_reply - .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)) - .is_ok() - { - return Err(common_meta::error::Error::External { - source: BoxedError::new(common_error::mock::MockError::new( - common_error::status_code::StatusCode::TableUnavailable, - )), - location: snafu::location!(), - }); - } - Ok(Self::response(Reply::Closed)) - } - } - } - - async fn handle_query( - &self, - _: QueryRequest, - ) -> common_meta::error::Result { - unreachable!() - } - } - - fn request() -> RegionRequest { - RegionRequest { - header: None, - body: Some(Body::Inserts(api::v1::region::InsertRequests { - requests: vec![Default::default()], - })), - } - } - - #[tokio::test] - async fn lost_control_and_write_replies_reuse_capability_and_exact_request() { - let datanode = Arc::new(MockDatanode::default()); - datanode.drop_open_reply.store(1, Ordering::SeqCst); - datanode.drop_write_reply.store(1, Ordering::SeqCst); - datanode.drop_close_reply.store(1, Ordering::SeqCst); - let response = dispatch_datanode(datanode.clone(), request()) - .await - .unwrap(); - assert_eq!(response.affected_rows, 7); - assert_eq!(datanode.business_write_attempts.load(Ordering::SeqCst), 2); - let writes = datanode.write_commands.lock().unwrap(); - assert_eq!(writes.len(), 2); - assert!(writes.iter().all(|capability| capability == "cap-1")); - let requests = datanode.requests.lock().unwrap(); - let writes: Vec<_> = requests - .iter() - .filter(|request| matches!(MockDatanode::command(request), Command::Write { .. })) - .collect(); - assert_eq!(writes.len(), 2); - assert_eq!(writes[0].body, writes[1].body); - assert_eq!(writes[0].header, writes[1].header); - assert_eq!( - requests - .iter() - .filter(|request| matches!( - MockDatanode::command(request), - Command::Open { .. } | Command::Close { .. } - )) - .count(), - 4 - ); - assert!(requests - .iter() - .filter(|request| matches!(MockDatanode::command(request), Command::Open { .. } | Command::Close { .. })) - .all(|request| matches!(request.body, Some(Body::Inserts(ref inserts)) if inserts.requests.is_empty()))); - } - - #[tokio::test] - async fn unsupported_open_never_submits_business_request() { - struct Unsupported; - #[async_trait::async_trait] - impl Datanode for Unsupported { - async fn handle_request( - &self, - _: Arc, - ) -> common_meta::error::Result { - Ok(RegionResponse::new(0)) - } - async fn handle_query( - &self, - _: QueryRequest, - ) -> common_meta::error::Result { - unreachable!() - } - } - let datanode: DatanodeRef = Arc::new(Unsupported); - let error = dispatch_datanode(datanode, request()).await.unwrap_err(); - assert_eq!( - error.status_code(), - common_error::status_code::StatusCode::Unexpected - ); - } - - #[tokio::test] - async fn all_peer_writes_drain_before_terminal_error_returns() { - let failing = Arc::new(MockDatanode { - terminal_error: true, - ..Default::default() - }); - let latched = Arc::new(MockDatanode { - latch_write: true, - ..Default::default() - }); - let first_datanode: DatanodeRef = failing.clone(); - let second_datanode: DatanodeRef = latched.clone(); - let aggregate = tokio::spawn(async move { - join_all([ - dispatch_datanode(first_datanode, request()), - dispatch_datanode(second_datanode, request()), - ]) - .await - }); - latched.write_started.notified().await; - failing.close_started.notified().await; - assert!(!aggregate.is_finished()); - latched.release_write.notify_one(); - let results = aggregate.await.unwrap(); - assert_eq!(results.len(), 2); - assert_eq!(failing.business_write_attempts.load(Ordering::SeqCst), 1); - assert_eq!(latched.business_write_attempts.load(Ordering::SeqCst), 1); - assert!(results.into_iter().any(|result| result.is_err())); - } -} diff --git a/src/session/Cargo.toml b/src/session/Cargo.toml index 630d0713a62..93c46ff7ff7 100644 --- a/src/session/Cargo.toml +++ b/src/session/Cargo.toml @@ -4,9 +4,6 @@ version.workspace = true edition.workspace = true license.workspace = true -[features] -enterprise = [] - [lints] workspace = true diff --git a/src/session/src/context.rs b/src/session/src/context.rs index f46a2a590b2..02ee621e0e4 100644 --- a/src/session/src/context.rs +++ b/src/session/src/context.rs @@ -467,11 +467,6 @@ impl QueryContext { self.extensions.insert(key.into(), value.into()); } - #[cfg(feature = "enterprise")] - pub fn remove_extension(&mut self, key: &str) { - self.extensions.remove(key); - } - pub fn extension>(&self, key: S) -> Option<&str> { self.extensions.get(key.as_ref()).map(|v| v.as_str()) } From 4135e65a76cf7e9d832cd00b0ff7415e971ef478 Mon Sep 17 00:00:00 2001 From: discord9 Date: Wed, 28 Oct 2026 10:40:43 +0000 Subject: [PATCH 2/7] fix(query): keep requested sort when filtering on a lossy cast (#10026) fix(query): pin DataFusion cast constraint propagation fix Update the pinned GreptimeTeam/datafusion revision from e3221b8 to cc55344 (the 55.1 fork carrying apache/datafusion#25531 plus a stronger regression test). CastExpr::propagate_constraints used to cast a filter's output interval straight back to the input type. For CAST(k AS BIGINT) = 1 the singleton output [1, 1] was inverted to [1.0, 1.0] although k = 1.5 matches too, so FilterExec advertised k as constant, the equivalence classes dropped the ordering required by ORDER BY k, and rows returned in scan order. The sqlness case keeps every #9600 assertion and the explicit ORDER BY, and adds ascending and descending checks for the partitioned table, the control table and a table whose matching rows are stored in neither ascending nor descending k order. Cargo.lock only rewrites the 35 datafusion source lines. Signed-off-by: discord9 --- Cargo.lock | 70 +++++++++--------- Cargo.toml | 32 ++++---- .../optimizer/partition_pruning_cast.result | 74 +++++++++++++++++++ .../optimizer/partition_pruning_cast.sql | 36 +++++++++ 4 files changed, 161 insertions(+), 51 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6ada3b0a295..69996d9cbb2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3756,7 +3756,7 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8" [[package]] name = "datafusion" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -3808,7 +3808,7 @@ dependencies = [ [[package]] name = "datafusion-catalog" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3832,7 +3832,7 @@ dependencies = [ [[package]] name = "datafusion-catalog-listing" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3855,7 +3855,7 @@ dependencies = [ [[package]] name = "datafusion-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-ipc 59.2.0", @@ -3881,7 +3881,7 @@ dependencies = [ [[package]] name = "datafusion-common-runtime" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "futures", "log", @@ -3891,7 +3891,7 @@ dependencies = [ [[package]] name = "datafusion-datasource" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-compression", @@ -3927,7 +3927,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-arrow" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-ipc 59.2.0", @@ -3951,7 +3951,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-csv" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3974,7 +3974,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-json" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -3997,7 +3997,7 @@ dependencies = [ [[package]] name = "datafusion-datasource-parquet" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4029,12 +4029,12 @@ dependencies = [ [[package]] name = "datafusion-doc" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" [[package]] name = "datafusion-execution" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-buffer 59.2.0", @@ -4059,7 +4059,7 @@ dependencies = [ [[package]] name = "datafusion-expr" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4083,7 +4083,7 @@ dependencies = [ [[package]] name = "datafusion-expr-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4094,7 +4094,7 @@ dependencies = [ [[package]] name = "datafusion-functions" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-buffer 59.2.0", @@ -4125,7 +4125,7 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4145,7 +4145,7 @@ dependencies = [ [[package]] name = "datafusion-functions-aggregate-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4156,7 +4156,7 @@ dependencies = [ [[package]] name = "datafusion-functions-nested" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-ord 59.2.0", @@ -4180,7 +4180,7 @@ dependencies = [ [[package]] name = "datafusion-functions-table" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "async-trait", @@ -4195,7 +4195,7 @@ dependencies = [ [[package]] name = "datafusion-functions-window" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4211,7 +4211,7 @@ dependencies = [ [[package]] name = "datafusion-functions-window-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "datafusion-common", "datafusion-physical-expr-common", @@ -4220,7 +4220,7 @@ dependencies = [ [[package]] name = "datafusion-macros" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "datafusion-doc", "quote", @@ -4230,7 +4230,7 @@ dependencies = [ [[package]] name = "datafusion-optimizer" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "chrono", @@ -4278,7 +4278,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-schema 59.2.0", @@ -4301,7 +4301,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-adapter" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4315,7 +4315,7 @@ dependencies = [ [[package]] name = "datafusion-physical-expr-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "chrono", @@ -4332,7 +4332,7 @@ dependencies = [ [[package]] name = "datafusion-physical-optimizer" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4351,7 +4351,7 @@ dependencies = [ [[package]] name = "datafusion-physical-plan" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "arrow-data 59.2.0", @@ -4388,7 +4388,7 @@ dependencies = [ [[package]] name = "datafusion-proto" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-catalog", @@ -4414,7 +4414,7 @@ dependencies = [ [[package]] name = "datafusion-proto-common" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4424,7 +4424,7 @@ dependencies = [ [[package]] name = "datafusion-proto-models" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "datafusion-common", "datafusion-proto-common", @@ -4434,7 +4434,7 @@ dependencies = [ [[package]] name = "datafusion-pruning" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "datafusion-common", @@ -4449,7 +4449,7 @@ dependencies = [ [[package]] name = "datafusion-session" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow-schema 59.2.0", "async-trait", @@ -4463,7 +4463,7 @@ dependencies = [ [[package]] name = "datafusion-sql" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "arrow 59.2.0", "bigdecimal 0.4.8", @@ -4482,7 +4482,7 @@ dependencies = [ [[package]] name = "datafusion-substrait" version = "55.1.0" -source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=e3221b8f74b15c7192621576e5d1e354a6cf097a#e3221b8f74b15c7192621576e5d1e354a6cf097a" +source = "git+https://github.com/GreptimeTeam/datafusion.git?rev=cc5534492d5408831395609cdafb6520c7d514b7#cc5534492d5408831395609cdafb6520c7d514b7" dependencies = [ "async-recursion", "async-trait", diff --git a/Cargo.toml b/Cargo.toml index 0e75ddbd912..15539abb2c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -367,22 +367,22 @@ rev = "f743c3a5fe8c1f57363eac5866c356b7d91f9b39" [patch.crates-io] substrait = { git = "https://github.com/GreptimeTeam/substrait-rs.git", rev = "91ec978b0649417ad3da8390e7a515baec723b1b" } -datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } -datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "e3221b8f74b15c7192621576e5d1e354a6cf097a" } +datafusion = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-datasource = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-execution = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-functions = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-functions-aggregate-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-functions-window-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-optimizer = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-physical-expr = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-physical-expr-common = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-physical-plan = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-proto = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-sql = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } +datafusion-substrait = { git = "https://github.com/GreptimeTeam/datafusion.git", rev = "cc5534492d5408831395609cdafb6520c7d514b7" } datafusion-pg-catalog = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" } arrow-pg = { git = "https://github.com/datafusion-contrib/datafusion-postgres.git", rev = "3ae0a6cb30b1c5131687f4637247ff4f84ac11e4" } sqlparser = { git = "https://github.com/GreptimeTeam/sqlparser-rs.git", rev = "9e9019bb1c7040ed956f654e39378dd42ab17884" } diff --git a/tests/cases/distributed/optimizer/partition_pruning_cast.result b/tests/cases/distributed/optimizer/partition_pruning_cast.result index 2b18475fda8..2fda5e7a12a 100644 --- a/tests/cases/distributed/optimizer/partition_pruning_cast.result +++ b/tests/cases/distributed/optimizer/partition_pruning_cast.result @@ -97,6 +97,80 @@ ORDER BY k; | 1970-01-01T00:00:01 | 1.5 | 15 | 1 | +---------------------+-----+----+--------+ +-- The same rows must also come back in descending order: a filter on a lossy +-- cast must not turn `k` into a constant and drop the requested sort. +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_partitioned +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + ++---------------------+-----+----+--------+ +| ts | k | v | cast_k | ++---------------------+-----+----+--------+ +| 1970-01-01T00:00:01 | 1.5 | 15 | 1 | +| 1970-01-01T00:00:01 | 1.0 | 10 | 1 | ++---------------------+-----+----+--------+ + +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_control +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + ++---------------------+-----+----+--------+ +| ts | k | v | cast_k | ++---------------------+-----+----+--------+ +| 1970-01-01T00:00:01 | 1.5 | 15 | 1 | +| 1970-01-01T00:00:01 | 1.0 | 10 | 1 | ++---------------------+-----+----+--------+ + +-- A table whose matching rows are stored in neither ascending nor descending +-- order, so a dropped sort cannot accidentally satisfy the ASC assertion. +CREATE TABLE partition_pruning_cast_unsorted ( + ts TIMESTAMP TIME INDEX, + k FLOAT PRIMARY KEY, + v BIGINT, +); + +Affected Rows: 0 + +INSERT INTO partition_pruning_cast_unsorted VALUES + (1000, 1.5, 15), + (1000, 2.5, 25), + (1000, 1.0, 10), + (1000, 1.25, 12); + +Affected Rows: 4 + +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_unsorted +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k; + ++---------------------+------+----+--------+ +| ts | k | v | cast_k | ++---------------------+------+----+--------+ +| 1970-01-01T00:00:01 | 1.0 | 10 | 1 | +| 1970-01-01T00:00:01 | 1.25 | 12 | 1 | +| 1970-01-01T00:00:01 | 1.5 | 15 | 1 | ++---------------------+------+----+--------+ + +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_unsorted +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + ++---------------------+------+----+--------+ +| ts | k | v | cast_k | ++---------------------+------+----+--------+ +| 1970-01-01T00:00:01 | 1.5 | 15 | 1 | +| 1970-01-01T00:00:01 | 1.25 | 12 | 1 | +| 1970-01-01T00:00:01 | 1.0 | 10 | 1 | ++---------------------+------+----+--------+ + +DROP TABLE partition_pruning_cast_unsorted; + +Affected Rows: 0 + -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED diff --git a/tests/cases/distributed/optimizer/partition_pruning_cast.sql b/tests/cases/distributed/optimizer/partition_pruning_cast.sql index 058045f733a..f72355b892d 100644 --- a/tests/cases/distributed/optimizer/partition_pruning_cast.sql +++ b/tests/cases/distributed/optimizer/partition_pruning_cast.sql @@ -43,6 +43,42 @@ FROM partition_pruning_cast_control WHERE CAST(k AS BIGINT) = 1 ORDER BY k; +-- The same rows must also come back in descending order: a filter on a lossy +-- cast must not turn `k` into a constant and drop the requested sort. +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_partitioned +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_control +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + +-- A table whose matching rows are stored in neither ascending nor descending +-- order, so a dropped sort cannot accidentally satisfy the ASC assertion. +CREATE TABLE partition_pruning_cast_unsorted ( + ts TIMESTAMP TIME INDEX, + k FLOAT PRIMARY KEY, + v BIGINT, +); + +INSERT INTO partition_pruning_cast_unsorted VALUES + (1000, 1.5, 15), + (1000, 2.5, 25), + (1000, 1.0, 10), + (1000, 1.25, 12); + +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_unsorted +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k; +SELECT ts, k, v, CAST(k AS BIGINT) AS cast_k +FROM partition_pruning_cast_unsorted +WHERE CAST(k AS BIGINT) = 1 +ORDER BY k DESC; + +DROP TABLE partition_pruning_cast_unsorted; + -- SQLNESS REPLACE (-+) - -- SQLNESS REPLACE (\s\s+) _ -- SQLNESS REPLACE (elapsed_compute.*) REDACTED From c818b6ac2a290a4b40802b959d8d687fdfa6efed Mon Sep 17 00:00:00 2001 From: Ning Sun Date: Wed, 28 Oct 2026 08:00:41 +0000 Subject: [PATCH 3/7] feat(postgres): influxdb line protocol ingest via COPY FROM STDIN (#9982) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(postgres): influxdb line protocol ingest via COPY FROM STDIN COPY FROM STDIN WITH (FORMAT influxdb [, precision 'ns']) ingests InfluxDB line protocol over the postgres wire protocol, reusing the HTTP ingestion pipeline wholesale for correctness and performance parity: the whole payload is buffered and completed once at CopyDone through the frontend's InfluxdbLineProtocolHandler::exec — conversion, permissions, line-protocol interceptors, timestamp alignment to table time-index units, merge mode and inserts are the same path an HTTP write of the same bytes takes, under the connection's regular postgres query context. Formats are an explicit, closed enum (CopyFormat::Csv | CopyFormat::Influxdb(options)); each variant states its own rules in the copy lifecycle's match arms — csv requires a target table and parses incrementally, influxdb forbids one (each line names its own measurement) and buffers one bounded request body. The COPY layer owns only the buffering: record boundaries, including newlines inside quoted field values and after escapes, belong to the line-protocol parser alone — one COPY statement is one bounded ingestion request (64 MiB; larger imports are multiple COPY statements). - Wiring: PostgresServer::with_influxdb_handler attaches the shared line-protocol handler; unwired servers reject the format when a copy starts. - Grammar: COPY FROM STDIN without a table is scanned (an unquoted FROM cannot be a table name); table-bound formats reject it with guidance, influxdb rejects a named table. - Options: precision accepts the HTTP endpoint's values via the shared parse_time_precision (moved to servers::influxdb), defaulting to nanoseconds. Review findings (fengjiachun) are fixed at the root by removing the pre-splitter rather than repairing it: the retired naive line splitter broke quoted multiline records at chunk/flush boundaries (found by removing record splitting entirely), drained the buffer quadratically (found by append-only buffering), and capped nothing (found by an explicit payload limit). e2e: multi-measurement ingest with chunked feeds; a 32,768-physical-line flush-threshold regression with a multiline quoted record split across CopyData chunks; precision 'ms' epoch verification; invalid UTF-8 and trailing-record-without-newline handling; payload limit; table-named rejection; malformed-line abort with connection recovery. Signed-off-by: Ning Sun * chore: typo --------- Signed-off-by: Ning Sun --- src/frontend/src/server.rs | 1 + src/servers/src/http/influxdb.rs | 23 +- src/servers/src/influxdb.rs | 23 +- src/servers/src/postgres.rs | 10 +- src/servers/src/postgres/copy_in/codec.rs | 118 +++---- src/servers/src/postgres/copy_in/csv.rs | 52 ++- src/servers/src/postgres/copy_in/influxdb.rs | 95 ++++++ src/servers/src/postgres/copy_in/mod.rs | 305 +++++++++++++----- src/servers/src/postgres/copy_in/parse.rs | 73 ++++- src/servers/src/postgres/server.rs | 27 +- tests-integration/src/test_util.rs | 69 ++-- .../src/tests/postgres_copy_in_test.rs | 300 +++++++++++++++++ 12 files changed, 851 insertions(+), 245 deletions(-) create mode 100644 src/servers/src/postgres/copy_in/influxdb.rs diff --git a/src/frontend/src/server.rs b/src/frontend/src/server.rs index 0b1e2b9713e..d84f01fce95 100644 --- a/src/frontend/src/server.rs +++ b/src/frontend/src/server.rs @@ -429,6 +429,7 @@ where user_provider.clone(), Some(self.instance.process_manager().clone()), ) + .with_influxdb_handler(instance.clone()) .with_batching_enabled(postgres_batching), ) as Box; diff --git a/src/servers/src/http/influxdb.rs b/src/servers/src/http/influxdb.rs index 671beb7bae2..44815cae3a1 100644 --- a/src/servers/src/http/influxdb.rs +++ b/src/servers/src/http/influxdb.rs @@ -24,7 +24,7 @@ use common_grpc::precision::Precision; use common_telemetry::tracing; use session::context::{Channel, QueryContext, QueryContextRef}; -use crate::error::{Result, TimePrecisionSnafu}; +use crate::error::Result; use crate::http::header::write_cost_header_map; use crate::influxdb::InfluxdbRequest; use crate::query_handler::InfluxdbLineProtocolHandlerRef; @@ -107,30 +107,13 @@ pub async fn influxdb_write( )) } -fn parse_time_precision(value: &str) -> Result { - // Precision conversion needs to be compatible with influxdb v1 v2 api. - // For details, see the Influxdb documents. - // https://docs.influxdata.com/influxdb/v1.8/tools/api/#apiv2write-http-endpoint - // https://docs.influxdata.com/influxdb/v1.8/tools/api/#write-http-endpoint - match value { - "n" | "ns" => Ok(Precision::Nanosecond), - "u" | "us" => Ok(Precision::Microsecond), - "ms" => Ok(Precision::Millisecond), - "s" => Ok(Precision::Second), - "m" => Ok(Precision::Minute), - "h" => Ok(Precision::Hour), - unknown => TimePrecisionSnafu { - name: unknown.to_string(), - } - .fail(), - } -} +pub(crate) use crate::influxdb::parse_time_precision; #[cfg(test)] mod tests { use common_grpc::precision::Precision; - use crate::http::influxdb::parse_time_precision; + use super::parse_time_precision; #[test] fn test_parse_time_precision() { diff --git a/src/servers/src/influxdb.rs b/src/servers/src/influxdb.rs index 9bff0bbc6e4..9dd26d9cda7 100644 --- a/src/servers/src/influxdb.rs +++ b/src/servers/src/influxdb.rs @@ -20,7 +20,7 @@ use hyper::Request; use influxdb_line_protocol::{FieldValue, parse_lines}; use snafu::ResultExt; -use crate::error::{Error, InfluxdbLineProtocolSnafu}; +use crate::error::{Error, InfluxdbLineProtocolSnafu, TimePrecisionSnafu}; use crate::row_writer::{self, MultiTableData}; const INFLUXDB_API_PATH_NAME: &str = "influxdb"; @@ -113,6 +113,27 @@ fn unwrap_or_default_precision(precision: Option) -> Precision { } } +/// Parses an InfluxDB time-precision name shared by the HTTP write +/// endpoints (v1/v2) and the `precision` option of COPY FROM STDIN. +pub(crate) fn parse_time_precision(value: &str) -> crate::error::Result { + // Precision conversion needs to be compatible with influxdb v1 v2 api. + // For details, see the Influxdb documents. + // https://docs.influxdata.com/influxdb/v1.8/tools/api/#apiv2write-http-endpoint + // https://docs.influxdata.com/influxdb/v1.8/tools/api/#write-http-endpoint + match value { + "n" | "ns" => Ok(Precision::Nanosecond), + "u" | "us" => Ok(Precision::Microsecond), + "ms" => Ok(Precision::Millisecond), + "s" => Ok(Precision::Second), + "m" => Ok(Precision::Minute), + "h" => Ok(Precision::Hour), + unknown => TimePrecisionSnafu { + name: unknown.to_string(), + } + .fail(), + } +} + #[cfg(test)] mod tests { use api::v1::value::ValueData; diff --git a/src/servers/src/postgres.rs b/src/servers/src/postgres.rs index e13ec7392d5..fbef2e9ac4c 100644 --- a/src/servers/src/postgres.rs +++ b/src/servers/src/postgres.rs @@ -43,8 +43,8 @@ use session::context::Channel; use self::auth_handler::{PgUserProviderSource, ZeroPidSecretKeyGenerator}; use self::handler::DefaultQueryParser; -use crate::query_handler::CopyInHandlerRef; use crate::query_handler::sql::ServerSqlQueryHandlerRef; +use crate::query_handler::{CopyInHandlerRef, InfluxdbLineProtocolHandlerRef}; pub(crate) struct GreptimeDBStartupParameters { version: String, @@ -81,6 +81,11 @@ pub struct PostgresServerHandlerInner { query_handler: ServerSqlQueryHandlerRef, auth_source: Option>, copy_in_handler: CopyInHandlerRef, + /// Executes influxdb line-protocol batches flushed by a table-less + /// COPY FROM STDIN — the same handler the HTTP write endpoints use. + /// Absent on servers not wired for it; such connections reject the + /// influxdb format when a copy starts. + influxdb_handler: Option, force_tls: bool, auth_driver: AuthDriver, UserInfoRef>, /// SCRAM selected; failures get the uniform metric label. @@ -99,6 +104,8 @@ pub struct PostgresServerHandlerInner { pub(crate) struct MakePostgresServerHandler { query_handler: ServerSqlQueryHandlerRef, copy_in_handler: CopyInHandlerRef, + #[builder(default)] + influxdb_handler: Option, user_provider: Option, #[builder(default = "Arc::new(GreptimeDBStartupParameters::new())")] param_provider: Arc, @@ -149,6 +156,7 @@ impl MakePostgresServerHandler { .clone() .map(|p| Arc::new(PgUserProviderSource::new(p))), copy_in_handler: self.copy_in_handler.clone(), + influxdb_handler: self.influxdb_handler.clone(), force_tls: self.force_tls, auth_driver: AuthDriver::new(self.param_provider.clone()) .with_pid_secret_key_generator(Arc::new(ZeroPidSecretKeyGenerator)), diff --git a/src/servers/src/postgres/copy_in/codec.rs b/src/servers/src/postgres/copy_in/codec.rs index 37a94811309..a7672c619ef 100644 --- a/src/servers/src/postgres/copy_in/codec.rs +++ b/src/servers/src/postgres/copy_in/codec.rs @@ -12,58 +12,63 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! The COPY FROM STDIN codec framework. +//! The COPY FROM STDIN formats. //! -//! A *codec* binds one COPY data format to its implementation. Codecs are -//! stateless strategies: they validate the options they accept at -//! statement-parse time, describe which column types they can ingest, and -//! create the stateful [`RecordParser`] per stream. -//! -//! Formats are not limited to PostgreSQL's own — GreptimeDB-specific -//! formats (a line protocol, a JSON-lines dialect, ...) register exactly -//! like `csv` does, and may define their own options through the open -//! `WITH (...)` clause. +//! [`CopyFormat`] is the closed, explicit set of supported formats — a +//! small enum over the real implementations rather than a generic +//! format framework. Each variant carries its validated options and +//! its rules are stated where they apply: a variant's match arms in +//! the copy lifecycle (see the parent module) decide whether a target +//! table is required, how the `CopyData` bytes are consumed, and which +//! existing ingestion pipeline completes the copy. Adding a format is +//! a normal extension: a new variant plus its arms. //! //! # Parsing and conversion //! -//! A [`RecordParser`] consumes raw `CopyData` bytes and emits complete, -//! insertable rows: one [`ParsedRow`] per record, in the order of the -//! targeted columns. Parsers validate record shape (field counts) and -//! convert field values themselves — `csv` delegates both splitting and -//! typed conversion to arrow-csv's incremental decoder (the engine -//! behind `COPY ... FROM 'file.csv'`) and turns decoded batches into -//! rows with the shared `api::helper::vectors_to_rows`. A future format -//! that carries values as text (e.g. a line protocol) would reintroduce -//! shared field-conversion helpers here; see the removed `text` codec in -//! git history for the shape they had. +//! Table-bound formats parse incrementally through a [`RecordParser`]: +//! it consumes raw `CopyData` bytes and emits complete, insertable +//! rows — one [`ParsedRow`] per record, in the order of the targeted +//! columns. `csv` delegates splitting and typed conversion to +//! arrow-csv's incremental decoder (the engine behind +//! `COPY ... FROM 'file.csv'`) and turns decoded batches into rows +//! with the shared `api::helper::vectors_to_rows`. +//! +//! Formats that delegate to an existing ingestion pipeline (the +//! influxdb line protocol) do not parse here at all: the whole payload +//! is buffered as one bounded request body and completed through that +//! pipeline, so record boundaries and values stay with the pipeline's +//! own parser. //! //! # Options //! //! The `WITH (...)` clause is open: every `KEY value` entry the client -//! writes is collected into a [`CopyOptionSet`] (see `options`) regardless -//! of whether any format understands it — the statement is parsed -//! textually (see `parse`) precisely so options beyond sqlparser's COPY -//! grammar can reach the codecs. A codec builder takes the options it -//! understands (`take_string`, `take_single_byte`, `take_flag`, or raw -//! `take_value` for codec-specific shapes) and rejects the rest with -//! `reject_leftovers`, so a future format like -//! `COPY t FROM STDIN WITH (FORMAT influxdb_line, precision 'ns')` only -//! needs its own codec and registry entry. -//! -//! To add a format: -//! -//! 1. implement [`CopyInCodec`] for a config struct holding the format's -//! validated options (see `csv::CsvCodec` for the example), -//! 2. write a builder `fn(CopyOptionSet) -> PgWireResult>` that applies defaults and rejects options the format -//! does not accept, -//! 3. register the builder under every accepted `FORMAT` name (including -//! aliases) in `REGISTERED_FORMATS` in the parent module. +//! writes is collected into a [`CopyOptionSet`] (see `options`) +//! regardless of whether any format understands it — the statement is +//! parsed textually (see `parse`) precisely so options beyond +//! sqlparser's COPY grammar can reach the formats. A format builder +//! takes the options it understands (`take_string`, +//! `take_single_byte`, `take_flag`, or raw `take_value` for +//! format-specific shapes) and rejects the rest with +//! `reject_leftovers`. -use datatypes::prelude::ConcreteDataType; -use datatypes::schema::ColumnSchema; use pgwire::error::PgWireResult; +use crate::postgres::copy_in::csv::CsvCodec; +use crate::postgres::copy_in::influxdb::InfluxdbOptions; + +/// A resolved COPY FROM STDIN format with its validated options. +#[derive(Debug, Clone)] +pub(super) enum CopyFormat { + /// Table-bound CSV: records are parsed incrementally against the + /// targeted table's columns and inserted in batches. + Csv(CsvCodec), + /// Table-less influxdb line protocol: the whole payload is one + /// bounded request body, completed through the line-protocol + /// pipeline the HTTP write endpoints use (one COPY statement is one + /// ingestion request; streaming ingest is not supported). + Influxdb(InfluxdbOptions), +} + /// A parsed, insertable row: one gRPC value per targeted column, in COPY /// field order. Every parser emits these directly, whatever mechanism it /// used to produce them. @@ -83,34 +88,3 @@ pub(super) trait RecordParser: Send { /// stream ended exactly at a record boundary. fn finish(&mut self) -> PgWireResult>; } - -/// A COPY FROM STDIN data format implementation. -/// -/// Implementations are shared per statement (hence `Send + Sync`) and must -/// be stateless; per-stream state belongs to the [`RecordParser`] they -/// create. Every method is tailored to the format: `check_column_type` -/// declares the types the format can decode (csv is bounded by what -/// arrow-csv supports). -pub(super) trait CopyInCodec: Send + Sync + std::fmt::Debug { - /// The canonical format name, used in error messages. - fn name(&self) -> &'static str; - /// The format code advertised in the `CopyInResponse` header: 0 when - /// the client sends textual data (the default), 1 for binary. - fn format_code(&self) -> i8 { - 0 - } - /// Validates that a column of `data_type` can be ingested by this - /// format. - fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()>; - /// Creates the stateful parser for one copy stream over the targeted - /// columns (in COPY field order). - /// - /// `timezone` is the session timezone (an IANA name or a UTC offset): - /// formats that parse offset-free timestamp strings from text should - /// interpret them in this zone, matching SQL INSERT. - fn create_parser( - &self, - columns: &[ColumnSchema], - timezone: &str, - ) -> PgWireResult>; -} diff --git a/src/servers/src/postgres/copy_in/csv.rs b/src/servers/src/postgres/copy_in/csv.rs index b2919210e3f..ab8f521098d 100644 --- a/src/servers/src/postgres/copy_in/csv.rs +++ b/src/servers/src/postgres/copy_in/csv.rs @@ -40,12 +40,12 @@ use datatypes::schema::{ColumnSchema, Schema as GreptimeSchema}; use datatypes::vectors::{BooleanVector, Helper, StringVector, Vector}; use pgwire::error::{PgWireError, PgWireResult}; -use crate::postgres::copy_in::codec::{CopyInCodec, ParsedRow, RecordParser}; +use crate::postgres::copy_in::codec::{CopyFormat, ParsedRow, RecordParser}; use crate::postgres::copy_in::options::CopyOptionSet; use crate::postgres::copy_in::{COPY_IN_FLUSH_ROWS, bad_copy_data, invalid_text_repr, unsupported}; /// The validated `csv` format configuration. -#[derive(Debug)] +#[derive(Debug, Clone)] pub(super) struct CsvCodec { delimiter: u8, quote: u8, @@ -54,7 +54,7 @@ pub(super) struct CsvCodec { } /// Builds the CSV codec from the parsed options. -pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult> { +pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult { let delimiter = options.take_single_byte("DELIMITER")?.unwrap_or(b','); let quote = options.take_single_byte("QUOTE")?.unwrap_or(b'"'); // In PostgreSQL the default escape character for CSV is the quote @@ -75,7 +75,7 @@ pub(super) fn build_csv_codec(mut options: CopyOptionSet) -> PgWireResult PgWireResult &'static str { - "csv" - } - +impl CsvCodec { /// The column types arrow-csv can decode against. - fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> { + pub(super) fn check_column_type(&self, data_type: &ConcreteDataType) -> PgWireResult<()> { let supported = matches!( data_type, ConcreteDataType::Boolean(_) @@ -117,7 +113,7 @@ impl CopyInCodec for CsvCodec { Ok(()) } - fn create_parser( + pub(super) fn create_parser( &self, columns: &[ColumnSchema], timezone: &str, @@ -292,9 +288,15 @@ mod tests { ] } + fn build_codec(set: CopyOptionSet) -> CsvCodec { + match build_csv_codec(set).unwrap() { + CopyFormat::Csv(codec) => codec, + other => panic!("expected csv format, got {other:?}"), + } + } + fn parser() -> Box { - build_csv_codec(CopyOptionSet::default()) - .unwrap() + build_codec(CopyOptionSet::default()) .create_parser(&test_columns(), "UTC") .unwrap() } @@ -308,8 +310,7 @@ mod tests { fn rows_with(mut set: CopyOptionSet) -> Box { set.take_format().unwrap(); - build_csv_codec(set) - .unwrap() + build_codec(set) .create_parser(&test_columns(), "UTC") .unwrap() } @@ -329,8 +330,8 @@ mod tests { #[test] fn test_build_defaults() { - let codec = build_csv_codec(CopyOptionSet::default()).unwrap(); - assert_eq!(codec.name(), "csv"); + let codec = build_codec(CopyOptionSet::default()); + assert!(matches!(codec, CsvCodec { .. })); } #[test] @@ -368,7 +369,7 @@ mod tests { #[test] fn test_check_column_type() { - let codec = build_csv_codec(CopyOptionSet::default()).unwrap(); + let codec = build_codec(CopyOptionSet::default()); assert!( codec .check_column_type(&ConcreteDataType::json_datatype()) @@ -524,8 +525,7 @@ mod tests { .into_bytes(); let check = |chunk: usize| { - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&sweep_columns, "UTC") .unwrap(); let mut ids: Vec = Vec::new(); @@ -560,8 +560,7 @@ mod tests { check(chunk); let mut shifted = payload.clone(); shifted.drain(..37); - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&sweep_columns, "UTC") .unwrap(); let mut count = 0usize; @@ -585,8 +584,7 @@ mod tests { false, ), ]; - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&columns, "UTC") .unwrap(); let rows = feed_all( @@ -628,8 +626,7 @@ mod tests { false, ), ]; - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&columns, "UTC") .unwrap(); parser.feed(b"maybe,2024-01-01 00:00:00\n").unwrap(); @@ -656,8 +653,7 @@ mod tests { false, ), ]; - let mut parser = build_csv_codec(CopyOptionSet::default()) - .unwrap() + let mut parser = build_codec(CopyOptionSet::default()) .create_parser(&columns, "Asia/Shanghai") .unwrap(); let rows = feed_all( diff --git a/src/servers/src/postgres/copy_in/influxdb.rs b/src/servers/src/postgres/copy_in/influxdb.rs new file mode 100644 index 00000000000..b4e2a9add30 --- /dev/null +++ b/src/servers/src/postgres/copy_in/influxdb.rs @@ -0,0 +1,95 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! The `influxdb` line protocol format for COPY FROM STDIN. +//! +//! `COPY FROM STDIN WITH (FORMAT influxdb, precision 'ns')` ingests +//! [InfluxDB line protocol](https://docs.influxdata.com/influxdb/v1.8/write_protocols/line_protocol_reference/) +//! text. The format is table-less — each line names its own measurement +//! — and does not parse here at all: the COPY layer buffers the whole +//! payload (bounded by [`crate::postgres::copy_in::COPY_IN_MAX_PAYLOAD_BYTES`]) +//! and completes the copy by handing it to the frontend's line-protocol +//! write pipeline as one body, exactly like the HTTP +//! `/v1/influxdb/v1/write` endpoint receives one request body: +//! conversion, permissions, interceptors, timestamp alignment, merge +//! mode and inserts are the same path, and record boundaries (including +//! newlines inside quoted field values and after escapes) are decided +//! by the line-protocol parser alone — the COPY layer never splits +//! records. +//! +//! One COPY statement is therefore one bounded ingestion request; a +//! larger import is multiple COPY statements. +//! +//! The `precision` option carries the same values as the HTTP +//! `precision` query parameter (`ns`, `us`, `ms`, `s`, ...), defaults to +//! nanoseconds, and is resolved by the shared `parse_time_precision`. + +use common_grpc::precision::Precision; +use pgwire::error::PgWireResult; + +use crate::postgres::copy_in::bad_copy_data; +use crate::postgres::copy_in::codec::CopyFormat; +use crate::postgres::copy_in::options::CopyOptionSet; + +/// The format's validated options. A `None` precision carries the +/// pipeline's default (nanoseconds), exactly like an HTTP write without +/// a `precision` parameter. +#[derive(Debug, Clone)] +pub(super) struct InfluxdbOptions { + pub(super) precision: Option, +} + +pub(super) fn build_influxdb_codec(mut options: CopyOptionSet) -> PgWireResult { + let precision = match options.take_string("precision")? { + Some(value) => Some( + crate::influxdb::parse_time_precision(&value) + .map_err(|e| bad_copy_data(format!("invalid precision option: {e}")))?, + ), + None => None, + }; + options.reject_leftovers("influxdb")?; + Ok(CopyFormat::Influxdb(InfluxdbOptions { precision })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::postgres::copy_in::options::CopyOptionValue; + + #[test] + fn test_builder_options() { + let format = build_influxdb_codec(CopyOptionSet::default()).unwrap(); + assert!(matches!(format, CopyFormat::Influxdb(_))); + assert!(matches!(format, CopyFormat::Influxdb(_))); + + let mut set = CopyOptionSet::default(); + set.insert("precision".into(), CopyOptionValue::String("ms".into())) + .unwrap(); + assert!(matches!( + build_influxdb_codec(set).unwrap(), + CopyFormat::Influxdb(InfluxdbOptions { + precision: Some(Precision::Millisecond) + }) + )); + + let mut set = CopyOptionSet::default(); + set.insert("precision".into(), CopyOptionValue::String("bogus".into())) + .unwrap(); + assert!(build_influxdb_codec(set).is_err()); + + let mut set = CopyOptionSet::default(); + set.insert("unknown".into(), CopyOptionValue::Flag).unwrap(); + assert!(build_influxdb_codec(set).is_err()); + } +} diff --git a/src/servers/src/postgres/copy_in/mod.rs b/src/servers/src/postgres/copy_in/mod.rs index a3959a23830..92528d4ab2f 100644 --- a/src/servers/src/postgres/copy_in/mod.rs +++ b/src/servers/src/postgres/copy_in/mod.rs @@ -21,38 +21,42 @@ //! the data stream incrementally and flushes it into the query handler as //! [`RowInsertRequests`] batches. //! -//! # Format framework +//! # Formats //! -//! Each COPY data format is implemented as a [`codec::CopyInCodec`]: a -//! stateless strategy that validates its options at statement-parse time, -//! describes the column types it can ingest, and creates the stateful -//! record parser for one stream. Formats register a builder under every -//! accepted `FORMAT` name in [`REGISTERED_FORMATS`] — `csv` is the only -//! implemented format today; PostgreSQL's `text`/`binary` and -//! GreptimeDB-specific formats alike can be added the same way. See the -//! `codec` module docs. +//! The supported formats are the explicit [`codec::CopyFormat`] enum — +//! `csv` (table-bound, incremental row parsing) and `influxdb` +//! (table-less, one bounded whole-payload request). Each format states +//! its own target rule and ingestion shape in the match arms of the +//! copy lifecycle below; adding a format is a new variant plus its +//! arms. Builders resolve a `FORMAT` name (and its aliases) through +//! [`REGISTERED_FORMATS`]. See the `codec` module docs. mod codec; mod csv; +mod influxdb; mod options; mod parse; use std::fmt::Debug; use std::sync::Arc; +use crate::influxdb::InfluxdbRequest; use api::helper::ColumnDataTypeWrapper; use api::v1::column_def::options_from_column_schema; use api::v1::{ Row as GrpcRow, RowInsertRequest, RowInsertRequests, Rows as GrpcRows, SemanticType, }; use async_trait::async_trait; -use codec::{CopyInCodec, RecordParser}; +use codec::{CopyFormat, RecordParser}; +use common_grpc::precision::Precision; use common_query::OutputData; use common_telemetry::{info, warn}; +use csv::CsvCodec; use datafusion::sql::sqlparser::ast::{CopyTarget, Statement as SqlParserStatement}; use datatypes::data_type::DataType; use datatypes::schema::{ColumnSchema, SchemaRef}; use futures::{Sink, SinkExt, stream}; +use influxdb::InfluxdbOptions; use pgwire::api::copy::CopyHandler; use pgwire::api::results::{CopyResponse, Response, Tag}; use pgwire::api::{ClientInfo, PgWireConnectionState}; @@ -80,38 +84,43 @@ use crate::postgres::utils::convert_err; /// the per-batch fixed costs negligible. pub(crate) const COPY_IN_FLUSH_ROWS: usize = 32768; -/// Builds a codec from the format-neutral option set. -type CodecBuilder = fn(options::CopyOptionSet) -> PgWireResult>; +/// Upper bound of an influxdb COPY FROM STDIN payload. One COPY +/// statement is one bounded ingestion request (the whole payload is +/// buffered like one HTTP write body); a larger import is multiple COPY +/// statements. Streaming ingest may arrive later, with framing owned by +/// the shared line-protocol parser rather than the COPY layer. +pub(crate) const COPY_IN_MAX_PAYLOAD_BYTES: usize = 64 * 1024 * 1024; + +/// Builds a format from the format-neutral option set. +type FormatBuilder = fn(options::CopyOptionSet) -> PgWireResult; /// The registered COPY FROM STDIN formats: accepted `FORMAT` name to /// builder. `csv` is the only implemented format; the others are /// registered so they report a clear "not supported yet" instead of an /// unknown-format error. -const REGISTERED_FORMATS: &[(&str, CodecBuilder)] = &[ +const REGISTERED_FORMATS: &[(&str, FormatBuilder)] = &[ ("csv", csv::build_csv_codec), + ("influxdb", influxdb::build_influxdb_codec), + ("influxdb_line", influxdb::build_influxdb_codec), ("text", build_unimplemented_text_codec), ("txt", build_unimplemented_text_codec), ("binary", build_unimplemented_binary_codec), ]; -fn build_unimplemented_text_codec( - _options: options::CopyOptionSet, -) -> PgWireResult> { +fn build_unimplemented_text_codec(_options: options::CopyOptionSet) -> PgWireResult { Err(unsupported( "the text format is not supported yet; use WITH (FORMAT csv)", )) } -fn build_unimplemented_binary_codec( - _options: options::CopyOptionSet, -) -> PgWireResult> { +fn build_unimplemented_binary_codec(_options: options::CopyOptionSet) -> PgWireResult { Err(unsupported( "COPY FROM STDIN WITH (FORMAT binary) is not supported yet", )) } -/// Resolves the format codec from the parsed options. -fn resolve_codec(options: &mut options::CopyOptionSet) -> PgWireResult> { +/// Resolves the format from the parsed options. +fn resolve_format(options: &mut options::CopyOptionSet) -> PgWireResult { let name = options.take_format()?.ok_or_else(|| { unsupported( "COPY FROM STDIN requires an explicit format in this version; use WITH (FORMAT csv)", @@ -133,15 +142,15 @@ pub(crate) struct CopyFromStdin { table: Vec, /// Requested column list; empty means all columns in table order. columns: Vec, - /// The resolved format codec, validated and ready to run. - codec: Arc, + /// The resolved format with its validated options. + format: CopyFormat, } fn copy_in_error(code: PgErrorCode, message: impl Into) -> PgWireError { PgWireError::UserError(Box::new(code.to_err_info(message.into()))) } -fn unsupported(message: impl Into) -> PgWireError { +pub(super) fn unsupported(message: impl Into) -> PgWireError { copy_in_error(PgErrorCode::Ec0A000, message) } @@ -174,11 +183,11 @@ pub(crate) fn copy_from_stdin_from_sql(sql: &str) -> PgWireResult raw, }; let mut option_set = raw.options; - let codec = resolve_codec(&mut option_set)?; + let format = resolve_format(&mut option_set)?; Ok(Some(CopyFromStdin { table: raw.table, columns: raw.columns, - codec, + format, })) } @@ -221,26 +230,49 @@ fn resolve_table_name( } /// Per-connection state of an in-progress COPY FROM STDIN. +/// +/// The payload shape follows the codec: table-bound formats (csv) parse +/// records into rows against the targeted table's columns; table-less +/// formats (influxdb line protocol) split the stream into complete +/// lines that each route to their own measurement, and flush through +/// the handler's line-protocol pipeline — the same one the HTTP write +/// endpoint uses. pub(crate) struct CopyInState { query_ctx: QueryContextRef, - /// The gRPC column schemas of the targeted columns. Cloned into each - /// flushed batch: `Rows.schema` is an owned `Vec` in the proto - /// request, so one copy per request is inherent. - grpc_schema: Vec, - table_name: String, - parser: Box, + payload: Payload, /// The resolved codec's name, for logging. codec_name: &'static str, /// The wire format code of the resolved codec. codec_format_code: i8, - /// Parsed rows not yet flushed to the handler. - rows: Vec, rows_written: u64, } +enum Payload { + /// Table-bound rows: parsed against `grpc_schema` and flushed to + /// `table_name` via `copy_in_insert`. The schema is cloned into each + /// flushed batch: `Rows.schema` is an owned `Vec` in the proto + /// request, so one copy per request is inherent. + Table { + grpc_schema: Vec, + table_name: String, + parser: Box, + /// Parsed rows not yet flushed to the handler. + rows: Vec, + }, + /// The whole buffered influxdb line-protocol payload with its + /// request precision. One COPY statement is one bounded ingestion + /// request, buffered until `CopyDone` — exactly like one HTTP write + /// body — and record boundaries belong to the line-protocol parser, + /// never to the COPY layer. + Influxdb { + data: Vec, + precision: Option, + }, +} + impl CopyInState { fn new( - codec: Arc, + codec: &CsvCodec, columns: Vec, table_info: Arc, query_ctx: QueryContextRef, @@ -249,7 +281,7 @@ impl CopyInState { let schema = table_info.meta.schema.clone(); let timestamp_index = schema.timestamp_index(); - let columns = resolve_columns(codec.as_ref(), columns, &schema, &table_info)?; + let columns = resolve_columns(codec, columns, &schema, &table_info)?; if let Some(ts_index) = timestamp_index { let ts_column = &schema.column_schemas()[ts_index]; if !columns.iter().any(|column| column.name == ts_column.name) { @@ -268,58 +300,122 @@ impl CopyInState { Ok(Self { query_ctx, - grpc_schema, - table_name, - parser, - codec_name: codec.name(), - codec_format_code: codec.format_code(), - rows: Vec::with_capacity(COPY_IN_FLUSH_ROWS), + payload: Payload::Table { + grpc_schema, + table_name, + parser, + rows: Vec::with_capacity(COPY_IN_FLUSH_ROWS), + }, + codec_name: "csv", + codec_format_code: 0, rows_written: 0, }) } + /// State for the influxdb format: the whole payload is buffered and + /// completed once at `CopyDone` through the line-protocol pipeline. + fn new_influxdb(options: &InfluxdbOptions, query_ctx: QueryContextRef) -> Self { + Self { + query_ctx, + payload: Payload::Influxdb { + data: Vec::new(), + precision: options.precision, + }, + codec_name: "influxdb", + codec_format_code: 0, + rows_written: 0, + } + } + /// The wire format code advertised to the client. pub(crate) fn format_code(&self) -> i8 { self.codec_format_code } - /// Feeds a `CopyData` chunk into the parser and buffers parsed rows. + /// Feeds a `CopyData` chunk into the parser and buffers parsed rows + /// (csv) or payload bytes (influxdb). fn feed(&mut self, data: &[u8]) -> PgWireResult<()> { - self.rows.extend(self.parser.feed(data)?); + match &mut self.payload { + Payload::Table { parser, rows, .. } => rows.extend(parser.feed(data)?), + Payload::Influxdb { data: buffered, .. } => { + if buffered.len() + data.len() > COPY_IN_MAX_PAYLOAD_BYTES { + return Err(bad_copy_data(format!( + "COPY FROM STDIN payload exceeds the {} limit; split the import into multiple COPY statements", + COPY_IN_MAX_PAYLOAD_BYTES + ))); + } + buffered.extend_from_slice(data); + } + } Ok(()) } /// Parses the buffered tail at `CopyDone`; a final record without a /// trailing newline is accepted. fn finish(&mut self) -> PgWireResult<()> { - self.rows.extend(self.parser.finish()?); + match &mut self.payload { + Payload::Table { parser, rows, .. } => rows.extend(parser.finish()?), + // The whole payload is one request body; nothing to finalize. + Payload::Influxdb { .. } => {} + } Ok(()) } fn should_flush(&self) -> bool { - self.rows.len() >= COPY_IN_FLUSH_ROWS + match &self.payload { + Payload::Table { rows, .. } => rows.len() >= COPY_IN_FLUSH_ROWS, + // Completed once at CopyDone, not mid-stream. + Payload::Influxdb { .. } => false, + } } /// Takes the buffered rows as an insert request, if any. fn take_requests(&mut self) -> Option { - if self.rows.is_empty() { + let Payload::Table { + grpc_schema, + table_name, + rows, + .. + } = &mut self.payload + else { + return None; + }; + if rows.is_empty() { return None; } let rows = GrpcRows { - schema: self.grpc_schema.clone(), - rows: std::mem::take(&mut self.rows), + schema: grpc_schema.clone(), + rows: std::mem::take(rows), }; Some(RowInsertRequests { inserts: vec![RowInsertRequest { - table_name: self.table_name.clone(), + table_name: table_name.clone(), rows: Some(rows), }], }) } + + /// Takes the buffered payload as one line-protocol request body, if + /// any — the same bytes an HTTP write of the same records would + /// carry. + fn take_lines(&mut self) -> PgWireResult> { + let Payload::Influxdb { data, precision } = &mut self.payload else { + return Ok(None); + }; + if data.is_empty() { + return Ok(None); + } + let lines = String::from_utf8(std::mem::take(data)) + .map_err(|e| bad_copy_data(format!("COPY FROM STDIN data is not valid UTF-8: {e}")))?; + Ok(Some(InfluxdbRequest { + precision: *precision, + lines, + })) + } } fn resolve_columns( - codec: &dyn CopyInCodec, + codec: &CsvCodec, columns: Vec, schema: &SchemaRef, table_info: &Arc, @@ -411,27 +507,63 @@ impl PostgresServerHandlerInner { // pending-rows batcher like SQL INSERT when it is enabled for // this connection. let query_ctx = self.new_query_context(); - let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?; - let Some(table_info) = self - .copy_in_handler - .copy_in_table(&catalog, &schema, &table, query_ctx.clone()) - .await - .map_err(convert_err)? - else { - return Err(copy_in_error( - PgErrorCode::Ec42P01, - format!("relation \"{}\" does not exist", stmt.table.join(".")), - )); + // Each format states its own target rule and ingestion shape + // explicitly. + let state = match &stmt.format { + // csv requires a target table: records are parsed against + // its columns and inserted in batches. + CopyFormat::Csv(codec) => { + if stmt.table.is_empty() { + return Err(unsupported( + "format csv requires a table: COPY tbl [(cols)] FROM STDIN WITH (FORMAT csv)", + )); + } + let (catalog, schema, table) = resolve_table_name(&query_ctx, &stmt.table)?; + + let Some(table_info) = self + .copy_in_handler + .copy_in_table(&catalog, &schema, &table, query_ctx.clone()) + .await + .map_err(convert_err)? + else { + return Err(copy_in_error( + PgErrorCode::Ec42P01, + format!("relation \"{}\" does not exist", stmt.table.join(".")), + )); + }; + + // The insert path resolves the bare table name against the + // query context, so point the context at the resolved + // catalog and schema when the COPY target is qualified. + let query_ctx = adjust_query_context(query_ctx, &catalog, &schema); + + CopyInState::new(codec, stmt.columns, table_info, query_ctx, table)? + } + // influxdb forbids a target table — each line names its own + // measurement — and completes through the line-protocol + // pipeline the HTTP write endpoints use; the server must be + // wired for it. + CopyFormat::Influxdb(options) => { + if !stmt.table.is_empty() { + return Err(unsupported(format!( + "format influxdb routes each record to its own table; \"COPY {} FROM STDIN\" must not name one", + stmt.table.join(".") + ))); + } + if self.influxdb_handler.is_none() { + return Err(unsupported( + "this server is not wired for the influxdb line protocol format", + )); + } + CopyInState::new_influxdb(options, query_ctx) + } + }; + let num_columns = match &state.payload { + Payload::Table { grpc_schema, .. } => grpc_schema.len(), + // No fixed column set: the format routes per record. + Payload::Influxdb { .. } => 0, }; - - // The insert path resolves the bare table name against the query - // context, so point the context at the resolved catalog and schema - // when the COPY target is qualified. - let query_ctx = adjust_query_context(query_ctx, &catalog, &schema); - - let state = CopyInState::new(stmt.codec, stmt.columns, table_info, query_ctx, table)?; - let num_columns = state.grpc_schema.len(); let format_code = state.format_code(); *self.copy_in_state.lock().await = Some(state); @@ -443,13 +575,34 @@ impl PostgresServerHandlerInner { ))) } - /// Flushes buffered rows of an in-progress copy. Returns the number of - /// rows written by the flushed batch. + /// Flushes the buffered payload of an in-progress copy. Returns the + /// number of rows written by the flushed batch. async fn flush_copy_in(&self, state: &mut CopyInState) -> PgWireResult { + let query_ctx = state.query_ctx.clone(); + // The buffered influxdb payload is completed through the + // line-protocol pipeline — the same handler the HTTP write + // endpoints use, so conversion, permissions, interceptors, + // timestamp alignment and inserts are identical to an HTTP + // write of the same bytes. The context stays this connection's + // postgres context. + if let Some(request) = state.take_lines()? { + let Some(influxdb_handler) = &self.influxdb_handler else { + return Err(unsupported( + "this server is not wired for the influxdb line protocol format", + )); + }; + let output = influxdb_handler + .exec(request, query_ctx) + .await + .map_err(convert_err)?; + return match output.data { + OutputData::AffectedRows(rows) => Ok(rows as u64), + OutputData::RecordBatches(_) | OutputData::Stream(_) => Ok(0), + }; + } let Some(requests) = state.take_requests() else { return Ok(0); }; - let query_ctx = state.query_ctx.clone(); let output = self .copy_in_handler .copy_in_insert(requests, query_ctx) @@ -587,8 +740,8 @@ mod tests { .unwrap(); assert_eq!(copy.table, vec!["t"]); assert!(copy.columns.is_empty()); - assert_eq!(copy.codec.name(), "csv"); - assert_eq!(copy.codec.format_code(), 0); + assert!(matches!(copy.format, CopyFormat::Csv(_))); + // Both formats are textual: format code 0. } #[test] @@ -599,7 +752,7 @@ mod tests { .unwrap() .unwrap(); assert_eq!(copy.columns, vec!["a", "b"]); - assert_eq!(copy.codec.name(), "csv"); + assert!(matches!(copy.format, CopyFormat::Csv(_))); } #[test] diff --git a/src/servers/src/postgres/copy_in/parse.rs b/src/servers/src/postgres/copy_in/parse.rs index 8139960bfa4..e9be443eea5 100644 --- a/src/servers/src/postgres/copy_in/parse.rs +++ b/src/servers/src/postgres/copy_in/parse.rs @@ -32,7 +32,7 @@ use pgwire::error::PgWireResult; use crate::postgres::copy_in::options::{CopyOptionSet, CopyOptionValue}; use crate::postgres::copy_in::{bad_copy_data, copy_in_must_run_alone_error}; -/// A scanned `COPY tbl [(cols)] FROM STDIN [WITH (...)]` statement. +/// A scanned `COPY [tbl [(cols)]] FROM STDIN [WITH (...)]` statement. /// /// Unquoted identifiers are folded to lowercase and quoted ones keep their /// case (`COPY Metrics` addresses the same table as `CREATE TABLE Metrics`, @@ -41,7 +41,9 @@ use crate::postgres::copy_in::{bad_copy_data, copy_in_must_run_alone_error}; #[derive(Debug)] pub(super) struct RawCopyFromStdin { /// Table name parts, as written (`t`, `schema.t`, - /// `catalog.schema.t`); quoted names keep their case. + /// `catalog.schema.t`); quoted names keep their case. Empty for + /// table-less formats whose records carry their own routing (e.g. + /// the influxdb line protocol names its measurement per line). pub(super) table: Vec, /// Requested column list; empty means all columns in table order. pub(super) columns: Vec, @@ -89,13 +91,27 @@ pub(super) fn scan_copy_from_stdin(sql: &str) -> PgWireResult { return Ok(CopyInScan::NotCopyIn); } - let table = match parse_object_name(&mut cursor) { - Some(table) => table, - None => return Ok(CopyInScan::NotCopyIn), + // Table-less statements (`COPY FROM STDIN WITH (FORMAT influxdb) ...`) + // are table-format specific: the codec decides whether a missing + // table is legal. An unquoted `FROM` cannot be a table name (SQL + // would require quoting it), so peek instead of letting the + // identifier parser swallow the keyword. A column list without a + // table is not. + let table = if cursor.peek_keyword("from") { + Vec::new() + } else { + match parse_object_name(&mut cursor) { + Some(table) => table, + None => return Ok(CopyInScan::NotCopyIn), + } }; - let columns = match parse_column_list(&mut cursor) { - Some(columns) => columns, - None => return Ok(CopyInScan::NotCopyIn), + let columns = if table.is_empty() { + Vec::new() + } else { + match parse_column_list(&mut cursor) { + Some(columns) => columns, + None => return Ok(CopyInScan::NotCopyIn), + } }; if !cursor.take_keyword("from") || !cursor.take_keyword("stdin") { @@ -151,16 +167,20 @@ impl<'a> Tokens<'a> { /// Consumes the next token if it is the unquoted keyword `keyword`. fn take_keyword(&mut self, keyword: &str) -> bool { - match self.peek() { - Some(Token::Word(w)) - if w.quote_style.is_none() && w.value.eq_ignore_ascii_case(keyword) => - { - self.pos += 1; - true - } - _ => false, + if self.peek_keyword(keyword) { + self.pos += 1; + true + } else { + false } } + + /// Whether the next token is the unquoted keyword `keyword`, without + /// consuming it. + fn peek_keyword(&self, keyword: &str) -> bool { + matches!(self.tokens.get(self.pos), Some(Token::Word(w)) + if w.quote_style.is_none() && w.value.eq_ignore_ascii_case(keyword)) + } } /// Returns the identifier with the SQL parser's canonicalization: quoted @@ -275,6 +295,27 @@ mod tests { }) } + #[test] + fn test_scan_tableless() { + // Table-less statements: the codec decides whether a missing + // table is legal (the influxdb line protocol names its + // measurement per line). + let raw = scan("COPY FROM STDIN WITH (FORMAT influxdb, precision 'ns')") + .unwrap() + .unwrap(); + assert!(raw.table.is_empty()); + assert!(raw.columns.is_empty()); + + let raw = scan("copy from stdin (format influxdb)").unwrap().unwrap(); + assert!(raw.table.is_empty()); + + // A column list without a table is not a copy-in statement. + assert!(scan("COPY (a, b) FROM STDIN").unwrap().is_none()); + // COPY OUT and file COPY are unaffected. + assert!(scan("COPY (SELECT 1) TO STDOUT").unwrap().is_none()); + assert!(scan("COPY t FROM '/tmp/x.csv'").unwrap().is_none()); + } + #[test] fn test_scan_basic() { let raw = scan("COPY t FROM STDIN").unwrap().unwrap(); diff --git a/src/servers/src/postgres/server.rs b/src/servers/src/postgres/server.rs index 7e3b3e2b7bd..3919081ba62 100644 --- a/src/servers/src/postgres/server.rs +++ b/src/servers/src/postgres/server.rs @@ -30,6 +30,7 @@ use tokio_rustls::TlsAcceptor; use crate::error::Result; use crate::postgres::{MakePostgresServerHandler, MakePostgresServerHandlerBuilder}; use crate::query_handler::CopyInHandlerRef; +use crate::query_handler::InfluxdbLineProtocolHandlerRef; use crate::query_handler::sql::ServerSqlQueryHandlerRef; use crate::server::{AbortableStream, BaseTcpServer, Server}; use crate::tls::ReloadableTlsServerConfig; @@ -40,6 +41,7 @@ pub struct PostgresServer { tls_server_config: Arc, keep_alive_secs: u64, batching_enabled: bool, + influxdb_handler: Option, bind_addr: Option, process_manager: Option, } @@ -77,6 +79,7 @@ impl PostgresServer { tls_server_config, keep_alive_secs, batching_enabled: false, + influxdb_handler: None, bind_addr: None, process_manager, } @@ -88,12 +91,34 @@ impl PostgresServer { self } + /// Wires the influxdb line-protocol handler used by table-less + /// `COPY FROM STDIN WITH (FORMAT influxdb)` flushes — the same + /// handler the HTTP influxdb write endpoints use, so a flushed batch + /// runs through the identical pipeline. + pub fn with_influxdb_handler(mut self, handler: InfluxdbLineProtocolHandlerRef) -> Self { + self.influxdb_handler = Some(handler); + self + } + fn accept( &self, io_runtime: Runtime, accepting_stream: AbortableStream, ) -> impl Future + use<> { - let handler_maker = self.make_handler.clone(); + // Assemble the per-connection handler directly, including any + // `with_*` wiring applied after construction (the influxdb + // line-protocol handler). Constructing the struct — instead of + // going through the builder — keeps this infallible: no + // `.build().unwrap()` on the hot accept path. + let make_handler = &self.make_handler; + let handler_maker = Arc::new(MakePostgresServerHandler { + query_handler: make_handler.query_handler.clone(), + copy_in_handler: make_handler.copy_in_handler.clone(), + influxdb_handler: self.influxdb_handler.clone(), + user_provider: make_handler.user_provider.clone(), + param_provider: make_handler.param_provider.clone(), + force_tls: make_handler.force_tls, + }); let batching_enabled = self.batching_enabled; let tls_server_config = self.tls_server_config.clone(); let process_manager = self.process_manager.clone(); diff --git a/tests-integration/src/test_util.rs b/tests-integration/src/test_util.rs index 3cc820619c6..3dd451b4716 100644 --- a/tests-integration/src/test_util.rs +++ b/tests-integration/src/test_util.rs @@ -1204,16 +1204,19 @@ pub async fn setup_pg_server_with_slow_query_threshold( .expect("Failed to load certificates and keys"), ); - let mut pg_server = Box::new(PostgresServer::new( - fe_instance_ref.clone(), - fe_instance_ref.clone(), - opts.tls.should_force_tls(), - tls_server_config, - 0, - runtime, - None, - None, - )); + let mut pg_server = Box::new( + PostgresServer::new( + fe_instance_ref.clone(), + fe_instance_ref.clone(), + opts.tls.should_force_tls(), + tls_server_config, + 0, + runtime, + None, + None, + ) + .with_influxdb_handler(fe_instance_ref.clone()), + ); pg_server .start(fe_pg_addr.parse::().unwrap()) @@ -1248,16 +1251,19 @@ pub async fn setup_pg_server_with_user_provider( .expect("Failed to load certificates and keys"), ); - let mut pg_server = Box::new(PostgresServer::new( - fe_instance_ref.clone(), - fe_instance_ref.clone(), - opts.tls.should_force_tls(), - tls_server_config, - 0, - runtime, - user_provider, - None, - )); + let mut pg_server = Box::new( + PostgresServer::new( + fe_instance_ref.clone(), + fe_instance_ref.clone(), + opts.tls.should_force_tls(), + tls_server_config, + 0, + runtime, + user_provider, + None, + ) + .with_influxdb_handler(fe_instance_ref.clone()), + ); pg_server .start(fe_pg_addr.parse::().unwrap()) @@ -1304,16 +1310,19 @@ pub async fn setup_pg_server_with_prom_native_histogram( .expect("Failed to load certificates and keys"), ); - let mut pg_server = Box::new(PostgresServer::new( - instance.fe_instance().clone(), - instance.fe_instance().clone(), - opts.tls.should_force_tls(), - tls_server_config, - 0, - runtime, - None, - None, - )); + let mut pg_server = Box::new( + PostgresServer::new( + instance.fe_instance().clone(), + instance.fe_instance().clone(), + opts.tls.should_force_tls(), + tls_server_config, + 0, + runtime, + None, + None, + ) + .with_influxdb_handler(instance.fe_instance().clone()), + ); pg_server .start(fe_pg_addr.parse::().unwrap()) diff --git a/tests-integration/src/tests/postgres_copy_in_test.rs b/tests-integration/src/tests/postgres_copy_in_test.rs index 82e076e7a65..94b19c1315d 100644 --- a/tests-integration/src/tests/postgres_copy_in_test.rs +++ b/tests-integration/src/tests/postgres_copy_in_test.rs @@ -316,6 +316,7 @@ async fn test_postgres_copy_in_failed_copy_then_new_copy() { Err(e) => e, }; assert!(err.as_db_error().is_some(), "{err}"); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; // The connection is usable and a NEW copy succeeds on it. let rows = feed_copy_in( @@ -519,3 +520,302 @@ async fn test_postgres_copy_in_empty_field_is_null() { server.shutdown().await.unwrap(); } + +/// `COPY FROM STDIN WITH (FORMAT influxdb)` ingests line protocol through +/// the same pipeline as the HTTP influxdb write endpoint: lines route to +/// their own measurements, tables are auto-created, and a batch behaves +/// like an HTTP write of the same bytes. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_line_protocol() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + let payload = b"monitor,host=hosta cpu=66.6,memory=1024 1663840496100023100\n\ + monitor,host=hostb memory=1027 1663840496400340001\n\ + weather,location=us-midwest temperature=82 1663840496100023102\n"; + + // Feed byte-by-byte-ish: lines and UTF-8 may span CopyData chunks. + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + payload.chunks(7).map(Bytes::copy_from_slice).collect(), + ) + .await + .unwrap(); + assert_eq!(rows, 3); + + let messages = client + .simple_query("SELECT host, cpu, memory FROM monitor ORDER BY host") + .await + .unwrap(); + let rows: Vec<(String, String, String)> = messages + .iter() + .filter_map(|m| { + let tokio_postgres::SimpleQueryMessage::Row(row) = m else { + return None; + }; + Some(( + row.get(0).unwrap_or("").to_string(), + row.get(1).unwrap_or("").to_string(), + row.get(2).unwrap_or("").to_string(), + )) + }) + .collect(); + assert_eq!( + rows, + vec![ + ("hosta".into(), "66.6".into(), "1024.0".into()), + ("hostb".into(), "".into(), "1027.0".into()), + ] + ); + + let messages = client + .simple_query("SELECT temperature FROM weather") + .await + .unwrap(); + let temps: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + assert_eq!(temps, vec!["82.0".to_string()]); + + server.shutdown().await.unwrap(); +} + +/// The `precision` option carries the HTTP endpoint's semantics: +/// nanosecond timestamps by default, other units on request. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_precision() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_prec").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb, precision 'ms')", + vec![Bytes::from_static(b"prec,host=h v=1 1465839830100\n")], + ) + .await + .unwrap(); + assert_eq!(rows, 1); + + let messages = client + .simple_query("SELECT CAST(greptime_timestamp AS BIGINT) FROM prec") + .await + .unwrap(); + let ts: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + // 1465839830100 ms == 1465839830100000000 ns + assert_eq!(ts.len(), 1); + let ts_ns: i64 = ts[0].parse().unwrap(); + assert_eq!(ts_ns, 1465839830100000000); + + server.shutdown().await.unwrap(); +} + +/// Records with newlines INSIDE quoted field values are one line-protocol +/// record: the parser owns record boundaries, so a CopyData chunk boundary +/// inside the quoted string — the case a naive line splitter breaks on — +/// must not split it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_multiline_quoted_field() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_ml").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + // A record whose string field value contains a physical newline, and + // one with a backslash right before the newline (the parser skips the + // escaped newline; also not a record boundary). + let payload: Vec = b"mlog,host=a line=\"first\nsecond\" 100\n\ + mlog,host=b line=\"tail\\\nmore\" 200\n" + .to_vec(); + + // Split exactly on the internal newline of the first record: chunk 1 + // ends after `first`, chunk 2 starts with the newline. + let split_at = payload.windows(6).position(|w| w == b"first\n").unwrap() + b"first".len(); + let (head, tail) = payload.split_at(split_at); + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![Bytes::copy_from_slice(head), Bytes::copy_from_slice(tail)], + ) + .await + .unwrap(); + assert_eq!(rows, 2); + + let messages = client + .simple_query("SELECT line FROM mlog ORDER BY host") + .await + .unwrap(); + let lines: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + // The quoted values keep their physical newlines: `first`, newline, + // `second`; and `tail`, backslash, newline, `more` (a backslash only + // escapes `\` and `"` in line-protocol strings, so it stays literal + // before the newline). + assert_eq!( + lines, + vec!["first\nsecond".to_string(), "tail\\\nmore".to_string()] + ); + + server.shutdown().await.unwrap(); +} + +/// The payload is bounded by the HTTP write endpoints' own body limit. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_payload_limit() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_cap").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + // The HTTP write endpoints' default body limit (64 MiB) — kept in + // sync with servers::http::DEFAULT_BODY_LIMIT. + let limit = 64 * 1024 * 1024; + // Several chunks over the limit, none containing a record boundary. + let chunk = vec![b'x'; 1024 * 1024]; + let mut sent = 0usize; + let mut sink = Box::pin( + client + .copy_in("COPY FROM STDIN WITH (FORMAT influxdb)") + .await + .unwrap(), + ); + while sent <= limit { + sink.as_mut() + .send(Bytes::from(chunk.clone())) + .await + .unwrap(); + sent += chunk.len(); + } + // The cap fires mid-stream; the error surfaces when the copy + // completes (the sink buffers sends locally). + let error = sink + .as_mut() + .finish() + .await + .expect_err("expected the oversized payload to fail"); + assert!( + error + .as_db_error() + .map(|d| d.message().contains("exceeds")) + .unwrap_or(false), + "unexpected error: {error}" + ); + + // The connection stays usable. + let messages = client.simple_query("SELECT 1").await.unwrap(); + assert!(!messages.is_empty()); + + server.shutdown().await.unwrap(); +} + +/// The regression for the retired line-splitter's failure mode: with +/// 32,767 ordinary records plus a multiline quoted record whose first +/// physical line lands exactly on the old 32,768-line flush threshold — +/// and a CopyData chunk boundary at the quoted value's internal newline — +/// the whole payload must still ingest as one request. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_flush_threshold_multiline() { + init_default_ut_logging(); + let (_guard, server) = + setup_pg_server(StorageType::File, "pg_copy_in_influxdb_threshold").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + // 32,767 ordinary records, then a record whose quoted value spans + // three physical lines. + let mut head = String::new(); + for i in 0..32_767 { + head.push_str(&format!( + "m,host=h{i} v={i} {} +", + 1_000 + i + )); + } + head.push_str("mlog,host=z line=\"first\nsecond\nthird\" 99999"); + let tail = " +" + .to_string(); + + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![ + Bytes::from(head.into_bytes()), + Bytes::from(tail.into_bytes()), + ], + ) + .await + .unwrap(); + assert_eq!(rows, 32_768); + + let messages = client.simple_query("SELECT line FROM mlog").await.unwrap(); + let lines: Vec = messages + .iter() + .filter_map(|m| match m { + tokio_postgres::SimpleQueryMessage::Row(row) => row.get(0).map(str::to_string), + _ => None, + }) + .collect(); + assert_eq!(lines, vec!["first\nsecond\nthird".to_string()]); + + server.shutdown().await.unwrap(); +} + +/// Invalid UTF-8 fails the copy with a clear error and the connection +/// stays usable; a trailing record without a newline is still ingested. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn test_postgres_copy_in_influxdb_invalid_utf8_and_trailing_record() { + init_default_ut_logging(); + let (_guard, server) = setup_pg_server(StorageType::File, "pg_copy_in_influxdb_utf8").await; + let port = server.bind_addr().unwrap().port(); + let client = connect(port).await; + + // Trailing record without a newline: accepted. + let rows = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![Bytes::from_static(b"m2,host=a v=7 300")], + ) + .await + .unwrap(); + assert_eq!(rows, 1); + + // Invalid UTF-8: the copy fails, the connection stays usable. + let error = feed_copy_in( + &client, + "COPY FROM STDIN WITH (FORMAT influxdb)", + vec![Bytes::from_static(b"m3 v=1 100\n\xff\xfe")], + ) + .await + .unwrap_err(); + assert!( + error + .as_db_error() + .map(|d| d.message().contains("not valid UTF-8")) + .unwrap_or(false), + "unexpected error: {error}" + ); + let messages = client.simple_query("SELECT 1").await.unwrap(); + assert!(!messages.is_empty()); + + server.shutdown().await.unwrap(); +} From df33737e9d093d2415df363f2942ff62ef904597 Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Wed, 28 Oct 2026 08:45:10 +0000 Subject: [PATCH 4/7] feat: add shared asynchronous cache primitives (#9790) Signed-off-by: WenyXu --- Cargo.lock | 10 + Cargo.toml | 1 + src/common/cache/Cargo.toml | 16 ++ src/common/cache/src/cache.rs | 473 ++++++++++++++++++++++++++++++++ src/common/cache/src/lib.rs | 21 ++ src/common/cache/src/metrics.rs | 194 +++++++++++++ 6 files changed, 715 insertions(+) create mode 100644 src/common/cache/Cargo.toml create mode 100644 src/common/cache/src/cache.rs create mode 100644 src/common/cache/src/lib.rs create mode 100644 src/common/cache/src/metrics.rs diff --git a/Cargo.lock b/Cargo.lock index 69996d9cbb2..8e4183994d4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2340,6 +2340,16 @@ dependencies = [ "tokio", ] +[[package]] +name = "common-cache" +version = "1.4.0-alpha.0" +dependencies = [ + "futures", + "moka", + "prometheus 0.14.0", + "tokio", +] + [[package]] name = "common-catalog" version = "1.4.0-alpha.0" diff --git a/Cargo.toml b/Cargo.toml index 15539abb2c7..a5e3db37960 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ members = [ "src/cmd", "src/common/base", "src/common/batcher", + "src/common/cache", "src/common/catalog", "src/common/config", "src/common/datasource", diff --git a/src/common/cache/Cargo.toml b/src/common/cache/Cargo.toml new file mode 100644 index 00000000000..1e2f9d83a5a --- /dev/null +++ b/src/common/cache/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "common-cache" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lints] +workspace = true + +[dependencies] +moka = { workspace = true, features = ["future"] } +prometheus.workspace = true + +[dev-dependencies] +futures.workspace = true +tokio = { workspace = true, features = ["macros", "rt", "sync"] } diff --git a/src/common/cache/src/cache.rs b/src/common/cache/src/cache.rs new file mode 100644 index 00000000000..98efb890f29 --- /dev/null +++ b/src/common/cache/src/cache.rs @@ -0,0 +1,473 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::borrow::Borrow; +use std::hash::Hash; +use std::sync::Arc; + +use crate::metrics::{CacheMetrics, CacheSizeMetric, CacheSizeRegistration}; + +/// Reason for releasing an entry from the cache. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RemovalCause { + /// The entry reached its expiration time. + Expired, + /// The entry was explicitly invalidated. + Explicit, + /// A new value replaced the entry. + Replaced, + /// The entry was removed to satisfy the capacity policy. + Size, +} + +impl RemovalCause { + /// Returns the established eviction metric label. + pub fn as_str(self) -> &'static str { + match self { + Self::Expired => "expired", + Self::Explicit => "explicit", + Self::Replaced => "replaced", + Self::Size => "size", + } + } +} + +impl From for RemovalCause { + fn from(value: moka::notification::RemovalCause) -> Self { + match value { + moka::notification::RemovalCause::Expired => Self::Expired, + moka::notification::RemovalCause::Explicit => Self::Explicit, + moka::notification::RemovalCause::Replaced => Self::Replaced, + moka::notification::RemovalCause::Size => Self::Size, + } + } +} + +/// A weighted memory cache with backend-provided asynchronous load deduplication. +/// Values should be inexpensive to clone, such as `Arc` or `Bytes`. +/// Capacity is maintained asynchronously; insertion does not guarantee retention. +#[derive(Clone)] +pub struct Cache { + inner: moka::future::Cache, + capacity: u64, + size_registration: Option, + metrics: Option>, +} + +impl Cache +where + K: Eq + Hash + Send + Sync + 'static, + V: Clone + Send + Sync + 'static, +{ + /// Creates a cache with the caller's weight and eviction accounting. + pub fn new(name: &str, capacity: u64, weigher: W, listener: L) -> Self + where + W: Fn(&K, &V) -> u32 + Send + Sync + 'static, + L: Fn(Arc, V, RemovalCause) + Send + Sync + 'static, + { + Self { + inner: moka::future::Cache::builder() + .name(name) + .max_capacity(capacity) + .support_invalidation_closures() + .weigher(weigher) + .eviction_listener(move |key, value, cause| listener(key, value, cause.into())) + .build(), + capacity, + size_registration: None, + metrics: None, + } + } + + /// Attaches caller-bound metrics without changing existing hit/miss accounting. + pub fn with_metrics(mut self, metrics: Arc) -> Self { + self.metrics = Some(metrics); + self + } + + /// Samples this cache's retained weight when the caller collects byte metrics. + pub fn with_size_metric(mut self, metric: CacheSizeMetric) -> Self { + let cache = self.inner.clone(); + self.size_registration = Some(metric.register(move || cache.weighted_size())); + self + } + + /// Gets a completed value without starting a load. + pub fn get<'a, Q>(&'a self, key: &'a Q) -> impl Future> + Send + 'a + where + K: Borrow, + Q: Hash + Eq + Sync + ?Sized, + { + self.inner.get(key) + } + + /// Shares a successful load among concurrent callers with the same key and error type. + /// Errors are shared with current waiters but are not retained as cached values. + /// Cancelling the active loader lets a remaining caller execute its own loader. + pub async fn try_get_with(&self, key: &Q, load: F) -> Result> + where + K: Borrow, + Q: ToOwned + Hash + Eq + ?Sized, + F: Future>, + E: Send + Sync + 'static, + { + let request = self + .metrics + .as_ref() + .map(|metrics| metrics.requests.start()); + let result = self + .inner + .try_get_with_by_ref(key, async { + // Only the backend-selected loader contributes physical load metrics. + let operation = self.metrics.as_ref().map(|metrics| metrics.loads.start()); + let result = load.await; + if let Some(operation) = operation { + operation.finish(&result); + } + result + }) + .await; + if let Some(request) = request { + request.finish(&result); + } + result + } + + /// Submits a completed value to the cache's admission and eviction policy. + pub async fn insert(&self, key: K, value: V) { + self.inner.insert(key, value).await; + } + + /// Invalidates a completed entry. This does not cancel a concurrent loader. + pub async fn invalidate(&self, key: &Q) + where + K: Borrow, + Q: Hash + Eq + ?Sized, + { + self.inner.invalidate(key).await; + } + + /// Invalidates completed entries matching a predicate. Pending loaders are not fenced. + /// Physical removal and eviction accounting run asynchronously. + pub fn invalidate_if(&self, predicate: F) -> std::io::Result<()> + where + F: Fn(&K, &V) -> bool + Send + Sync + 'static, + { + self.inner + .invalidate_entries_if(predicate) + .map(|_| ()) + .map_err(std::io::Error::other) + } + + /// Returns the configured weight capacity. + pub fn capacity(&self) -> u64 { + self.capacity + } + + /// Returns the approximate number of retained entries. + pub fn entry_count(&self) -> u64 { + self.inner.entry_count() + } + + /// Returns the approximate total retained weight. + pub fn weighted_size(&self) -> u64 { + self.inner.weighted_size() + } + + /// Applies pending admission, eviction, and accounting work. + pub async fn run_pending_tasks(&self) { + self.inner.run_pending_tasks().await; + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use tokio::sync::Notify; + + use super::*; + + // This is also a compile-time contract for generic callers crossing async-trait boundaries. + fn send_lookup<'a, K, V, Q>( + cache: &'a Cache, + key: &'a Q, + ) -> impl Future> + Send + 'a + where + K: Borrow + Eq + Hash + Send + Sync + 'static, + V: Clone + Send + Sync + 'static, + Q: Hash + Eq + Sync + ?Sized, + { + cache.get(key) + } + + #[tokio::test] + async fn test_borrowed_lookup_has_a_send_future() { + let cache = cache(1024); + cache + .insert("key".to_string(), Arc::new("value".to_string())) + .await; + let future: futures::future::BoxFuture<'_, Option>> = + Box::pin(send_lookup(&cache, "key")); + assert_eq!(future.await.as_deref().map(String::as_str), Some("value")); + } + + #[tokio::test] + async fn test_predicate_invalidation_preserves_other_entries() { + let cache = cache(1024); + cache + .insert("old".to_string(), Arc::new("a".to_string())) + .await; + cache + .insert("keep".to_string(), Arc::new("b".to_string())) + .await; + cache.run_pending_tasks().await; + cache.invalidate_if(|key, _| key == "old").unwrap(); + assert!(cache.get("old").await.is_none()); + assert_eq!( + cache.get("keep").await.as_deref().map(String::as_str), + Some("b") + ); + } + + fn cache(capacity: u64) -> Cache> { + Cache::new( + "test", + capacity, + |_, value: &Arc| value.len() as u32, + |_, _, _| {}, + ) + } + + fn operation_metrics(name: &str) -> crate::metrics::OperationMetrics { + use prometheus::{Histogram, HistogramOpts, IntCounter, IntGauge}; + + crate::metrics::OperationMetrics { + started: IntCounter::new(format!("{name}_started"), "test").unwrap(), + succeeded: IntCounter::new(format!("{name}_succeeded"), "test").unwrap(), + failed: IntCounter::new(format!("{name}_failed"), "test").unwrap(), + cancelled: IntCounter::new(format!("{name}_cancelled"), "test").unwrap(), + active: IntGauge::new(format!("{name}_active"), "test").unwrap(), + elapsed: Histogram::with_opts(HistogramOpts::new(format!("{name}_seconds"), "test")) + .unwrap(), + } + } + + fn instrumented_cache() -> (Cache>, Arc) { + let metrics = Arc::new(CacheMetrics { + requests: operation_metrics("requests"), + loads: operation_metrics("loads"), + }); + (cache(1024).with_metrics(metrics.clone()), metrics) + } + + #[tokio::test] + async fn test_metrics_distinguish_requests_from_executed_loads() { + let (cache, metrics) = instrumented_cache(); + // Merely constructing an async call does not start an operation. + drop(cache.try_get_with("unused", async { Ok::<_, ()>(Arc::new(String::new())) })); + assert_eq!(0, metrics.requests.started.get()); + let gate = Notify::new(); + let mut first = Box::pin(cache.try_get_with("key", async { + gate.notified().await; + Ok::<_, ()>(Arc::new("value".to_string())) + })); + let mut second = Box::pin(cache.try_get_with("key", async { Err::, _>(()) })); + assert!(futures::poll!(&mut first).is_pending()); + assert!(futures::poll!(&mut second).is_pending()); + assert_eq!(2, metrics.requests.active.get()); + assert_eq!(1, metrics.loads.active.get()); + gate.notify_waiters(); + let (first, second) = tokio::join!(first, second); + assert!(Arc::ptr_eq(&first.unwrap(), &second.unwrap())); + cache + .try_get_with("key", async { Err::, _>(()) }) + .await + .unwrap(); + assert_eq!(3, metrics.requests.started.get()); + assert_eq!(3, metrics.requests.succeeded.get()); + assert_eq!(1, metrics.loads.started.get()); + assert_eq!(1, metrics.loads.succeeded.get()); + assert_eq!(0, metrics.requests.active.get()); + assert_eq!(0, metrics.loads.active.get()); + assert_eq!(3, metrics.requests.elapsed.get_sample_count()); + assert_eq!(1, metrics.loads.elapsed.get_sample_count()); + assert_eq!(0, metrics.requests.failed.get()); + assert_eq!(0, metrics.requests.cancelled.get()); + } + + #[tokio::test] + async fn test_metrics_release_active_work_on_cancellation_and_error() { + let (cache, metrics) = instrumented_cache(); + let mut producer = + Box::pin(cache.try_get_with("key", std::future::pending::, ()>>())); + let mut waiter = + Box::pin(cache.try_get_with("key", std::future::pending::, ()>>())); + assert!(futures::poll!(&mut producer).is_pending()); + assert!(futures::poll!(&mut waiter).is_pending()); + drop(waiter); + assert_eq!(1, metrics.requests.cancelled.get()); + assert_eq!(0, metrics.loads.cancelled.get()); + drop(producer); + assert_eq!(2, metrics.requests.cancelled.get()); + assert_eq!(1, metrics.loads.cancelled.get()); + let result = cache + .try_get_with("key", async { Err::, _>(()) }) + .await; + assert!(result.is_err()); + assert_eq!(1, metrics.requests.failed.get()); + assert_eq!(1, metrics.loads.failed.get()); + assert_eq!(0, metrics.requests.active.get()); + assert_eq!(0, metrics.loads.active.get()); + assert_eq!(3, metrics.requests.elapsed.get_sample_count()); + assert_eq!(2, metrics.loads.elapsed.get_sample_count()); + } + + #[tokio::test] + async fn test_instrumented_loading_future_is_send() { + fn assert_send(value: T) -> T { + value + } + + let (cache, _) = instrumented_cache(); + assert_send( + cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("value".to_string())) }), + ) + .await + .unwrap(); + } + + #[tokio::test] + async fn test_shares_load_and_bypasses_loader_on_hit() { + let cache = cache(1024); + let calls = AtomicUsize::new(0); + let gate = Notify::new(); + let load = || async { + calls.fetch_add(1, Ordering::Relaxed); + gate.notified().await; + Ok::<_, ()>(Arc::new("value".to_string())) + }; + let mut first = Box::pin(cache.try_get_with("key", load())); + let mut second = Box::pin(cache.try_get_with("key", load())); + assert!(futures::poll!(&mut first).is_pending()); + assert!(futures::poll!(&mut second).is_pending()); + assert_eq!(1, calls.load(Ordering::Relaxed)); + gate.notify_waiters(); + let (first, second) = tokio::join!(first, second); + let first = first.unwrap(); + assert!(Arc::ptr_eq(&first, &second.unwrap())); + let hit = cache + .try_get_with("key", async { Err::, _>(()) }) + .await + .unwrap(); + assert!(Arc::ptr_eq(&first, &hit)); + } + + #[tokio::test] + async fn test_remaining_waiter_loads_after_producer_cancellation() { + let (cache, metrics) = instrumented_cache(); + let mut first = + Box::pin(cache.try_get_with("key", std::future::pending::, ()>>())); + assert!(futures::poll!(&mut first).is_pending()); + let mut second = Box::pin( + cache.try_get_with("key", async { Ok::<_, ()>(Arc::new("retry".to_string())) }), + ); + assert!(futures::poll!(&mut second).is_pending()); + drop(first); + assert_eq!("retry", second.await.unwrap().as_str()); + assert_eq!(2, metrics.requests.started.get()); + assert_eq!(1, metrics.requests.cancelled.get()); + assert_eq!(1, metrics.requests.succeeded.get()); + assert_eq!(2, metrics.loads.started.get()); + assert_eq!(1, metrics.loads.cancelled.get()); + assert_eq!(1, metrics.loads.succeeded.get()); + assert_eq!(0, metrics.requests.active.get()); + assert_eq!(0, metrics.loads.active.get()); + } + + #[tokio::test] + async fn test_errors_are_shared_but_not_cached() { + let (cache, metrics) = instrumented_cache(); + let calls = AtomicUsize::new(0); + let gate = Notify::new(); + let load = || async { + calls.fetch_add(1, Ordering::Relaxed); + gate.notified().await; + Err::, _>("read failed") + }; + let mut first = Box::pin(cache.try_get_with("key", load())); + let mut second = Box::pin(cache.try_get_with("key", load())); + assert!(futures::poll!(&mut first).is_pending()); + assert!(futures::poll!(&mut second).is_pending()); + gate.notify_waiters(); + let (first, second) = tokio::join!(first, second); + assert!(Arc::ptr_eq(&first.unwrap_err(), &second.unwrap_err())); + assert_eq!(2, metrics.requests.failed.get()); + assert_eq!(1, metrics.loads.failed.get()); + assert_eq!(0, metrics.requests.active.get()); + assert_eq!(0, metrics.loads.active.get()); + assert_eq!(1, calls.load(Ordering::Relaxed)); + assert!(cache.get("key").await.is_none()); + assert_eq!( + "retry", + cache + .try_get_with("key", async { + Ok::<_, &'static str>(Arc::new("retry".to_string())) + }) + .await + .unwrap() + .as_str() + ); + } + + #[tokio::test] + async fn test_sampled_size_sums_instances_and_preserves_manual_bytes() { + use crate::metrics::CacheSizeMetrics; + use prometheus::Opts; + use prometheus::core::Collector; + + let metrics = + CacheSizeMetrics::new(Opts::new("test_cache_bytes", "test"), &["type"]).unwrap(); + let manual = metrics.with_label_values(&["shared"]); + manual.set(3); + let make_cache = || { + Cache::new("sampled", 100, |_: &u64, _: &Arc| 7, |_, _, _| {}) + .with_size_metric(metrics.bind(&["shared"])) + }; + let a = make_cache(); + let b = make_cache(); + let sample = || { + metrics.collect()[0].get_metric()[0] + .get_gauge() + .as_ref() + .map_or(0.0, |gauge| gauge.value()) + }; + a.insert(1, Arc::new("one".into())).await; + b.insert(2, Arc::new("two".into())).await; + a.run_pending_tasks().await; + b.run_pending_tasks().await; + assert_eq!(17.0, sample()); + assert_eq!(3, manual.get()); + let consumer = a.get(&1).await.unwrap(); + a.invalidate(&1).await; + a.run_pending_tasks().await; + assert_eq!(10.0, sample()); + drop(consumer); + let cloned = b.clone(); + drop(b); + assert_eq!(10.0, sample()); + drop(cloned); + assert_eq!(3.0, sample()); + } +} diff --git a/src/common/cache/src/lib.rs b/src/common/cache/src/lib.rs new file mode 100644 index 00000000000..58d54adee68 --- /dev/null +++ b/src/common/cache/src/lib.rs @@ -0,0 +1,21 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Shared memory cache primitives with native asynchronous load deduplication. + +mod cache; + +pub mod metrics; + +pub use cache::{Cache, RemovalCause}; diff --git a/src/common/cache/src/metrics.rs b/src/common/cache/src/metrics.rs new file mode 100644 index 00000000000..fd02c32b689 --- /dev/null +++ b/src/common/cache/src/metrics.rs @@ -0,0 +1,194 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::{Arc, Mutex, Weak}; +use std::time::Instant; + +use prometheus::core::{Collector, Desc}; +use prometheus::proto::{Gauge, MetricFamily}; +use prometheus::{Histogram, IntCounter, IntGauge, IntGaugeVec, Opts}; + +/// Caller-bound metrics for native cache loading. No collectors are registered here. +/// Requests count only `try_get_with` calls, including its cache hits and callers sharing +/// another request's load. Plain `get` calls are not counted. Loads count +/// only loader futures actually polled by the backend; their difference is not a waiter count. +#[derive(Clone)] +pub struct CacheMetrics { + pub requests: OperationMetrics, + pub loads: OperationMetrics, +} + +/// Metrics for one operation, with labels bound once when constructing a cache. +/// Completion counters are mutually exclusive. Dropping an unfinished future is cancellation. +#[derive(Clone)] +pub struct OperationMetrics { + pub started: IntCounter, + pub succeeded: IntCounter, + pub failed: IntCounter, + pub cancelled: IntCounter, + pub active: IntGauge, + /// Wall-clock lifetime, including suspended time, for every outcome. + pub elapsed: Histogram, +} + +impl OperationMetrics { + /// Starts tracking an operation and its elapsed time. + pub(crate) fn start(&self) -> OperationGuard<'_> { + self.started.inc(); + self.active.inc(); + OperationGuard { + metrics: self, + started: Instant::now(), + completed: false, + } + } +} + +/// Tracks an operation, recording cancellation if dropped before completion. +pub(crate) struct OperationGuard<'a> { + metrics: &'a OperationMetrics, + started: Instant, + completed: bool, +} + +impl OperationGuard<'_> { + /// Records success or failure and completes the operation. + pub(crate) fn finish(mut self, result: &Result) { + if result.is_ok() { + self.metrics.succeeded.inc(); + } else { + self.metrics.failed.inc(); + } + self.completed = true; + } +} + +impl Drop for OperationGuard<'_> { + fn drop(&mut self) { + if !self.completed { + self.metrics.cancelled.inc(); + } + self.metrics.active.dec(); + self.metrics + .elapsed + .observe(self.started.elapsed().as_secs_f64()); + } +} + +/// Cache byte metrics combining manually maintained gauges and sampled cache weights. +/// Sampling does not force backend maintenance or include pending loader values. +#[derive(Clone)] +pub struct CacheSizeMetrics { + gauges: IntGaugeVec, + sources: Arc>>, +} + +/// A byte metric with labels bound for one or more cache instances. +#[derive(Clone)] +pub struct CacheSizeMetric { + metrics: CacheSizeMetrics, + gauge: IntGauge, +} + +/// Keeps a cache instance registered for size sampling while any owner remains. +#[derive(Clone)] +pub struct CacheSizeRegistration { + _reader: Arc u64 + Send + Sync>, +} + +struct CacheSizeSource { + gauge: IntGauge, + read: Weak u64 + Send + Sync>, +} + +impl CacheSizeMetrics { + /// Creates an unregistered collector. Register a clone with the caller's registry. + pub fn new(opts: Opts, labels: &[&str]) -> prometheus::Result { + Ok(Self { + gauges: IntGaugeVec::new(opts, labels)?, + sources: Arc::new(Mutex::new(Vec::new())), + }) + } + + /// Returns the backing gauges for callers retaining manual accounting. + pub fn gauges(&self) -> &IntGaugeVec { + &self.gauges + } + + /// Returns a manually maintained gauge for existing non-cache accounting. + pub fn with_label_values(&self, labels: &[&str]) -> IntGauge { + self.gauges.with_label_values(labels) + } + + /// Binds labels for sampled cache weights. Instances sharing labels are summed. + pub fn bind(&self, labels: &[&str]) -> CacheSizeMetric { + CacheSizeMetric { + metrics: self.clone(), + gauge: self.gauges.with_label_values(labels), + } + } +} + +impl CacheSizeMetric { + /// Registers a cache-level weight reader without retaining it in the collector. + /// Keep the returned registration alongside the cache, including in its clones. + pub fn register( + &self, + read: impl Fn() -> u64 + Send + Sync + 'static, + ) -> CacheSizeRegistration { + let read: Arc u64 + Send + Sync> = Arc::new(read); + self.metrics + .sources + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(CacheSizeSource { + gauge: self.gauge.clone(), + read: Arc::downgrade(&read), + }); + CacheSizeRegistration { _reader: read } + } +} + +impl Collector for CacheSizeMetrics { + fn desc(&self) -> Vec<&Desc> { + self.gauges.desc() + } + + fn collect(&self) -> Vec { + let mut families = self.gauges.collect(); + let mut sources = self.sources.lock().unwrap_or_else(|e| e.into_inner()); + sources.retain(|source| { + let Some(read) = source.read.upgrade() else { + return false; + }; + let labels = source.gauge.collect(); + for family in &mut families { + for metric in family.mut_metric() { + if metric.get_label() == labels[0].get_metric()[0].get_label() { + let bytes = metric + .get_gauge() + .as_ref() + .map_or(0.0, |gauge| gauge.value()) + + read() as f64; + let mut gauge = Gauge::default(); + gauge.set_value(bytes); + metric.set_gauge(gauge); + } + } + } + true + }); + families + } +} From 05536cd7f52a3b5fbe96f3d3f672b6e9c3855b3e Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Wed, 28 Oct 2026 09:39:45 +0000 Subject: [PATCH 5/7] fix(meta): register failure detectors for regions switched before a rollback (#9989) * fix(meta): register failure detectors for regions switched before a rollback A region migration switches the routes of its tables one table at a time. If it aborts after some tables were switched, those regions are already served by the target, but the rollback deregistered the target's failure detectors for every region and registered only the source's. The target's next heartbeat registers them again, so if the target stopped before sending one, nothing detected its failure and the switched regions stayed unavailable until the metasrv leader changed or the target came back. The rollback now collects, from the routes it already reads, the regions whose leader is the target and resets the target's failure detectors for them at the end. It also skips a table whose route no longer exists, so a table dropped meanwhile no longer fails the rollback before the detectors are handled. Signed-off-by: jeremyhi * test(meta): roll back a downgrading leader in the rollback detector test The table that was not switched yet keeps a downgrading leader in a real abort, so the test now builds it that way and checks that the rollback clears it. Signed-off-by: jeremyhi * fix(meta): monitor regions switched before a rollback only on the target The rollback registered the source's failure detectors for every region of the migration, including the regions already switched to the target. Those regions are served by the target after the rollback, so their source detectors watched the wrong peer: when one fired, the failover found the leader had changed and only removed it. The rollback now registers the source's detectors only for the regions that were not switched, and keeps resetting the target's detectors for the others. Signed-off-by: jeremyhi * refactor(meta): rename reset_failure_detectors_for_candidate_regions to reset_failure_detectors Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- .../src/procedure/region_migration.rs | 110 ++++++++++++++++-- .../rollback_downgraded_region.rs | 3 +- .../upgrade_candidate_region.rs | 3 +- 3 files changed, 103 insertions(+), 13 deletions(-) diff --git a/src/meta-srv/src/procedure/region_migration.rs b/src/meta-srv/src/procedure/region_migration.rs index 75ab5c79397..4f7967dd3c4 100644 --- a/src/meta-srv/src/procedure/region_migration.rs +++ b/src/meta-srv/src/procedure/region_migration.rs @@ -630,13 +630,13 @@ impl Context { Ok(datanode_table_value) } - /// Notifies the RegionSupervisor to register failure detectors of failed region. + /// Notifies the RegionSupervisor to register failure detectors of the given regions on the + /// source peer. /// /// The original failure detector was removed once the procedure was triggered. /// Now, we need to register the failure detector for the failed region again. - pub async fn register_failure_detectors(&self) { + pub async fn register_failure_detectors(&self, region_ids: &[RegionId]) { let datanode_id = self.persistent_ctx.from_peer.id; - let region_ids = &self.persistent_ctx.region_ids; let detecting_regions = region_ids .iter() .map(|region_id| (datanode_id, *region_id)) @@ -650,10 +650,10 @@ impl Context { ); } - /// Notifies the RegionSupervisor to reset failure detectors of candidate regions. - pub async fn reset_failure_detectors_for_candidate_regions(&self) { + /// Notifies the RegionSupervisor to reset failure detectors of the given regions on the target + /// peer. + pub async fn reset_failure_detectors(&self, region_ids: &[RegionId]) { let datanode_id = self.persistent_ctx.to_peer.id; - let region_ids = &self.persistent_ctx.region_ids; let detecting_regions = region_ids .iter() .map(|region_id| (datanode_id, *region_id)) @@ -662,7 +662,7 @@ impl Context { .reset_failure_detectors(detecting_regions) .await; info!( - "Reset failure detectors after migration success for datanode {}, regions {:?}", + "Reset failure detectors of regions for datanode {}, regions {:?}", datanode_id, region_ids ); } @@ -878,12 +878,29 @@ impl RegionMigrationProcedure { .with_label_values(&["rollback"]) .start_timer(); let ctx = &self.context; + let to_peer_id = ctx.persistent_ctx.to_peer.id; let table_regions = ctx.persistent_ctx.table_regions(); + // Regions whose route was switched to the target before the procedure aborted. + let mut switched_regions = Vec::new(); for (table_id, regions) in table_regions { let table_lock = TableLock::Write(table_id).into(); let _guard = procedure_ctx.provider.acquire_lock(&table_lock).await; - let table_route = ctx.get_table_route_value(table_id).await?; + let table_route = match ctx.get_table_route_value(table_id).await { + Ok(table_route) => table_route, + // The table has been dropped meanwhile. + Err(error::Error::TableRouteNotFound { .. }) => continue, + Err(err) => return Err(err), + }; let region_routes = table_route.region_routes().unwrap(); + switched_regions.extend( + region_routes + .iter() + .filter(|route| regions.contains(&route.region.id)) + .filter(|route| { + route.leader_peer.as_ref().map(|peer| peer.id) == Some(to_peer_id) + }) + .map(|route| route.region.id), + ); let downgraded = region_routes .iter() .filter(|route| regions.contains(&route.region.id)) @@ -912,7 +929,24 @@ impl RegionMigrationProcedure { self.context .deregister_failure_detectors_for_candidate_regions() .await; - self.context.register_failure_detectors().await; + // The switched regions are served by the target, so they are monitored there instead. + let unswitched_regions = ctx + .persistent_ctx + .region_ids + .iter() + .filter(|region_id| !switched_regions.contains(region_id)) + .copied() + .collect::>(); + self.context + .register_failure_detectors(&unswitched_regions) + .await; + // The target's next heartbeat would register these detectors again, but nothing would if + // the target stopped before sending one. + if !switched_regions.is_empty() { + self.context + .reset_failure_detectors(&switched_regions) + .await; + } Ok(()) } @@ -1014,8 +1048,8 @@ mod tests { use common_meta::distributed_time_constants::default_distributed_time_constants; use common_meta::instruction::Instruction; - use common_meta::key::test_utils::new_test_table_info; - use common_meta::rpc::router::{Region, RegionRoute}; + use common_meta::key::test_utils::{new_test_table_info, new_test_table_info_with_name}; + use common_meta::rpc::router::{LeaderState, Region, RegionRoute}; use super::*; use crate::handler::HeartbeatMailbox; @@ -1025,12 +1059,66 @@ mod tests { new_downgrade_region_reply, new_flush_region_reply_for_region, new_open_region_reply, new_upgrade_region_reply, }; + use crate::region::supervisor::{Event, RegionFailureDetectorControl}; use crate::service::mailbox::Channel; fn new_persistent_context() -> PersistentContext { test_util::new_persistent_context(1, 2, RegionId::new(1024, 1)) } + #[tokio::test] + async fn test_rollback_registers_detectors_for_switched_regions() { + let env = TestingEnv::new(); + // The route switch aborted after the table of `switched` was switched to the target and + // before the table of `unswitched`, whose leader is still downgrading; the table of + // `dropped` has been dropped. + let switched = RegionId::new(1024, 1); + let unswitched = RegionId::new(1025, 1); + let dropped = RegionId::new(1026, 1); + for (region_id, leader) in [(switched, 2), (unswitched, 1)] { + let table_id = region_id.table_id(); + let table_info = new_test_table_info_with_name(table_id, &format!("table_{table_id}")); + let region_routes = vec![RegionRoute { + region: Region::new_test(region_id), + leader_peer: Some(Peer::empty(leader)), + leader_state: (region_id == unswitched).then_some(LeaderState::Downgrading), + ..Default::default() + }]; + env.create_physical_table_metadata(table_info, region_routes) + .await; + } + let mut persistent_ctx = new_persistent_context(); + persistent_ctx.region_ids = vec![switched, unswitched, dropped]; + let (tx, mut rx) = tokio::sync::mpsc::channel(8); + let mut context_factory = env.context_factory(); + context_factory.region_failure_detector_controller = + Arc::new(RegionFailureDetectorControl::new(tx)); + let mut procedure = RegionMigrationProcedure::new(persistent_ctx, context_factory, vec![]); + + procedure + .rollback_inner(&new_procedure_context()) + .await + .unwrap(); + + // The target's detectors are replaced by the source's, except for `switched`, which stays + // monitored on the target. + let target = [switched, unswitched, dropped].map(|region_id| (2, region_id)); + let source = [unswitched, dropped].map(|region_id| (1, region_id)); + assert_matches!(rx.try_recv(), Ok(Event::DeregisterFailureDetectors(r)) if r == target); + assert_matches!(rx.try_recv(), Ok(Event::RegisterFailureDetectors(r)) if r == source); + assert_matches!(rx.try_recv(), Ok(Event::ResetFailureDetectors(r)) if r == [(2, switched)]); + assert!(rx.try_recv().is_err()); + let table_route = env + .table_metadata_manager() + .table_route_manager() + .table_route_storage() + .get(unswitched.table_id()) + .await + .unwrap() + .unwrap(); + assert_eq!(table_route.region_routes().unwrap()[0].leader_state, None); + } + #[test] fn test_lock_key() { let persistent_context = new_persistent_context(); diff --git a/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs b/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs index 2f0ed0fbe9a..1c9c12a9bc1 100644 --- a/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs +++ b/src/meta-srv/src/procedure/region_migration/update_metadata/rollback_downgraded_region.rs @@ -64,7 +64,8 @@ impl UpdateMetadata { "Rolling back downgraded leader region table route success, table_id: {table_id}, regions: {regions:?}" ); } - ctx.register_failure_detectors().await; + ctx.register_failure_detectors(&ctx.persistent_ctx.region_ids) + .await; Ok(()) } diff --git a/src/meta-srv/src/procedure/region_migration/update_metadata/upgrade_candidate_region.rs b/src/meta-srv/src/procedure/region_migration/update_metadata/upgrade_candidate_region.rs index 5c55891e590..68931e21761 100644 --- a/src/meta-srv/src/procedure/region_migration/update_metadata/upgrade_candidate_region.rs +++ b/src/meta-srv/src/procedure/region_migration/update_metadata/upgrade_candidate_region.rs @@ -215,7 +215,8 @@ impl UpdateMetadata { } ctx.deregister_failure_detectors().await; - ctx.reset_failure_detectors_for_candidate_regions().await; + ctx.reset_failure_detectors(&ctx.persistent_ctx.region_ids) + .await; // Consumes the guard. ctx.volatile_ctx.opening_region_guards.clear(); From 89a5df31418add4a168c7318d4cae55b90ddce00 Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Wed, 28 Oct 2026 11:18:25 +0000 Subject: [PATCH 6/7] fix: ignore stale leader grants after a region is downgraded (#9987) * fix: ignore stale leader grants after a region is downgraded Signed-off-by: jeremyhi * fix: compare stale leader grants with the longest lease seen Signed-off-by: jeremyhi * fix: treat a lease too long to store as unknown A lease longer than a u64 of nanoseconds saturated to a shorter one, so the derived send time could be later than the real one. Now such a lease makes the send time unknown, which counts as earlier than any gate. Signed-off-by: jeremyhi * fix: address review comments on stale leader grants Scope the early send time claim to after a lease has been seen, drop the unused role parameter of demote, clarify a test comment and check that a fresh grant still makes a reopened region writable. Signed-off-by: jeremyhi * refactor: compare stale leader grants with the heartbeat send time Pass the send time of the heartbeat behind a lease to set_region_role_with_lease, and return whether the role was applied. Mito compares the send time with the grant gate directly, so it no longer derives it from the longest lease seen. The datanode finalizes leadership only when the grant was applied. Signed-off-by: jeremyhi * test: cover stale grants through the datanode and repeated downgrades Signed-off-by: jeremyhi * refactor: keep leader grant rules in one region method Apply a role grant in MitoRegion::apply_role_grant, which renews the lease and decides whether the role changes; the engine only looks up the region. Rename the gate to downgrade_started_at and demote to begin_downgrade, keep the field private, and copy it on reopen through inherit_downgrade_state_from. Signed-off-by: jeremyhi * refactor: drop a needless borrow Signed-off-by: jeremyhi * refactor: keep lease concepts in the engine and role ordering in the region ManifestContext, which owns the role, records when the role was last demoted and promotes a region only for a promotion issued after that. The time starts when the context is created, so a reopened region ignores grants for heartbeats sent before the reopen, without copying state. The engine translates leases: it renews the deadline and promotes with the heartbeat send time. MitoRegion keeps no grant state. Signed-off-by: jeremyhi * fix: keep the data region of a metric region off a grant its metadata region ignores The metric engine applies a grant to the metadata region first and stops if it is ignored, so the data region, whose role the engine reports, never becomes a leader that skips finalization. Also describe what promoting returns. Signed-off-by: jeremyhi * docs: describe when a lease grant is ignored and flatten the finalize check Signed-off-by: jeremyhi * refactor: move lease types out of the region and the Leader deadline into ManifestContext Signed-off-by: jeremyhi * refactor: name the promotion fence after the downgrade it records Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- src/datanode/src/alive_keeper.rs | 129 ++++++++++++++++++---- src/datanode/src/region_server.rs | 9 +- src/datanode/src/tests.rs | 8 +- src/file-engine/src/engine.rs | 5 +- src/metric-engine/src/engine.rs | 54 ++++++++-- src/metric-engine/src/engine/put.rs | 2 +- src/mito2/src/engine.rs | 12 ++- src/mito2/src/engine/lease_test.rs | 112 +++++++++++++++++++- src/mito2/src/lease.rs | 91 ++++++++++++++++ src/mito2/src/lib.rs | 1 + src/mito2/src/region.rs | 141 +++++++++++-------------- src/mito2/src/region/opener.rs | 2 - src/mito2/src/worker.rs | 12 ++- src/mito2/src/worker/handle_catchup.rs | 2 +- src/mito2/src/worker/handle_create.rs | 2 +- src/mito2/src/worker/handle_write.rs | 6 +- src/query/src/optimizer/test_util.rs | 3 +- src/store-api/src/region_engine.rs | 7 +- 18 files changed, 457 insertions(+), 141 deletions(-) create mode 100644 src/mito2/src/lease.rs diff --git a/src/datanode/src/alive_keeper.rs b/src/datanode/src/alive_keeper.rs index bef59d715c5..13af76202d5 100644 --- a/src/datanode/src/alive_keeper.rs +++ b/src/datanode/src/alive_keeper.rs @@ -134,13 +134,18 @@ impl RegionAliveKeeper { } } - /// Renews the lease of regions to `deadline`. - async fn renew_region_leases(&self, regions: &[GrantedRegion], deadline: Instant) { + /// Renews the lease of regions to `deadline`, granted for a heartbeat sent at `sent_at`. + async fn renew_region_leases( + &self, + regions: &[GrantedRegion], + sent_at: Instant, + deadline: Instant, + ) { for region in regions { let (role, region_id) = (region.role().into(), RegionId::from(region.region_id)); if let Some(handle) = self.find_handle(region_id).await { handle - .reset_deadline(role, deadline, region.extensions.clone()) + .reset_deadline(role, sent_at, deadline, region.extensions.clone()) .await; } else { warn!( @@ -281,7 +286,7 @@ impl HeartbeatResponseHandler for RegionAliveKeeper { if let Some(mito) = self.region_server.mito_engine() { mito.renew_node_lease(deadline.into_std()); } - self.renew_region_leases(®ion_lease.regions, deadline) + self.renew_region_leases(®ion_lease.regions, start_instant, deadline) .await; self.close_staled_regions(®ion_lease.closeable_region_ids) .await; @@ -296,8 +301,8 @@ enum CountdownCommand { /// 4 * `heartbeat_interval_millis` Start(u64), /// Reset countdown deadline to the given instance. - /// (NextRole, Deadline, ExtensionInfo) - Reset((RegionRole, Instant, HashMap>)), + /// (NextRole, HeartbeatSentAt, Deadline, ExtensionInfo) + Reset((RegionRole, Instant, Instant, HashMap>)), /// Returns the current deadline of the countdown task. #[cfg(test)] Deadline(oneshot::Sender), @@ -377,12 +382,18 @@ impl CountdownTaskHandle { async fn reset_deadline( &self, role: RegionRole, + sent_at: Instant, deadline: Instant, extension_info: HashMap>, ) { if let Err(e) = self .tx - .send(CountdownCommand::Reset((role, deadline, extension_info))) + .send(CountdownCommand::Reset(( + role, + sent_at, + deadline, + extension_info, + ))) .await { warn!( @@ -436,20 +447,25 @@ impl CountdownTask { started = true; } }, - Some(CountdownCommand::Reset((role, deadline, extension_info))) => { + Some(CountdownCommand::Reset((role, sent_at, deadline, extension_info))) => { let prev_role_leader = self.region_server.is_region_leader(self.region_id).unwrap_or(false); - if let Err(err) = self.region_server.set_region_role_with_lease(self.region_id, role, deadline.into_std()) { - if err.status_code() == StatusCode::RegionNotFound { - // Table metadata in metasrv is deleted after its regions are dropped. - // The datanode may still receive lease renewal responses that depend on the metadata - // during the short period before it is removed. - warn!(err; "Failed to set region role to {role} for region {region_id}"); - } else { - error!(err; "Failed to set region role to {role} for region {region_id}"); + let applied = match self.region_server.set_region_role_with_lease(self.region_id, role, sent_at.into_std(), deadline.into_std()) { + Ok(applied) => applied, + Err(err) => { + if err.status_code() == StatusCode::RegionNotFound { + // Table metadata in metasrv is deleted after its regions are dropped. + // The datanode may still receive lease renewal responses that depend on the metadata + // during the short period before it is removed. + warn!(err; "Failed to set region role to {role} for region {region_id}"); + } else { + error!(err; "Failed to set region role to {role} for region {region_id}"); + } + false } + }; - // Finalize leadership: persist backfilled metadata. - } else if !prev_role_leader && role == RegionRole::Leader + // Finalize leadership if the grant was applied: persist backfilled metadata. + if applied && !prev_role_leader && role == RegionRole::Leader && let Err(err) = self .region_server .set_region_role_state_gracefully(self.region_id, SettableRegionRoleState::Leader) @@ -503,26 +519,42 @@ impl CountdownTask { #[cfg(test)] mod test { + use std::sync::atomic::AtomicUsize; + use api::v1::Rows; use api::v1::meta::{HeartbeatResponse, RegionLease}; use common_meta::heartbeat::mailbox::HeartbeatMailbox; use mito2::config::MitoConfig; + use mito2::engine::MITO_ENGINE_NAME; use mito2::test_util::{CreateRequestBuilder, TestEnv, build_rows, rows_schema}; - use store_api::region_engine::RegionEngine; + use store_api::region_engine::{ + RegionEngine, SetRegionRoleStateResponse, SetRegionRoleStateSuccess, + }; use store_api::region_request::{ EnterStagingRequest, RegionPutRequest, StagingPartitionDirective, }; use super::*; - use crate::tests::mock_region_server; + use crate::tests::{MockRegionEngine, mock_region_server}; /// Handles a heartbeat response that grants `regions` for a heartbeat sent now. async fn handle_lease_response(alive_keeper: &RegionAliveKeeper, regions: Vec) { + let sent_at = alive_keeper.epoch().elapsed(); + handle_lease_response_sent_at(alive_keeper, sent_at, regions).await; + } + + /// Handles a heartbeat response that grants `regions` for a heartbeat sent at `sent_at` + /// after the epoch. + async fn handle_lease_response_sent_at( + alive_keeper: &RegionAliveKeeper, + sent_at: Duration, + regions: Vec, + ) { let (tx, _rx) = mpsc::channel(1); let response = HeartbeatResponse { region_lease: Some(RegionLease { regions, - duration_since_epoch: alive_keeper.epoch().elapsed().as_millis() as u64, + duration_since_epoch: sent_at.as_millis() as u64, // The countdown of a granted region does not expire during the test. lease_seconds: 86400, closeable_region_ids: vec![], @@ -534,6 +566,38 @@ mod test { alive_keeper.handle(&mut ctx).await.unwrap(); } + #[tokio::test(flavor = "multi_thread")] + async fn ignored_leader_grant_does_not_finalize_leadership() { + common_telemetry::init_default_ut_logging(); + let region_server = mock_region_server(); + let finalized = Arc::new(AtomicUsize::new(0)); + let (engine, _) = MockRegionEngine::with_custom_apply_fn(MITO_ENGINE_NAME, |engine| { + // The engine ignores the grant, so the region stays a follower. + engine.mock_role = Some(Some(RegionRole::Follower)); + let finalized = finalized.clone(); + engine.handle_set_readonly_gracefully_mock_fn = Some(Box::new(move |_| { + finalized.fetch_add(1, Ordering::Relaxed); + Ok(SetRegionRoleStateResponse::success( + SetRegionRoleStateSuccess::mito(0), + )) + })); + }); + let region_id = RegionId::new(1024, 1); + region_server.register_test_region(region_id, engine); + let alive_keeper = + RegionAliveKeeper::new(region_server.clone(), None, Duration::from_millis(100)); + alive_keeper.register_region(region_id).await; + let grant = GrantedRegion { + region_id: region_id.as_u64(), + role: api::v1::meta::RegionRole::Leader.into(), + extensions: HashMap::new(), + }; + handle_lease_response(&alive_keeper, vec![grant]).await; + // The countdown task has handled the grant once it answers. + alive_keeper.deadline(region_id).await.unwrap(); + assert_eq!(0, finalized.load(Ordering::Relaxed)); + } + #[tokio::test(flavor = "multi_thread")] async fn lease_responses_let_regions_write() { common_telemetry::init_default_ut_logging(); @@ -583,10 +647,26 @@ mod test { role: api::v1::meta::RegionRole::Leader.into(), extensions: HashMap::new(), }; - handle_lease_response(&alive_keeper, vec![grant]).await; + handle_lease_response(&alive_keeper, vec![grant.clone()]).await; // The countdown task has applied the grant once it answers. alive_keeper.deadline(region_id).await.unwrap(); put(region_id).await.unwrap(); + + // A grant for a heartbeat sent before a downgrade does not make the region a leader again. + let sent_before = alive_keeper.epoch().elapsed(); + region_server + .set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower) + .await + .unwrap(); + handle_lease_response_sent_at(&alive_keeper, sent_before, vec![grant.clone()]).await; + alive_keeper.deadline(region_id).await.unwrap(); + assert_eq!(region_server.is_region_leader(region_id), Some(false)); + + // Send times have millisecond precision, so the next heartbeat is sent after the downgrade. + tokio::time::sleep(Duration::from_millis(2)).await; + handle_lease_response(&alive_keeper, vec![grant]).await; + alive_keeper.deadline(region_id).await.unwrap(); + put(region_id).await.unwrap(); } #[tokio::test(flavor = "multi_thread")] @@ -641,6 +721,7 @@ mod test { role: api::v1::meta::RegionRole::Leader.into(), extensions: HashMap::new(), }], + Instant::now(), Instant::now() + Duration::from_millis(200), ) .await; @@ -694,6 +775,7 @@ mod test { countdown_handle .reset_deadline( RegionRole::Leader, + Instant::now(), Instant::now() + Duration::from_millis(heartbeat_interval_millis * 5), HashMap::new(), ) @@ -744,6 +826,7 @@ mod test { role: api::v1::meta::RegionRole::StagingLeader.into(), extensions: HashMap::new(), }], + Instant::now(), Instant::now() + Duration::from_millis(3000), ) .await; @@ -792,6 +875,7 @@ mod test { role: api::v1::meta::RegionRole::Leader.into(), extensions: HashMap::new(), }], + Instant::now(), Instant::now() + Duration::from_millis(3000), ) .await; @@ -834,6 +918,7 @@ mod test { role: api::v1::meta::RegionRole::StagingLeader.into(), extensions: HashMap::new(), }], + Instant::now(), Instant::now() + Duration::from_millis(3000), ) .await; diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 6055b07dbf6..9d4c4b375fb 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -461,20 +461,23 @@ impl RegionServer { .with_context(|_| HandleRegionRequestSnafu { region_id }) } - /// Sets the role of a region from a lease the metasrv grants until `deadline`. + /// Sets the role of a region from a lease the metasrv grants until `deadline`, in reply to a + /// heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because the + /// region was downgraded or (re)opened after `sent_at`. pub fn set_region_role_with_lease( &self, region_id: RegionId, role: RegionRole, + sent_at: std::time::Instant, deadline: std::time::Instant, - ) -> Result<()> { + ) -> Result { let engine = self .inner .region_map .get(®ion_id) .with_context(|| RegionNotFoundSnafu { region_id })?; engine - .set_region_role_with_lease(region_id, role, deadline) + .set_region_role_with_lease(region_id, role, sent_at, deadline) .with_context(|_| HandleRegionRequestSnafu { region_id }) } diff --git a/src/datanode/src/tests.rs b/src/datanode/src/tests.rs index 4fa247d07ca..a126d3429fd 100644 --- a/src/datanode/src/tests.rs +++ b/src/datanode/src/tests.rs @@ -292,10 +292,12 @@ impl RegionEngine for MockRegionEngine { fn set_region_role_with_lease( &self, _region_id: RegionId, - _role: RegionRole, + role: RegionRole, + _sent_at: std::time::Instant, _deadline: std::time::Instant, - ) -> Result<(), BoxedError> { - Ok(()) + ) -> Result { + // A mocked role stays, so a grant of another role is not applied. + Ok(self.mock_role.flatten().is_none_or(|mocked| mocked == role)) } async fn set_region_role_state_gracefully( diff --git a/src/file-engine/src/engine.rs b/src/file-engine/src/engine.rs index be1d141bcbd..98ad7409f43 100644 --- a/src/file-engine/src/engine.rs +++ b/src/file-engine/src/engine.rs @@ -137,9 +137,10 @@ impl RegionEngine for FileRegionEngine { &self, region_id: RegionId, role: RegionRole, + _sent_at: Instant, _deadline: Instant, - ) -> Result<(), BoxedError> { - self.set_region_role(region_id, role) + ) -> Result { + self.set_region_role(region_id, role).map(|_| true) } async fn set_region_role_state_gracefully( diff --git a/src/metric-engine/src/engine.rs b/src/metric-engine/src/engine.rs index 0c1b1114448..319ddc539d2 100644 --- a/src/metric-engine/src/engine.rs +++ b/src/metric-engine/src/engine.rs @@ -388,23 +388,27 @@ impl RegionEngine for MetricEngine { &self, region_id: RegionId, role: RegionRole, + sent_at: Instant, deadline: Instant, - ) -> Result<(), BoxedError> { - // ignore the region not found error + ) -> Result { + // The metadata region goes first. If it ignores the grant, the data region, whose role the + // engine reports, must not take it either. A region that is not found is ignored. for x in [ utils::to_metadata_region_id(region_id), utils::to_data_region_id(region_id), ] { - if let Err(e) = self + match self .inner .mito - .set_region_role_with_lease(x, role, deadline) - && e.status_code() != StatusCode::RegionNotFound + .set_region_role_with_lease(x, role, sent_at, deadline) { - return Err(e); + Ok(true) => {} + Ok(false) => return Ok(false), + Err(e) if e.status_code() != StatusCode::RegionNotFound => return Err(e), + Err(_) => {} } } - Ok(()) + Ok(true) } async fn sync_region( @@ -887,6 +891,42 @@ mod test { assert!(!object_store.exists(&data_region_dir).await.unwrap()); } + #[tokio::test] + async fn test_leader_grant_ignored_by_metadata_region_leaves_data_region() { + let env = TestEnv::new().await; + env.init_metric_region().await; + let (engine, mito) = (env.metric(), env.mito()); + let physical_region_id = env.default_physical_region_id(); + let lease = std::time::Duration::from_secs(10); + // The data region is downgraded before the heartbeat is sent, the metadata region after it. + let downgrade = |region_id| { + mito.set_region_role_state_gracefully(region_id, SettableRegionRoleState::Follower) + }; + downgrade(utils::to_data_region_id(physical_region_id)) + .await + .unwrap(); + let sent_at = Instant::now(); + downgrade(utils::to_metadata_region_id(physical_region_id)) + .await + .unwrap(); + + let grant = |sent_at: Instant| { + engine + .set_region_role_with_lease( + physical_region_id, + RegionRole::Leader, + sent_at, + sent_at + lease, + ) + .unwrap() + }; + assert!(!grant(sent_at)); + assert_eq!(engine.role(physical_region_id), Some(RegionRole::Follower)); + + assert!(grant(Instant::now())); + assert_eq!(engine.role(physical_region_id), Some(RegionRole::Leader)); + } + #[tokio::test] async fn test_role() { let env = TestEnv::new().await; diff --git a/src/metric-engine/src/engine/put.rs b/src/metric-engine/src/engine/put.rs index e8098131612..eac38d0ab39 100644 --- a/src/metric-engine/src/engine/put.rs +++ b/src/metric-engine/src/engine/put.rs @@ -2379,7 +2379,7 @@ mod tests { let at = |n| start + n * Duration::from_secs(10); let grant = |n| { engine - .set_region_role_with_lease(physical_region_id, RegionRole::Leader, at(n)) + .set_region_role_with_lease(physical_region_id, RegionRole::Leader, start, at(n)) .unwrap() }; let expire = |n| mito.freeze_lease_clock(at(n)); diff --git a/src/mito2/src/engine.rs b/src/mito2/src/engine.rs index 3791489d73f..c628b968b2b 100644 --- a/src/mito2/src/engine.rs +++ b/src/mito2/src/engine.rs @@ -1605,15 +1605,21 @@ impl RegionEngine for MitoEngine { &self, region_id: RegionId, role: RegionRole, + sent_at: Instant, deadline: Instant, - ) -> Result<(), BoxedError> { + ) -> Result { let region = self.inner.find_region(region_id).map_err(BoxedError::new)?; // Before the role, and even if the role leaves the region's state unchanged. if role.writable() { - region.leader_deadline.extend(deadline); + region.manifest_ctx.leader_deadline.extend(deadline); + } + if role == RegionRole::Leader { + return Ok(region + .manifest_ctx + .promote_unless_downgrade_started_after(sent_at, region_id)); } region.set_role(role); - Ok(()) + Ok(true) } async fn set_region_role_state_gracefully( diff --git a/src/mito2/src/engine/lease_test.rs b/src/mito2/src/engine/lease_test.rs index a0e68f7e94b..5fa0a897d63 100644 --- a/src/mito2/src/engine/lease_test.rs +++ b/src/mito2/src/engine/lease_test.rs @@ -13,8 +13,10 @@ // limitations under the License. //! Tests that a region acknowledges only writes whose WAL append completed within its leader -//! lease. +//! lease, and that Leader grants for heartbeats sent before a downgrade do not make it writable +//! again. +use std::collections::HashMap; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -24,8 +26,11 @@ use common_error::ext::{BoxedError, ErrorExt}; use common_recordbatch::RecordBatches; use rstest::rstest; use rstest_reuse::apply; -use store_api::region_engine::{RegionEngine, RegionRole}; -use store_api::region_request::{RegionCatchupRequest, RegionPutRequest, RegionRequest}; +use store_api::region_engine::{RegionEngine, RegionRole, SettableRegionRoleState}; +use store_api::region_request::{ + EnterStagingRequest, RegionCatchupRequest, RegionPutRequest, RegionRequest, + StagingPartitionDirective, +}; use store_api::storage::{RegionId, ScanRequest}; use tokio::task::JoinHandle; @@ -34,10 +39,11 @@ use crate::engine::MitoEngine; use crate::engine::basic_test::build_bulk_insert_request; use crate::engine::listener::WriteWalListener; use crate::error::Error; +use crate::region::{RegionLeaderState, RegionRoleState}; use crate::test_util::{ CreateRequestBuilder, LogStoreFactory, TestEnv, build_rows, kafka_log_store_factory, multiple_log_store_factories, prepare_test_for_kafka_log_store, raft_engine_log_store_factory, - rows_schema, + reopen_region, rows_schema, }; const LEASE: Duration = Duration::from_secs(10); @@ -66,10 +72,18 @@ async fn create_region( fn grant(engine: &MitoEngine, role: RegionRole, deadline: Instant) { engine - .set_region_role_with_lease(REGION_ID, role, deadline) + .set_region_role_with_lease(REGION_ID, role, Instant::now(), deadline) .unwrap(); } +/// Grants Leader for a heartbeat sent at `sent_at`, and returns whether the role was applied. +fn grant_leader_at(engine: &MitoEngine, sent_at: Instant) -> bool { + let deadline = Instant::now() + LEASE; + engine + .set_region_role_with_lease(REGION_ID, RegionRole::Leader, sent_at, deadline) + .unwrap() +} + /// Returns a request that writes rows `start..start + 3`. fn put_request(schema: &[ColumnSchema], start: usize) -> RegionRequest { let rows = Rows { @@ -282,3 +296,91 @@ async fn test_upgraded_region_writes_before_leader_grant() { .unwrap(); put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); } + +#[rstest] +#[case::downgrading(SettableRegionRoleState::DowngradingLeader)] +#[case::follower(SettableRegionRoleState::Follower)] +#[tokio::test] +async fn test_stale_leader_grant_after_downgrade(#[case] downgraded_to: SettableRegionRoleState) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("stale-leader-grant").await; + let (_listener, engine, _schema) = create_region(&mut env, None).await; + let sent_before = Instant::now() - Duration::from_millis(1); + engine + .set_region_role_state_gracefully(REGION_ID, downgraded_to) + .await + .unwrap(); + let downgraded = engine.get_region(REGION_ID).unwrap().state(); + // Another downgrade raises the gate again, though the role does not change. + let sent_between = Instant::now(); + engine + .set_region_role_state_gracefully(REGION_ID, downgraded_to) + .await + .unwrap(); + + // Grants for heartbeats sent before either downgrade arrive late. + assert!(!grant_leader_at(&engine, sent_before)); + assert!(!grant_leader_at(&engine, sent_between)); + assert_eq!(downgraded, engine.get_region(REGION_ID).unwrap().state()); + + assert!(grant_leader_at(&engine, Instant::now())); + assert!(engine.get_region(REGION_ID).unwrap().is_writable()); +} + +#[rstest] +#[case::catchup(false)] +#[case::close_and_open(true)] +#[tokio::test] +async fn test_reopened_region_ignores_earlier_grants(#[case] close: bool) { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("reopened-region-grant").await; + let (_listener, engine, schema) = create_region(&mut env, None).await; + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + // The memtable is not empty, so the catchup below reopens the region. + put(&engine, REGION_ID, &schema, 0).await.unwrap().unwrap(); + let sent_before = Instant::now() - Duration::from_millis(1); + let region = engine.get_region(REGION_ID).unwrap(); + if close { + let table_dir = CreateRequestBuilder::new().build().table_dir; + reopen_region(&engine, REGION_ID, table_dir, false, HashMap::new()).await; + } else { + engine + .set_region_role_state_gracefully(REGION_ID, SettableRegionRoleState::Follower) + .await + .unwrap(); + let request = RegionRequest::Catchup(RegionCatchupRequest::default()); + engine.handle_request(REGION_ID, request).await.unwrap(); + } + assert!(!Arc::ptr_eq( + ®ion, + &engine.get_region(REGION_ID).unwrap() + )); + + assert!(!grant_leader_at(&engine, sent_before)); + assert!(!engine.get_region(REGION_ID).unwrap().is_writable()); + + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + assert!(engine.get_region(REGION_ID).unwrap().is_writable()); +} + +#[tokio::test] +async fn test_leader_grant_exits_staging() { + common_telemetry::init_default_ut_logging(); + let mut env = TestEnv::with_prefix("staging-leader-grant").await; + let (_listener, engine, _schema) = create_region(&mut env, None).await; + let request = EnterStagingRequest { + partition_directive: StagingPartitionDirective::RejectAllWrites, + }; + engine + .handle_request(REGION_ID, RegionRequest::EnterStaging(request)) + .await + .unwrap(); + let state = || engine.get_region(REGION_ID).unwrap().state(); + assert_eq!(RegionRoleState::Leader(RegionLeaderState::Staging), state()); + + grant(&engine, RegionRole::Leader, Instant::now() + LEASE); + assert_eq!( + RegionRoleState::Leader(RegionLeaderState::Writable), + state() + ); +} diff --git a/src/mito2/src/lease.rs b/src/mito2/src/lease.rs new file mode 100644 index 00000000000..95e076825eb --- /dev/null +++ b/src/mito2/src/lease.rs @@ -0,0 +1,91 @@ +// Copyright 2023 Greptime Team +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use std::sync::LazyLock; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::time::Instant; + +/// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64]. +static LEASE_EPOCH: LazyLock = LazyLock::new(Instant::now); + +fn lease_nanos(instant: Instant) -> u64 { + instant.saturating_duration_since(*LEASE_EPOCH).as_nanos() as u64 +} + +/// A lease deadline in nanoseconds since [LEASE_EPOCH]. It only moves forward; 0 means none. +#[derive(Debug, Default)] +pub(crate) struct Deadline(AtomicU64); + +impl Deadline { + pub(crate) fn extend(&self, deadline: Instant) { + self.0.fetch_max(lease_nanos(deadline), Ordering::Relaxed); + } + + pub(crate) fn get(&self) -> u64 { + self.0.load(Ordering::Relaxed) + } +} + +/// Lease of this node: the latest deadline of the heartbeat responses that carry region leases. +#[derive(Debug, Default)] +pub(crate) struct NodeLease { + /// Whether writes need a lease. Only a datanode the metasrv controls sets it. + enabled: AtomicBool, + deadline: Deadline, + /// The time of the lease checks while a test freezes it, in the unit of [Deadline]; 0 when + /// it is not frozen. + #[cfg(any(test, feature = "test"))] + frozen_now: AtomicU64, +} + +impl NodeLease { + pub(crate) fn enable(&self) { + self.enabled.store(true, Ordering::Relaxed); + } + + pub(crate) fn is_enabled(&self) -> bool { + self.enabled.load(Ordering::Relaxed) + } + + pub(crate) fn renew(&self, deadline: Instant) { + self.deadline.extend(deadline); + } + + /// Returns the current time in the unit of [Deadline]. + pub(crate) fn now(&self) -> u64 { + #[cfg(any(test, feature = "test"))] + { + let frozen_now = self.frozen_now.load(Ordering::Relaxed); + if frozen_now != 0 { + return frozen_now; + } + } + lease_nanos(Instant::now()) + } + + #[cfg(any(test, feature = "test"))] + pub(crate) fn freeze_clock(&self, at: Instant) { + self.frozen_now + .store(lease_nanos(at).max(1), Ordering::Relaxed); + } + + /// Lets a region created or upgraded on this node write until the node's deadline. The + /// metasrv granted that deadline before the creation or upgrade, so a later migration of the + /// region waits past it. Later responses do not extend it; the region's Leader grants do. + pub(crate) fn seed(&self, leader_deadline: &Deadline) { + leader_deadline + .0 + .fetch_max(self.deadline.get(), Ordering::Relaxed); + } +} diff --git a/src/mito2/src/lib.rs b/src/mito2/src/lib.rs index a01bca47dd7..116e8ed5833 100644 --- a/src/mito2/src/lib.rs +++ b/src/mito2/src/lib.rs @@ -31,6 +31,7 @@ pub mod error; pub mod extension; pub mod flush; pub mod gc; +mod lease; pub mod manifest; pub mod memtable; mod metrics; diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index ef5b24f9de5..923f223c8c7 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -23,8 +23,8 @@ pub(crate) mod version; use std::cell::OnceCell; use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; -use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; -use std::sync::{Arc, LazyLock, Mutex, RwLock}; +use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, RwLock}; use std::time::Instant; use common_base::hash::partition_expr_version; @@ -59,6 +59,7 @@ use crate::error::{ FlushableRegionStateSnafu, InvalidPartitionExprSnafu, RegionNotFoundSnafu, RegionStateSnafu, RegionTruncatedSnafu, Result, UnexpectedSnafu, UpdateManifestSnafu, }; +use crate::lease::Deadline; use crate::manifest::action::{ RegionChange, RegionManifest, RegionMetaAction, RegionMetaActionList, }; @@ -186,8 +187,6 @@ pub struct MitoRegion { /// There are no WAL entries in range [flushed_entry_id, topic_latest_entry_id] for current region, /// which means these WAL entries maybe able to be pruned up to `topic_latest_entry_id`. pub(crate) topic_latest_entry_id: AtomicU64, - /// Deadline of the region's latest Leader or StagingLeader lease from the metasrv. - pub(crate) leader_deadline: Deadline, /// Region stats. pub(crate) region_stats: RegionStats, /// manifest stats @@ -224,80 +223,6 @@ impl RegionStats { pub type MitoRegionRef = Arc; -/// The instant lease deadlines count from, so that a deadline fits in an [AtomicU64]. -static LEASE_EPOCH: LazyLock = LazyLock::new(Instant::now); - -fn lease_nanos(instant: Instant) -> u64 { - instant.saturating_duration_since(*LEASE_EPOCH).as_nanos() as u64 -} - -/// A lease deadline in nanoseconds since [LEASE_EPOCH]. It only moves forward; 0 means none. -#[derive(Debug, Default)] -pub(crate) struct Deadline(AtomicU64); - -impl Deadline { - pub(crate) fn extend(&self, deadline: Instant) { - self.0.fetch_max(lease_nanos(deadline), Ordering::Relaxed); - } - - pub(crate) fn get(&self) -> u64 { - self.0.load(Ordering::Relaxed) - } -} - -/// Lease of this node: the latest deadline of the heartbeat responses that carry region leases. -#[derive(Debug, Default)] -pub(crate) struct NodeLease { - /// Whether writes need a lease. Only a datanode the metasrv controls sets it. - enabled: AtomicBool, - deadline: Deadline, - /// The time of the lease checks while a test freezes it, in the unit of [Deadline]; 0 when - /// it is not frozen. - #[cfg(any(test, feature = "test"))] - frozen_now: AtomicU64, -} - -impl NodeLease { - pub(crate) fn enable(&self) { - self.enabled.store(true, Ordering::Relaxed); - } - - pub(crate) fn is_enabled(&self) -> bool { - self.enabled.load(Ordering::Relaxed) - } - - pub(crate) fn renew(&self, deadline: Instant) { - self.deadline.extend(deadline); - } - - /// Returns the current time in the unit of [Deadline]. - pub(crate) fn now(&self) -> u64 { - #[cfg(any(test, feature = "test"))] - { - let frozen_now = self.frozen_now.load(Ordering::Relaxed); - if frozen_now != 0 { - return frozen_now; - } - } - lease_nanos(Instant::now()) - } - - #[cfg(any(test, feature = "test"))] - pub(crate) fn freeze_clock(&self, at: Instant) { - self.frozen_now - .store(lease_nanos(at).max(1), Ordering::Relaxed); - } - - /// Lets a region created or upgraded on this node write until the node's deadline. The - /// metasrv granted that deadline before the creation or upgrade, so a later migration of the - /// region waits past it. Later responses do not extend it; the region's Leader grants do. - pub(crate) fn seed(&self, leader_deadline: &Deadline) { - leader_deadline - .0 - .fetch_max(self.deadline.get(), Ordering::Relaxed); - } -} - #[derive(Debug, Clone)] pub(crate) struct StagingPartitionInfo { pub(crate) partition_directive: StagingPartitionDirective, @@ -1290,6 +1215,17 @@ pub(crate) struct ManifestContext { /// The state of the region. The region checks the state before updating /// manifest. state: AtomicCell, + /// When the region last began a downgrade. A promotion issued before it does not apply. The + /// lock covers comparing or raising it and the role change. + /// + /// It starts at creation time, so promotions issued before the region was opened or reopened + /// do not apply. A context that replaces this one is created after the worker loop closes or + /// reopens the region, so after its last downgrade began. + downgrade_started_at: Mutex, + /// Deadline of the region's latest Leader or StagingLeader lease from the metasrv, which is how + /// long the Leader role stays valid. The engine extends it from those leases, and writes check + /// it. + pub(crate) leader_deadline: Deadline, /// Partition info of the region in staging mode. /// /// During the staging mode, the region metadata in [`VersionControlRef`] is not updated, @@ -1308,6 +1244,8 @@ impl ManifestContext { ManifestContext { manifest_manager: tokio::sync::RwLock::new(manager), state: AtomicCell::new(state), + downgrade_started_at: Mutex::new(Instant::now()), + leader_deadline: Deadline::default(), staging_partition_info: Mutex::new(None), hook, } @@ -1666,6 +1604,33 @@ impl ManifestContext { self.update_and_fire(manager, action_list, is_staging).await } + /// Raises the downgrade start time to now, then marks the region downgrading. + pub(crate) fn begin_downgrade(&self, region_id: RegionId) { + let mut downgrade_started_at = self.downgrade_started_at.lock().unwrap(); + *downgrade_started_at = Instant::now(); + self.set_role(RegionRole::DowngradingLeader, region_id); + } + + /// Promotes the region to a writable leader unless a downgrade started after `issued_at`. + /// Returns false if the promotion is ignored for that reason; otherwise the role changes as + /// [`Self::set_role`] allows. + pub(crate) fn promote_unless_downgrade_started_after( + &self, + issued_at: Instant, + region_id: RegionId, + ) -> bool { + // A writable leader needs no change; a staging leader is promoted below. + if self.state.load() == RegionRoleState::Leader(RegionLeaderState::Writable) { + return true; + } + let downgrade_started_at = self.downgrade_started_at.lock().unwrap(); + if issued_at < *downgrade_started_at { + return false; + } + self.set_role(RegionRole::Leader, region_id); + true + } + /// Sets the [`RegionRole`]. /// /// ```text @@ -2341,7 +2306,6 @@ mod tests { last_schedule_compaction_millis: Default::default(), time_provider: Arc::new(StdTimeProvider), topic_latest_entry_id: Default::default(), - leader_deadline: Default::default(), region_stats: RegionStats::new(), stats: ManifestStats::default(), } @@ -2457,6 +2421,24 @@ mod tests { } } + #[tokio::test] + async fn test_promoting_writable_leader_takes_no_lock() { + let env = SchedulerEnv::new().await; + let region = Arc::new(build_test_region(&env).await); + let _downgrade_started_at = region.manifest_ctx.downgrade_started_at.lock().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let promoted = region.clone(); + std::thread::spawn(move || { + let manifest_ctx = &promoted.manifest_ctx; + let issued_at = std::time::Instant::now(); + tx.send( + manifest_ctx.promote_unless_downgrade_started_after(issued_at, promoted.region_id), + ) + .unwrap(); + }); + assert!(rx.recv_timeout(std::time::Duration::from_secs(10)).unwrap()); + } + #[tokio::test] async fn test_compaction_update_manifest_allows_editing_state() { let env = SchedulerEnv::new().await; @@ -2945,7 +2927,6 @@ mod tests { last_schedule_compaction_millis: Default::default(), time_provider: Arc::new(StdTimeProvider), topic_latest_entry_id: Default::default(), - leader_deadline: Default::default(), region_stats: RegionStats::new(), stats: ManifestStats::default(), }; diff --git a/src/mito2/src/region/opener.rs b/src/mito2/src/region/opener.rs index 947844c8f20..d10545198f7 100644 --- a/src/mito2/src/region/opener.rs +++ b/src/mito2/src/region/opener.rs @@ -459,7 +459,6 @@ impl RegionOpener { last_schedule_compaction_millis: AtomicI64::new(now), time_provider: self.time_provider.clone(), topic_latest_entry_id: AtomicU64::new(flushed_entry_id), - leader_deadline: Default::default(), region_stats: RegionStats::new(), stats: self.stats, })) @@ -698,7 +697,6 @@ impl RegionOpener { last_schedule_compaction_millis: AtomicI64::new(now), time_provider: self.time_provider.clone(), topic_latest_entry_id: AtomicU64::new(topic_latest_entry_id), - leader_deadline: Default::default(), region_stats: RegionStats::new(), stats: self.stats.clone(), }; diff --git a/src/mito2/src/worker.rs b/src/mito2/src/worker.rs index 50fb5bc0eb1..b93331d99dc 100644 --- a/src/mito2/src/worker.rs +++ b/src/mito2/src/worker.rs @@ -52,7 +52,7 @@ use rand::{Rng, rng}; use snafu::ResultExt; use store_api::logstore::LogStore; use store_api::region_engine::{ - RegionRole, SetRegionRoleStateResponse, SetRegionRoleStateSuccess, SettableRegionRoleState, + SetRegionRoleStateResponse, SetRegionRoleStateSuccess, SettableRegionRoleState, }; use store_api::storage::{FileId, RegionId}; use tokio::sync::mpsc::{Receiver, Sender}; @@ -67,12 +67,13 @@ use crate::config::MitoConfig; use crate::error::{self, CreateDirSnafu, JoinSnafu, Result, WorkerStoppedSnafu}; use crate::flush::{FlushScheduler, WriteBufferManagerImpl, WriteBufferManagerRef}; use crate::gc::{GcLimiter, GcLimiterRef}; +use crate::lease::NodeLease; use crate::memtable::MemtableBuilderProvider; use crate::metrics::{REGION_COUNT, REQUEST_WAIT_TIME, WRITE_STALLING}; use crate::region::opener::PartitionExprFetcherRef; use crate::region::{ - CatchupRegions, CatchupRegionsRef, MitoRegionRef, NodeLease, OpeningRegions, OpeningRegionsRef, - RegionMap, RegionMapRef, + CatchupRegions, CatchupRegionsRef, MitoRegionRef, OpeningRegions, OpeningRegionsRef, RegionMap, + RegionMapRef, }; use crate::request::{ BackgroundNotify, BulkInsertRequest, DdlRequest, OptionOutputTx, SenderBulkRequest, @@ -1516,8 +1517,9 @@ impl RegionWorkerLoop { ) { // Fence writes here: writes the worker handles later see // Downgrading, and earlier ones have finished. This only - // changes a writable or staging leader. - region.set_role(RegionRole::DowngradingLeader); + // changes a writable or staging leader, but always fences + // promotions issued before. + region.manifest_ctx.begin_downgrade(region_id); } #[cfg(feature = "hdfs-object-store")] let sweep_older_than = self.config.gc.unknown_file_lingering_time; diff --git a/src/mito2/src/worker/handle_catchup.rs b/src/mito2/src/worker/handle_catchup.rs index 65f20c5837a..0ca51b98a11 100644 --- a/src/mito2/src/worker/handle_catchup.rs +++ b/src/mito2/src/worker/handle_catchup.rs @@ -87,7 +87,7 @@ impl RegionWorkerLoop { if request.set_writable { // The region takes writes under the node lease until its next Leader // grant. - node_lease.seed(®ion.leader_deadline); + node_lease.seed(®ion.manifest_ctx.leader_deadline); region.set_role(RegionRole::Leader); // Finalize leadership: persist backfilled metadata. match region diff --git a/src/mito2/src/worker/handle_create.rs b/src/mito2/src/worker/handle_create.rs index 15641385e59..d2eab4a3f59 100644 --- a/src/mito2/src/worker/handle_create.rs +++ b/src/mito2/src/worker/handle_create.rs @@ -107,7 +107,7 @@ impl RegionWorkerLoop { } // The region takes writes under the node lease until its first Leader grant. - self.node_lease.seed(®ion.leader_deadline); + self.node_lease.seed(®ion.manifest_ctx.leader_deadline); // Insert the MitoRegion into the RegionMap. self.register_region(region); if let Some(state) = &self.series_index_task_state { diff --git a/src/mito2/src/worker/handle_write.rs b/src/mito2/src/worker/handle_write.rs index 6b8e5be4276..269859cb7e8 100644 --- a/src/mito2/src/worker/handle_write.rs +++ b/src/mito2/src/worker/handle_write.rs @@ -340,7 +340,7 @@ impl RegionWorkerLoop { match region.state() { RegionRoleState::Leader(RegionLeaderState::Writable) | RegionRoleState::Leader(RegionLeaderState::Staging) => { - let leader_deadline = region.leader_deadline.get(); + let leader_deadline = region.manifest_ctx.leader_deadline.get(); if lease_now.is_some_and(|now| now >= leader_deadline) { sender_req .sender @@ -497,7 +497,7 @@ impl RegionWorkerLoop { match region.state() { RegionRoleState::Leader(RegionLeaderState::Writable) | RegionRoleState::Leader(RegionLeaderState::Staging) => { - let leader_deadline = region.leader_deadline.get(); + let leader_deadline = region.manifest_ctx.leader_deadline.get(); if lease_now.is_some_and(|now| now >= leader_deadline) { bulk_req .sender @@ -606,7 +606,7 @@ impl RegionWorkerLoop { for (region_id, region_ctx) in region_ctxs.iter_mut() { // A Leader grant may have extended the deadline during the append. let expired = region_ctx.lease.as_ref().is_some_and(|(region, deadline)| { - now >= *deadline && now >= region.leader_deadline.get() + now >= *deadline && now >= region.manifest_ctx.leader_deadline.get() }); if !expired || region_ctx.is_failed() { continue; diff --git a/src/query/src/optimizer/test_util.rs b/src/query/src/optimizer/test_util.rs index a6b95ffdeba..09f72bb08b7 100644 --- a/src/query/src/optimizer/test_util.rs +++ b/src/query/src/optimizer/test_util.rs @@ -107,8 +107,9 @@ impl RegionEngine for MetaRegionEngine { &self, _region_id: RegionId, _role: RegionRole, + _sent_at: std::time::Instant, _deadline: std::time::Instant, - ) -> Result<(), BoxedError> { + ) -> Result { unimplemented!() } diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 6dffdd03c3b..2a2bc7b7f1f 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -1082,7 +1082,9 @@ pub trait RegionEngine: Send + Sync { /// take effect. fn set_region_role(&self, region_id: RegionId, role: RegionRole) -> Result<(), BoxedError>; - /// Sets [RegionRole] for a region from a lease the metasrv grants until `deadline`. + /// Sets [RegionRole] for a region from a lease the metasrv grants until `deadline`, in reply + /// to a heartbeat sent at `sent_at`. Returns false if the engine ignores a Leader lease because + /// the region was downgraded or (re)opened after `sent_at`. /// /// The region must not acknowledge a write whose WAL append completes at or after the /// deadline of its latest Leader or StagingLeader lease. Leases of other roles do not extend @@ -1091,8 +1093,9 @@ pub trait RegionEngine: Send + Sync { &self, region_id: RegionId, role: RegionRole, + sent_at: Instant, deadline: Instant, - ) -> Result<(), BoxedError>; + ) -> Result; /// Syncs the region manifest to the given manifest version. async fn sync_region( From ebb7e22566f8cb6246f39eab01e32488c682a2c8 Mon Sep 17 00:00:00 2001 From: Weny Xu Date: Wed, 28 Oct 2026 12:51:52 +0000 Subject: [PATCH 7/7] chore(ci): gate fuzz, E2E and KV backends by diff scope (#9927) * ci: gate the integration CI long tail by diff scope `integration.yml` starts its long tail on every pull request: the three fuzz families, the chaos legs, the export/import E2E job and the two sqlness KvBackend legs. Most diffs cannot affect them, so a `scope` job now classifies the pull request and tells those jobs whether to start. The classifier is deterministic and fail-open. Forced modes (merge queue, `schedule`, `workflow_dispatch`, `ci:full`, `CI_SCOPE_FORCE_ALL`) and three floors -- always-run paths, an uncovered `src/` change, and a PromQL/flow filter -- can only widen the result; everything else is a glob match against the suite catalog. Every step of the job is `continue-on-error` and every gate reads `needs.scope.outputs. != 'false'`, so a classifier crash runs the jobs instead of skipping them. The rules are checked out from the pull request base, so a pull request cannot relax its own gate. The policy is data: `.github/ci/scope-rules.toml` holds the path groups, the suite catalog and the always-run list, with a `reason` on every exclusion. `ci_scope_rules.py` loads it with the stdlib `tomllib` and validates the shape (unknown or cyclic `@group` references, a `family` that disagrees with the suite id, an empty reason) and that every glob's literal prefix still exists, so a renamed crate cannot leave a rule that matches nothing. `make check-ci-scope` runs that check locally; the `CI Scope Rules` job runs it on `ubuntu-slim`, the same image the classifier uses. `.github/ci/scope-cases.toml` holds golden cases that `test_ci_scope.py` replays through the real classifier. The PostgreSQL and MySQL sqlness legs move into their own `sqlness-kvbackend` job so they can be gated: a job-level `if:` cannot read the matrix, and gating them inside `sqlness` would skip required checks and block the merge. They run the same cases as the required Basic leg, so only the backend itself matters. The verdict is visible where triage looks: one log line per suite, the exact gate values, `::warning::` when a lookup fails and the gate widens, and a job summary that lists each suite with the rule that decided it and the changed files that matched. Measured on 200 merged and open pull requests: 27.5% always run, 41% decided by path rules, 31.5% skip every gated job; 995 of 2600 suite selections are skipped, with no selection that a path rule makes. The classifier itself runs in about ten seconds on a single-vCPU runner. Signed-off-by: WenyXu * fix(ci): let the scope job read pull requests The `scope` job declared `permissions: contents: read`, and an explicit block sets every unlisted permission to `none`. `GET /pulls/{n}` therefore answered 403, `build_plan` widened to a full run as designed, and every gate read an absent output as "run": the gate could never skip anything. - `pull-requests: read` on the `scope` job. - `tests/runner/**` joins `@kv-backend`: the runner implements `--setup-pg`/`--setup-mysql`, which only the KV-backend legs pass, so a change there must not skip the only job that exercises it. The `UNMAPPED_CRATES` excuse is gone with it. - The README no longer claims a queue failure blocks the merge: the gated jobs are not required checks. Signed-off-by: WenyXu * fix(ci): run every suite when the kind registry script changes The distributed and chaos fuzz jobs start their cluster through `.github/actions/setup-kind`, which runs `.github/scripts/kind-with-registry.sh`. `.github/actions/**` is in `ALWAYS_RUN` but the script is not, so a change confined to it selected no suite at all and every gate stayed `false`: the jobs that exercise the changed cluster setup were skipped. The script joins `ALWAYS_RUN`, consistent with the action that calls it, and a golden case pins it. Signed-off-by: WenyXu * fix(ci): widen the gate for the fuzz corpus seeding script `fuzz-test/action.yaml` runs `.github/scripts/prepare-fuzz-corpus.sh` before the cache restore in every fuzz job, but the script was not in `ALWAYS_RUN`. A change confined to it therefore selected no suite: `any_fuzz` stayed `false` and every fuzz job that runs it was skipped. The script joins `ALWAYS_RUN` next to the other scripts the fuzz jobs execute, with a golden case for it. Both misses so far (this one and `kind-with-registry.sh`) came through a composite action, which the workflow never names. `WorkflowContractTests` now resolves `uses: ./.github/actions/` transitively for the gated jobs and fails when one of the scripts they run is not in `ALWAYS_RUN`. Signed-off-by: WenyXu --------- Signed-off-by: WenyXu --- .github/ci/README.md | 168 ++++ .github/ci/ci_scope.py | 623 ++++++++++++ .github/ci/ci_scope_rules.py | 277 ++++++ .github/ci/scope-rules.toml | 284 ++++++ .github/ci/tests/fixtures/scope-cases.toml | 158 +++ .github/ci/tests/test_ci_scope.py | 1018 ++++++++++++++++++++ .github/scripts/tests/test_ci_slash.py | 2 +- .github/workflows/checks.yml | 19 + .github/workflows/integration.yml | 161 +++- Makefile | 4 + 10 files changed, 2675 insertions(+), 39 deletions(-) create mode 100644 .github/ci/README.md create mode 100755 .github/ci/ci_scope.py create mode 100755 .github/ci/ci_scope_rules.py create mode 100644 .github/ci/scope-rules.toml create mode 100644 .github/ci/tests/fixtures/scope-cases.toml create mode 100755 .github/ci/tests/test_ci_scope.py diff --git a/.github/ci/README.md b/.github/ci/README.md new file mode 100644 index 00000000000..07de1fcae7b --- /dev/null +++ b/.github/ci/README.md @@ -0,0 +1,168 @@ +# Integration CI admission gate + +`integration.yml` runs its expensive jobs — fuzz, export/import E2E, the sqlness +KvBackend legs — on every non-draft pull request. Most pull requests cannot +affect any of them. This directory decides which of those jobs start, using only +the diff. + +The gate can only *skip* work, never add it, and it fails open: when the verdict +is missing or uncertain, every gated job runs. + +| File | Role | +|---|---| +| `ci_scope.py` | the classifier: reads the diff, writes `$GITHUB_OUTPUT` | +| `scope-rules.toml` | the policy: which paths select which suite, as data | +| `ci_scope_rules.py` | loads and validates the policy; `--check-paths` | +| `tests/` | unit tests, and `fixtures/scope-cases.toml` golden cases | + +Two words appear everywhere below. A **suite** is one matrix leg of a gated job, +named `/`. A **gate** is one `$GITHUB_OUTPUT` key that switches a +whole job. + +## What is gated + +Only `integration.yml`, and only these jobs: + +| Gated job | Runs | +|---|---| +| `prepare-fuzz-targets` | the fuzz targets only | +| `fuzztest` | standalone fuzz, 2 legs | +| `unstable-fuzztest` | unstable standalone create-table fuzz, 1 leg | +| `distributed-fuzztest` | distributed fuzz with remote WAL, 4 legs | +| `distributed-fuzztest-with-chaos` | Chaos Mesh, 3 legs | +| `build-greptime-ci` | the profile-CI binary only | +| `export-import-v2-e2e` | CLI `COPY DATABASE` export/import against S3 | +| `sqlness-kvbackend` | sqlness with PostgreSQL and MySQL as the metadata store | + +The legs themselves are the `matrix` entries in `integration.yml`; the rules +file repeats their ids so a verdict can name them. + +Everything else always runs: `rust.yml`, `checks.yml`, `docs.yml`, the debug +`build`, the required `sqlness` job (Basic, Remote WAL, Flat format), `compat` +and `compat-updater-check`. None of the gated jobs is in the required-check +matrix in `docs.yml`, so a skipped job can never block a merge. + +Two choices follow from that rule. The two KvBackend legs sit in their own +`sqlness-kvbackend` job because a job-level `if:` cannot read `matrix`, so +gating them inside `sqlness` would skip required checks and make the pull +request unmergeable. The multi-language SDK job stays ungated: it takes about +three minutes, less than the cost of getting its verdict wrong. + +## How a verdict is made + +First match wins: + +1. **Forced** — `merge_group`, `schedule`, `workflow_dispatch`, the `ci:full` + label or `CI_SCOPE_FORCE_ALL`. Everything runs. +2. **Too large to judge** — more than 300 changed files. Everything runs. +3. **Always-run file changed** — `Cargo.toml`, `Cargo.lock`, `tests-fuzz/**`, + this directory, or anything else that changes what the suites build or how + they start. Everything runs. +4. **Uncovered change** — a path under `src/` that no suite claims. This is the + net for a crate added, split or renamed after the rules were written. + Everything runs. +5. **Path rules** — the suites whose globs match the changed files, and only + those. + +The code is the source of truth for the details; its module docstring is worth +reading before changing it. + +## Why a check was skipped + +The run page's summary pane answers this without opening a log: one row per +suite, with its verdict, the rule that decided it, and up to three of the +changed files that matched. + +The step log of the `CI Scope` job has the same information in text form. It +starts with `CI scope: mode=… full=…` (`grep '^CI scope'` finds it), then one +line per suite — `run` or `skip`, source, reason — then `gates:` with the exact +values the jobs read. + +A degraded decision is never silent. A failed label or file lookup emits +`::warning::` and widens the gate to every suite. + +## Forcing a full run + +Add the `ci:full` label to the pull request and click "Re-run all jobs". The +label is read through the API at run time, not from the event payload, so one +added after the first run still counts. `/ci` dispatch +(`.github/scripts/ci-slash.py`), the `CI_SCOPE_FORCE_ALL` repository variable +and every merge-queue run also run everything: the classifier returns a forced +plan there, so a wrong skip is still exercised before the change lands. None of +the gated jobs is a required check, so a failure in the queue does not block the +merge by itself. + +`CI_SCOPE_FORCE_ALL` is the switch to flip while debugging the rules themselves. + +## Changing the rules + +`scope-rules.toml` is data, not code: `ci_scope_rules.py` loads it with the +standard library's `tomllib`. Two things are validated: + +- the shape — an unknown or cyclic `@group` reference, a `gate` that disagrees + with the suite id, a gate missing from `[gates]`, or an exemption without a + `reason` all raise; +- that every glob still points at something that exists, so a renamed or + deleted crate fails the check instead of silently matching nothing. + +Run both with `make check-ci-scope`, or the path half alone with +`python3 .github/ci/ci_scope_rules.py --check-paths`. The same command runs in +the `CI Scope Rules` job of `checks.yml`, on `ubuntu-slim` — the image the +classifier itself uses, so a path that exists there also exists when the verdict +is computed. + +A malformed file fails the classify step, and because every step of that job is +`continue-on-error`, every gated job runs instead. + +`[[matching.exempt]]` lists paths outside the gate's remit: they select no suite +and never widen the gate. Each one carries a `reason`, and the loader rejects an +empty one — what CI never runs is the part a reader must be able to justify. + +`tests/fixtures/scope-cases.toml` is test data, not configuration: a diff shape +and the suites it must start. `ScopeCaseTests` replays each case through the +classifier, so a rule edit that changes behaviour fails with the case name +instead of silently rerouting CI. The cases carry no pull request numbers; +`git log` has those. + +## Adding a suite + +1. Add a `[suites."/"]` table to `scope-rules.toml` with `gate`, + `paths` (globs or `@group` references) and a one-line `description`. The id + is `/`, and `gate` is that id with `-` replaced by `_`; + the loader and `test_suite_metadata` both enforce it. +2. Add the matching matrix leg to the job in `integration.yml`. +3. Gate the job's `if:` with the matching output, and list `scope` in its + `needs`. A new gate also needs a key in `derive_outputs` and in the `scope` + job's `outputs`; `test_every_gate_routes_to_an_output` fails when that + routing is missing. +4. Add a case to `tests/fixtures/scope-cases.toml` and run + `python3 .github/ci/tests/test_ci_scope.py`. `CrateCoverageTests` separately + fails when a workspace crate matches no suite and is not excused in + `UNMAPPED_CRATES`: the runtime net would run everything, but the rule table + is what should be updated. + +## Ground rules for the workflow + +These six rules keep the gate failing open. Break one and either CI runs jobs it +should have skipped, or a classifier failure takes CI down with it. + +- **Read the output as `!= 'false'`.** An absent output means "run"; writing + `== 'true'` inverts the failure direction. +- **Start every gate with `!cancelled()`.** Without a status function the + condition carries an implicit `success()` over `needs`, so a `scope` job that + times out would skip the gates. Other dependencies are therefore required + explicitly with `needs..result == 'success'`. +- **Every fallible step of `scope` is `continue-on-error: true`.** GitHub skips + the dependents of a *failed* job, so a classifier crash must leave the job + green with no outputs rather than take CI down with it. +- **Rules come from the base revision.** The `scope` job checks out + `pull_request.base.sha` (or `merge_group.base_sha`), so a pull request cannot + weaken its own gate. On the first pull request that introduces this directory + the base has no `ci_scope.py`: the step fails, no outputs are written, and + every gate runs. +- **One gate per job, never per leg.** GitHub does not expose `matrix` to + `jobs..if`. Per-suite verdicts stay visible in the log. +- **Pass the run's `head`/`base` SHAs and let the classifier compare them with + the pull request's live revisions.** A re-run keeps the original SHAs while + GitHub serves the *current* file list; without the comparison the new diff + would be judged against the old tree. With it, a mismatch runs everything. diff --git a/.github/ci/ci_scope.py b/.github/ci/ci_scope.py new file mode 100755 index 00000000000..571e975325a --- /dev/null +++ b/.github/ci/ci_scope.py @@ -0,0 +1,623 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Decide which integration CI suites must run for one pull request. + +Pipeline, in priority order: + +1. forced mode -- `merge_group`, `schedule`, `workflow_dispatch`, + `CI_SCOPE_FORCE_ALL`, or the `ci:full` label. Every suite runs. +2. always-run floor -- a changed file matches `ALWAYS_RUN`. Every suite runs. +3. uncovered build change -- a path under `SRC_TREE` that no suite claims, so a + crate added or renamed later still runs everything. +4. static path matches -- glob match of the changed files against the suite + catalog in `scope-rules.toml`. Paths under `EXEMPT_TREES` are outside the + gate's remit and are dropped first: `@server` claims `src/query/**`, which + would otherwise put a PromQL-only change through the whole fleet. + +The verdict is deterministic: the same diff always produces the same plan, and +a change that no rule explains falls through to "run everything". + +The plan maps to `$GITHUB_OUTPUT` keys that the `integration.yml` gate jobs +consume; `--dry-run` prints them as JSON. +""" + +import argparse +import json +import os +import re +import sys +import urllib.error +import urllib.request + +from ci_scope_rules import ( + ALWAYS_RUN, + EXEMPT_TREES, + SRC_TREE, + SUITES, + suite_group, + suite_paths, +) + +MAX_FILES = 300 +HTTP_TIMEOUT = 45 +FORCED_EVENTS = {"merge_group", "schedule", "workflow_dispatch"} +# A diff with no code, config or workflow file never needs a suite. +CODE_FILE = re.compile( + r"\.(rs|toml|lock|sh|ya?ml)$|(^|/)Makefile$|(^|/)Cargo\.toml$|\.sql$" +) +FUZZ_GATES = ("fuzz_standalone", "fuzz_distributed", "fuzz_chaos") + + +class ScopeError(Exception): + """A handled failure: the caller falls back instead of crashing.""" + + +# --------------------------------------------------------------------------- +# HTTP seam (tests replace `_request`) +# --------------------------------------------------------------------------- + + +def _request(method, url, headers, body=None, timeout=HTTP_TIMEOUT): + request = urllib.request.Request(url, data=body, headers=headers, method=method) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + return response.status, response.read() + except urllib.error.HTTPError as err: + return err.code, err.read() + except (urllib.error.URLError, TimeoutError, OSError) as err: + raise ScopeError(f"{method} {url}: {err}") from err + + +def _get(url, headers, timeout=HTTP_TIMEOUT): + return _request("GET", url, headers, None, timeout) + + +def _post(url, headers, body, timeout=HTTP_TIMEOUT): + return _request("POST", url, headers, body, timeout) + + +def get_json(url, headers, timeout=HTTP_TIMEOUT): + """GET returning (status, parsed json); transport failures raise `ScopeError`.""" + status, raw = _get(url, headers, timeout) + try: + payload = json.loads(raw.decode("utf-8", "replace")) if raw else None + except json.JSONDecodeError: + payload = None + return status, payload + + +# --------------------------------------------------------------------------- +# Path matching +# --------------------------------------------------------------------------- + + +def glob_to_regex(pattern): + """Translate a repo glob into an anchored regexp. + + `**/` also matches zero directories, `**` spans `/`, `*` and `?` do not. + """ + out = ["^"] + index = 0 + while index < len(pattern): + char = pattern[index] + if char == "*": + end = index + while end < len(pattern) and pattern[end] == "*": + end += 1 + if end - index >= 2: + if end < len(pattern) and pattern[end] == "/": + out.append("(?:.*/)?") + index = end + 1 + continue + out.append(".*") + else: + out.append("[^/]*") + index = end + elif char == "?": + out.append("[^/]") + index += 1 + else: + out.append(re.escape(char)) + index += 1 + out.append("$") + return re.compile("".join(out)) + + +def compile_patterns(patterns): + return [glob_to_regex(pattern) for pattern in patterns] + + +def matches_any(filename, compiled): + return any(regex.match(filename) for regex in compiled) + + +# --------------------------------------------------------------------------- +# GitHub API +# --------------------------------------------------------------------------- + + +def github_api(method, path, token, payload=None): + base = os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/") + url = base + path + headers = { + "Accept": "application/vnd.github+json", + "User-Agent": "greptimedb-ci-scope", + } + if token: + headers["Authorization"] = "Bearer " + token + body = None + if payload is not None: + body = json.dumps(payload).encode() + headers["Content-Type"] = "application/json" + if method == "GET": + return get_json(url, headers) + status, raw = _request(method, url, headers, body, HTTP_TIMEOUT) + try: + parsed = json.loads(raw.decode("utf-8", "replace")) if raw else None + except json.JSONDecodeError: + parsed = None + return status, parsed + + +def fetch_changed_files(repo, number, token): + """Return (files, truncated). `truncated` means the PR has more than MAX_FILES.""" + files = [] + page = 1 + while True: + status, payload = github_api( + "GET", f"/repos/{repo}/pulls/{number}/files?per_page=100&page={page}", token + ) + if status != 200 or not isinstance(payload, list): + raise ScopeError(f"cannot list pull request files (HTTP {status})") + for item in payload: + if not isinstance(item, dict): + continue + patch = item.get("patch") + files.append( + { + "filename": item.get("filename", ""), + "previous_filename": item.get("previous_filename") or "", + "status": item.get("status", "modified"), + "additions": item.get("additions", 0), + "deletions": item.get("deletions", 0), + "patch": patch if isinstance(patch, str) else "", + "patch_included": isinstance(patch, str) and bool(patch), + } + ) + if len(payload) < 100: + return files, False + if len(files) >= MAX_FILES: + # Keep `per_page=100`: with `per_page=1`, page N is item N, so the + # probe would answer "is there a file 4?" instead of "file 301?". + status, extra = github_api( + "GET", + f"/repos/{repo}/pulls/{number}/files?per_page=100&page={page + 1}", + token, + ) + if status != 200 or not isinstance(extra, list): + raise ScopeError( + "cannot confirm the changed file list is complete " + f"(HTTP {status})" + ) + del files[MAX_FILES:] + return files, bool(extra) + page += 1 + + +def fetch_pull(repo, number, token): + """Return (labels, head sha, base sha) for one pull request.""" + status, payload = github_api("GET", f"/repos/{repo}/pulls/{number}", token) + if status != 200 or not isinstance(payload, dict): + raise ScopeError(f"cannot read pull request (HTTP {status})") + labels = payload.get("labels") or [] + head = ((payload.get("head") or {}).get("sha") or "").strip() + base = ((payload.get("base") or {}).get("sha") or "").strip() + names = {label.get("name", "") for label in labels if isinstance(label, dict)} + return names, head, base + + +def revision_drift(args, head, base): + """Return a note when the tested revisions are no longer the live ones. + + A re-run keeps the run's original SHAs while the file list served by GitHub + is the pull request's current one. After a force-push the classifier would + judge the new diff for the old tree, so a mismatch runs every suite instead. + """ + for supplied, live, name in ( + (args.head_sha, head, "head"), + (args.base_sha, base, "base"), + ): + if supplied and live and supplied.lower() != live.lower(): + return ( + f"pull request {name} moved from {supplied[:12]} to " + f"{live[:12]} after this run started" + ) + return "" + + +# --------------------------------------------------------------------------- +# Decisions +# --------------------------------------------------------------------------- + + +def file_paths(item): + """Every path the change touched; a rename keeps the deleted side too.""" + names = [item["filename"]] + previous = item.get("previous_filename") + if previous and previous != item["filename"]: + names.append(previous) + return names + + +def gated_paths(item): + """The paths of one changed file that the gate judges. + + A path under `EXEMPT_TREES` is outside the remit: it selects no suite, and + it is not a change that "no rule covers", so it cannot widen the gate. + """ + return [name for name in file_paths(item) if not name.startswith(EXEMPT_TREES)] + + +def path_matches(files): + """Return (always_run_hits, {suite_id: [matching file paths]}).""" + always_compiled = compile_patterns(ALWAYS_RUN) + suite_matchers = { + suite_id: compile_patterns(suite_paths(suite)) + for suite_id, suite in SUITES.items() + } + always_hits = set() + matches = {suite_id: set() for suite_id in SUITES} + for item in files: + for name in file_paths(item): + if matches_any(name, always_compiled): + always_hits.add(name) + for name in gated_paths(item): + for suite_id, compiled in suite_matchers.items(): + if matches_any(name, compiled): + matches[suite_id].add(name) + return sorted(always_hits), { + suite_id: sorted(matched) for suite_id, matched in matches.items() + } + + +def uncovered_changes(files, matches): + """True when a change can reach code that no suite path claims. + + This is the net for a crate that was added, split or renamed after the rules + were written: without it such a change matches no suite and would skip every + gated job. A single unmatched path is enough, even when other paths in the + same diff match a suite. + """ + return first_uncovered(files, matches) is not None + + +def first_uncovered(files, matches): + """The first changed path that no suite claims, or None. + + Naming it is what makes the widening explainable in the log. + """ + matched = {name for names in matches.values() for name in names} + return next( + ( + name + for item in files + for name in gated_paths(item) + if name.startswith(SRC_TREE) and name not in matched + ), + None, + ) + + +def has_meaningful_changes(files): + return any(CODE_FILE.search(item["filename"]) for item in files) + + +def finalize(plan): + """`full` means every gated suite runs, whatever produced the decision.""" + plan["full"] = all(entry["run"] for entry in plan["suites"].values()) + return plan + + +def all_suites(run, reason, source): + return { + suite_id: {"run": run, "source": source, "reason": reason} + for suite_id in SUITES + } + + +def full_plan(plan, reason, source, mode="static"): + """Every suite runs; `finalize` derives `full` from the verdicts.""" + plan.update(mode=mode, suites=all_suites(True, reason, source)) + return finalize(plan) + + +def forced_reason(args, labels): + """Return why every suite must run, or an empty string.""" + event = args.event or os.environ.get("GITHUB_EVENT_NAME") or "pull_request" + if event in FORCED_EVENTS: + return f"event={event}" + if os.environ.get("CI_SCOPE_FORCE_ALL", "").strip().lower() in { + "1", + "true", + "yes", + "on", + }: + return "CI_SCOPE_FORCE_ALL" + if "ci:full" in labels: + return "label ci:full" + return "" + + +def build_plan(args, token): + notes = [] + plan = { + "mode": "static", + "head_sha": args.head_sha or "", + "base_sha": args.base_sha or "", + "full": False, + "suites": {}, + "matching": {}, + "notes": notes, + } + + # Events and variables that force a run need no GitHub call at all; the + # `ci:full` label is the only reason to read the pull request early. + forced = forced_reason(args, set()) + labels, head_live, base_live = set(), "", "" + if args.pr and not forced: + try: + labels, head_live, base_live = fetch_pull( + args.repo, args.pr, token + ) + except ScopeError as err: + # A failed lookup must widen the gate, never narrow it. + notes.append(f"pull request lookup failed: {err}") + return full_plan(plan, "pull request lookup failed", "always-run") + forced = forced_reason(args, labels) + + if forced: + notes.append(f"forced: {forced}") + return full_plan(plan, f"forced by {forced}", "forced", mode="forced") + + if not args.pr: + raise ScopeError("--pr is required unless the event forces every suite") + + drift = revision_drift(args, head_live, base_live) + if drift: + notes.append(drift) + return full_plan(plan, drift, "always-run") + + files, truncated = fetch_changed_files(args.repo, args.pr, token) + if truncated: + notes.append(f"changed file list truncated at {MAX_FILES}") + return full_plan( + plan, + f"pull request has more than {MAX_FILES} changed files", + "always-run", + ) + + always_hits, matches = path_matches(files) + # Keep the evidence: the step summary explains a verdict by naming the files + # that matched, which is what triage asks for first. + plan["matching"] = {suite_id: sorted(names) for suite_id, names in matches.items()} + if always_hits: + notes.append(f"always-run: {', '.join(sorted(always_hits)[:5])}") + return full_plan( + plan, + "always-run path: " + ", ".join(sorted(always_hits)[:3]), + "always-run", + ) + + first = first_uncovered(files, matches) + if first is not None: + notes.append(f"uncovered build change: {first}") + return full_plan(plan, f"uncovered build change: {first}", "uncovered") + + static_run = {suite_id: bool(matched) for suite_id, matched in matches.items()} + + if not has_meaningful_changes(files) and not any(static_run.values()): + plan.update( + mode="static", + full=False, + suites={ + suite_id: { + "run": False, + "source": "static", + "reason": "no code, config or workflow file changed", + } + for suite_id in SUITES + }, + ) + notes.append("no meaningful changes: skip every suite") + return finalize(plan) + + plan.update( + mode="static", + suites={ + suite_id: { + "run": static_run[suite_id], + "source": "static", + "reason": ("path rule: " + ", ".join(matches[suite_id][:3])) + if matches[suite_id] + else "no path rule matched", + } + for suite_id in SUITES + }, + ) + return finalize(plan) + + +def derive_outputs(plan): + """Flatten the plan into the `$GITHUB_OUTPUT` keys the workflow gates on. + + + Every gate in `SUITES` must route to a key here, otherwise its suites are + classified but never switch a job; `test_every_gate_routes_to_an_output` + asks this function directly, so a new gate fails there until it is routed. + + + Job-level `if:` cannot read the `matrix` context, so the workflow gates a + whole fuzz gate instead of individual matrix legs; the per-suite verdicts + stay visible in the step log. + """ + + def suites_of(gate): + return [ + suite_id + for suite_id, entry in plan["suites"].items() + if entry["run"] and SUITES[suite_id]["gate"] == gate + ] + + outputs = {} + legs = {} + for gate in FUZZ_GATES: + running = suites_of(gate) + legs[gate] = [suite_group(suite_id) for suite_id in running] + legs[gate] = [leg for leg in legs[gate] if leg] + outputs[gate] = "true" if running else "false" + unstable = bool(suites_of("fuzz_unstable")) + # Every gate outside the fuzz group switches exactly one job of its own. + for gate in sorted({suite["gate"] for suite in SUITES.values()}): + if gate not in FUZZ_GATES: + outputs[gate] = "true" if suites_of(gate) else "false" + outputs["any_fuzz"] = ( + "true" + if unstable or any(outputs[gate] == "true" for gate in FUZZ_GATES) + else "false" + ) + distributed = outputs["fuzz_distributed"] == "true" or outputs["fuzz_chaos"] == "true" + outputs["build_ci_needed"] = "true" if unstable or distributed else "false" + return outputs, legs + + +def render_log(plan): + """One line per suite plus the emitted gates, for the step log. + + Triage starts in the run log, so the verdict has to be readable there + without any other artifact. + """ + head = f"CI scope: mode={plan['mode']} full={'true' if plan['full'] else 'false'}" + lines = [head] + width = max((len(suite_id) for suite_id in plan["suites"]), default=0) + for suite_id, entry in plan["suites"].items(): + lines.append( + f" {'run ' if entry['run'] else 'skip'} {suite_id:<{width}} " + f"{entry['source']:<12} {entry['reason']}" + ) + outputs, _ = derive_outputs(plan) + lines.append( + " gates: " + " ".join(f"{key}={value}" for key, value in outputs.items()) + ) + for note in plan["notes"]: + lines.append(f" note: {note}") + return "\n".join(lines) + + +SUMMARY_MAX_FILES = 3 + + +def render_summary(plan): + """Markdown for the job summary: the matching evidence behind each verdict. + + The step log answers "what ran"; this answers "why", which is the question + when a pull request unexpectedly skips or starts a suite. + """ + lines = [ + f"### CI scope: mode={plan['mode']}, full={'true' if plan['full'] else 'false'}", + "", + "| suite | verdict | rule | matched files |", + "| --- | --- | --- | --- |", + ] + matching = plan.get("matching") or {} + for suite_id, entry in plan["suites"].items(): + matched = matching.get(suite_id) or [] + shown = ", ".join(f"`{name}`" for name in matched[:SUMMARY_MAX_FILES]) + if len(matched) > SUMMARY_MAX_FILES: + shown += f" +{len(matched) - SUMMARY_MAX_FILES} more" + lines.append( + f"| `{suite_id}` | {'run' if entry['run'] else 'skip'} | " + f"{entry['source']} | {shown or '—'} |" + ) + if plan["notes"]: + lines += ["", "

notes", ""] + lines += [f"- {note}" for note in plan["notes"]] + lines += ["", "
"] + return "\n".join(lines) + + +def log_annotations(plan): + """Workflow-run annotations for every degraded decision. + + A lookup failure widens the gate; it must be visible in the run list without + opening the job log, otherwise it looks like a confident verdict. + """ + annotations = [] + for note in plan["notes"]: + if note.startswith("pull request lookup failed"): + suffix = "every suite runs" + level = "warning" + else: + continue + message = f"CI scope: {note}; {suffix}"[:300] + annotations.append(f"::{level}::{message}") + return annotations + + +def emit(plan, args): + outputs, _ = derive_outputs(plan) + if args.dry_run: + print(json.dumps(outputs, indent=2)) + elif args.github_output: + with open(args.github_output, "a", encoding="utf-8") as handle: + for key, value in outputs.items(): + handle.write(f"{key}={value}\n") + if args.summary: + with open(args.summary, "a", encoding="utf-8") as handle: + handle.write(render_summary(plan) + "\n") + + +def parse_args(argv): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--repo", default=os.environ.get("GITHUB_REPOSITORY", "")) + parser.add_argument("--pr", type=int) + parser.add_argument("--head-sha", default="") + parser.add_argument("--base-sha", default="") + parser.add_argument( + "--event", + choices=["pull_request", "merge_group", "schedule", "workflow_dispatch"], + ) + parser.add_argument("--github-output") + parser.add_argument( + "--summary", + help="append the markdown matching table to this file ($GITHUB_STEP_SUMMARY)", + ) + parser.add_argument("--dry-run", action="store_true") + return parser.parse_args(argv) + + +def main(argv=None): + args = parse_args(argv) + token = os.environ.get("GITHUB_TOKEN") or os.environ.get("GH_TOKEN") or "" + plan = build_plan(args, token) + for annotation in log_annotations(plan): + print(annotation) + print(render_log(plan)) + emit(plan, args) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/ci/ci_scope_rules.py b/.github/ci/ci_scope_rules.py new file mode 100755 index 00000000000..c7453424848 --- /dev/null +++ b/.github/ci/ci_scope_rules.py @@ -0,0 +1,277 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Policy for the integration CI admission gate. + +The rules are data and live in `.github/ci/scope-rules.toml` so they can be +reviewed and changed without touching the classifier. This module parses that +file once at import, validates it, and exposes the names `ci_scope.py` uses. + +A malformed file raises at import: the classifier job's steps are +`continue-on-error`, so a broken rules file leaves the gate outputs empty and +every gated job runs. +""" + +import argparse +import pathlib +import sys +import tomllib + +RULES_PATH = pathlib.Path(__file__).resolve().with_name("scope-rules.toml") +# `.github/ci/scope-rules.toml`: parents[0] is `.github/ci`, parents[2] the repo. +REPO_ROOT = RULES_PATH.parents[2] + + + +class RulesError(ValueError): + """The rules file is missing, malformed or internally inconsistent.""" + + +def _require(table, key, where): + if key not in table: + raise RulesError(f"{where} is missing `{key}`") + return table[key] + + +def _strings(value, where): + if not isinstance(value, list) or not all(isinstance(item, str) for item in value): + raise RulesError(f"{where} must be an array of strings") + return list(value) + + +def _trees(entries, where): + """Normalise `[[matching.*_tree]]` tables into bare path prefixes. + + Each entry carries a `reason`: the exclusions decide what CI never runs, so + the justification is part of the contract, not a comment. + """ + if not isinstance(entries, list): + raise RulesError(f"{where} must be an array of tables") + paths = [] + for index, entry in enumerate(entries): + if not isinstance(entry, dict): + raise RulesError(f"{where}[{index}] is not a table") + path = _require(entry, "path", f"{where}[{index}]") + if not isinstance(path, str) or not path: + raise RulesError(f"{where}[{index}].path must be a non-empty string") + reason = _require(entry, "reason", f"{where}[{index}]") + if not isinstance(reason, str) or not reason.strip(): + raise RulesError(f"{where}[{index}].reason must explain the exclusion") + paths.append(path) + return paths + + +def validate(data): + """Check the shape of a parsed rules document and return it normalised.""" + if not isinstance(data, dict): + raise RulesError("rules document is not a table") + matching = _require(data, "matching", "the rules file") + gates_in = _require(data, "gates", "the rules file") + groups_in = _require(data, "groups", "the rules file") + suites_in = _require(data, "suites", "the rules file") + + groups = {} + for name, paths in groups_in.items(): + groups[name] = _strings(paths, f"groups.{name}") + + def expand(entries, stack=()): + out = [] + for entry in entries: + if not entry.startswith("@"): + out.append(entry) + continue + name = entry[1:] + if name not in groups: + raise RulesError(f"unknown path group `{entry}`") + if name in stack: + raise RulesError(f"path group cycle: {' -> '.join(stack + (name,))}") + out.extend(expand(groups[name], stack + (name,))) + return out + + for name in groups: + expand([f"@{name}"]) # every group must resolve on its own + + suites = {} + for suite_id, suite in suites_in.items(): + if not isinstance(suite, dict): + raise RulesError(f"suites.{suite_id} is not a table") + gate = _require(suite, "gate", f"suites.{suite_id}") + paths = _strings( + _require(suite, "paths", f"suites.{suite_id}"), f"suites.{suite_id}.paths" + ) + description = _require(suite, "description", f"suites.{suite_id}") + if not isinstance(description, str) or not description.strip(): + raise RulesError(f"suites.{suite_id}.description is empty") + # `gate/leg` for a matrix job, or a bare gate for a single-leg job. + prefix = suite_id.split("/", 1)[0].replace("-", "_") + if prefix != gate: + raise RulesError( + f"suites.{suite_id}.gate is `{gate}`, expected `{prefix}`" + ) + expand(paths) + suites[suite_id] = { + "gate": gate, + "paths": paths, + "description": description, + } + + gate_jobs = {} + for gate, job in gates_in.items(): + if not isinstance(job, str) or not job: + raise RulesError(f"gates.{gate} must name a job id") + gate_jobs[gate] = job + used = {suite["gate"] for suite in suites.values()} + unknown = sorted(used - set(gate_jobs)) + if unknown: + raise RulesError(f"suites use gates missing from [gates]: {', '.join(unknown)}") + dead = sorted(set(gate_jobs) - used) + if dead: + raise RulesError(f"[gates] names gates no suite uses: {', '.join(dead)}") + + return { + "always_run": _strings( + _require(matching, "always_run", "matching"), "matching.always_run" + ), + "src_tree": _require(matching, "src_tree", "matching"), + "exempt_trees": _trees( + _require(matching, "exempt", "matching"), "matching.exempt" + ), + "gates": gate_jobs, + "groups": groups, + "suites": suites, + } + + +def load(path=None): + """Parse and validate the rules file.""" + path = RULES_PATH if path is None else path + try: + raw = pathlib.Path(path).read_bytes() + except OSError as err: + raise RulesError(f"cannot read {path}: {err}") from err + try: + data = tomllib.loads(raw.decode("utf-8")) + except (tomllib.TOMLDecodeError, UnicodeDecodeError) as err: + raise RulesError(f"{path} is not valid TOML: {err}") from err + return validate(data) + + +_RULES = load() + +ALWAYS_RUN = _RULES["always_run"] +SRC_TREE = _RULES["src_tree"] +EXEMPT_TREES = tuple(_RULES["exempt_trees"]) +GATE_JOBS = _RULES["gates"] +PATH_GROUPS = _RULES["groups"] +SUITES = _RULES["suites"] + + +def main(argv=None): + """Validate the rules file and print what it holds; non-zero on failure.""" + parser = argparse.ArgumentParser(description="Validate the CI scope rules.") + parser.add_argument( + "--check-paths", + action="store_true", + help="also fail when a pattern's literal prefix does not exist", + ) + args = parser.parse_args(argv) + try: + rules = load() + except RulesError as err: + print(f"scope rules invalid: {err}", file=sys.stderr) + return 1 + if args.check_paths: + missing = missing_paths(rules) + for pattern, prefix in missing: + print(f"missing path: {pattern} (nothing under {prefix})", file=sys.stderr) + return 1 if missing else 0 + print( + f"scope rules ok: {len(rules['suites'])} suites, " + f"{len(rules['groups'])} path groups, " + f"{len(rules['always_run'])} always-run entries" + ) + return 0 + + +def suite_group(suite_id): + """Return the matrix group id encoded in a suite id, or None.""" + _, _, group = suite_id.partition("/") + return group or None + + +def expand_paths(entries, groups=None): + """Expand `@group` references, including groups nested in other groups.""" + groups = PATH_GROUPS if groups is None else groups + patterns = [] + for entry in entries: + if entry.startswith("@"): + patterns.extend(expand_paths(groups[entry[1:]], groups)) + else: + patterns.append(entry) + return patterns + + +def suite_paths(suite): + """Expand `@group` references in one suite definition into globs.""" + return expand_paths(suite["paths"]) + + +def _literal_prefix(pattern): + """Return the longest leading path that the glob cannot vary. + + Everything from the first `*`, `?` or `[` onwards is variable. When that + wildcard sits inside a segment the incomplete segment is dropped, so + `src/a/foo*.rs` yields `src/a/`; a wildcard in the very first segment (for + example `*.md`) yields `""` because the whole path is variable. + """ + cuts = [pattern.find(ch) for ch in "*?[" if ch in pattern] + if not cuts: + return pattern + prefix = pattern[: min(cuts)] + if "/" not in prefix: + return "" + return prefix.rsplit("/", 1)[0] + "/" + + +def _all_patterns(rules): + """Every glob the rules mention, with `@group` references expanded.""" + patterns = [] + for key in ("always_run", "exempt_trees"): + patterns.extend(expand_paths(rules[key], rules["groups"])) + for suite in rules["suites"].values(): + patterns.extend(expand_paths(suite["paths"], rules["groups"])) + return patterns + + +def missing_paths(rules=None, root=None): + """Return `(pattern, prefix)` for patterns whose literal prefix is absent. + + A rule that names a directory nobody renamed would otherwise match nothing + forever, silently narrowing the gate. A pattern with no fixed prefix is + skipped: there is nothing on disk to check. + """ + rules = _RULES if rules is None else rules + root = pathlib.Path(REPO_ROOT if root is None else root) + missing = set() + for pattern in _all_patterns(rules): + prefix = _literal_prefix(pattern) + if prefix and not (root / prefix).exists(): + missing.add((pattern, prefix)) + return sorted(missing) + + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/ci/scope-rules.toml b/.github/ci/scope-rules.toml new file mode 100644 index 00000000000..ba2b92deda2 --- /dev/null +++ b/.github/ci/scope-rules.toml @@ -0,0 +1,284 @@ +# Rules for the integration CI admission gate. +# +# Data only: `ci_scope_rules.py` loads this file with the stdlib `tomllib`, and +# `ci_scope.py` matches diffs against it. Edit this file, not the code, when a +# suite's paths change. +# +# Conventions +# ----------- +# - `**` crosses directories, `*` does not; a trailing `/**` covers everything +# under a directory. +# - `@name` inside `suites.*.paths` expands `[groups].name`, and groups may +# reference other groups. Expansion is recursive. +# - A suite id is `/`; `gate` is the `$GITHUB_OUTPUT` +# key that switches the job, and it must equal the id prefix with `-` +# replaced by `_`. +# - Everything here is a floor, never a filter: an unmatched `src/` path runs +# every suite, and a malformed file fails the classifier job, whose steps are +# `continue-on-error`, so the gated jobs run. + +[matching] +# A changed file matching one of these runs every suite. +# Put here anything that changes what the suites build or how they start. +always_run = [ + "Cargo.toml", + "Cargo.lock", + "rust-toolchain.toml", + ".cargo/**", + "tests-fuzz/**", + "tests-integration/**", + "config/**", + "docker/**", + ".github/ci/**", + ".github/workflows/integration.yml", + ".github/actions/**", + # Both run through a composite action, so neither appears in the workflow: + # `setup-kind` starts the cluster for the distributed and chaos jobs, and + # `fuzz-test` seeds the corpus every fuzz job starts from. + ".github/scripts/kind-with-registry.sh", + ".github/scripts/prepare-fuzz-corpus.sh", + ".github/scripts/run-fuzz-targets.sh", + ".github/scripts/collect-fuzz-target-artifacts.sh", + ".github/scripts/wait-kafka-ready.sh", + ".github/scripts/pull-test-deps-images.sh", +] + +# A change under `src/` that no suite claims runs every suite: that is the net +# for a crate added, split or renamed after these rules were written. +src_tree = "src/" + +# Paths outside the gate's remit. They select no suite, and they do not count as +# "no rule covers this" either, so they never widen the gate. Each needs a +# `reason`: what CI covers them instead. +[[matching.exempt]] +path = "src/promql/" +reason = "PromQL crate: rust.yml and the promql sqlness cases own it; the fuzz suites speak SQL." + +[[matching.exempt]] +path = "src/query/src/promql/" +reason = "PromQL module inside `src/query`, which `@server` claims as `src/query/**`." + +[[matching.exempt]] +path = "src/flow/" +reason = "Flow engine: rust.yml and the flow sqlness cases own it; no fuzz suite loads it." + +# Which job each gate switches. The keys are `$GITHUB_OUTPUT` names; the values +# are job ids in `integration.yml`. The classifier cannot read YAML, so the +# mapping is data here, and a test proves both directions line up. +[gates] +fuzz_standalone = "fuzztest" +fuzz_unstable = "unstable-fuzztest" +fuzz_distributed = "distributed-fuzztest" +fuzz_chaos = "distributed-fuzztest-with-chaos" +export_import_v2 = "export-import-v2-e2e" +sqlness_kvbackend = "sqlness-kvbackend" + +[groups] +server = [ + "src/operator/**", + "src/sql/**", + "src/catalog/**", + "src/datatypes/**", + "src/table/**", + "src/store-api/**", + "src/session/**", + "src/api/**", + "src/servers/**", + "src/frontend/**", + # Also covers `src/query/src/promql/`, which is exempt (see + # `[[matching.exempt]]`): a PromQL-only change must not run the fuzz fleet. + "src/query/**", + "src/partition/**", + "src/index/**", + "src/object-store/**", + "src/cache/**", + "src/puffin/**", + "src/auth/**", + "src/client/**", + "src/log-query/**", + "src/pipeline/**", + "src/plugins/**", + "src/cmd/**", + "src/standalone/**", + "src/datanode/**", + "src/common/base/**", + "src/common/batcher/**", + "src/common/catalog/**", + "src/common/config/**", + "src/common/datasource/**", + "src/common/decimal/**", + "src/common/error/**", + "src/common/event-recorder/**", + "src/common/frontend/**", + "src/common/function/**", + "src/common/grpc/**", + "src/common/grpc-expr/**", + "src/common/greptimedb-telemetry/**", + "src/common/macro/**", + "src/common/mem-prof/**", + "src/common/memory-manager/**", + "src/common/options/**", + "src/common/plugins/**", + "src/common/pprof/**", + "src/common/query/**", + "src/common/recordbatch/**", + "src/common/runtime/**", + "src/common/session/**", + "src/common/sql/**", + "src/common/stat/**", + "src/common/substrait/**", + "src/common/telemetry/**", + "src/common/test-util/**", + "src/common/time/**", + "src/common/version/**", + "src/common/workload/**", +] + +# Storage engines and WAL. +engine = [ + "src/mito2/**", + "src/mito-codec/**", + "src/metric-engine/**", + "src/file-engine/**", + "src/log-store/**", + "src/common/wal/**", +] + +# DDL and procedure code standalone executes in-process: it builds a +# `DdlManager` and runs `LocalProcedureExecutor` without any metasrv. +meta-core = [ + "src/common/meta/**", + "src/common/procedure/**", + "src/common/procedure-test/**", +] + +# Everything that sits on the KV backend the two sqlness KvBackend legs +# exercise: the backend implementations, the metadata service and the startup +# wiring that picks a backend. +kv-backend = [ + # The runner implements `--setup-pg`/`--setup-mysql`, which only these legs pass. + "tests/runner/**", + "src/common/meta/**", + "src/meta-srv/**", + "src/meta-client/**", + "src/common/procedure/**", + "src/cmd/**", + "src/common/config/**", + "src/common/options/**", +] + +# Adds the metasrv/meta-client crates on top of the in-process DDL code. +meta = [ + "src/meta-srv/**", + "src/meta-client/**", + "@meta-core", +] + +[suites."fuzz-standalone/database-and-regular-table"] +gate = "fuzz_standalone" +paths = [ + "@server", + "@engine", + "@meta-core", +] +description = "Standalone-server black-box fuzz of CREATE DATABASE/TABLE, ALTER, INSERT over MySQL." + +[suites."fuzz-standalone/logical-table"] +gate = "fuzz_standalone" +paths = [ + "@server", + "@engine", + "@meta-core", +] +description = "Standalone logical-table DDL/INSERT fuzz (mito2 logical tables)." + +[suites."fuzz-unstable/standalone"] +gate = "fuzz_unstable" +paths = [ + "@server", + "@engine", + "@meta-core", +] +description = "Unstable standalone create-table fuzz (nix build feature)." + +[suites."fuzz-distributed/database-and-regular-table"] +gate = "fuzz_distributed" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Distributed (frontend/datanode/metasrv, remote WAL) DDL/DML fuzz." + +[suites."fuzz-distributed/logical-table"] +gate = "fuzz_distributed" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Distributed logical-table fuzz." + +[suites."fuzz-distributed/repartition"] +gate = "fuzz_distributed" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Distributed repartition ALTER TABLE + GC fuzz." + +[suites."fuzz-distributed/logical-pruning"] +gate = "fuzz_distributed" +paths = [ + "@engine", + "@meta", +] +description = "Remote-WAL logical table pruning of stale manifests." + +[suites."fuzz-chaos/migration"] +gate = "fuzz_chaos" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Region migration under Chaos Mesh, mito and metric engines." + +[suites."fuzz-chaos/failover"] +gate = "fuzz_chaos" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Region failover under Chaos Mesh, mito and metric engines." + +[suites."fuzz-chaos/repartition"] +gate = "fuzz_chaos" +paths = [ + "@server", + "@engine", + "@meta", +] +description = "Repartition + GC under Chaos Mesh." + +[suites."export-import-v2"] +gate = "export_import_v2" +paths = [ + "src/cli/**", + "@server", + "@engine", + "@meta-core", +] +description = "CLI COPY DATABASE export/import v2 end-to-end against S3." + +[suites."sqlness-kvbackend/metasrv-postgres"] +gate = "sqlness_kvbackend" +paths = ["@kv-backend"] +description = "Sqlness with PostgreSQL as the metadata KV backend." + +[suites."sqlness-kvbackend/metasrv-mysql"] +gate = "sqlness_kvbackend" +paths = ["@kv-backend"] +description = "Sqlness with MySQL as the metadata KV backend." diff --git a/.github/ci/tests/fixtures/scope-cases.toml b/.github/ci/tests/fixtures/scope-cases.toml new file mode 100644 index 00000000000..d159bd3e32d --- /dev/null +++ b/.github/ci/tests/fixtures/scope-cases.toml @@ -0,0 +1,158 @@ +# Golden cases for the admission gate. +# +# `tests/test_ci_scope.py` replays every case through the real classifier, +# so an edit to `scope-rules.toml` that changes behaviour fails with the case +# name here. The cases encode intent, not implementation: each one says which +# suites a kind of change must start. +# +# `suites` is a list of globs over suite ids; `["*"]` means every suite and +# `[]` means none. + +[[case]] +name = "server crate: the whole fuzz fleet except the pruning suite" +note = "A change to `src/api` reaches every suite that builds the server binary." +paths = [ + "src/api/src/lib.rs", +] +suites = [ + "fuzz-standalone/database-and-regular-table", + "fuzz-standalone/logical-table", + "fuzz-unstable/standalone", + "fuzz-distributed/database-and-regular-table", + "fuzz-distributed/logical-table", + "fuzz-distributed/repartition", + "fuzz-chaos/migration", + "fuzz-chaos/failover", + "fuzz-chaos/repartition", + "export-import-v2", +] + +[[case]] +name = "storage engine: every fuzz suite, including remote-WAL pruning" +note = "logical-pruning needs engine and DDL code, so an engine change starts it." +paths = [ + "src/mito2/src/lib.rs", +] +suites = [ + "fuzz-standalone/*", + "fuzz-unstable/*", + "fuzz-distributed/*", + "fuzz-chaos/*", + "export-import-v2", +] + +[[case]] +name = "in-process DDL code registers the procedures standalone executes" +paths = [ + "src/common/meta/src/lib.rs", +] +suites = [ + "fuzz-standalone/*", + "fuzz-unstable/*", + "fuzz-distributed/*", + "fuzz-chaos/*", + "export-import-v2", + "sqlness-kvbackend/*", +] + +[[case]] +name = "metasrv only: distributed and chaos families" +note = "Standalone builds a DdlManager in-process and never links a metasrv." +paths = [ + "src/meta-srv/src/discovery/lease.rs", +] +suites = [ + "fuzz-distributed/database-and-regular-table", + "fuzz-distributed/logical-table", + "fuzz-distributed/repartition", + "fuzz-distributed/logical-pruning", + "fuzz-chaos/migration", + "fuzz-chaos/failover", + "fuzz-chaos/repartition", + "sqlness-kvbackend/*", +] + +[[case]] +name = "CLI only touches the export/import path" +paths = [ + "src/cli/src/lib.rs", +] +suites = [ + "export-import-v2", +] + +[[case]] +name = "PromQL crate: no suite" +note = "rust.yml and the promql sqlness cases own it; the fuzz suites speak SQL." +paths = [ + "src/promql/src/lib.rs", +] +suites = [] + +[[case]] +name = "PromQL module inside the query crate is not fuzzable either" +note = "`@server` claims `src/query/**`, so the module must be exempt." +paths = [ + "src/query/src/promql/src/lib.rs", +] +suites = [] + +[[case]] +name = "flow engine: no suite" +paths = [ + "src/flow/src/lib.rs", +] +suites = [] + +[[case]] +name = "mixed diff: the PromQL file subtracts nothing" +note = "The engine change still starts every suite." +paths = [ + "src/mito2/src/lib.rs", + "src/promql/src/lib.rs", +] +suites = [ + "fuzz-standalone/*", + "fuzz-unstable/*", + "fuzz-distributed/*", + "fuzz-chaos/*", + "export-import-v2", +] + +[[case]] +name = "crate added after the rules were written" +note = "No suite claims it, so the gate widens instead of skipping everything." +paths = [ + "src/brand-new/src/lib.rs", +] +suites = ["*"] + +[[case]] +name = "integration harness change" +paths = [ + "tests-integration/tests/fuzz.rs", +] +suites = ["*"] + +[[case]] +name = "documentation only" +paths = [ + "docs/readme.md", +] +suites = [] + +[[case]] +name = "kind registry setup: every suite" +note = "The distributed and chaos fuzz jobs start their cluster with this script." +paths = [ + ".github/scripts/kind-with-registry.sh", +] +suites = ["*"] + +[[case]] +name = "fuzz corpus seeding: every suite" +note = "Every fuzz job seeds its corpus through the `fuzz-test` action first." +paths = [ + ".github/scripts/prepare-fuzz-corpus.sh", +] +suites = ["*"] diff --git a/.github/ci/tests/test_ci_scope.py b/.github/ci/tests/test_ci_scope.py new file mode 100755 index 00000000000..77839aaaffa --- /dev/null +++ b/.github/ci/tests/test_ci_scope.py @@ -0,0 +1,1018 @@ +#!/usr/bin/env python3 +# Copyright 2023 Greptime Team +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Offline tests for the integration CI admission gate.""" + +import contextlib +import fnmatch +import io +import json +import os +import re +import pathlib +import sys +import tempfile +import tomllib +import unittest +from urllib.parse import parse_qs, urlparse + +GATE_DIR = pathlib.Path(__file__).resolve().parents[1] +WORKFLOWS = GATE_DIR.parent / "workflows" +REPO_ROOT = GATE_DIR.parents[1] +sys.path.insert(0, str(GATE_DIR)) + +import ci_scope # noqa: E402 +import ci_scope_rules # noqa: E402 + +SCOPE_CASES = pathlib.Path(__file__).resolve().parent / "fixtures" / "scope-cases.toml" +from ci_scope_rules import ( # noqa: E402 + ALWAYS_RUN, + PATH_GROUPS, + SUITES, + suite_paths, +) + +def file_entry(name, patch="@@ -1 +1 @@\n- old\n+ new\n", status="modified"): + entry = { + "filename": name, + "status": status, + "additions": 1, + "deletions": 1, + } + if patch is not None: + entry["patch"] = patch + return entry + + +class FakeHTTP: + """Records requests and serves canned GitHub API responses.""" + + def __init__(self): + self.calls = [] + self.file_pages = {1: []} + self.labels = [] + self.pull_status = 200 + self.draft = False + self.head_sha = "" + self.base_sha = "" + self.file_queries = [] + + def __call__(self, method, url, headers, body=None, timeout=None): + parsed = urlparse(url) + query = parse_qs(parsed.query) + self.calls.append((method, parsed.path, query.get("page", ["1"])[0])) + if parsed.path.endswith("/files"): + self.file_queries.append(dict(query)) + page = int(query.get("page", ["1"])[0]) + per_page = int(query.get("per_page", ["100"])[0]) + items = [] + for pageno in sorted(self.file_pages): + canned = self.file_pages[pageno] + if isinstance(canned, int): + # An int stands for an HTTP error status for that page. + if pageno == page: + return canned, b"{}" + continue + items.extend(canned) + # `file_pages` is stored at per_page=100; honour the requested + # window so a probe at per_page=1 cannot read past item 1. + start = (page - 1) * per_page + return 200, json.dumps(items[start : start + per_page]).encode() + if parsed.path.endswith("/pulls/1"): + if self.pull_status != 200: + return self.pull_status, b"{}" + return 200, json.dumps( + { + "labels": [{"name": name} for name in self.labels], + "head": {"sha": self.head_sha}, + "base": {"sha": self.base_sha}, + } + ).encode() + return 404, b"{}" + + +class ScopeTestCase(unittest.TestCase): + def setUp(self): + self.fake = FakeHTTP() + self._original = ci_scope._request + ci_scope._request = self.fake + self._environ = dict(os.environ) + for key in ["CI_SCOPE_FORCE_ALL"]: + os.environ.pop(key, None) + os.environ["GITHUB_API_URL"] = "https://api.github.com" + + def tearDown(self): + ci_scope._request = self._original + os.environ.clear() + os.environ.update(self._environ) + + def plan(self, files, pages=None, event="pull_request", extra_args=(), pr=1): + if pages is None: + pages = {1: files} + self.fake.file_pages = dict(pages) + args = ci_scope.parse_args( + ["--repo", "GreptimeTeam/greptimedb", "--pr", str(pr), "--event", event] + + list(extra_args) + ) + return ci_scope.build_plan(args, "token") + + def assert_all_run(self, plan): + for suite_id, entry in plan["suites"].items(): + self.assertTrue(entry["run"], suite_id) + + +class GlobTests(unittest.TestCase): + def test_double_star_crosses_directories(self): + regex = ci_scope.glob_to_regex("src/**/*.rs") + self.assertTrue(regex.match("src/a.rs")) + self.assertTrue(regex.match("src/a/b/c.rs")) + self.assertFalse(regex.match("tests/a.rs")) + + def test_single_star_stays_in_one_segment(self): + regex = ci_scope.glob_to_regex("src/*.rs") + self.assertTrue(regex.match("src/main.rs")) + self.assertFalse(regex.match("src/cmd/main.rs")) + self.assertFalse(regex.match("src/main.toml")) + + def test_question_mark_matches_one_character(self): + regex = ci_scope.glob_to_regex("a?.rs") + self.assertTrue(regex.match("ab.rs")) + self.assertFalse(regex.match("abc.rs")) + self.assertFalse(regex.match("a/.rs")) + + def test_suffix_glob(self): + regex = ci_scope.glob_to_regex(".cargo/**") + self.assertTrue(regex.match(".cargo/config.toml")) + self.assertFalse(regex.match("cargo/config.toml")) + + def test_suite_groups_expand(self): + for group in PATH_GROUPS: + self.assertTrue(PATH_GROUPS[group]) + self.assertTrue(any( + entry == "@" + group + for suite in SUITES.values() + for entry in suite["paths"] + ), group) + paths = suite_paths(SUITES["fuzz-distributed/repartition"]) + self.assertIn("src/mito2/**", paths) + self.assertIn("src/meta-srv/**", paths) + self.assertNotIn("@server", paths) + + def test_every_gate_routes_to_an_output(self): + # Ask the producer, not a copy of its key list: a new gate must fail + # here until `derive_outputs` routes it to a gate key. + plan = { + "mode": "static", + "full": True, + "notes": [], + "suites": { + suite_id: {"run": True, "source": "static", "reason": ""} + for suite_id in SUITES + }, + } + outputs, _ = ci_scope.derive_outputs(plan) + gates = {suite["gate"] for suite in SUITES.values()} + self.assertLessEqual(gates, set(outputs)) + + def test_suite_metadata(self): + for suite_id, suite in SUITES.items(): + self.assertEqual(suite_id, suite_id.strip()) + self.assertTrue(suite["description"]) + self.assertEqual(suite_id.split("/")[0].replace("-", "_"), suite["gate"]) + if suite["gate"] in ci_scope.FUZZ_GATES: + self.assertEqual(ci_scope.suite_group(suite_id), suite_id.split("/", 1)[1]) + + +class ForcedModeTests(ScopeTestCase): + def test_merge_group_forces_without_http(self): + plan = self.plan([], event="merge_group") + self.assertEqual(plan["mode"], "forced") + self.assert_all_run(plan) + self.assertEqual(self.fake.calls, []) + + def test_schedule_and_workflow_dispatch_force(self): + for event in ("schedule", "workflow_dispatch"): + plan = self.plan([], event=event) + self.assertEqual(plan["mode"], "forced", event) + + def test_force_all_env_forces(self): + os.environ["CI_SCOPE_FORCE_ALL"] = "true" + plan = self.plan([], event="pull_request") + self.assertEqual(plan["mode"], "forced") + + def test_ci_full_label_forces(self): + self.fake.labels = ["ci:full"] + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + self.assertEqual(plan["mode"], "forced") + self.assert_all_run(plan) + + +class UncoveredChangeTests(ScopeTestCase): + def test_uncovered_crate_runs_everything(self): + # `src/common/telemetry` is mapped by the server group; a crate added + # later is not, and must widen the gate. + plan = self.plan([file_entry("src/common/brand-new/src/lib.rs")]) + self.assertTrue(plan["full"], plan["notes"]) + self.assertEqual(plan["suites"]["export-import-v2"]["source"], "uncovered") + self.assertIn("uncovered build change", " ".join(plan["notes"])) + + def test_mapped_crate_keeps_the_path_decision(self): + plan = self.plan([file_entry("src/query/src/lib.rs")]) + self.assertFalse(plan["full"]) + self.assertTrue(plan["suites"]["fuzz-standalone/logical-table"]["run"]) + # `src/query` reaches `COPY DATABASE` and the chaos scenarios too. + self.assertTrue(plan["suites"]["export-import-v2"]["run"]) + self.assertTrue(plan["suites"]["fuzz-chaos/migration"]["run"]) + + def test_exempt_trees_do_not_widen(self): + plan = self.plan( + [file_entry("src/promql/src/lib.rs"), file_entry("src/flow/src/lib.rs")] + ) + self.assertFalse(plan["full"]) + for entry in plan["suites"].values(): + self.assertFalse(entry["run"], entry) + + def test_exempt_tree_is_not_claimed_by_a_broader_glob(self): + # `@server` claims `src/query/**`; the PromQL module under it must be + # dropped before matching, and must not count as uncovered either. + plan = self.plan([file_entry("src/query/src/promql/src/lib.rs")]) + self.assertFalse(plan["full"]) + for entry in plan["suites"].values(): + self.assertFalse(entry["run"], entry) + + +class StaticDecisionTests(ScopeTestCase): + def outputs(self, plan): + return ci_scope.derive_outputs(plan)[0] + + def test_always_run_forces_everything(self): + plan = self.plan([file_entry("Cargo.lock")]) + self.assertEqual(plan["mode"], "static") + self.assertTrue(plan["full"]) + self.assert_all_run(plan) + + def test_meta_only_skips_standalone_fuzz(self): + plan = self.plan([file_entry("src/meta-srv/src/lib.rs")]) + self.assertEqual(plan["mode"], "static") + outputs, legs = ci_scope.derive_outputs(plan) + self.assertEqual(outputs["fuzz_standalone"], "false") + self.assertEqual(outputs["fuzz_unstable"], "false") + self.assertIn("migration", legs["fuzz_chaos"]) + self.assertIn("logical-pruning", legs["fuzz_distributed"]) + self.assertEqual(outputs["export_import_v2"], "false") + self.assertEqual(outputs["any_fuzz"], "true") + self.assertEqual(outputs["build_ci_needed"], "true") + + def test_flow_and_promql_skip_every_gated_suite(self): + plan = self.plan( + [file_entry("src/flow/src/lib.rs"), file_entry("src/promql/src/lib.rs")] + ) + self.assertEqual(plan["mode"], "static") + for entry in plan["suites"].values(): + self.assertFalse(entry["run"], entry) + outputs, legs = ci_scope.derive_outputs(plan) + self.assertEqual(outputs["any_fuzz"], "false") + self.assertEqual(outputs["build_ci_needed"], "false") + self.assertEqual(outputs["export_import_v2"], "false") + for gate in ci_scope.FUZZ_GATES: + self.assertEqual(outputs[gate], "false") + self.assertTrue(all(not values for values in legs.values())) + + def test_docs_only_short_circuits(self): + plan = self.plan([file_entry("docs/readme.md")]) + self.assertEqual(plan["mode"], "static") + self.assertIn("no meaningful changes", " ".join(plan["notes"])) + + def test_mapped_change_records_the_path_rule_source(self): + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + self.assertEqual(plan["mode"], "static") + self.assertEqual(plan["suites"]["fuzz-standalone/logical-table"]["source"], "static") + + def test_file_cap_truncates(self): + files = [file_entry("src/mito2/f%d.rs" % index) for index in range(300)] + extra = [file_entry("src/mito2/overflow.rs")] + plan = self.plan(files, pages={1: files[:100], 2: files[100:200], 3: files[200:], 4: extra}) + self.assertTrue(plan["full"]) + self.assert_all_run(plan) + self.assertTrue(all(entry["source"] == "always-run" for entry in plan["suites"].values())) + + def test_exactly_max_files_is_not_truncated(self): + files = [file_entry("src/promql/f%d.rs" % index) for index in range(300)] + plan = self.plan([], pages={1: files[:100], 2: files[100:200], 3: files[200:], 4: []}) + self.assertFalse(plan["full"], plan["notes"]) + self.assertNotIn("truncated", " ".join(plan["notes"])) + self.assertEqual(len(self.fake.file_queries), 4) + self.assertEqual( + self.fake.file_queries[-1], {"per_page": ["100"], "page": ["4"]} + ) + + def test_force_push_after_the_run_widens_the_gate(self): + self.fake.head_sha = "b" * 40 + plan = self.plan( + [file_entry("src/promql/src/lib.rs")], + extra_args=("--head-sha", "a" * 40, "--base-sha", "c" * 40), + ) + self.assertTrue(plan["full"]) + self.assertIn("head moved from aaaaaaaaaaaa", " ".join(plan["notes"])) + + def test_matching_revisions_keep_the_static_verdict(self): + self.fake.head_sha = "a" * 40 + self.fake.base_sha = "c" * 40 + plan = self.plan( + [file_entry("src/promql/src/lib.rs")], + extra_args=("--head-sha", "a" * 40, "--base-sha", "c" * 40), + ) + self.assertFalse(plan["full"]) + self.assertNotIn("moved", " ".join(plan["notes"])) + + def test_pull_request_is_read_once_per_run(self): + self.plan([file_entry("src/mito2/src/lib.rs")]) + pulls = [ + path + for _, path, _ in self.fake.calls + if path.endswith("/pulls/1") + ] + self.assertEqual(len(pulls), 1) + + def test_failed_completeness_probe_fails_instead_of_narrowing(self): + # Raising leaves the gate outputs empty, which the workflow treats as + # "run everything"; returning False here would silently classify a + # truncated file list as complete. + files = [file_entry("src/mito2/f%d.rs" % index) for index in range(300)] + with self.assertRaises(ci_scope.ScopeError): + self.plan( + files, + pages={1: files[:100], 2: files[100:200], 3: files[200:], 4: 500}, + ) + + def test_file_list_pagination_stops_at_short_page(self): + files = [file_entry("src/mito2/f%d.rs" % index) for index in range(120)] + self.plan(files, pages={1: files[:100], 2: files[100:]}) + pages = [ + page for _, path, page in self.fake.calls if path.endswith("/files") + ] + self.assertEqual(pages, ["1", "2"]) + + +# Crates no gated suite exercises. Changing one either runs everything through +# the always-run floor, or reaches CI that is not gated here. +UNMAPPED_CRATES = { + "src/flow": "flow execution is covered by rust.yml and sqlness", + "src/promql": "PromQL execution is covered by rust.yml and sqlness", + "tests-fuzz": "in ALWAYS_RUN", + "tests-integration": "in ALWAYS_RUN", +} + + +def workspace_crates(): + """Every workspace member directory, so nested crates are not collapsed.""" + data = tomllib.loads((REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")) + return sorted(member.rstrip("/") for member in data["workspace"]["members"]) + + +def rules_doc(): + return { + "matching": { + "always_run": ["Cargo.toml"], + "src_tree": "src/", + "exempt": [{"path": "src/flow/", "reason": "test fixture"}], + }, + "gates": {"fuzz_x": "fuzztest"}, + "groups": {"server": ["src/a/**"]}, + "suites": { + "fuzz-x/g": { + "gate": "fuzz_x", + "paths": ["@server"], + "description": "a suite", + } + }, + } + + +class RulesFileTests(unittest.TestCase): + def test_repository_rules_are_valid(self): + rules = ci_scope_rules.load() + self.assertEqual(len(rules["suites"]), 13) + + def test_unknown_group_is_rejected(self): + doc = rules_doc() + doc["suites"]["fuzz-x/g"]["paths"] = ["@nope"] + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_group_cycle_is_rejected(self): + doc = rules_doc() + doc["groups"]["a"] = ["@b"] + doc["groups"]["b"] = ["@a"] + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_gate_must_match_the_suite_prefix(self): + doc = rules_doc() + doc["suites"]["fuzz-x/g"]["gate"] = "fuzz_y" + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_unknown_key_in_matching_is_ignored_but_missing_is_not(self): + doc = rules_doc() + del doc["matching"]["src_tree"] + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_validator_entry_point_succeeds_on_the_repository_rules(self): + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertEqual(ci_scope_rules.main([]), 0) + self.assertIn("scope rules ok", out.getvalue()) + + def test_malformed_toml_names_the_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = pathlib.Path(tmp) / "rules.toml" + path.write_text("this is not toml [[[") + with self.assertRaises(ci_scope_rules.RulesError) as ctx: + ci_scope_rules.load(path) + self.assertIn("not valid TOML", str(ctx.exception)) + + +def stub_rules(**overrides): + """A rules dict in the shape `validate` returns, naming only real paths.""" + rules = { + "always_run": ["Cargo.toml"], + "src_tree": "src/", + "exempt_trees": [], + "gates": {"fuzz_x": "fuzztest"}, + "groups": {"server": ["Cargo.toml"]}, + "suites": { + "fuzz-x": { + "gate": "fuzz_x", + "paths": ["@server"], + "description": "a suite", + } + }, + } + rules.update(overrides) + return rules + + +class PathCheckTests(unittest.TestCase): + def test_repository_rules_name_only_existing_paths(self): + self.assertEqual(ci_scope_rules.missing_paths(), []) + + def test_a_vanished_path_is_reported_with_its_prefix(self): + doc = stub_rules() + doc["suites"]["fuzz-x"]["paths"] = ["@server", "src/does-not-exist/**"] + self.assertEqual( + ci_scope_rules.missing_paths(doc), + [("src/does-not-exist/**", "src/does-not-exist/")], + ) + + def test_patterns_without_a_fixed_prefix_are_skipped(self): + doc = stub_rules(groups={"server": ["*.md"]}, always_run=["*.md"]) + self.assertEqual(ci_scope_rules.missing_paths(doc), []) + + + def test_cli_reports_a_missing_path(self): + text = """\ +[matching] +always_run = ["Cargo.toml"] +src_tree = "src/" + +[[matching.exempt]] +path = "src/flow/" +reason = "test fixture" + +[[matching.exempt]] +path = "src/promql/" +reason = "test fixture" + +[gates] +fuzz_x = "fuzztest" + +[groups] +server = ["src/does-not-exist/**"] + +[suites."fuzz-x"] +gate = "fuzz_x" +paths = ["@server"] +description = "a suite" +""" + with tempfile.TemporaryDirectory() as tmp: + path = pathlib.Path(tmp) / "scope-rules.toml" + path.write_text(text) + original = ci_scope_rules.RULES_PATH + ci_scope_rules.RULES_PATH = path + err = io.StringIO() + try: + with contextlib.redirect_stderr(err): + code = ci_scope_rules.main(["--check-paths"]) + finally: + ci_scope_rules.RULES_PATH = original + self.assertEqual(code, 1) + self.assertIn("missing path: src/does-not-exist/**", err.getvalue()) + + def test_cli_succeeds_on_the_repository_rules(self): + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + code = ci_scope_rules.main(["--check-paths"]) + self.assertEqual(code, 0) + self.assertEqual(err.getvalue(), "") + + + +class RulesReasonTests(unittest.TestCase): + def test_exclusion_without_a_reason_is_rejected(self): + doc = rules_doc() + del doc["matching"]["exempt"][0]["reason"] + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_blank_reason_is_rejected(self): + doc = rules_doc() + doc["matching"]["exempt"][0]["reason"] = " " + with self.assertRaises(ci_scope_rules.RulesError): + ci_scope_rules.validate(doc) + + def test_repository_rules_explain_every_exclusion(self): + raw = tomllib.loads(ci_scope_rules.RULES_PATH.read_text()) + matching = raw["matching"] + self.assertTrue(matching["exempt"]) + for entry in matching["exempt"]: + self.assertTrue(entry["reason"].strip(), entry) + + +class ScopeCaseTests(ScopeTestCase): + """Replay `fixtures/scope-cases.toml` through the real classifier.""" + + @staticmethod + def cases(): + return tomllib.loads(SCOPE_CASES.read_text())["case"] + + def test_every_case_matches_the_classifier(self): + for case in self.cases(): + with self.subTest(case=case["name"]): + plan = self.plan([file_entry(path) for path in case["paths"]]) + expected = { + suite_id + for suite_id in ci_scope.SUITES + if any( + fnmatch.fnmatchcase(suite_id, pattern) + for pattern in case["suites"] + ) + } + actual = { + suite_id + for suite_id, entry in plan["suites"].items() + if entry["run"] + } + self.assertEqual(expected, actual, plan["notes"]) + + def test_cases_cover_every_suite(self): + covered = set() + for case in self.cases(): + covered |= { + suite_id + for suite_id in ci_scope.SUITES + if any( + fnmatch.fnmatchcase(suite_id, pattern) + for pattern in case["suites"] + ) + } + self.assertEqual(covered, set(ci_scope.SUITES)) + + +class SummaryTests(ScopeTestCase): + def summary(self, plan, path): + args = ci_scope.parse_args( + ["--repo", "GreptimeTeam/greptimedb", "--pr", "1", "--summary", path] + ) + ci_scope.emit(plan, args) + return pathlib.Path(path).read_text() + + def test_summary_names_the_files_that_matched(self): + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + with tempfile.TemporaryDirectory() as tmp: + text = self.summary(plan, str(pathlib.Path(tmp) / "summary.md")) + self.assertIn("### CI scope: mode=static", text) + row = next( + line + for line in text.splitlines() + if line.startswith("| `fuzz-standalone/logical-table`") + ) + self.assertIn("| run |", row) + self.assertIn("`src/mito2/src/lib.rs`", row) + + def test_summary_marks_a_skipped_suite_without_files(self): + plan = self.plan([file_entry("src/cli/src/lib.rs")]) + with tempfile.TemporaryDirectory() as tmp: + text = self.summary(plan, str(pathlib.Path(tmp) / "summary.md")) + row = next( + line + for line in text.splitlines() + if line.startswith("| `fuzz-standalone/database-and-regular-table`") + ) + self.assertIn("| skip |", row) + self.assertTrue(row.endswith("| — |"), row) + + def test_summary_truncates_long_file_lists(self): + files = [file_entry(f"src/mito2/src/f{index}.rs") for index in range(5)] + plan = self.plan(files) + with tempfile.TemporaryDirectory() as tmp: + text = self.summary(plan, str(pathlib.Path(tmp) / "summary.md")) + self.assertIn("+2 more", text) + + def test_summary_appends_instead_of_overwriting(self): + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + with tempfile.TemporaryDirectory() as tmp: + path = pathlib.Path(tmp) / "summary.md" + path.write_text("existing\n") + self.summary(plan, str(path)) + text = path.read_text() + self.assertTrue(text.startswith("existing\n")) + self.assertEqual(text.count("### CI scope"), 1) + + def test_summary_carries_the_notes(self): + plan = self.plan([file_entry("Cargo.lock")]) + with tempfile.TemporaryDirectory() as tmp: + text = self.summary(plan, str(pathlib.Path(tmp) / "summary.md")) + self.assertIn("
notes", text) + + +class CrateCoverageTests(unittest.TestCase): + """A new crate must not silently match no suite: the runtime net would + catch it by running everything, but the rule table should be updated.""" + + def test_every_workspace_crate_is_mapped_or_excused(self): + patterns = [ + ci_scope.glob_to_regex(path) + for suite in SUITES.values() + for path in suite_paths(suite) + ] + unmapped = [ + crate + for crate in workspace_crates() + if crate not in UNMAPPED_CRATES + and not any(p.match(crate + "/src/lib.rs") for p in patterns) + ] + self.assertEqual(unmapped, [], "crate matches no suite and no excuse") + + def test_excuses_reference_existing_crates(self): + stale = sorted(set(UNMAPPED_CRATES) - set(workspace_crates())) + self.assertEqual(stale, [], "excuse points at a crate that is gone") + + +class PathRuleCoverageTests(ScopeTestCase): + """A rule must select every suite the change can actually break.""" + + def test_copy_parser_selects_export_import(self): + plan = self.plan([file_entry("src/sql/src/parsers/copy_parser.rs")]) + self.assertTrue(plan["suites"]["export-import-v2"]["run"]) + + def test_shared_ddl_selects_standalone_fuzz(self): + plan = self.plan([file_entry("src/common/meta/src/ddl/create_table.rs")]) + for suite in ( + "fuzz-standalone/database-and-regular-table", + "fuzz-standalone/logical-table", + "fuzz-unstable/standalone", + ): + self.assertTrue(plan["suites"][suite]["run"], suite) + + def test_sqlness_runner_selects_the_kvbackend_legs(self): + # `--setup-pg` / `--setup-mysql` live in the runner and only these legs + # pass them, so a change there must not skip the only job that uses it. + plan = self.plan([file_entry("tests/runner/src/server_mode.rs")]) + for suite in ("sqlness-kvbackend/metasrv-postgres", "sqlness-kvbackend/metasrv-mysql"): + self.assertTrue(plan["suites"][suite]["run"], suite) + + def test_shared_ddl_selects_export_import(self): + # The E2E creates databases, tables and views and recreates them on + # import, all through the in-process DDL manager. + plan = self.plan([file_entry("src/common/procedure/src/lib.rs")]) + self.assertTrue(plan["suites"]["export-import-v2"]["run"]) + + def test_group_references_resolve_recursively(self): + self.assertIn("src/common/meta/**", ci_scope.suite_paths(SUITES["fuzz-chaos/migration"])) + + +class OutputTests(ScopeTestCase): + def test_flat_outputs(self): + plan = self.plan([file_entry("src/mito2/src/lib.rs")]) + outputs, legs = ci_scope.derive_outputs(plan) + self.assertEqual( + set(outputs), + { + "any_fuzz", + "build_ci_needed", + "fuzz_standalone", + "fuzz_distributed", + "fuzz_chaos", + "fuzz_unstable", + "export_import_v2", + "sqlness_kvbackend", + }, + ) + for key in outputs: + self.assertIn(outputs[key], ("true", "false"), key) + self.assertEqual( + sorted(legs["fuzz_standalone"]), + ["database-and-regular-table", "logical-table"], + ) + + def test_emit_writes_the_gate_outputs(self): + import tempfile + + with tempfile.TemporaryDirectory() as tmp: + out_path = os.path.join(tmp, "github_output") + args = ci_scope.parse_args( + [ + "--repo", + "GreptimeTeam/greptimedb", + "--pr", + "1", + "--event", + "merge_group", + "--github-output", + out_path, + ] + ) + ci_scope.emit(ci_scope.build_plan(args, "token"), args) + with open(out_path, encoding="utf-8") as handle: + text = handle.read() + self.assertIn("any_fuzz=true" + "\n", text) + self.assertIn("fuzz_unstable=true", text) + self.assertIn("fuzz_chaos=true", text) + self.assertEqual(text.count("\n"), 8) + + + +class GateJobContractTests(unittest.TestCase): + """The rules say which job each gate switches; prove the YAML agrees.""" + + WORKFLOW = WORKFLOWS / "integration.yml" + + def job_blocks(self): + blocks = {} + current = None + for line in self.WORKFLOW.read_text().splitlines(): + marker = re.match(r"^ ([A-Za-z0-9_-]+):$", line) + if marker: + current = marker.group(1) + blocks[current] = [] + elif current: + blocks[current].append(line) + return {name: "\n".join(lines) for name, lines in blocks.items()} + + def test_every_gate_names_a_job_that_reads_it(self): + blocks = self.job_blocks() + for gate, job in ci_scope_rules.GATE_JOBS.items(): + self.assertIn(job, blocks, gate) + self.assertIn(f"needs.scope.outputs.{gate} != 'false'", blocks[job], gate) + + def test_every_gated_job_is_named_by_a_gate(self): + derived = {"any_fuzz", "build_ci_needed"} + declared = set(ci_scope_rules.GATE_JOBS) + for name, block in self.job_blocks().items(): + for gate in re.findall(r"needs\.scope\.outputs\.([a-z0-9_]+)", block): + self.assertIn(gate, declared | derived, name) + + def test_a_suite_gate_missing_from_the_table_is_rejected(self): + doc = rules_doc() + del doc["gates"]["fuzz_x"] + with self.assertRaises(ci_scope_rules.RulesError) as ctx: + ci_scope_rules.validate(doc) + self.assertIn("missing from [gates]", str(ctx.exception)) + + def test_gates_no_suite_uses_are_rejected(self): + doc = rules_doc() + doc["gates"]["fuzz_y"] = "fuzztest" + with self.assertRaises(ci_scope_rules.RulesError) as ctx: + ci_scope_rules.validate(doc) + self.assertIn("no suite uses", str(ctx.exception)) + + +class WorkflowContractTests(unittest.TestCase): + """Keep the YAML gate contract in sync with the classifier outputs.""" + + WORKFLOW = WORKFLOWS / "integration.yml" + + def job_blocks(self): + text = self.WORKFLOW.read_text() + blocks = {} + current = None + for line in text.splitlines(): + marker = re.match(r"^ ([A-Za-z0-9_-]+):$", line) + if marker: + current = marker.group(1) + blocks[current] = [] + elif current: + blocks[current].append(line) + return {name: "\n".join(lines) for name, lines in blocks.items()} + + def test_every_script_a_gated_job_runs_is_always_run(self): + """A script a gated job executes must widen the gate. + + A change confined to such a script would otherwise select no suite, so + the jobs that run it are skipped exactly when they are worth running. + The reference is often not in the workflow: a composite action the job + `uses` can run the script, so the search follows those actions too. + """ + action_use = re.compile(r"uses:\s*\./(\.github/actions/[A-Za-z0-9_.-]+)") + script_ref = re.compile( + r"(?:\./)?(\.github/[A-Za-z0-9_./-]+\.(?:sh|py|js|cjs|ts))\b" + ) + always = [ci_scope.glob_to_regex(pattern) for pattern in ALWAYS_RUN] + + gated = [b for b in self.job_blocks().values() if "needs.scope.outputs" in b] + pending = {ref for block in gated for ref in script_ref.findall(block)} + pending |= {a for block in gated for a in action_use.findall(block)} + seen = set() + while pending: + reference = pending.pop() + if reference in seen: + continue + seen.add(reference) + if not reference.startswith(".github/actions/"): + continue + for suffix in ("action.yml", "action.yaml"): + path = REPO_ROOT / reference / suffix + if path.exists(): + text = path.read_text() + pending |= set(script_ref.findall(text)) + pending |= set(action_use.findall(text)) + break + uncovered = sorted( + ref for ref in seen if not any(pattern.match(ref) for pattern in always) + ) + self.assertEqual(uncovered, [], "a gated job runs a script ALWAYS_RUN misses") + + def test_gates_treat_a_missing_output_as_run(self): + blocks = self.job_blocks() + gated = [ + "export-import-v2-e2e", + "prepare-fuzz-targets", + "fuzztest", + "unstable-fuzztest", + "build-greptime-ci", + "distributed-fuzztest", + "distributed-fuzztest-with-chaos", + "sqlness-kvbackend", + ] + declared = set( + re.findall( + r"^ ([a-z0-9_]+): \$\{\{ steps\.classify\.outputs\.\1 \}\}$", + blocks["scope"], + re.MULTILINE, + ) + ) + self.assertIn("any_fuzz", declared) + seen = set() + for name in gated: + self.assertIn("scope", blocks[name], name) + match = re.search( + r"needs\.scope\.outputs\.([a-z0-9_]+) != 'false'", blocks[name] + ) + self.assertTrue(match, name) + seen.add(match.group(1)) + self.assertEqual(seen, declared) + + def test_gates_override_the_implicit_success_check(self): + # A condition without a status function carries an implicit success() + # over `needs`, so a scope job that times out or dies on the runner + # would skip the gates despite the fail-open output comparison. + blocks = self.job_blocks() + for name in ( + "export-import-v2-e2e", + "prepare-fuzz-targets", + "fuzztest", + "unstable-fuzztest", + "build-greptime-ci", + "distributed-fuzztest", + "distributed-fuzztest-with-chaos", + ): + block = blocks[name] + condition = re.search(r"^ if: \$\{\{ (.*?) \}\}$", block, re.M) + self.assertTrue(condition, name) + self.assertTrue(condition.group(1).startswith("!cancelled() && "), name) + needs = re.search(r"^ needs: \[(.*?)\]$", block, re.M) + self.assertTrue(needs, name) + for dep in [item.strip() for item in needs.group(1).split(",")]: + if not dep or dep == "scope": + continue + key = f"needs['{dep}'].result" if "-" in dep else f"needs.{dep}.result" + self.assertIn(key + " == 'success'", condition.group(1), name) + + def test_scope_job_cannot_fail_and_skip_the_gates(self): + block = self.job_blocks()["scope"] + self.assertNotIn("Fail-open defaults", block) + self.assertIn("github.event.merge_group.base_sha", block) + self.assertIn("CI_SCOPE_FORCE_ALL", block) + # Every step that can fail must be continue-on-error: a failed scope job + # would make GitHub skip the gated jobs instead of running them. + steps = block.split("\n - ") + guarded = [ + step + for step in steps + if step.startswith("uses: actions/checkout") + or step.startswith("name: Classify") + ] + self.assertEqual(len(guarded), 2) + for step in guarded: + self.assertIn("continue-on-error: true", step, step.splitlines()[0]) + + + +class LogRenderingTests(ScopeTestCase): + """The step log is where a triage starts; the verdict must be there.""" + + def sample_plan(self): + return { + "mode": "static", + "head_sha": "a" * 40, + "base_sha": "b" * 40, + "full": False, + "notes": ["always-run: Cargo.lock"], + "suites": { + "fuzz-standalone/logical-table": { + "run": True, + "source": "static", + "reason": "touches mito2", + }, + "fuzz-chaos/migration": { + "run": False, + "source": "static", + "reason": "meta docs only", + }, + }, + } + + def test_header_names_mode_and_full(self): + self.assertEqual( + ci_scope.render_log(self.sample_plan()).splitlines()[0], + "CI scope: mode=static full=false", + ) + + def test_one_line_per_suite_with_source_and_reason(self): + lines = ci_scope.render_log(self.sample_plan()).splitlines() + self.assertIn(" run fuzz-standalone/logical-table", lines[1]) + self.assertIn("static", lines[1]) + self.assertIn("touches mito2", lines[1]) + self.assertIn(" skip fuzz-chaos/migration", lines[2]) + self.assertIn("meta docs only", lines[2]) + + def test_gates_and_notes_are_printed(self): + log = ci_scope.render_log(self.sample_plan()) + self.assertIn(" gates: fuzz_standalone=true", log) + self.assertIn("any_fuzz=true", log) + self.assertIn("export_import_v2=false", log) + self.assertIn(" note: always-run: Cargo.lock", log) + + def test_a_failed_pull_request_lookup_is_annotated_and_runs_everything(self): + # Drive the real failure path: the label lookup and the revision + # comparison share one request, so a 500 here must widen the gate and + # still produce the warning the annotation promises. + self.fake.pull_status = 500 + plan = self.plan([file_entry("src/promql/src/lib.rs")]) + self.assertTrue(plan["full"]) + self.assertIn("pull request lookup failed", " ".join(plan["notes"])) + annotations = ci_scope.log_annotations(plan) + self.assertEqual(len(annotations), 1) + self.assertTrue(annotations[0].startswith("::warning::"), annotations) + self.assertIn("every suite runs", annotations[0]) + + def test_main_prints_the_log(self): + self.fake.file_pages = {1: [file_entry("src/mito2/src/lib.rs")]} + stdout = io.StringIO() + with contextlib.redirect_stdout(stdout): + self.assertEqual( + ci_scope.main( + [ + "--repo", + "GreptimeTeam/greptimedb", + "--pr", + "1", + "--event", + "pull_request", + "--dry-run", + ] + ), + 0, + ) + text = stdout.getvalue() + self.assertIn("CI scope: mode=", text) + self.assertIn(" run fuzz-standalone/logical-table", text) + self.assertIn("any_fuzz=true", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/scripts/tests/test_ci_slash.py b/.github/scripts/tests/test_ci_slash.py index c8c01ceda15..e551a4f5297 100644 --- a/.github/scripts/tests/test_ci_slash.py +++ b/.github/scripts/tests/test_ci_slash.py @@ -136,7 +136,7 @@ class CiSlashTest(unittest.TestCase): def test_fork_rerun_gates_cover_standard_jobs(self): import re - for name, count in [("rust", 7), ("integration", 5), ("checks", 5), ("docs", 3)]: + for name, count in [("rust", 7), ("integration", 7), ("checks", 6), ("docs", 3)]: workflow = (SCRIPT.parents[1] / "workflows" / (name + ".yml")).read_text() gates = re.findall(r"^ if:.*github.run_attempt > 1.*$", workflow, re.MULTILINE) self.assertEqual(len(gates), count, name) diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 3bc54372d06..b3ff212ade4 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -92,6 +92,8 @@ jobs: run: .github/scripts/run-fuzz-targets-test.sh - name: Run CI comment-command tests run: python3 .github/scripts/tests/test_ci_slash.py + - name: Run CI scope gate tests + run: python3 .github/ci/tests/test_ci_scope.py - name: Run metric snapshot benchmark tests run: python3 -m unittest discover -s .github/scripts/tests -p 'test_metric_snapshot*.py' - name: Run query-regression Python tooling tests @@ -107,6 +109,23 @@ jobs: python3 tests/perf/test_agent_observability_summary.py python3 tests/perf/test_tracesbench_summary.py + scope-rules: + if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + name: CI Scope Rules + # Same runner image as the `scope` job in integration.yml: if the rules file + # stops parsing there, the gate silently runs every job, so this check exists + # to fail the pull request instead. + runs-on: ubuntu-slim + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - name: Show the interpreter + run: python3 -VV + - name: Validate .github/ci/scope-rules.toml + run: python3 .github/ci/ci_scope_rules.py --check-paths + check: if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} name: Check diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index afce4a8c796..6106e5a2860 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -42,6 +42,57 @@ concurrency: cancel-in-progress: true jobs: + # Which jobs this gate skips, and why: .github/ci/README.md. + scope: + name: CI Scope + if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + # ubuntu-slim ships python3, git and curl; this job only classifies. + runs-on: ubuntu-slim + timeout-minutes: 10 + permissions: + contents: read + # `/pulls/{n}` and `/pulls/{n}/files`. An explicit block sets every + # unlisted permission to none, and a 403 here would silently widen every + # gate instead of classifying. + pull-requests: read + outputs: + any_fuzz: ${{ steps.classify.outputs.any_fuzz }} + build_ci_needed: ${{ steps.classify.outputs.build_ci_needed }} + fuzz_standalone: ${{ steps.classify.outputs.fuzz_standalone }} + fuzz_distributed: ${{ steps.classify.outputs.fuzz_distributed }} + fuzz_chaos: ${{ steps.classify.outputs.fuzz_chaos }} + fuzz_unstable: ${{ steps.classify.outputs.fuzz_unstable }} + export_import_v2: ${{ steps.classify.outputs.export_import_v2 }} + sqlness_kvbackend: ${{ steps.classify.outputs.sqlness_kvbackend }} + steps: + # Rules come from the pull request base (the queue base on merge_group), + # so a pull request cannot weaken its own gate. If this job or the Classify + # step fails, the outputs stay empty and every gate below treats an absent + # value as "run", which keeps CI fail-open. + - uses: actions/checkout@v4 + # A checkout failure leaves the outputs empty, which every gate treats + # as "run"; letting the step fail would skip the gates instead. + continue-on-error: true + with: + ref: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || github.sha }} + persist-credentials: false + - name: Classify + id: classify + continue-on-error: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CI_SCOPE_FORCE_ALL: ${{ vars.CI_SCOPE_FORCE_ALL || 'false' }} + run: | + args=(--repo "$GITHUB_REPOSITORY" --event "$GITHUB_EVENT_NAME" + --github-output "$GITHUB_OUTPUT" + --summary "$GITHUB_STEP_SUMMARY") + if [[ "${GITHUB_EVENT_NAME}" == "pull_request" ]]; then + args+=(--pr "${{ github.event.pull_request.number }}" + --head-sha "${{ github.event.pull_request.head.sha }}" + --base-sha "${{ github.event.pull_request.base.sha }}") + fi + python3 .github/ci/ci_scope.py "${args[@]}" + build: if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} name: Build GreptimeDB binaries @@ -116,28 +167,12 @@ jobs: - name: "Basic" opts: "" kafka: false - postgres: false - mysql: false - name: "Remote WAL" opts: "-w kafka -k 127.0.0.1:9092" kafka: true - postgres: false - mysql: false - - name: "PostgreSQL KvBackend" - opts: "--setup-pg postgresql://greptimedb:admin@127.0.0.1:5432/postgres" - kafka: false - postgres: true - mysql: false - - name: "MySQL KvBackend" - opts: "--setup-mysql mysql://greptimedb:admin@127.0.0.1:3306/mysql" - kafka: false - postgres: false - mysql: true - name: "Flat format" opts: "--enable-flat-format" kafka: false - postgres: false - mysql: false timeout-minutes: 60 steps: - uses: actions/checkout@v4 @@ -149,16 +184,6 @@ jobs: working-directory: tests-integration/fixtures run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait kafka - - if: matrix.mode.postgres - name: Setup PostgreSQL - working-directory: tests-integration/fixtures - run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait postgres - - - if: matrix.mode.mysql - name: Setup MySQL - working-directory: tests-integration/fixtures - run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait mysql - - name: Download pre-built binaries uses: actions/download-artifact@v4 with: @@ -183,10 +208,68 @@ jobs: /tmp/sqlness* retention-days: 3 + sqlness-kvbackend: + # The two foreign KV backends are the only sqlness legs that are not + # required checks, so they are the only ones this gate may skip. They run + # the same cases as the `Basic` leg, so the diff only matters when it can + # reach the backend itself; the merge queue runs them regardless. + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.sqlness_kvbackend != 'false' }} + name: Sqlness Test (${{ matrix.mode.name }}) + needs: [scope, build] + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ ubuntu-latest ] + mode: + - name: "Metasrv on PostgreSQL" + id: "metasrv-postgres" + opts: "--setup-pg postgresql://greptimedb:admin@127.0.0.1:5432/postgres" + postgres: true + mysql: false + - name: "Metasrv on MySQL" + id: "metasrv-mysql" + opts: "--setup-mysql mysql://greptimedb:admin@127.0.0.1:3306/mysql" + postgres: false + mysql: true + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - if: matrix.mode.postgres + name: Setup PostgreSQL + working-directory: tests-integration/fixtures + run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait postgres + + - if: matrix.mode.mysql + name: Setup MySQL + working-directory: tests-integration/fixtures + run: ../../.github/scripts/pull-test-deps-images.sh && docker compose up -d --wait mysql + + - name: Download pre-built binaries + uses: actions/download-artifact@v4 + with: + name: bins + path: . + - name: Unzip binaries + run: tar -xvf ./bins.tar.gz + - name: Run sqlness + run: RUST_BACKTRACE=1 ./bins/sqlness-runner bare ${{ matrix.mode.opts }} -c ./tests/cases --bins-dir ./bins --preserve-state + - name: Upload sqlness logs + if: failure() + uses: actions/upload-artifact@v4 + with: + name: sqlness-logs-${{ matrix.mode.name }} + path: | + /tmp/sqlness* + retention-days: 3 + export-import-v2-e2e: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && (github.event_name != 'pull_request' || github.event.pull_request.draft == false || github.run_attempt > 1) && needs.build.result == 'success' && needs.scope.outputs.export_import_v2 != 'false' }} name: Export/Import V2 E2E Test - needs: build + needs: [scope, build] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -319,8 +402,9 @@ jobs: retention-days: 3 prepare-fuzz-targets: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile != 'none') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile != 'none') && needs.scope.outputs.any_fuzz != 'false' }} name: Prepare Fuzz Targets + needs: [scope] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -433,9 +517,9 @@ jobs: if-no-files-found: error fuzztest: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') && needs.build.result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_standalone != 'false' }} name: Fuzz Test (Standalone, ${{ matrix.group.name }}) - needs: [build, prepare-fuzz-targets] + needs: [build, prepare-fuzz-targets, scope] runs-on: ubuntu-latest timeout-minutes: 60 strategy: @@ -514,9 +598,9 @@ jobs: artifact-name: fuzz-standalone-${{ matrix.group.id }} unstable-fuzztest: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'standalone' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_unstable != 'false' }} name: Unstable Fuzz Test - needs: [build-greptime-ci, prepare-fuzz-targets] + needs: [build-greptime-ci, prepare-fuzz-targets, scope] runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -574,8 +658,9 @@ jobs: artifact-name: fuzz-unstable-standalone build-greptime-ci: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command && inputs.fuzz_profile != 'none')) }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command && inputs.fuzz_profile != 'none') || github.event_name == 'merge_group') && needs.scope.outputs.build_ci_needed != 'false' }} name: Build GreptimeDB binary (profile-CI) + needs: [scope] runs-on: ${{ matrix.os }} strategy: matrix: @@ -634,10 +719,10 @@ jobs: version: current distributed-fuzztest: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'distributed' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_distributed != 'false' }} name: Fuzz Test (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }}) runs-on: ubuntu-latest - needs: [build-greptime-ci, prepare-fuzz-targets] + needs: [build-greptime-ci, prepare-fuzz-targets, scope] timeout-minutes: 60 strategy: fail-fast: false @@ -873,10 +958,10 @@ jobs: docker system prune -f distributed-fuzztest-with-chaos: - if: ${{ github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command)) && (github.event_name == 'pull_request' || inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all') }} + if: ${{ !cancelled() && github.repository == 'GreptimeTeam/greptimedb' && ((github.event_name == 'pull_request' && github.event.pull_request.draft == false) || (github.event_name == 'workflow_dispatch' && inputs.ci_command) || github.event_name == 'merge_group') && (github.event_name == 'pull_request' || github.event_name == 'merge_group' || inputs.fuzz_profile == 'chaos' || inputs.fuzz_profile == 'all') && needs['build-greptime-ci'].result == 'success' && needs['prepare-fuzz-targets'].result == 'success' && needs.scope.outputs.fuzz_chaos != 'false' }} name: Fuzz Test with Chaos (Distributed, ${{ matrix.mode.name }}, ${{ matrix.group.name }}) runs-on: ubuntu-latest - needs: [build-greptime-ci, prepare-fuzz-targets] + needs: [build-greptime-ci, prepare-fuzz-targets, scope] timeout-minutes: 60 strategy: fail-fast: false diff --git a/Makefile b/Makefile index 21c87cc3707..073a95cb1fa 100644 --- a/Makefile +++ b/Makefile @@ -249,6 +249,10 @@ fmt-check: ## Check code format. check-enterprise-license: ## Check enterprise-gated files are listed in both license configs. python3 scripts/check-enterprise-license.py +.PHONY: check-ci-scope +check-ci-scope: ## Check the CI scope rules still match existing paths. + python3 .github/ci/ci_scope_rules.py --check-paths + .PHONY: start-etcd start-etcd: ## Start single node etcd for testing purpose. docker run --rm -d --network=host -p 2379-2380:2379-2380 ${ETCD_IMAGE}