Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ingestion-consumer): report batcher requests and load on the debug API (#118372)

José Sequeirafdc764b33484
diff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.md
index 5396cd923050..3f0f8963cda7 100644
--- a/rust/ingestion-consumer/README.md
+++ b/rust/ingestion-consumer/README.md
@@ -84,9 +84,11 @@ Set `DEBUG_API_ENABLED=true` **and** `DEBUG_API_SECRET` to mount a real-time deb
Every request must present the secret as `X-Debug-Api-Secret`; enabling without a secret fails closed (nothing is mounted).
The secret is dedicated to this control-plane→consumer hop — deliberately not `INTERNAL_API_SECRET` (see `.agents/security.md`).
The ingestion control plane UI consumes these endpoints to render the consumer's live state.
-`debug_recorder.rs` keeps a bounded in-memory buffer of structured lifecycle events (batch dispatch, commit and failure, worker health and membership), recorded at the same points that emit metrics, and it never influences routing.
+`debug_recorder.rs` keeps a bounded in-memory buffer of structured lifecycle events, recorded at the same points that emit metrics, and it never influences routing: poll dispatch, commit and failure; every request the batcher sends (`RequestSent`) and how it settled (`RequestResolved`, with the unfinished count of a partial ack, or `RequestFailed` with its cause); worker health and membership.
+A poll and a request both carry their assignment epoch and their offsets per topic-partition as runs of consecutive offsets, which is how the control plane UI matches a request to exactly the polls it carries, because a request can merge messages from several polls.
+Routing keys never enter the payload, because they hold distinct ids.
-- `/debug/load` — cheap JSON snapshot (worker health + the batcher's in-flight and pending counts), safe to poll fast.
+- `/debug/load` — cheap JSON snapshot (worker health with each worker's in-flight requests and messages, plus the batcher's key-table counts), safe to poll fast. The batcher task answers the snapshot itself between two actions, so the hot path pays nothing when nobody asks; a task that does not answer within a second yields only the totals it last published.
- `/debug/state` — the same plus the retained event backlog.
- `/debug/events` — SSE stream: backlog replay, then live events (concurrent subscribers capped at 8; 429 beyond).
diff --git a/rust/ingestion-consumer/src/batcher/driver.rs b/rust/ingestion-consumer/src/batcher/driver.rs
index 3fb98ad88d9a..d894caedd9a0 100644
--- a/rust/ingestion-consumer/src/batcher/driver.rs
+++ b/rust/ingestion-consumer/src/batcher/driver.rs
@@ -1,29 +1,36 @@
//! Runs the batcher state machine on one task and performs its effects.
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
-use std::time::Instant;
+use std::time::{Duration, Instant};
use common_kafka_consumer::{AssignmentEpoch, GroupCompletion};
use futures::future::{BoxFuture, FutureExt};
use futures::stream::{FuturesUnordered, StreamExt};
use metrics::{counter, histogram};
-use tokio::sync::mpsc;
+use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tracing::error;
use super::in_flight::RequestId;
-use super::key_queues::KeyRun;
-use super::state_machine::{BatcherStateMachine, Effects, FailureCause, SendRequest};
+use super::key_queues::{payload_bytes, KeyRun};
+use super::state_machine::{
+ BatcherSnapshot, BatcherStateMachine, Effects, FailureCause, SendRequest,
+};
use super::worker_pool::WorkerPoolSource;
use super::{make_batch_id, BatcherOutputs};
+use crate::debug_recorder::{partition_offsets, record_if, DebugEventKind, DebugRecorder};
use crate::grpc_transport::{GrpcTransport, SendOptions};
use crate::order_sentinel::{KeyOrderSentinel, SendKind, SentinelBatch};
use crate::transport::{SendError, SendOutcome};
use crate::types::{Accumulator, SerializedKafkaMessage};
use crate::worker_registry::WorkerId;
+/// A task that does not answer within this is wedged; the debug API then
+/// falls back to the totals the task last published.
+const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(1);
+
pub(super) struct StateMachineDriver {
inputs: mpsc::UnboundedSender<Input>,
assignment_epoch: AssignmentEpoch,
@@ -39,6 +46,8 @@ enum Input {
},
PartitionsRevoked(Vec<(String, i32)>),
Shutdown,
+ /// Answered between two actions, so the snapshot is consistent.
+ Snapshot(oneshot::Sender<BatcherSnapshot>),
}
#[derive(Debug, Default)]
@@ -50,6 +59,21 @@ pub(super) struct Load {
pub(super) struct RevokeSender(mpsc::UnboundedSender<Input>);
+#[derive(Clone)]
+pub(super) struct SnapshotSender(mpsc::UnboundedSender<Input>);
+
+impl SnapshotSender {
+ /// `None` when the task is gone or does not answer in time.
+ pub(super) async fn snapshot(&self) -> Option<BatcherSnapshot> {
+ let (reply, response) = oneshot::channel();
+ self.0.send(Input::Snapshot(reply)).ok()?;
+ tokio::time::timeout(SNAPSHOT_TIMEOUT, response)
+ .await
+ .ok()?
+ .ok()
+ }
+}
+
pub(super) trait RequestSender: Send + Sync + 'static {
fn assignment_epoch(&self) -> AssignmentEpoch;
@@ -116,6 +140,9 @@ struct BatcherTask<S, W> {
completions: mpsc::UnboundedSender<GroupCompletion>,
errors: mpsc::UnboundedSender<String>,
load: Arc<Load>,
+ recorder: Option<Arc<DebugRecorder>>,
+ /// The worker of each request sent while a recorder is present.
+ debug_requests: HashMap<RequestId, WorkerId>,
}
enum Event {
@@ -129,6 +156,7 @@ impl StateMachineDriver {
state: BatcherStateMachine,
workers: W,
sender: Arc<S>,
+ recorder: Option<Arc<DebugRecorder>>,
) -> (Self, BatcherOutputs) {
let (inputs_tx, inputs_rx) = mpsc::unbounded_channel();
let (completions_tx, completions_rx) = mpsc::unbounded_channel();
@@ -146,6 +174,8 @@ impl StateMachineDriver {
completions: completions_tx,
errors: errors_tx,
load: Arc::clone(&load),
+ recorder,
+ debug_requests: HashMap::new(),
};
let task = tokio::spawn(task.run(state));
(
@@ -175,6 +205,10 @@ impl StateMachineDriver {
RevokeSender(self.inputs.clone())
}
+ pub(super) fn snapshot_sender(&self) -> SnapshotSender {
+ SnapshotSender(self.inputs.clone())
+ }
+
pub(super) fn submit(&self, accumulator: Accumulator) -> u64 {
let assignment_epoch = self.assignment_epoch.current();
let runs = KeyRun::from_groups(accumulator.into_groups());
@@ -243,6 +277,14 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
}
fn handle(&mut self, state: BatcherStateMachine, event: Event) -> BatcherStateMachine {
+ // A snapshot changes nothing and must not replace the pending wakeup.
+ let event = match event {
+ Event::Input(Input::Snapshot(reply)) => {
+ let _ = reply.send(state.snapshot());
+ return state;
+ }
+ event => event,
+ };
// Read through tokio, so tests on paused time control the clock.
let now = tokio::time::Instant::now().into_std();
let mut assigned = false;
@@ -261,7 +303,9 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
state.on_partitions_revoked(now, &partitions)
}
Event::Input(Input::Shutdown) => state.on_shutdown(now, &self.workers.candidates()),
+ Event::Input(Input::Snapshot(_)) => unreachable!("answered above"),
Event::Response(request, Ok(SendOutcome::Accepted(accepted))) => {
+ self.record_resolved(request, accepted, 0);
state.on_request_succeeded(now, &self.workers.candidates(), request, accepted)
}
Event::Response(
@@ -270,13 +314,16 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
accepted,
unfinished,
}),
- ) => state.on_request_partial(
- now,
- &self.workers.candidates(),
- request,
- accepted,
- unfinished,
- ),
+ ) => {
+ self.record_resolved(request, accepted, unfinished.len());
+ state.on_request_partial(
+ now,
+ &self.workers.candidates(),
+ request,
+ accepted,
+ unfinished,
+ )
+ }
Event::Response(request, Err(failure)) => {
// Backpressure is transient, not a worker fault.
let cause = if failure.error.is_backpressure() {
@@ -284,6 +331,7 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
} else {
FailureCause::Fault
};
+ self.record_failed(request, cause, failure.messages.len());
let requeued = state.on_request_failed(
now,
&self.workers.candidates(),
@@ -374,6 +422,7 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
} else {
SendKind::Fresh
};
+ let routing_keys = send.runs.len();
let mut messages = Vec::new();
for run in send.runs {
sentinel.note_sent(&run.routing_key, &run.messages, kind);
@@ -389,6 +438,21 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
"worker" => send.worker.clone()
)
.increment(messages.len() as u64);
+ if self.recorder.is_some() {
+ self.debug_requests
+ .insert(send.request, send.worker.clone());
+ }
+ record_if(&self.recorder, || DebugEventKind::RequestSent {
+ request_id: send.request.as_u64(),
+ worker: send.worker.to_string(),
+ messages: messages.len(),
+ routing_keys,
+ bytes: payload_bytes(&messages),
+ replay: send.class.replay,
+ budgeted: send.soft_budget.is_some(),
+ assignment_epoch: send.class.assignment_epoch,
+ spans: partition_offsets(&messages),
+ });
let options = SendOptions {
replay: send.class.replay,
soft_budget: send.soft_budget,
@@ -398,6 +462,31 @@ impl<S: RequestSender, W: Workers> BatcherTask<S, W> {
self.responses
.push(async move { (request, response.await) }.boxed());
}
+
+ fn record_resolved(&mut self, request: RequestId, accepted: u32, unfinished: usize) {
+ if let Some(worker) = self.debug_requests.remove(&request) {
+ record_if(&self.recorder, || DebugEventKind::RequestResolved {
+ request_id: request.as_u64(),
+ worker: worker.to_string(),
+ accepted,
+ unfinished,
+ });
+ }
+ }
+
+ fn record_failed(&mut self, request: RequestId, cause: FailureCause, messages: usize) {
+ if let Some(worker) = self.debug_requests.remove(&request) {
+ record_if(&self.recorder, || DebugEventKind::RequestFailed {
+ request_id: request.as_u64(),
+ worker: worker.to_string(),
+ cause: match cause {
+ FailureCause::Busy => "busy",
+ FailureCause::Fault => "fault",
+ },
+ messages,
+ });
+ }
+ }
}
async fn sleep_until(wakeup: Option<Instant>) {
@@ -412,14 +501,12 @@ mod tests {
use std::num::{NonZeroU32, NonZeroUsize};
use std::time::Duration;
- use tokio::sync::oneshot;
-
use super::*;
use crate::batcher::packer::{PackTargets, Packer};
use crate::batcher::retry_policy::RetryPolicy;
use crate::batcher::state_machine::RequestBudget;
use crate::batcher::test_support::{message, offsets};
- use crate::batcher::worker_assigner::WorkerAssigner;
+ use crate::batcher::worker_assigner::{WorkerAssigner, WorkerInFlight};
use crate::routing::{Router, RoutingStrategy};
use crate::transport::{FenceGuard, TransportError};
@@ -510,13 +597,36 @@ mod tests {
impl Harness {
fn new(workers: &[&str], max_requests_per_worker: usize) -> Self {
- Self::budgeted(workers, max_requests_per_worker, None)
+ Self::build(workers, max_requests_per_worker, None, None)
}
fn budgeted(
workers: &[&str],
max_requests_per_worker: usize,
budget: Option<RequestBudget>,
+ ) -> Self {
+ Self::build(workers, max_requests_per_worker, budget, None)
+ }
+
+ fn recorded(
+ workers: &[&str],
+ max_requests_per_worker: usize,
+ ) -> (Self, Arc<DebugRecorder>) {
+ let recorder = DebugRecorder::new(64, Duration::from_secs(60));
+ let harness = Self::build(
+ workers,
+ max_requests_per_worker,
+ None,
+ Some(Arc::clone(&recorder)),
+ );
+ (harness, recorder)
+ }
+
+ fn build(
+ workers: &[&str],
+ max_requests_per_worker: usize,
+ budget: Option<RequestBudget>,
+ recorder: Option<Arc<DebugRecorder>>,
) -> Self {
let assigner =
WorkerAssigner::new(Router::new(RoutingStrategy::P2c), max_requests_per_worker)
@@ -545,7 +655,7 @@ mod tests {
fence: Mutex::new(None),
});
let (driver, outputs) =
- StateMachineDriver::new(state, fake_workers.clone(), Arc::clone(&sender));
+ StateMachineDriver::new(state, fake_workers.clone(), Arc::clone(&sender), recorder);
Self {
driver,
outputs,
@@ -831,4 +941,94 @@ mod tests {
settle().await;
assert_eq!(Arc::strong_count(&sender), 1);
}
+
+ #[tokio::test(start_paused = true)]
+ async fn a_snapshot_answers_through_the_task_with_the_live_load() {
+ let h = Harness::new(&["w"], 4);
+ let snapshots = h.driver.snapshot_sender();
+ h.submit(vec![run("a", &[1]), run("b", &[2])]);
+ settle().await;
+
+ let snapshot = snapshots.snapshot().await.expect("the task answers");
+ assert_eq!(snapshot.keys, 2);
+ assert_eq!(snapshot.claimed_keys, 2);
+ assert_eq!(snapshot.in_flight_requests, 2);
+ assert_eq!(snapshot.in_flight_messages, 2);
+ assert_eq!(snapshot.pending_messages, 0);
+ assert_eq!(
+ snapshot.per_worker,
+ vec![WorkerInFlight {
+ worker: WorkerId::from("w"),
+ requests: 2,
+ messages: 2,
+ }]
+ );
+
+ drop(h);
+ settle().await;
+ assert!(
+ snapshots.snapshot().await.is_none(),
+ "a dropped batcher answers nothing"
+ );
+ }
+
+ #[tokio::test(start_paused = true)]
+ async fn request_events_follow_a_failed_send_and_its_replay() {
+ let (h, recorder) = Harness::recorded(&["w"], 4);
+ h.submit(vec![run("a", &[1])]);
+ settle().await;
+ let send = h.take_sent().pop().unwrap();
+ let failure = busy(&send, None);
+ send.reply.send(Err(failure)).unwrap();
+ settle().await;
+ tokio::time::advance(BUSY_DELAY).await;
+ settle().await;
+ let replay = h.take_sent().pop().unwrap();
+ replay.reply.send(Ok(SendOutcome::Accepted(1))).unwrap();
+ settle().await;
+
+ let events: Vec<String> = recorder
+ .backlog()
+ .into_iter()
+ .map(|event| match event.kind {
+ DebugEventKind::RequestSent {
+ request_id,
+ worker,
+ messages,
+ routing_keys,
+ replay,
+ spans,
+ ..
+ } => format!(
+ "sent #{request_id} {worker} {messages} msgs {routing_keys} keys replay={replay} spans={:?}",
+ spans
+ .iter()
+ .map(|span| (span.partition, span.ranges.clone()))
+ .collect::<Vec<_>>()
+ ),
+ DebugEventKind::RequestFailed {
+ request_id,
+ worker,
+ cause,
+ messages,
+ } => format!("failed #{request_id} {worker} {cause} {messages} msgs"),
+ DebugEventKind::RequestResolved {
+ request_id,
+ worker,
+ accepted,
+ unfinished,
+ } => format!("resolved #{request_id} {worker} {accepted}/{unfinished}"),
+ _ => "other".to_string(),
+ })
+ .collect();
+ assert_eq!(
+ events,
+ vec![
+ "sent #0 w 1 msgs 1 keys replay=false spans=[(0, [(1, 1)])]",
+ "failed #0 w busy 1 msgs",
+ "sent #1 w 1 msgs 1 keys replay=true spans=[(0, [(1, 1)])]",
+ "resolved #1 w 1/0",
+ ]
+ );
+ }
}
diff --git a/rust/ingestion-consumer/src/batcher/in_flight.rs b/rust/ingestion-consumer/src/batcher/in_flight.rs
index 9a4ab233fcd5..349772a6c7f9 100644
--- a/rust/ingestion-consumer/src/batcher/in_flight.rs
+++ b/rust/ingestion-consumer/src/batcher/in_flight.rs
@@ -12,6 +12,12 @@ use crate::worker_registry::WorkerId;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct RequestId(u64);
+impl RequestId {
+ pub fn as_u64(self) -> u64 {
+ self.0
+ }
+}
+
#[derive(Debug)]
pub struct SentMessage {
pub partition: i32,
diff --git a/rust/ingestion-consumer/src/batcher/mod.rs b/rust/ingestion-consumer/src/batcher/mod.rs
index ec8771eb143e..9fa784cc8f1a 100644
--- a/rust/ingestion-consumer/src/batcher/mod.rs
+++ b/rust/ingestion-consumer/src/batcher/mod.rs
@@ -32,8 +32,9 @@ use common_kafka_consumer::GroupCompletion;
use tokio::sync::mpsc;
use self::driver::StateMachineDriver;
-use self::state_machine::BatcherStateMachine;
+use self::state_machine::{BatcherSnapshot, BatcherStateMachine};
use self::worker_pool::WorkerPoolSource;
+use crate::debug_recorder::DebugRecorder;
use crate::grpc_transport::GrpcTransport;
use crate::order_sentinel::KeyOrderSentinel;
use crate::types::Accumulator;
@@ -60,8 +61,10 @@ impl Batcher {
state_machine: BatcherStateMachine,
pool_source: WorkerPoolSource,
transport: Arc<GrpcTransport>,
+ recorder: Option<Arc<DebugRecorder>>,
) -> (Self, BatcherOutputs) {
- let (driver, outputs) = StateMachineDriver::new(state_machine, pool_source, transport);
+ let (driver, outputs) =
+ StateMachineDriver::new(state_machine, pool_source, transport, recorder);
(Self { driver }, outputs)
}
@@ -84,7 +87,10 @@ impl Batcher {
/// A read-only view of the batcher's load, for the drain reaper, the
/// debug API and tests.
pub fn observer(&self) -> BatcherObserver {
- BatcherObserver(self.driver.load())
+ BatcherObserver {
+ load: self.driver.load(),
+ snapshots: self.driver.snapshot_sender(),
+ }
}
/// The consumer stopped polling. The state machine takes no new groups
@@ -96,22 +102,39 @@ impl Batcher {
/// A read-only view of the batcher's load.
#[derive(Clone)]
-pub struct BatcherObserver(Arc<driver::Load>);
+pub struct BatcherObserver {
+ /// Totals the batcher task publishes after every action.
+ load: Arc<driver::Load>,
+ snapshots: driver::SnapshotSender,
+}
impl BatcherObserver {
/// Whether the worker has sent, unresolved work. The reaper completes a
/// draining worker's drain only when it has none.
pub fn has_in_flight(&self, worker: &WorkerId) -> bool {
- self.0.busy_workers.lock().unwrap().contains(worker)
+ self.load.busy_workers.lock().unwrap().contains(worker)
}
- /// Messages held for a later send: queued, packed and unplaced.
+ /// Messages queued for a later send.
pub fn pending_messages(&self) -> usize {
- self.0.pending_messages.load(Ordering::Relaxed)
+ self.load.pending_messages.load(Ordering::Relaxed)
}
pub fn total_in_flight(&self) -> usize {
- self.0.in_flight_messages.load(Ordering::Relaxed)
+ self.load.in_flight_messages.load(Ordering::Relaxed)
+ }
+
+ /// The task's own view of its load, or only the published totals when
+ /// it does not answer.
+ pub async fn snapshot(&self) -> BatcherSnapshot {
+ match self.snapshots.snapshot().await {
+ Some(snapshot) => snapshot,
+ None => BatcherSnapshot {
+ pending_messages: self.pending_messages(),
+ in_flight_messages: self.total_in_flight(),
+ ..BatcherSnapshot::default()
+ },
+ }
}
}
diff --git a/rust/ingestion-consumer/src/batcher/state_machine.rs b/rust/ingestion-consumer/src/batcher/state_machine.rs
index f30db0cb9970..5aeb766d6764 100644
--- a/rust/ingestion-consumer/src/batcher/state_machine.rs
+++ b/rust/ingestion-consumer/src/batcher/state_machine.rs
@@ -26,7 +26,7 @@ use super::key_queues::{KeyQueues, KeyRun, Settlement};
use super::packer::Packer;
use super::request::{Request, RequestClass};
use super::retry_policy::{RetryPolicy, RetryReason};
-use super::worker_assigner::WorkerAssigner;
+use super::worker_assigner::{WorkerAssigner, WorkerInFlight};
use crate::order_sentinel::ack_mark;
use crate::types::SerializedKafkaMessage;
use crate::worker_registry::WorkerId;
@@ -82,6 +82,19 @@ pub struct Effects {
pub next_wakeup: Option<Instant>,
}
+/// A point-in-time view of the batcher's load, for the debug API.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct BatcherSnapshot {
+ pub keys: usize,
+ pub pending_messages: usize,
+ pub queued_bytes: usize,
+ pub waiting_keys: usize,
+ pub claimed_keys: usize,
+ pub in_flight_requests: usize,
+ pub in_flight_messages: usize,
+ pub per_worker: Vec<WorkerInFlight>,
+}
+
pub enum BatcherStateMachine {
Running(ActiveState),
Draining(ActiveState),
@@ -240,6 +253,11 @@ impl BatcherStateMachine {
.map_or(0, |active| active.assigner.in_flight_messages())
}
+ pub fn snapshot(&self) -> BatcherSnapshot {
+ self.active()
+ .map_or_else(BatcherSnapshot::default, ActiveState::snapshot)
+ }
+
fn active(&self) -> Option<&ActiveState> {
match self {
BatcherStateMachine::Running(active) | BatcherStateMachine::Draining(active) => {
@@ -312,6 +330,19 @@ impl ActiveState {
self.keys.queued_messages()
}
+ fn snapshot(&self) -> BatcherSnapshot {
+ BatcherSnapshot {
+ keys: self.keys.key_count(),
+ pending_messages: self.keys.queued_messages(),
+ queued_bytes: self.keys.queued_bytes(),
+ waiting_keys: self.keys.waiting_keys(),
+ claimed_keys: self.keys.claimed_keys(),
+ in_flight_requests: self.in_flight.len(),
+ in_flight_messages: self.assigner.in_flight_messages(),
+ per_worker: self.assigner.in_flight_per_worker(),
+ }
+ }
+
/// The stall clock starts when work becomes pending, not at the last
/// action before a quiet period.
fn restart_stall_clock_if_quiet(&mut self, now: Instant) {
diff --git a/rust/ingestion-consumer/src/batcher/worker_assigner.rs b/rust/ingestion-consumer/src/batcher/worker_assigner.rs
index 30a4a2a2bb0c..7091ea73eaef 100644
--- a/rust/ingestion-consumer/src/batcher/worker_assigner.rs
+++ b/rust/ingestion-consumer/src/batcher/worker_assigner.rs
@@ -12,6 +12,13 @@ pub struct WorkerAssigner {
request_load: HashMap<WorkerId, usize>,
}
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct WorkerInFlight {
+ pub worker: WorkerId,
+ pub requests: usize,
+ pub messages: usize,
+}
+
impl WorkerAssigner {
pub fn new(router: Router, max_requests_per_worker: usize) -> Result<Self, String> {
if max_requests_per_worker == 0 {
@@ -29,6 +36,18 @@ impl WorkerAssigner {
self.message_load.values().sum()
}
+ /// Every worker with a request in flight.
+ pub fn in_flight_per_worker(&self) -> Vec<WorkerInFlight> {
+ self.request_load
+ .iter()
+ .map(|(worker, requests)| WorkerInFlight {
+ worker: worker.clone(),
+ requests: *requests,
+ messages: self.message_load.get(worker).copied().unwrap_or(0),
+ })
+ .collect()
+ }
+
pub fn free_slots(&self, pool: &[WorkerId]) -> usize {
pool.iter()
.map(|worker| self.max_requests_per_worker - self.requests_on(worker))
diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rs
index 9016d2e08c73..de35a9f2e029 100644
--- a/rust/ingestion-consumer/src/consumer.rs
+++ b/rust/ingestion-consumer/src/consumer.rs
@@ -19,7 +19,9 @@ use crate::commit_monitor::spawn_commit_monitor;
use crate::commit_pacer::ImmediateCommitPacer;
use crate::commit_sentinel::{CommitSentinel, CommitViolation};
use crate::config::Config;
-use crate::debug_recorder::{record_if, DebugEventKind, DebugRecorder, PartitionOffset};
+use crate::debug_recorder::{
+ record_if, DebugEventKind, DebugRecorder, PartitionOffset, PartitionOffsets,
+};
use crate::discovery::DiscoveryMode;
use crate::grpc_transport::GrpcTransport;
use crate::ledger_rejection::{warn_rejection, RejectedSlice};
@@ -634,11 +636,6 @@ impl IngestionConsumer {
} = collected;
let message_count = accumulator.message_count();
let poll_id = make_batch_id();
- record_if(&self.debug_recorder, || DebugEventKind::BatchDispatched {
- batch_id: poll_id.clone(),
- messages: message_count,
- partitions: debug_partition_offsets(&partitions),
- });
emit_poll_stats(
&stats,
&partitions,
@@ -649,6 +646,13 @@ impl IngestionConsumer {
);
let assignment_epoch = self.batcher.submit(accumulator);
+ record_if(&self.debug_recorder, || DebugEventKind::BatchDispatched {
+ batch_id: poll_id.clone(),
+ messages: message_count,
+ partitions: debug_partition_offsets(&partitions),
+ assignment_epoch,
+ spans: debug_partition_spans(&partitions),
+ });
info!(
batch_id = %poll_id,
@@ -1129,6 +1133,20 @@ fn debug_partition_offsets(
.collect()
}
+/// Per-partition offset ranges, so the debug UI can match requests to polls.
+fn debug_partition_spans(
+ partitions: &HashMap<TopicPartition, PartitionDeliveries>,
+) -> Vec<PartitionOffsets> {
+ partitions
+ .iter()
+ .map(|(topic_partition, partition)| PartitionOffsets {
+ topic: topic_partition.topic.clone(),
+ partition: topic_partition.partition,
+ ranges: vec![(partition.span.first, partition.span.last)],
+ })
+ .collect()
+}
+
/// One delivered message's cost against the ledger: one event, and the bytes
/// the process holds for the message. The byte count is a memory bound, so it
/// is the payload plus the key plus every header key and value, not only the
diff --git a/rust/ingestion-consumer/src/debug_recorder.rs b/rust/ingestion-consumer/src/debug_recorder.rs
index aa1280d40870..d3ad9b974bfd 100644
--- a/rust/ingestion-consumer/src/debug_recorder.rs
+++ b/rust/ingestion-consumer/src/debug_recorder.rs
@@ -2,17 +2,18 @@
//! ingestion control plane UI).
//!
//! When `DEBUG_API_ENABLED` is set, an `Arc<DebugRecorder>` is injected into
-//! the consumer and the worker registry. Each records a structured
-//! [`DebugEvent`] at the same points it already emits metrics: batch
-//! dispatch, commit and failure, worker health transitions and membership.
-//! The recorder keeps a bounded rolling window of recent events (for a client
-//! connecting mid-stream to see history) and broadcasts every new event to
-//! live subscribers (the SSE feed at `/debug/events`).
+//! the consumer, the batcher task and the worker registry. Each records a
+//! structured [`DebugEvent`] at the same points it already emits metrics:
+//! poll dispatch, commit and failure, every request the batcher sends and
+//! how it settled, worker health transitions and membership. The recorder
+//! keeps a bounded rolling window of recent events (for a client connecting
+//! mid-stream to see history) and broadcasts every new event to live
+//! subscribers (the SSE feed at `/debug/events`).
//!
//! It is a pure observer: it never influences routing. When the feature is off,
//! the recorder is `None` everywhere and nothing is constructed or recorded.
-use std::collections::VecDeque;
+use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
@@ -20,6 +21,8 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::Serialize;
use tokio::sync::broadcast;
+use crate::types::SerializedKafkaMessage;
+
/// A topic-partition and the batch's max offset there, with observed lag.
#[derive(Clone, Serialize)]
pub struct PartitionOffset {
@@ -29,6 +32,52 @@ pub struct PartitionOffset {
pub lag_ms: i64,
}
+/// The offsets a poll or a request carries on one topic-partition, as runs
+/// of consecutive offsets. A request's runs fall inside the polls it carries
+/// and nowhere else, so the UI matches the two exactly even when a key
+/// skipped a poll in between.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
+pub struct PartitionOffsets {
+ pub topic: String,
+ pub partition: i32,
+ /// Inclusive `(first, last)` pairs in offset order.
+ pub ranges: Vec<(i64, i64)>,
+}
+
+pub fn partition_offsets(messages: &[SerializedKafkaMessage]) -> Vec<PartitionOffsets> {
+ let mut spans: Vec<PartitionOffsets> = Vec::new();
+ let mut index: HashMap<(&str, i32), usize> = HashMap::new();
+ for message in messages {
+ let position = *index
+ .entry((message.topic.as_ref(), message.partition))
+ .or_insert_with(|| {
+ spans.push(PartitionOffsets {
+ topic: message.topic.to_string(),
+ partition: message.partition,
+ ranges: Vec::new(),
+ });
+ spans.len() - 1
+ });
+ spans[position]
+ .ranges
+ .push((message.offset, message.offset));
+ }
+ // A request's messages are grouped by key, so one partition's offsets
+ // arrive out of order and interleaved with other keys'.
+ for span in &mut spans {
+ span.ranges.sort_unstable();
+ let mut merged: Vec<(i64, i64)> = Vec::with_capacity(span.ranges.len());
+ for (first, last) in span.ranges.drain(..) {
+ match merged.last_mut() {
+ Some((_, previous)) if first <= *previous + 1 => *previous = (*previous).max(last),
+ _ => merged.push((first, last)),
+ }
+ }
+ span.ranges = merged;
+ }
+ spans
+}
+
/// The distinct event kinds recorded across the consumer's lifecycle. Serialized
/// with an internal `type` tag so the UI can switch on it.
#[derive(Clone, Serialize)]
@@ -40,11 +89,43 @@ pub enum DebugEventKind {
group_id: String,
workers: Vec<String>,
},
- /// A Kafka batch was collected and handed to a processing task.
+ /// A Kafka poll was collected and submitted to the batcher. The epoch
+ /// and the spans let the UI match requests to the polls they carry, and
+ /// keep a reassigned partition's replays off the old assignment's polls.
BatchDispatched {
batch_id: String,
messages: usize,
partitions: Vec<PartitionOffset>,
+ assignment_epoch: u64,
+ spans: Vec<PartitionOffsets>,
+ },
+ /// The batcher sent a request to a worker. `routing_keys` is a count:
+ /// the keys themselves hold distinct ids and stay out of the payload.
+ RequestSent {
+ request_id: u64,
+ worker: String,
+ messages: usize,
+ routing_keys: usize,
+ bytes: usize,
+ replay: bool,
+ budgeted: bool,
+ assignment_epoch: u64,
+ spans: Vec<PartitionOffsets>,
+ },
+ /// A worker acked a request. `unfinished` above zero is a partial ack:
+ /// those messages go out again at once.
+ RequestResolved {
+ request_id: u64,
+ worker: String,
+ accepted: u32,
+ unfinished: usize,
+ },
+ /// A request failed (`cause`: busy/fault); its messages are requeued.
+ RequestFailed {
+ request_id: u64,
+ worker: String,
+ cause: &'static str,
+ messages: usize,
},
/// A batch's offsets were committed to Kafka.
BatchCommitted {
@@ -98,13 +179,20 @@ pub struct WorkerHealthSnapshot {
pub passive_samples: usize,
}
-/// The batcher's current load accounting.
+/// The batcher's current load, as its task reports it.
#[derive(Serialize)]
pub struct BatcherLoad {
- /// Messages sent and not yet resolved.
pub total_in_flight: usize,
- /// Messages held for a later send: queued, packed and unplaced.
pub pending_messages: usize,
+ pub in_flight_requests: usize,
+ /// Keys with messages queued or in flight.
+ pub keys: usize,
+ /// Key-plus-value bytes of the queued messages.
+ pub queued_bytes: usize,
+ /// Keys whose retry delay has not passed.
+ pub waiting_keys: usize,
+ /// Keys with a request in flight.
+ pub claimed_keys: usize,
}
/// The consumer's routing configuration and, under aperture, its current
@@ -124,8 +212,7 @@ pub struct RoutingDebug {
pub slice: Option<Vec<String>>,
}
-/// Merged worker row: registry health plus whether the batcher has a request
-/// in flight on the worker.
+/// Merged worker row: registry health plus the batcher's in-flight load.
#[derive(Serialize)]
pub struct WorkerStatus {
pub url: String,
@@ -134,7 +221,8 @@ pub struct WorkerStatus {
pub consecutive_probe_failures: u32,
pub passive_error_rate: f64,
pub passive_samples: usize,
- pub busy: bool,
+ pub in_flight_requests: usize,
+ pub in_flight_messages: usize,
}
/// The full snapshot returned by `/debug/state` (workers + load + event backlog).
diff --git a/rust/ingestion-consumer/src/main.rs b/rust/ingestion-consumer/src/main.rs
index ba247d7eabc6..6cc20bee9631 100644
--- a/rust/ingestion-consumer/src/main.rs
+++ b/rust/ingestion-consumer/src/main.rs
@@ -290,8 +290,12 @@ async fn async_main(config: Config) -> Result<()> {
let state_machine = config
.batcher_state_machine()
.map_err(|err| anyhow::anyhow!("invalid batcher configuration: {err}"))?;
- let (batcher, batcher_outputs) =
- Batcher::new(state_machine, pool_source.clone(), Arc::clone(&transport));
+ let (batcher, batcher_outputs) = Batcher::new(
+ state_machine,
+ pool_source.clone(),
+ Arc::clone(&transport),
+ debug_recorder.clone(),
+ );
// Select the worker discovery provider and start it (static applies the
// configured list immediately; endpointslice watches and keeps in sync).
@@ -364,18 +368,26 @@ async fn async_main(config: Config) -> Result<()> {
app = app.route(
"/debug/load",
get(move |headers: axum::http::HeaderMap| {
- let result = if !debug_authorized(&headers, &secret) {
- Err(axum::http::StatusCode::UNAUTHORIZED)
- } else {
- Ok(axum::Json(build_debug_load(
+ let registry = Arc::clone(&registry);
+ let pool_source = pool_source.clone();
+ let observer = observer.clone();
+ let peer_tracker = peer_tracker.clone();
+ let group_id = group_id.clone();
+ let secret = Arc::clone(&secret);
+ async move {
+ if !debug_authorized(&headers, &secret) {
+ return Err(axum::http::StatusCode::UNAUTHORIZED);
+ }
+ let load = build_debug_load(
&group_id,
&registry,
&pool_source,
&observer,
&peer_tracker,
- )))
- };
- ready(result)
+ )
+ .await;
+ Ok(axum::Json(load))
+ }
}),
);
}
@@ -390,16 +402,25 @@ async fn async_main(config: Config) -> Result<()> {
app = app.route(
"/debug/state",
get(move |headers: axum::http::HeaderMap| {
- let result = if !debug_authorized(&headers, &secret) {
- Err(axum::http::StatusCode::UNAUTHORIZED)
- } else {
+ let recorder = Arc::clone(&recorder);
+ let registry = Arc::clone(&registry);
+ let pool_source = pool_source.clone();
+ let observer = observer.clone();
+ let peer_tracker = peer_tracker.clone();
+ let group_id = group_id.clone();
+ let secret = Arc::clone(&secret);
+ async move {
+ if !debug_authorized(&headers, &secret) {
+ return Err(axum::http::StatusCode::UNAUTHORIZED);
+ }
let load = build_debug_load(
&group_id,
&registry,
&pool_source,
&observer,
&peer_tracker,
- );
+ )
+ .await;
Ok(axum::Json(DebugState {
group_id: load.group_id,
workers: load.workers,
@@ -409,8 +430,7 @@ async fn async_main(config: Config) -> Result<()> {
routing: load.routing,
events: recorder.backlog(),
}))
- };
- ready(result)
+ }
}),
);
}
@@ -590,7 +610,7 @@ fn constant_time_eq(a: &str, b: &str) -> bool {
/// Merge the registry's health snapshots with the batcher's load into the
/// `/debug/load` payload.
-fn build_debug_load(
+async fn build_debug_load(
group_id: &str,
registry: &WorkerRegistry,
pool_source: &WorkerPoolSource,
@@ -604,6 +624,7 @@ fn build_debug_load(
}
None => (None, None),
};
+ let batcher = observer.snapshot().await;
// One registry pass feeds the worker rows AND the routing ring/slice, so a
// worker joining or changing health mid-request can't make the payload
// show slice badges that contradict the worker table.
@@ -628,22 +649,35 @@ fn build_debug_load(
};
let workers = snapshots
.into_iter()
- .map(|snap| WorkerStatus {
- busy: observer.has_in_flight(&WorkerId::from(snap.url.as_str())),
- url: snap.url,
- state: snap.state,
- draining: snap.draining,
- consecutive_probe_failures: snap.consecutive_probe_failures,
- passive_error_rate: snap.passive_error_rate,
- passive_samples: snap.passive_samples,
+ .map(|snap| {
+ let (in_flight_requests, in_flight_messages) = batcher
+ .per_worker
+ .iter()
+ .find(|load| load.worker.as_ref() == snap.url)
+ .map_or((0, 0), |load| (load.requests, load.messages));
+ WorkerStatus {
+ url: snap.url,
+ state: snap.state,
+ draining: snap.draining,
+ consecutive_probe_failures: snap.consecutive_probe_failures,
+ passive_error_rate: snap.passive_error_rate,
+ passive_samples: snap.passive_samples,
+ in_flight_requests,
+ in_flight_messages,
+ }
})
.collect();
DebugLoad {
group_id: group_id.to_string(),
workers,
batcher: BatcherLoad {
- total_in_flight: observer.total_in_flight(),
- pending_messages: observer.pending_messages(),
+ total_in_flight: batcher.in_flight_messages,
+ pending_messages: batcher.pending_messages,
+ in_flight_requests: batcher.in_flight_requests,
+ keys: batcher.keys,
+ queued_bytes: batcher.queued_bytes,
+ waiting_keys: batcher.waiting_keys,
+ claimed_keys: batcher.claimed_keys,
},
peer_index,
peer_count,
diff --git a/rust/ingestion-consumer/tests/common/mod.rs b/rust/ingestion-consumer/tests/common/mod.rs
index 593d7f35277c..10de6fc0e015 100644
--- a/rust/ingestion-consumer/tests/common/mod.rs
+++ b/rust/ingestion-consumer/tests/common/mod.rs
@@ -50,7 +50,7 @@ pub fn batcher(
)
.expect("valid stall timeout")
.with_request_budget(budget);
- Batcher::new(state_machine, pool_source, transport)
+ Batcher::new(state_machine, pool_source, transport, None)
}
/// A batcher that sends every message in its own request.
diff --git a/rust/ingestion-control-plane/src/ui/consumer_debug.html b/rust/ingestion-control-plane/src/ui/consumer_debug.html
index 4f2c0d4b8f81..7b76e0821b5a 100644
--- a/rust/ingestion-control-plane/src/ui/consumer_debug.html
+++ b/rust/ingestion-control-plane/src/ui/consumer_debug.html
@@ -54,7 +54,7 @@
td .bar { height: 6px; border-radius: 3px; background: var(--accent); min-width: 2px; }
.pill { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 11px; font-weight: 600; white-space: nowrap; }
.pill.healthy, .pill.committed { background: rgba(63,185,80,0.16); color: var(--good); }
- .pill.degraded, .pill.retrying { background: rgba(210,153,34,0.16); color: var(--warn); }
+ .pill.degraded, .pill.retrying, .pill.partial { background: rgba(210,153,34,0.16); color: var(--warn); }
.pill.unhealthy, .pill.stalled, .pill.failed { background: rgba(248,81,73,0.16); color: var(--error); }
.pill.draining, .pill.inflight { background: rgba(139,147,161,0.18); color: var(--muted); }
.pill.accent { background: rgba(79,124,255,0.18); color: #a9c0ff; }
@@ -81,9 +81,9 @@
.controls { display: flex; gap: 8px; align-items: center; }
.controls label { color: var(--muted); font-size: 11px; }
- /* batches list: grows with content — the page (or embedding iframe)
+ /* polls list: grows with content — the page (or embedding iframe)
expands instead of squeezing the list into an inner scroll box. */
- #batches-view { overflow-y: visible; }
+ #polls-view { overflow-y: visible; }
.brow { display: grid; grid-template-columns: 96px 90px 1fr auto; gap: 10px; align-items: center; padding: 8px 14px; border-bottom: 1px solid var(--border); cursor: pointer; }
.brow:hover { background: var(--panel-2); }
.brow .id { font-family: var(--mono); color: #d2a8ff; }
@@ -163,9 +163,9 @@
<h2>Workers</h2>
<table>
<thead>
- <tr><th>Worker</th><th>State</th><th>Busy</th><th>Fails</th><th>Err</th></tr>
+ <tr><th>Worker</th><th>State</th><th>Requests</th><th>Messages</th><th>Fails</th><th>Err</th></tr>
</thead>
- <tbody id="workers"><tr><td class="empty" colspan="5">Waiting for data…</td></tr></tbody>
+ <tbody id="workers"><tr><td class="empty" colspan="6">Waiting for data…</td></tr></tbody>
</table>
</section>
</div>
@@ -174,7 +174,7 @@
<section class="panel">
<div class="tabs">
<div class="tab active" data-tab="feed">Live feed</div>
- <div class="tab" data-tab="batches">Batches <span class="badge" id="badge-batches"></span></div>
+ <div class="tab" data-tab="polls">Polls <span class="badge" id="badge-polls"></span></div>
<div class="tab" data-tab="commits">Commits <span class="badge" id="badge-commits"></span></div>
</div>
@@ -188,15 +188,15 @@
<div id="feed"><div class="empty">Waiting for events…</div></div>
</div>
- <div id="tab-batches" style="display:none;">
+ <div id="tab-polls" style="display:none;">
<h2>
- Batches
+ Polls
<span class="controls">
- <label><input type="checkbox" id="batches-pause" /> pause list</label>
- <label><input type="checkbox" id="batches-issues" /> issues only</label>
+ <label><input type="checkbox" id="polls-pause" /> pause list</label>
+ <label><input type="checkbox" id="polls-issues" /> issues only</label>
</span>
</h2>
- <div id="batches-view"><div class="empty">Waiting for batches…</div></div>
+ <div id="polls-view"><div class="empty">Waiting for polls…</div></div>
</div>
<div id="tab-commits" style="display:none;">
@@ -208,18 +208,22 @@
<script>
const MAX_FEED = 600;
- const MAX_BATCHES = 400;
+ const MAX_POLLS = 400;
+ const MAX_REQUESTS = 2000;
+ const MAX_POLL_EVENTS = 500;
const MAX_COMMITS = 400;
const seen = new Set();
let feedEmpty = true;
let activeTab = "feed";
- let selectedBatch = null;
+ let selectedPoll = null;
let openDetailId = null;
// client-side models rebuilt from the event stream
- let batches = {};
- let batchOrder = [];
+ let polls = {};
+ let pollOrder = [];
+ let requests = {};
+ let requestOrder = [];
let commits = [];
let partitionHigh = {}; // "topic/partition" -> highest committed offset
let oooCount = 0;
@@ -247,6 +251,7 @@
const d = new Date(ms);
return d.toLocaleTimeString("en-US", { hour12: false }) + "." + String(d.getMilliseconds()).padStart(3, "0");
};
+ const fmtBytes = (n) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`);
const fmtDur = (ms) => {
if (ms == null || !isFinite(ms) || ms < 0) return "—";
if (ms < 1000) return `${Math.round(ms)}ms`;
@@ -298,9 +303,15 @@
$("disp-stats").innerHTML = [
["in-flight", d.total_in_flight ?? 0],
["peak 4s", peak],
+ ["requests", d.in_flight_requests ?? 0],
["pending", d.pending_messages ?? 0],
+ ["queued", fmtBytes(d.queued_bytes ?? 0)],
+ ["keys", d.keys ?? 0],
+ ["claimed", d.claimed_keys ?? 0],
+ ["waiting", d.waiting_keys ?? 0],
].map(([l, n]) => `<div class="stat"><div class="n">${n}</div><div class="l">${l}</div></div>`).join("");
+ const maxLoad = Math.max(1, ...s.workers.map((w) => w.in_flight_messages ?? 0));
// Stable order — slice members first, then by IP. Sorting by load made
// rows jump around on every poll.
const workerSortKey = (url) => {
@@ -317,58 +328,161 @@
const cls = w.draining ? "draining" : w.state;
const label = w.draining ? "draining" : w.state;
const rate = (w.passive_error_rate * 100).toFixed(0) + "%";
+ const inFlight = w.in_flight_messages ?? 0;
+ const pct = Math.round((inFlight / maxLoad) * 100);
const slice = sliceSet.has(w.url) ? ` <span class="badge-min" title="in this consumer's aperture slice">slice</span>` : "";
return `<tr>
<td class="mono">${shortWorker(w.url)}${slice}</td>
<td><span class="pill ${cls}">${label}</span></td>
- <td><span class="pill ${w.busy ? "accent" : "inflight"}">${w.busy ? "busy" : "idle"}</span></td>
+ <td class="mono">${w.in_flight_requests ?? 0}</td>
+ <td class="mono"><div style="display:flex;align-items:center;gap:8px;">
+ <div class="bar" style="width:${pct}%"></div><span>${inFlight}</span></div></td>
<td class="mono">${w.consecutive_probe_failures}</td>
<td class="mono">${rate}</td>
</tr>`;
}).join("")
- : `<tr><td class="empty" colspan="5">No workers</td></tr>`;
+ : `<tr><td class="empty" colspan="6">No workers</td></tr>`;
}
// ---------- event → model ----------
+ // A poll is one Kafka batch the consumer submitted; a request is one
+ // send the batcher made. A request can merge messages from consecutive
+ // polls, so the two are matched by the topic-partition offset ranges
+ // both events carry.
function resetModels() {
seen.clear();
- batches = {}; batchOrder = []; commits = []; partitionHigh = {}; oooCount = 0;
- selectedBatch = null;
+ polls = {}; pollOrder = []; requests = {}; requestOrder = []; commits = []; partitionHigh = {}; oooCount = 0;
+ selectedPoll = null;
$("feed").innerHTML = '<div class="empty">Waiting for events…</div>';
feedEmpty = true;
scheduleRender();
}
- function batchFor(id) {
- let b = batches[id];
- if (!b) {
- b = { id, ts: null, messages: 0, distinct_ids: 0, partitions: [],
- assigned: [], retries: [], exhausted: [], splits: [],
- committed: null, events: [] };
- batches[id] = b;
- batchOrder.push(id);
- while (batchOrder.length > MAX_BATCHES) delete batches[batchOrder.shift()];
+ function pollFor(id) {
+ let p = polls[id];
+ if (!p) {
+ p = { id, ts: null, messages: 0, partitions: [], assignment_epoch: null, spans: [], requests: [],
+ committed: null, failed: null, events: [] };
+ polls[id] = p;
+ pollOrder.push(id);
+ while (pollOrder.length > MAX_POLLS) delete polls[pollOrder.shift()];
}
- return b;
+ return p;
+ }
+
+ function requestFor(id) {
+ let r = requests[id];
+ if (!r) {
+ r = { id, ts: null, worker: null, messages: 0, routing_keys: 0, bytes: 0, replay: false, budgeted: false,
+ assignment_epoch: null, spans: [], polls: [], resolved: null, failed: null, events: [] };
+ requests[id] = r;
+ requestOrder.push(id);
+ if (requestOrder.length > MAX_REQUESTS) evictRequest();
+ }
+ return r;
+ }
+
+ // Drop the oldest settled request, and only an unsettled one when
+ // nothing settled is left: its response is still to come, and the poll
+ // that carries it would otherwise lose the outcome.
+ function evictRequest() {
+ let index = requestOrder.findIndex((id) => { const r = requests[id]; return !r || r.resolved || r.failed; });
+ if (index < 0) index = 0;
+ const [id] = requestOrder.splice(index, 1);
+ const r = requests[id];
+ delete requests[id];
+ if (!r) return;
+ r.polls.forEach((pid) => {
+ const p = polls[pid];
+ if (!p) return;
+ p.requests = p.requests.filter((rid) => rid !== id);
+ p.events = p.events.filter((ev) => ev.request_id !== id);
+ });
+ }
+
+ const overlaps = (a, b) => a.some((x) => b.some((y) =>
+ x.topic === y.topic && x.partition === y.partition &&
+ x.ranges.some(([xf, xl]) => y.ranges.some(([yf, yl]) => xf <= yl && yf <= xl))));
+
+ // Attach a request to every poll whose offsets it carries. The epoch
+ // must match too: after a partition is revoked and read again, the new
+ // assignment's requests repeat offsets the old assignment's polls hold.
+ function linkRequest(r) {
+ for (let i = pollOrder.length - 1; i >= 0; i--) {
+ const p = polls[pollOrder[i]];
+ if (!p || p.assignment_epoch !== r.assignment_epoch || p.requests.includes(r.id) || !overlaps(r.spans, p.spans)) continue;
+ p.requests.push(r.id);
+ r.polls.push(p.id);
+ }
+ }
+
+ // A request's events also go on the timeline of every poll it carries.
+ // A poll that retries for long keeps its own events and the newest
+ // request events only.
+ function noteRequestEvent(r, ev) {
+ r.events.push(ev);
+ r.polls.forEach((id) => {
+ const p = polls[id];
+ if (!p) return;
+ p.events.push(ev);
+ if (p.events.length > MAX_POLL_EVENTS) {
+ const oldest = p.events.findIndex((e) => e.request_id !== undefined);
+ if (oldest >= 0) p.events.splice(oldest, 1);
+ }
+ });
}
function updateModel(ev) {
- const id = ev.batch_id;
- if (id) {
- const b = batchFor(id);
- if (b.ts === null) b.ts = ev.ts_ms;
- b.events.push(ev);
- switch (ev.type) {
- case "BatchDispatched": b.messages = ev.messages; b.partitions = ev.partitions; break;
- case "SendRetry": b.retries.push({ worker: ev.worker, attempt: ev.attempt, reason: ev.reason, ts: ev.ts_ms }); break;
- case "SendSplit": b.splits.push({ worker: ev.worker, reason: ev.reason, chunks: ev.chunks, messages: ev.messages, ts: ev.ts_ms }); break;
- case "SendExhausted": b.exhausted.push({ worker: ev.worker, error: ev.error, ts: ev.ts_ms }); break;
- case "BatchCommitted":
- b.committed = { accepted: ev.accepted, duration_ms: ev.duration_ms, partitions: ev.partitions, ts: ev.ts_ms };
- recordCommit(ev); break;
+ switch (ev.type) {
+ case "ConsumerStarted":
+ polls = {}; pollOrder = []; requests = {}; requestOrder = []; commits = []; partitionHigh = {}; oooCount = 0;
+ break;
+ case "BatchDispatched": {
+ const p = pollFor(ev.batch_id);
+ p.ts = ev.ts_ms; p.messages = ev.messages; p.partitions = ev.partitions;
+ p.assignment_epoch = ev.assignment_epoch; p.spans = ev.spans || [];
+ p.events.push(ev);
+ break;
+ }
+ case "BatchCommitted": {
+ const p = pollFor(ev.batch_id);
+ if (p.ts === null) p.ts = ev.ts_ms;
+ p.committed = { accepted: ev.accepted, duration_ms: ev.duration_ms, partitions: ev.partitions, ts: ev.ts_ms };
+ p.events.push(ev);
+ recordCommit(ev);
+ break;
+ }
+ case "BatchFailed": {
+ if (!ev.batch_id) break;
+ const p = pollFor(ev.batch_id);
+ p.failed = { error: ev.error, ts: ev.ts_ms };
+ p.events.push(ev);
+ break;
+ }
+ case "RequestSent": {
+ const r = requestFor(ev.request_id);
+ r.ts = ev.ts_ms; r.worker = ev.worker; r.messages = ev.messages; r.routing_keys = ev.routing_keys;
+ r.bytes = ev.bytes; r.replay = ev.replay; r.budgeted = ev.budgeted;
+ r.assignment_epoch = ev.assignment_epoch; r.spans = ev.spans || [];
+ linkRequest(r);
+ noteRequestEvent(r, ev);
+ break;
+ }
+ case "RequestResolved": {
+ const r = requestFor(ev.request_id);
+ r.worker = r.worker || ev.worker;
+ r.resolved = { accepted: ev.accepted, unfinished: ev.unfinished, ts: ev.ts_ms };
+ noteRequestEvent(r, ev);
+ break;
+ }
+ case "RequestFailed": {
+ const r = requestFor(ev.request_id);
+ r.worker = r.worker || ev.worker;
+ r.failed = { cause: ev.cause, messages: ev.messages, ts: ev.ts_ms };
+ noteRequestEvent(r, ev);
+ break;
}
}
- if (ev.type === "ConsumerStarted") { batches = {}; batchOrder = []; commits = []; partitionHigh = {}; oooCount = 0; }
}
function recordCommit(ev) {
@@ -385,29 +499,42 @@
while (commits.length > MAX_COMMITS) commits.pop();
}
- function batchStatus(b) {
- if (b.committed) return "committed";
- if (b.exhausted.length) return "stalled";
- if (b.retries.length) return "retrying";
+ const pollRequests = (p) => p.requests.map((id) => requests[id]).filter(Boolean);
+ const isPartial = (r) => r.resolved && r.resolved.unfinished > 0;
+
+ function pollStatus(p) {
+ if (p.committed) return "committed";
+ if (p.failed) return "failed";
+ const rs = pollRequests(p);
+ if (rs.some((r) => r.failed)) return "retrying";
+ if (rs.some(isPartial)) return "partial";
return "inflight";
}
- // A batch whose lifecycle involved a retry or a failure: the interesting
- // ones, even if they ultimately committed cleanly.
- function hadIssue(b) {
- return b.retries.length || b.exhausted.length;
+ // A poll whose requests failed, came back partial, or were replays: the
+ // interesting ones, even if they ultimately committed cleanly.
+ function hadIssue(p) {
+ return p.failed || pollRequests(p).some((r) => r.failed || r.replay || isPartial(r));
}
// ---------- live feed rendering ----------
function describe(ev) {
switch (ev.type) {
case "ConsumerStarted": return ["accent", `▶ consumer started — group <code>${ev.group_id}</code>, ${ev.workers.length} worker(s)`];
- case "BatchDispatched": return ["", `batch <code>${shortId(ev.batch_id)}</code> dispatched — ${ev.messages} msgs, ${ev.partitions.length} partition(s)`];
- case "BatchCommitted": return ["good", `✓ committed batch <code>${shortId(ev.batch_id)}</code> — ${ev.accepted} msgs in ${ev.duration_ms}ms`];
- case "BatchFailed": return ["error", `✗ batch failed — ${ev.error}`];
- case "SendRetry": return ["warn", `↻ retry #${ev.attempt} [${ev.reason}] — ${shortWorker(ev.worker)}, batch <code>${shortId(ev.batch_id)}</code>`];
- case "SendSplit": return ["warn", `✂ split [${ev.reason}] — ${ev.messages} msgs → ${ev.chunks} chunk(s), ${shortWorker(ev.worker)}, batch <code>${shortId(ev.batch_id)}</code>`];
- case "SendExhausted": return ["error", `✗ send exhausted — ${shortWorker(ev.worker)}: ${ev.error}`];
+ case "BatchDispatched": return ["", `poll <code>${shortId(ev.batch_id)}</code> dispatched — ${ev.messages} msgs, ${ev.partitions.length} partition(s)`];
+ case "RequestSent": {
+ const tags = [];
+ if (ev.replay) tags.push("replay");
+ if (ev.budgeted) tags.push("budget");
+ return ["accent", `→ request <code>#${ev.request_id}</code> to ${shortWorker(ev.worker)} — ${ev.messages} msgs, ${ev.routing_keys} key(s), ${fmtBytes(ev.bytes)}${tags.length ? `<span class="tag"> · ${tags.join(" · ")}</span>` : ""}`];
+ }
+ case "RequestResolved": return ev.unfinished
+ ? ["warn", `◐ request <code>#${ev.request_id}</code> partial — ${shortWorker(ev.worker)} acked ${ev.accepted}, ${ev.unfinished} unfinished`]
+ : ["", `✓ request <code>#${ev.request_id}</code> acked — ${shortWorker(ev.worker)}, ${ev.accepted} msgs`];
+ case "RequestFailed": return [ev.cause === "busy" ? "warn" : "error", `✗ request <code>#${ev.request_id}</code> failed [${ev.cause}] — ${shortWorker(ev.worker)}, ${ev.messages} msgs requeued`];
+ case "BatchCommitted": return ["good", `✓ committed poll <code>${shortId(ev.batch_id)}</code> — ${ev.accepted} msgs in ${ev.duration_ms}ms`];
+ case "BatchFailed": return ["error", `✗ poll failed — ${ev.error}`];
+ case "CommitFailed": return ["error", `✗ commit failed — ${ev.error}`];
case "WorkerStateChanged": return [ev.to === "unhealthy" ? "error" : ev.to === "healthy" ? "good" : "warn", `worker ${shortWorker(ev.worker)} ${ev.from} → ${ev.to}`];
case "WorkerMembership": return ["accent", `worker ${shortWorker(ev.worker)} ${ev.action}`];
default: return ["", ev.type];
@@ -434,130 +561,174 @@
scheduleRender();
}
- // ---------- batches + commits rendering (throttled) ----------
+ // ---------- polls + commits rendering (throttled) ----------
function scheduleRender() {
if (renderPending) return;
renderPending = true;
setTimeout(() => {
renderPending = false;
- $("badge-batches").textContent = batchOrder.length ? `(${batchOrder.length})` : "";
+ $("badge-polls").textContent = pollOrder.length ? `(${pollOrder.length})` : "";
$("badge-commits").textContent = commits.length ? (oooCount ? `(${commits.length} · ⚠${oooCount})` : `(${commits.length})`) : "";
- // While the list is paused, freeze it so a batch doesn't scroll away
+ // While the list is paused, freeze it so a poll doesn't scroll away
// before you can click it, but keep an open detail view live.
- if (activeTab === "batches" && (!$("batches-pause").checked || selectedBatch)) renderBatches();
+ if (activeTab === "polls" && (!$("polls-pause").checked || selectedPoll)) renderPolls();
if (activeTab === "commits") renderCommits();
}, 250);
}
- function workerAgg(b) {
+ // A poll's requests, grouped by the worker that received them.
+ function workerAgg(p) {
const m = {};
- const touch = (w) => (m[w] = m[w] || { worker: w, messages: 0, assignedMsgs: 0, retries: 0, splits: 0, exhausted: false });
- b.assigned.forEach((s) => { const x = touch(s.worker); x.messages += s.messages; x.assignedMsgs += s.messages; });
- b.retries.forEach((r) => (touch(r.worker).retries += 1));
- b.splits.forEach((s) => (touch(s.worker).splits += 1));
- b.exhausted.forEach((e) => (touch(e.worker).exhausted = true));
+ const touch = (w) => (m[w] = m[w] || { worker: w, requests: 0, messages: 0, acked: 0, unfinished: 0, failed: 0, replays: 0, pending: 0 });
+ pollRequests(p).forEach((r) => {
+ const x = touch(r.worker || "?");
+ x.requests += 1; x.messages += r.messages;
+ if (r.replay) x.replays += 1;
+ if (r.resolved) { x.acked += r.resolved.accepted; x.unfinished += r.resolved.unfinished; }
+ else if (r.failed) x.failed += 1;
+ else x.pending += 1;
+ });
return Object.values(m);
}
- function renderBatches() {
- const view = $("batches-view");
- if (selectedBatch && batches[selectedBatch]) { renderBatchDetail(batches[selectedBatch]); return; }
- selectedBatch = null;
+ function renderPolls() {
+ const view = $("polls-view");
+ if (selectedPoll && polls[selectedPoll]) { renderPollDetail(polls[selectedPoll]); return; }
+ selectedPoll = null;
openDetailId = null;
- const issuesOnly = $("batches-issues").checked;
- let ids = batchOrder.slice().reverse();
- if (issuesOnly) ids = ids.filter((id) => hadIssue(batches[id]));
+ const issuesOnly = $("polls-issues").checked;
+ let ids = pollOrder.slice().reverse();
+ if (issuesOnly) ids = ids.filter((id) => hadIssue(polls[id]));
if (!ids.length) {
- view.innerHTML = `<div class="empty">${issuesOnly ? "No batches with retries or failures yet…" : "Waiting for batches…"}</div>`;
+ view.innerHTML = `<div class="empty">${issuesOnly ? "No polls with failed, partial or replayed requests yet…" : "Waiting for polls…"}</div>`;
return;
}
const rows = ids.map((id) => {
- const b = batches[id];
- const st = batchStatus(b);
- const workers = workerAgg(b);
- const badges = [];
- badges.push(`<span class="badge-min">${workers.length}w</span>`);
- const retries = b.retries.length;
- if (retries) badges.push(`<span class="badge-min warn">↻${retries}</span>`);
- if (b.splits.length) badges.push(`<span class="badge-min warn">✂${b.splits.length}</span>`);
- if (b.exhausted.length) badges.push(`<span class="badge-min error">✗${b.exhausted.length}</span>`);
+ const p = polls[id];
+ const st = pollStatus(p);
+ const rs = pollRequests(p);
+ const workers = new Set(rs.map((r) => r.worker)).size;
+ const replays = rs.filter((r) => r.replay).length;
+ const partial = rs.filter(isPartial).length;
+ const failed = rs.filter((r) => r.failed).length;
+ const badges = [`<span class="badge-min">${rs.length}req · ${workers}w</span>`];
+ if (replays) badges.push(`<span class="badge-min warn">↻${replays}</span>`);
+ if (partial) badges.push(`<span class="badge-min warn">◐${partial}</span>`);
+ if (failed) badges.push(`<span class="badge-min error">✗${failed}</span>`);
return `<div class="brow" data-id="${id}">
<span class="id">${shortId(id)}</span>
<span><span class="pill ${st}">${st === "inflight" ? "in-flight" : st}</span></span>
<span class="badges">${badges.join("")}</span>
- <span class="tm">${b.messages} msg · ${b.ts ? fmtTime(b.ts) : ""}</span>
+ <span class="tm">${p.messages} msg · ${p.ts ? fmtTime(p.ts) : ""}</span>
</div>`;
}).join("");
setHTML(view, `<div class="blist">${rows}</div>`, "prepend");
- view.querySelectorAll(".brow").forEach((el) => el.addEventListener("click", () => { selectedBatch = el.dataset.id; renderBatchDetail(batches[selectedBatch]); }));
+ view.querySelectorAll(".brow").forEach((el) => el.addEventListener("click", () => { selectedPoll = el.dataset.id; renderPollDetail(polls[selectedPoll]); }));
+ }
+
+ function requestOutcome(r) {
+ if (r.resolved) {
+ return r.resolved.unfinished
+ ? `<span class="pill partial">partial · ${r.resolved.unfinished} unfinished</span>`
+ : `<span class="pill committed">acked ${r.resolved.accepted}</span>`;
+ }
+ if (r.failed) return `<span class="pill ${r.failed.cause === "busy" ? "retrying" : "failed"}">${r.failed.cause}</span>`;
+ return `<span class="pill inflight">in-flight</span>`;
}
- function renderBatchDetail(b) {
- const view = $("batches-view");
- const st = batchStatus(b);
- const workers = workerAgg(b);
+ function renderPollDetail(p) {
+ const view = $("polls-view");
+ const st = pollStatus(p);
+ const rs = pollRequests(p);
+ const workers = workerAgg(p);
const sum = [
["status", `<span class="pill ${st}">${st === "inflight" ? "in-flight" : st}</span>`],
- ["messages", b.messages],
- ["distinct_ids", b.distinct_ids],
+ ["messages", p.messages],
+ ["requests", rs.length],
["workers", workers.length],
- ["retries", b.retries.length],
- ["splits", b.splits.length],
+ ["replays", rs.filter((r) => r.replay).length],
+ ["partial", rs.filter(isPartial).length],
+ ["failed", rs.filter((r) => r.failed).length],
].map(([l, n]) => `<div class="stat"><div class="n">${n}</div><div class="l">${l}</div></div>`).join("");
- const flow = buildFlow(b, workers);
+ const flow = buildFlow(p, workers);
+
+ const requestRows = rs.map((r) => {
+ const settled = r.resolved ? r.resolved.ts : r.failed ? r.failed.ts : null;
+ const tags = [r.replay ? "replay" : "", r.budgeted ? "budget" : "", r.polls.length > 1 ? `${r.polls.length} polls` : ""].filter(Boolean).join(" · ");
+ return `<tr>
+ <td class="mono">#${r.id}</td>
+ <td class="mono">${shortWorker(r.worker)}</td>
+ <td class="mono">${r.messages}</td>
+ <td class="mono">${r.routing_keys}</td>
+ <td class="mono">${fmtBytes(r.bytes)}</td>
+ <td>${requestOutcome(r)}</td>
+ <td class="mono">${settled !== null ? fmtDur(settled - r.ts) : "—"}</td>
+ <td class="mono">${tags}</td>
+ </tr>`;
+ }).join("") || `<tr><td class="empty" colspan="8">No request carries this poll's offsets yet</td></tr>`;
- const timeline = b.events.map((ev) => {
+ // A request's events sit on every poll it carries, so order the
+ // timeline by sequence to interleave them with the poll's own.
+ const timeline = p.events.slice().sort((a, b) => a.seq - b.seq).map((ev) => {
const [cls, html] = describe(ev);
return `<div class="item ${cls}"><span class="t">${fmtTime(ev.ts_ms)}</span>${html}</div>`;
}).join("");
- const fresh = openDetailId !== b.id;
- openDetailId = b.id;
+ const fresh = openDetailId !== p.id;
+ openDetailId = p.id;
const detailHtml = `<div class="detail">
- <span class="back" id="back">← all batches</span>
+ <span class="back" id="back">← all polls</span>
<div class="dsum">${sum}</div>
- <h2 style="border:none;padding:0 0 8px;">Flow · batch ${shortId(b.id)}</h2>
+ <h2 style="border:none;padding:0 0 8px;">Flow · poll ${shortId(p.id)}</h2>
<div class="flow-legend">
- <span><i style="background:#4f7cff"></i>routed</span>
- <span><i style="background:#f85149"></i>send failed</span>
+ <span><i style="background:#4f7cff"></i>sent</span>
+ <span><i style="background:#d29922"></i>replay / partial</span>
+ <span><i style="background:#f85149"></i>failed</span>
<span><i style="background:#3fb950"></i>acked / committed</span>
</div>
${flow.html}
- <h2 style="border:none;padding:0 0 8px;">Lifecycle</h2>
+ <h2 style="border:none;padding:0 0 8px;">Requests</h2>
+ <table><thead><tr><th>Request</th><th>Worker</th><th>Msgs</th><th>Keys</th><th>Bytes</th><th>Outcome</th><th>Took</th><th></th></tr></thead><tbody>${requestRows}</tbody></table>
+ <h2 style="border:none;padding:12px 0 8px;">Lifecycle</h2>
<div class="tl">${timeline}</div>
</div>`;
setHTML(view, detailHtml, fresh ? "none" : "append");
- $("back").addEventListener("click", () => { selectedBatch = null; renderBatches(); });
+ $("back").addEventListener("click", () => { selectedPoll = null; renderPolls(); });
requestAnimationFrame(() => drawEdges(document.getElementById("flow"), flow.edges));
}
- // Build the node/edge model for a batch's flow graph. Nodes sit in four
- // lanes (Kafka → assign → workers → commit).
- function buildFlow(b, workers) {
- const partsShort = b.partitions.map((p) => `${p.partition}@${p.offset}`).join(" ") || "—";
- const sourceNode = `<div class="node src" id="n-source"><div class="title">Kafka batch</div><div class="big">${b.messages}</div><div class="sub">msgs · p ${partsShort}</div></div>`;
- const assignNode = `<div class="node" id="n-assign"><div class="title">Assign</div><div class="big">${b.distinct_ids}</div><div class="sub">distinct_ids</div></div>`;
+ // Build the node/edge model for a poll's flow graph. Nodes sit in four
+ // lanes (Kafka → batcher → workers → commit).
+ function buildFlow(p, workers) {
+ const partsShort = p.partitions.map((pp) => `${pp.partition}@${pp.offset}`).join(" ") || "—";
+ const sourceNode = `<div class="node src" id="n-source"><div class="title">Kafka poll</div><div class="big">${p.messages}</div><div class="sub">msgs · p ${partsShort}</div></div>`;
+ const rs = pollRequests(p);
+ const keyRuns = rs.reduce((a, r) => a + r.routing_keys, 0);
+ const batcherNode = `<div class="node" id="n-batcher"><div class="title">Batcher</div><div class="big">${rs.length}</div><div class="sub">request(s) · ${keyRuns} key run(s)</div></div>`;
const workerNodes = workers.map((w, i) => {
- const cls = w.exhausted ? "stalled" : b.committed ? "acked" : "";
+ const settled = w.pending === 0 && w.requests > 0;
+ const cls = w.failed ? "stalled" : settled ? "acked" : "";
const badges = [];
- if (w.retries) badges.push(`<span class="badge-min warn">↻${w.retries}</span>`);
- if (w.splits) badges.push(`<span class="badge-min warn">✂×${w.splits}</span>`);
- if (w.exhausted) badges.push(`<span class="badge-min error">exhausted</span>`);
- if (!w.exhausted && b.committed) badges.push(`<span class="badge-min">✓ acked</span>`);
- return `<div class="node worker ${cls}" id="n-w-${i}"><div class="title">${shortWorker(w.worker)}</div><div class="big">${w.assignedMsgs}</div><div class="sub">${badges.join(" ") || "sent"}</div></div>`;
- }).join("") || '<div class="node" id="n-w-none"><div class="sub">not yet assigned</div></div>';
-
- const sinkNode = b.committed
- ? `<div class="node sink-ok" id="n-sink"><div class="title">Committed</div><div class="big">${b.committed.accepted}</div><div class="sub">${b.committed.duration_ms}ms · ${b.committed.partitions.map((p) => `${p.partition}@${p.offset}`).join(" ")}</div></div>`
- : `<div class="node sink-pending" id="n-sink"><div class="title">In-flight</div><div class="sub">not committed</div></div>`;
+ if (w.replays) badges.push(`<span class="badge-min warn">↻${w.replays}</span>`);
+ if (w.unfinished) badges.push(`<span class="badge-min warn">◐${w.unfinished}</span>`);
+ if (w.failed) badges.push(`<span class="badge-min error">✗${w.failed}</span>`);
+ if (settled && !w.failed) badges.push(`<span class="badge-min">✓ acked ${w.acked}</span>`);
+ return `<div class="node worker ${cls}" id="n-w-${i}"><div class="title">${shortWorker(w.worker)}</div><div class="big">${w.messages}</div><div class="sub">${w.requests} req · ${badges.join(" ") || "in flight"}</div></div>`;
+ }).join("") || '<div class="node" id="n-w-none"><div class="sub">no request yet</div></div>';
+
+ const sinkNode = p.committed
+ ? `<div class="node sink-ok" id="n-sink"><div class="title">Committed</div><div class="big">${p.committed.accepted}</div><div class="sub">${p.committed.duration_ms}ms · ${p.committed.partitions.map((pp) => `${pp.partition}@${pp.offset}`).join(" ")}</div></div>`
+ : p.failed
+ ? `<div class="node worker stalled" id="n-sink"><div class="title">Failed</div><div class="sub">${escapeXml(p.failed.error)}</div></div>`
+ : `<div class="node sink-pending" id="n-sink"><div class="title">In-flight</div><div class="sub">not committed</div></div>`;
const html = `<div class="flow" id="flow">
<div class="flow-main">
<div class="flow-col">${sourceNode}</div>
- <div class="flow-col">${assignNode}</div>
+ <div class="flow-col">${batcherNode}</div>
<div class="flow-col">${workerNodes}</div>
<div class="flow-col">${sinkNode}</div>
</div>
@@ -566,12 +737,15 @@
const C = { muted: "#8b93a1", warn: "#d29922", good: "#3fb950", error: "#f85149", accent: "#4f7cff" };
const edges = [];
- edges.push({ from: "n-source", to: "n-assign", label: `${b.messages} msgs`, color: C.accent });
- workers.forEach((w, i) => { if (w.assignedMsgs > 0) edges.push({ from: "n-assign", to: `n-w-${i}`, label: `sent ${w.assignedMsgs}${w.retries ? ` · ↻${w.retries}` : ""}`, color: w.retries ? C.warn : C.muted }); });
+ edges.push({ from: "n-source", to: "n-batcher", label: `${p.messages} msgs`, color: C.accent });
+ workers.forEach((w, i) => {
+ const color = w.failed ? C.error : (w.replays || w.unfinished) ? C.warn : C.muted;
+ edges.push({ from: "n-batcher", to: `n-w-${i}`, label: `${w.requests} req · ${w.messages} msgs`, color });
+ });
- if (b.committed) {
- if (workers.length) workers.forEach((w, i) => { if (!w.exhausted) edges.push({ from: `n-w-${i}`, to: "n-sink", label: "acked", color: C.good }); });
- else edges.push({ from: "n-assign", to: "n-sink", label: "", color: C.good });
+ if (p.committed) {
+ if (workers.length) workers.forEach((w, i) => { if (!w.failed) edges.push({ from: `n-w-${i}`, to: "n-sink", label: "acked", color: C.good }); });
+ else edges.push({ from: "n-batcher", to: "n-sink", label: "", color: C.good });
}
return { html, edges };
@@ -666,19 +840,19 @@
activeTab = t.dataset.tab;
document.querySelectorAll(".tab").forEach((x) => x.classList.toggle("active", x === t));
$("tab-feed").style.display = activeTab === "feed" ? "" : "none";
- $("tab-batches").style.display = activeTab === "batches" ? "" : "none";
+ $("tab-polls").style.display = activeTab === "polls" ? "" : "none";
$("tab-commits").style.display = activeTab === "commits" ? "" : "none";
- if (activeTab === "batches") renderBatches();
+ if (activeTab === "polls") renderPolls();
if (activeTab === "commits") renderCommits();
})
);
- // Re-render immediately when the batch filters change (and on un-pause).
- $("batches-issues").addEventListener("change", renderBatches);
- $("batches-pause").addEventListener("change", () => { if (!$("batches-pause").checked) renderBatches(); });
+ // Re-render immediately when the poll filters change (and on un-pause).
+ $("polls-issues").addEventListener("change", renderPolls);
+ $("polls-pause").addEventListener("change", () => { if (!$("polls-pause").checked) renderPolls(); });
// Redraw the flow graph's edges when the layout width changes.
window.addEventListener("resize", () => {
- if (activeTab === "batches" && selectedBatch && batches[selectedBatch]) renderBatchDetail(batches[selectedBatch]);
+ if (activeTab === "polls" && selectedPoll && polls[selectedPoll]) renderPollDetail(polls[selectedPoll]);
});
// ---------- live SSE ----------