Skip to content

Commit f7e7387

Browse files
NIFI-16599 Preserve FlowFile order across restart for queues that are swapping (#11936)
- Restore FlowFiles in priority order on recovery when there are no swap files, sharing the logic used when swap files exist - Keep the place of a swap file rewritten by a selective drop by reusing the timestamp and counter of the replaced swap file - Add a counter to swap file names so that swap files written in the same millisecond are recovered in the order written Co-authored-by: Cursor <cursoragent@cursor.com> Signed-off-by: David Handermann <exceptionfactory@apache.org>
1 parent 67b1e48 commit f7e7387

5 files changed

Lines changed: 215 additions & 62 deletions

File tree

‎nifi-framework-api/src/main/java/org/apache/nifi/controller/repository/FlowFileSwapManager.java‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,23 @@ public interface FlowFileSwapManager {
5252
*/
5353
String swapOut(List<FlowFileRecord> flowFiles, FlowFileQueue flowFileQueue, final String partitionName) throws IOException;
5454

55+
/**
56+
* Swaps out the given FlowFiles to a new swap file that takes the place of an existing swap file, such as when some FlowFiles are removed
57+
* from the existing swap file. When swap files are recovered, the new swap file is placed where the existing swap file would have been placed,
58+
* rather than after all other swap files. The existing swap file is neither modified nor deleted.
59+
*
60+
* @param flowFiles the FlowFiles to swap out to external storage
61+
* @param flowFileQueue the queue that the FlowFiles belong to
62+
* @param partitionName the name of the partition within the queue, or <code>null</code> if the queue is not partitioned
63+
* @param replacedSwapLocation the location of the existing swap file whose place the new swap file takes
64+
* @return the location of the externally stored swap file
65+
*
66+
* @throws IOException if unable to swap the FlowFiles out
67+
*/
68+
default String swapOut(final List<FlowFileRecord> flowFiles, final FlowFileQueue flowFileQueue, final String partitionName, final String replacedSwapLocation) throws IOException {
69+
return swapOut(flowFiles, flowFileQueue, partitionName);
70+
}
71+
5572
/**
5673
* Recovers the FlowFiles from the swap file that lives at the given location. This action
5774
* provides a view of the FlowFiles but does not actively swap them in, meaning that the swap file

‎nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FileSystemSwapManager.java‎

Lines changed: 70 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@
6464
import java.util.Objects;
6565
import java.util.Set;
6666
import java.util.UUID;
67+
import java.util.concurrent.atomic.AtomicLong;
6768
import java.util.regex.Matcher;
6869
import java.util.regex.Pattern;
6970
import java.util.stream.Collectors;
@@ -86,6 +87,7 @@ public class FileSystemSwapManager implements FlowFileSwapManager {
8687

8788
private final File storageDirectory;
8889
private final FieldCache fieldCache = new CaffeineFieldCache(10_000_000);
90+
private final AtomicLong swapFileCounter = new AtomicLong();
8991

9092
// effectively final
9193
private FlowFileRepository flowFileRepository;
@@ -133,7 +135,26 @@ public String swapOut(final List<FlowFileRecord> toSwap, final FlowFileQueue flo
133135
return null;
134136
}
135137

136-
final String swapFileName = getSwapFileName(flowFileQueue.getIdentifier(), partitionName);
138+
return writeSwapFile(toSwap, flowFileQueue, partitionName, System.currentTimeMillis(), swapFileCounter.incrementAndGet());
139+
}
140+
141+
@Override
142+
public String swapOut(final List<FlowFileRecord> toSwap, final FlowFileQueue flowFileQueue, final String partitionName, final String replacedSwapLocation) throws IOException {
143+
if (toSwap == null || toSwap.isEmpty()) {
144+
return null;
145+
}
146+
147+
// Swap files are recovered in the order of the timestamp and counter in their names, so the new swap file takes those of the swap file that it replaces
148+
final Long replacedTimestamp = getTimestampFromFilename(replacedSwapLocation);
149+
if (replacedTimestamp == null) {
150+
return swapOut(toSwap, flowFileQueue, partitionName);
151+
}
152+
153+
return writeSwapFile(toSwap, flowFileQueue, partitionName, replacedTimestamp, getCounterFromFilename(replacedSwapLocation));
154+
}
155+
156+
private String writeSwapFile(final List<FlowFileRecord> toSwap, final FlowFileQueue flowFileQueue, final String partitionName, final long timestamp, final long counter) throws IOException {
157+
final String swapFileName = getSwapFileName(flowFileQueue.getIdentifier(), partitionName, timestamp, counter);
137158
final Path storageDirectoryPath = storageDirectory.toPath();
138159
final Path swapFilePath = storageDirectoryPath.resolve(swapFileName).toAbsolutePath();
139160

@@ -293,8 +314,8 @@ public List<String> recoverSwapLocations(final FlowFileQueue flowFileQueue, fina
293314
continue;
294315
}
295316

296-
// split the filename by dashes. The old filenaming scheme was "<timestamp>-<randomuuid>.swap" but the new naming scheme is
297-
// "<timestamp>-<queue identifier>-<random uuid>.[partition name.]swap".
317+
// split the filename by dashes. The old filenaming scheme was "<timestamp>-<randomuuid>.swap" but newer naming schemes are
318+
// "<timestamp>-<queue identifier>-<random uuid>.[partition name.]swap" and "<timestamp>-<queue identifier>-<counter>-<random uuid>.[partition name.]swap".
298319
final String ownerQueueId = getOwnerQueueIdentifier(swapFile);
299320
if (ownerQueueId != null) {
300321
if (!ownerQueueId.equals(flowFileQueue.getIdentifier())) {
@@ -425,28 +446,56 @@ public int compare(final String o1, final String o2) {
425446
return timeComparisonValue;
426447
}
427448

449+
final int counterComparisonValue = Long.compare(getCounterFromFilename(o1), getCounterFromFilename(o2));
450+
if (counterComparisonValue != 0) {
451+
return counterComparisonValue;
452+
}
453+
428454
return o1.compareTo(o2);
429455
}
456+
}
430457

431-
private Long getTimestampFromFilename(final String fullyQualifiedFilename) {
432-
if (fullyQualifiedFilename == null) {
433-
return null;
434-
}
458+
private static Long getTimestampFromFilename(final String fullyQualifiedFilename) {
459+
if (fullyQualifiedFilename == null) {
460+
return null;
461+
}
435462

436-
final File file = new File(fullyQualifiedFilename);
437-
final String filename = file.getName();
463+
final File file = new File(fullyQualifiedFilename);
464+
final String filename = file.getName();
438465

439-
final int idx = filename.indexOf("-");
440-
if (idx < 1) {
441-
return null;
442-
}
466+
final int idx = filename.indexOf("-");
467+
if (idx < 1) {
468+
return null;
469+
}
443470

444-
final String millisVal = filename.substring(0, idx);
445-
try {
446-
return Long.parseLong(millisVal);
447-
} catch (final NumberFormatException e) {
448-
return null;
449-
}
471+
final String millisVal = filename.substring(0, idx);
472+
try {
473+
return Long.parseLong(millisVal);
474+
} catch (final NumberFormatException e) {
475+
return null;
476+
}
477+
}
478+
479+
/**
480+
* Returns the counter from a swap file name of the form "&lt;timestamp&gt;-&lt;queue identifier&gt;-&lt;counter&gt;-&lt;random uuid&gt;". The counter orders
481+
* swap files that were written within the same millisecond.
482+
*
483+
* @param fullyQualifiedFilename the swap location
484+
* @return the counter from the swap file name, or 0 if the name does not contain a counter
485+
*/
486+
private static long getCounterFromFilename(final String fullyQualifiedFilename) {
487+
final String filename = new File(fullyQualifiedFilename).getName();
488+
final int dotIndex = filename.indexOf(".");
489+
final String baseName = dotIndex < 0 ? filename : filename.substring(0, dotIndex);
490+
final String[] splits = baseName.split("-");
491+
if (splits.length != 12) {
492+
return 0L;
493+
}
494+
495+
try {
496+
return Long.parseLong(splits[6]);
497+
} catch (final NumberFormatException e) {
498+
return 0L;
450499
}
451500
}
452501

@@ -475,7 +524,7 @@ public String changePartitionName(final String swapLocation, final String newPar
475524
return newFile.getAbsolutePath();
476525
}
477526

478-
private String getSwapFileName(final String flowFileQueueIdentifier, final String partitionName) {
527+
private String getSwapFileName(final String flowFileQueueIdentifier, final String partitionName, final long timestamp, final long counter) {
479528
final UUID identifier;
480529
final Matcher identifierMatcher = UUID_PATTERN.matcher(flowFileQueueIdentifier);
481530
if (identifierMatcher.find()) {
@@ -484,7 +533,7 @@ private String getSwapFileName(final String flowFileQueueIdentifier, final Strin
484533
throw new IllegalArgumentException("FlowFile Queue Identifier [%s] not valid".formatted(flowFileQueueIdentifier));
485534
}
486535

487-
final String swapFilePrefix = System.currentTimeMillis() + "-" + identifier + "-" + UUID.randomUUID();
536+
final String swapFilePrefix = timestamp + "-" + identifier + "-" + counter + "-" + UUID.randomUUID();
488537
final String swapFileBaseName = partitionName == null ? swapFilePrefix : swapFilePrefix + "." + partitionName;
489538
return swapFileBaseName + ".swap";
490539
}

‎nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java‎

Lines changed: 50 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1180,8 +1180,8 @@ private SwapFileDropResult processSwapFileForDrop(final String swapLocation, fin
11801180
return new SwapFileDropResult(swapLocation, null, droppedFromThisSwapFile, droppedFromSwapFileBytes, 0L, 0L);
11811181
}
11821182

1183-
// Some FlowFiles remain - write to new swap file
1184-
final String newSwapLocation = swapManager.swapOut(remainingFlowFiles, flowFileQueue, swapPartitionName);
1183+
// Some FlowFiles remain - write to a new swap file that keeps the place of the existing swap file when swap files are recovered
1184+
final String newSwapLocation = swapManager.swapOut(remainingFlowFiles, flowFileQueue, swapPartitionName, swapLocation);
11851185
return new SwapFileDropResult(swapLocation, newSwapLocation, droppedFromThisSwapFile,
11861186
droppedFromSwapFileBytes, remainingMinQueueDate, remainingTotalQueueDate);
11871187
}
@@ -1270,10 +1270,10 @@ public SwapSummary recoverSwappedFlowFiles() {
12701270
if (!swapLocations.isEmpty()) {
12711271
// FlowFiles added from now on must wait behind the swap files, even if the oldest swap file cannot be read
12721272
swapMode = true;
1273-
final String oldestSwapLocation = swapLocations.iterator().next();
1274-
restoreActiveFlowFilesToSwapQueue(oldestSwapLocation);
12751273
}
12761274

1275+
restoreFlowFilesInPriorityOrder(swapLocations);
1276+
12771277
updateTopPenaltyExpiration();
12781278
} finally {
12791279
writeLock.unlock("Recover Swap Files");
@@ -1292,34 +1292,56 @@ public SwapSummary recoverSwappedFlowFiles() {
12921292
}
12931293

12941294
/**
1295-
* On restart, the FlowFiles that were held in memory are restored from the FlowFile Repository before the swap files are recovered, so they
1296-
* fill the active queue regardless of whether they were queued before or after the swapped FlowFiles. Because swap files are not swapped in
1297-
* until the active queue is empty, this keeps in the active queue only the FlowFiles that come before the highest priority FlowFile of the
1298-
* oldest swap file and moves all others to the swap queue, which is processed after the swap files.
1295+
* On restart, the FlowFiles that were held in memory are restored from the FlowFile Repository in no particular order and before the swap
1296+
* files are recovered. Whichever FlowFiles are restored first fill the active queue, regardless of their priority or of whether they were
1297+
* queued before or after the swapped FlowFiles, and the rest go to the swap queue. This puts the restored FlowFiles back in priority order.
1298+
*
1299+
* Because swap files are not swapped in until the active queue is empty, when there are swap files the active queue keeps only the restored
1300+
* FlowFiles that come before the highest priority FlowFile of the oldest swap file, and all others go to the swap queue, which is processed
1301+
* after the swap files. When there are no swap files, the active queue keeps the same number of FlowFiles, chosen from the highest priority
1302+
* restored FlowFiles.
12991303
*
13001304
* This method MUST be called with the write lock held.
13011305
*
1302-
* @param oldestSwapLocation the location of the oldest recovered swap file
1306+
* @param recoveredSwapLocations the locations of the recovered swap files, oldest first
13031307
*/
1304-
private void restoreActiveFlowFilesToSwapQueue(final String oldestSwapLocation) {
1305-
final List<FlowFileRecord> swappedFlowFiles;
1306-
try {
1307-
swappedFlowFiles = swapManager.peek(oldestSwapLocation, flowFileQueue).getFlowFiles();
1308-
} catch (final Exception e) {
1309-
logger.warn("Failed to read Swap File {} for {}; FlowFiles restored from the FlowFile Repository may be processed before older swapped FlowFiles",
1310-
oldestSwapLocation, this, e);
1311-
return;
1312-
}
1313-
1314-
if (swappedFlowFiles.isEmpty()) {
1308+
private void restoreFlowFilesInPriorityOrder(final Collection<String> recoveredSwapLocations) {
1309+
if (recoveredSwapLocations.isEmpty() && swapQueue.isEmpty()) {
13151310
return;
13161311
}
13171312

13181313
final QueuePrioritizer prioritizer = new QueuePrioritizer(getPriorities());
1319-
final FlowFileRecord firstSwappedFlowFile = Collections.min(swappedFlowFiles, prioritizer);
1320-
13211314
final List<FlowFileRecord> restoredFlowFiles = new ArrayList<>(activeQueue);
13221315
restoredFlowFiles.addAll(swapQueue);
1316+
restoredFlowFiles.sort(prioritizer);
1317+
1318+
final int activeCount;
1319+
if (recoveredSwapLocations.isEmpty()) {
1320+
activeCount = activeQueue.size();
1321+
} else {
1322+
final String oldestSwapLocation = recoveredSwapLocations.iterator().next();
1323+
final List<FlowFileRecord> swappedFlowFiles;
1324+
try {
1325+
swappedFlowFiles = swapManager.peek(oldestSwapLocation, flowFileQueue).getFlowFiles();
1326+
} catch (final Exception e) {
1327+
logger.warn("Failed to read Swap File {} for {}; FlowFiles restored from the FlowFile Repository may be processed before older swapped FlowFiles",
1328+
oldestSwapLocation, this, e);
1329+
return;
1330+
}
1331+
1332+
if (swappedFlowFiles.isEmpty()) {
1333+
return;
1334+
}
1335+
1336+
final FlowFileRecord firstSwappedFlowFile = Collections.min(swappedFlowFiles, prioritizer);
1337+
int countBeforeSwappedFlowFiles = 0;
1338+
while (countBeforeSwappedFlowFiles < restoredFlowFiles.size() && prioritizer.compare(restoredFlowFiles.get(countBeforeSwappedFlowFiles), firstSwappedFlowFile) < 0) {
1339+
countBeforeSwappedFlowFiles++;
1340+
}
1341+
1342+
activeCount = countBeforeSwappedFlowFiles;
1343+
}
1344+
13231345
final int originalActiveCount = activeQueue.size();
13241346
long originalActiveBytes = 0L;
13251347
for (final FlowFileRecord flowFile : activeQueue) {
@@ -1328,17 +1350,15 @@ private void restoreActiveFlowFilesToSwapQueue(final String oldestSwapLocation)
13281350

13291351
activeQueue.clear();
13301352
swapQueue.clear();
1353+
activeQueue.addAll(restoredFlowFiles.subList(0, activeCount));
1354+
swapQueue.addAll(restoredFlowFiles.subList(activeCount, restoredFlowFiles.size()));
1355+
13311356
long activeBytes = 0L;
1332-
for (final FlowFileRecord flowFile : restoredFlowFiles) {
1333-
if (prioritizer.compare(flowFile, firstSwappedFlowFile) < 0) {
1334-
activeQueue.add(flowFile);
1335-
activeBytes += flowFile.getSize();
1336-
} else {
1337-
swapQueue.add(flowFile);
1338-
}
1357+
for (final FlowFileRecord flowFile : activeQueue) {
1358+
activeBytes += flowFile.getSize();
13391359
}
13401360

1341-
final int movedToActiveCount = activeQueue.size() - originalActiveCount;
1361+
final int movedToActiveCount = activeCount - originalActiveCount;
13421362
final long movedToActiveBytes = activeBytes - originalActiveBytes;
13431363
incrementActiveQueueSize(movedToActiveCount, movedToActiveBytes);
13441364
incrementSwapQueueSize(-movedToActiveCount, -movedToActiveBytes, 0);

‎nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/TestFileSystemSwapManager.java‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,24 @@ public void testFailureOnRepoSwapOut() throws IOException {
107107
() -> swapManager.swapOut(flowFileRecords, flowFileQueue, "partition-1"));
108108
}
109109

110+
@Test
111+
public void testRecoverSwapLocationsInOrderWritten() throws IOException {
112+
final FlowFileQueue flowFileQueue = mock(FlowFileQueue.class);
113+
when(flowFileQueue.getIdentifier()).thenReturn("87bb99fe-412c-49f6-a441-d1b0af4e20b4");
114+
final FlowFileRepository flowFileRepo = mock(FlowFileRepository.class);
115+
when(flowFileRepo.isValidSwapLocationSuffix(anyString())).thenReturn(true);
116+
final FileSystemSwapManager swapManager = createSwapManager(flowFileRepo);
117+
118+
// Writing many small swap files in a row results in several swap files being written within the same millisecond
119+
final List<String> swapLocations = new ArrayList<>();
120+
for (int i = 0; i < 100; i++) {
121+
swapLocations.add(swapManager.swapOut(List.of(new MockFlowFileRecord(i)), flowFileQueue, "partition-1"));
122+
}
123+
124+
final FileSystemSwapManager restartedSwapManager = createSwapManager(flowFileRepo);
125+
assertEquals(swapLocations, restartedSwapManager.recoverSwapLocations(flowFileQueue, "partition-1"));
126+
}
127+
110128
@Test
111129
public void testSwapFileUnknownToRepoNotSwappedIn() throws IOException {
112130
final FlowFileQueue flowFileQueue = mock(FlowFileQueue.class);

0 commit comments

Comments
 (0)