Skip to content

fix(atg): invalidate configurationValidationResult on ChargingStationEvents.updated - #1977

Merged
jerome-benoit merged 1 commit into
mainfrom
fix/atg-configuration-validation-cache-invalidation
Jul 8, 2026
Merged

jerome-benoit merged 1 commit into
mainfrom
fix/atg-configuration-validation-cache-invalidation

Conversation

@jerome-benoit

@jerome-benoit jerome-benoit commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1965.

Step 0 audit trail — bug verified, not trusted

HEAD-at-inspection = origin/main = c55793e9. Verified each claim against the codebase before touching code (per lesson from #1964 postmortem: issue premises can be stale). Line numbers below reference branch head 6fd96d6a (post-diff), not main (pre-diff), unless annotated. AutomaticTransactionGenerator.ts production-side line positions are stable across all force-pushes since 590112c1.

Confirmed in-flight ATG-config mutation path that bypasses stop(): ChargingStation.ts:1153-1164 — the templateFileWatcher reload handler.

When this.automaticTransactionGenerator?.started === false at reload time (L1154):

  • L1155-1157: stopAutomaticTransactionGenerator() is skipped → ATG cache not cleared.
  • L1158: delete this.automaticTransactionGeneratorConfiguration unconditionally discards the CS-side cached config so the next getAutomaticTransactionGeneratorConfiguration() re-reads reloaded template bounds.
  • L1159-1164: ATG is not restarted.
  • Result: AutomaticTransactionGenerator.configurationValidationResult remains stale.

The templateFileWatcher callback itself does not emit ChargingStationEvents.updated. The fix works via the always-emit invariant of chargingStation.startAutomaticTransactionGenerator at ChargingStation.ts:1213: every start attempt unconditionally emits updated after saveAutomaticTransactionGeneratorConfiguration(), so the ATG-side subscription clears the cache between successive retries.

Reproduction (see test 2 for machine-verified reproduction):

  1. Caller invokes chargingStation.startAutomaticTransactionGenerator([1]) via broadcast channel (ChargingStationWorkerBroadcastChannel.ts:213-217).
  2. chargingStation.startAutomaticTransactionGenerator at ChargingStation.ts:1200-1214 delegates to atg.startConnector(1) (not atg.start()) → validateConfiguration on invalid bounds caches false. atg.started remains false. Post-attempt L1213 emit clears the cache (with this PR).
  3. Template file reload fires with corrected bounds → cache stays cleared through the reload block.
  4. Next startConnector re-parses fresh bounds → succeeds. Without this PR, step 2's cache-set-to-false survives (no L1213 subscriber existed) and step 4 short-circuits.

Verified ATG side (branch head 6fd96d6a):

  • configurationValidationResult: boolean | undefined at L51.
  • Initialized to undefined in constructor at L63.
  • Constructor subscribes at L71 (this.chargingStation.on(ChargingStationEvents.updated, this.onUpdated)).
  • deleteInstance unsubscribes at L84 (instance.chargingStation.off(ChargingStationEvents.updated, instance.onUpdated)).
  • stop() safety-net clear at L154 (was L140 on main — shifted by the constructor comment + deleteInstance unsubscribe plumbing, semantic-identical).
  • New arrow class field onUpdated at L432-434.
  • validateConfiguration at L576-607 memoizes at L577-578 (was L558-589 / L559-560 on main).
  • ATG only self-emits at L414 and L458 — was L400/L440 on main.

Verified emitter side of ChargingStationEvents.updated — full enumeration:

  • ChargingStation.ts: L1118, L1213 (always-emit invariant), L1312, L1819, L2348, L2370, L2518, L2564.
  • OCPPRequestService.ts: L341, L366.
  • AutomaticTransactionGenerator.ts: L414, L458.
  • Total: 12 emit sites across src/.

Approach chosen: subscribe to ChargingStationEvents.updated

Rationale over alternatives:

  • New dedicated event — over-engineering for a single O(1) cache. Rejected.
  • Hash-based comparison inside validateConfiguration — converts cheap 4-bound-check into unconditional hash+compare per call. Strictly worse. Rejected.
  • Delete the memoization entirely — regresses log-noise UX (N invalid connectors would emit N identical logger.error lines per start cycle). Rejected.

Why updated is not too chatty: handler is O(1). Chattiness at ChargingStation.ts:1819 and OCPPRequestService.ts:341/366 is negligible.

Circular subscription safety: ATG emits updated at L414/L458, both after validateConfiguration has already returned — no race.

Listener-leak invariant: constructor subscribes; deleteInstance unsubscribes symmetrically. Test 5 asserts listenerCount === 1 across 5 successive delete/get cycles and verifies double-consecutive deleteInstance idempotency (returns false, listener count stays 0).

Serialization boundary safety: buildUpdatedMessage and buildStartedMessage (MessageChannelUtils.ts) never structured-clone the ATG instance's arrow-field listener reference.

Class-field init order: with target: ESNext + strict: true, instance-field initializers run before the constructor body. this.onUpdated is defined by the time L71's this.chargingStation.on(...) runs.

hashId invariance: written once at ChargingStation.ts:1637. Never mutated.

Changes

  • src/charging-station/AutomaticTransactionGenerator.ts (+18 lines):

    • Constructor subscribes to ChargingStationEvents.updated at L71.
    • deleteInstance unsubscribes at L74-90 (cleanup-then-map-delete pattern, structurally mirrors CoherentMeterValuesManager.deleteInstance).
    • New private arrow class field onUpdated at L432-434.
    • stop() L154 safety-net clear preserved (constraint honored).
    • Zero changes to validateConfiguration logic (constraint honored).
  • tests/charging-station/AutomaticTransactionGenerator.test.ts (+182 lines):

    • wireEventEmitter (with explicit ordering-requirement JSDoc warning) and setATGBounds test helpers.
    • 5 new tests under configurationValidationResult cache invalidation (issue #1965):
      1. should invalidate the cache on ChargingStationEvents.updated — unit-level: verifies the cache-clear on emit.
      2. should recover startConnector after ChargingStationEvents.updated invalidates a cached-false decision — end-to-end reproduction of the Step 0 bug scenario: startConnector(1) with invalid bounds → cache=false → correct bounds + emit → startConnector(1) → cache=true.
      3. should still clear the cache on stop() (redundant with event-driven invalidation) — safety-net regression guard.
      4. should be idempotent under sequential updated events — no exception under back-to-back sync emits.
      5. should not leak listeners across deleteInstance/getInstance cycles — listenerCount(ChargingStationEvents.updated) stays at 1 across 5 delete/get cycles plus double-consecutive deleteInstance idempotency: second call returns false, listener count stays 0.
  • tests/charging-station/helpers/StationHelpers.factory.ts (+2 lines):

    • Added off: () => station no-op for EventEmitter parity.

No changes outside the ATG scope

Per mission constraints: validateConfiguration internal logic untouched, existing emit sites in ChargingStation.ts and OCPPRequestService.ts untouched, stop() safety-net clear preserved.

Verification gates

Gate Result
pnpm format clean
pnpm typecheck 0 errors
pnpm lint 0 errors, 0 warnings
pnpm test (root) 2941 pass, 0 fail
pnpm build exit 0
Listener count invariant 1 across 5 cycles + double-delete idempotency (test 5)
Step 0 bug reproduction test 2 end-to-end passes
GitHub CI 44 checks SUCCESS, 0 failed, 0 in-progress

Session-established review method — 11 rounds

Round Reviewers Outcome Actions
1 Oracle + Explore HIGH saturation, 2 MINORs, 3 doc discrepancies Comment tightening + PR body corrections → 03caf3b3
2 Oracle HIGH saturation (amended state) none
3 Oracle + Explore HIGH saturation × 2, 3 MINORs Terminology fix (hot-reload → reload) → b5e9c3c5
4 Oracle + Explore HIGH saturation, saturation exhausted none
Post-4 User pushback on skips 3 valid findings previously skipped Handler rename onChargingStationUpdated → onUpdated; test "back-to-back" → "sequential"; constructor comment pattern-lead + sibling divergence → c4a46687
5 Oracle HIGH saturation, approve none
6 Oracle + Explore 2 MINOR (Oracle) + 2 DISCREPANCY (Explore); 2 disagreements resolved via v7 in favor of Oracle 3 fixes: constructor comment tightened (drop sibling-drift clause per Priority-3 whitelist); test 2 title → (redundant with event-driven invalidation); new end-to-end test 2 (originally "1b") → 590112c1
7 Oracle HIGH saturation, approve (post-round-6 confirmation) none
8 External GitHub bot 2 valid + 1 refuted (off/on alphabetical order self-contradiction) JSDoc ordering-requirement warning on wireEventEmitter; redundant test 3 assertion dropped → 622c8867
9 Oracle + Explore Oracle declared "terminal saturation"; Explore caught a genuine coverage gap (double-consecutive deleteInstance not tested) 4-line assertion extension in test 5 for double-delete idempotency → 6fd96d6a
10 Oracle + Explore Oracle: "tank empty"; Explore: PR body staleness (branch-head SHA, review method table, test description) PR body refreshed to reflect 6fd96d6a
11 Oracle + Explore HIGH saturation × 2; 2 cosmetic PR-body drifts (test-numbering + CI-count) PR body polish applied

v7 cross-agent divergence resolutions

  • Round 6 Explore Bump chalk from 4.1.2 to 5.0.1 #1 (emitChargingStationEvent guard bypass): Oracle correctly countered that L265 constructor listener guarantees listenerCount ≥ 1; test bypass has zero practical impact. Skip.
  • Round 6 Explore Bump eslint-plugin-jsdoc from 39.2.9 to 39.3.0 #7 (enable: true dead in setATGBounds): Oracle correctly countered that it's a DRY-parity mirror of addATGMethodsToStation. Skip.
  • Round 9: Explore correctly overrode Oracle's "covered" claim on double-consecutive deleteInstance — the loop pattern is {delete; get; delete; get; ...}, never consecutive deletes. Applied Explore's fix.
  • Round 10: Explore correctly identified PR body staleness as blocker; Oracle rated it "optional metadata churn". Applied Explore's finding — refreshed body.
  • Round 11: Oracle correctly flagged 2 cosmetic drifts (test-numbering / stale CI count) that Explore missed. Applied Oracle's finding.

Adapted-scope criteria — all 22 dimensions final

# Criterion Verdict
1-3 Elegance (design/impl/algo) GOOD
4-5 Maths / physics / OCPP spec N/A (qmd verified twice, both dictionaries)
6-7 TS/JS state of the art + harmonization GOOD
8 Content — comments, docs, description, terminology GOOD (rounds 3, 6, 8, 10, 11 fixes converged the terminology)
9 Cross-validation (12 emit sites) GOOD
10 Regression-chain / v6 (through 8 force-pushes) GOOD
11 Listener-leak invariant + double-delete idempotency GOOD (test 5 extended in round 9)
12 Serialization boundary GOOD
13 hashId invariance GOOD
14 EventEmitter listener ordering GOOD
15 Test-quality depth (5 tests including end-to-end Step 0 reproduction) GOOD
16 Constructor failure modes GOOD
17 Memory footprint per ATG GOOD
18 Monorepo blast radius GOOD (zero references in ui/* + tests/ocpp-server/)
19 ESLint / JSDoc alignment GOOD (extended wireEventEmitter JSDoc verified idiomatic — 72+ Markdown-emphasis precedents in codebase)
20 resetATGInstances hygiene GOOD (per-test locals GC-eligible; Oracle-validated skip)
21 MaxListenersExceededWarning risk GOOD (1-to-1 per station, never approaches Node default of 10)
22 Rebase / merge conflict risk GOOD (origin/main unchanged since PR opened; no rebase needed)

Total across 11 rounds: 18 reviewer invocations (11 Oracle + 5 Explore + 3 external GitHub bot comments). 13 fixes applied across the session. All quality gates green. GitHub CI: 44/44 checks pass. Awaiting requested reviewer approval.

@hyperspace-pr-bot

Copy link
Copy Markdown
Contributor

Summary

The following content is AI-generated and provides a summary of the pull request:


PR Checklist

  • Please add a description of your changes.
  • Please ensure title follows conventional commits.
  • We need your changes to come with unit tests in order to keep this project in quality and easy to maintain.
  • If your changes contain any new feature please be sure to document it.
  • Please add a link to the open issue or task that this pull request will resolve.

Does this PR introduce a breaking change?

  • Yes
  • No

Bug Fix: Invalidate configurationValidationResult cache on ChargingStationEvents.updated

Overview

AutomaticTransactionGenerator.validateConfiguration() memoizes its result in configurationValidationResult. Previously, this cache was only cleared in stop(), meaning hot-reloaded configuration changes (e.g. via templateFileWatcher) could leave a stale validation result — causing connector startup to be silently aborted even after invalid bounds were corrected.

Changes

src/charging-station/AutomaticTransactionGenerator.ts

  • The ATG constructor now subscribes to ChargingStationEvents.updated via a new private arrow field onChargingStationUpdated, which sets configurationValidationResult = undefined.
  • deleteInstance now unsubscribes the handler before removing the map entry, preventing listener leaks across getInstance/deleteInstance churn cycles.
  • The stop() cache clear at L140 is preserved as a safety net.
  • validateConfiguration logic is unchanged.

tests/charging-station/AutomaticTransactionGenerator.test.ts

  • Added wireEventEmitter helper to wire a real EventEmitter onto the mock station for event-driven tests.
  • Added setATGBounds helper to steer validateConfiguration pass/fail within a test.
  • 4 new tests under configurationValidationResult cache invalidation (issue #1965):
    1. Cache invalidated on ChargingStationEvents.updated ✅
    2. Regression guard: stop() still clears the cache ✅
    3. Idempotent under back-to-back updated events ✅
    4. No listener leaks across 5 deleteInstance/getInstance cycles ✅

tests/charging-station/helpers/StationHelpers.factory.ts

  • Added off: () => station no-op to the mock station to match the EventEmitter.off API used in deleteInstance.

Closes #1965


  • 🔄 Regenerate and Update Summary
  • ✏️ Insert as PR Description (deletes this comment)
  • 🗑️ Delete comment
PR Bot Information

Version: 1.27.2

@hyperspace-pr-bot hyperspace-pr-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The PR is well-structured and correctly addresses the stale-cache bug. The core production change in AutomaticTransactionGenerator.ts — subscribing to ChargingStationEvents.updated in the constructor and unsubscribing symmetrically in deleteInstance — is sound and the listener-leak invariant is properly tested. The main concern flagged is that wireEventEmitter is order-sensitive (must precede getDefinedATG) but this dependency is undocumented in the helper, creating a footgun for future test authors; this should be called out clearly in the JSDoc. The other observations are minor clarity issues rather than defects.

PR Bot Information

Version: 1.27.2

@jerome-benoit
jerome-benoit force-pushed the fix/atg-configuration-validation-cache-invalidation branch 5 times, most recently from 590112c to 622c886 Compare July 8, 2026 01:45
…Events.updated

Subscribe to ChargingStationEvents.updated in AutomaticTransactionGenerator's
constructor so in-flight configuration mutations that reach any charging
station mutation emit cannot leave a stale memoized validation decision
behind. stop() still clears the cache as a redundant safety net.

deleteInstance unsubscribes the handler before removing the entry so the
retired instance is not retained via the charging station's listener array
across a getInstance/deleteInstance churn cycle.

Fixes #1965.
@jerome-benoit
jerome-benoit force-pushed the fix/atg-configuration-validation-cache-invalidation branch from 622c886 to 6fd96d6 Compare July 8, 2026 02:01
@jerome-benoit
jerome-benoit merged commit 56479e4 into main Jul 8, 2026
44 checks passed
@jerome-benoit
jerome-benoit deleted the fix/atg-configuration-validation-cache-invalidation branch July 8, 2026 14:25
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.

[BUG] AutomaticTransactionGenerator: configurationValidationResult cache not invalidated on hot-reload

1 participant