17 Commits
Author SHA1 Message Date
serversdown e9c01ce8d4 Merge pull request 'Release v0.32.0 — event times you can trust, and Series 4 mapped' (#54) from dev into main
Reviewed-on: #54
2026-10-27 11:00:59 -04:00
serversdownandClaude Opus 5.5 1aa07e75d9 docs(release): v0.32.0 README status and dedup notes, release date, TOOL_VERSION comment
README: the intro no longer calls the Series-IV binary codec 'on the roadmap';
a v0.32.0 status entry; the ingest and Database sections describe the restamp
and estimate rules; the NULL-timestamp roadmap item points at #52.
CHANGELOG: v0.32.0 dated 2026-10-27, when its content was final.
TOOL_VERSION comment: times come from the event record, not the name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 02:32:25 -04:00
serversdownandClaude Opus 5.5 04acb99310 docs(changelog): v0.32.0 — waveform times from the instrument's event record, estimates never merge
The release had not shipped, so its entries are corrected in place: the theme,
the time-source entry (the embedded event record, not the filename), the
estimate guard, and a note that the deploy rehearsal stands (record and filename
agree on all 1,394 prod waveforms).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 00:18:59 -04:00
serversdownandClaude Opus 5.5 3a6df9d7f4 merge: Series-3 waveform times from the instrument's embedded event record
Brings fix/waveform-time-from-record (f91949b, 6cfcd04, and a docs pointer): the
trigger comes from the event record the unit sends in its 5A stream, validated
strictly; a filename is only a cross-check; no validated record means a
flagged estimate that never overwrites, merges or duplicates a row.  Real data,
no names: 7,961/7,961 waveforms on the record, 0 disagreements.  Suite vs dev:
the same 16 failures, byte-identical reasons.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 00:18:08 -04:00
serversdownandClaude Opus 5.5 7100d8344a docs(reference): point §7.8.9's open items at the Series-III audit, #53
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-27 00:17:15 -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 f91949be89 fix(decode): a Series-3 waveform's time comes from the instrument's embedded event record
Brian's requirements: the instrument's data is the only time source; a filename
is a cross-check, never a fallback (an event SFM receives itself has none).

The record (found by reading a seismo_lab Inspector dump; Series-III reference
§7.8.9): 00 28 05 00 ?? ?? | fe 80 | trigger | stop, times dd mm yyyy(BE) 00 hh
mm ss.  Measured on 7,935 waveforms (DL2 + prod store): exactly one candidate
validates in every file; trigger = Blastware's report 1,320/1,320, = filename
7,935/7,935, = the unit's 0C record 10/10.

Provenance (requirement 6, measured): in Blastware's download of 8 BE9441
events the record -- with 24 B before and 22 after -- occurs exactly once in the
unit's own A5 reply payloads; SFM-only downloads (no Blastware) carry it too.
It is instrument data, not Blastware's.

- _embedded_event_record(): every fe 80 before the footer is a candidate; it
  counts only with the lead bytes, two well-formed times (zero byte zero),
  footer ts1 <= trigger <= stop, stop = footer ts2 or a second before, and a
  length matching the record time.  Exactly one must count; none or several is
  a decode problem, never a guess.
- Without one: the footer estimate, timestamp_source 'estimate', a
  decode_problems entry, a WARNING.  No filename fallback.
- A filename that disagrees is logged; the decoded time is kept.  A paired
  report fills in only without a validated record (apply_report_to_event, the
  sidecar dict overlay, event_to_sidecar_dict) and is logged when it disagrees.
- decode_blastware_bytes(raw, name=None): no file or name needed;
  save_imported_bw uses it (no temp file).  Event gains timestamp_source and
  decode_problems; the sidecar records both.
- Histograms unchanged (#51): their record (fe f5) is noted, not used.

Tests: raw bytes with no name (ZI0, 7 BE12844 oracles), a disagreeing name, each
validation rule alone, two valid candidates, no filename fallback, report
precedence, sidecar.  7 mutants, each caught.  Real data, decoded with no name:
7,961/7,961 waveforms on the record, 0 disagreements with filename or report;
10,433/10,433 prod histograms unchanged.  Suite: only the 16 known failures.

Open (reported, not changed): 3 DL2 files named as waveforms whose body the
waveform codec does not recognise keep the footer start, 4 s off, as on dev.
None in prod.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL
2026-10-26 23:59:22 -04:00
serversdown d2258dad4e Merge pull request 'Release v0.31.0 — report parity + the inverted rescue (0.29.0 → 0.31.0)' (#40) from dev into main
Reviewed-on: #40
2026-09-18 16:46:41 -04:00
serversdown e050e602c2 Merge pull request 'Release v0.29.0 — offset detector + false_trigger_reason + BlastMate serials (0.27.0→0.29.0)' (#36) from dev into main
Reviewed-on: #36
2026-09-07 15:57:37 -04:00
serversdown fc1c7c7936 Merge pull request 'Docs/claude.md corrections' (#35) from dev into main
Reviewed-on: #35
2026-08-29 15:48:33 -04:00
serversdown 7d0d12079b Merge pull request 'v0.27.0 Decoder fixes, offset exploration and testing.' (#34) from dev into main
Reviewed-on: #34
2026-08-28 22:40:34 -04:00
serversdown 5203aab849 Merge pull request 'update to 0.26.0. Big chonking update including 0.23, 0.24, and 0.25 as well.' (#33) from dev into main
Reviewed-on: #33
2026-08-27 13:43:00 -04:00
serversdown 5b65718b72 Merge pull request 'v0.23.0 - ZC freq in events store' (#31) from dev into main
Reviewed-on: #31
2026-08-06 12:12:19 -04:00
serversdown 483762607e Merge pull request 'Update to v0.22.0' (#30) from dev into main
Reviewed-on: #30
2026-07-03 15:35:20 -04:00
serversdown d0b66368d5 Merge pull request 'update to v0.21.1, thor data import successful' (#29) from dev into main
Reviewed-on: #29
2026-06-01 16:54:23 -04:00
serversdown 2eb1d25028 Merge pull request 'v0.20.0 -- Full s3 event parse and PDF creation.' (#28) from dev into main
Reviewed-on: #28
2026-05-28 17:54:31 -04:00
claude cc821f9ee3 hotfix: fix dockerfile on main to fix import bug on prod 2026-05-21 20:42:15 +00:00
12 changed files with 625 additions and 115 deletions

No files matched your search

+50 -21
View File
@@ -4,14 +4,15 @@ All notable changes to seismo-relay are documented here.
--- ---
## v0.32.0 — 2026-10-26 ## v0.32.0 — 2026-10-27
**Event times you can trust, and Series 4 mapped end to end.** Two threads. **Event times you can trust, and Series 4 mapped end to end.** Two threads.
The first is correctness on stored data. Series-3 waveforms were stamped with The first is correctness on stored data. Series-3 waveforms were stamped with
the monitoring-session start, hours off; they now carry Blastware's own time, the monitoring-session start, hours off; they now carry the instrument's own
read from the Blastware filename, which matches Blastware's reports on every trigger time, read from the event record the unit sends inside its 5A stream,
one of 1,330 report-paired waveforms. Getting the correction into prod safely which matches Blastware's reports on every one of 1,320 report-paired
waveforms -- no filename needed. Getting the correction into prod safely
needed three more fixes found on the way: re-storing an event at its corrected needed three more fixes found on the way: re-storing an event at its corrected
time duplicated it, prod's ISO-dated reports were never read, and the binary's time duplicated it, prod's ISO-dated reports were never read, and the binary's
own estimate is a second off often enough to land waveforms on their histogram own estimate is a second off often enough to land waveforms on their histogram
@@ -44,7 +45,8 @@ work lands with the parity branch. The SFM webapp gains a Diagnostics tab.
Histograms keep `ts1` (the ~24 h window start). A paired report's Histograms keep `ts1` (the ~24 h window start). A paired report's
`event_datetime` stays authoritative (unit-clock drift). `event_datetime` stays authoritative (unit-clock drift).
⚠ **Needs a re-decode backfill** to correct existing stored events' timestamps. ⚠ **Needs a re-decode backfill** to correct existing stored events' timestamps.
⚠ **As released, the time comes from the Blastware filename** (entry below): ⚠ **As released, the time comes from the instrument's embedded event record**
(entry below):
`ts2 - record time` turned out a second off on 260 of prod's 1,394 waveforms, `ts2 - record time` turned out a second off on 260 of prod's 1,394 waveforms,
and the backfill this needs duplicated every corrected event until the and the backfill this needs duplicated every corrected event until the
restamp fix below. See *Migration*. restamp fix below. See *Migration*.
@@ -167,21 +169,44 @@ work lands with the parity branch. The SFM webapp gains a Diagnostics tab.
The sidecar's `bw_report` block also never stored the event time and the The sidecar's `bw_report` block also never stored the event time and the
backfill's overlay never applied it; both do now, and `--reparse-txt` backfill's overlay never applied it; both do now, and `--reparse-txt`
re-reads the saved `.TXT`s. Codec-library change. re-reads the saved `.TXT`s. Codec-library change.
- **A Series-3 waveform's time comes from its Blastware filename.** The name - **A Series-3 waveform's time comes from the instrument's own event record.**
encodes Blastware's own time to the second: equal to the report's Event Time The unit sends a copy of its event record inside the 5A stream, so it is in
on 81/81 prod and 1,249/1,249 DL2 report-paired waveforms. The binary's every Blastware file and every SFM download:
`ts2 - record time` is a second off on 260 of prod's 1,394 (199 late, 61 `00 28 05 00 ?? ?? fe 80 [trigger][stop]`, each time
early). That second mattered: on BE9558 the 61 early ones landed on their `dd mm yyyy(BE) 00 hh mm ss`.
histogram twin's second, so a fresh import wrote each waveform over its - **Measured on 7,935 waveforms.** Its trigger equals Blastware's report
histogram's row (888 files -> 827 rows), and the backfill would have moved 1,320/1,320, the filename 7,935/7,935 and the unit's `0C` record 10/10.
161 rows v0.31.0 had right a second off. New - **Provenance.** It occurs once in the unit's own A5 replies for each of 8
`blastware_file.blastware_filename_time()`; `read_blastware_file(path, recorded events, and in SFM-only downloads.
name=...)`, which the import passes the upload's real name. The binary's - **Why it mattered.** The footer's `ts2 - record time` is a second off on
estimate remains the fallback for other names. **Histograms keep `ts1`**, 260 of prod's 1,394 (199 late, 61 early). On BE9558 the 61 early ones landed
though it runs a second early against Blastware on 97% of them: with both on on their histogram twin's second, so a fresh import wrote each waveform over
Blastware's times a waveform and its histogram share a second 209 times in its histogram's row (888 files -> 827 rows). The backfill would also have
prod's store, which `(serial, timestamp)` cannot hold -- #51. Codec-library moved 161 rows that v0.31.0 had right a second off.
change. - **Validation.** A record counts only if its lead bytes, marker, both times,
its relation to the footer and its length all check out, and exactly one
candidate does.
- **Fallbacks.** Without one the estimate stands, recorded in the event's new
`decode_problems` and the sidecar's `timestamp_source`. A filename is never a
time source, only a cross-check, logged when it disagrees. A paired report
fills in only when there is no record.
- **An estimate is kept, never trusted.** An event is never discarded for
want of an exact time. But an estimated time never moves a row, never adds a
second row for an event already stored, and never lands on another event's
row (`insert_events` writes nothing and logs a warning naming both). The
file and sidecar are kept either way.
- **API.** New `decode_blastware_bytes(raw, name=None)` needs no file (the
import no longer writes a temp file); `blastware_file.blastware_filename_time()`
decodes a name for cross-checks.
- **Histograms keep `ts1`.** It runs a second early against Blastware on 97%
of them, though their record (marker `fe f5`) holds the exact start. With
both on exact times, a waveform and its histogram share a second 209 times
in prod's store, which `(serial, timestamp)` cannot hold -- #51.
- **Open.** 3 archive files named as waveforms are not recognised by the
waveform codec and keep the footer start, as before (none in prod).
Series-III reference §7.8.9.
Codec-library change.
### Added ### Added
@@ -575,7 +600,11 @@ id kept, none lost or merged, no refusals, no errors. Histograms do not move
(#51). One known extra row: a histogram whose time does not decode (#51). One known extra row: a histogram whose time does not decode
(BE18003 `T003LCYV.JD0H`) gains a duplicate on every backfill -- pre-existing, (BE18003 `T003LCYV.JD0H`) gains a duplicate on every backfill -- pre-existing,
#52. A log line "nothing stored" from `insert_events` names a file whose #52. A log line "nothing stored" from `insert_events` names a file whose
corrected second another file already holds; expected zero. corrected second another file already holds; expected zero. (The rehearsal
ran when waveform times came from the filename; the event record that replaced
it gives the identical time on all 1,394 of those waveforms, so it stands.) A
log line "no validated embedded event record" names a waveform kept on the
footer estimate; expected zero (every prod waveform has one).
**Terra-View** reads SFM's rows by id and needs no change, but its views show **Terra-View** reads SFM's rows by id and needs no change, but its views show
the corrected times: waveforms move up to hours later in the day, so an event the corrected times: waveforms move up to hours later in the day, so an event
+34 -3
View File
@@ -4,8 +4,8 @@ A ground-up replacement for **Blastware** — Instantel's aging Windows-only
software for managing seismographs. Supports both the **MiniMate Plus software for managing seismographs. Supports both the **MiniMate Plus
(Series III)** and the **Micromate (Series IV / "Thor")** families: (Series III)** and the **Micromate (Series IV / "Thor")** families:
Series III via the live RS-232 / TCP wire protocol *and* Blastware ACH file Series III via the live RS-232 / TCP wire protocol *and* Blastware ACH file
ingest; Series IV currently via Thor TXT-paired IDF file ingest, with the ingest; Series IV via Thor IDF file ingest (binary codec verified per-sample
binary codec on the roadmap. against Thor's own exports), plus a read-only live client in `micromate/`.
Built in Python. Runs on Windows, Linux, or macOS. Connects to instruments Built in Python. Runs on Windows, Linux, or macOS. Connects to instruments
over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55). over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55).
@@ -59,6 +59,21 @@ over direct RS-232 or cellular modem (Sierra Wireless RV50 / RV55).
> recent.zip` (recent events' waveform files), and a gated > recent.zip` (recent events' waveform files), and a gated
> `POST /db/restore` (`SFM_DB_RESTORE_ENABLED`, dev-only). Terra-View > `POST /db/restore` (`SFM_DB_RESTORE_ENABLED`, dev-only). Terra-View
> v0.17.0 drives them to pull a one-pass prod→dev refresh. > v0.17.0 drives them to pull a one-pass prod→dev refresh.
> **v0.32.0 (2026-10-27)** makes stored event times trustworthy.
> - **Series-III waveform times** now come from the instrument's own event
> record, which the unit sends inside its 5A stream. They used to be stamped
> with the monitoring-session start, hours off. The new time matches
> Blastware on every one of 1,320 report-paired waveforms, with no filename
> needed.
> - **Re-storing an event at its corrected time moves its row in place**,
> instead of duplicating it.
> - **Sub-minute histograms recorded with the mic off now decode** (#47, #49).
> - **Micromate `.h5` samples are on Thor's own scale** (#42).
> - **Series IV:** the live protocol is mapped (`docs/micromate_protocol_reference.md`)
> and has a read-only client.
>
> ⚠ The deploy owes a backfill and moves stored waveform times; see the
> changelog's *Migration*.
> See [CHANGELOG.md](CHANGELOG.md) for full version history. > See [CHANGELOG.md](CHANGELOG.md) for full version history.
--- ---
@@ -209,6 +224,8 @@ Used by watcher daemons to push field-collected event files into the SFM DB
+ waveform store. Both accept multipart uploads of binary event files + waveform store. Both accept multipart uploads of binary event files
optionally paired with their ASCII sidecar reports; both dedup by optionally paired with their ASCII sidecar reports; both dedup by
`(serial, timestamp)` and UPSERT device-authoritative fields on re-import. `(serial, timestamp)` and UPSERT device-authoritative fields on re-import.
Since v0.32.0 a Series-III event re-stored at a corrected time is matched by
its Blastware filename and moved in place (see *Database* below).
| Method | URL | Description | | Method | URL | Description |
|--------|-----|-------------| |--------|-----|-------------|
@@ -348,6 +365,20 @@ resets to `0x01110000` after every erase, so timestamps are the correct
dedup field. Migration handles the transition transparently on first dedup field. Migration handles the transition transparently on first
startup. startup.
**Since v0.32.0**, `insert_events` also matches a row by its Blastware filename
(Blastware names only; a generic upload name like `imported.bw` says nothing):
- **A corrected time moves the row.** An event re-stored at a corrected time —
the v0.32.0 backfill, or a watcher re-forward — has its existing row moved in
place, keeping its id and review.
- **A taken second is refused.** If a different file already holds that second,
nothing is written.
- **An estimate never changes a row.** An event whose time is only an estimate
(no validated embedded event record; see Series-III reference §7.8.9) is still
stored, but its time never moves, merges into or duplicates a row.
Every refusal is logged as a warning.
**`device_family` (added v0.19.0)** discriminates Series III from Series **`device_family` (added v0.19.0)** discriminates Series III from Series
IV at the SQL level. Set by every import path; the UI dispatches on it IV at the SQL level. Set by every import path; the UI dispatches on it
to render mic units correctly (Series III: psi → dBL conversion; Series to render mic units correctly (Series III: psi → dBL conversion; Series
@@ -607,7 +638,7 @@ Implementation steps (concrete):
- [ ] Locate "Sensor Check" byte in compliance config (need capture with Disabled vs Before-monitoring). - [ ] Locate "Sensor Check" byte in compliance config (need capture with Disabled vs Before-monitoring).
- [ ] Call Home — map time slots 3/4 offsets; confirm `modem_power_relay_enabled`. - [ ] Call Home — map time slots 3/4 offsets; confirm `modem_power_relay_enabled`.
- [ ] RV55 DCD/DTR — newer RV55 firmware doesn't assert DCD by default; units don't resume monitoring after call-home disconnect (`--restart-monitoring` flag deferred). - [ ] RV55 DCD/DTR — newer RV55 firmware doesn't assert DCD by default; units don't resume monitoring after call-home disconnect (`--restart-monitoring` flag deferred).
- [ ] **NULL-timestamp duplicate-row dedup.** A small handful of events (2 known on prod as of 2026-05-22) have `events.timestamp IS NULL` because the codec couldn't extract a timestamp from the binary footer. The `UNIQUE(serial, timestamp)` constraint doesn't fire on `NULL` (SQL semantics: `NULL ≠ NULL`), so every `--force` backfill INSERTs a new row instead of UPSERTing the existing one. Cleanup: a one-shot SQL query that keeps only the newest row per `(serial, blastware_filename)` and deletes the rest. Longer-term: extend the unique key to `(serial, COALESCE(timestamp, blastware_filename))` or reject inserts with NULL timestamp. - [ ] **NULL-timestamp duplicate-row dedup (#52).** A small handful of events (2 known on prod as of 2026-05-22) have `events.timestamp IS NULL` because the codec couldn't extract a timestamp from the binary footer. The `UNIQUE(serial, timestamp)` constraint doesn't fire on `NULL` (SQL semantics: `NULL ≠ NULL`), so every `--force` backfill INSERTs a new row instead of UPSERTing the existing one. Cleanup: a one-shot SQL query that keeps only the newest row per `(serial, blastware_filename)` and deletes the rest. Longer-term: extend the unique key to `(serial, COALESCE(timestamp, blastware_filename))` or reject inserts with NULL timestamp.
- [ ] **Histogram body sub-format with `byte[5] != 0`.** ~3 events on prod (`T190LD5Q.LD0H`, `O121L4L1.GU0H`) use a histogram body my walker doesn't recognize — the first block has `byte[5] = 0x01` or `0x07` instead of `0x00`, and the entire body lacks the `1e 0a 00 00` tail signature. Codec returns 0 valid blocks; their DB PVS comes from the bw_report ASCII overlay (which BW computed from the same binary, so the DB columns are correct). Only the `.h5` waveform plot is empty. Cracking the sub-format would unlock the plot. Needs binary+ASCII pairs from a few `byte[5]!=0` events; same RE approach as the K558 case. - [ ] **Histogram body sub-format with `byte[5] != 0`.** ~3 events on prod (`T190LD5Q.LD0H`, `O121L4L1.GU0H`) use a histogram body my walker doesn't recognize — the first block has `byte[5] = 0x01` or `0x07` instead of `0x00`, and the entire body lacks the `1e 0a 00 00` tail signature. Codec returns 0 valid blocks; their DB PVS comes from the bw_report ASCII overlay (which BW computed from the same binary, so the DB columns are correct). Only the `.h5` waveform plot is empty. Cracking the sub-format would unlock the plot. Needs binary+ASCII pairs from a few `byte[5]!=0` events; same RE approach as the K558 case.
- [ ] **Histogram body sub-format with `byte[5] == 0x00` but undecodable.** Observed 2026-05-28 on BE17353 (S353) events: `S353L4H2.FZ0H`, `S353L4H2.P00H`, `S353L4H3.7O0H`, `S353L4H3.E10H`. Body starts `00 00 00 01 0a 00 XX 00 ...` which LOOKS like a valid histogram block header (marker 0x000a at byte[4:6] ✓, byte[5]=0x00 normal-format ✓), but the walker finds zero data blocks across the whole body. Likely an extra header before the block stream OR a different tail signature than `1e 0a 00 00`. Smaller body lengths (1900-2100 bytes) suggest these may be short-recording histogram variants. Same operational impact as the byte[5]!=0 case: event ingests cleanly, DB peaks correct via bw_report overlay, only the chart is empty. Worth dumping a hex view of one body to diagnose. - [ ] **Histogram body sub-format with `byte[5] == 0x00` but undecodable.** Observed 2026-05-28 on BE17353 (S353) events: `S353L4H2.FZ0H`, `S353L4H2.P00H`, `S353L4H3.7O0H`, `S353L4H3.E10H`. Body starts `00 00 00 01 0a 00 XX 00 ...` which LOOKS like a valid histogram block header (marker 0x000a at byte[4:6] ✓, byte[5]=0x00 normal-format ✓), but the walker finds zero data blocks across the whole body. Likely an extra header before the block stream OR a different tail signature than `1e 0a 00 00`. Smaller body lengths (1900-2100 bytes) suggest these may be short-recording histogram variants. Same operational impact as the byte[5]!=0 case: event ingests cleanly, DB peaks correct via bw_report overlay, only the chart is empty. Worth dumping a hex view of one body to diagnose.
- [ ] **Sensor-check waveform extraction from the BW binary.** BW's Event Report PDFs include a narrow panel on the right side of the waveform plot showing each channel's response to the sensor self-check signal (a damped sinusoid for geo, sawtooth-at-test-freq for mic). Our parser captures the test RESULTS (`test_freq_hz`, `test_ratio`, `test_amplitude_mv`, `test_results` pass/fail) and the PDF + modal display them as text — but BW's per-sample sensor-check waveform isn't accessible to us today. Two paths to add it: (a) RE the binary to find where the sensor-check samples are stored — could be a section before STRT, after the footer, or in a separate sub-record; protocol reference doesn't currently mention it. (b) If samples aren't in the binary, synthesize a representative waveform from the test parameters (damped sinusoid at `test_freq_hz` with damping from `test_ratio`). Path (a) is the honest answer; path (b) is decorative. Until either lands, the text-only sensor-check display in the report is fine. - [ ] **Sensor-check waveform extraction from the BW binary.** BW's Event Report PDFs include a narrow panel on the right side of the waveform plot showing each channel's response to the sensor self-check signal (a damped sinusoid for geo, sawtooth-at-test-freq for mic). Our parser captures the test RESULTS (`test_freq_hz`, `test_ratio`, `test_amplitude_mv`, `test_results` pass/fail) and the PDF + modal display them as text — but BW's per-sample sensor-check waveform isn't accessible to us today. Two paths to add it: (a) RE the binary to find where the sensor-check samples are stored — could be a section before STRT, after the footer, or in a separate sub-record; protocol reference doesn't currently mention it. (b) If samples aren't in the binary, synthesize a representative waveform from the test parameters (damped sinusoid at `test_freq_hz` with damping from `test_ratio`). Path (a) is the honest answer; path (b) is decorative. Until either lands, the text-only sensor-check display in the report is fine.
+69
View File
@@ -11,6 +11,7 @@
| Date | Section | Change | | Date | Section | Change |
|---|---|---| |---|---|---|
| 2026-10-26 (5) | §7.8.9 | ✅ **The embedded event record: the instrument's trigger time, inside the 5A stream.** Every Blastware waveform file carries `00 28 05 00 ?? ?? fe 80 [trigger 8 B][stop 8 B]`, times as `dd mm yyyy(BE) 00 hh mm ss`. The trigger equals Blastware's report 1,320/1,320, the filename 7,935/7,935 and the unit's 0C record 10/10. It occurs once in the unit's own A5 payloads (8/8 events) and in SFM-only downloads (2/2): instrument data, not Blastware's. The footer's `ts2 - record time` is only an estimate, a second off on ~19%. Decoder rule, validation and an open case (3 waveform-named files the codec does not recognise) in §7.8.9. 🔶 The §7.5 `0C` "sub_code" timestamp variants look like the same 8-byte form read with its escapes. |
| 2026-10-17 | §7.6.1 | 🔶 **OPEN — the 6-byte "stable anchor" may be two settings at their defaults, not a constant.** Series IV's `0x1A` has the same field order as the S3 compliance block, and a keypad diff pass on a Micromate (UM20147) measured the bytes in the anchor's position: `[f32 BE pre-trigger, negative seconds][record stop mode, 00 00 = Fixed]`. `be 80 00 00` is exactly −0.25 s. If S3 matches — **inferred, not measured on S3** — then any S3 unit set to Record Stop Mode = Auto (a basic Blastware Compliance Setup option) or a non-default pre-trigger loses the anchor, and `client.py` silently decodes no recording mode / sample rate / interval / record time and skips them on write. No S3 capture has ever been taken in Auto stop mode (see the 2026-03-09 Auto Window rows), which would explain why the anchor never broke. To settle: one BW capture with Record Stop Mode = Auto. See `docs/micromate_protocol_reference.md` → *The `0x1A` field map from a keypad pass*. | | 2026-10-17 | §7.6.1 | 🔶 **OPEN — the 6-byte "stable anchor" may be two settings at their defaults, not a constant.** Series IV's `0x1A` has the same field order as the S3 compliance block, and a keypad diff pass on a Micromate (UM20147) measured the bytes in the anchor's position: `[f32 BE pre-trigger, negative seconds][record stop mode, 00 00 = Fixed]`. `be 80 00 00` is exactly −0.25 s. If S3 matches — **inferred, not measured on S3** — then any S3 unit set to Record Stop Mode = Auto (a basic Blastware Compliance Setup option) or a non-default pre-trigger loses the anchor, and `client.py` silently decodes no recording mode / sample rate / interval / record time and skips them on write. No S3 capture has ever been taken in Auto stop mode (see the 2026-03-09 Auto Window rows), which would explain why the anchor never broke. To settle: one BW capture with Record Stop Mode = Auto. See `docs/micromate_protocol_reference.md` → *The `0x1A` field map from a keypad pass*. |
| 2026-08-26 | S7.6.2, S15 | **MULTI-INTERVAL HISTOGRAM BLOCKS - sub-minute intervals pack several per block.** The device always writes one minute of data per block, so a shorter histogram interval means more intervals packed into a longer block: 1 min -> 1 (the standard 32-byte block), 15 s -> 4 (stride 92), 2 s -> 30 (stride 612), with `stride = 12 + n * 20`. Each 20-byte record holds 8 x uint16 **little**-endian values (peak/half-period per channel) plus a 2-word tail whose first word is `0000` on every real interval. The standard block is big-endian - the variant is not. This recovers **415 files** (216 on BE18193 at 2 s, 199 on BE9440 at 15 s) that previously decoded to nothing, and before that were being accepted by the WAVEFORM codec and returning garbage up to 400x the device-reported PPV. | | 2026-08-26 | S7.6.2, S15 | **MULTI-INTERVAL HISTOGRAM BLOCKS - sub-minute intervals pack several per block.** The device always writes one minute of data per block, so a shorter histogram interval means more intervals packed into a longer block: 1 min -> 1 (the standard 32-byte block), 15 s -> 4 (stride 92), 2 s -> 30 (stride 612), with `stride = 12 + n * 20`. Each 20-byte record holds 8 x uint16 **little**-endian values (peak/half-period per channel) plus a 2-word tail whose first word is `0000` on every real interval. The standard block is big-endian - the variant is not. This recovers **415 files** (216 on BE18193 at 2 s, 199 on BE9440 at 15 s) that previously decoded to nothing, and before that were being accepted by the WAVEFORM codec and returning garbage up to 400x the device-reported PPV. |
| 2026-08-25 (3) | S7.6.1, S15 | **THE WAVEFORM BODY IS A RECORD CHAIN, NOT A TAG STREAM — supersedes the segment-header model entirely.** Records are self-delimiting: `off+2` is a uint16 BE length and `next = off + 2 + len`; the chain ends on a record whose chan_id is `0x06`. `off+8` holds a 3-valued mode enum - `02 00` (14-byte header, anchors, cumulative deltas), `01 00` (10-byte, no anchors, ABSOLUTE values), `00 03` (10-byte, no tags at all, raw 12-bit absolute). **`40 NN` is an ordinary int16 BE data block of length 2*NN+2**, never a header; reading it as a 2*NN+16 header is what made walks drift, and the 'variable prefix' of 0/2/4/6/8 bytes reported earlier the same day was walker drift, exactly `4 - (old_stop - true_record_start)`. Verified: chain terminates on `06` in 1387/1388 files; all four channels equal length in **1388/1388** (was 156/1388); ASCII sample-count exact 72/75 -> **75/75**, fully exact 70/75 -> **73/75**; device PPV on a live decode **1306/1306** waveform (mean abs ratio error 0.00000) and **4458/4459** histogram. Also eliminated the walker-over-read class: 24 of those files were histograms the waveform codec was wrongly accepting. The superseded model is retained as `decode_waveform_legacy` because `micromate/idf_file.py` pins it for Thor IDFW body-offset search. | | 2026-08-25 (3) | S7.6.1, S15 | **THE WAVEFORM BODY IS A RECORD CHAIN, NOT A TAG STREAM — supersedes the segment-header model entirely.** Records are self-delimiting: `off+2` is a uint16 BE length and `next = off + 2 + len`; the chain ends on a record whose chan_id is `0x06`. `off+8` holds a 3-valued mode enum - `02 00` (14-byte header, anchors, cumulative deltas), `01 00` (10-byte, no anchors, ABSOLUTE values), `00 03` (10-byte, no tags at all, raw 12-bit absolute). **`40 NN` is an ordinary int16 BE data block of length 2*NN+2**, never a header; reading it as a 2*NN+16 header is what made walks drift, and the 'variable prefix' of 0/2/4/6/8 bytes reported earlier the same day was walker drift, exactly `4 - (old_stop - true_record_start)`. Verified: chain terminates on `06` in 1387/1388 files; all four channels equal length in **1388/1388** (was 156/1388); ASCII sample-count exact 72/75 -> **75/75**, fully exact 70/75 -> **73/75**; device PPV on a live decode **1306/1306** waveform (mean abs ratio error 0.00000) and **4458/4459** histogram. Also eliminated the walker-over-read class: 24 of those files were histograms the waveform codec was wrongly accepting. The superseded model is retained as `decode_waveform_legacy` because `micromate/idf_file.py` pins it for Thor IDFW body-offset search. |
@@ -2240,6 +2241,74 @@ bulk stream protocol from §7.8.5. Use the `0x46` keys, not the `0x2C` keys, as
--- ---
#### 7.8.9 The embedded event record — the instrument's trigger time, inside the 5A stream ✅ 2026-10-26
Every Blastware waveform file carries a copy of the instrument's **event record**, and it
holds the event's **trigger time to the second**. It is the instrument's data, not
Blastware's: it arrives in the unit's own 5A stream (provenance below). Found by reading a
dump in `seismo_lab.py`'s Inspector, where it sits in the trailing region the Inspector
labels "unknown", after the notes and channel blocks.
**Layout** — offsets relative to `M`, the position of the marker:
| bytes | content | measured on 7,935 waveforms (DL2 archive 6,541 + prod store 1,394) |
|---|---|---|
| `[M-6:M-2]` | `00 28 05 00` | constant, 7,935/7,935 ✅ (meaning ❓) |
| `[M-2:M]` | 2 bytes | vary; not decoded ❓ |
| `[M:M+2]` | `fe 80` — marker | 7,935/7,935 ✅. Histogram files carry `fe f5` here instead (#51) |
| `[M+2:M+10]` | **trigger** — `dd mm yyyy(BE) 00 hh mm ss` | = Blastware's report Event Time 1,320/1,320; = the filename's time 7,935/7,935; = the unit's `0C` record 10/10 ✅ |
| `[M+10:M+18]` | **stop**, same format | = the footer's `ts2` on 7,836; one second before it on 99 ✅ |
| `[M+18:M+40]` | `[+18]` `00` (7,933/7,935), `[+22:24]` `00 00`, `[+26:34]` eight `00`, `[+36]` `00`, `[+37:39]` `16 32`, `[+39]` `00` | constant; meaning ❓ |
**Relations** (7,935/7,935): footer `ts1` (session start) ≤ trigger ≤ stop; and
`(stop - trigger) - record time` lies in −3 … +6 s.
**Ambiguity:** 30 files hold a second `fe 80`; it never passes the checks below, and every
file has exactly one candidate that does.
**Provenance** (where it comes from — measured):
- **Blastware's download of 8 BE9441 events** (2026-10-26 recording,
`tests/fixtures/minimate-bench-10-26-26-blastware/`). Each event's 18-byte record, with
the 24 bytes before it and the 22 after, occurs **exactly once in the unit's own A5 reply
payloads**. Its trigger equals the unit's separate `0C` (SUB F3) record 8/8: F3 data
`[11:19]` is the same `dd mm yyyy 00 hh mm ss` form.
- **SFM's own downloads of BE9441 events 0 and 1** (2026-10-25, no Blastware anywhere). The
record is present, and its trigger = the `0C` record, 2/2.
- So it is instrument-transmitted. An event SFM receives directly carries it, with no
Blastware name involved.
**What it replaces.** The footer alone gives only an estimate. `ts2` is the stop to the
second (its byte `[4]` is `00` in all 1,330 report-paired files, so it holds no fraction),
and `ts2 - record time` is exact on 1,113/1,330 report-paired waveforms and a second late
on 217. On prod's 1,394 it is a second off on 260: 199 late, 61 early.
**Decoder** (`event_file_io._embedded_event_record`).
- **What qualifies.** A candidate counts only when it has the lead bytes, the marker, two
well-formed times (zero byte zero), `ts1 ≤ trigger ≤ stop`, a stop equal to `ts2` or one
second before it, and a length that agrees with the record time.
- **One answer or none.** Exactly one candidate must qualify. With none, or more than one,
the event keeps the footer estimate and carries a `decode_problems` entry; nothing is
guessed.
- **Names and reports are cross-checks only.** A Blastware filename is never a time source:
a disagreement is logged and the record kept. A paired report's time fills in only when
there is no validated record.
- Decoded from raw bytes with no name: every waveform the codec recognises takes the
record's time, 7,961/7,961 (DL2 6,538, prod 1,394, bench 29), with 0 disagreements
against the filename or a report. The 3 it does not recognise are the open case below.
🔶 **For the decoder audit (#53), inferred only.** The `0C` timestamp layouts documented in §7.5
look like this same 8-byte form, read without its escapes:
- the "sub_code 0x10" 9-byte form;
- the 10-byte "continuous mode" form, whose own example `10 03 10 04 07 ea 00 0f 14 11` reads
as day 3, month 4, escaped, at 15:20:17.
The early captures were all in April (month `04`, sent as `10 04`). Not changed here.
⚠ **Open:** 3 DL2 files named as waveforms (`K440I4LG.JK0W`, `K888HW07.7K0W`,
`R349KPNU.FK0W`) carry a valid record, but their body is not recognised by the waveform
codec. They are decoded as histograms and stamped with the footer start, 4 s off; `dev`
behaves the same. Prod's store has none. Tracked in #53.
## 7.9 Compliance Config Field Inventory (Blastware UI, 2026-04-08) ✅ ## 7.9 Compliance Config Field Inventory (Blastware UI, 2026-04-08) ✅
Fields visible in the Blastware "Compliance Setup" dialog. ✅ = byte offset confirmed in code. ❓ = not yet located in raw bytes. Fields visible in the Blastware "Compliance Setup" dialog. ✅ = byte offset confirmed in code. ❓ = not yet located in raw bytes.
+148 -48
View File
@@ -50,7 +50,7 @@ SIDECAR_KIND = "sfm.event"
# bumped without a `pip install` re-run — leading to confusing stale # bumped without a `pip install` re-run — leading to confusing stale
# version stamps in sidecars. Bump this constant and CHANGELOG.md # version stamps in sidecars. Bump this constant and CHANGELOG.md
# together at release time. # together at release time.
TOOL_VERSION = "0.32.0" # waveform times from the BW name, report dates, histogram reader; gates the backfill regen TOOL_VERSION = "0.32.0" # waveform times from the event record, report dates, histogram reader; gates the backfill regen
try: try:
# Best-effort: prefer the installed metadata when it's NEWER than the # Best-effort: prefer the installed metadata when it's NEWER than the
@@ -299,16 +299,29 @@ def apply_report_to_event(event: Event, report: BwAsciiReport) -> None:
event.sample_rate = report.sample_rate_sps event.sample_rate = report.sample_rate_sps
if report.record_time_s is not None: if report.record_time_s is not None:
event.rectime_seconds = report.record_time_s event.rectime_seconds = report.record_time_s
# The report's event_datetime is Blastware's exact trigger time (parsed # The report's event_datetime is Blastware's copy of the unit's trigger time
# from Event Time + Event Date). Prefer it over the binary footer's stop # (Event Time + Event Date) -- see _apply_report_time.
# time so a report-paired import matches BW to the second. if report.event_datetime is not None:
edt = report.event_datetime _apply_report_time(event, report.event_datetime)
if edt is not None:
event.timestamp = Timestamp(
raw=b"", flag=0x10, def _apply_report_time(event: Event, edt: datetime.datetime) -> None:
year=edt.year, unknown_byte=0, month=edt.month, day=edt.day, """A paired report's time fills in only when the instrument's own event
hour=edt.hour, minute=edt.minute, second=edt.second, record gave none. Against a validated record it is a cross-check: a
) disagreement is logged and the record kept. (They agree on 1,320/1,320.)"""
if event.timestamp_source == "event_record" and event.timestamp is not None:
ts = event.timestamp
cur = datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
if cur != edt.replace(microsecond=0):
log.warning("event record says %s, its paired report %s; the event record "
"is kept", cur, edt)
return
event.timestamp = Timestamp(
raw=b"", flag=0x10,
year=edt.year, unknown_byte=0, month=edt.month, day=edt.day,
hour=edt.hour, minute=edt.minute, second=edt.second,
)
event.timestamp_source = "report"
def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None: def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
@@ -374,8 +387,8 @@ def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
rt = rec.get("record_time_s") rt = rec.get("record_time_s")
if rt is not None: if rt is not None:
event.rectime_seconds = rt event.rectime_seconds = rt
# As apply_report_to_event: Blastware's exact trigger beats the binary's, # As apply_report_to_event: the report's time fills in only without a
# which is a second late on 15 of prod's 81 report-paired waveforms. # validated event record (_apply_report_time).
edt = bw_report.get("event_datetime") edt = bw_report.get("event_datetime")
if edt: if edt:
try: try:
@@ -383,11 +396,7 @@ def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None:
except (TypeError, ValueError): except (TypeError, ValueError):
t = None t = None
if t is not None: if t is not None:
event.timestamp = Timestamp( _apply_report_time(event, t)
raw=b"", flag=0x10,
year=t.year, unknown_byte=0, month=t.month, day=t.day,
hour=t.hour, minute=t.minute, second=t.second,
)
def _project_info_to_dict(pi: Optional[ProjectInfo]) -> dict: def _project_info_to_dict(pi: Optional[ProjectInfo]) -> dict:
@@ -444,9 +453,8 @@ def event_to_sidecar_dict(
supplies a non-empty value (the report mirrors the device's supplies a non-empty value (the report mirrors the device's
compliance config, which is what BW shows in its event report). compliance config, which is what BW shows in its event report).
- ``event.timestamp`` is overlaid from the report's Event Date + - ``event.timestamp`` is overlaid from the report's Event Date +
Event Time (BW's report timestamps are second-resolution and Event Time -- unless it came from the instrument's own embedded event
match the binary's footer; we prefer the report value because record, which the report only cross-checks (see _apply_report_time).
the BW-binary footer timestamp can drift on some firmware).
""" """
if source_kind not in {"sfm-live", "sfm-ach", "bw-import", "idf-import"}: if source_kind not in {"sfm-live", "sfm-ach", "bw-import", "idf-import"}:
raise ValueError(f"unknown source_kind: {source_kind!r}") raise ValueError(f"unknown source_kind: {source_kind!r}")
@@ -455,7 +463,7 @@ def event_to_sidecar_dict(
# ── Overlay event fields from the report when present ─────────────────── # ── Overlay event fields from the report when present ───────────────────
timestamp_iso = _ts_iso(event.timestamp) timestamp_iso = _ts_iso(event.timestamp)
if bw_report and bw_report.event_datetime: if bw_report and bw_report.event_datetime and event.timestamp_source != "event_record":
timestamp_iso = bw_report.event_datetime.isoformat() timestamp_iso = bw_report.event_datetime.isoformat()
# Build peak_values, optionally overlaid from the report. The report # Build peak_values, optionally overlaid from the report. The report
@@ -485,6 +493,7 @@ def event_to_sidecar_dict(
event_block = { event_block = {
"serial": serial, "serial": serial,
"timestamp": timestamp_iso, "timestamp": timestamp_iso,
"timestamp_source": event.timestamp_source,
"waveform_key": event._waveform_key.hex() if event._waveform_key else None, "waveform_key": event._waveform_key.hex() if event._waveform_key else None,
"record_type": event.record_type, "record_type": event.record_type,
"sample_rate": event.sample_rate, "sample_rate": event.sample_rate,
@@ -492,6 +501,8 @@ def event_to_sidecar_dict(
"total_samples": event.total_samples, "total_samples": event.total_samples,
"pretrig_samples": event.pretrig_samples, "pretrig_samples": event.pretrig_samples,
} }
if event.decode_problems:
event_block["decode_problems"] = list(event.decode_problems)
if bw_report: if bw_report:
# Report values are authoritative — they're the user-configured # Report values are authoritative — they're the user-configured
# values BW reads back, not STRT-derived guesses. In particular # values BW reads back, not STRT-derived guesses. In particular
@@ -839,11 +850,75 @@ def derive_record_type_from_filename(filename, default: str = "Waveform") -> str
# float32 within it. The configured post-trigger record time (seconds) is a # float32 within it. The configured post-trigger record time (seconds) is a
# big-endian float32 exactly 30 bytes before the "Standard Recording Setup" # big-endian float32 exactly 30 bytes before the "Standard Recording Setup"
# label. Verified across the corpus reading 1.0 / 2.0 / 3.0 s on different # label. Verified across the corpus reading 1.0 / 2.0 / 3.0 s on different
# setups — and ts2 - record_time reproduces Blastware's trigger to the second # setups. ⚠ ts2 - record_time is only an estimate of the trigger: a second off
# (N844LQHB: stop 10:33:32 - 3.0 = 10:33:29). # on ~19% of files (measured 2026-10-26); the event record below is exact.
_RECSETUP_MARKER = b"Standard Recording Setup" _RECSETUP_MARKER = b"Standard Recording Setup"
_RECTIME_OFFSET_BEFORE_MARKER = 30 _RECTIME_OFFSET_BEFORE_MARKER = 30
# The instrument's own event record, which the unit sends in its 5A stream and
# Blastware therefore copies into every waveform file (measured 2026-10-26; see
# the Series-III reference, "The embedded event record"):
#
# [-6:-2] 00 28 05 00 [0:2] fe 80 [2:10] trigger [10:18] stop
#
# each time `dd mm yyyy(BE) 00 hh mm ss`. On 7,935 waveforms exactly one
# candidate passes every check below, and its trigger equals Blastware's report
# (1,320/1,320), its filename (7,935/7,935) and the unit's own 0C record.
_EVENT_RECORD_LEAD = b"\x00\x28\x05\x00"
_EVENT_RECORD_MARKER = b"\xfe\x80"
# (stop - trigger) - record time, seconds. Measured -3 .. +6 on 7,935 files.
_EVENT_RECORD_SLACK_S = (-5.0, 10.0)
def _ts8(b: bytes) -> Optional[datetime.datetime]:
"""`dd mm yyyy(BE) 00 hh mm ss`, strictly: the zero byte must be zero."""
if len(b) < 8 or b[4] != 0:
return None
try:
return datetime.datetime((b[2] << 8) | b[3], b[1], b[0], b[5], b[6], b[7])
except ValueError:
return None
def _embedded_event_record(
raw: bytes, end: int, start: Optional[datetime.datetime],
stop: Optional[datetime.datetime], record_time: Optional[float],
) -> tuple[Optional[datetime.datetime], str]:
"""The trigger time from the instrument's embedded event record, or (None, why).
Every `fe 80` before `end` (the footer) is a candidate. One counts only if
its lead bytes match, both its times are well formed, the footer's session
start <= trigger <= its stop, its stop is the footer's stop or a second
before it, and its length agrees with the record time. Exactly one may
pass: none, or more than one, is reported rather than guessed between.
"""
if start is None or stop is None:
return None, "the footer has no start and stop to check one against"
found, rejected = [], 0
i = raw.find(_EVENT_RECORD_MARKER, 6)
while 0 <= i and i + 18 <= end:
trig, rec_stop = _ts8(raw[i + 2:i + 10]), _ts8(raw[i + 10:i + 18])
valid = (
raw[i - 6:i - 2] == _EVENT_RECORD_LEAD
and trig is not None and rec_stop is not None
and start <= trig <= rec_stop
and 0 <= (stop - rec_stop).total_seconds() <= 1
and (record_time is None
or _EVENT_RECORD_SLACK_S[0]
<= (rec_stop - trig).total_seconds() - record_time
<= _EVENT_RECORD_SLACK_S[1])
)
if valid:
found.append(trig)
else:
rejected += 1
i = raw.find(_EVENT_RECORD_MARKER, i + 1)
if len(found) == 1:
return found[0], ""
if found:
return None, f"{len(found)} candidates validate"
return None, (f"{rejected} candidate(s), none valid" if rejected else "no candidate")
def _parse_record_time_seconds(raw: bytes) -> Optional[float]: def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
"""The configured post-trigger record time in seconds, from the recording- """The configured post-trigger record time in seconds, from the recording-
@@ -860,17 +935,27 @@ def _parse_record_time_seconds(raw: bytes) -> Optional[float]:
def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event: def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -> Event:
""" """Parse a Blastware event file into an Event: `decode_blastware_bytes` on its
Parse a Blastware waveform file into an Event. bytes, `name` defaulting to the file's own (see there -- never a time source)."""
path = Path(path)
return decode_blastware_bytes(path.read_bytes(), name=name or path.name)
`name` is the file's real Blastware name when `path` is not (an upload
stashed under a temp name); it defaults to `path.name`. A waveform's time def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event:
comes from it when it is one (see the timestamp block below). """
Parse a Blastware event's bytes into an Event. No filename is needed.
`name`, when given, labels the record type and is compared with the decoded
time -- a disagreement is logged -- but never supplies it: an event SFM
receives straight from a unit has no Blastware name.
Recovers: Recovers:
- waveform_key, rectime_seconds, total_samples, pretrig_samples - waveform_key, rectime_seconds, total_samples, pretrig_samples
(from the STRT record) (from the STRT record)
- timestamp (a waveform's from its Blastware filename, else the footer) - timestamp: a waveform's from the instrument's embedded event record
(`timestamp_source` "event_record"); without a validated one, an
estimate from the footer with a `decode_problems` entry; a histogram's
from the footer start ("footer")
- project_info (from ASCII labels embedded in the body) - project_info (from ASCII labels embedded in the body)
- raw_samples (Tran/Vert/Long/MicL int16 lists) - raw_samples (Tran/Vert/Long/MicL int16 lists)
- peak_values (computed from raw_samples; approximate — see notes - peak_values (computed from raw_samples; approximate — see notes
@@ -881,22 +966,20 @@ def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -
byte-for-byte regeneration of the BW file from this Event alone is byte-for-byte regeneration of the BW file from this Event alone is
not possible — the on-disk BW file IS the byte-for-byte source. not possible — the on-disk BW file IS the byte-for-byte source.
""" """
path = Path(path) label = name or "<bytes>"
name = name or path.name
raw = path.read_bytes()
if len(raw) < _bw._WAVEFORM_HEADER_SIZE + 21 + 26: if len(raw) < _bw._WAVEFORM_HEADER_SIZE + 21 + 26:
raise ValueError(f"{path}: file too short ({len(raw)} bytes) to be a BW event") raise ValueError(f"{label}: file too short ({len(raw)} bytes) to be a BW event")
# Header: validate magic prefix. # Header: validate magic prefix.
header = raw[:_bw._WAVEFORM_HEADER_SIZE] header = raw[:_bw._WAVEFORM_HEADER_SIZE]
if not header.startswith(_bw._FILE_HEADER_PREFIX): if not header.startswith(_bw._FILE_HEADER_PREFIX):
raise ValueError(f"{path}: not a Blastware file (bad header prefix)") raise ValueError(f"{label}: not a Blastware file (bad header prefix)")
# STRT record: 21 bytes immediately after the header. # STRT record: 21 bytes immediately after the header.
strt_raw = raw[_bw._WAVEFORM_HEADER_SIZE : _bw._WAVEFORM_HEADER_SIZE + 21] strt_raw = raw[_bw._WAVEFORM_HEADER_SIZE : _bw._WAVEFORM_HEADER_SIZE + 21]
strt_fields = _decode_strt(strt_raw) strt_fields = _decode_strt(strt_raw)
if not strt_fields: if not strt_fields:
raise ValueError(f"{path}: STRT record missing or malformed") raise ValueError(f"{label}: STRT record missing or malformed")
# Footer: locate the 0e 08 marker, validating the year is in a sane range. # Footer: locate the 0e 08 marker, validating the year is in a sane range.
body_start = _bw._WAVEFORM_HEADER_SIZE + 21 body_start = _bw._WAVEFORM_HEADER_SIZE + 21
@@ -935,7 +1018,7 @@ def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -
if footer_pos < 0 and len(raw) >= 26: if footer_pos < 0 and len(raw) >= 26:
footer_pos = len(raw) - 26 footer_pos = len(raw) - 26
if footer_pos < body_start: if footer_pos < body_start:
raise ValueError(f"{path}: footer not found") raise ValueError(f"{label}: footer not found")
body = raw[body_start : footer_pos] body = raw[body_start : footer_pos]
footer = raw[footer_pos : footer_pos + 26] footer = raw[footer_pos : footer_pos + 26]
@@ -982,7 +1065,7 @@ def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -
if decoded is None: if decoded is None:
log.warning( log.warning(
"%s: body codec failed to decode (body starts %s) — " "%s: body codec failed to decode (body starts %s) — "
"raw_samples will be empty", path, body[:8].hex(" "), "raw_samples will be empty", label, body[:8].hex(" "),
) )
samples = {"Tran": [], "Vert": [], "Long": [], "MicL": []} samples = {"Tran": [], "Vert": [], "Long": [], "MicL": []}
else: else:
@@ -1022,20 +1105,36 @@ def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -
# time — keep it. # time — keep it.
# Discriminate by ``is_waveform_body`` (the codec), not the filename. # Discriminate by ``is_waveform_body`` (the codec), not the filename.
# #
# ⚠ 2026-10-26 (measured): ts2 - record time is a second off on 260 of # ⚠ 2026-10-26 (measured): ts2 - record time is a second off on ~19% of
# prod's 1,394 waveforms (199 late, 61 early). A Blastware filename # waveforms. The exact trigger is in the instrument's own event record,
# carries Blastware's own time -- equal to the report's Event Time on # embedded in the 5A stream (_embedded_event_record), so a waveform takes
# 1,330/1,330 -- so a waveform takes it when `name` is one, and ts2 - # it from there. Without a validated one the estimate stands, reported as a
# record time only otherwise. Histograms stay on ts1 although it runs a # decode problem -- never a filename's time, which is only a cross-check.
# second early on 97%: in Blastware's timing a waveform and its histogram # Histograms stay on ts1 although it runs a second early on 97% (their
# share a second 209 times in prod's store, and events is unique on # record, marker fe f5, holds the exact start): in Blastware's timing a
# (serial, timestamp). # waveform and its histogram share a second 209 times in prod's store, and
# events is unique on (serial, timestamp) -- #51.
if is_waveform_body and ts2 is not None: if is_waveform_body and ts2 is not None:
_stop = datetime.datetime(ts2.year, ts2.month, ts2.day, _stop = datetime.datetime(ts2.year, ts2.month, ts2.day,
ts2.hour, ts2.minute, ts2.second) ts2.hour, ts2.minute, ts2.second)
_rt = _parse_record_time_seconds(raw) _rt = _parse_record_time_seconds(raw)
_trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop _start = (datetime.datetime(ts1.year, ts1.month, ts1.day, ts1.hour, ts1.minute, ts1.second)
_trig = _bw.blastware_filename_time(name) or _trig if ts1 is not None else None)
_trig, _why = _embedded_event_record(raw, footer_pos, _start, _stop, _rt)
if _trig is not None:
ev.timestamp_source = "event_record"
else:
_trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop
ev.timestamp_source = "estimate"
_problem = (f"no validated embedded event record ({_why}); the time is "
"estimated as the footer stop minus the record time, which is a "
"second off on ~19% of measured files")
ev.decode_problems.append(_problem)
log.warning("%s: %s", label, _problem)
_named = _bw.blastware_filename_time(name) if name else None
if _named is not None and _named != _trig:
log.warning("%s: decoded event time %s (%s) disagrees with the filename's %s; "
"the decoded time is kept", label, _trig, ev.timestamp_source, _named)
ev.timestamp = Timestamp( ev.timestamp = Timestamp(
raw=footer[10:18], raw=footer[10:18],
flag=0x10, flag=0x10,
@@ -1049,6 +1148,7 @@ def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) -
year=ts1.year, unknown_byte=0, month=ts1.month, day=ts1.day, year=ts1.year, unknown_byte=0, month=ts1.month, day=ts1.day,
hour=ts1.hour, minute=ts1.minute, second=ts1.second, hour=ts1.hour, minute=ts1.minute, second=ts1.second,
) )
ev.timestamp_source = "footer"
ev.project_info = ProjectInfo( ev.project_info = ProjectInfo(
project=project, client=client, operator=user, sensor_location=seisloc, project=project, client=client, operator=user, sensor_location=seisloc,
+9
View File
@@ -553,6 +553,15 @@ class Event:
# shape diagnostic (rendered fit-to-box). None when absent. # shape diagnostic (rendered fit-to-box). None when absent.
sensor_check: Optional[dict] = None # {"Tran": [...], ..., "MicL": [...]} sensor_check: Optional[dict] = None # {"Tran": [...], ..., "MicL": [...]}
# Where `timestamp` came from, when decoded from a Blastware binary
# (event_file_io): "event_record" -- the instrument's own event record in
# the 5A stream, validated; "report" -- a paired Blastware report;
# "footer" -- a histogram's footer start; "estimate" -- footer stop minus
# the record time, a second off on ~19% of measured files, so it comes with
# an entry in decode_problems. None: not decoded from a file.
timestamp_source: Optional[str] = None
decode_problems: list = field(default_factory=list)
# ── Debug / introspection ───────────────────────────────────────────────── # ── Debug / introspection ─────────────────────────────────────────────────
# Raw 210-byte waveform record bytes, set when debug mode is active. # Raw 210-byte waveform record bytes, set when debug mode is active.
# Exposed by the SFM server via ?debug=true so field layouts can be verified. # Exposed by the SFM server via ?debug=true so field layouts can be verified.
+39 -1
View File
@@ -432,7 +432,17 @@ class SeismoDb:
pi = ev.project_info pi = ev.project_info
rec = wave_recs.get(key) or {} rec = wave_recs.get(key) or {}
if rec.get("filename") and ts and \ if getattr(ev, "timestamp_source", None) == "estimate":
# No validated event record: the time may be a second off,
# so it is never allowed to move, merge into or duplicate
# a row (_estimate_guard). The file is already stored.
why = self._estimate_guard(conn, serial, rec.get("filename"), ts)
if why:
log.warning("insert_events: %s %s: %s", serial,
rec.get("filename") or key, why)
skipped += 1
continue
elif rec.get("filename") and ts and \
self._restamp_by_file(conn, serial, rec["filename"], ts) is False: self._restamp_by_file(conn, serial, rec["filename"], ts) is False:
skipped += 1 skipped += 1
continue continue
@@ -594,6 +604,34 @@ class SeismoDb:
serial, inserted, skipped) serial, inserted, skipped)
return inserted, skipped return inserted, skipped
@staticmethod
def _estimate_guard(conn: sqlite3.Connection, serial: str, filename: Optional[str],
ts: Optional[str]) -> Optional[str]:
"""Why an event whose time is only an estimate must not be written, or None.
An estimate (the decoder found no validated event record) may be a
second off, and (serial, timestamp) is the table's key. So it never
moves a row, never lands on another event's row, and never adds a second
row for an event already stored -- each refusal is logged by the caller,
and the event's file and sidecar are already in the store. Its own
row at the same second is refreshed as before; a free second is stored.
"""
named = filename if filename and blastware_filename_time(filename) is not None else None
if named:
own = [r[0] for r in conn.execute(
"SELECT timestamp FROM events WHERE serial = ? AND blastware_filename = ?",
(serial, named))]
if own and ts not in own:
return (f"already stored under {', '.join(str(t) for t in own)}; its estimated "
f"time {ts} does not move or duplicate it")
holder = conn.execute(
"SELECT blastware_filename FROM events WHERE serial = ? AND timestamp = ?",
(serial, ts)).fetchone()
if holder is not None and (named is None or holder[0] != named):
return (f"its estimated time {ts} is held by {holder[0] or 'another event'}; "
"not merged into it")
return None
@staticmethod @staticmethod
def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str, def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str,
ts: str) -> Optional[bool]: ts: str) -> Optional[bool]:
+3 -23
View File
@@ -323,29 +323,9 @@ class WaveformStore:
Returns (event, record_dict) so callers can both insert into Returns (event, record_dict) so callers can both insert into
SeismoDb and surface the parsed Event. SeismoDb and surface the parsed Event.
""" """
# Stash the bytes to a temp path so read_blastware_file (path-based) # Decode the bytes directly; the name only labels the record type and
# can parse without us duplicating its logic. # cross-checks the decoded time (event_file_io.decode_blastware_bytes).
import tempfile ev = event_file_io.decode_blastware_bytes(bw_bytes, name=source_path.name)
with tempfile.NamedTemporaryFile(suffix=".bw", delete=False) as tmp:
tmp.write(bw_bytes)
tmp_path = Path(tmp.name)
try:
ev = event_file_io.read_blastware_file(tmp_path, name=source_path.name)
finally:
try:
tmp_path.unlink()
except FileNotFoundError:
pass
# read_blastware_file derives record_type from its path arg, but
# that arg is the tmp file (suffix ".bw") — so override with the
# original filename's encoded type (H/W/M/E/C in the BW AB0T
# scheme). Without this override every BW-imported event lands
# in the DB with record_type="Waveform" regardless of the actual
# type (Histogram, Manual, etc.).
ev.record_type = event_file_io.derive_record_type_from_filename(
source_path.name
)
# Parse the BW ASCII report if one was supplied. Failures here # Parse the BW ASCII report if one was supplied. Failures here
# are non-fatal: we still write the binary + sidecar without the # are non-fatal: we still write the binary + sidecar without the
+194
View File
@@ -0,0 +1,194 @@
"""A Series-3 waveform's time comes from the instrument's own event record, not a filename.
A Blastware waveform file carries a copy of the unit's event record:
`00 28 05 00 ?? ?? | fe 80 | trigger | stop`, each time `dd mm yyyy(BE) 00 hh mm ss`.
Measured 2026-10-26:
* it is the instrument's data: in all 8 of BE9441's events Blastware downloaded,
the record occurs exactly once in the unit's own 5A replies, and the trigger
equals the unit's separate 0C record; SFM-only downloads carry it too;
* on 7,935 waveforms (DL2 + prod store) exactly one candidate validates, its
trigger equals Blastware's report (1,320/1,320) and filename (7,935/7,935);
* the footer-only estimate (stop minus record time) is a second off on ~19%.
A filename is never a time source -- an event SFM receives itself has none --
only a cross-check, logged when it disagrees.
"""
from __future__ import annotations
import datetime
import logging
import os
import sys
from pathlib import Path
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from minimateplus.blastware_file import blastware_filename_time # noqa: E402
from minimateplus.bw_ascii_report import BwAsciiReport # noqa: E402
from minimateplus.event_file_io import (apply_report_to_event, # noqa: E402
decode_blastware_bytes, read_blastware_file)
FIX = Path(__file__).parent / "fixtures"
ZI0 = FIX / "minimate-bench-10-26-26-blastware" / "blastware" / "K441LTOF.ZI0"
ORACLE = sorted((FIX / "fft-oracle-2026-09-14").glob("N844*W"))
HISTOGRAM = FIX / "ts-fix" / "K441LKZU.C30H"
TRIGGER = datetime.datetime(2026, 10, 26, 14, 23, 42) # the unit's 0C record; the record
ESTIMATE = datetime.datetime(2026, 10, 26, 14, 23, 43) # footer stop minus record time
def _dt(ts):
return datetime.datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)
def _record_at(raw: bytes) -> int:
return raw.rfind(b"\xfe\x80")
def _decode(raw: bytes, **kw):
ev = decode_blastware_bytes(bytes(raw), **kw)
return _dt(ev.timestamp), ev.timestamp_source, ev.decode_problems
# -- no filename at all --------------------------------------------------------
def test_raw_bytes_with_no_name_give_the_instruments_trigger():
assert _decode(ZI0.read_bytes()) == (TRIGGER, "event_record", [])
def test_the_name_changes_nothing():
assert _dt(read_blastware_file(ZI0).timestamp) == TRIGGER
assert _decode(ZI0.read_bytes(), name="upload.bw")[:2] == (TRIGGER, "event_record")
@pytest.mark.parametrize("path", ORACLE, ids=lambda p: p.name)
def test_every_oracle_waveform_decodes_from_bytes_alone_to_blastwares_time(path):
# BE12844's seven, Blastware's exact times (the fft-oracle reports)
t, source, problems = _decode(path.read_bytes())
assert (t, source, problems) == (blastware_filename_time(path.name), "event_record", [])
# -- the filename is a cross-check ---------------------------------------------
def test_a_disagreeing_filename_is_logged_and_the_record_wins(caplog):
# K441LTOF.ZJ0 is a valid Blastware name one second later
with caplog.at_level(logging.WARNING):
t, source, _ = _decode(ZI0.read_bytes(), name="K441LTOF.ZJ0")
assert (t, source) == (TRIGGER, "event_record")
assert any("14:23:42" in r.message and "14:23:43" in r.message for r in caplog.records)
def test_an_agreeing_filename_logs_nothing(caplog):
with caplog.at_level(logging.WARNING):
_decode(ZI0.read_bytes(), name=ZI0.name)
assert not [r for r in caplog.records if "filename" in r.message]
# -- validation: anything less than one clean candidate is a decode problem ---
def _session_starts_after_trigger(raw: bytearray, i: int) -> None:
# only this rule breaks: the footer's ts1 becomes the record's trigger + 1 s
f = len(raw) - 26
raw[f + 2:f + 10] = raw[i + 2:i + 10]
raw[f + 9] += 1
def _broken(edit) -> bytearray:
raw = bytearray(ZI0.read_bytes())
edit(raw, _record_at(raw))
return raw
@pytest.mark.parametrize("why,edit", [
("lead bytes", lambda r, i: r.__setitem__(i - 5, 0x29)), # 00 28 05 00 -> 00 29 ..
("marker", lambda r, i: r.__setitem__(i + 1, 0x81)),
("trigger zero byte", lambda r, i: r.__setitem__(i + 6, 0x01)),
("impossible date", lambda r, i: r.__setitem__(i + 3, 13)), # month 13
("stop far from the footer's", lambda r, i: r.__setitem__(i + 17, r[i + 17] - 5)),
("trigger before the session start", lambda r, i: _session_starts_after_trigger(r, i)),
], ids=lambda x: x if isinstance(x, str) else "")
def test_a_record_that_fails_validation_is_a_decode_problem_not_a_filename(why, edit, caplog):
with caplog.at_level(logging.WARNING):
t, source, problems = _decode(_broken(edit), name=ZI0.name) # a valid name is right there
assert (t, source) == (ESTIMATE, "estimate") # never the name's time
assert problems and "event record" in problems[0]
assert any("event record" in r.message for r in caplog.records)
def test_two_records_that_both_validate_are_not_guessed_between():
def dup(raw, i):
footer = len(raw) - 26
raw[footer - 24:footer] = raw[i - 6:i + 18] # a second, identical candidate
t, source, problems = _decode(_broken(dup))
assert source == "estimate" and "2 candidates" in problems[0]
# -- reports and histograms ----------------------------------------------------
def test_a_report_does_not_override_the_instruments_record(caplog):
ev = decode_blastware_bytes(ZI0.read_bytes())
with caplog.at_level(logging.WARNING):
apply_report_to_event(ev, BwAsciiReport(event_datetime=datetime.datetime(2026, 10, 26, 14, 23, 40)))
assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "event_record")
assert any("14:23:40" in r.message for r in caplog.records)
def test_a_report_fills_in_when_the_record_is_missing():
ev = decode_blastware_bytes(bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))))
apply_report_to_event(ev, BwAsciiReport(event_datetime=TRIGGER))
assert (_dt(ev.timestamp), ev.timestamp_source) == (TRIGGER, "report")
def test_a_histogram_keeps_its_footer_start_for_now():
# Its record (marker fe f5) also holds Blastware's start -- that change is #51.
ev = read_blastware_file(HISTOGRAM)
assert (_dt(ev.timestamp), ev.timestamp_source) == (datetime.datetime(2026, 5, 10, 19, 4, 50), "footer")
def test_the_sidecar_keeps_the_instruments_time_and_says_where_it_came_from():
from minimateplus.event_file_io import event_to_sidecar_dict
ev = decode_blastware_bytes(ZI0.read_bytes())
car = event_to_sidecar_dict(ev, serial="BE9441", blastware_filename="K441LTOF.ZI0",
blastware_filesize=0, blastware_sha256="", source_kind="bw-import",
bw_report=BwAsciiReport(event_datetime=datetime.datetime(2026, 10, 26, 14, 23, 40)))
assert (car["event"]["timestamp"], car["event"]["timestamp_source"]) == \
("2026-10-26T14:23:42", "event_record")
assert "decode_problems" not in car["event"]
def test_a_sidecar_carries_the_decode_problem():
from minimateplus.event_file_io import event_to_sidecar_dict
ev = decode_blastware_bytes(bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))))
car = event_to_sidecar_dict(ev, serial="BE9441", blastware_filename="K441LTOF.ZI0",
blastware_filesize=0, blastware_sha256="", source_kind="bw-import")
assert car["event"]["timestamp_source"] == "estimate"
assert "event record" in car["event"]["decode_problems"][0]
def test_an_imported_event_with_only_an_estimate_does_not_overwrite_its_neighbour(tmp_path, caplog):
import sqlite3
from minimateplus.models import Event, PeakValues, Timestamp
from sfm.database import SeismoDb
from sfm.waveform_store import WaveformStore
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
other = Event(index=0) # a different event at 14:23:43
other.timestamp = Timestamp(raw=b"", flag=0x10, year=2026, unknown_byte=0, month=10, day=26,
hour=14, minute=23, second=43)
other._waveform_key = bytes.fromhex("01110000")
other.peak_values = PeakValues(tran=0.01, vert=0.02, long=0.03, peak_vector_sum=0.04, micl=None)
db.insert_events([other], serial="BE9441", device_family="series3",
waveform_records={"01110000": {"filename": "K441LTOF.ZJ0H"}})
broken = bytes(_broken(lambda r, i: r.__setitem__(i + 1, 0x81))) # no validated record
ev, rec = store.save_imported_bw(broken, source_path=Path(ZI0.name))
assert (_dt(ev.timestamp), ev.timestamp_source) == (ESTIMATE, "estimate")
with caplog.at_level(logging.WARNING):
assert db.insert_events([ev], serial="BE9441", device_family="series3",
waveform_records={ev._waveform_key.hex(): rec}) == (0, 1)
with sqlite3.connect(str(db.db_path)) as c:
assert c.execute("SELECT blastware_filename, peak_vector_sum FROM events").fetchall() == \
[("K441LTOF.ZJ0H", 0.04)]
assert (tmp_path / "waveforms" / "BE9441" / "K441LTOF.ZI0").exists() # the data is kept
assert any("not merged" in r.message for r in caplog.records)
+10 -6
View File
@@ -1,7 +1,10 @@
"""A Series-3 waveform's time comes from its Blastware filename, which is Blastware's own. """The Blastware filename's time: a cross-check on the decoded time, never its source.
A Blastware name encodes the event time to the second (stem + AB, see A Blastware name encodes the event time to the second (stem + AB, see
`blastware_filename`). Measured 2026-10-26: `blastware_filename`) -- Blastware's own copy of the unit's trigger. The decoder
reads the time from the instrument's embedded event record instead (see
test_bw_event_record_time.py); an event SFM receives itself has no name.
Measured 2026-10-26:
* name == the report's Event Time on 81/81 prod-snapshot and 1,249/1,249 DL2 * name == the report's Event Time on 81/81 prod-snapshot and 1,249/1,249 DL2
report-paired waveforms; report-paired waveforms;
@@ -66,15 +69,16 @@ def test_other_names_give_nothing():
assert blastware_filename_time(name) is None, name assert blastware_filename_time(name) is None, name
def test_a_waveform_takes_its_names_time_not_the_binarys(): def test_a_waveform_decodes_to_the_time_its_name_encodes():
# BE9441, 2026-10-26: the binary says 14:23:43, Blastware (and the name) 14:23:42 # BE9441, 2026-10-26: the footer estimate says 14:23:43; the event record, the
# unit's 0C record and the name all say 14:23:42
assert _dt(read_blastware_file(ZI0).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 42) assert _dt(read_blastware_file(ZI0).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 42)
def test_a_waveform_read_under_another_name_is_told_its_real_one(tmp_path): def test_a_waveform_read_under_another_name_keeps_its_time(tmp_path):
tmp = tmp_path / "upload.bw" tmp = tmp_path / "upload.bw"
tmp.write_bytes(ZI0.read_bytes()) tmp.write_bytes(ZI0.read_bytes())
assert _dt(read_blastware_file(tmp).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 43) assert _dt(read_blastware_file(tmp).timestamp) == datetime.datetime(2026, 10, 26, 14, 23, 42)
assert _dt(read_blastware_file(tmp, name=ZI0.name).timestamp) == \ assert _dt(read_blastware_file(tmp, name=ZI0.name).timestamp) == \
datetime.datetime(2026, 10, 26, 14, 23, 42) datetime.datetime(2026, 10, 26, 14, 23, 42)
+48
View File
@@ -15,6 +15,7 @@ second). insert_events now moves that row to the corrected time in place.
from __future__ import annotations from __future__ import annotations
import datetime import datetime
import logging
import os import os
import sqlite3 import sqlite3
import sys import sys
@@ -156,3 +157,50 @@ def test_of_two_copies_the_reviewed_one_with_a_time_is_the_one_moved(tmp_path):
moved = {r["id"]: r["timestamp"] for r in _rows(db)} moved = {r["id"]: r["timestamp"] for r in _rows(db)}
assert moved[reviewed] == NEW_TIME and moved["untimed"] is None assert moved[reviewed] == NEW_TIME and moved["untimed"] is None
# -- an estimated time (no validated event record) never overwrites, merges or
# duplicates; the event is still stored when its second is free --------------
def _estimated(when: str, key: str = "0111646a", pvs: float = 0.5) -> Event:
ev = _event(when, key, pvs)
ev.timestamp_source = "estimate"
return ev
def test_an_estimate_on_a_free_second_is_stored(tmp_path):
db = SeismoDb(tmp_path / "seismo_relay.db")
assert _store(db, _estimated(NEW_TIME)) == (1, 0)
assert [r["timestamp"] for r in _rows(db)] == [NEW_TIME]
def test_an_estimate_never_merges_into_another_events_row(tmp_path, caplog):
db = SeismoDb(tmp_path / "seismo_relay.db")
_store(db, _event(NEW_TIME, key="01118a2c", pvs=0.9), filename="N844LQHC.000W")
with caplog.at_level(logging.WARNING):
assert _store(db, _estimated(NEW_TIME)) == (0, 1)
assert [(r["blastware_filename"], r["peak_vector_sum"]) for r in _rows(db)] == [("N844LQHC.000W", 0.9)]
assert any("N844LQHC.000W" in r.message and "estimated" in r.message for r in caplog.records)
def test_an_estimate_never_moves_or_duplicates_its_own_stored_event(tmp_path, caplog):
db = SeismoDb(tmp_path / "seismo_relay.db")
_store(db, _event(NEW_TIME)) # stored at a validated time
with caplog.at_level(logging.WARNING):
assert _store(db, _estimated(OLD_TIME, pvs=0.7)) == (0, 1)
assert [(r["timestamp"], r["peak_vector_sum"]) for r in _rows(db)] == [(NEW_TIME, 0.5)]
assert any(NEW_TIME in r.message and "estimated" in r.message for r in caplog.records)
def test_an_estimate_on_its_own_rows_second_refreshes_it_as_before(tmp_path):
db = SeismoDb(tmp_path / "seismo_relay.db")
_store(db, _event(NEW_TIME))
assert _store(db, _estimated(NEW_TIME, pvs=0.7)) == (0, 1)
assert [(r["timestamp"], r["peak_vector_sum"]) for r in _rows(db)] == [(NEW_TIME, 0.7)]
def test_a_generic_upload_name_does_not_make_two_estimates_one_event(tmp_path):
db = SeismoDb(tmp_path / "seismo_relay.db")
_store(db, _estimated(OLD_TIME), filename="imported.bw")
assert _store(db, _estimated(NEW_TIME, key="01118a2c"), filename="imported.bw") == (1, 0)
assert len(_rows(db)) == 2
+6 -5
View File
@@ -44,11 +44,12 @@ def test_histogram_timestamp_is_window_start_unchanged():
assert _tuple(ev.timestamp) == (2026, 5, 10, 19, 4, 50), _tuple(ev.timestamp) assert _tuple(ev.timestamp) == (2026, 5, 10, 19, 4, 50), _tuple(ev.timestamp)
def test_report_event_datetime_is_authoritative_over_binary(): def test_a_report_does_not_override_the_instruments_event_record():
# The binary already yields the exact trigger, but a paired report stays # Superseded 2026-10-26: the exact trigger is the instrument's embedded event
# authoritative (e.g. if the unit clock had drifted) — applying it wins. # record, and a paired report (Blastware's copy of the same unit time) is a
# cross-check -- they agree on 1,320/1,320. A disagreement is logged.
ev = read_blastware_file(WAVEFORM) ev = read_blastware_file(WAVEFORM)
assert _tuple(ev.timestamp) == (2026, 8, 25, 10, 33, 29) # exact, from binary assert _tuple(ev.timestamp) == (2026, 8, 25, 10, 33, 29) # exact, from the record
apply_report_to_event(ev, BwAsciiReport( apply_report_to_event(ev, BwAsciiReport(
event_datetime=datetime.datetime(2026, 8, 25, 10, 35, 0))) event_datetime=datetime.datetime(2026, 8, 25, 10, 35, 0)))
assert _tuple(ev.timestamp) == (2026, 8, 25, 10, 35, 0) # report wins assert _tuple(ev.timestamp) == (2026, 8, 25, 10, 33, 29) # the record stands
+15 -8
View File
@@ -54,11 +54,16 @@ def test_a_long_form_dated_report_still_gives_its_event_time():
def test_the_saved_report_block_carries_the_event_time_back_onto_the_event(): def test_the_saved_report_block_carries_the_event_time_back_onto_the_event():
block = _bw_report_to_dict(parse_report(_report('"Event Date : 2026-08-25"'))) # It fills in when the instrument's event record gave no time ...
block = json.loads(json.dumps(_bw_report_to_dict(parse_report(_report('"Event Date : 2026-08-25"')))))
ev = Event(index=0)
apply_bw_report_dict_to_event(ev, block) # as a sidecar holds it
assert (_tuple(ev.timestamp), ev.timestamp_source) == (REPORT_TIME, "report")
# ... and is only a cross-check against a validated one
ev = read_blastware_file(WAVEFORM) ev = read_blastware_file(WAVEFORM)
assert _tuple(ev.timestamp) == datetime.datetime(2026, 8, 25, 10, 33, 29) # the binary's apply_bw_report_dict_to_event(ev, block)
apply_bw_report_dict_to_event(ev, json.loads(json.dumps(block))) # as a sidecar holds it assert (_tuple(ev.timestamp), ev.timestamp_source) == \
assert _tuple(ev.timestamp) == REPORT_TIME (datetime.datetime(2026, 8, 25, 10, 33, 29), "event_record")
def test_a_saved_report_block_without_an_event_time_leaves_the_time_alone(): def test_a_saved_report_block_without_an_event_time_leaves_the_time_alone():
@@ -67,9 +72,10 @@ def test_a_saved_report_block_without_an_event_time_leaves_the_time_alone():
assert ev.timestamp is None assert ev.timestamp is None
def test_the_backfill_with_reparse_puts_a_v031_row_on_its_reports_time(tmp_path): def test_the_backfill_with_reparse_puts_a_v031_row_on_the_instruments_time(tmp_path):
"""prod's shape: a session-start row, a saved ISO-dated .TXT, a sidecar whose """prod's shape: a session-start row, a saved ISO-dated .TXT, a sidecar whose
report block has no event time (written by the old parser).""" report block has no event time (written by the old parser). The report here
disagrees by a second: the instrument's event record is kept."""
import scripts.backfill_sidecars as backfill import scripts.backfill_sidecars as backfill
store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db") store, db = WaveformStore(tmp_path / "waveforms"), SeismoDb(tmp_path / "seismo_relay.db")
@@ -89,5 +95,6 @@ def test_the_backfill_with_reparse_puts_a_v031_row_on_its_reports_time(tmp_path)
"--db-path", str(db.db_path), "--force", "--reparse-txt"]) == 0 "--db-path", str(db.db_path), "--force", "--reparse-txt"]) == 0
with sqlite3.connect(str(db.db_path)) as c: with sqlite3.connect(str(db.db_path)) as c:
assert c.execute("SELECT timestamp FROM events").fetchall() == [(REPORT_TIME.isoformat(),)] assert c.execute("SELECT timestamp FROM events").fetchall() == [("2026-08-25T10:33:29",)]
assert json.loads(car.read_text())["event"]["timestamp"] == REPORT_TIME.isoformat() assert json.loads(car.read_text())["event"]["timestamp"] == "2026-08-25T10:33:29"
assert json.loads(car.read_text())["bw_report"]["event_datetime"] == REPORT_TIME.isoformat()