This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new 00af52e77f98 CAMEL-27431: camel-azure-eventhubs - a checkpoint no 
longer passes an event still in flight, and no longer moves back (#30805)
00af52e77f98 is described below

commit 00af52e77f98e11123b39477108a9cad39e8c1b5
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:28:28 2026 +0530

    CAMEL-27431: camel-azure-eventhubs - a checkpoint no longer passes an event 
still in flight, and no longer moves back (#30805)
    
    The consumer checkpointed a partition with the event context of the 
exchange that completed last, and the
    checkpoint store keeps whichever write lands last. With an asynchronous 
route a checkpoint could pass an event
    still being processed (lost after a stop, crash or rebalance), reordered 
completions moved the stored checkpoint
    back, and with a synchronous route a late timer write could move it back 
over a later size checkpoint.
    
    - EventHubsPartitionCheckpoints (package-private, one per partition, under 
the consumer lock) records the
      delivered events by sequence number until every event before them is done 
(completed or failed); events done one
      after the other are one entry, so memory follows the events in flight.
    - A checkpoint, by batch size or by timeout, is written for the last event 
below which every delivered event is
      done, only if it is after the last one written; the timer now checkpoints 
under the consumer lock through the
      same path. One write per partition is in flight, the next waits for its 
answer, so writes land in order.
    - Events completed after an event in flight stay counted for the next 
checkpoint; a failure that lets the
      checkpoint move forward starts a window for them.
    - Completions of events delivered before a stop, a lost partition (new 
processPartitionClose handler, new
      four-argument EventHubsClientFactory.createEventProcessorClient) or a new 
delivery of the partition do not move
      the checkpoint. EVENT_PROCESSOR_SHUTDOWN keeps the state, so a graceful 
stop still checkpoints.
    - A failed exchange is still passed by the next checkpoint, as before. An 
exchange whose completion never runs (seda
      discardWhenFull) now holds the checkpoint of its partition until the 
partition is lost or the consumer restarts.
    - Tests: EventHubsConsumerCheckpointOrderTest; the DST world checks every 
stored checkpoint (in flight, going
      back) and stubs either factory overload; the unit tests that call 
processCommit record the delivery first.
    - Upgrade guide 4.24 entry; DST world invariants regenerated in the 
component JSON and the catalog.
    
    * CAMEL-27431: camel-azure-eventhubs - review follow-up: restore the count 
of a failed checkpoint under the lock
    
    - The error callback of a failed checkpoint write (it adds the events of a 
failed timeout
      checkpoint back to the count of the partition) now runs inside 
answered(), under the
      consumer lock. Run after the lock was released, a checkpoint taken in 
between reset the
      count, and the callback then added the events to it again, so the next 
checkpoint by
      batch size could come early. The checkpoint position was not affected.
    - close() drops completedUpTo, so the last event and its data are not kept 
after the
      partition is closed.
    - A comment on the identity check of the EventContext in completed(): an 
event delivered
      again at the same sequence number has another EventContext.
    
    New test EventHubsPartitionCheckpointsTest: the error callback of a failed 
write runs
    with the lock held (fails before this change).
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/components/azure-eventhubs.json  |   2 +-
 .../component/azure/eventhubs/azure-eventhubs.json |   2 +-
 .../eventhubs/EventHubsCheckpointUpdaterTask.java  |  18 +
 .../azure/eventhubs/EventHubsConsumer.java         | 187 +++++++++--
 .../eventhubs/EventHubsPartitionCheckpoints.java   | 236 +++++++++++++
 .../eventhubs/client/EventHubsClientFactory.java   |  14 +
 ...ntHubsConsumerCheckpointAfterBatchSizeTest.java |   9 +-
 .../EventHubsConsumerCheckpointOrderTest.java      | 370 +++++++++++++++++++++
 .../EventHubsConsumerCheckpointWindowTest.java     |   8 +-
 ...ventHubsConsumerPerPartitionCheckpointTest.java |  18 +-
 .../EventHubsPartitionCheckpointsTest.java         |  70 ++++
 .../eventhubs/dst/EventHubsCheckpointDstTest.java  |   4 +-
 .../azure/eventhubs/dst/EventHubsWorld.java        |  76 ++++-
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  29 ++
 14 files changed, 992 insertions(+), 51 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/azure-eventhubs.json
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/azure-eventhubs.json
index d7dab0e39771..b61c1a6830e3 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/azure-eventhubs.json
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/components/azure-eventhubs.json
@@ -94,6 +94,6 @@
     "tokenCredential": { "index": 25, "kind": "parameter", "displayName": 
"Token Credential", "group": "security", "label": "security", "required": 
false, "type": "object", "javaType": 
"com.azure.core.credential.TokenCredential", "deprecated": false, "autowired": 
true, "secret": true, "security": "secret", "configurationClass": 
"org.apache.camel.component.azure.eventhubs.EventHubsConfiguration", 
"configurationField": "configuration", "description": "Provide custom 
authentication credenti [...]
   },
   "dstWorlds": {
-    "EventHubsWorld": { "javaType": 
"org.apache.camel.component.azure.eventhubs.dst.EventHubsWorld", "fake": "a 
mocked EventHubsClientFactory that delivers the events per partition, and a 
fake CheckpointStore", "covers": [ "checkpointing by checkpointBatchSize and 
checkpointBatchTimeout", "one or two partitions with bursts and quiet periods 
of events", "an asynchronous downstream step" ], "faults": [ "the downstream 
step answers slowly", "the downstream step fails", "the checkpoint store [...]
+    "EventHubsWorld": { "javaType": 
"org.apache.camel.component.azure.eventhubs.dst.EventHubsWorld", "fake": "a 
mocked EventHubsClientFactory that delivers the events per partition, and a 
fake CheckpointStore", "covers": [ "checkpointing by checkpointBatchSize and 
checkpointBatchTimeout", "one or two partitions with bursts and quiet periods 
of events", "an asynchronous downstream step" ], "faults": [ "the downstream 
step answers slowly", "the downstream step fails", "the checkpoint store [...]
   }
 }
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/generated/resources/META-INF/org/apache/camel/component/azure/eventhubs/azure-eventhubs.json
 
b/components/camel-azure/camel-azure-eventhubs/src/generated/resources/META-INF/org/apache/camel/component/azure/eventhubs/azure-eventhubs.json
index d7dab0e39771..b61c1a6830e3 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/generated/resources/META-INF/org/apache/camel/component/azure/eventhubs/azure-eventhubs.json
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/generated/resources/META-INF/org/apache/camel/component/azure/eventhubs/azure-eventhubs.json
@@ -94,6 +94,6 @@
     "tokenCredential": { "index": 25, "kind": "parameter", "displayName": 
"Token Credential", "group": "security", "label": "security", "required": 
false, "type": "object", "javaType": 
"com.azure.core.credential.TokenCredential", "deprecated": false, "autowired": 
true, "secret": true, "security": "secret", "configurationClass": 
"org.apache.camel.component.azure.eventhubs.EventHubsConfiguration", 
"configurationField": "configuration", "description": "Provide custom 
authentication credenti [...]
   },
   "dstWorlds": {
-    "EventHubsWorld": { "javaType": 
"org.apache.camel.component.azure.eventhubs.dst.EventHubsWorld", "fake": "a 
mocked EventHubsClientFactory that delivers the events per partition, and a 
fake CheckpointStore", "covers": [ "checkpointing by checkpointBatchSize and 
checkpointBatchTimeout", "one or two partitions with bursts and quiet periods 
of events", "an asynchronous downstream step" ], "faults": [ "the downstream 
step answers slowly", "the downstream step fails", "the checkpoint store [...]
+    "EventHubsWorld": { "javaType": 
"org.apache.camel.component.azure.eventhubs.dst.EventHubsWorld", "fake": "a 
mocked EventHubsClientFactory that delivers the events per partition, and a 
fake CheckpointStore", "covers": [ "checkpointing by checkpointBatchSize and 
checkpointBatchTimeout", "one or two partitions with bursts and quiet periods 
of events", "an asynchronous downstream step" ], "faults": [ "the downstream 
step answers slowly", "the downstream step fails", "the checkpoint store [...]
   }
 }
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsCheckpointUpdaterTask.java
 
b/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsCheckpointUpdaterTask.java
index 1de96d0c19ab..af1191b4278f 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsCheckpointUpdaterTask.java
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsCheckpointUpdaterTask.java
@@ -38,6 +38,8 @@ public class EventHubsCheckpointUpdaterTask implements 
Runnable {
     private final Lock lock;
     // set when the task has taken the count of its window, or was cancelled; 
read and written under the lock only
     private boolean done;
+    // the checkpoint of the consumer, run under its lock instead of taking 
the count and the event context here
+    private final Runnable checkpoint;
 
     /**
      * Creates a task that synchronizes on a private lock of its own, 
unrelated to any consumer: for standalone or test
@@ -56,6 +58,18 @@ public class EventHubsCheckpointUpdaterTask implements 
Runnable {
         this.eventContext = eventContext;
         this.processedEvents = processedEvents;
         this.lock = lock;
+        this.checkpoint = null;
+    }
+
+    /**
+     * Creates the task of a window of {@link EventHubsConsumer}: when it 
runs, unless it was cancelled, it runs the
+     * checkpoint of the consumer under the lock of the consumer, which 
decides what to checkpoint.
+     */
+    EventHubsCheckpointUpdaterTask(Lock lock, Runnable checkpoint) {
+        this.eventContext = null;
+        this.processedEvents = null;
+        this.lock = lock;
+        this.checkpoint = checkpoint;
     }
 
     @Override
@@ -73,6 +87,10 @@ public class EventHubsCheckpointUpdaterTask implements 
Runnable {
                 return;
             }
             done = true;
+            if (checkpoint != null) {
+                checkpoint.run();
+                return;
+            }
             processed = processedEvents.getAndSet(0);
             context = eventContext;
         } finally {
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumer.java
 
b/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumer.java
index eddf97f3a7b2..664557e96e0d 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumer.java
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumer.java
@@ -25,6 +25,8 @@ import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.locks.ReentrantLock;
 
 import com.azure.messaging.eventhubs.EventProcessorClient;
+import com.azure.messaging.eventhubs.models.CloseContext;
+import com.azure.messaging.eventhubs.models.CloseReason;
 import com.azure.messaging.eventhubs.models.ErrorContext;
 import com.azure.messaging.eventhubs.models.EventContext;
 import org.apache.camel.AsyncCallback;
@@ -54,6 +56,7 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
     private final Map<String, AtomicInteger> processedEventsByPartition = new 
ConcurrentHashMap<>();
     private final Map<String, ScheduledFuture<?>> scheduledTasksByPartition = 
new ConcurrentHashMap<>();
     private final Map<String, EventHubsCheckpointUpdaterTask> 
checkpointTasksByPartition = new ConcurrentHashMap<>();
+    private final Map<String, EventHubsPartitionCheckpoints> 
checkpointsByPartition = new ConcurrentHashMap<>();
     private ScheduledExecutorService scheduledExecutorService;
 
     public EventHubsConsumer(final EventHubsEndpoint endpoint, final Processor 
processor) {
@@ -70,7 +73,7 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
 
         // create the client
         processorClient = 
EventHubsClientFactory.createEventProcessorClient(getConfiguration(),
-                this::onEventListener, this::onErrorListener);
+                this::onEventListener, this::onErrorListener, 
this::onPartitionClose);
 
         // start the client but we will rely on the Azure Client Scheduler for 
thread management
         processorClient.start();
@@ -87,6 +90,8 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
         processedEventsByPartition.clear();
         scheduledTasksByPartition.clear();
         checkpointTasksByPartition.clear();
+        // the exchanges still in flight no longer move the checkpoint: their 
events are delivered again after a start
+        checkpointsByPartition.clear();
 
         // shutdown camel consumer
         super.doStop();
@@ -179,6 +184,7 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
         pendingExchanges.incrementAndGet();
 
         final Exchange exchange = createAzureEventHubExchange(eventContext);
+        processDelivered(eventContext);
 
         // add exchange callback
         exchange.getExchangeExtension().addOnCompletion(new Synchronization() {
@@ -195,8 +201,8 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
             @Override
             public void onFailure(Exchange exchange) {
                 try {
-                    // we do nothing here
-                    processRollback(exchange);
+                    // the event is not delivered again, but it no longer 
holds back the checkpoint
+                    processRollback(exchange, eventContext);
                 } finally {
                     pendingExchanges.decrementAndGet();
                 }
@@ -207,6 +213,47 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
         getAsyncProcessor().process(exchange, cb);
     }
 
+    private void onPartitionClose(final CloseContext closeContext) {
+        // when the processor client stops, the exchanges in flight still 
complete and checkpoint
+        if (closeContext.getCloseReason() != 
CloseReason.LOST_PARTITION_OWNERSHIP) {
+            return;
+        }
+        final String partitionId = 
closeContext.getPartitionContext().getPartitionId();
+        lock.lock();
+        try {
+            // the new owner resumes after the stored checkpoint: the 
exchanges in flight here must not move it any
+            // more, as their events are delivered again there
+            if (dropPartition(partitionId)) {
+                LOG.info("Partition {} was lost: the exchanges of its events 
still in flight are not checkpointed",
+                        partitionId);
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Drops the checkpoint state of the partition, and cancels the timer of 
its window. Under the lock.
+     *
+     * @return whether the partition had a checkpoint state
+     */
+    private boolean dropPartition(String partitionId) {
+        final EventHubsPartitionCheckpoints checkpoints = 
checkpointsByPartition.remove(partitionId);
+        if (checkpoints != null) {
+            checkpoints.close();
+        }
+        final EventHubsCheckpointUpdaterTask checkpointTask = 
checkpointTasksByPartition.remove(partitionId);
+        if (checkpointTask != null) {
+            checkpointTask.cancel();
+        }
+        final ScheduledFuture<?> scheduledTask = 
scheduledTasksByPartition.remove(partitionId);
+        if (scheduledTask != null) {
+            scheduledTask.cancel(false);
+        }
+        processedEventsByPartition.remove(partitionId);
+        return checkpoints != null;
+    }
+
     private void onErrorListener(final ErrorContext errorContext) {
         final Exchange exchange = createAzureEventHubExchange(errorContext);
 
@@ -217,6 +264,33 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
         }
     }
 
+    /**
+     * The event is delivered to the route: until its exchange is done, no 
checkpoint of its partition passes it.
+     *
+     * @param eventContext the event context of the event
+     */
+    void processDelivered(final EventContext eventContext) {
+        lock.lock();
+        try {
+            final String partitionId = 
eventContext.getPartitionContext().getPartitionId();
+            final EventHubsPartitionCheckpoints checkpoints = 
checkpointsByPartition.computeIfAbsent(partitionId,
+                    ignored -> new EventHubsPartitionCheckpoints(lock));
+            if (!checkpoints.delivered(eventContext)) {
+                // the partition was claimed again (closed without being 
reported as lost) and the SDK delivers it again
+                // from the stored checkpoint: the exchanges of the earlier 
deliveries no longer move the checkpoint
+                LOG.info("Partition {} is delivered again from sequence number 
{}: the exchanges of its earlier deliveries"
+                         + " still in flight are not checkpointed",
+                        partitionId, 
eventContext.getEventData().getSequenceNumber());
+                dropPartition(partitionId);
+                final EventHubsPartitionCheckpoints again = new 
EventHubsPartitionCheckpoints(lock);
+                again.delivered(eventContext);
+                checkpointsByPartition.put(partitionId, again);
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
     /**
      * Strategy to commit the offset after message being processed 
successfully.
      *
@@ -227,6 +301,13 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
         lock.lock();
         try {
             final String partitionId = 
eventContext.getPartitionContext().getPartitionId();
+            final EventHubsPartitionCheckpoints checkpoints = 
checkpointsByPartition.get(partitionId);
+            if (checkpoints == null || !checkpoints.completed(eventContext, 
true)) {
+                LOG.debug("event of partition {} was delivered before the 
consumer was stopped or lost the partition:"
+                          + " it does not move the checkpoint",
+                        partitionId);
+                return;
+            }
             final AtomicInteger processedEvents = 
processedEventsByPartition.computeIfAbsent(partitionId,
                     ignored -> new AtomicInteger());
             EventHubsCheckpointUpdaterTask checkpointTask = 
checkpointTasksByPartition.get(partitionId);
@@ -236,23 +317,16 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
             // timer can run in the millisecond of its scheduled time, or 
later, and the event must be counted in the
             // window whose timer has not taken the count yet
             if (checkpointTask == null || checkpointTask.isDone()) {
-                checkpointTask = new 
EventHubsCheckpointUpdaterTask(eventContext, processedEvents, lock);
-                // delegate the checkpoint update to a dedicated Thread
-                long timeout = getConfiguration().getCheckpointBatchTimeout();
-                checkpointTask.setScheduledTime(System.currentTimeMillis() + 
timeout);
-                scheduledTask = 
scheduledExecutorService.schedule(checkpointTask, timeout, 
TimeUnit.MILLISECONDS);
-                checkpointTasksByPartition.put(partitionId, checkpointTask);
-                scheduledTasksByPartition.put(partitionId, scheduledTask);
-            } else {
-                // updates the eventContext to use for the offset to be the 
most accurate
-                checkpointTask.setEventContext(eventContext);
+                checkpointTask = startWindow(partitionId, checkpoints, 
processedEvents);
+                scheduledTask = scheduledTasksByPartition.get(partitionId);
             }
 
             try {
                 var cnt = processedEvents.incrementAndGet();
-                // >= and not ==: a failed timeout checkpoint adds its count 
back, so the count can pass the batch size
-                if (cnt >= getConfiguration().getCheckpointBatchSize()) {
-                    processedEvents.set(0);
+                // >= and not ==: a failed timeout checkpoint adds its count 
back, so the count can pass the batch size;
+                // and the checkpoint waits while every event completed since 
the last one is after an event in flight
+                if (cnt >= getConfiguration().getCheckpointBatchSize()
+                        && checkpoint(checkpoints, processedEvents, false)) {
                     
exchange.getIn().setHeader(EventHubsConstants.CHECKPOINT_UPDATED_BY, 
COMPLETED_BY_SIZE);
                     LOG.debug("eventhub consumer batch size of reached for 
partition {}", partitionId);
                     // a timer that has already started takes nothing (it 
waits for the lock)
@@ -264,12 +338,6 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
                     // scheduled time, else the events of the rest of that 
window are not checkpointed by the timeout
                     checkpointTasksByPartition.remove(partitionId);
                     scheduledTasksByPartition.remove(partitionId);
-                    eventContext.updateCheckpointAsync()
-                            .subscribe(unused -> LOG.debug("Processed one 
event..."),
-                                    error -> LOG.warn("Error when updating 
Checkpoint: {}", error.getMessage(), error),
-                                    () -> {
-                                        LOG.debug("Checkpoint updated.");
-                                    });
                 } else if (checkpointTask.isExpired()) {
                     
exchange.getIn().setHeader(EventHubsConstants.CHECKPOINT_UPDATED_BY, 
COMPLETED_BY_TIMEOUT);
                     LOG.debug("eventhub consumer batch timeout reached for 
partition {}", partitionId);
@@ -289,14 +357,83 @@ public class EventHubsConsumer extends DefaultConsumer 
implements ShutdownAware
     }
 
     /**
-     * Strategy when processing the exchange failed.
+     * Strategy when processing the exchange failed: the event is not 
delivered again, and is passed by the next
+     * checkpoint (it is not counted, nor checkpointed by itself).
      *
-     * @param exchange the exchange
+     * @param exchange     the exchange
+     * @param eventContext the event context of the event
      */
-    private void processRollback(Exchange exchange) {
+    void processRollback(final Exchange exchange, final EventContext 
eventContext) {
         final Exception cause = exchange.getException();
         if (cause != null) {
             getExceptionHandler().handleException("Error during processing 
exchange.", exchange, cause);
         }
+        lock.lock();
+        try {
+            final String partitionId = 
eventContext.getPartitionContext().getPartitionId();
+            final EventHubsPartitionCheckpoints checkpoints = 
checkpointsByPartition.get(partitionId);
+            if (checkpoints == null || !checkpoints.completed(eventContext, 
false)) {
+                return;
+            }
+            // events completed after this one waited for it: a window must 
checkpoint them
+            final AtomicInteger processedEvents = 
processedEventsByPartition.get(partitionId);
+            final EventHubsCheckpointUpdaterTask checkpointTask = 
checkpointTasksByPartition.get(partitionId);
+            if (processedEvents != null && processedEvents.get() > 0
+                    && (checkpointTask == null || checkpointTask.isDone())) {
+                startWindow(partitionId, checkpoints, processedEvents);
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    /**
+     * Starts a checkpoint window of the partition, whose timer checkpoints it 
after the batch timeout. Under the lock.
+     */
+    private EventHubsCheckpointUpdaterTask startWindow(
+            String partitionId, EventHubsPartitionCheckpoints checkpoints, 
AtomicInteger processedEvents) {
+        final EventHubsCheckpointUpdaterTask checkpointTask = new 
EventHubsCheckpointUpdaterTask(
+                lock, () -> checkpointByTimeout(checkpoints, processedEvents));
+        // delegate the checkpoint update to a dedicated Thread
+        final long timeout = getConfiguration().getCheckpointBatchTimeout();
+        checkpointTask.setScheduledTime(System.currentTimeMillis() + timeout);
+        final ScheduledFuture<?> scheduledTask
+                = scheduledExecutorService.schedule(checkpointTask, timeout, 
TimeUnit.MILLISECONDS);
+        checkpointTasksByPartition.put(partitionId, checkpointTask);
+        scheduledTasksByPartition.put(partitionId, scheduledTask);
+        return checkpointTask;
+    }
+
+    /**
+     * The timer of a window: checkpoints the partition if events were 
processed since the last checkpoint. Under the
+     * lock.
+     */
+    private void checkpointByTimeout(EventHubsPartitionCheckpoints 
checkpoints, AtomicInteger processedEvents) {
+        if (processedEvents.get() == 0) {
+            LOG.debug("skip checkpointing offset even if timeout is reached. 
No events processed");
+        } else if (checkpoint(checkpoints, processedEvents, true)) {
+            LOG.debug("checkpointing offset after reaching timeout");
+        } else {
+            LOG.debug("skip checkpointing offset after reaching timeout: the 
events processed since the last checkpoint"
+                      + " are after an event still in flight");
+        }
+    }
+
+    /**
+     * Checkpoints the partition up to the last event below which every 
delivered event has completed, if that is after
+     * the last checkpoint. The events completed after an event still in 
flight stay counted for the next checkpoint.
+     * Under the lock.
+     *
+     * @return false if there is nothing to checkpoint
+     */
+    private boolean checkpoint(
+            EventHubsPartitionCheckpoints checkpoints, AtomicInteger 
processedEvents, boolean byTimeout) {
+        if (!checkpoints.canCheckpoint()) {
+            return false;
+        }
+        final int ahead = checkpoints.succeededAhead();
+        final int covered = Math.max(0, processedEvents.getAndSet(ahead) - 
ahead);
+        // a failed checkpoint by timeout counts its events again for the next 
checkpoint
+        return checkpoints.checkpoint(byTimeout ? () -> 
processedEvents.addAndGet(covered) : null);
     }
 }
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsPartitionCheckpoints.java
 
b/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsPartitionCheckpoints.java
new file mode 100644
index 000000000000..ab557bc67585
--- /dev/null
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/EventHubsPartitionCheckpoints.java
@@ -0,0 +1,236 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.azure.eventhubs;
+
+import java.util.Map;
+import java.util.NavigableMap;
+import java.util.TreeMap;
+import java.util.concurrent.locks.Lock;
+
+import com.azure.messaging.eventhubs.models.EventContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import reactor.core.publisher.Mono;
+
+/**
+ * The checkpoint state of one partition owned by an {@link 
EventHubsConsumer}: the events delivered to the route and
+ * not yet passed by the checkpoint, and the checkpoint writes of the 
partition.
+ * <p>
+ * The exchanges of a partition can complete in any order (any asynchronous 
step in the route), while the checkpoint
+ * store keeps one position per partition and the next owner of the partition 
resumes after it. So a checkpoint is
+ * written only for an event below which every delivered event has completed 
(successfully or not), only when it is
+ * after the last checkpoint written, and only when the write before it has 
answered: the stored checkpoint never passes
+ * an event still in flight and never goes back.
+ * <p>
+ * Used under the lock of the consumer only (the answers of the writes take 
it).
+ */
+final class EventHubsPartitionCheckpoints {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(EventHubsPartitionCheckpoints.class);
+
+    private final Lock lock;
+    // the delivered events by sequence number, until every event before them 
has completed; the events completed one
+    // after the other are one entry, under the last of them, so an event that 
never completes holds one entry per run
+    // of events completed after it, not one per event
+    private final NavigableMap<Long, Delivered> delivered = new TreeMap<>();
+    private long lastDelivered = -1;
+    // the events in delivered that completed successfully: they wait for an 
earlier event still in flight
+    private int succeededAhead;
+    // the last event below which every delivered event has completed: the 
furthest a checkpoint may go
+    private EventContext completedUpTo;
+    // the sequence number of the last checkpoint written (or waiting to be 
written), and of the last one stored
+    private long written = -1;
+    private long stored = -1;
+    // a write is in flight; the next checkpoint waits for its answer
+    private boolean writing;
+    private EventContext waiting;
+    private Runnable waitingOnError;
+    // the partition was lost: its checkpoints belong to its new owner
+    private boolean closed;
+
+    EventHubsPartitionCheckpoints(Lock lock) {
+        this.lock = lock;
+    }
+
+    /**
+     * The event is delivered to the route. The SDK delivers the events of a 
partition one at a time, in order.
+     *
+     * @return false if the event is not after the last one delivered: the SDK 
delivers the partition again from the
+     *         stored checkpoint, so this state no longer applies
+     */
+    boolean delivered(EventContext eventContext) {
+        final long sequenceNumber = sequenceNumber(eventContext);
+        if (sequenceNumber <= lastDelivered) {
+            return false;
+        }
+        lastDelivered = sequenceNumber;
+        delivered.put(sequenceNumber, new Delivered(eventContext));
+        return true;
+    }
+
+    /**
+     * The exchange of the event is done, successfully or not.
+     *
+     * @return false if the event was not delivered by this owner of the 
partition (it was delivered before the consumer
+     *         was stopped or lost the partition), so it must not move the 
checkpoint
+     */
+    boolean completed(EventContext eventContext, boolean succeeded) {
+        final long sequenceNumber = sequenceNumber(eventContext);
+        final Delivered event = delivered.get(sequenceNumber);
+        // identity, not equals: an event delivered again at the same sequence 
number (after a rebalance) has another
+        // EventContext, and the completion of the earlier delivery must not 
move the checkpoint
+        if (event == null || event.eventContext != eventContext || 
event.completed) {
+            return false;
+        }
+        event.completed = true;
+        if (succeeded) {
+            event.succeeded = 1;
+            succeededAhead++;
+        }
+        // join the completed events next to it: a checkpoint can only use the 
last event of such a run
+        final Map.Entry<Long, Delivered> before = 
delivered.lowerEntry(sequenceNumber);
+        if (before != null && before.getValue().completed) {
+            event.succeeded += before.getValue().succeeded;
+            delivered.remove(before.getKey());
+        }
+        final Map.Entry<Long, Delivered> after = 
delivered.higherEntry(sequenceNumber);
+        if (after != null && after.getValue().completed) {
+            after.getValue().succeeded += event.succeeded;
+            delivered.remove(sequenceNumber);
+        }
+        Map.Entry<Long, Delivered> first;
+        while ((first = delivered.firstEntry()) != null && 
first.getValue().completed) {
+            delivered.pollFirstEntry();
+            completedUpTo = first.getValue().eventContext;
+            succeededAhead -= first.getValue().succeeded;
+        }
+        return true;
+    }
+
+    /**
+     * The number of events that completed successfully after an event still 
in flight: a checkpoint now does not cover
+     * them.
+     */
+    int succeededAhead() {
+        return succeededAhead;
+    }
+
+    /**
+     * Whether a checkpoint now would move the checkpoint of the partition 
forward.
+     */
+    boolean canCheckpoint() {
+        return !closed && completedUpTo != null && 
sequenceNumber(completedUpTo) > written;
+    }
+
+    /**
+     * Checkpoints the partition up to the last event below which every 
delivered event has completed, if that is after
+     * the last checkpoint written. When a write is in flight, the checkpoint 
is written when it answers (a later
+     * checkpoint replaces a waiting one), so the writes land in order.
+     *
+     * @param  onError called if the write of this checkpoint fails
+     * @return         false if there is nothing to checkpoint
+     */
+    boolean checkpoint(Runnable onError) {
+        if (!canCheckpoint()) {
+            return false;
+        }
+        written = sequenceNumber(completedUpTo);
+        if (writing) {
+            waiting = completedUpTo;
+            waitingOnError = onError;
+        } else {
+            write(completedUpTo, onError);
+        }
+        return true;
+    }
+
+    /**
+     * The partition was lost, or is delivered again: the checkpoints waiting 
to be written are dropped, and nothing
+     * more is written.
+     */
+    void close() {
+        closed = true;
+        waiting = null;
+        waitingOnError = null;
+        // nothing is checkpointed after the close, so do not keep the last 
event (and its data) reachable
+        completedUpTo = null;
+        delivered.clear();
+    }
+
+    private void write(EventContext eventContext, Runnable onError) {
+        final long sequenceNumber = sequenceNumber(eventContext);
+        final Mono<Void> update;
+        try {
+            update = eventContext.updateCheckpointAsync();
+        } catch (RuntimeException e) {
+            written = stored;
+            throw e;
+        }
+        writing = true;
+        update.subscribe(unused -> LOG.debug("Processed one event..."),
+                error -> {
+                    LOG.warn("Error when updating Checkpoint: {}", 
error.getMessage(), error);
+                    answered(sequenceNumber, false, onError);
+                },
+                () -> {
+                    LOG.debug("Checkpoint updated.");
+                    answered(sequenceNumber, true, null);
+                });
+    }
+
+    private void answered(long sequenceNumber, boolean ok, Runnable onError) {
+        lock.lock();
+        try {
+            writing = false;
+            if (ok) {
+                stored = sequenceNumber;
+            } else if (waiting == null) {
+                // a later checkpoint can write the same position again
+                written = stored;
+            }
+            if (!ok && onError != null) {
+                // under the lock, as the consumer resets the count of the 
partition under it: run outside, a
+                // checkpoint taken in between would reset the count, and this 
would then add the events to it again
+                onError.run();
+            }
+            if (waiting != null) {
+                EventContext next = waiting;
+                Runnable nextOnError = waitingOnError;
+                waiting = null;
+                waitingOnError = null;
+                write(next, nextOnError);
+            }
+        } finally {
+            lock.unlock();
+        }
+    }
+
+    private static long sequenceNumber(EventContext eventContext) {
+        return eventContext.getEventData().getSequenceNumber();
+    }
+
+    private static final class Delivered {
+        private final EventContext eventContext;
+        private boolean completed;
+        // the events of this entry that completed successfully
+        private int succeeded;
+
+        private Delivered(EventContext eventContext) {
+            this.eventContext = eventContext;
+        }
+    }
+}
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/client/EventHubsClientFactory.java
 
b/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/client/EventHubsClientFactory.java
index 5fd52a62650b..6f1b49a26356 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/client/EventHubsClientFactory.java
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/main/java/org/apache/camel/component/azure/eventhubs/client/EventHubsClientFactory.java
@@ -27,6 +27,7 @@ import 
com.azure.messaging.eventhubs.EventHubProducerAsyncClient;
 import com.azure.messaging.eventhubs.EventProcessorClient;
 import com.azure.messaging.eventhubs.EventProcessorClientBuilder;
 import com.azure.messaging.eventhubs.checkpointstore.blob.BlobCheckpointStore;
+import com.azure.messaging.eventhubs.models.CloseContext;
 import com.azure.messaging.eventhubs.models.ErrorContext;
 import com.azure.messaging.eventhubs.models.EventContext;
 import com.azure.storage.blob.BlobContainerAsyncClient;
@@ -107,6 +108,16 @@ public final class EventHubsClientFactory {
     public static EventProcessorClient createEventProcessorClient(
             final EventHubsConfiguration configuration, final 
Consumer<EventContext> processEvent,
             final Consumer<ErrorContext> processError) {
+        return createEventProcessorClient(configuration, processEvent, 
processError, null);
+    }
+
+    /**
+     * Creates the event processor client, with a handler that is called when 
a partition is closed (lost to another
+     * consumer, or the client is stopped), if processPartitionClose is not 
null.
+     */
+    public static EventProcessorClient createEventProcessorClient(
+            final EventHubsConfiguration configuration, final 
Consumer<EventContext> processEvent,
+            final Consumer<ErrorContext> processError, final 
Consumer<CloseContext> processPartitionClose) {
         EventProcessorClientBuilder eventProcessorClientBuilder = new 
EventProcessorClientBuilder()
                 
.initialPartitionEventPosition(configuration.getEventPosition())
                 .checkpointStore(createCheckpointStore(configuration))
@@ -115,6 +126,9 @@ public final class EventHubsClientFactory {
                 .transportType(configuration.getAmqpTransportType())
                 .processError(processError)
                 .processEvent(processEvent);
+        if (processPartitionClose != null) {
+            
eventProcessorClientBuilder.processPartitionClose(processPartitionClose);
+        }
 
         CredentialType type = configuration.getCredentialType();
         if (type == null) {
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointAfterBatchSizeTest.java
 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointAfterBatchSizeTest.java
index 19a22d70484b..2b983e82e6d7 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointAfterBatchSizeTest.java
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointAfterBatchSizeTest.java
@@ -22,6 +22,7 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicLong;
 
+import com.azure.messaging.eventhubs.EventData;
 import com.azure.messaging.eventhubs.models.EventContext;
 import com.azure.messaging.eventhubs.models.PartitionContext;
 import org.apache.camel.AsyncProcessor;
@@ -63,6 +64,7 @@ class EventHubsConsumerCheckpointAfterBatchSizeTest {
 
     private EventHubsConsumer consumer;
     private Method processCommit;
+    private long sequenceNumber;
 
     @BeforeEach
     void setUp() throws Exception {
@@ -207,6 +209,7 @@ class EventHubsConsumerCheckpointAfterBatchSizeTest {
         stored.tryEmitError(new IllegalStateException("store failed"));
 
         Exchange exchange = DefaultExchange.newFromEndpoint(endpoint);
+        consumer.processDelivered(fourth);
         processCommit.invoke(consumer, exchange, fourth);
 
         verify(fourth, times(1)).updateCheckpointAsync();
@@ -215,14 +218,18 @@ class EventHubsConsumerCheckpointAfterBatchSizeTest {
     }
 
     private void complete(EventContext eventContext) throws Exception {
+        consumer.processDelivered(eventContext);
         processCommit.invoke(consumer, 
DefaultExchange.newFromEndpoint(endpoint), eventContext);
     }
 
-    private static EventContext eventContext(String partitionId) {
+    private EventContext eventContext(String partitionId) {
         EventContext eventContext = mock(EventContext.class);
         PartitionContext partitionContext = mock(PartitionContext.class);
         when(partitionContext.getPartitionId()).thenReturn(partitionId);
         when(eventContext.getPartitionContext()).thenReturn(partitionContext);
+        EventData eventData = mock(EventData.class);
+        when(eventData.getSequenceNumber()).thenReturn(sequenceNumber++);
+        when(eventContext.getEventData()).thenReturn(eventData);
         when(eventContext.updateCheckpointAsync()).thenReturn(Mono.empty());
         return eventContext;
     }
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointOrderTest.java
 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointOrderTest.java
new file mode 100644
index 000000000000..c7344ce6163d
--- /dev/null
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointOrderTest.java
@@ -0,0 +1,370 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.azure.eventhubs;
+
+import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ScheduledFuture;
+import java.util.function.Consumer;
+
+import com.azure.messaging.eventhubs.CheckpointStore;
+import com.azure.messaging.eventhubs.EventData;
+import com.azure.messaging.eventhubs.EventProcessorClient;
+import com.azure.messaging.eventhubs.models.Checkpoint;
+import com.azure.messaging.eventhubs.models.CloseContext;
+import com.azure.messaging.eventhubs.models.CloseReason;
+import com.azure.messaging.eventhubs.models.EventContext;
+import com.azure.messaging.eventhubs.models.PartitionContext;
+import com.azure.messaging.eventhubs.models.PartitionOwnership;
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import 
org.apache.camel.component.azure.eventhubs.client.EventHubsClientFactory;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.AsyncProcessorSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The checkpoint of a partition when the exchanges complete in another order 
than their events were delivered (any
+ * asynchronous step in the route), and when checkpoint writes answer late. A 
real route and consumer, a mocked event
+ * processor client, and a checkpoint store that behaves like the blob 
checkpoint store: the write that lands last wins,
+ * whatever its sequence number. The checkpoint timer is run by the test (the 
batch timeout is long), so nothing depends
+ * on timing.
+ */
+class EventHubsConsumerCheckpointOrderTest {
+
+    private static final String PARTITION = "0";
+
+    /** The stored checkpoint (sequence number) and every write in the order 
it landed. */
+    private volatile long stored = -1;
+    private final List<Long> landed = new CopyOnWriteArrayList<>();
+    /** The writes of these sequence numbers are held until the test releases 
them. */
+    private final Set<Long> hold = ConcurrentHashMap.newKeySet();
+    private final Map<Long, Runnable> held = new ConcurrentHashMap<>();
+
+    private final Map<Long, AsyncCallback> callbacks = new 
ConcurrentHashMap<>();
+    private final Map<Long, Exchange> exchanges = new ConcurrentHashMap<>();
+    private DefaultCamelContext context;
+    private MockedStatic<EventHubsClientFactory> factory;
+    private volatile Consumer<EventContext> processEvent;
+    private volatile Consumer<CloseContext> processPartitionClose;
+
+    private void start(int batchSize, boolean async, long 
failingSequenceNumber) throws Exception {
+        EventProcessorClient processorClient = 
Mockito.mock(EventProcessorClient.class);
+        factory = Mockito.mockStatic(EventHubsClientFactory.class, invocation 
-> {
+            if 
("createEventProcessorClient".equals(invocation.getMethod().getName())) {
+                processEvent = invocation.getArgument(1);
+                if (invocation.getArguments().length > 3) {
+                    processPartitionClose = invocation.getArgument(3);
+                }
+                return processorClient;
+            }
+            return null;
+        });
+        context = new DefaultCamelContext();
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                var route = 
from("azure-eventhubs:ns/hub?sharedAccessName=x&sharedAccessKey=y&checkpointBatchSize="
+                                 + batchSize + 
"&checkpointBatchTimeout=600000")
+                        .routeId("eh");
+                if (async) {
+                    // a non-blocking downstream call: the test completes each 
exchange when it wants
+                    route.process(new AsyncProcessorSupport() {
+                        @Override
+                        public boolean process(Exchange exchange, 
AsyncCallback callback) {
+                            long seq = 
exchange.getMessage().getHeader(EventHubsConstants.SEQUENCE_NUMBER, Long.class);
+                            exchanges.put(seq, exchange);
+                            callbacks.put(seq, callback);
+                            return false;
+                        }
+                    });
+                } else {
+                    route.process(e -> {
+                        if 
(e.getMessage().getHeader(EventHubsConstants.SEQUENCE_NUMBER, Long.class)
+                            == failingSequenceNumber) {
+                            throw new IllegalStateException("downstream failed 
for e" + failingSequenceNumber);
+                        }
+                    });
+                }
+            }
+        });
+        context.start();
+    }
+
+    @AfterEach
+    void tearDown() {
+        // a test that failed may leave exchanges in flight: complete them, so 
the stop does not wait for them
+        callbacks.values().forEach(callback -> callback.done(false));
+        if (context != null) {
+            context.stop();
+        }
+        if (factory != null) {
+            factory.close();
+        }
+    }
+
+    @Test
+    void checkpointDoesNotPassAnEventStillInFlight() throws Exception {
+        start(2, true, -1);
+        deliver(1);
+        deliver(2);
+        deliver(3);
+        complete(1);
+        complete(3);
+
+        // e2 is in flight: a checkpoint at e3 would make the next owner of 
the partition resume at e4, and e2 would be
+        // lost if this consumer stopped now
+        assertTrue(callbacks.containsKey(2L), "e2 is still in flight");
+        assertEquals(1, stored, "the checkpoint stops before e2");
+
+        complete(2);
+        assertEquals(3, stored);
+        assertEquals(List.of(1L, 3L), landed);
+    }
+
+    @Test
+    void storedCheckpointDoesNotGoBackWithReorderedCompletions() throws 
Exception {
+        start(2, true, -1);
+        deliver(1);
+        deliver(2);
+        deliver(3);
+        complete(1);
+        complete(3);
+        complete(2);
+        runWindowTimer();
+
+        assertEquals(List.of(1L, 3L), landed, "the checkpoint only moves 
forward");
+        assertEquals(3, stored);
+    }
+
+    @Test
+    void storedCheckpointDoesNotGoBackWhenATimerWriteLandsLate() throws 
Exception {
+        start(2, false, -1);
+        hold.add(1L);
+        deliver(1);
+        // the timer checkpoints e1, and the store answers it late
+        runWindowTimer();
+        assertTrue(held.containsKey(1L));
+
+        // meanwhile e2 and e3 reach the batch size
+        deliver(2);
+        deliver(3);
+        held.remove(1L).run();
+
+        assertEquals(List.of(1L, 3L), landed, "the checkpoint at e3 is written 
after the late write of e1 answered");
+        assertEquals(3, stored);
+    }
+
+    @Test
+    void failedEventIsPassedByTheNextCheckpoint() throws Exception {
+        // unchanged: a failed exchange is not delivered again, the next 
checkpoint passes it
+        start(2, false, 1);
+        deliver(1);
+        deliver(2);
+        deliver(3);
+
+        assertEquals(3, stored);
+        assertEquals(List.of(3L), landed);
+    }
+
+    @Test
+    void failedEventDoesNotHoldBackTheEventsCompletedAfterIt() throws 
Exception {
+        start(2, true, -1);
+        deliver(1);
+        deliver(2);
+        deliver(3);
+        complete(1);
+        complete(3);
+        fail(2);
+        runWindowTimer();
+
+        assertEquals(3, stored);
+    }
+
+    @Test
+    void exchangesInFlightWhenThePartitionIsLostDoNotCheckpoint() throws 
Exception {
+        start(2, true, -1);
+        deliver(1);
+        deliver(2);
+        complete(1);
+        processPartitionClose.accept(new CloseContext(partitionContext(), 
CloseReason.LOST_PARTITION_OWNERSHIP));
+        // the new owner resumes after the stored checkpoint, and delivers e1 
and e2 again
+        complete(2);
+        runWindowTimer();
+
+        assertEquals(List.of(), landed);
+    }
+
+    @Test
+    void exchangesInFlightWhenTheProcessorStopsStillCheckpoint() throws 
Exception {
+        start(1, true, -1);
+        deliver(1);
+        processPartitionClose.accept(new CloseContext(partitionContext(), 
CloseReason.EVENT_PROCESSOR_SHUTDOWN));
+        complete(1);
+
+        assertEquals(1, stored);
+    }
+
+    @Test
+    void 
exchangesOfEarlierDeliveriesDoNotCheckpointWhenThePartitionIsDeliveredAgain() 
throws Exception {
+        start(1, true, -1);
+        deliver(1);
+        deliver(2);
+        AsyncCallback earlierE1 = callbacks.remove(1L);
+        // the partition is claimed again without being reported as lost: the 
SDK delivers it again from the stored
+        // checkpoint (none yet), while the exchanges of the earlier 
deliveries are still in flight
+        deliver(1);
+        complete(2);
+        assertEquals(List.of(), landed, "the earlier e2 must not pass the e1 
delivered again");
+
+        complete(1);
+        earlierE1.done(false);
+        assertEquals(List.of(1L), landed);
+    }
+
+    @Test
+    void eventsCompletedAfterAnEventInFlightAreKeptAsOneEntry() throws 
Exception {
+        start(2, true, -1);
+        for (long seq = 1; seq <= 50; seq++) {
+            deliver(seq);
+        }
+        for (long seq = 2; seq <= 50; seq += 2) {
+            complete(seq);
+        }
+        fail(25);
+        for (long seq = 3; seq <= 49; seq += 2) {
+            if (seq != 25) {
+                complete(seq);
+            }
+        }
+
+        // e1 is in flight (an exchange that never completes would hold it so 
for ever): the 49 events completed after
+        // it are one entry, which keeps the context of e50 only, not one 
entry (and event) each
+        assertEquals(List.of(), landed);
+        assertEquals(2, deliveredEntries(), "e1 in flight, and e2 to e50 
completed");
+
+        complete(1);
+        assertEquals(List.of(50L), landed);
+        assertEquals(0, deliveredEntries());
+    }
+
+    /** The SDK partition pump delivers event e{seq} (one at a time, as the 
event processor client does). */
+    private void deliver(long seq) {
+        EventData data = Mockito.spy(new EventData("e" + seq));
+        Mockito.doReturn(seq).when(data).getSequenceNumber();
+        Mockito.doReturn(seq * 100).when(data).getOffset();
+        processEvent.accept(new EventContext(partitionContext(), data, new 
Store(seq), null));
+    }
+
+    private static PartitionContext partitionContext() {
+        return new PartitionContext("ns.servicebus.windows.net", "hub", 
"$Default", PARTITION);
+    }
+
+    private void complete(long seq) {
+        callbacks.remove(seq).done(false);
+    }
+
+    private void fail(long seq) {
+        exchanges.get(seq).setException(new IllegalStateException("downstream 
failed for e" + seq));
+        callbacks.remove(seq).done(false);
+    }
+
+    /**
+     * Runs the timer of the current checkpoint window of the partition now, 
if there is one, instead of the scheduler
+     * (which would run it after the batch timeout).
+     */
+    private void runWindowTimer() throws Exception {
+        Object consumer = context.getRoute("eh").getConsumer();
+        ScheduledFuture<?> scheduled = this.<ScheduledFuture<?>> 
consumerMap(consumer, "scheduledTasksByPartition")
+                .get(PARTITION);
+        if (scheduled != null) {
+            scheduled.cancel(false);
+        }
+        EventHubsCheckpointUpdaterTask task
+                = this.<EventHubsCheckpointUpdaterTask> consumerMap(consumer, 
"checkpointTasksByPartition").get(PARTITION);
+        if (task != null) {
+            task.run();
+        }
+    }
+
+    private int deliveredEntries() throws Exception {
+        Object checkpoints = consumerMap(context.getRoute("eh").getConsumer(), 
"checkpointsByPartition").get(PARTITION);
+        Field field = 
EventHubsPartitionCheckpoints.class.getDeclaredField("delivered");
+        field.setAccessible(true);
+        return ((Map<?, ?>) field.get(checkpoints)).size();
+    }
+
+    @SuppressWarnings("unchecked")
+    private <T> Map<String, T> consumerMap(Object consumer, String name) 
throws Exception {
+        Field field = EventHubsConsumer.class.getDeclaredField(name);
+        field.setAccessible(true);
+        return (Map<String, T>) field.get(consumer);
+    }
+
+    /** The checkpoint store as seen by the event e{seq}: a write stores that 
event's sequence number. */
+    private final class Store implements CheckpointStore {
+        private final long seq;
+
+        Store(long seq) {
+            this.seq = seq;
+        }
+
+        @Override
+        public Mono<Void> updateCheckpoint(Checkpoint checkpoint) {
+            return Mono.create(sink -> {
+                Runnable landing = () -> {
+                    stored = seq;
+                    landed.add(seq);
+                    sink.success();
+                };
+                if (hold.remove(seq)) {
+                    held.put(seq, landing);
+                } else {
+                    landing.run();
+                }
+            });
+        }
+
+        @Override
+        public Flux<PartitionOwnership> listOwnership(String ns, String hub, 
String group) {
+            return Flux.empty();
+        }
+
+        @Override
+        public Flux<PartitionOwnership> 
claimOwnership(List<PartitionOwnership> requested) {
+            return Flux.empty();
+        }
+
+        @Override
+        public Flux<Checkpoint> listCheckpoints(String ns, String hub, String 
group) {
+            return Flux.empty();
+        }
+    }
+}
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointWindowTest.java
 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointWindowTest.java
index 3fc1b5525fb3..4122fdf0102a 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointWindowTest.java
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerCheckpointWindowTest.java
@@ -21,6 +21,7 @@ import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 
+import com.azure.messaging.eventhubs.EventData;
 import com.azure.messaging.eventhubs.models.EventContext;
 import com.azure.messaging.eventhubs.models.PartitionContext;
 import org.apache.camel.AsyncProcessor;
@@ -61,6 +62,7 @@ class EventHubsConsumerCheckpointWindowTest {
     private final ScheduledFuture scheduledFuture = 
mock(ScheduledFuture.class);
 
     private EventHubsConsumer consumer;
+    private long sequenceNumber;
 
     @BeforeEach
     void setUp() throws Exception {
@@ -139,6 +141,7 @@ class EventHubsConsumerCheckpointWindowTest {
     }
 
     private void complete(EventContext eventContext) throws Exception {
+        consumer.processDelivered(eventContext);
         consumer.processCommit(DefaultExchange.newFromEndpoint(endpoint), 
eventContext);
     }
 
@@ -156,11 +159,14 @@ class EventHubsConsumerCheckpointWindowTest {
         }
     }
 
-    private static EventContext eventContext() {
+    private EventContext eventContext() {
         EventContext eventContext = mock(EventContext.class);
         PartitionContext partitionContext = mock(PartitionContext.class);
         when(partitionContext.getPartitionId()).thenReturn("0");
         when(eventContext.getPartitionContext()).thenReturn(partitionContext);
+        EventData eventData = mock(EventData.class);
+        when(eventData.getSequenceNumber()).thenReturn(sequenceNumber++);
+        when(eventContext.getEventData()).thenReturn(eventData);
         when(eventContext.updateCheckpointAsync()).thenReturn(Mono.empty());
         return eventContext;
     }
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerPerPartitionCheckpointTest.java
 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerPerPartitionCheckpointTest.java
index 570833d609bc..44e1de7dc3fd 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerPerPartitionCheckpointTest.java
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsConsumerPerPartitionCheckpointTest.java
@@ -23,6 +23,7 @@ import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
+import com.azure.messaging.eventhubs.EventData;
 import com.azure.messaging.eventhubs.EventProcessorClient;
 import com.azure.messaging.eventhubs.models.EventContext;
 import com.azure.messaging.eventhubs.models.PartitionContext;
@@ -62,6 +63,7 @@ class EventHubsConsumerPerPartitionCheckpointTest {
 
     private EventHubsConsumer consumer;
     private Method processCommit;
+    private long sequenceNumber;
 
     @BeforeEach
     void setUp() throws Exception {
@@ -98,16 +100,17 @@ class EventHubsConsumerPerPartitionCheckpointTest {
     @Test
     void batchSizeCheckpointOnOnePartitionDoesNotResetOtherPartition() throws 
Exception {
         configuration.setCheckpointBatchSize(2);
-        EventContext partitionZeroContext = eventContext("0");
-        
when(partitionZeroContext.updateCheckpointAsync()).thenReturn(Mono.empty());
+        EventContext partitionZeroFirst = eventContext("0");
+        EventContext partitionZeroSecond = eventContext("0");
+        
when(partitionZeroSecond.updateCheckpointAsync()).thenReturn(Mono.empty());
 
         invokeProcessCommit(exchange(), eventContext("1"));
-        invokeProcessCommit(exchange(), partitionZeroContext);
-        invokeProcessCommit(exchange(), partitionZeroContext);
+        invokeProcessCommit(exchange(), partitionZeroFirst);
+        invokeProcessCommit(exchange(), partitionZeroSecond);
 
         assertThat(processedEventsForPartition("0")).isZero();
         assertThat(processedEventsForPartition("1")).isEqualTo(1);
-        verify(partitionZeroContext, times(1)).updateCheckpointAsync();
+        verify(partitionZeroSecond, times(1)).updateCheckpointAsync();
     }
 
     @Test
@@ -146,10 +149,12 @@ class EventHubsConsumerPerPartitionCheckpointTest {
         assertThat(getProcessedEventsByPartition()).isEmpty();
         assertThat(getCheckpointTasksByPartition()).isEmpty();
         assertThat(getScheduledTasksByPartition()).isEmpty();
+        assertThat((Map<?, ?>) getField(consumer, 
"checkpointsByPartition")).isEmpty();
         verify(processorClient).stop();
     }
 
     private void invokeProcessCommit(Exchange exchange, EventContext 
eventContext) throws Exception {
+        consumer.processDelivered(eventContext);
         processCommit.invoke(consumer, exchange, eventContext);
     }
 
@@ -162,6 +167,9 @@ class EventHubsConsumerPerPartitionCheckpointTest {
         PartitionContext partitionContext = mock(PartitionContext.class);
         when(partitionContext.getPartitionId()).thenReturn(partitionId);
         when(eventContext.getPartitionContext()).thenReturn(partitionContext);
+        EventData eventData = mock(EventData.class);
+        when(eventData.getSequenceNumber()).thenReturn(sequenceNumber++);
+        when(eventContext.getEventData()).thenReturn(eventData);
         return eventContext;
     }
 
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsPartitionCheckpointsTest.java
 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsPartitionCheckpointsTest.java
new file mode 100644
index 000000000000..b320581d65e4
--- /dev/null
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/EventHubsPartitionCheckpointsTest.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.azure.eventhubs;
+
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantLock;
+
+import com.azure.messaging.eventhubs.EventData;
+import com.azure.messaging.eventhubs.models.EventContext;
+import org.junit.jupiter.api.Test;
+import reactor.core.publisher.Sinks;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class EventHubsPartitionCheckpointsTest {
+
+    @Test
+    void failedCheckpointRunsItsErrorCallbackUnderTheLock() throws Exception {
+        ReentrantLock lock = new ReentrantLock();
+        EventHubsPartitionCheckpoints checkpoints = new 
EventHubsPartitionCheckpoints(lock);
+        Sinks.Empty<Void> answer = Sinks.empty();
+        EventContext event = event(1, answer);
+        CompletableFuture<Boolean> lockHeldInOnError = new 
CompletableFuture<>();
+
+        lock.lock();
+        try {
+            assertTrue(checkpoints.delivered(event));
+            assertTrue(checkpoints.completed(event, true));
+            assertTrue(checkpoints.checkpoint(() -> 
lockHeldInOnError.complete(lock.isHeldByCurrentThread())));
+        } finally {
+            lock.unlock();
+        }
+
+        // the checkpoint store answers on its own thread, as the Event Hubs 
client does
+        Thread answering = new Thread(() -> answer.tryEmitError(new 
IllegalStateException("store not reachable")));
+        answering.start();
+        answering.join(TimeUnit.SECONDS.toMillis(5));
+
+        assertTrue(lockHeldInOnError.get(5, TimeUnit.SECONDS),
+                "the error callback restores the count of the partition, which 
the consumer changes under the lock");
+        assertFalse(lock.isLocked(), "the lock is released after the answer");
+    }
+
+    private static EventContext event(long sequenceNumber, Sinks.Empty<Void> 
answer) {
+        EventData data = mock(EventData.class);
+        when(data.getSequenceNumber()).thenReturn(sequenceNumber);
+        EventContext context = mock(EventContext.class);
+        when(context.getEventData()).thenReturn(data);
+        when(context.updateCheckpointAsync()).thenReturn(answer.asMono());
+        return context;
+    }
+}
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/dst/EventHubsCheckpointDstTest.java
 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/dst/EventHubsCheckpointDstTest.java
index 3073d242c7fa..2f4743712413 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/dst/EventHubsCheckpointDstTest.java
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/dst/EventHubsCheckpointDstTest.java
@@ -31,7 +31,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
  * Deterministic simulation test of the checkpointing of camel-azure-eventhubs 
under seeded event bursts, downstream
  * latency and failures, and slow or failing checkpoint store answers: every 
completed event is checkpointed when the
  * partition goes quiet. Regression test for CAMEL-25683 (apache/camel#27922): 
before that fix 2064 of 5000 seeds fail.
- * A failing seed is replayed with {@code -Ddst.seed=<seed>}; {@code 
-Ddst.seeds=5000} runs more seeds.
+ * Each successful answer of the checkpoint store is checked too: the stored 
checkpoint of a partition never passes an
+ * event still in flight (the asynchronous downstream step completes the 
events in any order) and never goes back. A
+ * failing seed is replayed with {@code -Ddst.seed=<seed>}; {@code 
-Ddst.seeds=5000} runs more seeds.
  * <p>
  * Seed 3042 (of 5000) failed before CAMEL-25781 and is pinned below: an event 
that completed in the millisecond in
  * which the timer of its window ran joined that window after the timer had 
taken its count, so it was not checkpointed
diff --git 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/dst/EventHubsWorld.java
 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/dst/EventHubsWorld.java
index 24f4e9e5b6a1..1be41abeb85d 100644
--- 
a/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/dst/EventHubsWorld.java
+++ 
b/components/camel-azure/camel-azure-eventhubs/src/test/java/org/apache/camel/component/azure/eventhubs/dst/EventHubsWorld.java
@@ -37,6 +37,7 @@ import 
com.azure.messaging.eventhubs.models.PartitionOwnership;
 import org.apache.camel.AsyncCallback;
 import org.apache.camel.Exchange;
 import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.azure.eventhubs.EventHubsConstants;
 import org.apache.camel.component.azure.eventhubs.EventHubsConsumer;
 import 
org.apache.camel.component.azure.eventhubs.client.EventHubsClientFactory;
 import org.apache.camel.impl.DefaultCamelContext;
@@ -53,8 +54,6 @@ import org.mockito.Mockito;
 import reactor.core.publisher.Flux;
 import reactor.core.publisher.Mono;
 
-import static org.mockito.ArgumentMatchers.any;
-
 /**
  * The world around a camel-azure-eventhubs consumer: a fake Event Hubs SDK 
that delivers events per partition (bursts
  * and quiet periods chosen by the seed), an asynchronous downstream step with 
latency and failures, and a fake
@@ -70,7 +69,10 @@ import static org.mockito.ArgumentMatchers.any;
           faults = {
                   "the downstream step answers slowly", "the downstream step 
fails",
                   "the checkpoint store answers slowly", "the checkpoint store 
fails" },
-          invariants = "every completed message is acknowledged when the 
partition goes quiet",
+          invariants = {
+                  "every completed message is acknowledged when the partition 
goes quiet",
+                  "a stored checkpoint never passes an event still in flight",
+                  "the stored checkpoint of a partition never goes back" },
           issues = { "CAMEL-25683", "CAMEL-25738", "CAMEL-25781" })
 final class EventHubsWorld {
 
@@ -92,6 +94,10 @@ final class EventHubsWorld {
     private int inflight;
     private int arrivalsLeft;
     private final Map<String, Integer> sizeCheckpoints = new TreeMap<>();
+    // per partition: the sequence numbers of the events in flight, and the 
stored checkpoint (the store answered OK)
+    private final Map<String, TreeSet<Long>> inflightByPartition = new 
TreeMap<>();
+    private final Map<String, Long> storedByPartition = new TreeMap<>();
+    private final List<String> storeViolations = new ArrayList<>();
     private final DstExecutor store;
 
     private final boolean countProbes;
@@ -133,9 +139,12 @@ final class EventHubsWorld {
                                 // a non-blocking downstream call: answers 
after a latency chosen by the seed
                                 String id = 
exchange.getMessage().getBody(String.class);
                                 String partition = partitionOf(id);
+                                long sequenceNumber
+                                        = 
exchange.getMessage().getHeader(EventHubsConstants.SEQUENCE_NUMBER, Long.class);
                                 long latency = dst.chance(0.1)
                                         ? dst.between(timeout / 2, 2 * 
timeout) : dst.between(0, timeout / 2);
                                 downstream.schedule("downstream answer " + id, 
latency, () -> {
+                                    
inflightByPartition.get(partition).remove(sequenceNumber);
                                     if (dst.chance(0.05)) {
                                         exchange.setException(
                                                 Dst.injected(new 
IllegalStateException("downstream failed for " + id)));
@@ -152,12 +161,15 @@ final class EventHubsWorld {
                         });
             }
         });
-        try (MockedStatic<EventHubsClientFactory> factory = 
Mockito.mockStatic(EventHubsClientFactory.class)) {
-            factory.when(() -> 
EventHubsClientFactory.createEventProcessorClient(any(), any(), any()))
-                    .thenAnswer(inv -> {
-                        processEvent = inv.getArgument(1);
-                        return Mockito.mock(EventProcessorClient.class);
-                    });
+        // the consumer creates its event processor client with the event 
handler as the second argument (whichever
+        // overload it calls)
+        try (MockedStatic<EventHubsClientFactory> factory = 
Mockito.mockStatic(EventHubsClientFactory.class, inv -> {
+            if 
("createEventProcessorClient".equals(inv.getMethod().getName())) {
+                processEvent = inv.getArgument(1);
+                return Mockito.mock(EventProcessorClient.class);
+            }
+            return null;
+        })) {
             context.start();
             consumer = (EventHubsConsumer) 
context.getRoute(ROUTE).getConsumer();
             try {
@@ -167,7 +179,9 @@ final class EventHubsWorld {
                 // completed event must have been checkpointed
                 dst.trace("quiet");
                 dst.runFor(timeout + maxStoreLatency + 100);
-                
dst.check(withProbes(Invariants.lastCompletedAcknowledgedWhenQuiet(ledger, 
"completed", "checkpoint")));
+                
dst.check(withProbes(Invariants.lastCompletedAcknowledgedWhenQuiet(ledger, 
"completed", "checkpoint")),
+                        Invariants.of("a stored checkpoint never passes an 
event still in flight and never goes back",
+                                () -> storeViolations.isEmpty() ? null : 
String.join("; ", storeViolations)));
             } finally {
                 dst.dropPending();
                 context.stop();
@@ -196,9 +210,10 @@ final class EventHubsWorld {
             for (int b = 0; b < bursts; b++) {
                 int size = (int) dst.between(1, 2L * batchSize + 1);
                 for (int i = 0; i < size; i++) {
-                    String id = "p" + partition + "-e" + n++;
+                    long sequenceNumber = n++;
+                    String id = "p" + partition + "-e" + sequenceNumber;
                     arrivalsLeft++;
-                    sdk.schedule("deliver " + id, t, () -> deliver(partition, 
id));
+                    sdk.schedule("deliver " + id, t, () -> deliver(partition, 
id, sequenceNumber));
                     t += dst.between(0, 20);
                 }
                 t += dst.between(0, 3 * timeout);
@@ -206,12 +221,20 @@ final class EventHubsWorld {
         }
     }
 
-    private void deliver(String partition, String id) {
+    private void deliver(String partition, String id, long sequenceNumber) {
         arrivalsLeft--;
         inflight++;
         PartitionContext pc = new 
PartitionContext("dstns.servicebus.windows.net", "dsthub", "$Default", 
partition);
-        EventContext ctx = new EventContext(pc, new EventData(id), new 
FakeCheckpointStore(partition, id), null);
+        // the SDK delivers the events of a partition in the order of their 
sequence numbers
+        EventData data = new EventData(id) {
+            @Override
+            public Long getSequenceNumber() {
+                return sequenceNumber;
+            }
+        };
+        EventContext ctx = new EventContext(pc, data, new 
FakeCheckpointStore(partition, id, sequenceNumber), null);
         ledger.record("delivered", partition, id);
+        inflightByPartition.computeIfAbsent(partition, p -> new 
TreeSet<>()).add(sequenceNumber);
         processEvent.accept(ctx);
     }
 
@@ -265,14 +288,34 @@ final class EventHubsWorld {
         }
     }
 
-    /** A checkpoint store fake per event, so the trace says which event's 
offset is checkpointed. */
+    /**
+     * A checkpoint store fake per event, so the trace says which event's 
offset is checkpointed. Like the blob
+     * checkpoint store, a write stores the sequence number of its event 
whatever is stored already: the write that
+     * answers last wins.
+     */
     private final class FakeCheckpointStore implements CheckpointStore {
         private final String partition;
         private final String id;
+        private final long sequenceNumber;
 
-        FakeCheckpointStore(String partition, String id) {
+        FakeCheckpointStore(String partition, String id, long sequenceNumber) {
             this.partition = partition;
             this.id = id;
+            this.sequenceNumber = sequenceNumber;
+        }
+
+        /** The write of this event's checkpoint answered OK: it is the stored 
checkpoint of the partition now. */
+        private void stored() {
+            TreeSet<Long> inflight = inflightByPartition.get(partition);
+            if (inflight != null && !inflight.isEmpty() && inflight.first() <= 
sequenceNumber) {
+                storeViolations.add("partition " + partition + ": checkpoint " 
+ id + " stored while e"
+                                    + inflight.first() + " is in flight");
+            }
+            Long before = storedByPartition.put(partition, sequenceNumber);
+            if (before != null && before > sequenceNumber) {
+                storeViolations.add("partition " + partition + ": stored 
checkpoint went back from e" + before + " to "
+                                    + id);
+            }
         }
 
         @Override
@@ -294,6 +337,7 @@ final class EventHubsWorld {
                             if (fail) {
                                 sink.error(Dst.injected(new 
IllegalStateException("checkpoint store unavailable")));
                             } else {
+                                stored();
                                 sink.success();
                             }
                             int after = count();
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 0d4329074f07..6320adc7e621 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -7816,6 +7816,35 @@ scheduled time of its window, but before the (late) 
timer has run, joins that wi
 checkpointed by that timer. Before, such an event always started a new window, 
so `timeout` was practically never
 set. Routes that read this header can now see `timeout` as well as `size`.
 
+=== camel-azure-eventhubs - a checkpoint no longer passes an event that is 
still being processed
+
+The consumer now checkpoints a partition up to the last event below which 
every delivered event of the partition has
+been processed (successfully or not), and a checkpoint never moves the stored 
position back. Before, the checkpoint
+was the offset of the event whose exchange completed last. With an 
asynchronous step in the route, the exchanges of a
+partition complete in any order, so a checkpoint could pass an event that was 
still being processed, and that event
+was lost if the consumer stopped or the partition moved to another consumer 
before it completed. A late checkpoint
+write could also move the stored position back, so already processed events 
were delivered again.
+
+What you may notice:
+
+* With an asynchronous route, the stored checkpoint can lag behind while an 
earlier event of the partition is still
+  being processed. After a restart at that point, that event is delivered 
again together with the events completed
+  after it (before, that event was skipped).
+  Routes that process each event synchronously are not affected.
+* An exchange whose completion never runs holds the checkpoint of its 
partition until the partition is lost or the
+  consumer is restarted, and then its event and the events after it are 
delivered again. Before, the next checkpoint
+  passed such an event. This happens, for example, when a `seda` endpoint with 
`discardWhenFull` drops the exchange
+  because its queue is full.
+* The `CamelAzureEventHubsCheckpointUpdatedBy` header is `size` only on the 
exchange whose completion actually wrote
+  a checkpoint: when the batch size is reached while an earlier event is still 
being processed, the checkpoint is
+  written by the first completion after that, or by the batch timeout.
+* A failed exchange is still not delivered again: it does not hold the 
checkpoint back, as before.
+* When a partition is lost to another consumer, the exchanges still in flight 
for it no longer write checkpoints:
+  the new owner delivers their events again.
+* `EventHubsClientFactory` has a new `createEventProcessorClient` method with 
a handler for closed partitions, which
+  the consumer now uses. Tests that mock the three-argument method to capture 
the event handler must mock the
+  four-argument one.
+
 === camel-azure-functions - invokeFunction fails on an HTTP error status, and 
sends the body as bytes
 
 The `invokeFunction` operation now fails the exchange with an 
`org.apache.camel.http.base.HttpOperationFailedException`

Reply via email to