Skip to content

fix(ocpp): drive FirmwareStatusNotification trigger from last-sent notification (L01.FR.26) - #1981

Merged
jerome-benoit merged 1 commit into
mainfrom
fix/ocpp20-firmware-trigger-l01-fr-26-last-sent
Jul 8, 2026
Merged

jerome-benoit merged 1 commit into
mainfrom
fix/ocpp20-firmware-trigger-l01-fr-26-last-sent

Conversation

@jerome-benoit

Copy link
Copy Markdown
Contributor

Closes #1979.

Bug

OCPP20IncomingRequestService, in the FirmwareStatusNotification case of the TRIGGER_MESSAGE listener, gated the emitted FirmwareStatusNotification on activeFirmwareUpdateRequestId != null && hasFirmwareUpdateInProgress() and fell back to Idle otherwise. hasFirmwareUpdateInProgress returns false for every terminal firmware status (DownloadFailed, InvalidSignature, InstallationFailed, InstallVerificationFailed, Installed). After any non-Installed terminal was emitted from simulateFirmwareUpdateLifecycle, an incoming TriggerMessage(FirmwareStatusNotification) returned Idle instead of the last-sent status — a SHALL violation of L01.FR.26 (and its L02.FR.17 mirror).

OCPP spec anchors

Verbatim from OCPP-2.0.1_edition3_part2_specification.md:

  • L01.FR.25 (Table 193): "Charging Station receives a TriggerMessageRequest for FirmwareStatusNotification AND last sent FirmwareStatusNotificationRequest had status = Installed" → "Charging Station SHALL return a FirmwareStatusNotificationRequest with status = Idle."
  • L01.FR.26 (Table 193): "Charging Station receives a TriggerMessageRequest for FirmwareStatusNotification AND last sent FirmwareStatusNotificationRequest had NOT status Installed" → "Charging Station SHALL return a FirmwareStatusNotificationRequest with the last sent status." — the violated SHALL.
  • L01.FR.20 (Table 193): "The field requestId in FirmwareStatusNotificationRequest is mandatory, unless status = Idle."
  • FirmwareStatusEnumType (§ 3.33), value 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."
  • L02.FR.16 / L02.FR.17 (Table 195, Non-Secure Firmware): mirror L01.FR.25 / L01.FR.26 byte-for-byte (verified verbatim). L02.FR.14 mirrors L01.FR.20 byte-for-byte. The single unified trigger path in OCPP20IncomingRequestService covers both use cases, so this fix satisfies L01 and L02 in one change.

Fix (three touchpoints, ~15 SLOC net)

  1. Extend OCPP20StationState with an optional lastFirmwareStatusNotification: { requestId: number; status: OCPP20FirmwareStatusEnumType } (alphabetized).
  2. Persist inside sendFirmwareStatusNotification immediately after the existing stationInfo.firmwareStatus = status assignment — every emission path writes it.
  3. Replace the FirmwareStatusNotification trigger case body with a last-sent-driven emit:
    • lastSent == null OR lastSent.status === Installed → { status: Idle } (L01.FR.25 + fresh station)
    • else → { requestId: lastSent.requestId, status: lastSent.status } (L01.FR.26)

The trigger case body uses a typed local payload: OCPP20FirmwareStatusNotificationRequest — control-flow narrowing on the Installed discriminant gives a clean typed result without the as OCPP20FirmwareStatusNotificationRequest cast that appeared in the issue's design sketch.

Dual-source rationale (deliberate, documented)

stationInfo.firmwareStatus is retained. Its three downstream consumers — handleRequestReset firmware-update rejection (L2336), isChargingStationIdle (L3304), isEvseIdle (L3319) — all use hasFirmwareUpdateInProgress, an "is an update currently running?" predicate, not an "L01.FR.26 last-sent projection". The two projections are orthogonal:

Source Semantics Consumers
stationInfo.firmwareStatus "in-progress" predicate via hasFirmwareUpdateInProgress (non-terminals only) Reset gate, station-idle, EVSE-idle
lastFirmwareStatusNotification "last-sent" projection (L01.FR.25 / L01.FR.26 / L02.FR.16 / L02.FR.17) TriggerMessage(FirmwareStatusNotification)

Unifying them is out of scope for this L01.FR.26 fix and would change reset-gate / idle-predicate behavior. The dual-source is anchored at the persistence site by an inline OCPP spec comment.

Test coverage

