asyncrpc: make AsyncRPCOperation::cancel() virtual, so a running auto-op can be stopped
The base class said "Override this method if you can interrupt execution of main()", but cancel()
was not virtual. Every caller holds a std::shared_ptr<AsyncRPCOperation> -- the queue's map, the
wallet schedulers, z_consolidate -- so the overrides in the sweep, consolidation and autoshield ops,
written to move an EXECUTING operation to CANCELLED, never ran: the base version only cancels an
operation that has not started. In practice that meant a stop could not interrupt a running
automatic round; the node waited for it to finish every remaining transaction. Consolidation had
grown its own ShutdownRequested() checks as a workaround.
- cancel() is virtual, and the three overrides are marked override, so this cannot silently
regress: with the base non-virtual again they fail to compile.
- Only the queue closing at shutdown can cancel a running round. The schedulers return early
while a round is in flight (the sweep since its in-flight guard, consolidation and autoshield on
their running flags) and z_consolidate refuses while a consolidation runs, so they only ever
cancel an operation that has finished, which the overrides leave alone.
- A round cancelled part-way stays CANCELLED instead of being relabelled SUCCESS or FAILED by how
much of it got done, and logs "(status=cancelled)".
- The sweep checks isCancelled() || ShutdownRequested() before starting each address as well as
after each build, so a stop does not wait for another multi-second build to be discarded.
- Comments that described the old behaviour are corrected.
New gtest AsyncRPCCancel: each override is reached through a shared_ptr<AsyncRPCOperation> and
stops an EXECUTING op, leaves SUCCESS/FAILED alone and still cancels a READY one; an op without an
override still only cancels before it starts (z_sendmany and friends are unaffected). With the old
declarations, the three override tests fail. Regtest, same fixture, the node stopped while a sweep
round was building its first of four transactions: dev took 56.2 s to exit, building all four first;
this exits in 9-12 s ("Canceled. Stopping.", status=cancelled), and the wallet is intact on restart.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,7 @@ hush_gtest_SOURCES = \
|
||||
gtest/test_mnemonic_compat.cpp \
|
||||
gtest/test_stratum_jobid.cpp \
|
||||
gtest/test_sweep_note_selection.cpp \
|
||||
gtest/test_asyncrpc_cancel.cpp \
|
||||
gtest/test_wallet_notedata.cpp \
|
||||
gtest/test_net_closesocket.cpp \
|
||||
gtest/test_fd_defense.cpp \
|
||||
|
||||
@@ -60,8 +60,10 @@ public:
|
||||
// You must implement this method in your subclass.
|
||||
virtual void main();
|
||||
|
||||
// Override this method if you can interrupt execution of main() in your subclass.
|
||||
void cancel();
|
||||
// Override this method if you can interrupt execution of main() in your subclass. It must be virtual:
|
||||
// callers hold a std::shared_ptr<AsyncRPCOperation> (the queue's map, the wallet schedulers). It used
|
||||
// not to be, which left every subclass override dead and a running operation uncancellable.
|
||||
virtual void cancel();
|
||||
|
||||
// Getters and setters
|
||||
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// Copyright (c) 2016-2024 The Hush developers
|
||||
// Distributed under the GPLv3 software license, see the accompanying
|
||||
// file COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <memory>
|
||||
#include <utility>
|
||||
|
||||
#include "asyncrpcoperation.h"
|
||||
#include "wallet/asyncrpcoperation_autoshieldcoinbase.h"
|
||||
#include "wallet/asyncrpcoperation_saplingconsolidation.h"
|
||||
#include "wallet/asyncrpcoperation_sweep.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// Lets a test put an operation into any state, without running it.
|
||||
template <class Op>
|
||||
class Probe : public Op {
|
||||
public:
|
||||
template <class... Args>
|
||||
explicit Probe(Args&&... args) : Op(std::forward<Args>(args)...) {}
|
||||
void Set(OperationStatus status) { this->set_state(status); }
|
||||
};
|
||||
|
||||
// An operation that does not override cancel(): the base behaviour.
|
||||
class PlainOp : public AsyncRPCOperation {
|
||||
public:
|
||||
void main() override {}
|
||||
void Set(OperationStatus status) { set_state(status); }
|
||||
};
|
||||
|
||||
int S(OperationStatus status) { return static_cast<int>(status); }
|
||||
|
||||
// The queue's map and the wallet schedulers hold every operation as a shared_ptr<AsyncRPCOperation>, so
|
||||
// that is how cancel() is called here. Before cancel() was virtual, each of these overrides was dead.
|
||||
template <class P>
|
||||
void CheckOverride(std::shared_ptr<P> probe)
|
||||
{
|
||||
std::shared_ptr<AsyncRPCOperation> op = probe;
|
||||
|
||||
probe->Set(OperationStatus::EXECUTING);
|
||||
op->cancel();
|
||||
EXPECT_TRUE(op->isCancelled()) << "a running round can be stopped";
|
||||
|
||||
for (OperationStatus done : {OperationStatus::SUCCESS, OperationStatus::FAILED}) {
|
||||
probe->Set(done);
|
||||
op->cancel();
|
||||
EXPECT_EQ(S(done), S(op->getState())) << "a finished round is not relabelled as cancelled";
|
||||
}
|
||||
|
||||
probe->Set(OperationStatus::READY);
|
||||
op->cancel();
|
||||
EXPECT_TRUE(op->isCancelled()) << "a round that has not started is cancelled, as before";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
TEST(AsyncRPCCancel, TheSweepOverrideIsReachedThroughTheBasePointer) {
|
||||
CheckOverride(std::make_shared<Probe<AsyncRPCOperation_sweep>>(100));
|
||||
}
|
||||
|
||||
TEST(AsyncRPCCancel, TheConsolidationOverrideIsReachedThroughTheBasePointer) {
|
||||
CheckOverride(std::make_shared<Probe<AsyncRPCOperation_saplingconsolidation>>(100, SaplingConsolidationRequest()));
|
||||
}
|
||||
|
||||
TEST(AsyncRPCCancel, TheAutoshieldOverrideIsReachedThroughTheBasePointer) {
|
||||
CheckOverride(std::make_shared<Probe<AsyncRPCOperation_autoshieldcoinbase>>(100));
|
||||
}
|
||||
|
||||
TEST(AsyncRPCCancel, AnOperationWithoutAnOverrideOnlyCancelsBeforeItStarts) {
|
||||
auto plain = std::make_shared<PlainOp>();
|
||||
std::shared_ptr<AsyncRPCOperation> op = plain;
|
||||
|
||||
plain->Set(OperationStatus::EXECUTING);
|
||||
op->cancel();
|
||||
EXPECT_TRUE(op->isExecuting()) << "z_sendmany and friends are not interrupted mid-run";
|
||||
|
||||
plain->Set(OperationStatus::READY);
|
||||
op->cancel();
|
||||
EXPECT_TRUE(op->isCancelled());
|
||||
}
|
||||
@@ -82,7 +82,9 @@ void AsyncRPCOperation_autoshieldcoinbase::main() {
|
||||
}
|
||||
}
|
||||
|
||||
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
|
||||
// A round cancelled part-way (the queue at shutdown) stays CANCELLED rather than being relabelled.
|
||||
if (!isCancelled())
|
||||
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
|
||||
setResult();
|
||||
|
||||
LogPrintf("%s: autoshield operation finished (status=%s, txs=%d, shielded=%s)\n",
|
||||
@@ -475,11 +477,12 @@ void AsyncRPCOperation_autoshieldcoinbase::setResult() {
|
||||
}
|
||||
|
||||
void AsyncRPCOperation_autoshieldcoinbase::cancel() {
|
||||
// Cancelling is how the scheduler stops an in-flight round, so unlike the base
|
||||
// class this must be able to move an EXECUTING operation to CANCELLED. What it
|
||||
// must not do is overwrite a state that is already terminal: the scheduler
|
||||
// cancels the previous operation when it enqueues the next one, and that one may
|
||||
// have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
|
||||
// Lets the queue stop an executing round when it closes at shutdown, so unlike the
|
||||
// base class this must be able to move an EXECUTING operation to CANCELLED. The
|
||||
// scheduler never cancels a running round (it returns early while one is in flight);
|
||||
// it cancels the previous operation only when enqueueing the next, by which time
|
||||
// that one is terminal -- and a terminal state must not be overwritten, or a
|
||||
// SUCCEEDED result would be relabelled as cancelled.
|
||||
if (isSuccess() || isFailed() || isCancelled())
|
||||
return;
|
||||
set_state(OperationStatus::CANCELLED);
|
||||
|
||||
@@ -52,7 +52,7 @@ public:
|
||||
AsyncRPCOperation_autoshieldcoinbase& operator=(AsyncRPCOperation_autoshieldcoinbase&&) = delete;
|
||||
|
||||
virtual void main();
|
||||
virtual void cancel();
|
||||
virtual void cancel() override;
|
||||
virtual UniValue getStatus() const;
|
||||
|
||||
private:
|
||||
|
||||
@@ -245,14 +245,15 @@ void AsyncRPCOperation_saplingconsolidation::main() {
|
||||
|
||||
stop_execution_clock();
|
||||
|
||||
if (success) {
|
||||
set_state(OperationStatus::SUCCESS);
|
||||
} else {
|
||||
set_state(OperationStatus::FAILED);
|
||||
}
|
||||
// A round cancelled part-way (only the queue closing at shutdown cancels a running op) stays
|
||||
// CANCELLED rather than being relabelled by how much of it got done.
|
||||
if (!isCancelled())
|
||||
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
|
||||
|
||||
std::string s = strprintf("%s: Sapling Consolidation operation complete. (status=%s", getId(), getStateAsString());
|
||||
if (success) {
|
||||
if (isCancelled()) {
|
||||
s += ")\n";
|
||||
} else if (success) {
|
||||
s += strprintf(", success)\n");
|
||||
} else {
|
||||
s += strprintf(", error=%s)\n", getErrorMessage());
|
||||
@@ -447,8 +448,8 @@ bool AsyncRPCOperation_saplingconsolidation::main_impl() {
|
||||
};
|
||||
|
||||
for (const PlannedTx& planned : txs) {
|
||||
// The queue's cancel at shutdown never reaches an executing op (AsyncRPCOperation::cancel() is
|
||||
// not virtual), so look for the shutdown here, or a stop would wait for the whole round.
|
||||
// ShutdownRequested() too: the shutdown flag is set well before the queue is closed and this op
|
||||
// is cancelled, so checking it stops the round as soon as a stop is asked for.
|
||||
if (isCancelled() || ShutdownRequested()) {
|
||||
LogPrintf("%s: %s. Stopping.\n", opid, isCancelled() ? "Canceled" : "Shutting down");
|
||||
tally.error = isCancelled() ? "cancelled" : "shutting down";
|
||||
@@ -581,11 +582,12 @@ void AsyncRPCOperation_saplingconsolidation::setConsolidationResult(const Consol
|
||||
}
|
||||
|
||||
void AsyncRPCOperation_saplingconsolidation::cancel() {
|
||||
// Cancelling is how the scheduler stops an in-flight round, so unlike the base
|
||||
// class this must be able to move an EXECUTING operation to CANCELLED. What it
|
||||
// must not do is overwrite a state that is already terminal: the scheduler
|
||||
// cancels the previous operation when it enqueues the next one, and that one may
|
||||
// have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
|
||||
// Lets the queue stop an executing round when it closes at shutdown, so unlike the
|
||||
// base class this must be able to move an EXECUTING operation to CANCELLED. The
|
||||
// scheduler never cancels a running round (it returns early while one is in flight);
|
||||
// it cancels the previous operation only when enqueueing the next, by which time
|
||||
// that one is terminal -- and a terminal state must not be overwritten, or a
|
||||
// SUCCEEDED result would be relabelled as cancelled.
|
||||
if (isSuccess() || isFailed() || isCancelled())
|
||||
return;
|
||||
set_state(OperationStatus::CANCELLED);
|
||||
|
||||
@@ -121,7 +121,7 @@ public:
|
||||
|
||||
virtual void main();
|
||||
|
||||
virtual void cancel();
|
||||
virtual void cancel() override;
|
||||
|
||||
virtual UniValue getStatus() const;
|
||||
|
||||
|
||||
@@ -54,11 +54,10 @@ void AsyncRPCOperation_sweep::main() {
|
||||
|
||||
stop_execution_clock();
|
||||
|
||||
if (success) {
|
||||
set_state(OperationStatus::SUCCESS);
|
||||
} else {
|
||||
set_state(OperationStatus::FAILED);
|
||||
}
|
||||
// A round cancelled part-way (only the queue closing at shutdown cancels a running op) stays
|
||||
// CANCELLED rather than being relabelled by how much of it got done.
|
||||
if (!isCancelled())
|
||||
set_state(success ? OperationStatus::SUCCESS : OperationStatus::FAILED);
|
||||
|
||||
// Scheduler bookkeeping, done here so it runs on success AND failure AND
|
||||
// exception (main_impl's terminal code is skipped when it throws). Only the
|
||||
@@ -78,7 +77,9 @@ void AsyncRPCOperation_sweep::main() {
|
||||
}
|
||||
|
||||
std::string s = strprintf("%s: Sweep operation finished. (status=%s", getId(), getStateAsString());
|
||||
if (success) {
|
||||
if (isCancelled()) {
|
||||
s += ")\n";
|
||||
} else if (success) {
|
||||
s += strprintf(", success)\n");
|
||||
} else {
|
||||
s += strprintf(", error=%s)\n", getErrorMessage());
|
||||
@@ -271,6 +272,11 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
bool sweepComplete = true;
|
||||
|
||||
for (std::map<libzcash::SaplingPaymentAddress, std::vector<SaplingNoteEntry>>::iterator it = mapAddresses.begin(); it != mapAddresses.end(); it++) {
|
||||
// Stop before starting another address: building takes seconds, and a stop would only discard it.
|
||||
if (isCancelled() || ShutdownRequested()) {
|
||||
LogPrintf("%s: %s. Stopping.\n", getId(), isCancelled() ? "Canceled" : "Shutting down");
|
||||
break;
|
||||
}
|
||||
auto addr = (*it).first;
|
||||
auto saplingEntries = (*it).second;
|
||||
|
||||
@@ -385,8 +391,8 @@ bool AsyncRPCOperation_sweep::main_impl() {
|
||||
}
|
||||
CTransaction tx = maybe_tx.get();
|
||||
|
||||
if (isCancelled()) {
|
||||
LogPrintf("%s: Canceled. Stopping.\n", getId());
|
||||
if (isCancelled() || ShutdownRequested()) {
|
||||
LogPrintf("%s: %s. Stopping.\n", getId(), isCancelled() ? "Canceled" : "Shutting down");
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -447,11 +453,12 @@ void AsyncRPCOperation_sweep::setSweepResult(int numTxCreated, const CAmount& am
|
||||
}
|
||||
|
||||
void AsyncRPCOperation_sweep::cancel() {
|
||||
// Cancelling is how the scheduler stops an in-flight round, so unlike the base
|
||||
// class this must be able to move an EXECUTING operation to CANCELLED. What it
|
||||
// must not do is overwrite a state that is already terminal: the scheduler
|
||||
// cancels the previous operation when it enqueues the next one, and that one may
|
||||
// have already SUCCEEDED, whose result would otherwise be relabelled as cancelled.
|
||||
// Lets the queue stop an executing round when it closes at shutdown, so unlike the
|
||||
// base class this must be able to move an EXECUTING operation to CANCELLED. The
|
||||
// scheduler never cancels a running round (it returns early while one is in flight);
|
||||
// it cancels the previous operation only when enqueueing the next, by which time
|
||||
// that one is terminal -- and a terminal state must not be overwritten, or a
|
||||
// SUCCEEDED result would be relabelled as cancelled.
|
||||
if (isSuccess() || isFailed() || isCancelled())
|
||||
return;
|
||||
set_state(OperationStatus::CANCELLED);
|
||||
|
||||
@@ -64,7 +64,7 @@ public:
|
||||
|
||||
virtual void main();
|
||||
|
||||
virtual void cancel();
|
||||
virtual void cancel() override;
|
||||
|
||||
virtual UniValue getStatus() const;
|
||||
|
||||
|
||||
@@ -643,11 +643,11 @@ void CWallet::RunSaplingSweep(int blockHeight) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Self-guard: let an in-flight round finish. Re-dispatching on every block, as this used to, never
|
||||
// stopped the running op -- AsyncRPCOperation::cancel() is not virtual, so through the queue's base
|
||||
// pointer it only cancels an op that has not started -- it just queued a fresh round behind it,
|
||||
// which then repeated note selection over the whole wallet for nothing. (On a single async worker
|
||||
// a replacement could not get past a hung op anyway.)
|
||||
// Self-guard: let an in-flight round finish. Re-dispatching on every block, as this used to, cancels
|
||||
// the running op (now that AsyncRPCOperation::cancel() is virtual, the sweep's override can stop an
|
||||
// executing round), discarding the transaction it is building -- on a wallet where one build
|
||||
// outlasts a block, nothing would ever be swept. Before cancel() was virtual it merely queued a
|
||||
// redundant round behind the running one.
|
||||
if (fSweepInFlight) {
|
||||
LogPrintf("%s: sweep operation %s (enqueued at height %d) is still running at blockHeight=%d; "
|
||||
"not re-dispatching\n", __func__, saplingSweepOperationId, sweepDispatchHeight, blockHeight);
|
||||
|
||||
Reference in New Issue
Block a user