Commit Graph
36 Commits
Author SHA1 Message Date
serversdownandClaude Opus 5.5 ba826dfac6 fix(mlg): final-review fixes
A fresh whole-branch review found four Important issues; three of its
Minors and one item it set aside were re-graded up.  Each has a test that
failed first.

- A windowed timeline 500'd when a file came without its modified time
  (Python 3.10 rejects the 'Z' of received_at).  received_at is now
  +00:00 and timeline times parse 'Z' too.
- On the clock-step day an event-triggered call-in moved the event into
  the next session and lost the step.  An event now joins the 'monitoring
  started' record of its own file.
- A call-in whose records came first in another file (a cable download)
  read 'nothing_new'.  Each file now keeps its own call summary
  (last_stop, no_file_stops) from when it arrived.
- Sessions and call-ins now carry record_ids / file_ids / file_id, the
  shot report's proof (spec 5).
- A non-'started' record with no stop made the unit's timeline 500 for
  good; it now opens a session whose end is unknown.
- A serial from a file's bytes (or a hint) could write outside the store;
  only plain serials are used, and records with no serial are refused, not
  dropped.
- Times with a UTC offset, an empty 'at', or a bad mtimes value gave 500s
  (or stored half a request); they are now 400s, checked first.
- A missing call-in file made the gap after its Modem Exit read 'not
  monitoring' for days.  Files are numbered <serial><counter>; a gap
  across a missing number is now 'records missing' (unknown).  A long gap
  after a call-in with no number missing is 'no restart after a call-in':
  real outages on the DL2 data (BE6907 14 days from 2026-10-07; BE8081
  over Labor Day 2019).  Real fixtures BE6907 #899-#902 added.
- Docs: BE8081 did write one empty file (BE80811.MLG).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 14:17:08 -05:00
serversdownandClaude Opus 5.5 84d6cd05c3 feat(mlg): store .MLG files and records, each record once
Two new tables, created on first start (no migration):
mlg_files (one row per file received, deduped by name + sha256) and
mlg_records (one row per log record, unique on serial, start, stop,
flag word and trigger source; COALESCE on the stop, since an open
record's NULL stop is distinct to a UNIQUE constraint).  The text is not
part of a record's identity: Blastware writes it, and two copies of the
same records differ there.  WaveformStore.save_mlg keeps the original
file byte for byte under <serial>/mlg/.

Operational consequence: two new tables on first start; no migration,
no backfill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R9LdWawLzUxwewZGA1
2026-11-13 13:43:47 -05:00
serversdownandClaude Opus 5.5 2d237be5ef fix(ingest): a live download is held to its record type (#51)
Since #51 a waveform and a histogram recorded in the same second are two
events (UNIQUE(serial, timestamp, record_type)).  persist_download's
'already stored?' checks matched any row at the second and any row under
the letterless Blastware name both twins share, so a live download of
one twin was skipped as stored.  Both checks now hold to the download's
own type, read from its file (STRT[18]; IDFW / IDFH); an untyped row at
that second, or a download whose type does not read, still counts as
stored.  find_event_by_blastware_name takes an optional record_type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 12:34:46 -05:00
serversdownandClaude Opus 5.5 f24913189b merge: dev 9b458b5 into the parity branch (group A/B, #51 histogram timing)
Brings the checker's file-only decode work onto the parity branch so the
phase-5 bench runs on the code that will ship.  One conflict, the CRLF
Series-III reference changelog: both kept, phase 5's row numbered
'2026-11-03 (5)' above dev's (4)/(3)/(2).  test_event_ingest's live-
histogram dedup test asserted the stored row sits a second off the 0C
time -- the #51 bug, fixed on dev -- so its premise now reads the event's
own second; the dedup it tests still holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-11-04 12:31:21 -05:00
serversdownandClaude Opus 5.5 ea2dfc21b7 feat(db): events are identified by unit + time + type (#51)
The events table was UNIQUE(serial, timestamp): one event per unit per
second.  A unit records a waveform and a histogram in the same second
legitimately -- 209 times in prod's 2026-09-30 store once histograms
carry Blastware's start -- so the key is now (serial, timestamp,
record_type).  Agreed with Brian 2026-11-03.

- Migration 3 rebuilds the table from its own current definition with
  only the key swapped, in one transaction: every column, row and id is
  kept (Terra-View reads rows by id) and the indexes are recreated.
  Migration 1's check no longer mistakes the new key for a missing one.
- The upsert, the estimate guard and the restamp match on the type too.
  The restamp also re-types a file's own row in place: before v0.33.0 a
  row's type came from the filename, and a re-import under the file's
  own type must not add a second row.
- An untyped event still refreshes the untyped row at its second (a
  UNIQUE key treats NULLs as distinct).
- scripts/repair_unknown_serials.py checks the new key.

No time changes yet: that is the next commit, and they ship together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ALX2R8pghDaZuti9U7mEE9
2026-11-03 21:29:46 -05:00
serversdownandClaude Opus 5.5 b6ed5f5bd5 feat(sfm): SFM's MiniMate files carry the W/H type letter Blastware's direct downloads leave off
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
2026-10-30 00:36:26 -04:00
serversdownandClaude Opus 5.5 3a1d34ae92 fix(sfm): a download the store already holds is found by its Blastware name, not only its time (#8 review)
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
2026-10-29 23:56:44 -04:00
serversdownandClaude Opus 5.5 342c69602d merge: dev into feat/series4-sfm-parity -- v0.32.0, #42, #47/#49, #44/#45, the S3 decode checker
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
2026-10-29 22:51:42 -04:00
serversdownandClaude Opus 5.5 6cfcd04513 fix(sfm): an estimated event time never overwrites, merges into or duplicates a row
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
2026-10-27 00:15:32 -04:00
serversdownandClaude Opus 5.5 3948dc1a3c fix(decode): a Series-3 waveform's time comes from its Blastware filename
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
2026-10-26 19:15:59 -04:00
serversdownandClaude Opus 5.5 847900baeb fix(sfm): a re-stored event at a corrected time moves its row instead of duplicating it
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
2026-10-26 18:18:23 -04:00
serversdownandClaude Opus 5.5 8f68b09f5e fix(sfm): a change that fails after the send says so; the audit row records sent + states; S3 unknown states refused
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
2026-10-23 19:16:45 -04:00
serversdownandClaude Opus 5.5 ff0cce1cb2 fix(sfm): an audit row can be finished once, from pending -- anything else raises
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-23 16:24:46 -04:00
serversdownandClaude Opus 5.5 fb9b48f259 feat(sfm): device_commands audit table -- one row per change attempt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-23 16:22:28 -04:00
serversdownandClaude Opus 4.8 c0cf6547d9 feat(ft): optional false_trigger_reason ("offset" etc.) as an FT subtype
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
2026-09-03 20:53:57 +00:00
serversdownandClaude Opus 4.8 3554d00583 feat(offset): DC-offset detector productionized into the shape pipeline
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
2026-09-02 04:47:01 +00:00
serversdownandClaude Opus 4.8 75ac610c61 fix(twins): interval-based histogram/waveform matching in find_twins (#102 sub-task 2)
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
2026-08-28 05:23:30 +00:00
serversdown 37043a47e9 fix(review): quick FT path enforces 3-state exclusivity + twin propagation; changelog + twin caveat
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.
2026-08-25 00:55:38 +00:00
serversdown 7aae0208f8 feat(review): propagate false_trigger/reviewed_real to twins on sidecar PATCH 2026-08-25 00:42:27 +00:00
serversdown 5ffa92ab87 feat(db): find_twins (serial + identical PVS + time window) 2026-08-25 00:38:49 +00:00
serversdown f73c8eec91 feat(db): update_event_review mirrors reviewed_real + enforces 3-state exclusivity 2026-08-25 00:34:25 +00:00
serversdown 23e4f585a8 fix(db): keep reviewed_real out of the Migration-1 rebuild table (positional SELECT *); regression test 2026-08-25 00:31:39 +00:00
serversdown d9cc5f1780 feat(db): reviewed_real column on events (+ auto-migrate) 2026-08-25 00:26:22 +00:00
serversdown 54c4182023 feat(db): insert_events persists shape_* from waveform record 2026-08-22 05:55:25 +00:00
serversdown a894b001b1 feat(db): shape_* columns on events (+ auto-migrate) 2026-08-22 05:50:45 +00:00
serversdownandClaude Opus 4.8 1744eb1803 feat(db): persist per-channel ZC freq on insert/upsert
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YDXjZCr4RqT2U3QvMDhgzf
2026-07-29 17:27:36 +00:00
serversdown 248276d141 feat(db): add per-channel ZC-freq columns to events (+ migration) 2026-07-29 17:13:59 +00:00
serversdown e95ac692ee feat: add device family to separate s3 and s4 events. 2026-05-20 06:15:50 +00:00
serversdown 1fff8179d6 Add runbook for recovering wedged units and new scripts for device management
- 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.
2026-05-17 07:58:13 +00:00
serversdown 6b2a44ff02 fix(import): overlay BW report onto Event + upsert DB row on re-import
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.
2026-05-11 05:51:39 +00:00
serversdown cc57a8e618 fix(db): /db/units surfaces events-only serials too
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.
2026-05-11 05:15:09 +00:00
serversdown c641d5fc10 feat: v0.15.0
### 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).
2026-05-08 04:39:51 +00:00
serversdown 0484680c89 fix(docs/comments): rename refs to 'event files' to reflect their timestamp extenion names. 2026-05-06 19:08:38 +00:00
serversdown 3711b11bda feat: add waveform store handling 2026-05-06 19:03:38 +00:00
claude 27d9823cc1 fix: update unique constraints in events and monitor_log tables to use timestamp and serial number. Can't use event keys because minimates resuse them after clearing memory. 2026-04-13 22:45:58 -04:00
claudeandClaude Sonnet 4.6 03d224ccc3 v0.11.0 — SQLite persistence layer (SeismoDb)
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>
2026-04-13 00:45:38 -04:00