Skip to main content

cortex/dispatcher/
ventilator.rs

1use std::collections::HashMap;
2use std::io::Read;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::mpsc::SyncSender;
6use std::time::Duration;
7
8use crate::backend;
9use crate::dispatcher::prefetch::Prefetcher;
10use crate::dispatcher::server;
11use crate::helpers;
12use crate::helpers::{TaskProgress, TaskReport};
13use crate::models::WorkerMetadataSender;
14use std::error::Error;
15use tracing::{debug, info, trace, warn};
16use zmq::SNDMORE;
17
18/// Specifies the binding and operation parameters for a ZMQ ventilator component
19pub struct Ventilator {
20  /// port to listen on
21  pub port: usize,
22  /// the size of the dispatch queue
23  /// (also the batch size for Task store queue requests)
24  pub queue_size: usize,
25  /// size of an individual message chunk sent via zeromq
26  /// (keep this small to avoid large RAM use, increase to reduce network bandwidth)
27  pub message_size: usize,
28  /// address for the Task store postgres endpoint
29  pub backend_address: String,
30  /// backpressure threshold: stop leasing new work once this many tasks are in-flight
31  /// (dispatched-but-unfinished), so the in-flight set drains via the sink instead of growing
32  /// toward the hard panic bound (KNOWN_ISSUES D-6)
33  pub max_in_flight: usize,
34  /// non-blocking handle to the background worker-metadata writer
35  pub metadata: WorkerMetadataSender,
36}
37
38impl Ventilator {
39  /// Starts a new dispatch `Server` (ZMQ Ventilator), to serve tasks to processing workers.
40  /// The ventilator shares state with other manager threads via queues for tasks in progress,
41  /// as well as a queue for completed tasks pending persisting to disk.
42  /// A job limit can be provided as a termination condition for the sink server.
43  ///
44  /// Upon premature termination, returns the number of tasks processed.
45  pub fn start(
46    &self,
47    services_arc: &Arc<server::ServiceCache>,
48    sandboxes_arc: &Arc<server::SandboxCache>,
49    progress_queue_arc: &Arc<server::InFlightSet>,
50    done_tx: &SyncSender<TaskReport>,
51    job_limit: Option<usize>,
52    dispatch_complete: &Arc<AtomicBool>,
53  ) -> Result<usize, Box<dyn Error>> {
54    // We have a Ventilator-exclusive "queues" stack of tasks to be dispatched, keyed by service id
55    // so a reaped task is always re-queued to its own service (not whichever service is
56    // requesting).
57    let mut queues: HashMap<i32, Vec<TaskProgress>> = HashMap::new();
58    // Recover leftover Queued tasks from a previously-crashed run — but NOT the ones currently in
59    // flight. On a ventilator *restart* (KNOWN_ISSUES D-4) the sink is still processing dispatched
60    // tasks held in `progress_queue`; resetting those to TODO would re-lease them while their
61    // original results are still pending (a double-dispatch). On first start `progress_queue` is
62    // empty, so this recovers all leftover Queued tasks exactly as before.
63    let mut backend = backend::from_address(&self.backend_address);
64    let in_flight_ids: Vec<i64> = progress_queue_arc.ids();
65    backend.clear_limbo_tasks_except(&in_flight_ids)?;
66    // Ok, let's bind to a port and start broadcasting
67    let context = zmq::Context::new();
68    let ventilator = context.socket(zmq::ROUTER)?;
69    ventilator.set_router_handover(true)?;
70    // Fail LOUD, not silent, when a reply can't be routed (KNOWN_ISSUES D-22). A ZMQ `ROUTER`
71    // *silently discards* a message addressed to an identity it can't route unless
72    // `ZMQ_ROUTER_MANDATORY` is set — so a worker that vanished between its request and our reply
73    // used to swallow the whole dispatch with no error, stranding the (already-leased) task until
74    // the lease reaper reclaimed it 240s+ later, with zero observability (exactly what
75    // DESIGN_PRINCIPLES forbids). With mandatory set, an unroutable send returns `EHOSTUNREACH`
76    // instead, which every routing-frame send below catches → logs, counts, and skips. Note the
77    // libzmq contract this relies on (verified empirically 2026-07-20): only the *routing*
78    // (first) frame reports `EHOSTUNREACH`; a rejected routing frame is NOT started as a
79    // multipart, so skipping the reply's remaining frames leaves the socket cleanly at
80    // message-start (no desync). Body frames after a *successful* routing frame never surface it
81    // (a peer dying mid-stream drops silently, and the task is already recorded in-flight for the
82    // reaper — see the ordering note further down). The reverted first attempt (D-22 history)
83    // crashed not from desync but from letting `EHOSTUNREACH` propagate via `?` on the *unguarded*
84    // mock-reply routing sends; guarding all three sites below is the fix.
85    ventilator.set_router_mandatory(true)?;
86    // Keep idle remote-worker connections alive across NAT/firewall idle-timeouts (set before bind
87    // so accepted connections inherit it). Correctness is the reaper's job, not keepalive's.
88    server::apply_tcp_keepalive(
89      &ventilator,
90      crate::config::config()
91        .dispatcher
92        .tcp_keepalive_idle_seconds,
93    )?;
94
95    let address = format!("tcp://*:{}", self.port);
96    // Propagate a bind failure (e.g. `EADDRINUSE` when the port is still held by a just-restarted
97    // dispatcher in TIME_WAIT, or a second instance) instead of an opaque `.unwrap()` panic — same
98    // fail-fast (the manager aborts the thread → external restart), but with a diagnosable cause
99    // and consistent with every other fallible call here + the sink's bind (KNOWN_ISSUES
100    // robustness: no bare `unwrap` on the dispatch path).
101    // Retry the bind: on a restart the port can sit in TCP TIME_WAIT held by the
102    // previous dispatcher's closed connections. That lasts ~`tcp_fin_timeout` (60s on
103    // Linux by default), NOT "a second or two" — so a short retry window crash-loops the
104    // new process on EADDRINUSE the whole time TIME_WAIT persists (observed 2026-07-01: a
105    // 7.5s / 15-attempt window kept failing on the sink port through the full 60s TIME_WAIT,
106    // systemd hit its start-limit and gave up). Size the window to comfortably OUTLAST
107    // TIME_WAIT (75s > 60s + margin) so a normal restart self-heals without operator action;
108    // a genuinely-occupied port still fails (with a diagnosable cause → manager aborts →
109    // external restart), just after the full window.
110    {
111      // 150 * 500ms = 75s > tcp_fin_timeout (60s) TIME_WAIT, with margin.
112      const BIND_ATTEMPTS: u32 = 150;
113      let mut attempt = 1u32;
114      loop {
115        match ventilator.bind(&address) {
116          Ok(()) => break,
117          Err(e) if attempt < BIND_ATTEMPTS => {
118            warn!(
119              "ventilator: bind {address} attempt {attempt}/{BIND_ATTEMPTS} failed ({e}); \
120               retrying in 500ms (port handover from a restarting dispatcher?)"
121            );
122            std::thread::sleep(Duration::from_millis(500));
123            attempt += 1;
124          },
125          Err(e) => {
126            return Err(
127              std::io::Error::other(format!(
128                "ventilator: zeromq bind {address} failed after {BIND_ATTEMPTS} attempts: {e}"
129              ))
130              .into(),
131            );
132          },
133        }
134      }
135    }
136    // Wake the blocking `recv` periodically instead of blocking forever when idle, so the
137    // graceful-shutdown flag (checked at the top of the loop) is observed promptly even with no
138    // worker traffic. Without this an idle ventilator blocks in `recv` until the supervisor's
139    // stop-timeout SIGKILL — the ~120s `systemctl restart` hang (KNOWN_ISSUES D-15). 250ms matches
140    // the sink's termination poll; the only cost is one no-op wakeup per quarter-second while idle.
141    ventilator.set_rcvtimeo(250)?;
142    let mut source_job_count: usize = 0;
143    // Count of *fresh* tasks actually leased to a worker (a `retries == 0` lease), as distinct from
144    // `source_job_count` which counts every request — including the mock-replies (unknown service,
145    // backpressure, momentary-empty-queue). A bounded run (`job_limit = Some(N)`) terminates on N
146    // **real dispatches**, not N requests: the unit mismatch — three threads counting `job_limit`
147    // in three incompatible units — was the KNOWN_ISSUES D-5 lockstep-termination hang.
148    let mut real_dispatched: usize = 0;
149    // Reap timed-out in-flight tasks on a cadence rather than only on refetch (KNOWN_ISSUES D-6),
150    // so the in-flight set drains even under sustained backpressure (when refetch never runs). The
151    // cadence is runtime-configurable (`dispatcher.reap_interval_seconds`, default 60s — well below
152    // the lease timeout, so an expired task is recovered promptly without scanning on every
153    // request).
154    let reap_interval_secs = crate::config::config().dispatcher.reap_interval_seconds;
155    let mut last_reap_sec = chrono::Utc::now().timestamp();
156    // Rate-limited logging for discarded requests (malformed framing, unknown service names). A
157    // sustained malformed-request flood must not turn per-message `stderr` writes into a
158    // throughput-DoS (KNOWN_ISSUES D-11) — count, don't narrate.
159    let mut discard_log = server::RateLimitedLog::new(Duration::from_secs(5));
160    // Rate-limited logging for dispatches/replies dropped because the worker was unroutable at send
161    // time (D-22). A dying-worker or restart storm can make this fire per-request, so aggregate it
162    // (like `discard_log`) — count, don't narrate — so it can never become a throughput-DoS (D-11).
163    let mut unroutable_log = server::RateLimitedLog::new(Duration::from_secs(5));
164
165    // Input-archive prefetcher (D-20): warm each fetched batch's archives into the OS page cache
166    // ahead of dispatch, so the inline `/data` read below is served from RAM (~0.02 ms) instead of
167    // the cold QLC-RAID6 platter (~10 ms — the single-thread dispatch ceiling at full-arXiv scale).
168    // A no-op when `input_prefetchers = 0`; the read path stays byte-for-byte unchanged. Each
169    // warmer's channel is sized to a full batch so the round-robin feed never drops within one.
170    let dispatcher_cfg = &crate::config::config().dispatcher;
171    let prefetcher = Prefetcher::new(
172      dispatcher_cfg.input_prefetchers,
173      self.queue_size,
174      dispatcher_cfg.prefetch_max_entry_mb * 1024 * 1024,
175      dispatcher_cfg.prefetch_budget_mb * 1024 * 1024,
176    );
177
178    loop {
179      // Graceful shutdown (O-1): a SIGTERM/SIGINT set the flag. Stop leasing new work, signal
180      // completion (so the sink drains the in-flight set and finalize flushes its last batch), and
181      // return cleanly — the manager then takes the drain path instead of restarting us. Reached on
182      // the next loop iteration; the recv below polls on a 250ms `RCVTIMEO`, so even a *fully idle*
183      // dispatcher (no worker requests to cycle the loop) observes the flag within ~250ms and stops
184      // promptly — no waiting out the supervisor's stop timeout (KNOWN_ISSUES D-15).
185      if server::shutdown_requested() {
186        info!(
187          "ventilator: graceful shutdown requested — ceasing to lease; the sink will drain in-flight work"
188        );
189        dispatch_complete.store(true, Ordering::SeqCst);
190        return Ok(real_dispatched);
191      }
192      // Reap timed-out in-flight tasks on a **wall-clock** cadence, decoupled from worker request
193      // traffic (D-19). Runs at the top of every loop iteration — including the idle ~250ms
194      // RCVTIMEO ticks below — so an expired task is requeued/dead-lettered within
195      // ~`reap_interval` even at a fully idle tail (e.g. D-18-deferred empty results awaiting
196      // retry after the fleet drained), not just when a worker next happens to ask for work.
197      // The `reap_interval` gate keeps the actual scan to its cadence; the per-iteration
198      // timestamp compare is cheap. Routes each expired task back to its own service's queue
199      // or reports it Fatal, so the in-flight set drains even while saturated (backpressure)
200      // — closes the D-6 reaping-coupling residual.
201      let now_sec = chrono::Utc::now().timestamp();
202      if now_sec - last_reap_sec >= reap_interval_secs {
203        last_reap_sec = now_sec;
204        let reaped = server::reap_expired_into(&mut queues, progress_queue_arc, done_tx);
205        // Health signal (Arm 8 observability; transport-independent): the in-flight gauge plus the
206        // re-lease / dead-letter counts for this reaping pass. Only logged when something actually
207        // timed out (the cadence is otherwise quiet), at `info` because a dead-letter is a task we
208        // gave up on — an operator-relevant event.
209        if reaped.requeued + reaped.dead_lettered > 0 {
210          info!(
211            in_flight = progress_queue_arc.len(),
212            requeued = reaped.requeued,
213            dead_lettered = reaped.dead_lettered,
214            "dispatcher: reaped timed-out in-flight tasks"
215          );
216        }
217      }
218      let mut identity = zmq::Message::new();
219      let mut msg = zmq::Message::new();
220      // A worker request is exactly `[identity, service_name]` on the ROUTER: the DEALER worker
221      // sends a single service-name frame and ROUTER prepends its identity. Read with strict
222      // multipart-framing discipline so a malformed / empty / over-long request cannot desync the
223      // message boundary and *permanently shuffle* every later request — the rare "3 adjacent empty
224      // messages" failure seen in 08.2025 sandbox testing (KNOWN_ISSUES D-4). The previous code
225      // read a second frame unconditionally, so a truncated `[identity]`-only message made it
226      // read the *next* request's identity as this request's service (the shuffle), and
227      // bailed the whole ventilator on the both-empty case (a restart band-aid). Instead:
228      // require the service frame via `RCVMORE` before reading it (never read across a
229      // message boundary), drain any unexpected trailing frames to stay aligned, and *skip* a
230      // malformed request rather than restarting. This mirrors the sink's `[identity,
231      // service, taskid, …]` envelope hardening.
232      match ventilator.recv(&mut identity, 0) {
233        Ok(()) => {},
234        // RCVTIMEO elapsed with no request — loop back to re-check the shutdown flag and run the
235        // wall-clock reap at the top of the loop (D-15 + D-19: an idle ventilator both stops within
236        // ~250ms of SIGTERM and keeps reaping expired in-flight tasks).
237        Err(zmq::Error::EAGAIN) => continue,
238        Err(e) => return Err(e.into()),
239      }
240      if !ventilator.get_rcvmore().unwrap_or(false) {
241        // `[identity]` with no service frame — truncated. Skipping consumes nothing further, so the
242        // next request's frames are left intact (no desync).
243        if let Some(n) = discard_log.record() {
244          warn!(
245            "ventilator: discarded {n} malformed request(s) [latest: truncated, no service frame] (rate-limited)"
246          );
247        }
248        continue;
249      }
250      ventilator.recv(&mut msg, 0)?;
251      // A well-formed request ends at the service frame; drain anything beyond it (an over-long /
252      // malformed request) so it can't bleed into the next request — frame-alignment is exactly
253      // what D-4 lost.
254      while ventilator.get_rcvmore().unwrap_or(false) {
255        let mut extra = zmq::Message::new();
256        if ventilator.recv(&mut extra, 0).is_err() {
257          break;
258        }
259      }
260      let identity_str = identity.as_str().unwrap_or_default().to_string();
261      let service_name = msg.as_str().unwrap_or_default().to_string();
262      if service_name.is_empty() {
263        // Empty service request (e.g. the "3 adjacent empty messages") — skip without desyncing.
264        if let Some(n) = discard_log.record() {
265          warn!(
266            "ventilator: discarded {n} malformed request(s) [latest: empty service from {identity_str:?}] (rate-limited)"
267          );
268        }
269        continue;
270      }
271
272      let request_time = chrono::Utc::now();
273      source_job_count += 1;
274      // Whether this iteration actually leased a task to the worker (vs. a mock-reply). Drives the
275      // bounded-run source-drain check at the bottom of the loop.
276      let mut dispatched_this_iter = false;
277      // (Reaping happens at the loop top now, on a wall-clock cadence — see D-19 above.)
278      // Requests for unknown service names will be silently ignored.
279      let service_opt = match server::get_sync_service(&service_name, services_arc, &mut backend) {
280        Some(s) => Some(s),
281        None => {
282          // An unknown service name is now handled gracefully — mock-reply so the (mis)configured
283          // worker backs off — rather than the old fatal desync (the request framing is robust now,
284          // D-4). Rate-limit the log so a flood of bad-service requests can't DoS us (D-11).
285          if let Some(n) = discard_log.record() {
286            warn!(
287              "ventilator: discarded {n} request(s) [latest: unknown service {service_name:?} from {identity_str:?}, mock-replied] (rate-limited)"
288            );
289          }
290          if !route_worker_frame(&ventilator, identity, &identity_str, &mut unroutable_log)? {
291            continue;
292          }
293          ventilator.send("0", SNDMORE)?;
294          ventilator.send(Vec::new(), 0)?;
295          continue;
296        },
297      };
298      if let Some(service) = service_opt {
299        // Backpressure (KNOWN_ISSUES D-6, principle #4): if the in-flight set is saturated, don't
300        // lease more work — mock-reply so the worker backs off and retries. The set then drains as
301        // the sink receives results, instead of growing toward the hard panic bound. Degrade
302        // gracefully under overload rather than crash.
303        if server::in_flight_saturated(progress_queue_arc.len(), self.max_in_flight) {
304          debug!(
305            in_flight_cap = self.max_in_flight,
306            worker = %identity_str,
307            "BACKPRESSURE: in-flight set at capacity; mock-replying to worker"
308          );
309          if !route_worker_frame(&ventilator, identity, &identity_str, &mut unroutable_log)? {
310            continue;
311          }
312          ventilator.send("0", SNDMORE)?;
313          ventilator.send(Vec::new(), 0)?;
314          continue;
315        }
316        let task_queue: &mut Vec<TaskProgress> = queues.entry(service.id).or_default();
317        if task_queue.is_empty() {
318          debug!(
319            "No tasks in task queue for service {:?}, fetching up to {:?} more from backend...",
320            service_name, self.queue_size
321          );
322          // Refetch a new batch of tasks
323          let now = chrono::Utc::now().timestamp();
324          let fetched_tasks = backend
325            .fetch_tasks(&service, self.queue_size)
326            .unwrap_or_default();
327          // D-20: warm this batch's input archives into page cache in DISPATCH order. `task_queue`
328          // is popped LIFO (from the end after the `extend` below), so the batch is dispatched in
329          // reverse of fetch order — feed reversed so the next-to-dispatch archives warm first.
330          // No-op when prefetching is disabled.
331          prefetcher.warm_batch(fetched_tasks.iter().rev().map(|task| task.entry.clone()));
332          // D-17: capture the effective lease for THIS service — its `lease_timeout_seconds`
333          // override, else the global dispatcher default — at dispatch time. `expected_at` uses the
334          // captured value, so one dispatcher serves fast (latexml-oxide) and slow (Perl) services
335          // with the right lease each, and a later config change never re-times an in-flight task.
336          let lease = service
337            .lease_timeout_seconds
338            .map(i64::from)
339            .unwrap_or_else(|| crate::config::config().dispatcher.lease_timeout_seconds);
340          task_queue.extend(fetched_tasks.into_iter().map(|task| TaskProgress {
341            task,
342            created_at: now,
343            retries: 0,
344            lease_timeout_seconds: lease,
345          }));
346        }
347
348        // Routing frame under ROUTER_MANDATORY, sent BEFORE the lease (the `pop()` below): if the
349        // worker vanished between its request and now, `EHOSTUNREACH` is caught here having leased
350        // nothing, so the task stays queued for the next worker — no strand, no reaper wait (D-22).
351        if !route_worker_frame(&ventilator, identity, &identity_str, &mut unroutable_log)? {
352          continue;
353        }
354        if let Some(current_task_progress) = task_queue.pop() {
355          dispatched_this_iter = true;
356          // A `retries == 0` task is entering the pipeline for the first time; a re-leased task
357          // (retries > 0, from the reaper requeue) was already counted on its first dispatch, so
358          // only fresh leases advance the bounded-run target — keeping `real_dispatched` a true
359          // unique-task count that finalize can eventually match.
360          if current_task_progress.retries == 0 {
361            real_dispatched += 1;
362          }
363          // Record the dispatch in the in-flight set BEFORE streaming the payload to the worker. A
364          // fast worker (e.g. echo) can return its result to the sink before this iteration even
365          // finishes; if the task were recorded only *after* the send (as it was), the sink's
366          // `pop_progress_task` could miss it and discard the result, stranding the task `Queued`
367          // until the ≥1h visibility-timeout reaper — the single-task-loss race that surfaced under
368          // NOTE (D-21, 2026-07-20): two caveats on the citation above. (1) DISPATCHER_BENCH.md
369          // attributes that 8-worker loss to **D-10**, not D-4 — this reference is stale. (2) The
370          // bench harness that produced it gave all N worker threads ONE shared ZMQ identity
371          // (D-21), which was never controlled for. The ordering fix below is not in doubt — it
372          // held for 18 consecutive clean runs at the previously-failing concurrencies — but the
373          // two defects coexisted, so read that bench number as D-10 plus an uncontrolled D-21
374          // component, not as clean proof of this race alone.
375          // higher worker concurrency (KNOWN_ISSUES D-4 / docs/DISPATCHER_BENCH.md 8-worker loss).
376          // Recording first also leaves a mid-stream send failure correctly in-flight for the
377          // reaper.
378          progress_queue_arc.insert(current_task_progress.clone());
379
380          let current_task = current_task_progress.task;
381          let mut taskid = current_task.id;
382          let serviceid = current_task.service_id;
383          // Memoise this task's corpus → sandbox id now, before the payload is sent (so before the
384          // result can return), so the sink scopes the result archive without its own DB hit (F-6).
385          server::get_sync_sandbox_id(current_task.corpus_id, sandboxes_arc, &mut backend);
386          trace!(
387            job = source_job_count,
388            worker = %identity_str,
389            task_id = taskid,
390            "ventilator: worker received task"
391          );
392          ventilator.send(&taskid.to_string(), SNDMORE)?;
393          if serviceid == 1 {
394            // No payload needed for init
395            ventilator.send(Vec::new(), 0)?;
396          } else {
397            // Regular services fetch the task payload and transfer it to the worker
398            let file_opt = helpers::prepare_input_stream(&current_task);
399            if file_opt.is_ok() {
400              let mut file = file_opt?;
401              let mut total_outgoing: usize = 0;
402              loop {
403                // Stream input data via zmq
404                let mut data = vec![0; self.message_size];
405                let size = file.read(&mut data)?;
406                total_outgoing += size;
407                data.truncate(size);
408
409                if size < self.message_size {
410                  // If exhausted, send the last frame
411                  ventilator.send(&data, 0)?;
412                  // And terminate
413                  break;
414                } else {
415                  // If more to go, send the frame and indicate there's more to come
416                  ventilator.send(&data, SNDMORE)?;
417                }
418              }
419              let responded_time = chrono::Utc::now();
420              let request_duration = (responded_time - request_time).num_milliseconds();
421              trace!(
422                job = source_job_count,
423                task_id = taskid,
424                bytes = total_outgoing,
425                took_ms = request_duration,
426                "ventilator: streamed task payload to worker"
427              );
428            } else {
429              warn!(
430                task_id = taskid,
431                "ventilator: failed to prepare input stream for task"
432              );
433              debug!(task_id = taskid, "task details: {current_task:?}");
434              taskid = -1;
435              ventilator.send(Vec::new(), 0)?;
436            }
437          }
438          // A real task was leased — count it as a dispatch (drives total_dispatched /
439          // outstanding).
440          self.metadata.dispatched(identity_str, service.id, taskid);
441        } else {
442          trace!(
443            job = source_job_count,
444            worker = %identity_str,
445            "ventilator: worker received mock reply"
446          );
447          ventilator.send("0", SNDMORE)?;
448          ventilator.send(Vec::new(), 0)?;
449          // An empty-queue ping leased no task: record a liveness heartbeat (refreshes the worker's
450          // "last dispatch requested" time so an idle-but-alive poller still reads as fresh) but do
451          // NOT bump the dispatch tally. Counting these is what made a fully-drained corpus's idle
452          // pollers accrue phantom "outstanding" forever — total_dispatched meant "replies sent",
453          // not "tasks leased" (the 17k-outstanding /workers confusion).
454          self.metadata.heartbeat(identity_str, service.id);
455        }
456      } else {
457        warn!(
458          service = %service_name,
459          worker = %identity_str,
460          "ventilator: request for unknown service"
461        );
462      }
463      if let Some(limit_number) = job_limit {
464        // Bounded run terminates on N *real* dispatches (not N requests). Publish the shared
465        // completion signal so the sink (which then drains the in-flight set) and finalize (which
466        // the manager disconnects) agree on "done" — one condition instead of the three
467        // incompatible per-thread counters that used to deadlock (KNOWN_ISSUES D-5).
468        if real_dispatched >= limit_number {
469          info!(
470            "vent: bounded job limit ({limit_number}) reached after {real_dispatched} real dispatch(es); terminating ventilator"
471          );
472          dispatch_complete.store(true, Ordering::Release);
473          return Ok(real_dispatched);
474        }
475        // Source-drain: this iteration leased nothing (the queue was empty after a refetch) and no
476        // task is still in flight, so there is genuinely no more work to dispatch — stop rather
477        // than mock-reply forever toward an unreachable limit (the owner-noted "empty-queue
478        // mock-replies forever" gap). The in-flight-empty guard prevents terminating while
479        // results are still pending; it is exact for the single-service bounded runs
480        // `job_limit` is used for (a multi-service bounded run could drain one service
481        // early — acceptable, benchmark-only).
482        if !dispatched_this_iter && progress_queue_arc.is_empty() {
483          info!(
484            "vent: source exhausted after {real_dispatched} dispatch(es) (< limit {limit_number}); terminating ventilator"
485          );
486          dispatch_complete.store(true, Ordering::Release);
487          return Ok(real_dispatched);
488        }
489      }
490    }
491  }
492}
493
494/// Send the ROUTER routing (identity) frame for a worker reply under `ZMQ_ROUTER_MANDATORY`
495/// (KNOWN_ISSUES D-22). Returns `Ok(true)` when the worker routed and the caller may stream the
496/// rest of the reply; `Ok(false)` when the worker was unroutable (`EHOSTUNREACH`) — the caller MUST
497/// emit nothing further for this reply and `continue`. A rejected routing frame is never *started*
498/// as a multipart (verified empirically against libzmq 4.3.5), so skipping the reply's remaining
499/// frames leaves the socket cleanly aligned at message-start — no desync. The drop is counted and
500/// rate-limit-logged here so it is never silent (the D-22 gap DESIGN_PRINCIPLES forbids) and never
501/// a per-request log-DoS (D-11). Any *other* send error is a genuine fault and propagates
502/// (fail-fast → manager aborts the thread → external restart), consistent with the rest of the
503/// dispatch loop.
504fn route_worker_frame(
505  sock: &zmq::Socket,
506  identity: zmq::Message,
507  identity_str: &str,
508  unroutable_log: &mut server::RateLimitedLog,
509) -> Result<bool, zmq::Error> {
510  match sock.send(identity, SNDMORE) {
511    Ok(()) => Ok(true),
512    Err(zmq::Error::EHOSTUNREACH) => {
513      if let Some(n) = unroutable_log.record() {
514        warn!(
515          "ventilator: {n} reply/dispatch(es) dropped — worker unroutable at send time \
516           (EHOSTUNREACH) [latest: {identity_str:?}]; no work lost, task stays queued (rate-limited)"
517        );
518      }
519      Ok(false)
520    },
521    Err(e) => Err(e),
522  }
523}