fix(storage): propagate buffered WAL failures before publication (#6533)

* fix(storage): propagate buffered WAL failures before publication

Rebase the focused WAL correction onto official main after the independent SQS rollback and snapshot fix merged as #7008. Retain buffered ordinary writes, atomic batch sync, safe rollback and exception propagation before publication.

* fix(storage): reject an unavailable buffered WAL path

Retain the existing unavailable-log and closed-writer fault controls while reconciling the signed WAL contribution with the merged SQS rollback dependency. No WAL behavior change from the previously validated contribution.
This commit is contained in:
Daniel Adler authored and GitHub committed 2026-10-30 14:02:11 -04:00
1 parent 71f18f5ff3
commit 5ba98ad7b1
4 files changed
+635 -101

No files matched your search

+23
View File
@@ -268,3 +268,26 @@ FLOCI_STORAGE_HOST_PERSISTENT_PATH=/absolute/host/path/data
`FLOCI_STORAGE_HOST_PERSISTENT_PATH` must be an absolute path (starting with `/`). Volume
names and relative paths are not supported and will be silently ignored, falling back to
named-volume mode.
### WAL write failures
Ordinary WAL puts, batches of puts, and deletions encode their records, then append and
flush through the buffered WAL writer before publishing the changed mappings in memory.
They do not force the log to disk on each change. A missing writer, encoding error, or
log write/flush failure is reported to the caller. A failed append is rolled back to its
previous log length. If rollback or the buffered writer cannot be trusted, further writes
are rejected until recovery rather than acknowledged only in memory.
Writes after a WAL backend has shut down are rejected as well; they cannot change the
acknowledged in-memory state or the closed log. Create a fresh `StorageFactory` to load
persisted state and resume writes.
The PUT and DELETE record formats are unchanged. `putAll` still writes separate PUT
records and is not a crash-atomic replacement operation; use `putAllAtomically` when the
whole replacement must replay together. Atomic batches retain their forced-log commit
boundary. Values already stored must not be mutated in place before a write, as with the
existing atomic-batch contract.
Flushing the writer does not establish a host-power-loss guarantee: snapshot replacement,
directory metadata and retiring the old log require their own durability protocol. Hybrid
storage retains its asynchronous flush policy, and DynamoDB uses a separate per-table
journal.
@@ -21,10 +21,12 @@ import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@@ -65,13 +67,25 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
private final TypeReference<Map<K, V>> typeReference;
private final ReentrantReadWriteLock compactionLock = new ReentrantReadWriteLock();
private final ScheduledExecutorService scheduler;
private final ChannelSync channelSync;
private volatile DataOutputStream walWriter;
// Set under the read lock by every mutation and cleared under the write lock by compaction,
// so an idle store does not rewrite its snapshot on every compaction tick.
private volatile IOException walFailure;
// Mutations and compaction hold the write lock; idle stores need no new snapshot.
private volatile boolean dirty;
@FunctionalInterface
interface ChannelSync {
void force(FileChannel channel) throws IOException;
}
public WalStorage(Path snapshotPath, Path walPath, TypeReference<Map<K, V>> typeReference,
long compactionIntervalMs) {
this(snapshotPath, walPath, typeReference, compactionIntervalMs, channel -> channel.force(true));
}
WalStorage(Path snapshotPath, Path walPath, TypeReference<Map<K, V>> typeReference,
long compactionIntervalMs, ChannelSync channelSync) {
this.channelSync = channelSync;
this.snapshotPath = snapshotPath;
this.walPath = walPath;
this.typeReference = typeReference;
@@ -90,32 +104,32 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
@Override
public void put(K key, V value) {
compactionLock.readLock().lock();
byte[] record = encodePuts(Map.of(key, value));
compactionLock.writeLock().lock();
try {
commitBufferedRecord(record);
store.put(key, value);
dirty = true;
appendPut(key, value);
} finally {
compactionLock.readLock().unlock();
compactionLock.writeLock().unlock();
}
}
/**
* Appends the whole batch as one contiguous run of WAL records with a single flush, so a
* batch costs one write instead of one per entry. An empty batch touches nothing.
*/
/** Encodes every entry before publishing or appending any of the batch. */
@Override
public void putAll(Map<K, V> entries) {
if (entries.isEmpty()) {
Map<K, V> replacements = Map.copyOf(entries);
if (replacements.isEmpty()) {
return;
}
compactionLock.readLock().lock();
byte[] records = encodePuts(replacements);
compactionLock.writeLock().lock();
try {
store.putAll(entries);
commitBufferedRecord(records);
store.putAll(replacements);
dirty = true;
appendPuts(entries);
} finally {
compactionLock.readLock().unlock();
compactionLock.writeLock().unlock();
}
}
@@ -153,44 +167,14 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
private void commitBatch(byte operation, byte[] payload, Map<K, V> replacements, Set<K> deletions) {
compactionLock.writeLock().lock();
try {
if (walWriter == null) {
throw new IllegalStateException("WAL writer is not open");
}
ConcurrentHashMap<K, V> candidate = new ConcurrentHashMap<>(store);
candidate.putAll(replacements);
candidate.keySet().removeAll(deletions);
walWriter.flush();
FileChannel channel = FileChannel.open(walPath, StandardOpenOption.WRITE);
try {
long offset = channel.size();
channel.position(offset);
ByteBuffer record = ByteBuffer.allocate(1 + Integer.BYTES + payload.length);
record.put(operation).putInt(payload.length).put(payload).flip();
try {
while (record.hasRemaining()) {
channel.write(record);
}
channel.force(true);
} catch (IOException exception) {
try {
channel.truncate(offset);
channel.force(true);
} catch (IOException rollbackFailure) {
exception.addSuppressed(rollbackFailure);
}
throw exception;
}
} finally {
try {
channel.close();
} catch (IOException exception) {
LOG.warnv(exception, "Failed to close atomic batch channel for {0}", walPath);
}
}
ByteBuffer record = ByteBuffer.allocate(1 + Integer.BYTES + payload.length);
record.put(operation).putInt(payload.length).put(payload).flip();
commitRecord(record);
store = candidate;
dirty = true;
} catch (IOException exception) {
throw new UncheckedIOException("Failed to commit atomic WAL batch to " + walPath, exception);
} finally {
compactionLock.writeLock().unlock();
}
@@ -203,13 +187,14 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
@Override
public void delete(K key) {
compactionLock.readLock().lock();
byte[] record = encodeDelete(Objects.requireNonNull(key));
compactionLock.writeLock().lock();
try {
commitBufferedRecord(record);
store.remove(key);
dirty = true;
appendDelete(key);
} finally {
compactionLock.readLock().unlock();
compactionLock.writeLock().unlock();
}
}
@@ -266,6 +251,7 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
Files.deleteIfExists(walPath);
Files.deleteIfExists(snapshotPath);
dirty = false;
walFailure = null;
} catch (IOException e) {
LOG.errorv(e, "Failed to delete WAL/snapshot files");
// A snapshot that survived must be overwritten by the next compaction.
@@ -315,7 +301,7 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
private void compact() {
compactionLock.writeLock().lock();
try {
if (!dirty) {
if (!dirty || walFailure != null) {
return;
}
StorageFiles.writeAtomically(snapshotPath, tempFile -> snapshotMapper.writeValue(tempFile.toFile(), store));
@@ -337,66 +323,142 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
}
}
private void appendPut(K key, V value) {
DataOutputStream out = walWriter;
if (out == null) return;
private void commitBufferedRecord(byte[] record) {
ensureWriterOpen();
long offset;
try {
byte[] keyBytes = walMapper.writeValueAsBytes(key);
byte[] valueBytes = walMapper.writeValueAsBytes(value);
synchronized (out) {
writePutRecord(out, keyBytes, valueBytes);
out.flush();
BasicFileAttributes attributes = Files.readAttributes(walPath, BasicFileAttributes.class);
if (!attributes.isRegularFile()) {
throw new IOException("WAL path is not a regular file: " + walPath);
}
} catch (IOException e) {
LOG.errorv(e, "Failed to append PUT WAL entry");
offset = attributes.size();
} catch (IOException exception) {
throw new UncheckedIOException("Failed to inspect WAL at " + walPath, exception);
}
DataOutputStream writer = walWriter;
try {
writer.write(record);
writer.flush();
} catch (IOException exception) {
rollbackBufferedRecord(writer, offset, exception);
throw new UncheckedIOException("Failed to append WAL record to " + walPath, exception);
}
}
private void appendPuts(Map<K, V> entries) {
DataOutputStream out = walWriter;
if (out == null) {
return;
private void rollbackBufferedRecord(DataOutputStream writer, long offset, IOException exception) {
walWriter = null;
try {
// Closing may flush pending bytes, so it must happen before truncating the failed append.
writer.close();
} catch (IOException closeFailure) {
addSuppressedFailure(exception, closeFailure);
walFailure = closeFailure;
}
try (FileChannel channel = FileChannel.open(walPath, StandardOpenOption.WRITE)) {
channel.truncate(offset);
} catch (IOException rollbackFailure) {
addSuppressedFailure(exception, rollbackFailure);
walFailure = rollbackFailure;
}
if (walFailure == null) {
try {
walWriter = newWalWriter();
} catch (IOException reopenFailure) {
addSuppressedFailure(exception, reopenFailure);
walFailure = reopenFailure;
}
}
}
private static void addSuppressedFailure(IOException exception, IOException additionalFailure) {
if (exception != additionalFailure) {
exception.addSuppressed(additionalFailure);
}
}
private void ensureWriterOpen() {
if (walFailure != null) {
throw new IllegalStateException("WAL recovery is required after an uncertain write", walFailure);
}
if (walWriter == null) {
throw new IllegalStateException("WAL writer is not open");
}
}
private void commitRecord(ByteBuffer record) {
ensureWriterOpen();
try {
walWriter.flush();
} catch (IOException exception) {
walFailure = exception;
closeWalWriter();
throw new UncheckedIOException("Failed to flush WAL writer at " + walPath, exception);
}
try {
// Encode the whole batch off the shared writer so the lock is held for one write.
FileChannel channel = FileChannel.open(walPath, StandardOpenOption.WRITE);
try {
long offset = channel.size();
channel.position(offset);
try {
while (record.hasRemaining()) {
channel.write(record);
}
channelSync.force(channel);
} catch (IOException exception) {
try {
channel.truncate(offset);
channelSync.force(channel);
} catch (IOException rollbackFailure) {
addSuppressedFailure(exception, rollbackFailure);
walFailure = rollbackFailure;
closeWalWriter();
}
throw exception;
}
} finally {
try {
channel.close();
} catch (IOException exception) {
LOG.warnv(exception, "Failed to close WAL commit channel for {0}", walPath);
}
}
} catch (IOException exception) {
throw new UncheckedIOException("Failed to commit WAL record to " + walPath, exception);
}
}
private byte[] encodePuts(Map<K, V> entries) {
try {
ByteArrayOutputStream batch = new ByteArrayOutputStream();
DataOutputStream records = new DataOutputStream(batch);
for (Map.Entry<K, V> entry : entries.entrySet()) {
writePutRecord(records, walMapper.writeValueAsBytes(entry.getKey()),
walMapper.writeValueAsBytes(entry.getValue()));
byte[] key = walMapper.writeValueAsBytes(entry.getKey());
byte[] value = walMapper.writeValueAsBytes(entry.getValue());
records.writeByte(OP_PUT);
records.writeInt(key.length);
records.write(key);
records.writeInt(value.length);
records.write(value);
}
records.flush();
synchronized (out) {
batch.writeTo(out);
out.flush();
}
} catch (IOException e) {
LOG.errorv(e, "Failed to append {0} PUT WAL entries", entries.size());
return batch.toByteArray();
} catch (IOException exception) {
throw new UncheckedIOException("Failed to encode PUT WAL entries", exception);
}
}
private static void writePutRecord(DataOutputStream out, byte[] keyBytes, byte[] valueBytes)
throws IOException {
out.writeByte(OP_PUT);
out.writeInt(keyBytes.length);
out.write(keyBytes);
out.writeInt(valueBytes.length);
out.write(valueBytes);
}
private void appendDelete(K key) {
DataOutputStream out = walWriter;
if (out == null) return;
private byte[] encodeDelete(K key) {
try {
byte[] keyBytes = walMapper.writeValueAsBytes(key);
synchronized (out) {
out.writeByte(OP_DELETE);
out.writeInt(keyBytes.length);
out.write(keyBytes);
out.flush();
}
} catch (IOException e) {
LOG.errorv(e, "Failed to append DELETE WAL entry");
byte[] encodedKey = walMapper.writeValueAsBytes(key);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
DataOutputStream record = new DataOutputStream(bytes);
record.writeByte(OP_DELETE);
record.writeInt(encodedKey.length);
record.write(encodedKey);
record.flush();
return bytes.toByteArray();
} catch (IOException exception) {
throw new UncheckedIOException("Failed to encode DELETE WAL entry", exception);
}
}
@@ -507,16 +569,22 @@ public class WalStorage<K, V> implements StorageBackend<K, V> {
}
private void openWalWriter() {
if (walFailure != null) {
return;
}
try {
Files.createDirectories(walPath.getParent());
walWriter = new DataOutputStream(
new BufferedOutputStream(Files.newOutputStream(walPath,
StandardOpenOption.CREATE, StandardOpenOption.APPEND)));
walWriter = newWalWriter();
} catch (IOException e) {
LOG.errorv(e, "Failed to open WAL writer at {0}", walPath);
}
}
private DataOutputStream newWalWriter() throws IOException {
Files.createDirectories(walPath.getParent());
return new DataOutputStream(new BufferedOutputStream(Files.newOutputStream(walPath,
StandardOpenOption.CREATE, StandardOpenOption.APPEND)));
}
private void closeWalWriter() {
if (walWriter != null) {
try {
@@ -14,6 +14,7 @@ import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
@@ -85,7 +86,8 @@ class StorageFactoryLifecycleTest {
assertTrue(Files.readString(tempDir.resolve("svc-snapshot.json")).contains("before"),
"final shutdown must flush the store into the snapshot");
long walSizeAfterShutdown = walSize();
backend.put("after", "v2");
assertThrows(IllegalStateException.class, () -> backend.put("after", "v2"));
assertEquals(Optional.empty(), backend.get("after"), "a rejected write must not change memory");
assertEquals(walSizeAfterShutdown, walSize(), "no WAL writer may be open after shutdown");
}
@@ -100,7 +102,8 @@ class StorageFactoryLifecycleTest {
assertDoesNotThrow(factory::shutdownAll);
long walSizeAfterShutdown = walSize();
backend.put("after", "v2");
assertThrows(IllegalStateException.class, () -> backend.put("after", "v2"));
assertEquals(Optional.empty(), backend.get("after"), "a rejected write must not change memory");
assertEquals(walSizeAfterShutdown, walSize(), "no WAL writer may be open after shutdown");
StorageFactory reloaded = newFactory("wal");
@@ -0,0 +1,440 @@
package io.github.hectorvent.floci.core.storage;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class WalStorageWriteFailureTest {
private static final TypeReference<Map<String, String>> STRINGS = new TypeReference<>() {};
@TempDir
Path directory;
enum Mutation { PUT, PUT_ALL, DELETE }
@ParameterizedTest
@EnumSource(Mutation.class)
void aMissingWriterRejectsMutations(Mutation mutation) {
WalStorage<String, String> store = store();
try {
assertThrows(IllegalStateException.class, () -> mutate(store, mutation));
assertTrue(store.keys().isEmpty());
} finally {
store.shutdown();
}
}
@ParameterizedTest
@EnumSource(Mutation.class)
void aWriterFlushFailureDoesNotPublishTheMutation(Mutation mutation) throws Exception {
WalStorage<String, String> store = store();
store.load();
try {
store.put("keep", "old");
replaceWriter(store, new DataOutputStream(OutputStream.nullOutputStream()) {
@Override
public void flush() throws IOException {
throw new IOException("synthetic flush failure");
}
});
assertThrows(UncheckedIOException.class, () -> mutate(store, mutation));
assertOldValue(store);
} finally {
store.shutdown();
}
}
@ParameterizedTest
@EnumSource(Mutation.class)
void anUnwritableLogDoesNotPublishAndCanBeRetried(Mutation mutation) throws IOException {
WalStorage<String, String> store = store();
store.load();
Path log = directory.resolve("data.wal");
Path savedLog = directory.resolve("retained.wal");
try {
store.put("keep", "old");
Files.move(log, savedLog);
Files.createDirectory(log);
try {
assertThrows(UncheckedIOException.class, () -> mutate(store, mutation));
assertOldValue(store);
} finally {
Files.delete(log);
Files.move(savedLog, log);
}
mutate(store, mutation);
Map<String, String> replayed = WalStorage.readContents(directory.resolve("snapshot.json"), log, STRINGS);
if (mutation == Mutation.DELETE) {
assertTrue(replayed.isEmpty());
} else {
assertEquals("new", replayed.get("keep"));
}
} finally {
store.shutdown();
}
}
@ParameterizedTest
@EnumSource(Mutation.class)
void aClosedWriterDoesNotPublishAndCanBeRetried(Mutation mutation) throws Exception {
WalStorage<String, String> store = store();
store.load();
Path log = directory.resolve("data.wal");
try {
store.put("keep", "old");
currentWriter(store).close();
assertThrows(UncheckedIOException.class, () -> mutate(store, mutation));
assertOldValue(store);
mutate(store, mutation);
Map<String, String> replayed = WalStorage.readContents(directory.resolve("snapshot.json"), log, STRINGS);
if (mutation == Mutation.DELETE) {
assertTrue(replayed.isEmpty());
} else {
assertEquals("new", replayed.get("keep"));
}
} finally {
store.shutdown();
}
}
@Test
void aFailedBufferedRollbackRejectsLaterWritesAndPreservesTheRecoveryLog() throws Exception {
WalStorage<String, String> store = store();
store.load();
Path log = directory.resolve("data.wal");
Path retained = directory.resolve("retained.wal");
try {
store.put("keep", "old");
byte[] committedLog = Files.readAllBytes(log);
replaceWriter(store, new DataOutputStream(OutputStream.nullOutputStream()) {
@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
Files.move(log, retained);
Files.createDirectory(log);
throw new IOException("synthetic write failure with unavailable rollback path");
}
});
UncheckedIOException failure = assertThrows(UncheckedIOException.class, () -> store.put("keep", "new"));
assertEquals(1, failure.getCause().getSuppressed().length);
assertOldValue(store);
assertThrows(IllegalStateException.class, () -> store.put("later", "unsafe"));
store.flush();
assertTrue(Files.notExists(directory.resolve("snapshot.json")));
assertArrayEquals(committedLog, Files.readAllBytes(retained));
} finally {
store.shutdown();
}
}
@Test
void aRepeatedWriterExceptionStillPropagatesTheOriginalFailure() throws Exception {
WalStorage<String, String> store = store();
store.load();
IOException original = new IOException("synthetic repeated writer failure");
try {
store.put("keep", "old");
replaceWriter(store, new DataOutputStream(OutputStream.nullOutputStream()) {
@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
throw original;
}
@Override
public void close() throws IOException {
throw original;
}
});
UncheckedIOException failure = assertThrows(UncheckedIOException.class, () -> store.put("keep", "new"));
assertSame(original, failure.getCause());
assertOldValue(store);
assertThrows(IllegalStateException.class, () -> store.put("later", "unsafe"));
} finally {
store.shutdown();
}
}
@Test
void anUnserializableValueIsNotPublished() {
WalStorage<String, Object> store = new WalStorage<>(directory.resolve("snapshot.json"),
directory.resolve("data.wal"), new TypeReference<>() {}, Long.MAX_VALUE);
store.load();
try {
assertThrows(UncheckedIOException.class, () -> store.put("bad", new BrokenValue()));
assertTrue(store.keys().isEmpty());
} finally {
store.shutdown();
}
}
@Test
void anUnserializableBatchPublishesNoneOfItsValues() {
WalStorage<String, Object> store = new WalStorage<>(directory.resolve("snapshot.json"),
directory.resolve("data.wal"), new TypeReference<>() {}, Long.MAX_VALUE);
store.load();
try {
store.put("keep", "old");
assertThrows(UncheckedIOException.class,
() -> store.putAll(Map.of("keep", "new", "bad", new BrokenValue())));
assertEquals("old", store.get("keep").orElseThrow());
assertTrue(store.get("bad").isEmpty());
} finally {
store.shutdown();
}
}
@Test
void ordinaryWritesKeepTheLegacyRecordLayout() throws IOException {
WalStorage<String, String> store = store();
store.load();
try {
store.put("a", "1");
store.putAll(Map.of("b", "2", "c", "3"));
store.delete("a");
List<Integer> operations = new ArrayList<>();
try (DataInputStream input = new DataInputStream(Files.newInputStream(directory.resolve("data.wal")))) {
while (input.available() > 0) {
int operation = input.readUnsignedByte();
operations.add(operation);
input.skipNBytes(input.readInt());
if (operation == 1) {
input.skipNBytes(input.readInt());
}
}
}
assertEquals(List.of(1, 1, 1, 2), operations);
assertEquals(Map.of("b", "2", "c", "3"),
WalStorage.readContents(directory.resolve("snapshot.json"), directory.resolve("data.wal"), STRINGS));
} finally {
store.shutdown();
}
}
@ParameterizedTest
@EnumSource(Mutation.class)
void aPartialBufferedWriteRollsBackAndAllowsARetry(Mutation mutation) throws Exception {
assertBufferedFailureRollsBack(mutation, false);
}
@ParameterizedTest
@EnumSource(Mutation.class)
void aFlushFailureRollsBackAndAllowsARetry(Mutation mutation) throws Exception {
assertBufferedFailureRollsBack(mutation, true);
}
private void assertBufferedFailureRollsBack(Mutation mutation, boolean failFlush) throws Exception {
WalStorage<String, String> store = store();
store.load();
Path log = directory.resolve("data.wal");
try {
store.put("keep", "old");
byte[] committedLog = Files.readAllBytes(log);
AtomicBoolean failNext = new AtomicBoolean(true);
OutputStream output = Files.newOutputStream(log, StandardOpenOption.APPEND);
replaceWriter(store, new DataOutputStream(new BufferedOutputStream(new OutputStream() {
@Override
public void write(int value) throws IOException {
output.write(value);
}
@Override
public void write(byte[] bytes, int offset, int length) throws IOException {
if (!failFlush && failNext.getAndSet(false)) {
output.write(bytes, offset, Math.min(3, length));
throw new IOException("synthetic partial buffered write failure");
}
output.write(bytes, offset, length);
}
@Override
public void flush() throws IOException {
assertOldValue(store);
output.flush();
if (failFlush && failNext.getAndSet(false)) {
throw new IOException("synthetic flush failure after writing the record");
}
}
@Override
public void close() throws IOException {
output.close();
}
})));
UncheckedIOException failure = assertThrows(UncheckedIOException.class, () -> mutate(store, mutation));
assertTrue(failure.getCause().getMessage().contains("synthetic"));
assertOldValue(store);
assertArrayEquals(committedLog, Files.readAllBytes(log));
assertEquals(Map.of("keep", "old"),
WalStorage.readContents(directory.resolve("snapshot.json"), log, STRINGS));
mutate(store, mutation);
Map<String, String> replayed = WalStorage.readContents(directory.resolve("snapshot.json"), log, STRINGS);
if (mutation == Mutation.DELETE) {
assertTrue(replayed.isEmpty());
} else {
assertEquals("new", replayed.get("keep"));
}
} finally {
store.shutdown();
}
}
enum AtomicMutation { PUT_ALL, DELETE_ALL }
@ParameterizedTest
@EnumSource(AtomicMutation.class)
void aFailedAtomicSyncRollsBackTheLogAndAllowsARetry(AtomicMutation mutation) throws IOException {
AtomicBoolean failNext = new AtomicBoolean();
WalStorage<String, String> store = new WalStorage<>(directory.resolve("snapshot.json"),
directory.resolve("data.wal"), STRINGS, Long.MAX_VALUE, channel -> {
if (failNext.getAndSet(false)) {
throw new IOException("synthetic sync failure");
}
channel.force(true);
});
store.load();
try {
store.put("keep", "old");
long committedLength = Files.size(directory.resolve("data.wal"));
failNext.set(true);
assertThrows(UncheckedIOException.class, () -> mutateAtomically(store, mutation));
assertOldValue(store);
assertEquals(committedLength, Files.size(directory.resolve("data.wal")));
assertEquals(Map.of("keep", "old"), WalStorage.readContents(directory.resolve("snapshot.json"),
directory.resolve("data.wal"), STRINGS));
mutateAtomically(store, mutation);
Map<String, String> replayed = WalStorage.readContents(directory.resolve("snapshot.json"),
directory.resolve("data.wal"), STRINGS);
if (mutation == AtomicMutation.DELETE_ALL) {
assertTrue(replayed.isEmpty());
} else {
assertEquals("new", replayed.get("keep"));
}
} finally {
store.shutdown();
}
}
@Test
void aFailedRollbackRejectsLaterWritesAndPreservesTheRecoveryLog() throws IOException {
AtomicBoolean failSync = new AtomicBoolean();
WalStorage<String, String> store = new WalStorage<>(directory.resolve("snapshot.json"),
directory.resolve("data.wal"), STRINGS, Long.MAX_VALUE, channel -> {
if (failSync.get()) {
throw new IOException("synthetic disk failure during sync and rollback");
}
channel.force(true);
});
store.load();
try {
store.put("keep", "old");
byte[] committedLog = Files.readAllBytes(directory.resolve("data.wal"));
failSync.set(true);
UncheckedIOException failure = assertThrows(UncheckedIOException.class,
() -> store.putAllAtomically(Map.of("keep", "new")));
assertEquals(1, failure.getCause().getSuppressed().length);
assertOldValue(store);
assertThrows(IllegalStateException.class, () -> store.put("later", "unsafe"));
store.flush();
assertArrayEquals(committedLog, Files.readAllBytes(directory.resolve("data.wal")));
assertTrue(Files.notExists(directory.resolve("snapshot.json")));
} finally {
store.shutdown();
}
}
@Test
void ordinaryWritesReuseTheBufferedWriterWhileAtomicBatchesForceTheLog() throws Exception {
AtomicInteger syncs = new AtomicInteger();
WalStorage<String, String> store = new WalStorage<>(directory.resolve("snapshot.json"),
directory.resolve("data.wal"), STRINGS, Long.MAX_VALUE, channel -> {
channel.force(true);
syncs.incrementAndGet();
});
store.load();
try {
DataOutputStream writer = currentWriter(store);
store.put("keep", "old");
assertEquals(0, syncs.get());
store.putAll(Map.of("keep", "new", "added", "value"));
assertEquals(0, syncs.get());
store.delete("added");
assertEquals(0, syncs.get());
assertSame(writer, currentWriter(store));
store.putAllAtomically(Map.of("batch", "value"));
assertEquals(1, syncs.get());
store.deleteAllAtomically(Set.of("batch"));
assertEquals(2, syncs.get());
} finally {
store.shutdown();
}
}
private void mutateAtomically(WalStorage<String, String> store, AtomicMutation mutation) {
switch (mutation) {
case PUT_ALL -> store.putAllAtomically(Map.of("keep", "new", "added", "value"));
case DELETE_ALL -> store.deleteAllAtomically(Set.of("keep"));
}
}
private WalStorage<String, String> store() {
return new WalStorage<>(directory.resolve("snapshot.json"), directory.resolve("data.wal"),
STRINGS, Long.MAX_VALUE);
}
private void mutate(WalStorage<String, String> store, Mutation mutation) {
switch (mutation) {
case PUT -> store.put("keep", "new");
case PUT_ALL -> store.putAll(Map.of("keep", "new", "added", "value"));
case DELETE -> store.delete("keep");
}
}
private void assertOldValue(WalStorage<String, String> store) {
assertEquals("old", store.get("keep").orElseThrow());
assertTrue(store.get("added").isEmpty());
}
private DataOutputStream currentWriter(WalStorage<?, ?> store) throws Exception {
Field field = WalStorage.class.getDeclaredField("walWriter");
field.setAccessible(true);
return (DataOutputStream) field.get(store);
}
private void replaceWriter(WalStorage<?, ?> store, DataOutputStream replacement) throws Exception {
Field field = WalStorage.class.getDeclaredField("walWriter");
field.setAccessible(true);
((DataOutputStream) field.get(store)).close();
field.set(store, replacement);
}
public static class BrokenValue {
public String getValue() {
throw new IllegalStateException("synthetic serialization failure");
}
}
}