Skip to content

NIFI-16310 Preserve migration-created Controller Services across flow updates - #11813

Open
awelless wants to merge 3 commits into
apache:mainfrom
awelless:NIFI-16310-deterministic-migration-service-ids
Open

awelless wants to merge 3 commits into
apache:mainfrom
awelless:NIFI-16310-deterministic-migration-service-ids

Conversation

@awelless

@awelless awelless commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

NIFI-16310

Controller Services created by property migration get a versioned component ID that is the same on every instance of a flow, so a flow author and its consumers match these services on a version change instead of replacing them and losing their state.

The ID is assigned once, after all migrations of a synchronization have finished. It is a hash of:

  • the owning group's identity: the flow identifier for the synchronized flow or a version-controlled child group, otherwise the group's versioned ID;
  • the service type;
  • the service's properties after its own migration. A property that references another service contributes that service's versioned ID.

A created service stays unversioned, as today, when:

  • it holds an inline sensitive value. Inline secrets aren't saved to the registry, so instances can't agree on an ID. Parameter references are hashed like any other value;
  • it references a service without a stable versioned ID, or one outside the synchronized flow;
  • another service in the same group has or would get the same ID.

Services the proposed flow no longer contains are now removed at the end of the synchronization, and only when no remaining component references them. Before, a service that migration still needed could be removed.

The behavior is unchanged for services with inline secrets, and more robust for services without them.

Code changes

  • StandardControllerServiceFactory only records the services it creates, including those created by a service's own migration.
  • StandardVersionedComponentSynchronizer assigns the versioned IDs after migration, in one method shared by synchronization and paste. Paste now also migrates reporting tasks.
  • StandardVersionedComponentSynchronizer records missing services during synchronization and removes those that are no longer referenced at the end.

Verification

  • Synchronizer unit tests.
  • System tests: MigrationCreatedControllerServiceVersioningIT covers startup and import migration, shared and separate services, a consumer that skips a version, and services with inline secrets.

Additional changes

FileSystemFlowRegistryClient which is used in system tests was moved into a separate NAR, to be available before and after NAR swap.

Suggested review order

  • MigrationCreatedControllerServiceVersioningIT and its dependencies to see the relevant use cases.
  • StandardVersionedComponentSynchronizer for the implementation.

Tracking

Please complete the following tracking steps prior to pull request creation.

Issue Tracking

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 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 according to the License Policy
  • New dependencies are documented in applicable LICENSE and NOTICE files

Documentation

  • Documentation formatting appears as expected in rendered files

… updates

Derive stable versioned service identities from the owning flow or group so independently migrated instances retain their services, references, and state when applying saved flow versions.
Retain migration-marked services absent from incoming flows and verify migration, update, paste, and restart behavior with focused unit and system tests.
}
});

final VersionedExternalFlowMetadata metadata = versionedExternalFlow.getMetadata();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Originally I tried to always rely on VersionControlInformation in the CS factory for top-level versioned groups.
However, during the flow import and upgrades VersionControlInformation is absent. That's why owningGroupIdentity is determined in synchronizer - that's the only place where we have the necessary identifiers.

});

final VersionedExternalFlowMetadata metadata = versionedExternalFlow.getMetadata();
final String flowIdentifier = metadata == null ? null : metadata.getFlowIdentifier();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

flowIdentifier is supposed to be unique in each flow, and is saved in json definition, thus portable across different flow instances.

Please let me know if I'm missing something here, and we cannot rely on this identifier to be unique and consistent.

Comment on lines +5 to +6
"flowIdentifier" : "0831859c-f4a1-4ff6-99b3-58aeb35cb17f",
"version" : "1",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

V1 flow was exported from an actual NiFi instance.
V2 flow is composed and saved in the system tests.


private void saveMigratedFlow(final String groupId, final FlowRegistryClientEntity registryClient)
throws NiFiClientException, IOException, InterruptedException {
clearMigrationComment(waitForSingleStoreService(groupId), findProcessor(groupId, MIGRATING_PROCESSOR_NAME));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently migration comment has to be cleared manually when saving a new flow. Otherwise the controller service would always be ignored during removal.

@markap14

Copy link
Copy Markdown
Contributor

[Claude Opus 5.5]

Thanks for digging into this, @awelless. The predictable versioned ID is the right core idea. It's what lets the service a flow author saves match the service each consumer already has. A few things need to change before this can be merged, though.

1. Don't use the comment to decide whether a service is removed

removeMissingControllerServices now skips any service whose comment equals MIGRATION_CREATED_COMMENT. A comment is free text: users can edit it, it's shown in the UI, and it's copied into registry snapshots. We already rely on it in FlowDifferenceFilters, and we don't want to give it more meaning. It also causes real problems here:

  • The flow author has to clear the comment by hand before saving a version, as the system test does. If they don't, every consumer inherits the marker, and no later version can ever remove that service.
  • The rule applies to every synchronization, including a node reconnecting to the cluster. Suppose that while a node is disconnected, the cluster moves from v1 to v2 (which adopts the service and replaces its comment) and then to v3 (which drops it). The disconnected node still has the marker from v1, so it keeps the service when it reconnects, and its flow no longer matches the cluster's.

Please base the decision on references instead: a service that the proposed flow doesn't contain should be removed only if nothing in the flow still references it once synchronization and property migration have finished.

This isn't a special case for migration. StandardControllerServiceNode.verifyCanDelete() only checks that the service is disabled. So today the synchronizer will delete a service that a processor still points at, and that is exactly the bug in the Jira: the service is deleted, then migration recreates it with the same ID and empty state.

Rough outline:

  • In the per-group synchronize, record the services that are missing from the proposed group instead of removing them right away, similar to how createdAndModifiedExtensions is collected.
  • In the public synchronize, after the property-migration loop and before getComponentScheduler().resume(), remove each recorded service that has no remaining references. References from other recorded services shouldn't count, and the check should repeat until nothing changes, so that a chain of services referencing each other is removed together.
  • Update the order-of-operations comment in synchronize, since step 1 moves to the end.

With that rule:

  • The new version declares the service: it's matched by versioned ID and updated in place, as it is now.
  • The new version doesn't declare it, but the processor still references it: it's kept, with its state.
  • The new version removes the referencing processor: it's removed, so unused services don't pile up.
  • A node reconnects to the cluster: it ends up with exactly the services the cluster flow references.
  • The author and consumer computed different IDs (for example, a flow promoted from one registry to another): after the update nothing references the consumer's old service, so it's removed instead of being left beside the new one.

One behavior change is worth noting in the Jira. If a nested versioned child group isn't updated (updateDescendantVersionedFlows is false), and its processor references a parent-group service that the new version drops, that service is now kept instead of being deleted out from under the processor.

The system test's step that clears the migration comment before saving should go away.

2. Leave sensitive values out of the versioned ID

generateVersionedId hashes every property value passed to the new service. When a migration moves a sensitive literal into a service (for example, credentials moved into a credentials provider), the author and consumer will hold different values, because sensitive values aren't stored in the registry. Their IDs won't match. It also puts a hash of the secret into the registry snapshot. Please build the ID from non-sensitive values only. If that would give two services in the same group the same versioned ID, leave the new service unversioned.

3. System tests

MigrationCreatedControllerServiceVersioningIT adds 342 seconds to every system test run, because each of its 11 tests builds a new NiFi instance and restarts it at least once. That's too much for this change. Please reduce it to a single test method with one upgrade restart: set up every flow first, upgrade once, then run the version changes and checks.

Only a few things need a real NiFi instance: migration at startup, migration at import, the two producing the same ID, and state surviving a version change. Suggested shape:

  1. Setup (old extensions):
    • Register the registry client and copy in legacy v1.
    • The author imports v1 and starts it, then adds the unrelated processor and saves v2.
    • Consumer 1 imports v1 and starts it.
  2. Upgrade: swap the NARs and restart once.
  3. Author:
    • The service exists, is enabled, is referenced by the processor, and has a versioned ID.
    • The processor is valid and the flow shows as up to date.
    • Consumer 1's service has the same versioned ID as the author's, and its flow is stale but has no local changes.
  4. Consumer 2 imports v2 and starts it. Its service has the same versioned ID as the author's, which shows that the startup and import paths agree.
  5. Consumer 1 changes from v1 to v2. The same service remains and its state is kept.
  6. The author makes a small change, such as renaming the processor, and saves v3. Consumers 1 and 2 both change to v3. Each keeps the same service instance and its state, the versioned ID matches, and the flow is up to date.

The rest can be removed:

  • The three restart tests: the versioned ID is saved and reloaded like any other field.
  • The three paste tests: the unit tests already cover which identity a paste uses.
  • testFlowUpdateMigrationUsesSameServiceIdentityAsStartup: migration during a version change uses the same code path as import. migrationInSynchronizedGroupUsesIncomingFlowIdAfterVersionControlIsCleared covers it.
  • The nested parent-update test: migrationInIndependentlyVersionedChildUsesChildFlowId covers which identity a nested child uses.
  • testRuntimeUpgradeCreatesEnabledReferencedService: its checks move into step 3.

There's also an unnecessary restart in AbstractNarSwapMigrationIT's @AfterEach. That's being handled separately in NIFI-16500, so no change is needed here.

4. Unit tests

  • testUserAddedControllerServiceRemovedWhenAbsentFromProposedFlow duplicates the existing testControllerServiceRemoved. Please strengthen that test instead of adding a new one.
  • The two synchronizationRetains... tests should become a single reference-based test: one case where a remaining processor still references the service (it's kept), and one where nothing does (it's removed).
  • expectedMigrationServiceId copies the production hash formula, so these tests break whenever the formula changes, even if the behavior is still correct. Compare against the ID produced by a StandardControllerServiceFactory built with the expected identity instead.

5. Smaller items

  • In getOwningProcessGroupIdentity, the topLevelGroup parameter is really the group being synchronized. Please rename it to something like synchronizedGroup. Inside synchronize, topLevelGroup already means the group from syncOptions.getTopLevelGroupId().
  • In the comment on line 458, please spell out "VCI". The line above talks about the versioned component ID, so it's unclear whether "VCI" means that or version control information.
  • When the deferred removal keeps a service because something still references it, please log that at info, naming the service and what references it. It explains why a service the new version doesn't declare is still there.

…ervices

- Remove Controller Services absent from the proposed flow only after synchronization and property migration, and only when no remaining component references them, directly or through other removed services
- Log retained Controller Services with the components that still reference them
- Exclude sensitive property values from the generated versioned component ID
- Consolidate MigrationCreatedControllerServiceVersioningIT into a single test with one upgrade restart
- Cover Controller Service removal through flow synchronization on cluster reconnect
- Strengthen and simplify unit tests

@awelless awelless left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @markap14, I addressed your comments.

Now controller services are removed based on whether any remaining component references them, directly or indirectly.
E.g. in this situation no controller service is removed:

[remaining processor] -> [missing service 1] -> [missing service 2]
[remaining service] -> [missing service 3]

It's done in a single pass, with a mark-sweep approach.


@Test
public void testUnnecessaryProcessorsAndConnectionsRemoved() throws NiFiClientException, IOException, InterruptedException {
public void testUnnecessaryProcessorsConnectionsAndControllerServicesRemoved() throws NiFiClientException, IOException, InterruptedException {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now this test verifies that an orphaned controller service is removed too.

Comment on lines +118 to +119
final Set<ControllerServiceNode> groupControllerServices = group.map(processGroup -> processGroup.getControllerServices(false)).orElse(Collections.emptySet());
final boolean occupied = groupControllerServices.stream()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since owning group identity is a part of the hash for versioned id, we're checking for occupied versioned ids in the owning group only.

@markap14 markap14 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

Thanks for the quick turnaround, @awelless. Deciding removal by references is the right rule, and the single system test is much better. There are still two outcomes that this change must not allow, though, and the current code allows both:

  1. A consumer's service is thrown away and replaced by a new, empty one. This happens whenever the author's and the consumer's versioned IDs don't match. Today that is the normal case for the AWS and proxy migrations: the passwords those migrations pass are still part of the hash, so every instance gets a different ID. It also means a hash of each password is saved in the registry.
  2. A processor is pointed at another processor's service. For example, it ends up using another processor's credentials. When two services in a group come out with the same ID, the first one created keeps it. Which one is first depends on the order processors are migrated, and that order isn't guaranteed to be the same on every instance. If the author and a consumer migrate in different orders, the next version update re-points the consumer's processors at each other's services.

Both come from the same cause: the factory picks the versioned ID while each service is being created, one service at a time. At that point it doesn't know which components will end up using the service, and the service hasn't run its own migrateConfiguration yet. So the fix is to assign the versioned IDs once, after every migration in the update has finished:

  • The factory stops computing IDs. It only records each service it creates in a list that the synchronizer passes in.
  • After the migration loop, the synchronizer gives each recorded service a versioned ID built from:
    • the owning flow or group identity, as now;
    • the service type;
    • its non-sensitive property values, read after the service's own migration so renamed sensitive properties are recognized;
    • the sorted versioned IDs of the components that reference it.

The last item is what removes the ordering problem:

  • Two processors with different secrets have separate services, and each service is referenced by a different processor, so the IDs differ.
  • Two processors sharing one service produce the same ID no matter which one created it.

I've added inline comments with exactly where each piece goes. There's also an inline comment on the removal code: it can be about a quarter of its current size, and the smaller version also avoids a failure where the update tries to delete a service that migration has just created and enabled.

On tests: most of the new identity tests go away with this change, because the factory no longer computes anything. The synchronizer tests should check the contract (same inputs give the same ID, regardless of order) by comparing IDs between runs, not by rebuilding the expected ID. The system test covers the right paths, but its setup can't produce either problem above. It needs a secret that the service renames and a second migrating processor. Details are inline.

The two CI failures don't come from this PR. The MongoDB ITs couldn't reach their Docker container, and OffloadContentClaimTruncationIT also fails on main without this change.


final Map<String, String> sortedProperties = new TreeMap<>();
for (final Map.Entry<String, String> property : creationDetails.serviceProperties().entrySet()) {
if (!serviceNode.getPropertyDescriptor(property.getKey()).isSensitive()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

This check runs before serviceNode.migrateConfiguration(...) on line 130, and that is where the service renames old property names to its current ones. For a name the service doesn't recognize, getPropertyDescriptor returns a non-sensitive placeholder, so the value is included in the hash.

The two real migrations that pass secrets both use old names:

  • AbstractAwsProcessor passes Secret Key. AWSCredentialsProviderControllerService only renames it to Secret Access Key in its own migrateProperties.
  • ProxyServiceMigration passes proxy-user-password. StandardProxyConfigurationService calls it Proxy User Password.

So the password goes into the hash. The author and each consumer get different IDs, the service is replaced on update and loses its state, and a hash of the password is saved in the registry.

Please move this logic into the synchronizer, which runs after the service's migration (see my comment on lines 428-445 of StandardVersionedComponentSynchronizer). The factory shouldn't compute the ID at all.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved to the synchronizer, which reads properties after the service's own migration, so renamed secrets are recognized. Instead of skipping sensitive values, a Parameter reference is hashed and an inline secret leaves the service unversioned (see the top-level comment).

Comment on lines +116 to +127
final String versionedId = generateVersionedId(creationDetails, serviceNode);
if (versionedId != null) {
final Set<ControllerServiceNode> groupControllerServices = group.map(processGroup -> processGroup.getControllerServices(false)).orElse(Collections.emptySet());
final boolean occupied = groupControllerServices.stream()
.map(ControllerServiceNode::getVersionedComponentId)
.flatMap(Optional::stream)
.anyMatch(versionedId::equals);

if (!occupied) {
serviceNode.setVersionedComponentId(versionedId);
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

This "first one created keeps the ID" rule can point a processor at another processor's service.

Example: two AWS processors in the same group with different keys. With sensitive values properly left out, both services hash to the same ID. Whichever processor migrates first gets the ID, and the other service stays unversioned. Migration order follows the order of a hash set of processors, so it isn't guaranteed to be the same on the author and the consumer.

If the order differs, the consumer's ID is on processor 2's service while the author's is on processor 1's. On the next version update, the synchronizer points processor 1 at the service holding processor 2's credentials. Processor 2 gets a new, empty service.

Please change the factory so that it only records what it creates:

  • Replace the owningGroupIdentity constructor argument and field (lines 62 and 69-76) with a Collection<ControllerServiceNode> createdServices. The 4-argument constructor, used by VersionedFlowSynchronizer for controller-level components, can pass new ArrayList<>().
  • Right after serviceNode.setProperties(...) on line 114, add createdServices.add(serviceNode). It has to come before line 130, so that a service is always in the list before any service its own migration creates.
  • Pass the same createdServices into the nested factory on line 129.
  • Delete lines 116-127 and generateVersionedId (lines 148-162).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The factory now only records created services, the nested factory shares the collection, and the ID code is gone. One difference: the service is recorded right after creation rather than before its migration specifically, since the order no longer matters once IDs are computed after all migrations.

Comment on lines 428 to 439
final VersionedExternalFlowMetadata metadata = versionedExternalFlow.getMetadata();
final String flowIdentifier = metadata == null ? null : metadata.getFlowIdentifier();
for (final CreatedOrModifiedExtension createdOrModifiedExtension : createdAndModifiedExtensions) {
final ComponentNode extension = createdOrModifiedExtension.extension();
final Map<String, String> originalPropertyValues = createdOrModifiedExtension.propertyValues();

final String owningGroupIdentity = getOwningProcessGroupIdentity(extension, group, flowIdentifier);
final ControllerServiceFactory serviceFactory = new StandardControllerServiceFactory(context.getExtensionManager(), context.getFlowManager(),
context.getControllerServiceProvider(), extension);
context.getControllerServiceProvider(), extension, owningGroupIdentity);

if (extension instanceof final ProcessorNode processor) {
processor.migrateConfiguration(originalPropertyValues, serviceFactory);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

This is where the versioned IDs should be assigned, after every migration in the update has finished.

Please replace this loop (lines 428-445) and the near-copy in addVersionedComponentsToProcessGroup (lines 316-330) with one private method that both call. synchronize would call it with group and the metadata flowIdentifier. addVersionedComponentsToProcessGroup would call it with group and determineProcessGroupIdentity(group). Roughly:

private void migrateCreatedAndModifiedExtensions(final ProcessGroup synchronizedGroup, final String synchronizedGroupIdentity) {
    final List<ControllerServiceNode> createdServices = new ArrayList<>();
    for (final CreatedOrModifiedExtension createdOrModifiedExtension : createdAndModifiedExtensions) {
        final ComponentNode extension = createdOrModifiedExtension.extension();
        final Map<String, String> originalPropertyValues = createdOrModifiedExtension.propertyValues();
        final ControllerServiceFactory serviceFactory = new StandardControllerServiceFactory(context.getExtensionManager(), context.getFlowManager(),
            context.getControllerServiceProvider(), extension, createdServices);

        if (extension instanceof final ProcessorNode processor) {
            processor.migrateConfiguration(originalPropertyValues, serviceFactory);
        } else if (extension instanceof final ControllerServiceNode service) {
            service.migrateConfiguration(originalPropertyValues, serviceFactory);
        } else if (extension instanceof final ReportingTaskNode task) {
            task.migrateConfiguration(originalPropertyValues, serviceFactory);
        }
    }

    // A service is added to the list before any service that its own migration creates, so the referencing service has its versioned ID first
    for (final ControllerServiceNode service : createdServices) {
        assignVersionedComponentId(service, synchronizedGroup, synchronizedGroupIdentity);
    }
}

assignVersionedComponentId builds the ID from the following parts. Each one is the same on every instance and doesn't depend on migration order.

  1. getOwningProcessGroupIdentity(service, synchronizedGroup, synchronizedGroupIdentity). If it is null, leave the service unversioned, as now.
  2. service.getCanonicalClassName().
  3. A TreeMap of property name to value from service.getRawPropertyValues(). Look up each descriptor with service.getPropertyDescriptor(name) so that sensitive dynamic properties are recognized. Skip it if it is sensitive or if getControllerServiceDefinition() != null. Instance IDs of other services differ between instances, and the reference is captured by step 4 of the referenced service anyway.
  4. The sorted versioned IDs of service.getReferences().getReferencingComponents(). Use a switch on ProcessorNode and ControllerServiceNode to call getVersionedComponentId(). Avoid an instanceof VersionedComponent check, because org.apache.nifi.flow.VersionedComponent is already imported in this class. If any referencing component has no versioned ID, leave the service unversioned.

Hash the four parts with UUID.nameUUIDFromBytes, the same way as today. If that ID is already used by another service in service.getProcessGroup(), add a counter (1, 2, ...) to the hashed text until it's unused. That can only happen when a single component's migration creates two services of the same type that differ only in secret values. The order within one migration is fixed by its code, so the counter gives the same result on every instance.

With this in place, the occupied check in the factory goes away, along with the extra constructor argument.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is now one shared method for synchronize and paste. It differs from your outline in three ways:

  • referenced IDs replace referrer IDs (see the top-level comment);
  • instead of a counter, created services that would share an ID within a group stay unversioned;
  • missing services are removed before IDs are assigned, so a created service can take the ID of the one it replaces.

Comment on lines 316 to 326
final String groupIdentity = determineProcessGroupIdentity(group);
for (final CreatedOrModifiedExtension createdOrModifiedExtension : createdAndModifiedExtensions) {
final ComponentNode extension = createdOrModifiedExtension.extension();
final Map<String, String> originalPropertyValues = createdOrModifiedExtension.propertyValues();

final String owningGroupIdentity = getOwningProcessGroupIdentity(extension, group, groupIdentity);
final ControllerServiceFactory serviceFactory = new StandardControllerServiceFactory(context.getExtensionManager(), context.getFlowManager(),
context.getControllerServiceProvider(), extension);
context.getControllerServiceProvider(), extension, owningGroupIdentity);

if (extension instanceof final ProcessorNode processor) {
processor.migrateConfiguration(originalPropertyValues, serviceFactory);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

Please replace this loop (lines 316-330) with a call to the shared method described in my comment on lines 428-445: migrateCreatedAndModifiedExtensions(group, determineProcessGroupIdentity(group)). A paste has to assign versioned IDs the same way as an import or a version change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Paste now uses the shared method. It also migrates reporting tasks, as synchronize does.

}
}

removeMissingControllerServices(group, versionedExternalFlow.getFlowContents());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

This builds the list of services to remove after property migration, so it includes services that migration has just created. The factory enables those right away. If one of them isn't referenced through a Controller Service property, removeControllerService calls verifyCanDelete, which throws because the service isn't disabled. That fails the whole update after everything else has already been applied. At startup, NiFi would not start.

Recording the missing services during the per-group synchronize, before migration runs, fixes this. It also replaces lines 1207-1321 with much less code:

  1. Add private final Set<ControllerServiceNode> missingControllerServices = new HashSet<>(); next to createdAndModifiedExtensions (line 180), and clear it next to createdAndModifiedExtensions.clear() (line 351).
  2. In the per-group synchronize, right before synchronizeControllerServices(...) on line 616, add every entry of controllerServicesByVersionedId whose key isn't the identifier of a service in proposed.getControllerServices(). The per-group method only runs for groups that are being synchronized, so no separate walk over child groups is needed.
  3. Replace this line with a call to:
private void removeUnreferencedMissingControllerServices() {
    final Set<ComponentNode> keptServices = new HashSet<>();
    boolean serviceKept = true;
    while (serviceKept) {
        serviceKept = false;
        for (final ControllerServiceNode service : missingControllerServices) {
            if (!keptServices.contains(service)) {
                for (final ComponentNode referencingComponent : service.getReferences().getReferencingComponents()) {
                    if (!missingControllerServices.contains(referencingComponent) || keptServices.contains(referencingComponent)) {
                        keptServices.add(service);
                        serviceKept = true;
                        break;
                    }
                }
            }
        }
    }

    for (final ControllerServiceNode service : missingControllerServices) {
        if (keptServices.contains(service)) {
            LOG.info("Keeping {} although the proposed flow does not contain it, because it is still referenced by {}", service, service.getReferences().getReferencingComponents());
        } else {
            LOG.info("Removing {} from {}", service, service.getProcessGroup());
            context.getControllerServiceProvider().removeControllerService(service);
        }
    }
}

This keeps chains of services that something still uses, and removes cycles that nothing outside the cycle uses. Removal order doesn't matter, because StandardProcessGroup.removeControllerService already clears the references the removed service held.

  1. Delete lines 1207-1321. On line 757, restore the original childCoordinates == null || syncOptions.isUpdateDescendantVersionedFlows() condition, and update the comment on lines 602-603 to say the services are recorded here and removed at the end.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented as you suggested, with your loop. One addition: the lookup by versioned ID skips services recorded as missing, so a reference resolves to the service that replaces them.

Comment on lines +158 to +294
@Nested
class VersionedIdAssignment {
private static final String ENDPOINT_PROPERTY = "Endpoint";
private static final String ENDPOINT_PARAMETER = "#{endpoint}";
private static final String MODE_PROPERTY = "Mode";
private static final String READ_MODE = "read";
private static final String PASSWORD_PROPERTY = "Password";

private static final String OWNING_GROUP_IDENTITY = "shared-version";

private static final String CONSUMER_GROUP_ID = "consumer-instance";

@Test
void testVersionedIdentityDependsOnSuppliedIdentityTypeAndProperties() {
final Map<String, String> properties = new LinkedHashMap<>();
properties.put(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER);
properties.put(MODE_PROPERTY, READ_MODE);
final String first = createServiceAndGetVersionedId("author-instance", OWNING_GROUP_IDENTITY, IMPL_CLASS, properties);

final Map<String, String> reordered = new LinkedHashMap<>();
reordered.put(MODE_PROPERTY, READ_MODE);
reordered.put(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER);
final String second = createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, reordered);

assertNotNull(first);
assertEquals(first, second);
assertNotEquals(first, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, "different-version", IMPL_CLASS, properties));
assertNotEquals(first, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, "AnotherService", properties));
assertNotEquals(first, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, Map.of()));
}

@Test
void testSensitiveValuesDoNotAffectVersionedIdentity() {
final Map<String, String> authorProperties = Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER, PASSWORD_PROPERTY, "author-password");
final Map<String, String> consumerProperties = Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER, PASSWORD_PROPERTY, "consumer-password");
final String authorId = createServiceAndGetVersionedId("author-instance", OWNING_GROUP_IDENTITY, IMPL_CLASS, authorProperties);
final String consumerId = createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, consumerProperties);

assertEquals(authorId, consumerId);
assertEquals(authorId, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER)));
assertNotEquals(authorId, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS,
Map.of(ENDPOINT_PROPERTY, "another-endpoint", PASSWORD_PROPERTY, "consumer-password")));
assertNotEquals(factory.determineServiceId(IMPL_CLASS, authorProperties), factory.determineServiceId(IMPL_CLASS, consumerProperties));
}

@Test
void testOccupiedVersionedIdentityLeavesNewServiceUnversioned() {
final Map<String, String> properties = Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER);
final String occupiedId = createServiceAndGetVersionedId("author-instance", OWNING_GROUP_IDENTITY, IMPL_CLASS, properties);
final ControllerServiceNode existingService = mock(ControllerServiceNode.class);
when(existingService.getVersionedComponentId()).thenReturn(Optional.of(occupiedId));

final ControllerServiceNode newService = createService(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, properties, Set.of(existingService));

verify(newService, never()).setVersionedComponentId(any());
verify(existingService, never()).setVersionedComponentId(any());
verify(newService).migrateConfiguration(eq(properties), any());
}

@Test
void testUnversionedAndDifferentVersionedServicesDoNotOccupyIdentity() {
final Map<String, String> properties = Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER);
final String expectedId = createServiceAndGetVersionedId("author-instance", OWNING_GROUP_IDENTITY, IMPL_CLASS, properties);
final ControllerServiceNode unversionedService = mock(ControllerServiceNode.class);
when(unversionedService.getVersionedComponentId()).thenReturn(Optional.empty());
final ControllerServiceNode differentlyVersionedService = mock(ControllerServiceNode.class);
when(differentlyVersionedService.getVersionedComponentId()).thenReturn(Optional.of("another-versioned-id"));

final ControllerServiceNode newService = createService(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, properties,
Set.of(unversionedService, differentlyVersionedService));

verify(newService).setVersionedComponentId(expectedId);
verify(unversionedService, never()).setVersionedComponentId(any());
verify(differentlyVersionedService, never()).setVersionedComponentId(any());
}

@Test
void testCreationWithoutOwningGroupIdentity() {
final ComponentNode creator = mock(ComponentNode.class);
final FlowManager flowManager = mock(FlowManager.class);
final StandardControllerServiceFactory factory = new StandardControllerServiceFactory(
mock(ExtensionManager.class), flowManager, mock(ControllerServiceProvider.class), creator);
final ControllerServiceNode service = mock(ControllerServiceNode.class);
final ControllerServiceCreationDetails details = new ControllerServiceCreationDetails("service-id", IMPL_CLASS,
createCoordinate(LONE_BUNDLE, VERSION_2), Map.of(), ControllerServiceCreationDetails.CreationState.SERVICE_TO_BE_CREATED);
when(flowManager.createControllerService(eq(IMPL_CLASS), anyString(), any(), any(), eq(true), eq(true), eq(null))).thenReturn(service);
when(creator.getParentProcessGroup()).thenReturn(Optional.empty());

factory.create(details);

verify(flowManager).addRootControllerService(service);
verify(service, never()).setVersionedComponentId(any());

final ProcessGroup group = mock(ProcessGroup.class);
when(creator.getParentProcessGroup()).thenReturn(Optional.of(group));

factory.create(details);

verify(group).addControllerService(service);
verify(service, never()).setVersionedComponentId(any());
}

private String createServiceAndGetVersionedId(final String localGroupId, final String owningGroupIdentity, final String type, final Map<String, String> properties) {
final ControllerServiceNode service = createService(localGroupId, owningGroupIdentity, type, properties, Set.of());
final ArgumentCaptor<String> versionedId = ArgumentCaptor.forClass(String.class);
verify(service).setVersionedComponentId(versionedId.capture());
return versionedId.getValue();
}

