Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(expr): distributed make timestamptz #13647

Merged
merged 9 commits into from
Nov 30, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ SELECT make_timestamptz(1973, 07, 15, 08, 15, 55.33);
----
1973-07-15 08:15:55.330-04:00

statement ok
create table ttz(tstz timestamptz);

statement ok
insert into ttz values(make_timestamptz(1973, 06, 25, 08, 15, 55.33));

query TT
select * from ttz;
----
1973-06-25 08:15:55.330-04:00

statement ok
drop table ttz;

query error Invalid parameter time_zone: 'Nehwon/Lankhmar' is not a valid timezone
SELECT make_timestamptz(1910, 12, 24, 0, 0, 0, 'Nehwon/Lankhmar');

Expand Down
5 changes: 5 additions & 0 deletions proto/stream_plan.proto
Original file line number Diff line number Diff line change
Expand Up @@ -878,3 +878,8 @@ message StreamFragmentGraph {
// If none, default parallelism will be applied.
Parallelism parallelism = 6;
}

// Provide statement-local context, e.g. session info like time zone, for execution.
message CapturedExecutionContext {
string time_zone = 1;
}
2 changes: 2 additions & 0 deletions proto/task_service.proto
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ message CreateTaskRequest {
batch_plan.PlanFragment plan = 2;
common.BatchQueryEpoch epoch = 3;
map<string, string> tracing_context = 4;
stream_plan.CapturedExecutionContext captured_execution_context = 5;
}

message CancelTaskRequest {
Expand All @@ -63,6 +64,7 @@ message ExecuteRequest {
batch_plan.PlanFragment plan = 2;
common.BatchQueryEpoch epoch = 3;
map<string, string> tracing_context = 4;
stream_plan.CapturedExecutionContext captured_execution_context = 5;
}

service TaskService {
Expand Down
2 changes: 2 additions & 0 deletions src/batch/src/execution/grpc_exchange.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use std::fmt::{Debug, Formatter};

use futures::StreamExt;
use risingwave_common::array::DataChunk;
use risingwave_expr::captured_execution_context::capture_execution_context;
use risingwave_pb::batch_plan::exchange_source::LocalExecutePlan::{self, Plan};
use risingwave_pb::batch_plan::TaskOutputId;
use risingwave_pb::task_service::{ExecuteRequest, GetDataResponse};
Expand Down Expand Up @@ -50,6 +51,7 @@ impl GrpcExchangeSource {
plan: plan.plan,
epoch: plan.epoch,
tracing_context: plan.tracing_context,
captured_execution_context: Some(capture_execution_context()?),
};
client.execute(execute_request).await?
}
Expand Down
11 changes: 10 additions & 1 deletion src/batch/src/rpc/service/task_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ impl TaskService for BatchServiceImpl {
plan,
epoch,
tracing_context,
captured_execution_context,
} = request.into_inner();

let (state_tx, state_rx) = tokio::sync::mpsc::channel(TASK_STATUS_BUFFER_SIZE);
Expand All @@ -79,6 +80,7 @@ impl TaskService for BatchServiceImpl {
),
state_reporter,
TracingContext::from_protobuf(&tracing_context),
captured_execution_context.expect("no captured execution context found"),
)
.await;
match res {
Expand Down Expand Up @@ -119,12 +121,15 @@ impl TaskService for BatchServiceImpl {
plan,
epoch,
tracing_context,
captured_execution_context,
} = req.into_inner();

let task_id = task_id.expect("no task id found");
let plan = plan.expect("no plan found").clone();
let epoch = epoch.expect("no epoch found");
let tracing_context = TracingContext::from_protobuf(&tracing_context);
let captured_execution_context =
captured_execution_context.expect("no captured execution context found");

let context = ComputeNodeContext::new_for_local(self.env.clone());
trace!(
Expand All @@ -135,7 +140,11 @@ impl TaskService for BatchServiceImpl {
let task = BatchTaskExecution::new(&task_id, plan, context, epoch, self.mgr.runtime())?;
let task = Arc::new(task);
let (tx, rx) = tokio::sync::mpsc::channel(LOCAL_EXECUTE_BUFFER_SIZE);
if let Err(e) = task.clone().async_execute(None, tracing_context).await {
if let Err(e) = task
.clone()
.async_execute(None, tracing_context, captured_execution_context)
.await
{
error!(
"failed to build executors and trigger execution of Task {:?}: {}",
task_id, e
Expand Down
28 changes: 18 additions & 10 deletions src/batch/src/task/task_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ use risingwave_common::array::DataChunk;
use risingwave_common::util::panic::FutureCatchUnwindExt;
use risingwave_common::util::runtime::BackgroundShutdownRuntime;
use risingwave_common::util::tracing::TracingContext;
use risingwave_expr::captured_execution_context_scope;
use risingwave_pb::batch_plan::{PbTaskId, PbTaskOutputId, PlanFragment};
use risingwave_pb::common::BatchQueryEpoch;
use risingwave_pb::stream_plan::CapturedExecutionContext;
use risingwave_pb::task_service::task_info_response::TaskStatus;
use risingwave_pb::task_service::{GetDataResponse, TaskInfoResponse};
use risingwave_pb::PbFieldNotFound;
Expand Down Expand Up @@ -425,6 +427,7 @@ impl<C: BatchTaskContext> BatchTaskExecution<C> {
self: Arc<Self>,
state_tx: Option<StateReporter>,
tracing_context: TracingContext,
captured_execution_context: CapturedExecutionContext,
) -> Result<()> {
let mut state_tx = state_tx;
trace!(
Expand All @@ -433,14 +436,17 @@ impl<C: BatchTaskContext> BatchTaskExecution<C> {
serde_json::to_string_pretty(self.plan.get_root()?).unwrap()
);

let exec = ExecutorBuilder::new(
self.plan.root.as_ref().unwrap(),
&self.task_id,
self.context.clone(),
self.epoch.clone(),
self.shutdown_rx.clone(),
let exec = captured_execution_context_scope!(
captured_execution_context.clone(),
Comment on lines +439 to +440
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a result, we have to find all paths to provide the context before evaluating. ...(the frontend inline rewriting approach) is really easy to implement and not invasive at all.

We either need to find all paths to provide the context before evaluating, or find all paths to inline the context before evaluating. The primary goal of these make_timestamptz PRs are not to support this new function for users, but to be the pioneer and see if the new approach is better than existing one.

@KeXiangWang How did you figure out these places to provide context in this PR? If some of them slip through, how easy are they exposed as a runtime error? My impression was that there are less places and easier to surface compared to the expr rewrite approach (recent addition #13724). But this can be wrong and simply due to we had more time to receive bugs on the rewrite approach.

I also agree inlining is less invasive, to the extend that it is solely in frontend. But if approach A requires awareness in 10 submodules in 1 module, while approach B requires awareness in 2 submodules in 3 parent modules each, it may also be acceptable to consider A as more invasive because 10 > 2 * 3. Again these numbers are made up arbitrarily and personally I feel the difference between 10 and 6 is not large enough to justify it.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went through the codes in frontend and run some test examples to help verify whether all of them are found.

The good thing is when there's an expression been evaluated without context, it will throw an error like "context TIME_ZONE not found" and the error is shown in psql console, making it easy to recognize. For streaming mode, it will generate one log with the same error message and when we read from the MV, the result of that row is missed.

Another benefit is that we only need to find all the paths (to provide the context before evaluating) once. Once it's finished correctly with make_timestamptz, unless we have new paths, we don't need to care it in following the implementation of other expressions.

ExecutorBuilder::new(
self.plan.root.as_ref().unwrap(),
&self.task_id,
self.context.clone(),
self.epoch.clone(),
self.shutdown_rx.clone(),
)
.build()
)
.build()
.await?;

let sender = self.sender.clone();
Expand Down Expand Up @@ -472,9 +478,11 @@ impl<C: BatchTaskContext> BatchTaskExecution<C> {

// We should only pass a reference of sender to execution because we should only
// close it after task error has been set.
t_1.run(exec, sender, state_tx.as_mut())
.instrument(span)
.await;
captured_execution_context_scope!(
captured_execution_context,
t_1.run(exec, sender, state_tx.as_mut()).instrument(span)
)
.await;
};

if let Some(batch_metrics) = batch_metrics {
Expand Down
17 changes: 12 additions & 5 deletions src/batch/src/task/task_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use risingwave_common::util::runtime::BackgroundShutdownRuntime;
use risingwave_common::util::tracing::TracingContext;
use risingwave_pb::batch_plan::{PbTaskId, PbTaskOutputId, PlanFragment};
use risingwave_pb::common::BatchQueryEpoch;
use risingwave_pb::stream_plan::CapturedExecutionContext;
use risingwave_pb::task_service::task_info_response::TaskStatus;
use risingwave_pb::task_service::{GetDataResponse, TaskInfoResponse};
use tokio::sync::mpsc::Sender;
Expand Down Expand Up @@ -102,6 +103,7 @@ impl BatchManager {
context: ComputeNodeContext,
state_reporter: StateReporter,
tracing_context: TracingContext,
captured_execution_context: CapturedExecutionContext,
) -> Result<()> {
trace!("Received task id: {:?}, plan: {:?}", tid, plan);
let task = BatchTaskExecution::new(tid, plan, context, epoch, self.runtime())?;
Expand All @@ -128,11 +130,15 @@ impl BatchManager {
task_id,
);
};
task.async_execute(Some(state_reporter), tracing_context)
.await
.inspect_err(|_| {
self.cancel_task(&task_id.to_prost());
})?;
task.async_execute(
Some(state_reporter),
tracing_context,
captured_execution_context,
)
.await
.inspect_err(|_| {
self.cancel_task(&task_id.to_prost());
})?;
ret
}

Expand All @@ -151,6 +157,7 @@ impl BatchManager {
ComputeNodeContext::for_test(),
StateReporter::new_with_test(),
TracingContext::none(),
CapturedExecutionContext::default(),
KeXiangWang marked this conversation as resolved.
Show resolved Hide resolved
)
.await
}
Expand Down
4 changes: 4 additions & 0 deletions src/expr/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ risingwave_udf = { workspace = true }
smallvec = "1"
static_assertions = "1"
thiserror = "1"
tokio = { version = "0.2", package = "madsim-tokio", features = [
"rt",
"macros",
] }
tracing = "0.1"

[target.'cfg(not(madsim))'.dependencies]
Expand Down
28 changes: 28 additions & 0 deletions src/expr/core/src/captured_execution_context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2023 RisingWave Labs
//
// 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 risingwave_expr::{define_context, Result as ExprResult};
use risingwave_pb::stream_plan::CapturedExecutionContext;

// For all execution mode.
define_context! {
pub TIME_ZONE: String,
}

pub fn capture_execution_context() -> ExprResult<CapturedExecutionContext> {
let ctx = TIME_ZONE::try_with(|time_zone| CapturedExecutionContext {
time_zone: time_zone.to_owned(),
})?;
Ok(ctx)
KeXiangWang marked this conversation as resolved.
Show resolved Hide resolved
}
1 change: 1 addition & 0 deletions src/expr/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
extern crate self as risingwave_expr;

pub mod aggregate;
pub mod captured_execution_context;
#[doc(hidden)]
pub mod codegen;
mod error;
Expand Down
1 change: 1 addition & 0 deletions src/expr/impl/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
#![feature(test)]
#![feature(arc_unwrap_or_clone)]
#![feature(iter_array_chunks)]
#![feature(result_flattening)]

mod aggregate;
mod scalar;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,11 @@
// limitations under the License.

use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
use risingwave_common::types::{FloatExt, Timestamptz, F64};
use risingwave_common::types::{FloatExt, Timestamp, Timestamptz, F64};
use risingwave_expr::captured_execution_context::TIME_ZONE;
use risingwave_expr::{capture_context, function, ExprError, Result};

use super::context::TIME_ZONE;

/// Just a wrapper to reuse the `map_err` logic.
#[inline(always)]
pub fn time_zone_err(inner_err: String) -> ExprError {
ExprError::InvalidParam {
name: "time_zone",
reason: inner_err.into(),
}
}
use crate::scalar::timestamptz::timestamp_at_time_zone;

// year int, month int, day int, hour int, min int, sec double precision
#[function("make_timestamptz(int4, int4, int4, int4, int4, float8) -> timestamptz")]
Expand Down Expand Up @@ -64,7 +56,6 @@ fn make_timestamptz_impl(
min: i32,
sec: F64,
) -> Result<Timestamptz> {
let time_zone = Timestamptz::lookup_time_zone(time_zone).map_err(time_zone_err)?;
if !sec.is_finite() || sec.0.is_sign_negative() {
return Err(ExprError::InvalidParam {
name: "sec",
Expand All @@ -86,16 +77,6 @@ fn make_timestamptz_impl(
reason: "invalid time".into(),
})?,
);
let date_time = naive_date_time
.and_local_timezone(time_zone)
.latest()
.ok_or_else(|| ExprError::InvalidParam {
name: "time_zone",
reason: format!(
"fail to interpret local timestamp \"{:?}\" in time zone \"{}\"",
naive_date_time, time_zone
)
.into(),
})?;
Ok(Timestamptz::from(date_time))

timestamp_at_time_zone(Timestamp(naive_date_time), time_zone)
}
1 change: 1 addition & 0 deletions src/expr/impl/src/scalar/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ mod jsonb_info;
mod jsonb_object;
mod length;
mod lower;
mod make_timestamptz;
mod md5;
mod overlay;
mod position;
Expand Down
16 changes: 15 additions & 1 deletion src/expr/macro/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use itertools::Itertools;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned, ToTokens};
use syn::parse::{Parse, ParseStream};
use syn::{Error, FnArg, Ident, ItemFn, Result, Token, Type, Visibility};
use syn::{Error, Expr, FnArg, Ident, ItemFn, Result, Token, Type, Visibility};

use crate::utils::extend_vis_with_super;

Expand Down Expand Up @@ -224,3 +224,17 @@ pub(super) fn generate_captured_function(
#new_user_fn
})
}

pub(super) struct CapturedExecutionContextScopeInput {
pub context: Expr,
pub closure: Expr,
}

impl Parse for CapturedExecutionContextScopeInput {
fn parse(input: ParseStream<'_>) -> Result<Self> {
let context: Expr = input.parse()?;
input.parse::<Token![,]>()?;
let closure: Expr = input.parse()?;
Ok(Self { context, closure })
}
}
Loading
Loading