Skip to content

Replace identity-hash Koin scopeId with a monotonic counter in context classes#759

Draft
bedaHovorka with Copilot wants to merge 4 commits into
toKdisco0.6.1from
copilot/fix-koin-scope-id-collision
Draft

Replace identity-hash Koin scopeId with a monotonic counter in context classes#759
bedaHovorka with Copilot wants to merge 4 commits into
toKdisco0.6.1from
copilot/fix-koin-scope-id-collision

Conversation

Copilot AI commented Jul 12, 2026

Copy link
Copy Markdown
Contributor

DefaultSimulationContext and DefaultEditingContext derived their Koin scopeId from identity hash codes (platformIdentityCode / hashCode()). Identity hash codes live in a 31-bit space and are not unique, so under high context-creation volume (e.g. JMH benchmarks creating tens of thousands of contexts) two live contexts can collide, throwing ScopeAlreadyCreatedException.

Scope id generation

  • Added ContextScopeIds.kt with nextContextScopeId(), a process-wide, atomicfu-backed monotonic counter that is unique by construction regardless of context creation rate.
  • DefaultSimulationContext and DefaultEditingContext now use nextContextScopeId() instead of an identity hash code:
override val scope =
    KoinPlatformTools.defaultContext().get()
        .createScope(
            scopeId = nextContextScopeId(),
            qualifier = named<DefaultSimulationContext>(),
            source = this
        )

Documentation

  • Clarified platformIdentityCode's KDoc to explicitly state it must not be used as a unique identifier (debug logging only), since its own collision caveat was previously being ignored at a load-bearing call site.

Tests

  • Added ContextScopeIdUniquenessTest (commonTest) asserting scope ids stay unique across thousands of contexts and that nextContextScopeId() never repeats.

bedaHovorka and others added 3 commits July 11, 2026 21:26
…lity (~9% fast-sim win) (#754)

* fix(#749): gate findNextReservationTarget on reservation-eligibility

ShuntingLoop.toBlockInputObservation resolved BlockInputObservation.toSeparatorName
by calling PathReservationService.findNextReservationTarget for every block input on
every tick, including inputs that provably cannot take a forward reservation.

The call is a BFS (findNextSemaphoresVia) plus a full topological-path enumeration per
candidate (isPathAvailable -> findAllTopologicalPaths). Measured on vyhybna: 906 calls
per `example shuntingLoop 300`, of which 892 (98.5%) are discarded unread by
RuleBasedDispatcher.checkInput, which already returns null for FREE, not-approaching
and already-extended inputs. Cost: 30.3 ms of 342 ms wall (~9%).

Gate the search on eligibility. The three facts it needs (isApproachingThisInput,
pathSetUpTowardThisInput, pathAlreadyExtendedBeyond) are already computed in the same
function, so the gate is free.

This narrows the sensor-port contract: toSeparatorName is now populated only where a
forward reservation is possible, and is null elsewhere without the search having run.
RuleBasedDispatcher behaviour is unchanged by construction. Documented on
BlockInputObservation so a future LLM dispatcher does not read null as "track ahead is
occupied".

Native linuxX64 release, example shuntingLoop 300, median of 7:
  before  341 ms
  after   318 ms
Golden output byte-for-byte identical (90/90 event lines, 5 trains, 211.1 s sim time).

ShuntingLoopReservationTargetLazinessTest locks the contract and fails 2/2 without the
gate (a FREE input resolves k1->doA1=A).

Gates: core:jvmTest 2194, core:integrationTest 725, core:heavyTest 1001,
dispatcher-agent:test 51, desktop-ui:test 650, desktop-ui:integrationTest 247 — all
green. purity/detekt/ktlint clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Extract reservation-target helper

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
… JMH

`:core:integrationTest` failed on run 29165254178 (725 tests, 1 failed).
The failure was DefaultSimulationContextControllerTest.controlledLoopOverheadIsNegligible,
a wall-clock microbenchmark living inside the CI correctness gate: it timed one
300s ShuntingLoop run per arm and asserted the ratio was < 5%. It measured 5.33%.

It could not have held up. One sample per arm, no JIT warmup (the baseline arm ran
first and absorbed it, biasing the ratio negative, so it passed for a reason unrelated
to the property it claimed to test), and a 5% threshold on a shared runner whose
CPU-steal variance far exceeds 5%.

Note TwoTrainConcurrencyTest passed 150/150 in that run and is not implicated; the
simulation is a single-threaded kDisco discrete-event loop with a seeded RNG, so there
is no race here to serialize.

- Delete the wall-clock assertion. The class keeps its four deterministic tests
  (throttle invoked per event, non-negative deltas, StopSimulation propagates,
  awaitIfPaused called), which is what a correctness gate should assert.

- Add ControlledLoopOverheadBenchmark to the existing :desktop-ui JMH harness, with
  two independently reported arms instead of one fragile ratio. Only ctx.run(controller)
  is timed; context construction sits in @setup(Level.Invocation). Mode is SingleShotTime:
  the payload is a single-use, millisecond-scale run, and under AverageTime the resulting
  context churn collides Koin scope ids, since DefaultSimulationContext derives its scope
  id from a (non-unique) identity hash code.

  Measured: baseline 0.699 +/- 0.103 ms/op, with-controller 0.685 +/- 0.062 ms/op.
  Indistinguishable -- the hook overhead is below the noise floor, so the original
  claim was true; only the instrument was broken.

- Fix a latent order-dependent bug in TwoTrainConcurrencyTest found en route. It matched
  train names by substring, and Train.countValue is a process-global counter that is never
  reset, so once names reach two digits "Train #1" matches "Train #12". Now compares
  extracted whole tokens and indexes by identity rather than List.indexOf.

Verified: :core:integrationTest 724/724 (was 725/1 failed), :core:jvmTest 2194/2194,
:desktop-ui:test + integrationTest green, detekt + ktlintCheck clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Copilot AI changed the title [WIP] Fix Koin scope id generation in DefaultSimulationContext Replace identity-hash Koin scopeId with a monotonic counter in context classes Jul 12, 2026
Copilot AI requested a review from bedaHovorka July 12, 2026 04:48
@bedaHovorka bedaHovorka changed the base branch from goal-10 to toKdisco0.6.1 July 12, 2026 06:56
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.

DefaultSimulationContext derives its Koin scope id from an identity hash code (not unique)

2 participants