private ControllerServiceNode createService(final String localGroupId, final String owningGroupIdentity, final String type,
final Map<String, String> properties, final Set<ControllerServiceNode> existingServices) {
final ComponentNode component = mock(ComponentNode.class);
final ProcessGroup group = mock(ProcessGroup.class);
when(component.getParentProcessGroup()).thenReturn(Optional.of(group));
when(component.getProcessGroupIdentifier()).thenReturn(localGroupId);
final FlowManager manager = mock(FlowManager.class);
final ControllerServiceNode service = mock(ControllerServiceNode.class);
when(service.getPropertyDescriptor(anyString())).thenAnswer(invocation -> {
final String name = invocation.getArgument(0);
return new PropertyDescriptor.Builder().name(name).sensitive(PASSWORD_PROPERTY.equals(name)).build();
});
final Set<ControllerServiceNode> groupServices = new HashSet<>(existingServices);
groupServices.add(service);
when(group.getControllerServices(false)).thenReturn(groupServices);
when(manager.createControllerService(eq(type), anyString(), any(), any(), eq(true), eq(true), eq(null))).thenReturn(service);

final StandardControllerServiceFactory serviceFactory = new StandardControllerServiceFactory(
mock(ExtensionManager.class), manager, mock(ControllerServiceProvider.class), component, owningGroupIdentity);
final String instanceId = serviceFactory.determineServiceId(type, properties);
final ControllerServiceCreationDetails details = new ControllerServiceCreationDetails(instanceId, type, createCoordinate(LONE_BUNDLE, VERSION_2), properties,
ControllerServiceCreationDetails.CreationState.SERVICE_TO_BE_CREATED);
serviceFactory.create(details);

verify(service).setProperties(properties);
return service;
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

Once the factory only records the services it creates, this nested class can be removed. The recording is simple wiring, and the synchronizer tests cover it. That also removes two assertions about behavior this PR doesn't change: the instance ID assertion on line 200, and the controller-level service path in testCreationWithoutOwningGroupIdentity.

For what it's worth, the sensitive-value test passed only because the mock service on line 277 already recognizes Password under the exact name passed in. The real services only learn the current name in their own migration. The synchronizer test should use an old name (see my comment there).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed; the file matches main.

Comment on lines +574 to +794
@Nested
class MigrationCreatedControllerService {

private static final String SNAPSHOT_ROOT_ID = "snapshot-root-id";
private static final String LOCAL_CHILD_ID = "local-child";
private static final String CHILD_GROUP_ID = "child-group-id";
private static final String PARENT_GROUP_ID = "parent-group-id";
private static final String CHILD_PLACEMENT_ID = "child-placement-id";
private static final String DESTINATION_GROUP_ID = "destination-group-id";

private static final String INCOMING_FLOW_ID = "incoming-flow-id";
private static final String DESTINATION_FLOW_ID = "destination-flow-id";
private static final String PARENT_FLOW_ID = "parent-flow-id";
private static final String CHILD_FLOW_ID = "child-flow-id";

private static final String REGISTRY_ID = "registry-id";
private static final String SERVICE_TYPE = TestControllerService.class.getName();
private static final Map<String, String> SERVICE_PROPERTIES = Map.of("mode", "read");

@Test
void migrationInSynchronizedGroupUsesIncomingFlowIdAfterVersionControlIsCleared() {
final ProcessGroup targetGroup = createMockProcessGroup();
final VersionControlInformation oldVersionControl = mock(VersionControlInformation.class);
when(oldVersionControl.getFlowIdentifier()).thenReturn("old-flow-id");

final AtomicReference<VersionControlInformation> liveVersionControl = new AtomicReference<>(oldVersionControl);
when(targetGroup.getVersionControlInformation()).thenAnswer(invocation -> liveVersionControl.get());
doAnswer(invocation -> {
liveVersionControl.set(null);
return null;
}).when(targetGroup).disconnectVersionControl();

final VersionedProcessGroup proposed = new VersionedProcessGroup();
proposed.setIdentifier(SNAPSHOT_ROOT_ID);
proposed.setProcessors(Set.of(createMinimalVersionedProcessor()));

final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposed);

final VersionedExternalFlowMetadata metadata = new VersionedExternalFlowMetadata();
metadata.setFlowIdentifier(INCOMING_FLOW_ID);
incoming.setMetadata(metadata);

mockMigratingProcessorIn(targetGroup);

synchronizer.synchronize(targetGroup, incoming, synchronizationOptions);

assertNull(targetGroup.getVersionControlInformation());
final String expectedId = expectedMigrationServiceId(INCOMING_FLOW_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void migrationInChildWithoutOwnFlowUsesChildVersionedId() {
final ProcessGroup parentGroup = createMockProcessGroup();
final ProcessGroup childGroup = createMockProcessGroup();
when(childGroup.getIdentifier()).thenReturn(LOCAL_CHILD_ID);
when(childGroup.getParent()).thenReturn(parentGroup);
when(childGroup.getVersionedComponentId()).thenReturn(Optional.of(CHILD_GROUP_ID));
when(parentGroup.getProcessGroups()).thenReturn(Set.of(childGroup));

final VersionedProcessGroup proposedChild = new VersionedProcessGroup();
proposedChild.setIdentifier(CHILD_GROUP_ID);
proposedChild.setProcessors(Set.of(createMinimalVersionedProcessor()));

final VersionedProcessGroup proposedParent = new VersionedProcessGroup();
proposedParent.setIdentifier(PARENT_GROUP_ID);
proposedParent.setProcessGroups(Set.of(proposedChild));

final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposedParent);

final VersionedExternalFlowMetadata metadata = new VersionedExternalFlowMetadata();
metadata.setFlowIdentifier(PARENT_FLOW_ID);
incoming.setMetadata(metadata);

mockMigratingProcessorIn(childGroup);

synchronizer.synchronize(parentGroup, incoming, synchronizationOptions);

final String expectedId = expectedMigrationServiceId(CHILD_GROUP_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void migrationInIndependentlyVersionedChildUsesChildFlowId() {
final ProcessGroup parentGroup = createMockProcessGroup();
final ProcessGroup childGroup = createMockProcessGroup();
when(childGroup.getIdentifier()).thenReturn(LOCAL_CHILD_ID);
when(childGroup.getParent()).thenReturn(parentGroup);
when(childGroup.getVersionedComponentId()).thenReturn(Optional.of(CHILD_PLACEMENT_ID));
when(parentGroup.getProcessGroups()).thenReturn(Set.of(childGroup));

final AtomicReference<VersionControlInformation> childVersionControl = new AtomicReference<>();
when(childGroup.getVersionControlInformation()).thenAnswer(invocation -> childVersionControl.get());
doAnswer(invocation -> {
childVersionControl.set(invocation.getArgument(0));
return null;
}).when(childGroup).setVersionControlInformation(any(), anyMap());

when(flowManager.getFlowRegistryClient(REGISTRY_ID)).thenReturn(mock(FlowRegistryClientNode.class));
final VersionedFlowCoordinates coordinates = new VersionedFlowCoordinates();
coordinates.setRegistryId(REGISTRY_ID);
coordinates.setBucketId("bucket");
coordinates.setFlowId(CHILD_FLOW_ID);
coordinates.setVersion("1");

final VersionedProcessGroup proposedChild = new VersionedProcessGroup();
proposedChild.setIdentifier(CHILD_PLACEMENT_ID);
proposedChild.setVersionedFlowCoordinates(coordinates);
proposedChild.setProcessors(Set.of(createMinimalVersionedProcessor()));

final VersionedProcessGroup proposedParent = new VersionedProcessGroup();
proposedParent.setIdentifier(PARENT_GROUP_ID);
proposedParent.setProcessGroups(Set.of(proposedChild));

final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposedParent);

final VersionedExternalFlowMetadata metadata = new VersionedExternalFlowMetadata();
metadata.setFlowIdentifier(PARENT_FLOW_ID);
incoming.setMetadata(metadata);

mockMigratingProcessorIn(childGroup);

synchronizer.synchronize(parentGroup, incoming, synchronizationOptions);

assertNotNull(childGroup.getVersionControlInformation());
assertEquals(CHILD_FLOW_ID, childGroup.getVersionControlInformation().getFlowIdentifier());
final String expectedId = expectedMigrationServiceId(CHILD_FLOW_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void pasteIntoVersionControlledGroupUsesDestinationFlowId() {
final ProcessGroup destination = createMockProcessGroup();
when(destination.getVersionedComponentId()).thenReturn(Optional.of(DESTINATION_GROUP_ID));

final VersionControlInformation versionControl = mock(VersionControlInformation.class);
when(versionControl.getFlowIdentifier()).thenReturn(DESTINATION_FLOW_ID);
when(destination.getVersionControlInformation()).thenReturn(versionControl);

mockMigratingProcessorIn(destination);

synchronizer.addVersionedComponentsToProcessGroup(destination, legacyProcessorAdditions(), synchronizationOptions);

final String expectedId = expectedMigrationServiceId(DESTINATION_FLOW_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void pasteIntoGroupWithoutOwnFlowUsesDestinationVersionedId() {
final ProcessGroup destination = createMockProcessGroup();
when(destination.getVersionedComponentId()).thenReturn(Optional.of(DESTINATION_GROUP_ID));
mockMigratingProcessorIn(destination);

synchronizer.addVersionedComponentsToProcessGroup(destination, legacyProcessorAdditions(), synchronizationOptions);

final String expectedId = expectedMigrationServiceId(DESTINATION_GROUP_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void pasteWithoutDestinationIdentityLeavesServiceUnversioned() {
final ProcessGroup destination = createMockProcessGroup();
mockMigratingProcessorIn(destination);

synchronizer.addVersionedComponentsToProcessGroup(destination, legacyProcessorAdditions(), synchronizationOptions);

verify(destination).addControllerService(controllerServiceNode);
verify(controllerServiceNode, never()).setVersionedComponentId(any());
}

private void mockMigratingProcessorIn(final ProcessGroup owner) {
final ProcessorNode processor = createMockProcessor();
when(processor.getParentProcessGroup()).thenReturn(Optional.of(owner));
when(flowManager.createProcessor(any(), any(), any(), eq(true))).thenReturn(processor);

final ControllerServiceCreationDetails details = mock(ControllerServiceCreationDetails.class);
when(details.serviceIdentifier()).thenReturn("new-service");
when(details.type()).thenReturn(SERVICE_TYPE);
when(details.serviceBundleCoordinate()).thenReturn(bundleCoordinate);
when(details.serviceProperties()).thenReturn(SERVICE_PROPERTIES);
when(controllerServiceNode.getPropertyDescriptor("mode")).thenReturn(new PropertyDescriptor.Builder().name("mode").build());

doAnswer(invocation -> {
final ControllerServiceFactory serviceFactory = invocation.getArgument(1);
serviceFactory.create(details);
return null;
}).when(processor).migrateConfiguration(anyMap(), any(ControllerServiceFactory.class));
}

private VersionedComponentAdditions legacyProcessorAdditions() {
final VersionedProcessor processor = createMinimalVersionedProcessor();
processor.setGroupIdentifier("source-group-not-destination");
return new VersionedComponentAdditions.Builder().setProcessors(Set.of(processor)).build();
}

private String expectedMigrationServiceId(final String owningGroupIdentity) {
final FlowManager expectedFlowManager = mock(FlowManager.class);
final ControllerServiceNode expectedService = mock(ControllerServiceNode.class);
when(expectedService.getPropertyDescriptor("mode")).thenReturn(new PropertyDescriptor.Builder().name("mode").build());
when(expectedFlowManager.createControllerService(eq(SERVICE_TYPE), anyString(), any(), anySet(), eq(true), eq(true), eq(null))).thenReturn(expectedService);

final ComponentNode creator = mock(ComponentNode.class);
when(creator.getParentProcessGroup()).thenReturn(Optional.of(mock(ProcessGroup.class)));
final StandardControllerServiceFactory factory = new StandardControllerServiceFactory(
mock(ExtensionManager.class), expectedFlowManager, mock(ControllerServiceProvider.class), creator, owningGroupIdentity);
final ControllerServiceCreationDetails details = mock(ControllerServiceCreationDetails.class);
when(details.serviceIdentifier()).thenReturn("expected-service");
when(details.type()).thenReturn(SERVICE_TYPE);
when(details.serviceBundleCoordinate()).thenReturn(bundleCoordinate);
when(details.serviceProperties()).thenReturn(SERVICE_PROPERTIES);

factory.create(details);

final ArgumentCaptor<String> versionedId = ArgumentCaptor.forClass(String.class);
verify(expectedService).setVersionedComponentId(versionedId.capture());
return versionedId.getValue();
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

With the IDs assigned in the synchronizer, please rework these tests around the contract: the same inputs give the same ID on every instance, and different inputs give different IDs. Compare the IDs captured from setVersionedComponentId across runs, instead of rebuilding the expected value with a second factory. expectedMigrationServiceId can then be deleted.

  • Keep the synchronized-group test and the two child-group tests. Assert that the ID changes when the flow ID or child versioned ID changes, not that it equals a value rebuilt here.

  • Keep one paste test. The other two cover the same branches of determineProcessGroupIdentity as the child-group tests, and the factory no longer has a "no identity" case to test.

  • Add one test for migration order, which is the actual bug:

    • Set up two processors in the same group. Each migration creates a service of the same type that differs only in a sensitive value.
    • Pass the sensitive value under an old name that the mock service reports, after its own migration, under a sensitive descriptor with the current name. That is what the AWS and proxy services do.
    • Use a LinkedHashSet for proposed.getProcessors() so you can run the sync once with the processors in one order and once in the other.
    • Assert that each processor's service gets the same ID in both runs and that the two IDs differ.

    This test fails with the current first-wins rule.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests compare IDs between runs, and expectedMigrationServiceId is gone. The order test runs in both directions with a LinkedHashSet. It uses Parameter-referenced secrets plus one inline secret rather than an old property name, because the rename happens in the service's own migration, which the system test covers.

Comment on lines +796 to +918
@Nested
class MissingControllerServiceRemoval {

private static final String ROOT_GROUP_ID = "root-group-id";
private static final String PARENT_GROUP_ID = "parent-group-id";
private static final String CHILD_GROUP_ID = "child-group-id";
private static final String VERSIONED_CHILD_GROUP_ID = "versioned-child-group-id";

@Test
void synchronizationKeepsMissingServicesReachableFromRemainingProcessor() {
final ProcessGroup targetGroup = createMockProcessGroup();
final ControllerServiceNode directlyReferenced = createMockControllerService();
final ControllerServiceNode referencedByDirect = createMockControllerService();
final ControllerServiceNode referencedByIndirect = createMockControllerService();
setReferences(directlyReferenced, createMockProcessor());
setReferences(referencedByDirect, directlyReferenced);
setReferences(referencedByIndirect, referencedByDirect);
when(targetGroup.getControllerServices(false)).thenReturn(Set.of(directlyReferenced, referencedByDirect, referencedByIndirect));

synchronizer.synchronize(targetGroup, incomingFlowWithoutServices(), synchronizationOptions);

verify(controllerServiceProvider, never()).removeControllerService(directlyReferenced);
verify(controllerServiceProvider, never()).removeControllerService(referencedByDirect);
verify(controllerServiceProvider, never()).removeControllerService(referencedByIndirect);
}

@Test
void synchronizationRemovesMissingServicesReferencedOnlyByOtherMissingServices() {
final ProcessGroup targetGroup = createMockProcessGroup();
final ControllerServiceNode cycleFirst = createMockControllerService();
final ControllerServiceNode cycleSecond = createMockControllerService();
final ControllerServiceNode unreferenced = createMockControllerService();
setReferences(cycleFirst, cycleSecond);
setReferences(cycleSecond, cycleFirst);
when(targetGroup.getControllerServices(false)).thenReturn(Set.of(cycleFirst, cycleSecond, unreferenced));

synchronizer.synchronize(targetGroup, incomingFlowWithoutServices(), synchronizationOptions);

verify(controllerServiceProvider).removeControllerService(cycleFirst);
verify(controllerServiceProvider).removeControllerService(cycleSecond);
verify(controllerServiceProvider).removeControllerService(unreferenced);
}

@Test
void synchronizationKeepsMissingServiceReferencedAfterPropertyMigration() {
final ProcessGroup targetGroup = createMockProcessGroup();
final ControllerServiceNode service = createMockControllerService();
when(targetGroup.getControllerServices(false)).thenReturn(Set.of(service));

final ProcessorNode processor = createMockProcessor();
when(processor.getParentProcessGroup()).thenReturn(Optional.of(targetGroup));
when(flowManager.createProcessor(any(), any(), any(), eq(true))).thenReturn(processor);
doAnswer(invocation -> service.getReferences().getReferencingComponents().add(processor))
.when(processor).migrateConfiguration(anyMap(), any(ControllerServiceFactory.class));

final VersionedProcessGroup proposed = new VersionedProcessGroup();
proposed.setIdentifier(ROOT_GROUP_ID);
proposed.setProcessors(Set.of(createMinimalVersionedProcessor()));
final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposed);

synchronizer.synchronize(targetGroup, incoming, synchronizationOptions);

verify(controllerServiceProvider, never()).removeControllerService(service);
}

@Test
void synchronizationRemovesMissingServicesOnlyInSynchronizedChildGroups() {
final ProcessGroup parentGroup = createMockProcessGroup();
final ProcessGroup childGroup = createMockProcessGroup();
when(childGroup.getVersionedComponentId()).thenReturn(Optional.of(CHILD_GROUP_ID));
final ProcessGroup versionedChildGroup = createMockProcessGroup();
when(versionedChildGroup.getVersionedComponentId()).thenReturn(Optional.of(VERSIONED_CHILD_GROUP_ID));
when(parentGroup.getProcessGroups()).thenReturn(Set.of(childGroup, versionedChildGroup));

final ControllerServiceNode childService = createMockControllerService();
when(childGroup.getControllerServices(false)).thenReturn(Set.of(childService));
final ControllerServiceNode versionedChildService = createMockControllerService();
when(versionedChildGroup.getControllerServices(false)).thenReturn(Set.of(versionedChildService));

final ProcessorNode versionedChildProcessor = createMappableProcessor(versionedChildGroup);
when(versionedChildGroup.getProcessors()).thenReturn(Set.of(versionedChildProcessor));
final ControllerServiceNode parentService = createMockControllerService();
setReferences(parentService, versionedChildProcessor);
when(parentGroup.getControllerServices(false)).thenReturn(Set.of(parentService));

final VersionedFlowCoordinates coordinates = new VersionedFlowCoordinates();
coordinates.setRegistryId("registry-id");
coordinates.setBucketId("bucket");
coordinates.setFlowId("child-flow-id");
coordinates.setVersion("1");

final VersionedProcessGroup proposedChild = new VersionedProcessGroup();
proposedChild.setIdentifier(CHILD_GROUP_ID);
final VersionedProcessGroup proposedVersionedChild = new VersionedProcessGroup();
proposedVersionedChild.setIdentifier(VERSIONED_CHILD_GROUP_ID);
proposedVersionedChild.setVersionedFlowCoordinates(coordinates);
final VersionedProcessGroup proposedParent = new VersionedProcessGroup();
proposedParent.setIdentifier(PARENT_GROUP_ID);
proposedParent.setProcessGroups(Set.of(proposedChild, proposedVersionedChild));
final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposedParent);

final FlowSynchronizationOptions parentOnlyOptions = FlowSynchronizationOptions.Builder.from(synchronizationOptions)
.updateDescendantVersionedFlows(false)
.build();

synchronizer.synchronize(parentGroup, incoming, parentOnlyOptions);

verify(controllerServiceProvider).removeControllerService(childService);
verify(controllerServiceProvider, never()).removeControllerService(versionedChildService);
verify(controllerServiceProvider, never()).removeControllerService(parentService);
}

private VersionedExternalFlow incomingFlowWithoutServices() {
final VersionedProcessGroup proposed = new VersionedProcessGroup();
proposed.setIdentifier(ROOT_GROUP_ID);

final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposed);
return incoming;
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

These can come down to two tests:

  • Fold the chain case (line 805) and the cycle case (line 823) into the existing testControllerServiceRemoved (line 1844), which this PR already strengthens.
    • Its "unreferenced service is removed" case duplicates the unreferenced service in the cycle test, so drop one of them.
    • Its last verify (line 1878) repeats line 1856.
  • Keep synchronizationKeepsMissingServiceReferencedAfterPropertyMigration, which is the real regression test for the Jira. Strengthen it with a second service that migration creates and nothing references, and verify that it isn't removed. That covers the failure described in my comment on line 447 of the synchronizer.
  • synchronizationRemovesMissingServicesOnlyInSynchronizedChildGroups can be removed. Once missing services are recorded in the per-group synchronize, it only checks behavior that existed before this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Folded and strengthened as suggested; the child-group test is removed.

return;
}

storeService.append("row-" + rowCounter.getAndIncrement());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

This processor has no run schedule, so it writes the service's local state on every run, nonstop, for the whole test. The created value the service writes when it's first enabled already proves the service wasn't recreated. Please drop the row counting:

  • onTrigger can do nothing.
  • Remove append from StoreService and StateBackedStoreService, along with the rowCount and lastRow keys.
  • Remove countRows and the waits on lines 207 and 235-236 of MigrationCreatedControllerServiceVersioningIT.
  • The "still present" check in readCreatedTimestamp can also go, because both callers have just confirmed the service exists.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Row counting removed; onTrigger is a no-op.

Path registryDirectory;

@Test
void testStartupAndImportMigratedServicesSurviveFlowVersionUpdates() throws NiFiClientException, IOException, InterruptedException {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Claude Opus 5.5]

This test covers the right paths: startup and import migration, then updates with and without the service. But it can't catch either problem described in the review:

  • The migration passes one value that isn't sensitive and keeps its name, so every instance hashes the same input.
  • There is only one service per group (the processor added in V2 has no Store Name, so it creates nothing), so two services never compete for an ID.

Please strengthen this test rather than adding a new one:

  1. Add a secret that the service renames, like the AWS processors do.

    • Pre-upgrade MigrateToControllerService: add a required, sensitive Store Password.
    • Post-upgrade MigrateToControllerService: pass it as "store-password".
    • StateBackedStoreService: declare a required, sensitive Store Password and rename store-password to it in migrateProperties.
    • snapshot.json: add the descriptor with no value.
    • Before the upgrade, set different passwords on the author and on the startup consumer. Set the import consumer's password on its service after import.

    Because the property is required, the existing "enabled" checks also show that each secret survives the update. With the current code this fails on line 111.

  2. Add a second migrating processor with the same Store Name and a different password.

    • Replace the "exactly one service" checks (waitForSingleStoreService and line 220) with checks for each processor: the same service instance ID and created timestamp before and after each update.
    • Check that the two services have different versioned IDs.
    • Check that each consumer processor's service has the same versioned ID as the author's service for the same processor.

    This shows that each processor keeps its own service and secret.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Strengthened in the same single method: a required password renamed by the service, a second processor with shared and separate services, and a consumer that skipped a version. One difference: instead of a different inline password per instance, the legacy snapshot references #{password}, because a service with an inline secret stays unversioned. Secret separation is covered by the flows where processors use different secrets.

Assign versioned IDs to Controller Services created by property migration once all migrations have run, so that the result does not depend on migration order and reflects each service's own migration. A reference to another Controller Service contributes that service's versioned ID. Services with inline sensitive values, unresolvable or external references, or duplicate IDs stay unversioned as before. Missing services are recorded per group and removed after migration unless still referenced.
@awelless
awelless force-pushed the NIFI-16310-deterministic-migration-service-ids branch from 8b60216 to f778214 Compare November 13, 2026 13:21

@awelless awelless left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @markap14. I followed the restructure: the factory only records the services it creates, and the synchronizer assigns IDs once, after all migrations. I deviated on how the ID is built.

Referenced IDs instead of referrer IDs

A property that references another service contributes that service's versioned ID, including when migration created both services.

We have to support consumers that skip versions: there is no way to make a consumer update to the then-latest version before it upgrades NiFi. Referrer IDs depend on which components reference the service when it is created, and that differs between versions. For example, the author creates the service at V2, where processors A and B share it, and a consumer updates from V1 straight to V3. With referrer IDs, the two get different IDs and the consumer's service is replaced; with referenced IDs, they match. The system test covers this case.

Inline secrets keep the service unversioned

Parameter references in sensitive properties are hashed like any other value. A service with an inline secret stays unversioned.

If the secret were left out of the hash, services that differ only in their secret would get the same ID and could be matched to each other. Because a service's ID includes the IDs of the services it references, that wrong match would also spread to every service that references it. Inline secrets aren't saved to the registry, so these services behave as today. AWS and proxy services that use Parameters now keep their identity.

No regressions are introduced: the behavior is the same as today for services with inline secrets, and more robust for services without them.


final Map<String, String> sortedProperties = new TreeMap<>();
for (final Map.Entry<String, String> property : creationDetails.serviceProperties().entrySet()) {
if (!serviceNode.getPropertyDescriptor(property.getKey()).isSensitive()) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved to the synchronizer, which reads properties after the service's own migration, so renamed secrets are recognized. Instead of skipping sensitive values, a Parameter reference is hashed and an inline secret leaves the service unversioned (see the top-level comment).

Comment on lines +116 to +127
final String versionedId = generateVersionedId(creationDetails, serviceNode);
if (versionedId != null) {
final Set<ControllerServiceNode> groupControllerServices = group.map(processGroup -> processGroup.getControllerServices(false)).orElse(Collections.emptySet());
final boolean occupied = groupControllerServices.stream()
.map(ControllerServiceNode::getVersionedComponentId)
.flatMap(Optional::stream)
.anyMatch(versionedId::equals);

if (!occupied) {
serviceNode.setVersionedComponentId(versionedId);
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The factory now only records created services, the nested factory shares the collection, and the ID code is gone. One difference: the service is recorded right after creation rather than before its migration specifically, since the order no longer matters once IDs are computed after all migrations.

Comment on lines 428 to 439
final VersionedExternalFlowMetadata metadata = versionedExternalFlow.getMetadata();
final String flowIdentifier = metadata == null ? null : metadata.getFlowIdentifier();
for (final CreatedOrModifiedExtension createdOrModifiedExtension : createdAndModifiedExtensions) {
final ComponentNode extension = createdOrModifiedExtension.extension();
final Map<String, String> originalPropertyValues = createdOrModifiedExtension.propertyValues();

final String owningGroupIdentity = getOwningProcessGroupIdentity(extension, group, flowIdentifier);
final ControllerServiceFactory serviceFactory = new StandardControllerServiceFactory(context.getExtensionManager(), context.getFlowManager(),
context.getControllerServiceProvider(), extension);
context.getControllerServiceProvider(), extension, owningGroupIdentity);

if (extension instanceof final ProcessorNode processor) {
processor.migrateConfiguration(originalPropertyValues, serviceFactory);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is now one shared method for synchronize and paste. It differs from your outline in three ways:

  • referenced IDs replace referrer IDs (see the top-level comment);
  • instead of a counter, created services that would share an ID within a group stay unversioned;
  • missing services are removed before IDs are assigned, so a created service can take the ID of the one it replaces.

Comment on lines 316 to 326
final String groupIdentity = determineProcessGroupIdentity(group);
for (final CreatedOrModifiedExtension createdOrModifiedExtension : createdAndModifiedExtensions) {
final ComponentNode extension = createdOrModifiedExtension.extension();
final Map<String, String> originalPropertyValues = createdOrModifiedExtension.propertyValues();

final String owningGroupIdentity = getOwningProcessGroupIdentity(extension, group, groupIdentity);
final ControllerServiceFactory serviceFactory = new StandardControllerServiceFactory(context.getExtensionManager(), context.getFlowManager(),
context.getControllerServiceProvider(), extension);
context.getControllerServiceProvider(), extension, owningGroupIdentity);

if (extension instanceof final ProcessorNode processor) {
processor.migrateConfiguration(originalPropertyValues, serviceFactory);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Paste now uses the shared method. It also migrates reporting tasks, as synchronize does.

}
}

removeMissingControllerServices(group, versionedExternalFlow.getFlowContents());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented as you suggested, with your loop. One addition: the lookup by versioned ID skips services recorded as missing, so a reference resolves to the service that replaces them.

Comment on lines +158 to +294
@Nested
class VersionedIdAssignment {
private static final String ENDPOINT_PROPERTY = "Endpoint";
private static final String ENDPOINT_PARAMETER = "#{endpoint}";
private static final String MODE_PROPERTY = "Mode";
private static final String READ_MODE = "read";
private static final String PASSWORD_PROPERTY = "Password";

private static final String OWNING_GROUP_IDENTITY = "shared-version";

private static final String CONSUMER_GROUP_ID = "consumer-instance";

@Test
void testVersionedIdentityDependsOnSuppliedIdentityTypeAndProperties() {
final Map<String, String> properties = new LinkedHashMap<>();
properties.put(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER);
properties.put(MODE_PROPERTY, READ_MODE);
final String first = createServiceAndGetVersionedId("author-instance", OWNING_GROUP_IDENTITY, IMPL_CLASS, properties);

final Map<String, String> reordered = new LinkedHashMap<>();
reordered.put(MODE_PROPERTY, READ_MODE);
reordered.put(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER);
final String second = createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, reordered);

assertNotNull(first);
assertEquals(first, second);
assertNotEquals(first, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, "different-version", IMPL_CLASS, properties));
assertNotEquals(first, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, "AnotherService", properties));
assertNotEquals(first, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, Map.of()));
}

@Test
void testSensitiveValuesDoNotAffectVersionedIdentity() {
final Map<String, String> authorProperties = Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER, PASSWORD_PROPERTY, "author-password");
final Map<String, String> consumerProperties = Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER, PASSWORD_PROPERTY, "consumer-password");
final String authorId = createServiceAndGetVersionedId("author-instance", OWNING_GROUP_IDENTITY, IMPL_CLASS, authorProperties);
final String consumerId = createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, consumerProperties);

assertEquals(authorId, consumerId);
assertEquals(authorId, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER)));
assertNotEquals(authorId, createServiceAndGetVersionedId(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS,
Map.of(ENDPOINT_PROPERTY, "another-endpoint", PASSWORD_PROPERTY, "consumer-password")));
assertNotEquals(factory.determineServiceId(IMPL_CLASS, authorProperties), factory.determineServiceId(IMPL_CLASS, consumerProperties));
}

@Test
void testOccupiedVersionedIdentityLeavesNewServiceUnversioned() {
final Map<String, String> properties = Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER);
final String occupiedId = createServiceAndGetVersionedId("author-instance", OWNING_GROUP_IDENTITY, IMPL_CLASS, properties);
final ControllerServiceNode existingService = mock(ControllerServiceNode.class);
when(existingService.getVersionedComponentId()).thenReturn(Optional.of(occupiedId));

final ControllerServiceNode newService = createService(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, properties, Set.of(existingService));

verify(newService, never()).setVersionedComponentId(any());
verify(existingService, never()).setVersionedComponentId(any());
verify(newService).migrateConfiguration(eq(properties), any());
}

@Test
void testUnversionedAndDifferentVersionedServicesDoNotOccupyIdentity() {
final Map<String, String> properties = Map.of(ENDPOINT_PROPERTY, ENDPOINT_PARAMETER);
final String expectedId = createServiceAndGetVersionedId("author-instance", OWNING_GROUP_IDENTITY, IMPL_CLASS, properties);
final ControllerServiceNode unversionedService = mock(ControllerServiceNode.class);
when(unversionedService.getVersionedComponentId()).thenReturn(Optional.empty());
final ControllerServiceNode differentlyVersionedService = mock(ControllerServiceNode.class);
when(differentlyVersionedService.getVersionedComponentId()).thenReturn(Optional.of("another-versioned-id"));

final ControllerServiceNode newService = createService(CONSUMER_GROUP_ID, OWNING_GROUP_IDENTITY, IMPL_CLASS, properties,
Set.of(unversionedService, differentlyVersionedService));

verify(newService).setVersionedComponentId(expectedId);
verify(unversionedService, never()).setVersionedComponentId(any());
verify(differentlyVersionedService, never()).setVersionedComponentId(any());
}

@Test
void testCreationWithoutOwningGroupIdentity() {
final ComponentNode creator = mock(ComponentNode.class);
final FlowManager flowManager = mock(FlowManager.class);
final StandardControllerServiceFactory factory = new StandardControllerServiceFactory(
mock(ExtensionManager.class), flowManager, mock(ControllerServiceProvider.class), creator);
final ControllerServiceNode service = mock(ControllerServiceNode.class);
final ControllerServiceCreationDetails details = new ControllerServiceCreationDetails("service-id", IMPL_CLASS,
createCoordinate(LONE_BUNDLE, VERSION_2), Map.of(), ControllerServiceCreationDetails.CreationState.SERVICE_TO_BE_CREATED);
when(flowManager.createControllerService(eq(IMPL_CLASS), anyString(), any(), any(), eq(true), eq(true), eq(null))).thenReturn(service);
when(creator.getParentProcessGroup()).thenReturn(Optional.empty());

factory.create(details);

verify(flowManager).addRootControllerService(service);
verify(service, never()).setVersionedComponentId(any());

final ProcessGroup group = mock(ProcessGroup.class);
when(creator.getParentProcessGroup()).thenReturn(Optional.of(group));

factory.create(details);

verify(group).addControllerService(service);
verify(service, never()).setVersionedComponentId(any());
}

private String createServiceAndGetVersionedId(final String localGroupId, final String owningGroupIdentity, final String type, final Map<String, String> properties) {
final ControllerServiceNode service = createService(localGroupId, owningGroupIdentity, type, properties, Set.of());
final ArgumentCaptor<String> versionedId = ArgumentCaptor.forClass(String.class);
verify(service).setVersionedComponentId(versionedId.capture());
return versionedId.getValue();
}

private ControllerServiceNode createService(final String localGroupId, final String owningGroupIdentity, final String type,
final Map<String, String> properties, final Set<ControllerServiceNode> existingServices) {
final ComponentNode component = mock(ComponentNode.class);
final ProcessGroup group = mock(ProcessGroup.class);
when(component.getParentProcessGroup()).thenReturn(Optional.of(group));
when(component.getProcessGroupIdentifier()).thenReturn(localGroupId);
final FlowManager manager = mock(FlowManager.class);
final ControllerServiceNode service = mock(ControllerServiceNode.class);
when(service.getPropertyDescriptor(anyString())).thenAnswer(invocation -> {
final String name = invocation.getArgument(0);
return new PropertyDescriptor.Builder().name(name).sensitive(PASSWORD_PROPERTY.equals(name)).build();
});
final Set<ControllerServiceNode> groupServices = new HashSet<>(existingServices);
groupServices.add(service);
when(group.getControllerServices(false)).thenReturn(groupServices);
when(manager.createControllerService(eq(type), anyString(), any(), any(), eq(true), eq(true), eq(null))).thenReturn(service);

final StandardControllerServiceFactory serviceFactory = new StandardControllerServiceFactory(
mock(ExtensionManager.class), manager, mock(ControllerServiceProvider.class), component, owningGroupIdentity);
final String instanceId = serviceFactory.determineServiceId(type, properties);
final ControllerServiceCreationDetails details = new ControllerServiceCreationDetails(instanceId, type, createCoordinate(LONE_BUNDLE, VERSION_2), properties,
ControllerServiceCreationDetails.CreationState.SERVICE_TO_BE_CREATED);
serviceFactory.create(details);

verify(service).setProperties(properties);
return service;
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed; the file matches main.

Comment on lines +574 to +794
@Nested
class MigrationCreatedControllerService {

private static final String SNAPSHOT_ROOT_ID = "snapshot-root-id";
private static final String LOCAL_CHILD_ID = "local-child";
private static final String CHILD_GROUP_ID = "child-group-id";
private static final String PARENT_GROUP_ID = "parent-group-id";
private static final String CHILD_PLACEMENT_ID = "child-placement-id";
private static final String DESTINATION_GROUP_ID = "destination-group-id";

private static final String INCOMING_FLOW_ID = "incoming-flow-id";
private static final String DESTINATION_FLOW_ID = "destination-flow-id";
private static final String PARENT_FLOW_ID = "parent-flow-id";
private static final String CHILD_FLOW_ID = "child-flow-id";

private static final String REGISTRY_ID = "registry-id";
private static final String SERVICE_TYPE = TestControllerService.class.getName();
private static final Map<String, String> SERVICE_PROPERTIES = Map.of("mode", "read");

@Test
void migrationInSynchronizedGroupUsesIncomingFlowIdAfterVersionControlIsCleared() {
final ProcessGroup targetGroup = createMockProcessGroup();
final VersionControlInformation oldVersionControl = mock(VersionControlInformation.class);
when(oldVersionControl.getFlowIdentifier()).thenReturn("old-flow-id");

final AtomicReference<VersionControlInformation> liveVersionControl = new AtomicReference<>(oldVersionControl);
when(targetGroup.getVersionControlInformation()).thenAnswer(invocation -> liveVersionControl.get());
doAnswer(invocation -> {
liveVersionControl.set(null);
return null;
}).when(targetGroup).disconnectVersionControl();

final VersionedProcessGroup proposed = new VersionedProcessGroup();
proposed.setIdentifier(SNAPSHOT_ROOT_ID);
proposed.setProcessors(Set.of(createMinimalVersionedProcessor()));

final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposed);

final VersionedExternalFlowMetadata metadata = new VersionedExternalFlowMetadata();
metadata.setFlowIdentifier(INCOMING_FLOW_ID);
incoming.setMetadata(metadata);

mockMigratingProcessorIn(targetGroup);

synchronizer.synchronize(targetGroup, incoming, synchronizationOptions);

assertNull(targetGroup.getVersionControlInformation());
final String expectedId = expectedMigrationServiceId(INCOMING_FLOW_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void migrationInChildWithoutOwnFlowUsesChildVersionedId() {
final ProcessGroup parentGroup = createMockProcessGroup();
final ProcessGroup childGroup = createMockProcessGroup();
when(childGroup.getIdentifier()).thenReturn(LOCAL_CHILD_ID);
when(childGroup.getParent()).thenReturn(parentGroup);
when(childGroup.getVersionedComponentId()).thenReturn(Optional.of(CHILD_GROUP_ID));
when(parentGroup.getProcessGroups()).thenReturn(Set.of(childGroup));

final VersionedProcessGroup proposedChild = new VersionedProcessGroup();
proposedChild.setIdentifier(CHILD_GROUP_ID);
proposedChild.setProcessors(Set.of(createMinimalVersionedProcessor()));

final VersionedProcessGroup proposedParent = new VersionedProcessGroup();
proposedParent.setIdentifier(PARENT_GROUP_ID);
proposedParent.setProcessGroups(Set.of(proposedChild));

final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposedParent);

final VersionedExternalFlowMetadata metadata = new VersionedExternalFlowMetadata();
metadata.setFlowIdentifier(PARENT_FLOW_ID);
incoming.setMetadata(metadata);

mockMigratingProcessorIn(childGroup);

synchronizer.synchronize(parentGroup, incoming, synchronizationOptions);

final String expectedId = expectedMigrationServiceId(CHILD_GROUP_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void migrationInIndependentlyVersionedChildUsesChildFlowId() {
final ProcessGroup parentGroup = createMockProcessGroup();
final ProcessGroup childGroup = createMockProcessGroup();
when(childGroup.getIdentifier()).thenReturn(LOCAL_CHILD_ID);
when(childGroup.getParent()).thenReturn(parentGroup);
when(childGroup.getVersionedComponentId()).thenReturn(Optional.of(CHILD_PLACEMENT_ID));
when(parentGroup.getProcessGroups()).thenReturn(Set.of(childGroup));

final AtomicReference<VersionControlInformation> childVersionControl = new AtomicReference<>();
when(childGroup.getVersionControlInformation()).thenAnswer(invocation -> childVersionControl.get());
doAnswer(invocation -> {
childVersionControl.set(invocation.getArgument(0));
return null;
}).when(childGroup).setVersionControlInformation(any(), anyMap());

when(flowManager.getFlowRegistryClient(REGISTRY_ID)).thenReturn(mock(FlowRegistryClientNode.class));
final VersionedFlowCoordinates coordinates = new VersionedFlowCoordinates();
coordinates.setRegistryId(REGISTRY_ID);
coordinates.setBucketId("bucket");
coordinates.setFlowId(CHILD_FLOW_ID);
coordinates.setVersion("1");

final VersionedProcessGroup proposedChild = new VersionedProcessGroup();
proposedChild.setIdentifier(CHILD_PLACEMENT_ID);
proposedChild.setVersionedFlowCoordinates(coordinates);
proposedChild.setProcessors(Set.of(createMinimalVersionedProcessor()));

final VersionedProcessGroup proposedParent = new VersionedProcessGroup();
proposedParent.setIdentifier(PARENT_GROUP_ID);
proposedParent.setProcessGroups(Set.of(proposedChild));

final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposedParent);

final VersionedExternalFlowMetadata metadata = new VersionedExternalFlowMetadata();
metadata.setFlowIdentifier(PARENT_FLOW_ID);
incoming.setMetadata(metadata);

mockMigratingProcessorIn(childGroup);

synchronizer.synchronize(parentGroup, incoming, synchronizationOptions);

assertNotNull(childGroup.getVersionControlInformation());
assertEquals(CHILD_FLOW_ID, childGroup.getVersionControlInformation().getFlowIdentifier());
final String expectedId = expectedMigrationServiceId(CHILD_FLOW_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void pasteIntoVersionControlledGroupUsesDestinationFlowId() {
final ProcessGroup destination = createMockProcessGroup();
when(destination.getVersionedComponentId()).thenReturn(Optional.of(DESTINATION_GROUP_ID));

final VersionControlInformation versionControl = mock(VersionControlInformation.class);
when(versionControl.getFlowIdentifier()).thenReturn(DESTINATION_FLOW_ID);
when(destination.getVersionControlInformation()).thenReturn(versionControl);

mockMigratingProcessorIn(destination);

synchronizer.addVersionedComponentsToProcessGroup(destination, legacyProcessorAdditions(), synchronizationOptions);

final String expectedId = expectedMigrationServiceId(DESTINATION_FLOW_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void pasteIntoGroupWithoutOwnFlowUsesDestinationVersionedId() {
final ProcessGroup destination = createMockProcessGroup();
when(destination.getVersionedComponentId()).thenReturn(Optional.of(DESTINATION_GROUP_ID));
mockMigratingProcessorIn(destination);

synchronizer.addVersionedComponentsToProcessGroup(destination, legacyProcessorAdditions(), synchronizationOptions);

final String expectedId = expectedMigrationServiceId(DESTINATION_GROUP_ID);
verify(controllerServiceNode).setVersionedComponentId(expectedId);
}

@Test
void pasteWithoutDestinationIdentityLeavesServiceUnversioned() {
final ProcessGroup destination = createMockProcessGroup();
mockMigratingProcessorIn(destination);

synchronizer.addVersionedComponentsToProcessGroup(destination, legacyProcessorAdditions(), synchronizationOptions);

verify(destination).addControllerService(controllerServiceNode);
verify(controllerServiceNode, never()).setVersionedComponentId(any());
}

private void mockMigratingProcessorIn(final ProcessGroup owner) {
final ProcessorNode processor = createMockProcessor();
when(processor.getParentProcessGroup()).thenReturn(Optional.of(owner));
when(flowManager.createProcessor(any(), any(), any(), eq(true))).thenReturn(processor);

final ControllerServiceCreationDetails details = mock(ControllerServiceCreationDetails.class);
when(details.serviceIdentifier()).thenReturn("new-service");
when(details.type()).thenReturn(SERVICE_TYPE);
when(details.serviceBundleCoordinate()).thenReturn(bundleCoordinate);
when(details.serviceProperties()).thenReturn(SERVICE_PROPERTIES);
when(controllerServiceNode.getPropertyDescriptor("mode")).thenReturn(new PropertyDescriptor.Builder().name("mode").build());

doAnswer(invocation -> {
final ControllerServiceFactory serviceFactory = invocation.getArgument(1);
serviceFactory.create(details);
return null;
}).when(processor).migrateConfiguration(anyMap(), any(ControllerServiceFactory.class));
}

private VersionedComponentAdditions legacyProcessorAdditions() {
final VersionedProcessor processor = createMinimalVersionedProcessor();
processor.setGroupIdentifier("source-group-not-destination");
return new VersionedComponentAdditions.Builder().setProcessors(Set.of(processor)).build();
}

private String expectedMigrationServiceId(final String owningGroupIdentity) {
final FlowManager expectedFlowManager = mock(FlowManager.class);
final ControllerServiceNode expectedService = mock(ControllerServiceNode.class);
when(expectedService.getPropertyDescriptor("mode")).thenReturn(new PropertyDescriptor.Builder().name("mode").build());
when(expectedFlowManager.createControllerService(eq(SERVICE_TYPE), anyString(), any(), anySet(), eq(true), eq(true), eq(null))).thenReturn(expectedService);

final ComponentNode creator = mock(ComponentNode.class);
when(creator.getParentProcessGroup()).thenReturn(Optional.of(mock(ProcessGroup.class)));
final StandardControllerServiceFactory factory = new StandardControllerServiceFactory(
mock(ExtensionManager.class), expectedFlowManager, mock(ControllerServiceProvider.class), creator, owningGroupIdentity);
final ControllerServiceCreationDetails details = mock(ControllerServiceCreationDetails.class);
when(details.serviceIdentifier()).thenReturn("expected-service");
when(details.type()).thenReturn(SERVICE_TYPE);
when(details.serviceBundleCoordinate()).thenReturn(bundleCoordinate);
when(details.serviceProperties()).thenReturn(SERVICE_PROPERTIES);

factory.create(details);

final ArgumentCaptor<String> versionedId = ArgumentCaptor.forClass(String.class);
verify(expectedService).setVersionedComponentId(versionedId.capture());
return versionedId.getValue();
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests compare IDs between runs, and expectedMigrationServiceId is gone. The order test runs in both directions with a LinkedHashSet. It uses Parameter-referenced secrets plus one inline secret rather than an old property name, because the rename happens in the service's own migration, which the system test covers.

Comment on lines +796 to +918
@Nested
class MissingControllerServiceRemoval {

private static final String ROOT_GROUP_ID = "root-group-id";
private static final String PARENT_GROUP_ID = "parent-group-id";
private static final String CHILD_GROUP_ID = "child-group-id";
private static final String VERSIONED_CHILD_GROUP_ID = "versioned-child-group-id";

@Test
void synchronizationKeepsMissingServicesReachableFromRemainingProcessor() {
final ProcessGroup targetGroup = createMockProcessGroup();
final ControllerServiceNode directlyReferenced = createMockControllerService();
final ControllerServiceNode referencedByDirect = createMockControllerService();
final ControllerServiceNode referencedByIndirect = createMockControllerService();
setReferences(directlyReferenced, createMockProcessor());
setReferences(referencedByDirect, directlyReferenced);
setReferences(referencedByIndirect, referencedByDirect);
when(targetGroup.getControllerServices(false)).thenReturn(Set.of(directlyReferenced, referencedByDirect, referencedByIndirect));

synchronizer.synchronize(targetGroup, incomingFlowWithoutServices(), synchronizationOptions);

verify(controllerServiceProvider, never()).removeControllerService(directlyReferenced);
verify(controllerServiceProvider, never()).removeControllerService(referencedByDirect);
verify(controllerServiceProvider, never()).removeControllerService(referencedByIndirect);
}

@Test
void synchronizationRemovesMissingServicesReferencedOnlyByOtherMissingServices() {
final ProcessGroup targetGroup = createMockProcessGroup();
final ControllerServiceNode cycleFirst = createMockControllerService();
final ControllerServiceNode cycleSecond = createMockControllerService();
final ControllerServiceNode unreferenced = createMockControllerService();
setReferences(cycleFirst, cycleSecond);
setReferences(cycleSecond, cycleFirst);
when(targetGroup.getControllerServices(false)).thenReturn(Set.of(cycleFirst, cycleSecond, unreferenced));

synchronizer.synchronize(targetGroup, incomingFlowWithoutServices(), synchronizationOptions);

verify(controllerServiceProvider).removeControllerService(cycleFirst);
verify(controllerServiceProvider).removeControllerService(cycleSecond);
verify(controllerServiceProvider).removeControllerService(unreferenced);
}

@Test
void synchronizationKeepsMissingServiceReferencedAfterPropertyMigration() {
final ProcessGroup targetGroup = createMockProcessGroup();
final ControllerServiceNode service = createMockControllerService();
when(targetGroup.getControllerServices(false)).thenReturn(Set.of(service));

final ProcessorNode processor = createMockProcessor();
when(processor.getParentProcessGroup()).thenReturn(Optional.of(targetGroup));
when(flowManager.createProcessor(any(), any(), any(), eq(true))).thenReturn(processor);
doAnswer(invocation -> service.getReferences().getReferencingComponents().add(processor))
.when(processor).migrateConfiguration(anyMap(), any(ControllerServiceFactory.class));

final VersionedProcessGroup proposed = new VersionedProcessGroup();
proposed.setIdentifier(ROOT_GROUP_ID);
proposed.setProcessors(Set.of(createMinimalVersionedProcessor()));
final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposed);

synchronizer.synchronize(targetGroup, incoming, synchronizationOptions);

verify(controllerServiceProvider, never()).removeControllerService(service);
}

@Test
void synchronizationRemovesMissingServicesOnlyInSynchronizedChildGroups() {
final ProcessGroup parentGroup = createMockProcessGroup();
final ProcessGroup childGroup = createMockProcessGroup();
when(childGroup.getVersionedComponentId()).thenReturn(Optional.of(CHILD_GROUP_ID));
final ProcessGroup versionedChildGroup = createMockProcessGroup();
when(versionedChildGroup.getVersionedComponentId()).thenReturn(Optional.of(VERSIONED_CHILD_GROUP_ID));
when(parentGroup.getProcessGroups()).thenReturn(Set.of(childGroup, versionedChildGroup));

final ControllerServiceNode childService = createMockControllerService();
when(childGroup.getControllerServices(false)).thenReturn(Set.of(childService));
final ControllerServiceNode versionedChildService = createMockControllerService();
when(versionedChildGroup.getControllerServices(false)).thenReturn(Set.of(versionedChildService));

final ProcessorNode versionedChildProcessor = createMappableProcessor(versionedChildGroup);
when(versionedChildGroup.getProcessors()).thenReturn(Set.of(versionedChildProcessor));
final ControllerServiceNode parentService = createMockControllerService();
setReferences(parentService, versionedChildProcessor);
when(parentGroup.getControllerServices(false)).thenReturn(Set.of(parentService));

final VersionedFlowCoordinates coordinates = new VersionedFlowCoordinates();
coordinates.setRegistryId("registry-id");
coordinates.setBucketId("bucket");
coordinates.setFlowId("child-flow-id");
coordinates.setVersion("1");

final VersionedProcessGroup proposedChild = new VersionedProcessGroup();
proposedChild.setIdentifier(CHILD_GROUP_ID);
final VersionedProcessGroup proposedVersionedChild = new VersionedProcessGroup();
proposedVersionedChild.setIdentifier(VERSIONED_CHILD_GROUP_ID);
proposedVersionedChild.setVersionedFlowCoordinates(coordinates);
final VersionedProcessGroup proposedParent = new VersionedProcessGroup();
proposedParent.setIdentifier(PARENT_GROUP_ID);
proposedParent.setProcessGroups(Set.of(proposedChild, proposedVersionedChild));
final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposedParent);

final FlowSynchronizationOptions parentOnlyOptions = FlowSynchronizationOptions.Builder.from(synchronizationOptions)
.updateDescendantVersionedFlows(false)
.build();

synchronizer.synchronize(parentGroup, incoming, parentOnlyOptions);

verify(controllerServiceProvider).removeControllerService(childService);
verify(controllerServiceProvider, never()).removeControllerService(versionedChildService);
verify(controllerServiceProvider, never()).removeControllerService(parentService);
}

private VersionedExternalFlow incomingFlowWithoutServices() {
final VersionedProcessGroup proposed = new VersionedProcessGroup();
proposed.setIdentifier(ROOT_GROUP_ID);

final VersionedExternalFlow incoming = new VersionedExternalFlow();
incoming.setFlowContents(proposed);
return incoming;
}
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Folded and strengthened as suggested; the child-group test is removed.

return;
}

storeService.append("row-" + rowCounter.getAndIncrement());

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Row counting removed; onTrigger is a no-op.

Path registryDirectory;

@Test
void testStartupAndImportMigratedServicesSurviveFlowVersionUpdates() throws NiFiClientException, IOException, InterruptedException {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Strengthened in the same single method: a required password renamed by the service, a second processor with shared and separate services, and a consumer that skipped a version. One difference: instead of a different inline password per instance, the legacy snapshot references #{password}, because a service with an inline secret stays unversioned. Secret separation is covered by the flows where processors use different secrets.

@awelless
awelless requested a review from markap14 November 13, 2026 13:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants