Skip to content

Drop displaced InstanceFactory state on declare override - #2490

Open
Inf1mum wants to merge 2 commits into
InsertKoinIO:mainfrom
Inf1mum:fix/2412-declare-displaced
Open

Inf1mum wants to merge 2 commits into
InsertKoinIO:mainfrom
Inf1mum:fix/2412-declare-displaced

Conversation

@Inf1mum

@Inf1mum Inf1mum commented Nov 4, 2026

Copy link
Copy Markdown

Fixes #2412

The leak

When a binding is overridden via koin.declare(...) (or any InstanceRegistry.saveMapping call with allowOverride = true), the displaced InstanceFactory is replaced in InstanceRegistry._instances, but its cached value is never dropped. Because Module.mappings still holds the original factory by reference, that factory survives stopKoin() with its old singleton intact: Koin.close() → instanceRegistry.close() only iterates _instances (i.e. the declare-owned factory), so the orphaned original keeps its SingleInstanceFactory.value.

The next startKoin { modules(sameModuleInstance) } re-registers the still-cached factory from Module.mappings, and the next get<T>() returns a stale instance — including any state mutations from the previous Koin lifecycle. This matters most in test setups that reuse a Module across startKoin/stopKoin cycles (e.g. kotest 6's KoinExtension, which now captures the module once per spec — see the issue for details).

The fix

In InstanceRegistry.saveMapping, when an override displaces a different factory, drop the displaced factory's cached state before replacing it:

// drop the displaced factory's cached state, as it can still be
// referenced from module mappings and survive Koin restart
if (displaced !== factory) {
    displaced.dropAll()
}

The displaced !== factory guard keeps the no-op behavior when the same factory is re-registered (e.g. loading the same Module again in the same lifecycle, or re-saving secondary-type mappings of the factory itself).

Note on onClose timing

As a consequence, the displaced factory's onClose hook is now invoked at the moment of displacement (override), with the cached instance — instead of never, or at close() only for factories still present in _instances. This matches the semantics of InstanceRegistry.close(), which already calls dropAll() (and therefore onClose) on every registered factory. Calling onClose with a null value for a never-resolved factory is also consistent with existing behavior (FactoryInstanceFactory.drop() already does exactly that).

Test

Added a regression test in DeclareInstanceTest following the issue scenario: startKoin with a module holding a stateful singleton → get and mutate → declare an override of the same type → stopKoin → startKoin with the same Module instance → get. The test asserts assertNotSame with the previous lifecycle's instance and fresh state; it fails on main without the fix.


This supersedes the stale #2413 (auto-closed on 2026-10-14) — happy to coordinate with @glasser if they want to continue on it.

Verification

  • ./gradlew :core:koin-core:jvmTest: 295 tests, 0 failures (2 pre-existing skips), including the new regression test.
  • ./gradlew :core:koin-test:jvmTest: 25 tests, 0 failures.

…re override

Signed-off-by: Inf1mum <vadim.lazuk@mail.ru>
@glasser

glasser commented Nov 13, 2026

Copy link
Copy Markdown

@Inf1mum Yeah, this looks the same as mine — since mine got stale-closed, let's go with this one if you can get a maintainer's attention :)

@Inf1mum

Inf1mum commented Nov 16, 2026

Copy link
Copy Markdown
Author

Thanks @glasser — acknowledged, both PRs implement the same fix for the displaced factory's stale cached state on declare override. @arnaudgiuliani for visibility: this PR and glasser's #2413 (closed by the stale bot) are equivalent implementations of that fix, so we're happy to consolidate on or adjust either per your preference.

// drop the displaced factory's cached state, as it can still be
// referenced from module mappings and survive Koin restart
if (displaced !== factory) {
displaced.dropAll()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

One edge case with secondary bindings (binds): a SingleInstanceFactory is stored in _instances under both its primary type and every bound secondary type. If a caller overrides just one of those mappings (e.g. declare<Foo>(fakeFoo) while FooImpl or Bar still points to displaced), calling displaced.dropAll() here drops the live singleton and fires onClose for the remaining active bindings too. Checking that displaced has no remaining references in _instances after overwriting _instances[mapping] = factory (e.g. _instances.values.none { it === displaced }) would avoid breaking partial overrides while still clearing fully displaced factories.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch - fixed in ce5e660: saveMapping now decides on dropping only after the mapping is overwritten, and drops the displaced factory only when no other entry in _instances still references it (your none { it === displaced } check). A partially overridden factory stays live under its remaining bindings with its cached instance and onClose untouched, while a fully displaced factory is still dropped, exactly once. Two regression tests in DeclareInstanceTest cover both cases; :core:koin-core:jvmTest (297 tests, 0 failures) and :core:koin-test:jvmTest (25 tests, 0 failures) pass.

…eferences it

A SingleInstanceFactory is stored under its primary type and every bound
secondary type. Overriding just one of those mappings used to drop the
displaced factory even though it was still live under its other bindings,
closing its cached instance and firing onClose for active bindings.

Decide on dropping only after the mapping is overwritten: drop the
displaced factory only when no mapping in _instances still references it;
fully displaced factories are still dropped, exactly once.

Signed-off-by: Inf1mum <vadim.lazuk@mail.ru>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants