Skip to content

Commit

Permalink
Add benchmarking for FlightSQL from CLI (datafusion-contrib#194)
Browse files Browse the repository at this point in the history
Adds FlightSQL benchmarking functionality to the cli. The breakdown is
expected to include duration summary stats for each flightsql grpc
request, such as:

get_flight_info
time to first byte (time to get first batch from do_get)
total do_get time
total execution

As part of this i refactored `AppExecution` to now hold
`ExecutionContext` and `FlightSQLContext`. Each of these context's
contain the core execution functionality used by both the CLI and TUI
(i.e. executing queries, benchmarking queries, loading ddl, etc). I can
envision a future where there is also a `RayContext` or
`BallistaContext`.
  • Loading branch information
matthewmturner authored Oct 15, 2024
1 parent 25f69d7 commit 3e1576a
Show file tree
Hide file tree
Showing 16 changed files with 806 additions and 424 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ Both of the commands above support the `--flightsql` parameter to run the SQL wi
The CLI can also run your configured DDL prior to executing the query by adding the `--ddl` parameter.

#### Benchmarking
You can benchmark queries by adding the `--bench` parameter. This will run the query a configurable number of times and output a breakdown of the queries execution time with summary statistics for each component of the query (logical planning, physical planning, execution time, and total time). Currently only local queries can be benchmarked but benchmarking of FlightSQL queries is planned.
You can benchmark queries by adding the `--bench` parameter. This will run the query a configurable number of times and output a breakdown of the queries execution time with summary statistics for each component of the query (logical planning, physical planning, execution time, and total time).

## `dft` FlightSQL Server

Expand Down
22 changes: 20 additions & 2 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ impl CliApp {
#[cfg(feature = "flightsql")]
async fn flightsql_benchmark_files(&self, files: &[PathBuf]) -> Result<()> {
info!("Benchmarking FlightSQL files: {:?}", files);
for file in files {
let query = std::fs::read_to_string(file)?;
self.flightsql_benchmark_from_string(&query).await?;
}

Ok(())
}
Expand Down Expand Up @@ -197,11 +201,14 @@ impl CliApp {
#[cfg(feature = "flightsql")]
async fn flightsql_benchmark_commands(&self, commands: &[String]) -> color_eyre::Result<()> {
info!("Benchmark FlightSQL commands: {:?}", commands);
for command in commands {
self.flightsql_benchmark_from_string(command).await?;
}

Ok(())
}

async fn exec_from_string(&self, sql: &str) -> color_eyre::Result<()> {
async fn exec_from_string(&self, sql: &str) -> Result<()> {
let dialect = datafusion::sql::sqlparser::dialect::GenericDialect {};
let statements = DFParser::parse_sql_with_dialect(sql, &dialect)?;
let start = if self.args.time {
Expand All @@ -226,7 +233,7 @@ impl CliApp {
Ok(())
}

async fn benchmark_from_string(&self, sql: &str) -> color_eyre::Result<()> {
async fn benchmark_from_string(&self, sql: &str) -> Result<()> {
let stats = self
.app_execution
.execution_ctx()
Expand All @@ -236,6 +243,17 @@ impl CliApp {
Ok(())
}

#[cfg(feature = "flightsql")]
async fn flightsql_benchmark_from_string(&self, sql: &str) -> Result<()> {
let stats = self
.app_execution
.flightsql_ctx()
.benchmark_query(sql)
.await?;
println!("{}", stats);
Ok(())
}

/// run and execute SQL statements and commands from a file, against a context
/// with the given print options
pub async fn exec_from_file(&self, file: &Path) -> color_eyre::Result<()> {
Expand Down
11 changes: 7 additions & 4 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ pub fn get_data_dir() -> PathBuf {
}
}

#[derive(Debug, Default, Deserialize)]
#[derive(Clone, Debug, Default, Deserialize)]
pub struct AppConfig {
#[serde(default = "default_execution_config")]
pub execution: ExecutionConfig,
Expand Down Expand Up @@ -92,7 +92,7 @@ fn default_flightsql_config() -> FlightSQLConfig {
FlightSQLConfig::default()
}

#[derive(Debug, Deserialize)]
#[derive(Clone, Debug, Deserialize)]
pub struct DisplayConfig {
#[serde(default = "default_frame_rate")]
pub frame_rate: f64,
Expand Down Expand Up @@ -217,7 +217,7 @@ impl Default for ExecutionConfig {
}
}

#[derive(Debug, Default, Deserialize)]
#[derive(Clone, Debug, Default, Deserialize)]
pub struct InteractionConfig {
#[serde(default = "default_mouse")]
pub mouse: bool,
Expand All @@ -238,13 +238,16 @@ fn default_paste() -> bool {
pub struct FlightSQLConfig {
#[serde(default = "default_connection_url")]
pub connection_url: String,
#[serde(default = "default_benchmark_iterations")]
pub benchmark_iterations: usize,
}

#[cfg(feature = "flightsql")]
impl Default for FlightSQLConfig {
fn default() -> Self {
Self {
connection_url: default_connection_url(),
benchmark_iterations: default_benchmark_iterations(),
}
}
}
Expand All @@ -254,7 +257,7 @@ pub fn default_connection_url() -> String {
"http://localhost:50051".to_string()
}

#[derive(Debug, Default, Deserialize)]
#[derive(Clone, Debug, Default, Deserialize)]
pub struct EditorConfig {
pub experimental_syntax_highlighting: bool,
}
Expand Down
130 changes: 130 additions & 0 deletions src/execution/flightsql.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 arrow_flight::sql::client::FlightSqlServiceClient;
use datafusion::sql::parser::DFParser;
use log::{error, info, warn};

use color_eyre::eyre::{self, Result};
use tokio::sync::Mutex;
use tokio_stream::StreamExt;
use tonic::{transport::Channel, IntoRequest};

use crate::config::FlightSQLConfig;

use crate::execution::flightsql_benchmarks::FlightSQLBenchmarkStats;

pub type FlightSQLClient = Mutex<Option<FlightSqlServiceClient<Channel>>>;

#[derive(Default)]
pub struct FlightSQLContext {
config: FlightSQLConfig,
flightsql_client: FlightSQLClient,
}

impl FlightSQLContext {
pub fn new(config: FlightSQLConfig) -> Self {
Self {
config,
flightsql_client: Mutex::new(None),
}
}

pub fn client(&self) -> &FlightSQLClient {
&self.flightsql_client
}

/// Create FlightSQL client from users FlightSQL config
pub async fn create_client(&self) -> Result<()> {
let url = Box::leak(self.config.connection_url.clone().into_boxed_str());
info!("Connecting to FlightSQL host: {}", url);
let channel = Channel::from_static(url).connect().await;
match channel {
Ok(c) => {
let client = FlightSqlServiceClient::new(c);
let mut guard = self.flightsql_client.lock().await;
*guard = Some(client);
Ok(())
}
Err(e) => Err(eyre::eyre!(
"Error creating channel for FlightSQL client: {:?}",
e
)),
}
}

pub async fn benchmark_query(&self, query: &str) -> Result<FlightSQLBenchmarkStats> {
let iterations = self.config.benchmark_iterations;
let mut get_flight_info_durations = Vec::with_capacity(iterations);
let mut ttfb_durations = Vec::with_capacity(iterations);
let mut do_get_durations = Vec::with_capacity(iterations);
let mut total_durations = Vec::with_capacity(iterations);

let dialect = datafusion::sql::sqlparser::dialect::GenericDialect {};
let statements = DFParser::parse_sql_with_dialect(query, &dialect)?;
if statements.len() == 1 {
if let Some(ref mut client) = *self.flightsql_client.lock().await {
for _ in 0..iterations {
let start = std::time::Instant::now();
let flight_info = client.execute(query.to_string(), None).await?;
if flight_info.endpoint.len() > 1 {
warn!("More than one endpoint: Benchmark results will not be reliable");
}
let get_flight_info_duration = start.elapsed();
// Current logic wont properly handle having multiple endpoints
for endpoint in flight_info.endpoint {
if let Some(ticket) = &endpoint.ticket {
match client.do_get(ticket.clone().into_request()).await {
Ok(ref mut s) => {
while let Some((i, _)) =
futures::stream::StreamExt::enumerate(&mut *s).next().await
{
if i == 0 {
let ttfb_duration =
start.elapsed() - get_flight_info_duration;
ttfb_durations.push(ttfb_duration);
}
}
let do_get_duration =
start.elapsed() - get_flight_info_duration;
do_get_durations.push(do_get_duration);
}
Err(e) => {
error!("Error getting Flight stream: {:?}", e);
}
}
}
}
get_flight_info_durations.push(get_flight_info_duration);
let total_duration = start.elapsed();
total_durations.push(total_duration);
}
} else {
return Err(eyre::eyre!("No FlightSQL client configured"));
}
Ok(FlightSQLBenchmarkStats::new(
query.to_string(),
get_flight_info_durations,
ttfb_durations,
do_get_durations,
total_durations,
))
} else {
Err(eyre::eyre!("Only a single statement can be benchmarked"))
}
}
}
100 changes: 100 additions & 0 deletions src/execution/flightsql_benchmarks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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::time::Duration;

use super::local_benchmarks::DurationsSummary;

pub struct FlightSQLBenchmarkStats {
query: String,
runs: usize,
get_flight_info_durations: Vec<Duration>,
ttfb_durations: Vec<Duration>,
do_get_durations: Vec<Duration>,
total_durations: Vec<Duration>,
}

impl FlightSQLBenchmarkStats {
pub fn new(
query: String,
get_flight_info_durations: Vec<Duration>,
ttfb_durations: Vec<Duration>,
do_get_durations: Vec<Duration>,
total_durations: Vec<Duration>,
) -> Self {
let runs = get_flight_info_durations.len();
Self {
query,
runs,
get_flight_info_durations,
ttfb_durations,
do_get_durations,
total_durations,
}
}

fn summarize(&self, durations: &[Duration]) -> DurationsSummary {
let mut sorted = durations.to_vec();
sorted.sort();
let len = sorted.len();
let min = *sorted.first().unwrap();
let max = *sorted.last().unwrap();
let mean = sorted.iter().sum::<Duration>() / len as u32;
let median = sorted[len / 2];
let this_total = durations.iter().map(|d| d.as_nanos()).sum::<u128>();
let total_duration = self
.total_durations
.iter()
.map(|d| d.as_nanos())
.sum::<u128>();
let percent_of_total = (this_total as f64 / total_duration as f64) * 100.0;
DurationsSummary {
min,
max,
mean,
median,
percent_of_total,
}
}
}

impl std::fmt::Display for FlightSQLBenchmarkStats {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f)?;
writeln!(f, "----------------------------")?;
writeln!(f, "Benchmark Stats ({} runs)", self.runs)?;
writeln!(f, "----------------------------")?;
writeln!(f, "{}", self.query)?;
writeln!(f, "----------------------------")?;

let logical_planning_summary = self.summarize(&self.get_flight_info_durations);
writeln!(f, "Get Flight Info")?;
writeln!(f, "{}", logical_planning_summary)?;

let physical_planning_summary = self.summarize(&self.ttfb_durations);
writeln!(f, "Time to First Byte")?;
writeln!(f, "{}", physical_planning_summary)?;

let execution_summary = self.summarize(&self.do_get_durations);
writeln!(f, "Do Get")?;
writeln!(f, "{}", execution_summary)?;

let total_summary = self.summarize(&self.total_durations);
writeln!(f, "Total")?;
writeln!(f, "{}", total_summary)
}
}
Loading

0 comments on commit 3e1576a

Please sign in to comment.