Skip to content

[Draft, CI only - do not merge] 4.3.0-Beta1 - #2483

Draft
arnaudgiuliani wants to merge 28 commits into
mainfrom
4.3.0
Draft

arnaudgiuliani wants to merge 28 commits into
mainfrom
4.3.0

Conversation

@arnaudgiuliani

@arnaudgiuliani arnaudgiuliani commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Draft, CI only. Do not merge. This PR exists to run build.yml / test.yml on the 4.3.0 branch before tagging 4.3.0-Beta1. 4.3.0 is the next-minor line; fixes reach main (4.2.x) through separate ports.

What & why

Content of 4.3.0-Beta1 on top of main:

  • koin-core performance work: no debug strings when logging is off, allocation-free repeat lookups through a lazy typed cache, cheaper registration and getAll.
  • Ktor request-scope lifecycle fix: GitHub issues 2463 and 2472 (supersedes community PRs 2464 and 2473, co-authored by both authors).
  • Ktor: close Koin only when its own Application stops (community PR 2468, 2461).
  • ParametersHolder.set(i, null) no longer throws (community PR 2476).
  • Compiler-plugin scoped ViewModels are bound to ViewModel.
  • Agent docs and guardrails: AGENTS.md, root CLAUDE.md, shared .claude/settings.json, PR template.

Public API

  • ./gradlew apiCheck passes
  • No public API change in published modules. Only core/benchmark/api/benchmark.api changed (benchmark module, not published).
  • No removals or signature changes

Behavior change

  • Typed lookup cache (koin-core): none intended vs main; resolution results are the same. A first-lookup race, an overflow lock and an eviction gap found in review are fixed, with regression tests.
  • Ktor request scope:
    • Answered calls, including the engine's own error response: closed on ResponseSent, unchanged.
    • Response committed but never sent (stream failing mid-body, a response hook installed after Koin failing), cancelled call, channel I/O failure the engine only logs, engine error response failing: old leaked the scope and its ApplicationCall; new closes it once the application pipeline has unwound (after the handler's catch blocks and CallFailed handlers), or from a send-pipeline guard for the engine's error response.
    • WebSocket with HttpRequestLifecycle(cancelCallOnClose = true): old leaked; new closes when the call is cancelled, before the session handler's own finally.
    • A failing onClose no longer replaces the call's original exception (added as suppressed).
  • Ktor stop guard: old any ApplicationStopping on the shared monitor closed Koin; new only the plugin's own application closes it (Ktor 3.5 create-then-swap reload).
  • ParametersHolder.set(i, null): old NPE; new stores null like parametersOf does.
  • Scoped compiler-plugin ViewModels: old bound to KClass (unreachable as ViewModel); new bound to ViewModel. If a scope also binds another definition to ViewModel, scope.get<ViewModel>() can now return the plugin ViewModel; across modules strictOverride() reports the duplicate.

Tests

  • Every bug fix has a regression test that fails without it (TypedIndexRaceTest, TypedIndexTest, KoinPluginRunTest, RequestScopeLeakNettyTest, KoinFeatureTest, ParametersHolderTest, ParametersInjectionTest, ScopedViewModelBindingTest).
  • commonMain changes without commonTest tests: the race tests need real threads (JVM); the Ktor tests use the Ktor test host and a real Netty server, which run on the JVM here.

Verified beyond the JVM

  • Local: ./test.sh green, apiCheck green. koin-core JS and wasmJs show only the known createdAtStart failures; macosArm64 runs 303 tests with 0 failures (its Gradle reporter bug is tracked separately). koin-ktor and koin-core-viewmodel compile for wasmJs, JS and macosArm64.

Docs

  • insert-koin.io docs update needed for the Ktor request-scope lifecycle (onClose now also runs for failed and cancelled calls). Not done in the legacy docs/ folder.

🤖 Generated with Claude Code

arnaudgiuliani and others added 28 commits September 9, 2026 16:24
core/benchmark had no getAll coverage and never realized a graph, which is why
the gap the Metro benchmark measures never showed up here.

- multibindingModule(count): Metro-shaped workload (concrete primary type bound
  to a marker interface, consumed via getAll). Qualifiers keep definitions
  distinct so _instances actually grows with count — loading the same module N
  times collides on identical index keys and leaves the registry flat, so the
  O(N) scan in InstanceRegistry.getAll is never exercised.
- GetAllBenchmark: three-timer split (module build / registration / realization
  / scan / warm resolution) at 100, 500 and 1800 definitions.
- AllocationProbe: B/op via getThreadAllocatedBytes. kotlinx-benchmark 0.4.16
  accepts only nativeFork, nativeGCAfterIteration, jvmForks and jsUseBridge as
  advanced options, so JMH's -prof gc cannot be reached through the plugin.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Logger.debug(String) is a non-inline overload, so every interpolated debug
message was built at the call site before the level was checked. Koin's default
logger is EmptyLogger at Level.NONE, so this work was pure waste in the common
case.

- ResolutionContext.debugTag is now computed instead of stored. It was built on
  every get() and read by nobody: both CoreResolverV2 call sites are commented
  out and the remaining readers live in CoreResolver, which is not wired
  (Koin.kt instantiates CoreResolverV2). getDebugTag() is unchanged.
- InstanceFactory.create, InstanceRegistry.saveMapping (both the debug and the
  override warning), ScopeRegistry, PropertyRegistry, Koin.createEagerInstances,
  CoreResolverV2.resolveInExtensions and six Scope sites now use the inline
  log(Level) { } overload. saveMapping and create were each calling
  BeanDefinition.toString(), itself a buildString + joinTo.

Measured on GetAllBenchmark at 1800 definitions (5400 index entries), JVM:

  registration only      1652 -> 1035 us/op   (-37%)
  registration + realize 2435 -> 1720 us/op   (-29%)
  registration alone     927 -> 300 us/op     (-68%, t1 minus module build)

AllocationProbe, same workload:

  t1 registration        9.43 -> 2.89 MB/op   (-69%)
  t2 + realize          11.60 -> 3.25 MB/op   (-72%)
  t4 warm resolution      587 -> 324 B/op     (-45%)
  t4b warm qualified      616 -> 353 B/op     (-43%)

No public API change: apiCheck passes. LazyLoggingTest fails on the unfixed
source (verified by stash) and covers both directions — nothing is built at
INFO or with the default logger, and the messages are still produced at DEBUG.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Three internal changes on the module-build / registry path, measured on
GetAllBenchmark at 1800 definitions (5400 index entries) on top of the
debug-string fix:

- indexKey(): presized StringBuilder. Keys run 80-120 chars and the default
  16-char builder grew and copied three times per key. Output is byte-identical,
  including the pre-existing asymmetry (type qualifier -> value, scope qualifier
  -> toString()), which BeanDefinitionDefaultsTest now pins.
- BeanDefinition.callbacks: one shared empty Callbacks instead of one per
  definition. Callbacks is an immutable data class whose only field defaults to
  null, so sharing is safe; the test proves replacing it on one definition does
  not leak into another.
- InstanceRegistry.getAll: filter + distinct + mapNotNull fused into one pass
  with the same predicate, the same identity dedup and the same iteration order
  over _instances.values. Resolution is kept as a second phase so a definition
  calling declare() during creation never mutates the map under iteration.
  GetAllSemanticsTest checks the result against the old pipeline as an oracle.

Tried and reverted: lazily allocating BeanDefinition._secondaryTypes. It breaks
BeanDefinitionSecondaryTypesTest.getter_is_stable_across_binds, a deliberate
4.2.2 contract (same list instance across bind()), and measured as noise anyway.

AllocationProbe, cumulative from the pre-branch baseline:

  t0 module build         2.70 -> 2.04 MB/op  (-24%)
  t1 registration         9.43 -> 2.24 MB/op  (-76%)
  t2 + realize           11.60 -> 2.53 MB/op  (-78%)
  t3 getAll scan           207 ->  149 KB/op  (-28%)
  t4 warm resolution       587 ->  202 B/op   (-66%)

JMH, same machine, pre-branch dc86ef8 vs this commit:

  GetAll t1 registration        1652 -> 900 us/op   (-46%)
  GetAll t2 + realize           2435 -> 1324 us/op  (-46%)
  GetAll t4 warm get             157 -> 56 ns/op    (-64%)
  HeavyStartup module1000        279 -> 162 ms/op   (-42%)
  HeavyStartup module1000+binds  385 -> 220 ms/op   (-43%)
  JvmBenchmark.retrieveDependency 114 -> 58 ns/op   (-49%)

No public API change: apiCheck passes. wasmJs and macosArm64 compile, main and
test.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Same machine, before = dc86ef8, after = 4557213. Includes the new
GetAllBenchmark three-timer split and the AllocationProbe bytes-per-op rows.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
resolveDefinition rebuilt the ~100-char String IndexKey on every call — about
160 of the ~200 bytes a warm get() still allocated after the debug-string fix.
The String map cannot change (instances and Module.mappings are public API), so
InstanceRegistry now keeps a private cache in front of it, keyed by the same
three components already split (class full name -> short chain of (scope key,
qualifier key, factory)). A repeat lookup is one map get plus a chain walk with
no allocation; the only object left on a warm get() is the ResolutionContext.

Populated lazily, from a String-path hit, never at registration. An eagerly
maintained mirror was built first and measured: warm get 56 -> 33 ns, but
registration 900 -> 1565 us/op (+74%) — a net loss for startup, where every
definition is resolved exactly once and a cache can only cost. The lazy form
measures registration at 901 us/op (unchanged) and t2 within noise.

Correctness rules, all covered by TypedIndexTest (9 tests):
- _instances stays the single source of truth. Every write to it (saveMapping,
  unloadModule, close) drops the chains for the factory's class names;
  over-invalidation is safe and only costs a re-populate.
- A populate re-checks `_instances[key] === factory` under the same lock the
  writers take, so a concurrent override cannot leave a stale entry.
- A miss always falls through to the String map, so a caller hand-building keys
  through saveMapping keeps today's behavior to the byte.
- Classes with more than MAX_TYPED_CHAIN (8) scope/qualifier variants stay on
  the String map instead of turning lookups into long chain walks.

Also in this commit, from the independent review of the previous commits:
- Callbacks.kt documents the immutability invariant the shared empty instance
  relies on; the BeanDefinitionDefaultsTest comment now states what it pins.
- LazyLoggingTest now reaches ScopeRegistry (counting scope source),
  PropertyRegistry, Koin.createEagerInstances (createdAtStart) and the
  Scope.getOrNull catch paths, not just saveMapping/create/debugTag.

Same machine, pre-index -> this commit (JMH):

  GetAll t1 registration (1800)      900 ->  902 us/op   (unchanged)
  GetAll t4 warm get                  56 ->   26 ns/op   (-54%)
  GetAll t4b warm qualified get       70 ->   24 ns/op   (-66%)
  JvmBenchmark.retrieveDependency     56 ->   21 ns/op   (-63%)
  ScopeBenchmark.rootScope            70 ->   21 ns/op   (-70%)
  ScopeBenchmark.activityScope       312 ->  224 ns/op
  HeavyStartup module1000            160 ->  162 ms/op   (noise)
  HeavyStartup lazy_module1000      27.8 -> 28.4 ms/op   (noise)

AllocationProbe: t4 warm get 202 -> 56 B/op (one object); t1 registration
2.237 -> 2.237 MB/op.

Cumulative from the pre-branch baseline dc86ef8: warm get 157 -> 26 ns and
587 -> 56 B/op; retrieveDependency 114 -> 21 ns.

No public API change: apiCheck passes (a private companion object had to become
a top-level private const — BCV still lists the generated Companion).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

4.3.0-Beta1 Bump
- CoreResolverV2 registry order as implemented (own scopeQualifier defs, archetype defs, scope source unqualified-only, linked scopes)
- Stale root .api dumps and the AGP 9 apiCheck blind spot
- Record that the commonTest backtick/runTest rules are contradicted by passing JS/wasmJs test compilation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y points

- .claude/settings.json (root + projects/): deny the Central Portal release and force-push, block edits to the dead root .api dumps (and docs/ from the root); ask before git push, gh pr create/merge, and Gradle runs with -x
- Root CLAUDE.md imports AGENTS.md, which Claude Code otherwise skips when projects/CLAUDE.md exists
- AGENTS.md: branches, never-do list, examples entry point, PR template
- projects/CLAUDE.md: branch model (main = 4.2.x stable, 4.3.0 = next minor), one commit style (Fix #NNNN / KTZ-NNNN), docs/ is legacy, koin-test-coroutines in the module map, resolution extensions in the resolver chain, commonTest rules restated with verified reasons
- PR template carrying both PR guards
- CONTRIBUTING commit convention aligned; .gitignore covers the root settings.local.json

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…kups, benchmark API dump

- Race: a first lookup racing an override or unload on another thread could leave the typed
  cache serving the replaced definition for good. Writers skipped invalidation on an unlocked
  emptiness check; they now skip it on a volatile flag set before the populate's re-check.
  Registration cost unchanged (t1 1800: 904-908 -> 910 us/op).
- Overflow: lookups of a class past MAX_TYPED_CHAIN variants took the cache lock on every call.
  The lock-free walk now counts the chain and skips the populate when it is full.
  8 threads: 1,369 -> 106 ns/op (new t4c benchmark; main: ~172 ns).
- core/benchmark/api/benchmark.api regenerated (apiCheck was red).

Behavior vs main: none. Resolution results are identical; the fixes restore the
"_instances is the single source of truth" contract the cache promised.

Tests: TypedIndexRaceTest (jvmTest, needs real threads) races a fresh container each round;
fails on the previous code and on a flag-after-recheck mutant, passes on the fix.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ed calls

The request scope was closed only on ResponseSent. Calls that never reach it kept their scope,
and the whole ApplicationCall graph, in the ScopeRegistry until the server ran out of memory.

Behavior, old vs new:
- Answered calls (including the engine's own error response): closed on ResponseSent, unchanged.
  Error pages and response hooks still resolve request-scoped dependencies.
- Response committed but never sent (stream failing mid-body, response hook failing after
  Koin's #2463, client aborting a stream): leaked; now closed once the application pipeline
  has unwound, after the handler's catch blocks and every CallFailed handler.
- Cancelled call (#2472) and channel I/O failures the engine only logs: leaked; now closed.
- Engine error response failing after commit: leaked; now closed by a send-pipeline guard.
- WebSocket with HttpRequestLifecycle(cancelCallOnClose = true): the scope now closes when the
  call is cancelled, before the session handler's own finally. It used to leak.
- A failing onClose no longer masks the call's original exception (added as suppressed).

No public API change. Tests are in jvmTest because they need the Ktor test host and a real
Netty server; the plugin code is common.

Tests: KoinPluginRunTest keeps the tests from #2464 and #2473 and adds engine-error-response,
timeout (504), error-page ordering and production-mode cancellation cases.
RequestScopeLeakNettyTest reproduces each leak on a real Netty server.

Co-authored-by: Ilya Nemtsev <ilya.nemtsev@outlook.com>
Co-authored-by: NathanFallet <contact@nathanfallet.me>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 2490637)
Ktor 3.5 create-then-swap reload raises ApplicationStopping on a shared
monitor; ignore events for other Application instances so the new Koin
context is not closed when the previous application stops.

Fixes gh-2461

(cherry picked from commit a74bb8e)
ScopeDSL.buildViewModel bound `ViewModel::class::class` (KClass itself) as the secondary type,
so ViewModels generated in a scope by the compiler plugin were not reachable as ViewModel:
scope.getAll<ViewModel>() missed them. The module-level buildViewModel already bound ViewModel.

Behavior vs before: scoped plugin-generated ViewModels now also resolve as ViewModel, like
module-level ones. No API change. Present since 4.2.0, port to main tracked in KTZ-5310.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- macosArm64Test reports FAILED from Gradle's TestOutputStore "Multiple entries with same key"
  while every test passes; renaming DynamicModulesTest to snake_case changed nothing (KTZ-5309).
- Backtick names in commonTest are a style preference, not a proven hazard.
- createdAtStart known failures also hit JS, not only wasmJs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both ViewModels sit in one module, whose mappings overwrite duplicate keys, so strictOverride
could never trigger there; the test checks that every scoped ViewModel resolves as ViewModel.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tory's current types

The cache dropped, on every registry write, the chains of the factory's current primary and
secondary types. A key whose type was not among them was never evicted, so the cache kept
serving a replaced or unloaded definition:
- secondaryTypes reassigned after bind (withOptions), then unload: get<Foo>() still resolved;
- a hand-written key of another type, then overridden: get<Foo>() kept the old factory.
main returns the String map's answer in both cases.

Chains are keyed by the class name that opens every IndexKey, so a write or removal now drops
the chain of its key's own class. That is exact (other keys are untouched) and does fewer
removals per write. Comments updated, including ART in the memory-model note and the real
meaning of MAX_TYPED_CHAIN.

Tests: two TypedIndexTest cases, failing before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…onse fails

Follow-up to a062b32 from its 4th independent review:
- A response hook failing before commit (for example onCallRespond resolving a request-scoped
  dependency whose factory throws) fails the engine's error response too, which then answers
  through a fallback outside the send pipeline. ResponseSent never fired and the scope leaked
  (before a062b32 as well). The send guard now closes on any send failure once the application
  pipeline has exited, since that send can only be the engine's own error response.
- The send guard had no test. Both paths are now covered (the after-commit test fails with the
  guard removed, the before-commit test failed before this change).
- closeRequestScope no longer calls addSuppressed with the in-flight exception itself
  ("Self-suppression not permitted" would have replaced the original failure).
- Comment: a response hook installed after Koin runs before Koin's ResponseSent handler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From the 4.3.0 consistency review:
- koin-ktor is KMP (JVM, JS, wasmJs, native), not "JVM server"
- test-macos.sh covers koin-core on macosArm64 only
- koin-ktor.api is the live dump; only koin-ktor3.api and the four root dumps are dead
- the two settings files share deny/ask rules but differ (docs/ deny, pre-allowed test scripts)
- CI runs on pull requests only, and the tag workflow runs no tests; settings cannot enforce green-before-push
- examples/ pins a released Koin, so it does not test the branch by default
- known-failures intro no longer contradicts its re-verified entries; stale CONTRIBUTING note dropped
- -prof gc: allocProbe or benchmark-gc.sh, consistently across GetAllBenchmark and AllocationProbe

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tten key

1371894 dropped the chain for `mapping.substringBefore(':')`, which is the key's class only when
the class name holds no ':'. Kotlin/JS accepts escaped class names such as `a:b` (simpleName is the
cache key there) and generated JVM classes may carry ':' too; for those, an override or unload left
the cache serving the old factory. forget() now drops every prefix ending before a ':', which
covers the real class name and stays free until the cache is first used.

Tests: TypedIndexColonClassNameTest (jvmTest: defines a class named `Colon:Type` at runtime),
failing before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
f78617e closed the request scope on any send failing after the application pipeline exited.
Sends nested in the engine's error response also hit the guard: a StatusPages status page whose
own render fails before commit, then recovered by the user (fallback page, or swallowed so the
original 500 goes out), found the scope closed. main does not do that. A send-depth attribute now
limits the close to the outermost send, which is the engine's error response itself.

Also removes the self-suppression check added in f78617e: Kotlin's common
Throwable.addSuppressed already ignores `this === exception`, so it could not trigger. The new
onClose test pins the behavior (the original failure survives an onClose rethrowing it).

Tests: two status-page tests (recovered render, swallowed render) failing on f78617e, plus the
onClose test (isolated Koin context so its throwing onClose stays out of the global one).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Comments, test KDocs, benchmark notes and agent docs referred to internal ticket IDs that mean
nothing outside the team. They now describe the work itself. The commit-style rule keeps
`Fix #NNNN - description` for GitHub issues and a plain description otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
buildViewModel, the runtime call behind the compiler plugin's viewModel<T>() and
@KoinViewModel, bound each ViewModel to androidx.lifecycle.ViewModel. Every ViewModel
then shared one index key: ViewModels in two or more modules failed at start under
strictOverride(), and logged one override warning per ViewModel otherwise. Nothing in
Koin resolves ViewModels by that type.

Both overloads now register the ViewModel under its own type only, like viewModel { }
and viewModelOf. This also removes the scoped binding added in 0430f98.

Behavior vs before: get<ViewModel>() and getAll<ViewModel>() no longer return
compiler-plugin ViewModels. get<ViewModel>() used to return the last one loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- AGENTS.md, projects/CLAUDE.md: user-visible changes update docs/ in the same PR; docs/ removed from the never-do list
- .claude/settings.json: drop the Edit(/docs/**) deny
- PR template: Docs checkbox asks for the docs/ update

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Pages restructured for readability and single-source concepts; new intro pages core-concepts and choosing-your-style
- Pages merged away by the restructure removed
- Navigation 3: koinEntryProvider<T>() route type with a typed NavDisplay, with the compiler error it prevents

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

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

Development

Successfully merging this pull request may close these issues.

3 participants