From f91949be8985cc25d9e850e0589c148c0e369a96 Mon Sep 17 00:00:00 2001 From: serversdown Date: Mon, 26 Oct 2026 23:59:22 -0400 Subject: [PATCH 1/3] fix(decode): a Series-3 waveform's time comes from the instrument's embedded event record MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL --- docs/instantel_protocol_reference.md | 69 ++++++++++ minimateplus/event_file_io.py | 194 ++++++++++++++++++++------- minimateplus/models.py | 9 ++ sfm/waveform_store.py | 26 +--- tests/test_bw_event_record_time.py | 167 +++++++++++++++++++++++ tests/test_bw_filename_time.py | 16 ++- tests/test_event_timestamp.py | 11 +- tests/test_report_event_time.py | 23 ++-- 8 files changed, 426 insertions(+), 89 deletions(-) create mode 100644 tests/test_bw_event_record_time.py diff --git a/docs/instantel_protocol_reference.md b/docs/instantel_protocol_reference.md index b236d5c..01c18cf 100644 --- a/docs/instantel_protocol_reference.md +++ b/docs/instantel_protocol_reference.md @@ -11,6 +11,7 @@ | 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-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. | @@ -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, 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. + ## 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. diff --git a/minimateplus/event_file_io.py b/minimateplus/event_file_io.py index a6d487e..f8c8108 100644 --- a/minimateplus/event_file_io.py +++ b/minimateplus/event_file_io.py @@ -299,16 +299,29 @@ def apply_report_to_event(event: Event, report: BwAsciiReport) -> None: event.sample_rate = report.sample_rate_sps if report.record_time_s is not None: event.rectime_seconds = report.record_time_s - # The report's event_datetime is Blastware's exact trigger time (parsed - # from Event Time + Event Date). Prefer it over the binary footer's stop - # time so a report-paired import matches BW to the second. - edt = report.event_datetime - if edt is not None: - 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, - ) + # The report's event_datetime is Blastware's copy of the unit's trigger time + # (Event Time + Event Date) -- see _apply_report_time. + if report.event_datetime is not None: + _apply_report_time(event, report.event_datetime) + + +def _apply_report_time(event: Event, edt: datetime.datetime) -> None: + """A paired report's time fills in only when the instrument's own event + 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: @@ -374,8 +387,8 @@ def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None: rt = rec.get("record_time_s") if rt is not None: event.rectime_seconds = rt - # As apply_report_to_event: Blastware's exact trigger beats the binary's, - # which is a second late on 15 of prod's 81 report-paired waveforms. + # As apply_report_to_event: the report's time fills in only without a + # validated event record (_apply_report_time). edt = bw_report.get("event_datetime") if edt: try: @@ -383,11 +396,7 @@ def apply_bw_report_dict_to_event(event: Event, bw_report: dict) -> None: except (TypeError, ValueError): t = None if t is not None: - event.timestamp = Timestamp( - 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, - ) + _apply_report_time(event, t) 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 compliance config, which is what BW shows in its event report). - ``event.timestamp`` is overlaid from the report's Event Date + - Event Time (BW's report timestamps are second-resolution and - match the binary's footer; we prefer the report value because - the BW-binary footer timestamp can drift on some firmware). + Event Time -- unless it came from the instrument's own embedded event + record, which the report only cross-checks (see _apply_report_time). """ if source_kind not in {"sfm-live", "sfm-ach", "bw-import", "idf-import"}: 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 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ 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() # Build peak_values, optionally overlaid from the report. The report @@ -485,6 +493,7 @@ def event_to_sidecar_dict( event_block = { "serial": serial, "timestamp": timestamp_iso, + "timestamp_source": event.timestamp_source, "waveform_key": event._waveform_key.hex() if event._waveform_key else None, "record_type": event.record_type, "sample_rate": event.sample_rate, @@ -492,6 +501,8 @@ def event_to_sidecar_dict( "total_samples": event.total_samples, "pretrig_samples": event.pretrig_samples, } + if event.decode_problems: + event_block["decode_problems"] = list(event.decode_problems) if bw_report: # Report values are authoritative โ€” they're the user-configured # 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 # 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 -# setups โ€” and ts2 - record_time reproduces Blastware's trigger to the second -# (N844LQHB: stop 10:33:32 - 3.0 = 10:33:29). +# setups. โš  ts2 - record_time is only an estimate of the trigger: a second off +# on ~19% of files (measured 2026-10-26); the event record below is exact. _RECSETUP_MARKER = b"Standard Recording Setup" _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]: """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: - """ - Parse a Blastware waveform file into an Event. + """Parse a Blastware event file into an Event: `decode_blastware_bytes` on its + 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 - comes from it when it is one (see the timestamp block below). + +def decode_blastware_bytes(raw: bytes, *, name: Optional[str] = None) -> Event: + """ + 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: - waveform_key, rectime_seconds, total_samples, pretrig_samples (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) - raw_samples (Tran/Vert/Long/MicL int16 lists) - 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 not possible โ€” the on-disk BW file IS the byte-for-byte source. """ - path = Path(path) - name = name or path.name - raw = path.read_bytes() + label = name or "" 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 = raw[:_bw._WAVEFORM_HEADER_SIZE] 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_raw = raw[_bw._WAVEFORM_HEADER_SIZE : _bw._WAVEFORM_HEADER_SIZE + 21] strt_fields = _decode_strt(strt_raw) 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. 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: footer_pos = len(raw) - 26 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] 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: log.warning( "%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": []} else: @@ -1022,20 +1105,36 @@ def read_blastware_file(path: Union[str, Path], *, name: Optional[str] = None) - # time โ€” keep it. # Discriminate by ``is_waveform_body`` (the codec), not the filename. # - # โš  2026-10-26 (measured): ts2 - record time is a second off on 260 of - # prod's 1,394 waveforms (199 late, 61 early). A Blastware filename - # carries Blastware's own time -- equal to the report's Event Time on - # 1,330/1,330 -- so a waveform takes it when `name` is one, and ts2 - - # record time only otherwise. Histograms stay on ts1 although it runs a - # second early on 97%: in Blastware's timing a waveform and its histogram - # share a second 209 times in prod's store, and events is unique on - # (serial, timestamp). + # โš  2026-10-26 (measured): ts2 - record time is a second off on ~19% of + # waveforms. The exact trigger is in the instrument's own event record, + # embedded in the 5A stream (_embedded_event_record), so a waveform takes + # it from there. Without a validated one the estimate stands, reported as a + # decode problem -- never a filename's time, which is only a cross-check. + # Histograms stay on ts1 although it runs a second early on 97% (their + # record, marker fe f5, holds the exact start): in Blastware's timing a + # 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: _stop = datetime.datetime(ts2.year, ts2.month, ts2.day, ts2.hour, ts2.minute, ts2.second) _rt = _parse_record_time_seconds(raw) - _trig = _stop - datetime.timedelta(seconds=_rt) if _rt is not None else _stop - _trig = _bw.blastware_filename_time(name) or _trig + _start = (datetime.datetime(ts1.year, ts1.month, ts1.day, ts1.hour, ts1.minute, ts1.second) + 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( raw=footer[10:18], 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, hour=ts1.hour, minute=ts1.minute, second=ts1.second, ) + ev.timestamp_source = "footer" ev.project_info = ProjectInfo( project=project, client=client, operator=user, sensor_location=seisloc, diff --git a/minimateplus/models.py b/minimateplus/models.py index 9e7865d..2c5aec4 100644 --- a/minimateplus/models.py +++ b/minimateplus/models.py @@ -553,6 +553,15 @@ class Event: # shape diagnostic (rendered fit-to-box). None when absent. 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 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ # 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. diff --git a/sfm/waveform_store.py b/sfm/waveform_store.py index 7b26682..aa053fc 100644 --- a/sfm/waveform_store.py +++ b/sfm/waveform_store.py @@ -323,29 +323,9 @@ class WaveformStore: Returns (event, record_dict) so callers can both insert into SeismoDb and surface the parsed Event. """ - # Stash the bytes to a temp path so read_blastware_file (path-based) - # can parse without us duplicating its logic. - import tempfile - 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 - ) + # Decode the bytes directly; the name only labels the record type and + # cross-checks the decoded time (event_file_io.decode_blastware_bytes). + ev = event_file_io.decode_blastware_bytes(bw_bytes, name=source_path.name) # Parse the BW ASCII report if one was supplied. Failures here # are non-fatal: we still write the binary + sidecar without the diff --git a/tests/test_bw_event_record_time.py b/tests/test_bw_event_record_time.py new file mode 100644 index 0000000..f77f813 --- /dev/null +++ b/tests/test_bw_event_record_time.py @@ -0,0 +1,167 @@ +"""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] diff --git a/tests/test_bw_filename_time.py b/tests/test_bw_filename_time.py index 244b8ee..70a1ddd 100644 --- a/tests/test_bw_filename_time.py +++ b/tests/test_bw_filename_time.py @@ -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 -`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 report-paired waveforms; @@ -66,15 +69,16 @@ def test_other_names_give_nothing(): assert blastware_filename_time(name) is None, name -def test_a_waveform_takes_its_names_time_not_the_binarys(): - # BE9441, 2026-10-26: the binary says 14:23:43, Blastware (and the name) 14:23:42 +def test_a_waveform_decodes_to_the_time_its_name_encodes(): + # 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) -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.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) == \ datetime.datetime(2026, 10, 26, 14, 23, 42) diff --git a/tests/test_event_timestamp.py b/tests/test_event_timestamp.py index f4e692a..0f08be6 100644 --- a/tests/test_event_timestamp.py +++ b/tests/test_event_timestamp.py @@ -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) -def test_report_event_datetime_is_authoritative_over_binary(): - # The binary already yields the exact trigger, but a paired report stays - # authoritative (e.g. if the unit clock had drifted) โ€” applying it wins. +def test_a_report_does_not_override_the_instruments_event_record(): + # Superseded 2026-10-26: the exact trigger is the instrument's embedded event + # 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) - 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( 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 diff --git a/tests/test_report_event_time.py b/tests/test_report_event_time.py index 8de8004..d273eed 100644 --- a/tests/test_report_event_time.py +++ b/tests/test_report_event_time.py @@ -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(): - 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) - assert _tuple(ev.timestamp) == datetime.datetime(2026, 8, 25, 10, 33, 29) # the binary's - apply_bw_report_dict_to_event(ev, json.loads(json.dumps(block))) # as a sidecar holds it - assert _tuple(ev.timestamp) == REPORT_TIME + apply_bw_report_dict_to_event(ev, block) + assert (_tuple(ev.timestamp), ev.timestamp_source) == \ + (datetime.datetime(2026, 8, 25, 10, 33, 29), "event_record") 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 -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 - 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 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 with sqlite3.connect(str(db.db_path)) as c: - assert c.execute("SELECT timestamp FROM events").fetchall() == [(REPORT_TIME.isoformat(),)] - assert json.loads(car.read_text())["event"]["timestamp"] == REPORT_TIME.isoformat() + assert c.execute("SELECT timestamp FROM events").fetchall() == [("2026-08-25T10:33:29",)] + 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() From 6cfcd045134b0c2a03428a9a0b99fdb7b9c7563f Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 27 Oct 2026 00:15:32 -0400 Subject: [PATCH 2/3] 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 Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL --- sfm/database.py | 40 ++++++++++++++++++++++++- tests/test_bw_event_record_time.py | 27 +++++++++++++++++ tests/test_event_restamp.py | 48 ++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 1 deletion(-) diff --git a/sfm/database.py b/sfm/database.py index 12c5aa3..76ee65c 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -432,7 +432,17 @@ class SeismoDb: pi = ev.project_info 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: skipped += 1 continue @@ -594,6 +604,34 @@ class SeismoDb: serial, 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 def _restamp_by_file(conn: sqlite3.Connection, serial: str, filename: str, ts: str) -> Optional[bool]: diff --git a/tests/test_bw_event_record_time.py b/tests/test_bw_event_record_time.py index f77f813..8521dd7 100644 --- a/tests/test_bw_event_record_time.py +++ b/tests/test_bw_event_record_time.py @@ -165,3 +165,30 @@ def test_a_sidecar_carries_the_decode_problem(): 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) diff --git a/tests/test_event_restamp.py b/tests/test_event_restamp.py index 98b7013..a10320c 100644 --- a/tests/test_event_restamp.py +++ b/tests/test_event_restamp.py @@ -15,6 +15,7 @@ second). insert_events now moves that row to the corrected time in place. from __future__ import annotations import datetime +import logging import os import sqlite3 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)} 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 From 7100d8344a1ade506e3e93fcdee24fe4d9ab7a7d Mon Sep 17 00:00:00 2001 From: serversdown Date: Tue, 27 Oct 2026 00:17:15 -0400 Subject: [PATCH 3/3] =?UTF-8?q?docs(reference):=20point=20=C2=A77.8.9's=20?= =?UTF-8?q?open=20items=20at=20the=20Series-III=20audit,=20#53?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MUHR251NLznsFvPSrfegqL --- docs/instantel_protocol_reference.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/instantel_protocol_reference.md b/docs/instantel_protocol_reference.md index 01c18cf..760959b 100644 --- a/docs/instantel_protocol_reference.md +++ b/docs/instantel_protocol_reference.md @@ -2296,7 +2296,7 @@ on 217. On prod's 1,394 it is a second off on 260: 199 late, 61 early. 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, inferred only.** The `0C` timestamp layouts documented in ยง7.5 +๐Ÿ”ถ **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 @@ -2307,7 +2307,7 @@ The early captures were all in April (month `04`, sent as `10 04`). Not changed โš  **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. +behaves the same. Prod's store has none. Tracked in #53. ## 7.9 Compliance Config Field Inventory (Blastware UI, 2026-04-08) โœ