: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ingestion): message browser in control plane kafka visualizer (#78696)
José Sequeirae4651461d317
diff --git a/rust/ingestion-control-plane/README.md b/rust/ingestion-control-plane/README.mdindex 8132edd59eff..0ece4fca339c 100644--- a/rust/ingestion-control-plane/README.md+++ b/rust/ingestion-control-plane/README.md@@ -15,6 +15,8 @@ Discovers ingestion topics and consumer groups from the cluster by prefix (a groResults are broken down per token (resolved to `team_id` via Postgres when `DATABASE_URL` is set), with events and distinct_ids nested under each token, plus a message-size distribution and header-flag counts. Analyses use a dedicated consumer group (`ingestion-control-plane-inspector`) and never touch the real group's offsets.+Clicking a team, event, or distinct_id in an analysis result opens the message browser: a filtered scan over the same partition (`/api/messages`) that lists individual matching messages. Filters are equality matches on the `token`, `event`, and `distinct_id` headers; a facets sidebar aggregates the loaded messages so results can be narrowed further. Each request returns up to 100 matches and a cursor, and "Load more" resumes from it; per-request scanning is bounded by a message budget, a deadline, and a byte budget so a rarely-matching filter still returns promptly. Matched messages carry their payload (truncated to 64 KB per message), shown by expanding a row, so this surface exposes raw event payloads — another reason the tool must stay behind the internal ingress.+### Consumer debugLists live ingestion-consumer pods and serves the consumer's routing debug UI per pod at `/pods/<namespace>/<name>/` (static pods use the `static` pseudo-namespace), backed by a proxy to the pod's debug API (`/debug/state`, `/debug/load`, SSE `/debug/events`). The UI lives here; the consumer only exposes the JSON/SSE API (gated behind `DEBUG_UI_ENABLED` on the consumer side).@@ -34,6 +36,10 @@ Lists live ingestion-consumer pods and serves the consumer's routing debug UI pe| `ANALYSIS_MESSAGE_COUNT` | `10000` | Messages per analysis || `ANALYSIS_DEADLINE_SECS` | `120` | || `ANALYSIS_MAX_FETCH_BYTES` | `536870912` | Kafka transfers full records even for header-only analysis |+| `BROWSE_SCAN_MESSAGE_COUNT` | `25000` | Messages scanned per message-browser request |+| `BROWSE_DEADLINE_SECS` | `10` | |+| `BROWSE_MAX_FETCH_BYTES` | `268435456` | Byte budget per message-browser request |+| `BROWSE_MAX_CONCURRENT` | `3` | Concurrent browse requests; more get 429 || `POD_DISCOVERY_MODE` | `kubernetes` | `static` for local testing || `STATIC_PODS` | `local=127.0.0.1:3301` | `name=host:port` pairs for static mode || `POD_LABEL_SELECTORS` | `ingestion-analytics-main/app=ingestion-analytics-main,ingestion-analytics-async/app=ingestion-analytics-async` | One `namespace/key=value` per entry (each lane runs in its own namespace); bare `key=value` uses `K8S_NAMESPACE` |diff --git a/rust/ingestion-control-plane/src/api.rs b/rust/ingestion-control-plane/src/api.rsindex 55ab1d38ab1f..ea5b26aee654 100644--- a/rust/ingestion-control-plane/src/api.rs+++ b/rust/ingestion-control-plane/src/api.rs@@ -1,5 +1,8 @@+use std::collections::HashMap;use std::sync::Arc;+use std::time::Duration;+use anyhow::Context;use axum::extract::{Path, Query, State};use axum::http::StatusCode;use axum::response::{IntoResponse, Response};@@ -12,6 +15,8 @@ use uuid::Uuid;use k8s_awareness::DiscoveredPod;use crate::jobs::{AnalysisRequest, JobView};+use crate::kafka::browse::{self, BrowseParams, BrowseStop, MessageFilter, MessageRecord};+use crate::kafka::client;use crate::kafka::lag::{self, ConsumerTarget, GroupLag, LagOverview};use crate::proxy;use crate::state::AppState;@@ -195,6 +200,117 @@ async fn cancel_analysis(}}+#[derive(Deserialize)]+struct MessagesQuery {+ group: String,+ topic: String,+ partition: i32,+ /// Cursor; defaults to the group's committed offset (or the low+ /// watermark when the group never committed).+ start_offset: Option<i64>,+ limit: Option<usize>,+ token: Option<String>,+ event: Option<String>,+ distinct_id: Option<String>,+}++#[derive(Serialize)]+struct MessagesResponse {+ partition: i32,+ start_offset: i64,+ /// Cursor for the next page.+ next_offset: i64,+ low_watermark: i64,+ high_watermark: i64,+ scanned: u64,+ stop: BrowseStop,+ reached_end: bool,+ duration_ms: u64,+ messages: Vec<MessageRecord>,+ /// team_id per distinct token in `messages` (null when unresolvable).+ token_teams: HashMap<String, Option<i32>>,+}++/// Synchronous filtered scan of one partition, returning matched message+/// headers (never payloads) plus a cursor. Bounded per request by the page+/// limit, a scan budget, a deadline, and a byte budget, whichever hits first.+async fn get_messages(+ State(state): State<AppState>,+ Query(query): Query<MessagesQuery>,+) -> Result<Json<MessagesResponse>, ApiError> {+ let target = validated_target(&state, &query.group, &query.topic).await?;+ if query.partition < 0 {+ return Err(ApiError::bad_request("partition must be non-negative"));+ }+ let limit = query.limit.unwrap_or(100).clamp(1, 500);+ // An empty query-param value means "not filtered", so it can never pin a+ // filter to the empty string.+ let non_empty = |s: Option<String>| s.filter(|s| !s.is_empty());+ let filter = MessageFilter {+ token: non_empty(query.token),+ event: non_empty(query.event),+ distinct_id: non_empty(query.distinct_id),+ };++ let Ok(_permit) = Arc::clone(&state.browse_permits).try_acquire_owned() else {+ return Err(ApiError::too_many_requests(+ "too many concurrent message scans; wait for one to finish",+ ));+ };++ let config = Arc::clone(&state.config);+ let partition = query.partition;+ let requested_start = query.start_offset;+ let (bounds, start_offset, outcome) = tokio::task::spawn_blocking(move || {+ let timeout = Duration::from_millis(config.kafka_metadata_timeout_ms);+ let bounds = lag::fetch_partition_bounds_blocking(&config, &target, partition, timeout)?;+ let start_offset = requested_start+ .unwrap_or_else(|| bounds.committed_offset.unwrap_or(bounds.low_watermark))+ .clamp(bounds.low_watermark, bounds.high_watermark);+ let params = BrowseParams {+ topic: target.topic.clone(),+ partition,+ start_offset,+ end_offset_exclusive: bounds.high_watermark,+ limit,+ scan_limit: config.browse_scan_message_count,+ deadline: Duration::from_secs(config.browse_deadline_secs),+ max_bytes: config.browse_max_fetch_bytes,+ poll_timeout: Duration::from_millis(config.kafka_fetch_poll_timeout_ms),+ };+ let consumer = client::fetch_consumer(&config).context("create fetch client")?;+ let outcome = browse::run_browse(&consumer, ¶ms, &filter)?;+ anyhow::Ok((bounds, start_offset, outcome))+ })+ .await+ .context("browse task panicked")+ .and_then(|res| res)+ .map_err(|e| ApiError::upstream(format!("message scan failed: {e:#}")))?;++ let mut tokens: Vec<String> = outcome+ .records+ .iter()+ .filter_map(|record| record.token.clone())+ .collect();+ tokens.sort();+ tokens.dedup();+ let token_teams = state.teams.resolve(&tokens).await;++ Ok(Json(MessagesResponse {+ partition: query.partition,+ start_offset,+ next_offset: outcome.next_offset,+ low_watermark: bounds.low_watermark,+ high_watermark: bounds.high_watermark,+ scanned: outcome.scanned,+ stop: outcome.stop,+ reached_end: outcome.next_offset >= bounds.high_watermark,+ duration_ms: outcome.duration_ms,+ messages: outcome.records,+ token_teams,+ }))+}+#[derive(Serialize)]struct PodsResponse {pods: Vec<DiscoveredPod>,@@ -214,6 +330,7 @@ pub fn router(state: AppState) -> Router {.route("/", get(ui::index)).route("/api/lag", get(get_lag)).route("/api/lag/overview", get(get_lag_overview))+ .route("/api/messages", get(get_messages)).route("/api/analyses", get(list_analyses).post(create_analysis)).route("/api/analyses/:id",diff --git a/rust/ingestion-control-plane/src/config.rs b/rust/ingestion-control-plane/src/config.rsindex c5df18d9e783..df4f0ce15fd9 100644--- a/rust/ingestion-control-plane/src/config.rs+++ b/rust/ingestion-control-plane/src/config.rs@@ -87,6 +87,24 @@ pub struct Config {#[envconfig(default = "2")]pub analysis_max_concurrent_jobs: usize,+ /// Messages scanned per synchronous browse request while filling a page+ /// of matches; a rarely-matching filter stops here and resumes from the+ /// returned cursor on the next request.+ #[envconfig(default = "25000")]+ pub browse_scan_message_count: u64,++ #[envconfig(default = "10")]+ pub browse_deadline_secs: u64,++ /// Kafka transfers full records even though browsing only returns+ /// headers, so bound the bytes fetched per request. 256 MiB by default.+ #[envconfig(default = "268435456")]+ pub browse_max_fetch_bytes: u64,++ /// Concurrent synchronous browse requests; more are rejected with 429.+ #[envconfig(default = "3")]+ pub browse_max_concurrent: usize,+/// `kubernetes` discovers consumer pods via the K8s API; `static` uses/// the fixed `STATIC_PODS` list (local testing, like the/// ingestion-consumer's static worker discovery).diff --git a/rust/ingestion-control-plane/src/kafka/browse.rs b/rust/ingestion-control-plane/src/kafka/browse.rsnew file mode 100644index 000000000000..0cde778ed54a--- /dev/null+++ b/rust/ingestion-control-plane/src/kafka/browse.rs@@ -0,0 +1,344 @@+use std::time::{Duration, Instant};++use anyhow::Context;+use common_types::CapturedEventHeaders;+use rdkafka::consumer::{BaseConsumer, Consumer};+use rdkafka::message::Message;+use rdkafka::{Offset, TopicPartitionList};+use serde::Serialize;++/// Why a browse scan stopped where it did.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]+#[serde(rename_all = "snake_case")]+pub enum BrowseStop {+ /// Collected the requested number of matching messages.+ Limit,+ /// Scanned the per-request message budget before filling the page.+ ScanBudget,+ Deadline,+ ByteBudget,+ /// Caught up with the high watermark.+ EndOfPartition,+}++/// Equality filters over message headers. No filters matches every message;+/// a message without headers only matches when no filters are set, since it+/// has no values to compare against.+#[derive(Debug, Default, Clone)]+pub struct MessageFilter {+ pub token: Option<String>,+ pub event: Option<String>,+ pub distinct_id: Option<String>,+}++impl MessageFilter {+ fn is_empty(&self) -> bool {+ self.token.is_none() && self.event.is_none() && self.distinct_id.is_none()+ }++ pub fn matches(&self, headers: Option<&CapturedEventHeaders>) -> bool {+ let Some(headers) = headers else {+ return self.is_empty();+ };+ let wants = |want: &Option<String>, got: &Option<String>| match want {+ None => true,+ Some(want) => got.as_deref() == Some(want.as_str()),+ };+ wants(&self.token, &headers.token)+ && wants(&self.event, &headers.event)+ && wants(&self.distinct_id, &headers.distinct_id)+ }+}++/// Per-message cap on payload bytes carried in a record. Kafka already+/// transferred the full record to scan its headers, so keeping a bounded+/// slice costs nothing extra on the broker side while keeping a 100-message+/// response from ballooning past a few MB.+const PAYLOAD_LIMIT: usize = 65_536;++/// One matched message: headers plus the payload, truncated to+/// [`PAYLOAD_LIMIT`] bytes.+#[derive(Debug, Clone, Serialize)]+pub struct MessageRecord {+ pub offset: i64,+ /// Broker/producer timestamp in epoch milliseconds, when present.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub timestamp_ms: Option<i64>,+ pub payload_bytes: u64,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub token: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub distinct_id: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub event: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub uuid: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub session_id: Option<String>,+ /// The event's own `timestamp` header, distinct from the Kafka timestamp.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub event_timestamp: Option<String>,+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub missing_headers: bool,+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub historical_migration: bool,+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub force_disable_person_processing: bool,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub dlq_reason: Option<String>,+ /// Payload text (lossy UTF-8; ingestion topics carry plain JSON),+ /// truncated to [`PAYLOAD_LIMIT`] bytes.+ pub payload: String,+ #[serde(skip_serializing_if = "std::ops::Not::not")]+ pub payload_truncated: bool,+}++impl MessageRecord {+ fn new(+ offset: i64,+ timestamp_ms: Option<i64>,+ payload: &[u8],+ headers: Option<&CapturedEventHeaders>,+ ) -> Self {+ let payload_bytes = payload.len() as u64;+ let payload_truncated = payload.len() > PAYLOAD_LIMIT;+ // Lossy conversion on a byte cut can split a UTF-8 sequence; the+ // replacement character at the cut point is fine for display.+ let payload = String::from_utf8_lossy(&payload[..payload.len().min(PAYLOAD_LIMIT)]);+ let base = Self {+ offset,+ timestamp_ms,+ payload_bytes,+ token: None,+ distinct_id: None,+ event: None,+ uuid: None,+ session_id: None,+ event_timestamp: None,+ missing_headers: true,+ historical_migration: false,+ force_disable_person_processing: false,+ dlq_reason: None,+ payload: payload.into_owned(),+ payload_truncated,+ };+ let Some(headers) = headers else {+ return base;+ };+ Self {+ token: headers.token.clone(),+ distinct_id: headers.distinct_id.clone(),+ event: headers.event.clone(),+ uuid: headers.uuid.clone(),+ session_id: headers.session_id.clone(),+ event_timestamp: headers.timestamp.clone(),+ missing_headers: false,+ historical_migration: headers.historical_migration == Some(true),+ force_disable_person_processing: headers.force_disable_person_processing == Some(true),+ dlq_reason: headers.dlq_reason.clone(),+ ..base+ }+ }+}++pub struct BrowseParams {+ pub topic: String,+ pub partition: i32,+ pub start_offset: i64,+ /// Where to stop reading (the high watermark at request time).+ pub end_offset_exclusive: i64,+ /// Matching messages to collect before returning.+ pub limit: usize,+ /// Messages to scan before returning even without a full page, so a+ /// filter that matches nothing still returns promptly with a cursor.+ pub scan_limit: u64,+ pub deadline: Duration,+ pub max_bytes: u64,+ pub poll_timeout: Duration,+}++pub struct BrowseOutcome {+ pub records: Vec<MessageRecord>,+ /// Next unread offset; the cursor for the follow-up request.+ pub next_offset: i64,+ pub scanned: u64,+ pub stop: BrowseStop,+ pub duration_ms: u64,+}++/// Scan `[start_offset, end_offset_exclusive)` on one partition, collecting+/// records for messages matching `filter` until a stop condition hits.+/// Non-matching payloads are dropped immediately; matching ones are kept,+/// truncated to [`PAYLOAD_LIMIT`]. Synchronous, so run it on the blocking+/// pool.+pub fn run_browse(+ consumer: &BaseConsumer,+ params: &BrowseParams,+ filter: &MessageFilter,+) -> anyhow::Result<BrowseOutcome> {+ let mut tpl = TopicPartitionList::new();+ tpl.add_partition_offset(+ ¶ms.topic,+ params.partition,+ Offset::Offset(params.start_offset),+ )+ .context("build assignment")?;+ consumer.assign(&tpl).context("assign partition")?;++ let started = Instant::now();+ let mut records: Vec<MessageRecord> = Vec::new();+ let mut next_offset = params.start_offset;+ let mut scanned: u64 = 0;+ let mut bytes_read: u64 = 0;++ let stop = loop {+ if next_offset >= params.end_offset_exclusive {+ break BrowseStop::EndOfPartition;+ }+ if records.len() >= params.limit {+ break BrowseStop::Limit;+ }+ if scanned >= params.scan_limit {+ break BrowseStop::ScanBudget;+ }+ if bytes_read >= params.max_bytes {+ break BrowseStop::ByteBudget;+ }+ if started.elapsed() >= params.deadline {+ break BrowseStop::Deadline;+ }++ let Some(result) = consumer.poll(params.poll_timeout) else {+ continue;+ };+ let message = result.context("poll partition")?;+ // librdkafka prefetches; drop anything past the requested range.+ if message.offset() >= params.end_offset_exclusive {+ break BrowseStop::EndOfPartition;+ }++ let payload_size = message.payload_len() as u64;+ let headers = message+ .headers()+ .map(|h| CapturedEventHeaders::from(h.detach()));+ if filter.matches(headers.as_ref()) {+ records.push(MessageRecord::new(+ message.offset(),+ message.timestamp().to_millis(),+ message.payload().unwrap_or_default(),+ headers.as_ref(),+ ));+ }++ next_offset = message.offset() + 1;+ scanned += 1;+ bytes_read += payload_size;+ };++ Ok(BrowseOutcome {+ records,+ next_offset,+ scanned,+ stop,+ duration_ms: started.elapsed().as_millis() as u64,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn headers(token: &str, distinct_id: &str, event: &str) -> CapturedEventHeaders {+ CapturedEventHeaders {+ token: Some(token.to_string()),+ distinct_id: Some(distinct_id.to_string()),+ session_id: None,+ timestamp: None,+ event: Some(event.to_string()),+ uuid: None,+ now: None,+ force_disable_person_processing: None,+ historical_migration: None,+ skip_heatmap_processing: None,+ dlq_reason: None,+ dlq_step: None,+ dlq_timestamp: None,+ content_encoding: None,+ }+ }++ fn filter(+ token: Option<&str>,+ event: Option<&str>,+ distinct_id: Option<&str>,+ ) -> MessageFilter {+ MessageFilter {+ token: token.map(String::from),+ event: event.map(String::from),+ distinct_id: distinct_id.map(String::from),+ }+ }++ #[test]+ fn filters_are_conjunctive_equality_matches() {+ let h = headers("token_a", "user_1", "$pageview");+ let cases = [+ (filter(None, None, None), true),+ (filter(Some("token_a"), None, None), true),+ (filter(Some("token_b"), None, None), false),+ (filter(Some("token_a"), Some("$pageview"), None), true),+ (filter(Some("token_a"), Some("$identify"), None), false),+ (filter(None, None, Some("user_1")), true),+ (+ filter(Some("token_a"), Some("$pageview"), Some("user_2")),+ false,+ ),+ ];+ for (f, expected) in cases {+ assert_eq!(f.matches(Some(&h)), expected, "{f:?}");+ }+ }++ #[test]+ fn headerless_messages_match_only_the_empty_filter() {+ assert!(filter(None, None, None).matches(None));+ assert!(!filter(Some("token_a"), None, None).matches(None));+ }++ #[test]+ fn filtered_header_field_must_be_present_to_match() {+ // A filter on a field the message lacks must not match: missing is+ // not a wildcard.+ let mut h = headers("token_a", "user_1", "$pageview");+ h.event = None;+ assert!(!filter(None, Some("$pageview"), None).matches(Some(&h)));+ }++ #[test]+ fn record_carries_flags_and_payload() {+ let mut h = headers("token_a", "user_1", "$pageview");+ h.historical_migration = Some(true);+ let record = MessageRecord::new(42, Some(1_700_000_000_000), b"{\"a\":1}", Some(&h));+ assert_eq!(record.offset, 42);+ assert_eq!(record.payload_bytes, 7);+ assert_eq!(record.payload, "{\"a\":1}");+ assert!(!record.payload_truncated);+ assert_eq!(record.token.as_deref(), Some("token_a"));+ assert!(record.historical_migration);+ assert!(!record.missing_headers);++ let headerless = MessageRecord::new(43, None, b"", None);+ assert!(headerless.missing_headers);+ assert!(headerless.token.is_none());+ }++ #[test]+ fn oversized_payloads_are_truncated_with_a_flag() {+ let h = headers("token_a", "user_1", "$pageview");+ let big = vec![b'x'; PAYLOAD_LIMIT + 1];+ let record = MessageRecord::new(0, None, &big, Some(&h));+ assert_eq!(record.payload_bytes, (PAYLOAD_LIMIT + 1) as u64);+ assert_eq!(record.payload.len(), PAYLOAD_LIMIT);+ assert!(record.payload_truncated);+ }+}diff --git a/rust/ingestion-control-plane/src/kafka/mod.rs b/rust/ingestion-control-plane/src/kafka/mod.rsindex 7f42bfdc69d1..f240a879a16b 100644--- a/rust/ingestion-control-plane/src/kafka/mod.rs+++ b/rust/ingestion-control-plane/src/kafka/mod.rs@@ -1,4 +1,5 @@pub mod analysis;+pub mod browse;pub mod client;pub mod fetch;pub mod lag;diff --git a/rust/ingestion-control-plane/src/state.rs b/rust/ingestion-control-plane/src/state.rsindex 14ebefe15ccd..b8802899229a 100644--- a/rust/ingestion-control-plane/src/state.rs+++ b/rust/ingestion-control-plane/src/state.rs@@ -2,6 +2,7 @@ use std::sync::Arc;use std::time::Duration;use common_database::PoolConfig;+use tokio::sync::Semaphore;use crate::cache::TtlCache;use crate::config::Config;@@ -21,6 +22,9 @@ pub struct AppState {pub discovery: Arc<TtlCache<Vec<ConsumerTarget>>>,/// Overview scan results; short TTL + single-flight bounds broker load.pub overview: Arc<TtlCache<LagOverview>>,+ /// Caps concurrent synchronous message-browse scans; each holds a Kafka+ /// consumer on the blocking pool for up to the browse deadline.+ pub browse_permits: Arc<Semaphore>,}impl AppState {@@ -63,6 +67,7 @@ impl AppState {overview: Arc::new(TtlCache::new(Duration::from_secs(config.overview_cache_ttl_secs,))),+ browse_permits: Arc::new(Semaphore::new(config.browse_max_concurrent.max(1))),config: Arc::new(config),})}diff --git a/rust/ingestion-control-plane/src/ui/index.html b/rust/ingestion-control-plane/src/ui/index.htmlindex 312c9ef6b0a6..7c2fada02045 100644--- a/rust/ingestion-control-plane/src/ui/index.html+++ b/rust/ingestion-control-plane/src/ui/index.html@@ -124,6 +124,42 @@/* Height is driven by the embedded document (same-origin), so the panelexpands to fit the debug UI instead of squeezing it into a viewport box. */iframe.debug { width: 100%; min-height: 480px; border: 0; background: var(--bg); display: block; }++ /* message browser */+ .overlay {+ position: fixed; inset: 0; background: rgba(8, 10, 13, 0.6); z-index: 20;+ display: flex; align-items: center; justify-content: center; padding: 24px;+ }+ .browser {+ background: var(--panel); border: 1px solid var(--border); border-radius: 10px;+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);+ width: min(1180px, 100%); height: min(780px, 100%);+ display: flex; flex-direction: column; overflow: hidden;+ }+ .browser-head { display: flex; align-items: center; gap: 10px; padding: 10px 14px; border-bottom: 1px solid var(--border); flex-wrap: wrap; }+ .browser-head .title { font-weight: 600; }+ .browser-body { display: flex; flex: 1 1 auto; min-height: 0; }+ .facets { flex: 0 0 250px; border-right: 1px solid var(--border); overflow-y: auto; padding: 8px 14px 12px; }+ .facets h3 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); margin: 10px 0 4px; }+ .facet-row { cursor: pointer; border-radius: 4px; margin: 0 -4px; padding: 2px 4px; }+ .facet-row:hover { background: var(--panel-2); }+ .msgs { flex: 1 1 auto; min-width: 0; overflow-y: auto; }+ .browser-foot { border-top: 1px solid var(--border); }+ .browser-foot .status { margin-right: auto; }+ .chip {+ display: inline-flex; align-items: center; gap: 4px; font-size: 11px;+ background: var(--panel-2); border: 1px solid var(--border); border-radius: 10px; padding: 1px 4px 1px 8px;+ }+ .chip .val { font-family: var(--mono); max-width: 260px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; }+ .chip .val:hover { color: #a9c0ff; }+ .chip .x { background: none; border: 0; color: var(--muted); cursor: pointer; padding: 0 4px; font-size: 12px; }+ .chip .x:hover { color: var(--error); }+ tr.msg-detail td { background: var(--panel-2); }+ pre.payload {+ margin: 0 0 8px; padding: 10px; background: var(--bg); border: 1px solid var(--border); border-radius: 6px;+ font-family: var(--mono); font-size: 11px; white-space: pre-wrap; word-break: break-word;+ max-height: 340px; overflow: auto;+ }</style></head><body>@@ -176,8 +212,10 @@return body;};const copy = (text) => navigator.clipboard && navigator.clipboard.writeText(text);+ // Copy clicks must not also trigger row-level handlers (e.g. expanding+ // a message row in the browser).const copyable = (text, cls) =>- el("span", { class: cls, title: `${text} (click to copy)`, onclick: () => copy(text) }, text);+ el("span", { class: cls, title: `${text} (click to copy)`, onclick: (e) => { e.stopPropagation(); copy(text); } }, text);// Client-side search + pagination over an in-memory row list. The search// input is kept stable across re-renders so typing survives refreshes.@@ -432,6 +470,20 @@function renderAnalysisResult(job) {const r = job.result;+ // Browsing starts where the analysis started, so the messages shown+ // line up with the aggregates that led here.+ const browseSpec = {+ group: job.spec.group,+ topic: job.spec.topic,+ partition: job.spec.partition,+ startOffset: job.spec.start_offset,+ };+ const browseKey = (text, filters) =>+ el("span", {+ class: "key",+ title: `${text} (click to browse matching messages)`,+ onclick: () => messageBrowser.open(browseSpec, filters),+ }, text);const chips = el("div",{ class: "row" },@@ -447,7 +499,7 @@r.token_overflow ? el("span", { class: "pill warn" }, `token overflow: ${fmtInt(r.token_overflow)}`) : null);- const topList = (title, rows) => {+ const topList = (title, rows, makeFilter) => {const max = Math.max(1, ...rows.map((row) => row.count));return el("div", {},el("h3", {}, title),@@ -455,7 +507,7 @@rows.map((row) =>el("div", { class: "krow" },el("span", { class: "kbar", style: `width:${Math.max(3, (row.count / max) * 80)}px` }),- copyable(row.key, "key"),+ browseKey(row.key, makeFilter(row.key)),el("span", { class: "cnt" }, `${fmtInt(row.count)} · ${row.pct.toFixed(1)}%`))));@@ -465,18 +517,28 @@const tokenBlocks = r.top_tokens.map((t) =>el("div", { class: "token-block" },el("div", { class: "token-head" },- el("span", { class: t.team_id === null ? "pill muted" : "pill accent" }, t.team_id === null ? "team ?" : `team ${t.team_id}`),- copyable(t.token, "tok"),+ el("span", {+ class: t.team_id === null ? "pill muted" : "pill accent",+ style: "cursor: pointer",+ title: "Browse this team's messages",+ onclick: () => messageBrowser.open(browseSpec, { token: t.token }),+ }, t.team_id === null ? "team ?" : `team ${t.team_id}`),+ el("span", {+ class: "tok",+ title: `${t.token} (click to browse matching messages)`,+ onclick: () => messageBrowser.open(browseSpec, { token: t.token }),+ }, t.token),el("span", { class: "share" },el("span", { class: "bar", style: `width:${Math.max(3, (t.count / maxTokenCount) * 160)}px` }),el("span", { class: "mono muted" }, `${fmtInt(t.count)} msgs · ${t.pct.toFixed(1)}% · ${fmtBytes(t.total_bytes)}`))),el("div", { class: "token-cols" },- topList("events", t.top_events),+ topList("events", t.top_events, (key) => ({ token: t.token, event: key })),topList(t.distinct_id_overflow? `distinct_ids (${fmtInt(t.distinct_ids_tracked)} tracked, ${fmtInt(t.distinct_id_overflow)} overflow)`: "distinct_ids",- t.top_distinct_ids+ t.top_distinct_ids,+ (key) => ({ token: t.token, distinct_id: key })))));@@ -505,6 +567,255 @@return el("div", {}, chips, ...tokenBlocks, sizes);}+ // ---------- message browser ----------+ // Modal opened from analysis results: scans the partition for messages+ // matching header filters, 100 matches per request, with facets over+ // the loaded messages to refine further.+ const FACET_DIMS = [+ { key: "token", title: "tokens" },+ { key: "event", title: "events" },+ { key: "distinct_id", title: "distinct_ids" },+ ];+ const PAGE_LIMIT = 100;++ const messageBrowser = {+ overlay: null,+ state: null,+ epoch: 0,++ open(spec, filters) {+ this.close();+ this.state = {+ spec,+ filters: { ...filters },+ records: [],+ tokenTeams: {},+ scanned: 0,+ nextOffset: spec.startOffset,+ reachedEnd: false,+ loading: false,+ error: null,+ };++ this.listView = listView({+ placeholder: "Filter loaded messages…",+ pageSize: PAGE_LIMIT,+ matches: (record, q) =>+ ["token", "event", "distinct_id", "uuid", "session_id", "payload"].some((key) => (record[key] || "").toLowerCase().includes(q)) ||+ String(record.offset).includes(q),+ renderTable: (rows) => this.renderTable(rows),+ emptyText: "No matching messages loaded yet. Load more to scan further along the partition.",+ });++ this.ui = {+ chips: el("div", { class: "row", style: "padding: 0; flex: 1 1 auto" }),+ facets: el("div", { class: "facets" }),+ error: el("div", {}),+ status: el("span", { class: "muted mono status" }),+ loadBtn: el("button", { class: "small", onclick: () => this.fetchPage() }, "Load more"),+ };++ this.overlay = el("div", { class: "overlay", onclick: (e) => { if (e.target === this.overlay) this.close(); } },+ el("div", { class: "browser" },+ el("div", { class: "browser-head" },+ el("span", { class: "title" }, `Messages · ${spec.group} · ${spec.topic} p${spec.partition}`),+ this.ui.chips,+ el("button", { class: "small", onclick: () => this.close() }, "✕ close")),+ el("div", { class: "browser-body" },+ this.ui.facets,+ el("div", { class: "msgs" }, this.ui.error, this.listView.body)),+ el("div", { class: "row browser-foot" }, this.ui.status, this.ui.loadBtn)));+ document.body.append(this.overlay);+ this.escHandler = (e) => { if (e.key === "Escape") this.close(); };+ document.addEventListener("keydown", this.escHandler);++ this.render();+ this.fetchPage();+ },++ close() {+ this.epoch++;+ if (this.escHandler) document.removeEventListener("keydown", this.escHandler);+ if (this.overlay) this.overlay.remove();+ this.overlay = null;+ this.state = null;+ this.escHandler = null;+ },++ setFilter(key, value) {+ this.state.filters[key] = value;+ this.restart();+ },++ removeFilter(key) {+ delete this.state.filters[key];+ this.restart();+ },++ // Any filter change rescans from the original start offset so counts+ // and facets stay consistent with a single contiguous range.+ restart() {+ this.epoch++;+ const s = this.state;+ s.records = [];+ s.scanned = 0;+ s.nextOffset = s.spec.startOffset;+ s.reachedEnd = false;+ s.loading = false;+ s.error = null;+ this.listView.reset();+ this.render();+ this.fetchPage();+ },++ async fetchPage() {+ const s = this.state;+ if (!s || s.loading) return;+ const epoch = this.epoch;+ s.loading = true;+ s.error = null;+ this.render();+ const params = new URLSearchParams({+ group: s.spec.group,+ topic: s.spec.topic,+ partition: s.spec.partition,+ start_offset: s.nextOffset,+ limit: PAGE_LIMIT,+ });+ for (const dim of FACET_DIMS) {+ if (s.filters[dim.key] !== undefined) params.set(dim.key, s.filters[dim.key]);+ }+ try {+ const data = await fetchJSON(`api/messages?${params}`);+ if (epoch !== this.epoch) return;+ s.records = s.records.concat(data.messages);+ s.scanned += data.scanned;+ s.nextOffset = data.next_offset;+ s.reachedEnd = data.reached_end;+ Object.assign(s.tokenTeams, data.token_teams);+ } catch (e) {+ if (epoch !== this.epoch) return;+ s.error = String(e);+ }+ s.loading = false;+ this.render();+ },++ render() {+ const s = this.state;+ if (!s) return;++ const chips = FACET_DIMS.filter((dim) => s.filters[dim.key] !== undefined).map((dim) =>+ el("span", { class: "chip" },+ el("span", { class: "muted" }, `${dim.key}=`),+ el("span", { class: "val", title: `${s.filters[dim.key]} (click to copy)`, onclick: () => copy(s.filters[dim.key]) }, s.filters[dim.key]),+ el("button", { class: "x", title: "Remove this filter", onclick: () => this.removeFilter(dim.key) }, "×")));+ this.ui.chips.replaceChildren(+ chips.length ? el("span", { class: "muted", style: "font-size: 11px" }, "filters:") : el("span", { class: "muted", style: "font-size: 11px" }, "no filters, showing all messages"),+ ...chips);++ this.ui.error.replaceChildren(s.error ? el("div", { class: "error-box" }, s.error) : "");+ this.listView.setRows(s.records);+ this.renderFacets();++ const bits = [`${fmtInt(s.records.length)} matched`, `${fmtInt(s.scanned)} scanned`];+ if (s.loading) bits.push("scanning…");+ else if (s.reachedEnd) bits.push("caught up to the high watermark");+ else bits.push(`next offset ${fmtInt(s.nextOffset)}`);+ this.ui.status.textContent = bits.join(" · ");+ this.ui.loadBtn.disabled = s.loading;+ this.ui.loadBtn.textContent = s.loading ? "Loading…" : s.reachedEnd ? "Check for new messages" : "Load more";+ },++ teamLabel(token) {+ const team = this.state.tokenTeams[token];+ return team === null || team === undefined ? null : team;+ },++ renderFacets() {+ const s = this.state;+ const blocks = [];+ for (const dim of FACET_DIMS) {+ if (s.filters[dim.key] !== undefined) continue;+ const counts = new Map();+ for (const record of s.records) {+ const value = record[dim.key];+ if (value === undefined || value === null) continue;+ counts.set(value, (counts.get(value) || 0) + 1);+ }+ const entries = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, 25);+ const max = Math.max(1, ...entries.map(([, count]) => count));+ blocks.push(el("div", {},+ el("h3", {}, dim.title),+ entries.length === 0 ? el("div", { class: "muted", style: "font-size: 11px" }, "none loaded") : null,+ entries.map(([value, count]) => {+ const team = dim.key === "token" ? this.teamLabel(value) : null;+ return el("div", { class: "krow facet-row", title: `${value} (click to filter)`, onclick: () => this.setFilter(dim.key, value) },+ el("span", { class: "kbar", style: `width:${Math.max(3, (count / max) * 50)}px` }),+ el("span", { class: "key" }, team === null ? value : `team ${team}`),+ el("span", { class: "cnt" }, fmtInt(count)));+ })));+ }+ blocks.push(el("div", { class: "muted", style: "font-size: 11px; padding: 10px 0" },+ "Facets count the messages loaded so far. Click a value to filter the scan by it."));+ this.ui.facets.replaceChildren(...blocks);+ },++ renderTable(rows) {+ return el("table", {},+ el("thead", {}, el("tr", {},+ el("th", {}, "offset"), el("th", {}, "time"), el("th", {}, "event"),+ el("th", {}, "distinct_id"), el("th", {}, "team"), el("th", {}, "size"), el("th", {}, "flags"))),+ el("tbody", {}, rows.map((record) => {+ const flags = [];+ if (record.missing_headers) flags.push(el("span", { class: "pill bad" }, "no headers"));+ if (record.historical_migration) flags.push(el("span", { class: "pill warn" }, "historical"));+ if (record.force_disable_person_processing) flags.push(el("span", { class: "pill muted" }, "no-person"));+ if (record.dlq_reason) flags.push(el("span", { class: "pill bad", title: record.dlq_reason }, "dlq"));+ const team = record.token ? this.teamLabel(record.token) : null;+ const row = el("tr", { class: "clickable", title: "Click to view the payload" },+ el("td", { class: "mono" }, fmtInt(record.offset)),+ el("td", { class: "muted mono" }, record.timestamp_ms ? new Date(record.timestamp_ms).toLocaleString() : "–"),+ el("td", { class: "mono" }, record.event ? copyable(record.event, "key") : el("span", { class: "muted" }, "–")),+ el("td", { class: "mono" }, record.distinct_id ? copyable(record.distinct_id, "key") : el("span", { class: "muted" }, "–")),+ el("td", {}, record.token+ ? el("span", { class: team === null ? "pill muted" : "pill accent", title: `${record.token} (click to copy)`, style: "cursor: pointer", onclick: (e) => { e.stopPropagation(); copy(record.token); } }, team === null ? "team ?" : `team ${team}`)+ : el("span", { class: "muted" }, "–")),+ el("td", { class: "muted mono" }, fmtBytes(record.payload_bytes)),+ el("td", {}, flags));+ row.addEventListener("click", () => this.toggleDetail(row, record));+ return row;+ })));+ },++ toggleDetail(row, record) {+ const next = row.nextElementSibling;+ if (next && next.classList.contains("msg-detail")) {+ next.remove();+ row.classList.remove("selected");+ return;+ }+ let payload = record.payload;+ try {+ payload = JSON.stringify(JSON.parse(record.payload), null, 2);+ } catch {+ // Not JSON; show the raw text.+ }+ row.classList.add("selected");+ row.after(el("tr", { class: "msg-detail" },+ el("td", { colspan: "7" },+ el("div", { class: "row", style: "padding: 8px 0 6px" },+ record.uuid ? el("span", { class: "muted mono" }, `uuid ${record.uuid}`) : null,+ record.session_id ? el("span", { class: "muted mono" }, `session ${record.session_id}`) : null,+ record.token ? el("span", { class: "muted mono" }, `token ${record.token}`) : null,+ record.payload_truncated+ ? el("span", { class: "pill warn" }, `showing the first 64 KB of ${fmtBytes(record.payload_bytes)}`)+ : null,+ el("button", { class: "small", style: "margin-left: auto", onclick: () => copy(record.payload) }, "copy payload")),+ el("pre", { class: "payload" }, payload || el("span", { class: "muted" }, "empty payload")))));+ },+ };+// ---------- section: consumer debug ----------const debugSection = {id: "debug",