Skip to content

common/async: add call_once() algorithm for optional_yield - #62466

Closed
cbodley wants to merge 3 commits into
ceph:mainfrom
cbodley:wip-async-call-once
Closed

cbodley wants to merge 3 commits into
ceph:mainfrom
cbodley:wip-async-call-once

Conversation

@cbodley

@cbodley cbodley commented Mar 24, 2025

Copy link
Copy Markdown
Contributor

modeled after std::call_once() to guarantee that racing callers wait for the initial caller to finish. the main differences here are:

  • support for coroutine callers to suspend instead of blocking while waiting for the initial caller, and
  • the wrapped function must return a value, which is cached and returned to all callers
Show available Jenkins commands

@cbodley
cbodley force-pushed the wip-async-call-once branch 6 times, most recently from 7f122df to b45df66 Compare March 24, 2025 23:34
@cbodley cbodley mentioned this pull request Mar 25, 2025
4 of 14 tasks
@cbodley
cbodley force-pushed the wip-async-call-once branch from 3614785 to 57cdefa Compare March 27, 2025 15:57
@cbodley
cbodley marked this pull request as ready for review March 27, 2025 15:58
@cbodley
cbodley requested a review from adamemerson March 27, 2025 15:58
@cbodley

cbodley commented Mar 27, 2025

Copy link
Copy Markdown
Contributor Author
  • the wrapped function must return a value, which is cached and returned to all callers

once_flag probably deserves a specialization for void to match the behavior of std::call_once(), but
a) it's not necessary for the caching use case in #61256, and
b) void specializations are a pain in the butt. yield_waiter, for example, has to duplicate most of the class to make this work

@cbodley

cbodley commented Mar 27, 2025

Copy link
Copy Markdown
Contributor Author

@cbodley

cbodley commented Mar 27, 2025

Copy link
Copy Markdown
Contributor Author

jenkins test make check arm64

@cbodley

cbodley commented Mar 27, 2025

Copy link
Copy Markdown
Contributor Author

test cases both passing under asan, tsan, and valgrind ex

$ valgrind --tool=memcheck --exit-on-first-error=yes bin/unittest_async_call_once --gtest_repeat=1000

@adamemerson adamemerson left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I like this quite a bit, perhaps call it call_cached or cache_single_call if you wanted to be very specific..

@cbodley

cbodley commented Mar 27, 2025

Copy link
Copy Markdown
Contributor Author

windows build failed:

common/async/yield_waiter.h:231:13: error: no viable constructor or deduction guide for deduction of template arguments of 'lock_handler'
            detail::lock_handler{std::move(s.handler), s.lock}, ec));
            ^

@cbodley

cbodley commented Mar 27, 2025

Copy link
Copy Markdown
Contributor Author

I like this quite a bit, perhaps call it call_cached or cache_single_call if you wanted to be very specific..

what do you think about keeping the name call_once(), but overloading it for once_flag (the void-returning version) and once_result<T> (the cached version)?

@adamemerson

Copy link
Copy Markdown
Contributor

I like this quite a bit, perhaps call it call_cached or cache_single_call if you wanted to be very specific..

what do you think about keeping the name call_once(), but overloading it for once_flag (the void-returning version) and once_result<T> (the cached version)?

Sounds good to me.

@chardan chardan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'll have to read through this again after a few things have settled more, but overall this looks like a very high-quality implementation and it's a pleasure to see! (My understanding of Asio presently leaves much to be desired, so it's hard for me to comment too meaningfully on some of this, and the potential interactions are difficult anyways.) I don't have any big quibbles, but I would like to see some consideration maybe toward the names that conflict with the standard library's, and to make sure I'm following some of this, especially with a better understanding of the context. But overall this was a pleasure to read and appears very useful, thanks for all of the work on it!

/*
* Ceph - scalable distributed file system
*
* Copyright contributors to the Ceph project

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is a date needed?

Comment thread src/common/async/call_once.h Outdated
/// The cached Result type must be semiregular (copyable and default-
/// constructible).
template <std::semiregular Result>
class once_flag final : public service_list_base_hook {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I would prefer that we try to avoid names that conflict with standard library names (especially when we know they are). There are two main reasons:

  1. if someone has imported it into the namespace they may not be aware that this isn't the standard library component, and be surprised by differing behavior; this is a big one. Even though "that's what namespaces are for", my experience has been that this can still cause very real confusion.
  2. it makes it a bit harder to search for, or to search for meaningfully

I know it's a bit of a pain, but please consider a different name.
once_base_hook_flag (I'm not sure what base_hook does, but...)
once_hook_flag (sounds catchy!)
once_result_flag
...

It might also be good to capture in comments the reason for not using a regular once_flag-- from the type requirements, I gather that it's because a std::once_flag is neither copyable nor movable, and this type is?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks, agreed on the name conflict especially because important semantics differ with the std version. will call this once_result<T> and probably omit the void-returning version

It might also be good to capture in comments the reason for not using a regular once_flag-- from the type requirements, I gather that it's because a std::once_flag is neither copyable nor movable, and this type is?

this class isn't copyable/movable either, but unlike std::once_flag it a) stores a return value and b) has a call_once() that takes optional_yield for coroutine support

/// completion and return its result. Otherwise, call f() and return its
/// result. f() must return Result when called with no arguments. If it
/// throws, that exception is rethrown by all calls.
template <typename Callable>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same of course applies here.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Just to clarify, this is a kind of memoizer that works for concurrent requests? So the first request blocks until a result is obtained, and the cached result is returned to all future callers; if the call is already cached, the result is returned OR the exception is thrown?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm trying to get my head around the queuing part still. Is this part of ASIO internals?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same of course applies here.

this refers to the naming conflict with std::call_once()? i think it's less of an issue here because, with ADL, call_once(foo...) is going to call the right version either way. and this call_once() also takes an extra optional_yield argument so there's no abiguity

Just to clarify ...

all accurate

I'm trying to get my head around the queuing part still. Is this part of ASIO internals?

the queueing part is handled by the Wait state and its list of Waiters. the asio stuff is only involved for the AsyncWaiters who passed in a non-empty optional_yield

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I agree that ADL will find it. I'm less concerned about the compiler than the human reader. That said, this feels /comparatively/ ok, but if we think of a nicer name I wouldn't object to it being changed. The extra argument does make a difference also, but I hope we don't do this too often, it can get really confusing (like in the case of "list").

Comment thread src/common/async/call_once.h Outdated
void operator()(Wait& wait) {
while (!wait.waiters.empty()) {
auto& waiter = wait.waiters.front();
wait.waiters.pop_front();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do we need to lock during this? Or is that handled by the other code?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this service_shutdown() stuff is triggered by the asio::io_context destructor: https://www.boost.org/doc/libs/1_87_0/doc/html/boost_asio/reference/io_context/_io_context.html

if we're in the destructor, we can safely assume that any threads calling io_context::run() have returned, so are no longer running anything that could race with this cleanup

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thinking more on this, the mix of sync/async waiters makes this tricky. i pushed one more commit with message:

service_shutdown() is really just for async waiters that we know won't complete. synchronous callers in other threads may still complete, so we shouldn't mess with their waiters

split sync/async waiters into separate lists so can leave the sync ones

[this, &lock] (handler_type h) {
auto slot = get_associated_cancellation_slot(h);
if (slot.is_connected()) {
slot.template emplace<op_cancellation>(this);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Right, "slot::emplace()" is a dependent name, get_associated_cancellation_slot() has a pretty magical return type.

namespace boost::asio {

// forward the handler's associated executor, allocator, cancellation slot, etc
template <template <typename, typename> class Associator,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Template-templates on the move! Here, we look to be playing some CRTP games and are very, very happy that auto is a thing. I need to read about Associator, but it is pleasant compared to The Old Way(TM)!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I need to read about Associator

https://www.boost.org/doc/libs/1_87_0/doc/html/boost_asio/overview/model/associators.html might be a good place to start. in asio, it's a common pattern for handlers to wrap other handlers. this template is a convenient way to preserve properties of the wrapped handler

#include <boost/intrusive/list.hpp>

#include "common/async/yield_context.h"
#include "common/async/yield_waiter.h"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'll have to learn more about this gadget, looks handy!

Comment thread src/common/async/call_once.h Outdated

template <typename Callable>
struct CallVisitor {
once_flag& self;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm guessing this is "our" once_flag!

Comment thread src/common/async/call_once.h Outdated
requires std::convertible_to<std::invoke_result_t<Callable>, Result>
{
auto lock = std::unique_lock{self.mutex};
return std::visit(CallVisitor{self, lock, y, std::forward<Callable>(f)},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'm going to have to skip ahead and read about the adventures of CallVisitor first! Looks good.

std::latch call_latch{1};
std::latch wait_latch{2};

call_future = std::async(std::launch::async, [&] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It's lambdas all the way down...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yo dawg, i heard you like lambdas

@cbodley

cbodley commented Mar 28, 2025

Copy link
Copy Markdown
Contributor Author

updates:

  • Wait state doesn't depend on the Result type, so move it into detail namespace
  • move service_shutdown stuff into Wait state to avoid ShutdownVisitor
  • encapsulate waiting and wakeup logic in Wait state
  • replace CallVisitor with fu2::overload() and lambdas
  • rename once_flag -> once_result to differentiate from std::once_flag
  • expanded documentation for call_once()

@chardan

chardan commented Mar 28, 2025

Copy link
Copy Markdown
Contributor

With the caveat that my Asio-fu is currently pretty basic and this heads into deeper water than I've been in, LGTM! Thank you for doing this.

cbodley added 3 commits March 28, 2025 15:31
if async_wait() can race with complete() across threads, the
yield_waiter's handler_state needs to be protected by a mutex. add
an async_wait() overload for unique_lock that behaves like
condition_variable::wait(): the lock is released immediately before
suspending, and reacquired immediately before calling its completion
handler

Signed-off-by: Casey Bodley <[email protected]>
also adds an empty() function so it's easier to specify its precondition

Signed-off-by: Casey Bodley <[email protected]>
modeled after std::call_once() to guarantee that racing callers wait for
the initial caller to finish. the main differences here are

* support for coroutine callers to suspend instead of blocking while
  waiting for the initial caller, and
* the wrapped function must return a value, which is cached and returned
  to all callers

Signed-off-by: Casey Bodley <[email protected]>
@cbodley
cbodley force-pushed the wip-async-call-once branch from abbf916 to 6e9c07f Compare March 28, 2025 19:33
@github-actions

Copy link
Copy Markdown

This pull request has been automatically marked as stale because it has not had any activity for 60 days. It will be closed if no further activity occurs for another 30 days.
If you are a maintainer or core committer, please follow-up on this pull request to identify what steps should be taken by the author to move this proposed change forward.
If you are the author of this pull request, thank you for your proposed contribution. If you believe this change is still appropriate, please ensure that any feedback has been addressed and ask for a code review.

@github-actions github-actions Bot added the stale label May 27, 2025
@ceph ceph deleted a comment from github-actions Bot Jan 6, 2026
@adamemerson adamemerson added needs-qa and removed stale labels Jan 6, 2026
@JonBailey1993

Copy link
Copy Markdown
Contributor

@yuriw

yuriw commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

jenkins test this please

@yuriw

yuriw commented Mar 20, 2026

Copy link
Copy Markdown
Contributor

@cbodley this PR was approved pls merge at will when all checks passed
ref: https://tracker.ceph.com/issues/75119

@cbodley

cbodley commented Mar 20, 2026

Copy link
Copy Markdown
Contributor Author

thanks @yuriw. i think #61256 is probably close enough to merging, so i'm not in a hurry to merge this separately

@cbodley Does this have a basic flaw or does it just need eyes/attention?

your approval is good enough for me. i was expecting these commits to merge with #61256, but it would be fine to merge this separately. this modifies yield_waiter which we use in rgw_notify.cc and rgw_pubsub_push.cc, so it's probably worth running through the rgw suite for validation

@adamemerson if we want to validate/merge this, it just needs the rgw suite

@anrao19

anrao19 commented Apr 9, 2026

Copy link
Copy Markdown
Contributor

FYI, pr testing is in progress...
Tracker created for same is : https://tracker.ceph.com/issues/75779

@anrao19

anrao19 commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor

FYI, pr testing is in progress... Tracker created for same is : https://tracker.ceph.com/issues/75779

Pr testing completed. Tacker approved by @ivancich. More details : https://tracker.ceph.com/issues/75779
@cbodley , if no further testing needed, pr can be merged

@anrao19

anrao19 commented Apr 17, 2026

Copy link
Copy Markdown
Contributor

jenkins test make check arm64

@adamemerson

Copy link
Copy Markdown
Contributor

jenkins test make check

@adamemerson

Copy link
Copy Markdown
Contributor

jenkins test make check arm64

@adamemerson

Copy link
Copy Markdown
Contributor

jenkins test docs

@github-actions

github-actions Bot commented Jun 9, 2026

Copy link
Copy Markdown

This pull request can no longer be automatically merged: a rebase is needed and changes have to be manually resolved

@cbodley

cbodley commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

merged in #61256

@cbodley cbodley closed this Jun 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants