This is an automated email from the ASF dual-hosted git repository.
exceptionfactory pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/nifi.git
The following commit(s) were added to refs/heads/main by this push:
new 6a4b37c04e4 NIFI-16580 Preserve FIFO order of restored FlowFiles when
recovering swap files (#11921)
6a4b37c04e4 is described below
commit 6a4b37c04e44ffb7163ff01c161c8a5dd1845e47
Author: Mark Payne <[email protected]>
AuthorDate: Mon Nov 16 08:42:07 2026 -0500
NIFI-16580 Preserve FIFO order of restored FlowFiles when recovering swap
files (#11921)
After a restart, FlowFiles restored from the FlowFile Repository are added
to
the queue before its swap files are recovered, so newer FlowFiles could fill
the active queue and be processed before older swapped FlowFiles. When swap
files are recovered, keep in the active queue only the FlowFiles that come
before the first FlowFile of the oldest swap file, move the rest to the swap
queue, and place the queue in swap mode.
Co-authored-by: Cursor <[email protected]>
Signed-off-by: David Handermann <[email protected]>
---
.../controller/queue/SwappablePriorityQueue.java | 60 ++++++++++++
.../clustered/TestSwappablePriorityQueue.java | 40 ++++++++
.../tests/system/VerifySequentialOrder.java | 103 +++++++++++++++++++++
.../services/org.apache.nifi.processor.Processor | 1 +
.../system/restart/FlowFileRestorationIT.java | 53 +++++++++++
5 files changed, 257 insertions(+)
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java
index 171113afb4a..4c22407a5c1 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/queue/SwappablePriorityQueue.java
@@ -1267,6 +1267,13 @@ public class SwappablePriorityQueue {
incrementSwapQueueSize(swapFlowFileCount, swapByteCount,
swapLocations.size());
this.swapLocations.addAll(swapLocations);
+ if (!swapLocations.isEmpty()) {
+ // FlowFiles added from now on must wait behind the swap
files, even if the oldest swap file cannot be read
+ swapMode = true;
+ final String oldestSwapLocation =
swapLocations.iterator().next();
+ restoreActiveFlowFilesToSwapQueue(oldestSwapLocation);
+ }
+
updateTopPenaltyExpiration();
} finally {
writeLock.unlock("Recover Swap Files");
@@ -1284,6 +1291,59 @@ public class SwappablePriorityQueue {
return new StandardSwapSummary(new QueueSize(swapFlowFileCount,
swapByteCount), maxId, resourceClaims, minSwappedQueueDate,
totalSwappedQueueDate);
}
+ /**
+ * On restart, the FlowFiles that were held in memory are restored from
the FlowFile Repository before the swap files are recovered, so they
+ * fill the active queue regardless of whether they were queued before or
after the swapped FlowFiles. Because swap files are not swapped in
+ * until the active queue is empty, this keeps in the active queue only
the FlowFiles that come before the highest priority FlowFile of the
+ * oldest swap file and moves all others to the swap queue, which is
processed after the swap files.
+ *
+ * This method MUST be called with the write lock held.
+ *
+ * @param oldestSwapLocation the location of the oldest recovered swap file
+ */
+ private void restoreActiveFlowFilesToSwapQueue(final String
oldestSwapLocation) {
+ final List<FlowFileRecord> swappedFlowFiles;
+ try {
+ swappedFlowFiles = swapManager.peek(oldestSwapLocation,
flowFileQueue).getFlowFiles();
+ } catch (final Exception e) {
+ logger.warn("Failed to read Swap File {} for {}; FlowFiles
restored from the FlowFile Repository may be processed before older swapped
FlowFiles",
+ oldestSwapLocation, this, e);
+ return;
+ }
+
+ if (swappedFlowFiles.isEmpty()) {
+ return;
+ }
+
+ final QueuePrioritizer prioritizer = new
QueuePrioritizer(getPriorities());
+ final FlowFileRecord firstSwappedFlowFile =
Collections.min(swappedFlowFiles, prioritizer);
+
+ final List<FlowFileRecord> restoredFlowFiles = new
ArrayList<>(activeQueue);
+ restoredFlowFiles.addAll(swapQueue);
+ final int originalActiveCount = activeQueue.size();
+ long originalActiveBytes = 0L;
+ for (final FlowFileRecord flowFile : activeQueue) {
+ originalActiveBytes += flowFile.getSize();
+ }
+
+ activeQueue.clear();
+ swapQueue.clear();
+ long activeBytes = 0L;
+ for (final FlowFileRecord flowFile : restoredFlowFiles) {
+ if (prioritizer.compare(flowFile, firstSwappedFlowFile) < 0) {
+ activeQueue.add(flowFile);
+ activeBytes += flowFile.getSize();
+ } else {
+ swapQueue.add(flowFile);
+ }
+ }
+
+ final int movedToActiveCount = activeQueue.size() -
originalActiveCount;
+ final long movedToActiveBytes = activeBytes - originalActiveBytes;
+ incrementActiveQueueSize(movedToActiveCount, movedToActiveBytes);
+ incrementSwapQueueSize(-movedToActiveCount, -movedToActiveBytes, 0);
+ }
+
public long getMinLastQueueDate() {
readLock.lock();
try {
diff --git
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java
index 02add0e4e4d..72237fa19b1 100644
---
a/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java
+++
b/nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/queue/clustered/TestSwappablePriorityQueue.java
@@ -609,6 +609,46 @@ public class TestSwappablePriorityQueue {
queue.poll(exp, 500000);
}
+ @Test
+ public void testRecoverSwappedFlowFilesPreservesOrder() throws IOException
{
+ final FlowFilePrioritizer iAttributePrioritizer = (o1, o2) -> {
+ final int i1 = Integer.parseInt(o1.getAttribute("i"));
+ final int i2 = Integer.parseInt(o2.getAttribute("i"));
+ return Integer.compare(i1, i2);
+ };
+
+ // Before a restart, the active queue held the oldest FlowFiles, a
swap file held the next 100, and the in-memory swap queue held the newest 50.
+ // On restart, the active and in-memory swap queue FlowFiles are
restored newest first, and then the swap file is recovered.
+ for (final int activeCount : new int[] {40, 80}) {
+ swapManager = new MockSwapManager();
+ queue = new SwappablePriorityQueue(swapManager, 100,
eventReporter, flowFileQueue, dropAction, "local");
+ queue.setPriorities(List.of(iAttributePrioritizer));
+
+ final List<FlowFileRecord> swappedFlowFiles = new ArrayList<>();
+ for (int i = activeCount; i < activeCount + 100; i++) {
+ swappedFlowFiles.add(new MockFlowFileRecord(Map.of("i",
String.valueOf(i)), 1L));
+ }
+ swapManager.swapOut(swappedFlowFiles, flowFileQueue, "local");
+
+ final int totalCount = activeCount + 150;
+ for (int i = totalCount - 1; i >= 0; i--) {
+ if (i < activeCount || i >= activeCount + 100) {
+ queue.put(new MockFlowFileRecord(Map.of("i",
String.valueOf(i)), 1L));
+ }
+ }
+
+ queue.recoverSwappedFlowFiles();
+ queue.put(new MockFlowFileRecord(Map.of("i",
String.valueOf(totalCount)), 1L));
+ assertEquals(totalCount + 1, queue.size().getObjectCount());
+
+ for (int i = 0; i <= totalCount; i++) {
+ assertEquals(String.valueOf(i),
queue.poll(Collections.emptySet(), 0L).getAttribute("i"));
+ }
+
+ assertNull(queue.poll(Collections.emptySet(), 0L));
+ }
+ }
+
@Test
public void testQueueCountsUpdatedWhenIncompleteSwapFile() {
for (int i = 1; i <= 20000; i++) {
diff --git
a/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/java/org/apache/nifi/processors/tests/system/VerifySequentialOrder.java
b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/java/org/apache/nifi/processors/tests/system/VerifySequentialOrder.java
new file mode 100644
index 00000000000..bc7206b0fba
--- /dev/null
+++
b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/java/org/apache/nifi/processors/tests/system/VerifySequentialOrder.java
@@ -0,0 +1,103 @@
+/*
+ * 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.nifi.processors.tests.system;
+
+import org.apache.nifi.annotation.behavior.TriggerSerially;
+import org.apache.nifi.annotation.documentation.CapabilityDescription;
+import org.apache.nifi.components.PropertyDescriptor;
+import org.apache.nifi.expression.ExpressionLanguageScope;
+import org.apache.nifi.flowfile.FlowFile;
+import org.apache.nifi.processor.AbstractProcessor;
+import org.apache.nifi.processor.ProcessContext;
+import org.apache.nifi.processor.ProcessSession;
+import org.apache.nifi.processor.Relationship;
+import org.apache.nifi.processor.exception.ProcessException;
+import org.apache.nifi.processor.util.StandardValidators;
+
+import java.util.List;
+import java.util.Set;
+
+@TriggerSerially
+@CapabilityDescription("""
+ Pulls one FlowFile at a time from the incoming queue and routes it to
'sequential' if its Value to Consider is exactly one greater than the
+ Value to Consider of the previous FlowFile that this Processor received.
Otherwise, the FlowFile is routed to 'failure'. The first FlowFile
+ that the Processor receives is always routed to 'sequential'.
+ """)
+public class VerifySequentialOrder extends AbstractProcessor {
+
+ static final PropertyDescriptor VALUE_TO_CONSIDER = new
PropertyDescriptor.Builder()
+ .name("Value to Consider")
+ .description("The whole number to compare against the Value to
Consider of the previous FlowFile")
+ .required(true)
+ .addValidator(StandardValidators.LONG_VALIDATOR)
+
.expressionLanguageSupported(ExpressionLanguageScope.FLOWFILE_ATTRIBUTES)
+ .build();
+
+ static final Relationship REL_SEQUENTIAL = new Relationship.Builder()
+ .name("sequential")
+ .description("The first FlowFile, and any FlowFile whose Value to
Consider is exactly one greater than that of the previous FlowFile")
+ .build();
+
+ static final Relationship REL_FAILURE = new Relationship.Builder()
+ .name("failure")
+ .description("Any FlowFile whose Value to Consider is not exactly one
greater than that of the previous FlowFile, or is not a whole number")
+ .build();
+
+ private static final List<PropertyDescriptor> PROPERTY_DESCRIPTORS =
List.of(VALUE_TO_CONSIDER);
+ private static final Set<Relationship> RELATIONSHIPS =
Set.of(REL_SEQUENTIAL, REL_FAILURE);
+
+ private volatile Long previousValue;
+
+ @Override
+ protected List<PropertyDescriptor> getSupportedPropertyDescriptors() {
+ return PROPERTY_DESCRIPTORS;
+ }
+
+ @Override
+ public Set<Relationship> getRelationships() {
+ return RELATIONSHIPS;
+ }
+
+ @Override
+ public void onTrigger(final ProcessContext context, final ProcessSession
session) throws ProcessException {
+ final FlowFile flowFile = session.get();
+ if (flowFile == null) {
+ return;
+ }
+
+ final String value =
context.getProperty(VALUE_TO_CONSIDER).evaluateAttributeExpressions(flowFile).getValue();
+ final long currentValue;
+ try {
+ currentValue = Long.parseLong(value);
+ } catch (final NumberFormatException e) {
+ getLogger().error("Routing {} to failure because its Value to
Consider [{}] is not a whole number", flowFile, value);
+ session.transfer(flowFile, REL_FAILURE);
+ return;
+ }
+
+ final Long lastValue = previousValue;
+ previousValue = currentValue;
+
+ if (lastValue == null || currentValue == lastValue + 1) {
+ session.transfer(flowFile, REL_SEQUENTIAL);
+ } else {
+ getLogger().warn("Routing {} to failure because its Value to
Consider is {} but the previous FlowFile's value was {}", flowFile,
currentValue, lastValue);
+ session.transfer(flowFile, REL_FAILURE);
+ }
+ }
+}
diff --git
a/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor
b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor
index 7d9389d9be3..dfbae6496ec 100644
---
a/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor
+++
b/nifi-system-tests/nifi-system-test-extensions-bundle/nifi-system-test-extensions/src/main/resources/META-INF/services/org.apache.nifi.processor.Processor
@@ -67,6 +67,7 @@
org.apache.nifi.processors.tests.system.VerifyClasspathResource
org.apache.nifi.processors.tests.system.VerifyContents
org.apache.nifi.processors.tests.system.VerifyEvenThenOdd
org.apache.nifi.processors.tests.system.VerifyMethodSignatureResource
+org.apache.nifi.processors.tests.system.VerifySequentialOrder
org.apache.nifi.processors.tests.system.WriteFlowFileCountToFile
org.apache.nifi.processors.tests.system.WriteLifecycleEvents
org.apache.nifi.processors.tests.system.WriteToFile
diff --git
a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/restart/FlowFileRestorationIT.java
b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/restart/FlowFileRestorationIT.java
index cb9749ad8c0..bfbe763f189 100644
---
a/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/restart/FlowFileRestorationIT.java
+++
b/nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/restart/FlowFileRestorationIT.java
@@ -31,6 +31,7 @@ import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
+import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -39,6 +40,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class FlowFileRestorationIT extends NiFiSystemIT {
+ private static final int SWAP_THRESHOLD = 20;
+
+ @Override
+ protected Map<String, String> getNifiPropertiesOverrides() {
+ return Map.of("nifi.queue.swap.threshold",
String.valueOf(SWAP_THRESHOLD));
+ }
@Test
public void testDataInMissingQueueRestoredWhenQueueRestored() throws
NiFiClientException, IOException, InterruptedException {
@@ -85,6 +92,52 @@ public class FlowFileRestorationIT extends NiFiSystemIT {
assertArrayEquals(flowFileContents, contentsAfterRestart);
}
+ @Test
+ public void testSwappedFlowFileOrderPreservedAfterRestart() throws
NiFiClientException, IOException, InterruptedException {
+ final int flowFileCount = 100;
+ final int newerFlowFileCount = 2;
+ ProcessorEntity generate =
getClientUtil().createProcessor(GENERATE_FLOWFILE);
+ generate = getClientUtil().updateProcessorProperties(generate,
Map.of("Batch Size", String.valueOf(flowFileCount), "sequence",
"${nextInt()}"));
+
+ ProcessorEntity verifyOrder =
getClientUtil().createProcessor("VerifySequentialOrder");
+ verifyOrder = getClientUtil().updateProcessorProperties(verifyOrder,
Map.of("Value to Consider", "${sequence}"));
+ final ConnectionEntity connection =
getClientUtil().updateConnectionPrioritizer(getClientUtil().createConnection(generate,
verifyOrder, SUCCESS), "FirstInFirstOutPrioritizer");
+
+ final ProcessorEntity terminate =
getClientUtil().createProcessor(TERMINATE_FLOWFILE);
+ final ConnectionEntity sequentialConnection =
getClientUtil().createConnection(verifyOrder, terminate, "sequential");
+ final ConnectionEntity failureConnection =
getClientUtil().createConnection(verifyOrder, terminate, "failure");
+
+ generate = getClientUtil().runProcessorOnce(generate);
+ getClientUtil().waitForStoppedProcessor(generate.getId());
+ waitForQueueCount(connection.getId(), flowFileCount);
+
+ // The oldest FlowFiles are held in memory and the rest are written to
swap files. Process as many of the oldest FlowFiles as the number
+ // of newer FlowFiles and then queue the newer FlowFiles, which wait
behind the swapped FlowFiles. All FlowFiles held in memory then fit
+ // within the swap threshold when they are restored.
+ for (int i = 0; i < newerFlowFileCount; i++) {
+ verifyOrder = getClientUtil().runProcessorOnce(verifyOrder);
+ getClientUtil().waitForStoppedProcessor(verifyOrder.getId());
+ }
+
+ generate =
getNifiClient().getProcessorClient().getProcessor(generate.getId());
+ generate = getClientUtil().updateProcessorProperties(generate,
Map.of("Batch Size", String.valueOf(newerFlowFileCount)));
+ generate = getClientUtil().runProcessorOnce(generate);
+ getClientUtil().waitForStoppedProcessor(generate.getId());
+ waitForQueueCount(connection.getId(), flowFileCount);
+ assertEquals(SWAP_THRESHOLD - newerFlowFileCount,
getClientUtil().performQueueListing(connection.getId()).getListingRequest().getFlowFileSummaries().size());
+
+ final NiFiInstance nifiInstance = getNiFiInstance();
+ nifiInstance.stop();
+ nifiInstance.start();
+ waitForQueueCount(connection.getId(), flowFileCount);
+
+ // Process all FlowFiles, including the swapped FlowFiles. Each
FlowFile must be processed directly after the FlowFile created before it.
+ verifyOrder =
getNifiClient().getProcessorClient().getProcessor(verifyOrder.getId());
+ getClientUtil().startProcessor(verifyOrder);
+ waitFor(() -> getConnectionQueueSize(sequentialConnection.getId()) +
getConnectionQueueSize(failureConnection.getId()) == flowFileCount +
newerFlowFileCount);
+ assertEquals(0, getConnectionQueueSize(failureConnection.getId()));
+ }
+
private byte[] getFlowFileContents(final String connectionId, final int
flowFileIndex) throws IOException, NiFiClientException {
try (final InputStream in =
getClientUtil().getFlowFileContent(connectionId, flowFileIndex);
final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {