Skip to content

FELIX-6886: Release events of removed instance-bound dependencies - #606

Open
pderop wants to merge 2 commits into
apache:masterfrom
pderop:FELIX-6886
Open

pderop wants to merge 2 commits into
apache:masterfrom
pderop:FELIX-6886

Conversation

@pderop

@pderop pderop commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Motivation:

When a component instance is destroyed, the dependencies added from its init() callback (instance-bound dependencies) are removed and stopped, but ComponentImpl keeps their entry in its dependency events map. Each destroy/init cycle leaks a dependency context and its events, and the services held by these events are never released.

Modification:

ComponentImpl now removes the entry of each instance-bound dependency it removes and closes its events. Events sent late by a removed dependency (for example when its tracker is closed) are ignored. A unit test reproduces the leak.

Result:

Removing an instance-bound dependency leaves no reference to it or to its events, as with Component.remove(Dependency).

Motivation:

When a component instance is destroyed, the dependencies added from its
init() callback (instance-bound dependencies) are removed and stopped, but
ComponentImpl keeps their entry in its dependency events map. Each
destroy/init cycle leaks a dependency context and its events, and the
services held by these events are never released.

Modification:

ComponentImpl now removes the entry of each instance-bound dependency it
removes and closes its events. Events sent late by a removed dependency
(for example when its tracker is closed) are ignored. A unit test
reproduces the leak.

Result:

Removing an instance-bound dependency leaves no reference to it or to its
events, as with Component.remove(Dependency).
@pderop pderop self-assigned this Nov 27, 2026
@shihchengwei-lab

Copy link
Copy Markdown

The new early return in handleAdded can leak a service acquired by an ADDED event that was queued while an instance-bound dependency was stopping.

I reproduced this on 86d55800e388710eebbeafb7f05b362dcefc248b. A second thread submits a ServiceEventImpl while stop() is still running. After stop() returns, this PR removes the dependency's entry from m_dependencyEvents; the queued handleAdded then sees null and returns without closing the event. BundleContext.ungetService(reference) is never called.

Adding e.close() before that return makes this reproducer and the three existing FELIX6886_InstanceBoundDependencyLeakTest cases pass.

Minimal reproduction
package test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.apache.felix.dm.Component;
import org.apache.felix.dm.context.ComponentContext;
import org.apache.felix.dm.impl.ComponentImpl;
import org.apache.felix.dm.impl.ServiceEventImpl;
import org.junit.Assert;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

public class FELIX6886_LateAddedServiceTest {
    @Test
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void lateAddedServiceQueuedDuringStopIsReleased() throws Exception {
        BundleContext bundleContext = mock(BundleContext.class);
        ComponentContext componentContext = mock(ComponentContext.class);
        ServiceReference reference = mock(ServiceReference.class);
        when(componentContext.getBundleContext()).thenReturn(bundleContext);
        ServiceEventImpl lateEvent =
            new ServiceEventImpl(componentContext, reference, new Object());

        SimpleServiceDependency required = new SimpleServiceDependency();
        required.setRequired(true);

        SimpleServiceDependency lateDependency = new SimpleServiceDependency() {
            @Override
            public void stop() {
                super.stop();
                Thread sender = new Thread(() -> add(lateEvent));
                sender.start();
                try {
                    sender.join(10_000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new AssertionError(e);
                }
                if (sender.isAlive()) {
                    throw new AssertionError("late ADDED event was not queued");
                }
            }
        };
        lateDependency.setRequired(false);

        ComponentImpl component = new ComponentImpl();
        component.setImplementation(new Object() {
            @SuppressWarnings("unused")
            void init(Component comp) {
                comp.add(lateDependency);
            }
        });
        component.add(required);
        component.start();

        EventImpl requiredEvent = new EventImpl(1);
        required.add(requiredEvent);
        required.remove(requiredEvent);

        Assert.assertNull(component.getDependencyEvents(lateDependency));
        verify(bundleContext).ungetService(reference);
        component.stop();
    }
}

On the PR head, the final verification fails with:

Wanted but not invoked:
bundleContext.ungetService(reference)

Could rejected incoming events be closed before these early returns? The same ownership pattern appears for newEvent in handleSwapped after the dependency entry is gone, although I only reproduced the ADDED path.

This review, reproducer, and comment were prepared with AI assistance; I reviewed the evidence before posting.

Motivation:

A late ADDED or SWAPPED event sent by an instance-bound dependency while it
is being stopped is ignored once the dependency has been removed from the
component. The service held by this event must still be released.

Modification:

Add a unit test where the late ADDED event is followed by the REMOVED event
a service tracker sends for every service it has added, and an integration
test using the real service tracker for a late ADDED event and a late
SWAPPED event.

Result:

The tests check that the services obtained for these late events are
released, and that handling the late events does not fail.
@pderop

pderop commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks a lot for the careful review and the reproducer, much appreciated!

You're right that the early return in handleAdded (and in handleSwapped for newEvent) doesn't close the incoming event. However, I'm not yet sure this can actually leak with the real ServiceDependencyImpl.

Tracker contract

As far as I understand the DM tracker, every event for which addingService obtained the service also gets a REMOVED for the same event object:

  • if the service is tracked when the tracker is closed, ServiceTracker.close() sends a REMOVED for it;
  • if it's still being added when the tracker closes, trackAdding sees closed and sends a REMOVED instead of an ADDED.

handleRemoved always closes the event in its finally block, even when the dependency entry is gone. So the late ADDED ends up on an event that is already closed (or will be).

Tests

I added the following tests in commit 22f4f3f

  • FELIX6886_LateAddedServiceTest (unit test, adapted from your reproducer): your reproducer sends a late ADDED with no matching REMOVED, which the real tracker doesn't seem to do. I've kept your scenario and added one step: like the tracker does for every service it has added, the dependency then sends a REMOVED for the same event. This REMOVED releases the service even though the dependency has been removed, and the test also checks that handling the late ADDED doesn't log any error.

  • FELIX6886_LateServiceEventTest (integration test, real Felix framework and real DM tracker), covering the two cases you mentioned:

    • a late ADDED, for a service registered while the instance is being destroyed;
    • a late SWAPPED, for an aspect registered while the instance is being destroyed.

    In both cases, the late event is handled after the dependency has been removed, and the services are released without the extra close().

I may well be missing something here, though. If you think there is a path where the real tracker delivers an ADDED (or a SWAPPED) without a matching REMOVED for the same event, please don't hesitate to come back to me.

Next step

That said, I still need to think about it a bit more: closing the rejected events in those early returns might still be a cheap defensive measure (for example for custom Dependency implementations). I'll come back to it.

Thanks again!

@shihchengwei-lab

Copy link
Copy Markdown

Thanks for adding the tests with the real tracker. My reproducer missed the matching REMOVED event.

@pderop

pderop commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

I'm the one who should thank you! Your review was very much appreciated. And please don't hesitate to reach out if you have any further concerns about this PR.

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