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

Introduce ArcVec<T> to improve Copy performance of messages #2015

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 2 additions & 1 deletion crates/types/src/net/replicated_loglet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::logs::metadata::SegmentIndex;
use crate::logs::{LogId, LogletOffset, Record, SequenceNumber, TailState};
use crate::net::define_rpc;
use crate::replicated_loglet::ReplicatedLogletId;
use crate::storage::ArcVec;

// ----- ReplicatedLoglet Sequencer API -----
define_rpc! {
Expand Down Expand Up @@ -69,7 +70,7 @@ impl CommonResponseHeader {
pub struct Append {
#[serde(flatten)]
pub header: CommonRequestHeader,
pub payloads: Vec<Record>,
pub payloads: ArcVec<Record>,
}

impl Append {
Expand Down
124 changes: 124 additions & 0 deletions crates/types/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,17 @@
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0.

use core::fmt;
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
use std::sync::Arc;

use bytes::{Buf, BufMut, Bytes, BytesMut};
use downcast_rs::{impl_downcast, DowncastSync};
use serde::de::{DeserializeOwned, Error as DeserializationError};
use serde::ser::Error as SerializationError;
use serde::ser::SerializeSeq;
use serde::{Deserialize, Serialize};
use tracing::error;

Expand Down Expand Up @@ -395,6 +399,126 @@ pub fn decode_from_flexbuffers<T: DeserializeOwned, B: Buf>(
}
}

/// [`ArcVec`] mainly used by `message` types to improve
/// cloning of messages.
///
/// It can replace [`Vec<T>`] most of the time in all structures
/// that need to be serialized over the wire.
///
/// Internally it keeps the data inside an [`Arc<[T]>`]
#[derive(Debug)]
pub struct ArcVec<T> {
inner: Arc<[T]>,
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a benefit over Arc<Vec<T>>? If I understand the API correctly, then converting from Vec<T> into an Arc<[T]> requires an extra allocation whereas the former adds another level of pointer indirection.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The only reason that I used Arc<[T]> instead of Arc<Vec<T>> is because Arc<[T]> is very common type in Bifrost.

In Bifrost the Loglet::enqueue_batch method accepts an Arc<[Record]> as a param, but when we actually need to send this over the wire (in case of replicated loglet client, or to log servers), the message data types are using Vec<Record> type. This requires copying all records to build, which can be quite heavy in case we sending the same set of records to multiple log servers for example.

In other wards, the most common usage patter is to build an ArcVec from an Arc<[Record]> not from Vec.

That being said, I should actually Arc<[T]>::from(vec) instead of from_iter to build the ArcVec from a Vec (in case of deseralization) to avoid one extra allocation. as per here

Copy link
Contributor

Choose a reason for hiding this comment

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

Thanks for the explanation.

I think that Arc<[T]>::from(vec) will also require one additional allocation.

Once this becomes a problem and measurable, we can revisit it.

}

impl<T> Deref for ArcVec<T> {
type Target = [T];
fn deref(&self) -> &Self::Target {
&self.inner
}
}

impl<T> serde::Serialize for ArcVec<T>
where
T: serde::Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let mut seq = serializer.serialize_seq(Some(self.len()))?;
for elem in self.iter() {
seq.serialize_element(elem)?;
}

seq.end()
}
}

impl<'de, T> serde::Deserialize<'de> for ArcVec<T>
where
T: serde::Deserialize<'de>,
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
deserializer.deserialize_seq(ArcVecVisitor::default())
}
}

struct ArcVecVisitor<T> {
_phantom: PhantomData<T>,
}

impl<T> Default for ArcVecVisitor<T> {
fn default() -> Self {
Self {
_phantom: PhantomData,
}
}
}

impl<'de, T> serde::de::Visitor<'de> for ArcVecVisitor<T>
where
T: serde::Deserialize<'de>,
{
type Value = ArcVec<T>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "expecting an array")
}

fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let mut vec: Vec<T> = Vec::with_capacity(seq.size_hint().unwrap_or_default());
while let Some(value) = seq.next_element()? {
vec.push(value);
}

Ok(vec.into())
Comment on lines +476 to +481
Copy link
Contributor

Choose a reason for hiding this comment

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

Once rust-lang/rust#129401 lands with Rust 1.82, we can avoid the extra allocation of a Vec here and directly produce into the Arc<[T]> slice.

}
}

impl<T> Clone for ArcVec<T> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
}
}
}

impl<T> From<ArcVec<T>> for Arc<[T]> {
fn from(value: ArcVec<T>) -> Self {
value.inner
}
}

impl<T> From<ArcVec<T>> for Vec<T>
where
T: Clone,
{
fn from(value: ArcVec<T>) -> Self {
Vec::from_iter(value.iter().cloned())
}
}

impl<T> From<Vec<T>> for ArcVec<T> {
fn from(value: Vec<T>) -> Self {
Self {
inner: value.into(),
}
}
}

impl<T> From<Arc<[T]>> for ArcVec<T> {
fn from(value: Arc<[T]>) -> Self {
Self { inner: value }
}
}

#[cfg(test)]
mod tests {
use bytes::Bytes;
Expand Down
Loading