Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,46 @@ public ByteBuf getEntry(long ledgerId, long entryId) throws IOException, BookieE

@Override
public long getLastAddConfirmed(long ledgerId) throws IOException {
return interleavedLedgerStorage.getLastAddConfirmed(ledgerId);
LedgerCache ledgerCache = interleavedLedgerStorage.getLedgerCache();
// Throws NoLedgerException for unknown or deleted ledgers. An evicted FileInfo
// reloads from its index file without a LAC, so this returns null instead.
Long cachedLac = ledgerCache.getLastAddConfirmed(ledgerId);
if (cachedLac != null) {
return cachedLac;
}

Long memTableLac = lastAddConfirmedFromMemTable(ledgerId);
if (memTableLac != null) {
return ledgerCache.updateLastAddConfirmed(ledgerId, memTableLac);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Related sibling: waitForLastAddConfirmedUpdate (just below, unchanged) still only looks at the FileInfo LAC. After eviction with unflushed entries 0-2 (memtable LAC 1), the first long poll, before any getLastAddConfirmed call, returns true and parks, even though previousLAC = -1 is already behind the real LAC:

testAdvFirstLongPollAfterEvictionDoesNotPark:
  memtable LAC is 1 > previousLAC -1, so the long poll must not park

The control (same poll after a getLastAddConfirmed call has run this write-back) returns false, so the write-back works; it is just only triggered by a LAC read. This existed before the PR and is bounded by the poll timeout, so it is a nit. The PR's own long-poll assertion runs after getLastAddConfirmed, which is why it is not caught. A cheap fix is to call getLastAddConfirmed(ledgerId) at the start of waitForLastAddConfirmedUpdate.

}

try {
return interleavedLedgerStorage.getLastAddConfirmed(ledgerId);
} catch (Bookie.NoLedgerException | Bookie.NoEntryException e) {
// An entry may have been added after the memtable check above.
Long latestMemTableLac = lastAddConfirmedFromMemTable(ledgerId);
if (latestMemTableLac == null) {
return interleavedLedgerStorage.getLastAddConfirmed(ledgerId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cost nit: for a ledger with no entries anywhere (e.g. right after setMasterKey, before the first write), the first interleavedLedgerStorage.getLastAddConfirmed throws, the memtable recheck finds nothing, and this line runs the same index lookup a second time, which throws again. The caller sees the same exception as before, but the index is queried twice per call.

A call counter shows it: with a spied InterleavedLedgerStorage, verify(u, times(1)).getLastAddConfirmed(ledgerId) fails on a new empty ledger. The control (flushed entries, FileInfo evicted) makes exactly one lookup and passes. Suggest rethrowing the original exception when the recheck is also empty, instead of calling the index again.

}
return ledgerCache.updateLastAddConfirmed(ledgerId, latestMemTableLac);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test gap: nothing reaches this line. I replaced it with return -99L; and the whole SortedLedgerStorageTest class (including the new tests) still passed. testGetLastAddConfirmedRetriesAfterIndexMiss only gets here with an empty memtable, so it takes the line above. A test where the memtable gets its first entry between the first memtable check and the index miss (e.g. a spied memtable whose first getLastEntry returns null and whose second returns an entry) would cover it.

Same for the readableBytes() < 3 * Long.BYTES guard in lastAddConfirmedFromMemTable: weakening it to < 0 also passes every test, because no test adds a short entry to the memtable.

}
}

private Long lastAddConfirmedFromMemTable(long ledgerId) throws IOException {
EntryKeyValue kv = memTable.getLastEntry(ledgerId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getLastEntry can return a lower entry than the ledger's highest when a flush is in progress. It takes kvmap.floorKey(...) and only falls back to snapshot if the ledger is absent from kvmap.

Scenario: entries 10-13 (LAC 12) are in the snapshot, then a lower entry id (entry 3, LAC 2, e.g. re-replicated by auto-recovery) lands in the live map. With the FileInfo evicted, getLastAddConfirmed returns 2 and writes 2 back to the cache, instead of 12.

Reproduced against this head (both parameterizations of SortedLedgerStorageTest):

sortedLedgerStorage.setCheckpointSource(CheckpointSource.DEFAULT);   // so snapshot() really snapshots
sortedLedgerStorage.setMasterKey(ledgerId, key);
for (long e = 10; e <= 13; e++) add(ledgerId, e, /*lac*/ e - 1);
assertNotNull(sortedLedgerStorage.memTable.snapshot());
add(ledgerId, 3, 2);
evictFileInfo(ledgerId);
assertEquals(12L, sortedLedgerStorage.getLastAddConfirmed(ledgerId));
// expected:<12> but was:<2>

The control without the late entry 3 passes. The shared getLastEntry is not changed by this PR, but this method now depends on it. Smallest fix: in getLastEntry (or here), compare the floor entries of both kvmap and snapshot and take the one with the larger entry id for this ledger.

if (kv == null) {
return null;
}
ByteBuf entry = kv.getValueAsByteBuffer();
try {
if (entry.readableBytes() < 3 * Long.BYTES) {
return null;
}
entry.skipBytes(2 * Long.BYTES);
return entry.readLong();
} finally {
entry.release();
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,20 @@
import static org.apache.bookkeeper.bookie.BookKeeperServerStats.BOOKIE_SCOPE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledByteBufAllocator;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.PrimitiveIterator.OfLong;
Expand All @@ -41,7 +48,9 @@
import org.apache.bookkeeper.test.TestStatsProvider;
import org.apache.bookkeeper.util.DiskChecker;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

Expand All @@ -56,6 +65,9 @@ public class SortedLedgerStorageTest {
LedgerDirsManager ledgerDirsManager;
SortedLedgerStorage sortedLedgerStorage = new SortedLedgerStorage();

@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();

final long numWrites = 2000;
final long moreNumOfWrites = 3000;
final long entriesPerWrite = 2;
Expand Down Expand Up @@ -191,4 +203,231 @@ public void testGetListOfEntriesOfLedgerAfterFlush() throws IOException {
}));
}
}

/**
* A newer memtable LAC must remain visible after an evicted FileInfo is flushed.
*/
@Test
public void testGetLastAddConfirmedAfterFileInfoEviction() throws Exception {
File tmpDir = File.createTempFile("bkLac", ".dir");
tmpDir.delete();
tmpDir.mkdir();
BookieImpl.checkDirectoryStructure(BookieImpl.getCurrentDirectory(tmpDir));

ServerConfiguration limited = TestBKConfiguration.newServerConfiguration();
limited.setEntryLogPerLedgerEnabled(conf.isEntryLogPerLedgerEnabled());
limited.setLedgerDirNames(new String[] { tmpDir.toString() });
limited.setOpenFileLimit(2);
limited.setNumAddWorkerThreads(1);
limited.setNumReadWorkerThreads(1);
limited.setSkipListSizeLimit(64 * 1024 * 1024);

LedgerDirsManager dirs = new LedgerDirsManager(limited, limited.getLedgerDirs(),
new DiskChecker(limited.getDiskUsageThreshold(), limited.getDiskUsageWarnThreshold()));
InterleavedLedgerStorage underlying = new InterleavedLedgerStorage();
SortedLedgerStorage storage = new SortedLedgerStorage(underlying);
storage.initialize(limited, null, dirs, dirs,
statsProvider.getStatsLogger(BOOKIE_SCOPE), UnpooledByteBufAllocator.DEFAULT);
storage.setCheckpointSource(CheckpointSource.DEFAULT);
storage.setCheckpointer(checkpointer);
try {
long ledgerId = 0L;
storage.setMasterKey(ledgerId, ("ledger-" + ledgerId).getBytes());
for (long entryId = 0; entryId < 5; entryId++) {
ByteBuf entry = Unpooled.buffer(128);
try {
entry.writeLong(ledgerId);
entry.writeLong(entryId);
entry.writeLong(entryId - 1);
entry.writeByte(1);
storage.addEntry(entry);
} finally {
entry.release();
}
}
storage.flush();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This flush() doesn't flush the memtable. In this class, checkpointSource.newCheckpoint() returns Checkpoint.MAX. EntryMemTable#snapshot(Checkpoint.MAX) only takes a snapshot when kvmap.cp.compareTo(MAX) < 0, which is never true for MAX.

I checked that entry 0 is still in storage.memTable afterwards. So the next assertion runs the memtable path again, not the post-flush index path.

Using CheckpointSource.DEFAULT (which returns Checkpoint.MIN) for this storage, and asserting storage.memTable.isEmpty() after the flush, would make it test what the message says. The current code does return the right LAC from the index after a real flush.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since entries 0–4 are flushed here, the index lookup in getLastAddConfirmed succeeds (it returns 3), so this test only runs the try branch. The catch branch is the fix for #4900 itself: the index throws for an evicted ledger with nothing flushed. That branch isn't covered any more. The earlier version of this test was replaced, and testGetLastAddConfirmedRetriesAfterIndexMiss only reaches that branch with an empty memtable.

I checked locally with two changes to SortedLedgerStorage#getLastAddConfirmed. All 8 tests in this class still pass with either one:

Removing the write-back in the try branch does fail this test, so it's a good guard for the partially flushed case.

Could you keep this test and add a fully unflushed case next to it? With the same setup:

  1. Add entries 0–2 without flushing.
  2. Evict with the same invalidate calls.
  3. Assert LAC 1.
  4. Assert waitForLastAddConfirmedUpdate(ledgerId, 0, watcher) returns false (the write-back reached the cache).
  5. Call flush(), assert the memtable is empty, and assert LAC 1 again.

In my local checks, assertions like these fail under both changes above.


for (long entryId = 5; entryId < 10; entryId++) {
ByteBuf entry = Unpooled.buffer(128);
try {
entry.writeLong(ledgerId);
entry.writeLong(entryId);
entry.writeLong(entryId - 1);
entry.writeByte(1);
storage.addEntry(entry);
} finally {
entry.release();
}
}
LedgerCacheImpl ledgerCache = (LedgerCacheImpl) underlying.ledgerCache;
IndexPersistenceMgr indexPersistenceManager = ledgerCache.getIndexPersistenceManager();
indexPersistenceManager.readFileInfoCache.invalidate(ledgerId);
indexPersistenceManager.writeFileInfoCache.invalidate(ledgerId);
indexPersistenceManager.readFileInfoCache.cleanUp();
indexPersistenceManager.writeFileInfoCache.cleanUp();

assertEquals("LAC of an evicted ledger must include newer memtable entries",
8L, storage.getLastAddConfirmed(ledgerId));
storage.flush();
assertTrue("memtable must be empty after a real flush", storage.memTable.isEmpty());
assertEquals("LAC must not move backwards after the memtable is flushed",
8L, storage.getLastAddConfirmed(ledgerId));
assertThrows(Bookie.NoLedgerException.class, () -> storage.getLastAddConfirmed(9_999L));
} finally {
storage.shutdown();
}
}

/**
* An unflushed LAC must be written back to the ledger cache after FileInfo eviction.
*/
@Test
public void testGetLastAddConfirmedAfterUnflushedFileInfoEviction() throws Exception {
File tmpDir = temporaryFolder.newFolder("bkLacUnflushed");
BookieImpl.checkDirectoryStructure(BookieImpl.getCurrentDirectory(tmpDir));

ServerConfiguration limited = TestBKConfiguration.newServerConfiguration();
limited.setEntryLogPerLedgerEnabled(conf.isEntryLogPerLedgerEnabled());
limited.setLedgerDirNames(new String[] { tmpDir.toString() });
limited.setOpenFileLimit(2);
limited.setNumAddWorkerThreads(1);
limited.setNumReadWorkerThreads(1);
limited.setSkipListSizeLimit(64 * 1024 * 1024);

LedgerDirsManager dirs = new LedgerDirsManager(limited, limited.getLedgerDirs(),
new DiskChecker(limited.getDiskUsageThreshold(), limited.getDiskUsageWarnThreshold()));
InterleavedLedgerStorage underlying = new InterleavedLedgerStorage();
SortedLedgerStorage storage = new SortedLedgerStorage(underlying);
boolean initialized = false;
try {
storage.initialize(limited, null, dirs, dirs,
statsProvider.getStatsLogger(BOOKIE_SCOPE), UnpooledByteBufAllocator.DEFAULT);
initialized = true;
storage.setCheckpointSource(CheckpointSource.DEFAULT);
storage.setCheckpointer(checkpointer);
long ledgerId = 0L;
storage.setMasterKey(ledgerId, ("ledger-" + ledgerId).getBytes());
for (long entryId = 0; entryId < 3; entryId++) {
ByteBuf entry = Unpooled.buffer(128);
try {
entry.writeLong(ledgerId);
entry.writeLong(entryId);
entry.writeLong(entryId - 1);
entry.writeByte(1);
storage.addEntry(entry);
} finally {
entry.release();
}
}
LedgerCacheImpl ledgerCache = (LedgerCacheImpl) underlying.ledgerCache;
IndexPersistenceMgr indexPersistenceManager = ledgerCache.getIndexPersistenceManager();
indexPersistenceManager.readFileInfoCache.invalidate(ledgerId);
indexPersistenceManager.writeFileInfoCache.invalidate(ledgerId);
indexPersistenceManager.readFileInfoCache.cleanUp();
indexPersistenceManager.writeFileInfoCache.cleanUp();

assertEquals("LAC must include unflushed memtable entries", 1L, storage.getLastAddConfirmed(ledgerId));
assertFalse("LAC write-back must make the update immediately visible to long polls",
storage.waitForLastAddConfirmedUpdate(ledgerId, 0L, notification -> { }));
storage.flush();
assertTrue("memtable must be empty after a real flush", storage.memTable.isEmpty());
assertEquals("LAC must remain visible after the memtable is flushed",
1L, storage.getLastAddConfirmed(ledgerId));
} finally {
if (initialized) {
storage.shutdown();
}
}
}

@Test
public void testGetLastAddConfirmedRetriesAfterIndexMiss() throws Exception {
InterleavedLedgerStorage underlying = mock(InterleavedLedgerStorage.class);
LedgerCache ledgerCache = mock(LedgerCache.class);
when(underlying.getLedgerCache()).thenReturn(ledgerCache);
when(ledgerCache.getLastAddConfirmed(0L)).thenReturn(null);
when(underlying.getLastAddConfirmed(0L))
.thenThrow(new Bookie.NoEntryException(0L, -1L))
.thenReturn(1L);
SortedLedgerStorage storage = new SortedLedgerStorage(underlying);
storage.initialize(conf, null, ledgerDirsManager, ledgerDirsManager,
statsProvider.getStatsLogger(BOOKIE_SCOPE), UnpooledByteBufAllocator.DEFAULT);
storage.setCheckpointSource(checkpointSource);
storage.setCheckpointer(checkpointer);
try {
assertEquals(1L, storage.getLastAddConfirmed(0L));
verify(underlying, times(2)).getLastAddConfirmed(0L);
verify(underlying, times(0)).ledgerExists(0L);
} finally {
storage.shutdown();
}
}

@Test
public void testGetLastAddConfirmedUsesCachedValueBeforeMemTable() throws Exception {
InterleavedLedgerStorage underlying = mock(InterleavedLedgerStorage.class);
LedgerCache ledgerCache = mock(LedgerCache.class);
when(underlying.getLedgerCache()).thenReturn(ledgerCache);
when(ledgerCache.getLastAddConfirmed(0L)).thenReturn(8L);
SortedLedgerStorage storage = new SortedLedgerStorage(underlying);
storage.initialize(conf, null, ledgerDirsManager, ledgerDirsManager,
statsProvider.getStatsLogger(BOOKIE_SCOPE), UnpooledByteBufAllocator.DEFAULT);
storage.setCheckpointSource(checkpointSource);
storage.setCheckpointer(checkpointer);
EntryMemTable memTable = spy(storage.memTable);
storage.memTable = memTable;
try {
assertEquals(8L, storage.getLastAddConfirmed(0L));
verify(memTable, times(0)).getLastEntry(0L);
verify(underlying, times(0)).getLastAddConfirmed(0L);
verify(underlying, times(0)).ledgerExists(0L);
} finally {
storage.shutdown();
}
}

@Test
public void testGetLastAddConfirmedFallsBackToMemTableWhenCacheMisses() throws Exception {
InterleavedLedgerStorage underlying = mock(InterleavedLedgerStorage.class);
LedgerCache ledgerCache = mock(LedgerCache.class);
when(underlying.getLedgerCache()).thenReturn(ledgerCache);
when(ledgerCache.getLastAddConfirmed(0L)).thenReturn(null);
when(ledgerCache.updateLastAddConfirmed(0L, 8L)).thenReturn(8L);
SortedLedgerStorage storage = new SortedLedgerStorage(underlying);
storage.initialize(conf, null, ledgerDirsManager, ledgerDirsManager,
statsProvider.getStatsLogger(BOOKIE_SCOPE), UnpooledByteBufAllocator.DEFAULT);
storage.setCheckpointSource(checkpointSource);
storage.setCheckpointer(checkpointer);
try {
ByteBuffer entry = ByteBuffer.allocate(3 * Long.BYTES);
entry.putLong(0L).putLong(9L).putLong(8L).flip();
storage.memTable.addEntry(0L, 9L, entry, storage);

assertEquals(8L, storage.getLastAddConfirmed(0L));
verify(ledgerCache).updateLastAddConfirmed(0L, 8L);
verify(underlying, times(0)).getLastAddConfirmed(0L);
verify(underlying, times(0)).ledgerExists(0L);
} finally {
storage.shutdown();
}
}

@Test
public void testGetLastAddConfirmedDoesNotReadDeletedLedgerFromMemTable() throws Exception {
long ledgerId = 0L;
sortedLedgerStorage.setMasterKey(ledgerId, ("ledger-" + ledgerId).getBytes());
ByteBuf entry = Unpooled.buffer(128);
entry.writeLong(ledgerId);
entry.writeLong(0L);
entry.writeLong(-1L);
entry.writeByte(1);
try {
sortedLedgerStorage.addEntry(entry);
sortedLedgerStorage.deleteLedger(ledgerId);
assertThrows(Bookie.NoLedgerException.class,
() -> sortedLedgerStorage.getLastAddConfirmed(ledgerId));
} finally {
entry.release();
}
}
}