Skip to content

fix(rs350,ffmpeg,lane): RS-350 watchdog and self-recovery, duplicate clips, HLS sweep, struct copies - #55

Merged
5 commits merged into
ORNL:mainfrom
mjd948:fix/rs350-camera-reliability
Nov 24, 2026
Merged

5 commits merged into
ORNL:mainfrom
mjd948:fix/rs350-camera-reliability

Conversation

@mjd948

@mjd948 mjd948 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Five independent field fixes, one commit each. Each commit message has the full reasoning and how
it was verified.

Commit Problem Fix
RS350/lane: stop mutating registered structures BackgroundOutput/ForegroundOutput resized the registered DataRecord's variable-size spectrum arrays to live data. An in-JVM restart then failed re-registration with "Cannot update the record structure … if it already has observations" (core side: ORNL/osh-core#9). Same for AdjudicationControl.createResultData. Build each message's record on dataStruct.copy().
Fix duplicate clip recording after a camera module restart OccupancyWrapper de-duplicated cameras by object identity. A restarted camera module is a new object, so both entries recorded; the two record commands raced for one file name, and the alarm ended up with two empty video paths. De-duplicate by camera UID in add and remove (bulk setFFmpegSensors too), and stop the outgoing wrapper on re-init.
Make the RS-350 connection watchdog actually measure silence MessageHandler.timeSinceLastMessage was set to 0 once and never re-stamped, so connectionStatus stayed isConnected:true at 1 Hz while all data was 22 min stale. The reconnect branch was unreachable. Keep a volatile last-message timestamp: stamped per complete message, seeded at start, elapsed time returned (as in the Rapiscan driver).
Recover the RS-350 automatically when the detector comes back Reconnect was gated on RobustConnection.isConnected(), which never clears on peer loss. Even when it ran, the reader thread had exited on EOF and could not restart. Trigger on data silence, and rebuild comm provider + stream + MessageHandler in place, keeping the module STARTED. This deliberately avoids RobustConnection.reconnect(), which gives up after reconnectAttempts. Works with ORNL's journal-aware staged stop.
Stop the HLS sweep and module stop from throwing before they act HlsStreamHandler.stopStream and FFMPEGSensorBase.beforeStop built commands with BigId.NONE, which OshAsserts.checkValidInternalID rejects. The inactivity sweep died on its first expiry (scheduleAtFixedRate cancels on throw), and a camera stop never closed its recording or ended HLS. Use the direct-to-driver CommandData(id, params) constructor, and catch per stream in the sweep.

Compatibility

No config, datastream or API changes.

Tests

Run on the 3.11.13 tree (ORNL/oscar checkout with this branch overlaid, as the modules CI does):

  • node tools/validate-release-metadata.js passes;
  • :sensorhub-driver-rs350:test, :sensorhub-system-lane:test, and :sensorhub-driver-ffmpeg:test
    with HlsStreamHandlerTest, FFMPEGSensorReconnectTest and FileControlPublicationTest:
    all pass, with 4 hardware-only tests skipped and 0 failures.

Field evidence

All five were seen on a 24/7 node with RS-350 backpack and Rapiscan + RTSP-camera lanes:

  • With the detector's TCP port blocked and then reopened, the RS-350 reported offline within about
    10 s and resumed about 10 s after the port reopened, with no operator action. This held across
    outages longer than the old give-up window.
  • After two forced camera restarts, alarms recorded a single non-empty clip.

🤖 Generated with Claude Code

mjd948 and others added 5 commits November 24, 2026 21:22
BackgroundOutput/ForegroundOutput called updateSize()/setData() on the live
DataRecord returned by getRecordDescription(), so the registered template's
variable-size spectrum arrays grew to match live data. On an in-JVM module
restart (stop -> start without re-init) the re-registration then compared
that mutated structure against the stored one and failed with "Cannot update
the record structure or encoding of a datastream if it already has
observations" (see matching osh-core fix). Records are now built on a
dataStruct.copy() per message, leaving the template pristine. Same treatment
for AdjudicationControl.createResultData and its isotopes/filePaths arrays.

