Blastware names a direct download K441LTON.900 and only its call-in copy
K441LTON.900H, so a folder of directly downloaded events cannot be sorted by
kind. SFM's own files now always carry the letter. It is read from the file's
own record-type byte (STRT[18], #41) by the new with_type_letter() -- not from
the recording mode: BE9441's K441LTOK.R10 is a waveform that triggered 2 s into
histogram K441LTOK.QZ0 (Histogram+Continuous). A file whose type does not read
keeps the plain name; a name never fails a download.
All three paths that name a MiniMate file SFM builds: the device-access
download (the page's event list), WaveformStore.save (the legacy route's store
copy, the bench call-in server), and the legacy /device/event/{i}/blastware_file
download. Verified on BE9441's recorded 5A walk: 0111f210 -> K441LTON.900H,
011106a0 -> K441LTOK.R10W, byte-identical to Blastware's files.
find_event_by_blastware_name tightens with it: a lettered name matches itself
and the letterless form, not the other letter (a waveform and a histogram in the
same second are different events); a letterless name still matches all three.
Store consequence: new downloads only; rows and files stored before keep their
names, and 'already stored' still finds them. No schema change, no migration.
The event list shows the plain name until the event is downloaded (the type is
not known before the 5A).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
persist_download checked 'already stored' on the unit's 0C time only, but a
histogram's row is stored at its file's time, a second earlier on most
histograms (#51): K441LTOK.QZ0 decodes to 16:06:34, its 0C says 16:06:35. So a
live download of an event the watcher had imported missed the check and
re-stored it -- UPSERTing over the watcher's row (Blastware's ZC frequencies and
vector sum lost) and rewriting its sidecar as sfm-live -- and every repeat live
download rewrote the files again.
New SeismoDb.find_event_by_blastware_name(): the row stored under the same
Blastware name (the event's second, per blastware_filename_time; the rule
_restamp_by_file uses), matching a direct name to the call-in copy's W/H name.
Any other name matches nothing. Also two comments from 9492e49 that said the
opposite of the code (the unit's peaks are overlaid; source.kind is a parameter).
Store consequence: none for existing rows; no schema change, no migration.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
Brings the branch up to dev (41 commits) before the 1c bench fixes, which
touch code dev changed: the histogram reader (#47/#49, bench finding #2), the
v0.32.0 event-time rules, the Blastware file's setup-block fields (#44/#45),
and the decode checker for verifying stored S3 downloads.
One conflict: the top of the Series-III reference's change table -- both sides
added rows; kept all, in date order, CRLF preserved. CLAUDE.md, README,
blastware_file.py, models.py and database.py merged cleanly. Suite: the known
16 failures only (15 test_bw_ascii_report, test_save_imported_bw_without_report_
works_unchanged, which also fails on dev); 1237 passed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
Brian: keep an event whose time is only an estimate (no validated embedded
event record) -- never discard a measurement for want of an exact timestamp --
but it must not silently cause an overwrite, merge or dedup collision.
insert_events, for timestamp_source 'estimate' (_estimate_guard):
- never restamps (moves) a row;
- if its file (a Blastware name) is already stored under another time, writes
nothing -- no second row, the stored time kept;
- if a different event already holds that second, writes nothing -- the old
upsert would have written this event over that one;
- otherwise stores it, or refreshes its own row at the same second, as before.
Each refusal is a WARNING naming both sides; the file and sidecar (which says
'estimate' and carries the decode problem) are already in the store. A generic
upload name ('imported.bw') is not taken as identity.
Tests: each rule, an estimate on a free second kept, generic names, and an
import end to end (a corrupted record next to a different event's second).
3 mutants, each caught. Suite vs clean origin/dev: the same 16 failing tests,
failure reasons byte-identical; 582 passed vs 553.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
The review of this branch measured (and I re-measured) that the binary's
trigger -- ts2 minus the record time, from 1e76d08 -- is a second off on 260 of
prod's 1,394 waveforms (2026-09-30 snapshot): 199 late, 61 early. A Blastware
filename encodes Blastware's own time to the second: it equals the report's
Event Time on 81/81 prod and 1,249/1,249 DL2 report-paired waveforms.
The cost of the second was real, not cosmetic:
- events is unique on (serial, timestamp), and on BE9558 the 61 early
waveforms land on their histogram twin's second -- a fresh import wrote each
waveform over its histogram's row (888 files -> 827 rows on dev);
- the release backfill would have moved 161 prod rows that v0.31.0 already had
exactly right a second off.
Same-second collisions across all 11,827 prod-snapshot files: 61 with the
binary's times, 0 with waveform names. Histograms keep the binary's ts1: their
name is Blastware's start time too (13,089/13,089) and ts1 runs a second early
on 97% of them, but with both on Blastware's times a waveform and its
histogram share a second 209 times -- the key cannot hold that. Correcting
histogram times needs the key changed; not here.
- blastware_file.blastware_filename_time(): the inverse of
blastware_filename(), V10.72 'AB0' names only, None for anything else.
- read_blastware_file(path, *, name=None): a waveform takes the name's time;
save_imported_bw passes the upload's real name (it reads a temp file).
- insert_events' restamp matches only Blastware names (every unnamed upload is
'imported.bw', so two events could share it) and, of several copies, moves a
reviewed one with a time first (review items M1, M2).
Tests: the decoder (documented names, encoder round trip, other names), a
waveform's name time, a temp-named read, histograms unchanged, the twin
collision on BE9441's own ZI0 (binary 14:23:43, Blastware 14:23:42), and both
review items. 5 mutants, each caught. Suite: only the 16 known failures.
Codec-library change: TOOL_VERSION to be bumped at release. No schema change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
The waveform event-time fix (a84a46e / 1e76d08, on dev since 2026-09-20)
changed what time a Series-3 waveform decodes to: the trigger, where v0.31.0
stamped the monitoring-session start -- hours off. events is unique on
(serial, timestamp), so re-storing an old event at its corrected time matched
nothing and inserted it a second time.
Measured 2026-10-26: files stored with v0.31.0 (prod's code), then dev's
backfill_sidecars --force -- the release's own deploy step -- gave every
waveform two rows, one at each time. N844LQHB.ZT0W (BE12844): 06:00:13 and
10:33:29, its false-trigger mark only on the wrong-time copy. A Blastware
re-forward of an old event would do the same with no backfill at all. Prod
has not run the new decoder, so it holds no duplicates yet.
insert_events now matches a row by its stored file first (serial +
blastware_filename; a Blastware name encodes the serial and the second): one
under another time is moved to the new time in place -- same id, review kept --
and the usual refresh follows. When a different stored file already holds the
corrected second, nothing moves and nothing is written; the old upsert wrote
this event's file and peaks over that other event's row. Rows with no stored
file are matched on time alone, as before.
Tests: the move (id, review, refresh), a different file, no file, the
collision, a duplicate already at the new time, and the release backfill end
to end on a v0.31.0-shaped row. Re-checked across versions: v0.31.0 import,
then this branch's backfill -- 5 real files, every row corrected in place, no
duplicates. Suite: only the 16 known fixture failures.
No schema change, no migration, no codec change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
Final fix wave for phase 3 (start/stop monitoring), per the whole-phase review.
- I1 + M2: every failure after the send has started is a ChangeUnconfirmed
(audit_id, sent = "acknowledged" | "unknown", the cause's HTTP status) whose
message says the frame was sent and names the audit record -- the ring in
place of the ack, the four lost-ack follow-ups, and the three read-back
paths. Series4Session releases the line on it. Every audit finish goes
through one helper; a finish that fails is AuditIncomplete (500) and still
says what happened to the unit. The line is kept.
- I2: device_commands gains `sent` (1 acknowledged, 0 nothing sent, NULL
unknown) and `states` (before / seen / after), with an idempotent ADD COLUMN
in _migrate for a table created earlier on this branch.
- M1: a RADIO RING already buffered is caught before 0x96/0x97 goes out
(pre_send = read_unsolicited, one 10 ms transport read). That is a
CallHomeInProgress with sent=0, not ChangeUnconfirmed.
- M3: Series 3 reads the raw 0x1C flag (new MonitorStatus.state_flag); a byte
other than 0x00/0x10, or a short section, is unknown(...) and refused.
- M8: even_if_already on a unit already in the state notes that the read-back
proves nothing.
- M10: a scan pins `.protocol.execute(` to sfm/device_access/s4.py; both
scans fail closed on a file that does not parse.
- M11: docs corrected (CLAUDE.md phase-2 sentence, phase-3 bullet, REST list;
micromate/protocol.py scope and the 0x49 read_state docstring; s4.py; route
docstrings). "No command has ever been originated" is NOT retracted.
- M12: GET /db/device_commands normalises the serial.
- Minors: unused imports, S3 dry-run frames and 120 s timeout pinned, test
rename, serial-cache and short-0x49 tests, _RUN_STATES comment.
Schema: two NULLable columns on the branch-new device_commands table, added
by _migrate on open; no backfill. No codec change, TOOL_VERSION unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
A reason records *why* an event is a false trigger. It is optional (plain
FT flags still record no reason) and is a subtype of the FT flag: setting a
reason implies false_trigger=1, and the reason is cleared whenever FT ends
up 0 (confirm-real, clear-FT, set_false_trigger(false)). Twin propagation
carries the reason to the histogram/waveform twin alongside the FT flag.
New nullable `false_trigger_reason TEXT` column (schema + _migrate ADD
COLUMN only — not the Migration-1 rebuild). 7 tests.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YDXjZCr4RqT2U3QvMDhgzf
Productionizes the validated scratch/offset_scan3.py: a DC offset (baseline
shifted off zero — sensor bumped/settled/drifted) is |median(pre-trigger)| >= 5
counts (0.025 in/s) AND flat across pre/mid/end thirds (spread <= 0.02); a
transient moves one third and is rejected by the spread test.
- shape_metrics: offset_from_samples / offset_from_h5 (reads .h5 samples +
pretrig_samples attr; range-aware via the .h5's in/s float samples)
- events schema: shape_offset / _axis / _pre / _spread (via _SCHEMA + the
_migrate ADD COLUMN loop only; NOT the Migration-1 rebuild), threaded through
insert + upsert mirroring shape_*
- ingest: computed at all three waveform_store save paths alongside shape
- backfill_event_shape: also computes + stores (and stale-clears) offset
- exposed via /db/events automatically (SELECT *)
Gating to waveforms is done downstream in terra-view ft_suspicion (mirrors how
shape is ignored for histograms), not at the SFM call sites. 13 new tests.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YDXjZCr4RqT2U3QvMDhgzf
A real trigger is recorded twice — as a triggered waveform (stamped at the
trigger instant) and inside the scheduled histogram whose interval contains it
(stamped at the 7am/7pm interval start). The two twins routinely differ by
HOURS, so the old ±5-minute window in find_twins silently missed them — which
broke review propagation (flagging one twin left its twin unflagged).
Twins are now matched by: same serial + identical peak_vector_sum + OPPOSITE
record type + the waveform's timestamp falling within the histogram's interval
(bounded by the next same-serial histogram). Matching keys off record timestamps
(not call-in/received times, which drift with field connectivity). window_seconds
is retained but ignored.
Rewrote test_find_twins + test_twin_propagation for the new contract (incl. the
75-min-apart UM12947 case, cross-type exclusion, containing-interval selection,
open-ended latest interval). Full suite: 264 passed; the 16 failures are
pre-existing (missing gitignored fixtures + a v0.26.0 codec case), unchanged
from baseline.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YDXjZCr4RqT2U3QvMDhgzf
set_false_trigger now clears reviewed_real when flagging false_trigger=True
(mirrors update_event_review's exclusivity), and the quick
PATCH /db/events/{id}/false_trigger endpoint now calls
propagate_review_to_twins after the flag write, matching the sidecar PATCH
path's try/except-with-log.warning pattern. Previously the quick path could
leave both flags set and never touched twins.
Also corrects the v0.25.0 CHANGELOG bullet (exclusivity was not actually
enforced on the quick path until this commit) and adds a caveat comment on
find_twins about rare clamped/saturated-PVS false-positive twin matches.
- Created a comprehensive runbook (`wedged_unit_recovery.md`) detailing the recovery process for units stuck in a call-home loop, including symptoms, recovery steps, and explanations of the failure mode.
- Added `blind_stop.sh` script to send stop-monitoring commands in a tight loop for unresponsive devices.
- Introduced `rescue_device.sh` script to disable Auto Call Home and erase events from a busy device.
- Implemented `slow_drip.sh` script to send stop-monitoring frames at a slow rate to prevent UART overrun.
- Developed `spam_stop.sh` script to rapidly send stop-monitoring commands to a device.
- Created `watch_unit.sh` script for passive monitoring of device reachability, logging results over time.
Two compounding bugs caused forwarded events to land in the DB with
broken-codec peak values (~10 in/s saturation on every channel) and
no project info, even when the watcher correctly paired a BW ASCII
report with the binary.
Bug 1: save_imported_bw built the sidecar JSON with the report's
authoritative peak / project values via event_to_sidecar_dict(
bw_report=...), but never overlaid those onto the in-memory Event
that flows to db.insert_events(). So the DB row got peak_values
from read_blastware_file()._peaks_from_samples() — which runs the
still-undecoded waveform body codec assuming raw int16 LE and
produces ±32K-shaped noise (= ±10 in/s at Normal range) regardless
of the actual signal. The sidecar JSON had the truth but the DB
columns (which the webapp queries for fast filter/sort) lied.
Bug 2: insert_events' IntegrityError handler only refreshed the
filename/filesize/a5_pickle/sidecar columns when a duplicate
(serial, timestamp) was seen. Peak values, project info,
sample_rate, record_type stayed locked in at whatever the FIRST
insert wrote. So even after Bug 1 was fixed, the historical
events in the DB (already inserted with broken-codec peaks) would
never get their values corrected, because a re-forward would just
hit IntegrityError and skip the field refresh.
Fix 1 (minimateplus/event_file_io.py + sfm/waveform_store.py):
- New apply_report_to_event(event, report) helper folds the BW
report's device-authoritative fields onto the Event in-place:
per-channel PPV, peak vector sum, mic PSPL→psi, project /
client / operator / sensor_location, sample_rate, record_time.
- save_imported_bw() calls the helper right after parsing the
report. The Event that flows to insert_events() now carries
correct values.
Fix 2 (sfm/database.py):
- insert_events()'s IntegrityError UPDATE now refreshes every
device-authoritative column from the new data: tran_ppv,
vert_ppv, long_ppv, peak_vector_sum, mic_ppv, project, client,
operator, sensor_location, sample_rate, record_type, plus
the existing filename/filesize/a5_pickle/sidecar fields.
- Preserves: id, waveform_key, session_id, created_at (immutable
/ FK fields), and false_trigger (operator review state).
End-to-end simulation verified:
- Step 1: import without report → DB has ±10 in/s peaks, no project
- Step 2: re-import WITH report → upsert path fires, DB now has
device-authoritative 0.005 in/s peaks + sensor_location
- Step 3: operator sets false_trigger=1, re-import again → flag
preserved, peaks remain correct
For the user's situation: deleting the watcher state file forces a
re-forward of all events. Each re-forward now pairs with its
_ASCII.TXT, applies the report onto the Event, and the upsert
refreshes the DB row. No DB nuke needed.
Full SFM suite: 62 passed, 44 skipped.
Previous query_units() only joined on ach_sessions, which is created
exclusively by the live ACH server. The BW-importer path
(/db/import/blastware_file → WaveformStore.save_imported_bw →
SeismoDb.insert_events) populates `events` but never creates an
ach_sessions row. Consequence: every serial whose events flowed in
through the series3-watcher forwarder was invisible to
/db/units (and therefore to the SFM webapp's fleet overview / units
list), even though the events were correctly populated in the
events table with proper serial attribution.
Rewrite query_units() to aggregate from BOTH tables and union the
serials:
- total_events / last_event_at come from `events` (every ingest path)
- last_session_at / total_monitor_entries / total_sessions
come from `ach_sessions` (ACH-only),
0 when no sessions exist for the serial
- last_seen = max(last_event_at, last_session_at)
Verified on the user's actual prod DB after the
repair_unknown_serials run: /db/units now returns 24 serials instead
of 2. All 3,257 watcher-forwarded events become visible in the
fleet overview without any further DB surgery.
### Added
- **Layered event storage architecture.** Each event now lands as four
files in the per-serial waveform store, each with a clear role:
- `<filename>` — the Blastware-readable binary (BW file). Untouched.
- `<filename>.a5.pkl` — the raw 5A frames (regenerative source).
- `<filename>.h5` — clean per-channel waveform arrays in physical
units (in/s for geo, psi for mic) plus event metadata (HDF5 with
gzip compression). This is the canonical format for downstream
analysis tools.
- `<filename>.sfm.json` — the modern review/metadata sidecar (peaks,
project, source provenance, review state, extensions).
SQLite (`seismo_relay.db`) is the searchable index over all four.
- **Plot-ready waveform JSON (`sfm.plot.v1`).** The `/device/event/{idx}/waveform`
and `/db/events/{id}/waveform.json` endpoints now return samples in
physical units with explicit time-axis metadata, peak markers, and
per-channel unit hints — no more guessing the ADC-to-velocity scale
client-side. The webapp waveform viewer was rewritten to consume
this shape.
- **In-app waveform viewer accuracy fix.** The standalone SFM webapp
viewer was scaling geophone amplitudes by `geoAdcScale / 32767`
(≈ 6.206 / 32767), where `geoAdcScale = 6.206053` is the device's
*in/s per V* hardware constant — not the ADC-counts-to-velocity
factor. This silently scaled every plot ~38% too low for Normal-range
geophones (the correct full-scale is 10.0 in/s, or 1.25 in/s for
Sensitive). Conversion is now done server-side using the geo_range
from compliance config; the client just plots.
- New `sfm/event_hdf5.py` module: `write_event_hdf5()`,
`read_event_hdf5()`, plus a plot-JSON helper.
- Backfill script extended to also emit `.h5` for existing events.
### Dependencies
- Added `h5py>=3.10` and `numpy>=1.24` for the HDF5 storage layer.
- Added `python-multipart>=0.0.7` (required by FastAPI for the
`/db/import/blastware_file` endpoint introduced in this release).
sfm/database.py (new)
- SeismoDb class: three tables keyed by unit serial number
- ach_sessions: one row per ACH call-home
- events: one row per triggered event, deduped by (serial, waveform_key)
- monitor_log: one row per monitoring interval, deduped by (serial, waveform_key)
- WAL mode, per-request connections, silent dedup via UNIQUE constraint
- Query helpers: query_events(), query_monitor_log(), get_sessions(), query_units()
- false_trigger flag on events for future review UI / report filtering
bridges/ach_server.py
- Import SeismoDb; create shared instance at startup pointed at
bridges/captures/seismo_relay.db
- After each call-home: insert_events() + insert_monitor_log() + insert_ach_session()
- DB failures logged as warnings, never abort the session
sfm/server.py
- Import SeismoDb; lazy singleton via _get_db()
- New DB read endpoints: GET /db/units, /db/events, /db/monitor_log, /db/sessions
- PATCH /db/events/{id}/false_trigger for manual review flagging
CLAUDE.md / CHANGELOG.md
- Document DB schema, SFM DB endpoints, architecture decision (unit-keyed only)
- Version bump to v0.11.0
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>