3 Commits
Author SHA1 Message Date
serversdownandClaude Opus 5.5 a72d3a98a9 fix(minimateplus): refuse a settings write whose four fields would not read back as asked (#1 review)
_encode_compliance_config patches the raw SUB 1A bytes at offsets measured at
1024 sps (April 2026), where the escape before 04 sits between the mode and the
anchor.  b320a53 moved the decoder to the measured layout (unescaped: mode -7,
rate -6, interval -4, record time +6), which exposed the encoder: on BE9441's
recorded 10-25 Continuous / 4096 block a mode change rewrote the byte in front
of the mode, and on the 10-26 Histogram+Continuous / 2048 block a sample-rate
change landed one byte off.  The old decoder read the same wrong bytes, so such
a write looked as if it had taken.

The encoder now decodes its own result with the decoder and raises ValueError
when mode, sample rate, interval or record time would not read back as asked
(or a field not asked for would change) -- before push_config_raw sends a byte.
No write offset is moved: rewriting the encoder on unescaped bytes is #46's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:56:44 -04:00
serversdownandClaude Opus 5.5 3a1d34ae92 fix(sfm): a download the store already holds is found by its Blastware name, not only its time (#8 review)
persist_download checked 'already stored' on the unit's 0C time only, but a
histogram's row is stored at its file's time, a second earlier on most
histograms (#51): K441LTOK.QZ0 decodes to 16:06:34, its 0C says 16:06:35.  So a
live download of an event the watcher had imported missed the check and
re-stored it -- UPSERTing over the watcher's row (Blastware's ZC frequencies and
vector sum lost) and rewriting its sidecar as sfm-live -- and every repeat live
download rewrote the files again.

New SeismoDb.find_event_by_blastware_name(): the row stored under the same
Blastware name (the event's second, per blastware_filename_time; the rule
_restamp_by_file uses), matching a direct name to the call-in copy's W/H name.
Any other name matches nothing.  Also two comments from 9492e49 that said the
opposite of the code (the unit's peaks are overlaid; source.kind is a parameter).

Store consequence: none for existing rows; no schema change, no migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:56:44 -04:00
serversdownandClaude Opus 5.5 dbd8a91661 fix(sfm): wake a MiniMate before the read-back reconnect reads its serial (#9 review)
The reconnect in ce441a0 opened a fresh connection and sent a bare 0x15 (the
identity check) before any SESSION_RESET + POLL.  It exists for a unit that has
just started -- sensor check, then monitoring -- and a monitoring MiniMate
ignores a bare request until woken (measured 2026-04-08), so the identity read
would have timed out and the start reported unconfirmed anyway.  Now: open,
wake (the same retried wake the read-back uses), read the serial, read 0x1C --
the order the status read and the legacy write routes use.  Still one
reconnect, TCP only, nothing re-sent.

The fake gains bare_requests_ignored (off unless a test asks): a fresh
connection's reads time out, with the real client's TimeoutError, until woken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
2026-10-29 23:56:44 -04:00
9 changed files with 178 additions and 8 deletions

No files matched your search

+37 -1
View File
@@ -2122,7 +2122,13 @@ def _encode_compliance_config(
DLE-jitter shifts):
Anchor: b'\\xbe\\x80\\x00\\x00\\x00\\x00' (confirmed stable, both BE11529 and BE18189)
recording_mode → uint8 at anchor_pos - 8 (BOTH read and write)
⚠ 2026-10-29: these RAW offsets were measured at 1024 sps, where the escape
before `04` sits between the mode and the anchor. The decoder now reads
the four fields after unescaping (mode -7, rate -6, interval -4, record
time +6), so at any other layout these patch the wrong bytes. Until the
encoder is rewritten on unescaped bytes (#46), a payload whose four fields
do not read back as asked raises ValueError -- see the end of this function.
recording_mode → uint8 at anchor_pos - 8 (raw; right at 1024 sps only)
Values: 0x00=Single Shot, 0x01=Continuous, 0x03=Histogram, 0x04=Histogram+Continuous
NOTE: The byte at anchor_pos - 7 is always 0x10 (a DLE marker regenerated by
device firmware in every E5 response). It must NOT be overwritten during
@@ -2305,10 +2311,40 @@ def _encode_compliance_config(
_set_string(b"Seis Loc:", seis_loc)
_set_string(b"Extended Notes", notes)
# ── Read-back check: the payload must decode to what was asked ────────────
# The decoder is the measured layout (every recorded reply); these offsets are
# 1024-sps raw ones. A mode change on BE9441's 10-25 Continuous / 4096 block
# rewrote the byte in front of the mode and read back unchanged. Refuse it
# here, before push_config_raw sends anything.
asked = {"recording_mode": recording_mode, "sample_rate": sample_rate,
"histogram_interval_sec": histogram_interval_sec, "record_time": record_time}
if any(v is not None for v in asked.values()):
before, after = _settings_read_back(raw), _settings_read_back(bytes(buf))
if record_time is not None:
asked["record_time"] = struct.unpack(">f", struct.pack(">f", record_time))[0]
want = {k: (v if v is not None else before[k]) for k, v in asked.items()}
wrong = {k: (after[k], want[k]) for k in asked if after[k] != want[k]}
if wrong:
raise ValueError(
"_encode_compliance_config: the patched block would not read back as asked ("
+ ", ".join(f"{k} reads {got!r}, not {exp!r}" for k, (got, exp) in wrong.items())
+ ") -- refused, nothing built or sent. The encoder's offsets were measured at "
"1024 sps and need rewriting on unescaped bytes (#46)."
)
# 2-byte footer — checksum formula unknown; \x00\x00 confirmed accepted by device
return bytes(buf) + b"\x00\x00"
def _settings_read_back(data: bytes) -> dict:
"""Mode, sample rate, interval and record time as the decoder reads `data`."""
info = DeviceInfo(serial="", firmware_minor=0)
_decode_compliance_config_into(data, info)
cc = info.compliance_config
return {k: getattr(cc, k, None) if cc is not None else None
for k in ("recording_mode", "sample_rate", "histogram_interval_sec", "record_time")}
def _decode_compliance_config_into(data: bytes, info: DeviceInfo) -> None:
"""
Decode a 2090-byte SUB 1A (COMPLIANCE_CONFIG) response into a ComplianceConfig.
+22
View File
@@ -808,6 +808,28 @@ class SeismoDb:
).fetchone()
return dict(row) if row else None
def find_event_by_blastware_name(self, serial: str, filename: str) -> Optional[dict]:
"""The row stored under `filename`'s Blastware name, or None.
A Blastware name encodes the serial and the event's second
(`blastware_filename_time`), so the same name is the same event -- the
rule `_restamp_by_file` uses. A direct download is `<stem>.<AB>0` and
Blastware's call-in copy of the same event `<stem>.<AB>0W` / `H`; all
three forms match. Any other name ("imported.bw") matches nothing.
"""
if blastware_filename_time(filename) is None:
return None
base = filename.upper()
if len(base.rsplit(".", 1)[-1]) == 4:
base = base[:-1]
with self._connect() as conn:
row = conn.execute(
"SELECT * FROM events WHERE serial = ? AND UPPER(blastware_filename) IN (?, ?, ?) "
"ORDER BY rowid LIMIT 1",
(serial, base, base + "W", base + "H"),
).fetchone()
return dict(row) if row else None
def query_events(
self,
serial: Optional[str] = None,
+5 -1
View File
@@ -249,8 +249,12 @@ class Series3Adapter:
address.key, exc)
client.close()
client.open()
# Wake first: the identity read is a bare 0x15, which a unit that
# has just started ignores until SESSION_RESET + POLL (the order
# the status read and the legacy write routes use: poll, then read).
client.wake(attempt_s=S3_WAKE_ATTEMPT_S, deadline_s=S3_WAKE_DEADLINE_S)
self._check(client.read_serial(), serial, address)
return _woken_state(client)
return s3_run_state(client.get_monitor_status())
return run_change(
serial=serial, series=3, start=start, dry_run=dry_run,
+7 -2
View File
@@ -123,6 +123,11 @@ def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownlo
rows = db.query_events(serial=dl.serial, from_dt=dl.timestamp, to_dt=dl.timestamp, limit=1)
if rows:
return _already_stored(dl, rows[0])
# A histogram's row is stored at its file's time, a second before the unit's
# on most (#51), so the time above misses it; its Blastware name does not.
row = db.find_event_by_blastware_name(dl.serial, dl.filename)
if row is not None:
return _already_stored(dl, row)
if dl.series == 4:
ev, rec = store.save_imported_idf(dl.idf_bytes, source_path=Path(dl.filename),
serial_hint=dl.serial)
@@ -132,8 +137,8 @@ def persist_download(dl: DownloadedEvent, *, store: Any, db: Any) -> EventDownlo
else:
# The same path production's watcher uses for Blastware's own files: the
# event is decoded from the file (samples, histogram, setup-block sample
# rate and record time), not from the live 5A decode. The unit's 0C peaks
# stay what they were -- the download *check* (verify_s3_download).
# rate and record time), not from the live 5A decode. The unit's own 0C
# peaks, mic and vector sum then go over the file's (_overlay_s3_record).
if not dl.bw_bytes:
raise IngestError(f"{dl.filename}: the download carried no event file; nothing was stored")
geo_range = getattr(dl.compliance, "geo_range", None) if dl.compliance else None
+2 -1
View File
@@ -317,7 +317,8 @@ class WaveformStore:
3. Resolve serial from BW filename (`<P><serial3>...`) or use
serial_hint. Falls back to "UNKNOWN".
4. Copy the BW bytes verbatim into <root>/<serial>/<filename>.
5. Write the .sfm.json sidecar with source.kind = "bw-import"
5. Write the .sfm.json sidecar with source.kind = `source_kind`
("bw-import"; "sfm-live" for SFM's own downloads)
and a5_pickle_filename = None. Does NOT write a .a5.pkl
(no A5 source available; byte-for-byte regeneration not
possible — the on-disk BW file IS the byte-for-byte source).
+23 -3
View File
@@ -18,6 +18,9 @@ SETUP_FIXTURE = Path(__file__).parent / "fixtures" / "micromate-setup" / "um2014
THOR_IDF = Path(__file__).parent / "fixtures" / "thor-idf"
from minimateplus.protocol import TimeoutError as mmp_TimeoutError # noqa: E402
class _Base:
def __init__(self, fail=None, open_error=None):
self.fail = list(fail or [])
@@ -75,9 +78,14 @@ def default_s3_events():
class FakeMiniMateClient(_Base):
def __init__(self, serial="BE18193", *, monitoring=False, compliance="default", events=None,
monitor_states=None, write_error=None, serial_reported=None, wake_errors=None, **kw):
monitor_states=None, write_error=None, serial_reported=None, wake_errors=None,
bare_requests_ignored=False, **kw):
super().__init__(**kw)
self.serial = serial
# As a monitoring MiniMate (measured 2026-04-08): on a fresh connection a
# read before SESSION_RESET + POLL goes unanswered. Off unless a test asks.
self.bare_requests_ignored = bare_requests_ignored
self._woken = False
# read_serial()'s answer (connect() keeps answering `serial`), and errors
# raised by wake() once a write has gone out -- the read-back's wakes.
self.serial_reported = serial if serial_reported is None else serial_reported
@@ -98,8 +106,18 @@ class FakeMiniMateClient(_Base):
self.download_requests: list = [] # (key4, expected_timestamp) per download
self.last_download = None
def open(self):
super().open()
self._woken = False
def _bare_read(self, name):
self._step(name)
if self.bare_requests_ignored and not self._woken:
raise mmp_TimeoutError(f"{name}: no reply (the unit was not woken)")
def connect(self) -> DeviceInfo:
self._step("connect")
self._woken = True # connect() starts with the startup handshake
return DeviceInfo(
serial=self.serial, firmware_minor=17, firmware_version="S338.17",
dsp_version="10.72", manufacturer="Instantel", model="MiniMate Plus",
@@ -108,18 +126,20 @@ class FakeMiniMateClient(_Base):
def poll(self) -> None:
self._step("poll")
self._woken = True
def wake(self, **kw) -> None:
self._step("wake")
if self.writes and self.wake_errors:
raise self.wake_errors.pop(0)
self._woken = True
def read_serial(self) -> str:
self._step("read_serial")
self._bare_read("read_serial")
return self.serial_reported
def get_monitor_status(self) -> MonitorStatus:
self._step("get_monitor_status")
self._bare_read("get_monitor_status")
state = self.monitor_states.pop(0) if len(self.monitor_states) > 1 else self.monitor_states[0]
# A bool is a measured state; an int (or None: a short section) is the raw 0x1C flag byte.
flag = (0x10 if state else 0x00) if isinstance(state, bool) else state
+13
View File
@@ -816,6 +816,19 @@ def test_series3_start_read_back_reconnects_after_a_dropped_line():
assert fake.opened == 2 and "read_serial" in fake.calls
def test_series3_read_back_reconnect_wakes_the_unit_before_reading_it():
# The unit the reconnect is for has just started (sensor check, then
# monitoring), and a monitoring MiniMate ignores a bare request until it is
# woken -- so the fresh connection's identity read must come after the wake.
fake = FakeMiniMateClient(monitor_states=[False, True], bare_requests_ignored=True,
wake_errors=[BrokenPipeError(32, "Broken pipe")])
r = access3(fake).start_monitoring(TCP3, "BE18193")
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "monitoring")
assert fake.writes == ["start_monitoring"] and fake.opened == 2
after = fake.calls[fake.calls.index("start_monitoring"):]
assert after.index("read_serial") > len(after) - 1 - after[::-1].index("wake")
def test_series3_read_back_reconnects_only_once():
fake = FakeMiniMateClient(monitor_states=[False],
wake_errors=[BrokenPipeError(32, "x"), BrokenPipeError(32, "x")])
+40
View File
@@ -335,3 +335,43 @@ def test_the_units_range_reaches_the_store(tmp_path):
timestamp=datetime.datetime(2026, 10, 1, 8, 0, 0))
persist_download(dl, store=store, db=SeismoDb(tmp_path / "seismo.db"))
assert store.geo_range == 1
# Review finding (2026-10-29): a histogram's row is stored at its file's time,
# a second before the unit's 0C time on most histograms (#51) -- K441LTOK.QZ0
# decodes to 16:06:34, its 0C says 16:06:35 -- so a pre-check on the 0C time
# alone missed it, and a live download overwrote the watcher's row and sidecar.
# The Blastware name encodes the event's own second and does not miss.
@pytest.mark.parametrize("stored_as", ["K441LTOK.QZ0", "K441LTOK.QZ0H"]) # direct / call-in name
def test_a_live_histogram_the_watcher_already_stored_writes_nothing(sdm, stored_as):
import json
store, db = sdm
ev, rec = store.save_imported_bw((HIST_FIX / "K441LTOK.QZ0").read_bytes(),
source_path=Path(stored_as), serial_hint=None,
bw_report_text=(HIST_FIX / "K441LTOK_QZ0_ASCII.TXT").read_bytes())
db.insert_events([ev], serial="BE9441", waveform_records={ev._waveform_key.hex(): rec},
device_family="series3") # as the import route (server.py) does
[row0] = db.query_events(serial="BE9441")
assert row0["timestamp"] != "2026-10-26T16:06:35" # the case: the row sits a second off
assert row0["blastware_filename"] == stored_as
out = persist_download(_hist_download("K441LTOK.QZ0", "01110000",
datetime.datetime(2026, 10, 26, 16, 6, 35)), store=store, db=db)
assert out.inserted is False and out.detail["already_stored"] is True
assert db.query_events(serial="BE9441") == [row0]
sidecar = json.loads(store.sidecar_path_for("BE9441", stored_as).read_text())
assert sidecar["source"]["kind"] == "bw-import"
def test_a_repeat_live_histogram_a_second_off_its_file_adds_nothing(sdm):
store, db = sdm
when = datetime.datetime(2026, 10, 26, 16, 6, 35)
first = persist_download(_hist_download("K441LTOK.QZ0", "01110000", when), store=store, db=db)
again = persist_download(_hist_download("K441LTOK.QZ0", "01110000", when), store=store, db=db)
assert first.inserted is True and again.inserted is False and again.detail["already_stored"] is True
assert len(db.query_events(serial="BE9441")) == 1
def test_a_name_that_is_not_blastwares_matches_nothing(sdm):
store, db = sdm
assert db.find_event_by_blastware_name("BE9441", "imported.bw") is None
+29
View File
@@ -94,3 +94,32 @@ def test_a_reply_without_the_settings_block_reads_as_unknown():
cc = _decode(fe)
assert (cc.recording_mode, cc.sample_rate, cc.histogram_interval_sec, cc.record_time) == \
(None, None, None, None)
# The write side (review finding, 2026-10-29). _encode_compliance_config patches
# the RAW bytes at offsets measured at 1024 sps (April 2026), where an escape sits
# between the mode and the anchor. At other rates the mode is one byte later, so
# a mode change rewrote the byte in front of it. A payload that would not read
# back as asked is refused before anything is sent.
from minimateplus.client import _encode_compliance_config # noqa: E402
def _block(i):
return _settings_replies()[i].ljust(2126, b"\x00") # a whole block's length
@pytest.mark.parametrize("i, change", [
(0, {"recording_mode": 0}), # 10-25 Continuous / 4096: mode sits at -7, not -8
(1, {"sample_rate": 4096}), # 10-26 Histogram+Continuous / 2048: escaped mode shifts the rate
])
def test_a_change_that_would_not_read_back_is_refused(i, change):
with pytest.raises(ValueError, match="read back"):
_encode_compliance_config(_block(i), **change)
def test_a_change_that_reads_back_as_asked_is_built():
out = _encode_compliance_config(_block(0), record_time=7.0)
cc = _decode(out)
assert (cc.recording_mode, cc.sample_rate, cc.histogram_interval_sec, cc.record_time) == \
(1, 4096, 5, 7.0)