Skip to content

Commit b241f33

Browse files
authored
perf(vm): improve parallel precompile timeout handling (#7026)
* fix(vm): bound parallel precompile waits and clean up tasks Collect parallel precompile results against the remaining VM deadline and cancel unfinished tasks on timeout, interruption, and failed submission. Preserve the existing timeout policies for BatchValidateSign and VerifyTransferProof, including debug, solidity, and pre-energy-adjustment execution. Add regression coverage for delayed result publication, interruption, worker failure, and cancellation. * fix(vm): share parallel deadline and cover VM timeout compatibility Capture the invocation deadline once for the latch wait and result reads, and cover terminal precompile calls through the VM, actuator, and runtime across CPU enforcement modes.
1 parent ce0cd24 commit b241f33

3 files changed

Lines changed: 1020 additions & 54 deletions

File tree

‎actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java‎

Lines changed: 171 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,13 @@
3030
import java.util.HashSet;
3131
import java.util.List;
3232
import java.util.concurrent.Callable;
33+
import java.util.concurrent.CancellationException;
3334
import java.util.concurrent.CountDownLatch;
3435
import java.util.concurrent.ExecutionException;
3536
import java.util.concurrent.ExecutorService;
3637
import java.util.concurrent.Future;
3738
import java.util.concurrent.TimeUnit;
39+
import java.util.concurrent.TimeoutException;
3840
import lombok.AllArgsConstructor;
3941
import lombok.Getter;
4042
import lombok.Setter;
@@ -481,14 +483,121 @@ public void setResult(ProgramResult result) {
481483
}
482484

483485
protected long getCPUTimeLeftInNanoSecond() {
484-
long left = getVmShouldEndInUs() * VMConstant.ONE_THOUSAND - System.nanoTime();
486+
return getCPUTimeLeftInNanoSecond(getVmShouldEndInUs());
487+
}
488+
489+
private long getCPUTimeLeftInNanoSecond(long deadlineUs) {
490+
long left = deadlineUs * VMConstant.ONE_THOUSAND - System.nanoTime();
485491
if (left <= 0) {
486492
throw Program.Exception.notEnoughTime("call");
487493
} else {
488494
return left;
489495
}
490496
}
491497

498+
/**
499+
* Returns whether to collect results under the precompile's historical timeout policy.
500+
* DROP rejects any timed-out wait. MATCH_CPU_CHECK still accepts one when
501+
* {@link #allowTimedOutResult(long)} is true. A budget exhausted before waiting is
502+
* rejected either way. Cancellation belongs to {@link #collectParallel}.
503+
*/
504+
boolean awaitParallel(CountDownLatch latch, ParallelTimeout timeout)
505+
throws InterruptedException {
506+
return awaitParallel(latch, timeout, getVmShouldEndInUs());
507+
}
508+
509+
private boolean awaitParallel(CountDownLatch latch, ParallelTimeout timeout, long deadlineUs)
510+
throws InterruptedException {
511+
boolean withNoTimeout;
512+
try {
513+
withNoTimeout = latch.await(getCPUTimeLeftInNanoSecond(deadlineUs), TimeUnit.NANOSECONDS);
514+
} catch (OutOfTimeException expired) {
515+
// Budget was already gone, so the historical path does not read results.
516+
return false;
517+
} catch (InterruptedException interrupted) {
518+
Thread.currentThread().interrupt();
519+
throw interrupted;
520+
}
521+
return withNoTimeout
522+
|| (timeout == ParallelTimeout.MATCH_CPU_CHECK && allowTimedOutResult(deadlineUs));
523+
}
524+
525+
/**
526+
* Returns null on timeout or cancellation; propagates interruption and worker failures.
527+
* Capture the invocation deadline once for the latch wait and all result reads.
528+
* The latch opens before FutureTask publishes its result, so a bounded read uses the
529+
* same instant as {@link Program#checkCPUTimeLimit}. Values are copied into the
530+
* returned list before {@code finally} runs. Cancel is a no-op on a completed future
531+
* and does not discard those values.
532+
*/
533+
<T> List<T> collectParallel(CountDownLatch latch, List<? extends Future<T>> futures,
534+
ParallelTimeout timeout) throws InterruptedException, ExecutionException {
535+
final long deadlineUs = getVmShouldEndInUs();
536+
try {
537+
if (!awaitParallel(latch, timeout, deadlineUs)) {
538+
return null;
539+
}
540+
List<T> results = new ArrayList<>(futures.size());
541+
for (Future<T> future : futures) {
542+
results.add(readFuture(future, deadlineUs));
543+
}
544+
return results;
545+
} catch (TimeoutException | CancellationException ignored) {
546+
return null;
547+
} catch (InterruptedException interrupted) {
548+
Thread.currentThread().interrupt();
549+
throw interrupted;
550+
} finally {
551+
cancelAll(futures);
552+
}
553+
}
554+
555+
private <T> T readFuture(Future<T> future, long deadlineUs)
556+
throws InterruptedException, ExecutionException, TimeoutException {
557+
if (!boundsCollection()) {
558+
return future.get();
559+
}
560+
// CPU checks reject only when floor(nowNs / 1000) is greater than deadlineUs.
561+
long remainNs = (deadlineUs + 1) * VMConstant.ONE_THOUSAND - System.nanoTime();
562+
if (remainNs <= 0) {
563+
throw new TimeoutException();
564+
}
565+
return future.get(remainNs, TimeUnit.NANOSECONDS);
566+
}
567+
568+
/** Debug, solidity, and pre-energy-adjustment nodes keep the historical untimed read. */
569+
private static boolean boundsCollection() {
570+
CommonParameter parameter = CommonParameter.getInstance();
571+
if (parameter.isDebug() || parameter.isSolidityNode()) {
572+
return false;
573+
}
574+
return VMConfig.allowEnergyAdjustment();
575+
}
576+
577+
/** Completed futures are unaffected; cancellation of running work is best effort. */
578+
static void cancelAll(List<? extends Future<?>> futures) {
579+
for (Future<?> future : futures) {
580+
future.cancel(true);
581+
}
582+
}
583+
584+
/**
585+
* A timed-out latch may still be read when the VM will not turn this call into
586+
* an out-of-time transaction. Debug and solidity nodes skip
587+
* {@link Program#checkCPUTimeLimit}. Without energy adjustment there is no
588+
* end-of-transaction check, so a last opcode can still succeed. Otherwise the
589+
* same microsecond boundary as that opcode check applies.
590+
*/
591+
private boolean allowTimedOutResult(long deadlineUs) {
592+
return !boundsCollection()
593+
|| System.nanoTime() / VMConstant.ONE_THOUSAND <= deadlineUs;
594+
}
595+
596+
enum ParallelTimeout {
597+
DROP,
598+
MATCH_CPU_CHECK
599+
}
600+
492601
protected byte[] dataOne() {
493602
byte[] ret = new byte[WORD_SIZE];
494603
ret[31] = 1;
@@ -1206,26 +1315,27 @@ private Pair<Boolean, byte[]> doExecute(byte[] data)
12061315
// add check
12071316
CountDownLatch countDownLatch = new CountDownLatch(cnt);
12081317
List<Future<RecoverAddrResult>> futures = new ArrayList<>(cnt);
1209-
1210-
for (int i = 0; i < cnt; i++) {
1211-
Future<RecoverAddrResult> future = workers
1212-
.submit(new RecoverAddrTask(countDownLatch, hash, signatures[i], i));
1213-
futures.add(future);
1214-
}
1215-
boolean withNoTimeout = countDownLatch
1216-
.await(getCPUTimeLeftInNanoSecond(), TimeUnit.NANOSECONDS);
1217-
1218-
if (!withNoTimeout) {
1219-
logger.info("BatchValidateSign timeout");
1220-
throw Program.Exception.notEnoughTime("call BatchValidateSign precompile method");
1221-
}
1222-
1223-
for (Future<RecoverAddrResult> future : futures) {
1224-
RecoverAddrResult result = future.get();
1225-
int index = result.nonce;
1226-
if (DataWord.equalAddressByteArray(result.addr, addresses[index])) {
1227-
res[index] = 1;
1318+
try {
1319+
for (int i = 0; i < cnt; i++) {
1320+
Future<RecoverAddrResult> future = workers
1321+
.submit(new RecoverAddrTask(countDownLatch, hash, signatures[i], i));
1322+
futures.add(future);
1323+
}
1324+
List<RecoverAddrResult> results = collectParallel(countDownLatch, futures,
1325+
ParallelTimeout.DROP);
1326+
if (results == null) {
1327+
logger.info("BatchValidateSign timeout");
1328+
throw Program.Exception.notEnoughTime("call BatchValidateSign precompile method");
1329+
}
1330+
for (RecoverAddrResult result : results) {
1331+
int index = result.nonce;
1332+
if (DataWord.equalAddressByteArray(result.addr, addresses[index])) {
1333+
res[index] = 1;
1334+
}
12281335
}
1336+
} finally {
1337+
// Also covers failure partway through submission.
1338+
cancelAll(futures);
12291339
}
12301340
}
12311341
return Pair.of(true, res);
@@ -1580,42 +1690,49 @@ public Pair<Boolean, byte[]> execute(byte[] data) {
15801690
workers = workersInNonConstantCall;
15811691
}
15821692

1583-
// submit check spend task
1584-
for (int i = 0; i < spendCount; i++) {
1585-
Future<Boolean> futureCheckSpend = workers
1586-
.submit(new SaplingCheckSpendTask(countDownLatch, spendCv[i], anchor[i],
1587-
nullifier[i], rk[i], spendProof[i], spendAuthSig[i], signHash));
1588-
futures.add(futureCheckSpend);
1589-
}
1590-
//submit check output task
1591-
for (int i = 0; i < receiveCount; i++) {
1592-
Future<Boolean> futureCheckOutput = workers
1593-
.submit(new SaplingCheckOutputTask(countDownLatch, receiveCv[i], receiveCm[i],
1594-
receiveEpk[i], receiveProof[i]));
1595-
futures.add(futureCheckOutput);
1596-
}
1597-
// submit check binding signature
1598-
Future<Boolean> futureCheckBindingSig = workers
1599-
.submit(new SaplingCheckBingdingSig(countDownLatch, value, bindingSig,
1600-
signHash, spendCvs, spendCount * 32, receiveCvs, receiveCount * 32));
1601-
futures.add(futureCheckBindingSig);
1602-
1603-
boolean withNoTimeout = countDownLatch.await(getCPUTimeLeftInNanoSecond(),
1604-
TimeUnit.NANOSECONDS);
1605-
boolean checkResult = true;
1606-
for (Future<Boolean> future : futures) {
1607-
boolean eachTaskResult = future.get();
1608-
checkResult = checkResult && eachTaskResult;
1609-
}
1610-
if (checkResult) {
1611-
return insertLeaves(frontier, leafCount, receiveCm);
1612-
} else {
1613-
return Pair.of(true, DataWord.ZERO().getData());
1693+
try {
1694+
// submit check spend task
1695+
for (int i = 0; i < spendCount; i++) {
1696+
Future<Boolean> futureCheckSpend = workers
1697+
.submit(new SaplingCheckSpendTask(countDownLatch, spendCv[i], anchor[i],
1698+
nullifier[i], rk[i], spendProof[i], spendAuthSig[i], signHash));
1699+
futures.add(futureCheckSpend);
1700+
}
1701+
//submit check output task
1702+
for (int i = 0; i < receiveCount; i++) {
1703+
Future<Boolean> futureCheckOutput = workers
1704+
.submit(new SaplingCheckOutputTask(countDownLatch, receiveCv[i], receiveCm[i],
1705+
receiveEpk[i], receiveProof[i]));
1706+
futures.add(futureCheckOutput);
1707+
}
1708+
// submit check binding signature
1709+
Future<Boolean> futureCheckBindingSig = workers
1710+
.submit(new SaplingCheckBingdingSig(countDownLatch, value, bindingSig,
1711+
signHash, spendCvs, spendCount * 32, receiveCvs, receiveCount * 32));
1712+
futures.add(futureCheckBindingSig);
1713+
1714+
List<Boolean> results = collectParallel(countDownLatch, futures,
1715+
ParallelTimeout.MATCH_CPU_CHECK);
1716+
if (results == null) {
1717+
return Pair.of(true, DataWord.ZERO().getData());
1718+
}
1719+
boolean checkResult = true;
1720+
for (Boolean eachTaskResult : results) {
1721+
checkResult = checkResult && eachTaskResult;
1722+
}
1723+
if (checkResult) {
1724+
return insertLeaves(frontier, leafCount, receiveCm);
1725+
} else {
1726+
return Pair.of(true, DataWord.ZERO().getData());
1727+
}
1728+
} finally {
1729+
// Also covers failure partway through submission.
1730+
cancelAll(futures);
16141731
}
1615-
} catch (InterruptedException e) {
1616-
Thread.currentThread().interrupt();
1617-
logger.info("VerifyTransferProof exception: " + e.getMessage());
16181732
} catch (Throwable any) {
1733+
if (any instanceof InterruptedException) {
1734+
Thread.currentThread().interrupt();
1735+
}
16191736
String errorMsg = any.getMessage();
16201737
if (errorMsg == null && any.getCause() != null) {
16211738
errorMsg = any.getCause().getMessage();

0 commit comments

Comments
 (0)