Skip to content

Parallelize Soroban pre-apply step. - #5402

Merged
dmkozh merged 1 commit into
stellar:masterfrom
dmkozh:par_pre_apply
Sep 16, 2026
Merged

dmkozh merged 1 commit into
stellar:masterfrom
dmkozh:par_pre_apply

Conversation

@dmkozh

@dmkozh dmkozh commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

While the current logic intertwines reads and writes, in fact it can be cleanly separated into a read-only validation step, and a sequential commit step that simply bumps the sequence numbers and removes pre-authorized tx signers. This is possible because that while the writes change the entries that take part in validation, none of these changes are relevant during the validation. Specifically, sequence number bump is only observable by a single transaction (the one that has the respective account as a source), and the pre-authorized tx signer by definition belongs to a single transaction. There is also a subtle caveat to the latter operation: it increases the available balance of the signer owner (or its sponsor), but since at the pre-apply time the fees have already been charged, we're only checking that the account available balance is non-negative, which is an invariant that must always hold in the current protocol.

The change is not protocol-gated because it's not a protocol change for the current protocol. It was technically a protocol change prior to p26 where we had a bug that actually did allow overcharging the fee bump source accounts and thus making their available balance to go negative. However, the bug has been fixed without the behavior ever triggering on-chain, and thus this replay-only behavior change should be non-observable.

This change significantly speeds up the pre-apply step. On the local high TPL benchmarks I'm getting 30-60ms improvement locally compared to the main branch version.

This PR also adds test coverage for the edge case pre-apply interactions that weren't covered well (or at all), such as pre-auth signer removal, tx invalidation due to sequence bumps etc. This also contains a randomized acceptance test that ensures that parallel pre-apply logic is deterministic across any number of worker threads.

Checklist

  • Reviewed the contributing document
  • Rebased on top of master (no merge commits)
  • Ran clang-format v8.0.0 (via make format or the Visual Studio extension)
  • Compiles
  • Ran all tests
  • If change impacts performance, include supporting evidence per the performance document

Copilot AI balanced review requested due to automatic review settings August 4, 2026 01:05
@dmkozh
dmkozh force-pushed the par_pre_apply branch 2 times, most recently from b7896a9 to be994a5 Compare August 4, 2026 01:07

Copilot AI 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.

Pull request overview

Parallelizes Soroban pre-apply validation while preserving serial ledger mutations.

Changes:

  • Splits pre-apply into parallel read-only and sequential write phases.
  • Adds a ledger view combining classic-phase changes with LCL state.
  • Adds concurrency and signer/sequence regression tests with updated baselines.

Reviewed changes

Copilot reviewed 18 out of 18 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
test-tx-meta-baseline-next/InvokeHostFunctionTests.json Updates next-protocol test baselines.
test-tx-meta-baseline-current/InvokeHostFunctionTests.json Updates current-protocol test baselines.
src/util/BatchExecutor.h Exposes preferred parallelism controls.
src/util/BatchExecutor.cpp Computes preferred worker count.
src/transactions/TransactionFrameBase.h Splits the pre-apply interface.
src/transactions/TransactionFrame.h Declares read/write pre-apply paths.
src/transactions/TransactionFrame.cpp Implements separated pre-apply processing.
src/transactions/test/TransactionTestFrame.h Adapts the test transaction interface.
src/transactions/test/TransactionTestFrame.cpp Delegates split pre-apply calls.
src/transactions/test/SorobanTxTestUtils.cpp Corrects footprint deduplication.
src/transactions/test/ParallelApplyTest.cpp Tests worker-count independence.
src/transactions/test/InvokeHostFunctionTests.cpp Adds pre-apply regression coverage.
src/transactions/ParallelApplyUtils.h Declares parallel pre-apply orchestration.
src/transactions/ParallelApplyUtils.cpp Runs parallel reads and serial writes.
src/transactions/FeeBumpTransactionFrame.h Splits fee-bump pre-apply APIs.
src/transactions/FeeBumpTransactionFrame.cpp Implements fee-bump pre-apply phases.
src/ledger/ImmutableLedgerView.h Defines the pre-apply ledger view.
src/ledger/ImmutableLedgerView.cpp Implements combined ledger lookups.
Suppressed comments (3)

src/transactions/ParallelApplyUtils.cpp:442

  • Cap the task count at the number of bundles. BatchExecutor::ensureWorkers creates and retains one worker per submitted task, so a small ledger on a many-core host currently starts dozens of workers whose ranges are empty, adding startup and wake-up overhead to the path this PR is optimizing.
    size_t taskCount = app.getBatchExecutor().preferredTaskCount();

src/transactions/ParallelApplyUtils.cpp:400

  • This rationale has the direction backwards: removing a signer decreases the owner's sub-entry count (and, when sponsored, the sponsor's sponsoring count), which can only increase available balance. State that monotonic effect explicitly because it is the reason deferring these writes cannot invalidate another transaction.
    // - The removal of one-time pre-authorized tx signers - this is also fine
    //   because any given transaction in a ledger is unique, and increasing the
    //   sub-entry count of a source/sponsor account is not relevant at that
    //   point, as the fees have already been successfully charged.

src/transactions/ParallelApplyUtils.cpp:391

  • Correct the typo “separatation” to “separation”.
    // This phase separatation hinges on the fact that the validation outcome

Comment thread src/ledger/ImmutableLedgerView.cpp Resolved
Comment thread src/transactions/ParallelApplyUtils.cpp Resolved
Comment thread src/util/BatchExecutor.cpp Resolved
@dmkozh
dmkozh force-pushed the par_pre_apply branch 2 times, most recently from 6f7c2f1 to 4cdc91b Compare August 4, 2026 18:18
@dmkozh
dmkozh force-pushed the par_pre_apply branch 2 times, most recently from d7c7629 to 02b730f Compare August 14, 2026 20:10
@dmkozh
dmkozh requested review from graydon and sisuresh August 14, 2026 20:49
Comment thread src/transactions/TransactionFrame.cpp Resolved
Copilot AI review requested due to automatic review settings September 9, 2026 23:21

Copilot AI 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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated 3 comments.

Suppressed comments (1)

src/util/BatchExecutor.cpp:226

  • Ceiling the range size does not reliably create numTasks ranges: for example, count=4, numTasks=3 creates only two tasks. This underutilizes available cores in the performance-sensitive path and contradicts the API contract. Distribute the remainder across exactly numTasks ranges instead.
    auto rangeSize = (count + numTasks - 1) / numTasks;
    std::vector<std::function<int()>> tasks;
    tasks.reserve(numTasks);
    for (size_t begin = 0; begin < count; begin += rangeSize)

Comment thread src/util/BatchExecutor.cpp Resolved
Comment thread src/transactions/ParallelApplyUtils.cpp Resolved
Comment thread src/util/BatchExecutor.h Resolved
Copilot AI review requested due to automatic review settings September 10, 2026 01:14

Copilot AI 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.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 3 comments.

Comment thread src/util/BatchExecutor.cpp Resolved
Copilot AI review requested due to automatic review settings September 10, 2026 16:57

Copilot AI 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.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 1 comment.

Suppressed comments (1)

src/util/BatchExecutor.cpp:223

  • This ceiling-division expression can overflow size_t. For example, count == SIZE_MAX and numTasks == 2 produces rangeSize == 0, so the following loop never advances; even with a safe quotient, begin + rangeSize also needs overflow protection. Compute the quotient/remainder without addition overflow and advance via a clamped end.
    auto rangeSize = (count + numTasks - 1) / numTasks;

Comment thread src/transactions/ParallelApplyUtils.cpp Resolved
Copilot AI review requested due to automatic review settings September 11, 2026 17:41

Copilot AI 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.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/transactions/FeeBumpTransactionFrame.cpp:122

  • The new parallel write path removes the fee-source pre-auth signer before delegating to the inner transaction, but the added Soroban tests only fee-bump transactions whose fee source has no pre-auth signer; existing one-time-signer coverage exercises the old sequential apply path. Please add a p23+ parallel test that installs the fee-bump hash as a signer on the fee source (including sponsorship if supported) and verifies its removal and metadata.
            LedgerTxn ltxTx(ltx);
            removeOneTimeSignerKeyFromFeeSource(ltxTx);
            meta.pushTxChangesBefore(ltxTx);
            ltxTx.commit();
        }
        mInnerTx->preParallelApplyWrite(app, ltx, meta, txResult);

Note

Copilot is running an experiment and ran this review at Lite.

SirTyson
SirTyson previously approved these changes Sep 15, 2026

@SirTyson SirTyson 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.

Overall LGTM. I am most familiar with the snapshot interface, it might be nice for someone with more experience in the tx subsystem to take a look as well, but I can't see any form of divergence for current protocol.

I still have a bit of a reservation regarding multi-threaded structs accessing the ltx object. I agree it's all correct, but I almost want some abstraction like ThreadSafeLtx with a limited set of const, thread safe map accessors, and some way of "deactivating" the parent ltx object such that we can ensure there are no races. That being said, we already have many, many layers of abstraction in the snapshot and state access interface, and we only use getNewestVersionBelowRoot, so maybe it's fine as is.

Copilot AI review requested due to automatic review settings September 15, 2026 20:51

Copilot AI 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.

Note

Copilot was unable to run its full agentic suite in this review.

Pull request overview

Copilot reviewed 19 out of 19 changed files in this pull request and generated 5 comments.

Comment thread src/ledger/ImmutableLedgerView.cpp Resolved
Comment thread src/ledger/ImmutableLedgerView.cpp Resolved
Comment thread src/util/BatchExecutor.cpp Resolved
Comment thread src/util/BatchExecutor.h Resolved
Comment thread src/util/test/BatchExecutorTests.cpp Resolved
Copilot AI review requested due to automatic review settings September 15, 2026 22:18

Copilot AI 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.

Pull request overview

Copilot reviewed 21 out of 21 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/transactions/ParallelApplyUtils.cpp:450

  • This introduces a new hot-path parallelization of ledger apply, but the PR only reports an informal local 30–60 ms improvement and does not include a comparison against latest master or a release. Please add reproducible performance evidence (at least the relevant execution-time comparison) before approval, as required by performance-eval/performance-eval.md:3-6.
    batchExecutor.executeBatchOverRanges(
        txBundles.size(), batchExecutor.preferredTaskCount(),
        [&](size_t begin, size_t end, size_t) {

Note

Copilot is running an experiment and ran this review at Lite.

SirTyson
SirTyson previously approved these changes Sep 15, 2026

@SirTyson SirTyson 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.

Thanks for the hadening around the LTX interface! Two small nits.

Comment thread src/transactions/ParallelApplyUtils.cpp Resolved
Comment thread src/ledger/ImmutableLedgerView.h Resolved

Copilot AI 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.

Pull request overview

Copilot reviewed 21 out of 21 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/transactions/ParallelApplyUtils.cpp:455

  • This change directly affects ledger replay/apply performance, but the PR currently provides only an informal local timing claim. Please add a reproducible comparison against master or a release, including the execution-time and resource-utilization measurements required by performance-eval/performance-eval.md:3-13, so regressions from the new worker scheduling and per-range ledger-view setup can be evaluated before merging.
    batchExecutor.executeBatchOverRanges(
        txBundles.size(), batchExecutor.preferredTaskCount(),
        [&](size_t begin, size_t end, size_t) {
            // NB: mLCLApplyView is not thread-safe, so we need to copy it into
            // a thread-local view.
            CheckValidLedgerViewWrapper ledgerView(
                std::make_unique<SorobanPreApplyLedgerView>(
                    header, getUpdatedEntry, mLCLApplyView));

Note

Copilot is running an experiment and ran this review at Lite.

Copilot AI review requested due to automatic review settings September 16, 2026 00:40

Copilot AI 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.

Pull request overview

Copilot reviewed 24 out of 24 changed files in this pull request and generated no new comments.

Suppressed comments (2)

src/util/BatchExecutor.cpp:223

  • executeBatchOverRanges calls runBatchImpl without taking the mBatchRunning guard used by executeBatch. Two concurrent range batches (or a range batch concurrent with executeBatch) can overwrite mRunTask, mWorkersRequested, and the completion counters while the first batch is still running, causing tasks to run against the wrong callback or hang. Add the same assertion/RAII reset guard before entering runBatchImpl so the documented single-batch invariant is enforced.
    auto rangeSize = (count + numTasks - 1) / numTasks;

src/util/BatchExecutor.cpp:227

  • rangeSize = ceil(count / numTasks) does not produce numTasks ranges: for example, count=17 and numTasks=16 creates only 9 ranges, leaving 7 workers idle. Since this is called with preferredTaskCount() to parallelize pre-apply validation, this loses substantial parallelism for batch sizes just above the worker count; split the remainder across exactly numTasks ranges (and add a boundary-case test).
    auto rangeSize = (count + numTasks - 1) / numTasks;
    std::vector<std::function<int()>> tasks;
    tasks.reserve(numTasks);
    for (size_t begin = 0; begin < count; begin += rangeSize)
    {

Note

Copilot is running an experiment and ran this review at Lite.

While the current logic intertwines reads and writes, in fact it can be cleanly separated into a read-only validation step, and a sequential commit step that simply bumps the sequence numbers and removes pre-authorized tx signers. This is possible because that while the writes change the entries that take part in validation, none of these changes are relevant during the validation. Specifically, sequence number bump is only observable by a single transaction (the one that has the respective account as a source), and the pre-authorized tx signer by definition belongs to a single transaction. There is also a subtle caveat to the latter operation: it increases the available balance of the signer owner (or its sponsor), but since at the pre-apply time the fees have already been charged, we're only checking that the account available balance is non-negative, which is an invariant that must always hold in the current protocol.

The change is not protocol-gated because it's not a protocol change for the *current* protocol. It was technically a protocol change prior to p26 where we had a bug that actually did allow overcharging the fee bump source accounts and thus making their available balance to go negative. However, the bug has been fixed without the behavior ever triggering on-chain, and thus this replay-only behavior change should be non-observable.

This change significantly speeds up the pre-apply step. On the local high TPL benchmarks I'm getting 30-60ms improvement locally compared to the main branch version.
Copilot AI review requested due to automatic review settings September 16, 2026 01:49

Copilot AI 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.

Pull request overview

Copilot reviewed 23 out of 24 changed files in this pull request and generated no new comments.

Suppressed comments (1)

src/transactions/ParallelApplyUtils.cpp:449

  • This changes a hot ledger-apply path, but the PR description only reports an informal local 30–60 ms improvement. The repository performance requirements call for a comparison against latest master or a release with the relevant resource metrics; please add reproducible benchmark setup and results, including regression checks, before relying on this optimization.
    batchExecutor.executeBatchOverRanges(
        txBundles.size(), batchExecutor.preferredTaskCount(),

Note

Copilot is running an experiment and ran this review at Lite.

@dmkozh
dmkozh enabled auto-merge September 16, 2026 18:14
@dmkozh
dmkozh added this pull request to the merge queue Sep 16, 2026
Merged via the queue into stellar:master with commit 6ede7be Sep 16, 2026
55 of 56 checks passed
@dmkozh
dmkozh deleted the par_pre_apply branch September 16, 2026 19:11
sisuresh added a commit to sisuresh/stellar-core that referenced this pull request Sep 18, 2026
Master added six [tx] tests that close ledgers (stellar#5420) and fixed the test
footprint deduplication helper (stellar#5402), which had been placing read-only
keys in the read-write footprint. Both tiers gain 6 leaves and 138 rewritten
InvokeHostFunctionTests vectors whose transactions now carry the corrected
footprints and fees.

Claude-Session: https://claude.ai/code/session_01Rq9SZEScpZhaDqJpqjXu6b
sisuresh added a commit to sisuresh/stellar-core that referenced this pull request Sep 22, 2026
Master added six [tx] tests that close ledgers (stellar#5420) and fixed the test
footprint deduplication helper (stellar#5402), which had been placing read-only
keys in the read-write footprint. Both tiers gain 6 leaves and 138 rewritten
InvokeHostFunctionTests vectors whose transactions now carry the corrected
footprints and fees.

Claude-Session: https://claude.ai/code/session_01Rq9SZEScpZhaDqJpqjXu6b
SirTyson added a commit to SirTyson/stellar-core that referenced this pull request Nov 9, 2026
Brings overlay-v2-shared up to date with master. The previous master
merge (b90d48e, stellar#5428) was recorded with master's tip 100cc38 missing
from its parents, so this merge used 100cc38 as its base (temporary
graft of b90d48e, removed afterwards).

Notable master changes brought in:
- Protocol 30: CURRENT_LEDGER_PROTOCOL_VERSION follows
  MAX_SUPPORTED_PROTOCOL_VERSION; CAP-0084 and CAP-0087 ungated, p29 and
  p30 Soroban hosts (stellar#5472, stellar#5478, stellar#5484, stellar#5483).
- Millisecond-resolution close times at protocol 30 (stellar#5423):
  ConsensusTime/ApplyTime types, STELLAR_VALUE_SIGNED_MS and
  STELLAR_VALUE_EMPTY_TX_SET_MS.
- Tx set validity hardening (stellar#5481), lower max message size in protocol
  29 (stellar#733), sub-second ledger edge-case fixes.
- Simplified ledger view hierarchy (stellar#5461); the overlay-only-mode
  sequence number skip now lives in TransactionFrame::checkValid.
- Banned accounts deprecated (CAP-0077 is active).
- Apply-path performance work (stellar#5402, stellar#5411, stellar#5414, stellar#5415, stellar#5418, stellar#5421,
  stellar#5436, stellar#5286), apply-load tx set construction mode (stellar#5448), --check-lcm
  (stellar#5435), v29.0.0 release merge.

Conflict resolution:
- Files overlay-v2-shared deleted and master modified (the C++ overlay,
  TransactionQueue, TransactionQueueTests, UpgradesTests, private/Horizon/RPC
  workflows): kept deleted. Master's changes to them are C++ overlay
  peer/flow-control logic, tx queue admission and tests for those.
- Herder: kept the Rust-overlay submission path (recvTransaction returns
  TxSubmitStatus) and dropped the deprecated `force` parameter as master did.
  triggerNextLedger keeps the prepared/built tx set path from the Rust
  mempool, now with ConsensusTime close times and master's apply-time
  close-time offset. The early tx set preparation path (prepareTxSet,
  buildTxSet, setupTriggerNextLedger) takes ConsensusTime. Kept master's
  mNominatedTxSetOverride test hook (applied before the tx set is cached in
  the Rust overlay) and the herder.txset.build timer (now timing
  buildTxSet). Dropped the banned-accounts setup and tx queue maintenance.
- AppConnector: dropped both ov2's maybeUpdateImmutableLedgerView and
  master's C++-overlay getOverlayThreadSnapshot.
- LoadGenerator: master's CachedTestAccountPtr with ov2's TxSubmitStatus.
- Tests: kept ov2's removal of tests that need the C++ overlay, standalone
  mode or the tx queue (standalone, manualclose, flooding, tx queue limits,
  far-future slot cleanup, herderExternalizesValuesWithProtocol, MAX_SAC_TPS,
  custom token, soroswap and noisy binary search apply-load tests). Added
  master's ms close time HerderTests and the non-canonical empty tx set test
  on ov2's Rust-overlay topologies. The tx set size test checks against
  overlay-v2's own tx set allowance. The sub-second
  getUpperBoundCloseTimeOffset test checks the offset directly, since there
  is no C++ tx queue admission. Tests that used CheckValidLedgerViewWrapper
  now use getLCLView().
- Cargo.lock: master's lockfile plus the overlay crate's packages,
  regenerated by cargo; semver-compatible duplicates take the newer
  version.
- Build: Makefile.am keeps the Rust overlay rules and adds tracy
  import-chrome; ci-build.sh keeps ASAN off and takes master's -g1.
- Needed to compile: PendingEnvelopes.cpp includes LedgerManager.h
  (master got it through the C++ OverlayManager.h); ov2's early-nomination
  and checkpoint-slot tests use ConsensusTime/ApplyTimeOffset; OverlayIPC
  tests take ledger views from the LedgerManager.
@SirTyson SirTyson mentioned this pull request Nov 9, 2026
5 of 6 tasks
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.

4 participants