Skip to content

fix(ocpp): reset stationInfo.firmwareStatus on abort/exception in simulateFirmwareUpdateLifecycle - #1976

Merged
jerome-benoit merged 1 commit into
mainfrom
fix/ocpp20-firmware-status-reset-on-abort
Jul 8, 2026
Merged

jerome-benoit merged 1 commit into
mainfrom
fix/ocpp20-firmware-status-reset-on-abort

Conversation

@jerome-benoit

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

Copy link
Copy Markdown
Contributor

Closes #1969.

Problem

OCPP20IncomingRequestService.simulateFirmwareUpdateLifecycle writes chargingStation.stationInfo.firmwareStatus at every status transition via sendFirmwareStatusNotification, but its finally block only cleared the per-station WeakMap state via clearActiveFirmwareUpdate. On exception or abort (supersession, stop()), stationInfo.firmwareStatus retained the last-emitted non-terminal value indefinitely (e.g. 'Downloading').

The TriggerMessage(FirmwareStatusNotification) reader in handleRequestTriggerMessage already cross-checks against activeFirmwareUpdateRequestId, but consumers of hasFirmwareUpdateInProgress (handleRequestReset, isChargingStationIdle, isEvseIdle) read stationInfo.firmwareStatus as 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:

Precondition — When a Charging Station is installing new Firmware OR is going to install new Firmware, but has received an UpdateFirmware command to install it at a later time AND the Charging Station receives a new UpdateFirmwareRequest

Requirement definition — The Charging Station SHOULD cancel the ongoing firmware update AND respond with status AcceptedCanceled.

Note — The Charging Station SHOULD NOT first check if the new firmware file exists, this way the CSMS will be able to cancel an ongoing firmware update without starting a new one. The Charging Station may send a FirmwareStatusNotificationRequest with status DownloadFailed or InstallationFailed for the firmware update that has now been canceled.

The lowercase may in the Note makes the terminal *Failed FirmwareStatusNotification on supersession optional. L02.FR.15 Note omits the *Failed MAY 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.15 Note in OCPP 2.1 adds only a Same as L01.FR.24 cross-reference tag (structural annotation), still no *Failed clause imported.

FirmwareStatusEnumType (Idle restriction)

Verbatim from OCPP-2.0.1_edition3_part2_specification.md, FirmwareStatusEnumType (Part 2 data types):

Idle — Charging Station is not performing firmware update related tasks. Status Idle SHALL only be used as in a FirmwareStatusNotificationRequest that was triggered by TriggerMessageRequest.

Idle as a persistent local state is therefore only valid before install starts — once the lifecycle has entered install (stage = 'install' after successful Installing notification), a clean abort must collapse to InstallationFailed (spec-recognized for the cancellation scenario per L01.FR.24 Note) rather than Idle. The Idle SHALL restriction is the exclusionary anchor (why not Idle); L01.FR.24 Note is the recognition anchor (why InstallationFailed is spec-blessed). The internal stationInfo.firmwareStatus field is a mirror of the last-sent notification value, and honoring the spec's Idle scope-restriction at the field level keeps the mirror semantically valid.

Fix

Track lifecycle stage via a module-scope type FirmwareStage = 'download' | 'install' | 'installed' and a Record<Exclude<FirmwareStage, 'installed'>, OCPP20FirmwareStatusEnumType> failure-status mapping. Naming stage (not phase) avoids collision with the electrical phase terminology (L1-N/L2-N) elsewhere in the codebase. In the existing finally, reset stationInfo.firmwareStatus when the lifecycle did not reach Installed:

Exit path stage aborted Terminal value
Clean supersession/stop mid-download download true Idle
Clean supersession/stop mid-install install true InstallationFailed
Exception during download download false DownloadFailed
Exception during install install false InstallationFailed
Retries-exhausted DownloadFailed emitted from try download false (preserved — isExplicitTerminal skips)
InvalidSignature emitted from try download false (preserved — isExplicitTerminal skips)
Successor lifecycle (T2) has already claimed activeFirmwareUpdateRequestId any non-installed any (preserved — successorClaimed skips)
Happy path completion installed any (untouched — remains Installed)

Compile-time-exhaustive failure-stage mapping

type FirmwareStage = 'download' | 'install' | 'installed'

const FIRMWARE_STAGE_FAILURE_STATUS = {
  download: OCPP20FirmwareStatusEnumType.DownloadFailed,
  install: OCPP20FirmwareStatusEnumType.InstallationFailed,
} as const satisfies Record<Exclude<FirmwareStage, 'installed'>, OCPP20FirmwareStatusEnumType>
  • 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.
  • SCREAMING_SNAKE_CASE naming matches the codebase convention for private module-scope Record lookup tables (mirrors PHASE_FAMILY / PHASE_RANK in CoherentMeterValueBuilder).

Stage-tracker invariant

stage advances only on actual advancement — never on error/abort branches. Two placements only:

await this.sendFirmwareStatusNotification(chargingStation, OCPP20FirmwareStatusEnumType.Installing, requestId)
stage = 'install'
// ... sleep + checkAborted ...
await this.sendFirmwareStatusNotification(chargingStation, OCPP20FirmwareStatusEnumType.Installed, requestId)
stage = 'installed'

If the Installing await rejects, stage remains 'download' → DownloadFailed. If the Installed await rejects, stage was already 'install' → InstallationFailed. If a supersession fires during an awaited sleep, abortController.signal.aborted === true combines with the stage: download-phase → Idle; install-phase → InstallationFailed.

Supersession-race guard

In production, supersession spawns a T2 lifecycle via the constructor's UPDATE_FIRMWARE listener, which fires on both Accepted AND AcceptedCanceled responses. If T1 is blocked on a non-abort-aware await requestHandler(...) when supersession fires, T2 launches and claims activeFirmwareUpdateRequestId before T1's finally runs. The finally mirrors clearActiveFirmwareUpdate's requestId-supersession pattern:

} finally {
  // ... spec-anchor + rationale comment ...
  const activeRequestId =
    this.stationsState.get(chargingStation)?.activeFirmwareUpdateRequestId
  const successorClaimed = activeRequestId != null && activeRequestId !== requestId
  const currentStatus = chargingStation.stationInfo?.firmwareStatus
  const isExplicitTerminal =
    currentStatus === OCPP20FirmwareStatusEnumType.DownloadFailed ||
    currentStatus === OCPP20FirmwareStatusEnumType.InstallationFailed ||
    currentStatus === OCPP20FirmwareStatusEnumType.InvalidSignature
  if (
    stage !== 'installed' &&
    !successorClaimed &&
    !isExplicitTerminal &&
    chargingStation.stationInfo != null
  ) {
    chargingStation.stationInfo.firmwareStatus =
      abortController.signal.aborted && stage === 'download'
        ? OCPP20FirmwareStatusEnumType.Idle
        : FIRMWARE_STAGE_FAILURE_STATUS[stage]
  }
  // Guarantee cleanup on every exit path (happy, abort, throw): without
  // this, a thrown await would leave activeFirmwareUpdateAbortController
  // set and any subsequent UpdateFirmware.req would abort a non-existent
  // in-progress update while the station stays stuck.
  this.clearActiveFirmwareUpdate(chargingStation, requestId)
}

Design constraints honoured:

Test coverage

