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(core): Log protocol upgrades on trace #3128

Merged
merged 9 commits into from
Dec 14, 2022
69 changes: 61 additions & 8 deletions core/src/upgrade/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ use multistream_select::{self, DialerSelectFuture, ListenerSelectFuture};
use std::{iter, mem, pin::Pin, task::Context, task::Poll};

pub use multistream_select::Version;
use smallvec::SmallVec;
use std::fmt;

// TODO: Still needed?
/// Applies an upgrade to the inbound and outbound direction of a connection or substream.
Expand Down Expand Up @@ -105,6 +107,7 @@ where
},
Upgrade {
future: Pin<Box<U::Future>>,
name: SmallVec<[u8; 32]>,
Copy link
Member

Choose a reason for hiding this comment

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

A stream upgrade involves various I/O operations on many layers. I don't think a heap allocated 32 byte vector have a significant performance impact.

Thus, unless the performance improvement is proven through a benchmark, I suggest allocating on the heap here.

Suggested change
name: SmallVec<[u8; 32]>,
name: Vec<u8>,

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Given that all protocol names I’m aware of are quite small, I see no reason to unconditionally allocate on the heap — why should that be the default that needs no reason? I could reduce the inline capacity to keep size_of equal to that of a Vec<u8>, if you want.

Copy link
Contributor

Choose a reason for hiding this comment

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

I am with @rkuhn here. I think it is good to avoid allocations for the majority of the cases. I don't see the use of a different type as too much complexity.

Copy link
Member

Choose a reason for hiding this comment

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

I see no reason to unconditionally allocate on the heap — why should that be the default that needs no reason?

Reason for me to not use SmallVec by default is that it adds noise, additional compile time and increases the attack vector in our dependency supply chain. Though the last one might be a lost fight in the first place.

I wrote a benchmark to try to replicate a performance benefit using SmallVec here. I have not been able thus far. Please take a look at Actyx#95. Maybe I can nerd-snipe either of you into proving me wrong @rkuhn and @thomaseizinger.

I am sorry in case this comes across as nit-picky. I am not trying to start an argument. I am genuinely interested in performance optimizations in rust-libp2p. I am curious in which cases we could optimize through stack allocation. I don't think this is one of those cases.

On a more general note, again out of curiosity, is either of you aware of a case where heap allocation is faster than stack allocation? I can not come up with a real world case where the heap would be faster than the stack.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

To me this is foremost a question of using the most appropriate data structure for the job. SmallVec was already in the dependencies, and it is better suited than Vec due to usage characteristics, so I used it.


Regarding the benchmark: memory management cannot be benchmarked in this fashion. In general, microbenchmarks like yours are very rarely meaningful and even then they require careful interpretation of the result. The reason is that most of the time you are looking at a huge machine doing a tiny task, with all sorts of optimisations kicking in. And when you run a relevant task instead, different optimisations will completely change the picture. It is quite obvious that a stack allocation takes less than one CPU cycle and that a heap allocation can in general not be this fast. If your microbenchmark finds them to be equally fast, then your heap usage allows the malloc implementation to optimise down to a single pointer subtraction — which is a very likely thread-local optimisation to make for malloc().

But all of this theory is irrelevant in my opinion because we’re not optimising for the last percent of performance (as far as I’m aware we’re nowhere close to getting there at this point). So I just propose usage of the most appropriate data structure at hand.

Copy link
Contributor

Choose a reason for hiding this comment

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

I think it is reasonable to trust in CS knowledge like "stack allocations are faster than heap", even if you can't produce a micro benchmark that proves it.

Soon, this will be replaced by Cow so I am happy either way. If @mxinden feels strongly, let's go with Vec.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

BTW: this discussion uses “heap” and “stack”, but “stack” doesn’t actually enter the picture in the code in question since we’re talking about a memory slot in a generator, which will end up spawned onto a thread pool, so allocated on the heap in any case.

Copy link
Contributor

Choose a reason for hiding this comment

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

Right, what would be the right terminology then (out of curiosity?). "local variable"?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That sounds appropriate to me — it’ll end up being stored in a compiler-generated enum variant if it lives across an .await point.

Copy link
Member

Choose a reason for hiding this comment

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

Thanks for expanding here. I think the points above are valid. That said, I haven't yet formed a good guiding principle for rust-libp2p.

As said above, the concrete instance is not relevant. Let's get this merged. Looking forward to the easier debugging of protocol upgrades on streams.

},
Undefined,
}
Expand Down Expand Up @@ -137,22 +140,27 @@ where
return Poll::Pending;
}
};
let name = SmallVec::from_slice(info.protocol_name());
self.inner = InboundUpgradeApplyState::Upgrade {
future: Box::pin(upgrade.upgrade_inbound(io, info.0)),
name,
};
}
InboundUpgradeApplyState::Upgrade { mut future } => {
InboundUpgradeApplyState::Upgrade { mut future, name } => {
match Future::poll(Pin::new(&mut future), cx) {
Poll::Pending => {
self.inner = InboundUpgradeApplyState::Upgrade { future };
self.inner = InboundUpgradeApplyState::Upgrade { future, name };
return Poll::Pending;
}
Poll::Ready(Ok(x)) => {
debug!("Successfully applied negotiated protocol");
log::trace!("Upgraded inbound stream to {}", DisplayProtocolName(name));
return Poll::Ready(Ok(x));
}
Poll::Ready(Err(e)) => {
debug!("Failed to apply negotiated protocol");
debug!(
"Failed to upgrade inbound stream to {}",
DisplayProtocolName(name)
);
return Poll::Ready(Err(UpgradeError::Apply(e)));
}
}
Expand Down Expand Up @@ -185,6 +193,7 @@ where
},
Upgrade {
future: Pin<Box<U::Future>>,
name: SmallVec<[u8; 32]>,
},
Undefined,
}
Expand Down Expand Up @@ -217,22 +226,30 @@ where
return Poll::Pending;
}
};
let name = SmallVec::from_slice(info.protocol_name());
self.inner = OutboundUpgradeApplyState::Upgrade {
future: Box::pin(upgrade.upgrade_outbound(connection, info.0)),
name,
};
}
OutboundUpgradeApplyState::Upgrade { mut future } => {
OutboundUpgradeApplyState::Upgrade { mut future, name } => {
match Future::poll(Pin::new(&mut future), cx) {
Poll::Pending => {
self.inner = OutboundUpgradeApplyState::Upgrade { future };
self.inner = OutboundUpgradeApplyState::Upgrade { future, name };
return Poll::Pending;
}
Poll::Ready(Ok(x)) => {
debug!("Successfully applied negotiated protocol");
log::trace!(
"Upgraded outbound stream to {}",
DisplayProtocolName(name)
);
return Poll::Ready(Ok(x));
}
Poll::Ready(Err(e)) => {
debug!("Failed to apply negotiated protocol");
debug!(
"Failed to upgrade outbound stream to {}",
DisplayProtocolName(name)
);
return Poll::Ready(Err(UpgradeError::Apply(e)));
}
}
Expand All @@ -256,3 +273,39 @@ impl<N: ProtocolName> AsRef<[u8]> for NameWrap<N> {
self.0.protocol_name()
}
}

/// Wrapper for printing a [`ProtocolName`] that is expected to be mostly ASCII
pub(crate) struct DisplayProtocolName<N>(pub N);

impl<N: ProtocolName> fmt::Display for DisplayProtocolName<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use fmt::Write;
for byte in self.0.protocol_name() {
if (b' '..=b'~').contains(byte) {
f.write_char(char::from(*byte))?;
} else {
write!(f, "<{:02X}>", byte)?;
}
}
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn display_protocol_name() {
assert_eq!(DisplayProtocolName(b"/hello/1.0").to_string(), "/hello/1.0");
assert_eq!(DisplayProtocolName("/hellö/").to_string(), "/hell<C3><B6>/");
assert_eq!(
DisplayProtocolName((0u8..=255).collect::<Vec<_>>()).to_string(),
(0..32)
.map(|c| format!("<{:02X}>", c))
.chain((32..127).map(|c| format!("{}", char::from_u32(c).unwrap())))
.chain((127..256).map(|c| format!("<{:02X}>", c)))
.collect::<String>()
);
}
}