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:
2026-11-20 19:05:53 -06:00
co-authored by Claude Opus 5.5
parent b0e0d211d2
commit 2ff5c5d541
10 changed files with 139 additions and 42 deletions
@@ -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;
+20 -13
View File
@@ -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);
+1 -1
View File
@@ -64,7 +64,7 @@ public:
virtual void main();
virtual void cancel();
virtual void cancel() override;
virtual UniValue getStatus() const;
+5 -5
View File
@@ -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);