Skip to content

Commit 87201aa

Browse files
authored
Network/Scheduling Improvements (stellar#5450)
# Description This PR contains a collection of implementation specific fixes and optimizations. There aren't really any design or logical changes (with the exception of early tx set preparation), but just a bunch of cleanups and optimizations at the scheduling and networking stack layer. I think these are all cheap, uncontroversial wins that remove some bottlenecks that might affect future larger experiments. Each change has it's own commit: - `f3dcf1357` Fixes a loadgen bug, were we'd always submit a TX to our mempool twice. - `c87b8750b` Enables concurrent TX set emission. Previously, while the underlying transport layer was parallel, the command dispatcher blocked on completion of some workloads, like tx sets. This means the leader had a de-facto serial scheduling conflict. This commit removes a bunch of unnecessary blocking at the command dispatch level. It also has a few other scheduling optimizations, like separating fetch request from the actual response write in the scheduler. - `f85d70def` Prepare tx sets in advance. This is the only logical change. TX set preparation takes a long time for the leader. However, if we finish a ledger early, the leader just waits idle until the next ledger trigger, then starts construction. This starts construction early, such that the leader node starts preparing a tx set immediately after closing the last ledger. We also extend this to the 2nd eligible leader, where they also prepare a tx set in advance so we don't stall further on nomination time out. - `368fa9044` Stream priorities. This implements stream priorities, such the SCP messages are highest priority, TX Sets next, then transaction flooding at lowest priority. This is all done via QUIC native capabilities. We also move some of the message types previously in the TX Set stream into the SCP stream. Specifically, the tx set fetching (and in the future, DONT_HAVE messages) all get assigned in the high priority SCP stream, where the actual tx set payload comes through the TX set stream. Basically, any small message related to consensus (SCP messages and "control" messages related to tx set fetching) are highest priority in SCP stream. - `4db17d26f` UDP buffer settings. This changes a few low level UDP settings. During load, we actually have a lot of dropped packets, so I (claude) tinkered with the network settings. This made a surprisingly large difference. - `842e4e690` Only deliver TX sets to core on request. This change makes is such that the rust overlay subprocess will cache incoming tx sets and only give them to core when requested. TX set serialization across C++ and rust is expensive, and the issue is that rust would sent multiple copies of the same TX set to C++ before C++ told rust that it had got and processed the tx set. This removes this duplication so we process a given TX set just once. - `ff620f2fe` Reduce tx set copies. We maintain less redundant copies and allocations when a leader is transmitting TX sets. - `1a0e5fa80` Fixes race conditions in the tx queue, where sometimes we wouldn't properly remove externalized TXs. These changes made a significant impact on top line performance. I was mostly concerned with benchmarking the phase 1 SAC goals (3k SAC TPS, 10 orgs, 2s block). We are still quite far from this goal in overlay-v2-shared, so I ran latency tests at 1k TPS and 2k TPS (3k TPS just fails at any block time). This was all with 200 ms simulated apply. ## 1000 TPS | Metric | Original overlay-v2-shared |Changes | |---|---:|---:| | Median block interval | 2.143 s | 1.995 s | | p99 block interval | 4.244 s | 2.189 s | | Maximum block interval | 4.399 s | 2.889 s | | Harness verdict | **FAIL** | **PASS** | ## 2000 TPS | Metric | Original overlay-v2-shared |Changes | |---|---:|---:| | Median block interval | 4.735 s | 3.803 s | | p99 block interval | 8.131 s | 5.420 s | | Maximum block interval | 8.117 s | 5.930 s | | Harness verdict | **FAIL** | **FAIL** | These changes did have an impact on median latency, but most importantly, we are much more stable under load with more bounded extremes. Note that the diff is large because I had to self vendor a dependency. The low-level QUIC features aren't configurable based on the wrapper that libp2p exposes. It's unfortunate, QUIC supports the features, the libraries that libp2p uses under the hood support the features, but libp2p itself doesn't pass the args forward. The hack is to self-vendor a patched libp2p. Not a great prod solution, but I don't really care for this feature branch, and the features made a very meaningful impact. # Checklist - [x] Reviewed the [contributing](https://github.com/stellar/stellar-core/blob/master/CONTRIBUTING.md#opening-a-pull-request) document - [x] Rebased on top of master (no merge commits) - [x] Ran `clang-format` v8.0.0 (via `make format` or the Visual Studio extension) - [x] Compiles - [x] Ran all tests - [ ] If change impacts performance, include supporting evidence per the [performance document](https://github.com/stellar/stellar-core/blob/master/performance-eval/performance-eval.md)
2 parents b90d48e + d4e11c1 commit 87201aa

151 files changed

Lines changed: 30626 additions & 1010 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.dockerignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,5 @@ lib/libmedida/test/
105105
**/*.vcxproj.user
106106
**/.vs
107107

108+
# These generated protobuf bindings are shipped source in the vendored crate.
109+
!overlay/vendor/libp2p-core/src/generated/

‎.github/workflows/rpc.yml‎

Lines changed: 0 additions & 19 deletions
This file was deleted.

‎Cargo.lock‎

Lines changed: 1 addition & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
11
[workspace]
22
resolver = "2"
33
members = ["src/rust", "overlay"]
4-
exclude = ["overlay-stub"]
4+
exclude = ["overlay-stub", "overlay/vendor/*"]
5+
6+
# Preserve QUIC stream priority through libp2p's stream wrappers. These are the
7+
# already-pinned releases with a small API bridge; see overlay/vendor/README.md.
8+
[patch.crates-io]
9+
libp2p-core = { path = "overlay/vendor/libp2p-core" }
10+
libp2p-swarm = { path = "overlay/vendor/libp2p-swarm" }
11+
libp2p-quic = { path = "overlay/vendor/libp2p-quic" }
12+
multistream-select = { path = "overlay/vendor/multistream-select" }
513

614
[profile.release]
715
codegen-units = 1

‎Makefile.am‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,9 @@ RUST_PROFILE_DIR=release
8282
endif
8383

8484
RUST_OVERLAY_BINARY=$(RUST_OVERLAY_TARGET)/$(RUST_PROFILE_DIR)/stellar-overlay
85+
RUST_OVERLAY_VENDOR_FILES=$(shell find $(RUST_OVERLAY_DIR)/vendor -type f)
8586

86-
$(RUST_OVERLAY_BINARY): $(wildcard $(RUST_OVERLAY_DIR)/src/*.rs) $(wildcard $(RUST_OVERLAY_DIR)/src/**/*.rs) $(RUST_OVERLAY_DIR)/Cargo.toml
87+
$(RUST_OVERLAY_BINARY): $(wildcard $(RUST_OVERLAY_DIR)/src/*.rs) $(wildcard $(RUST_OVERLAY_DIR)/src/**/*.rs) $(RUST_OVERLAY_DIR)/Cargo.toml $(top_srcdir)/Cargo.toml $(top_srcdir)/Cargo.lock $(RUST_OVERLAY_VENDOR_FILES)
8788
@echo "Building Rust overlay ($(RUST_BUILD_PROFILE))..."
8889
cd $(RUST_OVERLAY_DIR) && $(CARGO) build $(RUST_PROFILE_FLAG)
8990

@@ -107,7 +108,7 @@ check-local: check-rust
107108
endif # USE_RUST_OVERLAY
108109

109110
EXTRA_DIST = stellar-core.supp test/testnet/multitail.conf \
110-
test/testnet/run-test.sh README.md make-mks
111+
test/testnet/run-test.sh README.md make-mks overlay/vendor
111112

112113
@VALGRIND_CHECK_RULES@
113114
VALGRIND_FLAGS = --num-callers=30 --trace-children=yes \

‎docs/RUST_OVERLAY_DESIGN.md‎

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,15 @@ dedicated doc under [`docs/rust-overlay/`](rust-overlay/):
5151
│ ┌───────────────────────────────────▼──────────────────────────┐│
5252
│ │ Main event loop ││
5353
│ │ • Reads IPC messages from Core ││
54-
│ │ • Consumes libp2p events (SCP / TxSet / peer / TX) ││
54+
│ │ • Consumes libp2p events (SCP / TxSet / peer) ││
5555
│ │ • Drives reconnect timer ││
5656
│ └──────────┬──────────────────────────────────┬────────────────┘│
5757
│ │ │ │
5858
│ ┌──────────▼──────────┐ ┌────────────▼───────────────┐ │
5959
│ │ Mempool + flood │ │ libp2p Swarm (QUIC) │ │
6060
│ │ (integrated.rs, │ │ │ │
6161
│ │ flood/) │ │ Behaviours: │ │
62-
│ │ │ │ • libp2p-stream (3 protos)│ │
62+
│ │ │ │ • libp2p-stream (routes) │ │
6363
│ │ • Fee-ordered pool │ │ • Identify (informational)│ │
6464
│ │ • INV batching │ │ │ │
6565
│ │ • GETDATA tracking │ │ Transport: QUIC over UDP │ │
@@ -69,7 +69,7 @@ dedicated doc under [`docs/rust-overlay/`](rust-overlay/):
6969
│ ┌───────────────┼───────────────┐ │
7070
│ ▼ ▼ ▼ │
7171
│ [Peer 1] [Peer 2] [Peer N] │
72-
│ SCP stream SCP stream SCP stream │
72+
│ Ctl stream Ctl stream Ctl stream │
7373
│ TX stream TX stream TX stream │
7474
│ TxSet stream TxSet stream TxSet str. │
7575
└──────────────────────────────────────────────────────────────────┘
@@ -80,11 +80,13 @@ dedicated doc under [`docs/rust-overlay/`](rust-overlay/):
8080
- **Transport**: QUIC over UDP, via libp2p. TLS 1.3, 0-RTT reconnects,
8181
per-stream flow control. Listen port = `peer_port + 1000`. See
8282
[transport.md](rust-overlay/transport.md).
83-
- **Stream independence**: SCP, TX, and TxSet each get their own libp2p
84-
stream (`/stellar/scp/1.0.0`, `/stellar/tx/1.0.0`,
85-
`/stellar/txset/1.0.0`). A multi-MB TxSet write cannot stall a
86-
500-byte SCP envelope. This is the single biggest design win over the
87-
legacy single-TCP-stream overlay.
83+
- **Stream routing and priority**: control traffic (SCP and tx-set requests)
84+
uses `/stellar/control/1.0.0` at highest send priority; tx-set responses use
85+
`/stellar/txset/1.0.0` next; TX flooding uses `/stellar/tx/1.0.0` last.
86+
Legacy peers remain supported. Writes run outside the dispatcher, with
87+
bounded bulk-send admission. Streams still share bandwidth and connection
88+
flow control; priority is not a bandwidth reservation. See
89+
[transport.md](rust-overlay/transport.md).
8890
- **Peer membership is Core-driven**. There is no peer-discovery
8991
protocol — no Kademlia, no peer exchange, no gossip. The overlay
9092
connects to addresses Core sends via `SetPeerConfig` and accepts any
@@ -100,19 +102,21 @@ dedicated doc under [`docs/rust-overlay/`](rust-overlay/):
100102
- **Mempool lives in the overlay**. Fee-ordered, capacity 100,000,
101103
300-second max age. Core queries it for nomination via `GetTopTxs`.
102104
See [mempool.md](rust-overlay/mempool.md).
103-
- **Backpressure asymmetry**. SCP and TxSet events to Core are on an
104-
unbounded channel and never drop. TX events are on a bounded channel
105-
(10,000) and may drop under load — TXs are re-fetchable via the same
106-
INV/GETDATA protocol, so this is acceptable. See
107-
[ipc.md](rust-overlay/ipc.md#channel-discipline).
105+
- **Bounded network TX admission**. Readers enqueue directly into the same
106+
mempool FIFO as Core submissions, removals, and queries. A shared semaphore
107+
bounds queued plus active network insertions at 10,000. Refused admissions
108+
remain retryable; controls need no admission permit. SCP, TxSet, and peer
109+
events use an unbounded App channel. See
110+
[ordered admission](rust-overlay/mempool.md#tx-received-over-the-network) and
111+
[IPC channel discipline](rust-overlay/ipc.md#channel-discipline).
108112

109113
## What changed vs. the legacy C++ overlay
110114

111115
| Property | Legacy (C++) | Rust overlay |
112116
|-----------------------------|-------------------------------------------|-------------------------------------------------------|
113117
| Process boundary | In-process with consensus | Separate process, IPC over Unix socket |
114118
| Transport | TCP + custom auth | QUIC (TLS 1.3 + multiplexing) via libp2p |
115-
| Stream isolation | Single TCP connection per peer | Three logical streams per peer over one QUIC conn |
119+
| Stream isolation | Single TCP connection per peer | Prioritized routes with legacy compatibility |
116120
| Memory-safety class | C++ | Safe Rust |
117121
| TX flooding | Pull-based (existing INV/GETDATA scheme) | Pull-based (INV/GETDATA), reimplemented |
118122
| SCP flooding | Push-based | Push-based |
@@ -121,27 +125,23 @@ dedicated doc under [`docs/rust-overlay/`](rust-overlay/):
121125

122126
## Configuration
123127

124-
TOML, parsed at startup (`config.rs`):
125-
126-
| Field | Type | Default | Description |
127-
|---------------------|---------------|-------------------------------|-----------------------------------------------------|
128-
| `core_socket` | `PathBuf` | `/tmp/stellar-overlay.sock` | IPC socket path |
129-
| `listen_addr` | `SocketAddr` | `0.0.0.0:11625` | Legacy peer-port placeholder |
130-
| `libp2p_listen_ip` | `String` | `0.0.0.0` | QUIC bind interface |
131-
| `peer_port` | `u16` | `11625` | Base port. QUIC listens on `peer_port + 1000` |
132-
| `target_outbound_peers` | `usize` | `8` | **Defined but unused** |
133-
| `max_inbound_peers` | `usize` | `64` | **Defined but unused** |
134-
| `preferred_peers` | `Vec<SocketAddr>` | `[]` | Static preferred peers (see note below) |
135-
| `known_peers` | `Vec<SocketAddr>` | `[]` | Static known peers (see note below) |
136-
| `tx_push_peer_count`| `usize` | `8` | **Defined but unused** in network code |
137-
| `max_mempool_size` | `usize` | `100_000` | **Defined but unused** — mempool is hardcoded |
138-
| `http_addr` | `Option<SocketAddr>` | `127.0.0.1:11626` | HTTP server (TX submission, status) |
139-
| `log_level` | `String` | `info` | `tracing` log level |
140-
141-
> **About `known_peers` / `preferred_peers` in the file**: peer
142-
> membership at runtime is set by Core via the `SetPeerConfig` IPC
143-
> message, *not* by the values in this file. The static fields here are
144-
> kept for tooling and tests but are not the source of truth.
128+
TOML, parsed at startup (`config.rs`). Unknown fields are rejected.
129+
130+
| Field | Type | Default | Description |
131+
|-------|------|---------|-------------|
132+
| `core_socket` | `PathBuf` | `/tmp/stellar-overlay.sock` | IPC socket path |
133+
| `libp2p_listen_ip` | `String` | `0.0.0.0` | QUIC bind interface |
134+
| `peer_port` | `u16` | `11625` | Base port; QUIC listens on `peer_port + 1000` |
135+
| `log_level` | `String` | `info` | `tracing` log level |
136+
137+
Core supplies peer membership through the `SetPeerConfig` IPC message.
138+
The overlay performance behavior is unconditional: concurrent sends, control
139+
and tx-set priorities, 4 MiB UDP receive-buffer requests, demand-driven Core
140+
set delivery, shared tx-set payloads, and ordered bounded network admission
141+
have no feature switches. See [transport](rust-overlay/transport.md) for the
142+
mandatory OS buffer allowance. Early nomination preparation also runs
143+
automatically for eligible validators; its ledger, time, and capacity checks
144+
preserve proposal validity and refresh underfilled snapshots.
145145

146146
## Code structure
147147

‎docs/rust-overlay/ipc.md‎

Lines changed: 19 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,8 @@ are rejected with `InvalidData`.
6363
| 7 | `Shutdown` | (empty) | Graceful shutdown |
6464
| 8 | `SetPeerConfig` | UTF-8 JSON (see below) | Configure peer addresses |
6565
| 10 | `SubmitTx` | `[fee:i64 LE][num_ops:u32 LE][tx_xdr]` | Submit TX for flood + mempool |
66-
| 11 | `RequestTxSet` | `[hash:32]` | Fetch TX set body by hash |
67-
| 12 | `CacheTxSet` | `[hash:32][txset_xdr]` | Tell overlay to cache a locally-built TX set |
66+
| 11 | `RequestTxSet` | `[hash:32][slot:u32 LE]` | Fetch TX set body by hash |
67+
| 12 | `CacheTxSet` | `[hash:32][slot:u32 LE][txset_xdr]` | Tell overlay to cache a locally-built TX set |
6868
| 13 | `RequestOverlayMetrics` | (empty) | Request metrics snapshot |
6969

7070
### Overlay → Core
@@ -101,30 +101,23 @@ are rejected with `InvalidData`.
101101

102102
## Channel discipline
103103

104-
The overlay's main loop consumes IPC messages from a single `mpsc`
105-
receiver
106-
(`main.rs:554-566`, the `core_ipc.receiver.recv()` arm). On the libp2p
107-
side it consumes events from two channels:
108-
109-
| Channel | Bound | Drops? | Carries |
110-
|---------------------------|--------|--------|-----------------------------------------------|
111-
| `event_rx` (libp2p) | unbounded | never | SCP envelopes, TxSet events, peer events |
112-
| `tx_event_rx` (libp2p) | bounded (10,000) | yes, on overflow | TX-flood events only |
113-
| `core_ipc.sender` | mpsc unbounded | never | Outbound to Core |
114-
| `core_ipc.receiver` | mpsc | mpsc semantics | Inbound from Core |
115-
116-
Two consequences:
117-
118-
- SCP and TxSet messages from peers **cannot be dropped** at the
119-
overlay-Core boundary. If Core stalls processing them, the overlay
120-
will accumulate work in the unbounded queue (which is acceptable for
121-
the relatively low volume of SCP/TxSet messages).
122-
- TX flood events **can be dropped** — see
123-
[tx-propagation.md](tx-propagation.md#backpressure). The TX itself
124-
remains in the overlay's `tx_buffer` and is still served to peers via
125-
GETDATA; only the upcall to Core for that single arrival is lost.
126-
Subsequent INVs from peers (or our own future GETDATA cycles) re-push
127-
it.
104+
The App loop consumes Core IPC and a separate libp2p event channel. Network
105+
transactions enter the mempool command FIFO directly, without passing through
106+
App or sending a per-transaction IPC upcall to Core.
107+
108+
| Channel or admission point | Bound | Carries |
109+
|---|---|---|
110+
| libp2p App events | Unbounded; no overflow dropping | SCP, TxSet, and peer events |
111+
| Network mempool admission | 10,000 queued plus active inserts; nonblocking refusal | Network TXs |
112+
| Mempool command FIFO | Unbounded channel; network producers require admission permits | Admissions, Core submissions, removals, queries |
113+
| Core IPC sender | Unbounded | Outbound IPC messages |
114+
| Core IPC receiver | Existing mpsc channel | Inbound IPC messages |
115+
116+
Network saturation does not prevent removal or query commands from entering
117+
the FIFO. Refused admissions are not marked seen, allowing a later response
118+
to succeed. Unbounded queues can accumulate work if consumers stall, and sends
119+
to closed channels still fail. See [ordered admission](mempool.md#tx-received-over-the-network)
120+
and [TX backpressure](tx-propagation.md#backpressure).
128121

129122
## Failure modes
130123

‎docs/rust-overlay/mempool.md‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,13 +97,18 @@ entry with `ValidatedTx::from_core_trusted`, which trusts Core's
9797
metadata and does not re-decode (it only rejects fee-bumps via the
9898
envelope discriminant and hashes the bytes).
9999

100-
### TX received over the network (`main.rs:727-734`)
101-
102-
`LibP2pOverlayEvent::TxReceived` already carries an `Arc<ValidatedTx>`:
103-
the per-peer TX stream reader minted it with `ValidatedTx::from_network`
104-
during its single strict decode of the inbound message
105-
(`flood/inv_messages.rs`), reading fee/op metadata off the decoded
106-
envelope. The handler just forwards it to `submit_tx`.
100+
### TX received over the network
101+
102+
The per-peer reader creates an `Arc<ValidatedTx>` with `from_network` during
103+
its strict decode, extracting fee/op metadata from the envelope. The receive
104+
handler enqueues it directly through `try_submit_network_tx`, before recording
105+
it as seen or awaiting relay bookkeeping. This shares the Core command FIFO
106+
and bounds queued plus active network admissions at 10,000. There is no App
107+
forwarding queue.
108+
109+
An admission queued before externalization runs before the subsequent removal.
110+
An admission first queued after removal is allowed; this design does not retain
111+
finalized-hash history or assume ordering between independent network streams.
107112

108113
## Querying
109114

‎docs/rust-overlay/peer-connections.md‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,9 @@ Steps performed:
5959
[DNS resolution](#dns-resolution).
6060
4. **Schedule a retry task** for any addresses where DNS failed.
6161

62-
Note: `target_outbound_peers` and `max_inbound_peers` are defined in
63-
`config.rs` but are **not enforced anywhere in the network code**. The
64-
overlay attempts to connect to every address Core sends and accepts all
65-
inbound connections.
62+
The overlay attempts to connect to every address Core sends and accepts all
63+
inbound connections. There are no overlay configuration fields for inbound
64+
or outbound peer-count limits.
6665

6766
## DNS resolution
6867

@@ -159,8 +158,8 @@ informational only.
159158
and is no longer in `Cargo.toml` or the source tree.
160159
- **No peer-exchange / gossip.** Peers do not learn about other peers from
161160
each other.
162-
- **No outbound connection limit.** `target_outbound_peers` is unused.
163-
- **No inbound connection limit.** `max_inbound_peers` is unused.
161+
- **No outbound connection limit.** All Core-configured addresses are dialed.
162+
- **No inbound connection limit.** Incoming peers are accepted without a count limit.
164163
- **No banlist or DoS scoring.** Misbehaving peers are not throttled or
165164
evicted by the overlay (this lives in Core for the legacy overlay; not
166165
yet ported here).

0 commit comments

Comments
 (0)