diff --git a/sfm/device_access/s3.py b/sfm/device_access/s3.py index a7efaa6..cc8b6d5 100644 --- a/sfm/device_access/s3.py +++ b/sfm/device_access/s3.py @@ -9,6 +9,7 @@ from typing import Any, Callable, Optional from minimateplus import MiniMateClient from minimateplus.blastware_file import blastware_filename +from minimateplus.event_file_io import _GEO_INT16_FS from minimateplus.framing import build_bw_write_frame from minimateplus.protocol import SUB_START_MONITORING, SUB_STOP_MONITORING from minimateplus.transport import TcpTransport @@ -97,6 +98,45 @@ def _s3_ref(ev: Any, serial: str) -> EventRef: ) +_GEO_FULL_SCALE_IPS = 10.0 # normal range; one decoder step = 0.005 in/s +_PEAK_TOLERANCE_IPS = 0.0051 # one 0.005 in/s step, plus the 0C's float32 slop + + +def verify_s3_download(ev: Any, compliance: Any) -> tuple: + """Check a downloaded waveform against the unit's own 0C peaks: (verified, why). + + True: all three geophone channels decode to the same length and each + channel's peak is the unit's own to one 0.005 in/s step. None: nothing to + check against -- no waveform decode (a histogram: none of ~430 fixture + histograms decodes as a waveform) or a sensitive-range unit, whose scale is + still open (the 8x discrepancy). Raises MalformedReply ("not saved") + otherwise: a short or misassembled event must not reach the store. BE9441's + bench (2026-10-25) stored two such events as successes before this existed. + """ + samples = getattr(ev, "raw_samples", None) or {} + chans = ("Tran", "Vert", "Long") + if not all(samples.get(c) for c in chans): + return None, "no waveform decode to check (a histogram, or no codec for it)" + if getattr(compliance, "geo_range", 0) not in (0, None): + return None, "sensitive range: the sample scale is not settled, so not checked" + lengths = {c: len(samples[c]) for c in chans} + if len(set(lengths.values())) != 1: + raise MalformedReply( + f"the downloaded waveform's channels have different lengths {lengths} -- the " + "download is incomplete or misassembled; not saved") + pv = ev.peak_values + unit = {"Tran": pv.tran, "Vert": pv.vert, "Long": pv.long} if pv else {} + for c in chans: + if unit.get(c) is None: + return None, f"the unit's record gives no {c} peak to check against" + decoded = max(abs(x) for x in samples[c]) * _GEO_FULL_SCALE_IPS / _GEO_INT16_FS + if abs(decoded - unit[c]) > _PEAK_TOLERANCE_IPS: + raise MalformedReply( + f"the downloaded {c} peak is {decoded:.4f} in/s but the unit's own record says " + f"{unit[c]:.4f} -- the download is incomplete or misassembled; not saved") + return True, f"{lengths['Tran']} samples per channel, peaks match the unit's own" + + class Series3Adapter: def __init__(self, client_factory: Callable[..., Any] = default_s3_client_factory) -> None: self._factory = client_factory @@ -272,10 +312,11 @@ class Series3Adapter: filename = _s3_filename(ev, serial) if filename is None: raise MalformedReply(f"event {key.hex()} has no usable timestamp, so it cannot be named or stored") + verified, why = verify_s3_download(ev, info.compliance_config) return DownloadedEvent( event_id=make_event_id(serial, key, found), serial=serial, series=3, - filename=filename, verified=None, event=ev, a5_frames=ev._a5_frames, + filename=filename, verified=verified, event=ev, a5_frames=ev._a5_frames, compliance=info.compliance_config, timestamp=_s3_dt(ev), - detail={"a5_frames": len(ev._a5_frames)}, + detail={"a5_frames": len(ev._a5_frames), "check": why}, ) return self._run(address, op, timeout=S3_EVENT_TIMEOUT) diff --git a/tests/minimate_replay.py b/tests/minimate_replay.py new file mode 100644 index 0000000..8e75391 --- /dev/null +++ b/tests/minimate_replay.py @@ -0,0 +1,82 @@ +"""BE9441's recorded bench session (2026-10-25), replayed reply for reply. + +Shared by the MiniMate download tests. See +tests/fixtures/minimate-bench-10-25-26/README.md for the provenance. +""" +from __future__ import annotations + +from pathlib import Path + +import minimateplus.protocol as mp +from minimateplus.framing import S3FrameParser + +FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-25-26" / "BE9441_event1_0111646a_rx.bin" +KEY = bytes.fromhex("0111646a") +STAMP = "2026-10-25T14:10:49" +UNIT_PEAKS = {"Tran": 0.030, "Vert": 0.095, "Long": 0.020} # the unit's own 0C peaks, in/s +SESSION_RESET = b"\x41\x03" + + +def recorded_replies(): + """[(sub, raw_bytes)] for every frame of the session, in order.""" + raw, out, start, p = FIX.read_bytes(), [], 0, S3FrameParser() + for i in range(len(raw)): + for f in p.feed(raw[i:i + 1]): + out.append((f.sub, raw[start:i + 1])) + start = i + 1 + return out + + +class SessionReplay: + """Answers each request with the next recorded reply of its own SUB (reply = + 0xFF - request). `quiet_5a_from`: from that 5A request on, the 5A stream gets + one stray 0x41 and then nothing, while every other request is still answered + -- BE9441 dropped out of the stream as it rebooted, then answered the walk.""" + + def __init__(self, replies, quiet_5a_from=None): + self.queues = {} + for sub, raw in replies: + self.queues.setdefault(sub, []).append(raw) + self.quiet_5a_from, self.n5a, self._buf, self.open_ = quiet_5a_from, 0, b"", False + + def connect(self): + self.open_ = True + + def disconnect(self): + self.open_ = False + + def is_connected(self): + return self.open_ + + def write(self, data): + data = bytes(data) + if data == SESSION_RESET: + return + req = data[5] # 41 02 10 10 00 + if req == 0x5A: + n, self.n5a = self.n5a, self.n5a + 1 + if self.quiet_5a_from is not None and n >= self.quiet_5a_from: + if n == self.quiet_5a_from: + self._buf += b"\x41" + return + self._buf += self.queues[0xFF - req].pop(0) + + def read(self, n): + out, self._buf = self._buf[:n], self._buf[n:] + return out + + def read_until_idle(self, *a, **kw): + out, self._buf = self._buf, b"" + return out + + + +def fast_clock(monkeypatch): + """Make the protocol's 10 s receive deadlines pass in a few loop turns.""" + t = [0.0] + + def tick(): + t[0] += 0.5 + return t[0] + monkeypatch.setattr(mp.time, "monotonic", tick) + monkeypatch.setattr(mp.time, "sleep", lambda s: None) diff --git a/tests/test_device_access_s3_verify.py b/tests/test_device_access_s3_verify.py new file mode 100644 index 0000000..a4f5ee4 --- /dev/null +++ b/tests/test_device_access_s3_verify.py @@ -0,0 +1,95 @@ +"""A MiniMate download is checked against the unit's own peaks before it is stored. + +Series 4 downloads were already checked (decoded PVS against the unit's). +Series 3's were not, so two bad files went into the store as successes at the +bench (2026-10-25). Now: if the waveform decodes, all three geophone channels +must be the same length and each channel's peak must match the unit's own 0C +peak to one 0.005 in/s step, or the download is refused and nothing is stored. +No waveform decode (a histogram -- 0 of ~430 fixture histograms decode as one) +or a sensitive-range unit (its scale is still open) is stored unverified. +""" +from __future__ import annotations + +import os +import sys + +import pytest + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +import minimateplus.blastware_file as bw # noqa: E402 +import minimateplus.client as mc # noqa: E402 +from minimate_replay import KEY, SessionReplay, fast_clock, recorded_replies # noqa: E402 +from minimateplus.models import ComplianceConfig, Event, PeakValues # noqa: E402 +from sfm.device_access.errors import MalformedReply # noqa: E402 +from sfm.device_access.models import UnitAddress # noqa: E402 +from sfm.device_access.s3 import Series3Adapter, verify_s3_download # noqa: E402 + +CABLE = UnitAddress(host=None, tcp_port=None, port="/dev/ttyUSB0", baud=38400) +COUNTS_PER_IPS = 3200 # 32000 counts = 10.000 in/s (normal range) + + +@pytest.fixture(autouse=True) +def _fast(monkeypatch): + fast_clock(monkeypatch) + + +def event(samples, peaks): + ev = Event(index=0) + ev.raw_samples = samples + ev.peak_values = PeakValues(tran=peaks[0], vert=peaks[1], long=peaks[2]) + return ev + + +def flat(n, peak_ips): + return [0] * (n - 1) + [round(peak_ips * COUNTS_PER_IPS)] + + +NORMAL = ComplianceConfig(geo_range=0) + + +def test_matching_peaks_and_lengths_verify(): + ev = event({c: flat(100, p) for c, p in zip(("Tran", "Vert", "Long"), (0.03, 0.095, 0.02))}, + (0.02999996, 0.09499989, 0.01999998)) + assert verify_s3_download(ev, NORMAL)[0] is True + + +def test_a_peak_that_disagrees_is_refused(): + ev = event({c: flat(100, p) for c, p in zip(("Tran", "Vert", "Long"), (0.01, 0.01, 0.005))}, + (0.03, 0.095, 0.02)) + with pytest.raises(MalformedReply, match="Tran peak is 0.0100.*not saved"): + verify_s3_download(ev, NORMAL) + + +def test_unequal_channel_lengths_are_refused(): + ev = event({"Tran": flat(100, 0.03), "Vert": flat(100, 0.095), "Long": flat(90, 0.02)}, + (0.03, 0.095, 0.02)) + with pytest.raises(MalformedReply, match="lengths.*not saved"): + verify_s3_download(ev, NORMAL) + + +def test_no_waveform_decode_is_stored_unverified(): + assert verify_s3_download(event(None, (0.03, 0.095, 0.02)), NORMAL)[0] is None + + +def test_a_sensitive_range_unit_is_stored_unverified(): + ev = event({c: flat(100, 0.5) for c in ("Tran", "Vert", "Long")}, (0.03, 0.095, 0.02)) + assert verify_s3_download(ev, ComplianceConfig(geo_range=1))[0] is None + + +def adapter(): + def factory(address, **kw): + return mc.MiniMateClient(transport=SessionReplay(recorded_replies())) + return Series3Adapter(client_factory=factory) + + +def test_be9441_event_1_downloads_verified(): + dl = adapter().download_event(CABLE, "BE9441", KEY, "20261025141049") + assert dl.verified is True + + +def test_the_check_refuses_the_file_the_metadata_page_bug_produced(monkeypatch): + monkeypatch.setattr(bw, "_has_metadata_pages", lambda frames: True) # the bug, back + with pytest.raises(MalformedReply, match="not saved"): + adapter().download_event(CABLE, "BE9441", KEY, "20261025141049") diff --git a/tests/test_minimate_download_replay.py b/tests/test_minimate_download_replay.py index 702d619..ef2d7af 100644 --- a/tests/test_minimate_download_replay.py +++ b/tests/test_minimate_download_replay.py @@ -10,84 +10,20 @@ from __future__ import annotations import os import sys -from pathlib import Path import pytest sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -import minimateplus.client as mc # noqa: E402 -import minimateplus.protocol as mp # noqa: E402 -from minimateplus.framing import S3FrameParser # noqa: E402 - -FIX = Path(__file__).parent / "fixtures" / "minimate-bench-10-25-26" / "BE9441_event1_0111646a_rx.bin" -KEY = bytes.fromhex("0111646a") -STAMP = "2026-10-25T14:10:49" -SESSION_RESET = b"\x41\x03" - - -def recorded_replies(): - """[(sub, raw_bytes)] for every frame of the session, in order.""" - raw, out, start, p = FIX.read_bytes(), [], 0, S3FrameParser() - for i in range(len(raw)): - for f in p.feed(raw[i:i + 1]): - out.append((f.sub, raw[start:i + 1])) - start = i + 1 - return out - - -class SessionReplay: - """Answers each request with the next recorded reply of its own SUB (reply = - 0xFF - request). `quiet_5a_from`: from that 5A request on, the 5A stream gets - one stray 0x41 and then nothing, while every other request is still answered - -- BE9441 dropped out of the stream as it rebooted, then answered the walk.""" - - def __init__(self, replies, quiet_5a_from=None): - self.queues = {} - for sub, raw in replies: - self.queues.setdefault(sub, []).append(raw) - self.quiet_5a_from, self.n5a, self._buf, self.open_ = quiet_5a_from, 0, b"", False - - def connect(self): - self.open_ = True - - def disconnect(self): - self.open_ = False - - def is_connected(self): - return self.open_ - - def write(self, data): - data = bytes(data) - if data == SESSION_RESET: - return - req = data[5] # 41 02 10 10 00 - if req == 0x5A: - n, self.n5a = self.n5a, self.n5a + 1 - if self.quiet_5a_from is not None and n >= self.quiet_5a_from: - if n == self.quiet_5a_from: - self._buf += b"\x41" - return - self._buf += self.queues[0xFF - req].pop(0) - - def read(self, n): - out, self._buf = self._buf[:n], self._buf[n:] - return out - - def read_until_idle(self, *a, **kw): - out, self._buf = self._buf, b"" - return out +import minimateplus.client as mc # noqa: E402 +import minimateplus.protocol as mp # noqa: E402 +from minimate_replay import KEY, STAMP, SessionReplay, fast_clock, recorded_replies # noqa: E402 @pytest.fixture(autouse=True) -def fast_clock(monkeypatch): - t = [0.0] - - def tick(): - t[0] += 0.5 - return t[0] - monkeypatch.setattr(mp.time, "monotonic", tick) - monkeypatch.setattr(mp.time, "sleep", lambda s: None) +def _fast(monkeypatch): + fast_clock(monkeypatch) def download(quiet_5a_from=None):