Skip to content

Commit 14157c8

Browse files
authored
Harden periodically check to avoid endless flush loop (#29125)
In #28350, we fixed an endless flushing loop which may happen on replicas by tightening the relation between the flush action and the periodically flush condition. 1. The periodically flush condition is enabled only if it is disabled after a flush. 2. If the periodically flush condition is enabled then a flush will actually happen regardless of Lucene state. (1) and (2) guarantee that a flushing loop will be terminated. Sadly, the condition 1 can be violated in edge cases as we used two different algorithms to evaluate the current and future uncommitted translog size. - We use method `uncommittedSizeInBytes` to calculate current uncommitted size. It is the sum of translogs whose generation at least the minGen (determined by a given seqno). We pick a continuous range of translogs since the minGen to evaluate the current uncommitted size. - We use method `sizeOfGensAboveSeqNoInBytes` to calculate the future uncommitted size. It is the sum of translogs whose maxSeqNo at least the given seqNo. Here we don't pick a range but select translog one by one. Suppose we have 3 translogs `gen1={#1,#2}, gen2={}, gen3={#3} and seqno=#1`, `uncommittedSizeInBytes` is the sum of gen1, gen2, and gen3 while `sizeOfGensAboveSeqNoInBytes` is the sum of gen1 and gen3. Gen2 is excluded because its maxSeqno is still -1. This commit removes both `sizeOfGensAboveSeqNoInBytes` and `uncommittedSizeInBytes` methods, then enforces an engine to use only `sizeInBytesByMinGen` method to evaluate the periodically flush condition. Closes #29097 Relates ##28350
1 parent c93c7f3 commit 14157c8

File tree

8 files changed

+94
-67
lines changed

8 files changed

+94
-67
lines changed

server/src/main/java/org/elasticsearch/index/engine/InternalEngine.java

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1361,7 +1361,8 @@ final boolean tryRenewSyncCommit() {
13611361
ensureOpen();
13621362
ensureCanFlush();
13631363
String syncId = lastCommittedSegmentInfos.getUserData().get(SYNC_COMMIT_ID);
1364-
if (syncId != null && translog.uncommittedOperations() == 0 && indexWriter.hasUncommittedChanges()) {
1364+
long translogGenOfLastCommit = Long.parseLong(lastCommittedSegmentInfos.userData.get(Translog.TRANSLOG_GENERATION_KEY));
1365+
if (syncId != null && indexWriter.hasUncommittedChanges() && translog.totalOperationsByMinGen(translogGenOfLastCommit) == 0) {
13651366
logger.trace("start renewing sync commit [{}]", syncId);
13661367
commitIndexWriter(indexWriter, translog, syncId);
13671368
logger.debug("successfully sync committed. sync id [{}].", syncId);
@@ -1383,19 +1384,30 @@ final boolean tryRenewSyncCommit() {
13831384
@Override
13841385
public boolean shouldPeriodicallyFlush() {
13851386
ensureOpen();
1387+
final long translogGenerationOfLastCommit = Long.parseLong(lastCommittedSegmentInfos.userData.get(Translog.TRANSLOG_GENERATION_KEY));
13861388
final long flushThreshold = config().getIndexSettings().getFlushThresholdSize().getBytes();
1387-
final long uncommittedSizeOfCurrentCommit = translog.uncommittedSizeInBytes();
1388-
if (uncommittedSizeOfCurrentCommit < flushThreshold) {
1389+
if (translog.sizeInBytesByMinGen(translogGenerationOfLastCommit) < flushThreshold) {
13891390
return false;
13901391
}
13911392
/*
1392-
* We should only flush ony if the shouldFlush condition can become false after flushing.
1393-
* This condition will change if the `uncommittedSize` of the new commit is smaller than
1394-
* the `uncommittedSize` of the current commit. This method is to maintain translog only,
1395-
* thus the IndexWriter#hasUncommittedChanges condition is not considered.
1393+
* We flush to reduce the size of uncommitted translog but strictly speaking the uncommitted size won't always be
1394+
* below the flush-threshold after a flush. To avoid getting into an endless loop of flushing, we only enable the
1395+
* periodically flush condition if this condition is disabled after a flush. The condition will change if the new
1396+
* commit points to the later generation the last commit's(eg. gen-of-last-commit < gen-of-new-commit)[1].
1397+
*
1398+
* When the local checkpoint equals to max_seqno, and translog-gen of the last commit equals to translog-gen of
1399+
* the new commit, we know that the last generation must contain operations because its size is above the flush
1400+
* threshold and the flush-threshold is guaranteed to be higher than an empty translog by the setting validation.
1401+
* This guarantees that the new commit will point to the newly rolled generation. In fact, this scenario only
1402+
* happens when the generation-threshold is close to or above the flush-threshold; otherwise we have rolled
1403+
* generations as the generation-threshold was reached, then the first condition (eg. [1]) is already satisfied.
1404+
*
1405+
* This method is to maintain translog only, thus IndexWriter#hasUncommittedChanges condition is not considered.
13961406
*/
1397-
final long uncommittedSizeOfNewCommit = translog.sizeOfGensAboveSeqNoInBytes(localCheckpointTracker.getCheckpoint() + 1);
1398-
return uncommittedSizeOfNewCommit < uncommittedSizeOfCurrentCommit;
1407+
final long translogGenerationOfNewCommit =
1408+
translog.getMinGenerationForSeqNo(localCheckpointTracker.getCheckpoint() + 1).translogFileGeneration;
1409+
return translogGenerationOfLastCommit < translogGenerationOfNewCommit
1410+
|| localCheckpointTracker.getCheckpoint() == localCheckpointTracker.getMaxSeqNo();
13991411
}
14001412

14011413
@Override

server/src/main/java/org/elasticsearch/index/translog/Translog.java

Lines changed: 7 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -356,26 +356,11 @@ public long getMinFileGeneration() {
356356
}
357357
}
358358

359-
360-
/**
361-
* Returns the number of operations in the translog files that aren't committed to lucene.
362-
*/
363-
public int uncommittedOperations() {
364-
return totalOperations(deletionPolicy.getTranslogGenerationOfLastCommit());
365-
}
366-
367-
/**
368-
* Returns the size in bytes of the translog files that aren't committed to lucene.
369-
*/
370-
public long uncommittedSizeInBytes() {
371-
return sizeInBytesByMinGen(deletionPolicy.getTranslogGenerationOfLastCommit());
372-
}
373-
374359
/**
375360
* Returns the number of operations in the translog files
376361
*/
377362
public int totalOperations() {
378-
return totalOperations(-1);
363+
return totalOperationsByMinGen(-1);
379364
}
380365

381366
/**
@@ -406,9 +391,9 @@ static long findEarliestLastModifiedAge(long currentTime, Iterable<TranslogReade
406391
}
407392

408393
/**
409-
* Returns the number of operations in the transaction files that aren't committed to lucene..
394+
* Returns the number of operations in the translog files at least the given generation
410395
*/
411-
private int totalOperations(long minGeneration) {
396+
public int totalOperationsByMinGen(long minGeneration) {
412397
try (ReleasableLock ignored = readLock.acquire()) {
413398
ensureOpen();
414399
return Stream.concat(readers.stream(), Stream.of(current))
@@ -429,9 +414,9 @@ public int estimateTotalOperationsFromMinSeq(long minSeqNo) {
429414
}
430415

431416
/**
432-
* Returns the size in bytes of the translog files above the given generation
417+
* Returns the size in bytes of the translog files at least the given generation
433418
*/
434-
private long sizeInBytesByMinGen(long minGeneration) {
419+
public long sizeInBytesByMinGen(long minGeneration) {
435420
try (ReleasableLock ignored = readLock.acquire()) {
436421
ensureOpen();
437422
return Stream.concat(readers.stream(), Stream.of(current))
@@ -441,16 +426,6 @@ private long sizeInBytesByMinGen(long minGeneration) {
441426
}
442427
}
443428

444-
/**
445-
* Returns the size in bytes of the translog files with ops above the given seqNo
446-
*/
447-
public long sizeOfGensAboveSeqNoInBytes(long minSeqNo) {
448-
try (ReleasableLock ignored = readLock.acquire()) {
449-
ensureOpen();
450-
return readersAboveMinSeqNo(minSeqNo).mapToLong(BaseTranslogReader::sizeInBytes).sum();
451-
}
452-
}
453-
454429
/**
455430
* Creates a new translog for the specified generation.
456431
*
@@ -758,7 +733,8 @@ private void closeOnTragicEvent(Exception ex) {
758733
public TranslogStats stats() {
759734
// acquire lock to make the two numbers roughly consistent (no file change half way)
760735
try (ReleasableLock lock = readLock.acquire()) {
761-
return new TranslogStats(totalOperations(), sizeInBytes(), uncommittedOperations(), uncommittedSizeInBytes(), earliestLastModifiedAge());
736+
final long uncommittedGen = deletionPolicy.getTranslogGenerationOfLastCommit();
737+
return new TranslogStats(totalOperations(), sizeInBytes(), totalOperationsByMinGen(uncommittedGen), sizeInBytesByMinGen(uncommittedGen), earliestLastModifiedAge());
762738
}
763739
}
764740

server/src/main/java/org/elasticsearch/index/translog/TranslogDeletionPolicy.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,6 @@ public synchronized long getMinTranslogGenerationForRecovery() {
211211

212212
/**
213213
* Returns a translog generation that will be used to calculate the number of uncommitted operations since the last index commit.
214-
* See {@link Translog#uncommittedOperations()} and {@link Translog#uncommittedSizeInBytes()}
215214
*/
216215
public synchronized long getTranslogGenerationOfLastCommit() {
217216
return translogGenerationOfLastCommit;

server/src/test/java/org/elasticsearch/index/engine/EngineDiskUtilsTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ public void testCurrentTranslogIDisCommitted() throws IOException {
156156
assertEquals(engine.getTranslog().getTranslogUUID(), userData.get(Translog.TRANSLOG_UUID_KEY));
157157
engine.recoverFromTranslog();
158158
assertEquals(2, engine.getTranslog().currentFileGeneration());
159-
assertEquals(0L, engine.getTranslog().uncommittedOperations());
159+
assertEquals(0L, engine.getTranslog().stats().getUncommittedOperations());
160160
}
161161
}
162162

server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java

Lines changed: 51 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -725,8 +725,7 @@ protected void commitIndexWriter(IndexWriter writer, Translog translog, String s
725725
super.commitIndexWriter(writer, translog, syncId);
726726
}
727727
};
728-
729-
assertThat(recoveringEngine.getTranslog().uncommittedOperations(), equalTo(docs));
728+
assertThat(recoveringEngine.getTranslog().stats().getUncommittedOperations(), equalTo(docs));
730729
recoveringEngine.recoverFromTranslog();
731730
assertTrue(committed.get());
732731
} finally {
@@ -3614,7 +3613,7 @@ protected long doGenerateSeqNoForOperation(Operation operation) {
36143613
System.nanoTime(),
36153614
reason));
36163615
assertThat(noOpEngine.getLocalCheckpointTracker().getCheckpoint(), equalTo((long) (maxSeqNo + 1)));
3617-
assertThat(noOpEngine.getTranslog().uncommittedOperations(), equalTo(1 + gapsFilled));
3616+
assertThat(noOpEngine.getTranslog().stats().getUncommittedOperations(), equalTo(1 + gapsFilled));
36183617
// skip to the op that we added to the translog
36193618
Translog.Operation op;
36203619
Translog.Operation last = null;
@@ -3814,7 +3813,7 @@ public void testFillUpSequenceIdGapsOnRecovery() throws IOException {
38143813
assertEquals(maxSeqIDOnReplica, replicaEngine.getLocalCheckpointTracker().getMaxSeqNo());
38153814
assertEquals(checkpointOnReplica, replicaEngine.getLocalCheckpointTracker().getCheckpoint());
38163815
recoveringEngine = new InternalEngine(copy(replicaEngine.config(), globalCheckpoint::get));
3817-
assertEquals(numDocsOnReplica, recoveringEngine.getTranslog().uncommittedOperations());
3816+
assertEquals(numDocsOnReplica, recoveringEngine.getTranslog().stats().getUncommittedOperations());
38183817
recoveringEngine.recoverFromTranslog();
38193818
assertEquals(maxSeqIDOnReplica, recoveringEngine.getLocalCheckpointTracker().getMaxSeqNo());
38203819
assertEquals(checkpointOnReplica, recoveringEngine.getLocalCheckpointTracker().getCheckpoint());
@@ -3848,7 +3847,7 @@ public void testFillUpSequenceIdGapsOnRecovery() throws IOException {
38483847
try {
38493848
recoveringEngine = new InternalEngine(copy(replicaEngine.config(), globalCheckpoint::get));
38503849
if (flushed) {
3851-
assertEquals(0, recoveringEngine.getTranslog().uncommittedOperations());
3850+
assertThat(recoveringEngine.getTranslog().stats().getUncommittedOperations(), equalTo(0));
38523851
}
38533852
recoveringEngine.recoverFromTranslog();
38543853
assertEquals(maxSeqIDOnReplica, recoveringEngine.getLocalCheckpointTracker().getMaxSeqNo());
@@ -4252,39 +4251,80 @@ public void testCleanupCommitsWhenReleaseSnapshot() throws Exception {
42524251
public void testShouldPeriodicallyFlush() throws Exception {
42534252
assertThat("Empty engine does not need flushing", engine.shouldPeriodicallyFlush(), equalTo(false));
42544253
// A new engine may have more than one empty translog files - the test should account this extra.
4255-
final long extraTranslogSizeInNewEngine = engine.getTranslog().uncommittedSizeInBytes() - Translog.DEFAULT_HEADER_SIZE_IN_BYTES;
4254+
final Translog translog = engine.getTranslog();
4255+
final long extraTranslogSizeInNewEngine = engine.getTranslog().stats().getUncommittedSizeInBytes() - Translog.DEFAULT_HEADER_SIZE_IN_BYTES;
42564256
int numDocs = between(10, 100);
42574257
for (int id = 0; id < numDocs; id++) {
42584258
final ParsedDocument doc = testParsedDocument(Integer.toString(id), null, testDocumentWithTextField(), SOURCE, null);
42594259
engine.index(indexForDoc(doc));
42604260
}
42614261
assertThat("Not exceeded translog flush threshold yet", engine.shouldPeriodicallyFlush(), equalTo(false));
42624262
long flushThreshold = RandomNumbers.randomLongBetween(random(), 100,
4263-
engine.getTranslog().uncommittedSizeInBytes() - extraTranslogSizeInNewEngine);
4263+
engine.getTranslog().stats().getUncommittedSizeInBytes()- extraTranslogSizeInNewEngine);
42644264
final IndexSettings indexSettings = engine.config().getIndexSettings();
42654265
final IndexMetaData indexMetaData = IndexMetaData.builder(indexSettings.getIndexMetaData())
42664266
.settings(Settings.builder().put(indexSettings.getSettings())
42674267
.put(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), flushThreshold + "b")).build();
42684268
indexSettings.updateIndexMetaData(indexMetaData);
42694269
engine.onSettingsChanged();
4270-
assertThat(engine.getTranslog().uncommittedOperations(), equalTo(numDocs));
4270+
assertThat(engine.getTranslog().stats().getUncommittedOperations(), equalTo(numDocs));
42714271
assertThat(engine.shouldPeriodicallyFlush(), equalTo(true));
42724272
engine.flush();
4273-
assertThat(engine.getTranslog().uncommittedOperations(), equalTo(0));
4273+
assertThat(engine.getTranslog().stats().getUncommittedOperations(), equalTo(0));
42744274
// Stale operations skipped by Lucene but added to translog - still able to flush
42754275
for (int id = 0; id < numDocs; id++) {
42764276
final ParsedDocument doc = testParsedDocument(Integer.toString(id), null, testDocumentWithTextField(), SOURCE, null);
42774277
final Engine.IndexResult result = engine.index(replicaIndexForDoc(doc, 1L, id, false));
42784278
assertThat(result.isCreated(), equalTo(false));
42794279
}
42804280
SegmentInfos lastCommitInfo = engine.getLastCommittedSegmentInfos();
4281-
assertThat(engine.getTranslog().uncommittedOperations(), equalTo(numDocs));
4281+
assertThat(engine.getTranslog().stats().getUncommittedOperations(), equalTo(numDocs));
42824282
assertThat(engine.shouldPeriodicallyFlush(), equalTo(true));
42834283
engine.flush(false, false);
42844284
assertThat(engine.getLastCommittedSegmentInfos(), not(sameInstance(lastCommitInfo)));
4285-
assertThat(engine.getTranslog().uncommittedOperations(), equalTo(0));
4285+
assertThat(engine.getTranslog().stats().getUncommittedOperations(), equalTo(0));
4286+
// If the new index commit still points to the same translog generation as the current index commit,
4287+
// we should not enable the periodically flush condition; otherwise we can get into an infinite loop of flushes.
4288+
engine.getLocalCheckpointTracker().generateSeqNo(); // create a gap here
4289+
for (int id = 0; id < numDocs; id++) {
4290+
if (randomBoolean()) {
4291+
translog.rollGeneration();
4292+
}
4293+
final ParsedDocument doc = testParsedDocument("new" + id, null, testDocumentWithTextField(), SOURCE, null);
4294+
engine.index(replicaIndexForDoc(doc, 2L, engine.getLocalCheckpointTracker().generateSeqNo(), false));
4295+
if (engine.shouldPeriodicallyFlush()) {
4296+
engine.flush();
4297+
assertThat(engine.getLastCommittedSegmentInfos(), not(sameInstance(lastCommitInfo)));
4298+
assertThat(engine.shouldPeriodicallyFlush(), equalTo(false));
4299+
}
4300+
}
42864301
}
42874302

4303+
public void testStressShouldPeriodicallyFlush() throws Exception {
4304+
final long flushThreshold = randomLongBetween(100, 5000);
4305+
final long generationThreshold = randomLongBetween(1000, 5000);
4306+
final IndexSettings indexSettings = engine.config().getIndexSettings();
4307+
final IndexMetaData indexMetaData = IndexMetaData.builder(indexSettings.getIndexMetaData())
4308+
.settings(Settings.builder().put(indexSettings.getSettings())
4309+
.put(IndexSettings.INDEX_TRANSLOG_GENERATION_THRESHOLD_SIZE_SETTING.getKey(), generationThreshold + "b")
4310+
.put(IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), flushThreshold + "b")).build();
4311+
indexSettings.updateIndexMetaData(indexMetaData);
4312+
engine.onSettingsChanged();
4313+
final int numOps = scaledRandomIntBetween(100, 10_000);
4314+
for (int i = 0; i < numOps; i++) {
4315+
final long localCheckPoint = engine.getLocalCheckpointTracker().getCheckpoint();
4316+
final long seqno = randomLongBetween(Math.max(0, localCheckPoint), localCheckPoint + 5);
4317+
final ParsedDocument doc = testParsedDocument(Long.toString(seqno), null, testDocumentWithTextField(), SOURCE, null);
4318+
engine.index(replicaIndexForDoc(doc, 1L, seqno, false));
4319+
if (rarely() && engine.getTranslog().shouldRollGeneration()) {
4320+
engine.rollTranslogGeneration();
4321+
}
4322+
if (rarely() || engine.shouldPeriodicallyFlush()) {
4323+
engine.flush();
4324+
assertThat(engine.shouldPeriodicallyFlush(), equalTo(false));
4325+
}
4326+
}
4327+
}
42884328

42894329
public void testStressUpdateSameDocWhileGettingIt() throws IOException, InterruptedException {
42904330
final int iters = randomIntBetween(1, 15);

server/src/test/java/org/elasticsearch/index/shard/IndexShardIT.java

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -342,29 +342,29 @@ public void testMaybeFlush() throws Exception {
342342
IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, update -> {});
343343
assertTrue(shard.shouldPeriodicallyFlush());
344344
final Translog translog = shard.getEngine().getTranslog();
345-
assertEquals(2, translog.uncommittedOperations());
345+
assertEquals(2, translog.stats().getUncommittedOperations());
346346
client().prepareIndex("test", "test", "2").setSource("{}", XContentType.JSON)
347347
.setRefreshPolicy(randomBoolean() ? IMMEDIATE : NONE).get();
348348
assertBusy(() -> { // this is async
349349
assertFalse(shard.shouldPeriodicallyFlush());
350350
});
351-
assertEquals(0, translog.uncommittedOperations());
351+
assertEquals(0, translog.stats().getUncommittedOperations());
352352
translog.sync();
353-
long size = Math.max(translog.uncommittedSizeInBytes(), Translog.DEFAULT_HEADER_SIZE_IN_BYTES + 1);
354-
logger.info("--> current translog size: [{}] num_ops [{}] generation [{}]", translog.uncommittedSizeInBytes(),
355-
translog.uncommittedOperations(), translog.getGeneration());
353+
long size = Math.max(translog.stats().getUncommittedSizeInBytes(), Translog.DEFAULT_HEADER_SIZE_IN_BYTES + 1);
354+
logger.info("--> current translog size: [{}] num_ops [{}] generation [{}]",
355+
translog.stats().getUncommittedSizeInBytes(), translog.stats().getUncommittedOperations(), translog.getGeneration());
356356
client().admin().indices().prepareUpdateSettings("test").setSettings(Settings.builder().put(
357357
IndexSettings.INDEX_TRANSLOG_FLUSH_THRESHOLD_SIZE_SETTING.getKey(), new ByteSizeValue(size, ByteSizeUnit.BYTES))
358358
.build()).get();
359359
client().prepareDelete("test", "test", "2").get();
360-
logger.info("--> translog size after delete: [{}] num_ops [{}] generation [{}]", translog.uncommittedSizeInBytes(),
361-
translog.uncommittedOperations(), translog.getGeneration());
360+
logger.info("--> translog size after delete: [{}] num_ops [{}] generation [{}]",
361+
translog.stats().getUncommittedSizeInBytes(), translog.stats().getUncommittedOperations(), translog.getGeneration());
362362
assertBusy(() -> { // this is async
363-
logger.info("--> translog size on iter : [{}] num_ops [{}] generation [{}]", translog.uncommittedSizeInBytes(),
364-
translog.uncommittedOperations(), translog.getGeneration());
363+
logger.info("--> translog size on iter : [{}] num_ops [{}] generation [{}]",
364+
translog.stats().getUncommittedSizeInBytes(), translog.stats().getUncommittedOperations(), translog.getGeneration());
365365
assertFalse(shard.shouldPeriodicallyFlush());
366366
});
367-
assertEquals(0, translog.uncommittedOperations());
367+
assertEquals(0, translog.stats().getUncommittedOperations());
368368
}
369369

370370
public void testMaybeRollTranslogGeneration() throws Exception {

0 commit comments

Comments
 (0)