You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@nifi.apache.org by "markap14 (via GitHub)" <gi...@apache.org> on 2026/04/20 21:11:32 UTC
[PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
markap14 opened a new pull request, #11164:
URL: https://github.com/apache/nifi/pull/11164
…e bounding how many tasks can be run at once
<!-- 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. -->
# Summary
[NIFI-00000](https://issues.apache.org/jira/browse/NIFI-00000)
# Tracking
Please complete the following tracking steps prior to pull request creation.
### Issue Tracking
- [Apache NiFi Jira](https://issues.apache.org/jira/browse/NIFI) issue created
### Pull Request Tracking
- Pull Request title starts with Apache NiFi Jira issue number, such as `NIFI-00000`
- Pull Request commit message starts with Apache NiFi Jira issue number, as such `NIFI-00000`
- Pull request contains [commits signed](https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits) with a registered key indicating `Verified` status
### Pull Request Formatting
- Pull Request based on current revision of the `main` branch
- Pull Request refers to a feature branch with one commit containing changes
# Verification
Please indicate the verification steps performed prior to pull request creation.
### Build
- [ ] Build completed using `./mvnw clean install -P contrib-check`
- [ ] JDK 21
- [ ] JDK 25
### Licensing
- [ ] New dependencies are compatible with the [Apache License 2.0](https://apache.org/licenses/LICENSE-2.0) according to the [License Policy](https://www.apache.org/legal/resolved.html)
- [ ] New dependencies are documented in applicable `LICENSE` and `NOTICE` files
### Documentation
- [ ] Documentation formatting appears as expected in rendered files
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-4442252182
I decided to go ahead and add something to nifi.properties that would allow us to enable/disable the virtual threads. This is a significant enough change that it's worth adding the ability to quickly disable if we find any issues.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5706264297
[gpt-sol-5.6] The **macos-15 Java 21** system-test shard failed in [`ClusteredConnectorTroubleshootingIT.testConfigurationAndAuthoritativeFlowRestoredAfterTroubleshootingRestart`](https://github.com/apache/nifi/actions/runs/35152336670/job/104983428762):
```
org.opentest4j.AssertionFailedError: Running Connector must write the configured sensitive value to the configured Sensitive Output File ==> expected: <configured-secret-value> but was: <>
at org.apache.nifi.tests.system.connectors.ConnectorTroubleshootingIT.testConfigurationAndAuthoritativeFlowRestoredAfterTroubleshootingRestart(ConnectorTroubleshootingIT.java:1036)
at java.base/java.lang.reflect.Method.invoke(Method.java:580)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
```
I downloaded and checked the troubleshooting archive. This is a pre-existing timing flaw in this unrelated Connector test: it waits only for both shared output files to exist before reading them, while either clustered node can create or truncate a file before writing its content. The node logs show both connectors starting successfully and both nodes subsequently writing 23 bytes to the same sensitive-output path, with no NiFi error. I have rerun only the failed shard.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5640299412
[GPT-5.6 Sol] @joewitt you were right on both counts. Thank you again for putting this much real effort into the review—and for continuing to spelunk through the scheduler cave with a flashlight and an alarmingly effective goblin detector. This is exactly the kind of quality review that makes a change like this safer.
Addressed in the latest commits:
- 97d0afe7ea1 keeps the framework `FlowEngine` at eight threads when virtual scheduling is active. UI changes to the component limit now resize only the virtual-thread semaphore, and the active component-thread metric no longer includes framework housekeeping work. Standard scheduling still sizes and resizes the platform pool from the configured component limit.
- d39ac04ebaf changes the default system-test profile to `AUTO`, so Java 21 exercises standard scheduling and Java 25 exercises virtual scheduling. Clustered and Python profiles remain explicitly `VIRTUAL`, and `VirtualThreadStartStopCycleIT` continues to force `VIRTUAL` for focused coverage.
The 47 focused framework tests pass, as do Checkstyle and PMD. Fresh CI will run the complete Java 21/25 system-test matrix.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "pvillard31 (via GitHub)" <gi...@apache.org>.
pvillard31 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3188014336
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,564 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Scheduling agent that runs processors, funnels, ports, and reporting tasks on virtual
+ * threads rather than on a shared thread pool. A single {@link DynamicSemaphore} bounds
+ * the number of invocations that may run concurrently across the entire flow. Its permit
+ * count replaces the old Timer-Driven thread pool size and is adjustable at runtime via
+ * {@link #setMaxThreadCount(int)}.
+ * <p>
+ * The agent is used for both {@link SchedulingStrategy#TIMER_DRIVEN} and
+ * {@link SchedulingStrategy#CRON_DRIVEN} connectables. Each scheduled connectable is given
+ * one virtual thread per concurrent task; every iteration of the scheduling loop acquires
+ * a permit, calls {@link ConnectableTask#invoke()}, releases the permit, and then sleeps
+ * until the next invocation is due.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ /**
+ * Sleeps in the scheduling loop are broken up into chunks of at most this long so that
+ * a processor that is unscheduled while a scheduling thread is sleeping will exit the
+ * sleep and observe the state change quickly rather than having to wait for the full
+ * scheduling period to elapse.
+ */
+ private static final long POLL_INTERVAL_NANOS = TimeUnit.MILLISECONDS.toNanos(25L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private final Set<Thread> runningThreads = ConcurrentHashMap.newKeySet();
+ private volatile boolean shutdown = false;
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new RuntimeException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration);
+ }
+ }
+
+ /**
+ * Marks the agent as shut down and interrupts every virtual thread that is currently running a scheduling loop,
+ * a run-once invocation, or a reporting-task loop. After {@code shutdown()} returns, subsequent calls to any of
+ * the {@code schedule} methods will fail fast with {@link IllegalStateException}. This method is idempotent and
+ * may be called multiple times (for example, both on the {@code kill} path in {@code FlowController.shutdown}
+ * and again from {@code StandardProcessScheduler.shutdown}). Interrupts are a best-effort mechanism: processor
+ * code that does not honor interruption will continue to run until it completes naturally, but the virtual
+ * threads themselves are daemon threads and will be reaped when the JVM exits.
+ */
+ @Override
+ public void shutdown() {
+ shutdown = true;
+ int interrupted = 0;
+ for (final Thread thread : runningThreads) {
+ thread.interrupt();
+ interrupted++;
+ }
+ if (interrupted > 0) {
+ logger.info("Shutdown interrupted {} virtual threads managed by the VirtualThreadSchedulingAgent", interrupted);
+ }
+ }
+
+ /**
+ * Schedules the given connectable to run on virtual threads. This method transitions the
+ * {@link LifecycleState} to scheduled and then spawns one virtual thread per concurrent task. Each scheduling loop
+ * captures {@link LifecycleState#getLastStopTime()} at startup and will exit as soon as either
+ * {@link LifecycleState#isScheduled()} becomes {@code false} or the last-stop-time advances, which is how the
+ * agent guards against a rapid stop/start cycle leaving prior loops running alongside newly-spawned ones. The
+ * corresponding {@link #unschedule(Connectable, LifecycleState)} call performs the inverse transition. Calling
+ * {@code setScheduled(true)} here is intentionally idempotent: the framework scheduler also marks the state as
+ * scheduled in some code paths (for example, reporting-task startup), and double-calling is harmless because the
+ * last-stop-time only advances on transitions to the stopped state.
+ */
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final CronExpression cronExpression;
+ if (connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ } else {
+ cronExpression = null;
+ }
+
+ // setScheduled(true) is idempotent with the state the framework already set before calling into the agent.
+ // It is done here too so that the agent is self-consistent even for callers that do not follow the framework
+ // contract, but it also means that if anything below fails we MUST roll it back: otherwise the component
+ // would be left flagged as scheduled with zero (or a partial set of) scheduling loops actually running.
+ // Any loops that did start before the failure will exit on their next isActive() check when the rollback
+ // flips the flag back to false.
+ lifecycleState.setScheduled(true);
+ try {
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ startTrackedVirtualThread(threadName, () -> runSchedulingLoop(connectable, connectableTask, lifecycleState, startStopTime, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ } catch (final Throwable t) {
+ lifecycleState.setScheduled(false);
+ throw t;
+ }
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ lifecycleState.setScheduled(true);
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ startTrackedVirtualThread(threadName, () -> runOnce(connectable, connectableTask, stopCallback));
+ } catch (final Throwable t) {
+ lifecycleState.setScheduled(false);
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ lifecycleState.setScheduled(true);
+ try {
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ startTrackedVirtualThread(threadName,
+ () -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, startStopTime));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ } catch (final Throwable t) {
+ lifecycleState.setScheduled(false);
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ /**
+ * @return {@code true} if {@code lifecycleState} is still scheduled and its last-stop-time has not changed since
+ * the scheduling loop was spawned (meaning the loop is still running against its original scheduling generation).
+ * Used by the scheduling loops and their polling helpers to detect both the normal stop path (isScheduled flips to
+ * false) and the rapid stop/start race (a stop increments lastStopTime even if a quick restart flips isScheduled
+ * back to true before the old loop has observed the stop).
+ */
+ private boolean isActive(final LifecycleState lifecycleState, final long startStopTime) {
+ return lifecycleState.isScheduled() && lifecycleState.getLastStopTime() == startStopTime;
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public synchronized void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ int getRunningThreadCount() {
+ return runningThreads.size();
+ }
+
+ boolean isShutdown() {
+ return shutdown;
+ }
+
+ /**
+ * @return the number of virtual threads that are currently executing a processor or
+ * reporting-task invocation. A thread counts as active when it is holding a permit on
+ * the global semaphore, which mirrors the old Timer-Driven engine's active-count
+ * semantics used by the cluster heartbeat and UI active-thread counter.
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getInUsePermits();
+ }
+
+ /**
+ * Runs the scheduling loop for a {@link Connectable}. Each iteration acquires a permit from the global semaphore,
+ * invokes the connectable, releases the permit, and sleeps until the next invocation is due. The entire body of
+ * the loop is wrapped in a {@code try/catch(Throwable)} so that no exception or error -- including
+ * {@link Error} subclasses or bugs in the scheduling logic itself -- can cause the virtual thread to terminate
+ * silently. A processor is expected to continue being triggered as long as it is scheduled, so on any unexpected
+ * {@link Throwable} the error is logged, an administrative yield is applied to prevent tight-looping on a broken
+ * task, and the loop continues on its next iteration.
+ */
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask,
+ final LifecycleState lifecycleState, final long startStopTime, final CronExpression cronExpression) {
+
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the component", connectable);
+ return;
+ }
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), lifecycleState, startStopTime);
+ }
+ }
+
+ while (isActive(lifecycleState, startStopTime)) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, startStopTime)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting", connectable);
+ return;
+ }
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(sleepMillis), lifecycleState, startStopTime);
+ } else {
+ sleepForSchedulingPeriod(connectable, lifecycleState, startStopTime, invocationResult);
+ }
+ } catch (final Throwable t) {
+ // Nothing in the loop body is expected to throw (ConnectableTask.invoke() catches Throwable itself, and
+ // acquirePermitWithPolling handles InterruptedException). If anything does escape to here, it must not
+ // be allowed to kill the scheduling virtual thread: as long as the component remains scheduled we will
+ // keep triggering it. Log the error, apply an administrative yield to avoid tight-looping on a broken
+ // invocation, and continue with the next iteration.
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback) {
+ try {
+ try {
+ globalSemaphore.acquire();
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+
+ try {
+ connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+ } catch (final Throwable t) {
+ logger.error("Unexpected error running {} once", connectable, t);
+ } finally {
+ try {
+ stopCallback.call();
+ } catch (final Throwable t) {
+ logger.error("Error while stopping {} after running once", connectable, t);
+ }
+ }
+ }
+
+ /**
+ * Runs the reporting-task scheduling loop. As with {@link #runSchedulingLoop}, the loop body is wrapped in a
+ * {@code try/catch(Throwable)} so that no unexpected failure can cause the virtual thread to exit. A reporting
+ * task is expected to continue running until it is unscheduled. When {@code cronExpression} is non-null the loop
+ * sleeps until the next CRON firing; otherwise it sleeps for {@code schedulingNanos} after each run.
+ */
+ private void runReportingTaskLoop(final ReportingTaskNode taskNode, final Runnable reportingTaskWrapper, final long schedulingNanos,
+ final CronExpression cronExpression, final LifecycleState lifecycleState, final long startStopTime) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the reporting task",
+ taskNode.getReportingTask());
+ return;
+ }
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), lifecycleState, startStopTime);
+ }
+ }
+
+ while (isActive(lifecycleState, startStopTime)) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, startStopTime)) {
+ return;
+ }
+
+ try {
+ reportingTaskWrapper.run();
+ } finally {
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting",
+ taskNode.getReportingTask());
+ return;
+ }
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(sleepMillis), lifecycleState, startStopTime);
+ } else {
+ sleepWithPolling(schedulingNanos, lifecycleState, startStopTime);
+ }
+ } catch (final Throwable t) {
+ // ReportingTaskWrapper.run() is expected to catch Throwable itself, so reaching this handler indicates
+ // an unexpected framework-level failure. Log and continue so that one bad invocation does not
+ // permanently kill the scheduling loop for this reporting task.
+ logger.error("Unexpected error in scheduling loop for {}. Continuing on next scheduled interval.", taskNode.getReportingTask(), t);
+ }
+ }
+ }
+
+ private void sleepForSchedulingPeriod(final Connectable connectable, final LifecycleState lifecycleState, final long startStopTime,
+ final InvocationResult invocationResult) {
+ final long sleepNanos;
+ final long yieldExpiration = connectable.getYieldExpiration();
+ final long now = System.currentTimeMillis();
+ if (yieldExpiration > now) {
+ sleepNanos = TimeUnit.MILLISECONDS.toNanos(yieldExpiration - now);
+ } else if (invocationResult.isYield()) {
+ sleepNanos = noWorkYieldNanos;
+ } else {
+ sleepNanos = connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ sleepWithPolling(sleepNanos, lifecycleState, startStopTime);
+ }
+
+ /**
+ * Attempts to acquire a permit from the global semaphore, waking up periodically to re-check whether the
+ * scheduling generation this loop belongs to is still active. This prevents a scheduling thread from blocking
+ * indefinitely on {@link DynamicSemaphore#acquire()} when the flow is heavily loaded and the component has been
+ * unscheduled; without this, stopping a processor while all global permits were held elsewhere would have to wait
+ * for one of those other processors to release a permit before the stop could take effect.
+ *
+ * @return {@code true} if a permit was acquired (the caller MUST release it), {@code false} if the scheduling
+ * generation ended (i.e., the component was stopped) or the thread was interrupted before a permit could be acquired
+ */
+ private boolean acquirePermitWithPolling(final LifecycleState lifecycleState, final long startStopTime) {
+ while (isActive(lifecycleState, startStopTime)) {
+ try {
+ if (globalSemaphore.tryAcquire(POLL_INTERVAL_NANOS, TimeUnit.NANOSECONDS)) {
+ return true;
+ }
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Sleeps for approximately {@code sleepNanos}, waking up periodically to check whether the scheduling generation
+ * this loop belongs to is still active. This allows a stop/unschedule request to take effect promptly even when
+ * the scheduling period is long: rather than calling {@code Thread.sleep(sleepNanos)} and forcing the caller to
+ * wait out the entire delay, the sleep is broken into chunks of at most {@link #POLL_INTERVAL_NANOS} and the
+ * generation is re-checked between chunks. Returns immediately if {@code sleepNanos <= 0} so that a zero
+ * scheduling period (run-as-fast-as-possible) does not incur any artificial delay.
+ */
+ private void sleepWithPolling(final long sleepNanos, final LifecycleState lifecycleState, final long startStopTime) {
+ if (sleepNanos <= 0L) {
+ return;
+ }
+
+ final long sleepExpiration = System.nanoTime() + sleepNanos;
+ while (isActive(lifecycleState, startStopTime)) {
+ final long remainingNanos = sleepExpiration - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ return;
+ }
+
+ final long chunkNanos = Math.min(remainingNanos, POLL_INTERVAL_NANOS);
+ try {
+ TimeUnit.NANOSECONDS.sleep(chunkNanos);
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+ }
+ }
+
+ private static String buildThreadName(final Connectable connectable, final int taskIndex) {
+ return connectable.getName() + "[type=" + connectable.getComponentType() + ", id=" + connectable.getIdentifier()
Review Comment:
What if the user renames the component and/or its parent group? would that be properly reflected?
##########
nifi-framework-api/src/main/java/org/apache/nifi/diagnostics/ThreadDumpTask.java:
##########
@@ -16,116 +16,51 @@
*/
package org.apache.nifi.diagnostics;
-import java.lang.management.LockInfo;
+import com.sun.management.HotSpotDiagnosticMXBean;
+
+import java.io.IOException;
import java.lang.management.ManagementFactory;
-import java.lang.management.MonitorInfo;
-import java.lang.management.ThreadInfo;
-import java.lang.management.ThreadMXBean;
-import java.util.ArrayList;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Objects;
+/**
+ * Captures a textual dump of every thread in the JVM. Uses
+ * {@link HotSpotDiagnosticMXBean#dumpThreads(String, HotSpotDiagnosticMXBean.ThreadDumpFormat)}
+ * so that virtual threads are included in the dump alongside platform threads.
+ */
public class ThreadDumpTask implements DiagnosticTask {
- @Override
- public DiagnosticsDumpElement captureDump(boolean verbose) {
- final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
-
- final ThreadInfo[] infos = mbean.dumpAllThreads(true, true);
- final long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
- final long[] monitorDeadlockThreadIds = mbean.findMonitorDeadlockedThreads();
-
- final List<ThreadInfo> sortedInfos = new ArrayList<>(infos.length);
- Collections.addAll(sortedInfos, infos);
- sortedInfos.sort(new Comparator<>() {
- @Override
- public int compare(ThreadInfo o1, ThreadInfo o2) {
- return o1.getThreadName().toLowerCase().compareTo(o2.getThreadName().toLowerCase());
- }
- });
-
- final StringBuilder sb = new StringBuilder();
- for (final ThreadInfo info : sortedInfos) {
- sb.append("\n");
- sb.append("\"").append(info.getThreadName()).append("\" Id=");
- sb.append(info.getThreadId()).append(" ");
- sb.append(info.getThreadState().toString()).append(" ");
-
- switch (info.getThreadState()) {
- case BLOCKED:
- case TIMED_WAITING:
- case WAITING:
- sb.append(" on ");
- sb.append(info.getLockInfo());
- break;
- default:
- break;
- }
-
- if (info.isSuspended()) {
- sb.append(" (suspended)");
- }
- if (info.isInNative()) {
- sb.append(" (in native code)");
- }
-
- if (deadlockedThreadIds != null) {
- for (final long id : deadlockedThreadIds) {
- if (id == info.getThreadId()) {
- sb.append(" ** DEADLOCKED THREAD **");
- }
- }
- }
- if (monitorDeadlockThreadIds != null) {
- for (final long id : monitorDeadlockThreadIds) {
- if (id == info.getThreadId()) {
- sb.append(" ** MONITOR-DEADLOCKED THREAD **");
- }
- }
- }
-
- final StackTraceElement[] stackTraces = info.getStackTrace();
- for (final StackTraceElement element : stackTraces) {
- sb.append("\n\tat ").append(element);
-
- final MonitorInfo[] monitors = info.getLockedMonitors();
- for (final MonitorInfo monitor : monitors) {
- if (Objects.equals(monitor.getLockedStackFrame(), element)) {
- sb.append("\n\t- waiting on ").append(monitor);
- }
- }
+ @Override
+ public DiagnosticsDumpElement captureDump(final boolean verbose) {
+ String threadDump;
+
+ Path tempDirectory = null;
+ try {
+ final HotSpotDiagnosticMXBean diagnosticMXBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
+ // dumpThreads requires that the destination file does not already exist. Creating a private
+ // temporary directory and writing to a fresh filename inside it avoids a time-of-check to
+ // time-of-use race that would exist if we created a temp file and then deleted it before the
+ // dumpThreads call.
+ tempDirectory = Files.createTempDirectory("nifi-thread-dump-");
+ final Path tempFile = tempDirectory.resolve("thread-dump.txt");
+ try {
+ diagnosticMXBean.dumpThreads(tempFile.toString(), HotSpotDiagnosticMXBean.ThreadDumpFormat.TEXT_PLAIN);
+ threadDump = Files.readString(tempFile);
+ } finally {
+ Files.deleteIfExists(tempFile);
}
-
- final LockInfo[] lockInfos = info.getLockedSynchronizers();
- if (lockInfos.length > 0) {
- sb.append("\n\t");
- sb.append("Number of Locked Synchronizers: ").append(lockInfos.length);
- for (final LockInfo lockInfo : lockInfos) {
- sb.append("\n\t- ").append(lockInfo.toString());
+ } catch (final IOException e) {
+ threadDump = "Failed to capture thread dump: " + e.getMessage();
+ } finally {
+ if (tempDirectory != null) {
+ try {
+ Files.deleteIfExists(tempDirectory);
+ } catch (final IOException ignored) {
Review Comment:
Should we at least log this at debug so that a recurring failure to delete nifi-thread-dump-* directories is discoverable?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-4434355527
[claude-opus-4.7] @markap14 important: I had to revert my last push.
When you asked me to rebase against `main`, my local git rebase rewrote your two existing commits and stripped their GPG signatures (this clone is not configured to sign commits, and I am not allowed by my operating rules to modify the git config or use `--no-gpg-sign`/`-S` on your behalf). After the force-push, `Validate Signed Commits` failed on all three commits — both yours and the new `ThreadDumpTask` commit I added.
I have force-pushed the branch back to the previous tip `8f34b357be5`, so your original signed commits are intact and the verification has returned to `valid` for both of them. The PR is back to where it was before I touched it today.
What still needs to happen, in your hands:
1. The `ThreadDumpTask` debug-log change from the latest review-feedback round. The one-line patch is:
```diff
- } catch (final IOException ignored) {
+ } catch (final IOException e) {
+ logger.debug(\"Failed to delete temporary thread-dump directory {}\", tempDirectory, e);
}
```
(plus the `org.slf4j.Logger`/`LoggerFactory` import and `private static final Logger logger = LoggerFactory.getLogger(ThreadDumpTask.class);` field at the top of the class). I can post the full unified diff if useful.
2. Whether to actually rebase against `main`. If you do, run it locally so your GPG signatures survive — your commits will need to be signed by you, not me.
Sorry for the churn. Watcher subagent is stopping until you let me know how you'd like to proceed.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5643756633
Put a second pair and can get to 450K EPS which saturates CPU.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "pvillard31 (via GitHub)" <gi...@apache.org>.
pvillard31 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3125769844
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Scheduling agent that runs processors, funnels, ports, and reporting tasks on virtual
+ * threads rather than on a shared thread pool. A single {@link DynamicSemaphore} bounds
+ * the number of invocations that may run concurrently across the entire flow. Its permit
+ * count replaces the old Timer-Driven thread pool size and is adjustable at runtime via
+ * {@link #setMaxThreadCount(int)}.
+ * <p>
+ * The agent is used for both {@link SchedulingStrategy#TIMER_DRIVEN} and
+ * {@link SchedulingStrategy#CRON_DRIVEN} connectables. Each scheduled connectable is given
+ * one virtual thread per concurrent task; every iteration of the scheduling loop acquires
+ * a permit, calls {@link ConnectableTask#invoke()}, releases the permit, and then sleeps
+ * until the next invocation is due.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ /**
+ * Sleeps in the scheduling loop are broken up into chunks of at most this long so that
+ * a processor that is unscheduled while a scheduling thread is sleeping will exit the
+ * sleep and observe the state change quickly rather than having to wait for the full
+ * scheduling period to elapse.
+ */
+ private static final long POLL_INTERVAL_NANOS = TimeUnit.MILLISECONDS.toNanos(25L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new RuntimeException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration);
+ }
+ }
+
+ @Override
+ public void shutdown() {
+ }
+
+ /**
+ * Schedules the given connectable to run on virtual threads. This method transitions the
+ * {@link LifecycleState} to scheduled and then spawns one virtual thread per concurrent task. Each scheduling loop
+ * captures {@link LifecycleState#getLastStopTime()} at startup and will exit as soon as either
+ * {@link LifecycleState#isScheduled()} becomes {@code false} or the last-stop-time advances, which is how the
+ * agent guards against a rapid stop/start cycle leaving prior loops running alongside newly-spawned ones. The
+ * corresponding {@link #unschedule(Connectable, LifecycleState)} call performs the inverse transition. Calling
+ * {@code setScheduled(true)} here is intentionally idempotent: the framework scheduler also marks the state as
+ * scheduled in some code paths (for example, reporting-task startup), and double-calling is harmless because the
+ * last-stop-time only advances on transitions to the stopped state.
+ */
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final CronExpression cronExpression;
+ if (connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ } else {
+ cronExpression = null;
+ }
+
+ lifecycleState.setScheduled(true);
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ Thread.ofVirtual().name(threadName).start(() -> runSchedulingLoop(connectable, connectableTask, lifecycleState, startStopTime, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ lifecycleState.setScheduled(true);
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ Thread.ofVirtual().name(threadName).start(() -> runOnce(connectable, connectableTask, stopCallback));
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ lifecycleState.setScheduled(true);
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ Thread.ofVirtual().name(threadName).start(() -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, startStopTime));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ /**
+ * @return {@code true} if {@code lifecycleState} is still scheduled and its last-stop-time has not changed since
+ * the scheduling loop was spawned (meaning the loop is still running against its original scheduling generation).
+ * Used by the scheduling loops and their polling helpers to detect both the normal stop path (isScheduled flips to
+ * false) and the rapid stop/start race (a stop increments lastStopTime even if a quick restart flips isScheduled
+ * back to true before the old loop has observed the stop).
+ */
+ private boolean isActive(final LifecycleState lifecycleState, final long startStopTime) {
+ return lifecycleState.isScheduled() && lifecycleState.getLastStopTime() == startStopTime;
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ /**
+ * @return the number of virtual threads that are currently executing a processor or
+ * reporting-task invocation. A thread counts as active when it is holding a permit on
+ * the global semaphore, which mirrors the old Timer-Driven engine's active-count
+ * semantics used by the cluster heartbeat and UI active-thread counter.
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getMaxPermits() - globalSemaphore.availablePermits();
+ }
+
+ /**
+ * Runs the scheduling loop for a {@link Connectable}. Each iteration acquires a permit from the global semaphore,
+ * invokes the connectable, releases the permit, and sleeps until the next invocation is due. The entire body of
+ * the loop is wrapped in a {@code try/catch(Throwable)} so that no exception or error -- including
+ * {@link Error} subclasses or bugs in the scheduling logic itself -- can cause the virtual thread to terminate
+ * silently. A processor is expected to continue being triggered as long as it is scheduled, so on any unexpected
+ * {@link Throwable} the error is logged, an administrative yield is applied to prevent tight-looping on a broken
+ * task, and the loop continues on its next iteration.
+ */
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask,
+ final LifecycleState lifecycleState, final long startStopTime, final CronExpression cronExpression) {
+
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), lifecycleState, startStopTime);
+ }
+ }
+
+ while (isActive(lifecycleState, startStopTime)) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, startStopTime)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(sleepMillis), lifecycleState, startStopTime);
+ } else {
+ sleepForSchedulingPeriod(connectable, lifecycleState, startStopTime, invocationResult);
+ }
+ } catch (final Throwable t) {
+ // Nothing in the loop body is expected to throw (ConnectableTask.invoke() catches Throwable itself, and
+ // acquirePermitWithPolling handles InterruptedException). If anything does escape to here, it must not
+ // be allowed to kill the scheduling virtual thread: as long as the component remains scheduled we will
+ // keep triggering it. Log the error, apply an administrative yield to avoid tight-looping on a broken
+ // invocation, and continue with the next iteration.
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback) {
+ try {
+ try {
+ globalSemaphore.acquire();
Review Comment:
Should we use `acquirePermitWithPolling`?
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Scheduling agent that runs processors, funnels, ports, and reporting tasks on virtual
+ * threads rather than on a shared thread pool. A single {@link DynamicSemaphore} bounds
+ * the number of invocations that may run concurrently across the entire flow. Its permit
+ * count replaces the old Timer-Driven thread pool size and is adjustable at runtime via
+ * {@link #setMaxThreadCount(int)}.
+ * <p>
+ * The agent is used for both {@link SchedulingStrategy#TIMER_DRIVEN} and
+ * {@link SchedulingStrategy#CRON_DRIVEN} connectables. Each scheduled connectable is given
+ * one virtual thread per concurrent task; every iteration of the scheduling loop acquires
+ * a permit, calls {@link ConnectableTask#invoke()}, releases the permit, and then sleeps
+ * until the next invocation is due.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ /**
+ * Sleeps in the scheduling loop are broken up into chunks of at most this long so that
+ * a processor that is unscheduled while a scheduling thread is sleeping will exit the
+ * sleep and observe the state change quickly rather than having to wait for the full
+ * scheduling period to elapse.
+ */
+ private static final long POLL_INTERVAL_NANOS = TimeUnit.MILLISECONDS.toNanos(25L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new RuntimeException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration);
+ }
+ }
+
+ @Override
+ public void shutdown() {
+ }
+
+ /**
+ * Schedules the given connectable to run on virtual threads. This method transitions the
+ * {@link LifecycleState} to scheduled and then spawns one virtual thread per concurrent task. Each scheduling loop
+ * captures {@link LifecycleState#getLastStopTime()} at startup and will exit as soon as either
+ * {@link LifecycleState#isScheduled()} becomes {@code false} or the last-stop-time advances, which is how the
+ * agent guards against a rapid stop/start cycle leaving prior loops running alongside newly-spawned ones. The
+ * corresponding {@link #unschedule(Connectable, LifecycleState)} call performs the inverse transition. Calling
+ * {@code setScheduled(true)} here is intentionally idempotent: the framework scheduler also marks the state as
+ * scheduled in some code paths (for example, reporting-task startup), and double-calling is harmless because the
+ * last-stop-time only advances on transitions to the stopped state.
+ */
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final CronExpression cronExpression;
+ if (connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ } else {
+ cronExpression = null;
+ }
+
+ lifecycleState.setScheduled(true);
Review Comment:
Should we have a try/catch here? Something like `try { ... } catch (Throwable) { lifecycleState.setScheduled(false); ...; throw; }`. If there is a problem with the loop after, we would leave it as scheduled, no?
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Scheduling agent that runs processors, funnels, ports, and reporting tasks on virtual
+ * threads rather than on a shared thread pool. A single {@link DynamicSemaphore} bounds
+ * the number of invocations that may run concurrently across the entire flow. Its permit
+ * count replaces the old Timer-Driven thread pool size and is adjustable at runtime via
+ * {@link #setMaxThreadCount(int)}.
+ * <p>
+ * The agent is used for both {@link SchedulingStrategy#TIMER_DRIVEN} and
+ * {@link SchedulingStrategy#CRON_DRIVEN} connectables. Each scheduled connectable is given
+ * one virtual thread per concurrent task; every iteration of the scheduling loop acquires
+ * a permit, calls {@link ConnectableTask#invoke()}, releases the permit, and then sleeps
+ * until the next invocation is due.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ /**
+ * Sleeps in the scheduling loop are broken up into chunks of at most this long so that
+ * a processor that is unscheduled while a scheduling thread is sleeping will exit the
+ * sleep and observe the state change quickly rather than having to wait for the full
+ * scheduling period to elapse.
+ */
+ private static final long POLL_INTERVAL_NANOS = TimeUnit.MILLISECONDS.toNanos(25L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new RuntimeException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration);
+ }
+ }
+
+ @Override
+ public void shutdown() {
+ }
+
+ /**
+ * Schedules the given connectable to run on virtual threads. This method transitions the
+ * {@link LifecycleState} to scheduled and then spawns one virtual thread per concurrent task. Each scheduling loop
+ * captures {@link LifecycleState#getLastStopTime()} at startup and will exit as soon as either
+ * {@link LifecycleState#isScheduled()} becomes {@code false} or the last-stop-time advances, which is how the
+ * agent guards against a rapid stop/start cycle leaving prior loops running alongside newly-spawned ones. The
+ * corresponding {@link #unschedule(Connectable, LifecycleState)} call performs the inverse transition. Calling
+ * {@code setScheduled(true)} here is intentionally idempotent: the framework scheduler also marks the state as
+ * scheduled in some code paths (for example, reporting-task startup), and double-calling is harmless because the
+ * last-stop-time only advances on transitions to the stopped state.
+ */
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final CronExpression cronExpression;
+ if (connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ } else {
+ cronExpression = null;
+ }
+
+ lifecycleState.setScheduled(true);
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ Thread.ofVirtual().name(threadName).start(() -> runSchedulingLoop(connectable, connectableTask, lifecycleState, startStopTime, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ lifecycleState.setScheduled(true);
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ Thread.ofVirtual().name(threadName).start(() -> runOnce(connectable, connectableTask, stopCallback));
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ lifecycleState.setScheduled(true);
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ Thread.ofVirtual().name(threadName).start(() -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, startStopTime));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ /**
+ * @return {@code true} if {@code lifecycleState} is still scheduled and its last-stop-time has not changed since
+ * the scheduling loop was spawned (meaning the loop is still running against its original scheduling generation).
+ * Used by the scheduling loops and their polling helpers to detect both the normal stop path (isScheduled flips to
+ * false) and the rapid stop/start race (a stop increments lastStopTime even if a quick restart flips isScheduled
+ * back to true before the old loop has observed the stop).
+ */
+ private boolean isActive(final LifecycleState lifecycleState, final long startStopTime) {
+ return lifecycleState.isScheduled() && lifecycleState.getLastStopTime() == startStopTime;
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
Review Comment:
`incrementMaxThreadCount` is synchronized but `setMaxThreadCount` is not. Feels like we could have an update race condition, no?
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java:
##########
Review Comment:
IIUC you didn't make any change on the shutdown path so we do not attempt to interrupt in-flight component virtual threads and the kill of the JVM will just kill threads. That seems wrong, no?
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java:
##########
@@ -2133,13 +2132,14 @@ public int getMaxTimerDrivenThreadCount() {
}
public int getActiveTimerDrivenThreadCount() {
- return timerDrivenEngineRef.get().getActiveCount();
+ return timerDrivenEngineRef.get().getActiveCount() + virtualThreadSchedulingAgent.getActiveThreadCount();
}
public void setMaxTimerDrivenThreadCount(final int maxThreadCount) {
writeLock.lock();
try {
setMaxThreadCount(maxThreadCount, "Timer Driven", this.timerDrivenEngineRef.get(), this.maxTimerDrivenThreads);
+ virtualThreadSchedulingAgent.setMaxThreadCount(maxThreadCount);
Review Comment:
IIUC we now use the maxThreadCount value in two different places: the FlowEngine thread pool and the semaphore for the VT agent. Should we have separate properties?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5640687503
[GPT-5.6 Sol] The [Ubuntu Java 21 integration check](https://github.com/apache/nifi/actions/runs/34644804139/job/103413074126) failed in the unchanged SMB extension:
```
org.opentest4j.AssertionFailedError: expected: <1> but was: <0>
at org.apache.nifi.util.StandardProcessorTestRunner.assertTransferCount(StandardProcessorTestRunner.java:406)
at org.apache.nifi.processors.smb.ListSmbIT.testInitialListingStrategy(ListSmbIT.java:296)
at org.apache.nifi.processors.smb.ListSmbIT.testInitialListingStrategyNewFiles(ListSmbIT.java:265)
```
This is a pre-existing timing flake: [the exact same assertion failed on an unrelated PR two days ago](https://github.com/apache/nifi/actions/runs/34399658415), and this branch does not change the SMB processor or its test framework. The test compares millisecond JVM time with timestamps returned by the SMB container; the container timestamp can fall behind the recorded boundary because of its timestamp precision. I have rerun only the failed integration-test workflow.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5689105003
[GPT-5.6 Sol] The workflow has completed, so I have now rerun the failed [Scan check](https://github.com/apache/nifi/actions/runs/35031764646/job/104591644809). As noted above, the original attempt failed before compilation when Maven Central temporarily reported `org.apache:apache:pom:39` as absent.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639763405
Interrupt status kills the scheduling loop — share this
This is a real behavioral change versus the current pool.
Today, TimerDrivenSchedulingAgent submits a short-lived Runnable to FlowEngine. After onTrigger returns, that task is done. The next fire is a new executor task on a worker that has a clean interrupt flag. Processors that catch InterruptedException and do the textbook Thread.currentThread().interrupt() are therefore fine.
On this PR, each concurrent task is one virtual thread that never dies:
invoke() → waitForDelay() → acquirePermitWithPolling() → invoke() …
If onTrigger leaves the interrupt flag set:
waitForDelay() hits CountDownLatch.await and immediately throws InterruptedException.
The catch restores the interrupt (Thread.currentThread().interrupt()).
Next iteration, tryAcquire(...) throws immediately.
acquirePermitWithPolling returns false, and runSchedulingLoop returns.
The Processor stays RUNNING. The generation is still registered. Nothing reschedules that task. UI/thread count can look healthy. Throughput for that concurrent slot is just gone until stop/start.
I reproduced the primitive on JDK 21: a platform-pool worker’s next task is not interrupted; a persistent virtual thread that restored interrupt does fail the next timed wait.
This is not exotic. NiFi itself does this (e.g. DebugFlow, ExecuteProcess, ConsumeKafka backlog path, AMQP, Kinesis, HDFS, Listen processors). Any extension that “restores interrupt status and returns” is now a silent death sentence for that scheduling chain.
Ask Mark to either:
clear interrupt at a defined framework boundary after onTrigger unless shutdown/unschedule requested the interrupt, or
use a fresh virtual thread per invocation (old model, virtualized), or
treat interrupt as “this invocation was cancelled” and continue the loop if lifecycleState.isScheduled().
A regression test is easy: Processor that interrupt()s itself in onTrigger must fire again without a restart. Same for a Reporting Task.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3229384337
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,564 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Scheduling agent that runs processors, funnels, ports, and reporting tasks on virtual
+ * threads rather than on a shared thread pool. A single {@link DynamicSemaphore} bounds
+ * the number of invocations that may run concurrently across the entire flow. Its permit
+ * count replaces the old Timer-Driven thread pool size and is adjustable at runtime via
+ * {@link #setMaxThreadCount(int)}.
+ * <p>
+ * The agent is used for both {@link SchedulingStrategy#TIMER_DRIVEN} and
+ * {@link SchedulingStrategy#CRON_DRIVEN} connectables. Each scheduled connectable is given
+ * one virtual thread per concurrent task; every iteration of the scheduling loop acquires
+ * a permit, calls {@link ConnectableTask#invoke()}, releases the permit, and then sleeps
+ * until the next invocation is due.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ /**
+ * Sleeps in the scheduling loop are broken up into chunks of at most this long so that
+ * a processor that is unscheduled while a scheduling thread is sleeping will exit the
+ * sleep and observe the state change quickly rather than having to wait for the full
+ * scheduling period to elapse.
+ */
+ private static final long POLL_INTERVAL_NANOS = TimeUnit.MILLISECONDS.toNanos(25L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private final Set<Thread> runningThreads = ConcurrentHashMap.newKeySet();
+ private volatile boolean shutdown = false;
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new RuntimeException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration);
+ }
+ }
+
+ /**
+ * Marks the agent as shut down and interrupts every virtual thread that is currently running a scheduling loop,
+ * a run-once invocation, or a reporting-task loop. After {@code shutdown()} returns, subsequent calls to any of
+ * the {@code schedule} methods will fail fast with {@link IllegalStateException}. This method is idempotent and
+ * may be called multiple times (for example, both on the {@code kill} path in {@code FlowController.shutdown}
+ * and again from {@code StandardProcessScheduler.shutdown}). Interrupts are a best-effort mechanism: processor
+ * code that does not honor interruption will continue to run until it completes naturally, but the virtual
+ * threads themselves are daemon threads and will be reaped when the JVM exits.
+ */
+ @Override
+ public void shutdown() {
+ shutdown = true;
+ int interrupted = 0;
+ for (final Thread thread : runningThreads) {
+ thread.interrupt();
+ interrupted++;
+ }
+ if (interrupted > 0) {
+ logger.info("Shutdown interrupted {} virtual threads managed by the VirtualThreadSchedulingAgent", interrupted);
+ }
+ }
+
+ /**
+ * Schedules the given connectable to run on virtual threads. This method transitions the
+ * {@link LifecycleState} to scheduled and then spawns one virtual thread per concurrent task. Each scheduling loop
+ * captures {@link LifecycleState#getLastStopTime()} at startup and will exit as soon as either
+ * {@link LifecycleState#isScheduled()} becomes {@code false} or the last-stop-time advances, which is how the
+ * agent guards against a rapid stop/start cycle leaving prior loops running alongside newly-spawned ones. The
+ * corresponding {@link #unschedule(Connectable, LifecycleState)} call performs the inverse transition. Calling
+ * {@code setScheduled(true)} here is intentionally idempotent: the framework scheduler also marks the state as
+ * scheduled in some code paths (for example, reporting-task startup), and double-calling is harmless because the
+ * last-stop-time only advances on transitions to the stopped state.
+ */
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final CronExpression cronExpression;
+ if (connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ } else {
+ cronExpression = null;
+ }
+
+ // setScheduled(true) is idempotent with the state the framework already set before calling into the agent.
+ // It is done here too so that the agent is self-consistent even for callers that do not follow the framework
+ // contract, but it also means that if anything below fails we MUST roll it back: otherwise the component
+ // would be left flagged as scheduled with zero (or a partial set of) scheduling loops actually running.
+ // Any loops that did start before the failure will exit on their next isActive() check when the rollback
+ // flips the flag back to false.
+ lifecycleState.setScheduled(true);
+ try {
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ startTrackedVirtualThread(threadName, () -> runSchedulingLoop(connectable, connectableTask, lifecycleState, startStopTime, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ } catch (final Throwable t) {
+ lifecycleState.setScheduled(false);
+ throw t;
+ }
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ lifecycleState.setScheduled(true);
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ startTrackedVirtualThread(threadName, () -> runOnce(connectable, connectableTask, stopCallback));
+ } catch (final Throwable t) {
+ lifecycleState.setScheduled(false);
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ lifecycleState.setScheduled(true);
+ try {
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ startTrackedVirtualThread(threadName,
+ () -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, startStopTime));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ } catch (final Throwable t) {
+ lifecycleState.setScheduled(false);
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ /**
+ * @return {@code true} if {@code lifecycleState} is still scheduled and its last-stop-time has not changed since
+ * the scheduling loop was spawned (meaning the loop is still running against its original scheduling generation).
+ * Used by the scheduling loops and their polling helpers to detect both the normal stop path (isScheduled flips to
+ * false) and the rapid stop/start race (a stop increments lastStopTime even if a quick restart flips isScheduled
+ * back to true before the old loop has observed the stop).
+ */
+ private boolean isActive(final LifecycleState lifecycleState, final long startStopTime) {
+ return lifecycleState.isScheduled() && lifecycleState.getLastStopTime() == startStopTime;
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public synchronized void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ int getRunningThreadCount() {
+ return runningThreads.size();
+ }
+
+ boolean isShutdown() {
+ return shutdown;
+ }
+
+ /**
+ * @return the number of virtual threads that are currently executing a processor or
+ * reporting-task invocation. A thread counts as active when it is holding a permit on
+ * the global semaphore, which mirrors the old Timer-Driven engine's active-count
+ * semantics used by the cluster heartbeat and UI active-thread counter.
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getInUsePermits();
+ }
+
+ /**
+ * Runs the scheduling loop for a {@link Connectable}. Each iteration acquires a permit from the global semaphore,
+ * invokes the connectable, releases the permit, and sleeps until the next invocation is due. The entire body of
+ * the loop is wrapped in a {@code try/catch(Throwable)} so that no exception or error -- including
+ * {@link Error} subclasses or bugs in the scheduling logic itself -- can cause the virtual thread to terminate
+ * silently. A processor is expected to continue being triggered as long as it is scheduled, so on any unexpected
+ * {@link Throwable} the error is logged, an administrative yield is applied to prevent tight-looping on a broken
+ * task, and the loop continues on its next iteration.
+ */
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask,
+ final LifecycleState lifecycleState, final long startStopTime, final CronExpression cronExpression) {
+
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the component", connectable);
+ return;
+ }
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), lifecycleState, startStopTime);
+ }
+ }
+
+ while (isActive(lifecycleState, startStopTime)) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, startStopTime)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting", connectable);
+ return;
+ }
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(sleepMillis), lifecycleState, startStopTime);
+ } else {
+ sleepForSchedulingPeriod(connectable, lifecycleState, startStopTime, invocationResult);
+ }
+ } catch (final Throwable t) {
+ // Nothing in the loop body is expected to throw (ConnectableTask.invoke() catches Throwable itself, and
+ // acquirePermitWithPolling handles InterruptedException). If anything does escape to here, it must not
+ // be allowed to kill the scheduling virtual thread: as long as the component remains scheduled we will
+ // keep triggering it. Log the error, apply an administrative yield to avoid tight-looping on a broken
+ // invocation, and continue with the next iteration.
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback) {
+ try {
+ try {
+ globalSemaphore.acquire();
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+
+ try {
+ connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+ } catch (final Throwable t) {
+ logger.error("Unexpected error running {} once", connectable, t);
+ } finally {
+ try {
+ stopCallback.call();
+ } catch (final Throwable t) {
+ logger.error("Error while stopping {} after running once", connectable, t);
+ }
+ }
+ }
+
+ /**
+ * Runs the reporting-task scheduling loop. As with {@link #runSchedulingLoop}, the loop body is wrapped in a
+ * {@code try/catch(Throwable)} so that no unexpected failure can cause the virtual thread to exit. A reporting
+ * task is expected to continue running until it is unscheduled. When {@code cronExpression} is non-null the loop
+ * sleeps until the next CRON firing; otherwise it sleeps for {@code schedulingNanos} after each run.
+ */
+ private void runReportingTaskLoop(final ReportingTaskNode taskNode, final Runnable reportingTaskWrapper, final long schedulingNanos,
+ final CronExpression cronExpression, final LifecycleState lifecycleState, final long startStopTime) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the reporting task",
+ taskNode.getReportingTask());
+ return;
+ }
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), lifecycleState, startStopTime);
+ }
+ }
+
+ while (isActive(lifecycleState, startStopTime)) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, startStopTime)) {
+ return;
+ }
+
+ try {
+ reportingTaskWrapper.run();
+ } finally {
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting",
+ taskNode.getReportingTask());
+ return;
+ }
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(sleepMillis), lifecycleState, startStopTime);
+ } else {
+ sleepWithPolling(schedulingNanos, lifecycleState, startStopTime);
+ }
+ } catch (final Throwable t) {
+ // ReportingTaskWrapper.run() is expected to catch Throwable itself, so reaching this handler indicates
+ // an unexpected framework-level failure. Log and continue so that one bad invocation does not
+ // permanently kill the scheduling loop for this reporting task.
+ logger.error("Unexpected error in scheduling loop for {}. Continuing on next scheduled interval.", taskNode.getReportingTask(), t);
+ }
+ }
+ }
+
+ private void sleepForSchedulingPeriod(final Connectable connectable, final LifecycleState lifecycleState, final long startStopTime,
+ final InvocationResult invocationResult) {
+ final long sleepNanos;
+ final long yieldExpiration = connectable.getYieldExpiration();
+ final long now = System.currentTimeMillis();
+ if (yieldExpiration > now) {
+ sleepNanos = TimeUnit.MILLISECONDS.toNanos(yieldExpiration - now);
+ } else if (invocationResult.isYield()) {
+ sleepNanos = noWorkYieldNanos;
+ } else {
+ sleepNanos = connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ sleepWithPolling(sleepNanos, lifecycleState, startStopTime);
+ }
+
+ /**
+ * Attempts to acquire a permit from the global semaphore, waking up periodically to re-check whether the
+ * scheduling generation this loop belongs to is still active. This prevents a scheduling thread from blocking
+ * indefinitely on {@link DynamicSemaphore#acquire()} when the flow is heavily loaded and the component has been
+ * unscheduled; without this, stopping a processor while all global permits were held elsewhere would have to wait
+ * for one of those other processors to release a permit before the stop could take effect.
+ *
+ * @return {@code true} if a permit was acquired (the caller MUST release it), {@code false} if the scheduling
+ * generation ended (i.e., the component was stopped) or the thread was interrupted before a permit could be acquired
+ */
+ private boolean acquirePermitWithPolling(final LifecycleState lifecycleState, final long startStopTime) {
+ while (isActive(lifecycleState, startStopTime)) {
+ try {
+ if (globalSemaphore.tryAcquire(POLL_INTERVAL_NANOS, TimeUnit.NANOSECONDS)) {
+ return true;
+ }
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Sleeps for approximately {@code sleepNanos}, waking up periodically to check whether the scheduling generation
+ * this loop belongs to is still active. This allows a stop/unschedule request to take effect promptly even when
+ * the scheduling period is long: rather than calling {@code Thread.sleep(sleepNanos)} and forcing the caller to
+ * wait out the entire delay, the sleep is broken into chunks of at most {@link #POLL_INTERVAL_NANOS} and the
+ * generation is re-checked between chunks. Returns immediately if {@code sleepNanos <= 0} so that a zero
+ * scheduling period (run-as-fast-as-possible) does not incur any artificial delay.
+ */
+ private void sleepWithPolling(final long sleepNanos, final LifecycleState lifecycleState, final long startStopTime) {
+ if (sleepNanos <= 0L) {
+ return;
+ }
+
+ final long sleepExpiration = System.nanoTime() + sleepNanos;
+ while (isActive(lifecycleState, startStopTime)) {
+ final long remainingNanos = sleepExpiration - System.nanoTime();
+ if (remainingNanos <= 0L) {
+ return;
+ }
+
+ final long chunkNanos = Math.min(remainingNanos, POLL_INTERVAL_NANOS);
+ try {
+ TimeUnit.NANOSECONDS.sleep(chunkNanos);
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return;
+ }
+ }
+ }
+
+ private static String buildThreadName(final Connectable connectable, final int taskIndex) {
+ return connectable.getName() + "[type=" + connectable.getComponentType() + ", id=" + connectable.getIdentifier()
Review Comment:
The thread name would get generated whenever the Processor is started. It would not change. The only ways to change it would be to track all Virtual Thread objects so that setName could update them, or to constantly update it to whatever the current name is. Both introduce a decent bit of complexity for what I'd argue is fairly minimal gain. Especially since I don't think we even allow changing the name of the processor while it's running from the UI. I think the REST tier does allow it, but the UI would not, though I may be mistaken.
##########
nifi-framework-api/src/main/java/org/apache/nifi/diagnostics/ThreadDumpTask.java:
##########
@@ -16,116 +16,51 @@
*/
package org.apache.nifi.diagnostics;
-import java.lang.management.LockInfo;
+import com.sun.management.HotSpotDiagnosticMXBean;
+
+import java.io.IOException;
import java.lang.management.ManagementFactory;
-import java.lang.management.MonitorInfo;
-import java.lang.management.ThreadInfo;
-import java.lang.management.ThreadMXBean;
-import java.util.ArrayList;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Objects;
+/**
+ * Captures a textual dump of every thread in the JVM. Uses
+ * {@link HotSpotDiagnosticMXBean#dumpThreads(String, HotSpotDiagnosticMXBean.ThreadDumpFormat)}
+ * so that virtual threads are included in the dump alongside platform threads.
+ */
public class ThreadDumpTask implements DiagnosticTask {
- @Override
- public DiagnosticsDumpElement captureDump(boolean verbose) {
- final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
-
- final ThreadInfo[] infos = mbean.dumpAllThreads(true, true);
- final long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
- final long[] monitorDeadlockThreadIds = mbean.findMonitorDeadlockedThreads();
-
- final List<ThreadInfo> sortedInfos = new ArrayList<>(infos.length);
- Collections.addAll(sortedInfos, infos);
- sortedInfos.sort(new Comparator<>() {
- @Override
- public int compare(ThreadInfo o1, ThreadInfo o2) {
- return o1.getThreadName().toLowerCase().compareTo(o2.getThreadName().toLowerCase());
- }
- });
-
- final StringBuilder sb = new StringBuilder();
- for (final ThreadInfo info : sortedInfos) {
- sb.append("\n");
- sb.append("\"").append(info.getThreadName()).append("\" Id=");
- sb.append(info.getThreadId()).append(" ");
- sb.append(info.getThreadState().toString()).append(" ");
-
- switch (info.getThreadState()) {
- case BLOCKED:
- case TIMED_WAITING:
- case WAITING:
- sb.append(" on ");
- sb.append(info.getLockInfo());
- break;
- default:
- break;
- }
-
- if (info.isSuspended()) {
- sb.append(" (suspended)");
- }
- if (info.isInNative()) {
- sb.append(" (in native code)");
- }
-
- if (deadlockedThreadIds != null) {
- for (final long id : deadlockedThreadIds) {
- if (id == info.getThreadId()) {
- sb.append(" ** DEADLOCKED THREAD **");
- }
- }
- }
- if (monitorDeadlockThreadIds != null) {
- for (final long id : monitorDeadlockThreadIds) {
- if (id == info.getThreadId()) {
- sb.append(" ** MONITOR-DEADLOCKED THREAD **");
- }
- }
- }
-
- final StackTraceElement[] stackTraces = info.getStackTrace();
- for (final StackTraceElement element : stackTraces) {
- sb.append("\n\tat ").append(element);
-
- final MonitorInfo[] monitors = info.getLockedMonitors();
- for (final MonitorInfo monitor : monitors) {
- if (Objects.equals(monitor.getLockedStackFrame(), element)) {
- sb.append("\n\t- waiting on ").append(monitor);
- }
- }
+ @Override
+ public DiagnosticsDumpElement captureDump(final boolean verbose) {
+ String threadDump;
+
+ Path tempDirectory = null;
+ try {
+ final HotSpotDiagnosticMXBean diagnosticMXBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
+ // dumpThreads requires that the destination file does not already exist. Creating a private
+ // temporary directory and writing to a fresh filename inside it avoids a time-of-check to
+ // time-of-use race that would exist if we created a temp file and then deleted it before the
+ // dumpThreads call.
+ tempDirectory = Files.createTempDirectory("nifi-thread-dump-");
+ final Path tempFile = tempDirectory.resolve("thread-dump.txt");
+ try {
+ diagnosticMXBean.dumpThreads(tempFile.toString(), HotSpotDiagnosticMXBean.ThreadDumpFormat.TEXT_PLAIN);
+ threadDump = Files.readString(tempFile);
+ } finally {
+ Files.deleteIfExists(tempFile);
}
-
- final LockInfo[] lockInfos = info.getLockedSynchronizers();
- if (lockInfos.length > 0) {
- sb.append("\n\t");
- sb.append("Number of Locked Synchronizers: ").append(lockInfos.length);
- for (final LockInfo lockInfo : lockInfos) {
- sb.append("\n\t- ").append(lockInfo.toString());
+ } catch (final IOException e) {
+ threadDump = "Failed to capture thread dump: " + e.getMessage();
+ } finally {
+ if (tempDirectory != null) {
+ try {
+ Files.deleteIfExists(tempDirectory);
+ } catch (final IOException ignored) {
Review Comment:
Sure, that's reasonalbe.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639529664
[GPT-5.6 Sol] @exceptionfactory good suggestion. Commit c78511de928 replaces the boolean with `nifi.scheduler.mode`, backed by a `ComponentSchedulingMode` enum with `STANDARD` and `VIRTUAL` values. Invalid values now fail during startup instead of silently selecting an implementation.
I kept `VIRTUAL` as the default because the earlier rollout discussion settled on default-on with `STANDARD` as the escape hatch. The new push also starts a fresh `MacOS Zulu JDK 21 JP` run, so the pre-existing test race reported above will be retested on the current head instead of rerunning the superseded workflow.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639826769
Mark —
On the 25 millisecond permit wait: I want to make sure we are comparing this to what timer-driven scheduling does today, not to a busy loop.
Today. Each concurrent task is a delayed future on the existing FlowEngine pool. If the Processor is not due yet, it sits in the delayed queue. If it is due and all of the max timer-driven threads are already in onTrigger, it sits in the executor queue. There is no thread dedicated to that waiting task. Stop of a task that is not currently in onTrigger is cancel(false), which typically takes it off the queue immediately. Nothing wakes periodically just to ask “do I have a slot yet?”
This change. Each concurrent task is a long-lived virtual thread for the whole time the component is RUNNING. When it cannot get a permit from the global semaphore, that thread parks in tryAcquire(25 milliseconds), wakes, checks whether it is still scheduled, and parks again. That loop does not exist on main.
That is why the 25 millisecond interval is there: unschedule still does not interrupt an in-flight onTrigger, same as today’s cancel(false). A thread blocked in a plain acquire() would not notice Stop until a permit showed up. Polling is the compromise so a waiter can leave when the component is stopped.
Where it is not worse. While a Processor is in onTrigger, Stop still waits for the invocation to return. Between invocations, you wait on the generation latch; unschedule can wake that wait immediately, which is at least as good as canceling a delayed future.
Where it is a bit worse. The cost shows up only when work is queued behind the max-thread cap: scheduled concurrent tasks that do not currently hold a permit. Each of those virtual threads wakes about 40 times per second. That is new framework overhead. Stop of a waiter can also take up to 25 milliseconds, versus today’s cancel of a queued future, which is usually immediate.
On a small graph, or when almost everyone already has a permit, this will not matter. On a large canvas with a small max thread count and many one-thread Processors, we pay a wait-for-capacity tax that the current pool does not pay. I do not think that is a merge blocker, but it is a real before-and-after difference.
A cleaner shape, if you want Stop and permit handoff to stay as immediate as today: a condition that both unschedule and release signal, so waiters are not on a 25 millisecond timer.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639933977
[GPT-5.6 Sol] @joewitt follow-up on permit waiting: after reviewing the targeted wake-up approach, we chose to keep the simpler bounded wait and increased the interval from 25 milliseconds to 1 second in 947b12a4902. `tryAcquire` still returns immediately when a permit is released, so this does not delay normal permit handoff. It reduces timeout wakeups by 40× while bounding Stop detection at one second when no permit becomes available. All 27 `VirtualThreadSchedulingAgentTest` tests pass, including the fully contended unschedule case.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "exceptionfactory (via GitHub)" <gi...@apache.org>.
exceptionfactory commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r4029836154
##########
nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/controller/StandardProcessorNode.java:
##########
@@ -574,7 +574,7 @@ public void yield() {
@Override
Review Comment:
The `getActiveThreads()` method still uses the map of `ThreadInfo` objects, which looks like it could lead to a NullPointerException if it is called while a Processor is running under a Virtual Thread. Can you take a closer look at that method and evaluate the implications?
##########
nifi-framework-api/src/main/java/org/apache/nifi/diagnostics/ThreadDumpTask.java:
##########
@@ -16,116 +16,139 @@
*/
package org.apache.nifi.diagnostics;
+import com.sun.management.HotSpotDiagnosticMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
+/**
+ * Captures platform and virtual thread stack traces when supported by the Java runtime.
+ */
public class ThreadDumpTask implements DiagnosticTask {
+
+ private static final Logger logger = LoggerFactory.getLogger(ThreadDumpTask.class);
+
@Override
- public DiagnosticsDumpElement captureDump(boolean verbose) {
- final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
-
- final ThreadInfo[] infos = mbean.dumpAllThreads(true, true);
- final long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
- final long[] monitorDeadlockThreadIds = mbean.findMonitorDeadlockedThreads();
-
- final List<ThreadInfo> sortedInfos = new ArrayList<>(infos.length);
- Collections.addAll(sortedInfos, infos);
- sortedInfos.sort(new Comparator<>() {
- @Override
- public int compare(ThreadInfo o1, ThreadInfo o2) {
- return o1.getThreadName().toLowerCase().compareTo(o2.getThreadName().toLowerCase());
+ public DiagnosticsDumpElement captureDump(final boolean verbose) {
+ final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
+ final String threadDump = captureThreadDump(threadMXBean);
+
+ final StringBuilder dumpBuilder = new StringBuilder(threadDump);
+ appendDeadlockedThreadIds(dumpBuilder, "DEADLOCK DETECTED", threadMXBean.findDeadlockedThreads());
+ appendDeadlockedThreadIds(dumpBuilder, "MONITOR DEADLOCK DETECTED", threadMXBean.findMonitorDeadlockedThreads());
+
+ return new StandardDiagnosticsDumpElement("Thread Dump", Collections.singletonList(dumpBuilder.toString()));
+ }
+
+ private String captureThreadDump(final ThreadMXBean threadMXBean) {
+ try {
+ return captureHotSpotThreadDump();
+ } catch (final IOException | RuntimeException | LinkageError e) {
+ logger.warn("Failed to capture virtual threads using the HotSpot diagnostic interface; capturing platform threads instead", e);
+ return capturePlatformThreadDump(threadMXBean);
+ }
+ }
+
+ private String captureHotSpotThreadDump() throws IOException {
+ final HotSpotDiagnosticMXBean diagnosticMXBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
+ if (diagnosticMXBean == null) {
+ throw new UnsupportedOperationException("HotSpot diagnostic interface is not available");
+ }
+
+ final Path tempDirectory = Files.createTempDirectory("nifi-thread-dump-");
+ final Path tempFile = tempDirectory.resolve("thread-dump.txt");
+ try {
Review Comment:
For tracing, what do you think about using the current class name for these files?
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,627 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.Triggerable;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.nar.NarThreadContextClassLoader;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Scheduling agent that runs components on virtual threads. A {@link DynamicSemaphore}
+ * limits the number of component invocations that can run concurrently.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ private static final long PERMIT_POLL_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(1L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private final ExecutorService executorService;
+ private final ConcurrentMap<String, SchedulingGeneration> schedulingGenerations = new ConcurrentHashMap<>();
+ private final AtomicBoolean shutdown = new AtomicBoolean();
+ private final AtomicInteger runningThreadCount = new AtomicInteger();
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new IllegalStateException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration, e);
+ }
+
+ final ThreadFactory threadFactory = runnable -> {
+ final Thread thread = Thread.ofVirtual().inheritInheritableThreadLocals(false).unstarted(runnable);
+ thread.setContextClassLoader(NarThreadContextClassLoader.getInstance());
+ return thread;
+ };
+ executorService = Executors.newThreadPerTaskExecutor(threadFactory);
+ logger.info("VirtualThreadSchedulingAgent initialized with {} permits", maxThreadCount);
+ }
+
+ @Override
+ public void shutdown() {
+ signalShutdown(true);
+ executorService.shutdownNow();
+ }
+
+ public void shutdownGracefully() {
+ signalShutdown(false);
+ executorService.shutdown();
+ }
+
+ private void signalShutdown(final boolean interrupt) {
+ shutdown.set(true);
+
+ for (final SchedulingGeneration generation : schedulingGenerations.values()) {
+ generation.stop(interrupt);
+ }
+ }
+
+ public boolean awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException {
+ return executorService.awaitTermination(timeout, timeUnit);
+ }
+
+ public boolean isTerminated() {
+ return executorService.isTerminated();
+ }
+
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final boolean cronDriven = connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ submitTask(threadName, generation, () -> runSchedulingLoop(connectable, connectableTask, schedulingNanos, lifecycleState, generation, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ submitTask(threadName, generation, () -> {
+ try {
+ runOnce(connectable, connectableTask, stopCallback, lifecycleState, generation);
+ } finally {
+ stopSchedulingGeneration(componentId, generation, false);
+ }
+ });
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(connectable.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = taskNode.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ submitTask(threadName, generation,
+ () -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, generation));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(taskNode.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ private SchedulingGeneration registerSchedulingGeneration(final String componentId) {
+ if (shutdown.get()) {
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ final SchedulingGeneration generation = new SchedulingGeneration();
+ final SchedulingGeneration existingGeneration = schedulingGenerations.putIfAbsent(componentId, generation);
+ if (existingGeneration != null) {
+ throw new IllegalStateException("Component " + componentId + " is already scheduled");
+ }
+
+ if (shutdown.get()) {
+ stopSchedulingGeneration(componentId, generation, true);
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ return generation;
+ }
+
+ private boolean stopSchedulingGeneration(final String componentId, final SchedulingGeneration generation, final boolean interrupt) {
+ final boolean removed = schedulingGenerations.remove(componentId, generation);
+ generation.stop(interrupt);
+ return removed;
+ }
+
+ private boolean isActive(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ return !shutdown.get() && lifecycleState.isScheduled() && !generation.isStopped();
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public synchronized void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ int getRunningThreadCount() {
+ return runningThreadCount.get();
+ }
+
+ boolean isShutdown() {
+ return shutdown.get();
+ }
+
+ /**
+ * @return number of component invocations currently holding global permits
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getInUsePermits();
+ }
+
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask, final long schedulingNanos,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation, final CronExpression cronExpression) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the component", connectable);
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting", connectable);
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForNextInvocation(connectable, schedulingNanos, generation, invocationResult);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ if (isActive(lifecycleState, generation)) {
+ logger.warn("Run once request for {} was not executed because permit acquisition was interrupted", connectable);
+ } else {
+ logger.warn("Run once request for {} was not executed because scheduling is no longer active", connectable);
+ }
+
+ return;
+ }
+
+ try {
+ connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+ } catch (final Throwable t) {
+ logger.error("Unexpected error running {} once", connectable, t);
+ } finally {
+ try {
+ stopCallback.call();
+ } catch (final Throwable t) {
+ logger.error("Error while stopping {} after running once", connectable, t);
+ }
+ }
+ }
+
+ private void runReportingTaskLoop(final ReportingTaskNode taskNode, final Runnable reportingTaskWrapper, final long schedulingNanos,
+ final CronExpression cronExpression, final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the reporting task",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ reportingTaskWrapper.run();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForDelay(schedulingNanos, generation);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will wait for {} and continue.", taskNode.getReportingTask(), adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void waitForNextInvocation(final Connectable connectable, final long schedulingNanos, final SchedulingGeneration generation,
+ final InvocationResult invocationResult) {
+ final long sleepNanos;
+ final long yieldExpiration = connectable.getYieldExpiration();
+ final long yieldDelayNanos;
+ if (yieldExpiration == 0L) {
+ yieldDelayNanos = 0L;
+ } else {
+ yieldDelayNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(yieldExpiration - System.currentTimeMillis(), 0L));
+ }
+
+ if (yieldDelayNanos > 0L) {
+ sleepNanos = Math.max(schedulingNanos, yieldDelayNanos);
+ } else if (invocationResult.isYield()) {
+ sleepNanos = noWorkYieldNanos > 0L ? noWorkYieldNanos : schedulingNanos;
+ } else {
+ sleepNanos = schedulingNanos;
+ }
+
+ waitForDelay(sleepNanos, generation);
+ }
+
+ private boolean acquirePermitWithPolling(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
Review Comment:
Thanks for the reply. For clarity, I was referring to a race between `acquirePermitWithPolling()` and `invoke()`. Can you take a closer look at the relationship between those method calls?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5643610345
Whoa. Testing a GenerateFF to UpdateAttr flow before this PR yields 150,000 EPS on my laptop. With this PR it jumps to 250,000 EPS. The virtual threads provide at least in this scenario dramatically better lock handling/hand-offs. The bottleneck now is just lock contention on the queue/connection when pulling flowfiles. Wow.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639834336
@markap14 left three chunky comments from various findings after wrestling through it with Cursor. Ignored the ones that didn't seem worthy and focused on what look like real findings. I'll keep an eye on this important change and will get to hands on live testing too once we're a little further.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639478672
[GPT-5.6 Sol] CI failure on `MacOS Zulu JDK 21 JP` — classified as a pre-existing test race; the failed shard will be rerun after the parent workflow completes.
**Failed check:** `MacOS Zulu JDK 21 JP` — https://github.com/apache/nifi/actions/runs/34631800449/job/103370270431
**Failing test:** `org.apache.nifi.controller.scheduling.TestStandardProcessScheduler.validateNeverEnablingServiceCanStillBeDisabled`
```
org.opentest4j.AssertionFailedError: expected: <0> but was: <1>
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:569)
at org.apache.nifi.controller.scheduling.TestStandardProcessScheduler.validateNeverEnablingServiceCanStillBeDisabled(TestStandardProcessScheduler.java:563)
```
This failure is unrelated to the PR. The test and controller-service lifecycle implementation are unchanged. The test calls asynchronous `disableControllerService()` and then immediately asserts that `@OnDisabled` has not run; on this runner, the callback completed quickly enough for the count to reach 1 first. The only branch diff in `StandardProcessScheduler` is comment wording in `startConnectable()`.
**Plan:** rerun only this failed shard once run 34631800449 completes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5640406192
I have never felt so appreciated. " Thank you again for putting this much real effort into the review—and for continuing to spelunk through the scheduler cave with a flashlight and an alarmingly effective goblin detector. This is exactly the kind of quality review that makes a change like this safer." Classic.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639769379
Virtual threads do not each get an OS thread. They share a small pool of carrier platform threads (ForkJoin, ~core count).
When a virtual thread does a JDK-managed blocking call (Socket.read, Lock.lock, Semaphore.acquire, most java.net/java.nio), the JVM unmounts it: the carrier is free to run someone else. That’s the win.
Pinning means the virtual thread cannot unmount. The carrier sits idle in that blocking call as if it were a normal platform thread. If all carriers are pinned, no other virtual thread in the JVM can run — including unrelated Processors, reporting tasks, and (in this PR) framework tasks that also use virtual threads.
On JDK 21 (what NiFi 2 still supports and CI still runs), a virtual thread is pinned if it blocks:
inside synchronized / while waiting to enter synchronized / in Object.wait
in native/JNI / Panama
in a few leftover JDK paths (class init, some file I/O)
Concrete NiFi case: Processor holds synchronized (this) or a connection monitor and then does JDBC/HttpClient I/O. That is extremely common in older NARs and in libraries we did not write. Eight such concurrent tasks on an 8-core box can pin every carrier. Then a ListenTCP / ConsumeKafka / funnel that would have unmounted is stuck behind those eight.
JDK 24+ (JEP 491) largely fixes monitor pinning. Native pinning remains. Hadoop/HDFS, some crypto, some compression, some Python/JNI bridges still pin.
Why this is different from the current engine: today’s timer pool threads are OS threads. Blocking in synchronized just blocks that one worker. The other 9 pool threads keep running. There is no “whole scheduler stalls because 8 monitors pinned 8 carriers.”
ReportingTaskWrapper dropping synchronized is the right framework hygiene. It does not make customer NARs safe.
What to tell Mark: if default stays on, JDK 21 is a product risk, not a theoretical Loom footnote. Either default off until 24/25 is the floor, or ship with JFR jdk.VirtualThreadPinned guidance and a known-bad list. I would not block the code on this; I would block default-on on JDK 21.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5648132513
# Follow-on notes from validating NIFI-15862 (virtual-thread scheduling)
These notes are **not** a review of the scheduling-agent change itself. I have been running Mark’s `nifi-15862-virtual-threads` work (`NIFI-15862` / https://github.com/apache/nifi/pull/11164) as the baseline, with the goal of seeing whether virtual threads actually raise FlowFile/sec on a CPU-bound loop — and then whether leftover engine hotspots, once VT is in play, are worth a **later, separate PR**.
Nothing below is meant to block or expand this PR. The lock / map / comparator patches are local follow-on experiments.
## What we were trying to learn
1. Does VT scheduling keep the engine busy on a flow that is **not** disk-bound (0-byte FlowFiles, volatile repos)?
2. When we stack independent Generate → UpdateAttribute loops, does throughput **add**, or do the pairs steal from each other?
3. If they steal, is that the scheduler, virtual-thread pinning, or an older engine lock/allocation path that VTs just make more obvious?
## Test setup
- **Build:** NiFi `2.12.0-SNAPSHOT` on branch `nifi-15862-virtual-threads`
- **JDK:** Azul Zulu 25, macOS, 16 cores
- **Heap:** 16g (`-Xms16g -Xmx16g`)
- **Repos (deliberate, so we are not measuring WAL/content disk):**
- `nifi.flowfile.repository.implementation=org.apache.nifi.controller.repository.VolatileFlowFileRepository`
- `nifi.provenance.repository.implementation=org.apache.nifi.provenance.VolatileProvenanceRepository`
- **Scheduling:** `nifi.scheduling.strategy=AUTO` (virtual threads on this JDK), controller `maxTimerDriven=64`
- **Flow:** one process group with independent pairs of GenerateFlowFile → UpdateAttribute
- 0-byte FlowFiles
- Generate batch size 1000
- no user prioritizers on the connections
- pair 4 left stopped; three pairs running for the stacked tests
- concurrent tasks were not uniform (one UpdateAttribute was at 20, others at 5; Generates at 4–5). Extra concurrent tasks on a single pair did **not** move the needle much once the pair was already saturated.
- **What we refused to do for the benchmark:** skip provenance event construction, NoOp provenance, or otherwise disable work the engine would do in a real flow. Volatile repos only avoid *persistence*, not in-memory event/attribute work.
### How we measured
NiFi’s processor status `flowFilesOut` is a **5-minute rolling window**. Dividing that by 300 is a decent steady-state rate after the window is full; a 30-second delta of those counters is **wrong** once the window is sliding (old seconds drop off → negative “rates”). After a restart, 30-second deltas of the filling 5-minute counters *are* usable.
We therefore treated:
- 5-minute Generate out / 300 as the long-run rate
- 30-second deltas only when the window was filling from a restart, or when we knew the counters were monotonic
- `top` / load average / heap from system-diagnostics as the machine picture
- JFR (`profile` settings) plus park-stack aggregation to see *why* CPU stopped scaling
## Results on Mark’s code (before any follow-on patches)
| Configuration | Approx. Generate throughput | Notes |
|---|---|---|
| 1 pair | ~163k FF/s, later ~252k FF/s | same loop; later number after the JVM/flow had warmed |
| 2 pairs | ~526k FF/s (about 252k + 274k) | **adds** — this is the encouraging VT result |
| 3 pairs, extra threads | **did not add**; pairs stole from each other | CPU ~660%, disk idle, ~30% sys time |
So: virtual threads **do** let two independent CPU-bound loops run together. A third pair did not buy a third of the machine; the ceiling was not disk and not “we ran out of platform threads.”
### JFR (3-pair steal, still fair queue locks)
Ruled **out**:
- content/repo disk (idle)
- virtual-thread **pinning** (no pinned-thread events in the recording)
Ruled **in** (hot / park stacks):
- `ReentrantReadWriteLock` **fair** path (`hasQueuedPredecessors`) on `SwappablePriorityQueue` put/poll — VT park convoy on every FlowFile
- provenance attribute handling (`unmodifiableMap` / enrich)
- `PriorityQueue.siftDown` / `QueuePrioritizer.compare`
- ConcurrentHashMap / UpdateAttribute attribute-map churn
The scheduler itself was not the thing we were parked on.
## Follow-on changes (local, for a later PR)
All of these sit on top of NIFI-15862. They are engine-path tweaks that VTs made expensive because many more tasks actually run the put/poll path at once.
### 1. Non-fair lock on `SwappablePriorityQueue` — **this is the one that mattered**
**Change:** `new ReentrantReadWriteLock(true)` → `new ReentrantReadWriteLock()`.
**Why:** FlowFile **order** is the heap comparator (penalty → user prioritizers → content claim → id), not lock-acquisition FIFO. Fairness was only ordering *waiters*. With virtual threads, every put/poll that lost the fair lock paid a park/unpark handoff. Three pairs convoyed on that.
**Risk we accepted:** barge-in / theoretical waiter starvation on a tiny critical section (heap op + size counters). UI/status `readLock` snapshots can wait a bit longer under a write storm; same class of issue as any non-fair RW lock. We do **not** lose queue ordering semantics.
**Result:** three pairs went to **~607k FF/s** combined (was fighting itself below the two-pair **~526k**). JVM CPU dropped some (~645% → ~563% in one sample; later samples still ~650% depending on heap/GC). Fair-lock scheduling disappeared from the post-fix profile.
This is the change I would most like considered for a follow-on PR. It is small, and it is specifically more important once VT increases concurrent put/poll.
### 2. Non-fair lock on `StandardFlowFileQueue` — consistency only
**Change:** same `true` → default (non-fair).
**Why:** leftover twin of (1). **Put/poll never take this lock**; they go to `SwappablePriorityQueue`. The outer lock is only `session.get(FlowFileFilter)` across **multiple incoming connections** (lock-order deadlock avoidance) and selective drops.
**Result:** not re-benchmarked on purpose. This Generate → UpdateAttribute loop never acquires it (`get()` without a filter does not lock-all-queues). No expected throughput change. Fine as the same cleanup if we touch (1).
Note for later, not this experiment: `lock()` does not wrap the inner queue, so “lock all queues” does not freeze puts/polls on the heap. Separate design leftover.
### 3. Freeze FlowFile / provenance attribute maps once (`Map.copyOf`)
**Change:**
- `StandardFlowFileRecord` constructs a frozen map once; `getAttributes()` returns that instance instead of wrapping with `Collections.unmodifiableMap` on every call.
- Builder `fromFlowFile` still aliases the frozen map and copy-on-writes on mutate (same StackOverflow-avoidance story as today, without wrapping UnmodifiableMap in UnmodifiableMap).
- `StandardProvenanceEventRecord` previous/updated attribute maps likewise `Map.copyOf` at construct.
**Why:** JFR showed map wrap/copy on the provenance/session path. Intentionally **not** “skip building the event.”
**Result:** after this plus (4), 30s Generate rates were **~293k + 158k + 162k ≈ 613k FF/s** vs a 5-minute baseline of **~281k + 157k + 157k ≈ 595k** immediately before the deploy. That is **in the noise** of the ~607k we already had from (1). Pair 1 stayed much hotter than pairs 2 and 3 (concurrent-task mismatch, not a comparator bug).
Worth keeping as a real cleanup (and it matches the existing “don’t wrap the map N times” comment), but it is **not** the VT scaling fix.
### 4. `QueuePrioritizer` fast path for the default order
**Change:** if there are no user prioritizers, neither FlowFile is penalized, and both content claims are null, compare `contentClaimOffset` then `id` with `Long.compare`. Otherwise the existing chain (penalty → user prioritizers → claim → id).
**Why:** `PriorityQueue.siftDown` was hot; default order on this flow is claim-null + unpenalized, so id (after offset) decides. We did **not** replace `PriorityQueue` with `ArrayDeque`: default order is **not** arrival order (penalty → claim/offset → **id**).
**Result:** bundled with (3); no clear extra win on this flow.
## Tests run on the follow-on patches
- `TestSwappablePriorityQueue` (29)
- `TestStandardFlowFileQueue` (20)
- `QueuePrioritizerTest` (7, including default-order / penalty / claim still honored)
- `TestStandardFlowFileRecord` (frozen map + UOE on mutate)
- `StandardProvenanceEventRecordTest` (2)
All passed. Not a substitute for a clustered load-balance run or a flow that uses user prioritizers / penalties heavily.
## What I would take from this for NIFI-15862 vs a later PR
- **This PR’s VT scheduler looks like it is doing its job** on a CPU-bound, 0-byte loop: two pairs **add**. We did not see pinning. We did not see the scheduler as the 3-pair ceiling.
- The 3-pair ceiling was **fair `SwappablePriorityQueue` locking** interacting badly with many virtual threads pounding put/poll. That lock predates VT; VT just lights it up.
- I would **not** fold the follow-on patches into NIFI-15862. They are easier to reason about (and revert) on their own, and only (1) moved throughput.
- If we do a follow-on, start with (1), optionally (2) as the same one-liner family. (3) and (4) are optional / lower value on this particular flow.
- Remaining engine cost after (1), still visible in JFR and still **not** disk: provenance event construction/enrichment, attribute maps, `PriorityQueue` compares. We left those honest on purpose.
## Open questions / caveats
- Numbers are one Mac, 16 cores, volatile repos, 0-byte files. A WAL + persistent provenance + real content path will look different (and should).
- Pair imbalance (one loop ~2× another) is at least partly concurrent-task settings, not fully investigated.
- `StandardFlowFileQueue`’s outer lock vs inner lock split is a correctness/clarity issue for `get(FlowFileFilter)`, independent of fairness.
- We should still compare **TIMER_DRIVEN (platform threads)** vs **AUTO/VT** on the *same* flow and same machine if we want a clean “VT vs old scheduler” number. The work above was “VT on, then remove engine bottlenecks VT exposed,” not a head-to-head A/B of the two scheduling agents.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5648896619
ok @markap14 this was a lot of fun to review and experiment with. While I dont feel confident enough abou the true code itself and would like someone such as @exceptionfactory to give it a final review - i am +1 at this point after reasonably detailed testing and experimentation. Various results shared about. The first large markdown dump is from going beyond this and suggesting some follow-on changes. The second big block is from really focusing on behavior of scheduling/thread starvation/timing concerns. It holds up well.
I did my testing on Java 25. I didn't focus on Java 21. Since we are default off on Java 21 and default on with Java 25 I think that is fine.
I also ran the entire test suite/portfolio over the span of a copule hours and everything came up green.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-4434317344
[claude-opus-4.7] @pvillard31 thanks for the latest round of feedback. The new commit (2c0e041) addresses your remaining comments and rebases onto current `main`:
- `ThreadDumpTask` now logs at debug rather than silently swallowing the cleanup `IOException`, so a recurring failure to delete `nifi-thread-dump-*` directories is discoverable.
- On the thread-name-after-rename question: after some prototyping we decided not to refresh the virtual thread's name inside the scheduling loop. Resetting the name on every iteration adds an allocation-heavy `buildThreadName` call to a hot path that may run at zero scheduling period, and cache-and-compare workarounds add complexity for what is purely a diagnostic nicety. The name resolved at scheduling time (component name + type + id + parent-group name + task index) still contains the immutable component id, so threads remain identifiable in dumps. If the user wants the new name reflected, stopping and restarting the component is sufficient.
The earlier review-feedback commit (0abffe2) is also still on the branch and covers the prior round of comments: atomic schedule rollback (#3), thread tracking + `shutdown()` interrupt with `FlowController` kill-path hook (#5), `setMaxThreadCount` synchronization (#2), and the response on `runOnce` polling (#1). Force push was required to incorporate the `main` rebase.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5689052018
[GPT-5.6 Sol] The [Scan check](https://github.com/apache/nifi/actions/runs/35031764646/job/104591644809) failed before project compilation while resolving the parent POM:
```
[FATAL] Non-resolvable parent POM for org.apache.nifi:nifi:2.13.0-SNAPSHOT:
The following artifacts could not be resolved: org.apache:apache:pom:39 (absent):
Could not find artifact org.apache:apache:pom:39 in central (https://repo.maven.apache.org/maven2)
```
This is a transient dependency-resolution failure unrelated to this branch. Apache parent 39 comes from current `main`, and the current `main` Scan resolved the same parent and proceeded through Maven Package. The workflow is still running its sibling Validate job; I will rerun only the failed Scan job as soon as the workflow completes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5721973730
[gpt-sol-5.6] I have rerun the failed [Ubuntu Java 25 system-test job](https://github.com/apache/nifi/actions/runs/35271697279/job/105372395322). As noted above, the saved logs show that Processor stopping completed successfully and the timeout followed a cluster coordinator change during node offload; the same `OffloadIT.testOffload` timeout occurred on `main` yesterday.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3131457521
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java:
##########
@@ -2133,13 +2132,14 @@ public int getMaxTimerDrivenThreadCount() {
}
public int getActiveTimerDrivenThreadCount() {
- return timerDrivenEngineRef.get().getActiveCount();
+ return timerDrivenEngineRef.get().getActiveCount() + virtualThreadSchedulingAgent.getActiveThreadCount();
}
public void setMaxTimerDrivenThreadCount(final int maxThreadCount) {
writeLock.lock();
try {
setMaxThreadCount(maxThreadCount, "Timer Driven", this.timerDrivenEngineRef.get(), this.maxTimerDrivenThreads);
+ virtualThreadSchedulingAgent.setMaxThreadCount(maxThreadCount);
Review Comment:
Yeah, I had this fixed locally but forgot to push the commit. Now, the timer-driven engine is used only for framework tasks, so I renamed it and just hardcoded it to 8 threads.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3131451935
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Scheduling agent that runs processors, funnels, ports, and reporting tasks on virtual
+ * threads rather than on a shared thread pool. A single {@link DynamicSemaphore} bounds
+ * the number of invocations that may run concurrently across the entire flow. Its permit
+ * count replaces the old Timer-Driven thread pool size and is adjustable at runtime via
+ * {@link #setMaxThreadCount(int)}.
+ * <p>
+ * The agent is used for both {@link SchedulingStrategy#TIMER_DRIVEN} and
+ * {@link SchedulingStrategy#CRON_DRIVEN} connectables. Each scheduled connectable is given
+ * one virtual thread per concurrent task; every iteration of the scheduling loop acquires
+ * a permit, calls {@link ConnectableTask#invoke()}, releases the permit, and then sleeps
+ * until the next invocation is due.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ /**
+ * Sleeps in the scheduling loop are broken up into chunks of at most this long so that
+ * a processor that is unscheduled while a scheduling thread is sleeping will exit the
+ * sleep and observe the state change quickly rather than having to wait for the full
+ * scheduling period to elapse.
+ */
+ private static final long POLL_INTERVAL_NANOS = TimeUnit.MILLISECONDS.toNanos(25L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new RuntimeException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration);
+ }
+ }
+
+ @Override
+ public void shutdown() {
+ }
+
+ /**
+ * Schedules the given connectable to run on virtual threads. This method transitions the
+ * {@link LifecycleState} to scheduled and then spawns one virtual thread per concurrent task. Each scheduling loop
+ * captures {@link LifecycleState#getLastStopTime()} at startup and will exit as soon as either
+ * {@link LifecycleState#isScheduled()} becomes {@code false} or the last-stop-time advances, which is how the
+ * agent guards against a rapid stop/start cycle leaving prior loops running alongside newly-spawned ones. The
+ * corresponding {@link #unschedule(Connectable, LifecycleState)} call performs the inverse transition. Calling
+ * {@code setScheduled(true)} here is intentionally idempotent: the framework scheduler also marks the state as
+ * scheduled in some code paths (for example, reporting-task startup), and double-calling is harmless because the
+ * last-stop-time only advances on transitions to the stopped state.
+ */
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final CronExpression cronExpression;
+ if (connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ } else {
+ cronExpression = null;
+ }
+
+ lifecycleState.setScheduled(true);
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ Thread.ofVirtual().name(threadName).start(() -> runSchedulingLoop(connectable, connectableTask, lifecycleState, startStopTime, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ lifecycleState.setScheduled(true);
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ Thread.ofVirtual().name(threadName).start(() -> runOnce(connectable, connectableTask, stopCallback));
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ lifecycleState.setScheduled(true);
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ Thread.ofVirtual().name(threadName).start(() -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, startStopTime));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ /**
+ * @return {@code true} if {@code lifecycleState} is still scheduled and its last-stop-time has not changed since
+ * the scheduling loop was spawned (meaning the loop is still running against its original scheduling generation).
+ * Used by the scheduling loops and their polling helpers to detect both the normal stop path (isScheduled flips to
+ * false) and the rapid stop/start race (a stop increments lastStopTime even if a quick restart flips isScheduled
+ * back to true before the old loop has observed the stop).
+ */
+ private boolean isActive(final LifecycleState lifecycleState, final long startStopTime) {
+ return lifecycleState.isScheduled() && lifecycleState.getLastStopTime() == startStopTime;
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
Review Comment:
Yeah, that's a good catch!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-4443838233
[claude-opus-4.7] CI rerun on `macos-15 Java 25` failed again, but on a **different** test than before. Classifying as a separate likely flake and rerunning the shard once more.
**Failed check:** `macos-15 Java 25` — https://github.com/apache/nifi/actions/runs/25806807059/job/75830543159
**Failing test (this run):** `org.apache.nifi.tests.system.parameters.ClusteredParameterContextIT > ParameterContextIT.testProcessorRestartedAfterLongDependentServiceValidationPeriod`
```
[ERROR] org.apache.nifi.tests.system.parameters.ClusteredParameterContextIT.testProcessorRestartedAfterLongDependentServiceValidationPeriod -- Time elapsed: 15.54 s <<< ERROR!
org.apache.nifi.toolkit.client.NiFiClientException: Error deleting Controller Service: Node localhost:5672 is unable to fulfill this request due to: StandardControllerServiceNode[service=StandardSleepService[...], name=StandardSleepService, active=false] cannot be deleted because it is not disabled
Caused by: jakarta.ws.rs.ClientErrorException: HTTP 409 Conflict
```
**Why this is most likely unrelated to the PR:**
- The `macos-15 Java 25` shard is independently flaky on this PR — the previous rerun was for a completely different test (`ClusterStateKeyDropIT.testCanDropSpecificStateKey`). Same shard failing on a different test each time is the signature of an environmentally flaky runner, not a deterministic regression from this PR.
- All other shards pass: `ubuntu-24.04 Java 21`, `ubuntu-24.04 Java 25`, `macos-15 Java 21`, plus all the language/locale shards.
- The test contains a pre-existing race independent of this PR: `NiFiClientUtil.disableControllerService(...)` (`nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/NiFiClientUtil.java:1014-1021`) only fires the disable request and returns immediately. It does **not** wait for the service to reach the `DISABLED` state. The very next line in the test (`ParameterContextIT.java:614-615`) calls `deleteControllerService`. The `StandardSleepService` under test has `Validate Sleep Time = 6 secs` set via the parameter context update, so if a validation cycle is in flight when disable is issued, the service stays in `DISABLING` long enough for the immediate delete to fail with HTTP 409 — exactly the observed error.
- This PR does not change controller-service lifecycle, validation scheduling, or the `disableControllerService` helper. The scheduling changes only affect processor / reporting-task `onTrigger` invocations.
**Action taken:** Reran only the failed `macos-15 Java 25` shard a second time via `gh run rerun 25806807059 --failed --repo apache/nifi`. If the same test fails again on the next run, I will stop reruns and investigate whether virtual-thread scheduling can prolong validation on macOS Java 25 specifically.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-4443129299
[claude-opus-4.7] CI failure on `macos-15 Java 25` (system-tests) — classified as pre-existing flake; failed shard rerun.
**Failed check:** `macos-15 Java 25` — https://github.com/apache/nifi/actions/runs/25806807059/job/75811748202
**Failing test:** `org.apache.nifi.tests.system.state.ClusterStateKeyDropIT.testCanDropSpecificStateKey`
```
[ERROR] org.apache.nifi.tests.system.state.ClusterStateKeyDropIT.testCanDropSpecificStateKey -- Time elapsed: 1.662 s <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: <{c=1, b=1, a=1}> but was: <{}>
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1188)
at org.apache.nifi.tests.system.state.ClusterStateKeyDropIT.testCanDropSpecificStateKey(ClusterStateKeyDropIT.java:124)
```
**Why this is unrelated to the PR:**
- `ClusterStateKeyDropIT` is known-flaky on macOS shards. NIFI-15763 (#11070) previously added retry logic to this class for transient cluster errors. The same class flaked on `main` run https://github.com/apache/nifi/actions/runs/25457358299 (May 6) on `macos-15 Java 21` for a sibling test method (`testCannotDropStateKeyWithLocalAndClusterState`), so the test class flakiness is independent of this PR.
- This PR does not touch cluster state management, state providers, the coordinator, or anything `ClusterStateKeyDropIT` exercises. It only affects scheduling (virtual vs. timer-driven thread agents).
- All other shards passed on this PR: `ubuntu-24.04 Java 21`, `ubuntu-24.04 Java 25`, and `macos-15 Java 21`. Only `macos-15 Java 25` flaked.
**Action taken:** Reran only the failed `macos-15 Java 25` shard via `gh run rerun 25806807059 --failed --repo apache/nifi`. Will continue to monitor.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639697266
[GPT-5.6 Sol] @exceptionfactory addressed in f637504ed67. The property is now `nifi.scheduling.strategy`, the enum has been removed, and `STANDARD` / `VIRTUAL` are handled as string values. `VIRTUAL` remains the default based on the earlier rollout decision. Focused scheduler and properties tests, Checkstyle, and PMD all pass.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "exceptionfactory (via GitHub)" <gi...@apache.org>.
exceptionfactory commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r4019345350
##########
nifi-docs/src/main/asciidoc/administration-guide.adoc:
##########
@@ -2952,6 +2952,7 @@ This cleanup mechanism takes into account only automatically created archived _f
|`nifi.flowservice.writedelay.interval`|When many changes are made to the _flow.json_, this property specifies how long to wait before writing out the changes, so as to batch the changes into a single write. The default value is `500 ms`.
|`nifi.administrative.yield.duration`|If a component allows an unexpected exception to escape, it is considered a bug. As a result, the framework will pause (or administratively yield) the component for this amount of time. This is done so that the component does not use up massive amounts of system resources, since it is known to have problems in the existing state. The default value is `30 secs`.
|`nifi.bored.yield.duration`|When a component has no work to do (i.e., is "bored"), this is the amount of time it will wait before checking to see if it has new data to work on. This way, it does not use up CPU resources by checking for new work too often. When setting this property, be aware that it could add extra latency for components that do not constantly have work to do, as once they go into this "bored" state, they will wait this amount of time before checking for more work. The default value is `10 ms`.
+|`nifi.scheduling.strategy`|Selects the scheduling engine for Timer-Driven and Cron-Driven components. `AUTO` (the default) uses virtual threads on Java 25 or newer and standard scheduling on older Java versions. `VIRTUAL` always uses virtual threads. On Java 21, blocking inside synchronized component code can also block the underlying platform thread and reduce throughput. `STANDARD` uses a fixed platform thread pool sized by `nifi.flowcontroller.maxTimerDrivenThreadCount`.
Review Comment:
The `maxTimerDrivenThreadCount` is set inside the flow configuration, so this wording should be adjusted to avoid confusion with application properties.
##########
nifi-framework-api/src/main/java/org/apache/nifi/diagnostics/ThreadDumpTask.java:
##########
@@ -16,116 +16,139 @@
*/
package org.apache.nifi.diagnostics;
+import com.sun.management.HotSpotDiagnosticMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
+/**
+ * Captures platform and virtual thread stack traces when supported by the Java runtime.
+ */
public class ThreadDumpTask implements DiagnosticTask {
+
+ private static final Logger logger = LoggerFactory.getLogger(ThreadDumpTask.class);
+
@Override
- public DiagnosticsDumpElement captureDump(boolean verbose) {
- final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
-
- final ThreadInfo[] infos = mbean.dumpAllThreads(true, true);
- final long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
- final long[] monitorDeadlockThreadIds = mbean.findMonitorDeadlockedThreads();
-
- final List<ThreadInfo> sortedInfos = new ArrayList<>(infos.length);
- Collections.addAll(sortedInfos, infos);
- sortedInfos.sort(new Comparator<>() {
- @Override
- public int compare(ThreadInfo o1, ThreadInfo o2) {
- return o1.getThreadName().toLowerCase().compareTo(o2.getThreadName().toLowerCase());
+ public DiagnosticsDumpElement captureDump(final boolean verbose) {
+ final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
+ final String threadDump = captureThreadDump(threadMXBean);
+
+ final StringBuilder dumpBuilder = new StringBuilder(threadDump);
+ appendDeadlockedThreadIds(dumpBuilder, "DEADLOCK DETECTED!", threadMXBean.findDeadlockedThreads());
+ appendDeadlockedThreadIds(dumpBuilder, "MONITOR DEADLOCK DETECTED!", threadMXBean.findMonitorDeadlockedThreads());
Review Comment:
I recommend removing the exclamation marks:
```suggestion
appendDeadlockedThreadIds(dumpBuilder, "DEADLOCK DETECTED", threadMXBean.findDeadlockedThreads());
appendDeadlockedThreadIds(dumpBuilder, "MONITOR DEADLOCK DETECTED", threadMXBean.findMonitorDeadlockedThreads());
```
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/FlowControllerTest.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * 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.controller;
+
+import org.apache.nifi.util.NiFiProperties;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class FlowControllerTest {
Review Comment:
This test class should be removed, I don't recommend exercised that scheduling method as it is mostly a tautology.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/tasks/ReportingTaskWrapperTest.java:
##########
@@ -0,0 +1,67 @@
+/*
+ * 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.controller.tasks;
+
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.scheduling.LifecycleState;
+import org.apache.nifi.nar.ExtensionManager;
+import org.apache.nifi.reporting.ReportingContext;
+import org.apache.nifi.reporting.ReportingTask;
+import org.junit.jupiter.api.Test;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class ReportingTaskWrapperTest {
Review Comment:
This test class looks unnecessary, perhaps introduced with the change to the `run()` method, is it needed or can it be removed?
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgentTest.java:
##########
@@ -0,0 +1,821 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.components.state.StateManager;
+import org.apache.nifi.components.state.StateManagerProvider;
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.GarbageCollectionLog;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.ScheduledState;
+import org.apache.nifi.controller.repository.FlowFileEventRepository;
+import org.apache.nifi.controller.repository.RepositoryContext;
+import org.apache.nifi.groups.ProcessGroup;
+import org.apache.nifi.nar.ExtensionManager;
+import org.apache.nifi.nar.NarThreadContextClassLoader;
+import org.apache.nifi.processor.Processor;
+import org.apache.nifi.reporting.ReportingContext;
+import org.apache.nifi.reporting.ReportingTask;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.NiFiProperties;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+
+import java.util.Collections;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class VirtualThreadSchedulingAgentTest {
+
+ private static final int MAX_THREADS = 10;
+ private static final String COMPONENT_ID = UUID.randomUUID().toString();
+
+ @Mock
+ private FlowController flowController;
+
+ @Mock
+ private RepositoryContextFactory contextFactory;
+
+ @Mock
+ private NiFiProperties nifiProperties;
+
+ @Mock
+ private StateManagerProvider stateManagerProvider;
+
+ @Mock
+ private StateManager stateManager;
+
+ @Mock
+ private GarbageCollectionLog garbageCollectionLog;
+
+ @Mock
+ private ExtensionManager extensionManager;
+
+ private VirtualThreadSchedulingAgent agent;
+
+ @BeforeEach
+ void setUp() {
+ when(nifiProperties.getBoredYieldDuration()).thenReturn("10 millis");
+ agent = new VirtualThreadSchedulingAgent(flowController, contextFactory, nifiProperties, MAX_THREADS);
+ }
+
+ @AfterEach
+ void tearDown() throws InterruptedException {
+ agent.shutdown();
+ assertTrue(agent.awaitTermination(5, TimeUnit.SECONDS));
+ }
+
+ @Test
+ void testIncrementMaxThreadCountAdjustsSemaphore() {
+ final int originalPermits = agent.getGlobalSemaphore().getMaxPermits();
+
+ agent.incrementMaxThreadCount(0);
+ assertEquals(originalPermits, agent.getGlobalSemaphore().getMaxPermits());
+
+ agent.incrementMaxThreadCount(5);
+ assertEquals(originalPermits + 5, agent.getGlobalSemaphore().getMaxPermits());
+
+ agent.incrementMaxThreadCount(-3);
+ assertEquals(originalPermits + 2, agent.getGlobalSemaphore().getMaxPermits());
+
+ assertThrows(IllegalStateException.class, () -> agent.incrementMaxThreadCount(-1000));
+ }
+
+ @Test
+ void testScheduleSpawnsThreadsThatInvoke() throws InterruptedException {
+ final int concurrentTasks = 3;
+ final AtomicInteger invocationCount = new AtomicInteger(0);
+ final CountDownLatch allTasksInvoked = new CountDownLatch(concurrentTasks);
+ final AtomicBoolean virtualThreadsUsed = new AtomicBoolean(true);
+
+ final Connectable connectable = createMockedConnectable(concurrentTasks, SchedulingStrategy.TIMER_DRIVEN, invocationCount, allTasksInvoked);
+ doAnswer(invocation -> {
+ invocationCount.incrementAndGet();
+ allTasksInvoked.countDown();
+ if (!Thread.currentThread().isVirtual()) {
+ virtualThreadsUsed.set(false);
+ }
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+
+ scheduleConnectable(connectable, lifecycleState);
+
+ assertTrue(allTasksInvoked.await(5, TimeUnit.SECONDS),
+ "Expected " + concurrentTasks + " threads to invoke, but only " + (concurrentTasks - allTasksInvoked.getCount()) + " did");
+ assertTrue(invocationCount.get() >= concurrentTasks,
+ "Expected at least " + concurrentTasks + " invocations but got " + invocationCount.get());
+ assertTrue(virtualThreadsUsed.get());
+
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void testProcessorContinuesAfterInterruptStatusSet() throws InterruptedException {
+ final AtomicInteger invocationCount = new AtomicInteger();
+ final CountDownLatch secondInvocation = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ doAnswer(invocation -> {
+ if (invocationCount.incrementAndGet() == 1) {
+ Thread.currentThread().interrupt();
+ } else {
+ secondInvocation.countDown();
+ }
+
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(secondInvocation.await(2, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ }
+ }
+
+ @Test
+ void testSchedulingThreadUsesFrameworkClassLoaderWithoutInheritedThreadLocals() throws InterruptedException {
+ final InheritableThreadLocal<String> inheritedValue = new InheritableThreadLocal<>();
+ final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
+ final ClassLoader lifecycleClassLoader = new ClassLoader(originalClassLoader) {
+ };
+ final AtomicReference<ClassLoader> observedClassLoader = new AtomicReference<>();
+ final AtomicReference<String> observedInheritedValue = new AtomicReference<>();
+ final CountDownLatch schedulingThreadObserved = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ when(connectable.getYieldExpiration()).thenAnswer(invocation -> {
+ observedClassLoader.compareAndSet(null, Thread.currentThread().getContextClassLoader());
+ observedInheritedValue.compareAndSet(null, inheritedValue.get());
+ schedulingThreadObserved.countDown();
+ return 0L;
+ });
+
+ inheritedValue.set("lifecycle-thread-value");
+ Thread.currentThread().setContextClassLoader(lifecycleClassLoader);
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+
+ try {
+ scheduleConnectable(connectable, lifecycleState);
+ assertTrue(schedulingThreadObserved.await(2, TimeUnit.SECONDS));
+ assertEquals(NarThreadContextClassLoader.getInstance(), observedClassLoader.get());
+ assertNull(observedInheritedValue.get());
+ } finally {
+ inheritedValue.remove();
+ Thread.currentThread().setContextClassLoader(originalClassLoader);
+ unscheduleConnectable(connectable, lifecycleState);
+ }
+ }
+
+ @Test
+ void testDuplicateScheduleIsRejected() throws InterruptedException {
+ final CountDownLatch invocationStarted = new CountDownLatch(1);
+ final CountDownLatch releaseInvocation = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ doAnswer(invocation -> {
+ invocationStarted.countDown();
+ releaseInvocation.await();
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(invocationStarted.await(2, TimeUnit.SECONDS));
+ assertThrows(IllegalStateException.class, () -> agent.schedule(connectable, lifecycleState));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ releaseInvocation.countDown();
+ }
+ }
+
+ @Test
+ void testComponentYieldDoesNotShortenSchedulingPeriod() throws InterruptedException {
+ final long schedulingPeriodMillis = 500L;
+ final AtomicLong yieldExpiration = new AtomicLong();
+ final AtomicInteger invocationCount = new AtomicInteger();
+ final CountDownLatch firstInvocation = new CountDownLatch(1);
+ final CountDownLatch secondInvocation = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ when(connectable.getSchedulingPeriod(TimeUnit.MILLISECONDS)).thenReturn(schedulingPeriodMillis);
+ when(connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS)).thenReturn(TimeUnit.MILLISECONDS.toNanos(schedulingPeriodMillis));
+ when(connectable.getYieldExpiration()).thenAnswer(invocation -> yieldExpiration.get());
+ doAnswer(invocation -> {
+ final int currentInvocation = invocationCount.incrementAndGet();
+ if (currentInvocation == 1) {
+ yieldExpiration.set(System.currentTimeMillis() + 50L);
+ firstInvocation.countDown();
+ } else if (currentInvocation == 2) {
+ secondInvocation.countDown();
+ }
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(firstInvocation.await(2, TimeUnit.SECONDS));
+ assertFalse(secondInvocation.await(250, TimeUnit.MILLISECONDS));
+ assertTrue(secondInvocation.await(2, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ }
+ }
+
+ @Test
+ void testZeroBoredYieldUsesSchedulingPeriod() throws InterruptedException {
+ agent.shutdown();
+ when(nifiProperties.getBoredYieldDuration()).thenReturn("0 millis");
+ agent = new VirtualThreadSchedulingAgent(flowController, contextFactory, nifiProperties, MAX_THREADS);
+
+ final long schedulingPeriodMillis = 500L;
+ final AtomicInteger schedulingAttempts = new AtomicInteger();
+ final CountDownLatch firstAttempt = new CountDownLatch(1);
+ final CountDownLatch secondAttempt = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ when(connectable.getSchedulingPeriod(TimeUnit.MILLISECONDS)).thenReturn(schedulingPeriodMillis);
+ when(connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS)).thenReturn(TimeUnit.MILLISECONDS.toNanos(schedulingPeriodMillis));
+ when(connectable.isIsolated()).thenAnswer(invocation -> {
+ final int attempt = schedulingAttempts.incrementAndGet();
+ if (attempt == 1) {
+ firstAttempt.countDown();
+ } else if (attempt == 2) {
+ secondAttempt.countDown();
+ }
+ return true;
+ });
+ when(flowController.isConfiguredForClustering()).thenReturn(true);
+ when(flowController.isPrimary()).thenReturn(false);
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(firstAttempt.await(2, TimeUnit.SECONDS));
+ assertFalse(secondAttempt.await(250, TimeUnit.MILLISECONDS));
+ assertTrue(secondAttempt.await(2, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ }
+ }
+
+ @Test
+ void testUnscheduleWakesLongSchedulingDelay() throws InterruptedException {
+ final CountDownLatch invocationCompleted = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), invocationCompleted);
+ when(connectable.getSchedulingPeriod(TimeUnit.MILLISECONDS)).thenReturn(TimeUnit.DAYS.toMillis(1L));
+ when(connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS)).thenReturn(TimeUnit.DAYS.toNanos(1L));
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+
+ scheduleConnectable(connectable, lifecycleState);
+ assertTrue(invocationCompleted.await(2, TimeUnit.SECONDS));
+
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ assertEquals(0, lifecycleState.getActiveThreadCount());
+ }
+
+ @Test
+ void testScheduleOnceInvokesAndStops() throws InterruptedException {
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ final CountDownLatch stopCallbackInvoked = new CountDownLatch(1);
+
+ lifecycleState.setScheduled(true);
+ agent.scheduleOnce(connectable, lifecycleState, () -> {
+ stopCallbackInvoked.countDown();
+ return null;
+ });
+
+ assertTrue(stopCallbackInvoked.await(5, TimeUnit.SECONDS),
+ "Stop callback should have been invoked after scheduleOnce");
+ }
+
+ @Test
+ void testUnscheduleExitsWhenSemaphoreFullyContended() throws InterruptedException {
+ agent.setMaxThreadCount(1);
+
+ final CountDownLatch releaseHeldPermit = new CountDownLatch(1);
+ final CountDownLatch permitAcquired = new CountDownLatch(1);
+ final Thread permitHolder = Thread.ofVirtual().start(() -> {
+ try {
+ agent.getGlobalSemaphore().acquire();
+ permitAcquired.countDown();
+ releaseHeldPermit.await();
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ agent.getGlobalSemaphore().release();
+ }
+ });
+ assertTrue(permitAcquired.await(2, TimeUnit.SECONDS), "Failed to acquire permit for test setup");
+
+ final AtomicInteger invocationCount = new AtomicInteger(0);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, invocationCount, new CountDownLatch(0));
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ waitForRunningThreadCount(1, 2, TimeUnit.SECONDS);
+ assertEquals(0, invocationCount.get());
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+
+ releaseHeldPermit.countDown();
+ permitHolder.join(1_000L);
+
+ assertEquals(0, invocationCount.get());
+ }
+
+ @Test
+ void testConcurrentIncrementMaxThreadCountIsThreadSafe() throws InterruptedException {
+ agent.setMaxThreadCount(100);
+
+ final int threadCount = 20;
+ final int incrementsPerThread = 50;
+ final CountDownLatch start = new CountDownLatch(1);
+ final CountDownLatch done = new CountDownLatch(threadCount);
+
+ for (int i = 0; i < threadCount; i++) {
+ Thread.ofVirtual().start(() -> {
+ try {
+ start.await();
+ for (int j = 0; j < incrementsPerThread; j++) {
+ agent.incrementMaxThreadCount(1);
+ }
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ done.countDown();
+ }
+ });
+ }
+
+ start.countDown();
+ assertTrue(done.await(5, TimeUnit.SECONDS));
+
+ assertEquals(100 + threadCount * incrementsPerThread, agent.getGlobalSemaphore().getMaxPermits(),
+ "Lost increments imply a race condition in incrementMaxThreadCount");
+ }
+
+ @Test
+ void testSchedulingPeriodReadOnceWhenScheduled() throws InterruptedException {
+ final CountDownLatch invocationsCompleted = new CountDownLatch(5);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), invocationsCompleted);
+ final AtomicInteger schedulingPeriodCalls = new AtomicInteger();
+ when(connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS)).thenAnswer(invocation -> {
+ schedulingPeriodCalls.incrementAndGet();
+ return TimeUnit.MILLISECONDS.toNanos(10L);
+ });
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(invocationsCompleted.await(5, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ }
+
+ assertEquals(1, schedulingPeriodCalls.get());
+ }
+
+ @Test
+ void testSchedulingLoopContinuesAfterUnexpectedError() throws InterruptedException {
+ agent.setAdministrativeYieldDuration("1 millis");
+ final CountDownLatch invocationCompleted = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), invocationCompleted);
+ when(connectable.isIsolated()).thenThrow(new AssertionError("Simulated scheduling error")).thenReturn(false);
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(invocationCompleted.await(2, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ }
+
+ assertEquals(MAX_THREADS, agent.getGlobalSemaphore().availablePermits());
+ }
+
+ @Test
+ void testInvocationExceptionStillReleasesPermit() throws InterruptedException {
+ agent.setMaxThreadCount(2);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ final AtomicInteger invocationCount = new AtomicInteger(0);
+ final CountDownLatch successfulInvocation = new CountDownLatch(1);
+ doAnswer(invocation -> {
+ final int count = invocationCount.incrementAndGet();
+ if (count <= 3) {
+ throw new IllegalStateException("Simulated failure " + count);
+ }
+ successfulInvocation.countDown();
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ assertTrue(successfulInvocation.await(2, TimeUnit.SECONDS));
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ assertEquals(2, agent.getGlobalSemaphore().availablePermits());
+ }
+
+ @Test
+ void testCronScheduleSpawnsThreadsAndInvokes() throws InterruptedException {
+ final AtomicInteger invocationCount = new AtomicInteger(0);
+ final CountDownLatch atLeastOneInvocation = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.CRON_DRIVEN, invocationCount, atLeastOneInvocation);
+ when(connectable.getSchedulingPeriod()).thenReturn("* * * * * ?");
+ when(connectable.evaluateParameters(eq("* * * * * ?"))).thenReturn("* * * * * ?");
Review Comment:
It looks like this cron expression is repeated multiple times and could be declared as a static final variable for reuse across all methods.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,627 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.Triggerable;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.nar.NarThreadContextClassLoader;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Scheduling agent that runs components on virtual threads. A {@link DynamicSemaphore}
+ * limits the number of component invocations that can run concurrently.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ private static final long PERMIT_POLL_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(1L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private final ExecutorService executorService;
+ private final ConcurrentMap<String, SchedulingGeneration> schedulingGenerations = new ConcurrentHashMap<>();
+ private final AtomicBoolean shutdown = new AtomicBoolean();
+ private final AtomicInteger runningThreadCount = new AtomicInteger();
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new IllegalStateException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration, e);
+ }
+
+ final ThreadFactory threadFactory = runnable -> {
+ final Thread thread = Thread.ofVirtual().inheritInheritableThreadLocals(false).unstarted(runnable);
+ thread.setContextClassLoader(NarThreadContextClassLoader.getInstance());
+ return thread;
+ };
+ executorService = Executors.newThreadPerTaskExecutor(threadFactory);
+ logger.info("VirtualThreadSchedulingAgent initialized with {} permits", maxThreadCount);
+ }
+
+ @Override
+ public void shutdown() {
+ signalShutdown(true);
+ executorService.shutdownNow();
+ }
+
+ public void shutdownGracefully() {
+ signalShutdown(false);
+ executorService.shutdown();
+ }
+
+ private void signalShutdown(final boolean interrupt) {
+ shutdown.set(true);
+
+ for (final SchedulingGeneration generation : schedulingGenerations.values()) {
+ generation.stop(interrupt);
+ }
+ }
+
+ public boolean awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException {
+ return executorService.awaitTermination(timeout, timeUnit);
+ }
+
+ public boolean isTerminated() {
+ return executorService.isTerminated();
+ }
+
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final boolean cronDriven = connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ submitTask(threadName, generation, () -> runSchedulingLoop(connectable, connectableTask, schedulingNanos, lifecycleState, generation, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ submitTask(threadName, generation, () -> {
+ try {
+ runOnce(connectable, connectableTask, stopCallback, lifecycleState, generation);
+ } finally {
+ stopSchedulingGeneration(componentId, generation, false);
+ }
+ });
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(connectable.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = taskNode.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ submitTask(threadName, generation,
+ () -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, generation));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(taskNode.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ private SchedulingGeneration registerSchedulingGeneration(final String componentId) {
+ if (shutdown.get()) {
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ final SchedulingGeneration generation = new SchedulingGeneration();
+ final SchedulingGeneration existingGeneration = schedulingGenerations.putIfAbsent(componentId, generation);
+ if (existingGeneration != null) {
+ throw new IllegalStateException("Component " + componentId + " is already scheduled");
+ }
+
+ if (shutdown.get()) {
+ stopSchedulingGeneration(componentId, generation, true);
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ return generation;
+ }
+
+ private boolean stopSchedulingGeneration(final String componentId, final SchedulingGeneration generation, final boolean interrupt) {
+ final boolean removed = schedulingGenerations.remove(componentId, generation);
+ generation.stop(interrupt);
+ return removed;
+ }
+
+ private boolean isActive(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ return !shutdown.get() && lifecycleState.isScheduled() && !generation.isStopped();
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public synchronized void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ int getRunningThreadCount() {
+ return runningThreadCount.get();
+ }
+
+ boolean isShutdown() {
+ return shutdown.get();
+ }
+
+ /**
+ * @return number of component invocations currently holding global permits
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getInUsePermits();
+ }
+
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask, final long schedulingNanos,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation, final CronExpression cronExpression) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the component", connectable);
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting", connectable);
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForNextInvocation(connectable, schedulingNanos, generation, invocationResult);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ if (isActive(lifecycleState, generation)) {
+ logger.warn("Run once request for {} was not executed because permit acquisition was interrupted", connectable);
+ } else {
+ logger.warn("Run once request for {} was not executed because scheduling is no longer active", connectable);
+ }
+
+ return;
+ }
+
+ try {
+ connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+ } catch (final Throwable t) {
+ logger.error("Unexpected error running {} once", connectable, t);
+ } finally {
+ try {
+ stopCallback.call();
+ } catch (final Throwable t) {
+ logger.error("Error while stopping {} after running once", connectable, t);
+ }
+ }
+ }
+
+ private void runReportingTaskLoop(final ReportingTaskNode taskNode, final Runnable reportingTaskWrapper, final long schedulingNanos,
+ final CronExpression cronExpression, final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the reporting task",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ reportingTaskWrapper.run();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForDelay(schedulingNanos, generation);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will wait for {} and continue.", taskNode.getReportingTask(), adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void waitForNextInvocation(final Connectable connectable, final long schedulingNanos, final SchedulingGeneration generation,
+ final InvocationResult invocationResult) {
+ final long sleepNanos;
+ final long yieldExpiration = connectable.getYieldExpiration();
+ final long yieldDelayNanos;
+ if (yieldExpiration == 0L) {
+ yieldDelayNanos = 0L;
+ } else {
+ yieldDelayNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(yieldExpiration - System.currentTimeMillis(), 0L));
+ }
+
+ if (yieldDelayNanos > 0L) {
+ sleepNanos = Math.max(schedulingNanos, yieldDelayNanos);
+ } else if (invocationResult.isYield()) {
+ sleepNanos = noWorkYieldNanos > 0L ? noWorkYieldNanos : schedulingNanos;
+ } else {
+ sleepNanos = schedulingNanos;
+ }
+
+ waitForDelay(sleepNanos, generation);
+ }
+
+ private boolean acquirePermitWithPolling(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
Review Comment:
Are there any synchronization concerns with this method being called from a stop and from runOnce? It seems possible to have a race condition based on the generation, but not quite clear.
##########
nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/scheduling/VirtualThreadStartStopCycleIT.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.tests.system.scheduling;
+
+import org.apache.nifi.tests.system.NiFiSystemIT;
+import org.apache.nifi.toolkit.client.NiFiClientException;
+import org.apache.nifi.web.api.dto.ProcessorConfigDTO;
+import org.apache.nifi.web.api.entity.ConnectionEntity;
+import org.apache.nifi.web.api.entity.ProcessorEntity;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Verifies that repeated start and stop cycles neither leak scheduling loops nor miss invocations.
+ */
+public class VirtualThreadStartStopCycleIT extends NiFiSystemIT {
Review Comment:
As a new test class, I recommend removing the `public` modifier from the class and methods.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,627 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.Triggerable;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.nar.NarThreadContextClassLoader;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Scheduling agent that runs components on virtual threads. A {@link DynamicSemaphore}
+ * limits the number of component invocations that can run concurrently.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ private static final long PERMIT_POLL_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(1L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private final ExecutorService executorService;
+ private final ConcurrentMap<String, SchedulingGeneration> schedulingGenerations = new ConcurrentHashMap<>();
+ private final AtomicBoolean shutdown = new AtomicBoolean();
+ private final AtomicInteger runningThreadCount = new AtomicInteger();
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new IllegalStateException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration, e);
+ }
+
+ final ThreadFactory threadFactory = runnable -> {
+ final Thread thread = Thread.ofVirtual().inheritInheritableThreadLocals(false).unstarted(runnable);
+ thread.setContextClassLoader(NarThreadContextClassLoader.getInstance());
+ return thread;
+ };
+ executorService = Executors.newThreadPerTaskExecutor(threadFactory);
+ logger.info("VirtualThreadSchedulingAgent initialized with {} permits", maxThreadCount);
+ }
+
+ @Override
+ public void shutdown() {
+ signalShutdown(true);
+ executorService.shutdownNow();
+ }
+
+ public void shutdownGracefully() {
+ signalShutdown(false);
+ executorService.shutdown();
+ }
+
+ private void signalShutdown(final boolean interrupt) {
+ shutdown.set(true);
+
+ for (final SchedulingGeneration generation : schedulingGenerations.values()) {
+ generation.stop(interrupt);
+ }
+ }
+
+ public boolean awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException {
+ return executorService.awaitTermination(timeout, timeUnit);
+ }
+
+ public boolean isTerminated() {
+ return executorService.isTerminated();
+ }
+
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final boolean cronDriven = connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ submitTask(threadName, generation, () -> runSchedulingLoop(connectable, connectableTask, schedulingNanos, lifecycleState, generation, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ submitTask(threadName, generation, () -> {
+ try {
+ runOnce(connectable, connectableTask, stopCallback, lifecycleState, generation);
+ } finally {
+ stopSchedulingGeneration(componentId, generation, false);
+ }
+ });
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(connectable.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = taskNode.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ submitTask(threadName, generation,
+ () -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, generation));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(taskNode.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ private SchedulingGeneration registerSchedulingGeneration(final String componentId) {
+ if (shutdown.get()) {
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ final SchedulingGeneration generation = new SchedulingGeneration();
+ final SchedulingGeneration existingGeneration = schedulingGenerations.putIfAbsent(componentId, generation);
+ if (existingGeneration != null) {
+ throw new IllegalStateException("Component " + componentId + " is already scheduled");
+ }
+
+ if (shutdown.get()) {
+ stopSchedulingGeneration(componentId, generation, true);
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ return generation;
+ }
+
+ private boolean stopSchedulingGeneration(final String componentId, final SchedulingGeneration generation, final boolean interrupt) {
+ final boolean removed = schedulingGenerations.remove(componentId, generation);
+ generation.stop(interrupt);
+ return removed;
+ }
+
+ private boolean isActive(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ return !shutdown.get() && lifecycleState.isScheduled() && !generation.isStopped();
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public synchronized void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ int getRunningThreadCount() {
+ return runningThreadCount.get();
+ }
+
+ boolean isShutdown() {
+ return shutdown.get();
+ }
+
+ /**
+ * @return number of component invocations currently holding global permits
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getInUsePermits();
+ }
+
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask, final long schedulingNanos,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation, final CronExpression cronExpression) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the component", connectable);
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting", connectable);
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForNextInvocation(connectable, schedulingNanos, generation, invocationResult);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ if (isActive(lifecycleState, generation)) {
+ logger.warn("Run once request for {} was not executed because permit acquisition was interrupted", connectable);
+ } else {
+ logger.warn("Run once request for {} was not executed because scheduling is no longer active", connectable);
+ }
+
+ return;
+ }
+
+ try {
+ connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+ } catch (final Throwable t) {
+ logger.error("Unexpected error running {} once", connectable, t);
+ } finally {
+ try {
+ stopCallback.call();
+ } catch (final Throwable t) {
+ logger.error("Error while stopping {} after running once", connectable, t);
+ }
+ }
+ }
+
+ private void runReportingTaskLoop(final ReportingTaskNode taskNode, final Runnable reportingTaskWrapper, final long schedulingNanos,
+ final CronExpression cronExpression, final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the reporting task",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ reportingTaskWrapper.run();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForDelay(schedulingNanos, generation);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will wait for {} and continue.", taskNode.getReportingTask(), adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void waitForNextInvocation(final Connectable connectable, final long schedulingNanos, final SchedulingGeneration generation,
+ final InvocationResult invocationResult) {
+ final long sleepNanos;
+ final long yieldExpiration = connectable.getYieldExpiration();
+ final long yieldDelayNanos;
+ if (yieldExpiration == 0L) {
+ yieldDelayNanos = 0L;
+ } else {
+ yieldDelayNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(yieldExpiration - System.currentTimeMillis(), 0L));
+ }
+
+ if (yieldDelayNanos > 0L) {
+ sleepNanos = Math.max(schedulingNanos, yieldDelayNanos);
+ } else if (invocationResult.isYield()) {
+ sleepNanos = noWorkYieldNanos > 0L ? noWorkYieldNanos : schedulingNanos;
+ } else {
+ sleepNanos = schedulingNanos;
+ }
+
+ waitForDelay(sleepNanos, generation);
+ }
+
+ private boolean acquirePermitWithPolling(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ while (isActive(lifecycleState, generation)) {
+ try {
+ if (globalSemaphore.tryAcquire(PERMIT_POLL_INTERVAL_NANOS, TimeUnit.NANOSECONDS)) {
+ if (isActive(lifecycleState, generation)) {
+ return true;
+ }
+
+ globalSemaphore.release();
+ return false;
+ }
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ private void waitForDelay(final long delayNanos, final SchedulingGeneration generation) {
+ if (delayNanos <= Triggerable.MINIMUM_SCHEDULING_NANOS) {
+ return;
+ }
+
+ try {
+ generation.awaitStop(delayNanos, TimeUnit.NANOSECONDS);
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ private static String buildThreadName(final Connectable connectable, final int taskIndex) {
+ return connectable.getName() + "[type=" + connectable.getComponentType() + ", id=" + connectable.getIdentifier()
Review Comment:
I recommend using a formatted String here for readability, instead of concatenation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r4020804647
##########
nifi-docs/src/main/asciidoc/administration-guide.adoc:
##########
@@ -2952,6 +2952,7 @@ This cleanup mechanism takes into account only automatically created archived _f
|`nifi.flowservice.writedelay.interval`|When many changes are made to the _flow.json_, this property specifies how long to wait before writing out the changes, so as to batch the changes into a single write. The default value is `500 ms`.
|`nifi.administrative.yield.duration`|If a component allows an unexpected exception to escape, it is considered a bug. As a result, the framework will pause (or administratively yield) the component for this amount of time. This is done so that the component does not use up massive amounts of system resources, since it is known to have problems in the existing state. The default value is `30 secs`.
|`nifi.bored.yield.duration`|When a component has no work to do (i.e., is "bored"), this is the amount of time it will wait before checking to see if it has new data to work on. This way, it does not use up CPU resources by checking for new work too often. When setting this property, be aware that it could add extra latency for components that do not constantly have work to do, as once they go into this "bored" state, they will wait this amount of time before checking for more work. The default value is `10 ms`.
+|`nifi.scheduling.strategy`|Selects the scheduling engine for Timer-Driven and Cron-Driven components. `AUTO` (the default) uses virtual threads on Java 25 or newer and standard scheduling on older Java versions. `VIRTUAL` always uses virtual threads. On Java 21, blocking inside synchronized component code can also block the underlying platform thread and reduce throughput. `STANDARD` uses a fixed platform thread pool sized by `nifi.flowcontroller.maxTimerDrivenThreadCount`.
Review Comment:
[GPT-5.6 Sol] Good point. Updated in 35dc8b9643f to refer to the Maximum Timer Driven Thread Count in Controller Settings rather than presenting it as an application property.
##########
nifi-framework-api/src/main/java/org/apache/nifi/diagnostics/ThreadDumpTask.java:
##########
@@ -16,116 +16,139 @@
*/
package org.apache.nifi.diagnostics;
+import com.sun.management.HotSpotDiagnosticMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
+/**
+ * Captures platform and virtual thread stack traces when supported by the Java runtime.
+ */
public class ThreadDumpTask implements DiagnosticTask {
+
+ private static final Logger logger = LoggerFactory.getLogger(ThreadDumpTask.class);
+
@Override
- public DiagnosticsDumpElement captureDump(boolean verbose) {
- final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
-
- final ThreadInfo[] infos = mbean.dumpAllThreads(true, true);
- final long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
- final long[] monitorDeadlockThreadIds = mbean.findMonitorDeadlockedThreads();
-
- final List<ThreadInfo> sortedInfos = new ArrayList<>(infos.length);
- Collections.addAll(sortedInfos, infos);
- sortedInfos.sort(new Comparator<>() {
- @Override
- public int compare(ThreadInfo o1, ThreadInfo o2) {
- return o1.getThreadName().toLowerCase().compareTo(o2.getThreadName().toLowerCase());
+ public DiagnosticsDumpElement captureDump(final boolean verbose) {
+ final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
+ final String threadDump = captureThreadDump(threadMXBean);
+
+ final StringBuilder dumpBuilder = new StringBuilder(threadDump);
+ appendDeadlockedThreadIds(dumpBuilder, "DEADLOCK DETECTED!", threadMXBean.findDeadlockedThreads());
+ appendDeadlockedThreadIds(dumpBuilder, "MONITOR DEADLOCK DETECTED!", threadMXBean.findMonitorDeadlockedThreads());
Review Comment:
[GPT-5.6 Sol] Updated in 35dc8b9643f. Both headings now omit the exclamation mark.
##########
nifi-system-tests/nifi-system-test-suite/src/test/java/org/apache/nifi/tests/system/scheduling/VirtualThreadStartStopCycleIT.java:
##########
@@ -0,0 +1,92 @@
+/*
+ * 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.tests.system.scheduling;
+
+import org.apache.nifi.tests.system.NiFiSystemIT;
+import org.apache.nifi.toolkit.client.NiFiClientException;
+import org.apache.nifi.web.api.dto.ProcessorConfigDTO;
+import org.apache.nifi.web.api.entity.ConnectionEntity;
+import org.apache.nifi.web.api.entity.ProcessorEntity;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * Verifies that repeated start and stop cycles neither leak scheduling loops nor miss invocations.
+ */
+public class VirtualThreadStartStopCycleIT extends NiFiSystemIT {
Review Comment:
[GPT-5.6 Sol] Updated in 35dc8b9643f. The new test class and method now use package-private visibility.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/FlowControllerTest.java:
##########
@@ -0,0 +1,36 @@
+/*
+ * 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.controller;
+
+import org.apache.nifi.util.NiFiProperties;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class FlowControllerTest {
Review Comment:
[GPT-5.6 Sol] Agreed. Removed the test class in 35dc8b9643f and restored the resolver method to private visibility. The Java 21 and Java 25 system-test profiles exercise `AUTO` in the running application.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,627 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.Triggerable;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.nar.NarThreadContextClassLoader;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Scheduling agent that runs components on virtual threads. A {@link DynamicSemaphore}
+ * limits the number of component invocations that can run concurrently.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ private static final long PERMIT_POLL_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(1L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private final ExecutorService executorService;
+ private final ConcurrentMap<String, SchedulingGeneration> schedulingGenerations = new ConcurrentHashMap<>();
+ private final AtomicBoolean shutdown = new AtomicBoolean();
+ private final AtomicInteger runningThreadCount = new AtomicInteger();
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new IllegalStateException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration, e);
+ }
+
+ final ThreadFactory threadFactory = runnable -> {
+ final Thread thread = Thread.ofVirtual().inheritInheritableThreadLocals(false).unstarted(runnable);
+ thread.setContextClassLoader(NarThreadContextClassLoader.getInstance());
+ return thread;
+ };
+ executorService = Executors.newThreadPerTaskExecutor(threadFactory);
+ logger.info("VirtualThreadSchedulingAgent initialized with {} permits", maxThreadCount);
+ }
+
+ @Override
+ public void shutdown() {
+ signalShutdown(true);
+ executorService.shutdownNow();
+ }
+
+ public void shutdownGracefully() {
+ signalShutdown(false);
+ executorService.shutdown();
+ }
+
+ private void signalShutdown(final boolean interrupt) {
+ shutdown.set(true);
+
+ for (final SchedulingGeneration generation : schedulingGenerations.values()) {
+ generation.stop(interrupt);
+ }
+ }
+
+ public boolean awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException {
+ return executorService.awaitTermination(timeout, timeUnit);
+ }
+
+ public boolean isTerminated() {
+ return executorService.isTerminated();
+ }
+
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final boolean cronDriven = connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ submitTask(threadName, generation, () -> runSchedulingLoop(connectable, connectableTask, schedulingNanos, lifecycleState, generation, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ submitTask(threadName, generation, () -> {
+ try {
+ runOnce(connectable, connectableTask, stopCallback, lifecycleState, generation);
+ } finally {
+ stopSchedulingGeneration(componentId, generation, false);
+ }
+ });
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(connectable.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = taskNode.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ submitTask(threadName, generation,
+ () -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, generation));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(taskNode.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ private SchedulingGeneration registerSchedulingGeneration(final String componentId) {
+ if (shutdown.get()) {
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ final SchedulingGeneration generation = new SchedulingGeneration();
+ final SchedulingGeneration existingGeneration = schedulingGenerations.putIfAbsent(componentId, generation);
+ if (existingGeneration != null) {
+ throw new IllegalStateException("Component " + componentId + " is already scheduled");
+ }
+
+ if (shutdown.get()) {
+ stopSchedulingGeneration(componentId, generation, true);
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ return generation;
+ }
+
+ private boolean stopSchedulingGeneration(final String componentId, final SchedulingGeneration generation, final boolean interrupt) {
+ final boolean removed = schedulingGenerations.remove(componentId, generation);
+ generation.stop(interrupt);
+ return removed;
+ }
+
+ private boolean isActive(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ return !shutdown.get() && lifecycleState.isScheduled() && !generation.isStopped();
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public synchronized void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ int getRunningThreadCount() {
+ return runningThreadCount.get();
+ }
+
+ boolean isShutdown() {
+ return shutdown.get();
+ }
+
+ /**
+ * @return number of component invocations currently holding global permits
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getInUsePermits();
+ }
+
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask, final long schedulingNanos,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation, final CronExpression cronExpression) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the component", connectable);
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting", connectable);
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForNextInvocation(connectable, schedulingNanos, generation, invocationResult);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ if (isActive(lifecycleState, generation)) {
+ logger.warn("Run once request for {} was not executed because permit acquisition was interrupted", connectable);
+ } else {
+ logger.warn("Run once request for {} was not executed because scheduling is no longer active", connectable);
+ }
+
+ return;
+ }
+
+ try {
+ connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+ } catch (final Throwable t) {
+ logger.error("Unexpected error running {} once", connectable, t);
+ } finally {
+ try {
+ stopCallback.call();
+ } catch (final Throwable t) {
+ logger.error("Error while stopping {} after running once", connectable, t);
+ }
+ }
+ }
+
+ private void runReportingTaskLoop(final ReportingTaskNode taskNode, final Runnable reportingTaskWrapper, final long schedulingNanos,
+ final CronExpression cronExpression, final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the reporting task",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ reportingTaskWrapper.run();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForDelay(schedulingNanos, generation);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will wait for {} and continue.", taskNode.getReportingTask(), adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void waitForNextInvocation(final Connectable connectable, final long schedulingNanos, final SchedulingGeneration generation,
+ final InvocationResult invocationResult) {
+ final long sleepNanos;
+ final long yieldExpiration = connectable.getYieldExpiration();
+ final long yieldDelayNanos;
+ if (yieldExpiration == 0L) {
+ yieldDelayNanos = 0L;
+ } else {
+ yieldDelayNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(yieldExpiration - System.currentTimeMillis(), 0L));
+ }
+
+ if (yieldDelayNanos > 0L) {
+ sleepNanos = Math.max(schedulingNanos, yieldDelayNanos);
+ } else if (invocationResult.isYield()) {
+ sleepNanos = noWorkYieldNanos > 0L ? noWorkYieldNanos : schedulingNanos;
+ } else {
+ sleepNanos = schedulingNanos;
+ }
+
+ waitForDelay(sleepNanos, generation);
+ }
+
+ private boolean acquirePermitWithPolling(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
Review Comment:
[GPT-5.6 Sol] I walked through the Stop and Run Once interleavings and this is safe. Registration and explicit unscheduling are serialized on `LifecycleState`. Cleanup uses `ConcurrentMap.remove(componentId, generation)`, so completion of an older Run Once cannot remove a newer registered generation. It then stops only the captured generation, and `SchedulingGeneration.stop()` is idempotent. No synchronization change is needed here.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgentTest.java:
##########
@@ -0,0 +1,821 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.components.state.StateManager;
+import org.apache.nifi.components.state.StateManagerProvider;
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.GarbageCollectionLog;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.ScheduledState;
+import org.apache.nifi.controller.repository.FlowFileEventRepository;
+import org.apache.nifi.controller.repository.RepositoryContext;
+import org.apache.nifi.groups.ProcessGroup;
+import org.apache.nifi.nar.ExtensionManager;
+import org.apache.nifi.nar.NarThreadContextClassLoader;
+import org.apache.nifi.processor.Processor;
+import org.apache.nifi.reporting.ReportingContext;
+import org.apache.nifi.reporting.ReportingTask;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.NiFiProperties;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+
+import java.util.Collections;
+import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class VirtualThreadSchedulingAgentTest {
+
+ private static final int MAX_THREADS = 10;
+ private static final String COMPONENT_ID = UUID.randomUUID().toString();
+
+ @Mock
+ private FlowController flowController;
+
+ @Mock
+ private RepositoryContextFactory contextFactory;
+
+ @Mock
+ private NiFiProperties nifiProperties;
+
+ @Mock
+ private StateManagerProvider stateManagerProvider;
+
+ @Mock
+ private StateManager stateManager;
+
+ @Mock
+ private GarbageCollectionLog garbageCollectionLog;
+
+ @Mock
+ private ExtensionManager extensionManager;
+
+ private VirtualThreadSchedulingAgent agent;
+
+ @BeforeEach
+ void setUp() {
+ when(nifiProperties.getBoredYieldDuration()).thenReturn("10 millis");
+ agent = new VirtualThreadSchedulingAgent(flowController, contextFactory, nifiProperties, MAX_THREADS);
+ }
+
+ @AfterEach
+ void tearDown() throws InterruptedException {
+ agent.shutdown();
+ assertTrue(agent.awaitTermination(5, TimeUnit.SECONDS));
+ }
+
+ @Test
+ void testIncrementMaxThreadCountAdjustsSemaphore() {
+ final int originalPermits = agent.getGlobalSemaphore().getMaxPermits();
+
+ agent.incrementMaxThreadCount(0);
+ assertEquals(originalPermits, agent.getGlobalSemaphore().getMaxPermits());
+
+ agent.incrementMaxThreadCount(5);
+ assertEquals(originalPermits + 5, agent.getGlobalSemaphore().getMaxPermits());
+
+ agent.incrementMaxThreadCount(-3);
+ assertEquals(originalPermits + 2, agent.getGlobalSemaphore().getMaxPermits());
+
+ assertThrows(IllegalStateException.class, () -> agent.incrementMaxThreadCount(-1000));
+ }
+
+ @Test
+ void testScheduleSpawnsThreadsThatInvoke() throws InterruptedException {
+ final int concurrentTasks = 3;
+ final AtomicInteger invocationCount = new AtomicInteger(0);
+ final CountDownLatch allTasksInvoked = new CountDownLatch(concurrentTasks);
+ final AtomicBoolean virtualThreadsUsed = new AtomicBoolean(true);
+
+ final Connectable connectable = createMockedConnectable(concurrentTasks, SchedulingStrategy.TIMER_DRIVEN, invocationCount, allTasksInvoked);
+ doAnswer(invocation -> {
+ invocationCount.incrementAndGet();
+ allTasksInvoked.countDown();
+ if (!Thread.currentThread().isVirtual()) {
+ virtualThreadsUsed.set(false);
+ }
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+
+ scheduleConnectable(connectable, lifecycleState);
+
+ assertTrue(allTasksInvoked.await(5, TimeUnit.SECONDS),
+ "Expected " + concurrentTasks + " threads to invoke, but only " + (concurrentTasks - allTasksInvoked.getCount()) + " did");
+ assertTrue(invocationCount.get() >= concurrentTasks,
+ "Expected at least " + concurrentTasks + " invocations but got " + invocationCount.get());
+ assertTrue(virtualThreadsUsed.get());
+
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void testProcessorContinuesAfterInterruptStatusSet() throws InterruptedException {
+ final AtomicInteger invocationCount = new AtomicInteger();
+ final CountDownLatch secondInvocation = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ doAnswer(invocation -> {
+ if (invocationCount.incrementAndGet() == 1) {
+ Thread.currentThread().interrupt();
+ } else {
+ secondInvocation.countDown();
+ }
+
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(secondInvocation.await(2, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ }
+ }
+
+ @Test
+ void testSchedulingThreadUsesFrameworkClassLoaderWithoutInheritedThreadLocals() throws InterruptedException {
+ final InheritableThreadLocal<String> inheritedValue = new InheritableThreadLocal<>();
+ final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
+ final ClassLoader lifecycleClassLoader = new ClassLoader(originalClassLoader) {
+ };
+ final AtomicReference<ClassLoader> observedClassLoader = new AtomicReference<>();
+ final AtomicReference<String> observedInheritedValue = new AtomicReference<>();
+ final CountDownLatch schedulingThreadObserved = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ when(connectable.getYieldExpiration()).thenAnswer(invocation -> {
+ observedClassLoader.compareAndSet(null, Thread.currentThread().getContextClassLoader());
+ observedInheritedValue.compareAndSet(null, inheritedValue.get());
+ schedulingThreadObserved.countDown();
+ return 0L;
+ });
+
+ inheritedValue.set("lifecycle-thread-value");
+ Thread.currentThread().setContextClassLoader(lifecycleClassLoader);
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+
+ try {
+ scheduleConnectable(connectable, lifecycleState);
+ assertTrue(schedulingThreadObserved.await(2, TimeUnit.SECONDS));
+ assertEquals(NarThreadContextClassLoader.getInstance(), observedClassLoader.get());
+ assertNull(observedInheritedValue.get());
+ } finally {
+ inheritedValue.remove();
+ Thread.currentThread().setContextClassLoader(originalClassLoader);
+ unscheduleConnectable(connectable, lifecycleState);
+ }
+ }
+
+ @Test
+ void testDuplicateScheduleIsRejected() throws InterruptedException {
+ final CountDownLatch invocationStarted = new CountDownLatch(1);
+ final CountDownLatch releaseInvocation = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ doAnswer(invocation -> {
+ invocationStarted.countDown();
+ releaseInvocation.await();
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(invocationStarted.await(2, TimeUnit.SECONDS));
+ assertThrows(IllegalStateException.class, () -> agent.schedule(connectable, lifecycleState));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ releaseInvocation.countDown();
+ }
+ }
+
+ @Test
+ void testComponentYieldDoesNotShortenSchedulingPeriod() throws InterruptedException {
+ final long schedulingPeriodMillis = 500L;
+ final AtomicLong yieldExpiration = new AtomicLong();
+ final AtomicInteger invocationCount = new AtomicInteger();
+ final CountDownLatch firstInvocation = new CountDownLatch(1);
+ final CountDownLatch secondInvocation = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ when(connectable.getSchedulingPeriod(TimeUnit.MILLISECONDS)).thenReturn(schedulingPeriodMillis);
+ when(connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS)).thenReturn(TimeUnit.MILLISECONDS.toNanos(schedulingPeriodMillis));
+ when(connectable.getYieldExpiration()).thenAnswer(invocation -> yieldExpiration.get());
+ doAnswer(invocation -> {
+ final int currentInvocation = invocationCount.incrementAndGet();
+ if (currentInvocation == 1) {
+ yieldExpiration.set(System.currentTimeMillis() + 50L);
+ firstInvocation.countDown();
+ } else if (currentInvocation == 2) {
+ secondInvocation.countDown();
+ }
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(firstInvocation.await(2, TimeUnit.SECONDS));
+ assertFalse(secondInvocation.await(250, TimeUnit.MILLISECONDS));
+ assertTrue(secondInvocation.await(2, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ }
+ }
+
+ @Test
+ void testZeroBoredYieldUsesSchedulingPeriod() throws InterruptedException {
+ agent.shutdown();
+ when(nifiProperties.getBoredYieldDuration()).thenReturn("0 millis");
+ agent = new VirtualThreadSchedulingAgent(flowController, contextFactory, nifiProperties, MAX_THREADS);
+
+ final long schedulingPeriodMillis = 500L;
+ final AtomicInteger schedulingAttempts = new AtomicInteger();
+ final CountDownLatch firstAttempt = new CountDownLatch(1);
+ final CountDownLatch secondAttempt = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ when(connectable.getSchedulingPeriod(TimeUnit.MILLISECONDS)).thenReturn(schedulingPeriodMillis);
+ when(connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS)).thenReturn(TimeUnit.MILLISECONDS.toNanos(schedulingPeriodMillis));
+ when(connectable.isIsolated()).thenAnswer(invocation -> {
+ final int attempt = schedulingAttempts.incrementAndGet();
+ if (attempt == 1) {
+ firstAttempt.countDown();
+ } else if (attempt == 2) {
+ secondAttempt.countDown();
+ }
+ return true;
+ });
+ when(flowController.isConfiguredForClustering()).thenReturn(true);
+ when(flowController.isPrimary()).thenReturn(false);
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(firstAttempt.await(2, TimeUnit.SECONDS));
+ assertFalse(secondAttempt.await(250, TimeUnit.MILLISECONDS));
+ assertTrue(secondAttempt.await(2, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ }
+ }
+
+ @Test
+ void testUnscheduleWakesLongSchedulingDelay() throws InterruptedException {
+ final CountDownLatch invocationCompleted = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), invocationCompleted);
+ when(connectable.getSchedulingPeriod(TimeUnit.MILLISECONDS)).thenReturn(TimeUnit.DAYS.toMillis(1L));
+ when(connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS)).thenReturn(TimeUnit.DAYS.toNanos(1L));
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+
+ scheduleConnectable(connectable, lifecycleState);
+ assertTrue(invocationCompleted.await(2, TimeUnit.SECONDS));
+
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ assertEquals(0, lifecycleState.getActiveThreadCount());
+ }
+
+ @Test
+ void testScheduleOnceInvokesAndStops() throws InterruptedException {
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ final CountDownLatch stopCallbackInvoked = new CountDownLatch(1);
+
+ lifecycleState.setScheduled(true);
+ agent.scheduleOnce(connectable, lifecycleState, () -> {
+ stopCallbackInvoked.countDown();
+ return null;
+ });
+
+ assertTrue(stopCallbackInvoked.await(5, TimeUnit.SECONDS),
+ "Stop callback should have been invoked after scheduleOnce");
+ }
+
+ @Test
+ void testUnscheduleExitsWhenSemaphoreFullyContended() throws InterruptedException {
+ agent.setMaxThreadCount(1);
+
+ final CountDownLatch releaseHeldPermit = new CountDownLatch(1);
+ final CountDownLatch permitAcquired = new CountDownLatch(1);
+ final Thread permitHolder = Thread.ofVirtual().start(() -> {
+ try {
+ agent.getGlobalSemaphore().acquire();
+ permitAcquired.countDown();
+ releaseHeldPermit.await();
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ agent.getGlobalSemaphore().release();
+ }
+ });
+ assertTrue(permitAcquired.await(2, TimeUnit.SECONDS), "Failed to acquire permit for test setup");
+
+ final AtomicInteger invocationCount = new AtomicInteger(0);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, invocationCount, new CountDownLatch(0));
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ waitForRunningThreadCount(1, 2, TimeUnit.SECONDS);
+ assertEquals(0, invocationCount.get());
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+
+ releaseHeldPermit.countDown();
+ permitHolder.join(1_000L);
+
+ assertEquals(0, invocationCount.get());
+ }
+
+ @Test
+ void testConcurrentIncrementMaxThreadCountIsThreadSafe() throws InterruptedException {
+ agent.setMaxThreadCount(100);
+
+ final int threadCount = 20;
+ final int incrementsPerThread = 50;
+ final CountDownLatch start = new CountDownLatch(1);
+ final CountDownLatch done = new CountDownLatch(threadCount);
+
+ for (int i = 0; i < threadCount; i++) {
+ Thread.ofVirtual().start(() -> {
+ try {
+ start.await();
+ for (int j = 0; j < incrementsPerThread; j++) {
+ agent.incrementMaxThreadCount(1);
+ }
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } finally {
+ done.countDown();
+ }
+ });
+ }
+
+ start.countDown();
+ assertTrue(done.await(5, TimeUnit.SECONDS));
+
+ assertEquals(100 + threadCount * incrementsPerThread, agent.getGlobalSemaphore().getMaxPermits(),
+ "Lost increments imply a race condition in incrementMaxThreadCount");
+ }
+
+ @Test
+ void testSchedulingPeriodReadOnceWhenScheduled() throws InterruptedException {
+ final CountDownLatch invocationsCompleted = new CountDownLatch(5);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), invocationsCompleted);
+ final AtomicInteger schedulingPeriodCalls = new AtomicInteger();
+ when(connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS)).thenAnswer(invocation -> {
+ schedulingPeriodCalls.incrementAndGet();
+ return TimeUnit.MILLISECONDS.toNanos(10L);
+ });
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(invocationsCompleted.await(5, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ }
+
+ assertEquals(1, schedulingPeriodCalls.get());
+ }
+
+ @Test
+ void testSchedulingLoopContinuesAfterUnexpectedError() throws InterruptedException {
+ agent.setAdministrativeYieldDuration("1 millis");
+ final CountDownLatch invocationCompleted = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), invocationCompleted);
+ when(connectable.isIsolated()).thenThrow(new AssertionError("Simulated scheduling error")).thenReturn(false);
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ try {
+ assertTrue(invocationCompleted.await(2, TimeUnit.SECONDS));
+ } finally {
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ }
+
+ assertEquals(MAX_THREADS, agent.getGlobalSemaphore().availablePermits());
+ }
+
+ @Test
+ void testInvocationExceptionStillReleasesPermit() throws InterruptedException {
+ agent.setMaxThreadCount(2);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.TIMER_DRIVEN, new AtomicInteger(), new CountDownLatch(0));
+ final AtomicInteger invocationCount = new AtomicInteger(0);
+ final CountDownLatch successfulInvocation = new CountDownLatch(1);
+ doAnswer(invocation -> {
+ final int count = invocationCount.incrementAndGet();
+ if (count <= 3) {
+ throw new IllegalStateException("Simulated failure " + count);
+ }
+ successfulInvocation.countDown();
+ return null;
+ }).when(connectable).onTrigger(any(), any());
+
+ final LifecycleState lifecycleState = new LifecycleState(COMPONENT_ID);
+ scheduleConnectable(connectable, lifecycleState);
+
+ assertTrue(successfulInvocation.await(2, TimeUnit.SECONDS));
+ unscheduleConnectable(connectable, lifecycleState);
+ waitForRunningThreadCount(0, 2, TimeUnit.SECONDS);
+ assertEquals(2, agent.getGlobalSemaphore().availablePermits());
+ }
+
+ @Test
+ void testCronScheduleSpawnsThreadsAndInvokes() throws InterruptedException {
+ final AtomicInteger invocationCount = new AtomicInteger(0);
+ final CountDownLatch atLeastOneInvocation = new CountDownLatch(1);
+ final Connectable connectable = createMockedConnectable(1, SchedulingStrategy.CRON_DRIVEN, invocationCount, atLeastOneInvocation);
+ when(connectable.getSchedulingPeriod()).thenReturn("* * * * * ?");
+ when(connectable.evaluateParameters(eq("* * * * * ?"))).thenReturn("* * * * * ?");
Review Comment:
[GPT-5.6 Sol] Updated in 35dc8b9643f. The repeated expression is now the shared `CRON_SCHEDULE` constant.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/test/java/org/apache/nifi/controller/tasks/ReportingTaskWrapperTest.java:
##########
@@ -0,0 +1,67 @@
+/*
+ * 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.controller.tasks;
+
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.scheduling.LifecycleState;
+import org.apache.nifi.nar.ExtensionManager;
+import org.apache.nifi.reporting.ReportingContext;
+import org.apache.nifi.reporting.ReportingTask;
+import org.junit.jupiter.api.Test;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+class ReportingTaskWrapperTest {
Review Comment:
[GPT-5.6 Sol] This test is intentional regression coverage. `ReportingTaskWrapper.run()` previously held its monitor while calling `ReportingTask.onTrigger()`, which would pin the carrier thread when explicit virtual scheduling is used on Java 21 and affect every Reporting Task. The test verifies that framework code does not hold that monitor while extension code runs, so I retained it.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,627 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.Triggerable;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.nar.NarThreadContextClassLoader;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Scheduling agent that runs components on virtual threads. A {@link DynamicSemaphore}
+ * limits the number of component invocations that can run concurrently.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ private static final long PERMIT_POLL_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(1L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private final ExecutorService executorService;
+ private final ConcurrentMap<String, SchedulingGeneration> schedulingGenerations = new ConcurrentHashMap<>();
+ private final AtomicBoolean shutdown = new AtomicBoolean();
+ private final AtomicInteger runningThreadCount = new AtomicInteger();
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new IllegalStateException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration, e);
+ }
+
+ final ThreadFactory threadFactory = runnable -> {
+ final Thread thread = Thread.ofVirtual().inheritInheritableThreadLocals(false).unstarted(runnable);
+ thread.setContextClassLoader(NarThreadContextClassLoader.getInstance());
+ return thread;
+ };
+ executorService = Executors.newThreadPerTaskExecutor(threadFactory);
+ logger.info("VirtualThreadSchedulingAgent initialized with {} permits", maxThreadCount);
+ }
+
+ @Override
+ public void shutdown() {
+ signalShutdown(true);
+ executorService.shutdownNow();
+ }
+
+ public void shutdownGracefully() {
+ signalShutdown(false);
+ executorService.shutdown();
+ }
+
+ private void signalShutdown(final boolean interrupt) {
+ shutdown.set(true);
+
+ for (final SchedulingGeneration generation : schedulingGenerations.values()) {
+ generation.stop(interrupt);
+ }
+ }
+
+ public boolean awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException {
+ return executorService.awaitTermination(timeout, timeUnit);
+ }
+
+ public boolean isTerminated() {
+ return executorService.isTerminated();
+ }
+
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final boolean cronDriven = connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ submitTask(threadName, generation, () -> runSchedulingLoop(connectable, connectableTask, schedulingNanos, lifecycleState, generation, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ submitTask(threadName, generation, () -> {
+ try {
+ runOnce(connectable, connectableTask, stopCallback, lifecycleState, generation);
+ } finally {
+ stopSchedulingGeneration(componentId, generation, false);
+ }
+ });
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(connectable.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = taskNode.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ submitTask(threadName, generation,
+ () -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, generation));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(taskNode.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ private SchedulingGeneration registerSchedulingGeneration(final String componentId) {
+ if (shutdown.get()) {
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ final SchedulingGeneration generation = new SchedulingGeneration();
+ final SchedulingGeneration existingGeneration = schedulingGenerations.putIfAbsent(componentId, generation);
+ if (existingGeneration != null) {
+ throw new IllegalStateException("Component " + componentId + " is already scheduled");
+ }
+
+ if (shutdown.get()) {
+ stopSchedulingGeneration(componentId, generation, true);
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ return generation;
+ }
+
+ private boolean stopSchedulingGeneration(final String componentId, final SchedulingGeneration generation, final boolean interrupt) {
+ final boolean removed = schedulingGenerations.remove(componentId, generation);
+ generation.stop(interrupt);
+ return removed;
+ }
+
+ private boolean isActive(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ return !shutdown.get() && lifecycleState.isScheduled() && !generation.isStopped();
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public synchronized void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ int getRunningThreadCount() {
+ return runningThreadCount.get();
+ }
+
+ boolean isShutdown() {
+ return shutdown.get();
+ }
+
+ /**
+ * @return number of component invocations currently holding global permits
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getInUsePermits();
+ }
+
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask, final long schedulingNanos,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation, final CronExpression cronExpression) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the component", connectable);
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting", connectable);
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForNextInvocation(connectable, schedulingNanos, generation, invocationResult);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ if (isActive(lifecycleState, generation)) {
+ logger.warn("Run once request for {} was not executed because permit acquisition was interrupted", connectable);
+ } else {
+ logger.warn("Run once request for {} was not executed because scheduling is no longer active", connectable);
+ }
+
+ return;
+ }
+
+ try {
+ connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+ } catch (final Throwable t) {
+ logger.error("Unexpected error running {} once", connectable, t);
+ } finally {
+ try {
+ stopCallback.call();
+ } catch (final Throwable t) {
+ logger.error("Error while stopping {} after running once", connectable, t);
+ }
+ }
+ }
+
+ private void runReportingTaskLoop(final ReportingTaskNode taskNode, final Runnable reportingTaskWrapper, final long schedulingNanos,
+ final CronExpression cronExpression, final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the reporting task",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ reportingTaskWrapper.run();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForDelay(schedulingNanos, generation);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will wait for {} and continue.", taskNode.getReportingTask(), adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void waitForNextInvocation(final Connectable connectable, final long schedulingNanos, final SchedulingGeneration generation,
+ final InvocationResult invocationResult) {
+ final long sleepNanos;
+ final long yieldExpiration = connectable.getYieldExpiration();
+ final long yieldDelayNanos;
+ if (yieldExpiration == 0L) {
+ yieldDelayNanos = 0L;
+ } else {
+ yieldDelayNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(yieldExpiration - System.currentTimeMillis(), 0L));
+ }
+
+ if (yieldDelayNanos > 0L) {
+ sleepNanos = Math.max(schedulingNanos, yieldDelayNanos);
+ } else if (invocationResult.isYield()) {
+ sleepNanos = noWorkYieldNanos > 0L ? noWorkYieldNanos : schedulingNanos;
+ } else {
+ sleepNanos = schedulingNanos;
+ }
+
+ waitForDelay(sleepNanos, generation);
+ }
+
+ private boolean acquirePermitWithPolling(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ while (isActive(lifecycleState, generation)) {
+ try {
+ if (globalSemaphore.tryAcquire(PERMIT_POLL_INTERVAL_NANOS, TimeUnit.NANOSECONDS)) {
+ if (isActive(lifecycleState, generation)) {
+ return true;
+ }
+
+ globalSemaphore.release();
+ return false;
+ }
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ return false;
+ }
+ }
+
+ return false;
+ }
+
+ private void waitForDelay(final long delayNanos, final SchedulingGeneration generation) {
+ if (delayNanos <= Triggerable.MINIMUM_SCHEDULING_NANOS) {
+ return;
+ }
+
+ try {
+ generation.awaitStop(delayNanos, TimeUnit.NANOSECONDS);
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ private static String buildThreadName(final Connectable connectable, final int taskIndex) {
+ return connectable.getName() + "[type=" + connectable.getComponentType() + ", id=" + connectable.getIdentifier()
Review Comment:
[GPT-5.6 Sol] Updated in 35dc8b9643f to use a formatted String.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "exceptionfactory (via GitHub)" <gi...@apache.org>.
exceptionfactory merged PR #11164:
URL: https://github.com/apache/nifi/pull/11164
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3131296534
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,454 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Scheduling agent that runs processors, funnels, ports, and reporting tasks on virtual
+ * threads rather than on a shared thread pool. A single {@link DynamicSemaphore} bounds
+ * the number of invocations that may run concurrently across the entire flow. Its permit
+ * count replaces the old Timer-Driven thread pool size and is adjustable at runtime via
+ * {@link #setMaxThreadCount(int)}.
+ * <p>
+ * The agent is used for both {@link SchedulingStrategy#TIMER_DRIVEN} and
+ * {@link SchedulingStrategy#CRON_DRIVEN} connectables. Each scheduled connectable is given
+ * one virtual thread per concurrent task; every iteration of the scheduling loop acquires
+ * a permit, calls {@link ConnectableTask#invoke()}, releases the permit, and then sleeps
+ * until the next invocation is due.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ /**
+ * Sleeps in the scheduling loop are broken up into chunks of at most this long so that
+ * a processor that is unscheduled while a scheduling thread is sleeping will exit the
+ * sleep and observe the state change quickly rather than having to wait for the full
+ * scheduling period to elapse.
+ */
+ private static final long POLL_INTERVAL_NANOS = TimeUnit.MILLISECONDS.toNanos(25L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new RuntimeException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration);
+ }
+ }
+
+ @Override
+ public void shutdown() {
+ }
+
+ /**
+ * Schedules the given connectable to run on virtual threads. This method transitions the
+ * {@link LifecycleState} to scheduled and then spawns one virtual thread per concurrent task. Each scheduling loop
+ * captures {@link LifecycleState#getLastStopTime()} at startup and will exit as soon as either
+ * {@link LifecycleState#isScheduled()} becomes {@code false} or the last-stop-time advances, which is how the
+ * agent guards against a rapid stop/start cycle leaving prior loops running alongside newly-spawned ones. The
+ * corresponding {@link #unschedule(Connectable, LifecycleState)} call performs the inverse transition. Calling
+ * {@code setScheduled(true)} here is intentionally idempotent: the framework scheduler also marks the state as
+ * scheduled in some code paths (for example, reporting-task startup), and double-calling is harmless because the
+ * last-stop-time only advances on transitions to the stopped state.
+ */
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final CronExpression cronExpression;
+ if (connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ } else {
+ cronExpression = null;
+ }
+
+ lifecycleState.setScheduled(true);
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ Thread.ofVirtual().name(threadName).start(() -> runSchedulingLoop(connectable, connectableTask, lifecycleState, startStopTime, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ lifecycleState.setScheduled(true);
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ Thread.ofVirtual().name(threadName).start(() -> runOnce(connectable, connectableTask, stopCallback));
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ lifecycleState.setScheduled(true);
+ final long startStopTime = lifecycleState.getLastStopTime();
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ Thread.ofVirtual().name(threadName).start(() -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, startStopTime));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ lifecycleState.setScheduled(false);
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ /**
+ * @return {@code true} if {@code lifecycleState} is still scheduled and its last-stop-time has not changed since
+ * the scheduling loop was spawned (meaning the loop is still running against its original scheduling generation).
+ * Used by the scheduling loops and their polling helpers to detect both the normal stop path (isScheduled flips to
+ * false) and the rapid stop/start race (a stop increments lastStopTime even if a quick restart flips isScheduled
+ * back to true before the old loop has observed the stop).
+ */
+ private boolean isActive(final LifecycleState lifecycleState, final long startStopTime) {
+ return lifecycleState.isScheduled() && lifecycleState.getLastStopTime() == startStopTime;
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ /**
+ * @return the number of virtual threads that are currently executing a processor or
+ * reporting-task invocation. A thread counts as active when it is holding a permit on
+ * the global semaphore, which mirrors the old Timer-Driven engine's active-count
+ * semantics used by the cluster heartbeat and UI active-thread counter.
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getMaxPermits() - globalSemaphore.availablePermits();
+ }
+
+ /**
+ * Runs the scheduling loop for a {@link Connectable}. Each iteration acquires a permit from the global semaphore,
+ * invokes the connectable, releases the permit, and sleeps until the next invocation is due. The entire body of
+ * the loop is wrapped in a {@code try/catch(Throwable)} so that no exception or error -- including
+ * {@link Error} subclasses or bugs in the scheduling logic itself -- can cause the virtual thread to terminate
+ * silently. A processor is expected to continue being triggered as long as it is scheduled, so on any unexpected
+ * {@link Throwable} the error is logged, an administrative yield is applied to prevent tight-looping on a broken
+ * task, and the loop continues on its next iteration.
+ */
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask,
+ final LifecycleState lifecycleState, final long startStopTime, final CronExpression cronExpression) {
+
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), lifecycleState, startStopTime);
+ }
+ }
+
+ while (isActive(lifecycleState, startStopTime)) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, startStopTime)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ sleepWithPolling(TimeUnit.MILLISECONDS.toNanos(sleepMillis), lifecycleState, startStopTime);
+ } else {
+ sleepForSchedulingPeriod(connectable, lifecycleState, startStopTime, invocationResult);
+ }
+ } catch (final Throwable t) {
+ // Nothing in the loop body is expected to throw (ConnectableTask.invoke() catches Throwable itself, and
+ // acquirePermitWithPolling handles InterruptedException). If anything does escape to here, it must not
+ // be allowed to kill the scheduling virtual thread: as long as the component remains scheduled we will
+ // keep triggering it. Log the error, apply an administrative yield to avoid tight-looping on a broken
+ // invocation, and continue with the next iteration.
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback) {
+ try {
+ try {
+ globalSemaphore.acquire();
Review Comment:
Use of `.acquire` is fine here because there's no way to explicitly stop a Processor when it's triggered with RunOnce anyway so doing it with polling doesn't buy us anything.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3131461615
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/FlowController.java:
##########
Review Comment:
Good catch, will ensure that they are interrupted.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3229385417
##########
nifi-framework-api/src/main/java/org/apache/nifi/diagnostics/ThreadDumpTask.java:
##########
@@ -16,116 +16,51 @@
*/
package org.apache.nifi.diagnostics;
-import java.lang.management.LockInfo;
+import com.sun.management.HotSpotDiagnosticMXBean;
+
+import java.io.IOException;
import java.lang.management.ManagementFactory;
-import java.lang.management.MonitorInfo;
-import java.lang.management.ThreadInfo;
-import java.lang.management.ThreadMXBean;
-import java.util.ArrayList;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Objects;
+/**
+ * Captures a textual dump of every thread in the JVM. Uses
+ * {@link HotSpotDiagnosticMXBean#dumpThreads(String, HotSpotDiagnosticMXBean.ThreadDumpFormat)}
+ * so that virtual threads are included in the dump alongside platform threads.
+ */
public class ThreadDumpTask implements DiagnosticTask {
- @Override
- public DiagnosticsDumpElement captureDump(boolean verbose) {
- final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
-
- final ThreadInfo[] infos = mbean.dumpAllThreads(true, true);
- final long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
- final long[] monitorDeadlockThreadIds = mbean.findMonitorDeadlockedThreads();
-
- final List<ThreadInfo> sortedInfos = new ArrayList<>(infos.length);
- Collections.addAll(sortedInfos, infos);
- sortedInfos.sort(new Comparator<>() {
- @Override
- public int compare(ThreadInfo o1, ThreadInfo o2) {
- return o1.getThreadName().toLowerCase().compareTo(o2.getThreadName().toLowerCase());
- }
- });
-
- final StringBuilder sb = new StringBuilder();
- for (final ThreadInfo info : sortedInfos) {
- sb.append("\n");
- sb.append("\"").append(info.getThreadName()).append("\" Id=");
- sb.append(info.getThreadId()).append(" ");
- sb.append(info.getThreadState().toString()).append(" ");
-
- switch (info.getThreadState()) {
- case BLOCKED:
- case TIMED_WAITING:
- case WAITING:
- sb.append(" on ");
- sb.append(info.getLockInfo());
- break;
- default:
- break;
- }
-
- if (info.isSuspended()) {
- sb.append(" (suspended)");
- }
- if (info.isInNative()) {
- sb.append(" (in native code)");
- }
-
- if (deadlockedThreadIds != null) {
- for (final long id : deadlockedThreadIds) {
- if (id == info.getThreadId()) {
- sb.append(" ** DEADLOCKED THREAD **");
- }
- }
- }
- if (monitorDeadlockThreadIds != null) {
- for (final long id : monitorDeadlockThreadIds) {
- if (id == info.getThreadId()) {
- sb.append(" ** MONITOR-DEADLOCKED THREAD **");
- }
- }
- }
-
- final StackTraceElement[] stackTraces = info.getStackTrace();
- for (final StackTraceElement element : stackTraces) {
- sb.append("\n\tat ").append(element);
-
- final MonitorInfo[] monitors = info.getLockedMonitors();
- for (final MonitorInfo monitor : monitors) {
- if (Objects.equals(monitor.getLockedStackFrame(), element)) {
- sb.append("\n\t- waiting on ").append(monitor);
- }
- }
+ @Override
+ public DiagnosticsDumpElement captureDump(final boolean verbose) {
+ String threadDump;
+
+ Path tempDirectory = null;
+ try {
+ final HotSpotDiagnosticMXBean diagnosticMXBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
+ // dumpThreads requires that the destination file does not already exist. Creating a private
+ // temporary directory and writing to a fresh filename inside it avoids a time-of-check to
+ // time-of-use race that would exist if we created a temp file and then deleted it before the
+ // dumpThreads call.
+ tempDirectory = Files.createTempDirectory("nifi-thread-dump-");
+ final Path tempFile = tempDirectory.resolve("thread-dump.txt");
+ try {
+ diagnosticMXBean.dumpThreads(tempFile.toString(), HotSpotDiagnosticMXBean.ThreadDumpFormat.TEXT_PLAIN);
+ threadDump = Files.readString(tempFile);
+ } finally {
+ Files.deleteIfExists(tempFile);
}
-
- final LockInfo[] lockInfos = info.getLockedSynchronizers();
- if (lockInfos.length > 0) {
- sb.append("\n\t");
- sb.append("Number of Locked Synchronizers: ").append(lockInfos.length);
- for (final LockInfo lockInfo : lockInfos) {
- sb.append("\n\t- ").append(lockInfo.toString());
+ } catch (final IOException e) {
+ threadDump = "Failed to capture thread dump: " + e.getMessage();
+ } finally {
+ if (tempDirectory != null) {
+ try {
+ Files.deleteIfExists(tempDirectory);
+ } catch (final IOException ignored) {
Review Comment:
Sure, that's reasonable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-4442651059
Thanks @markap14 - To clarify it would remain for now default off. We'd give it time to bake/prove itself then later consider swapping to default on. Then perhaps later remove the old model entirely?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r4030934521
##########
nifi-framework-bundle/nifi-framework/nifi-framework-core/src/main/java/org/apache/nifi/controller/scheduling/VirtualThreadSchedulingAgent.java:
##########
@@ -0,0 +1,627 @@
+/*
+ * 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.controller.scheduling;
+
+import org.apache.nifi.connectable.Connectable;
+import org.apache.nifi.controller.FlowController;
+import org.apache.nifi.controller.ReportingTaskNode;
+import org.apache.nifi.controller.Triggerable;
+import org.apache.nifi.controller.tasks.ConnectableTask;
+import org.apache.nifi.controller.tasks.InvocationResult;
+import org.apache.nifi.controller.tasks.ReportingTaskWrapper;
+import org.apache.nifi.nar.NarThreadContextClassLoader;
+import org.apache.nifi.scheduling.SchedulingStrategy;
+import org.apache.nifi.util.FormatUtils;
+import org.apache.nifi.util.NiFiProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.scheduling.support.CronExpression;
+
+import java.time.OffsetDateTime;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Scheduling agent that runs components on virtual threads. A {@link DynamicSemaphore}
+ * limits the number of component invocations that can run concurrently.
+ */
+public class VirtualThreadSchedulingAgent implements SchedulingAgent {
+
+ private static final Logger logger = LoggerFactory.getLogger(VirtualThreadSchedulingAgent.class);
+
+ private static final long PERMIT_POLL_INTERVAL_NANOS = TimeUnit.SECONDS.toNanos(1L);
+
+ private final FlowController flowController;
+ private final RepositoryContextFactory contextFactory;
+ private final DynamicSemaphore globalSemaphore;
+ private final long noWorkYieldNanos;
+ private final ExecutorService executorService;
+ private final ConcurrentMap<String, SchedulingGeneration> schedulingGenerations = new ConcurrentHashMap<>();
+ private final AtomicBoolean shutdown = new AtomicBoolean();
+ private final AtomicInteger runningThreadCount = new AtomicInteger();
+ private volatile String adminYieldDuration = "1 sec";
+ private volatile long adminYieldNanos = TimeUnit.SECONDS.toNanos(1L);
+
+ public VirtualThreadSchedulingAgent(final FlowController flowController, final RepositoryContextFactory contextFactory,
+ final NiFiProperties nifiProperties, final int maxThreadCount) {
+ this.flowController = flowController;
+ this.contextFactory = contextFactory;
+ this.globalSemaphore = new DynamicSemaphore(maxThreadCount);
+
+ final String boredYieldDuration = nifiProperties.getBoredYieldDuration();
+ try {
+ noWorkYieldNanos = FormatUtils.getTimeDuration(boredYieldDuration, TimeUnit.NANOSECONDS);
+ } catch (final IllegalArgumentException e) {
+ throw new IllegalStateException("Failed to create VirtualThreadSchedulingAgent because the "
+ + NiFiProperties.BORED_YIELD_DURATION + " property is set to an invalid time duration: " + boredYieldDuration, e);
+ }
+
+ final ThreadFactory threadFactory = runnable -> {
+ final Thread thread = Thread.ofVirtual().inheritInheritableThreadLocals(false).unstarted(runnable);
+ thread.setContextClassLoader(NarThreadContextClassLoader.getInstance());
+ return thread;
+ };
+ executorService = Executors.newThreadPerTaskExecutor(threadFactory);
+ logger.info("VirtualThreadSchedulingAgent initialized with {} permits", maxThreadCount);
+ }
+
+ @Override
+ public void shutdown() {
+ signalShutdown(true);
+ executorService.shutdownNow();
+ }
+
+ public void shutdownGracefully() {
+ signalShutdown(false);
+ executorService.shutdown();
+ }
+
+ private void signalShutdown(final boolean interrupt) {
+ shutdown.set(true);
+
+ for (final SchedulingGeneration generation : schedulingGenerations.values()) {
+ generation.stop(interrupt);
+ }
+ }
+
+ public boolean awaitTermination(final long timeout, final TimeUnit timeUnit) throws InterruptedException {
+ return executorService.awaitTermination(timeout, timeUnit);
+ }
+
+ public boolean isTerminated() {
+ return executorService.isTerminated();
+ }
+
+ @Override
+ public void schedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ final boolean cronDriven = connectable.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ final String cronSchedule = connectable.evaluateParameters(connectable.getSchedulingPeriod());
+ cronExpression = parseCronExpression(cronSchedule, connectable);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = connectable.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final int taskCount = connectable.getMaxConcurrentTasks();
+
+ for (int i = 0; i < taskCount; i++) {
+ final String threadName = buildThreadName(connectable, i);
+ submitTask(threadName, generation, () -> runSchedulingLoop(connectable, connectableTask, schedulingNanos, lifecycleState, generation, cronExpression));
+ }
+
+ logger.info("Scheduled {} to run with {} virtual threads", connectable, taskCount);
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void scheduleOnce(final Connectable connectable, final LifecycleState lifecycleState, final Callable<Future<Void>> stopCallback) {
+ final String componentId = connectable.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final ConnectableTask connectableTask = new ConnectableTask(this, connectable, flowController, contextFactory, lifecycleState);
+ final String threadName = buildThreadName(connectable, 0);
+
+ submitTask(threadName, generation, () -> {
+ try {
+ runOnce(connectable, connectableTask, stopCallback, lifecycleState, generation);
+ } finally {
+ stopSchedulingGeneration(componentId, generation, false);
+ }
+ });
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final Connectable connectable, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(connectable.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", connectable);
+ }
+
+ @Override
+ public void schedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ final boolean cronDriven = taskNode.getSchedulingStrategy() == SchedulingStrategy.CRON_DRIVEN;
+ final CronExpression cronExpression;
+ final long schedulingNanos;
+ if (cronDriven) {
+ cronExpression = parseCronExpression(taskNode.getSchedulingPeriod(), taskNode);
+ schedulingNanos = 0L;
+ } else {
+ cronExpression = null;
+ schedulingNanos = taskNode.getSchedulingPeriod(TimeUnit.NANOSECONDS);
+ }
+
+ final String componentId = taskNode.getIdentifier();
+ final SchedulingGeneration generation;
+ synchronized (lifecycleState) {
+ generation = registerSchedulingGeneration(componentId);
+ lifecycleState.setScheduled(true);
+ }
+
+ try {
+ final Runnable reportingTaskWrapper = new ReportingTaskWrapper(taskNode, lifecycleState, flowController.getExtensionManager());
+ final String threadName = "Reporting Task: " + taskNode.getName();
+
+ submitTask(threadName, generation,
+ () -> runReportingTaskLoop(taskNode, reportingTaskWrapper, schedulingNanos, cronExpression, lifecycleState, generation));
+
+ logger.info("{} started on virtual thread", taskNode.getReportingTask());
+ } catch (final Throwable t) {
+ synchronized (lifecycleState) {
+ if (stopSchedulingGeneration(componentId, generation, true)) {
+ lifecycleState.setScheduled(false);
+ }
+ }
+
+ throw t;
+ }
+ }
+
+ @Override
+ public void unschedule(final ReportingTaskNode taskNode, final LifecycleState lifecycleState) {
+ synchronized (lifecycleState) {
+ final SchedulingGeneration generation = schedulingGenerations.remove(taskNode.getIdentifier());
+ if (generation != null) {
+ generation.stop(false);
+ }
+
+ lifecycleState.setScheduled(false);
+ }
+
+ logger.info("Stopped scheduling {} to run", taskNode.getReportingTask());
+ }
+
+ private SchedulingGeneration registerSchedulingGeneration(final String componentId) {
+ if (shutdown.get()) {
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ final SchedulingGeneration generation = new SchedulingGeneration();
+ final SchedulingGeneration existingGeneration = schedulingGenerations.putIfAbsent(componentId, generation);
+ if (existingGeneration != null) {
+ throw new IllegalStateException("Component " + componentId + " is already scheduled");
+ }
+
+ if (shutdown.get()) {
+ stopSchedulingGeneration(componentId, generation, true);
+ throw new IllegalStateException("VirtualThreadSchedulingAgent has been shut down and cannot accept new work");
+ }
+
+ return generation;
+ }
+
+ private boolean stopSchedulingGeneration(final String componentId, final SchedulingGeneration generation, final boolean interrupt) {
+ final boolean removed = schedulingGenerations.remove(componentId, generation);
+ generation.stop(interrupt);
+ return removed;
+ }
+
+ private boolean isActive(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ return !shutdown.get() && lifecycleState.isScheduled() && !generation.isStopped();
+ }
+
+ private static CronExpression parseCronExpression(final String cronSchedule, final Object component) {
+ try {
+ return CronExpression.parse(cronSchedule);
+ } catch (final RuntimeException e) {
+ throw new IllegalStateException("Cannot schedule " + component + " to run because its scheduling period is not a valid CRON expression: " + cronSchedule, e);
+ }
+ }
+
+ @Override
+ public void onEvent(final Connectable connectable) {
+ }
+
+ @Override
+ public synchronized void setMaxThreadCount(final int maxThreads) {
+ globalSemaphore.setMaxPermits(maxThreads);
+ logger.info("Global semaphore permits updated to {}", maxThreads);
+ }
+
+ @Override
+ public synchronized void incrementMaxThreadCount(final int toAdd) {
+ if (toAdd == 0) {
+ return;
+ }
+
+ final int currentMax = globalSemaphore.getMaxPermits();
+ final int newMax = currentMax + toAdd;
+ if (newMax < 1) {
+ throw new IllegalStateException("Cannot remove " + (-toAdd) + " permits from global semaphore because there are only " + currentMax + " permits available");
+ }
+
+ globalSemaphore.setMaxPermits(newMax);
+ }
+
+ @Override
+ public void setAdministrativeYieldDuration(final String duration) {
+ this.adminYieldNanos = FormatUtils.getTimeDuration(duration, TimeUnit.NANOSECONDS);
+ this.adminYieldDuration = duration;
+ }
+
+ @Override
+ public String getAdministrativeYieldDuration() {
+ return adminYieldDuration;
+ }
+
+ @Override
+ public long getAdministrativeYieldDuration(final TimeUnit timeUnit) {
+ return timeUnit.convert(adminYieldNanos, TimeUnit.NANOSECONDS);
+ }
+
+ DynamicSemaphore getGlobalSemaphore() {
+ return globalSemaphore;
+ }
+
+ int getRunningThreadCount() {
+ return runningThreadCount.get();
+ }
+
+ boolean isShutdown() {
+ return shutdown.get();
+ }
+
+ /**
+ * @return number of component invocations currently holding global permits
+ */
+ public int getActiveThreadCount() {
+ return globalSemaphore.getInUsePermits();
+ }
+
+ private void runSchedulingLoop(final Connectable connectable, final ConnectableTask connectableTask, final long schedulingNanos,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation, final CronExpression cronExpression) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the component", connectable);
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ final InvocationResult invocationResult;
+ try {
+ invocationResult = connectableTask.invoke();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting", connectable);
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForNextInvocation(connectable, schedulingNanos, generation, invocationResult);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ connectable.yield(adminYieldNanos, TimeUnit.NANOSECONDS);
+ } catch (final Throwable yieldError) {
+ t.addSuppressed(yieldError);
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will yield for {} and continue.", connectable, adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void runOnce(final Connectable connectable, final ConnectableTask connectableTask, final Callable<Future<Void>> stopCallback,
+ final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ if (isActive(lifecycleState, generation)) {
+ logger.warn("Run once request for {} was not executed because permit acquisition was interrupted", connectable);
+ } else {
+ logger.warn("Run once request for {} was not executed because scheduling is no longer active", connectable);
+ }
+
+ return;
+ }
+
+ try {
+ connectableTask.invoke();
+ } finally {
+ globalSemaphore.release();
+ }
+ } catch (final Throwable t) {
+ logger.error("Unexpected error running {} once", connectable, t);
+ } finally {
+ try {
+ stopCallback.call();
+ } catch (final Throwable t) {
+ logger.error("Error while stopping {} after running once", connectable, t);
+ }
+ }
+ }
+
+ private void runReportingTaskLoop(final ReportingTaskNode taskNode, final Runnable reportingTaskWrapper, final long schedulingNanos,
+ final CronExpression cronExpression, final LifecycleState lifecycleState, final SchedulingGeneration generation) {
+ final boolean cronDriven = cronExpression != null;
+
+ OffsetDateTime nextCronSchedule = null;
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(OffsetDateTime.now(), cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no future firings; scheduling loop will exit without invoking the reporting task",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long initialDelayMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ if (initialDelayMillis > 0L) {
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(initialDelayMillis), generation);
+ }
+ }
+
+ while (true) {
+ try {
+ if (!acquirePermitWithPolling(lifecycleState, generation)) {
+ return;
+ }
+
+ try {
+ reportingTaskWrapper.run();
+ } finally {
+ // Interrupt status from one invocation must not carry into the scheduling loop.
+ Thread.interrupted();
+ globalSemaphore.release();
+ }
+
+ if (cronDriven) {
+ nextCronSchedule = getNextCronSchedule(nextCronSchedule, cronExpression);
+ if (nextCronSchedule == null) {
+ logger.warn("CRON expression for {} has no further firings after the current invocation; scheduling loop is exiting",
+ taskNode.getReportingTask());
+ return;
+ }
+
+ final long sleepMillis = Math.max(nextCronSchedule.toInstant().toEpochMilli() - System.currentTimeMillis(), 0L);
+ waitForDelay(TimeUnit.MILLISECONDS.toNanos(sleepMillis), generation);
+ } else {
+ waitForDelay(schedulingNanos, generation);
+ }
+ } catch (final Throwable t) {
+ if (!isActive(lifecycleState, generation)) {
+ return;
+ }
+
+ logger.error("Unexpected error in scheduling loop for {}. Will wait for {} and continue.", taskNode.getReportingTask(), adminYieldDuration, t);
+ waitForDelay(adminYieldNanos, generation);
+ }
+ }
+ }
+
+ private void waitForNextInvocation(final Connectable connectable, final long schedulingNanos, final SchedulingGeneration generation,
+ final InvocationResult invocationResult) {
+ final long sleepNanos;
+ final long yieldExpiration = connectable.getYieldExpiration();
+ final long yieldDelayNanos;
+ if (yieldExpiration == 0L) {
+ yieldDelayNanos = 0L;
+ } else {
+ yieldDelayNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(yieldExpiration - System.currentTimeMillis(), 0L));
+ }
+
+ if (yieldDelayNanos > 0L) {
+ sleepNanos = Math.max(schedulingNanos, yieldDelayNanos);
+ } else if (invocationResult.isYield()) {
+ sleepNanos = noWorkYieldNanos > 0L ? noWorkYieldNanos : schedulingNanos;
+ } else {
+ sleepNanos = schedulingNanos;
+ }
+
+ waitForDelay(sleepNanos, generation);
+ }
+
+ private boolean acquirePermitWithPolling(final LifecycleState lifecycleState, final SchedulingGeneration generation) {
Review Comment:
Thanks for clarifying. You were right: the final active check in `acquirePermitWithPolling()` could succeed, followed by an unschedule before `ConnectableTask` registered the invocation as active. `ConnectableTask` now calls `LifecycleState.tryIncrementActiveThreadCount()`, which checks the scheduled state and registers the invocation under the same lifecycle monitor used by unscheduling. If unscheduling wins, `onTrigger()` is skipped; if registration wins, the stop sequence sees an active invocation and waits for it. I added a deterministic regression test that pauses after permit acquisition and confirmed it failed with one invocation before this correction and now passes with zero.
##########
nifi-framework-bundle/nifi-framework/nifi-framework-components/src/main/java/org/apache/nifi/controller/StandardProcessorNode.java:
##########
@@ -574,7 +574,7 @@ public void yield() {
@Override
Review Comment:
Good catch. `ThreadMXBean.dumpAllThreads()` does not include virtual threads, so the lookup returned null and `ThreadUtils.createStackTrace(ThreadInfo, ...)` threw a `NullPointerException`. The method now falls back to the tracked `Thread` for its name, identifier, state, and stack trace when no `ThreadInfo` is available. The new test runs a Processor on a virtual thread and reproduced that exact exception before the correction.
##########
nifi-framework-api/src/main/java/org/apache/nifi/diagnostics/ThreadDumpTask.java:
##########
@@ -16,116 +16,139 @@
*/
package org.apache.nifi.diagnostics;
+import com.sun.management.HotSpotDiagnosticMXBean;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
import java.lang.management.LockInfo;
import java.lang.management.ManagementFactory;
import java.lang.management.MonitorInfo;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
+/**
+ * Captures platform and virtual thread stack traces when supported by the Java runtime.
+ */
public class ThreadDumpTask implements DiagnosticTask {
+
+ private static final Logger logger = LoggerFactory.getLogger(ThreadDumpTask.class);
+
@Override
- public DiagnosticsDumpElement captureDump(boolean verbose) {
- final ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
-
- final ThreadInfo[] infos = mbean.dumpAllThreads(true, true);
- final long[] deadlockedThreadIds = mbean.findDeadlockedThreads();
- final long[] monitorDeadlockThreadIds = mbean.findMonitorDeadlockedThreads();
-
- final List<ThreadInfo> sortedInfos = new ArrayList<>(infos.length);
- Collections.addAll(sortedInfos, infos);
- sortedInfos.sort(new Comparator<>() {
- @Override
- public int compare(ThreadInfo o1, ThreadInfo o2) {
- return o1.getThreadName().toLowerCase().compareTo(o2.getThreadName().toLowerCase());
+ public DiagnosticsDumpElement captureDump(final boolean verbose) {
+ final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
+ final String threadDump = captureThreadDump(threadMXBean);
+
+ final StringBuilder dumpBuilder = new StringBuilder(threadDump);
+ appendDeadlockedThreadIds(dumpBuilder, "DEADLOCK DETECTED", threadMXBean.findDeadlockedThreads());
+ appendDeadlockedThreadIds(dumpBuilder, "MONITOR DEADLOCK DETECTED", threadMXBean.findMonitorDeadlockedThreads());
+
+ return new StandardDiagnosticsDumpElement("Thread Dump", Collections.singletonList(dumpBuilder.toString()));
+ }
+
+ private String captureThreadDump(final ThreadMXBean threadMXBean) {
+ try {
+ return captureHotSpotThreadDump();
+ } catch (final IOException | RuntimeException | LinkageError e) {
+ logger.warn("Failed to capture virtual threads using the HotSpot diagnostic interface; capturing platform threads instead", e);
+ return capturePlatformThreadDump(threadMXBean);
+ }
+ }
+
+ private String captureHotSpotThreadDump() throws IOException {
+ final HotSpotDiagnosticMXBean diagnosticMXBean = ManagementFactory.getPlatformMXBean(HotSpotDiagnosticMXBean.class);
+ if (diagnosticMXBean == null) {
+ throw new UnsupportedOperationException("HotSpot diagnostic interface is not available");
+ }
+
+ final Path tempDirectory = Files.createTempDirectory("nifi-thread-dump-");
+ final Path tempFile = tempDirectory.resolve("thread-dump.txt");
+ try {
Review Comment:
Agreed. The temporary directory prefix and dump filename are now derived from `ThreadDumpTask.class.getSimpleName()`, making their source clear when tracing file activity.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "exceptionfactory (via GitHub)" <gi...@apache.org>.
exceptionfactory commented on code in PR #11164:
URL: https://github.com/apache/nifi/pull/11164#discussion_r3992691671
##########
nifi-commons/nifi-properties/src/main/java/org/apache/nifi/util/ComponentSchedulingMode.java:
##########
@@ -0,0 +1,25 @@
+/*
+ * 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.util;
+
+/**
+ * Scheduling mode used for Timer-Driven and Cron-Driven components.
+ */
+public enum ComponentSchedulingMode {
Review Comment:
A new enum should not be defined, instead, string values should be used.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-4443839456
@joewitt the intent here is to introduce it with default = on. Users could explicitly opt out if they wanted to. While the code here is not particularly complex and so I don't foresee specific issues, it is a pretty crucial part of the NiFi Engine. So introducing the option in nifi.properties as an 'escape hatch' just in case any issues do arise.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5627517846
Automated review is marking this PR as stale due to lack of updates in the past four months. This PR will be closed in 15 days if the stale label is not removed. This stale label and automated closure does not indicate a judgement of the PR, just lack of reviewer bandwidth and helps us keep the PR queue more manageable. If you would like this PR re-opened you can do so and a committer can remove the stale label. Or you can open a new PR. Try to help review other PRs to increase PR review bandwidth which in turn helps yours.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5639879817
[GPT-5.6 Sol] @joewitt thanks for the detailed review. The first two findings are addressed in the latest commits:
- a87ca6d6852 clears component interrupt status at the framework boundary after each Processor or Reporting Task invocation. The new regression tests failed on the prior code exactly as described—the second invocation never occurred—and now pass.
- 300f0c68e06 adds `AUTO` as the default scheduling strategy. It resolves to `STANDARD` below Java 25 and `VIRTUAL` on Java 25 or newer; explicit `STANDARD` and `VIRTUAL` values still override it. The administration guide also warns about Java 21 monitor pinning.
Your permit-wait polling note is also accurate. Eliminating that polling requires targeted wake-up of threads waiting for permits without interrupting a Processor currently in `onTrigger`, so I am reviewing that concurrency change separately with Mark.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5640200307
1. Please keep a system-test path on standard scheduling (or AUTO on Java 21).
What I am asking: the shipped default is now AUTO, which means Java 21 still runs the existing platform-thread scheduler. But every system-test nifi.properties on this branch sets nifi.scheduling.strategy=VIRTUAL (default, pythonic, both cluster nodes). VirtualThreadStartStopCycleIT also forces VIRTUAL. So CI on Java 21 will exercise the new engine, while a real Java 21 install with an untouched config will exercise the old one. There is no system-test graph that starts, stops, clusters, or fails over on STANDARD or on AUTO as Java 21 will actually resolve it.
Why it matters: we now have two production schedulers for a while. Virtual-thread coverage on Java 21 CI is useful bake — I would keep that. What we lose is regression coverage of the path most Java 21 operators will actually run, plus the resolution of AUTO itself (unit-tested only). Start/stop, run-once, terminate, clustered primary-node, and “disable the controller service then delete it” are exactly the races that differ between a delayed-future pool and a long-lived virtual thread. If those only run under VIRTUAL, we will not notice if STANDARD was accidentally broken by the wiring change, and we will not notice if AUTO on Java 21 fails to select standard scheduling in a real process.
A small matrix is enough: leave most shards on VIRTUAL so the new engine gets the heat, and keep at least one Java 21 system-test profile on STANDARD or unset/AUTO. The AUTO resolver already has a unit test; an integration assertion that the running node logged “platform thread pool” on Java 21 and “virtual threads” on Java 25 would close the loop.
2. Please shrink the leftover FlowEngine when virtual threads are in charge of components.
What I am asking: when VIRTUAL (or AUTO on Java 25) is selected, Processors and Reporting Tasks no longer run on the timer-driven FlowEngine. That pool is still created at nifi.flowcontroller.maxTimerDrivenThreadCount, and raising max threads in the UI still calls setCorePoolSize on it and resizes the virtual-thread semaphore. The “active timer-driven thread” metric is the sum of the two.
Why it matters: today, max threads = 200 means about 200 platform threads that are the component workers. After this change, max threads = 200 means 200 semaphore permits for component work plus a 200-thread platform pool that is only used for a handful of framework periodic tasks (status history snapshot, remote process group refresh, registry sync, Python extension discovery, analytics predictions). Those jobs do not need 200 workers. Pierre raised this earlier, and the earlier branch had the leftover pool as a small framework engine. The current rewrite puts the old size back.
That has three practical effects. Operators who raise max threads to feed a large canvas also stand up a large idle platform pool they no longer need. The thread-count statistic is no longer “how many component tasks are running”; it can show framework pool activity plus permit holders, so a quiet canvas can still look busy, or a busy canvas can look busier than the cap. Shutdown waits on the platform pool first, then the virtual-thread executor, so a large leftover pool can eat the graceful-stop budget before component threads are waited on.
The max-thread property should mean one thing: how many Processor/Reporting Task invocations may run at once. Under virtual-thread scheduling that is the semaphore. The leftover FlowEngine should be a small, fixed framework pool (something like the 8 you had locally before), not resized with max threads, and the active-thread metric should not add the two budgets together as if they were the same cap.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "joewitt (via GitHub)" <gi...@apache.org>.
joewitt commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5648885075
Saved at `/tmp/NIFI-15862-1000-pair-fairness.md`. Copy below:
```markdown
# Virtual-thread scheduling: 1,000-pair fairness run
Follow-on to the earlier NIFI-15862 notes. Same branch (`nifi-15862-virtual-threads`), same machine, same “do not cheat provenance” rule. This run is about whether the **global permit cap** still gives every component a fair turn when the canvas is far larger than the cap — including mixed scheduling periods.
## Setup
- **NiFi:** 2.12.0-SNAPSHOT, `nifi.scheduling.strategy=AUTO` → virtual threads (Java 25)
- **JDK:** Azul Zulu 25, macOS, 16 cores, heap 16g
- **Repos:** `VolatileFlowFileRepository` + `VolatileProvenanceRepository` (CPU/scheduling, not disk)
- **Controller cap:** Maximum Timer Driven Thread Count = **128** (global `DynamicSemaphore` permits, not a platform pool)
- **Flow:** **1,000 independent pairs** = **2,000 processors**, **1,000 connections**
- GenerateFlowFile → UpdateAttribute
- 0-byte FlowFiles, Generate **batch 50**
- **1 concurrent task** on every processor
- UpdateAttribute `benchmark=true`, run duration 25 ms, `success` auto-terminated
- connection backpressure 15,000 / 1 GB
- layout: 5 pairs across, Generate above UpdateAttribute, same spacing as the original three pairs
Built up in stages (3 → 20 → 220 → 1,000) with the same pair shape so we could see fairness at each scale.
## Scheduling mix (all 1,000 pairs)
Generate and UpdateAttribute in a pair share the same period. Assignment is `n % 10` so cadences are interleaved across the canvas, not parked in one corner.
| Period | Pairs | Share |
|---|---|---|
| 0 sec (as fast as possible) | 100 | 10% |
| 50 ms | 100 | 10% |
| 100 ms | 100 | 10% |
| 500 ms | 100 | 10% |
| 750 ms | 100 | 10% |
| 1 sec | 500 | 50% |
**2,000** scheduled tasks vs **128** permits (~15× oversubscribed).
## Findings
### Uniform pairs (before mixing periods)
At 1+1 concurrent tasks, batch 50, all 0 sec:
| Scale | Combined Generate FF/s | Per-pair | max/min | Notes |
|---|---|---|---|---|
| 20 pairs | ~549k | ~27.2k–27.8k | 1.02 | queues often at 15k; Generate yielded; **not** permit-bound (64 cap unused) |
| 220 pairs | ~630k | 2,858–2,865 | **1.002** | cap **pegged** (~127/128); 1–20 vs 21–220 same mean |
| 1,000 pairs | ~610k | 609.3–610.5 | **1.002** | stdev **0.19 FF/s**; slowest **99.9%** of equal share |
Raising the cap **64 → 128** did **not** double throughput (still ~600k). It let more tasks sit in `onTrigger` at once. Limit is **16 cores + engine work**, not a few pairs hogging the semaphore.
30s deltas of NiFi’s 5-minute counters will go negative when that window is sliding. Compare pairs with **5-minute count / 300**, or treat a uniform delta as “everyone moved together.” Generate **out** vs UpdateAttribute **in** also looks “starved vs busy” in the UI; that is processor type, not unfairness.
### Mixed periods (1,000 pairs)
5-minute averages, ~6 minutes after applying the mix. All 2,000 processors Running. Combined **~600k FF/s**. Generate FF/s ≈ tasks/s × 50 (batch size is real).
| Period | Pairs | Expected Generate Hz | Actual Hz | Of expected | Actual FF/s / pair | Expected FF/s |
|---|---|---|---|---|---|---|
| 0 sec | 100 | max | **86.6** | — | **4,329** | — |
| 50 ms | 100 | 20 | **16.3** | **81%** | 813 | 1,000 |
| 100 ms | 100 | 10 | **9.0** | **90%** | 449 | 500 |
| 500 ms | 100 | 2 | **1.96** | **98%** | 98 | 100 |
| 750 ms | 100 | 1.33 | **1.32** | **99%** | 66 | 67 |
| 1 sec | 500 | 1 | **0.99** | **99%** | 50 | 50 |
Within every bucket, max/min ≈ **1.00**. **Zero** of 500 one-second Generates were below 0.5 Hz or above 1.5 Hz.
Interpretation:
- **Slow pairs are not starved off the board.** 1 s / 750 ms / 500 ms hit their deadlines.
- **50 ms / 100 ms miss some deadlines** because they compete with 100 always-runnable 0-sec pairs.
- Those 0-sec pairs are 10% of pairs (~10% of processors) but held **~97 of ~133** active tasks and **~72%** of FlowFiles/s (433k of 600k). That is expected: the fair permit semaphore gives turns to whoever is runnable; 0-sec is always runnable.
- UpdateAttribute **task** counts on slow pairs are **not** a schedule check. Empty queue uses **bored yield (~10 ms)**, not the 1 s period, so UA tasks include no-work polls. **FlowFiles in** still tracks Generate.
## What this says about VT readiness
1. **The scheduler scales past the cap without collapsing into winners and losers.** 2,000 looping virtual threads vs 128 permits stayed even to three decimals on FlowFiles/s.
2. **Max Timer Driven Thread Count still means something** — it is a global concurrency throttle, not “create 128 platform threads.” Oversubscribe it and combined FF/s stays in the same ~600k band; each pair just gets a thinner slice.
3. **Timer-driven periods still work** under that oversubscription. One-second components kept ~1 Hz. The miss rate on 50–100 ms is permit competition with 0-sec work, the same class of effect you would get from a small platform pool — not VT-specific unfairness.
4. **Yield / no-work is a sleep**, not cancel-and-resubmit. Mixed cadences did not require future juggling. Stop/start of 2,000 processors was routine.
5. **We did not see pinning** on this path in earlier JFR; this 1,000-pair run did not re-profile, but behavior is consistent with “park on permit, run invoke, release.”
6. Combined throughput did **not** grow with pair count (20 → 220 → 1,000). That is **cores + engine** (queues, maps, provenance), not evidence the VT agent failed. Two stacked pairs earlier **did** add; that was the VT win. This run is the fairness/oversubscription win.
## Caveats (same as before)
- One Mac, 16 cores, volatile repos, 0-byte UpdateAttribute loop.
- Not a WAL / persistent provenance / real content soak.
- Not a head-to-head TIMER_DRIVEN vs AUTO A/B at 1,000 pairs.
- Default `AUTO` remains the right upgrade default (VT on Java 25+, platform pool on 21–24). `STANDARD` stays the escape hatch.
**Bottom line:** with 1,000 pairs, mixed periods, and a 128-permit cap, virtual-thread scheduling looked **ready** for the property it was meant to have — many concurrent tasks, a simple global bound, and a fair shake for slow timers rather than a few 0-sec processors owning the engine.
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15862: Moved Processors to using Virtual Threads with a Semaphor… [nifi]
Posted by "markap14 (via GitHub)" <gi...@apache.org>.
markap14 commented on PR #11164:
URL: https://github.com/apache/nifi/pull/11164#issuecomment-5721915784
[gpt-sol-5.6] The [Ubuntu Java 25 system-test job](https://github.com/apache/nifi/actions/runs/35271697279/job/105372395322) hit a pre-existing `OffloadIT.testOffload` failure. The same test timed out on `main` yesterday in [run 35155156816](https://github.com/apache/nifi/actions/runs/35155156816). The failure reported:
```
java.util.concurrent.TimeoutException: testOffload() timed out after 10 minutes
at org.apache.nifi.tests.system.NiFiSystemIT.waitForNodeStatus(NiFiSystemIT.java:472)
at org.apache.nifi.tests.system.clustering.OffloadIT.testIteration(OffloadIT.java:87)
```
The troubleshooting logs show the Processors stopped successfully in 111 ms. During the offload, cluster coordinator leadership moved from node 2 to node 1; node 2 completed its local offload but could not change its local coordinator state from `DISCONNECTED` to `OFFLOADED`. This is unrelated to the scheduling-generation check in the latest commit. I will rerun the failed job after the remaining jobs in this workflow finish.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org