: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): add ordering sentinels to rust consumer and worker (#70660)
José Sequeiraab8d9610c801
diff --git a/nodejs/src/ingestion/api/feed-order-sentinel.test.ts b/nodejs/src/ingestion/api/feed-order-sentinel.test.tsnew file mode 100644index 000000000000..2a87c9b196f7--- /dev/null+++ b/nodejs/src/ingestion/api/feed-order-sentinel.test.ts@@ -0,0 +1,73 @@+import { FeedOrderSentinel } from './feed-order-sentinel'+import { SerializedKafkaMessage } from './types'++function msg(offset: number, overrides: Partial<SerializedKafkaMessage> = {}): SerializedKafkaMessage {+ return {+ topic: 'events',+ partition: 0,+ offset,+ timestamp: 0,+ key: null,+ value: null,+ headers: { token: 't', distinct_id: 'a' },+ ...overrides,+ }+}++describe('FeedOrderSentinel', () => {+ it('passes messages fed in ascending offset order per key', () => {+ const sentinel = new FeedOrderSentinel()+ expect(sentinel.check([msg(1), msg(2)], 'c1', false)).toEqual({ outOfOrder: 0, replayed: 0 })+ expect(sentinel.check([msg(3)], 'c1', false)).toEqual({ outOfOrder: 0, replayed: 0 })+ })++ it('flags an offset regression within one consumer incarnation', () => {+ const sentinel = new FeedOrderSentinel()+ sentinel.check([msg(5)], 'c1', false)+ expect(sentinel.check([msg(3)], 'c1', false)).toEqual({ outOfOrder: 1, replayed: 0 })+ })++ it('counts a regression in a replay request as replayed, not a violation', () => {+ const sentinel = new FeedOrderSentinel()+ sentinel.check([msg(5)], 'c1', false)+ expect(sentinel.check([msg(5)], 'c1', true)).toEqual({ outOfOrder: 0, replayed: 1 })+ })++ it('rebaselines when the consumer incarnation changes', () => {+ const sentinel = new FeedOrderSentinel()+ sentinel.check([msg(100)], 'c1', false)+ // A restarted consumer replays from the last commit — not a violation.+ expect(sentinel.check([msg(50)], 'c2', false)).toEqual({ outOfOrder: 0, replayed: 0 })+ // But the new incarnation is now the baseline.+ expect(sentinel.check([msg(40)], 'c2', false)).toEqual({ outOfOrder: 1, replayed: 0 })+ })++ it('tracks keys independently across partitions and distinct_ids', () => {+ const sentinel = new FeedOrderSentinel()+ sentinel.check(+ [msg(10), msg(10, { partition: 1 }), msg(10, { headers: { token: 't', distinct_id: 'b' } })],+ 'c1',+ false+ )+ // Same offsets again on other keys don't interfere; only 'a' on partition 0 regresses.+ expect(sentinel.check([msg(9)], 'c1', false)).toEqual({ outOfOrder: 1, replayed: 0 })+ expect(sentinel.check([msg(11, { partition: 1 })], 'c1', false)).toEqual({ outOfOrder: 0, replayed: 0 })+ })++ it('skips messages without routing headers', () => {+ const sentinel = new FeedOrderSentinel()+ const result = sentinel.check([msg(5, { headers: {} }), msg(1, { headers: {} })], 'c1', false)+ expect(result).toEqual({ outOfOrder: 0, replayed: 0 })+ expect(sentinel.size).toBe(0)+ })++ it('evicts the least-recently-seen key at capacity and rebaselines it silently', () => {+ const sentinel = new FeedOrderSentinel(2)+ sentinel.check([msg(10)], 'c1', false)+ sentinel.check([msg(10, { headers: { token: 't', distinct_id: 'b' } })], 'c1', false)+ sentinel.check([msg(10, { headers: { token: 't', distinct_id: 'c' } })], 'c1', false)+ expect(sentinel.size).toBe(2)+ // 'a' was evicted: its regression rebaselines instead of firing.+ expect(sentinel.check([msg(5)], 'c1', false)).toEqual({ outOfOrder: 0, replayed: 0 })+ })+})diff --git a/nodejs/src/ingestion/api/feed-order-sentinel.ts b/nodejs/src/ingestion/api/feed-order-sentinel.tsnew file mode 100644index 000000000000..9a1849134454--- /dev/null+++ b/nodejs/src/ingestion/api/feed-order-sentinel.ts@@ -0,0 +1,128 @@+import { Counter, Gauge } from 'prom-client'++import { logger } from '~/common/utils/logger'++import { SerializedKafkaMessage } from './types'++const outOfOrderMessages = new Counter({+ name: 'ingestion_api_out_of_order_messages_total',+ help: 'Messages fed to the pipeline at or below their routing key’s last seen offset, outside a marked replay — a per-key ordering violation',+})++const replayedMessages = new Counter({+ name: 'ingestion_api_replayed_messages_total',+ help: 'Messages at or below their routing key’s last seen offset inside a marked replay request — expected at-least-once redelivery, not a violation',+})++const sentinelKeys = new Gauge({+ name: 'ingestion_api_order_sentinel_keys',+ help: 'Routing keys currently tracked by the feed-order sentinel',+})++const sentinelEvictions = new Counter({+ name: 'ingestion_api_order_sentinel_evictions_total',+ help: 'Routing keys evicted from the feed-order sentinel at capacity (their next appearance rebaselines unchecked)',+})++export interface FeedOrderCheckResult {+ outOfOrder: number+ replayed: number+}++interface KeyEntry {+ consumerId: string+ offset: number+}++/**+ * Verifies the pipeline's per-key ordering invariant at its measurement point:+ * the feed. The grouping stage processes each routing key's messages strictly+ * in feed order, so "fed in Kafka offset order per key" is exactly "processed+ * in order per key". Call `check` synchronously immediately before+ * `pipeline.feed()` — the shared event loop then makes check order identical+ * to feed order even with concurrent /ingest requests.+ *+ * The Rust consumer stamps each request with its process incarnation+ * (`consumer_id`) and a `replay` flag (HTTP retry or deferred-flush re-route).+ * An offset regression within one incarnation is an ordering violation unless+ * the request is a replay (at-least-once redelivery of un-ACKed messages). A+ * changed incarnation (consumer restart or partition handoff) legitimately+ * replays uncommitted offsets, so the key rebaselines instead of firing.+ *+ * State is a bounded LRU: at capacity the least-recently-seen key is dropped+ * and its next appearance rebaselines unchecked (sampling, not a guarantee+ * gap under normal cardinality).+ */+export class FeedOrderSentinel {+ private entries = new Map<string, KeyEntry>()++ constructor(private readonly maxKeys: number = 200_000) {}++ check(messages: SerializedKafkaMessage[], consumerId: string, replay: boolean): FeedOrderCheckResult {+ const result: FeedOrderCheckResult = { outOfOrder: 0, replayed: 0 }++ for (const message of messages) {+ const token = message.headers['token']+ const distinctId = message.headers['distinct_id']+ if (!token || !distinctId) {+ // No routing key: the consumer routes these individually under a+ // synthetic unique key, so there is no per-key order to check.+ continue+ }+ const key = `${message.topic}/${message.partition}/${token}:${distinctId}`++ const entry = this.entries.get(key)+ if (entry && entry.consumerId === consumerId) {+ if (message.offset <= entry.offset) {+ if (replay) {+ result.replayed+++ } else {+ result.outOfOrder+++ logger.warn('⚠️', 'Out-of-order message fed to ingestion pipeline', {+ key,+ offset: message.offset,+ lastSeenOffset: entry.offset,+ consumerId,+ })+ }+ } else {+ entry.offset = message.offset+ }+ // Refresh LRU recency (Map preserves insertion order).+ this.entries.delete(key)+ this.entries.set(key, entry)+ } else {+ // New key, or a new consumer incarnation: rebaseline.+ this.entries.delete(key)+ this.entries.set(key, { consumerId, offset: message.offset })+ }+ }++ let evicted = 0+ while (this.entries.size > this.maxKeys) {+ const oldest = this.entries.keys().next().value+ if (oldest === undefined) {+ break+ }+ this.entries.delete(oldest)+ evicted+++ }++ if (result.outOfOrder > 0) {+ outOfOrderMessages.inc(result.outOfOrder)+ }+ if (result.replayed > 0) {+ replayedMessages.inc(result.replayed)+ }+ if (evicted > 0) {+ sentinelEvictions.inc(evicted)+ }+ sentinelKeys.set(this.entries.size)++ return result+ }++ get size(): number {+ return this.entries.size+ }+}diff --git a/nodejs/src/ingestion/api/types.ts b/nodejs/src/ingestion/api/types.tsindex 74a3cbf0ab57..cd40157fc700 100644--- a/nodejs/src/ingestion/api/types.ts+++ b/nodejs/src/ingestion/api/types.ts@@ -19,6 +19,10 @@ export interface SerializedKafkaMessage {export interface IngestBatchRequest {batch_id: stringmessages: SerializedKafkaMessage[]+ /** Consumer process incarnation; the feed-order sentinel rebaselines a key when it changes. Optional for older consumers. */+ consumer_id?: string+ /** True when the request may repeat previously sent messages (HTTP retry or deferred-flush re-route). */+ replay?: boolean}export interface IngestBatchResponse {diff --git a/nodejs/src/ingestion/config.ts b/nodejs/src/ingestion/config.tsindex f425be3e6d84..a04606006d21 100644--- a/nodejs/src/ingestion/config.ts+++ b/nodejs/src/ingestion/config.ts@@ -121,6 +121,15 @@ export type IngestionConsumerConfig = {// (idle worker capacity) or the worker rejects with HTTP 503.INGESTION_WORKER_CONCURRENT_BATCHES: number+ // Feed-order sentinel (ingestion API server only): checks that each+ // routing key's messages enter the pipeline in Kafka offset order. The+ // Rust consumer's sentinels have their own flag+ // (CONSUMER_ORDER_SENTINEL_ENABLED).+ INGESTION_API_FEED_ORDER_SENTINEL_ENABLED: boolean+ // LRU capacity of the sentinel's per-key state; at capacity the+ // least-recently-seen key is dropped and rebaselines unchecked.+ INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS: number+// Person batch writing configPERSON_BATCH_WRITING_DB_WRITE_MODE: PersonBatchWritingDbWriteModePERSON_BATCH_WRITING_USE_BATCH_UPDATES: boolean@@ -243,6 +252,8 @@ export function getDefaultIngestionConsumerConfig(): IngestionConsumerConfig {INGESTION_FORCE_OVERFLOW_BY_TOKEN_DISTINCT_ID: '',INGESTION_OVERFLOW_PRESERVE_PARTITION_LOCALITY: false,INGESTION_WORKER_CONCURRENT_BATCHES: 1,+ INGESTION_API_FEED_ORDER_SENTINEL_ENABLED: true,+ INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS: 200_000,// Person batch writing configPERSON_BATCH_WRITING_DB_WRITE_MODE: 'NO_ASSERT',diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 978c59f288a0..2f91dd9de66a 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -61,6 +61,7 @@ import {} from '../cdp/hog-transformations/hog-transformer.service'import { EncryptedFields } from '../cdp/utils/encryption-utils'import { CommonConfig } from '../common/config'+import { FeedOrderSentinel } from '../ingestion/api/feed-order-sentinel'import { deserializeKafkaMessage } from '../ingestion/api/kafka-message-converter'import { IngestBatchRequest, IngestBatchResponse } from '../ingestion/api/types'import { EventFilterManagerComponent } from '../ingestion/common/event-filters'@@ -180,6 +181,8 @@ export class IngestionApiServer implements NodeServer {private promiseScheduler = new PromiseScheduler()private hogTransformer!: HogTransformerServiceprivate topHog!: TopHog+ // Set in startServices when INGESTION_API_FEED_ORDER_SENTINEL_ENABLED.+ private feedOrderSentinel?: FeedOrderSentinel// Latched on the first unexpected pipeline error. The joinedPipeline is a// single long-lived instance shared across all requests; a throw can leave@@ -418,6 +421,9 @@ export class IngestionApiServer implements NodeServer {this.joinedPipeline = createJoinedIngestionPipeline(joinedPipelineConfig, joinedPipelineDeps)// 8. Register the ingest endpoint and service+ if (this.config.INGESTION_API_FEED_ORDER_SENTINEL_ENABLED) {+ this.feedOrderSentinel = new FeedOrderSentinel(this.config.INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS)+ }this.lifecycle.expressApp.post('/ingest', async (req, res) => {await this.handleIngestRequest(req, res)})@@ -441,7 +447,7 @@ export class IngestionApiServer implements NodeServer {status: (code: number) => { json: (body: IngestBatchResponse) => void }}): Promise<void> {- const { batch_id, messages: serializedMessages } = req.body+ const { batch_id, messages: serializedMessages, consumer_id, replay } = req.bodyif (!serializedMessages || serializedMessages.length === 0) {res.status(400).json({ batch_id: batch_id ?? '', status: 'error', accepted: 0, error: 'Empty batch' })@@ -458,6 +464,11 @@ export class IngestionApiServer implements NodeServer {const messages: Message[] = serializedMessages.map(deserializeKafkaMessage)const batch = messages.map((message) => createOkContext({ message }, { message }))+ // Per-key order check, synchronously adjacent to feed() so check+ // order equals feed order across concurrent requests. The grouping+ // stage processes each key in feed order, so this measures the+ // "processed in order per distinct_id" invariant.+ this.feedOrderSentinel?.check(serializedMessages, consumer_id ?? 'unknown', replay ?? false)const feedResult = await this.joinedPipeline.feed(batch)if (!feedResult.ok) {// Capacity rejection should not happen under correct consumerdiff --git a/rust/ingestion-consumer/README.md b/rust/ingestion-consumer/README.mdindex b5fd6d2ff820..e53ef05050d1 100644--- a/rust/ingestion-consumer/README.md+++ b/rust/ingestion-consumer/README.md@@ -4,6 +4,29 @@ Rust Kafka consumer that routes analytics events to Node.js ingestion workers ovIt reads batches from Kafka, groups messages by `token:distinct_id`, pins each key to a worker (preserving per-person ordering), scatters sub-batches over HTTP, and commits offsets only after every message in the batch is accepted.Worker health combines active `/_ready` probes with passive send outcomes; workers that leave the pool drain gracefully — in-flight work finishes, new work for their keys defers and re-routes to survivors in order.+## Ordering sentinels++`order_sentinel.rs` turns the consumer's two core guarantees into always-on, alertable metrics (see the module docs for semantics).+Each guarantee has a violation counter that must stay flat and a denominator that must grow:++| Guarantee | Violations (must stay 0) | Denominator / supporting |+| --- | --- | --- |+| Commits are contiguous, monotonic, non-empty per partition | `ingestion_consumer_commit_violations_total{kind=gap\|out_of_order\|overlap\|empty}` | `ingestion_consumer_commits_checked_total`, `ingestion_consumer_committed_offset{topic,partition}` |+| Async commits actually succeed | `ingestion_consumer_commit_confirmation_lag{topic,partition}` persistently > 0 | `ingestion_consumer_broker_committed_offset{topic,partition}`, `ingestion_consumer_last_successful_commit_timestamp_seconds`, `ingestion_consumer_commit_monitor_errors_total` |+| Per-key sends are in offset order, never re-sent after ACK (keyed messages only) | `ingestion_consumer_key_order_violations_total{kind=intra_group_disorder\|resend_after_ack}` | `ingestion_consumer_key_replays_total` (legal at-least-once retries), `ingestion_consumer_key_sentinel_keys`, `ingestion_consumer_key_sentinel_unkeyed_total` (skipped null-key messages) |+| Messages enter the worker pipeline in per-key offset order (end to end) | `ingestion_api_out_of_order_messages_total` (worker-side) | `ingestion_api_replayed_messages_total`, `ingestion_api_order_sentinel_keys` |++Commit success can't be observed via rdkafka's `commit_callback` — librdkafka drops the result of manual async commits (no conf-level `offset_commit_cb` is ever registered by rust-rdkafka, and only sync commits attach a reply queue).+Instead a background commit monitor fetches the group's broker-committed offsets every 30s (one OffsetFetch) and compares them to what was attempted: `commit_confirmation_lag` is transiently positive while async commits are in flight, and persistently positive when commits are submitted but not landing (e.g. a stuck coordinator).+Alerts should gate on `ingestion_consumer_offset_commits_total > 0` — an idle consumer that never committed has nothing to confirm.++Both sides default to enabled and have kill switches: `CONSUMER_ORDER_SENTINEL_ENABLED` here, `INGESTION_API_FEED_ORDER_SENTINEL_ENABLED` (plus `INGESTION_API_FEED_ORDER_SENTINEL_MAX_KEYS`) on the worker.+The rebalance metrics from the consumer context stay on regardless, and the `consumer_id`/`replay` request fields are always stamped so either side can be toggled independently.+The worker-side check lives in `nodejs/src/ingestion/api/feed-order-sentinel.ts`, fed by the `consumer_id` (process incarnation) and `replay` fields the transport stamps on every `/ingest` request.+It measures the invariant at its end point: the worker's grouping stage processes each key strictly in feed order, so "fed in offset order per key" is "processed in order per key".+Rebalances reset all baselines (`ingestion_consumer_rebalances_total{event}` counts them), so partition handoffs don't fire false positives.+Null-key messages (e.g. overflow rerouting) are excluded from the consumer-side key checks: the producer deliberately spreads such a routing key across partitions, forfeiting per-key order, so offsets from different partitions are not comparable and there is no invariant to check. The worker-side check is unaffected — it scopes keys per partition, an invariant that holds for all traffic.+## Testing- `cargo test -p ingestion-consumer --lib` — unit tests.@@ -20,11 +43,11 @@ Sub-batches have no size bound: a batch (default 500 messages, each up to ~1 MBThe transport treats 4xx as non-retriable, so the same oversized sub-batch re-sends until the deferred-flush timeout, the process exits, Kafka redelivers, and it crash-loops deterministically — a stalled partition triggered by an ordinary burst of large events.Fix: cap sub-batch payload size at build time (chunks sent sequentially per worker to preserve per-key order), plus a defensive split-in-half retry on 413.-### 2. Commit-error observability+### 2. Commit-error observability — done-`commit_offsets` uses `CommitMode::Async` and never observes the result; persistent commit failure (e.g. after a rebalance) is invisible until restart-time redelivery.-Fix: a `ConsumerContext` with an offset-commit callback feeding a failure counter and a last-successful-commit gauge, alertable.-The same context provides rebalance callbacks — log partition assignment changes at minimum.+Addressed by the commit monitor plus `SentinelContext` (`order_sentinel.rs`): broker-committed offsets are polled and compared against attempted commits (see "Ordering sentinels" above), and rebalance callbacks log assignment changes and reset the ordering sentinels.+The originally envisioned offset-commit callback turned out to be unreachable for manual async commits (librdkafka drops their results unless a conf-level `offset_commit_cb` is registered, which rust-rdkafka never does) — hence the polling design.+Remaining: alert rules on the new metrics.### 3. DLQ for poison messagesdiff --git a/rust/ingestion-consumer/src/config.rs b/rust/ingestion-consumer/src/config.rsindex d3b2f35b6b4c..981643d7f7dc 100644--- a/rust/ingestion-consumer/src/config.rs+++ b/rust/ingestion-consumer/src/config.rs@@ -133,6 +133,17 @@ pub struct Config {#[envconfig(from = "CONSUMER_MAX_BACKGROUND_TASKS", default = "1")]pub consumer_max_background_tasks: usize,+ // ---- Ordering sentinels ----+ /// Kill switch for the ordering sentinels (per-partition commit+ /// contiguity/monotonicity checks and per-key send-order checks). They are+ /// pure observers with per-batch lock/state overhead bounded by in-flight+ /// work; disable only if that overhead is ever implicated. The commit-result+ /// and rebalance metrics from the consumer context stay on regardless. The+ /// worker-side feed-order sentinel has its own flag+ /// (INGESTION_API_FEED_ORDER_SENTINEL_ENABLED on the Node.js side).+ #[envconfig(from = "CONSUMER_ORDER_SENTINEL_ENABLED", default = "true")]+ pub consumer_order_sentinel_enabled: bool,+// ---- Worker transport ----/// Comma-separated list of worker HTTP URLs#[envconfig(default = "http://localhost:9001")]diff --git a/rust/ingestion-consumer/src/consumer.rs b/rust/ingestion-consumer/src/consumer.rsindex 4e33b71afa5c..988dbe50a758 100644--- a/rust/ingestion-consumer/src/consumer.rs+++ b/rust/ingestion-consumer/src/consumer.rs@@ -7,13 +7,14 @@ use lifecycle::Handle;use metrics::{counter, gauge, histogram};use rdkafka::consumer::{CommitMode, Consumer, StreamConsumer};use rdkafka::message::{Headers, Message};-use rdkafka::TopicPartitionList;+use rdkafka::{Offset, TopicPartitionList};use tokio::task::JoinHandle;use tracing::{error, info, warn};use crate::config::Config;use crate::discovery::DiscoveryMode;use crate::dispatcher::{Dispatcher, SubBatch};+use crate::order_sentinel::{CommitSentinel, OffsetSpan, SentinelContext};use crate::transport::HttpTransport;use crate::types::SerializedKafkaMessage;@@ -43,12 +44,12 @@ impl BatchStats {/// Output of `collect_batch`.struct CollectedBatch {messages: Vec<SerializedKafkaMessage>,- offsets: HashMap<(String, i32), i64>,+ offsets: HashMap<(String, i32), OffsetSpan>,stats: BatchStats,}struct ProcessedBatch {- offsets: HashMap<(String, i32), i64>,+ offsets: HashMap<(String, i32), OffsetSpan>,stats: BatchStats,/// Messages accepted so far. Deferred groups (keys whose worker was/// draining/dead) are flushed in `complete_oldest_batch`, which adds to this.@@ -81,7 +82,7 @@ pub struct IngestionConsumerOptions {/// via the health-aware Dispatcher, dispatches sub-batches to workers over/// HTTP, and commits offsets only after all workers ACK.pub struct IngestionConsumer {- consumer: StreamConsumer,+ consumer: Arc<StreamConsumer<SentinelContext>>,dispatcher: Arc<Dispatcher>,transport: Arc<HttpTransport>,worker_urls: Vec<String>,@@ -91,21 +92,28 @@ pub struct IngestionConsumer {deferred_flush_timeout: Duration,handle: Handle,group_id: String,+ /// Validates commit contiguity/monotonicity per partition. Shared with the+ /// consumer's [`SentinelContext`], which resets baselines on rebalance.+ commit_sentinel: Arc<CommitSentinel>,}impl IngestionConsumer {/// Constructs a consumer from pre-built parts. Useful in integration tests/// where the Kafka consumer is created and subscribed externally.pub fn from_parts(- consumer: StreamConsumer,+ consumer: StreamConsumer<SentinelContext>,dispatcher: Arc<Dispatcher>,transport: Arc<HttpTransport>,worker_urls: Vec<String>,options: IngestionConsumerOptions,handle: Handle,) -> Self {+ // Share the context's commit sentinel so rebalance callbacks reset the+ // same baselines the commit path checks against.+ let commit_sentinel = consumer.context().commit_sentinel();Self {- consumer,+ commit_sentinel,+ consumer: Arc::new(consumer),dispatcher,transport,worker_urls,@@ -136,7 +144,13 @@ impl IngestionConsumer {}let client_config = config.build_consumer_config();- let consumer: StreamConsumer = client_config.create()?;+ let commit_sentinel = Arc::new(CommitSentinel::new());+ commit_sentinel.set_enabled(config.consumer_order_sentinel_enabled);+ let key_sentinel = dispatcher.key_order_sentinel();+ key_sentinel.set_enabled(config.consumer_order_sentinel_enabled);+ let context = SentinelContext::new(Arc::clone(&commit_sentinel), key_sentinel);+ let consumer: StreamConsumer<SentinelContext> =+ client_config.create_with_context(context)?;consumer.subscribe(&[&config.ingestion_consumer_consume_topic])?;info!(@@ -148,7 +162,8 @@ impl IngestionConsumer {);Ok(Self {- consumer,+ consumer: Arc::new(consumer),+ commit_sentinel,dispatcher,transport,worker_urls,@@ -182,6 +197,16 @@ impl IngestionConsumer {info!("Consumer loop starting");+ // Verify async commits actually land: librdkafka drops the result of+ // manual async commits (see the note on SentinelContext), so poll the+ // broker's committed offsets instead. Aborted on drop so a consumer+ // torn down mid-test doesn't keep the rdkafka client alive.+ let _commit_monitor = AbortOnDrop(tokio::spawn(run_commit_monitor(+ Arc::clone(&self.consumer),+ Arc::clone(&self.commit_sentinel),+ self.handle.clone(),+ )));+let mut in_flight_batches = VecDeque::new();let mut accepting_new_batches = true;@@ -472,14 +497,18 @@ impl IngestionConsumer {let worker = sub_batch.worker.clone();let bid = batch_id.to_string();let routing_keys = sub_batch.routing_keys.clone();+ let key_offsets = sub_batch.key_offsets.clone();let message_count = sub_batch.messages.len();handles.push(tokio::spawn(async move {match transport- .send_batch(&worker, &bid, sub_batch.messages)+ .send_batch(&worker, &bid, sub_batch.messages, from_flush).await{Ok(accepted) => {+ // Advance ACK high-water marks before the resolve, which+ // may evict the keys' sentinel state.+ dispatcher.on_sub_batch_acked(&key_offsets);dispatcher.on_sub_batch_resolved(&worker,message_count,@@ -520,7 +549,7 @@ impl IngestionConsumer {/// Collect messages from Kafka up to batch_size or batch_timeout.async fn collect_batch(&self) -> anyhow::Result<CollectedBatch> {let mut messages = Vec::with_capacity(self.batch_size);- let mut offsets: HashMap<(String, i32), i64> = HashMap::new();+ let mut offsets: HashMap<(String, i32), OffsetSpan> = HashMap::new();let mut stats = BatchStats::new();let deadline = Instant::now() + self.batch_timeout;let batch_start_ms = current_time_ms();@@ -546,12 +575,8 @@ impl IngestionConsumer {offsets.entry((topic.clone(), partition))- .and_modify(|o| {- if offset > *o {- *o = offset;- }- })- .or_insert(offset);+ .and_modify(|span| span.extend(offset))+ .or_insert_with(|| OffsetSpan::new(offset));let kafka_ts = borrowed_message.timestamp().to_millis().unwrap_or(0);stats@@ -642,15 +667,23 @@ impl IngestionConsumer {}/// Commit the max offset for each topic-partition.- fn commit_offsets(&self, offsets: &HashMap<(String, i32), i64>) -> anyhow::Result<()> {+ fn commit_offsets(&self, offsets: &HashMap<(String, i32), OffsetSpan>) -> anyhow::Result<()> {if offsets.is_empty() {+ // Unreachable while batches require messages to be spawned; counted+ // so "no empty commits" is a measurable guarantee, not an assumption.+ counter!("ingestion_consumer_commit_violations_total", "kind" => "empty").increment(1);+ warn!("Commit requested with no offsets");return Ok(());}+ // Validate contiguity/monotonicity per partition before committing, so+ // a violation is attributed to the batch that caused it.+ self.commit_sentinel.check_commit(offsets);+let mut tpl = TopicPartitionList::new();- for ((topic, partition), offset) in offsets {+ for ((topic, partition), span) in offsets {// Commit offset + 1 (Kafka convention: committed offset = next to read)- tpl.add_partition_offset(topic, *partition, rdkafka::Offset::Offset(offset + 1))?;+ tpl.add_partition_offset(topic, *partition, rdkafka::Offset::Offset(span.last + 1))?;}self.consumer.commit(&tpl, CommitMode::Async)?;@@ -660,6 +693,74 @@ impl IngestionConsumer {}}+/// Aborts the wrapped task when dropped, covering every `process()` exit path.+struct AbortOnDrop(JoinHandle<()>);++impl Drop for AbortOnDrop {+ fn drop(&mut self) {+ self.0.abort();+ }+}++/// How often the commit monitor fetches the group's broker-committed offsets.+const COMMIT_MONITOR_INTERVAL: Duration = Duration::from_secs(30);++/// Periodically fetch the broker's committed offsets for the current+/// assignment (an OffsetFetch round trip) and feed them to the commit+/// sentinel, which compares them against attempted commits and stamps the+/// last-successful-commit gauge on progress.+async fn run_commit_monitor(+ consumer: Arc<StreamConsumer<SentinelContext>>,+ sentinel: Arc<CommitSentinel>,+ handle: Handle,+) {+ loop {+ tokio::select! {+ _ = handle.shutdown_recv() => return,+ _ = tokio::time::sleep(COMMIT_MONITOR_INTERVAL) => {}+ }++ let fetch_consumer = Arc::clone(&consumer);+ // assignment() and committed_offsets() block on librdkafka.+ let fetched = tokio::task::spawn_blocking(move || {+ let assignment = fetch_consumer.assignment()?;+ if assignment.count() == 0 {+ return Ok(None);+ }+ fetch_consumer+ .committed_offsets(assignment, Duration::from_secs(5))+ .map(Some)+ })+ .await;++ match fetched {+ Ok(Ok(Some(committed))) => {+ let observed: Vec<(String, i32, i64)> = committed+ .elements()+ .iter()+ .filter_map(|e| match e.offset() {+ Offset::Offset(offset) => {+ Some((e.topic().to_string(), e.partition(), offset))+ }+ // Invalid = no offset stored for the partition yet.+ _ => None,+ })+ .collect();+ sentinel.observe_broker_committed(observed);+ }+ Ok(Ok(None)) => {} // no assignment yet (e.g. before first rebalance)+ Ok(Err(err)) => {+ counter!("ingestion_consumer_commit_monitor_errors_total").increment(1);+ warn!(error = %err, "Commit monitor failed to fetch committed offsets");+ }+ Err(err) => {+ counter!("ingestion_consumer_commit_monitor_errors_total").increment(1);+ warn!(error = %err, "Commit monitor task join error");+ }+ }+ }+}+fn make_batch_id() -> String {let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)diff --git a/rust/ingestion-consumer/src/dispatcher.rs b/rust/ingestion-consumer/src/dispatcher.rsindex b423a6d06825..6223c2b13a72 100644--- a/rust/ingestion-consumer/src/dispatcher.rs+++ b/rust/ingestion-consumer/src/dispatcher.rs@@ -3,11 +3,23 @@ use std::sync::{Arc, Mutex};use metrics::{counter, gauge, histogram};+use crate::order_sentinel::KeyOrderSentinel;use crate::routing::{Router, RoutingStrategy, WorkerLoad};use crate::stash::{DeferredGroup, Stash};use crate::types::SerializedKafkaMessage;use crate::worker_registry::{WorkerId, WorkerRegistry};+/// The max offset a sub-batch carries for one routing key, over keyed+/// messages only (null-key offsets live on arbitrary partitions and carry no+/// per-key order promise). Passed back via+/// [`Dispatcher::on_sub_batch_acked`] when the worker ACKs, so the+/// [`KeyOrderSentinel`] can advance the key's ACK high-water mark.+#[derive(Clone)]+pub struct KeyOffset {+ pub routing_key: String,+ pub max_offset: i64,+}+/// A slice of a batch assigned to one worker, carrying the messages and the/// routing keys of all distinct_ids included. Routing keys are needed to/// decrement pin ref-counts when the sub-batch resolves.@@ -17,6 +29,9 @@ pub struct SubBatch {/// Unique routing keys contained in this sub-batch. Pass back to/// `Dispatcher::on_sub_batch_resolved` on ACK or DLQ.pub routing_keys: Vec<String>,+ /// Per-key max offsets. Pass back to `Dispatcher::on_sub_batch_acked` on+ /// a successful ACK (only) so the order sentinel tracks ACK progress.+ pub key_offsets: Vec<KeyOffset>,}/// Sticky pin for one routing key. Tracks which worker owns the key and how@@ -59,6 +74,7 @@ struct MessageGroup {struct WorkerSubBatchBuilder {messages: Vec<SerializedKafkaMessage>,routing_keys: Vec<String>,+ key_offsets: Vec<KeyOffset>,}impl WorkerSubBatchBuilder {@@ -88,8 +104,24 @@ impl WorkerAssignments {.or_insert_with(|| WorkerSubBatchBuilder {messages: Vec::new(),routing_keys: Vec::new(),+ key_offsets: Vec::new(),});+ // Only keyed messages participate in the key-order sentinel: a+ // null-key message lives on an arbitrary partition, so its offset+ // must not advance the key's ACK watermark.+ if let Some(max_offset) = group+ .messages+ .iter()+ .filter(|m| m.key.is_some())+ .map(|m| m.offset)+ .max()+ {+ builder.key_offsets.push(KeyOffset {+ routing_key: group.routing_key.clone(),+ max_offset,+ });+ }builder.messages.extend(group.messages);builder.routing_keys.push(group.routing_key);}@@ -109,6 +141,7 @@ impl WorkerAssignments {worker,messages: builder.messages,routing_keys: builder.routing_keys,+ key_offsets: builder.key_offsets,}).collect()}@@ -133,6 +166,10 @@ pub struct Dispatcher {/// Worker selector for unpinned keys. Behind its own mutex because P2C/// selection mutates the RNG.router: Mutex<Router>,+ /// Per-key send/ACK order checker. Called under the pin-table lock (lock+ /// order: pin_table → sentinel; the sentinel never takes the pin table),+ /// so its check order matches the intended per-key send order.+ key_sentinel: Arc<KeyOrderSentinel>,}impl Dispatcher {@@ -147,6 +184,7 @@ impl Dispatcher {pin_table: Mutex::new(PinTable::new()),registry,router: Mutex::new(Router::new(strategy)),+ key_sentinel: Arc::new(KeyOrderSentinel::new()),}}@@ -161,9 +199,16 @@ impl Dispatcher {pin_table: Mutex::new(PinTable::new()),registry,router: Mutex::new(Router::with_seed(strategy, seed)),+ key_sentinel: Arc::new(KeyOrderSentinel::new()),}}+ /// The per-key order sentinel, shared with the consumer's rdkafka context+ /// so rebalances can reset its baselines.+ pub fn key_order_sentinel(&self) -> Arc<KeyOrderSentinel> {+ Arc::clone(&self.key_sentinel)+ }+/// Assign a batch of messages to workers.////// Groups messages by routing key, then per group:@@ -219,6 +264,8 @@ impl Dispatcher {// ahead of it — honor it.table.pins.get_mut(&group.routing_key).unwrap().ref_count += 1;bump_load(&mut working_load, &worker, group.messages.len());+ self.key_sentinel+ .note_sent(&group.routing_key, &group.messages);assignments.add_group(worker, group);}Some(_) => {@@ -288,6 +335,8 @@ impl Dispatcher {ref_count: 1,},);+ self.key_sentinel+ .note_sent(&group.routing_key, &group.messages);assignments.add_group(worker, group);}drop(router);@@ -455,6 +504,8 @@ impl Dispatcher {);}}+ self.key_sentinel+ .note_sent(&group.routing_key, &group.messages);assignments.add_group(worker,MessageGroup {@@ -489,6 +540,16 @@ impl Dispatcher {/// deferral count, so the key keeps deferring newer messages from the moment/// it was first deferred until its flushed messages have actually landed —/// closing the window where a newer batch could race them.+ /// Call when a worker ACKed a sub-batch (success path only, **before**+ /// `on_sub_batch_resolved` so the sentinel state isn't evicted first).+ /// Advances each key's ACK high-water mark in the order sentinel.+ pub fn on_sub_batch_acked(&self, key_offsets: &[KeyOffset]) {+ for key_offset in key_offsets {+ self.key_sentinel+ .note_acked(&key_offset.routing_key, key_offset.max_offset);+ }+ }+pub fn on_sub_batch_resolved(&self,worker: &WorkerId,@@ -535,6 +596,9 @@ impl Dispatcher {pin.ref_count = pin.ref_count.saturating_sub(1);if pin.ref_count == 0 && !still_deferring {table.pins.remove(key);+ // All sends for the key resolved and nothing is deferred —+ // its order-sentinel history has nothing left to check.+ self.key_sentinel.evict(key);evictions += 1;}}@@ -644,7 +708,7 @@ mod tests {partition: 0,offset: 0,timestamp: 0,- key: None,+ key: Some(format!("{token}:{distinct_id}")),value: None,headers,}@@ -780,6 +844,47 @@ mod tests {);}+ #[test]+ fn test_key_offsets_only_track_keyed_messages() {+ // A null-key (overflow) message lands on an arbitrary partition; its+ // offset advancing the ACK watermark would make the next keyed send+ // look like a resend_after_ack.+ let keyed = SerializedKafkaMessage {+ offset: 100,+ ..make_msg("tok", "user-1")+ };+ let unkeyed = SerializedKafkaMessage {+ key: None,+ partition: 1,+ offset: 5000,+ ..make_msg("tok", "user-1")+ };++ let mut assignments = WorkerAssignments::new();+ assignments.add_group(+ wid(1),+ MessageGroup {+ routing_key: "tok:user-1".to_string(),+ messages: vec![keyed, unkeyed.clone()],+ },+ );+ let sub_batches = assignments.into_sub_batches();+ assert_eq!(sub_batches[0].key_offsets.len(), 1);+ assert_eq!(sub_batches[0].key_offsets[0].routing_key, "tok:user-1");+ assert_eq!(sub_batches[0].key_offsets[0].max_offset, 100);++ // An all-unkeyed group produces no ACK watermark at all.+ let mut assignments = WorkerAssignments::new();+ assignments.add_group(+ wid(1),+ MessageGroup {+ routing_key: "tok:user-1".to_string(),+ messages: vec![unkeyed],+ },+ );+ assert!(assignments.into_sub_batches()[0].key_offsets.is_empty());+ }+// ---- basic assignment ----#[test]diff --git a/rust/ingestion-consumer/src/lib.rs b/rust/ingestion-consumer/src/lib.rsindex 962f059960d8..abf99ce87969 100644--- a/rust/ingestion-consumer/src/lib.rs+++ b/rust/ingestion-consumer/src/lib.rs@@ -3,6 +3,7 @@ pub mod consumer;pub mod discovery;pub mod dispatcher;pub mod kafka_config;+pub mod order_sentinel;pub mod routing;pub mod stash;pub mod transport;diff --git a/rust/ingestion-consumer/src/order_sentinel.rs b/rust/ingestion-consumer/src/order_sentinel.rsnew file mode 100644index 000000000000..c3f6b240050e--- /dev/null+++ b/rust/ingestion-consumer/src/order_sentinel.rs@@ -0,0 +1,887 @@+//! Always-on ordering sentinels: cheap invariant checkers that turn the+//! consumer's two core guarantees into alertable metrics.+//!+//! **Commit order** ([`CommitSentinel`]): for every topic-partition, offsets+//! must be committed contiguously and monotonically — each batch's first+//! offset must equal the previously committed offset (no skips), and the+//! committed offset must never move backwards (no out-of-order commits).+//! Checked at commit time in the consumer loop; violations increment+//! `ingestion_consumer_commit_violations_total{kind}` and log the offending+//! offsets. `ingestion_consumer_commits_checked_total` is the denominator: the+//! guarantee holds while it grows and the violation counter stays flat.+//!+//! **Per-key send order** ([`KeyOrderSentinel`]): for every routing key+//! (`token:distinct_id`), messages must be handed to workers in Kafka offset+//! order, and a message must never be re-sent after it was ACKed. Replays of+//! un-ACKed messages (send failure → deferred flush) are legal at-least-once+//! behavior and are counted separately (`ingestion_consumer_key_replays_total`)+//! rather than flagged. Checked in the dispatcher at assignment time — the+//! point that defines the intended per-key order — under the pin-table lock.+//! Only messages produced with a Kafka key participate: null-key production+//! (e.g. overflow rerouting) spreads a routing key across partitions,+//! deliberately forfeiting per-key order, so there is no invariant to check+//! and offsets from different partitions are not comparable. Skipped messages+//! are counted in `ingestion_consumer_key_sentinel_unkeyed_total`.+//!+//! **Commit confirmation**: "commits are actually made" cannot be observed via+//! `ConsumerContext::commit_callback` — librdkafka drops the result of manual+//! async commits (see the note on [`SentinelContext`]). Instead the consumer's+//! commit monitor periodically fetches the group's broker-committed offsets and+//! feeds [`CommitSentinel::observe_broker_committed`], which emits+//! `ingestion_consumer_broker_committed_offset` and+//! `ingestion_consumer_commit_confirmation_lag` gauges and stamps+//! `ingestion_consumer_last_successful_commit_timestamp_seconds` on progress.+//!+//! [`SentinelContext`] is the consumer's rdkafka context: it resets sentinel+//! baselines on rebalances, where Kafka legitimately re-deals partitions and+//! both invariants must re-baseline instead of firing false positives.+//!+//! The sentinels are pure observers: they never influence routing or commits.++use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{SystemTime, UNIX_EPOCH};++use metrics::{counter, gauge};+use rdkafka::consumer::{BaseConsumer, ConsumerContext, Rebalance};+use rdkafka::ClientContext;+use tracing::{info, warn};++use crate::types::SerializedKafkaMessage;++/// The first and last Kafka offsets a batch holds for one topic-partition.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct OffsetSpan {+ pub first: i64,+ pub last: i64,+}++impl OffsetSpan {+ pub fn new(offset: i64) -> Self {+ Self {+ first: offset,+ last: offset,+ }+ }++ /// Widen the span to include `offset`.+ pub fn extend(&mut self, offset: i64) {+ self.first = self.first.min(offset);+ self.last = self.last.max(offset);+ }+}++/// How a commit violated the contiguous-monotonic invariant.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CommitViolationKind {+ /// The batch starts past the previously committed offset — the offsets in+ /// between were never part of a committed batch (skipped messages).+ Gap,+ /// The whole batch lies at or behind the committed offset — the commit+ /// moves the partition backwards.+ OutOfOrder,+ /// The batch partially re-covers already-committed offsets.+ Overlap,+}++impl CommitViolationKind {+ fn as_str(&self) -> &'static str {+ match self {+ CommitViolationKind::Gap => "gap",+ CommitViolationKind::OutOfOrder => "out_of_order",+ CommitViolationKind::Overlap => "overlap",+ }+ }+}++/// One detected commit-order violation, returned for tests and logged.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct CommitViolation {+ pub kind: CommitViolationKind,+ pub topic: String,+ pub partition: i32,+ /// The partition's committed offset (Kafka "next to read") before this batch.+ pub prev_committed: i64,+ pub span: OffsetSpan,+}++/// Per-partition commit tracking: what this process asked Kafka to commit+/// (attempted) and what the broker has confirmed as the group's committed+/// offset (observed by the commit monitor via OffsetFetch).+#[derive(Default, Clone, Copy)]+struct PartitionCommits {+ /// The offset value last submitted for commit (Kafka "next to read").+ attempted: Option<i64>,+ /// The broker-confirmed committed offset from the last monitor poll.+ confirmed: Option<i64>,+}++/// Tracks the last committed offset per topic-partition and checks each new+/// commit for contiguity and monotonicity. The first commit after a partition+/// is (re)assigned establishes a baseline and is never a violation — earlier+/// offsets may have been committed by another consumer in the group.+///+/// Caveat: legitimate offset gaps exist on topics with transactional producers+/// (control records consume offsets). The ingestion topics are produced by+/// capture without transactions, so a gap here is a real skip.+///+/// Because commits use `CommitMode::Async` and librdkafka silently drops the+/// result of manual async commits (no conf-level `offset_commit_cb` is ever+/// registered by rust-rdkafka, so `ConsumerContext::commit_callback` never+/// fires for them), commit *success* is verified out of band: the consumer's+/// commit monitor periodically fetches the group's broker-committed offsets+/// and feeds them to [`CommitSentinel::observe_broker_committed`].+pub struct CommitSentinel {+ partitions: Mutex<HashMap<(String, i32), PartitionCommits>>,+ /// Kill switch (`CONSUMER_ORDER_SENTINEL_ENABLED`). When off, checks+ /// no-op and no state accumulates.+ enabled: AtomicBool,+}++impl Default for CommitSentinel {+ fn default() -> Self {+ Self {+ partitions: Mutex::new(HashMap::new()),+ enabled: AtomicBool::new(true),+ }+ }+}++impl CommitSentinel {+ pub fn new() -> Self {+ Self::default()+ }++ pub fn set_enabled(&self, enabled: bool) {+ self.enabled.store(enabled, Ordering::Relaxed);+ }++ /// Check a batch's offset spans against the previous commit per partition,+ /// then advance the tracked committed offset to `span.last + 1`. Emits+ /// metrics and logs; returns the violations for tests.+ pub fn check_commit(&self, spans: &HashMap<(String, i32), OffsetSpan>) -> Vec<CommitViolation> {+ if !self.enabled.load(Ordering::Relaxed) {+ return Vec::new();+ }+ let mut partitions = self.partitions.lock().unwrap();+ let mut violations = Vec::new();++ for ((topic, partition), span) in spans {+ counter!("ingestion_consumer_commits_checked_total").increment(1);++ let state = partitions.entry((topic.clone(), *partition)).or_default();+ if let Some(prev) = state.attempted {+ let kind = if span.first == prev {+ None+ } else if span.first > prev {+ Some(CommitViolationKind::Gap)+ } else if span.last < prev {+ Some(CommitViolationKind::OutOfOrder)+ } else {+ Some(CommitViolationKind::Overlap)+ };++ if let Some(kind) = kind {+ counter!(+ "ingestion_consumer_commit_violations_total",+ "kind" => kind.as_str(),+ )+ .increment(1);+ warn!(+ kind = kind.as_str(),+ topic = %topic,+ partition = *partition,+ prev_committed = prev,+ batch_first = span.first,+ batch_last = span.last,+ "Commit order violation"+ );+ violations.push(CommitViolation {+ kind,+ topic: topic.clone(),+ partition: *partition,+ prev_committed: prev,+ span: *span,+ });+ }+ }++ state.attempted = Some(span.last + 1);+ gauge!(+ "ingestion_consumer_committed_offset",+ "topic" => topic.clone(),+ "partition" => partition.to_string(),+ )+ .set((span.last + 1) as f64);+ }++ violations+ }++ /// Feed broker-confirmed committed offsets (from an OffsetFetch of the+ /// group's assigned partitions) and compare against what this process+ /// attempted. Emits per-partition gauges:+ ///+ /// - `ingestion_consumer_broker_committed_offset` — the group's committed+ /// offset as the broker reports it;+ /// - `ingestion_consumer_commit_confirmation_lag` — attempted minus+ /// confirmed. Transiently positive while async commits are in flight;+ /// persistently positive means commits are being submitted but not+ /// landing (e.g. a stuck coordinator).+ ///+ /// Returns true when commits verifiably progressed since the last+ /// observation — the broker offset advanced, or everything attempted is+ /// confirmed — so the caller can stamp the last-successful-commit gauge.+ pub fn observe_broker_committed(+ &self,+ observed: impl IntoIterator<Item = (String, i32, i64)>,+ ) -> bool {+ if !self.enabled.load(Ordering::Relaxed) {+ return false;+ }+ let mut partitions = self.partitions.lock().unwrap();+ let mut advanced = false;++ for (topic, partition, committed) in observed {+ gauge!(+ "ingestion_consumer_broker_committed_offset",+ "topic" => topic.clone(),+ "partition" => partition.to_string(),+ )+ .set(committed as f64);++ let state = partitions.entry((topic.clone(), partition)).or_default();+ if let Some(attempted) = state.attempted {+ gauge!(+ "ingestion_consumer_commit_confirmation_lag",+ "topic" => topic.clone(),+ "partition" => partition.to_string(),+ )+ .set((attempted - committed).max(0) as f64);+ }+ // Only an increase over a *previous* observation counts as+ // progress — the first poll baselines (the broker may be reporting+ // a prior incarnation's commits, which say nothing about ours).+ if state.confirmed.is_some_and(|prev| committed > prev) {+ advanced = true;+ }+ state.confirmed = Some(committed);+ }++ let all_confirmed = {+ let attempted_any = partitions.values().any(|s| s.attempted.is_some());+ attempted_any+ && partitions.values().all(|s| match s.attempted {+ Some(attempted) => s.confirmed.is_some_and(|c| c >= attempted),+ None => true,+ })+ };++ let progressed = advanced || all_confirmed;+ if progressed {+ gauge!("ingestion_consumer_last_successful_commit_timestamp_seconds").set(+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs_f64(),+ );+ }+ progressed+ }++ /// Drop the baselines for revoked partitions so the next commit after a+ /// re-assignment baselines instead of reporting a false gap/overlap+ /// (another group member may have committed in between).+ pub fn forget_partitions<'a>(&self, revoked: impl IntoIterator<Item = (&'a str, i32)>) {+ let mut partitions = self.partitions.lock().unwrap();+ for (topic, partition) in revoked {+ partitions.remove(&(topic.to_string(), partition));+ }+ }+}++/// How a send violated the per-key order invariant.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum KeyOrderViolationKind {+ /// Offsets within one assigned group were not strictly ascending.+ IntraGroupDisorder,+ /// A message at or below the key's highest ACKed offset was sent again —+ /// duplicate processing of an already-acknowledged message.+ ResendAfterAck,+}++impl KeyOrderViolationKind {+ fn as_str(&self) -> &'static str {+ match self {+ KeyOrderViolationKind::IntraGroupDisorder => "intra_group_disorder",+ KeyOrderViolationKind::ResendAfterAck => "resend_after_ack",+ }+ }+}++/// One detected per-key order violation, returned for tests and logged.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct KeyOrderViolation {+ pub kind: KeyOrderViolationKind,+ pub routing_key: String,+ pub partition: i32,+ pub offset: i64,+}++struct KeyState {+ partition: i32,+ /// Highest offset ever handed to a worker for this key.+ last_sent: i64,+ /// Highest offset a worker has ACKed for this key.+ last_acked: Option<i64>,+}++/// Tracks per-routing-key send/ACK progress and checks every assignment+/// against it. State lives exactly as long as the key's pin: the dispatcher+/// evicts it when the pin is evicted (all sends resolved, nothing deferred),+/// so the map is bounded by in-flight work — the same bound as the pin table.+///+/// A key whose state was evicted rebaselines on its next send. That is sound+/// within a process: the key's messages arrive from its single partition in+/// offset order, and eviction requires every earlier send to have resolved.+pub struct KeyOrderSentinel {+ keys: Mutex<HashMap<String, KeyState>>,+ /// Kill switch (`CONSUMER_ORDER_SENTINEL_ENABLED`). When off, checks+ /// no-op and no state accumulates.+ enabled: AtomicBool,+}++impl Default for KeyOrderSentinel {+ fn default() -> Self {+ Self {+ keys: Mutex::new(HashMap::new()),+ enabled: AtomicBool::new(true),+ }+ }+}++impl KeyOrderSentinel {+ pub fn new() -> Self {+ Self::default()+ }++ /// Toggle the sentinel. Disabling clears existing state so a later+ /// re-enable rebaselines instead of comparing against stale watermarks.+ pub fn set_enabled(&self, enabled: bool) {+ self.enabled.store(enabled, Ordering::Relaxed);+ if !enabled {+ self.clear();+ }+ }++ /// Record that `messages` for `routing_key` are being handed to a worker+ /// (fresh assignment or deferred flush). Call at assignment time, under the+ /// dispatcher's pin-table lock, so the check order matches the intended+ /// per-key send order. Null-key messages are skipped — they carry no+ /// per-key order promise (see module docs). Emits metrics and logs;+ /// returns violations for tests.+ pub fn note_sent(+ &self,+ routing_key: &str,+ messages: &[SerializedKafkaMessage],+ ) -> Vec<KeyOrderViolation> {+ if !self.enabled.load(Ordering::Relaxed) {+ return Vec::new();+ }+ let keyed: Vec<&SerializedKafkaMessage> =+ messages.iter().filter(|m| m.key.is_some()).collect();+ let unkeyed = messages.len() - keyed.len();+ if unkeyed > 0 {+ counter!("ingestion_consumer_key_sentinel_unkeyed_total").increment(unkeyed as u64);+ }+ let Some(first) = keyed.first() else {+ return Vec::new();+ };+ let last = keyed.last().expect("non-empty");+ let mut violations = Vec::new();++ // Offsets within an assigned group must be strictly ascending: groups+ // are built in batch order, and a batch preserves partition order.+ for pair in keyed.windows(2) {+ if pair[1].partition == pair[0].partition && pair[1].offset <= pair[0].offset {+ violations.push(KeyOrderViolation {+ kind: KeyOrderViolationKind::IntraGroupDisorder,+ routing_key: routing_key.to_string(),+ partition: pair[1].partition,+ offset: pair[1].offset,+ });+ }+ }++ let mut keys = self.keys.lock().unwrap();+ match keys.get_mut(routing_key) {+ None => {+ keys.insert(+ routing_key.to_string(),+ KeyState {+ partition: first.partition,+ last_sent: last.offset,+ last_acked: None,+ },+ );+ }+ Some(state) => {+ if state.partition != first.partition {+ // With null-key messages filtered out, a key's messages all+ // come from the partition its Kafka key hashes to; a move+ // mid-flight is a real anomaly (e.g. partition-count+ // change). Count it and rebaseline rather than comparing+ // offsets across partitions, which would be meaningless.+ counter!("ingestion_consumer_key_partition_moves_total").increment(1);+ *state = KeyState {+ partition: first.partition,+ last_sent: last.offset,+ last_acked: None,+ };+ } else if first.offset > state.last_sent {+ // Normal forward progress.+ state.last_sent = last.offset;+ } else if state.last_acked.is_some_and(|acked| first.offset <= acked) {+ violations.push(KeyOrderViolation {+ kind: KeyOrderViolationKind::ResendAfterAck,+ routing_key: routing_key.to_string(),+ partition: first.partition,+ offset: first.offset,+ });+ state.last_sent = state.last_sent.max(last.offset);+ } else {+ // Replay of a not-yet-ACKed range: the legal retry path+ // (send failure → defer → flush re-routes the same messages).+ counter!("ingestion_consumer_key_replays_total").increment(1);+ state.last_sent = state.last_sent.max(last.offset);+ }+ }+ }+ let key_count = keys.len();+ drop(keys);+ gauge!("ingestion_consumer_key_sentinel_keys").set(key_count as f64);++ for violation in &violations {+ counter!(+ "ingestion_consumer_key_order_violations_total",+ "kind" => violation.kind.as_str(),+ )+ .increment(1);+ warn!(+ kind = violation.kind.as_str(),+ routing_key = %violation.routing_key,+ partition = violation.partition,+ offset = violation.offset,+ "Per-key send order violation"+ );+ }++ violations+ }++ /// Record that a worker ACKed this key's messages up to `max_offset`.+ /// ACKs may arrive out of order across concurrent sub-batches (HTTP+ /// completion order), so this only ever advances the high-water mark.+ pub fn note_acked(&self, routing_key: &str, max_offset: i64) {+ if !self.enabled.load(Ordering::Relaxed) {+ return;+ }+ let mut keys = self.keys.lock().unwrap();+ if let Some(state) = keys.get_mut(routing_key) {+ state.last_acked = Some(state.last_acked.map_or(max_offset, |a| a.max(max_offset)));+ }+ }++ /// Drop a key's state. Call when its pin is evicted — every send has+ /// resolved and nothing is deferred, so there is nothing left to order+ /// against and future offsets are necessarily higher.+ pub fn evict(&self, routing_key: &str) {+ if !self.enabled.load(Ordering::Relaxed) {+ return;+ }+ let mut keys = self.keys.lock().unwrap();+ keys.remove(routing_key);+ let key_count = keys.len();+ drop(keys);+ gauge!("ingestion_consumer_key_sentinel_keys").set(key_count as f64);+ }++ /// Drop all state. Called on rebalance: partitions may move to another+ /// consumer and back, legitimately replaying uncommitted offsets, so every+ /// baseline is stale.+ pub fn clear(&self) {+ self.keys.lock().unwrap().clear();+ gauge!("ingestion_consumer_key_sentinel_keys").set(0.0);+ }++ /// Number of tracked keys (bounded by in-flight work; exposed for tests).+ pub fn key_count(&self) -> usize {+ self.keys.lock().unwrap().len()+ }+}++/// The consumer's rdkafka context: observes async commit results (a+/// fire-and-forget `CommitMode::Async` failure is otherwise invisible until+/// restart-time redelivery) and resets sentinel baselines around rebalances.+pub struct SentinelContext {+ commit_sentinel: Arc<CommitSentinel>,+ key_sentinel: Arc<KeyOrderSentinel>,+}++impl SentinelContext {+ pub fn new(commit_sentinel: Arc<CommitSentinel>, key_sentinel: Arc<KeyOrderSentinel>) -> Self {+ Self {+ commit_sentinel,+ key_sentinel,+ }+ }++ /// A context with its own free-standing sentinels, for tests and tools+ /// that build the Kafka consumer separately from the dispatcher.+ pub fn detached() -> Self {+ Self::new(+ Arc::new(CommitSentinel::new()),+ Arc::new(KeyOrderSentinel::new()),+ )+ }++ pub fn commit_sentinel(&self) -> Arc<CommitSentinel> {+ Arc::clone(&self.commit_sentinel)+ }+}++impl ClientContext for SentinelContext {}++impl ConsumerContext for SentinelContext {+ fn pre_rebalance(&self, _consumer: &BaseConsumer<Self>, rebalance: &Rebalance) {+ match rebalance {+ Rebalance::Revoke(tpl) => {+ counter!("ingestion_consumer_rebalances_total", "event" => "revoke").increment(1);+ info!(partitions = tpl.count(), "Rebalance: partitions revoked");+ self.commit_sentinel+ .forget_partitions(tpl.elements().iter().map(|e| (e.topic(), e.partition())));+ // Revoked partitions may be replayed by another consumer (or by+ // us after re-assignment) from the last commit — every per-key+ // baseline is stale.+ self.key_sentinel.clear();+ }+ Rebalance::Assign(_) => {}+ Rebalance::Error(err) => {+ counter!("ingestion_consumer_rebalances_total", "event" => "error").increment(1);+ warn!(error = %err, "Rebalance error");+ }+ }+ }++ fn post_rebalance(&self, _consumer: &BaseConsumer<Self>, rebalance: &Rebalance) {+ if let Rebalance::Assign(tpl) = rebalance {+ counter!("ingestion_consumer_rebalances_total", "event" => "assign").increment(1);+ info!(partitions = tpl.count(), "Rebalance: partitions assigned");+ }+ }++ // NOTE: `ConsumerContext::commit_callback` is deliberately not implemented.+ // librdkafka only propagates a commit result to the application when a+ // conf-level `offset_commit_cb` is registered (rust-rdkafka never does) or+ // when the commit is synchronous (a replyq is attached); manual async+ // commits silently drop their result (`rd_kafka_cgrp_propagate_commit_result`).+ // Commit success is instead verified by the consumer's commit monitor via+ // `CommitSentinel::observe_broker_committed`.+}++#[cfg(test)]+mod tests {+ use super::*;++ fn spans(entries: &[(&str, i32, i64, i64)]) -> HashMap<(String, i32), OffsetSpan> {+ entries+ .iter()+ .map(|(topic, partition, first, last)| {+ (+ (topic.to_string(), *partition),+ OffsetSpan {+ first: *first,+ last: *last,+ },+ )+ })+ .collect()+ }++ fn msg_at(partition: i32, offset: i64) -> SerializedKafkaMessage {+ SerializedKafkaMessage {+ topic: "test".to_string(),+ partition,+ offset,+ timestamp: 0,+ key: Some("t:a".to_string()),+ value: None,+ headers: HashMap::new(),+ }+ }++ fn unkeyed_msg_at(partition: i32, offset: i64) -> SerializedKafkaMessage {+ SerializedKafkaMessage {+ key: None,+ ..msg_at(partition, offset)+ }+ }++ // ---- CommitSentinel ----++ #[test]+ fn contiguous_commits_pass() {+ let sentinel = CommitSentinel::new();+ assert!(+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)])).is_empty(),+ "first commit baselines"+ );+ assert!(+ sentinel+ .check_commit(&spans(&[("t", 0, 100, 149)]))+ .is_empty(),+ "next batch starts exactly at the committed offset"+ );+ }++ #[test]+ fn commit_gap_is_detected() {+ let sentinel = CommitSentinel::new();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));+ // Offsets 100..=104 were never committed — the batch skipped them.+ let violations = sentinel.check_commit(&spans(&[("t", 0, 105, 150)]));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, CommitViolationKind::Gap);+ assert_eq!(violations[0].prev_committed, 100);+ }++ #[test]+ fn commit_regression_is_out_of_order() {+ let sentinel = CommitSentinel::new();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));+ let violations = sentinel.check_commit(&spans(&[("t", 0, 10, 50)]));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, CommitViolationKind::OutOfOrder);+ }++ #[test]+ fn partial_recommit_is_overlap() {+ let sentinel = CommitSentinel::new();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));+ let violations = sentinel.check_commit(&spans(&[("t", 0, 90, 150)]));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, CommitViolationKind::Overlap);+ }++ #[test]+ fn partitions_are_tracked_independently() {+ let sentinel = CommitSentinel::new();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99), ("t", 1, 0, 9)]));+ // Partition 0 continues cleanly; partition 1 skips 10..=19.+ let violations = sentinel.check_commit(&spans(&[("t", 0, 100, 120), ("t", 1, 20, 30)]));+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].partition, 1);+ assert_eq!(violations[0].kind, CommitViolationKind::Gap);+ }++ #[test]+ fn broker_observation_baselines_then_tracks_progress() {+ let sentinel = CommitSentinel::new();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)])); // attempted next = 100+ // First poll baselines: a stale broker offset (previous incarnation)+ // is not evidence that OUR commits landed.+ assert!(!sentinel.observe_broker_committed([("t".to_string(), 0, 40)]));+ // Broker offset advancing across polls = commits are landing.+ assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 80)]));+ // No advance and still behind the attempted offset = no progress.+ assert!(!sentinel.observe_broker_committed([("t".to_string(), 0, 80)]));+ // Catching up to everything attempted also counts as progress.+ assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 100)]));+ // Fully confirmed and idle: repeated identical polls stay "progressed"+ // via the all-confirmed arm, keeping the liveness gauge fresh.+ assert!(sentinel.observe_broker_committed([("t".to_string(), 0, 100)]));+ }++ #[test]+ fn broker_observation_requires_every_attempted_partition_confirmed() {+ let sentinel = CommitSentinel::new();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99), ("t", 1, 0, 9)]));+ sentinel.observe_broker_committed([("t".to_string(), 0, 100), ("t".to_string(), 1, 5)]);+ // Partition 0 fully confirmed but partition 1 stuck below attempted and+ // not advancing: not progress.+ assert!(!sentinel+ .observe_broker_committed([("t".to_string(), 0, 100), ("t".to_string(), 1, 5)]));+ }++ #[test]+ fn forgotten_partition_rebaselines_without_violation() {+ let sentinel = CommitSentinel::new();+ sentinel.check_commit(&spans(&[("t", 0, 0, 99)]));+ sentinel.forget_partitions([("t", 0)]);+ // After revoke + re-assign another consumer may have committed past us;+ // a non-contiguous first commit must baseline, not fire.+ assert!(sentinel+ .check_commit(&spans(&[("t", 0, 500, 599)]))+ .is_empty());+ }++ // ---- KeyOrderSentinel ----++ #[test]+ fn forward_sends_pass() {+ let sentinel = KeyOrderSentinel::new();+ assert!(sentinel+ .note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)])+ .is_empty());+ assert!(sentinel+ .note_sent("t:a", &[msg_at(0, 3), msg_at(0, 4)])+ .is_empty());+ }++ #[test]+ fn intra_group_disorder_is_detected() {+ let sentinel = KeyOrderSentinel::new();+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 2), msg_at(0, 1)]);+ assert_eq!(violations.len(), 1);+ assert_eq!(+ violations[0].kind,+ KeyOrderViolationKind::IntraGroupDisorder+ );+ }++ #[test]+ fn replay_of_unacked_range_is_not_a_violation() {+ let sentinel = KeyOrderSentinel::new();+ sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)]);+ // Send failed (no ACK) → deferred flush re-sends the same messages.+ assert!(sentinel+ .note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)])+ .is_empty());+ }++ #[test]+ fn resend_after_ack_is_a_violation() {+ let sentinel = KeyOrderSentinel::new();+ sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)]);+ sentinel.note_acked("t:a", 2);+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 2)]);+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, KeyOrderViolationKind::ResendAfterAck);+ }++ #[test]+ fn older_messages_after_acked_newer_ones_are_a_violation() {+ // The exact race the deferral machinery exists to prevent: a key's+ // newer messages were sent and ACKed while its older ones were still+ // deferred — flushing the older ones now is out-of-order processing.+ let sentinel = KeyOrderSentinel::new();+ sentinel.note_sent("t:a", &[msg_at(0, 4), msg_at(0, 5)]);+ sentinel.note_acked("t:a", 5);+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)]);+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, KeyOrderViolationKind::ResendAfterAck);+ }++ #[test]+ fn out_of_order_acks_only_advance_the_watermark() {+ let sentinel = KeyOrderSentinel::new();+ sentinel.note_sent("t:a", &[msg_at(0, 1), msg_at(0, 2)]);+ sentinel.note_sent("t:a", &[msg_at(0, 3), msg_at(0, 4)]);+ // Sub-batch ACKs arrive in reverse HTTP-completion order.+ sentinel.note_acked("t:a", 4);+ sentinel.note_acked("t:a", 2);+ // Forward progress from the true high-water mark is still clean.+ assert!(sentinel.note_sent("t:a", &[msg_at(0, 5)]).is_empty());+ // …and re-sending below it still fires.+ let violations = sentinel.note_sent("t:a", &[msg_at(0, 3)]);+ assert_eq!(violations.len(), 1);+ assert_eq!(violations[0].kind, KeyOrderViolationKind::ResendAfterAck);+ }++ #[test]+ fn eviction_drops_state_and_rebaselines() {+ let sentinel = KeyOrderSentinel::new();+ sentinel.note_sent("t:a", &[msg_at(0, 5)]);+ sentinel.note_acked("t:a", 5);+ sentinel.evict("t:a");+ assert_eq!(sentinel.key_count(), 0);+ // A rebaselined key doesn't compare against evicted history.+ assert!(sentinel.note_sent("t:a", &[msg_at(0, 6)]).is_empty());+ }++ #[test]+ fn clear_resets_all_keys() {+ let sentinel = KeyOrderSentinel::new();+ sentinel.note_sent("t:a", &[msg_at(0, 5)]);+ sentinel.note_sent("t:b", &[msg_at(1, 7)]);+ sentinel.clear();+ assert_eq!(sentinel.key_count(), 0);+ // Post-rebalance redelivery of uncommitted offsets must not fire.+ assert!(sentinel.note_sent("t:a", &[msg_at(0, 3)]).is_empty());+ }++ #[test]+ fn disabled_sentinels_check_nothing_and_hold_no_state() {+ let commit = CommitSentinel::new();+ commit.set_enabled(false);+ commit.check_commit(&spans(&[("t", 0, 0, 99)]));+ // A blatant regression passes: the kill switch disarms the check.+ assert!(commit.check_commit(&spans(&[("t", 0, 10, 50)])).is_empty());++ let keys = KeyOrderSentinel::new();+ keys.set_enabled(false);+ keys.note_sent("t:a", &[msg_at(0, 5)]);+ assert!(keys+ .note_sent("t:a", &[msg_at(0, 2), msg_at(0, 1)])+ .is_empty());+ assert_eq!(keys.key_count(), 0, "no state accumulates while disabled");+ }++ #[test]+ fn disabling_key_sentinel_clears_stale_watermarks() {+ let keys = KeyOrderSentinel::new();+ keys.note_sent("t:a", &[msg_at(0, 5)]);+ keys.note_acked("t:a", 5);+ keys.set_enabled(false);+ keys.set_enabled(true);+ // Re-enable rebaselines: no comparison against pre-disable history.+ assert!(keys.note_sent("t:a", &[msg_at(0, 3)]).is_empty());+ }++ #[test]+ fn partition_move_rebaselines() {+ let sentinel = KeyOrderSentinel::new();+ sentinel.note_sent("t:a", &[msg_at(0, 100)]);+ // Same key on a different partition: offsets aren't comparable.+ assert!(sentinel.note_sent("t:a", &[msg_at(3, 1)]).is_empty());+ }++ #[test]+ fn null_key_messages_are_ignored() {+ let sentinel = KeyOrderSentinel::new();+ // Null-key production round-robins a key across partitions; there is+ // no per-key order to check, even when offsets regress across sends.+ assert!(sentinel+ .note_sent("t:a", &[unkeyed_msg_at(1, 5000)])+ .is_empty());+ assert_eq!(sentinel.key_count(), 0, "unkeyed sends hold no state");+ assert!(sentinel+ .note_sent("t:a", &[unkeyed_msg_at(0, 3)])+ .is_empty());+ }++ #[test]+ fn null_key_offsets_do_not_inflate_watermarks() {+ // A mixed group (keyed traffic that overflowed mid-stream): the+ // unkeyed message's offset comes from another partition and must not+ // advance the key's send/ACK watermarks — otherwise the next keyed+ // send would fire a false resend_after_ack.+ let sentinel = KeyOrderSentinel::new();+ assert!(sentinel+ .note_sent("t:a", &[msg_at(0, 100), unkeyed_msg_at(1, 5000)])+ .is_empty());+ sentinel.note_acked("t:a", 100);+ assert!(sentinel.note_sent("t:a", &[msg_at(0, 101)]).is_empty());+ }+}diff --git a/rust/ingestion-consumer/src/transport.rs b/rust/ingestion-consumer/src/transport.rsindex cf28fb74affe..cd7abc98bb1a 100644--- a/rust/ingestion-consumer/src/transport.rs+++ b/rust/ingestion-consumer/src/transport.rs@@ -58,6 +58,9 @@ pub struct HttpTransport {api_secret: Option<String>,worker_semaphores: DashMap<String, Arc<Semaphore>>,worker_concurrent_batches: usize,+ /// Process-unique sender id stamped on every request, so the worker-side+ /// feed-order sentinel can rebaseline when the consumer restarts.+ consumer_id: String,}impl HttpTransport {@@ -95,6 +98,7 @@ impl HttpTransport {api_secret,worker_semaphores,worker_concurrent_batches,+ consumer_id: make_consumer_id(),}}@@ -165,16 +169,22 @@ impl HttpTransport {/// here — that's the natural backpressure. The permit is released on/// drop, covering all return paths (success, retriable error, retries/// exhausted, non-retriable error).+ /// `replay` marks a request that may repeat previously sent messages (a+ /// deferred-flush re-route); HTTP retries within this call are marked as+ /// replays automatically.pub async fn send_batch(&self,worker_url: &str,batch_id: &str,messages: Vec<SerializedKafkaMessage>,+ replay: bool,) -> Result<u32, SendError> {let message_count = messages.len();- let request = IngestBatchRequest {+ let mut request = IngestBatchRequest {batch_id: batch_id.to_string(),messages,+ consumer_id: self.consumer_id.clone(),+ replay,};let url = format!("{worker_url}/ingest");@@ -210,6 +220,10 @@ impl HttpTransport {let mut last_was_busy = false;for attempt in 0..=self.max_retries {if attempt > 0 {+ // A retried request may repeat messages the worker already+ // processed (e.g. a timeout after the worker finished) — mark it+ // so the worker-side sentinel counts repeats as replays.+ request.replay = true;tokio::time::sleep(retry_backoff(attempt, last_was_busy)).await;counter!("ingestion_consumer_transport_retries_total",@@ -365,6 +379,17 @@ impl TransportError {/// that callers backing off the same worker don't retry in lockstep; other/// retriable errors use a short exponential backoff. `attempt` is 1-based (the/// first retry passes 1).+/// Process-unique sender id: workers use it to scope feed-order baselines to+/// one consumer incarnation.+fn make_consumer_id() -> String {+ let ts = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_millis();+ let rand: u32 = rand::random();+ format!("{ts:x}-{rand:08x}")+}+fn retry_backoff(attempt: u32, busy: bool) -> Duration {let exp = 2u64.saturating_pow(attempt.saturating_sub(1));if busy {diff --git a/rust/ingestion-consumer/src/types.rs b/rust/ingestion-consumer/src/types.rsindex ddc0bf15ad79..30fe25c76f26 100644--- a/rust/ingestion-consumer/src/types.rs+++ b/rust/ingestion-consumer/src/types.rs@@ -20,6 +20,15 @@ pub struct SerializedKafkaMessage {pub struct IngestBatchRequest {pub batch_id: String,pub messages: Vec<SerializedKafkaMessage>,+ /// Identifies this consumer process incarnation. The worker's feed-order+ /// sentinel rebaselines a key when the sender changes (restart/rebalance+ /// legitimately replays uncommitted offsets).+ pub consumer_id: String,+ /// True when this request may repeat previously sent messages (an HTTP+ /// retry, or a deferred-flush re-route after a send failure). The worker's+ /// sentinel counts repeats on replay requests as at-least-once replays+ /// rather than order violations.+ pub replay: bool,}/// Matches `IngestBatchResponse` in `nodejs/src/ingestion/api/types.ts`.diff --git a/rust/ingestion-consumer/tests/e2e_integration_test.rs b/rust/ingestion-consumer/tests/e2e_integration_test.rsindex 495e63812a35..a8efe2ac2ed6 100644--- a/rust/ingestion-consumer/tests/e2e_integration_test.rs+++ b/rust/ingestion-consumer/tests/e2e_integration_test.rs@@ -27,6 +27,7 @@ use uuid::Uuid;use ingestion_consumer::consumer::{IngestionConsumer, IngestionConsumerOptions};use ingestion_consumer::discovery::reconcile_membership;use ingestion_consumer::dispatcher::Dispatcher;+use ingestion_consumer::order_sentinel::SentinelContext;use ingestion_consumer::transport::HttpTransport;use ingestion_consumer::types::{IngestBatchRequest, IngestBatchResponse, SerializedKafkaMessage};use ingestion_consumer::worker_registry::{WorkerId, WorkerRegistry, WorkerRegistryConfig};@@ -371,7 +372,11 @@ struct Harness {/// the production batch consumer (no auto commit/store, earliest reset). The/// short session timeout makes group handovers observable quickly in tests./// `instance_id` opts into static membership (`group.instance.id`).-fn make_kafka_consumer(topic: &str, group_id: &str, instance_id: Option<&str>) -> StreamConsumer {+fn make_kafka_consumer(+ topic: &str,+ group_id: &str,+ instance_id: Option<&str>,+) -> StreamConsumer<SentinelContext> {let mut config = ClientConfig::new();config.set("bootstrap.servers", KAFKA_BROKERS)@@ -384,7 +389,9 @@ fn make_kafka_consumer(topic: &str, group_id: &str, instance_id: Option<&str>) -if let Some(id) = instance_id {config.set("group.instance.id", id);}- let kafka_consumer: StreamConsumer = config.create().expect("kafka consumer");+ let kafka_consumer: StreamConsumer<SentinelContext> = config+ .create_with_context(SentinelContext::detached())+ .expect("kafka consumer");kafka_consumer.subscribe(&[topic]).expect("subscribe");kafka_consumer}@@ -1263,7 +1270,7 @@ async fn drain_defer_flush_delivers_to_survivor_over_http() {let pinned_idx = workers.iter().position(|w| w.url == pinned_url).unwrap();let survivor_idx = 1 - pinned_idx;transport- .send_batch(&pinned_url, "batch-1", b1[0].messages.clone())+ .send_batch(&pinned_url, "batch-1", b1[0].messages.clone(), false).await.expect("batch-1 send");@@ -1290,7 +1297,12 @@ async fn drain_defer_flush_delivers_to_survivor_over_http() {"deferred group flushes to the survivor, not the drainer");transport- .send_batch(f2[0].worker.as_ref(), "batch-2", f2[0].messages.clone())+ .send_batch(+ f2[0].worker.as_ref(),+ "batch-2",+ f2[0].messages.clone(),+ false,+ ).await.expect("batch-2 flush send");diff --git a/rust/ingestion-consumer/tests/transport_integration_test.rs b/rust/ingestion-consumer/tests/transport_integration_test.rsindex a0685b114899..480db3fe55de 100644--- a/rust/ingestion-consumer/tests/transport_integration_test.rs+++ b/rust/ingestion-consumer/tests/transport_integration_test.rs@@ -222,7 +222,7 @@ async fn transport_sends_batch_and_receives_ack() {];let accepted = transport- .send_batch(&url, "batch-1", messages)+ .send_batch(&url, "batch-1", messages, false).await.unwrap();@@ -251,7 +251,9 @@ async fn transport_retries_on_server_error() {let messages = vec![make_message("tok", "user", 0, "{}")];- let result = transport.send_batch(&url, "batch-retry", messages).await;+ let result = transport+ .send_batch(&url, "batch-retry", messages, false)+ .await;assert!(result.is_err());}@@ -270,7 +272,7 @@ async fn transport_retries_on_worker_busy() {let start = std::time::Instant::now();let err = transport- .send_batch(&url, "batch-busy", messages)+ .send_batch(&url, "batch-busy", messages, false).await.unwrap_err();let elapsed = start.elapsed();@@ -298,7 +300,7 @@ async fn transport_recovers_after_worker_busy() {let messages = vec![make_message("tok", "user", 0, "{}")];let accepted = transport- .send_batch(&url, "batch-recover", messages)+ .send_batch(&url, "batch-recover", messages, false).await.expect("should succeed after the worker stops being busy");assert_eq!(accepted, 1);@@ -311,7 +313,9 @@ async fn transport_fails_on_unreachable_worker() {let transport = HttpTransport::new(Duration::from_secs(1), 0, None, &urls, 1);let messages = vec![make_message("tok", "user", 0, "{}")];- let result = transport.send_batch(&url, "batch-fail", messages).await;+ let result = transport+ .send_batch(&url, "batch-fail", messages, false)+ .await;assert!(result.is_err());}@@ -327,7 +331,7 @@ async fn transport_lazily_creates_semaphore_for_unseeded_worker() {let messages = vec![make_message("tok", "user", 0, "{}")];let accepted = transport- .send_batch(&url, "batch-lazy", messages)+ .send_batch(&url, "batch-lazy", messages, false).await.expect("send to an unseeded worker should succeed via lazy semaphore creation");@@ -361,6 +365,7 @@ async fn transport_serializes_concurrent_sends_to_same_worker() {&u,&format!("batch-{i}"),vec![make_message("tok", "u", 0, "{}")],+ false,).await.unwrap()@@ -404,18 +409,28 @@ async fn transport_parallelizes_across_different_workers() {let t = transport.clone();let u = url_a.clone();tokio::spawn(async move {- t.send_batch(&u, "batch-a", vec![make_message("tok", "u", 0, "{}")])- .await- .unwrap()+ t.send_batch(+ &u,+ "batch-a",+ vec![make_message("tok", "u", 0, "{}")],+ false,+ )+ .await+ .unwrap()})};let t2 = {let t = transport.clone();let u = url_b.clone();tokio::spawn(async move {- t.send_batch(&u, "batch-b", vec![make_message("tok", "u", 0, "{}")])- .await- .unwrap()+ t.send_batch(+ &u,+ "batch-b",+ vec![make_message("tok", "u", 0, "{}")],+ false,+ )+ .await+ .unwrap()})};t1.await.unwrap();@@ -481,7 +496,7 @@ async fn dispatcher_and_transport_end_to_end() {let d = Arc::clone(&dispatcher);handles.push(tokio::spawn(async move {let result = t- .send_batch(&worker, "batch-e2e", sub_batch.messages)+ .send_batch(&worker, "batch-e2e", sub_batch.messages, false).await.unwrap();d.on_sub_batch_resolved(&worker, message_count, &routing_keys, false);@@ -546,7 +561,7 @@ async fn wire_format_preserves_unicode_and_null_fields() {}];transport- .send_batch(&url, "batch-unicode", messages)+ .send_batch(&url, "batch-unicode", messages, false).await.unwrap();