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 844850dc4cf8 CAMEL-27436: camel-sql -
JdbcOrphanLockAwareIdempotentRepository: the old holder of a taken-over key no
longer removes or keeps alive the lease of the new holder (#30834)
844850dc4cf8 is described below
commit 844850dc4cf8429faf2f661c3e5fcb7703305cec
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 13:33:04 2026 +0530
CAMEL-27436: camel-sql - JdbcOrphanLockAwareIdempotentRepository: the old
holder of a taken-over key no longer removes or keeps alive the lease of the
new holder (#30834)
When an instance A cannot refresh a lease for longer than lockMaxAgeMillis,
another instance B takes the key over (the documented limitation: processed
twice). A still holds the key, and its statements matched the row by its key
only: its remove deleted B's live lease, so a third instance acquired the
key
while B still processed it; its keep-alive refreshed B's lease, so it did
not
expire when B crashed; and after A confirmed, B's remove deleted the
confirmed key.
- per held key, the repository remembers the createdAt it wrote last
(insert, takeover, keep-alive); the keys stay the keep-alive set
- the remove and the keep-alive of a held key add AND createdAt < ?, with
that value plus half of lockMaxAgeMillis + lockKeepAliveIntervalMillis:
a takeover writes more than lockMaxAgeMillis later, a keep-alive of the
instance itself about one interval later; a confirmed key (null) never
matches
- the margin is added to the instant and to the local time of the JVM, and
the later bound is used: a createdAt column without time zone holds the
local time, which goes back an hour at the end of daylight saving time,
and the lease of the instance written just before must still match
- a keep-alive that matches no row marks the lease lost (one WARN): the key
is no longer kept alive or removed, and stays a duplicate on the instance
until its exchange ends; such a remove returns false and logs a WARN
- a key the instance does not keep alive is removed by its key, as before
- the keep-alive sends one UPDATE per key (a batch may not report the count
of each key)
- a confirm still confirms by key: the message was processed
- OutageTest: the held statement is matched by its start
- docs: Orphan Lock section (and catalog copy), including the case of a
keep-alive that committed although it failed; 4.24 upgrade guide
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/catalog/docs/sql-component.adoc | 2 +
.../camel-sql/src/main/docs/sql-component.adoc | 2 +
.../JdbcOrphanLockAwareIdempotentRepository.java | 153 ++++++++++---
...hanLockAwareIdempotentRepositoryOutageTest.java | 4 +-
...nLockAwareIdempotentRepositoryTakeoverTest.java | 238 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 16 ++
6 files changed, 390 insertions(+), 25 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sql-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sql-component.adoc
index e248144f71fe..6fd6abfb2d48 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sql-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sql-component.adoc
@@ -858,6 +858,8 @@ The `createdAt` column must store null. The repository
checks this once when it
A lock is kept alive only while its instance reaches the database. When the
keep-alive fails (the database is down or cannot be reached, a failover, a
connection pool with no free connection), it logs an ERROR on every round; when
the instance holds keys and the keep-alive has not refreshed their locks for
longer than `lockMaxAgeMillis`, it logs a WARN, as they may now be taken over,
and an INFO when it refreshes them again. The instance itself keeps treating
the keys it holds as duplica [...]
+After such a takeover, the first instance does not touch the lock of the other
instance: the remove of the key (when the processing fails, or with
`readLockRemoveOnCommit=true`) and the keep-alive only match the `createdAt`
that this instance wrote last, so the key is not removed while the other
instance still processes its message, and a third instance does not take it
while that one keeps it alive. The first instance logs a WARN then, and still
treats the key as a duplicate until it is [...]
+
This repository has these additional configuration parameters
[cols="1,1"]
diff --git a/components/camel-sql/src/main/docs/sql-component.adoc
b/components/camel-sql/src/main/docs/sql-component.adoc
index e248144f71fe..6fd6abfb2d48 100644
--- a/components/camel-sql/src/main/docs/sql-component.adoc
+++ b/components/camel-sql/src/main/docs/sql-component.adoc
@@ -858,6 +858,8 @@ The `createdAt` column must store null. The repository
checks this once when it
A lock is kept alive only while its instance reaches the database. When the
keep-alive fails (the database is down or cannot be reached, a failover, a
connection pool with no free connection), it logs an ERROR on every round; when
the instance holds keys and the keep-alive has not refreshed their locks for
longer than `lockMaxAgeMillis`, it logs a WARN, as they may now be taken over,
and an INFO when it refreshes them again. The instance itself keeps treating
the keys it holds as duplica [...]
+After such a takeover, the first instance does not touch the lock of the other
instance: the remove of the key (when the processing fails, or with
`readLockRemoveOnCommit=true`) and the keep-alive only match the `createdAt`
that this instance wrote last, so the key is not removed while the other
instance still processes its message, and a third instance does not take it
while that one keeps it alive. The first instance logs a WARN then, and still
treats the key as a duplicate until it is [...]
+
This repository has these additional configuration parameters
[cols="1,1"]
diff --git
a/components/camel-sql/src/main/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepository.java
b/components/camel-sql/src/main/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepository.java
index 608fba264aef..d3b11cf35969 100644
---
a/components/camel-sql/src/main/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepository.java
+++
b/components/camel-sql/src/main/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepository.java
@@ -17,14 +17,19 @@
package org.apache.camel.processor.idempotent.jdbc;
import java.sql.Timestamp;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
import javax.sql.DataSource;
@@ -69,6 +74,11 @@ import
org.springframework.transaction.support.TransactionTemplate;
* inside a transaction of the caller. A confirm that fails later (for example
the connection is lost) logs a WARN, and
* when the repository joins a transaction of the caller (same DataSource), it
marks that transaction as rollback only,
* as a failed add or remove does.
+ * <p/>
+ * When another instance took a key over (this instance could not refresh it
for longer than the lockMaxAge), this
+ * instance no longer removes the key nor keeps it alive: the lease is then
the one of the other instance, which still
+ * processes the message. The remove and the keep-alive of a key that this
instance holds only match the lease that this
+ * instance wrote last (see the Lease class). A confirm still confirms the
key, as the message was processed.
*/
public class JdbcOrphanLockAwareIdempotentRepository extends
JdbcMessageIdRepository {
@@ -77,9 +87,11 @@ public class JdbcOrphanLockAwareIdempotentRepository extends
JdbcMessageIdReposi
protected static final String DEFAULT_CONFIRM_QUERY
= "UPDATE CAMEL_MESSAGEPROCESSED SET createdAt = NULL WHERE
processorName = ? AND messageId = ?";
- // a concurrent set, so no lock is held while SQL runs: add and remove
hold a connection of the pool while they
- // run, and the keep-alive needs one too, so a lock held across SQL could
deadlock with a small pool
- private final Set<ProcessorNameAndMessageId> processorNameMessageIdSet =
ConcurrentHashMap.newKeySet();
+ // the keys this instance holds and keeps alive, each with the lease this
instance last wrote for it. A concurrent
+ // map, so no lock is held while SQL runs: add and remove hold a
connection of the pool while they run, and the
+ // keep-alive needs one too, so a lock held across SQL could deadlock with
a small pool
+ private final Map<ProcessorNameAndMessageId, Lease> leases = new
ConcurrentHashMap<>();
+ private final Set<ProcessorNameAndMessageId> processorNameMessageIdSet =
leases.keySet();
// the keys whose confirm runs: the confirm takes them out of
processorNameMessageIdSet before its UPDATE, so that the
// keep-alive does not wait for the row lock of the confirm, but this
instance still holds them until the confirm ends
@@ -164,11 +176,46 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
@Override
protected int delete(String key) {
- int result = super.delete(key);
+ Lease lease = leases.get(new ProcessorNameAndMessageId(processorName,
key));
+ int result;
+ if (lease == null) {
+ // not a key that this instance keeps alive (such as a key removed
by hand, or one added before a restart of
+ // the JVM, or earlier in the current transaction): deleted by its
key
+ result = super.delete(key);
+ } else if (lease.lost) {
+ // the keep-alive found that another instance took the key over:
its row is not the lease of this instance
+ result = 0;
+ } else {
+ result = jdbcTemplate.update(getDeleteString() + " AND createdAt <
?", processorName, key, ownedBefore(lease));
+ if (result == 0) {
+ log.warn("Not removing the key {} of processor {} from the
idempotent repository: another instance took it"
+ + " over, as this instance could not refresh its
lease for longer than lockMaxAgeMillis, or confirmed"
+ + " or removed it. The other instance may still
process its message.",
+ key, processorName);
+ }
+ }
stopKeepAlive(key);
return result;
}
+ // the createdAt of a row that is the lease of this instance is earlier
than this: see Lease
+ private Timestamp ownedBefore(Lease lease) {
+ return ownedBefore(lease.writtenAt, (lockMaxAgeMillis +
lockKeepAliveIntervalMillis) / 2, ZoneId.systemDefault());
+ }
+
+ /**
+ * The lease written at writtenAt plus the margin. A createdAt column
without time zone (the default table) holds
+ * the local time of the JVM, which goes back an hour at the end of
daylight saving time: a lease written shortly
+ * before would then look later than the instant plus the margin. So the
margin is added to the local time too, and
+ * the later of the two is used. For a column with time zone, this matches
up to an hour more for a lease written
+ * shortly before that change, as the remove and the keep-alive matched
any createdAt before.
+ */
+ static Timestamp ownedBefore(long writtenAt, long margin, ZoneId zone) {
+ long local = LocalDateTime.ofInstant(Instant.ofEpochMilli(writtenAt),
zone).plus(margin, ChronoUnit.MILLIS)
+ .atZone(zone).toInstant().toEpochMilli();
+ return new Timestamp(Math.max(writtenAt + margin, local));
+ }
+
/**
* Confirms the key: the message was processed, so the key is no longer a
lock that is kept alive and that another
* instance can take over when this one stops. Its createdAt is set to
null, which the orphan check never treats as
@@ -195,8 +242,11 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
// deadlock with a later confirm or remove in the same transaction).
It is kept alive again when the confirm fails
// or its transaction does not commit; not when no row matched, as
then there is no lease of this instance.
// Until the confirm ends, this instance still holds the key (see
queryForInt), but does not keep it alive.
+ // The confirm matches the row by its key also when another instance
took the key over meanwhile: the message
+ // was processed, so the key is a duplicate from now on (the other
instance does not remove it then).
confirming.add(id);
- boolean keptAlive = processorNameMessageIdSet.remove(id);
+ Lease lease = leases.remove(id);
+ boolean keptAlive = lease != null;
boolean completed = false;
try {
// in a transaction of its own (or the one of the caller), as add
and remove
@@ -207,7 +257,7 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
// an insert of the key earlier in this transaction does not
keep it alive after the commit
cancelKeepAliveAfterCommit(id);
if (keptAlive &&
TransactionSynchronizationManager.isSynchronizationActive()) {
-
TransactionSynchronizationManager.registerSynchronization(new
KeepAliveUnlessCommitted(this, id));
+
TransactionSynchronizationManager.registerSynchronization(new
KeepAliveUnlessCommitted(this, id, lease));
}
return true;
});
@@ -222,7 +272,7 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
return false;
} finally {
if (keptAlive && !completed) {
- processorNameMessageIdSet.add(id);
+ leases.put(id, lease);
}
confirming.remove(id);
}
@@ -311,7 +361,7 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
Timestamp currentTimestamp = new Timestamp(System.currentTimeMillis());
if (jdbcTemplate.queryForObject(getQueryString(), Integer.class,
processorName, key) == 0) {
int result = jdbcTemplate.update(getInsertString(), processorName,
key, currentTimestamp);
- keepAliveAfterCommit(key);
+ keepAliveAfterCommit(key, currentTimestamp);
return result;
} else {
// Row exists — try to claim orphan lock with conditional UPDATE.
@@ -322,7 +372,7 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
int result = jdbcTemplate.update(orphanLockRecoverQueryString,
currentTimestamp, processorName, key, xMillisAgo);
if (result > 0) {
log.debug("Orphan lock seized for key: {}", key);
- keepAliveAfterCommit(key);
+ keepAliveAfterCommit(key, currentTimestamp);
}
return result;
}
@@ -333,12 +383,37 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
* transaction rolls back (for example in a transacted route with
removeOnFailure=false), the row is not there, so
* the key must not be kept alive: another node may insert it later, and
this node would keep its lease alive.
*/
- private void keepAliveAfterCommit(String key) {
+ private void keepAliveAfterCommit(String key, Timestamp createdAt) {
ProcessorNameAndMessageId id = new
ProcessorNameAndMessageId(processorName, key);
+ Lease lease = new Lease(createdAt.getTime(), false);
if (TransactionSynchronizationManager.isSynchronizationActive()) {
- TransactionSynchronizationManager.registerSynchronization(new
KeepAliveAfterCommit(this, id));
+ TransactionSynchronizationManager.registerSynchronization(new
KeepAliveAfterCommit(this, id, lease));
} else {
- processorNameMessageIdSet.add(id);
+ leases.put(id, lease);
+ }
+ }
+
+ /**
+ * The lease that this instance last wrote for a key it holds: the
createdAt of its insert or takeover, or of the
+ * last keep-alive that refreshed it. Another instance takes the key over
only when its createdAt is older than the
+ * lockMaxAge, and then writes a createdAt of its own, later than this one
by more than the lockMaxAge. A keep-alive
+ * of this instance whose outcome is not known yet (it runs while the key
is confirmed or removed, or it failed
+ * after the database committed it) writes about one keep-alive interval
later than this one. So the remove and the
+ * keep-alive of the key only match a createdAt earlier than halfway
between the two, which leaves room for a late
+ * keep-alive and for the rounding of the createdAt column. When the
keep-alive does not match the row, the lease is
+ * lost: the key is no longer kept alive, nor removed, but this instance
still holds it (see queryForInt) until it
+ * is removed or confirmed. The clocks of the instances do not need to
agree: the other instance compares the stored
+ * createdAt with its own clock, and writes a createdAt from the same
clock. A keep-alive of this instance that
+ * committed although it failed, after the keep-alive could not refresh
the key for longer than half of lockMaxAge
+ * minus the keep-alive interval, is not told apart from a takeover: the
lease is then marked lost.
+ */
+ private static final class Lease {
+ private final long writtenAt;
+ private final boolean lost;
+
+ private Lease(long writtenAt, boolean lost) {
+ this.writtenAt = writtenAt;
+ this.lost = lost;
}
}
@@ -349,18 +424,21 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
private static final class KeepAliveAfterCommit implements
TransactionSynchronization {
private final JdbcOrphanLockAwareIdempotentRepository repository;
private final ProcessorNameAndMessageId id;
+ private final Lease lease;
// set and read by the thread of the transaction
private boolean cancelled;
- private KeepAliveAfterCommit(JdbcOrphanLockAwareIdempotentRepository
repository, ProcessorNameAndMessageId id) {
+ private KeepAliveAfterCommit(JdbcOrphanLockAwareIdempotentRepository
repository, ProcessorNameAndMessageId id,
+ Lease lease) {
this.repository = repository;
this.id = id;
+ this.lease = lease;
}
@Override
public void afterCommit() {
if (!cancelled) {
- repository.processorNameMessageIdSet.add(id);
+ repository.leases.put(id, lease);
}
}
}
@@ -373,16 +451,19 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
private static final class KeepAliveUnlessCommitted implements
TransactionSynchronization {
private final JdbcOrphanLockAwareIdempotentRepository repository;
private final ProcessorNameAndMessageId id;
+ private final Lease lease;
- private
KeepAliveUnlessCommitted(JdbcOrphanLockAwareIdempotentRepository repository,
ProcessorNameAndMessageId id) {
+ private
KeepAliveUnlessCommitted(JdbcOrphanLockAwareIdempotentRepository repository,
ProcessorNameAndMessageId id,
+ Lease lease) {
this.repository = repository;
this.id = id;
+ this.lease = lease;
}
@Override
public void afterCompletion(int status) {
if (status != STATUS_COMMITTED) {
- repository.processorNameMessageIdSet.add(id);
+ repository.leases.put(id, lease);
}
}
}
@@ -449,23 +530,43 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
void keepAlive() {
// the leases get a later timestamp, taken once the connection was
obtained
long started = System.currentTimeMillis();
+ List<Refresh> refreshes;
try {
- transactionTemplate.execute(status -> {
+ refreshes = transactionTemplate.execute(status -> {
// take the timestamp and the keys inside the transaction,
after the connection was obtained (with the
// DataSourceTransactionManager), as waiting for it can take a
while
Timestamp currentTimestamp = new
Timestamp(System.currentTimeMillis());
- List<Object[]> args = processorNameMessageIdSet.stream()
- .map(processorNameMessageId -> new Object[] {
- currentTimestamp,
processorNameMessageId.processorName, processorNameMessageId.messageId })
- .collect(Collectors.toList());
- // not a key that was confirmed meanwhile (its createdAt is
null)
- return jdbcTemplate.batchUpdate(getUpdateTimestampQuery() + "
AND createdAt IS NOT NULL", args);
+ // only the lease of this instance (see Lease), and not a key
that was confirmed meanwhile (its createdAt
+ // is null). One statement per key, as a batch may not tell
which keys it updated
+ String query = getUpdateTimestampQuery() + " AND createdAt <
?";
+ List<Refresh> result = new ArrayList<>();
+ for (Map.Entry<ProcessorNameAndMessageId, Lease> entry :
leases.entrySet()) {
+ ProcessorNameAndMessageId id = entry.getKey();
+ Lease lease = entry.getValue();
+ if (!lease.lost) {
+ int updated = jdbcTemplate.update(query,
currentTimestamp, id.processorName, id.messageId,
+ ownedBefore(lease));
+ result.add(new Refresh(
+ id, lease,
+ updated > 0 ? new
Lease(currentTimestamp.getTime(), false) : new Lease(lease.writtenAt, true)));
+ }
+ }
+ return result;
});
} catch (Exception e) {
log.error("failed updating createdAt in keepAlive due to ", e);
warnOnceWhenLeasesMayHaveExpired();
return;
}
+ // once committed; not for a key that was removed or confirmed
meanwhile
+ for (Refresh refresh : refreshes) {
+ if (leases.replace(refresh.id, refresh.lease, refresh.next) &&
refresh.next.lost) {
+ log.warn("The keep-alive of processor {} no longer keeps the
key {} alive: another instance took it over, as"
+ + " this instance could not refresh its lease for
longer than lockMaxAgeMillis, or confirmed or"
+ + " removed it. This instance does not remove the
key, and still treats it as a duplicate.",
+ processorName, refresh.id.messageId);
+ }
+ }
if (leasesMayHaveExpired) {
leasesMayHaveExpired = false;
log.info("The keep-alive of processor {} refreshes the leases of
this instance again, {} ms after it last did:"
@@ -535,6 +636,10 @@ public class JdbcOrphanLockAwareIdempotentRepository
extends JdbcMessageIdReposi
this.lockKeepAliveIntervalMillis = lockKeepAliveIntervalMillis;
}
+ // a lease that a keep-alive refreshed, or found lost
+ private record Refresh(ProcessorNameAndMessageId id, Lease lease, Lease
next) {
+ }
+
class LockKeepAliveTask implements Runnable {
@Override
diff --git
a/components/camel-sql/src/test/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepositoryOutageTest.java
b/components/camel-sql/src/test/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepositoryOutageTest.java
index ad52c61cd0bc..fee0789c5b74 100644
---
a/components/camel-sql/src/test/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepositoryOutageTest.java
+++
b/components/camel-sql/src/test/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepositoryOutageTest.java
@@ -285,7 +285,9 @@ class JdbcOrphanLockAwareIdempotentRepositoryOutageTest {
@Override
public int update(String sql, Object... args) {
- if (sql.equals(pausedSql)) {
+ // the repository may add a condition to the statement (the remove
of a key it holds)
+ String pauseAt = pausedSql;
+ if (pauseAt != null && sql.startsWith(pauseAt)) {
pausedSql = null;
paused.countDown();
try {
diff --git
a/components/camel-sql/src/test/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepositoryTakeoverTest.java
b/components/camel-sql/src/test/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepositoryTakeoverTest.java
new file mode 100644
index 000000000000..3ba07530c971
--- /dev/null
+++
b/components/camel-sql/src/test/java/org/apache/camel/processor/idempotent/jdbc/JdbcOrphanLockAwareIdempotentRepositoryTakeoverTest.java
@@ -0,0 +1,238 @@
+/*
+ * 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.processor.idempotent.jdbc;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import javax.sql.DataSource;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DelegatingDataSource;
+import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
+import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
+import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Node A cannot reach the database for longer than lockMaxAgeMillis, so node
B takes over a key that node A still
+ * processes (the documented limitation: the message is processed twice, once
on each node). Node A must then leave the
+ * lease of node B alone: its remove must not delete it (a third node C would
take the key while node B still processes
+ * it), and its keep-alive must not refresh it (node C must take it over once
node B crashes). A confirm of node A
+ * confirms the key, as the message was processed, and node B must not remove
the confirmed key then. Three repository
+ * instances (three nodes) share one H2 database, each with its scheduled
keep-alive; only node A loses the database.
+ */
+class JdbcOrphanLockAwareIdempotentRepositoryTakeoverTest {
+
+ private static final String PROCESSOR_NAME = "APP_1";
+ private static final long LOCK_MAX_AGE_MILLIS = 1000L;
+ private static final long LOCK_KEEP_ALIVE_INTERVAL_MILLIS = 40L;
+
+ private EmbeddedDatabase database;
+ private JdbcTemplate jdbcTemplate;
+ private CamelContext context;
+ private Outage outage;
+ private RecordingLogger logsOfA;
+ private JdbcOrphanLockAwareIdempotentRepository nodeA;
+ private JdbcOrphanLockAwareIdempotentRepository nodeB;
+ private JdbcOrphanLockAwareIdempotentRepository nodeC;
+
+ @BeforeEach
+ void setup() {
+ database = new EmbeddedDatabaseBuilder()
+ .setType(EmbeddedDatabaseType.H2)
+ .generateUniqueName(true)
+ .build();
+ jdbcTemplate = new JdbcTemplate(database);
+ context = new DefaultCamelContext();
+ outage = new Outage(database);
+ logsOfA = new RecordingLogger();
+ nodeA = newRepository(outage);
+ nodeA.log = logsOfA.logger();
+ nodeB = newRepository(database);
+ nodeC = newRepository(database);
+ nodeA.start();
+ nodeB.start();
+ nodeC.start();
+ }
+
+ @AfterEach
+ void tearDown() {
+ nodeA.shutdown();
+ nodeB.shutdown();
+ nodeC.shutdown();
+ context.stop();
+ database.shutdown();
+ }
+
+ @Test
+ void testOldHolderDoesNotRemoveTheLeaseOfTheNewHolder() {
+ assertTrue(nodeA.add("ORDER_1"));
+ nodeBTakesOverDuringAnOutageOfNodeA("ORDER_1");
+ assertFalse(nodeC.add("ORDER_1"), "The lease of node B must protect
the key");
+
+ // the processing of ORDER_1 fails on node A, so it removes the key
(removeOnFailure; also the remove of a file
+ // read lock with readLockRemoveOnCommit=true once the file is
processed)
+ assertFalse(nodeA.remove("ORDER_1"), "Node A must not delete the lease
that node B took over");
+ assertNotNull(createdAt("ORDER_1"), "The lease of node B must still be
there");
+ assertTrue(logsOfA.warnings().stream().anyMatch(warning ->
warning.contains("another instance took it over")),
+ () -> "Node A must log that it does not remove the key: " +
logsOfA.warnings());
+ assertFalse(nodeC.add("ORDER_1"), "The key must not be taken a third
time while node B processes it");
+
+ // node B processes ORDER_1 as usual
+ assertTrue(nodeB.confirm("ORDER_1"));
+ assertNull(createdAt("ORDER_1"));
+ assertFalse(nodeA.add("ORDER_1"));
+ assertFalse(nodeC.add("ORDER_1"));
+ }
+
+ @Test
+ void testNewHolderDoesNotRemoveAKeyThatTheOldHolderConfirmed() {
+ assertTrue(nodeA.add("ORDER_2"));
+ nodeBTakesOverDuringAnOutageOfNodeA("ORDER_2");
+
+ // the processing of ORDER_2 succeeds on node A: its confirm confirms
the key, as the message was processed
+ assertTrue(nodeA.confirm("ORDER_2"));
+ assertNull(createdAt("ORDER_2"));
+
+ // the processing of ORDER_2 fails on node B: its remove must not
delete the confirmed key
+ assertFalse(nodeB.remove("ORDER_2"), "Node B must not delete a key
that node A confirmed");
+ assertEquals(1, rows("ORDER_2"));
+ assertNull(createdAt("ORDER_2"));
+ assertFalse(nodeC.add("ORDER_2"), "A confirmed key must stay a
duplicate");
+ }
+
+ @Test
+ void testOldHolderDoesNotKeepAliveTheLeaseOfTheNewHolder() {
+ assertTrue(nodeA.add("ORDER_3"));
+ nodeBTakesOverDuringAnOutageOfNodeA("ORDER_3");
+
+ // node B crashes while it processes ORDER_3, while node A still
processes it and its keep-alive runs again: the
+ // lease of node B must expire, so that node C takes the key over, as
for any node that crashed
+ nodeB.stop();
+ await().atMost(10, TimeUnit.SECONDS).pollInterval(20,
TimeUnit.MILLISECONDS)
+ .until(() -> nodeC.add("ORDER_3"));
+ await().atMost(10, TimeUnit.SECONDS).pollInterval(20,
TimeUnit.MILLISECONDS)
+ .untilAsserted(() -> assertTrue(
+ logsOfA.warnings().stream().anyMatch(warning ->
warning.contains("no longer keeps the key")),
+ () -> "Node A must log that it no longer keeps the key
alive: " + logsOfA.warnings()));
+
+ // node A, which still treats the key as a duplicate, leaves the lease
of node C alone too
+ assertFalse(nodeA.add("ORDER_3"));
+ assertFalse(nodeA.remove("ORDER_3"));
+ assertNotNull(createdAt("ORDER_3"));
+ }
+
+ @Test
+ void testLeaseWrittenBeforeTheEndOfDaylightSavingTimeStillMatches() {
+ // a createdAt column without time zone holds the local time of the
JVM, which goes back an hour on 2026-10-25 at
+ // 03:00 in Berlin: the lease of this instance written shortly before
must still be earlier than the bound, in
+ // local time too. The same around the start of daylight saving time,
and on a day without change
+ ZoneId berlin = ZoneId.of("Europe/Berlin");
+ long margin = (LOCK_MAX_AGE_MILLIS + LOCK_KEEP_ALIVE_INTERVAL_MILLIS)
/ 2;
+ for (String change : List.of("2026-10-25T01:00:00Z",
"2026-03-29T01:00:00Z", "2026-06-01T01:00:00Z")) {
+ long at = Instant.parse(change).toEpochMilli();
+ for (long writtenAt = at - 2 * margin; writtenAt <= at + 2 *
margin; writtenAt += 100) {
+ Timestamp bound =
JdbcOrphanLockAwareIdempotentRepository.ownedBefore(writtenAt, margin, berlin);
+ LocalDateTime written =
LocalDateTime.ofInstant(Instant.ofEpochMilli(writtenAt), berlin);
+ LocalDateTime localBound =
LocalDateTime.ofInstant(bound.toInstant(), berlin);
+ assertFalse(localBound.isBefore(written.plusNanos(margin *
1_000_000)),
+ "The lease written at " + written + " must be earlier
than the bound in local time: " + localBound);
+ assertTrue(bound.getTime() >= writtenAt + margin,
+ "The lease written at " +
Instant.ofEpochMilli(writtenAt) + " must be earlier than the bound: "
+ +
bound.toInstant());
+ }
+ }
+ }
+
+ // node A cannot refresh its lease; once the lease is older than the lock
max age, node B takes the key over (as it
+ // cannot tell node A from a node that crashed), and node A reaches the
database again
+ private void nodeBTakesOverDuringAnOutageOfNodeA(String key) {
+ outage.begin();
+ await().atMost(10, TimeUnit.SECONDS).pollInterval(20,
TimeUnit.MILLISECONDS)
+ .until(() -> nodeB.add(key));
+ outage.end();
+ }
+
+ private JdbcOrphanLockAwareIdempotentRepository newRepository(DataSource
dataSource) {
+ JdbcOrphanLockAwareIdempotentRepository repository
+ = new JdbcOrphanLockAwareIdempotentRepository(dataSource,
PROCESSOR_NAME, context);
+ repository.setLockMaxAgeMillis(LOCK_MAX_AGE_MILLIS);
+
repository.setLockKeepAliveIntervalMillis(LOCK_KEEP_ALIVE_INTERVAL_MILLIS);
+ return repository;
+ }
+
+ private Timestamp createdAt(String key) {
+ List<Timestamp> createdAt = jdbcTemplate.queryForList(
+ "SELECT createdAt FROM CAMEL_MESSAGEPROCESSED WHERE
processorName = ? AND messageId = ?", Timestamp.class,
+ PROCESSOR_NAME, key);
+ assertEquals(1, createdAt.size(), () -> "No row for the key " + key);
+ return createdAt.get(0);
+ }
+
+ private int rows(String key) {
+ return jdbcTemplate.queryForObject(
+ "SELECT COUNT(*) FROM CAMEL_MESSAGEPROCESSED WHERE
processorName = ? AND messageId = ?", Integer.class,
+ PROCESSOR_NAME, key);
+ }
+
+ /**
+ * The database as node A sees it: unreachable during an outage, so every
statement fails as it cannot get a
+ * connection.
+ */
+ private static final class Outage extends DelegatingDataSource {
+
+ private volatile boolean down;
+
+ Outage(EmbeddedDatabase database) {
+ super(database);
+ }
+
+ void begin() {
+ down = true;
+ }
+
+ void end() {
+ down = false;
+ }
+
+ @Override
+ public Connection getConnection() throws SQLException {
+ if (down) {
+ throw new SQLException("Connection refused: the database is
unreachable");
+ }
+ return super.getConnection();
+ }
+ }
+}
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 f8857a8e1a20..4ede109e2809 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
@@ -5367,6 +5367,22 @@ now logs a WARN, and an INFO when it refreshes them
again.
Code that sets the `createdAt` of a key older than `lockMaxAgeMillis` and
expects the repository that added the key
to see it as absent, such as a test of the keep-alive, has to check the key
with another repository instance.
+=== camel-sql - JdbcOrphanLockAwareIdempotentRepository does not remove a key
that another instance took over
+
+When another instance took a key over (the first instance could not refresh
its lock for longer than
+`lockMaxAgeMillis`), `JdbcOrphanLockAwareIdempotentRepository` on the first
instance no longer removes the key or keeps
+it alive: its remove and its keep-alive now only match the `createdAt` that
the instance wrote last. Before, the
+remove deleted the lock of the other instance while it still processed the
message, so a third instance could take
+the key, and the keep-alive refreshed the lock of the other instance. Such a
remove now returns false and logs a WARN.
+A confirm still confirms the key by its key.
+
+The repository adds `AND createdAt < ?` to `deleteString` for a key that it
holds, as it already does to `queryString`
+and to the update query. A custom `deleteString` must end with its `WHERE`
condition, as a custom `queryString`
+already must. Keep `lockMaxAgeMillis` larger than
`lockKeepAliveIntervalMillis` by a few seconds at least: an instance
+matches a `createdAt` earlier than halfway between the two after the one it
wrote last. The keep-alive now sends one
+statement per key, in one transaction, instead of a batch.
`getProcessorNameMessageIdSet()` now returns the key set of
+the map that holds the `createdAt` of each key: a key can be removed from it,
but no longer added.
+
=== camel-jta - an exchange marked rollback only last rolls back its
transaction
In a `transacted()` route that uses a JTA transaction manager,
`markRollbackOnlyLast()` now rolls back the