(The original commit, 683a0e9 on the old fork, also interrupted the
MessageHandler reader/notifier threads on stop. ORNL's staged
requestStop/awaitSourceStopped/awaitAncillaryStopped now does that, so
that half was dropped in the port.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OccupancyWrapper.addFFmpegSensor deduplicated its camera list with
contains(), i.e. by object identity. A camera module restart hands
LaneSystem's STATE_CHANGED handler a different object for the same
physical camera, so the stale entry survived and the new one was added
alongside it. The occupancy then issued one record command per entry a
few milliseconds apart; both resolved to the same timestamped file name,
the loser died on FileAlreadyExistsException, and BOTH contributed an
empty path to the occupancy — an alarm with no video at all.

Observed live 2026-08-12: every alarming occupancy after 18:11 UTC on
the three lanes whose modules had restarted carried videoPathCount=2
with two empty paths, while the lane without a restart recorded normally.

Deduplicate by camera UID instead, in both add and remove, and stop the
outgoing wrapper in doInit so a re-init cannot orphan a live one.

Verified on the running node: after forcing two camera restarts on
one lane through the admin UI, the next alarm recorded a single
non-empty path and a 1.5 MB clip; five alarms across four lanes over the
following hour, zero FileAlreadyExistsException.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
MessageHandler.timeSinceLastMessage was declared, assigned 0 once when the
reader thread started, and returned raw from getTimeSinceLastMessage() —
three references, never re-stamped. The getter therefore returned 0 forever,
so RS350Sensor.heartbeat()'s `getTimeSinceLastMessage() < reconnectPeriod`
test was always true: the driver published connectionStatus{isConnected:true}
at 1 Hz no matter how long the detector had been silent, and the else branch
that calls checkConnection() -> connection.reconnect() was unreachable, so a
dropped socket was never retried.

Observed on an RS-350 backpack lane with its simulator stopped: every data
stream (location, status, foreground/background report, dailyFile) 22 minutes
stale while connectionStatus stayed ~1 s fresh and true.

Hold a timestamp instead, mirroring the Rapiscan MessageHandler this was
copied from: volatile (the heartbeat reads it from another thread), stamped
when a complete message comes off the wire, seeded before the reader starts
so a detector that never sends ages out from module start rather than the
epoch, and the getter returns the elapsed time. With the deployed 10 s
reconnectPeriod the module now reports isConnected:false after 10 s of
silence and retries the connection.

Note the Aspect driver's MessageHandler keeps the same-named field but
measures the interval between loop iterations rather than time since the last
message, so it has an analogous blind spot; left alone here as there is no
Aspect hardware to verify against.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
A detector that dropped off stayed dark until someone restarted the module by
hand. Two separate reasons, both fixed here.

The reconnect never ran. checkConnection() gated on connection.isConnected(),
but RobustConnection sets its `connected` flag once on the first successful
connect and only clears it in cancel()/reconnect() — nothing clears it when
the peer disappears — so the flag stayed true and the branch was dead. Trigger
on data silence instead, which is the signal that actually means something
(and is what the Rapiscan driver uses).

Reconnecting alone would not have helped either. The reader thread exits the
moment the socket reports EOF, its InputStream belongs to the dead socket, and
a Java thread cannot be restarted — so a fresh socket had no reader attached.
Rebuild the comm provider, the stream and the MessageHandler together, wiring
the new handler to the same outputs via initMessageHandler(), extracted from
doStart().

Deliberately not RobustConnection.reconnect(): it stops and starts the whole
module and gives up after reconnectAttempts, so an outage longer than
reconnectAttempts * reconnectPeriod (110 s as deployed) would leave the module
in ERROR with no heartbeat left to retry — trading a dark lane for a dead one.
Rebuilding in place keeps the module STARTED and lets the heartbeat retry
indefinitely, paced at one attempt per reconnectPeriod.

Verified against the live node by blocking the detector's TCP port: comms
reported false within ~10 s, rebuild attempts logged and failed while blocked,
and data resumed ~10 s after the port reopened with no operator action —
including across an outage longer than the old give-up window.

messageHandler and isRunning are now volatile (written from the heartbeat
thread, read from others) and doStop() is synchronized against the rebuild so
a teardown cannot interleave with a swap.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
HlsStreamHandler.stopStream and FFMPEGSensorBase.beforeStop built their
internal commands with CommandData.Builder().withCommandStream(BigId.NONE).
The Builder validates that ID (OshAsserts.checkValidInternalID: must be
> 0), so build() threw before anything was submitted:

- the inactivity sweep threw on its first expiry, and scheduleAtFixedRate
  silently cancels a task on an uncaught exception, so idle HLS streams
  then muxed forever (the same failure fixed on the old fork in 2624aa4;
  ORNL's per-bucket handler map fixed the other half of that bug);
- every camera module stop logged 'Error stopping video output' and
  neither closed the recording file nor ended the HLS stream.

Use the CommandData(id, params) constructor, which exists for sending a
command directly to a driver, and make the sweep exception-proof per
stream. HlsStreamHandlerTest did not catch this because it registers
null controls, for which stopStream is a no-op.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tyronechrisharris tyronechrisharris closed this pull request by merging all changes into ORNL:main in 7a7324a Nov 24, 2026
@tyronechrisharris

Copy link
Copy Markdown
Collaborator

Merged into main (7a7324ae) via ORNL/osh-oakridge-modules#58 for OSCAR v3.11.14.

Architectural Review & Scale/Concurrency Refinements (c0c509ab)

Your root-cause fixes for RS-350 silence watchdog rebuilds, HlsStreamHandler idle-reaper .ts segment freshness, and duplicate video clip suppression are preserved in full (--no-ff). On top of your commits, we applied two 50-lane scale and concurrency refinements before merging:

  1. Zero 1 Hz SWE DataComponent Tree Cloning (BackgroundOutput & ForegroundOutput): Calling dataStruct.copy() on every 1 Hz frame allocates a deep SWE DataRecord + DataArray component tree per detector per second. Instead, liveDataStruct = dataStruct.copy() is now initialized once in init(), reused across 1 Hz frames with latestRecord = dataBlock, while keeping the canonical dataStruct returned by getRecordDescription() pristine for schema consumers.
  2. Non-Blocking RS350Sensor.reestablishConnection() Teardown (connectionSwapLock): Replaced method-level synchronized across tryConnect() with a dedicated connectionSwapLock so a 3–30 s blocking TCP reconnect timeout never stalls doStop() during lane teardown or restart, and ensured failed commProvider instances close cleanly.

mjd948 added a commit to mjd948/osh-oakridge-modules that referenced this pull request Nov 25, 2026
ORNL squash-merged our session, RS-350, lane-recovery and WebID fixes
(ORNL#54, ORNL#55, ORNL#56, ORNL#60) plus their own follow-ups (ORNL#61), so their side was
taken in every conflict except two:

- LaneSystem keeps our Mobile Detector design (the occupancy process
  member is reused across restarts and covers D5 walkers); ORNL's
  "detector already started" start-up is kept for a newly created
  process, for RS-350 and D5 alike. EML re-attach follows ORNL.
- Rs350OccupancyProcessModule takes ORNL's version: its event-bus
  restart handler (where our orphan guard lived) is gone upstream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

2 participants