Skip to content

FELIX-6874: Fix DM cache init when bundles start in parallel - #598

Merged
pderop merged 6 commits into
apache:masterfrom
pderop:FELIX-6874
Nov 25, 2026
Merged

pderop merged 6 commits into
apache:masterfrom
pderop:FELIX-6874

Conversation

@pderop

@pderop pderop commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Motivation:

ServiceRegistryCacheManager initialized itself from a static initializer, which called start() on the DM bundle in order to get its BundleContext. When a user bundle is started before the DM bundle, the framework may not start the DM bundle synchronously, so getBundleContext() returned null. The static initializer then failed with a NullPointerException, and ServiceRegistryCacheManager became unusable for every DM bundle (NoClassDefFoundError: Could not initialize class ...).

This can happen when threads that start bundles in parallel are launched while the framework is still starting and raising its start levels: a user bundle may then be started before the DM bundle, which is still waiting to be started by the framework start level thread.

Until now, DM in parallel mode has only been tested after the FrameworkStarted event, once the framework is fully started and all the start levels are reached. This is why the problem was never seen.

Modification:

The cache is now initialized by the DM bundle Activator, using its own BundleContext, and the static initializer is removed:

  • Activator.start() calls ServiceRegistryCacheManager.init(context), which creates the configured filter indices once. The framework serializes the Activator start, so no extra locking is needed.

  • getCache(), called by DependencyManager, now locates the DM bundle with FrameworkUtil and starts it transiently if it is not active. If another thread is already starting the DM bundle, the framework blocks the caller until the DM Activator has completed, so the cache is ready when the DependencyManager is created.

  • While the framework is raising its start level, it may refuse a transient start because the DM bundle start level is not met yet. In this case, the DM bundle is started with a persistent start, which lets the framework start it now if it can, else later (the caller then does not use the cache).

The service registry cache is only an optimization: getCache never throws. If the DM bundle cannot be started, the error is reported and the DependencyManager is created without cache, so that bundles can still start.

A new unit test, FELIX6874_ParallelStartTest, starts 100 user bundles and the DM bundle from a pool of threads, on an embedded Felix framework, with and without a filter index. The Felix framework is added as a test dependency for it.

Result:

Starting bundles in parallel no longer breaks ServiceRegistryCacheManager. The new test fails with the previous code and passes with this fix.

Ref #236

…ndles are started in parallel

Motivation:

ServiceRegistryCacheManager initialized itself from a static initializer,
which called start() on the DM bundle in order to get its BundleContext.
When a user bundle is started before the DM bundle, the framework may not
start the DM bundle synchronously, so getBundleContext() returned null.
The static initializer then failed with a NullPointerException, and
ServiceRegistryCacheManager became unusable for every DM bundle
(NoClassDefFoundError: Could not initialize class ...).

This can happen when threads that start bundles in parallel are launched
while the framework is still starting and raising its start levels: a
user bundle may then be started before the DM bundle, which is still
waiting to be started by the framework start level thread.

Until now, DM in parallel mode has only been tested after the
FrameworkStarted event, once the framework is fully started and all the
start levels are reached. This is why the problem was never seen.

Modification:

The cache is now initialized by the DM bundle Activator, using its own
BundleContext, and the static initializer is removed:

- Activator.start() calls ServiceRegistryCacheManager.init(context), which
  creates the configured filter indices once. The framework serializes the
  Activator start, so no extra locking is needed.

- DependencyManager now calls getCache(), which locates the DM bundle with
  FrameworkUtil and starts it transiently if it is not active. If another
  thread is already starting the DM bundle, the framework blocks the caller
  until the DM Activator has completed, so the cache is ready when the
  DependencyManager is created.

- While the framework is raising its start level, it may refuse a
  transient start because the DM bundle start level is not met yet. In
  this case, the DM bundle is started with a persistent start, which lets
  the framework start it now if it can, else later (the caller then does
  not use the cache).

The service registry cache is only an optimization: getCache never throws.
If the DM bundle cannot be started, the error is reported and the
DependencyManager is created without cache, so that bundles can still
start.

A new unit test, FELIX6874_ParallelStartTest, starts 100 user bundles and
the DM bundle from a pool of threads, on an embedded Felix framework, with
and without a filter index. The Felix framework is added as a test
dependency for it.

Result:

Starting bundles in parallel no longer breaks ServiceRegistryCacheManager.
The new test fails with the previous code and passes with this fix.

Ref apache#236

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

@paulrutter paulrutter 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.

