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 7b7c40ebee73 CAMEL-27418: camel-wal - a start that fails or crashes 
keeps the unconfirmed entries of the previous run (#30754)
7b7c40ebee73 is described below

commit 7b7c40ebee7396fbb82d7f4e7e00008f3f5eb183
Author: allthingssecurity <[email protected]>
AuthorDate: Wed Nov 25 13:29:51 2026 +0530

    CAMEL-27418: camel-wal - a start that fails or crashes keeps the 
unconfirmed entries of the previous run (#30754)
    
    WriteAheadResumeStrategy.start() read the previous log, then the LogWriter
    opened the same file with TRUNCATE_EXISTING and only then appended the 
carried
    unconfirmed entries, forced at the next supervisor tick. A crash, an 
exception
    (rejected flush schedule, IOException of an append) or a power loss in that
    window left an empty log, and the next start replayed nothing.
    
    The LogWriter now writes the header and the carried entries to <log>.tmp in
    the same directory, forces it, moves it atomically over the log and forces 
the
    directory where possible. Until the move the previous log is unchanged. The
    writer then writes the same header and entries again at the same positions 
of
    the moved log, so its positions and layers are built as before, forces it, 
and
    only then schedules the flush task. Where the log cannot be replaced 
atomically
    (the temporary file cannot be created or written, or the move fails), the
    temporary file is deleted, a WARN names the log and the reason, and the log 
is
    truncated and rewritten in place as before, but forced right after the 
carried
    entries, so start() does not fail where it started before. There is no
    non-atomic move. The new log keeps the POSIX permissions of the previous one
    where the file system allows it, and a symbolic link to the log is kept.
    Without entries to carry, the log is truncated in place as before; the 
public
    constructors are unchanged.
    
    Related to CAMEL-26107.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../org/apache/camel/component/wal/LogWriter.java  | 153 +++++++++++--
 .../component/wal/WriteAheadResumeStrategy.java    |  12 +-
 .../WriteAheadResumeStrategyStartFailureTest.java  | 239 +++++++++++++++++++++
 .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc    |  11 +
 4 files changed, 394 insertions(+), 21 deletions(-)

diff --git 
a/components/camel-wal/src/main/java/org/apache/camel/component/wal/LogWriter.java
 
b/components/camel-wal/src/main/java/org/apache/camel/component/wal/LogWriter.java
index ccb927759205..32e2c3fcc802 100644
--- 
a/components/camel-wal/src/main/java/org/apache/camel/component/wal/LogWriter.java
+++ 
b/components/camel-wal/src/main/java/org/apache/camel/component/wal/LogWriter.java
@@ -21,7 +21,11 @@ import java.io.File;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.nio.channels.FileChannel;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
 import java.nio.file.StandardOpenOption;
+import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
@@ -46,6 +50,7 @@ public final class LogWriter implements AutoCloseable {
 
     private final LogSupervisor flushPolicy;
     private final TransactionLog transactionLog;
+    private final List<EntryInfo.CachedEntryInfo> initialEntryInfos;
 
     private long startOfRecords;
 
@@ -72,15 +77,127 @@ public final class LogWriter implements AutoCloseable {
      * @throws IOException    in case of I/O errors
      */
     LogWriter(File logFile, LogSupervisor logSupervisor, int maxRecordCount) 
throws IOException {
-        this.fileChannel = FileChannel.open(logFile.toPath(), 
StandardOpenOption.CREATE, StandardOpenOption.WRITE,
-                StandardOpenOption.TRUNCATE_EXISTING);
-
-        final Header header = Header.WA_DEFAULT_V1;
-        writeHeader(header);
+        this(logFile, logSupervisor, maxRecordCount, List.of());
+    }
 
+    /**
+     * Constructs a new log writer whose new log holds the given entries 
first. Without entries, the file is truncated,
+     * as with the other constructors. With entries, the file is replaced only 
once the new log is on disk: the header
+     * and the entries are written to a temporary file in the same directory, 
which is forced to disk and then moved
+     * atomically over the file. If that is not possible (the temporary file 
cannot be written, or the file system
+     * cannot move it atomically over the file), a WARN is logged and the file 
is truncated and written in place, as
+     * without entries, and forced to disk right after the entries.
+     *
+     * @param  logFile        the transaction log file
+     * @param  logSupervisor  the log supervisor {@link LogSupervisor} for the 
writer
+     * @param  maxRecordCount the maximum number of records to keep in the 
file. Beyond this count, entries will be
+     *                        rolled-over.
+     * @param  entries        the entries the new log holds first (fewer than 
maxRecordCount)
+     * @throws IOException    in case of I/O errors
+     */
+    LogWriter(File logFile, LogSupervisor logSupervisor, int maxRecordCount, 
List<LogEntry> entries) throws IOException {
         this.flushPolicy = logSupervisor;
         this.transactionLog = new TransactionLog(maxRecordCount);
-        this.flushPolicy.start(this::tryFlush);
+
+        // with entries, the new log replaces the file a symbolic link points 
to, not the link
+        final Path path = entries.isEmpty() || !Files.exists(logFile.toPath())
+                ? logFile.toPath() : logFile.toPath().toRealPath();
+        final boolean replaced = !entries.isEmpty() && replace(path, entries);
+        // after the replacement, the file already holds the header and the 
entries: they are written again below at
+        // the same positions (the same bytes), so the positions and the 
layers are built as for a new log
+        this.fileChannel = replaced
+                ? FileChannel.open(path, StandardOpenOption.WRITE)
+                : FileChannel.open(path, StandardOpenOption.CREATE, 
StandardOpenOption.WRITE,
+                        StandardOpenOption.TRUNCATE_EXISTING);
+        try {
+            final Header header = Header.WA_DEFAULT_V1;
+            writeHeader(header);
+
+            final List<EntryInfo.CachedEntryInfo> entryInfos = new 
ArrayList<>(entries.size());
+            for (LogEntry entry : entries) {
+                entryInfos.add(append(entry));
+            }
+            this.initialEntryInfos = List.copyOf(entryInfos);
+
+            if (!entries.isEmpty()) {
+                // without the replacement, the entries are on disk only from 
here on
+                flush();
+            }
+
+            this.flushPolicy.start(this::tryFlush);
+        } catch (IOException | RuntimeException e) {
+            try {
+                fileChannel.close();
+            } catch (IOException suppressed) {
+                e.addSuppressed(suppressed);
+            }
+            throw e;
+        }
+    }
+
+    /**
+     * Replaces the file by a new log with the header and the entries: writes 
them to a temporary file in the same
+     * directory, forces it to disk and moves it atomically over the file. 
Until the move the file is unchanged.
+     *
+     * @return false, after a WARN, if the file could not be replaced (it is 
then unchanged)
+     */
+    private static boolean replace(Path target, List<LogEntry> entries) {
+        final Path tmp = target.resolveSibling(target.getFileName() + ".tmp");
+        boolean created = false;
+        try {
+            try (FileChannel channel = FileChannel.open(tmp, 
StandardOpenOption.CREATE, StandardOpenOption.WRITE,
+                    StandardOpenOption.TRUNCATE_EXISTING)) {
+                created = true;
+                write(channel, Header.WA_DEFAULT_V1);
+                for (LogEntry entry : entries) {
+                    write(channel, entry);
+                }
+                channel.force(true);
+            }
+
+            // the new log keeps the permissions of the previous one, as a 
truncated file would. A file system that
+            // cannot change them (such as FAT) does not prevent the 
replacement
+            if (Files.exists(target)) {
+                try {
+                    Files.setPosixFilePermissions(tmp, 
Files.getPosixFilePermissions(target));
+                } catch (UnsupportedOperationException | IOException e) {
+                    LOG.debug("Cannot give {} the permissions of {}: {}", tmp, 
target, e.getMessage());
+                }
+            }
+
+            // atomically or not at all: a move that is not atomic deletes the 
log first and may copy the file
+            Files.move(tmp, target, StandardCopyOption.ATOMIC_MOVE);
+        } catch (IOException | RuntimeException e) {
+            if (created) {
+                try {
+                    Files.deleteIfExists(tmp);
+                } catch (IOException suppressed) {
+                    LOG.debug("Cannot delete {}: {}", tmp, 
suppressed.getMessage());
+                }
+            }
+            LOG.warn("Cannot replace the transaction log {} atomically ({}): 
truncating and writing it in place instead."
+                     + " A crash before its unconfirmed entries are written 
again loses them",
+                    target, e.toString());
+            return false;
+        }
+
+        // make the move itself durable, where the file system allows a 
directory to be forced
+        final Path directory = target.toAbsolutePath().getParent();
+        if (directory != null) {
+            try (FileChannel channel = FileChannel.open(directory, 
StandardOpenOption.READ)) {
+                channel.force(true);
+            } catch (IOException e) {
+                LOG.debug("Cannot force the directory {} to disk: {}", 
directory, e.getMessage());
+            }
+        }
+        return true;
+    }
+
+    /**
+     * The entry information of the entries the new log was started with, in 
their order
+     */
+    List<EntryInfo.CachedEntryInfo> getInitialEntryInfos() {
+        return initialEntryInfos;
     }
 
     /**
@@ -127,14 +244,25 @@ public final class LogWriter implements AutoCloseable {
     }
 
     private void writeHeader(final Header header) throws IOException {
+        write(fileChannel, header);
+
+        startOfRecords = fileChannel.position();
+    }
+
+    private static void write(FileChannel channel, Header header) throws 
IOException {
         ByteBuffer headerBuffer = ByteBuffer.allocate(Header.BYTES);
 
         headerBuffer.put(header.getFormatName().getBytes());
         headerBuffer.putInt(header.getFileVersion());
 
-        IOUtil.write(fileChannel, headerBuffer);
+        IOUtil.write(channel, headerBuffer);
+    }
 
-        startOfRecords = fileChannel.position();
+    private static void write(FileChannel channel, LogEntry entry) throws 
IOException {
+        ByteBuffer writeBuffer = 
ByteBuffer.allocate(LogEntry.size(entry.getKey(), entry.getValue()));
+        IOUtil.serialize(writeBuffer, entry);
+
+        IOUtil.write(channel, writeBuffer);
     }
 
     /**
@@ -216,15 +344,8 @@ public final class LogWriter implements AutoCloseable {
      * @throws IOException in case of lower-level I/O errors
      */
     private EntryInfo.CachedEntryInfo persist(TransactionLog.EntryContainer 
container) throws IOException {
-        final LogEntry entry = container.logEntry;
-        final byte[] key = entry.getKey();
-        final byte[] value = entry.getValue();
-
-        ByteBuffer writeBuffer = ByteBuffer.allocate(LogEntry.size(key, 
value));
-        IOUtil.serialize(writeBuffer, entry);
-
         long recordPosition = fileChannel.position();
-        IOUtil.write(fileChannel, writeBuffer);
+        write(fileChannel, container.logEntry);
         container.position = recordPosition;
 
         return EntryInfo.createForCached(recordPosition, container.layerInfo);
diff --git 
a/components/camel-wal/src/main/java/org/apache/camel/component/wal/WriteAheadResumeStrategy.java
 
b/components/camel-wal/src/main/java/org/apache/camel/component/wal/WriteAheadResumeStrategy.java
index d08d133d1a85..a65ab5befe62 100644
--- 
a/components/camel-wal/src/main/java/org/apache/camel/component/wal/WriteAheadResumeStrategy.java
+++ 
b/components/camel-wal/src/main/java/org/apache/camel/component/wal/WriteAheadResumeStrategy.java
@@ -385,12 +385,14 @@ public class WriteAheadResumeStrategy implements 
ResumeStrategy, CamelContextAwa
             DefaultLogSupervisor flushPolicy = new DefaultLogSupervisor(
                     resumeStrategyConfiguration.getSupervisorInterval(),
                     executorService);
-            logWriter = new LogWriter(logFile, flushPolicy, maxRecordCount);
-
-            // keep them in the new log until loadCache() replays them, in 
case the system crashes again before
+            // keep them in the new log until loadCache() replays them, in 
case the system crashes again before. The
+            // new log replaces the previous one only once it holds them on 
disk, so a crash or a failure here does
+            // not lose them (where the log cannot be replaced atomically, it 
is rewritten in place and forced)
+            logWriter = new LogWriter(logFile, flushPolicy, maxRecordCount, 
entries);
+            final List<EntryInfo.CachedEntryInfo> entryInfos = 
logWriter.getInitialEntryInfos();
             final List<UnconfirmedEntry> carried = new 
ArrayList<>(entries.size());
-            for (LogEntry entry : entries) {
-                carried.add(new UnconfirmedEntry(entry, 
logWriter.append(entry)));
+            for (int i = 0; i < entries.size(); i++) {
+                carried.add(new UnconfirmedEntry(entries.get(i), 
entryInfos.get(i)));
             }
             unconfirmedEntries = carried;
         } catch (Exception e) {
diff --git 
a/components/camel-wal/src/test/java/org/apache/camel/component/wal/WriteAheadResumeStrategyStartFailureTest.java
 
b/components/camel-wal/src/test/java/org/apache/camel/component/wal/WriteAheadResumeStrategyStartFailureTest.java
new file mode 100644
index 000000000000..b7035084a8b1
--- /dev/null
+++ 
b/components/camel-wal/src/test/java/org/apache/camel/component/wal/WriteAheadResumeStrategyStartFailureTest.java
@@ -0,0 +1,239 @@
+/*
+ * 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.wal;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Proxy;
+import java.nio.ByteBuffer;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.resume.ResumeStrategy;
+import org.apache.camel.spi.ExecutorServiceManager;
+import org.apache.camel.support.resume.OffsetKeys;
+import org.apache.camel.support.resume.Offsets;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.DisabledOnOs;
+import org.junit.jupiter.api.condition.OS;
+import org.junit.jupiter.api.io.TempDir;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assumptions.assumeFalse;
+
+/**
+ * start() replaces the log of the previous run by a new log that holds the 
unconfirmed entries of the previous run. A
+ * start that fails (or a system that crashes) while it does so must not lose 
these entries: the next start replays
+ * them.
+ */
+class WriteAheadResumeStrategyStartFailureTest {
+
+    @TempDir
+    File testDir;
+
+    private final List<ScheduledExecutorService> executors = new ArrayList<>();
+
+    @AfterEach
+    void shutdownExecutors() {
+        executors.forEach(ScheduledExecutorService::shutdownNow);
+    }
+
+    /**
+     * A strategy whose flush task cannot be scheduled when rejectFlushTask is 
true (as when the executor is shut down):
+     * then start() fails after it read the log of the previous run
+     */
+    private WriteAheadResumeStrategy strategy(File logFile, ResumeStrategy 
delegate, boolean rejectFlushTask) {
+        WriteAheadResumeStrategy strategy = new WriteAheadResumeStrategy(
+                WriteAheadResumeStrategyConfigurationBuilder.newBuilder()
+                        
.withLogFile(logFile).withDelegateResumeStrategy(delegate).build(),
+                LogWriter.DEFAULT_CAPACITY);
+
+        ScheduledExecutorService executor = 
Executors.newSingleThreadScheduledExecutor();
+        executors.add(executor);
+        ScheduledExecutorService pool = (ScheduledExecutorService) 
Proxy.newProxyInstance(
+                getClass().getClassLoader(), new Class<?>[] { 
ScheduledExecutorService.class },
+                (proxy, method, args) -> {
+                    if (rejectFlushTask && 
"scheduleAtFixedRate".equals(method.getName())) {
+                        throw new RejectedExecutionException("the executor is 
shut down");
+                    }
+                    try {
+                        return method.invoke(executor, args);
+                    } catch (InvocationTargetException e) {
+                        throw e.getCause();
+                    }
+                });
+        ExecutorServiceManager executorServiceManager = 
(ExecutorServiceManager) Proxy.newProxyInstance(
+                getClass().getClassLoader(), new Class<?>[] { 
ExecutorServiceManager.class },
+                (proxy, method, args) -> 
"newScheduledThreadPool".equals(method.getName()) ? pool : null);
+        CamelContext camelContext = (CamelContext) Proxy.newProxyInstance(
+                getClass().getClassLoader(), new Class<?>[] { 
CamelContext.class },
+                (proxy, method, args) -> 
"getExecutorServiceManager".equals(method.getName())
+                        ? executorServiceManager : null);
+        strategy.setCamelContext(camelContext);
+        return strategy;
+    }
+
+    /**
+     * A run that appends the offset 1 of the key A, which the delegate never 
confirms, and stops
+     */
+    private File runWithAnUnconfirmedEntry() throws Exception {
+        return runWithAnUnconfirmedEntry(new File(testDir, "wal.data"));
+    }
+
+    private File runWithAnUnconfirmedEntry(File logFile) throws Exception {
+        WriteAheadResumeStrategy strategy
+                = strategy(logFile, new 
WriteAheadResumeStrategyRestartTest.NeverConfirmingDelegate(), false);
+        strategy.start();
+        strategy.loadCache();
+        strategy.updateLastOffset(OffsetKeys.of("A"), Offsets.of(1L));
+        strategy.stop();
+        assertEquals(List.of("A=1 NEW"), readLog(logFile));
+        return logFile;
+    }
+
+    private List<String> restart(File logFile, 
WriteAheadResumeStrategyRestartTest.Delegate delegate) throws Exception {
+        WriteAheadResumeStrategy strategy = strategy(logFile, delegate, false);
+        strategy.start();
+        strategy.loadCache();
+        // the new log takes new entries after the replayed one
+        strategy.updateLastOffset(OffsetKeys.of("B"), Offsets.of(1L));
+        strategy.stop();
+        return delegate.replayed;
+    }
+
+    /**
+     * Reads the log, as "key=value STATE" for each entry
+     */
+    private static List<String> readLog(File logFile) throws IOException {
+        WriteAheadResumeStrategyRestartTest.Adapter adapter = new 
WriteAheadResumeStrategyRestartTest.Adapter();
+        List<String> entries = new ArrayList<>();
+        try (LogReader reader = new LogReader(logFile)) {
+            PersistedLogEntry entry;
+            while ((entry = reader.readEntry()) != null) {
+                
entries.add(adapter.deserializeKey(ByteBuffer.wrap(entry.getKey())) + "="
+                            + 
adapter.deserializeValue(ByteBuffer.wrap(entry.getValue())) + " "
+                            + entry.getEntryState());
+            }
+        }
+        return entries;
+    }
+
+    @Test
+    void unconfirmedEntryIsReplayedAfterTheNextStart() throws Exception {
+        File logFile = runWithAnUnconfirmedEntry();
+
+        WriteAheadResumeStrategyRestartTest.Delegate delegate = new 
WriteAheadResumeStrategyRestartTest.Delegate();
+        assertEquals(List.of("A=1", "B=1"), restart(logFile, delegate));
+
+        // the delegate confirmed both in the log that replaced the previous 
one
+        assertEquals(List.of("A=1 PROCESSED", "B=1 PROCESSED"), 
readLog(logFile));
+        assertFalse(new File(testDir, "wal.data.tmp").exists(), "no temporary 
file is left");
+    }
+
+    @Test
+    void unconfirmedEntryIsReplayedAfterAStartThatFailedAfterReadingIt() 
throws Exception {
+        File logFile = runWithAnUnconfirmedEntry();
+
+        // start() reads A=1 as unconfirmed, then fails before the new log is 
supervised
+        WriteAheadResumeStrategy failing
+                = strategy(logFile, new 
WriteAheadResumeStrategyRestartTest.NeverConfirmingDelegate(), true);
+        assertThrows(RuntimeCamelException.class, failing::start);
+        assertEquals(List.of("A=1 NEW"), readLog(logFile), "the log still 
holds the unconfirmed entry");
+
+        WriteAheadResumeStrategyRestartTest.Delegate delegate = new 
WriteAheadResumeStrategyRestartTest.Delegate();
+        assertEquals(List.of("A=1", "B=1"), restart(logFile, delegate));
+        assertEquals(List.of("A=1 PROCESSED", "B=1 PROCESSED"), 
readLog(logFile));
+    }
+
+    @Test
+    void logIsRewrittenInPlaceWhenTheNewLogCannotReplaceIt() throws Exception {
+        File logFile = runWithAnUnconfirmedEntry();
+
+        // the temporary file of the new log cannot be created, so the log 
cannot be replaced atomically: start()
+        // rewrites it in place, as before, instead of failing
+        File blocked = new File(testDir, "wal.data.tmp");
+        Files.createDirectory(blocked.toPath());
+        WriteAheadResumeStrategy strategy
+                = strategy(logFile, new 
WriteAheadResumeStrategyRestartTest.NeverConfirmingDelegate(), false);
+        strategy.start();
+        assertEquals(List.of("A=1 NEW"), readLog(logFile), "the rewritten log 
holds the unconfirmed entry");
+        strategy.stop();
+        assertTrue(blocked.isDirectory(), "what has the name of the temporary 
file is not deleted");
+
+        WriteAheadResumeStrategyRestartTest.Delegate delegate = new 
WriteAheadResumeStrategyRestartTest.Delegate();
+        assertEquals(List.of("A=1", "B=1"), restart(logFile, delegate));
+        assertEquals(List.of("A=1 PROCESSED", "B=1 PROCESSED"), 
readLog(logFile));
+    }
+
+    @Test
+    void previousLogIsKeptWhenNeitherTheNewLogNorTheLogCanBeWritten() throws 
Exception {
+        File logFile = runWithAnUnconfirmedEntry();
+
+        // the temporary file cannot be created, and the log cannot be 
rewritten in place either: start() fails
+        File blocked = new File(testDir, "wal.data.tmp");
+        Files.createDirectory(blocked.toPath());
+        assertTrue(logFile.setWritable(false));
+        assumeFalse(Files.isWritable(logFile.toPath()), "the process can write 
to a read-only file (root)");
+        WriteAheadResumeStrategy failing
+                = strategy(logFile, new 
WriteAheadResumeStrategyRestartTest.NeverConfirmingDelegate(), false);
+        assertThrows(RuntimeCamelException.class, failing::start);
+        assertEquals(List.of("A=1 NEW"), readLog(logFile), "the log still 
holds the unconfirmed entry");
+
+        assertTrue(logFile.setWritable(true));
+        Files.delete(blocked.toPath());
+        WriteAheadResumeStrategyRestartTest.Delegate delegate = new 
WriteAheadResumeStrategyRestartTest.Delegate();
+        assertEquals(List.of("A=1", "B=1"), restart(logFile, delegate));
+    }
+
+    @Test
+    @DisabledOnOs(OS.WINDOWS)
+    void newLogKeepsThePermissionsOfThePreviousOne() throws Exception {
+        File logFile = runWithAnUnconfirmedEntry();
+        Files.setPosixFilePermissions(logFile.toPath(), 
PosixFilePermissions.fromString("rw-------"));
+
+        WriteAheadResumeStrategyRestartTest.Delegate delegate = new 
WriteAheadResumeStrategyRestartTest.Delegate();
+        assertEquals(List.of("A=1", "B=1"), restart(logFile, delegate));
+        assertEquals("rw-------", 
PosixFilePermissions.toString(Files.getPosixFilePermissions(logFile.toPath())));
+    }
+
+    @Test
+    @DisabledOnOs(OS.WINDOWS)
+    void newLogReplacesTheFileASymbolicLinkPointsTo() throws Exception {
+        Path data = Files.createDirectory(testDir.toPath().resolve("data"));
+        Path link = 
Files.createSymbolicLink(testDir.toPath().resolve("wal.data"), 
data.resolve("wal.data"));
+        File logFile = runWithAnUnconfirmedEntry(link.toFile());
+
+        WriteAheadResumeStrategyRestartTest.Delegate delegate = new 
WriteAheadResumeStrategyRestartTest.Delegate();
+        assertEquals(List.of("A=1", "B=1"), restart(logFile, delegate));
+        assertTrue(Files.isSymbolicLink(link), "the link is kept");
+        assertEquals(List.of("A=1 PROCESSED", "B=1 PROCESSED"), 
readLog(data.resolve("wal.data").toFile()));
+        assertFalse(Files.exists(data.resolve("wal.data.tmp")), "no temporary 
file is left");
+    }
+}
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 aa60b14f7473..a142a9de32c8 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
@@ -10171,6 +10171,17 @@ deserialize, is logged with a WARN and does not stop 
the start of the route. If
 incomplete (the JVM stopped while writing it) or invalid, the entries before 
it are replayed and a WARN is logged; the
 route still starts. A file that is not a log of this format is replaced by a 
new log, as before, with a WARN.
 
+When there are entries to keep, `start()` writes the new log with them to a 
file in the same directory, named as the
+log with the suffix `.tmp`, forces it to disk and then moves it atomically 
over the log. So a crash, a power loss or an
+error during `start()` does not lose them: until the move the previous log is 
unchanged, and after it the new log holds
+them on disk. Before, `start()` truncated the log first, and such a failure 
left an empty log. Where the log cannot be
+replaced that way (the process cannot create that file in the directory of the 
log, the log file is itself a mount
+point, such as a single file mounted into a container, or the file system 
cannot move it atomically), a WARN names the
+log and the reason, and `start()` truncates and rewrites the log in place, as 
before, but forces the entries to disk
+right after writing them. A crash during that rewrite can still lose them, as 
before; to avoid it, keep the log in a
+directory the process can write to. The new log gets the permissions of the 
previous one, not its owner or group.
+Without entries to keep, the log is truncated in place, as before.
+
 The log keeps 524,288 entries; after that it rolls over and holds the newest 
entries before the older ones, and the
 file does not say which are newer. So a log that holds that many entries is 
not replayed, as before: a WARN names the
 number of unconfirmed entries, which are discarded with the log. Replaying the 
wrong offset of a key would make the

Reply via email to