Convert train-movement event detection to kDisco waitCrossing state events (Issue #750, step 1)#756
Open
bedaHovorka with Copilot wants to merge 6 commits into
Open
Convert train-movement event detection to kDisco waitCrossing state events (Issue #750, step 1)#756bedaHovorka with Copilot wants to merge 6 commits into
bedaHovorka with Copilot wants to merge 6 commits into
Conversation
…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>
Copilot
AI
changed the title
[WIP] Fix excessive derivative evaluations in zero-crossing detection
Convert train-movement event detection to kDisco waitCrossing state events (Issue #750, step 1)
Jul 11, 2026
bedaHovorka
approved these changes
Jul 12, 2026
Owner
|
After publishing the new kDisco snapshot, do only this in PR #756:
|
… 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>
…de.kdisco) kDisco PR #54 renamed its Maven group and Kotlin package from the maintainer's personal namespace to the neutral cz.ksimulantenbande.kdisco and added public-domain license headers. Update all consumer-side references (dependency coordinates, imports, checkKdisco path, docs) to match. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
…itCrossing state events; keep dtMax=1e-3 pending Motor redesign
…ect comment, add regression tests Verifies and closes out the waitCrossing conversion from 16fb70c now that kDisco 0.6.1-SNAPSHOT (with waitCrossing) is locally publishable and the build works again: - Generator.kt: correct a comment that overclaimed velocity-target events are root-found — only block-boundary and tail-entry were converted; Motor's AccelerationStopCondition still uses plain waitUntil. The Motor/dtMax follow-up is now tracked separately in issue #760. - SimpleTestProcess.kt: fix a real regression exposed by the conversion. This test coordinator never runs Generator, so it silently relied on kDisco's own raw defaults (dtMin=1e-5, maxAbsError=1e-5 — nearly equal in magnitude). The waitCrossing guards intentionally leave a structural gap of exactly `dtMin` at the moment a threshold is reached (see the existing Train.kt comments on why that slack is necessary), which is negligible against the intended maxAbsError=1e-2 but trips LengthChecker's invariant when left at kDisco's near-equal raw defaults. Confirmed via A/B test against 74cd41b (same kDisco version, pre-conversion Train.kt) that this is new, not pre-existing. Fixed by configuring the same tolerances Generator.startAction() sets. - SimpleTestProcessTest.kt: relax an assertion that assumed `position` stays >= 0 immediately after a block-boundary crossing. The waitCrossing guard deliberately fires `dtMin` short of the boundary so it reliably crosses zero instead of asymptoting forever; this leaves a bounded, harmless negative transient that was never a documented invariant. - SimpleLinearTrackTestProcessTest.kt: add an explicit regression test proving both converted call sites fire correctly end-to-end. Verified locally: kDisco published to mavenLocal from copilot/add-zero-crossing-detection (feaa058), full build/test/ integrationTest/heavyTest all green (0 failures across all JUnit reports). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
fe07131 to
9a7ce9e
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
fast-simspends 60–70% of its wall time in RKF45 continuous integration becauseGeneratorhardcodesdtMax=1e-3, capping every step at 1 ms (~1.85M derivative evals/run). That tinydtMaxis load-bearing: block-boundary crossings are detected purely by step granularity, so raising it breaks the simulation. This converts the two train-movement event detections to kDisco's newwaitCrossing { guard }root-finding — step 1 of the issue's proposed direction.Depends on kDisco PR #68 (
waitCrossing); interlockSim CI cannot compile until that is merged and published.Changes (
sim/Train.kt)Site.actions):waitUntil { position.state + dtMin >= nextLength }→ root-found state event. ThedtMinslack is retained to avoid an asymptotic-stop hang when a train decelerates to a STOP semaphore sitting on the boundary and settles ~1e-8 short.Train.actions):waitUntil { front.totalDistance >= length }→ root-found state event with the samedtMinslack.import cz.ksimulantenbande.kdisco.dtMin.Generator.ktdtMaxleft at1e-3. See below.Not yet addressed —
dtMaxstays at 1e-3Raising
dtMaxstill collapses the run (5 → 2 trains), so the perf win is deferred. Two root causes were isolated; both need a Motor redesign, golden re-baselining, and expert sign-off under the conservativesim/rules:a = -v²/2sstops via a velocity-clamp, undershooting the boundary by ~O(dtMax²) (1.1e-8 @ 1e-3, 2.2e-5 @ 1e-2), so a fixed tolerance cannot absorb it asdtMaxgrows. Fix direction:waitCrossing { distanceToSemaphore() }to stop exactly ats=0.Motor.derivatives()mutates the sharedvelocity.statein place; front and tail then integrate against different velocities, drifting|front − tail − length|to 0.0246 @dtMax=1.0(>maxAbsError=1e-2, LengthChecker FATAL). Fix direction: an order-independent clamp.Validation notes
dtMax=1e-3(5 trains, 75TRAIN_EVENTSlines, 213.1 s sim) — the conversion introduces no drift.Train.ktandGenerator.kt; Motor, velocity-clamp, and LengthChecker are unchanged from the original.dtMax=1e-3this is groundwork with no runtime speedup on its own; the win lands once the Motor state-event work above is complete.:core:heavyTestand re-baselining still pending.