Added to tests/charging-station/ocpp/2.0/OCPP20IncomingRequestService-TriggerMessage.test.ts under new describe F06 - FirmwareStatusNotification trigger last-sent semantics (L01.FR.20/25/26, L02.FR.14/16/17). State is seeded through the real sendFirmwareStatusNotification code path via the testable interface, then the trigger event is emitted and the resulting request-handler payload is asserted.

# Scenario Assertion Anchor
1 Post-DownloadFailed (retries exhausted) { requestId: 42, status: DownloadFailed } + skipBufferingOnError + triggerMessage L01.FR.26
2 Post-InvalidSignature { requestId: 7, status: InvalidSignature } L01.FR.26
3 Post-InstallationFailed { requestId: 99, status: InstallationFailed } L01.FR.26
4 Post-Installed (happy path) { status: Idle } (no requestId) L01.FR.25 regression
5 Fresh station (no notification ever sent) { status: Idle } (no requestId) Fresh-boot semantics
6 L01.FR.20 guard across every non-Installed status + Installed + fresh requestId present iff status ≠ Idle L01.FR.20

Verification gates

  • pnpm format — clean on edited files
  • pnpm typecheck — 0 errors
  • pnpm lint — 0 new errors
  • pnpm test — 2974 pass / 0 fail (6 pre-existing skipped)
  • pnpm build — exit 0
  • Grep sanity: lastFirmwareStatusNotification appears in exactly 3 places (interface declaration, trigger read, sendFirmwareStatusNotification write)
  • hasFirmwareUpdateInProgress body: unchanged
  • simulateFirmwareUpdateLifecycle: untouched (diff scan: 0 hits)

Related work

@hyperspace-pr-bot

Copy link
Copy Markdown
Contributor

Summary

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


fix(ocpp): drive FirmwareStatusNotification trigger from last-sent notification (L01.FR.26)

🐛 Bug Fix

Fixes a SHALL violation of OCPP 2.0.1 L01.FR.26 (mirrored by L02.FR.17): after a non-Installed terminal firmware status (DownloadFailed, InvalidSignature, InstallationFailed, InstallVerificationFailed) was emitted, an incoming TriggerMessage(FirmwareStatusNotification) incorrectly responded with Idle instead of the last-sent status.

Root cause: The trigger handler gated its response on hasFirmwareUpdateInProgress(), which returns false for all terminal statuses — an "is-update-running?" predicate rather than an "L01.FR.26 last-sent-status" projection.

Changes

Three targeted touchpoints (~15 SLOC net):

  1. OCPP20StationState interface — adds optional lastFirmwareStatusNotification: { requestId: number; status: OCPP20FirmwareStatusEnumType } to persist the last-sent notification.

  2. sendFirmwareStatusNotification — persists lastFirmwareStatusNotification on every emission path, alongside the existing stationInfo.firmwareStatus assignment. A spec-anchor comment explains the dual-source design.

  3. FirmwareStatusNotification trigger case — replaced the hasFirmwareUpdateInProgress-gated logic with a last-sent-driven emit:

    • lastSent == null or lastSent.status === Installed → { status: Idle } (L01.FR.25 + fresh station)
    • otherwise → { requestId: lastSent.requestId, status: lastSent.status } (L01.FR.26)

    The typed payload: OCPP20FirmwareStatusNotificationRequest local removes the previous as OCPP20FirmwareStatusNotificationRequest cast.

  4. Testable interface (__testable__/index.ts) — exposes sendFirmwareStatusNotification so tests can seed state through the real code path.

✅ Tests Added

6 new tests under F06 - FirmwareStatusNotification trigger last-sent semantics (L01.FR.20/25/26, L02.FR.14/16/17):

Scenario Assertion Anchor
Post-DownloadFailed { requestId: 42, status: DownloadFailed } L01.FR.26
Post-InvalidSignature { requestId: 7, status: InvalidSignature } L01.FR.26
Post-InstallationFailed { requestId: 99, status: InstallationFailed } L01.FR.26
Post-Installed { status: Idle } (no requestId) L01.FR.25 regression
Fresh station { status: Idle } (no requestId) Fresh-boot semantics
L01.FR.20 across all statuses requestId present iff status ≠ Idle L01.FR.20

Full suite: 2974 pass / 0 fail / 6 skipped.

Closes #1979. Follow-up from #1976.

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

  • 🔄 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 implements the L01.FR.26 fix. Two issues were identified: a test closure-staleness bug where captureTriggeredFirmwareStatusPayload closes over mockStation/requestHandlerMock variables that get reassigned mid-test (causing the assertion to read from the wrong mock instance in the parametric loop), and a minor forward-compatibility gap in sendFirmwareStatusNotification where requestId is unconditionally included in the sent OCPP payload even for a hypothetical future Idle-status call, inconsistent with L01.FR.20 and the trigger-case logic added in this very PR.

PR Bot Information

Version: 1.27.2

Comment on lines +773 to +779
for (const status of nonInstalledStatuses) {
;({ mockStation, requestHandlerMock } = createTriggerMessageStation())
incomingRequestServiceForListener = new OCPP20IncomingRequestService()
testableService = createTestableIncomingRequestService(incomingRequestServiceForListener)
await seedLastSent(status, seed)

const { payload } = captureTriggeredFirmwareStatusPayload()

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: captureTriggeredFirmwareStatusPayload always reads from requestHandlerMock.mock.calls[0] but the mockStation variable it closes over is reassigned by seedLastSent indirectly (via re-assignments to { mockStation, requestHandlerMock } inside the parametric loop at lines 774 and 790). Within the loop the helper is re-invoked after those re-assignments, so captureTriggeredFirmwareStatusPayload emits on the old incomingRequestServiceForListener but asserts against the new requestHandlerMock. The assertion at line 685 (requestHandlerMock.mock.callCount() === 1) will therefore always read from the reset mock and will fail because it was never called by the old service instance, producing a misleading test failure.

The helper should take explicit parameters so each iteration operates on a consistent trio, or the re-assignments inside the test body at lines 774–777 and 790–792 should be refactored so the closure always captures the current values.


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

Comment on lines +3554 to +3557
this.getOrCreateStationState(chargingStation).lastFirmwareStatusNotification = {
requestId,
status,
}

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: sendFirmwareStatusNotification always includes requestId in the outgoing OCPP message at line 3562, even when status is OCPP20FirmwareStatusEnumType.Idle. Per L01.FR.20 (quoted in the PR description): "The field requestId in FirmwareStatusNotificationRequest is mandatory, unless status = Idle." No current internal caller passes Idle, but the lack of a guard means any future call with Idle would silently send a spec-violating payload that also contradicts the trigger path which deliberately omits requestId for Idle. Consider adding a payload guard analogous to the trigger-case logic so the method is always spec-compliant regardless of caller:

const payload: OCPP20FirmwareStatusNotificationRequest =
  status === OCPP20FirmwareStatusEnumType.Idle
    ? { status }
    : { requestId, status }
return chargingStation.ocppRequestService.requestHandler<
  OCPP20FirmwareStatusNotificationRequest,
  OCPP20FirmwareStatusNotificationResponse
>(chargingStation, OCPP20RequestCommand.FIRMWARE_STATUS_NOTIFICATION, payload)

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

Comment on lines +581 to +588
// L01.FR.25 (mirrored by L02.FR.16): last-sent = Installed → Idle.
// L01.FR.26 (mirrored by L02.FR.17): last-sent ≠ Installed → last-sent status.
// L01.FR.20 (mirrored by L02.FR.14): requestId is mandatory unless status = Idle.
// Fresh station (no notification ever sent) → Idle: spec is silent
// on this precondition, and FirmwareStatusEnumType defines Idle as
// "Charging Station is not performing firmware update related tasks.
// Status Idle SHALL only be used as in a FirmwareStatusNotificationRequest
// that was triggered by TriggerMessageRequest."

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Style, ≥2 reviewers concur — optional]

Oracle H2 + Explore #2/#3 both flag: this 7-line spec-anchor comment overlaps with the block at sendFirmwareStatusNotification L3549-3553 in the same PR. Both cite the same L01.FR.25/26 / L02.FR.16/17 anchor set. Adjacent trigger cases (BootNotification, Heartbeat, LogStatusNotification) carry zero comments — this block is the outlier.

Suggested consolidation: keep the full rationale (with the FirmwareStatusEnumType Idle quote and dual-source note) on the write side (sendFirmwareStatusNotification — the semantic source of truth for the projection), and shrink this trigger-case block to a one-liner:

// L01.FR.25/26 & L02.FR.16/17 — see sendFirmwareStatusNotification for the last-sent persistence rationale.

DRY per AGENTS.md. Non-blocking style suggestion.

Comment on lines +3554 to +3557
this.getOrCreateStationState(chargingStation).lastFirmwareStatusNotification = {
requestId,
status,
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Informational — pre-existing, out of scope]

Oracle H1: this persistence happens BEFORE the requestHandler(...) Promise resolves (the write is fire-and-forget from this method's perspective — the caller in simulateFirmwareUpdateLifecycle awaits it, but by then this write has already committed). If the WebSocket send rejects at the transport layer, lastFirmwareStatusNotification records a status that never reached the CSMS, and a subsequent TriggerMessage(FirmwareStatusNotification) will echo a status the CSMS never saw — technically satisfying "last SENT" only in the "last ATTEMPTED to send" sense.

Pre-existing symmetry with the stationInfo.firmwareStatus = status assignment two lines up (same fire-and-forget behavior). L01.FR.26 is silent on wire-failure semantics, so this is not a spec violation. Not blocking.

Follow-up candidate: move both assignments inside .then((response) => { … }) on the returned Promise, so both fields reflect "acknowledged by CSMS" rather than "attempted to emit". Symmetry with #1976's finally-block reset would need to be preserved.

Comment on lines +756 to +803
await it('should honor L01.FR.20 (requestId mandatory unless status = Idle) across every last-sent status', async () => {
const nonInstalledStatuses: OCPP20FirmwareStatusEnumType[] = [
OCPP20FirmwareStatusEnumType.DownloadFailed,
OCPP20FirmwareStatusEnumType.DownloadPaused,
OCPP20FirmwareStatusEnumType.DownloadScheduled,
OCPP20FirmwareStatusEnumType.Downloaded,
OCPP20FirmwareStatusEnumType.Downloading,
OCPP20FirmwareStatusEnumType.InstallRebooting,
OCPP20FirmwareStatusEnumType.InstallScheduled,
OCPP20FirmwareStatusEnumType.InstallVerificationFailed,
OCPP20FirmwareStatusEnumType.InstallationFailed,
OCPP20FirmwareStatusEnumType.Installing,
OCPP20FirmwareStatusEnumType.InvalidSignature,
OCPP20FirmwareStatusEnumType.SignatureVerified,
]

let seed = 1000
for (const status of nonInstalledStatuses) {
;({ mockStation, requestHandlerMock } = createTriggerMessageStation())
incomingRequestServiceForListener = new OCPP20IncomingRequestService()
testableService = createTestableIncomingRequestService(incomingRequestServiceForListener)
await seedLastSent(status, seed)

const { payload } = captureTriggeredFirmwareStatusPayload()

assert.strictEqual(payload.status, status, `expected trigger to echo ${status}`)
assert.strictEqual(
payload.requestId,
seed,
`expected requestId=${seed.toString()} to be present for non-Idle status ${status}`
)
seed += 1
}

;({ mockStation, requestHandlerMock } = createTriggerMessageStation())
incomingRequestServiceForListener = new OCPP20IncomingRequestService()
testableService = createTestableIncomingRequestService(incomingRequestServiceForListener)
await seedLastSent(OCPP20FirmwareStatusEnumType.Installed, 2000)
const { payload: installedPayload } = captureTriggeredFirmwareStatusPayload()
assert.strictEqual(installedPayload.status, OCPP20FirmwareStatusEnumType.Idle)
assert.strictEqual(installedPayload.requestId, undefined)

;({ mockStation, requestHandlerMock } = createTriggerMessageStation())
incomingRequestServiceForListener = new OCPP20IncomingRequestService()
testableService = createTestableIncomingRequestService(incomingRequestServiceForListener)
const { payload: freshPayload } = captureTriggeredFirmwareStatusPayload()
assert.strictEqual(freshPayload.status, OCPP20FirmwareStatusEnumType.Idle)
assert.strictEqual(freshPayload.requestId, undefined)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

[Style nit — Explore #4 + personal pass; Oracle deferred]

This L01.FR.20 guard manually re-instantiates the fixture 14 times inside a single it to escape stale stationsState bleed-over between iterations. The codebase's idiomatic parametric-test pattern is at L445-L485 in this file:

for (const { name, trigger } of triggerCases) {
  await it(`should fire ${name} requestHandler on Accepted`, () => { ... })
}

Refactoring test #6 to a for-of around await it(...) would:

  • give proper per-iteration beforeEach isolation for free (removes the 3 manual re-instantiations);
  • surface each of the 14 status cases as a separate test result (better failure localization);
  • align with the file's own precedent.

Oracle explicitly deferred this as "verbose but defensive — helper-extraction is cosmetic". Non-blocking; happy to skip if you'd rather keep the guard as a single monolithic it for atomic-invariant framing.

@jerome-benoit

Copy link
Copy Markdown
Contributor Author

Response to @hyperspace-insights[bot] findings (review)

Applying v7 caller-trace FP filter — both bot claims verified empirically.

Bot Claim 1: closure-staleness in test #6 — FALSE POSITIVE

Bot: "captureTriggeredFirmwareStatusPayload closes over mockStation/requestHandlerMock that get reassigned mid-test (causing the assertion to read from the wrong mock instance)."

Refutation:

  1. Language semantics. The captured variables are declared with let at the describe-block scope (test.ts:658-661). JS closures capture bindings, not values — reassigning a let between calls is visible to the closure on the next invocation. The ({ mockStation, requestHandlerMock } = createTriggerMessageStation()) destructuring assignment mutates the same binding, so seedLastSent() and captureTriggeredFirmwareStatusPayload() read the current iteration's fresh instances every call.
  2. Empirical. Isolated re-run of test Add UI HTTP server  #6:
    ✔ should honor L01.FR.20 (requestId mandatory unless status = Idle)
      across every last-sent status (534.34ms)
    
    If the bug were real, per-iteration assertions on 12 distinct requestId seeds (1000..1011) plus the Installed→Idle and fresh-station cases would fail on the very first iteration.
  3. Bug shape doesn't match: a closure-value-capture bug would fix the fixture to the first iteration's createTriggerMessageStation() instance, making iteration 2's sendFirmwareStatusNotification call go to a stale mock — the callCount assertion (===1 after resetCalls()) would still hold, but the payload would carry the previous iteration's status, so the assert.strictEqual(payload.status, status) would fail. It does not.

Bot Claim 2: requestId unconditionally in payload even for hypothetical future Idle — Technically valid, non-defect

Bot: "inconsistent with L01.FR.20 and the trigger-case logic added in this very PR."

Analysis:

  1. Spec reading. L01.FR.20 verbatim: "The field requestId in FirmwareStatusNotificationRequest is mandatory, unless status = Idle." This means Idle permits omission — it does NOT forbid presence. OCPP20FirmwareStatusNotificationRequest.requestId?: number is schema-optional. Passing { requestId: X, status: Idle } is schema-valid, hence not a SHALL violation.
  2. Callsite trace (v7 caller-trace): sendFirmwareStatusNotification is private. All 10 callers in simulateFirmwareUpdateLifecycle pass a real requestId from activeFirmwareUpdateRequestId, never Idle. Idle is never persisted through this method by construction.
  3. The trigger-case asymmetry is deliberate. Trigger case emits { status: Idle } (no requestId) via .requestHandler(...) directly, precisely because it does NOT route through sendFirmwareStatusNotification (which would incorrectly re-persist the trigger response into lastFirmwareStatusNotification). The two paths ARE meant to look different.
  4. Oracle concur: "If a future refactor accidentally calls this method with Idle outside the trigger path, it would violate the spec — though that would be a spec violation in the caller, not a defect in this code."

Defensive guard (5 SLOC to strip requestId when Idle) would harden against a hypothetical future refactor that doesn't currently exist. Non-blocking. Filing as a follow-up candidate if the reviewer wants belt-and-braces.


Convergence result: bot findings do not require amendments. My self-review's convergent style consolidation (H2) remains the only optional, actionable item from the reviewer pool.

…tification (L01.FR.26)

TriggerMessage(FirmwareStatusNotification) was gated on
`activeFirmwareUpdateRequestId != null && hasFirmwareUpdateInProgress()`,
falling back to Idle otherwise. Since `hasFirmwareUpdateInProgress` returns
false for every terminal status (`DownloadFailed`, `InvalidSignature`,
`InstallationFailed`, `InstallVerificationFailed`, `Installed`), the
station returned Idle after every non-Installed terminal, violating OCPP
2.0.1 L01.FR.26 (SHALL, mirrored by L02.FR.17).

Persist the last-sent `(requestId, status)` on `OCPP20StationState` and
drive the trigger from it. `stationInfo.firmwareStatus` is retained
because `hasFirmwareUpdateInProgress` and its 3 consumers (reset
rejection, isChargingStationIdle, isEvseIdle) depend on its
"in-progress predicate" semantics — deliberate dual-source, not
conflation.

Closes #1979
@jerome-benoit
jerome-benoit force-pushed the fix/ocpp20-firmware-trigger-l01-fr-26-last-sent branch from 69389b8 to 860152a Compare July 8, 2026 15:21
@jerome-benoit
jerome-benoit merged commit e406ab2 into main Jul 8, 2026
44 checks passed
@jerome-benoit
jerome-benoit deleted the fix/ocpp20-firmware-trigger-l01-fr-26-last-sent branch July 8, 2026 16:13
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: TriggerMessage(FirmwareStatusNotification) violates L01.FR.26 after non-Installed terminal emissions

1 participant