Repository navigation
fix(ocpp): reset stationInfo.firmwareStatus on abort/exception in simulateFirmwareUpdateLifecycle - #1976
Conversation
SummaryThe following content is AI-generated and provides a summary of the pull request: PR Checklist
Does this PR introduce a breaking change?
Bug Fix: Reset
|
| Exit path | phase |
aborted |
firmwareStatus after finally |
|---|---|---|---|
| Clean abort mid-download | download |
true |
Idle |
| Clean abort mid-install | install |
true |
Idle |
| Exception during download | download |
false |
DownloadFailed |
| Exception during install | install |
false |
InstallationFailed |
| Happy path | installed |
any | Installed (untouched) |
Per OCPP 2.0.1 L01.FR.24, the *Failed notification on supersession is optional (MAY), so collapsing to Idle on clean abort is spec-compliant. No FirmwareStatusNotification is emitted from finally to avoid racing the caller driving supersession.
Test Coverage
5 new tests added under stationInfo.firmwareStatus reset on exit (issue #1969):
- ✅ Clean abort mid-download →
Idle - ✅ Clean abort mid-install →
Idle - ✅ Exception during download →
DownloadFailed - ✅ Exception during install →
InstallationFailed - ✅ Happy path preserved →
Installed
Closes #1969
- 🔄 Regenerate and Update Summary
- ✏️ Insert as PR Description (deletes this comment)
- 🗑️ Delete comment
PR Bot Information
Version: 1.27.2
- Event Trigger:
pull_request.opened - LLM:
anthropic--claude-4.6-sonnet - GithubContextProvider: [FEATURE] OCPP 1.6: introduce per-station state WeakMap (prerequisite for supersession + timer-cancel + trigger cross-check) #1963
- File Content Strategy: Full file content
- GithubContextProvider: [BUG] OCPP 1.6: DiagnosticsStatusNotification and FirmwareStatusNotification triggers read stale stationInfo status #1973
- Summary Prompt: Default Prompt
- GithubContextProvider: [BUG] OCPP 2.0.1 firmware: stationInfo.firmwareStatus persists after abort or exception in simulateFirmwareUpdateLifecycle #1969
- GithubContextProvider: [BUG] OCPP 1.6: updateFirmwareSimulation setTimeout not cancelled on stop() #1972
- Output Template: Repository PR Template
- Correlation ID:
b3dcb0f0-7a60-11f1-9a05-9546eddd182d
There was a problem hiding this comment.
The PR fixes a real bug (stale firmwareStatus on abort/exception), but introduces a subtle correctness issue: the finally reset silently overwrites the InvalidSignature terminal value with DownloadFailed, leaving stationInfo.firmwareStatus inconsistent with the last notification actually sent. The two comments above identify the fix — extending FirmwarePhase with 'invalidSignature' and guarding against it in the finally condition. There is also no test asserting that stationInfo.firmwareStatus retains InvalidSignature after the signature-failure path, which would have caught this regression.
PR Bot Information
Version: 1.27.2
- Event Trigger:
pull_request.opened - LLM:
anthropic--claude-4.6-sonnet - File Content Strategy: Full file content
- Agent Instructions:
- Correlation ID:
b3dcb0f0-7a60-11f1-9a05-9546eddd182d
| if (phase !== 'installed' && chargingStation.stationInfo != null) { | ||
| chargingStation.stationInfo.firmwareStatus = abortController.signal.aborted | ||
| ? OCPP20FirmwareStatusEnumType.Idle | ||
| : phase === 'install' | ||
| ? OCPP20FirmwareStatusEnumType.InstallationFailed | ||
| : OCPP20FirmwareStatusEnumType.DownloadFailed | ||
| } |
There was a problem hiding this comment.
Logic Error: The finally reset overwrites a valid terminal InvalidSignature status with DownloadFailed.
When the InvalidSignature branch executes (L3865–L3879 in context), sendFirmwareStatusNotification(…, InvalidSignature, …) sets stationInfo.firmwareStatus = 'InvalidSignature' and the method returns. At that point phase === 'download' and signal.aborted === false, so the finally block unconditionally overwrites stationInfo.firmwareStatus to DownloadFailed. The last notification sent was InvalidSignature, but the field now says DownloadFailed — a semantically incorrect and misleading terminal value for this path.
Consider extending FirmwarePhase with an 'invalidSignature' value, assigning it before the return, and guarding with phase !== 'invalidSignature' in the finally condition. The corresponding type declaration at line 3789 and the phase initialization at line 3790 would also need updating.
| if (phase !== 'installed' && chargingStation.stationInfo != null) { | |
| chargingStation.stationInfo.firmwareStatus = abortController.signal.aborted | |
| ? OCPP20FirmwareStatusEnumType.Idle | |
| : phase === 'install' | |
| ? OCPP20FirmwareStatusEnumType.InstallationFailed | |
| : OCPP20FirmwareStatusEnumType.DownloadFailed | |
| } | |
| if ( | |
| phase !== 'installed' && | |
| phase !== 'invalidSignature' && | |
| chargingStation.stationInfo != null | |
| ) { | |
| chargingStation.stationInfo.firmwareStatus = abortController.signal.aborted | |
| ? OCPP20FirmwareStatusEnumType.Idle | |
| : phase === 'install' | |
| ? OCPP20FirmwareStatusEnumType.InstallationFailed | |
| : OCPP20FirmwareStatusEnumType.DownloadFailed | |
| } |
Double-check suggestion before committing. Edit this comment for amendments.
Please provide feedback on the review comment by checking the appropriate box:
- 🌟 Awesome comment, a human might have missed that.
- ✅ Helpful comment
- 🤷 Neutral
- ❌ This comment is not helpful
| // 'download' → still in the download/verify phase (initial) | ||
| // 'install' → Installing notification succeeded, install phase entered | ||
| // 'installed' → Installed notification succeeded, lifecycle reached success | ||
| type FirmwarePhase = 'download' | 'install' | 'installed' |
There was a problem hiding this comment.
Logic Error: FirmwarePhase type must include 'invalidSignature' to support the guard in the finally block.
If the InvalidSignature terminal path is to be excluded from the finally reset, the phase variable must be settable to 'invalidSignature'. Without this type member, any assignment phase = 'invalidSignature' before the return at the signature-failure branch would be a TypeScript compile error.
| type FirmwarePhase = 'download' | 'install' | 'installed' | |
| type FirmwarePhase = 'download' | 'install' | 'installed' | 'invalidSignature' |
Double-check suggestion before committing. Edit this comment for amendments.
Please provide feedback on the review comment by checking the appropriate box:
- 🌟 Awesome comment, a human might have missed that.
- ✅ Helpful comment
- 🤷 Neutral
- ❌ This comment is not helpful
299a3fd to
623b690
Compare
|
L01.FR.26 follow-up filed as #1979 with the concrete fix design (last-sent-notification persistence on |
04bbb46 to
f06c8c4
Compare
…ulateFirmwareUpdateLifecycle simulateFirmwareUpdateLifecycle wrote stationInfo.firmwareStatus at every status transition via sendFirmwareStatusNotification, but its finally block only cleared the per-station WeakMap state (activeFirmwareUpdateAbortController, activeFirmwareUpdateRequestId). On exception or abort (supersession, stop()), stationInfo.firmwareStatus stayed at the last-emitted non-terminal value (e.g. 'Downloading'), leaving a latent data-model split any future consumer that does not cross-check activeFirmwareUpdateRequestId would observe. Track the current lifecycle stage inside the lifecycle scope and, in the existing finally, reset stationInfo.firmwareStatus in-place when the lifecycle did not reach Installed. Per OCPP 2.0.1 FirmwareStatusEnumType, Idle SHALL only be used in TriggerMessage-triggered notifications, so as a persistent local state Idle is only valid before install starts: - clean download-phase abort -> Idle - clean install-phase abort -> InstallationFailed - exception during download stage -> DownloadFailed - exception during install stage -> InstallationFailed Per OCPP 2.0.1 L01.FR.24 Note the terminal *Failed FirmwareStatusNotification on supersession is optional; L02.FR.15 Note omits any such clause. Emitting no FirmwareStatusNotification from finally is safe under both profiles. The field is reset in-place; no FirmwareStatusNotification is emitted from finally, so the simulator does not race the caller driving the supersession. Stage transitions are placed only after successful advancement (after the Installing / Installed notification awaits resolve), never on error/abort branches, so the terminal-value selection in finally is unambiguous. The finally guards mirror clearActiveFirmwareUpdate's requestId-supersession pattern to avoid clobbering a superseder's live status, and preserve any explicit terminal already emitted from inside try (DownloadFailed / InvalidSignature / InstallationFailed). Stage->terminal mapping uses `Record<Exclude<FirmwareStage, 'installed'>, OCPP20FirmwareStatusEnumType>` with `as const satisfies` for compile-time exhaustiveness over the failure-eligible stages. Naming convention (SCREAMING_SNAKE_CASE) matches CoherentMeterValueBuilder's PHASE_FAMILY/PHASE_RANK pattern for private module-scope Record lookup tables. Add OCPP20VariableManager.getInstance().resetRuntimeOverrides() to the shared standardCleanup test helper so per-station variable overrides do not leak between tests (all mock stations share a hardcoded hashId). Add 8 tests covering: supersession mid-download -> Idle, supersession mid-install -> InstallationFailed, throw during download -> DownloadFailed, throw during install -> InstallationFailed, happy path preserved -> Installed, supersession-with-emit race (T2 launched via constructor listener) -> Downloading preserved, InvalidSignature preserved, retries-exhausted DownloadFailed preserved. Closes #1969
f06c8c4 to
7d9ccf3
Compare
Closes #1969.
Problem
OCPP20IncomingRequestService.simulateFirmwareUpdateLifecyclewriteschargingStation.stationInfo.firmwareStatusat every status transition viasendFirmwareStatusNotification, but itsfinallyblock only cleared the per-station WeakMap state viaclearActiveFirmwareUpdate. On exception or abort (supersession,stop()),stationInfo.firmwareStatusretained the last-emitted non-terminal value indefinitely (e.g.'Downloading').The
TriggerMessage(FirmwareStatusNotification)reader inhandleRequestTriggerMessagealready cross-checks againstactiveFirmwareUpdateRequestId, but consumers ofhasFirmwareUpdateInProgress(handleRequestReset,isChargingStationIdle,isEvseIdle) readstationInfo.firmwareStatusas authoritative — the data-model split was a latent hazard.OCPP 2.0.1 spec anchors
L01.FR.24 (supersession)
Verbatim from
OCPP-2.0.1_edition3_part2_specification.md, Table 193:The lowercase
mayin the Note makes the terminal*FailedFirmwareStatusNotification on supersession optional.L02.FR.15Note omits the*FailedMAY clause entirely; the no-notification-from-finally behavior is safe for both L01 (Secure) and L02 (Non-Secure). Forward-compat with OCPP 2.1:L02.FR.15Note in OCPP 2.1 adds only aSame as L01.FR.24cross-reference tag (structural annotation), still no*Failedclause imported.FirmwareStatusEnumType (Idle restriction)
Verbatim from
OCPP-2.0.1_edition3_part2_specification.md, FirmwareStatusEnumType (Part 2 data types):Idleas a persistent local state is therefore only valid before install starts — once the lifecycle has entered install (stage = 'install'after successfulInstallingnotification), a clean abort must collapse toInstallationFailed(spec-recognized for the cancellation scenario per L01.FR.24 Note) rather thanIdle. TheIdleSHALL restriction is the exclusionary anchor (why notIdle); L01.FR.24 Note is the recognition anchor (whyInstallationFailedis spec-blessed). The internalstationInfo.firmwareStatusfield is a mirror of the last-sent notification value, and honoring the spec'sIdlescope-restriction at the field level keeps the mirror semantically valid.Fix
Track lifecycle stage via a module-scope
type FirmwareStage = 'download' | 'install' | 'installed'and aRecord<Exclude<FirmwareStage, 'installed'>, OCPP20FirmwareStatusEnumType>failure-status mapping. Namingstage(notphase) avoids collision with the electricalphaseterminology (L1-N/L2-N) elsewhere in the codebase. In the existingfinally, resetstationInfo.firmwareStatuswhen the lifecycle did not reachInstalled:stageaborteddownloadtrueIdleinstalltrueInstallationFaileddownloadfalseDownloadFailedinstallfalseInstallationFailedDownloadFailedemitted from trydownloadfalseisExplicitTerminalskips)InvalidSignatureemitted from trydownloadfalseisExplicitTerminalskips)activeFirmwareUpdateRequestIdinstalledsuccessorClaimedskips)installedInstalled)Compile-time-exhaustive failure-stage mapping
Exclude<FirmwareStage, 'installed'>narrows the key type to failure-eligible stages only — no unreachable entry.as const satisfies Record<...>enforces exhaustive coverage: adding a failure-eligible stage without a mapping fails compilation.Recordlookup tables (mirrorsPHASE_FAMILY/PHASE_RANKinCoherentMeterValueBuilder).Stage-tracker invariant
stageadvances only on actual advancement — never on error/abort branches. Two placements only:If the
Installingawaitrejects,stageremains'download'→DownloadFailed. If theInstalledawaitrejects,stagewas already'install'→InstallationFailed. If a supersession fires during an awaited sleep,abortController.signal.aborted === truecombines with the stage: download-phase →Idle; install-phase →InstallationFailed.Supersession-race guard
In production, supersession spawns a T2 lifecycle via the constructor's
UPDATE_FIRMWARElistener, which fires on bothAcceptedANDAcceptedCanceledresponses. If T1 is blocked on a non-abort-awareawait requestHandler(...)when supersession fires, T2 launches and claimsactiveFirmwareUpdateRequestIdbefore T1'sfinallyruns. The finally mirrorsclearActiveFirmwareUpdate's requestId-supersession pattern:Design constraints honoured:
finallydoes not emit aFirmwareStatusNotification— field reset only, per L01.FR.24 Note (mayis optional) + L02.FR.15 (no clause at all).sendFirmwareStatusNotification,hasFirmwareUpdateInProgress,clearActiveFirmwareUpdateare unchanged.finallystatement order unchanged; pre-existing "Guarantee cleanup..." comment preserved verbatim;clearActiveFirmwareUpdate(chargingStation, requestId)still the last statement.simulateFirmwareUpdateLifecycle+ module-scopeFirmwareStagetype +FIRMWARE_STAGE_FAILURE_STATUSmapping + the matching test file + one line added tostandardCleanuptest helper forOCPP20VariableManagersingleton state reset (fixes latent test-isolation trap, unrelated to [BUG] OCPP 2.0.1 firmware: stationInfo.firmwareStatus persists after abort or exception in simulateFirmwareUpdateLifecycle #1969 but discovered during review). No OCPP 1.6 changes (companion issues [BUG] OCPP 1.6: updateFirmwareSimulation setTimeout not cancelled on stop() #1972/[BUG] OCPP 1.6: DiagnosticsStatusNotification and FirmwareStatusNotification triggers read stale stationInfo status #1973 blocked by [FEATURE] OCPP 1.6: introduce per-station state WeakMap (prerequisite for supersession + timer-cancel + trigger cross-check) #1963, out of scope).Test coverage
8 new tests under a new
stationInfo.firmwareStatus reset on exit (issue #1969)describe block:stationInfo.firmwareStatusafterfinallyhandleRequestUpdateFirmwaresupersedes while first is betweenDownloadingandDownloadedIdlehandleRequestUpdateFirmwaresupersedes while first is betweenInstallingandInstalledInstallationFailedrequestHandlerrejects on theDownloadedFirmwareStatusNotificationDownloadFailedrequestHandlerrejects on theInstalledFirmwareStatusNotification (afterstage = 'install')InstallationFailedInstalledInstalled(untouched)handleRequestUpdateFirmware+ explicitservice.emit(UPDATE_FIRMWARE, ..., AcceptedCanceled)replicating the production T2-launch pathDownloading(T2 preserved; T1's finally skipped bysuccessorClaimed)SimulateSignatureVerificationFailure=truetriggers the L01.FR.03 emit pathInvalidSignature(preserved byisExplicitTerminal)DownloadFailedidempotenceretries: 1exhausts the L01.FR.30 retry loopDownloadFailed(preserved byisExplicitTerminal)All 8 pass. Full suite: 2963 pass / 0 fail / 6 skipped.
Verification gates
pnpm formatpnpm typecheckpnpm lintpnpm testpnpm buildFollow-up (out of scope)
#1979 filed — pre-existing L01.FR.26 SHALL violation in
handleRequestTriggerMessage'sFirmwareStatusNotificationcase: the trigger returnsIdleinstead of the last-sent status when the last-sent was a non-Installedterminal (DownloadFailed,InvalidSignature,InstallationFailed,InstallVerificationFailed). Root cause: no persistence of "last-sent notification" —hasFirmwareUpdateInProgressis used as a gate but is an "is-in-progress" predicate, not a "last-sent-status" projection. Full concrete fix design (interface addition +sendFirmwareStatusNotificationtouch + trigger handler rewrite + 4 test scenarios) in #1979. Independent of #1969; requires the "NO other changes" scope constraint of this PR to be lifted.Diff footprint
src/charging-station/ocpp/2.0/OCPP20IncomingRequestService.ts:FirmwareStagetype +FIRMWARE_STAGE_FAILURE_STATUSRecord<Exclude<..>, ..>withsatisfies, stage tracker + init, 2 stage transitions, finally reset block with 3-guard + spec-anchor comment covering L01.FR.24 + L02.FR.15 + FirmwareStatusEnumType Idle restriction.tests/charging-station/ocpp/2.0/OCPP20IncomingRequestService-UpdateFirmware.test.ts: 8 tests in new describe block.tests/helpers/TestLifecycleHelpers.ts: 1 line added tostandardCleanup—OCPP20VariableManager.getInstance().resetRuntimeOverrides()— to reset the per-station variable override singleton between tests (all mock stations share a hardcodedhashId; without the reset, per-station variable overrides leak).Review history
Seven internal review rounds; each round applied fixes for every VALID finding.
stage !== 'installed'finally reset). Oracle + Explore concurred on a MAJOR race hazard: supersession launches T2 via theAcceptedCanceledbranch of the constructor listener.successorClaimedguard (mirrorsclearActiveFirmwareUpdate's requestId-supersession pattern) +isExplicitTerminalguard (preservesInvalidSignature/DownloadFailed/InstallationFailedemitted from inside try) + 3 tests (race with emit, InvalidSignature preservation, retries-exhausted idempotence).finallycomment compressed;activeRequestIddestructured; PR-review references stripped from test comment.phase→stage(Oracle:phasecollides with electricalphasein the same file); replaced nested ternary withRecord<FirmwareStage, ...>+satisfies; added L02.FR.15 clarification (Librarian: L02 lacks L01.FR.24's*FailedMAY clause); corrected commit body(MAY)→optional; filed [BUG] OCPP 2.0.1 firmware: TriggerMessage(FirmwareStatusNotification) violates L01.FR.26 after non-Installed terminal emissions #1979 with concrete fix design for pre-existing L01.FR.26 gap.firmwareStageTerminal→FIRMWARE_STAGE_FAILURE_STATUS(Explore + Oracle concurrence: SCREAMING_SNAKE_CASE for private module-scopeRecordlookup tables per codebase norm); tightened Record type toRecord<Exclude<FirmwareStage, 'installed'>, ...>(remove unreachableinstalledentry, preserve compile-time exhaustiveness over failure-eligible key set).Idlerestricted to download-phase clean aborts (per FirmwareStatusEnumType definition), install-phase clean aborts now collapse toInstallationFailed. Applied Explore F1.7:OCPP20VariableManager.getInstance().resetRuntimeOverrides()added tostandardCleanup.FirmwareStatusEnumType.IdleSHALL restriction as the exclusionary anchor for whyIdlecannot be a persistent local state after install starts + L01.FR.24 Note as the recognition anchor forInstallationFailedbeing spec-blessed for cancellation (rather than the prior imprecise cite of MAY-clause-alone for field-value justification, which conflated notification-emission permission with local-state-value permission); (b) Test 2 title extended from(L01.FR.24 MAY)to(Idle TriggerMessage-only; L01.FR.24 MAY)to reflect the dual anchor. Explore performed full audit ofstandardCleanup— 163 test-file call sites, 11 directOCPP20VariableManagerconsumers — zero cross-test hazards, sub-microsecond perf impact, all safe. Librarian re-verified byte-exact spec quotes forFirmwareStatusEnumType.Idle/InstallationFailed/DownloadFailedand OCPP 2.1 forward-compat — no drift.