Перейти к содержимому

Peer-auth live two-node failure: root cause and fix

Status: root cause found and fixed. The local two-node testnet-profile run now establishes ML-DSA-87 peer-auth sessions repeatedly (dialer B → acceptor A) with no connection lost errors; A serves one header request per session and prints session served: requests 1 rejected attempts 0.

Scope of the fix: crates/node/src/peer_accept.rs, crates/node/src/peer_session.rs, crates/node/src/peer_service.rs. peer_auth.rs and peer_manager.rs were read end to end and are not defective; no main.rs change is required. One same-class defect was in crates/node/src/peer_sync.rs; it is fixed on the same branch by the lazy-deadline change recorded below.

Verified live: Windows testnet-profile release binary built by D:\21-acl-recovery\build-testnet2.bat, artifacts in D:\21-acl-recovery\testnet-run (node-windows.json/node A, node-b.json/node B, mutual pins in peers.redb/peers-b.redb, shared CA:FALSE self-signed TLS certificate, allow_operator_managed_addresses: true). Evidence logs: live-verify-fixed-final.log (post-fix, binary rebuilt from this tree) and prefix-repro-evidence.log (pre-fix, temporary instrumentation) in the same directory.

Symptom

Both processes complete the QUIC/TLS handshake and the exporter-bound ML-DSA-87 proof exchange can succeed, yet the run looks broken:

  • dialer (node B): peer sync attempt failed: cannot connect to peer: peer session setup failed: peer session transport failed: QUIC peer-auth I/O failed: connection lost
  • acceptor (node A): inbound session failed: peer session failed: peer session failed: peer session frame failed: P2P frame I/O failed: connection lost

The transport, the TLS profile, the shared-certificate trust-anchor model, the ML-DSA-87 pins and the exporter derivation are all fine. The two defects are in how the peer session orchestration builds its deadlines and how a normal session end is classified.

Session setup call chain (reference)

  1. main.rs calls run_acceptor (node A) / run_dialer_loop (node B) with PeerTimingsV0 / DialerTimingsV0.
  2. peer_accept.rs::run_acceptor calls PeerManager::accept_from_pinned_peer(endpoint, records, identity, limits, accept_deadline, open_stream_deadline, auth_deadline, hello_deadline).
  3. peer_manager.rs::accept_from_pinned_peer performs, in order: MirageQuinnServerEndpoint::accept → reserve_inbound → QuinnPeerStream::accept (waits for the initiator’s first bidi stream) → authenticate_resolved (responder sends its peer-auth proof after reading the MRGS\x00\x01 preface, then verifies the initiator proof) → PeerSession::establish_after_transport_authentication (peer hello) → returns ManagedPeerSession.
  4. peer_accept.rs::run_acceptor then calls serve_peer_requests, which reads bounded frames (GET_HEADERS etc.) until the peer disconnects.
  5. The dialer path is symmetric: connect_to_pinned_peer → PeerSession::establish_quinn_initiator → header requests.

Each of steps 3’s four stages gets its own timeout future, and those futures are created by the caller before the call. The intended contract (also documented in docs/protocol/p2p-peer-manager-v0.md: “приложение само создаёт новый deadline для каждой попытки”) is a fresh, per-stage deadline that starts when that stage starts.

Root cause 1 — acceptor rejects healthy reconnects with already-expired deadlines

crates/node/src/peer_accept.rs at HEAD (commit c6c2046), lines 213–224:

let accepted = manager
.accept_from_pinned_peer(
endpoint,
records,
local_identity_key,
frame_limits.clone(),
sleep(timings.accept), // 10 s
sleep(timings.open_stream), // 5 s
sleep(timings.authenticate), // 5 s
sleep(timings.hello), // 5 s
)
.await;

tokio::time::sleep captures its deadline at construction time. All four futures are constructed before the call, so open_stream, authenticate and hello each have at most 5 s measured from the moment run_acceptor started waiting — not from the moment their stage begins. accept itself may legitimately block for its full 10 s (idle listener); every inbound connection that arrives more than 5 s into the accept window therefore starts the QuinnPeerStream::accept (server accept_bi) stage with an already-expired deadline.

What the finished connection then sees:

  • A accepts the QUIC/TLS connection, then QuinnPeerStream::accept’s select returns DeadlineExceeded immediately. quinn_transport.rs closes the whole connection with application error code 0x4D52 (“Mirage P2P session rejected”).
  • B is inside authenticate; its next read/write fails with ConnectionLost(ApplicationClosed(0x4D52)), which surfaces as QUIC peer-auth I/O failed: connection lost — the reported dialer error.
  • A counts it as a non-fatal rejected attempt and silently keeps listening, which is why no acceptor log line explains the failure.

