aion_server/worker/liminal_liveness.rs
1//! Server half of the liminal connection dead-man switch: the liveness probe.
2//!
3//! # The gap this closes
4//!
5//! The server's connection lease ([`HeartbeatTracker`]) is advanced by frames a
6//! worker SENDS, and an idle worker sends nothing. So on 2026-07-29 a healthy,
7//! connected, idle worker's lease expired 37 seconds after its last activity —
8//! "idle worker connection lease expired; worker deregistered" — the worker was
9//! never told, kept believing it was connected, and the next dispatch parked
10//! forever on a queue nobody was serving. The same absent mechanism cost a live
11//! run 28 minutes of mutual blindness when a link died mid-activity: the server
12//! pushed into a socket nobody was reading and the worker blocked on a socket
13//! nobody was writing.
14//!
15//! # The probe
16//!
17//! [`LivenessProbe`] pushes a [`LivenessPing`] to every liminal-connected worker
18//! on a fixed cadence and waits for the correlated [`LivenessPong`]. One
19//! exchange proves both legs:
20//!
21//! - The PONG proves the worker is alive to the server, and its arrival advances
22//! the worker's connection lease — so an idle-but-alive connection is no
23//! longer "idle" at the lease layer and the idle expiry cannot fire on it.
24//! That is the structural death of the first failure above.
25//! - The PING's arrival proves the server is alive to the worker, whose own
26//! dead-man switch (`aion-worker`'s `liminal_liveness`) declares the link dead
27//! when pings stop. That is the death of the second.
28//!
29//! A ping that is not answered inside the cadence is logged LOUDLY with the
30//! worker's identity and queue, and withdraws the worker's DISPATCH
31//! ELIGIBILITY once the silence outlasts the window.
32//!
33//! # Why eligibility, and not the connection lease
34//!
35//! This module used to claim that an unanswered ping let "a genuinely dead
36//! worker's lease run down" so the expiry sweep would reap it. **That was
37//! false, and run `dfd2117c` proved it**: the server could not push to a worker
38//! for fifteen minutes and the worker never lost its lease, because the
39//! worker-side liveness pump beats from a background task and keeps refreshing
40//! it whatever the worker's serve loop is doing.
41//!
42//! Two different facts were collapsed into one lease:
43//!
44//! - **the worker process is alive** — proven by anything the worker sends,
45//! pump included, on the worker-to-server direction;
46//! - **the server can reach the worker's dispatch path** — proven only by an
47//! answered ping, on the server-to-worker direction.
48//!
49//! Only the second is a dispatch precondition, and
50//! [`LiminalWorkerDelivery::push_payload_with_deadline`] already says why the
51//! ping is the only thing that can prove it: it rides "the exact path a
52//! dispatch would take, not a parallel one that could be healthy while the real
53//! one is not." The pump is exactly such a parallel channel, so it must not
54//! feed the fact the ping exists to establish.
55//!
56//! So the probe advances a SEPARATE reachability clock
57//! ([`HeartbeatTracker::record_dispatch_reachability`]) and publishes an
58//! eligibility verdict the dispatch selector honours. The connection lease and
59//! its expiry sweep are untouched and still own process liveness — there is
60//! still deliberately no second reaper, and an unreachable worker is excluded
61//! from dispatch rather than torn down.
62//!
63//! # No knobs
64//!
65//! Both timings are DERIVED from the operator's existing
66//! `worker.heartbeat_window` — the one place they already declared what silence
67//! means:
68//!
69//! - the ping cadence is [`sweep_interval`] of that window (a quarter of it,
70//! clamped to `[1s, window]`), the identical derivation the expiry sweeper
71//! uses, so a healthy connection is refreshed four times per window and the
72//! idle lease has no chance to expire;
73//! - the window the worker is told to expect is the heartbeat window ITSELF, so
74//! both ends of the link declare death on exactly the same operator contract.
75//!
76//! Nothing here is separately configurable, and the worker holds no copy of the
77//! window: it is carried on every ping.
78//!
79//! # Both transports, one probation (#197)
80//!
81//! This module is named for the transport it was built against, but
82//! [`LivenessProbe`] is no longer liminal-only. A round enumerates liminal
83//! connections AND gRPC-delivered registrations
84//! ([`grpc_liveness`](super::grpc_liveness)), pings each over ITS OWN
85//! transport, and feeds every answer into the SAME
86//! [`HeartbeatTracker`] probation and the SAME
87//! [`publish_reachability_verdict`](LivenessProbe::publish_reachability_verdict)
88//! — one [`DISPATCH_PROBATION_PINGS`], one eligibility set, one set of
89//! announcement transitions, no per-transport constant and no exemption.
90//!
91//! Only the wire differs: a liminal worker is pinged with the serde
92//! [`LivenessPing`] on its connection, a gRPC worker with the protobuf
93//! [`ProtoLivenessPing`](aion_proto::ProtoLivenessPing) on its task stream. The
94//! fact each establishes is identical, which is why the verdict is.
95//!
96//! The accepted cost of riding the task stream is that stream death is not a
97//! separate signal: a closed stream simply makes the NEXT ping unanswerable, so
98//! withdrawal latency is bounded by the probe cadence rather than being
99//! instantaneous. That is deliberate — a special-case fast path for stream
100//! death would be a second, softer route into the eligibility verdict, and the
101//! registry's own disconnect teardown already owns deregistration.
102//!
103//! # A verdict reaches only the transports this probe CARRIES (#25)
104//!
105//! The probation is transport-blind; the verdict's REACH is not. A probe
106//! publishes an exclusion for a worker only if it holds a wire on which that
107//! worker could have been asked — a liminal notifier for a liminal worker, a
108//! gRPC answer registry for a gRPC one ([`LivenessProbe::covers`]). Without
109//! that scope the verdict was formed from the whole of
110//! [`HeartbeatTracker::unreachable_workers`], so a worker of an uncarried
111//! transport could never bank an answer, never serve its probation, and never
112//! leave the exclusion set: registered, healthy, and withheld from dispatch for
113//! the life of the process. That was reported live against a server whose probe
114//! covered liminal only, and it is what [`LivenessProbe::new`] would still do to
115//! a gRPC fleet if the reach were left unscoped.
116//!
117//! Coverage is STRUCTURAL — which wires the probe holds — and never the set of
118//! targets a round happened to enumerate. The difference is load-bearing: a
119//! liminal worker whose connection has closed appears in no round's target list,
120//! and it is exactly the worker that must stay excluded. Scoping by enumeration
121//! would re-admit it, which is a worse defect than the one being cured.
122
123use std::collections::BTreeSet;
124use std::sync::Arc;
125use std::time::{Duration, Instant};
126
127use aion_core::WorkerTransport;
128use serde::{Deserialize, Serialize};
129use tokio::sync::watch;
130use tracing::{info, warn};
131
132use super::grpc_liveness::{GrpcLivenessTarget, GrpcLivenessWaiters, ping_grpc_worker};
133use super::heartbeat::{
134 DISPATCH_PROBATION_PINGS, DispatchExclusion, ExcludedWorker, HeartbeatTracker, sweep_interval,
135};
136use super::liminal_transport::{LiminalConnectionNotifier, LiminalWorkerDelivery};
137use super::liveness::{PingFailure, ProbedTransport};
138use super::registry::{ConnectedWorkerRegistry, WorkerId};
139
140/// Wire liveness ping the server pushes on an established liminal connection.
141///
142/// Field-for-field mirror of `aion-worker`'s `liminal_liveness::LivenessPing`
143/// (same serde field names), the same cross-crate contract the
144/// dispatch/response and intervention pairs pin. `liveness_ping` is also the
145/// worker's demux discriminator: no other pushed frame carries it, and a ping
146/// carries none of the fields a dispatch or intervention requires.
147#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
148pub struct LivenessPing {
149 /// Monotonic ping sequence within this connection, echoed on the answer.
150 pub liveness_ping: u64,
151 /// How long the worker may hear NOTHING on this connection before it must
152 /// declare the link dead — this server's `worker.heartbeat_window`, carried
153 /// on the wire so the worker never holds a second copy of it.
154 pub silence_window_ms: u64,
155}
156
157/// Wire answer the worker replies with, echoing the ping's sequence.
158///
159/// Field-for-field mirror of `aion-worker`'s `liminal_liveness::LivenessPong`.
160#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
161pub struct LivenessPong {
162 /// The sequence of the ping being answered, echoed verbatim.
163 pub liveness_pong: u64,
164}
165
166/// One connection the probe pings on a round: the connection pid, the worker it
167/// registered, and the push leg to reach it.
168#[derive(Clone, Debug)]
169pub struct LivenessTarget {
170 /// Liminal connection process id the worker is addressed on.
171 pub pid: u64,
172 /// Registry identity of the worker that registered on this connection.
173 pub worker_id: WorkerId,
174 /// Push leg used to deliver the ping and await its answer.
175 pub delivery: LiminalWorkerDelivery,
176}
177
178/// The production driver of the liminal connection dead-man switch.
179///
180/// Shares the server's shutdown watch, so it drains with the transports exactly
181/// like [`HeartbeatSweeper`](super::HeartbeatSweeper) and the outbox dispatcher.
182pub struct LivenessProbe {
183 /// The liminal connection census, or `None` on a boot that hosts no liminal
184 /// listener. `None` is not "no liveness": the gRPC half below still runs.
185 notifier: Option<Arc<LiminalConnectionNotifier>>,
186 /// The gRPC answer-correlation registry, or `None` when this probe has no
187 /// channel to receive gRPC answers on.
188 ///
189 /// Structural rather than a flag: a probe with no correlation registry
190 /// cannot hear a gRPC answer, so it must not push gRPC pings either — every
191 /// one would time out and hold healthy workers off dispatch. The production
192 /// wiring
193 /// ([`ServerState::spawn_liminal_liveness_probe`](crate::ServerState::spawn_liminal_liveness_probe))
194 /// always supplies one; [`LivenessProbe::new`] is the liminal-only
195 /// construction for callers with no gRPC fleet.
196 grpc: Option<GrpcLivenessWaiters>,
197 tracker: HeartbeatTracker,
198 registry: ConnectedWorkerRegistry,
199 cadence: Duration,
200 silence_window: Duration,
201}
202
203impl std::fmt::Debug for LivenessProbe {
204 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205 formatter
206 .debug_struct("LivenessProbe")
207 .field("cadence", &self.cadence)
208 .field("silence_window", &self.silence_window)
209 .finish_non_exhaustive()
210 }
211}
212
213impl LivenessProbe {
214 /// Build a probe over the notifier that owns the liminal connections, the
215 /// shared liveness tracker whose leases a pong refreshes, and the registry
216 /// the WARN lines resolve a worker's queue through.
217 ///
218 /// Both timings derive from `heartbeat_window` (see the module docs); there
219 /// is no separate configuration surface.
220 /// This construction probes the LIMINAL transport only: it carries no gRPC
221 /// answer-correlation registry, so it does not enumerate gRPC deliveries.
222 /// Use [`Self::across_transports`] for the production probe.
223 #[must_use]
224 pub fn new(
225 notifier: Arc<LiminalConnectionNotifier>,
226 tracker: HeartbeatTracker,
227 registry: ConnectedWorkerRegistry,
228 heartbeat_window: Duration,
229 ) -> Self {
230 Self::across_transports(Some(notifier), None, tracker, registry, heartbeat_window)
231 }
232
233 /// Build the probe that covers EVERY transport a worker may be delivered
234 /// over (#197).
235 ///
236 /// `notifier` is `None` on a boot with no liminal listener; `grpc` is the
237 /// correlation registry the gRPC stream handler delivers answers into, and
238 /// is `None` only for a probe that must not push gRPC pings it could never
239 /// hear the answers to.
240 ///
241 /// There is exactly ONE probe per server. Two would each publish a whole
242 /// eligibility set over the other's — the verdict is a replacement, not a
243 /// merge — so the last writer would silently erase the other transport's
244 /// findings every cadence.
245 #[must_use]
246 pub fn across_transports(
247 notifier: Option<Arc<LiminalConnectionNotifier>>,
248 grpc: Option<GrpcLivenessWaiters>,
249 tracker: HeartbeatTracker,
250 registry: ConnectedWorkerRegistry,
251 heartbeat_window: Duration,
252 ) -> Self {
253 Self {
254 notifier,
255 grpc,
256 tracker,
257 registry,
258 cadence: sweep_interval(heartbeat_window),
259 silence_window: heartbeat_window,
260 }
261 }
262
263 /// The interval between probe rounds.
264 #[must_use]
265 pub const fn cadence(&self) -> Duration {
266 self.cadence
267 }
268
269 /// The silence window this probe declares to every worker it pings.
270 #[must_use]
271 pub const fn silence_window(&self) -> Duration {
272 self.silence_window
273 }
274
275 /// Run the probe until `shutdown` flips to `true`.
276 ///
277 /// Rounds never overlap: each tick's pings are awaited to completion (each
278 /// bounded by the cadence) before the next round starts, and a missed tick
279 /// is skipped rather than queued.
280 ///
281 /// That bounds the concurrent WAITS to one per connection. It was once
282 /// claimed to bound the outstanding PUSHES to one as well, "so it can never
283 /// crowd out real dispatches against liminal's per-connection pending-push
284 /// cap." **That claim was false and the failure it denied is exactly what
285 /// happened** on run `dfd2117c`: a push slot is not released by the caller
286 /// giving up, only by a consumed reply, a deadline expiry, or a connection
287 /// close. Awaiting a round to completion ends the wait, not the slot. So
288 /// abandoning one unanswered no-deadline ping per round leaked one slot per
289 /// round — 32 of them, then total refusal of every push on that connection.
290 ///
291 /// The bound is now real because
292 /// [`LiminalWorkerDelivery::push_payload_with_deadline`] attaches the
293 /// cadence as the push's own reply deadline, so an unanswered ping's slot
294 /// expires and RELEASES its cap admission instead of accumulating.
295 pub async fn run(self, mut shutdown: watch::Receiver<bool>) {
296 info!(
297 cadence_ms = self.cadence.as_millis(),
298 silence_window_ms = self.silence_window.as_millis(),
299 "worker liveness probe started (liminal + grpc)"
300 );
301 let mut sequence = 0_u64;
302 let mut ticks = tokio::time::interval(self.cadence);
303 ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
304 loop {
305 tokio::select! {
306 _ = ticks.tick() => {
307 if *shutdown.borrow() {
308 break;
309 }
310 sequence = sequence.saturating_add(1);
311 self.probe_once(sequence).await;
312 }
313 changed = shutdown.changed() => {
314 // A receive error means every sender dropped; treat that as
315 // a shutdown request rather than spinning.
316 if changed.is_err() || *shutdown.borrow() {
317 break;
318 }
319 }
320 }
321 }
322 info!("worker liveness probe stopped");
323 }
324
325 /// Ping every reachable worker once — liminal connections and gRPC task
326 /// streams alike, concurrently — apply each answer to the worker's dispatch
327 /// probation, and publish ONE verdict for the round.
328 ///
329 /// The two transports are pinged over their own wires, CONCURRENTLY with
330 /// each other, and are otherwise indistinguishable from here down: the same
331 /// probation, the same tracker, the same single
332 /// [`Self::publish_reachability_verdict`] call.
333 ///
334 /// EVERY round publishes, including one that found no target to ping. This
335 /// module used to skip publication for an empty round, reasoning that
336 /// "publishing an empty exclusion set would be indistinguishable from
337 /// clearing one". They are the same act, and skipping it is what left a
338 /// stale verdict standing: a verdict is published by REPLACEMENT, so a round
339 /// that publishes nothing leaves the previous round's exclusions in force
340 /// over a fleet this round measured afresh. The set is derived from the
341 /// tracker's standing evidence rather than from this round's targets, so it
342 /// is well defined whether or not anything was pinged (#25).
343 ///
344 /// Public because it is the whole unit of work: [`Self::run`] is a timer
345 /// around it and adds nothing but the schedule. Driving rounds directly is
346 /// how a test states a probation in ROUNDS rather than in wall-clock
347 /// sleeps, which is the difference between asserting the law and asserting
348 /// this machine's timing.
349 ///
350 /// `sequence` must advance between rounds: it is the echo a worker's answer
351 /// is matched against, and repeating one would let a previous round's late
352 /// answer satisfy this round's ping.
353 pub async fn probe_once(&self, sequence: u64) {
354 let liminal = self
355 .notifier
356 .as_ref()
357 .map_or_else(Vec::new, |notifier| notifier.liveness_targets());
358 let grpc = self.grpc_targets();
359 let silence_window_ms = u64::try_from(self.silence_window.as_millis()).unwrap_or(u64::MAX);
360 // Joined, not sequenced. Each half bounds its own pings by the cadence,
361 // so awaiting them in turn would let a round of unanswered gRPC pings
362 // push the NEXT liminal ping a full cadence late — stretching the gap
363 // between a healthy liminal connection's refreshes toward three
364 // quarters of the heartbeat window and eroding the four-refreshes-per-
365 // window margin this module's timings are derived to guarantee. The
366 // halves share no state until their answers are applied, so there is
367 // nothing to serialize.
368 tokio::join!(
369 self.probe_liminal(sequence, silence_window_ms, liminal),
370 self.probe_grpc(sequence, silence_window_ms, grpc),
371 );
372 self.publish_reachability_verdict(sequence);
373 }
374
375 /// This round's gRPC targets, or none when this probe carries no answer
376 /// channel (see [`Self::grpc`]). A registry read failure is LOUD and yields
377 /// no targets: the alternative is pinging a fleet the probe cannot describe.
378 fn grpc_targets(&self) -> Vec<GrpcLivenessTarget> {
379 let Some(_) = self.grpc.as_ref() else {
380 return Vec::new();
381 };
382 match self.registry.grpc_liveness_targets() {
383 Ok(targets) => targets,
384 Err(error) => {
385 warn!(
386 %error,
387 "could not enumerate gRPC-delivered workers for this liveness round; they \
388 go unprobed and will therefore not clear their dispatch probation"
389 );
390 Vec::new()
391 }
392 }
393 }
394
395 /// Push the serde ping to every liminal connection concurrently.
396 async fn probe_liminal(
397 &self,
398 sequence: u64,
399 silence_window_ms: u64,
400 targets: Vec<LivenessTarget>,
401 ) {
402 if targets.is_empty() {
403 return;
404 }
405 let ping = LivenessPing {
406 liveness_ping: sequence,
407 silence_window_ms,
408 };
409 let payload = match serde_json::to_vec(&ping) {
410 Ok(payload) => payload,
411 Err(error) => {
412 // Structurally unreachable (two integers), but a probe that
413 // cannot encode its own ping must say so rather than silently
414 // stop being a dead-man switch.
415 warn!(%error, "liminal liveness probe could not encode its ping; skipping round");
416 return;
417 }
418 };
419 let deadline = self.cadence;
420 let answers = targets.into_iter().map(|target| {
421 let payload = payload.clone();
422 async move {
423 let outcome = tokio::task::spawn_blocking(move || {
424 ping_one(&target.delivery, payload, deadline)
425 })
426 .await;
427 (target.pid, target.worker_id, outcome)
428 }
429 });
430 for (pid, worker_id, outcome) in futures::future::join_all(answers).await {
431 self.apply_answer(pid, worker_id, sequence, outcome);
432 }
433 }
434
435 /// Push the protobuf ping down every gRPC task stream concurrently.
436 async fn probe_grpc(
437 &self,
438 sequence: u64,
439 silence_window_ms: u64,
440 targets: Vec<GrpcLivenessTarget>,
441 ) {
442 let (Some(waiters), false) = (self.grpc.as_ref(), targets.is_empty()) else {
443 return;
444 };
445 let deadline = self.cadence;
446 let answers = targets.iter().map(|target| async move {
447 let outcome = ping_grpc_worker(
448 waiters,
449 target,
450 aion_proto::ProtoLivenessPing {
451 liveness_ping: sequence,
452 silence_window_ms,
453 },
454 deadline,
455 )
456 .await;
457 (target.worker_id, outcome)
458 });
459 for (worker_id, outcome) in futures::future::join_all(answers).await {
460 self.apply_grpc_answer(worker_id, sequence, outcome);
461 }
462 }
463
464 /// Publish this round's reachability verdict to the registry, so dispatch
465 /// selection skips workers the server cannot reach.
466 ///
467 /// Runs after every round, including rounds where every ping succeeded —
468 /// that is what RESTORES eligibility to a worker whose pings have started
469 /// answering again. Recovery must not need a separate trigger.
470 ///
471 /// This is the half that makes the switch able to fire at all. A worker's
472 /// connection lease is refreshed by anything it sends, including its own
473 /// background liveness pump, so a worker whose dispatch path is completely
474 /// dead can look perfectly alive indefinitely. Reachability is tracked
475 /// separately and only an answered ping advances it, so the pump can no
476 /// longer hold dispatch eligibility open against failing pings.
477 ///
478 /// # What this says out loud, and why it changed
479 ///
480 /// Until 2026-08-05 this announced exactly one transition — the withdrawal
481 /// — in one sentence that was FALSE in the commonest case. Every healthy
482 /// worker start logged `WITHDRAWING DISPATCH ELIGIBILITY … the server has
483 /// not been able to reach its dispatch path within the window`, because
484 /// registration opens an unserved probation and the first round after it
485 /// always finds the probation unserved. At that instant the server had
486 /// reached the worker — one answer was already banked — and the window had
487 /// nothing to do with it. The remedy sentence was wrong too: it promised
488 /// eligibility back after "one ping", when
489 /// [`DISPATCH_PROBATION_PINGS`](super::heartbeat::DISPATCH_PROBATION_PINGS)
490 /// consecutive answers are required and one was already in hand.
491 ///
492 /// The restoration a few seconds later was silent, so an operator saw the
493 /// alarm and never the all-clear. On Tom's server that read as a broken
494 /// worker and was reported to him as a caveat on a fix that was in fact
495 /// working. An alarm that fires on every ordinary connect carries no
496 /// information; a resolution nobody announces cannot cancel it.
497 ///
498 /// So the three transitions are now distinguished and all three are said:
499 /// the probation opening (ordinary, INFO), the loss of eligibility that was
500 /// actually held (an incident, WARN), and the recovery (INFO).
501 ///
502 /// # A KNOWN FALSE RED IN THE WITHDRAWAL, STATED PLAINLY
503 ///
504 /// A gRPC worker running at its full concurrency stops reading its task
505 /// stream: the worker runtime's receive loop waits for a concurrency permit
506 /// before it reads the next frame, so a ping already on the wire is not
507 /// answered until a permit frees. A worker saturated for longer than one
508 /// probe cadence therefore LOOKS silent while it is in fact working, and
509 /// this WARN will say its dispatch path is unreachable when the truth is
510 /// that it is busy. The line is honest about what was measured — no answer
511 /// arrived — and wrong about what that means.
512 ///
513 /// It is bounded and self-healing, and no operator action is required:
514 /// eligibility is withdrawn, so no further dispatch is sent to that worker;
515 /// the worker finishes its in-flight activities and its permits free; it
516 /// reads and answers the next ping; it serves its two-ping probation and
517 /// returns to the eligible set with the INFO all-clear. In-flight work is
518 /// untouched throughout — this verdict governs who may be SELECTED, never
519 /// what happens to work already dispatched.
520 ///
521 /// The fix is on the admission path (the receive loop must read a frame
522 /// before it waits for a permit), which is a change to how work is
523 /// ACCEPTED, not to how liveness is measured, and it is board item #206.
524 /// This paragraph is struck by the change that lands it.
525 ///
526 /// It is written here rather than left to the reviewer's notes because a
527 /// verdict must not lie about what it measured: an operator reading a
528 /// withdrawal for a saturated worker deserves to find, at the place the
529 /// reason is minted, that this case is known, is not their fault, and needs
530 /// nothing from them.
531 fn publish_reachability_verdict(&self, sequence: u64) {
532 let now = Instant::now();
533 let measured = match self.tracker.unreachable_workers(now) {
534 Ok(workers) => workers,
535 Err(error) => {
536 warn!(
537 %error,
538 liveness_ping = sequence,
539 "could not read worker reachability; leaving the previous dispatch \
540 eligibility verdict in place rather than guessing"
541 );
542 return;
543 }
544 };
545 let Some(unreachable) = self.within_reach(&measured) else {
546 warn!(
547 liveness_ping = sequence,
548 "could not read which transport each unreachable worker is delivered over, so \
549 this round cannot tell an exclusion it is entitled to publish from one it has \
550 no wire to test; the previous verdict stands unchanged"
551 );
552 return;
553 };
554 let excluded_now: BTreeSet<WorkerId> = unreachable
555 .iter()
556 .map(|excluded| excluded.worker_id)
557 .collect();
558 // The previous verdict is what makes a transition a transition. If it
559 // cannot be read the announcements are SKIPPED rather than guessed —
560 // assuming an empty previous set would re-announce every standing
561 // exclusion as though it had just happened. The verdict itself still
562 // publishes below: gating dispatch is the load-bearing half, and it
563 // must not be dropped because the narration failed.
564 match self.registry.dispatch_ineligible() {
565 Ok(previously_excluded) => {
566 self.announce_transitions(
567 sequence,
568 &previously_excluded,
569 &unreachable,
570 &excluded_now,
571 );
572 }
573 Err(error) => warn!(
574 %error,
575 liveness_ping = sequence,
576 "could not read the published liminal dispatch eligibility set; this round's \
577 eligibility changes go UNANNOUNCED, though the verdict itself is still published"
578 ),
579 }
580 if let Err(error) = self.registry.set_dispatch_ineligible(excluded_now) {
581 warn!(
582 %error,
583 liveness_ping = sequence,
584 "could not publish worker dispatch eligibility; selection keeps the \
585 previous verdict"
586 );
587 }
588 }
589
590 /// Narrow the tracker's evidence to the workers this probe is ENTITLED to
591 /// judge: those delivered over a transport it carries a wire for (#25).
592 ///
593 /// A worker of an uncarried transport is dropped — not because it is
594 /// reachable (nothing here knows that) but because this probe has no way to
595 /// find out, and an exclusion it could never lift is a permanent withdrawal
596 /// dressed as a measurement. A worker that has left the registry is dropped
597 /// for the same reason: it has no transport at all, selection can no longer
598 /// see it, and naming it would put a fabricated fact in an operator-facing
599 /// set.
600 ///
601 /// `None` when the registry cannot be read: the caller must then publish
602 /// NOTHING. Falling back to the unscoped set would reinstate the defect at
603 /// exactly the moment the server is least able to explain itself.
604 fn within_reach(&self, measured: &[ExcludedWorker]) -> Option<Vec<ExcludedWorker>> {
605 let transports = self
606 .registry
607 .transports_of(measured.iter().map(|excluded| excluded.worker_id))
608 .map_err(|error| warn!(%error, "could not read worker transports"))
609 .ok()?;
610 Some(
611 measured
612 .iter()
613 .filter(|excluded| {
614 transports
615 .get(&excluded.worker_id)
616 .is_some_and(|transport| self.covers(*transport))
617 })
618 .copied()
619 .collect(),
620 )
621 }
622
623 /// Whether this probe holds a wire on which a worker of `transport` could be
624 /// asked its liveness question.
625 ///
626 /// Structural, and deliberately not a function of how many targets a round
627 /// enumerated: a liminal worker whose connection has closed is enumerated by
628 /// nothing and is precisely the worker a liminal-carrying probe must keep
629 /// excluded.
630 const fn covers(&self, transport: WorkerTransport) -> bool {
631 match transport {
632 WorkerTransport::Grpc => self.grpc.is_some(),
633 WorkerTransport::Liminal => self.notifier.is_some(),
634 }
635 }
636
637 /// Say what changed this round — and only what changed, so a persistently
638 /// excluded worker does not re-log every cadence.
639 fn announce_transitions(
640 &self,
641 sequence: u64,
642 previously_excluded: &BTreeSet<WorkerId>,
643 unreachable: &[ExcludedWorker],
644 excluded_now: &BTreeSet<WorkerId>,
645 ) {
646 for excluded in unreachable {
647 let Some(announcement) = transition(
648 previously_excluded.contains(&excluded.worker_id),
649 Some(excluded.exclusion),
650 ) else {
651 continue;
652 };
653 self.say(sequence, excluded.worker_id, announcement);
654 }
655 for worker_id in previously_excluded.difference(excluded_now) {
656 // A worker that DEPARTED is not a worker that recovered. The
657 // registry read is the discriminator: an entry no longer in it left
658 // the fleet, and announcing its recovery would be a fabrication.
659 let Some(task_queue) = self.task_queue_of(*worker_id) else {
660 continue;
661 };
662 let Some(announcement) = transition(true, None) else {
663 continue;
664 };
665 self.say_with_queue(sequence, *worker_id, &task_queue, announcement);
666 }
667 }
668
669 /// Emit one announcement, resolving the worker's queue for the line.
670 fn say(&self, sequence: u64, worker_id: WorkerId, announcement: Announcement) {
671 let task_queue = self
672 .task_queue_of(worker_id)
673 .unwrap_or_else(|| "<unregistered>".to_owned());
674 self.say_with_queue(sequence, worker_id, &task_queue, announcement);
675 }
676
677 /// Emit one announcement against an already-resolved queue.
678 fn say_with_queue(
679 &self,
680 sequence: u64,
681 worker_id: WorkerId,
682 task_queue: &str,
683 announcement: Announcement,
684 ) {
685 let transport = self.transport_of(worker_id);
686 match announcement {
687 Announcement::ProbationOpened { answers } => info!(
688 worker_id = worker_id.value(),
689 task_queue,
690 transport,
691 liveness_ping = sequence,
692 answers_banked = answers,
693 answers_required = DISPATCH_PROBATION_PINGS,
694 "worker is SERVING ITS DISPATCH PROBATION: it has answered {answers} of \
695 {DISPATCH_PROBATION_PINGS} consecutive liveness pings since it connected, and is \
696 not selected for dispatch until the run is complete. This is the ordinary cost of \
697 connecting — every healthy worker start passes through it, on every transport — \
698 not a fault, and not a statement that anything is unreachable"
699 ),
700 Announcement::EligibilityWithdrawn => warn!(
701 worker_id = worker_id.value(),
702 task_queue,
703 transport,
704 liveness_ping = sequence,
705 answers_required = DISPATCH_PROBATION_PINGS,
706 silence_window_ms = self.silence_window.as_millis(),
707 "WITHDRAWING DISPATCH ELIGIBILITY from worker: it had PROVED its dispatch path \
708 reachable on this connection and the server can no longer prove it — either a \
709 liveness ping failed or the last proof aged out of the window. It stays \
710 registered and keeps its in-flight work, and becomes eligible again after \
711 {DISPATCH_PROBATION_PINGS} consecutive answered pings"
712 ),
713 Announcement::EligibilityRestored => info!(
714 worker_id = worker_id.value(),
715 task_queue,
716 transport,
717 liveness_ping = sequence,
718 "DISPATCH ELIGIBILITY RESTORED to worker: it has answered a full run of \
719 consecutive liveness pings, so the server can again prove it reaches this \
720 worker's dispatch path. Dispatch selection includes it from now"
721 ),
722 }
723 }
724
725 /// The transport a worker is delivered over, for the announcement line.
726 ///
727 /// `"<unregistered>"` when the worker has left the registry or the registry
728 /// cannot be read — a departed worker's transport is genuinely unknowable
729 /// here, and naming one would be a fabrication.
730 fn transport_of(&self, worker_id: WorkerId) -> &'static str {
731 match self.registry.worker_by_id(worker_id) {
732 Ok(Some(handle)) => handle.delivery().transport().name(),
733 Ok(None) | Err(_) => "<unregistered>",
734 }
735 }
736
737 /// Apply one connection's ping outcome: a correct answer advances dispatch
738 /// reachability, anything else is logged LOUDLY, proves nothing, and RESETS
739 /// the probation — proof of reachability must be a consecutive run.
740 fn apply_answer(
741 &self,
742 pid: u64,
743 worker_id: WorkerId,
744 sequence: u64,
745 outcome: Result<Result<LivenessPong, PingFailure>, tokio::task::JoinError>,
746 ) {
747 let failure = match outcome {
748 Err(join_error) => {
749 PingFailure::Unanswered(format!("ping task failed to run: {join_error}"))
750 }
751 Ok(Err(failure)) => failure,
752 Ok(Ok(pong)) if pong.liveness_pong != sequence => PingFailure::Unanswered(format!(
753 "worker answered with mismatched sequence {}",
754 pong.liveness_pong
755 )),
756 Ok(Ok(_)) => {
757 self.record_reachable(ProbedTransport::Liminal { pid }, worker_id);
758 return;
759 }
760 };
761 self.record_unreachable(
762 ProbedTransport::Liminal { pid },
763 worker_id,
764 sequence,
765 failure,
766 );
767 }
768
769 /// The gRPC counterpart of [`Self::apply_answer`] (#197).
770 ///
771 /// Deliberately the same two outcomes fed into the same two recorders: the
772 /// only gRPC-specific step is that a mismatched echo cannot reach here at
773 /// all, because the correlation registry
774 /// ([`GrpcLivenessWaiters::answer`](super::grpc_liveness::GrpcLivenessWaiters::answer))
775 /// refuses to match one — so an echo that arrives is by construction the
776 /// sequence that was sent.
777 fn apply_grpc_answer(
778 &self,
779 worker_id: WorkerId,
780 sequence: u64,
781 outcome: Result<u64, PingFailure>,
782 ) {
783 match outcome {
784 Ok(echoed) if echoed == sequence => {
785 self.record_reachable(ProbedTransport::Grpc, worker_id);
786 }
787 Ok(echoed) => self.record_unreachable(
788 ProbedTransport::Grpc,
789 worker_id,
790 sequence,
791 PingFailure::Unanswered(format!(
792 "worker answered with mismatched sequence {echoed}"
793 )),
794 ),
795 Err(failure) => {
796 self.record_unreachable(ProbedTransport::Grpc, worker_id, sequence, failure);
797 }
798 }
799 }
800
801 /// Bank one answered ping: the ONE thing that proves the server can reach
802 /// this worker's DISPATCH path.
803 ///
804 /// Only an answer advances reachability — an inbound frame proves the
805 /// opposite direction and cannot stand in for it. A `false` return from the
806 /// tracker means the worker was already deregistered (an answer racing a
807 /// reap); an answer must never resurrect it.
808 fn record_reachable(&self, transport: ProbedTransport, worker_id: WorkerId) {
809 if let Err(error) = self
810 .tracker
811 .record_dispatch_reachability(worker_id, Instant::now())
812 {
813 warn!(
814 %error,
815 connection_pid = transport.pid(),
816 transport = transport.name(),
817 worker_id = worker_id.value(),
818 "failed to record worker dispatch reachability from a liveness answer"
819 );
820 }
821 }
822
823 /// Record one FAILED ping and say which of the two failures it was.
824 ///
825 /// A probation is CONSECUTIVE, so any failure resets it to zero. Without
826 /// this the counter would be cumulative, and a link that answers one probe
827 /// in three would still accrue its way to eligibility and then flap in and
828 /// out of it forever — which is exactly the defect the probation exists to
829 /// stop. Both failure classes reset: whether we could not ask or the worker
830 /// did not answer, the run of answers is broken either way. `Ok(false)`
831 /// means the worker was already deregistered; nothing to reset.
832 fn record_unreachable(
833 &self,
834 transport: ProbedTransport,
835 worker_id: WorkerId,
836 sequence: u64,
837 failure: PingFailure,
838 ) {
839 if let Err(error) = self.tracker.record_dispatch_unreachable(worker_id) {
840 warn!(
841 %error,
842 connection_pid = transport.pid(),
843 transport = transport.name(),
844 worker_id = worker_id.value(),
845 "failed to reset worker dispatch probation after a failed liveness ping; \
846 its eligibility may outlive the proof that earned it"
847 );
848 }
849 // The two failures are DIFFERENT FACTS and the operator must be able to
850 // tell them apart: one is about the worker, the other is about us.
851 let task_queue = self
852 .task_queue_of(worker_id)
853 .unwrap_or_else(|| "<unregistered>".to_owned());
854 let transport_name = transport.name();
855 match failure {
856 PingFailure::Unaskable(reason) => warn!(
857 connection_pid = transport.pid(),
858 transport = transport_name,
859 worker_id = worker_id.value(),
860 task_queue = %task_queue,
861 liveness_ping = sequence,
862 reason = %reason,
863 silence_window_ms = self.silence_window.as_millis(),
864 "THE SERVER COULD NOT ASK this {transport_name} worker for liveness — the push \
865 itself was refused, so nothing was sent and the worker has no idea it was probed. \
866 A dispatch would be refused by the same channel for the same reason. This says \
867 nothing about whether the worker is healthy; it says this server cannot currently \
868 reach it. Its dispatch eligibility is withdrawn NOW and it must answer a full run \
869 of consecutive pings to earn it back"
870 ),
871 PingFailure::Unanswered(reason) => warn!(
872 connection_pid = transport.pid(),
873 transport = transport_name,
874 worker_id = worker_id.value(),
875 task_queue = %task_queue,
876 liveness_ping = sequence,
877 reason = %reason,
878 silence_window_ms = self.silence_window.as_millis(),
879 "{transport_name} worker did not answer its liveness ping; the server could not \
880 prove it can reach this worker's dispatch path, so its dispatch eligibility is \
881 withdrawn NOW and it must answer a full run of consecutive pings to earn it back \
882 — an unanswered probe is direct evidence about the push leg, not mere silence. \
883 NOTE: the worker's connection lease may still be fresh — its liveness pump beats \
884 from a background task and keeps proving the process is alive — so do NOT expect \
885 an expiry sweep to reap it"
886 ),
887 }
888 }
889
890 /// The task queue a worker is registered on, for the WARN line. `None` when
891 /// the worker is no longer in the registry (already reaped).
892 fn task_queue_of(&self, worker_id: WorkerId) -> Option<String> {
893 self.registry
894 .worker_by_id(worker_id)
895 .ok()
896 .flatten()
897 .map(|handle| handle.task_queue().to_owned())
898 }
899}
900
901/// Push one ping and block for its correlated answer, bounded by `deadline`.
902///
903/// Runs on a blocking thread: the liminal push/await pair is thread-based, not
904/// async. Every failure is rendered as a reason string, because at this layer
905/// the distinction that matters is "answered" vs "did not answer" — the typed
906/// error text rides into the WARN verbatim.
907/// A change in one worker's dispatch standing that the operator must be told
908/// about — never the standing state itself, so a persistently excluded worker
909/// does not re-log every cadence.
910#[derive(Clone, Copy, Debug, PartialEq, Eq)]
911enum Announcement {
912 /// A freshly connected worker began serving its probation. Ordinary.
913 ProbationOpened {
914 /// Consecutive answers banked when the probation was announced.
915 answers: u32,
916 },
917 /// A worker that HELD eligibility lost it. An incident.
918 EligibilityWithdrawn,
919 /// A worker that was excluded is dispatchable again.
920 EligibilityRestored,
921}
922
923/// The whole truth table for one worker's standing between two rounds.
924///
925/// Pure and total on purpose: the four inputs are exhaustively enumerated in
926/// the tests, which is the only way to be sure the alarming half and the
927/// reassuring half are both reachable. The old code had no such function — the
928/// decision was inlined and only ever produced one of the three lines, so the
929/// missing two were invisible.
930const fn transition(
931 was_excluded: bool,
932 now_excluded: Option<DispatchExclusion>,
933) -> Option<Announcement> {
934 match (was_excluded, now_excluded) {
935 // Newly excluded. WHICH exclusion decides whether this is news.
936 (false, Some(DispatchExclusion::OpeningProbation { answers })) => {
937 Some(Announcement::ProbationOpened { answers })
938 }
939 (false, Some(DispatchExclusion::ReachabilityLost)) => {
940 Some(Announcement::EligibilityWithdrawn)
941 }
942 // Left the exclusion set: the all-clear.
943 (true, None) => Some(Announcement::EligibilityRestored),
944 // No CHANGE in standing, by either route: a worker still excluded (its
945 // exclusion was announced when it began, and repeating it every cadence
946 // is how a log stops being read), or one that was eligible and stayed
947 // eligible. Both are silence, for different reasons.
948 (true, Some(_)) | (false, None) => None,
949 }
950}
951
952fn ping_one(
953 delivery: &LiminalWorkerDelivery,
954 payload: Vec<u8>,
955 deadline: Duration,
956) -> Result<LivenessPong, PingFailure> {
957 // The deadline is attached to the PUSH, not just to the wait. Without it the
958 // reply slot is reclaimed only by a consumed reply or a connection close, so
959 // abandoning an unanswered ping every cadence leaks one slot per round until
960 // the connection's push cap is exhausted and nothing — ping, dispatch or
961 // intervention — can be pushed to that worker again.
962 let awaiter = delivery
963 .push_payload_with_deadline(payload, deadline)
964 .map_err(|error| PingFailure::Unaskable(error.to_string()))?;
965 let reply = awaiter
966 .receive(deadline)
967 .map_err(|error| PingFailure::Unanswered(format!("no answer arrived: {error}")))?;
968 serde_json::from_slice(&reply)
969 .map_err(|error| PingFailure::Unanswered(format!("answer could not be decoded: {error}")))
970}
971
972#[cfg(test)]
973mod tests {
974 use std::sync::Arc;
975 use std::time::{Duration, Instant};
976
977 use super::super::heartbeat::{DISPATCH_PROBATION_PINGS, HeartbeatTracker};
978 use super::super::liminal_transport::LiminalConnectionNotifier;
979 use super::super::registry::{ConnectedWorkerRegistry, WorkerId};
980 use super::{
981 Announcement, DispatchExclusion, LivenessPing, LivenessPong, LivenessProbe, PingFailure,
982 WorkerTransport, transition,
983 };
984
985 /// The WHOLE truth table, enumerated. Four inputs, and every one of them is
986 /// asserted here — which is the only way to be sure both the alarming and
987 /// the reassuring outcomes are reachable.
988 ///
989 /// The version of this logic that shipped until 2026-08-05 could emit
990 /// exactly one of these lines. The other two were not wrong; they did not
991 /// exist, so an operator saw the withdrawal on every healthy worker start
992 /// and never saw the recovery that followed seconds later.
993 #[test]
994 fn every_standing_change_has_exactly_one_announcement() {
995 assert_eq!(
996 transition(
997 false,
998 Some(DispatchExclusion::OpeningProbation { answers: 1 })
999 ),
1000 Some(Announcement::ProbationOpened { answers: 1 }),
1001 "a fresh connection serving its probation is ORDINARY and must not be announced as a \
1002 worker the server cannot reach"
1003 );
1004 assert_eq!(
1005 transition(false, Some(DispatchExclusion::ReachabilityLost)),
1006 Some(Announcement::EligibilityWithdrawn),
1007 "losing eligibility that was actually held is the incident the WARN exists for"
1008 );
1009 assert_eq!(
1010 transition(true, None),
1011 Some(Announcement::EligibilityRestored),
1012 "the all-clear must be said out loud — an alarm nobody cancels is read as ongoing"
1013 );
1014 assert_eq!(
1015 transition(true, Some(DispatchExclusion::ReachabilityLost)),
1016 None,
1017 "a standing exclusion must not re-log every cadence"
1018 );
1019 assert_eq!(
1020 transition(
1021 true,
1022 Some(DispatchExclusion::OpeningProbation { answers: 0 })
1023 ),
1024 None,
1025 "including while a still-excluded worker is still serving its probation"
1026 );
1027 assert_eq!(
1028 transition(false, None),
1029 None,
1030 "an eligible worker that stayed eligible is not news"
1031 );
1032 }
1033
1034 /// THE WHOLE COVERAGE TABLE, enumerated (#25). Two transports by two
1035 /// wire-holdings, and every cell asserted.
1036 ///
1037 /// Coverage is what decides whether this probe may publish an exclusion for
1038 /// a worker at all, so a cell that silently answered `true` would hand a
1039 /// permanent withdrawal to a fleet the probe has no way to ask — the whole
1040 /// injury. Enumerating it here is the only way to be sure the deny half and
1041 /// the admit half are BOTH reachable: a `covers` that returned `true`
1042 /// unconditionally is exactly the pre-fix behaviour, and it satisfies any
1043 /// test that only checks the admitting direction.
1044 #[test]
1045 fn a_probe_covers_exactly_the_transports_it_holds_a_wire_for() {
1046 let window = Duration::from_secs(30);
1047 let registry = ConnectedWorkerRegistry::default();
1048 let tracker = HeartbeatTracker::new(window);
1049 let notifier = || Arc::new(LiminalConnectionNotifier::new(registry.clone()));
1050 let build = |liminal: bool, grpc: bool| {
1051 LivenessProbe::across_transports(
1052 liminal.then(notifier),
1053 grpc.then(super::GrpcLivenessWaiters::new),
1054 tracker.clone(),
1055 registry.clone(),
1056 window,
1057 )
1058 };
1059
1060 let both = build(true, true);
1061 assert!(both.covers(WorkerTransport::Liminal));
1062 assert!(both.covers(WorkerTransport::Grpc));
1063
1064 let liminal_only = build(true, false);
1065 assert!(liminal_only.covers(WorkerTransport::Liminal));
1066 assert!(
1067 !liminal_only.covers(WorkerTransport::Grpc),
1068 "a probe holding no gRPC answer registry cannot hear a gRPC answer, so it must not \
1069 judge a gRPC worker: the exclusion it would publish could never be lifted"
1070 );
1071
1072 let grpc_only = build(false, true);
1073 assert!(
1074 !grpc_only.covers(WorkerTransport::Liminal),
1075 "and the same in the other direction — the reach follows the wire, not the fleet"
1076 );
1077 assert!(grpc_only.covers(WorkerTransport::Grpc));
1078
1079 // Not constructible in production (the composition root always supplies
1080 // at least the liminal notifier), but the fourth cell of a truth table
1081 // is not optional: a probe with no wire at all judges nobody.
1082 let neither = build(false, false);
1083 assert!(!neither.covers(WorkerTransport::Liminal));
1084 assert!(!neither.covers(WorkerTransport::Grpc));
1085 }
1086
1087 /// The ping/pong pair round-trips with stable field names — the cross-crate
1088 /// wire contract with `aion-worker`'s mirror of these types. A drift here is
1089 /// a wire break, so the exact JSON is pinned.
1090 #[test]
1091 fn the_liveness_pair_round_trips_through_json() -> Result<(), serde_json::Error> {
1092 let ping = LivenessPing {
1093 liveness_ping: 7,
1094 silence_window_ms: 30_000,
1095 };
1096 let encoded = serde_json::to_string(&ping)?;
1097 assert_eq!(encoded, r#"{"liveness_ping":7,"silence_window_ms":30000}"#);
1098 assert_eq!(serde_json::from_str::<LivenessPing>(&encoded)?, ping);
1099
1100 let answer = LivenessPong { liveness_pong: 7 };
1101 let encoded = serde_json::to_string(&answer)?;
1102 assert_eq!(encoded, r#"{"liveness_pong":7}"#);
1103 assert_eq!(serde_json::from_str::<LivenessPong>(&encoded)?, answer);
1104 Ok(())
1105 }
1106
1107 /// A ping decodes as NEITHER of the other two frames that share the push
1108 /// channel, and neither of them decodes as a ping — the demux contract the
1109 /// worker's serve loop relies on.
1110 #[test]
1111 fn a_liveness_ping_is_disjoint_from_the_other_pushed_frames() -> Result<(), serde_json::Error> {
1112 let ping = serde_json::to_vec(&LivenessPing {
1113 liveness_ping: 1,
1114 silence_window_ms: 1_000,
1115 })?;
1116 assert!(
1117 serde_json::from_slice::<super::super::liminal_transport::DispatchRequest>(&ping)
1118 .is_err(),
1119 "a liveness ping must never decode as a dispatch"
1120 );
1121 assert!(
1122 serde_json::from_slice::<super::super::liminal_transport::InterventionRequest>(&ping)
1123 .is_err(),
1124 "a liveness ping must never decode as an intervention"
1125 );
1126 Ok(())
1127 }
1128
1129 /// Both timings derive from the operator's heartbeat window, with no
1130 /// separate knob: the cadence is the sweeper's quarter-window derivation and
1131 /// the declared silence window is the heartbeat window itself.
1132 #[test]
1133 fn probe_timings_derive_from_the_heartbeat_window() {
1134 let window = Duration::from_secs(30);
1135 assert_eq!(super::sweep_interval(window), Duration::from_millis(7_500));
1136 // The declared window IS the operator's window; the cadence divides it,
1137 // so a healthy connection is refreshed four times per window.
1138 assert!(super::sweep_interval(window) * 4 <= window);
1139 }
1140
1141 /// 🔴 THE WIRING PIN. The probation lives in the tracker, but only the probe
1142 /// can tell it a ping FAILED — and a probe that recorded successes and
1143 /// dropped failures would compile, log its WARN lines exactly as it does
1144 /// now, and leave the probation permanently unreset. The eligibility bug
1145 /// would be silently back with every test in `heartbeat` still green,
1146 /// because those tests drive the tracker directly and never go through this
1147 /// seam.
1148 ///
1149 /// Every failure class is asserted individually. The fourth arm — a
1150 /// `JoinError` from the ping task — converges on the same
1151 /// `PingFailure::Unanswered` path these two take, one line above the reset.
1152 #[test]
1153 fn every_failed_probe_class_withdraws_dispatch_eligibility() {
1154 let window = Duration::from_secs(30);
1155 let worker = WorkerId::from_value(1);
1156 let start = Instant::now();
1157
1158 // Each class gets its own probe and its own served probation, so a class
1159 // cannot pass by inheriting the withdrawal an earlier class performed.
1160 let failures = [
1161 (
1162 "the push was refused, so nothing was even asked",
1163 Ok(Err(PingFailure::Unaskable("push refused".to_owned()))),
1164 ),
1165 (
1166 "the ping was sent and no answer came back",
1167 Ok(Err(PingFailure::Unanswered("no answer arrived".to_owned()))),
1168 ),
1169 (
1170 "an answer came back carrying the wrong sequence",
1171 Ok(Ok(LivenessPong { liveness_pong: 99 })),
1172 ),
1173 ];
1174
1175 for (class, outcome) in failures {
1176 let registry = ConnectedWorkerRegistry::default();
1177 let tracker = HeartbeatTracker::new(window);
1178 let probe = LivenessProbe::new(
1179 Arc::new(LiminalConnectionNotifier::new(registry.clone())),
1180 tracker.clone(),
1181 registry,
1182 window,
1183 );
1184
1185 assert!(
1186 tracker.register_connection(worker, start).is_ok(),
1187 "tracker registration must succeed for {class}"
1188 );
1189 for _ in 0..DISPATCH_PROBATION_PINGS {
1190 assert!(
1191 tracker
1192 .record_dispatch_reachability(worker, start)
1193 .is_ok_and(|tracked| tracked),
1194 "the worker serves its probation before {class}"
1195 );
1196 }
1197 assert!(
1198 tracker
1199 .is_dispatch_reachable(worker, start)
1200 .is_ok_and(|reachable| reachable),
1201 "precondition: the worker is eligible before {class}"
1202 );
1203
1204 // Sequence 1 is the ping that was sent; the mismatched-answer case
1205 // deliberately answers 99.
1206 probe.apply_answer(7, worker, 1, outcome);
1207
1208 assert!(
1209 tracker
1210 .is_dispatch_reachable(worker, start)
1211 .is_ok_and(|reachable| !reachable),
1212 "the probe must withdraw dispatch eligibility when {class} — otherwise the \
1213 probation never resets and a one-way link keeps its eligibility forever"
1214 );
1215 }
1216 }
1217
1218 /// The control for the pin above: the SUCCESS path through the same seam
1219 /// must keep eligibility. Without it, a probe that withdrew eligibility on
1220 /// every outcome — including healthy answers — would satisfy every
1221 /// assertion above and strand every worker on the fleet.
1222 #[test]
1223 fn an_answered_probe_keeps_dispatch_eligibility_through_the_same_seam() {
1224 let window = Duration::from_secs(30);
1225 let worker = WorkerId::from_value(1);
1226 let start = Instant::now();
1227 let registry = ConnectedWorkerRegistry::default();
1228 let tracker = HeartbeatTracker::new(window);
1229 let probe = LivenessProbe::new(
1230 Arc::new(LiminalConnectionNotifier::new(registry.clone())),
1231 tracker.clone(),
1232 registry,
1233 window,
1234 );
1235
1236 assert!(tracker.register_connection(worker, start).is_ok());
1237 for sequence in 1..=u64::from(DISPATCH_PROBATION_PINGS) {
1238 probe.apply_answer(
1239 7,
1240 worker,
1241 sequence,
1242 Ok(Ok(LivenessPong {
1243 liveness_pong: sequence,
1244 })),
1245 );
1246 }
1247
1248 assert!(
1249 tracker
1250 .is_dispatch_reachable(worker, start)
1251 .is_ok_and(|reachable| reachable),
1252 "answered probes must EARN eligibility through the probe seam, not merely fail to \
1253 withdraw it"
1254 );
1255 }
1256}