Skip to content

RSDK-10643: condition var refresh thread #428

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from

Conversation

lia-viam
Copy link
Collaborator

@lia-viam lia-viam commented May 1, 2025

so I think this is how we would want to do a condition_variable-based refresh thread in RobotClient, opening as WIP now for feedback though

@lia-viam lia-viam requested a review from acmorrow May 1, 2025 19:27
@lia-viam lia-viam requested a review from a team as a code owner May 1, 2025 19:27
@lia-viam lia-viam requested review from njooma and stuqdog and removed request for a team May 1, 2025 19:27
@@ -143,7 +143,11 @@ RobotClient::~RobotClient() {
}

void RobotClient::close() {
should_refresh_.store(false);
if (should_refresh_) {
Copy link
Member

Choose a reason for hiding this comment

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

If should_refresh_ is changing state, it should do so under the lock I think.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I think it is not changing state-- should_refresh_ is only mutated in this method and in the named constructor which sets it in the first place, so there may be a concurrent read happening here but there's no way for it to be read while being mutated

Copy link
Member

Choose a reason for hiding this comment

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

I'll argue that this is one of those cases where even if it is safe in practice, it is still better to do the check under the lock. It'll be annoying if someday we stand up TSAN and it whines about a leak here, and this isn't a hot path, so trying to eliminate the lock doesn't buy much of anything.

Copy link
Member

Choose a reason for hiding this comment

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

I mean race of course, not leak, since I'm talking about TSAN not ASAN.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

done!

Copy link
Member

Choose a reason for hiding this comment

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

I'd even move the read of should_referesh_ under the lock, or even eliminate the check entirely. It should be fine in close to just unconditionally set should_refresh_ = false (under the lock), and then notify. If there is no refresh thread, it is just a big no-op.


} catch (std::exception&) {
while (true) {
Copy link
Member

Choose a reason for hiding this comment

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

Could this be while (should_refresh_)?

std::atomic<bool> should_refresh_;
std::mutex refresh_lock_;
std::condition_variable refresh_cv_;
bool should_refresh_;
Copy link
Member

Choose a reason for hiding this comment

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

Might be possible to eliminate the bool by making refresh_interval_ an optional.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

i think you're right, we're storing a T data; bool valid; which is basically just what an optional is under the hood.

(we could just have refresh_interval_ alone do all the work, but it's a little less self-documenting, although there are compact_optional types that allow this sort of thing)

Copy link
Member

Choose a reason for hiding this comment

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

I think it is probably worth doing. There's just less state to manage, which means less risk of things decohering. It'd also simplify RobotClient::with_channel:

From

    robot->refresh_interval_ = std::chrono::seconds{options.refresh_interval()};
    robot->should_refresh_ = (robot->refresh_interval_ > std::chrono::seconds{0});
    if (robot->should_refresh_) {
        robot->refresh_thread_ = std::thread{&RobotClient::refresh_every, robot.get()};
    }

To

    if (options.refresh_interval() != 0) {
        robot->refresh_interval_.reset(options.refresh_interval());
        robot->refresh_thread_ = std::thread{&RobotClient::refresh_every, robot.get()}
    }


} catch (std::exception&) {
while (true) {
if (refresh_cv_.wait_for(lk, refresh_interval_) == std::cv_status::timeout) {
Copy link
Member

Choose a reason for hiding this comment

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

condvars can (in theory) have spurious wakeups (the reasons are somewhat historically [interesting] (https://stackoverflow.com/a/8594964)). Potentially, this could use wait_until to reenter the wait state should that happen. However, I'm not sure the complexity is warranted. Is there a risk to doing an early refresh in the event of a spurious wakeup?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

this one is interesting and relates to my answer about your other comments regarding the if and while conditions. spurious wakeups are the reason condvar code often needs an extra flag variable--if there's a wakeup we can tell if it's spurious or not by checking the value of bool no_i_really_meant_to_wake_you_up. all of the condition_variable::wait[_preposition] functions have an overload taking a predicate argument, and per cppreference (and, eg, libcxx) this is equivalent to while(!pred) wait(lk).

if we don't mind doing an extra refresh during a spurious wakeup, which I agree is probably harmless, it occurred to me that this whole function could just be

void RobotClient::refresh_every()
{
    std::unique_lock<std::mutex> lk{refresh_lock_}
    refresh_cv_.wait_for(lk, refresh_interval_, [this]{
        if (should_refresh_) refresh();
        return !should_refresh_;
    });
}

regarding the optional suggestion below though this would make me feel a bit weird about turning refresh_interval_ into an optional because I think that gets a little harder to reason about the validity of reading from refresh_interval_ or having to handle it being a nullopt

VIAM_SDK_LOG(warn) << "Refresh thread terminated with exception: " << e.what();
break;
}
} else if (should_refresh_ == false) {
Copy link
Member

Choose a reason for hiding this comment

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

Maybe can be part of the loop condition?

refresh();
} catch (const std::exception& e) {
VIAM_SDK_LOG(warn) << "Refresh thread terminated with exception: " << e.what();
break;
Copy link
Member

Choose a reason for hiding this comment

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

Can refresh fail for legit but transient reasons like network being down? If so, is it actually correct to permanently shut down the refresh loop?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

hmm good question, I was just copying the semantics from the previous implementation and adding a log statement. I imagine distinguishing types of errors could be done by catching GRPException separately and inspecting it

@@ -143,7 +143,11 @@ RobotClient::~RobotClient() {
}

void RobotClient::close() {
should_refresh_.store(false);
if (should_refresh_) {
Copy link
Member

Choose a reason for hiding this comment

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

I'll argue that this is one of those cases where even if it is safe in practice, it is still better to do the check under the lock. It'll be annoying if someday we stand up TSAN and it whines about a leak here, and this isn't a hot path, so trying to eliminate the lock doesn't buy much of anything.


} catch (std::exception&) {
break;
refresh_cv_.wait_for(lk, refresh_interval_, [this] {
Copy link
Member

Choose a reason for hiding this comment

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

I think this is going to terminate after one timeout, but tbh I always get this stuff wrong, so don't let me mislead you if you have thought it through and this actually does what is intended.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

you were right, classic case of a solution that is simple, elegant, and wrong 🙂

Copy link
Member

Choose a reason for hiding this comment

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

I'm generally skeptical of the predicate taking condition things because they are so easy to get wrong, and require too much thinking.

Here is how I think I would write this loop unrolled:

std::unique_lock<std::mutex> lk{refresh_lock_};
// Terminate if we ever see `should_refresh` as `false` while holding the lock
while (should_refresh_) {
    // Compute the absolute time on which the next refresh should happen
    const auto wake_time = std::chrono::steady_clock::now + refresh_interval_;
    // Loop until deadline is reached or `should_refresh_` becomes `false`
    while (should_refresh_) {
        const auto wait_result = refresh_cv.wait_until(lk, wake_time);
        if (wait_result == cv_status::timeout && should_refresh_) {
            // We hit the deadline: do a refresh
            try {
                refresh();
            } catch (...) { ... }
            // Break out of inner loop to compute next deadline
            break;
        } else {
            // If this was a spurious wake, then `should_refresh_` is still `true`, and
            // `wait_until` will be reinvoked with existing deadline. If this was not
            // a spurious wake, then we were notified, and both the inner and outer loop
            // will terminate.
        }
    }
}

But it is possible that the predicate version is more or less equivalent to that, in which case it should be fine.

@lia-viam lia-viam changed the title WIP: condition var refresh thread RSDK-10643: condition var refresh thread May 5, 2025
@lia-viam lia-viam requested a review from acmorrow May 5, 2025 14:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants