Files
seismo-relay/docs/superpowers/plans/2026-10-29-sfm-1c-bench-fixes-batch1.md
T

15 KiB
Raw Blame History

SFM 1c bench fixes, Batch 1 — Implementation Plan

For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (- [ ]) syntax for tracking.

Goal: Fix the three reliability findings from the 2026-10-29 bench that put wrong or missing data in front of a user: MiniMate settings read from escaped bytes (#1), a MiniMate start reported failed because the read-back did not survive a dropped modem line (#9), and MiniMate downloads stored without the file reader (#8).

Architecture: Three independent fixes on feat/series4-sfm-parity (merged up with dev at 342c696), each behind its own tests on recorded BE9441 bytes. #1 changes only the four anchor-relative fields of the live SUB 1A decode; #9 adds one guarded reconnect to the Series-3 start read-back; #8 stores Series-3 downloads through the same Blastware-file import path production uses (WaveformStore.save_imported_bw), the way Series 4 already uses save_imported_idf.

Tech Stack: Python 3.10, pytest; minimateplus (client, framing, blastware_file), sfm (device_access, event_ingest, waveform_store).

Spec: docs/superpowers/specs/2026-10-20-sfm-series4-parity-design.md → Left open by the 1c bench (2026-10-29), items 1, 8, 9 (and 15, retracted below).

Global Constraints

  • Branch feat/series4-sfm-parity only; push each commit; never main; no CHANGELOG.md edits (feature branch).
  • Reliability before speed (Brian, 2026-10-29): no change removes a check; a start/stop is still sent exactly once, never retried.
  • File boundary with the S3 decode-checker session: do not edit minimateplus/event_file_io.py, histogram_codec.py, waveform_codec.py, bw_xml_report.py, decode_check*.py.
  • docs/instantel_protocol_reference.md is CRLF: edit it with the Edit tool only.
  • Tests: /home/serversdown/seismo-relay/.venv/bin/python -m pytest -q -p no:cacheprovider; the baseline is exactly 16 known failures (15 test_bw_ascii_report.py, test_event_file_io.py::test_save_imported_bw_without_report_works_unchanged).
  • Store consequence (state it in the commit and docs): #8 changes how new live downloads are stored; existing rows and files are untouched; no backfill, no migration.

Review Focus

  1. A modem that closes the line cleanly (FIN) during the read-back shows as silence, not an OSError: no reconnect, the result stays "sent, not checked", nothing re-sent. (Task 2 test.)
  2. A MiniMate on a serial cable: never reconnect in the read-back — opening its port reboots the unit (measured 2026-10-25). (Task 2 test.)
  3. A settings read while the unit is monitoring returns the device-info block, not the settings block (measured 2026-10-29): mode, sample rate, interval and record time must come back None, not garbage. (Task 1 test.)
  4. Downloading an event twice, or one the watcher already imported, must not add a second row. (Task 3 tests.)
  5. The channel block (trigger level, range, scale) and the note strings must read exactly as before: only the four anchor fields move to unescaped bytes. (Task 1 test.)

Retraction carried by this plan

#15 is not a bug. device_commands.sent is documented as 1 acknowledged, 0 nothing sent, NULL unknown (sfm/database.py:148, change.py:12-14); a stop answered by a ring instead of its ack is exactly "unknown", and the row's error text already says the frame was sent. Task 4 retracts it in the spec.


Task 1: The live settings decode reads its four anchor fields from unescaped bytes (#1)

Files:

  • Modify: minimateplus/client.py — _decode_compliance_config_into (~line 2312), its anchor block (~2385–2440)
  • Create: tests/test_s3_compliance_anchor_fields.py

Interfaces: Produces nothing new; _decode_compliance_config_into(data: bytes, info: DeviceInfo) -> None keeps its signature. info.compliance_config fields recording_mode, sample_rate, histogram_interval_sec, record_time change meaning only for escaped replies.

Measured layout once escapes are removed (framing.unescape_reply), from every distinct recorded reply: mode anchor−7 (u8), sample rate anchor−6 (u16 BE), histogram interval anchor−4 (u16 BE, s), record time anchor+6 (f32 BE). The channel block and strings are correct on the raw bytes and must stay there (unescaped, "Tran"+28 reads 0.0 instead of 6.2061).

  • Step 1: Write the failing tests — a helper collects every SUB 0xE5 frame from tests/fixtures/minimate-bench-10-25-26/*_rx.bin and tests/fixtures/minimate-bench-10-26-26-histogram/unit_replies.bin whose data contains the anchor, de-duplicated by the 18 bytes around it (S3FrameParser().feed).
@pytest.mark.parametrize("fixture,expect", [   # (mode, sample_rate, interval_s, record_time_s)
    ("10-25", (1, 4096, 5, 5.0)),      # Continuous
    ("10-26a", (4, 2048, 2, 20.0)),    # Histogram + Continuous
    ("10-26b", (3, 4096, 900, 20.0)),  # Blastware's 16:26 write: Histogram, 15 min
    ("10-26c", (3, 4096, 2, 20.0)),    # Blastware's 16:27 write: back to 2 s (tonight's unit)
])
def test_anchor_fields_read_from_unescaped_bytes(fixture, expect): ...
    # decode the frame's data with _decode_compliance_config_into(DeviceInfo())
    # assert (cc.recording_mode, cc.sample_rate, cc.histogram_interval_sec, round(cc.record_time, 2)) == expect

def test_channel_block_still_reads_from_raw_bytes():
    # data = the 10-26c frame-B data + the next E5 frame whose data contains b"Tran"
    # assert cc.trigger_level_geo == pytest.approx(0.04, abs=1e-4)
    # assert cc.geo_adc_scale == pytest.approx(6.2061, abs=1e-3) and cc.geo_range == 0

def test_a_reply_without_the_settings_block_reads_as_unknown():
    # the recorded SUB 0xFE (device info) reply data -- what a monitoring BE9441 returned for 1A
    # assert all four anchor fields are None

The fixture labels are the test's own: number the de-duplicated replies in file order and map them to the four expectations above (assert there are exactly four).

  • Step 2: Run …pytest -q tests/test_s3_compliance_anchor_fields.py → FAIL: 10-25 reads mode 0, 10-26c reads sample rate 0 and interval 4098 (today's decoder on escaped bytes).
  • Step 3: Implement — in the anchor block, search _ANCHOR in logical = unescape_reply(data) (same 0:150 window) and read the four fields from logical at the offsets above; leave every other read on data. Update the layout comment to the measured logical layout and note the old "anchor−7 constant 0x10" was the escape before 04 at 1024 sps.
  • Step 4: Run the new tests, then the full suite → only the 16 known failures.
  • Step 5: Commit fix(minimateplus): read a MiniMate's mode, sample rate, interval and record time after removing escapes (#1).

Task 2: The Series-3 start read-back reconnects once after a dropped line (#9)

Files:

  • Modify: sfm/device_access/s3.py — change_monitoring's read_state (~line 230)
  • Modify: tests/device_access_fakes.py — FakeMiniMateClient: add read_serial() (returns serial_reported, default the unit's serial; records "read_serial") and wake_errors= (exceptions raised by successive wake() calls)
  • Test: tests/test_device_access_change.py

Interfaces: Consumes MiniMateClient.read_serial() (exists), normalise_serial (sfm/device_access/series.py). No new public names.

Behaviour: in read_state, an OSError from _woken_state(client) (Broken pipe / reset / aborted — measured: [Errno 32] Broken pipe at BE9441's first wake after the sensor check) on a TCP address, the first time only: log a warning "the line dropped during the read-back — reconnecting to read the state (nothing is re-sent)", client.close(), client.open(), require normalise_serial(client.read_serial()) == serial (else raise WrongUnit), then _woken_state(client). A second OSError, any other error, or a serial-cable address propagates as today.

  • Step 1: Write the failing tests
def test_series3_start_read_back_reconnects_after_a_dropped_line():
    fake = FakeMiniMateClient(monitor_states=[False, 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 and "read_serial" in fake.calls

def test_series3_read_back_reconnects_only_once():
    fake = FakeMiniMateClient(monitor_states=[False], wake_errors=[BrokenPipeError(32, "x")] * 2)
    with pytest.raises(ChangeUnconfirmed): access3(fake).start_monitoring(TCP3, "BE18193")
    assert fake.writes == ["start_monitoring"] and fake.opened == 2

def test_series3_read_back_reconnect_refuses_a_different_unit():
    fake = FakeMiniMateClient(monitor_states=[False], wake_errors=[BrokenPipeError(32, "x")], serial_reported="BE11529")
    with pytest.raises(ChangeUnconfirmed) as e: access3(fake).start_monitoring(TCP3, "BE18193")
    assert e.value.http_status == 409 and fake.writes == ["start_monitoring"]

def test_series3_read_back_does_not_reconnect_on_a_serial_cable():
    # address with port=, no host: opening a MiniMate's port reboots it
    ... assert fake.opened == 1 and raises ChangeUnconfirmed

def test_series3_read_back_silence_is_not_a_dropped_line():
    fake = FakeMiniMateClient(monitor_states=[False], wake_errors=[NoAnswer("quiet")])
    ... raises ChangeUnconfirmed; fake.opened == 1; writes == ["start_monitoring"]

(serial_reported applies to read_serial() only; connect() keeps returning the real serial so the pre-send identity check passes. Use the module's existing access3, TCP3 helpers; add a serial-cable UnitAddress beside TCP3.)

  • Step 2: Run them → the reconnect tests FAIL (no reconnect today); the last two may already pass — keep them as guards.
  • Step 3: Implement read_state as described (a closed-over reconnected flag).
  • Step 4: Run tests/test_device_access_change.py, then the full suite → only the 16 known failures.
  • Step 5: Commit fix(sfm): a MiniMate start's read-back reconnects once when the modem dropped the line (#9).

Task 3: MiniMate downloads are stored through the Blastware-file import path (#8)

Files:

  • Modify: minimateplus/blastware_file.py — add blastware_file_bytes(event: Event, a5_frames: list) -> bytes; write_blastware_file writes its result (no behaviour change)
  • Modify: sfm/device_access/models.py — DownloadedEvent.bw_bytes: Optional[bytes] = field(default=None, repr=False) (Series 3: the assembled Blastware file)
  • Modify: sfm/device_access/s3.py — download_event fills bw_bytes from the verified event's frames
  • Modify: sfm/waveform_store.py — save_imported_bw(..., source_kind: str = "bw-import") writes it into the sidecar's source.kind
  • Modify: sfm/event_ingest.py — persist_download's Series-3 branch
  • Test: tests/test_event_ingest.py, tests/test_5a_blastware_walk_histogram.py

Interfaces: Produces blastware_file_bytes(event, a5_frames) -> bytes; DownloadedEvent.bw_bytes; save_imported_bw(bw_bytes, source_path, *, serial_hint=None, bw_report_text=None, source_kind="bw-import") -> tuple[Event, dict].

Behaviour: Series 3 mirrors Series 4 — ev, rec = store.save_imported_bw(dl.bw_bytes, source_path=Path(dl.filename), serial_hint=dl.serial, source_kind="sfm-live"), then the existing db.insert_events(...). No backfill_series3_event on this path (the file's setup block supplies sample rate and record time, #44/#45); no overlay of the live 0C peaks (data comes from the binary — they stay the download check). A download with no bw_bytes raises IngestError("…the download carried no event file; nothing was stored"). The "Waveform" label on a live histogram stays until the checker session's #41 (record type from STRT[18]) lands on dev.

  • Step 1: Write the failing tests
# tests/test_5a_blastware_walk_histogram.py, beside the existing K441LTON.900 comparison:
def test_blastware_file_bytes_is_blastwares_file():
    # the walk's frames for key 0111f210 -> blastware_file_bytes(ev, frames) == (FIX/"blastware"/"K441LTON.900").read_bytes()

# tests/test_event_ingest.py
def test_a_series3_histogram_download_is_stored_from_its_file(tmp_path):
    bw = (HIST_FIX / "K441LTON.900").read_bytes()          # byte-identical to SFM's download (sha f10f39a8…)
    out = persist_download(DownloadedEvent(event_id="BE9441:0111f210:20261026170036", serial="BE9441",
            series=3, filename="K441LTON.900", verified=None, bw_bytes=bw,
            timestamp=datetime.datetime(2026, 10, 26, 17, 0, 36)), store=WaveformStore(tmp_path / "w"), db=SeismoDb(tmp_path / "s.db"))
    # assert the stored file's sha256 == hashlib.sha256(bw).hexdigest()
    # assert plot_json_from_hdf5(<h5>)["channels"]["Tran"]["values"]  (non-empty: the histogram decoded)
    # assert the sidecar's source.kind == "sfm-live" and the row's sample_rate == 4096

def test_the_small_mic_off_histogram_is_stored_with_samples(tmp_path):   # K441LTOK.QZ0, refused on 10-29
def test_a_repeat_series3_download_adds_no_row(tmp_path):                 # persist twice: one row; second inserted False
def test_a_series3_download_with_no_file_stores_nothing_and_says_so(tmp_path)  # replaces the no-event test

Rewrite test_a_series3_event_is_backfilled_then_stored_as_series3 to the new contract (bytes in, save_imported_bw called with source_kind="sfm-live", no backfill); keep test_downloading_an_event_the_watcher_stored_writes_nothing_series3 passing unchanged.

  • Step 2: Run them → FAIL (bw_bytes / blastware_file_bytes / source_kind do not exist).
  • Step 3: Implement the five file changes above.
  • Step 4: Run tests/test_event_ingest.py tests/test_5a_blastware_walk_histogram.py tests/test_device_access_events.py tests/test_server_device_access.py, then the full suite → only the 16 known failures.
  • Step 5: Commit fix(sfm): store a MiniMate download through the Blastware-file import path, as production does (#8) — body states: new live downloads only; existing rows untouched; no backfill or migration.

Task 4: Docs

Files: the spec (Left open by the 1c bench), docs/instantel_protocol_reference.md (CRLF — Edit tool), CLAUDE.md ("Where things stand").

  • Step 1: Spec: mark #1, #8, #9 fixed (commit ids); retract #15 in place (by design: sent NULL = sent without acknowledgement); #2 fixed by the dev merge (342c696).
  • Step 2: Instantel reference, a dated change-log row + §7.6.1 note: the measured logical 1A layout (mode −7, rate −6, interval −4, record time +6 after unescaping; the old "anchor−7 constant 0x10" was the escape before 04); while monitoring, BE9441 answered the 1A reads with its device-info block (measured 2026-10-29); the channel block is read on raw bytes, so a trigger/alarm float containing 02/03/04/10 would read shifted — open, unmeasured.
  • Step 3: CLAUDE.md: one line under the 1c entry — Batch 1 done (#1, #8, #9), #15 retracted.
  • Step 4: Commit docs: 1c bench Batch 1 -- #1, #8, #9 fixed; #15 retracted; the 1A layout after unescaping.