8 new tests under a new stationInfo.firmwareStatus reset on exit (issue #1969) describe block:

# Scenario Trigger Expected stationInfo.firmwareStatus after finally
1 Clean abort mid-download Second handleRequestUpdateFirmware supersedes while first is between Downloading and Downloaded Idle
2 Clean abort mid-install Second handleRequestUpdateFirmware supersedes while first is between Installing and Installed InstallationFailed
3 Exception during download Mock requestHandler rejects on the Downloaded FirmwareStatusNotification DownloadFailed
4 Exception during install Mock requestHandler rejects on the Installed FirmwareStatusNotification (after stage = 'install') InstallationFailed
5 Happy path preserved Full lifecycle to Installed Installed (untouched)
6 Supersession-with-emit race Second handleRequestUpdateFirmware + explicit service.emit(UPDATE_FIRMWARE, ..., AcceptedCanceled) replicating the production T2-launch path Downloading (T2 preserved; T1's finally skipped by successorClaimed)
7 InvalidSignature preservation SimulateSignatureVerificationFailure=true triggers the L01.FR.03 emit path InvalidSignature (preserved by isExplicitTerminal)
8 Retries-exhausted DownloadFailed idempotence Invalid location + retries: 1 exhausts the L01.FR.30 retry loop DownloadFailed (preserved by isExplicitTerminal)

All 8 pass. Full suite: 2963 pass / 0 fail / 6 skipped.

Verification gates

Gate Result
pnpm format exit 0
pnpm typecheck 0 errors
pnpm lint 0 errors
pnpm test 2963 pass / 0 fail / 6 skipped
pnpm build exit 0

Follow-up (out of scope)

#1979 filed — pre-existing L01.FR.26 SHALL violation in handleRequestTriggerMessage's FirmwareStatusNotification case: the trigger returns Idle instead of the last-sent status when the last-sent was a non-Installed terminal (DownloadFailed, InvalidSignature, InstallationFailed, InstallVerificationFailed). Root cause: no persistence of "last-sent notification" — hasFirmwareUpdateInProgress is used as a gate but is an "is-in-progress" predicate, not a "last-sent-status" projection. Full concrete fix design (interface addition + sendFirmwareStatusNotification touch + 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: FirmwareStage type + FIRMWARE_STAGE_FAILURE_STATUS Record<Exclude<..>, ..> with satisfies, 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 to standardCleanup — OCPP20VariableManager.getInstance().resetRuntimeOverrides() — to reset the per-station variable override singleton between tests (all mock stations share a hardcoded hashId; without the reset, per-station variable overrides leak).

Review history

Seven internal review rounds; each round applied fixes for every VALID finding.

  • v1 — initial fix (stage tracker + basic stage !== 'installed' finally reset). Oracle + Explore concurred on a MAJOR race hazard: supersession launches T2 via the AcceptedCanceled branch of the constructor listener.
  • v2 — added successorClaimed guard (mirrors clearActiveFirmwareUpdate's requestId-supersession pattern) + isExplicitTerminal guard (preserves InvalidSignature/DownloadFailed/InstallationFailed emitted from inside try) + 3 tests (race with emit, InvalidSignature preservation, retries-exhausted idempotence).
  • v3 — type alias moved to module scope; finally comment compressed; activeRequestId destructured; PR-review references stripped from test comment.
  • v4 — renamed phase → stage (Oracle: phase collides with electrical phase in the same file); replaced nested ternary with Record<FirmwareStage, ...> + satisfies; added L02.FR.15 clarification (Librarian: L02 lacks L01.FR.24's *Failed MAY 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.
  • v5 — renamed firmwareStageTerminal → FIRMWARE_STAGE_FAILURE_STATUS (Explore + Oracle concurrence: SCREAMING_SNAKE_CASE for private module-scope Record lookup tables per codebase norm); tightened Record type to Record<Exclude<FirmwareStage, 'installed'>, ...> (remove unreachable installed entry, preserve compile-time exhaustiveness over failure-eligible key set).
  • v6 — Oracle rewrote the finally comment; test comment de-anchored from line numbers (all line numbers removed from source, tests, PR body, and issue [BUG] OCPP 2.0.1 firmware: TriggerMessage(FirmwareStatusNotification) violates L01.FR.26 after non-Installed terminal emissions #1979 body — symbol-name references only, since line numbers drift on every insertion). Applied Librarian F2 spec-strict fix: Idle restricted to download-phase clean aborts (per FirmwareStatusEnumType definition), install-phase clean aborts now collapse to InstallationFailed. Applied Explore F1.7: OCPP20VariableManager.getInstance().resetRuntimeOverrides() added to standardCleanup.
  • v7 — Oracle + Librarian concurred (2/2) on two spec-precision findings. Applied: (a) finally comment now cites FirmwareStatusEnumType.Idle SHALL restriction as the exclusionary anchor for why Idle cannot be a persistent local state after install starts + L01.FR.24 Note as the recognition anchor for InstallationFailed being 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 of standardCleanup — 163 test-file call sites, 11 direct OCPP20VariableManager consumers — zero cross-test hazards, sub-microsecond perf impact, all safe. Librarian re-verified byte-exact spec quotes for FirmwareStatusEnumType.Idle/InstallationFailed/DownloadFailed and OCPP 2.1 forward-compat — no drift.

@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: Reset stationInfo.firmwareStatus on abort or exception in simulateFirmwareUpdateLifecycle

Problem

In OCPP20IncomingRequestService.simulateFirmwareUpdateLifecycle, chargingStation.stationInfo.firmwareStatus was updated at every status transition (Downloading, Downloaded, Installing, …) but the finally block only cleared the per-station WeakMap state (activeFirmwareUpdateAbortController, activeFirmwareUpdateRequestId). On clean abort (supersession or stop()) or mid-lifecycle exception, stationInfo.firmwareStatus would retain the last non-terminal value (e.g. 'Downloading') indefinitely — a stale data-model state that any future consumer not cross-checking activeFirmwareUpdateRequestId would observe as an in-progress update.

Fix

A phase tracker variable ('download' | 'install' | 'installed') is introduced in the lifecycle scope and advances only on successful awaits:

  • After Installing notification succeeds → phase = 'install'
  • After Installed notification succeeds → phase = 'installed'

In the finally block, when phase !== 'installed', stationInfo.firmwareStatus is reset to a coherent terminal value:

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

@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 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

Comment on lines +3981 to +3987
if (phase !== 'installed' && chargingStation.stationInfo != null) {
chargingStation.stationInfo.firmwareStatus = abortController.signal.aborted
? OCPP20FirmwareStatusEnumType.Idle
: phase === 'install'
? OCPP20FirmwareStatusEnumType.InstallationFailed
: OCPP20FirmwareStatusEnumType.DownloadFailed
}

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.

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.

Suggested change
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'

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.

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.

Suggested change
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

@jerome-benoit

Copy link
Copy Markdown
Contributor Author

L01.FR.26 follow-up filed as #1979 with the concrete fix design (last-sent-notification persistence on OCPP20StationState + trigger handler rewrite + 4 test scenarios). Pre-existing gap; independent of this PR.

@jerome-benoit
jerome-benoit force-pushed the fix/ocpp20-firmware-status-reset-on-abort branch 3 times, most recently from 04bbb46 to f06c8c4 Compare July 8, 2026 02:02
…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
@jerome-benoit
jerome-benoit force-pushed the fix/ocpp20-firmware-status-reset-on-abort branch from f06c8c4 to 7d9ccf3 Compare July 8, 2026 02:14
@jerome-benoit
jerome-benoit merged commit 4f959e9 into main Jul 8, 2026
44 checks passed
@jerome-benoit
jerome-benoit deleted the fix/ocpp20-firmware-status-reset-on-abort 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] OCPP 2.0.1 firmware: stationInfo.firmwareStatus persists after abort or exception in simulateFirmwareUpdateLifecycle

1 participant