Repository navigation
NIFI-16477: Implement Flow Evolution Drain Hooks and Flow persistence - #11872
Conversation
cb1a61a to
d1072b0
Compare
| public static final String CONNECTOR_REPOSITORY_IMPLEMENTATION = "nifi.connector.repository.implementation"; | ||
| public static final String CONNECTOR_SYNC_TIMEOUT = "nifi.connector.sync.timeout"; | ||
| public static final String DEFAULT_CONNECTOR_SYNC_TIMEOUT = "5 mins"; | ||
| public static final String CONNECTOR_FLOW_EVOLUTION_TIMEOUT = "nifi.components.connectors.flow.evolution.timeout"; |
There was a problem hiding this comment.
Should this property use the existing nifi.connector. prefix (for example nifi.connector.flow.evolution.timeout), to match nifi.connector.sync.timeout just above? Can we also add it to the Administration Guide?
There was a problem hiding this comment.
Agreed will fix. Also will add some information about evolution to the developer guide
| * @throws NullPointerException if the persistence context is null | ||
| */ | ||
| Future<Void> startConnector(ConnectorNode connector); | ||
| Future<Void> startConnector(ConnectorNode connector, ConnectorUpdateContext persistenceContext); |
There was a problem hiding this comment.
Since the repository implementation is configurable, should we keep the old startConnector(ConnectorNode) as a default method (or give getFlowEvolutionStatus a default) so custom implementations do not break?
There was a problem hiding this comment.
The feedback here is clear but I think keeping the old startConnector may imply that flow evolution logic is optional. Removing the ConnectorUpdateContext means we won't be able to save the flow following the successful start unless we introduce the ConnectorUpdateContext to the ConnectorRepository through another way. I did explore this a bit while creating the PR and it is possible to pass the ability to persist at construction. For example I could
[Opus 5.5]
FlowController now has a late-bound setFlowService (line 2530) and saveFlowAfterConnectorEvolution (line 2547). That means the initialization context could now carry this::saveFlowAfterConnectorEvolution, which looks up the flow service only when a save happens. So "during construction" would now work, with no setter and no cast.
Suggests the following pros/cons
Pros
- startConnector(ConnectorNode) goes back to main's signature, so custom repositories and their callers compile unchanged.
- The ConnectorDAO and StandardNiFiServiceFacade changes go away, along with the ConnectorAuditor pointcut change.
- It also removes markap14's minor comment about two save paths (r4473343087). Every evolution save would go through flowService.saveFlowChanges() instead of a mix of that and controllerFacade::saveImmediate.
- No mutable field and no instanceof: the save function is fixed when the repository is initialized, like the timeout.
Cons
- It adds a method to ConnectorRepositoryInitializationContext. That is another public interface change, though it can have a default.
- The repository decides how to save, not the caller. Today a start from the web layer saves immediately with saveImmediate. A built-in save function would always use the flow service's path, so one action could follow two different save rules.
- applyUpdate would still take a context as an argument while startConnector would not, which brings back the inconsistency the thread_flow_persistence_context plan removed.
- A save failure becomes harder to trace. With a parameter, the save that fails is the one the caller passed in. 5. With a built-in function, a save that failed because the flow service isn't set yet shows up as an IllegalStateException deep in the coordinator.
- Churn: the three save calls, the DAO, the facade, the auditor, and TestStandardConnectorRepository all change again, after the last change reached a stable state.
I am open to making this change but I think we should agree on whether evolution should be an optional implementation in the repository. I think it should be requried.
There was a problem hiding this comment.
All things considered, I agree that evolution should be required, so a default that skips it would be wrong. Let's just make sure we mention the breaking change in the migration guidance in case someone has a custom implementation of the connector repo.
There was a problem hiding this comment.
I was looking for the right place to mention the breaking change. We have guidance on upgrading from 1.x to 2.x in the admin guide, however this would be an inter 2.x upgrade. Does simply belong release notes type or a more long lived document on the site?
There was a problem hiding this comment.
We'll add an entry in https://cwiki.apache.org/confluence/spaces/NIFI/pages/57905503/Migration+Guidance
There was a problem hiding this comment.
ConnectorRepository is in framework-core-api. It's not really intended to be extended. Rather, the recommended extension point is the ConnectorConfigurationProvider, which is part of framework-api. nifi-framework-core-api is intended to be an internal API module.
| } | ||
| } | ||
|
|
||
| private void waitForFlowEvolutionStatus(final ConnectorNode connector, final FlowEvolutionStatus desiredStatus) |
There was a problem hiding this comment.
Should this wait have an overall timeout, so the coordinator does not loop forever when a node stays in CONNECTING?
There was a problem hiding this comment.
yes this make sense.
| public synchronized CompletableFuture<Void> startProcessor(final ProcessorNode procNode, final boolean failIfStopping) { | ||
| final LifecycleState lifecycleState = getLifecycleState(requireNonNull(procNode), true, false); | ||
| requireNonNull(procNode); | ||
| final CompletableFuture<Void> pendingStart = processorStartFutures.get(procNode.getIdentifier()); |
There was a problem hiding this comment.
This early return applies to all processors, not only Connector ones. Can we add a unit test for the pending-start and already-running cases?
There was a problem hiding this comment.
Good call out. I do have another PR that is fixing a separate issue that should add them. I can address this following the update in #11886
There was a problem hiding this comment.
Ended up removing this change while simplifying things following the drain. This should no longer be needed.
markap14
left a comment
There was a problem hiding this comment.
[Claude Opus 5.5] Thanks for working on this. I reviewed it with a focus on correctness, simplification and tests. Details are in the inline comments; this is the summary.
Critical (both found by reading the code at d1072b0695; I have not run them)
- Sensitive parameter values that are not exactly one configured secret are cleared on every normal restart. This affects connectors that are never upgraded. See the comment on
restorePersistedManagedFlow. - Synchronizing a running connector again (for example, when a node rejoins the cluster) stops its processors and never restarts them, while the connector still reports RUNNING. See the comment on
syncConnector.
Important
- The waits between nodes have no time limit and log only at debug level, so a connector can stay in DRAINING forever (
waitForFlowEvolutionStatus). - After a partial phase-two failure, nodes save different flows and nothing brings them back together.
- The
StandardProcessScheduler.startProcessorchange has no test or explanation. - A failed attempt can report STOPPED while processors the hook started are still running.
- Two checks depend on matching strings (an exception class name and the start of a reason message).
- The
StandardProcessGroupmapping options changed in a way that affects the troubleshooting restore, and they copyforPersistedFlow.
Simplification
The biggest opportunity is to reuse the existing update wait (PREPARING_FOR_UPDATE, then UPDATING, then UPDATED, through waitForState) instead of adding FlowEvolutionStatus as a second one. After that:
- Hold one immutable "attempt" object instead of about nine fields.
- Give the evolution steps their own explicit methods instead of hidden modes inside
applyUpdate,startandabortUpdate. - Merge the three restore methods into one decision made in
syncConnector.
Tests
- The PR adds about 30 unit tests and 13 system tests. Several cover the same behavior, and some check internal details such as which overload was called or how many times
abortUpdateran. Specific tests to merge or drop are in the inline comments. - The four new
StandardVersionedComponentSynchronizerTesttests share their setup and could be one test. The same goes for the two newStandardNiFiServiceFacadeTesttests. - Missing coverage:
- sensitive parameters after a same-bundle restart,
- processor states after a running connector is synchronized again (strengthen
ClusteredConnectorIT.testRunningConnectorSyncedOnReconnect), startProcessor,- a partial phase-two failure across nodes,
- the troubleshooting restore with the new mapping options.
- Some system tests run well over a minute, largely because the change-version tests inherit a base class that starts a fresh NiFi for every test.
CI
The Windows failure is a network error while downloading questdb. The macOS and Ubuntu system-test failures are only in ClusterStateKeyDropIT.testCanDropSpecificStateKey, which also fails on main. Neither is related to this PR, and all of the new system tests passed.
| if (sameManagedBundle(managedFlowBundle) && persistedManagedGroup != null) { | ||
| // The bundles match, so this is a restart rather than an upgrade. inheritConfiguration has already | ||
| // replaced the group; install the persisted one so connection identifiers still match the flow file. | ||
| restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, true); | ||
| adoptAuthoritativeSnapshot(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, managedFlowBundle); | ||
| return; |
There was a problem hiding this comment.
[Claude Opus 5.5] Critical: sensitive parameter values are cleared on every normal restart.
On a restart where the bundle hasn't changed, inheritConfiguration has already built the flow with the correct parameter values. This then restores the persisted flow on top of it. Sensitive values were stripped before saving, and ParameterSecretReferences.resolve puts a value back only when matchSensitiveParametersToSecretReferences tied it to exactly one secret. Every other sensitive value comes back as null, and finishRestorePersistedFlow pushes those nulls into the live parameter context, overwriting the good values.
Values that are affected:
- a sensitive value entered as a plain string,
- a value the connector builds from a secret (for example, a connection string that contains a password),
- a value that happens to equal two different secrets.
Processors that use those parameters become invalid after every restart, even for connectors that are never upgraded. When the bundle is unchanged, I think this path should keep the values from inheritConfiguration and take only the component identifiers from the persisted flow. I found this by reading the code and have not run it, so please correct me if I missed a step that puts these values back.
There was a problem hiding this comment.
Fixed in the latest push. On a normal restart the persisted flow is no longer restored over inheritConfiguration, so its parameter values are kept. The persisted flow is now restored only for ghost connectors and for upgrades interrupted by a restart. Those paths could still lose the values you listed, so sensitive values are now saved encrypted (enc{…}, same as regular parameter contexts) rather than stripped. On restore, secret-tied parameters take the secret's current value and the rest are decrypted. A missing secret or a decryption failure leaves components stopped.
|
|
||
| if (parameterContext != null && parameterContext.getParameters() != null) { | ||
| final ConnectorParameterLookup parameterLookup = new ConnectorParameterLookup(externalFlow.getParameterContexts().values(), assetManager); | ||
| getParameterContext().updateParameters(parameterLookup.getParameterValues()); |
There was a problem hiding this comment.
[Claude Opus 5.5] This passes every parameter value from the restored context, including the null sensitive values, to updateParameters. See my comment on StandardConnectorNode.restorePersistedManagedFlow for why that clears sensitive values on restart.
There was a problem hiding this comment.
[Claude Opus 5.5] Addressed along with the restorePersistedManagedFlow comment. This call no longer runs on a normal restart. On the ghost and interrupted-upgrade paths, sensitive values are now saved encrypted and restored with real values. A null reaches updateParameters only when a bound secret can't be resolved or a persisted value can't be decrypted. Both cases are logged and leave components stopped.
|
|
||
| assertEquals("current", getParameter(resolution.parameterContext(), "Resolved").getValue()); | ||
| assertNull(getParameter(resolution.parameterContext(), "Missing").getValue()); | ||
| assertNull(getParameter(resolution.parameterContext(), "Generated").getValue()); |
There was a problem hiding this comment.
[Claude Opus 5.5] This asserts that a sensitive value with no matching secret comes back as null. During a same-bundle restart, that null overwrites the real value (see my comment on restorePersistedManagedFlow). I would update this test to match the intended contract rather than lock in the current behavior.
There was a problem hiding this comment.
[Claude Opus 5.5] Updated. The strip test is removed, and the resolve test now checks that a sensitive value with no matching secret is saved encrypted and restored as its original value. A null is expected only when a bound secret can't be resolved or a value can't be decrypted. Both cases are reported and leave components stopped.
| return ConnectorSyncResult.failed(connector); | ||
| } | ||
| } else { | ||
| connector.restorePersistedManagedFlow(versionedConnector); |
There was a problem hiding this comment.
[Claude Opus 5.5] Critical: synchronizing a running connector again stops its processors and never restarts them.
This runs on every sync, including when the connector is RUNNING, for example when a node rejoins the cluster. The snapshot being restored was captured in applyUpdate, after the connector had been stopped, so it records every processor as stopped. The synchronizer treats the scheduled-state difference as an update. It stops the running processors and restarts a processor only if the restored state is RUNNING, which it is not here. The startConnector call that follows does nothing, because start returns early when the connector is already RUNNING. The connector then reports RUNNING while its processors are stopped.
The existing ClusteredConnectorIT.testRunningConnectorSyncedOnReconnect misses this because it checks only the connector state. Strengthening it to also check that the processors are running should show the problem. As above, I found this by reading the code and have not run it.
There was a problem hiding this comment.
Will verify this with a System Test. Agree this should be fixed if verified.
There was a problem hiding this comment.
[Claude Opus 5.5] Fixed. Outside of Troubleshooting, the sync no longer restores the persisted flow for a Connector whose extension is present, so a rejoining node leaves the running processors alone. ClusteredConnectorIT.testRunningConnectorSyncedOnReconnect now also waits for the managed GenerateFlowFile processor to be RUNNING on the rejoined node, not just the Connector state.
| activeFlowContext.getConfigurationContext().replaceConfiguration(inheritedConfiguration); | ||
|
|
||
| getComponentLog().info("Working Context has been applied to Active Context"); | ||
| captureAuthoritativeSnapshot(); |
There was a problem hiding this comment.
[Claude Opus 5.5] The snapshot is captured here, after prepareForUpdate has stopped the connector, so every processor in it is recorded as stopped. That is what lets the restore in StandardConnectorRepository.syncConnector stop the processors of a running connector (see my comment there).
There was a problem hiding this comment.
[Claude Opus 5.5] Addressed by the fix on the syncConnector comment. The snapshot is still captured after the connector stops, but it's no longer restored onto a running connector. It's restored only for a ghost connector, which stays stopped, or for a pending evolution at startup, before the connector starts. In that case the evolution starts the processors after applying the upgraded flow, so the stopped state recorded in the snapshot isn't what decides whether they run.
| restartKeepingIncomingVersion(); | ||
| requestStart(secretConnector.connectorId()); | ||
| getClientUtil().waitForConnectorState(secretConnector.connectorId(), ConnectorState.RUNNING); | ||
| assertNotPending(secretConnector.connectorId()); |
There was a problem hiding this comment.
[Claude Opus 5.5] The test name says the rotated secret is used, but it checks only that the connector is RUNNING and not pending. It never checks that the rotated value is in use. This is also a good place to cover the restart problem with sensitive values: have the connector build a second sensitive parameter from the secret, restart without changing the version, and check that the processor using it is still valid.
There was a problem hiding this comment.
[Claude Opus 5.5] Renamed to testPreUpgradeParameterSecretIsRefreshedAndCanBeRestored. It now also checks that the secret is persisted as a reference rather than a value, and that the upgrade completes after the secret is rotated, and it now also asserts that the rotated value is what the flow uses. The restart case for sensitive values is covered by ConnectorParameterContextIT, which restarts without changing the version and checks that the processors still write the sensitive and asset values.
|
|
||
| @Test | ||
| @Timeout(240) | ||
| public void testRunningConnectorAutoResumes() throws Exception { |
There was a problem hiding this comment.
[Claude Opus 5.5] This test takes about 100 seconds, which is over our one-minute limit for system tests. Most of the change-version drain tests take 30 to 50 seconds each.
There was a problem hiding this comment.
[Claude Opus 5.5] Fixed. NAR-swap tests that discard their environment after each test no longer restart NiFi just to put the NARs back. ClusteredConnectorUpgradeDrainIT now runs in about 58 seconds locally, down from about 78.
| /** | ||
| * Version-change test support. | ||
| */ | ||
| public abstract class AbstractChangeVersionDrainIT extends AbstractConnectorUpgradeDrainIT { |
There was a problem hiding this comment.
[Claude Opus 5.5] The change-version drain tests inherit from the NAR-swap base, which turns off instance reuse. So every test starts a fresh NiFi, which is likely why they are slow. The change-version tests don't swap NARs on disk, so they may not need that base class at all.
There was a problem hiding this comment.
[Claude Opus 5.5] Good catch. The change-version drain tests don't swap NARs, so they now reuse the instance: isAllowFactoryReuse returns true and isDestroyEnvironmentAfterEachTest returns false. The 13 standalone tests now take about 2.5 minutes in total.
| return getNumberOfNodes() <= 1 ? getNiFiInstance() : getNiFiInstance().getNodeInstance(1); | ||
| } | ||
|
|
||
| protected List<File> nodeDirectories() { |
There was a problem hiding this comment.
[Claude Opus 5.5] Several helpers here copy existing ones:
nodeDirectoriescopiesAbstractNarSwapMigrationIT.instanceDirectories.deleteGatescopiesdeleteNodeFiles(GATE_FILE), andcreateGatecopieswriteNodeFile.actionReasonis defined here and inConnectorChangeVersionIT.
Also, waitUntilDraining polls by hand instead of using the shared waitFor helper.
There was a problem hiding this comment.
[Claude Opus 5.5] nodeDirectories is gone in favor of the shared instanceDirectories, and the gate handling is down to one write helper and one delete helper. actionReason now lives once in NiFiClientUtil.getConnectorActionReasonNotAllowed, used by both the drain ITs and ConnectorChangeVersionIT. waitUntilDraining still polls by hand on purpose: it fails as soon as the connector reaches RUNNING, STOPPED or UPDATE_FAILED, while waitFor ignores exceptions and would wait out the full timeout instead.
| } | ||
| } | ||
|
|
||
| private void waitForNodeConnectorState(final int nodeIndex, final String connectorId, final ConnectorState expectedState) throws InterruptedException { |
There was a problem hiding this comment.
[Claude Opus 5.5] Many helpers in this class repeat the same "switch the client to a node, try, finally reset the client" wrapper. One helper that takes a node index and a lambda would replace them. The class also redefines the bundle-mismatch reason string instead of sharing it.
There was a problem hiding this comment.
[Claude Opus 5.5] Done. Per-node calls now go through a single onNode(nodeIndex, call) helper, plus waitForNode for polling, so the switch and reset happen in one place. The class no longer redefines the bundle-mismatch reason; it lives only in ConnectorEntityMerger, and ConnectorEntityMergerTest checks it there.
d1072b0 to
563792b
Compare
8398d81 to
442d9ab
Compare
0176c3d to
5f083ec
Compare
* Implement hooks to allow the Connector to drain the flow when its loaded version changes * When the Connector version differs from the version that built the authoritative flow load the persisted flow from the managedProcessGroup.
5f083ec to
53ffb1d
Compare
markap14
left a comment
There was a problem hiding this comment.
[Claude Opus 5.5] Thanks for the update, Bob. Both critical problems from the last review are fixed, and most of the other comments were handled well. The latest push also fixes the cancel/stop race and the flaky testAbortUpdateInterruptsBlockedFlowEvolutionHook.
This pass focused on failure paths and state changes: Connectors that throw, drains that never finish, and requests that arrive at awkward moments. Startup never waits on the hook. A RuntimeException from the hook, getActiveFlow, prepareForUpdate, or applyUpdate always ends in a defined state. And I found nothing that needs a NiFi restart to recover. But I did find the following, roughly in priority order (details inline):
Must fix
- If restoring the pre-upgrade flow fails at startup (for example, the secrets provider can't be reached), the next flow save erases the Connector's managed flow and its active and working configuration from
flow.json. - Stop futures can be left incomplete, for example by a STOP that arrives while the upgraded flow is being applied. Anything that waits on a stop then blocks forever, and orphan Connector removal during a node's reconnect already does that.
- START on a pending Connector that is STOPPING, PURGING, or running a user-requested drain passes verification and then fails silently. In a cluster, the other nodes then wait forever for this node.
StandardConnectorNode.start()has no pending-upgrade check, andrestartConnector(used by the asset synchronizer) calls it directly. That can run the new Connector code on the pre-upgrade flow.- The new system tests restart NiFi about 18 times. Most of those restarts happen only to read
flow.json.gzat the end of a test. The suite's run time matters to everyone, so this needs to come down to about two tests that restart NiFi: one test that checks what survives a restart, and the clustered NAR-swap startup test.
Should fix
6. waitForFlowEvolutionStatus still has no time limit.
7. Whether a Connector resumes its upgrade after a restart depends on whether some unrelated save happened during the drain.
8. The new source-change check in StandardVersionedComponentSynchronizer lost all its unit tests.
Suggestions
- Moving the flow evolution code out of
StandardConnectorNodeinto its own class. - Two minor items: the
instanceof StandardConnectorNodecast in the repository, andConnectorClusterUnavailableExceptionextendingRuntimeException.
Answers to your questions
- Save paths: both end up in
saveFlowChanges(), so leaving them as they are is fine with me. StandardProcessGroupmapping options: your reasoning holds. The only callers are the Connector restore paths, and both sides of the comparison now use the same options that write the persisted flow. The added mapper test only checks that one option is set, though. A restore round trip would be more useful: restore a flow with a controller service reference and an asset parameter, then check that nothing changed.ConnectorStatevsFlowEvolutionStatus, and retrying forward after a partial apply: both are reasonable as implemented.
| /** | ||
| * The node has drained the outgoing flow and has not yet applied the upgraded flow. | ||
| */ | ||
| EVOLVE_DRAIN_COMPLETE, |
There was a problem hiding this comment.
I presume the intent is for the lifecycle to go from EVOLVE_DRAIN_PENDING -> EVOLVE_DRAIN_COMPLETE -> INACTIVE ? It's not really clear. From the comments here and looking at the enum it seems like EVOLVE_DRAIN_COMPLETE should be followed by EVOLUTION_COMPLETE or something but there is no such thing. Can we clarify the expected lifecycle in the javadocs?
There was a problem hiding this comment.
[Claude Opus 5.5] Clarified the class Javadoc. A node reports INACTIVE until an upgrade is pending, then EVOLVE_DRAIN_PENDING, even before the first START. When its local drain finishes it reports EVOLVE_DRAIN_COMPLETE, and keeps reporting it while the upgraded flow is applied. Once the new snapshot is captured it goes back to INACTIVE. There's no separate "complete" value, because INACTIVE already means nothing is pending. FAILED is now documented too: it's reported instead of the drain status until the next START prepares a new attempt.
| * Restores a previously persisted flow while controlling whether components resume their captured scheduled state. | ||
| * When {@code resumeComponentState} is false, the flow structure is restored so queued FlowFiles can reattach, but | ||
| * no component is started or enabled. | ||
| * | ||
| * @param proposedSnapshot the proposed flow whose Instance Identifiers should be used as runtime identifiers | ||
| * @param resumeComponentState whether components should resume the running or enabled state captured in the snapshot | ||
| */ | ||
| void restoreFlowPreservingIdentifiers(VersionedExternalFlow proposedSnapshot, boolean resumeComponentState); |
There was a problem hiding this comment.
This is confusing to me. The method is named as if it will restore the flow without change IDs (which would be presumed). But the javadocs makes it sound like the intent is to restore the flow while optionally resuming the components' states. I guess this is intended just as an override to the restoreFlowPreservingIdentifiers method that takes just the VersionedExternalFlow argument, but it's confusing here, given the name and the JavaDocs. I also wonder if we need the override, rather than just adding an argument to the existing method.
It's also worth noting that we tend to prefer enums on public methods and especially interfaces, rather than booleans.
My recommendation, I think, would be to just add a new enum argument to the existing method and eliminate this one. Something like:
void restoreFlowPreservingIdentifiers(VerisonedExternalFlow proposedSnapshot, ResumeComponentState resumeStates)
Where ResumeComponentState has two values, RESUME_STATES, LEAVE_STOPPED or RESUME_STATES, LEAVE_UNCHANGED or whatever. This helps to make it very clear when passing the argument exactly what your intent is.
There was a problem hiding this comment.
[Claude Opus 5.5] Agreed. There's now a single restoreFlowPreservingIdentifiers(VersionedExternalFlow, ResumeComponentState), and the overload is gone. The new ResumeComponentState enum has two values, RESUME_AS_PERSISTED and LEAVE_STOPPED. I made the same change to FrameworkFlowContext.restorePersistedFlow. RESUME_AS_PERSISTED still honors nifi.flowcontroller.autoResumeState, as the single-argument method did.
| return stopCompleteFuture; | ||
| } | ||
|
|
||
| private boolean prepareFlowEvolutionStop(final CompletableFuture<Void> stopCompleteFuture) { |
There was a problem hiding this comment.
This method is confusing. It's a prepare method. But it's unclear what the return value is really telling us. And I would not expect a method named prepareFlowEvolutionStop to then call abortFlowEvolution - i would expect it only to do prep work
There was a problem hiding this comment.
[Claude Opus 5.5] Agreed, I removed it. stop() now checks inline whether an evolution is in progress and aborts it if so, the same way cancelDrainFlowFiles does. testStopCancelsFlowEvolutionInProgress covers it.
| activeFlowContext.restorePersistedFlow(flow, resolution.parameterContext()); | ||
| } else { | ||
| activeFlowContext.restorePersistedFlow(flow, resolution.parameterContext(), false); |
There was a problem hiding this comment.
This feels weird to call the same method but in one place rely on 'default values' while in the other passing them explicitly. Probably makes sense to extract the resumeComponents && unresolvedParameterSecretReferences.isEmpty() && resolution.undecryptableParameters().isEmpty() into a boolean and just pass that as the last argument, no?
There was a problem hiding this comment.
[Claude Opus 5.5] Agreed, it's now one call with the resume state worked out up front: LEAVE_STOPPED when a secret is unresolved or a value can't be decrypted, otherwise the requested state. Passing a plain true would have bypassed autoResumeState, and the enum avoids that.
| if (!extensionMissing && !sameManagedBundle(managedFlowBundle) && persistedManagedGroup != null) { | ||
| // Skip inheritConfiguration. Its applyUpdate would replace the pre-upgrade group with the new bundle's | ||
| // flow. The restored group keeps the previous bundle, so the next start evolves it. | ||
| restorePersistedFlow(persistedManagedGroup, persisted.getManagedParameterContext(), parameterSecretReferences, true); |
There was a problem hiding this comment.
[Claude Opus 5.5] A failure here can permanently lose the pre-upgrade flow and the Connector's configuration. Here's how:
- At startup,
restorePersistedFlowresolves secrets before it touches the flow. If the secrets provider can't be reached, the parameter provider throws anIllegalStateException(StandardParameterProviderNode#L295), and nothing catches it beforesyncConnector. - Because the restore comes first,
loadConfigurationsWithoutRebuildingFlowandadoptAuthoritativeSnapshotnever run. The Connector holds no snapshot and no configuration, so it isn't even treated as pending. syncConnectorcallsmarkInvalid, but the next validation clears that.- On the next flow save, from any change anywhere,
mapConnectorwrites no managed group, parameter context, or managed-flow bundle, because there's no snapshot (#L1151). It also writes empty active and working configurations, taken from the live Connector (#L1132, #L1138). - After that, a restart with the vault back up finds nothing to restore. The queued FlowFiles stay in the repository as orphans with no connection to rejoin.
The extension-missing path in restorePersistedManagedFlow already handles this case (#L1866-L1873). I'd do the same here:
- Load the configurations before restoring the flow. Loading doesn't depend on the managed flow, and doing it first means the snapshot below records the real active configuration, since
adoptAuthoritativeSnapshotcopies it from the live Connector (#L1966). - Catch a failed restore and call
markManagedFlowRestoreFailed().verifyCanStartand the START action already block on that, with a message telling the user to restart. - Record the persisted snapshot anyway, and return
trueso thatsyncConnectordoesn't rebuild the flow from the new bundle.
It's also worth considering whether an unreachable secrets provider should count as an unresolved secret. The code already handles that case by leaving components stopped.
For a test, an existing restore test in TestStandardConnectorNode could add a secrets manager that throws. It should check that START is refused and that the mapped Connector still has its managed group and active configuration.
There was a problem hiding this comment.
[Claude Opus 5.5] Agreed, thanks for walking through it.
I kept the restore before loading the configuration, because loading builds the working context by copying the active group, and that group has to be restored first. Instead the failure is now handled in two ways:
Unreachable secrets provider: this now counts as unresolved secrets. The flow is restored with components stopped, so the queues reattach.
Any other restore failure: it's caught and marks the restore as failed, which blocks START.
In both cases the configuration is still loaded and the persisted snapshot is adopted, so the next flow save keeps the managed group and the active and working configurations. Tests: testRestorePersistedFlowKeepsComponentsStoppedWhenSecretUnavailable and testRestorePendingFlowEvolutionAdoptsSnapshotWhenRestoreFails.
| * One attempt at a pending flow evolution. The futures are each set at most once per attempt, and are read and written | ||
| * only while holding the evolution lock, so closing the attempt cancels this attempt's work and never a newer attempt's. | ||
| */ | ||
| private static final class FlowEvolutionAttempt { |
There was a problem hiding this comment.
[Claude Opus 5.5] Not a blocker, but worth considering: this PR adds a little over 900 lines to StandardConnectorNode, which is now about 4,000 lines. Most of the new code is flow evolution:
- this class and
FlowEvolutionProgress; flowEvolutionLock;- the prepare, evolve-drain, begin-update, fail, and retry-stop methods;
- the snapshot handling.
Pulling that into its own class, owned by the node and called by it, would put all of the evolution state in one place. That would make it much easier to see which thread changes what, and to unit test the evolution states directly. The node would keep its lifecycle methods and delegate the evolution parts.
Curious whether you think that's worthwhile.
There was a problem hiding this comment.
[Claude Opus 5.5] I think it's worthwhile, so it's in this PR. The flow-evolution code now lives in a package-private ConnectorFlowEvolution owned by the node. That includes the lock, the progress and attempt state, the authoritative snapshot, and the prepare, evolve-drain, begin-update, fail and retry-stop steps. The node keeps its lifecycle methods and delegates to it, which takes about 700 lines out of StandardConnectorNode. The evolution tests stay in TestStandardConnectorNode and run through the node's public behavior, for example testFlowEvolutionLifecycle and testFlowEvolutionAfterFailedApplyResumesAfterHook. That way they don't depend on the new class's internals.
| } | ||
| } | ||
|
|
||
| protected void stopAndAssertNotPending(final String connectorId) throws IOException { |
There was a problem hiding this comment.
[Claude Opus 5.5] The new system tests restart NiFi far too often, and this helper is the biggest reason. It stops NiFi only so the test can read flow.json.gz. In the classes that share one NiFi instance between tests (ConnectorChangeVersionDrainIT and ClusteredConnectorChangeVersionDrainIT), the @AfterEach in AbstractNarSwapMigrationIT then sees that NiFi is not running and starts it again. So every test that ends this way pays for a full restart, even though it never checks anything across a restart.
Here is the count across the PR:
ConnectorChangeVersionDrainIT: 11 of its 13 tests restart NiFi, for 14 restarts in total.ClusteredConnectorChangeVersionDrainIT: 1 restart of the 2-node cluster, through this helper.ClusteredConnectorUpgradeDrainITandConnectorUpgradeDrainProviderIT: each builds a brand-new environment and then restarts it once for the NAR swap.ConnectorParameterContextIT: 1 added restart.
About 10 of those restarts happen only to read the flow file at the end of a test. The flow is saved shortly after each change, and assertPersistedOutgoing already reads the file while NiFi is running. Can this helper, and the getNiFiInstance().stop() calls followed by FlowDefinitionFiles.readConnector at the end of tests in ConnectorChangeVersionDrainIT, read the file with NiFi still running? Re-reading it inside a waitFor until it shows the expected bundle would handle the short delay before the save. Where the REST API already shows the same thing (for example, a flow evolution status of INACTIVE), checking through REST is simpler still.
Overall, I'd like the new tests to get down to two that restart NiFi: one test that checks what survives a restart (see my comment in ConnectorChangeVersionDrainIT), and the clustered NAR-swap startup test in ClusteredConnectorUpgradeDrainIT.
There was a problem hiding this comment.
[Claude Opus 5.5] Done. I removed the stop-and-read helper. The tests now re-read flow.json.gz inside waitFor, with NiFi still running, until it shows the expected bundle, or they check through REST. The stop-then-read calls at the end of the ConnectorChangeVersionDrainIT tests are gone too.
Two tests restart NiFi now: ConnectorChangeVersionDrainIT.testRestartKeepsPendingUpgrades and the clustered NAR-swap test in ClusteredConnectorUpgradeDrainIT.
| changeVersion(secretConnector.connectorId(), DRAIN_V2); | ||
| getClientUtil().updateParameterProviderProperties(secretConnector.parameterProvider(), Map.of("parameters", SECRET_NAME + "=rotated-secret")); | ||
|
|
||
| getNiFiInstance().stop(); |
There was a problem hiding this comment.
[Claude Opus 5.5] Only four tests in this class actually check behavior across a restart:
testPreUpgradeParameterSecretIsRefreshedAndCanBeRestoredtestPendingUpgradeEditsThenStartsWithoutReEvolving, which restarts twicetestRestartDuringDrainingComesBackPendingtestPendingUpgradeBlocksEndingTroubleshootingWithQueuedFlowFiles
Could these become one test with a single restart? Before restarting, set up one connector per scenario:
- one with a pending upgrade, working-configuration edits and a secret;
- one in troubleshooting with an upgrade pending;
- one draining, with its own
Gate File Pathso it can be held and released separately from the others.
Then restart once and check each connector. The second restart in testPendingUpgradeEditsThenStartsWithoutReEvolving checks the saved flow after the upgrade finishes. It can become a read of the flow file with NiFi still running.
Together with the change I suggested for stopAndAssertNotPending, this takes the class from 14 restarts to 1.
There was a problem hiding this comment.
[Claude Opus 5.5] Merged the four tests into testRestartKeepsPendingUpgrades, which sets up three Connectors and restarts once:
a pending Connector with working-configuration edits and a secret;
a Connector in Troubleshooting with an upgrade pending;
a draining Connector with its own Gate File Path.
The second restart that checked the saved flow is now a read while NiFi is running. The class restarts NiFi once.
| initial.put(LEGACY_NOTE, "v1-only"); | ||
| final String connectorId = createConnector("UpgradeDrainConnector", initial); | ||
|
|
||
| getNiFiInstance().stop(); |
There was a problem hiding this comment.
[Claude Opus 5.5] This test needs its own environment because of the provider properties, and the NAR swap adds a restart on top of that. Is the NAR swap important to what this test checks? If the provider-supplied configuration gets applied the same way when the version is changed through the REST API (as in AbstractChangeVersionDrainIT), this test could use a version change and skip the restart. If the NAR-swap startup path is the point of the test, could it be folded into ClusteredConnectorUpgradeDrainIT instead, so that we have one NAR-swap restart test instead of two?
There was a problem hiding this comment.
[Claude Opus 5.5] The NAR-swap startup path is what this test checks: it's where the provider's working configuration gets merged into the pending restore, and a version change through REST takes a different path. So I folded it into ClusteredConnectorUpgradeDrainIT and deleted ConnectorUpgradeDrainProviderIT. The combined test, testNarSwapResumesRunningConnectorAndAppliesProviderConfiguration, uses one environment and one restart with two Connectors. One is stopped and has a working configuration edited in the provider. The other is running and resumes its upgrade.
| assertEquals(ASSET_FILE_CONTENT, assetContent, "Asset output file should contain the asset file contents"); | ||
|
|
||
| // A same-bundle restart resumes the Connector with its sensitive and asset parameters still resolved | ||
| getNiFiInstance().stop(); |
There was a problem hiding this comment.
[Claude Opus 5.5] This restart adds time to the suite but doesn't protect against the earlier bug where a normal restart restored the saved flow over the newly built one. The sensitive value here comes straight from the secret, so the saved flow and the newly built flow are the same, and the test would pass with or without that bug. I'd either drop this restart and cover that case with a unit test in TestStandardConnectorRepository, or use a value that the connector derives from the secret so that the restart actually checks something.
There was a problem hiding this comment.
[Claude Opus 5.5] Agreed, I removed the restart. The same-bundle restart case is now a unit test in TestStandardConnectorRepository, testSameBundleSyncRebuildsFlowWithSecretDerivedParameter. It uses a sensitive parameter derived from a secret and checks that a same-bundle sync keeps the rebuilt flow rather than restoring the persisted group over it.
- Keep the managed flow and configurations in flow.json when restoring the pre-upgrade flow fails at startup; an unreachable Secrets Provider counts as unresolved secrets and leaves components stopped - Complete pending stop futures exceptionally when the Connector moves to a state other than STOPPING or STOPPED - Reject START of a pending Connector that is STOPPING, PURGING or in a user-requested drain, and refuse direct start() while an upgrade is pending - Always save RUNNING when an evolution begins so a restart during the drain resumes the upgrade - Replace restore overloads and booleans with ResumeComponentState - Restore with FlowMappingOptions.forPersistedFlow, matching capture - Move flow evolution state and steps into ConnectorFlowEvolution - Make ConnectorClusterUnavailableException an IOException, move the pre-upgrade stop retry into the node, and document FlowEvolutionStatus - Add isSourceChanged helper and restore its synchronizer test - Add unit tests and a capture/restore round-trip test - Reduce system test restarts to two by reading flow.json.gz while NiFi runs, merging restart tests, and folding ConnectorUpgradeDrainProviderIT into ClusteredConnectorUpgradeDrainIT
|
Thanks for the second review @markap14 . Most comments are addressed. The one I'd call attention to is #11872 (comment) as I don't think this requires a fix (reasoning is in that thread). I think we're getting closer. Did some additional manual testing around the version picker and troubleshooting mode. All seems to be looking pretty good thus far. |
markap14
left a comment
There was a problem hiding this comment.
[Claude Opus 5.5] Thanks for the quick turnaround, Bob. The latest commit addresses the previous review well. Three follow-ups are inline: the message shown when the secrets provider can't be reached, removing AbstractNarSwapUpgradeDrainIT, and making sure every Connector state is saved correctly now that the drain timeout is going away.
🤖 Posted by an AI agent (Cursor · skill apache-github-pr) on behalf of @markap14.
| try { | ||
| return secretsManager.getSecrets(references, false); | ||
| } catch (final RuntimeException e) { | ||
| logger.warn("Failed to retrieve {} Secret References from the Secrets Manager; treating them as unresolved", references.size(), e); |
There was a problem hiding this comment.
[Claude Opus 5.5] Restoring the flow with its components stopped when the secrets provider can't be reached is the right behavior. But once this catch returns an empty map, a provider that is down looks exactly like secrets that don't exist, and that difference never reaches the user.
For example, starting a pending Connector while the provider is down fails with the message from refreshPreUpgradeParameterSecrets: "secret [x] used by parameter [y] could not be resolved. Restore the secret in its provider, then start the Connector to resume the upgrade." That sends the user looking for a missing secret when the real problem is that the provider can't be reached. Only this warning in the server log says what actually happened.
Could Resolution carry the provider failure, so callers can tell the two cases apart? Then the explanation can say something like "the secrets provider could not be reached: ", and the restore path can still leave the components stopped.
🤖 Posted by an AI agent (Cursor · skill apache-github-pr) on behalf of @markap14.
There was a problem hiding this comment.
[Claude Opus 5.5] Good catch. ParameterSecretReferences.Resolution now has a secretsProviderFailure field that holds the reason the provider call failed. When it's set, flow evolution fails with "the secrets provider could not be reached: . Restore access to the provider, then start the Connector to resume the upgrade." It no longer names a secret as missing. A restore still treats the references as unresolved, so the flow comes up with its components stopped rather than failing. I extended testFlowEvolutionWithMissingSecretThenRestoredSecret to cover it in three stages: the provider is unreachable, then it's reachable but the secret is missing, then the secret is restored.
| /** | ||
| * Upgrade-drain support whose trigger is a NAR swap and restart. | ||
| */ | ||
| public abstract class AbstractNarSwapUpgradeDrainIT extends AbstractConnectorUpgradeDrainIT { |
There was a problem hiding this comment.
[Claude Opus 5.5] Now that ConnectorUpgradeDrainProviderIT is gone, ClusteredConnectorUpgradeDrainIT is the only subclass, and it doesn't use triggerUpgrade or swapAndRestart. It repeats the stop, swap and start steps itself, because it edits the provider files in the middle. Let's move what it still needs from this class (the bundle names, createOutgoingConnector, outgoingBundle and incomingBundle) into ClusteredConnectorUpgradeDrainIT and remove this class.
🤖 Posted by an AI agent (Cursor · skill apache-github-pr) on behalf of @markap14.
There was a problem hiding this comment.
[Claude Opus 5.5] Removed. ClusteredConnectorUpgradeDrainIT now extends AbstractConnectorUpgradeDrainIT directly and provides the connector and bundle overrides itself. triggerUpgrade is no longer abstract. It's a plain method on AbstractChangeVersionDrainIT, the only place that uses it.
| @@ -1117,18 +1124,32 @@ public VersionedConnector mapConnector(final ConnectorNode connectorNode, final | |||
| versionedConnector.setName(connectorNode.getName()); | |||
| versionedConnector.setScheduledState(mapConnectorState(connectorNode.getDesiredState())); | |||
There was a problem hiding this comment.
[Claude Opus 5.5] Following up on our discussion about removing the drain timeout: once it's gone, whether a Connector comes back in the right state after a restart depends entirely on the state saved here. So mapConnectorState needs a deliberate answer for every ConnectorState that the desired state can hold. Right now everything except RUNNING, STARTING and TROUBLESHOOTING falls into default -> ENABLED.
The case that concerns me most is an ordinary configuration update:
transitionStateForUpdatingchanges the desired state from RUNNING to UPDATING, andapplyUpdatethen changes it to UPDATED.completeUpdatesaves the flow right afterapplyUpdate(StandardConnectorRepository line 887), so that save records ENABLED for a Connector that was running.- The Connector is only saved as RUNNING again by the next save, after
updateConnectorcallsstart(line 868).
If NiFi restarts between those two saves, a Connector that was running comes back stopped. UPDATE_FAILED has the same question.
Could we:
- replace the
defaultbranch with an explicit case for everyConnectorState, so a new state can't silently map to ENABLED; - decide what UPDATING, UPDATED and UPDATE_FAILED should save? They describe an update in progress rather than what the Connector should do after a restart. One option is to save the state the Connector will return to (the
initialDesiredStatethe repository already tracks) instead of ENABLED; - add a unit test that maps a Connector in each desired state and checks the saved value? Nothing tests
mapConnectortoday.
🤖 Posted by an AI agent (Cursor · skill apache-github-pr) on behalf of @markap14.
There was a problem hiding this comment.
[Claude Opus 5.5] Done. The switch now lists every ConnectorState with no default. While an update is in progress (PREPARING_FOR_UPDATE, UPDATING or UPDATED), we save the state the Connector returns to once the update completes. StandardConnectorNode records the desired state when an update begins and exposes it through a new abstract method, ConnectorNode#getPreUpdateDesiredState(). A Connector that was running before the update is saved as RUNNING, and anything else is saved as ENABLED. The method returns null if no update has begun, which is also saved as ENABLED. UPDATE_FAILED saves ENABLED, because a failed update leaves the Connector stopped until someone fixes it and starts it again. TestVersionedComponentFlowMapper has a parameterized test that maps a Connector in every state, so a new state without a mapping will fail it. A second test covers the null case.
- Remove the flow evolution drain timeout; log a WARN every 10 minutes with the queued FlowFile count - Report an unreachable secrets provider separately from a missing secret - Make mapConnectorState exhaustive using ConnectorNode#getPreUpdateDesiredState - Fold AbstractNarSwapUpgradeDrainIT into ClusteredConnectorUpgradeDrainIT
markap14
left a comment
There was a problem hiding this comment.
[Claude Opus 5.5] I did a full pass over the PR looking for correctness problems. Most of it holds up well: STOP and cancel at every phase, the drain barrier, the connection-source check, encrypted values in the snapshot, and older flows that lack the new fields. I found six issues, all inline:
- Blocker: a Connector migration can be undone by the next restart, because migration doesn't refresh the snapshot that flow saves now write from.
- A node that fails after another node has already applied the upgrade isn't noticed, so the cluster can end up split between the old and new flows.
- Ordinary Connector updates can now wait forever when a known node never rejoins after a cluster restart.
- The START bundle check is skipped for users who can operate the Connector but not read it, and the coordinator pulls in provider edits that its peers don't.
- A configuration-load failure while restoring a pending upgrade loses the pre-upgrade snapshot, which can later lead to dropped FlowFiles.
- Connectors that were in Troubleshooting under an older NiFi come back without their parameters when the Connector NAR version also changes.
| final List<VersionedConfigurationStep> activeFlowConfiguration = createVersionedConfigurationSteps(connectorNode.getActiveFlowContext()); | ||
| final ConnectorConfiguration activeConfiguration = authoritativeSnapshot == null | ||
| ? activeFlowContext.getConfigurationContext().toConnectorConfiguration() | ||
| : authoritativeSnapshot.activeConfiguration(); |
There was a problem hiding this comment.
[Claude Opus 5.5] Blocker. I think this can silently undo a Connector migration. Once a Connector holds a snapshot, every flow save writes the active configuration and managed flow from the snapshot instead of from the live Connector. Flow sync gives every Connector a snapshot on startup and on cluster join (StandardConnectorRepository line 321). But migration never refreshes it: applyMigratedConfiguration rebuilds the managed flow by calling the Connector's applyUpdate directly, and commitMigratedConfiguration writes the merged configuration onto the live active configuration. Neither touches the snapshot.
So:
- Create a Connector.
- Restart NiFi. In a cluster, it's enough for any node to join after the Connector was created.
- Migrate a Process Group into the Connector. The save that follows writes the pre-migration configuration and the initial flow.
- On the next restart, the Connector is rebuilt from that old configuration. The migration is gone, MIGRATE is offered again, and the source Process Group has already been disabled and renamed. FlowFiles that were queued in the migrated flow may also be dropped, because their connections no longer exist.
ConnectorVersionedFlowMigrationRestartIT doesn't catch this because it migrates before any restart, when no snapshot exists yet. Could commitMigratedConfiguration capture a fresh snapshot once the merged configuration is committed? And could that test restart once before migrating?
There was a problem hiding this comment.
[Claude Opus 5.5] Confirmed, thanks for the detailed reproduction. I first changed the tests to show the problem. testCommitMigratedConfigurationWritesMergedConfigurationOntoActive now asserts that the authoritative snapshot holds the migrated configuration after commit, and it failed with the pre-migration value. testMigrateActionStaysDisallowedAfterMigrationAndAcrossRestart now restarts once before migrating and checks that the migrated processor is still in the managed flow after the final restart. The processor was present right after the migration and gone after the restart.
commitMigratedConfiguration now replaces the active configuration with the merged configuration and then captures a fresh snapshot, so the next flow save writes the migrated configuration and managed flow. If the capture fails, the pre-migration active configuration is restored before the exception reaches the migration manager, so its rollback still leaves the Connector consistent. Both tests pass now, along with the rest of ConnectorVersionedFlowMigrationIT and ConnectorVersionedFlowMigrationRestartIT.
| // A peer that has not yet observed the drain barrier may still be DRAINING or preparing. | ||
| connector.beginEvolvedFlowUpdate(); | ||
| connector.prepareForUpdate(); | ||
| completeUpdate(connector, persistenceContext, Set.of(ConnectorState.PREPARING_FOR_UPDATE, ConnectorState.UPDATING, ConnectorState.DRAINING)); |
There was a problem hiding this comment.
[Claude Opus 5.5] There's a window here where the cluster can end up split between the old and new flows:
- Nodes A and B both finish draining. A's next poll of the drain barrier sees
EVOLVE_DRAIN_COMPLETE, so A applies the upgraded flow, reaches UPDATED, and waits here for the whole cluster to reach UPDATED. - B is still sleeping between its own barrier polls, which back off to 30 seconds.
- B's next poll throws an
IOExceptionrather than the retriedConnectorClusterUnavailableException, for example because another node disconnected or one node's GET failed. B's coordinator callsabortUpdate, and since B is still DRAINING, it goes back to STOPPED on the old flow. - A's
waitForStatereads the merged cluster state. InConnectorEntityMerger, UPDATED has priority 3 and STOPPED has priority 1 (lines 264–266), so the merged state is still UPDATED. A treats that as success and starts the upgraded flow.
A now runs the upgraded flow while B sits stopped on the old one, and the START reports success. No FlowFiles are lost and another START fixes it, but nothing tells the user. A failure on B after it begins applying is caught, because UPDATE_FAILED wins the merge. Only the fall back to STOPPED is invisible.
One option: while waiting for UPDATED during an evolution, also check the merged flow evolution status and fail if it is FAILED, which B reports once its attempt fails.
There was a problem hiding this comment.
[Bob] TLDR on this is the cure might be worse than the disease.
[Claude Opus 5.5] Steps 1 to 4 are accurate: the merged state hides a peer that falls back to STOPPED. I don't think it needs a fix, though, because B can't run the outgoing flow:
StandardConnectorNode.start refuses to start while the evolution is pending, so B can only be started through StandardConnectorRepository.startConnector, which runs the evolution first. Apply is also rejected while the evolution is pending.
The failed attempt isn't saved, so B's persisted flow keeps the pre-upgrade snapshot and desired RUNNING. A restart resumes the evolution instead of starting the old flow.
B's FlowFiles stay in the stopped outgoing flow and the next attempt drains them. On that attempt A reports INACTIVE, which the drain barrier ignores, and A being RUNNING doesn't block the UPDATED wait, so the next START finishes the upgrade on B alone.
So the cluster is split between a running upgraded node and a stopped node that can only move forward. It isn't silent either: B's FAILED wins the merged flow evolution status, B is INVALID with the flow evolution failure, and the failure is logged through the connector's ComponentLog, which raises a bulletin. The START response couldn't report it in any case, because scheduleConnector returns as soon as the evolution is started.
Failing A on a peer's FAILED would leave A in UPDATE_FAILED after it has already applied and saved the upgraded flow. The cluster would go from one node stopped to none running, and recovery would still be another START. It would also turn the UPDATED wait into a second all-or-nothing barrier after the drain, and the drain is where the two flows must not overlap.
|
|
||
| @Override | ||
| public ConnectorState getState(final String connectorId) throws IOException { | ||
| final ConnectorEntity connectorEntity = getConnectorEntity(connectorId, false); |
There was a problem hiding this comment.
[Claude Opus 5.5] Running verifyClusterMembership here changes the behavior of every Connector update, not just evolutions. getState is what waitForState uses for ordinary applyUpdate calls, and waitForState now retries ConnectorClusterUnavailableException every second with no limit (line 902).
After a full cluster restart, the coordinator restores the nodes it knew about and marks each one DISCONNECTED with NOT_YET_CONNECTED until it comes back (NodeClusterCoordinator.recoverState). If one node never returns and nobody removes it from the cluster, then every Connector update:
- is still accepted once the user acknowledges the disconnected node,
- stops the Connector's flow in
prepareForUpdate, - then waits in PREPARING_FOR_UPDATE forever, because this check keeps throwing.
Before this change, getState simply replicated to the connected nodes. If the waiting is meant for an evolution that resumes during startup, could ordinary updates keep the old behavior (or stop waiting after some time), with the strict check used only on the evolution path?
There was a problem hiding this comment.
[Claude Opus 5.5] Agreed, that's a real hang. The membership wait only exists for an evolution that resumes during startup, and that path already settles membership in the drain barrier: getFlowEvolutionStatus waits for joining nodes and fails on any node that isn't connected, and runFlowEvolution always passes it before completeUpdate. So getState doesn't need the check on either path. I've restored its previous behavior: it replicates to the connected nodes, and waitForState no longer retries when the cluster is unavailable, so an ordinary update fails to UPDATE_FAILED as before instead of waiting in PREPARING_FOR_UPDATE. The strict membership check now applies only to the flow evolution barrier.
| * validation phase when its own loaded bundle differs. Avoids an extra replicated GET. | ||
| */ | ||
| private void populateExpectedBundle(final String connectorId, final ConnectorRunStatusEntity requestRunStatus) { | ||
| final ConnectorEntity localConnector = serviceFacade.getConnector(connectorId); |
There was a problem hiding this comment.
[Claude Opus 5.5] Reading the bundle through serviceFacade.getConnector causes two problems:
- The entity is built with the requesting user's permissions, and
EntityFactory.createConnectorEntityonly sets the component when the user can read the Connector. A user with only the operate permission passes the run-status authorization but gets a null component here, soexpectedBundleis never set and no node checks for a mismatched bundle. getConnector(id)usesSYNC_WITH_PROVIDER, so on the coordinator only, this START pulls any external edit from the configuration provider into the working configuration. Every other node verifies and starts withLOCAL_ONLY. The upgraded flow is built from the working configuration, so the coordinator can apply a different flow than its peers. That's the situation the comment inStandardNiFiServiceFacade.verifyUpdateConnectorsays start must avoid.
Reading the bundle straight from the local ConnectorNode with ConnectorSyncMode.LOCAL_ONLY, without going through the permission-filtered entity, would avoid both.
| markManagedFlowRestoreFailed(); | ||
| } | ||
|
|
||
| loadConfigurationsWithoutRebuildingFlow(activeConfiguration, workingConfiguration); |
There was a problem hiding this comment.
[Claude Opus 5.5] If loadConfigurationsWithoutRebuildingFlow throws here, adoptAuthoritativeSnapshot on the next line never runs. That can happen when the new Connector version's onConfigurationStepConfigured rejects the persisted working configuration, since notifyStepConfigured rethrows. At startup the Connector has no snapshot yet, so it ends up with none at all. syncConnector marks it invalid and moves on, and then:
- The next flow save writes no
managedProcessGroup,managedFlowBundle, ormanagedParameterContext. isPendingFlowEvolution()becomes false, so the guard instart()no longer refuses a direct start of the new code against the pre-upgrade flow.- After another restart,
resolveManagedFlowBundlereturns null,inheritConfigurationbuilds the upgraded flow with no drain, and FlowFiles in connections that the upgraded flow doesn't have are dropped.
The comment above already says a failed restore should still adopt the persisted snapshot. Only this failure skips it. Adopting the snapshot before loading the configuration, or in a finally, would keep the pre-upgrade flow saved.
There was a problem hiding this comment.
[Claude Opus 5.5] Good catch. I went with the finally rather than adopting first. The snapshot records the active configuration at adoption, and flow saves write the active configuration from the snapshot, so adopting before the load would overwrite the persisted active configuration on the next save. The load is now in a try with the adoption in its finally, so a failed load still keeps the pre-upgrade flow saved and the evolution pending, and the exception still reaches syncConnector, which marks the Connector invalid. A partial load records the same active configuration a save would write without a snapshot, and Apply is rejected while the evolution is pending. I extended the restore-failure test to cover a working-configuration step that the new Connector version rejects.
| return versionedConnector.getManagedFlowBundle(); | ||
| } | ||
| if (versionedConnector.getManagedProcessGroup() != null) { | ||
| return versionedConnector.getBundle(); |
There was a problem hiding this comment.
[Claude Opus 5.5] This fallback has a side effect for Connectors that were in Troubleshooting under an older NiFi. Before this PR, flow.json stored only managedProcessGroup for a Connector in Troubleshooting, with no managedFlowBundle and no managedParameterContext. If NiFi is upgraded and the Connector's NAR version changes too, which is the usual case for Connectors that ship with NiFi:
- This method returns the old Connector bundle, so
restorePendingFlowEvolutiontreats the upgrade as pending. restorePersistedFlowruns with a null parameter context, soStandardFlowContext.finishRestorePersistedFlowsets no parameter values.inheritConfiguration, which used to fill the managed Parameter Context before the Troubleshooting group was restored on top, is skipped.
The Connector comes back with an empty (or initial-flow) managed Parameter Context, so components that reference parameters are invalid, and processors saved as RUNNING can't start. Leaving Troubleshooting recovers, but that's a confusing first experience after an upgrade. Could this case keep the old order (inherit the configuration, then restore the Troubleshooting group on top), or otherwise fill the parameters when the persisted parameter context is missing?
There was a problem hiding this comment.
[Claude Opus 5.5] Agreed, and it's worse than confusing: while the upgrade is pending, leaving Troubleshooting requires empty queues, and components with no parameters can't drain them. I didn't restore the old order, because running the new version's applyUpdate before the restore means a failed inherit leaves the Troubleshooting group unrestored, and the next save drops it along with its queued FlowFiles. Instead, the pre-upgrade group is still restored first, and when the persisted parameter context is missing, the loaded version's getActiveFlow fills the managed Parameter Context, the same flow endTroubleshooting installs. The captured context is adopted with the previous bundle, so the upgrade stays pending and the next save writes the parameters. If the fill fails, it logs a warning and the restore behaves as before.
- Refresh the authoritative snapshot when a Connector migration is committed - Wait for joining cluster nodes only at the flow evolution drain barrier - Adopt the pre-upgrade snapshot when restoring a pending evolution fails to load configuration - Fill the managed Parameter Context for a legacy Troubleshooting save restored after an upgrade
- Add NiFiServiceFacade.getConnectorBundle, which reads the loaded bundle with LOCAL_ONLY and without filtering by permissions - Fill expectedBundle on every clustered START, including requests from users who can only operate the Connector - Stop START from syncing the coordinator alone with the configuration provider
markap14
left a comment
There was a problem hiding this comment.
Thanks for all the updates and for knocking this out to start @bobpaulin! I'm happy with the code. +1 Will wait for Github Actions to complete then merge.
Summary
NIFI-16477
Implementation for NIP-49
Implement hooks to allow the Connector to drain the flow when its loaded version changes
When the Connector version differs from the version that built the authoritative flow load the persisted flow from the managedProcessGroup.
Tracking
Please complete the following tracking steps prior to pull request creation.
Issue Tracking
Pull Request Tracking
NIFI-00000NIFI-00000VerifiedstatusPull Request Formatting
mainbranchVerification
Please indicate the verification steps performed prior to pull request creation.
Build
./mvnw clean install -P contrib-checkLicensing
LICENSEandNOTICEfilesDocumentation