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

Skip unnecessary updates if the new state matches the current one #1366

Merged
merged 14 commits into from
Jan 10, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions crates/core/src/client_events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,10 @@ async fn process_open_request(
Ok(ContractHandlerEvent::UpdateResponse {
new_value: Err(err),
}) => Err(OpError::from(err)),
Ok(ContractHandlerEvent::UpdateNoChange { key }) => {
tracing::debug!(%key, "update with no change, do not start op");
return Ok(None);
}
Err(err) => Err(err.into()),
Ok(_) => Err(OpError::UnexpectedOpState),
}
Expand Down
45 changes: 31 additions & 14 deletions crates/core/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub mod storages;

pub(crate) use executor::{
executor_channel, mock_runtime::MockRuntime, Callback, ExecutorToEventLoopChannel,
NetworkEventListenerHalve,
NetworkEventListenerHalve, UpsertResult,
};
pub(crate) use handler::{
client_responses_channel, contract_handler_channel, in_memory::MemoryContractHandler,
Expand Down Expand Up @@ -87,18 +87,30 @@ where
} => {
let put_result = contract_handler
.executor()
.upsert_contract_state(key, Either::Left(state), related_contracts, contract)
.upsert_contract_state(
key,
Either::Left(state.clone()),
related_contracts,
contract,
)
.instrument(tracing::info_span!("upsert_contract_state", %key))
.await;

let event_result = match put_result {
Ok(UpsertResult::NoChange) => ContractHandlerEvent::PutResponse {
new_value: Ok(state),
},
Ok(UpsertResult::Updated(state)) => ContractHandlerEvent::PutResponse {
new_value: Ok(state),
},
Err(err) => ContractHandlerEvent::PutResponse {
new_value: Err(err),
},
};

contract_handler
.channel()
.send_to_sender(
id,
ContractHandlerEvent::PutResponse {
new_value: put_result.map_err(Into::into),
},
)
.send_to_sender(id, event_result)
.await
.map_err(|error| {
tracing::debug!(%error, "shutting down contract handler");
Expand All @@ -123,14 +135,19 @@ where
.instrument(tracing::info_span!("upsert_contract_state", %key))
.await;

let event_result = match update_result {
Ok(UpsertResult::NoChange) => ContractHandlerEvent::UpdateNoChange { key },
Ok(UpsertResult::Updated(state)) => ContractHandlerEvent::UpdateResponse {
new_value: Ok(state),
},
Err(err) => ContractHandlerEvent::UpdateResponse {
new_value: Err(err),
},
};

contract_handler
.channel()
.send_to_sender(
id,
ContractHandlerEvent::UpdateResponse {
new_value: update_result.map_err(Into::into),
},
)
.send_to_sender(id, event_result)
.await
.map_err(|error| {
tracing::debug!(%error, "shutting down contract handler");
Expand Down
11 changes: 8 additions & 3 deletions crates/core/src/contract/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use freenet_stdlib::prelude::*;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc::{self};

use super::storages::Storage;
use crate::config::Config;
use crate::message::Transaction;
use crate::node::OpManager;
Expand All @@ -33,8 +34,6 @@ use crate::{
operations::{self, Operation},
};

use super::storages::Storage;

pub(super) mod mock_runtime;
pub(super) mod runtime;

Expand Down Expand Up @@ -399,6 +398,12 @@ struct UpdateContract {
new_state: WrappedState,
}

#[derive(Debug)]
pub(crate) enum UpsertResult {
NoChange,
Updated(WrappedState),
}

impl ComposeNetworkMessage<operations::update::UpdateOp> for UpdateContract {
fn initiate_op(self, _op_manager: &OpManager) -> operations::update::UpdateOp {
let UpdateContract { key, new_state } = self;
Expand Down Expand Up @@ -428,7 +433,7 @@ pub(crate) trait ContractExecutor: Send + 'static {
update: Either<WrappedState, StateDelta<'static>>,
related_contracts: RelatedContracts<'static>,
code: Option<ContractContainer>,
) -> impl Future<Output = Result<WrappedState, ExecutorError>> + Send;
) -> impl Future<Output = Result<UpsertResult, ExecutorError>> + Send;

fn register_contract_notifier(
&mut self,
Expand Down
7 changes: 3 additions & 4 deletions crates/core/src/contract/executor/mock_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ impl ContractExecutor for Executor<MockRuntime> {
state: Either<WrappedState, StateDelta<'static>>,
_related_contracts: RelatedContracts<'static>,
code: Option<ContractContainer>,
) -> Result<WrappedState, ExecutorError> {
) -> Result<UpsertResult, ExecutorError> {
// todo: instead allow to perform mutations per contract based on incoming value so we can track
// state values over the network
match (state, code) {
Expand All @@ -95,16 +95,15 @@ impl ContractExecutor for Executor<MockRuntime> {
.store(key, incoming_state.clone(), contract.params().into_owned())
.await
.map_err(ExecutorError::other)?;
Ok(incoming_state)
Ok(UpsertResult::Updated(incoming_state))
}
(Either::Left(incoming_state), None) => {
// update case

self.state_store
.update(&key, incoming_state.clone())
.await
.map_err(ExecutorError::other)?;
Ok(incoming_state)
Ok(UpsertResult::Updated(incoming_state))
}
(update, contract) => unreachable!("{update:?}, {contract:?}"),
}
Expand Down
16 changes: 14 additions & 2 deletions crates/core/src/contract/executor/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ impl ContractExecutor for Executor<Runtime> {
update: Either<WrappedState, StateDelta<'static>>,
related_contracts: RelatedContracts<'static>,
code: Option<ContractContainer>,
) -> Result<WrappedState, ExecutorError> {
) -> Result<UpsertResult, ExecutorError> {
let params = if let Some(code) = &code {
code.params()
} else {
Expand Down Expand Up @@ -134,7 +134,13 @@ impl ContractExecutor for Executor<Runtime> {
.validate_state(&key, &params, &updated_state, &related_contracts)
.map_err(|e| ExecutorError::execution(e, None))?
{
ValidateResult::Valid => Ok(updated_state),
ValidateResult::Valid => {
if updated_state.as_ref() == current_state.as_ref() {
Ok(UpsertResult::NoChange)
} else {
Ok(UpsertResult::Updated(updated_state))
}
}
ValidateResult::Invalid => Err(ExecutorError::request(
freenet_stdlib::client_api::ContractError::Update {
key,
Expand Down Expand Up @@ -536,6 +542,12 @@ impl Executor<Runtime> {
}
};
let new_state = WrappedState::new(new_state.into_bytes());

if new_state.as_ref() == current_state.as_ref() {
tracing::debug!("No changes in state for contract {key}, avoiding update");
return Ok(Either::Left(current_state.clone()));
}

self.state_store
.update(key, new_state.clone())
.await
Expand Down
7 changes: 7 additions & 0 deletions crates/core/src/contract/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,10 @@ pub(crate) enum ContractHandlerEvent {
UpdateResponse {
new_value: Result<WrappedState, ExecutorError>,
},
// The response to an update query where the state has not changed
UpdateNoChange {
key: ContractKey,
},
RegisterSubscriberListener {
key: ContractKey,
client_id: ClientId,
Expand Down Expand Up @@ -397,6 +401,9 @@ impl std::fmt::Display for ContractHandlerEvent {
write!(f, "update query failed {{ {e} }}",)
}
},
ContractHandlerEvent::UpdateNoChange { key } => {
write!(f, "update query no change {{ {key} }}",)
}
ContractHandlerEvent::RegisterSubscriberListener { key, client_id, .. } => {
write!(
f,
Expand Down
Loading