Thanks Pierre, this looks good to me. I reviewed the diff and code only (I did not run the new test locally); CI is green on 17/21/25/27.

Does it fix the exceptions reported in #236? Yes, both stack traces:

  • The ExceptionInInitializerError (NPE in ServiceRegistryCacheManager.<clinit>, getBundleContext() returning null) is gone: the static initializer is removed, and getCache() now starts the DM bundle transiently and waits for its Activator to finish.
  • The follow-up NoClassDefFoundError in Activator.start is gone too: init(context) uses the context handed to the Activator, so it cannot be null, and the class no longer has a failing static initializer.

Failure mode is also graceful now: getCache() never throws, and a bundle that can't get the cache is simply created without it.

Non-blocking comments:

  1. getCache() can revive a stopped DM bundle. Any new DependencyManager created while DM is not ACTIVE calls start() on it, so a deliberately stopped DM bundle would be restarted by a user bundle creating a DependencyManager. It also runs for every DependencyManager, so a failing start prints a stack trace each time. Maybe only attempt the start when the state is INSTALLED/RESOLVED/STARTING, or only once.
  2. Re-entrancy is documented but not guarded. FilterIndexCustomizer.addingService and ExecutorFactoryCustomizer run inside Activator.start and call getService on other bundles' services. If such a service factory creates a DependencyManager, getCache() is called on the Activator thread while DM is STARTING. A cheap guard (remember the activating thread in init) or confirming it is harmless would be nice.
  3. The START_TRANSIENT_ERROR fallback is not covered by the test. All bundles use the same start level, so the persistent-start branch never runs. A case with DM at a higher start level than the user bundles would cover it. Note that a DependencyManager created without the cache never picks it up later; fine as an optimization, just worth knowing.
  4. Test cost. The default of 200 runs x 2 tests x 101 bundles, each on a fresh Felix framework, is heavy for the regular build. Consider a lower default (e.g. 20) and keeping -Dfelix6874.runs for stress runs.
  5. Nit: init() guards on m_context != null, so after a DM stop/start without refresh the old context stays. Same as before, not a regression.

@paulrutter

Copy link
Copy Markdown
Contributor

Ps. I'm still trying to reproduce the old exception, but haven't been able up until now. Will keep you posted.

@pderop

pderop commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

@paulrutter

Hi Paul,

thank you so much for the review, I will address it.

Ps. I'm still trying to reproduce the old exception, but haven't been able up until now. Will keep you posted.

I have attached a reproducer sample in the jira, if you want to use it, see : https://issues.apache.org/jira/browse/FELIX-6874?focusedId=18149855&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-18149855

@pderop

pderop commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Added another reproducer , this time based on dependency manager in parallel mode + a "deployer" thread (similar to file install):

see https://issues.apache.org/jira/browse/FELIX-6874?focusedId=18149875&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-18149875

@paulrutter

Copy link
Copy Markdown
Contributor

Hi Pierre,

This PR fixes the ServiceRegistryCacheManager init, and the new test shows it. While testing parallel startup I found a possible second race. It is separate from this PR, so I report it here for your opinion.

The possible race

  • MultiPropertyFilterIndex.getPermutations sorts the array it receives, in place: Arrays.sort(values, String.CASE_INSENSITIVE_ORDER).
  • For the objectClass property, that array is the live array of the registration. The framework stores it as m_classes (ServiceRegistrationImpl) and getProperty returns it with no copy.
  • Adapter components share one array between all children. FilterComponent copies the interfaces once into m_serviceInterfaces. AdapterServiceImpl then passes that same array to setInterface for every child. So all children register with the same objectClass array.
  • Two threads that sort the same unsorted array at the same time can duplicate one name and lose another. A small test with two threads and a 4-name array corrupted 2 of 300,000 arrays.
  • A wrong array makes the index file the service under the wrong key. A dependency that uses the index then never finds the service.

Why I suspect it

In a parallel startup with 20 tenant-scoped copies of one adapter component, the application did not finish starting in 1 of about 150 runs. There was no error and no stuck thread. Every component that depends on the service from the shared array stayed unstarted, for all 20 copies at the same time. A shared array explains why all copies fail together.

What is proven and what is not

  • Proven: the in-place sort, and the shared array (code path above). This is the same in main and in 8.0.0.
  • Proven: a new unit test, objectClassArrayOfReferenceIsNotModified, fails without the fix and passes with it.
  • Not proven: that this race caused the stalled startup. I will compare the objectClass arrays of the next stalled run with a good run.

Proposed fix

Sort a copy in getPermutations:

List<MultiPropertyKey> getPermutations(String key, String[] propertyValues) {
    List<MultiPropertyKey> results = new ArrayList<>();
    // Sort a copy. The array of a service property can be the live array of the registration.
    String[] values = propertyValues.clone();
    Arrays.sort(values, String.CASE_INSENSITIVE_ORDER);
    ...

The change is 3 lines plus the test. createKeys also sorts the property keys in place. That one is safe today, because the framework returns a copy of the keys.

Do you prefer the fix in this PR, or in its own issue and PR?

@pderop

pderop commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, Paul. It looks like you're right, and I think your finding deserves a new Jira ticket and PR.

Feel free to go ahead with the PR if you want; I'll review it. Alternatively, I can take care of it myself. Let me know.

From my side, I may have found another issue, although it's unrelated to Parallel DM. It's in MultiPropertyFilterIndex.java, line 381.

The code uses reference instead of references, which can cause a ClassCastException when a service is unregistered.

I'll create a separate Jira ticket and PR for this.

@paulrutter

Copy link
Copy Markdown
Contributor

Alright we're on a spree then, haha. I'll take care of 'my' race then with a separate ticket plus PR.

…e only once

Motivation:

ServiceRegistryCacheManager.getCache() starts the DM bundle each time a
DependencyManager is created, if the DM bundle is not active (PR review):

- a DM bundle deliberately stopped was restarted by any user bundle; and
  the cache, opened with the bundle context of the stopped DM bundle, no
  longer receives service events;
- a failure to start the DM bundle printed a stack trace for each user
  bundle.

Modification:

- The DM Activator stop() calls ServiceRegistryCacheManager.stopped(),
  which sets a volatile flag, reset by init() at the next start. When the
  flag is set, or the DM bundle is STOPPING, getCache() returns null
  without starting the DM bundle. The bundle state is read before the
  flag, so that a concurrent stop is detected (see javadoc).

- The start failure is logged once (AtomicBoolean, getCache() may be called
  concurrently), at ERROR level with the DependencyManager Logger, and
  getCache() then returns null instead of a cache which may be bound to an
  invalid bundle context. The Logger is passed to getCache().

- The start is still attempted for each DependencyManager, not only once:
  when user bundles are started in parallel, each of them must call
  start() to wait for the DM activation in progress, so that it gets the
  cache.

- A new test in FELIX6874_ParallelStartTest stops the DM bundle, then
  starts a user bundle: the DM bundle must stay RESOLVED, the user bundle
  must not use the cache, and the DM bundle can still be restarted.

Known limitation (not changed here): restarting the DM bundle without
refreshing it, with the cache enabled, leaves the cache bound to the bundle
context of the previous activation.
@pderop

pderop commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the review! Commit b9f7be4. addresses your first comment: a DM bundle stopped by a management agent is no longer restarted by getCache(), and a start failure is logged only once. I'll address the other comments in follow-up commits.

One edge case is deliberately not handled: a stop which completes between the checks of getCache() and the moment Bundle.start() gets the bundle lock. For example:

  1. the start level thread is activating the DM bundle (STARTING, it holds the bundle lock);
  2. a user bundle calls getCache(), reads STARTING and m_stopped == false, calls start(START_TRANSIENT) and waits for the bundle lock;
  3. a management agent calls stop(), which also waits for the lock;
  4. the activation completes, and the management agent gets the lock first: the DM bundle is stopped (m_stopped == true, RESOLVED);
  5. the user bundle gets the lock, finds the DM bundle RESOLVED, and activates it again.

I thought about closing it with a ThreadLocal: the final decision is taken in init(), which runs in our Activator.start() while the framework holds the bundle lock (so a stop is either complete or not started), and the ThreadLocal tells init() whether the activation comes from getCache() (refused if the DM bundle has been stopped) or from the framework or a management agent (accepted). This works because the framework calls the activator in the thread which calls Bundle.start() (both Felix and Equinox do):

/** Set while getCache() starts the DependencyManager bundle (see init()). */
private static final ThreadLocal<Boolean> m_startedByGetCache = new ThreadLocal<>();

public static ServiceRegistryCache getCache(Logger logger) {
    try {
        Bundle dm = FrameworkUtil.getBundle(ServiceRegistryCacheManager.class);
        if (dm != null) {
            int state = dm.getState();
            if (state == Bundle.STOPPING || m_stopped) {
                return null; // shortcut: init() takes the final decision
            }
            if (state != Bundle.ACTIVE) {
                m_startedByGetCache.set(Boolean.TRUE);
                try {
                    startDependencyManager(dm);
                } finally {
                    m_startedByGetCache.remove();
                }
            }
        }
    } catch (Exception e) {
        if (m_stopped) {
            return null; // init() refused to restart the stopped DependencyManager bundle: not an error
        }
        if (m_startFailureLogged.compareAndSet(false, true)) {
            logger.log(Logger.LOG_ERROR,
                "Could not start the DependencyManager bundle, the service registry cache won't be used", e);
        }
        return null;
    }
    return m_cache;
}

public static void init(BundleContext context) {
    // called by our Activator start(), while the framework holds the bundle lock: a stop is either complete or not started
    if (m_stopped && m_startedByGetCache.get() != null) {
        throw new IllegalStateException("The DependencyManager bundle has been stopped, a user bundle must not restart it");
    }
    m_stopped = false;
    ...
}

When init() throws, the framework cancels the activation (the bundle goes back to RESOLVED), and getCache() returns null.

I didn't apply it, to keep the code simple.

The above patch is more complex, it adds a ThreadLocal, an exception thrown on purpose, and a hidden coupling between init() and getCache(), for an edge case that requires a management agent to stop the DM bundle exactly while it is being activated. Its effect is also limited: the DM bundle is only restarted transiently, so the persistent stop is still honored at the next framework start. The window is documented in the javadoc of getCache(). If you think it's worth closing, I can add it.

…hread

Motivation:

The DM Activator start() opens two ServiceTrackers, whose customizers call
getService() on other bundles' services (PR review). If such a service is a
ServiceFactory creating a DependencyManager, getCache() is called back on the
Activator thread, while the DM bundle is STARTING. This was only documented
("Never call this method from the DependencyManager Activator"):

- getCache() saw a bundle which is not ACTIVE, and started it: Felix rejects
  the start of a bundle being started by the same thread ("cannot be started,
  since it is starting");
- the error was logged as a failure to start the DM bundle, and consumed the
  "log once" flag, hiding a real start failure afterwards.

Modification:

- ServiceRegistryCacheManager.init() remembers the activating thread, and a
  new activated() method clears it. The Activator start() calls activated()
  in a finally block, so the thread is cleared even if the start fails.

- getCache() returns null at once when called by the activating thread: the
  DM bundle is not started again, and nothing is logged. The DependencyManager
  created by the ServiceFactory doesn't use the cache, which is only an
  optimization. Other threads are not affected.

- A new test in FELIX6874_ParallelStartTest starts a bundle registering a
  ComponentExecutorFactory ServiceFactory which creates a DependencyManager,
  then starts the DM bundle: the ServiceFactory must be called while the DM
  bundle is STARTING, the DM bundle must become ACTIVE, no start failure must
  be logged, and a user bundle started afterwards on the same thread must use
  the cache.

- The comments written for FELIX-6874 are wrapped at 100 columns (original
  Felix comments are unchanged).
@pderop

pderop commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Re-entrancy is documented but not guarded. FilterIndexCustomizer.addingService and ExecutorFactoryCustomizer run inside Activator.start and call getService on other bundles' services. If such a service factory creates a DependencyManager, getCache() is called on the Activator thread while DM is STARTING. A cheap guard (remember the activating thread in init) or confirming it is harmless would be nice.

Addressed your feedback in commit 3669425, thank you.

… a test

Motivation:

The START_TRANSIENT_ERROR fallback of ServiceRegistryCacheManager.getCache() was
not covered by the tests (PR review). getCache() starts the DM bundle with
START_TRANSIENT, and falls back to a persistent start if Felix rejects the
transient start with START_TRANSIENT_ERROR. In the existing tests, all bundles
use the same start level and the framework is stable, so the transient start
never fails and the persistent start branch never runs.

Modification:

- A new test in FELIX6874_ParallelStartTest, testTransientStartFailureFallsBackToPersistentStart,
  covers this branch. The DM bundle and the user bundle have the same start level (2),
  and the framework raises its start level from 1 to 2. The start level thread sets
  its target start level, then waits for the Felix global lock before queuing the
  bundles to start: in between, the active start level is still 1, and a persistent
  start called from another thread activates the bundle immediately. The
  DependencyManager created by the user bundle then fails to start the DM bundle with
  a transient start (START_TRANSIENT_ERROR).

- To open this window deterministically, the test thread holds the Felix global
  lock (internal API, called by reflection) while the framework raises its start
  level, waits for the target start level to be set, then starts the user bundle.

- The test verifies that the user and DM bundles are ACTIVE, that the DM bundle has
  been started by the persistent start fallback (a transient start doesn't mark the
  bundle as persistently started), that the user bundle uses the service registry
  cache, that no start failure is logged, and that the framework start level is
  finally raised.
@pderop

pderop commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

The START_TRANSIENT_ERROR fallback is not covered by the test. All bundles use the same start level, so the persistent-start branch never runs. A case with DM at a higher start level than the user bundles would cover it. Note that a DependencyManager created without the cache never picks it up later; fine as an optimization, just worth knowing.

Addressed feedback in commit fe36e47, thank you.

…rtTest

Motivation:

FELIX6874_ParallelStartTest repeats its race scenario 200 times by default
("felix6874.runs"), with 2 tests and 101 bundles per run, each on a fresh
embedded Felix framework. This is heavy for the regular build (PR review).

Modification:

- The default value of the "felix6874.runs" system property is lowered from 200
  to 20.

- The class comment says that a higher value can be used for stress runs, for
  example -Dfelix6874.runs=200.
@pderop

pderop commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Test cost. The default of 200 runs x 2 tests x 101 bundles, each on a fresh Felix framework, is heavy for the regular build. Consider a lower default (e.g. 20) and keeping -Dfelix6874.runs for stress runs.

Addressed your feedback in commit f8c0e4a, thank you.

… bundle

Motivation:

A stop/start of the DependencyManager bundle without refresh keeps the static
state of ServiceRegistryCacheManager (PR review), and is not supported: the
components created before the stop keep their interceptors on the old cache,
whose listeners were removed by the framework, and their bundles are not
restarted. The supported way is a refresh of the DependencyManager bundle.

Modification:

- A refresh creates a new wiring of the DependencyManager bundle, with a new
  class loader, so the static state of ServiceRegistryCacheManager starts from
  scratch (new context, new cache), and the bundles using DependencyManager are
  refreshed too, so their components use the new cache.

- New integration test, FELIX6874_DependencyManagerRefreshTest, in the new
  module index.itest.refresh.tests: with an "objectClass,dm.refresh.test" index
  configured by the system property, it refreshes the DependencyManager bundle
  and checks that a service dependency works before the refresh, and for a
  service registered after the refresh. For each of them, it also updates the
  service properties, and checks that the service event is propagated to the
  dependency. This test bundle must not import org.apache.felix.dm, else it
  would be refreshed in the middle of the test.

- New module index.itest.refresh.bundle: the bundle using DependencyManager
  which is refreshed with it. Its component depends on the Runnable services
  having the "dm.refresh.test" property (the bnd tester registers itself as a
  Runnable), and runs them when they are added or changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@pderop

pderop commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Nit: init() guards on m_context != null, so after a DM stop/start without refresh the old context stays. Same as before, not a regression.

Thanks! Agreed, this is not a regression, and I'd rather not change it in this PR: a stop/start of the DM bundle without refresh can't be fully supported as is. The components created before the stop keep their interceptors on the old cache, whose listeners were removed by the framework when the DM bundle was stopped, and their bundles are not restarted.

The supported way is a refresh: it creates a new wiring of the DM bundle, with a new class loader, so the static state of ServiceRegistryCacheManager starts from scratch (new context, new cache), and the bundles using DM are refreshed too, so their components use the new cache.

Commit e1f97f2 adds an integration test for this, FELIX6874_DependencyManagerRefreshTest (new modules index.itest.refresh.tests and index.itest.refresh.bundle). With an objectClass index configured by the system property, it refreshes the DM bundle and checks that a service dependency works before and after the refresh, including for a service registered after the refresh, and that the update of the service properties is propagated.

Supporting a stop/start without refresh would need a larger change (recreating the cache at each start, closing it at stop, and rebinding the existing components to the new cache), so if we want it, I suggest doing it in a separate PR.

@pderop

pderop commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

I think I addresses all your comments, let me know if there is something wrong ? or if I can ship this PR ?
thank you!

@paulrutter

Copy link
Copy Markdown
Contributor

I think I addresses all your comments, let me know if there is something wrong ? or if I can ship this PR ? thank you!

LGTM! good to merge

@pderop
pderop merged commit fb1890a into apache:master Nov 25, 2026
4 checks passed
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