The live session is flaky for exactly this reason: node B dials once immediately and then retries every 30 s (15 s per-address + 15 s loop pause in peer_sync.rs::run_dialer_loop), while A restarts its accept window after every served session. A connection that arrives inside the first 5 s of a given window succeeds; later ones are rejected instantly. The first attempt often passes narrowly (B is started ~4 s after A in the runbook), which is why the old evidence shows one silent success followed by repeated connection lost failures. On a busy machine the first attempt fails too.

Measured pre-fix (prefix-repro-evidence.log, temporary [dbg] instrumentation, since removed):

8000ms A.err [dbg] acceptor: transport accepted from 127.0.0.1:56723
8000ms A.err [dbg] acceptor: pending lease reserved
8000ms A.err [dbg] acceptor: application stream accepted
8015ms A.err [dbg] acceptor: session established (auth + hello) <- first attempt ok
8015ms A.err [dbg] service: received frame type 1
8015ms A.err [dbg] peer frame receive failed: Err(Io(Custom { kind: NotConnected,
error: ConnectionLost(ApplicationClosed(ApplicationClose {
error_code: 0, reason: b"" })) })) <- root cause 2
38031ms A.err [dbg] acceptor: transport accepted from 127.0.0.1:56723
38031ms A.err [dbg] acceptor: pending lease reserved
38031ms A.err [dbg] acceptor: stream accept failed: DeadlineExceeded <- root cause 1
38031ms B.err peer sync attempt failed: ... QUIC peer-auth I/O failed: connection lost

The same pattern exists in peer_accept.rs::connect_and_serve (HEAD lines 283–286, four sleep(...) call arguments) — that helper is currently unused, but the API misuse is identical and must not be reintroduced. The remaining live instance is in peer_sync.rs::sync_headers_from_peer (HEAD lines 249–252); see the out-of-scope patch.

Root cause 2 — a normal peer disconnect is reported as a session failure

crates/node/src/peer_session.rs at HEAD lines 84–89 and crates/node/src/peer_service.rs at HEAD lines 95–98:

let result = read_frame(&mut self.stream, &self.limits, deadline).await;
if result.is_err() {
self.poisoned = true;
self.stream.close_after_error();
}
result.map_err(PeerSessionError::Frame) // peer_session.rs
...
.map_err(PeerServiceErrorV0::Session)?; // peer_service.rs

A dialer that has finished its request/response work simply drops its session. Quinn implicitly closes the connection when the last Connection handle is dropped (documented: application error code 0, empty reason) or finishes the stream. The acceptor’s read then fails with UnexpectedEof, or NotConnected wrapping quinn::ReadError::ConnectionLost(quinn::ConnectionError::ApplicationClosed(code 0)).

That is the normal end of the session — exactly the outcome the runbook expects to be reported as session served: requests 1. The old code mapped every read failure to PeerSessionError::Frame, propagated it through PeerServiceErrorV0::Session out of run_acceptor, and main.rs printed the scary inbound session failed: ... connection lost line for a perfectly healthy disconnect. This also prevented run_acceptor from ever counting the served session (maximum_sessions = 1 was never reached; the function returned Err instead of Ok(PeerLoopStatsV0)).

The pre-fix trace shows the exact error object: ConnectionLost(ApplicationClosed(ApplicationClose { error_code: 0, reason: b"" })) — the implicit close of a dropped peer connection, not a transport fault.

Fix

1. Per-stage deadlines that start when the stage starts (peer_accept.rs)

New helper (lines 200–213):

/// Creates a timeout future whose clock starts when the stage that uses it starts.
///
/// `tokio::time::sleep` captures its deadline at construction time. Building
/// every handshake timeout before the blocking accept/connect call therefore
/// gives each later stage only whatever budget the earlier stage left over: ...
fn stage_timeout(timeout: Duration) -> impl Future<Output = ()> {
async move { sleep(timeout).await }
}

Used for all four stages in run_acceptor (lines 249–252) and in connect_and_serve (lines 315–318). An async block starts its timer only when its stage polls it, so open_stream/authenticate/hello each get their full budget starting at the stage.

2. Classify a clean peer disconnect (peer_session.rs)

New is_clean_peer_disconnect(&io::Error) -> bool (lines 23–61) recognises:

  • io::ErrorKind::UnexpectedEof — the peer finished the stream;
  • quinn::ReadError::Reset(_) / ClosedStream — the peer stopped the stream;
  • quinn::ReadError::ConnectionLost(cause) where cause is ApplicationClosed with error code 0 and an empty reason (Quinn’s implicit close when the peer drops its last Connection handle — the exact live case), ConnectionClosed (transport-level close by the peer), Reset (peer restarted) or TimedOut (idle timer).

Genuine faults stay errors: explicit application closes with a non-zero code or a reason (the peer is reporting an error), plain I/O errors, local timeouts, IllegalOrderedRead, ZeroRttRejected, QUIC transport/protocol errors.

PeerSession::receive (lines 119–145) now returns the new PeerSessionError::PeerClosed for a clean peer end (the session is poisoned; no connection-close frame is sent to a peer that already left) and keeps PeerSessionError::Frame for real failures.

3. Serve loop treats a clean peer end as a completed session (peer_service.rs)

serve_peer_requests (lines 98–102):

let frame: FrameV0 = match session.receive(read_deadline()).await {
Ok(frame) => frame,
Err(PeerSessionError::PeerClosed) => return Ok(served),
Err(error) => return Err(PeerServiceErrorV0::Session(error)),
};

The session now ends with Ok(served); run_acceptor increments sessions_served / requests_served and returns Ok(PeerLoopStatsV0), so main.rs prints session served: requests N rejected attempts M instead of inbound session failed.

4. Do not count idle accept timeouts as rejected peers (peer_accept.rs)

is_idle_accept_timeout (lines 133–143) keeps the rejected attempts counter meaningful: an accept deadline with no inbound connection is an idle listener, not a peer that was rejected. run_acceptor (lines 261–263) skips the counter for it.

Regression tests

  • peer_accept::tests::stage_timeouts_start_when_their_stage_starts — a stage timeout created before a 250 ms “slow accept” must still wait out its own 100 ms budget when polled afterwards (fails on the old eager sleep construction).
  • peer_session::tests::a_finished_stream_is_a_clean_peer_disconnect
  • peer_session::tests::a_peer_dropping_its_connection_is_a_clean_disconnect — constructs the exact implicit ApplicationClosed error observed live (code 0, empty reason).
  • peer_session::tests::an_explicit_error_close_is_not_a_clean_disconnect — the acceptor’s own 0x4D52 rejection close must stay a failure, not a clean end.
  • peer_session::tests::peer_side_stream_and_connection_ends_are_clean
  • peer_session::tests::local_timeouts_and_plain_io_errors_are_not_clean_disconnects
  • peer_session::tests::peer_closed_reports_the_session_end_explicitly
  • peer_accept::tests::an_idle_accept_timeout_is_not_a_rejected_peer

Dialer: same defect, fixed

The dialer does not expose the same bug on loopback because a connect finishes in milliseconds, but it had the identical eager-deadline construction. The patch below is now applied in crates/node/src/peer_sync.rs and covered by the node lib suite:

--- a/crates/node/src/peer_sync.rs
+++ b/crates/node/src/peer_sync.rs
@@ -246,10 +246,10 @@ pub async fn sync_headers_from_peer<L>(
frame_limits,
now_unix_seconds,
maximum_expiry_unix_seconds,
- tokio::time::sleep(connect_timeout),
- tokio::time::sleep(connect_timeout),
- tokio::time::sleep(connect_timeout),
- tokio::time::sleep(connect_timeout),
+ async move { tokio::time::sleep(connect_timeout).await },
+ async move { tokio::time::sleep(connect_timeout).await },
+ async move { tokio::time::sleep(connect_timeout).await },
+ async move { tokio::time::sleep(connect_timeout).await },
)
.await
.map_err(PeerSyncErrorV0::Connect)?;

DialerTimingsV0 has no separate open/auth/hello values, so all four stages share connect_timeout; laziness is what matters. main.rs needs no change.

Reproduction commands

Окно терминала
# 0. Identity password for automation (the operator path still prompts).
$env:MIRAGE_PEER_IDENTITY_PASSWORD = 'testnet-pass-1'
# 1. Rebuild the testnet-profile binary (D:\21-acl-recovery\build-testnet2.bat does this).
cmd /c "D:\21-acl-recovery\build-testnet2.bat"
# 2. Timestamped two-node run (line-accurate merged stdout/stderr, kills both at the end).
# Args: seconds, A->B start delay, binary path.
& "$env:PYTHON" D:\21-acl-recovery\repro_two_node.py 70 8 `
D:\21-acl-recovery\mirage-node-testnet.exe

Manual equivalent (two terminals, same result):

Окно терминала
$env:MIRAGE_PEER_IDENTITY_PASSWORD = 'testnet-pass-1'
# terminal A
D:\21-acl-recovery\mirage-node-testnet.exe --node-run D:\21-acl-recovery\testnet-run\node-windows.json
# wait 4 s (8 s reproduces the deadline bug deterministically on the pre-fix binary), then:
# terminal B
D:\21-acl-recovery\mirage-node-testnet.exe --node-run D:\21-acl-recovery\testnet-run\node-b.json
# wait 30-70 s and read both consoles.

Verification

Targeted tests (MSVC toolchain, CARGO_TARGET_DIR=D:\21-acl-recovery\target; see D:\21-acl-recovery\run-node-test.bat):

> cmd /c "D:\21-acl-recovery\run-node-test.bat peer_"
running 24 tests
test peer_accept::tests::stage_timeouts_start_when_their_stage_starts ... ok
test peer_session::tests::a_finished_stream_is_a_clean_peer_disconnect ... ok
test peer_session::tests::a_peer_dropping_its_connection_is_a_clean_disconnect ... ok
test peer_session::tests::an_explicit_error_close_is_not_a_clean_disconnect ... ok
test peer_session::tests::peer_side_stream_and_connection_ends_are_clean ... ok
test peer_session::tests::local_timeouts_and_plain_io_errors_are_not_clean_disconnects ... ok
test peer_session::tests::peer_closed_reports_the_session_end_explicitly ... ok
test peer_accept::tests::an_idle_accept_timeout_is_not_a_rejected_peer ... ok
... (16 pre-existing peer/peer_sync/config tests also pass)
test result: ok. 24 passed; 0 failed; 0 ignored; 0 measured; 61 filtered out

Live post-fix run with an 8 s A→B stagger (deliberately past the old 5 s per-stage budget; live-verify-fixed-final.log, identical results in live-verify-fixed.log):

1218ms A.out listening on 127.0.0.1:9400
9093ms B.err dialer: attempting peer 127.0.0.1:9400
9172ms A.out session served: requests 1 rejected attempts 0
39187ms B.err dialer: attempting peer 127.0.0.1:9400
39202ms A.out session served: requests 1 rejected attempts 0
69218ms B.err dialer: attempting peer 127.0.0.1:9400
69218ms A.out session served: requests 1 rejected attempts 0

No connection lost, no inbound session failed; both nodes stay up. Node B prints nothing on success because both nodes are at height 0 (genesis only) and run_dialer_loop’s progress callback only prints when headers_connected > 0; the wire traffic itself is GET_HEADERS (frame type 1, observed) answered by A.

Notes / follow-ups (not part of this fix)

  • quinn_transport.rs’s QuinnTransportError::Io displays only the outer connection lost text, discarding the underlying quinn::ConnectionError. This is what made the live failure opaque; surfacing Debug/source in that message is recommended (outside the scoped files).
  • main.rs still calls run_acceptor(maximum_sessions = 1) in a loop; that is fine with the fixed semantics (one session per iteration, then a fresh accept window).
  • There is no in-process QUIC-transport test in the crate: peer-session tests cover policy and framing only, which is why a timing bug in the orchestration layer escaped unit tests. The new tests pin the two behaviours (lazy stage timeouts, clean-close classification) directly.

Итоговая проверка (Docker, два узла, proof-carrying блок)

После фиксов оба узла подняты в Docker Desktop (образ mirage-sp1:v6.10.0, данные на диске D) во внутренней сети 172.28.0.0/24. Узел A отдаёт уже принятый блок height 1, узел B синхронизируется и принимает его с проверкой доказательств:

B: headers pulled from a peer: 1
B: block accepted: height 1 hash 0000040f2d7977568a8a305ed78bd7701780c7060b971d4dd16633bcb4991c19 minted 1500
A: session served: requests 10 rejected attempts 0

Ошибок peer-auth больше нет. Дополнительно на этом пути найдены и исправлены: eager-таймауты в dialer’е (peer_sync.rs), V0-геттер staged-тела в accept_staged_blocks_v1 и стартовый guard header tip == chain tip.