fix(sfm): a change that fails after the send says so; the audit row records sent + states; S3 unknown states refused
Final fix wave for phase 3 (start/stop monitoring), per the whole-phase review. - I1 + M2: every failure after the send has started is a ChangeUnconfirmed (audit_id, sent = "acknowledged" | "unknown", the cause's HTTP status) whose message says the frame was sent and names the audit record -- the ring in place of the ack, the four lost-ack follow-ups, and the three read-back paths. Series4Session releases the line on it. Every audit finish goes through one helper; a finish that fails is AuditIncomplete (500) and still says what happened to the unit. The line is kept. - I2: device_commands gains `sent` (1 acknowledged, 0 nothing sent, NULL unknown) and `states` (before / seen / after), with an idempotent ADD COLUMN in _migrate for a table created earlier on this branch. - M1: a RADIO RING already buffered is caught before 0x96/0x97 goes out (pre_send = read_unsolicited, one 10 ms transport read). That is a CallHomeInProgress with sent=0, not ChangeUnconfirmed. - M3: Series 3 reads the raw 0x1C flag (new MonitorStatus.state_flag); a byte other than 0x00/0x10, or a short section, is unknown(...) and refused. - M8: even_if_already on a unit already in the state notes that the read-back proves nothing. - M10: a scan pins `.protocol.execute(` to sfm/device_access/s4.py; both scans fail closed on a file that does not parse. - M11: docs corrected (CLAUDE.md phase-2 sentence, phase-3 bullet, REST list; micromate/protocol.py scope and the 0x49 read_state docstring; s4.py; route docstrings). "No command has ever been originated" is NOT retracted. - M12: GET /db/device_commands normalises the serial. - Minors: unused imports, S3 dry-run frames and 120 s timeout pinned, test rename, serial-cache and short-0x49 tests, _RUN_STATES comment. Schema: two NULLable columns on the branch-new device_commands table, added by _migrate on open; no backfill. No codec change, TOOL_VERSION unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44
This commit is contained in:
1 parent
ac33c8ffa4
commit
8f68b09f5e
18 files changed
+806
-107
No files matched your search
@@ -32,10 +32,12 @@ Read this first when picking the project back up.
|
||||
the setup rewrite, reproduced byte for byte against THOR's captured frames.
|
||||
`bridges/mm_dry_run.py` prints a write's planned frames from a live unit's
|
||||
reads (run on UM20147: sizes equal UM12947's). `MicromateProtocol._send`
|
||||
refuses every write opcode except one start/stop plan at a time through `execute()`, on a connection with a fresh Micromate reply, and `0xA2` always, so
|
||||
"no command has ever been originated against a unit" is still true and is now
|
||||
enforced in `micromate/` (its `_send` gate); the Series-3 `minimateplus`
|
||||
stack and raw-socket bench bridges are outside it. The reproduction's
|
||||
refuses every write opcode except one start/stop plan at a time through
|
||||
`execute()`, on a connection with a fresh Micromate reply, and refuses `0xA2`
|
||||
always. The only transmit path for a write is `execute()`, reached only from
|
||||
SFM's serial-named start/stop routes through `sfm/device_access` (identity,
|
||||
state, audit, read-back, never retried); the Series-3 `minimateplus` stack
|
||||
and raw-socket bench bridges are outside the gate. The reproduction's
|
||||
breadth is one distinct input per block (the five pushes share the same name,
|
||||
prefs and trigger block).
|
||||
- **✅ `micromate/` HAS a live client (2026-10-02).** `framing.py`,
|
||||
@@ -121,6 +123,16 @@ Read this first when picking the project back up.
|
||||
5 events, a waveform that verified, a histogram, one call-up for the whole
|
||||
sequence. ⚠ The MiniMate header walk is **unproven on a unit; a MiniMate
|
||||
bench check is owed before the branch merges.** Next: 1c (webapp).
|
||||
- **✅ Phase 3: start / stop monitoring by serial (2026-10-23) — built and
|
||||
reviewed offline; the first live send is pending at the bench.** Both
|
||||
series go through one safety core, `sfm/device_access/change.py`: a fresh
|
||||
identity read, the run state (calling home or never measured is refused),
|
||||
`dry_run` (the exact frames, nothing sent), a row in the new
|
||||
`device_commands` audit table (`GET /db/device_commands`; `sent` says whether
|
||||
a frame went out, `states` keeps every read), one send never retried, then a
|
||||
read-back. The HTTP status is an allow-list -- only a dry run, a skip or a
|
||||
send read back as made is a 200 -- and a failure after the send says so and
|
||||
names its audit record.
|
||||
- **🔑 ACH / call-home, captured end to end (2026-10-14).** A Micromate signals
|
||||
`RADIO RING`; **two paths exist and timing decides which**: if anything
|
||||
already holds the modem's single TCP session the ring rides that connection,
|
||||
@@ -1429,14 +1441,19 @@ GET /device/event?host=1.2.3.4&tcp_port=9034&index=0
|
||||
GET /device/monitor/status?host=1.2.3.4&tcp_port=9034 ← battery, memory, mode
|
||||
POST /device/monitor/start?host=1.2.3.4&tcp_port=9034 ← start recording
|
||||
POST /device/monitor/stop?host=1.2.3.4&tcp_port=9034 ← stop recording
|
||||
POST /device/monitor/start?serial=UM20147&host=...&tcp_port=...&dry_run=&even_if_already= ← audited start, either series
|
||||
POST /device/monitor/stop?serial=UM20147&host=...&tcp_port=...&dry_run=&even_if_already= ← audited stop, either series
|
||||
GET /device/settings?serial=UM20147&host=1.2.3.4&tcp_port=9034 ← shared-model settings, either series
|
||||
POST /device/hangup?host=1.2.3.4&tcp_port=9034 ← release a held Series-4 line
|
||||
```
|
||||
|
||||
`serial=` (UM = Series 4, BE/BA = Series 3) on `/device/info`, `/connect`,
|
||||
`/monitor/status`, `/settings` returns the shared model, uncached. A `UM` serial on any
|
||||
other `/device/*` route is 501; any request taking the legacy Series-3 path at a held
|
||||
Series-4 address is 409.
|
||||
`/monitor/status`, `/settings` returns the shared model, uncached; on `/events` and
|
||||
`/events/download` it lists and downloads by `event_id`; on `/monitor/start` and
|
||||
`/monitor/stop` it runs the audited change (`dry_run=true` returns the frames and sends
|
||||
nothing; `even_if_already=true` sends even when the unit is already in that state). A
|
||||
`UM` serial on any other `/device/*` route is 501; any request taking the legacy
|
||||
Series-3 path at a held Series-4 address is 409.
|
||||
SFM must run a single uvicorn worker (locks and held lines are per process).
|
||||
|
||||
Server retries once on `ProtocolError` for TCP connections (handles cold-boot timing).
|
||||
@@ -1449,6 +1466,7 @@ GET /db/events?serial=BE11529&from_dt=&to_dt=&limit= ← triggered events, ne
|
||||
GET /db/monitor_log?serial=BE11529&from_dt=&to_dt= ← monitoring intervals, newest first
|
||||
GET /db/sessions?serial=BE11529&limit=50 ← ACH call-home sessions, newest first
|
||||
PATCH /db/events/{id}/false_trigger?value=true ← flag/unflag false triggers
|
||||
GET /db/device_commands?serial=UM20147&limit=100 ← start/stop audit trail (sent, states), newest first
|
||||
```
|
||||
|
||||
DB file: `bridges/captures/seismo_relay.db` (default; override with `--db-path` at startup).
|
||||
|
||||
@@ -385,6 +385,7 @@ class MicromateClient:
|
||||
self._serial = _cstring(_content(self._proto.read_serial()))
|
||||
return self._serial
|
||||
|
||||
# Anything else reads unknown(0x..): the safe default, which the change path refuses.
|
||||
_RUN_STATES = {0x00: "idle", 0x02: "monitoring", 0x03: "calling_home"}
|
||||
|
||||
def read_run_state(self) -> MicromateRunState:
|
||||
|
||||
+21
-9
@@ -4,14 +4,17 @@ protocol.py — one method per Micromate (Series IV) wire command.
|
||||
Returns raw payload bytes. Interpretation belongs in ``client.py``; this layer
|
||||
knows frames, offsets and sequencing, and nothing about what a field means.
|
||||
|
||||
Scope: **reads only on the wire, enforced** (in this package: the Series-3
|
||||
`minimateplus` stack and raw-socket bench bridges are outside the gate). Every outgoing frame passes
|
||||
Scope: **reads, plus start/stop monitoring through `execute()` only --
|
||||
enforced** (in this package: the Series-3 `minimateplus` stack and raw-socket
|
||||
bench bridges are outside the gate). Every outgoing frame passes
|
||||
`micromate.opcodes.check_transmit()` in `_send`: a write opcode is refused
|
||||
unless it arrives through `execute()` (the connection itself holds no write
|
||||
permission), and `0xA2` -- CONFIRM ERASE on Series III -- is
|
||||
refused always. The gate is an allowlist: a SUB not catalogued in
|
||||
`opcodes` (read or write) is refused as unknown. No command has ever been originated against a unit by this
|
||||
project; every write in ``docs/micromate_protocol_reference.md`` was performed
|
||||
permission), `execute()` can permit only SUBs under `ENABLEABLE_WRITES`
|
||||
(`0x96` / `0x97`), and `0xA2` -- CONFIRM ERASE on Series III -- is refused
|
||||
always. The one caller of `execute()` is SFM's change path,
|
||||
`sfm/device_access/s4.py` (a test pins that). The gate is an allowlist: a SUB
|
||||
not catalogued in `opcodes` (read or write) is refused as unknown. No command
|
||||
has ever been originated against a unit by this project; every write in ``docs/micromate_protocol_reference.md`` was performed
|
||||
by THOR while we recorded. The first thing this codebase ever sends to a
|
||||
customer's instrument should be a decision someone made on purpose, not a side
|
||||
effect of a client that grew a method. Write frames are *built* in
|
||||
@@ -305,10 +308,19 @@ class MicromateProtocol:
|
||||
return self._read(SUB_DEVICE_INFO)
|
||||
|
||||
def read_state(self) -> bytes:
|
||||
"""`0x49` → `0xB6`. A cheap monitoring check; 16 B.
|
||||
"""`0x49` → `0xB6`. A cheap state check; 16 B of data.
|
||||
|
||||
⚠ Test `data[11]` for **non-zero**, never against a constant — it has
|
||||
read both `0x0E` and `0x0C` while monitoring.
|
||||
`data[11]` (content[0]) is the run state. Measured: `0x00` idle,
|
||||
`0x02` monitoring (every monitoring sample so far), and `0x03` while
|
||||
calling home (ten reads of ten in the captured 2026-10-14 ACH
|
||||
session). No other value has been seen.
|
||||
`MicromateClient.read_run_state` matches those three exactly and names
|
||||
anything else `unknown(0x..)`, which the change path refuses;
|
||||
`connect()`'s `monitoring` tests non-zero, so `0x03` reads True there.
|
||||
|
||||
⚠ `0x0E` and `0x0C` (both read while monitoring, so "test for
|
||||
non-zero") belong to `SUB 0x1C` `data[12]`, a separate field -- not to
|
||||
this byte. See the reference's `0x49` and `0x1C` sections.
|
||||
"""
|
||||
return self._read(SUB_STATE)
|
||||
|
||||
|
||||
@@ -2688,6 +2688,9 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus:
|
||||
# section[1] = 0x00 in all IDLE frames, 0x10 in all MONITORING frames.
|
||||
# (section[6] also changes but has non-binary values 0xea/0x07 — device-specific.)
|
||||
is_monitoring = len(section) > 1 and section[1] == 0x10
|
||||
# The same byte, raw -- but only from a real section: for data of 11 bytes
|
||||
# or fewer, `section` above falls back to the header itself.
|
||||
state_flag = data[12] if len(data) > 12 else None
|
||||
|
||||
battery_v = None
|
||||
memory_total = None
|
||||
@@ -2713,6 +2716,7 @@ def _decode_monitor_status(data: bytes) -> MonitorStatus:
|
||||
battery_v=battery_v,
|
||||
memory_total=memory_total,
|
||||
memory_free=memory_free,
|
||||
state_flag=state_flag,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -660,3 +660,8 @@ class MonitorStatus:
|
||||
battery_v: Optional[float] = None # Battery voltage in volts ✅
|
||||
memory_total: Optional[int] = None # Total flash memory in bytes ✅
|
||||
memory_free: Optional[int] = None # Free flash memory in bytes ✅
|
||||
# The raw flag byte `is_monitoring` is derived from: section[1] = data[12].
|
||||
# Measured: 0x00 idle, 0x10 monitoring. None when the section is too short
|
||||
# to hold it. Kept raw so a caller can refuse a value never measured,
|
||||
# where `is_monitoring` reads anything but 0x10 as idle.
|
||||
state_flag: Optional[int] = None
|
||||
+28
-6
@@ -143,7 +143,9 @@ CREATE TABLE IF NOT EXISTS device_commands (
|
||||
verified TEXT, -- "ok" | "mismatch" | "not_checked"
|
||||
outcome TEXT NOT NULL, -- "pending" | "sent" | "skipped" | "failed"
|
||||
error TEXT,
|
||||
caller TEXT -- "webapp" | "terra-view" | "script" | ...
|
||||
caller TEXT, -- "webapp" | "terra-view" | "script" | ...
|
||||
sent INTEGER, -- did a frame go out: 1 acknowledged, 0 nothing sent, NULL unknown
|
||||
states TEXT -- JSON: {"before": ..., "seen": [...], "after": ...}
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts);
|
||||
"""
|
||||
@@ -302,6 +304,17 @@ class SeismoDb:
|
||||
log.info("_migrate: device_family backfill complete (remaining NULL=%d)",
|
||||
remaining)
|
||||
|
||||
# Migration 1d: device_commands gained `sent` and `states` after the
|
||||
# table first shipped on feat/series4-sfm-parity. NULLable, so rows
|
||||
# written before read NULL (= unknown).
|
||||
existing_cols = {
|
||||
r[1] for r in conn.execute("PRAGMA table_info(device_commands)").fetchall()
|
||||
}
|
||||
for col, ddl in (("sent", "INTEGER"), ("states", "TEXT")):
|
||||
if col not in existing_cols:
|
||||
log.info("_migrate: device_commands ADD COLUMN %s %s", col, ddl)
|
||||
conn.execute(f"ALTER TABLE device_commands ADD COLUMN {col} {ddl}")
|
||||
|
||||
# Migration 2: change monitor_log UNIQUE from (serial, waveform_key) to
|
||||
# (serial, start_time) — same reasoning as events.
|
||||
row = conn.execute(
|
||||
@@ -429,16 +442,25 @@ class SeismoDb:
|
||||
verified: Optional[str],
|
||||
ack: Optional[dict],
|
||||
error: Optional[str],
|
||||
sent: Optional[int] = None,
|
||||
states: Optional[dict] = None,
|
||||
) -> None:
|
||||
"""Record the result of a command begun with begin_device_command()."""
|
||||
"""Record the result of a command begun with begin_device_command().
|
||||
|
||||
`sent`: 1 a frame went out and was acknowledged, 0 nothing was sent,
|
||||
None unknown (the ack was lost). `states`: what was read from the unit,
|
||||
``{"before": ..., "seen": [...], "after": ...}``.
|
||||
"""
|
||||
ts = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
with self._connect() as conn:
|
||||
cur = conn.execute(
|
||||
"UPDATE device_commands SET finished_ts=?, outcome=?, verified=?, "
|
||||
"ack=?, error=? WHERE id=? AND outcome='pending'",
|
||||
"ack=?, error=?, sent=?, states=? WHERE id=? AND outcome='pending'",
|
||||
(ts, outcome, verified,
|
||||
json.dumps(ack) if ack is not None else None,
|
||||
error, command_id),
|
||||
error, sent,
|
||||
json.dumps(states) if states is not None else None,
|
||||
command_id),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
known = conn.execute(
|
||||
@@ -453,7 +475,7 @@ class SeismoDb:
|
||||
serial: Optional[str] = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict]:
|
||||
"""Return audit rows, newest first, with request/ack parsed from JSON."""
|
||||
"""Return audit rows, newest first, with request/ack/states parsed from JSON."""
|
||||
with self._connect() as conn:
|
||||
if serial:
|
||||
rows = conn.execute(
|
||||
@@ -466,7 +488,7 @@ class SeismoDb:
|
||||
out = []
|
||||
for r in rows:
|
||||
d = dict(r)
|
||||
for k in ("request", "ack"):
|
||||
for k in ("request", "ack", "states"):
|
||||
if d[k] is not None:
|
||||
d[k] = json.loads(d[k])
|
||||
out.append(d)
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""One door for every device request -- see the 2026-10-20 parity spec."""
|
||||
from .errors import (
|
||||
AuditUnavailable, BadRequest, CallHomeInProgress, ConnectFailed, DeviceError, EventNotFound,
|
||||
MalformedReply, NoAnswer, NotSupported, StaleEvent, UnitBusy, UnitStateUnknown, WrongUnit,
|
||||
translate,
|
||||
AuditIncomplete, AuditUnavailable, BadRequest, CallHomeInProgress, ChangeUnconfirmed,
|
||||
ConnectFailed, DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported, StaleEvent,
|
||||
UnitBusy, UnitStateUnknown, WrongUnit, translate,
|
||||
)
|
||||
from .models import (
|
||||
ChangeResult, DownloadedEvent, EventDownload, EventList, EventRef, UnitAddress, UnitInfo,
|
||||
|
||||
+146
-38
@@ -1,24 +1,40 @@
|
||||
"""The series-independent core of a start/stop request.
|
||||
|
||||
Identity -> state -> (dry run | skip | audit -> send once -> read back -> audit).
|
||||
Each series supplies only its own pieces as callables: how to read the serial,
|
||||
how to read the run-state name, how to send (returning the ack record), and how
|
||||
to recognise a refusal or a ring. Nothing in here retries: `send` is called at
|
||||
most once, and every path after `audit.begin` calls `audit.finish` exactly once.
|
||||
Identity -> state -> (dry run | skip | audit -> pre-send drain -> send once ->
|
||||
read back -> audit). Each series supplies only its own pieces as callables:
|
||||
how to read the serial, how to read the run-state name, how to send (returning
|
||||
the ack record), how to recognise a refusal or a ring, and optionally what to
|
||||
drain from the line just before sending. Nothing in here retries: `send` is
|
||||
called at most once, and every path after `audit.begin` calls `audit.finish`
|
||||
exactly once, through `finish` below.
|
||||
|
||||
The state names `calling_home` and `unknown*` are Series-4 states; Series 3
|
||||
never produces them, so those branches are simply never taken there.
|
||||
Once the send has started, a failure is never reported as if nothing went out:
|
||||
it is a `ChangeUnconfirmed` naming the audit row, carrying the status its cause
|
||||
would have had. The row's `sent` column says whether a frame went out (1),
|
||||
did not (0), or may have (NULL), and `states` keeps every state read.
|
||||
|
||||
The state names `calling_home` and `unknown*` are Series-4 states, except
|
||||
`unknown(...)`, which Series 3 also produces for a flag byte never measured.
|
||||
Series 3 never produces `calling_home` or a ring, so those branches are simply
|
||||
never taken there.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable, Dict, Optional
|
||||
from typing import Any, Callable, Dict, List, NoReturn, Optional
|
||||
|
||||
from .errors import AuditUnavailable, CallHomeInProgress, NotSupported, UnitStateUnknown, WrongUnit
|
||||
from .errors import (
|
||||
AuditIncomplete, AuditUnavailable, CallHomeInProgress, ChangeUnconfirmed, NotSupported,
|
||||
UnitStateUnknown, WrongUnit, translate,
|
||||
)
|
||||
from .models import ChangeResult, UnitAddress
|
||||
from .series import normalise_serial
|
||||
|
||||
CALL_HOME_MESSAGE = ("the unit started calling home; SFM hung up so the call can "
|
||||
"reach THOR -- try again in a few minutes")
|
||||
_HUNG_UP = "SFM hung up so the call can reach THOR"
|
||||
|
||||
# The row's `sent` column.
|
||||
SENT_ACKNOWLEDGED, NOTHING_SENT, SENT_UNKNOWN = 1, 0, None
|
||||
|
||||
|
||||
def _never(exc: BaseException) -> bool:
|
||||
@@ -33,9 +49,11 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
|
||||
describe_plan: Callable[[], Dict[str, Any]],
|
||||
send: Callable[[], Dict[str, Any]],
|
||||
is_refusal: Callable[[BaseException], bool] = _never,
|
||||
is_ring: Callable[[BaseException], bool] = _never) -> ChangeResult:
|
||||
is_ring: Callable[[BaseException], bool] = _never,
|
||||
pre_send: Optional[Callable[[], None]] = None) -> ChangeResult:
|
||||
action = "start monitoring" if start else "stop monitoring"
|
||||
want = "monitoring" if start else "idle"
|
||||
became = "started" if start else "stopped"
|
||||
|
||||
reported = normalise_serial(read_serial())
|
||||
if reported != serial:
|
||||
@@ -63,45 +81,110 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise AuditUnavailable(
|
||||
f"the audit log could not be written -- nothing sent: {exc}") from exc
|
||||
|
||||
def states(seen: List[str], after: Optional[str]) -> Dict[str, Any]:
|
||||
return {"before": before, "seen": list(seen), "after": after}
|
||||
|
||||
def finish(unit: str, **fields: Any) -> None:
|
||||
"""The only way a row is finished. `unit` says what happened to the
|
||||
unit, so a finish that fails still says it."""
|
||||
try:
|
||||
audit.finish(cid, **fields)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise AuditIncomplete(
|
||||
f"{unit} -- but audit record {cid} could not be finished: {exc}") from exc
|
||||
|
||||
def unconfirmed(unit: str, cause: BaseException, *, went_out: str, status: int,
|
||||
**fields: Any) -> NoReturn:
|
||||
"""Finish the row, then say the change went out (or may have) and name it.
|
||||
`went_out` is "acknowledged" or "unknown"; the row's `sent` follows it."""
|
||||
finish(unit, sent=SENT_ACKNOWLEDGED if went_out == "acknowledged" else SENT_UNKNOWN,
|
||||
**fields)
|
||||
raise ChangeUnconfirmed(f"{unit} -- audit record {cid}", audit_id=cid, sent=went_out,
|
||||
http_status=status) from cause
|
||||
|
||||
def status_of(exc: BaseException) -> int:
|
||||
return translate(exc, connecting=False).http_status
|
||||
|
||||
if before == want and not even_if_already:
|
||||
audit.finish(cid, outcome="skipped", verified="not_checked", ack=None,
|
||||
error=f"already {want}")
|
||||
finish(f"nothing was sent ({serial} is already {want})",
|
||||
outcome="skipped", verified="not_checked", ack=None, error=f"already {want}",
|
||||
sent=NOTHING_SENT, states=states([before], None))
|
||||
return ChangeResult(dry_run=False, sent=False, outcome="skipped",
|
||||
verified="not_checked", state_after=before,
|
||||
audit_id=cid, detail={"reason": f"the unit is already {want}"}, **base)
|
||||
|
||||
if pre_send is not None:
|
||||
try:
|
||||
pre_send() # sends nothing: drains what is already waiting
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if is_ring(exc):
|
||||
finish("nothing was sent (a call-home began before sending)",
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error="a call-home began before sending -- nothing sent",
|
||||
sent=NOTHING_SENT, states=states([before], None))
|
||||
raise CallHomeInProgress(CALL_HOME_MESSAGE) from exc
|
||||
finish(f"nothing was sent (the line failed before sending: {exc})",
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"the line failed before sending -- nothing sent: {exc}",
|
||||
sent=NOTHING_SENT, states=states([before], None))
|
||||
raise # the link is suspect
|
||||
|
||||
try:
|
||||
ack = send() # the only send; nothing below can reach it again
|
||||
except Exception as exc: # noqa: BLE001 -- recorded, never retried
|
||||
if is_refusal(exc): # refused by the gate: nothing went out
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"refused before sending: {exc}")
|
||||
finish(f"nothing was sent (refused before sending: {exc})",
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"refused before sending: {exc}",
|
||||
sent=NOTHING_SENT, states=states([before], None))
|
||||
raise
|
||||
if is_ring(exc):
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"a call-home began in place of the ack: {exc}")
|
||||
raise
|
||||
unconfirmed(f"{action} was sent, but a call-home began in place of the "
|
||||
f"acknowledgement -- whether it {became} is unknown; {_HUNG_UP}",
|
||||
exc, went_out="unknown", status=CallHomeInProgress.http_status,
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"a call-home began in place of the ack: {exc}",
|
||||
states=states([before], None))
|
||||
try:
|
||||
after: Optional[str] = read_state()
|
||||
except Exception as follow: # noqa: BLE001
|
||||
if is_ring(follow):
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; a call-home began: {follow}")
|
||||
raise
|
||||
after = None
|
||||
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
|
||||
f"the unit then began calling home -- whether it {became} is "
|
||||
f"unknown; {_HUNG_UP}",
|
||||
follow, went_out="unknown", status=CallHomeInProgress.http_status,
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; a call-home began: {follow}",
|
||||
states=states([before], None))
|
||||
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
|
||||
f"reading the state afterwards failed ({follow}) -- whether it "
|
||||
f"{became} is unknown",
|
||||
exc, went_out="unknown", status=status_of(exc),
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; the follow-up read failed: {follow}",
|
||||
states=states([before], None))
|
||||
if after == "calling_home":
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; the unit is now calling home")
|
||||
raise CallHomeInProgress(CALL_HOME_MESSAGE) from exc
|
||||
audit.finish(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}")
|
||||
if after is None:
|
||||
raise # the link is suspect
|
||||
unconfirmed(f"{action} was sent but the acknowledgement was lost ({exc}), and "
|
||||
f"the unit then began calling home -- whether it {became} is "
|
||||
f"unknown; {_HUNG_UP}",
|
||||
exc, went_out="unknown", status=CallHomeInProgress.http_status,
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}; the unit is now calling home",
|
||||
states=states([before], after))
|
||||
finish(f"{action} was sent but the acknowledgement was lost ({exc}); the unit "
|
||||
f"now reads {after}",
|
||||
outcome="failed", verified="not_checked", ack=None,
|
||||
error=f"no clean ack: {exc}", sent=SENT_UNKNOWN, states=states([before], after))
|
||||
return ChangeResult(dry_run=False, sent=True, outcome="failed",
|
||||
verified="not_checked", state_after=after, audit_id=cid,
|
||||
detail={"error": f"no clean ack: {exc}"}, **base)
|
||||
|
||||
seen = [before]
|
||||
|
||||
def last_poll() -> Optional[str]:
|
||||
return seen[-1] if len(seen) > 1 else None
|
||||
|
||||
polls = int(verify_timeout_s // verify_interval_s)
|
||||
try:
|
||||
for _ in range(polls):
|
||||
@@ -110,17 +193,42 @@ def run_change(*, serial: str, series: int, start: bool, dry_run: bool, even_if_
|
||||
if seen[-1] == want or seen[-1] == "calling_home":
|
||||
break
|
||||
except Exception as exc: # noqa: BLE001 -- the row must not stay pending
|
||||
audit.finish(cid, outcome="sent", verified="not_checked", ack=ack,
|
||||
error=f"sent and acknowledged; reading the state back failed: {exc}")
|
||||
raise
|
||||
if is_ring(exc):
|
||||
unconfirmed(f"{action} was sent and acknowledged, but the unit then began "
|
||||
f"calling home before its state could be read back -- whether it "
|
||||
f"{became} is unknown; {_HUNG_UP}",
|
||||
exc, went_out="acknowledged", status=CallHomeInProgress.http_status,
|
||||
outcome="sent", verified="not_checked", ack=ack,
|
||||
error=f"sent and acknowledged; a call-home began while reading the "
|
||||
f"state back: {exc}",
|
||||
states=states(seen, last_poll()))
|
||||
unconfirmed(f"{action} was sent and acknowledged, but reading the state back "
|
||||
f"failed: {exc}",
|
||||
exc, went_out="acknowledged", status=status_of(exc),
|
||||
outcome="sent", verified="not_checked", ack=ack,
|
||||
error=f"sent and acknowledged; reading the state back failed: {exc}",
|
||||
states=states(seen, last_poll()))
|
||||
if seen[-1] == "calling_home":
|
||||
audit.finish(cid, outcome="sent", verified="not_checked", ack=ack,
|
||||
error="sent and acknowledged; the unit then began calling home")
|
||||
raise CallHomeInProgress(CALL_HOME_MESSAGE)
|
||||
cause = CallHomeInProgress(CALL_HOME_MESSAGE)
|
||||
unconfirmed(f"{action} was sent and acknowledged, but the unit then began calling "
|
||||
f"home -- whether it {became} is unknown; {_HUNG_UP}",
|
||||
cause, went_out="acknowledged", status=cause.http_status,
|
||||
outcome="sent", verified="not_checked", ack=ack,
|
||||
error="sent and acknowledged; the unit then began calling home",
|
||||
states=states(seen, last_poll()))
|
||||
ok = seen[-1] == want
|
||||
outcome, verified = ("sent", "ok") if ok else ("failed", "mismatch")
|
||||
audit.finish(cid, outcome=outcome, verified=verified, ack=ack,
|
||||
error=None if ok else f"unit reads {seen[-1]}, expected {want}")
|
||||
error = None if ok else f"unit reads {seen[-1]}, expected {want}"
|
||||
detail: Dict[str, Any] = {"states_seen": seen, "ack": ack}
|
||||
if even_if_already and before == want:
|
||||
note = (f"the unit was already {want} before sending; the read-back cannot show "
|
||||
"that this send changed anything")
|
||||
detail["note"] = note
|
||||
if error is None:
|
||||
error = note
|
||||
finish(f"{action} was sent and verified" if ok else
|
||||
f"{action} was sent and acknowledged, but the unit reads {seen[-1]}, not {want}",
|
||||
outcome=outcome, verified=verified, ack=ack, error=error,
|
||||
sent=SENT_ACKNOWLEDGED, states=states(seen, last_poll()))
|
||||
return ChangeResult(dry_run=False, sent=True, outcome=outcome, verified=verified,
|
||||
state_after=seen[-1], audit_id=cid,
|
||||
detail={"states_seen": seen, "ack": ack}, **base)
|
||||
state_after=seen[-1], audit_id=cid, detail=detail, **base)
|
||||
@@ -31,6 +31,31 @@ class AuditUnavailable(DeviceError):
|
||||
http_status = 503
|
||||
|
||||
|
||||
class AuditIncomplete(DeviceError):
|
||||
"""The unit was dealt with, but its audit row could not be finished. The
|
||||
message says what happened to the unit first, then names the row."""
|
||||
http_status = 500
|
||||
|
||||
|
||||
class ChangeUnconfirmed(DeviceError):
|
||||
"""A change failed after its frame went out, or may have gone out.
|
||||
|
||||
`sent` is "acknowledged" (the ack came back; the read-back failed) or
|
||||
"unknown" (the ack was lost, or a call-home took its place). The status is
|
||||
the one the cause would have had, set per instance, and the message names
|
||||
the audit record. It never means "nothing was sent".
|
||||
"""
|
||||
http_status = 500
|
||||
|
||||
def __init__(self, message: str, *, audit_id: str, sent: str, http_status: int) -> None:
|
||||
if sent not in ("acknowledged", "unknown"):
|
||||
raise ValueError(f"sent must be 'acknowledged' or 'unknown', not {sent!r}")
|
||||
super().__init__(message)
|
||||
self.audit_id = audit_id
|
||||
self.sent = sent
|
||||
self.http_status = http_status
|
||||
|
||||
|
||||
class UnitBusy(DeviceError):
|
||||
http_status = 423
|
||||
|
||||
|
||||
+15
-2
@@ -13,7 +13,7 @@ from minimateplus.framing import build_bw_write_frame
|
||||
from minimateplus.protocol import SUB_START_MONITORING, SUB_STOP_MONITORING
|
||||
from minimateplus.transport import TcpTransport
|
||||
|
||||
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, NotSupported, StaleEvent, WrongUnit, translate
|
||||
from .errors import DeviceError, EventNotFound, MalformedReply, NoAnswer, StaleEvent, WrongUnit, translate
|
||||
from .change import run_change
|
||||
from .events import iso_of, make_event_id, stamp_of
|
||||
from .models import ChangeResult, DownloadedEvent, EventList, EventRef, UnitAddress, UnitInfo, UnitSettings, UnitStatus
|
||||
@@ -26,6 +26,19 @@ S3_MODES = {0x00: "Single Shot", 0x01: "Continuous", 0x03: "Histogram", 0x04: "H
|
||||
|
||||
S3_EVENT_TIMEOUT = 120.0 # what the legacy event-download routes use
|
||||
|
||||
# The 0x1C flag byte (section[1]): the only two values ever measured.
|
||||
S3_RUN_STATES = {0x00: "idle", 0x10: "monitoring"}
|
||||
|
||||
|
||||
def s3_run_state(status: Any) -> str:
|
||||
"""The change path's state name from the raw 0x1C flag -- never
|
||||
`is_monitoring`, which reads every byte but 0x10 as idle. A value never
|
||||
measured is `unknown(0x..)`, and the change core refuses it."""
|
||||
flag = getattr(status, "state_flag", None)
|
||||
if flag is None:
|
||||
return "unknown(short)"
|
||||
return S3_RUN_STATES.get(flag, f"unknown(0x{flag:02X})")
|
||||
|
||||
|
||||
def default_s3_client_factory(address: UnitAddress, timeout: Optional[float] = None) -> MiniMateClient:
|
||||
if address.host:
|
||||
@@ -120,7 +133,7 @@ class Series3Adapter:
|
||||
even_if_already=even_if_already, audit=audit, address=address, caller=caller,
|
||||
sleep=sleep, verify_timeout_s=verify_timeout_s, verify_interval_s=verify_interval_s,
|
||||
read_serial=read_serial,
|
||||
read_state=lambda: "monitoring" if client.get_monitor_status().is_monitoring else "idle",
|
||||
read_state=lambda: s3_run_state(client.get_monitor_status()),
|
||||
describe_plan=describe_plan, send=send)
|
||||
return self._run(address, op, timeout=S3_EVENT_TIMEOUT, retry=False)
|
||||
|
||||
|
||||
+22
-7
@@ -1,5 +1,11 @@
|
||||
"""Series-4 sessions: call up once, stay on the line, hang up when idle.
|
||||
|
||||
⚠ **This module hosts a write path.** `s4_change_monitoring` is the Series-4
|
||||
wrapper of the shared change core (`change.run_change`): it sends `0x96` /
|
||||
`0x97` through `MicromateProtocol.execute()`, and it is the only caller of
|
||||
`.protocol.execute(` in the codebase (a test pins that). Everything else here
|
||||
is a read.
|
||||
|
||||
⚠ Imports only minimateplus.transport from the Series-3 package. Nothing
|
||||
here may build or send a Series-3 frame -- SESSION_RESET (41 03) has never
|
||||
been sent to a Micromate.
|
||||
@@ -17,8 +23,8 @@ from micromate.writes import plan_start_monitoring, plan_stop_monitoring
|
||||
from minimateplus.transport import BaseTransport, SerialTransport, TcpTransport
|
||||
|
||||
from .errors import (
|
||||
AuditUnavailable, CallHomeInProgress, DeviceError, EventNotFound, MalformedReply, NotSupported, StaleEvent,
|
||||
UnitStateUnknown, WrongUnit, translate,
|
||||
CallHomeInProgress, ChangeUnconfirmed, DeviceError, EventNotFound, MalformedReply, StaleEvent,
|
||||
WrongUnit, translate,
|
||||
)
|
||||
from .change import CALL_HOME_MESSAGE, run_change
|
||||
from .events import iso_of, make_event_id, stamp_of
|
||||
@@ -124,8 +130,10 @@ class Series4Session:
|
||||
so it hangs up too -- conservative, since the link may be fine. Operations
|
||||
added in later phases must keep to this: never wrap a link failure in a
|
||||
`DeviceError` inside an op, or the line stays open on a broken link.
|
||||
The one exception: `CallHomeInProgress` and `WrongUnit` release the line,
|
||||
because the line itself is the problem.
|
||||
The exceptions: `CallHomeInProgress` and `WrongUnit` release the line,
|
||||
because the line itself is the problem; so does `ChangeUnconfirmed`, which
|
||||
the change core raises only after a link fault or a ring, once the frame
|
||||
has gone out. `AuditIncomplete` is an ordinary verdict: the line is kept.
|
||||
"""
|
||||
|
||||
def __init__(self, address: UnitAddress, serial: str,
|
||||
@@ -173,10 +181,13 @@ class Series4Session:
|
||||
log.warning("RADIO RING from %s -- released the line so the call reaches THOR",
|
||||
self.address.key)
|
||||
raise CallHomeInProgress(_RING_MESSAGE) from exc
|
||||
except (CallHomeInProgress, WrongUnit) as exc:
|
||||
except (CallHomeInProgress, WrongUnit, ChangeUnconfirmed) as exc:
|
||||
# The line itself is the problem: a call-home rides whatever holds the
|
||||
# modem's single TCP session, and a line held for X that answers as Y
|
||||
# must not stay held.
|
||||
# must not stay held. ChangeUnconfirmed always follows a link fault
|
||||
# or a ring (the core converts those itself, so the RingDetected
|
||||
# clause above never sees them). All three are DeviceErrors, so this
|
||||
# clause must stay above `except DeviceError`.
|
||||
self.hang_up()
|
||||
log.warning("%s at %s -- released the line: %s", type(exc).__name__,
|
||||
self.address.key, exc)
|
||||
@@ -340,4 +351,8 @@ def s4_change_monitoring(client: Any, serial: str, *, start: bool, dry_run: bool
|
||||
read_state=lambda: client.read_run_state().name,
|
||||
describe_plan=plan.describe, send=send,
|
||||
is_refusal=lambda e: isinstance(e, OpcodeRefused),
|
||||
is_ring=lambda e: isinstance(e, RingDetected))
|
||||
is_ring=lambda e: isinstance(e, RingDetected),
|
||||
# A RADIO RING already buffered is caught here, before 0x96/0x97 goes
|
||||
# out. One transport read: RingWatchTransport over Tcp/SerialTransport,
|
||||
# each with a 10 ms read timeout, so it returns at once on a quiet line.
|
||||
pre_send=lambda: client.read_unsolicited())
|
||||
+56
-7
@@ -1869,9 +1869,31 @@ def device_monitor_start(
|
||||
|
||||
With `serial`: the unit's identity is read first (a different unit is a 409,
|
||||
nothing sent), then its state; `dry_run` returns the planned frames and sends
|
||||
nothing; a live change is audited, verified by reading the state back, and
|
||||
never retried. The response is the ChangeResult (409 if the unit never
|
||||
reached the state, 502 if the ack was lost).
|
||||
nothing; a live change is audited (`GET /db/device_commands`), verified by
|
||||
reading the state back, and never retried. `even_if_already` sends even
|
||||
when the unit is already in the target state.
|
||||
|
||||
Statuses with `serial`:
|
||||
200 the ChangeResult: a dry run, a skip (already in the state), or a send
|
||||
read back as made
|
||||
409 ChangeResult: sent and acknowledged, but the unit never reached the
|
||||
state (`verified: mismatch`, every state seen kept); or, as an
|
||||
error, a different unit answered or its state was never measured
|
||||
(nothing sent either way)
|
||||
502 ChangeResult: the ack was lost but the unit could be read afterwards
|
||||
422 a malformed serial or address; 423 the unit is busy;
|
||||
501 no audit log is configured (nothing sent)
|
||||
503 the unit is calling home, or a call-home was already waiting before
|
||||
sending (nothing sent); or the audit log could not be written
|
||||
(nothing sent)
|
||||
500 the audit row could not be finished -- the detail says first what
|
||||
happened to the unit (sent and verified, nothing sent, ...)
|
||||
504 / 502 / 503 a link failure before anything was sent
|
||||
A failure AFTER the frame went out (or may have) -- the read-back failed,
|
||||
the ack was lost and the unit could not be read, or a call-home began --
|
||||
takes the status its cause would have had (503 for a call-home, 504 for
|
||||
silence, 502 for a bad reply, 503 for a lost connection), and its detail
|
||||
says the frame was sent and names the audit record.
|
||||
|
||||
Without `serial`: the legacy behaviour above, unchanged.
|
||||
"""
|
||||
@@ -1912,9 +1934,31 @@ def device_monitor_stop(
|
||||
|
||||
With `serial`: the unit's identity is read first (a different unit is a 409,
|
||||
nothing sent), then its state; `dry_run` returns the planned frames and sends
|
||||
nothing; a live change is audited, verified by reading the state back, and
|
||||
never retried. The response is the ChangeResult (409 if the unit never
|
||||
reached the state, 502 if the ack was lost).
|
||||
nothing; a live change is audited (`GET /db/device_commands`), verified by
|
||||
reading the state back, and never retried. `even_if_already` sends even
|
||||
when the unit is already in the target state.
|
||||
|
||||
Statuses with `serial`:
|
||||
200 the ChangeResult: a dry run, a skip (already in the state), or a send
|
||||
read back as made
|
||||
409 ChangeResult: sent and acknowledged, but the unit never reached the
|
||||
state (`verified: mismatch`, every state seen kept); or, as an
|
||||
error, a different unit answered or its state was never measured
|
||||
(nothing sent either way)
|
||||
502 ChangeResult: the ack was lost but the unit could be read afterwards
|
||||
422 a malformed serial or address; 423 the unit is busy;
|
||||
501 no audit log is configured (nothing sent)
|
||||
503 the unit is calling home, or a call-home was already waiting before
|
||||
sending (nothing sent); or the audit log could not be written
|
||||
(nothing sent)
|
||||
500 the audit row could not be finished -- the detail says first what
|
||||
happened to the unit (sent and verified, nothing sent, ...)
|
||||
504 / 502 / 503 a link failure before anything was sent
|
||||
A failure AFTER the frame went out (or may have) -- the read-back failed,
|
||||
the ack was lost and the unit could not be read, or a call-home began --
|
||||
takes the status its cause would have had (503 for a call-home, 504 for
|
||||
silence, 502 for a bad reply, 503 for a lost connection), and its detail
|
||||
says the frame was sent and names the audit record.
|
||||
|
||||
Without `serial`: the legacy behaviour above, unchanged.
|
||||
"""
|
||||
@@ -3137,8 +3181,13 @@ def db_device_commands(
|
||||
) -> dict:
|
||||
"""
|
||||
The audit trail of changes SFM attempted on units, newest first.
|
||||
|
||||
Each row's `sent` says whether a frame went out (1 acknowledged, 0 nothing
|
||||
sent, null unknown) and `states` holds every state read (before / seen /
|
||||
after). `serial` is matched case-insensitively.
|
||||
"""
|
||||
return {"commands": _get_db().query_device_commands(serial, limit)}
|
||||
serial = normalise_serial(serial) if serial else None
|
||||
return {"commands": _get_db().query_device_commands(serial or None, limit)}
|
||||
|
||||
|
||||
# ── Entry point ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -108,9 +108,11 @@ class FakeMiniMateClient(_Base):
|
||||
def get_monitor_status(self) -> MonitorStatus:
|
||||
self._step("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
|
||||
return MonitorStatus(
|
||||
is_monitoring=state, battery_v=6.8,
|
||||
memory_total=983026, memory_free=900000,
|
||||
is_monitoring=flag == 0x10, battery_v=6.8,
|
||||
memory_total=983026, memory_free=900000, state_flag=flag,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -14,7 +14,8 @@ from sfm.device_access.s4 import RingDetected # no
|
||||
from device_access_fakes import FakeMicromateClient # noqa: E402
|
||||
from sfm.device_access.access import DeviceAccess # noqa: E402
|
||||
from sfm.device_access.errors import ( # noqa: E402
|
||||
AuditUnavailable, CallHomeInProgress, DeviceError, NoAnswer, NotSupported, UnitStateUnknown, WrongUnit,
|
||||
AuditIncomplete, AuditUnavailable, CallHomeInProgress, ChangeUnconfirmed, ConnectFailed, DeviceError,
|
||||
NotSupported, UnitStateUnknown, WrongUnit,
|
||||
)
|
||||
from sfm.device_access.models import UnitAddress # noqa: E402
|
||||
|
||||
@@ -40,6 +41,21 @@ def access(fake, audit="default"):
|
||||
sleep=lambda s: None, verify_timeout_s=6.0, verify_interval_s=2.0)
|
||||
|
||||
|
||||
def unconfirmed(excinfo, da, *, sent, status):
|
||||
"""A failure after the send: it names the one audit row, says a frame went
|
||||
out (or may have), and carries its cause's status. Returns the row."""
|
||||
((cid, row),) = da._audit.rows.items()
|
||||
e = excinfo.value
|
||||
assert (e.audit_id, e.sent, e.http_status) == (cid, sent, status)
|
||||
assert f"audit record {cid}" in str(e)
|
||||
assert "was sent" in str(e) and "nothing sent" not in str(e)
|
||||
return row
|
||||
|
||||
|
||||
def released(fake, da):
|
||||
return fake.is_open() is False and ADDR.key not in da._sessions
|
||||
|
||||
|
||||
def test_a_dry_run_returns_the_exact_frames_and_sends_nothing():
|
||||
fake = FakeMicromateClient(run_states=[0x00])
|
||||
da = access(fake)
|
||||
@@ -149,50 +165,64 @@ def test_a_read_back_that_fails_still_finishes_the_audit_row():
|
||||
raise mm_proto.TimeoutError("dropped")
|
||||
return orig()
|
||||
fake.read_run_state = flaky
|
||||
with pytest.raises(Exception):
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = da._audit.rows.values()
|
||||
row = unconfirmed(e, da, sent="acknowledged", status=504)
|
||||
assert "sent and acknowledged" in str(e.value) and "dropped" in str(e.value)
|
||||
assert len(fake.executed) == 1
|
||||
assert (row["outcome"], row["verified"]) == ("sent", "not_checked")
|
||||
assert row["ack"] is not None
|
||||
assert "reading the state back failed" in row["error"]
|
||||
assert row["sent"] == 1
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
|
||||
|
||||
def test_a_ring_in_place_of_the_ack_is_a_call_home_not_a_send():
|
||||
fake = FakeMicromateClient(run_states=[0x00], execute_error=RingDetected("RADIO RING"))
|
||||
da = access(fake)
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
row = unconfirmed(e, da, sent="unknown", status=503)
|
||||
assert "hung up so the call can reach THOR" in str(e.value)
|
||||
assert "whether it started is unknown" in str(e.value)
|
||||
assert len(fake.executed) == 1
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
|
||||
assert "call-home began in place of the ack" in row["error"]
|
||||
assert row["sent"] is None
|
||||
|
||||
|
||||
def test_calling_home_seen_while_polling_releases_the_line():
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x03])
|
||||
da = access(fake)
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
row = unconfirmed(e, da, sent="acknowledged", status=503)
|
||||
assert "hung up so the call can reach THOR" in str(e.value)
|
||||
assert len(fake.executed) == 1
|
||||
assert fake.calls.count("read_run_state") == 2 # the read before + the one poll
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"]) == ("sent", "not_checked")
|
||||
assert row["ack"] is not None
|
||||
assert row["sent"] == 1
|
||||
assert row["states"] == {"before": "idle", "seen": ["idle", "calling_home"],
|
||||
"after": "calling_home"}
|
||||
|
||||
|
||||
def test_calling_home_after_a_lost_ack_releases_the_line():
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x03],
|
||||
execute_error=mm_proto.TimeoutError("no ack"))
|
||||
da = access(fake)
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert fake.is_open() is False
|
||||
(row,) = da._audit.rows.values()
|
||||
row = unconfirmed(e, da, sent="unknown", status=503)
|
||||
assert "acknowledgement was lost" in str(e.value)
|
||||
assert "whether it started is unknown" in str(e.value)
|
||||
assert "hung up so the call can reach THOR" in str(e.value)
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
|
||||
assert row["sent"] is None
|
||||
assert row["states"] == {"before": "idle", "seen": ["idle"], "after": "calling_home"}
|
||||
|
||||
|
||||
def test_a_refusal_by_execute_is_not_a_send():
|
||||
@@ -227,10 +257,13 @@ def test_lost_ack_and_failed_follow_up_read_on_a_held_line_releases_it():
|
||||
raise mm_proto.TimeoutError("gone")
|
||||
return orig()
|
||||
fake.read_run_state = flaky
|
||||
with pytest.raises(NoAnswer):
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
row = unconfirmed(e, da, sent="unknown", status=504)
|
||||
assert "acknowledgement was lost" in str(e.value) and "gone" in str(e.value)
|
||||
assert len(fake.executed) == 1
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", None)
|
||||
|
||||
|
||||
def test_a_live_change_in_an_unmeasured_state_is_refused_but_a_dry_run_is_not():
|
||||
@@ -261,12 +294,14 @@ def test_a_ring_on_the_follow_up_read_after_a_lost_ack_finishes_the_row():
|
||||
raise RingDetected("RADIO RING")
|
||||
return orig()
|
||||
fake.read_run_state = ringing
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
row = unconfirmed(e, da, sent="unknown", status=503)
|
||||
assert "hung up so the call can reach THOR" in str(e.value)
|
||||
assert len(fake.executed) == 1
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"]) == ("failed", "not_checked")
|
||||
assert "a call-home began" in row["error"]
|
||||
assert row["sent"] is None
|
||||
assert fake.is_open() is False and ADDR.key not in da._sessions
|
||||
|
||||
|
||||
@@ -312,6 +347,11 @@ def test_series3_dry_run_returns_its_own_frame_and_sends_nothing():
|
||||
assert (r.series, r.outcome, r.state_before) == (3, "dry_run", "idle")
|
||||
assert r.plan["steps"][0]["sub"] == "0x96" and fake.writes == []
|
||||
assert r.plan["steps"][0]["expect_ack"] == "0x69" and r.plan["sends_nothing"] is True
|
||||
assert r.plan["steps"][0]["frame"] == "41021010009600000000000000000000000000a603"
|
||||
stop = access3(FakeMiniMateClient(monitor_states=[True])).stop_monitoring(
|
||||
TCP3, "BE18193", dry_run=True)
|
||||
assert stop.plan["steps"][0]["frame"] == "41021010009700000000000000000000000000a703"
|
||||
assert stop.plan["steps"][0]["expect_ack"] == "0x68" and stop.outcome == "dry_run"
|
||||
|
||||
|
||||
def test_series3_start_is_verified_by_monitor_status():
|
||||
@@ -321,6 +361,7 @@ def test_series3_start_is_verified_by_monitor_status():
|
||||
assert (r.outcome, r.verified, r.state_after) == ("sent", "ok", "monitoring")
|
||||
assert fake.writes == ["start_monitoring"]
|
||||
assert da._audit.rows[r.audit_id]["ack"] == {"subs": ["0x69"]}
|
||||
assert da.factory_calls == [{"timeout": 120.0}]
|
||||
|
||||
|
||||
def test_series3_stop_acks_0x68():
|
||||
@@ -338,7 +379,7 @@ def test_series3_wrong_unit_is_refused_before_writing():
|
||||
assert fake.writes == []
|
||||
|
||||
|
||||
def test_series3_a_lost_ack_is_never_retried_even_over_tcp():
|
||||
def test_series3_a_lost_ack_with_a_good_read_back_is_one_write():
|
||||
fake = FakeMiniMateClient(monitor_states=[False, True],
|
||||
write_error=mmp_proto.TimeoutError("no ack"))
|
||||
da = access3(fake)
|
||||
@@ -375,9 +416,9 @@ def test_series3_a_failing_read_back_is_audited_then_raised():
|
||||
raise mmp_proto.TimeoutError("quiet")
|
||||
return real()
|
||||
fake.get_monitor_status = flaky
|
||||
with pytest.raises(NoAnswer):
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(TCP3, "BE18193")
|
||||
row = next(iter(da._audit.rows.values()))
|
||||
row = unconfirmed(e, da, sent="acknowledged", status=504)
|
||||
assert (row["outcome"], row["verified"]) == ("sent", "not_checked")
|
||||
assert "reading the state back failed" in row["error"]
|
||||
assert fake.writes == ["start_monitoring"]
|
||||
@@ -405,12 +446,251 @@ def test_series3_lost_ack_with_unreadable_follow_up_raises_and_is_not_retried():
|
||||
raise mmp_proto.TimeoutError("still quiet")
|
||||
return real()
|
||||
fake.get_monitor_status = second_fails
|
||||
with pytest.raises(NoAnswer):
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(TCP3, "BE18193")
|
||||
row = unconfirmed(e, da, sent="unknown", status=504)
|
||||
assert fake.writes == ["start_monitoring"]
|
||||
assert len(da.factory_calls) == 1 # no second TCP attempt
|
||||
row = next(iter(da._audit.rows.values()))
|
||||
assert row["outcome"] == "failed"
|
||||
|
||||
# The other Series-3 operations still retry once over TCP on a cold unit:
|
||||
# tests/test_device_access_s3.py::test_a_cold_unit_over_tcp_gets_one_retry.
|
||||
|
||||
|
||||
# ── final fix wave: after-send honesty, the audit row, pre-send ring, S3 states ──
|
||||
|
||||
from sfm.audit import DbAudit # noqa: E402
|
||||
from sfm.database import SeismoDb # noqa: E402
|
||||
|
||||
|
||||
def test_a_lost_stop_ack_then_a_call_home_says_whether_it_stopped_is_unknown():
|
||||
fake = FakeMicromateClient(run_states=[0x02, 0x03],
|
||||
execute_error=mm_proto.TimeoutError("no ack"))
|
||||
da = access(fake)
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.stop_monitoring(ADDR, "UM20147")
|
||||
unconfirmed(e, da, sent="unknown", status=503)
|
||||
assert str(e.value).startswith("stop monitoring was sent but the acknowledgement was lost")
|
||||
assert "whether it stopped is unknown" in str(e.value)
|
||||
assert released(fake, da)
|
||||
|
||||
|
||||
def test_a_ring_on_a_read_back_poll_is_unconfirmed_and_releases_the_line():
|
||||
fake = FakeMicromateClient(run_states=[0x00])
|
||||
da = access(fake)
|
||||
orig, n = fake.read_run_state, []
|
||||
|
||||
def ringing():
|
||||
n.append(1)
|
||||
if len(n) == 2: # the first read-back poll
|
||||
raise RingDetected("RADIO RING")
|
||||
return orig()
|
||||
fake.read_run_state = ringing
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
row = unconfirmed(e, da, sent="acknowledged", status=503)
|
||||
assert "hung up so the call can reach THOR" in str(e.value)
|
||||
assert len(fake.executed) == 1
|
||||
assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "not_checked", 1)
|
||||
assert row["ack"] is not None and "call-home began" in row["error"]
|
||||
assert released(fake, da)
|
||||
|
||||
|
||||
def test_a_ring_already_waiting_before_the_send_sends_nothing():
|
||||
fake = FakeMicromateClient(run_states=[0x00])
|
||||
|
||||
def buffered_ring():
|
||||
fake.calls.append("read_unsolicited")
|
||||
raise RingDetected("RADIO RING")
|
||||
fake.read_unsolicited = buffered_ring
|
||||
da = access(fake)
|
||||
with pytest.raises(CallHomeInProgress) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert not isinstance(e.value, ChangeUnconfirmed)
|
||||
assert fake.executed == []
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", 0)
|
||||
assert row["error"] == "a call-home began before sending -- nothing sent"
|
||||
assert released(fake, da)
|
||||
|
||||
|
||||
def test_the_pre_send_drain_runs_after_the_state_read_and_before_the_send():
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x02])
|
||||
access(fake).start_monitoring(ADDR, "UM20147")
|
||||
assert fake.calls.index("read_unsolicited") > fake.calls.index("read_run_state")
|
||||
assert fake.calls.index("read_unsolicited") < fake.calls.index("execute")
|
||||
|
||||
|
||||
def test_a_skip_does_not_drain_the_line():
|
||||
fake = FakeMicromateClient(run_states=[0x02])
|
||||
access(fake).start_monitoring(ADDR, "UM20147")
|
||||
assert "read_unsolicited" not in fake.calls
|
||||
|
||||
|
||||
def test_a_link_fault_on_the_pre_send_drain_sends_nothing_and_finishes_the_row():
|
||||
fake = FakeMicromateClient(run_states=[0x00])
|
||||
|
||||
def dead():
|
||||
raise OSError("connection reset")
|
||||
fake.read_unsolicited = dead
|
||||
da = access(fake)
|
||||
with pytest.raises(ConnectFailed):
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert fake.executed == []
|
||||
(row,) = da._audit.rows.values()
|
||||
assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "not_checked", 0)
|
||||
assert "nothing sent" in row["error"]
|
||||
assert released(fake, da)
|
||||
|
||||
|
||||
class FinishFails(Audit):
|
||||
def finish(self, cid, **f):
|
||||
raise OSError("disk full")
|
||||
|
||||
|
||||
def test_a_finish_that_fails_after_a_verified_send_is_audit_incomplete_and_keeps_the_line():
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x02])
|
||||
da = access(fake, audit=FinishFails())
|
||||
with pytest.raises(AuditIncomplete) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
assert e.value.http_status == 500
|
||||
assert "start monitoring was sent and verified" in str(e.value)
|
||||
assert "audit record c1 could not be finished: disk full" in str(e.value)
|
||||
assert len(fake.executed) == 1
|
||||
assert fake.is_open() is True and da.held_serial(ADDR) == "UM20147"
|
||||
|
||||
|
||||
def test_a_finish_that_fails_on_a_skip_says_nothing_was_sent():
|
||||
fake = FakeMicromateClient(run_states=[0x02])
|
||||
with pytest.raises(AuditIncomplete, match="nothing was sent .*already monitoring"):
|
||||
access(fake, audit=FinishFails()).start_monitoring(ADDR, "UM20147")
|
||||
assert fake.executed == []
|
||||
|
||||
|
||||
def test_a_finish_that_fails_while_unconfirmed_keeps_the_unit_outcome():
|
||||
fake = FakeMicromateClient(run_states=[0x00], execute_error=RingDetected("RADIO RING"))
|
||||
with pytest.raises(AuditIncomplete) as e:
|
||||
access(fake, audit=FinishFails()).start_monitoring(ADDR, "UM20147")
|
||||
assert "start monitoring was sent" in str(e.value)
|
||||
assert "whether it started is unknown" in str(e.value)
|
||||
assert "could not be finished: disk full" in str(e.value)
|
||||
|
||||
|
||||
def test_even_if_already_notes_that_the_read_back_proves_nothing():
|
||||
fake = FakeMicromateClient(run_states=[0x02])
|
||||
da = access(fake)
|
||||
r = da.start_monitoring(ADDR, "UM20147", even_if_already=True)
|
||||
note = ("the unit was already monitoring before sending; the read-back cannot show "
|
||||
"that this send changed anything")
|
||||
assert (r.outcome, r.verified) == ("sent", "ok")
|
||||
assert r.detail["note"] == note
|
||||
assert da._audit.rows[r.audit_id]["error"] == note
|
||||
|
||||
|
||||
def test_without_even_if_already_there_is_no_note():
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x02])
|
||||
da = access(fake)
|
||||
r = da.start_monitoring(ADDR, "UM20147")
|
||||
assert "note" not in r.detail and da._audit.rows[r.audit_id]["error"] is None
|
||||
|
||||
|
||||
# -- the audit row records whether a frame went out, and the states, in the real DB
|
||||
|
||||
def db_access(fake, tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
da = access(fake, audit=DbAudit(lambda: db))
|
||||
return da, db
|
||||
|
||||
|
||||
def test_db_row_for_a_skip_says_nothing_was_sent(tmp_path):
|
||||
da, db = db_access(FakeMicromateClient(run_states=[0x02]), tmp_path)
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = db.query_device_commands()
|
||||
assert (row["outcome"], row["sent"]) == ("skipped", 0)
|
||||
assert row["states"] == {"before": "monitoring", "seen": ["monitoring"], "after": None}
|
||||
|
||||
|
||||
def test_db_row_for_a_verified_send(tmp_path):
|
||||
da, db = db_access(FakeMicromateClient(run_states=[0x00, 0x00, 0x02]), tmp_path)
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = db.query_device_commands()
|
||||
assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "ok", 1)
|
||||
assert row["states"] == {"before": "idle", "seen": ["idle", "idle", "monitoring"],
|
||||
"after": "monitoring"}
|
||||
|
||||
|
||||
def test_db_row_for_a_mismatch(tmp_path):
|
||||
da, db = db_access(FakeMicromateClient(run_states=[0x00]), tmp_path)
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = db.query_device_commands()
|
||||
assert (row["outcome"], row["verified"], row["sent"]) == ("failed", "mismatch", 1)
|
||||
assert row["states"] == {"before": "idle", "seen": ["idle"] * 4, "after": "idle"}
|
||||
|
||||
|
||||
def test_db_row_for_a_lost_ack_with_a_readable_follow_up(tmp_path):
|
||||
fake = FakeMicromateClient(run_states=[0x00, 0x02], execute_error=mm_proto.TimeoutError("no ack"))
|
||||
da, db = db_access(fake, tmp_path)
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = db.query_device_commands()
|
||||
assert (row["outcome"], row["sent"]) == ("failed", None)
|
||||
assert row["states"] == {"before": "idle", "seen": ["idle"], "after": "monitoring"}
|
||||
|
||||
|
||||
def test_db_row_for_a_read_back_failure(tmp_path):
|
||||
fake = FakeMicromateClient(run_states=[0x00])
|
||||
orig, n = fake.read_run_state, []
|
||||
|
||||
def flaky():
|
||||
n.append(1)
|
||||
if len(n) == 3: # the second read-back poll
|
||||
raise mm_proto.TimeoutError("dropped")
|
||||
return orig()
|
||||
fake.read_run_state = flaky
|
||||
da, db = db_access(fake, tmp_path)
|
||||
with pytest.raises(ChangeUnconfirmed) as e:
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = db.query_device_commands()
|
||||
assert e.value.audit_id == row["id"]
|
||||
assert (row["outcome"], row["verified"], row["sent"]) == ("sent", "not_checked", 1)
|
||||
assert row["states"] == {"before": "idle", "seen": ["idle", "idle"], "after": "idle"}
|
||||
|
||||
|
||||
def test_db_row_for_a_pre_send_ring_says_nothing_was_sent(tmp_path):
|
||||
fake = FakeMicromateClient(run_states=[0x00])
|
||||
|
||||
def buffered_ring():
|
||||
raise RingDetected("RADIO RING")
|
||||
fake.read_unsolicited = buffered_ring
|
||||
da, db = db_access(fake, tmp_path)
|
||||
with pytest.raises(CallHomeInProgress):
|
||||
da.start_monitoring(ADDR, "UM20147")
|
||||
(row,) = db.query_device_commands()
|
||||
assert (row["outcome"], row["sent"]) == ("failed", 0)
|
||||
|
||||
|
||||
# -- Series 3: the raw state byte, never collapsed into "idle" ----------------------
|
||||
|
||||
def test_series3_an_unmeasured_state_byte_is_refused_with_nothing_written():
|
||||
fake = FakeMiniMateClient(monitor_states=[0x07])
|
||||
da = access3(fake)
|
||||
with pytest.raises(UnitStateUnknown, match="0x07"):
|
||||
da.start_monitoring(TCP3, "BE18193")
|
||||
assert fake.writes == [] and da._audit.rows == {}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("flag,state", [(0x00, "idle"), (0x10, "monitoring"),
|
||||
(0x07, "unknown(0x07)"), (None, "unknown(short)")])
|
||||
def test_series3_state_names_come_from_the_raw_flag(flag, state):
|
||||
fake = FakeMiniMateClient(monitor_states=[flag])
|
||||
r = access3(fake).start_monitoring(TCP3, "BE18193", dry_run=True)
|
||||
assert r.state_before == state
|
||||
|
||||
|
||||
def test_series3_monitor_status_decode_keeps_the_raw_flag():
|
||||
from minimateplus.client import _decode_monitor_status
|
||||
tail = bytes.fromhex("02a8000effc0000e9e52") # battery + memory: the last 10 bytes
|
||||
for flag, monitoring in ((0x00, False), (0x10, True), (0x07, False)):
|
||||
st = _decode_monitor_status(bytes(11) + bytes([0x00, flag]) + bytes(34) + tail)
|
||||
assert (st.state_flag, st.is_monitoring) == (flag, monitoring)
|
||||
assert _decode_monitor_status(bytes(12)).state_flag is None # no section[1]
|
||||
assert _decode_monitor_status(b"").state_flag is None
|
||||
@@ -62,3 +62,62 @@ def test_a_second_finish_raises_and_keeps_the_first_result(tmp_path):
|
||||
row = db.query_device_commands()[0]
|
||||
assert (row["outcome"], row["verified"], row["ack"], row["error"]) == \
|
||||
("failed", "mismatch", {"subs": ["0x69"]}, "unit reads idle")
|
||||
|
||||
|
||||
def test_a_finish_records_whether_a_frame_went_out_and_the_states(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
states = {"before": "idle", "seen": ["idle", "monitoring"], "after": "monitoring"}
|
||||
cid = db.begin_device_command(**ROW)
|
||||
db.finish_device_command(cid, outcome="sent", verified="ok", ack={"subs": ["0x69"]},
|
||||
error=None, sent=1, states=states)
|
||||
row = db.query_device_commands()[0]
|
||||
assert (row["sent"], row["states"]) == (1, states)
|
||||
|
||||
|
||||
def test_sent_and_states_default_to_null(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
cid = db.begin_device_command(**ROW)
|
||||
db.finish_device_command(cid, outcome="failed", verified="not_checked", ack=None,
|
||||
error="no clean ack")
|
||||
row = db.query_device_commands()[0]
|
||||
assert (row["sent"], row["states"]) == (None, None)
|
||||
|
||||
|
||||
def test_db_audit_passes_sent_and_states_through(tmp_path):
|
||||
db = SeismoDb(tmp_path / "s.db")
|
||||
audit = DbAudit(lambda: db)
|
||||
cid = audit.begin(**ROW)
|
||||
audit.finish(cid, outcome="skipped", verified="not_checked", ack=None, error="already idle",
|
||||
sent=0, states={"before": "idle", "seen": ["idle"], "after": None})
|
||||
row = db.query_device_commands()[0]
|
||||
assert row["sent"] == 0 and row["states"]["before"] == "idle"
|
||||
|
||||
|
||||
# The device_commands table as Task 3 created it: no `sent`, no `states`.
|
||||
_TASK3_TABLE = """
|
||||
CREATE TABLE device_commands (
|
||||
id TEXT PRIMARY KEY, ts TEXT NOT NULL, finished_ts TEXT, serial TEXT NOT NULL,
|
||||
series INTEGER NOT NULL, address TEXT NOT NULL, action TEXT NOT NULL, tier TEXT NOT NULL,
|
||||
request TEXT, ack TEXT, verified TEXT, outcome TEXT NOT NULL, error TEXT, caller TEXT
|
||||
);
|
||||
INSERT INTO device_commands (id, ts, serial, series, address, action, tier, outcome)
|
||||
VALUES ('old', '2026-10-22T00:00:00+00:00', 'UM20147', 4, 'tcp:x', 'stop monitoring',
|
||||
'change', 'pending');
|
||||
"""
|
||||
|
||||
|
||||
def test_an_existing_task3_table_gains_sent_and_states(tmp_path):
|
||||
import sqlite3
|
||||
path = tmp_path / "s.db"
|
||||
with sqlite3.connect(path) as conn:
|
||||
conn.executescript(_TASK3_TABLE)
|
||||
db = SeismoDb(path)
|
||||
with sqlite3.connect(path) as conn:
|
||||
cols = {r[1] for r in conn.execute("PRAGMA table_info(device_commands)")}
|
||||
assert {"sent", "states"} <= cols
|
||||
old = db.query_device_commands()[0]
|
||||
assert (old["id"], old["sent"], old["states"]) == ("old", None, None)
|
||||
db.finish_device_command("old", outcome="failed", verified="not_checked", ack=None,
|
||||
error="x", sent=0, states={"before": "idle", "seen": ["idle"], "after": None})
|
||||
assert db.query_device_commands()[0]["sent"] == 0
|
||||
SeismoDb(path) # a second open is a no-op
|
||||
@@ -611,3 +611,27 @@ def test_serial_refresh_reads_the_unit_again():
|
||||
mm._serial = "UM99999" # a stale cached serial
|
||||
assert mm.serial(refresh=True) == "UM20147"
|
||||
assert len(t.written) == 1
|
||||
assert mm._serial == "UM20147" # the cache took the fresh read
|
||||
assert mm.serial() == "UM20147" and len(t.written) == 1 # and a plain read sends nothing
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [b"", bytes(11)])
|
||||
def test_an_empty_or_short_0x49_reply_raises(data):
|
||||
mm, _t = client([frame(0xB6, data)])
|
||||
with pytest.raises(ProtocolError, match="no content"):
|
||||
mm.read_run_state()
|
||||
|
||||
|
||||
def test_reading_unsolicited_bytes_keeps_executes_fresh_reply_precondition():
|
||||
"""The change path drains the line between its state read and its send. A
|
||||
raw transport read never goes through `_send`, so the trust `execute`
|
||||
needs survives it."""
|
||||
from micromate.protocol import ACK_DATA_LEN
|
||||
from micromate.writes import plan_start_monitoring
|
||||
mm, t = client([frame(0xB6, bytes(11) + bytes([0x00]) + bytes(4)), b"\x00\xff stray",
|
||||
frame(0x69, bytes(ACK_DATA_LEN))])
|
||||
assert mm.read_run_state().name == "idle"
|
||||
assert mm.read_unsolicited() == b"\x00\xff stray"
|
||||
assert mm.protocol.last_flags == FLAGS_CB
|
||||
acks = mm.protocol.execute(plan_start_monitoring())
|
||||
assert [a.sub for a in acks] == [0x69] and len(t.written) == 2
|
||||
@@ -231,17 +231,55 @@ def test_the_scanner_ignores_ordinary_calls():
|
||||
assert scan_source("p._send(frame)\nf(a, b=1)") == []
|
||||
|
||||
|
||||
def test_only_protocol_py_grants_write_permission():
|
||||
def scan_file(scanner, src: str, rel: str) -> list[str]:
|
||||
"""Fails closed: a file the scanner cannot parse is a hit, not a pass."""
|
||||
try:
|
||||
return scanner(src, rel)
|
||||
except SyntaxError as exc:
|
||||
return [f"{rel}: does not parse, so it cannot be scanned ({exc})"]
|
||||
|
||||
|
||||
def scan_tracked(scanner, skip) -> list[str]:
|
||||
root = pathlib.Path(__file__).resolve().parent.parent
|
||||
files = subprocess.run(["git", "ls-files", "*.py"], cwd=root, capture_output=True,
|
||||
text=True, check=True).stdout.split()
|
||||
hits = []
|
||||
for rel in files:
|
||||
if rel.startswith("tests/") or rel == "micromate/protocol.py":
|
||||
if rel.startswith("tests/") or skip(rel):
|
||||
continue
|
||||
try:
|
||||
src = (root / rel).read_text(errors="ignore")
|
||||
hits += scan_source(src, rel)
|
||||
except SyntaxError:
|
||||
pass
|
||||
assert hits == []
|
||||
hits += scan_file(scanner, (root / rel).read_text(errors="ignore"), rel)
|
||||
return hits
|
||||
|
||||
|
||||
def test_a_file_that_does_not_parse_fails_the_scan():
|
||||
assert scan_file(scan_source, "def broken(:\n", "x.py")
|
||||
assert scan_file(scan_execute_callers, "def broken(:\n", "x.py")
|
||||
|
||||
|
||||
def test_only_protocol_py_grants_write_permission():
|
||||
assert scan_tracked(scan_source, lambda rel: rel == "micromate/protocol.py") == []
|
||||
|
||||
|
||||
# -- nothing outside the safety layer calls protocol.execute( -------------------
|
||||
|
||||
def scan_execute_callers(src: str, name: str = "<s>") -> list[str]:
|
||||
"""Hits: any `<x>.protocol.execute(...)` call -- the Series-4 write entry."""
|
||||
hits = []
|
||||
for node in ast.walk(ast.parse(src)):
|
||||
if not isinstance(node, ast.Call):
|
||||
continue
|
||||
fn = node.func
|
||||
if (isinstance(fn, ast.Attribute) and fn.attr == "execute"
|
||||
and isinstance(fn.value, ast.Attribute) and fn.value.attr == "protocol"):
|
||||
hits.append(f"{name}:{node.lineno} .protocol.execute call")
|
||||
return hits
|
||||
|
||||
|
||||
def test_the_execute_scanner_catches_a_protocol_execute_and_not_sqlite():
|
||||
assert scan_execute_callers("client.protocol.execute(plan)")
|
||||
assert scan_execute_callers("conn.execute('SELECT 1')") == []
|
||||
|
||||
|
||||
def test_only_the_safety_layer_calls_protocol_execute():
|
||||
assert scan_tracked(scan_execute_callers,
|
||||
lambda rel: rel == "sfm/device_access/s4.py") == []
|
||||
@@ -398,3 +398,27 @@ def test_monitor_without_a_serial_runs_the_legacy_path_unchanged(monkeypatch, fn
|
||||
monkeypatch.setattr(srv, "_build_client", legacy_client)
|
||||
with pytest.raises(Legacy):
|
||||
getattr(srv, fn)(**{**CH, "serial": None})
|
||||
|
||||
|
||||
def test_a_change_unconfirmed_keeps_its_cause_status_and_names_the_audit_record(monkeypatch):
|
||||
from sfm.device_access.errors import ChangeUnconfirmed
|
||||
|
||||
class Raises:
|
||||
def start_monitoring(self, *a, **kw):
|
||||
raise ChangeUnconfirmed(
|
||||
"start monitoring was sent and acknowledged, but reading the state back "
|
||||
"failed: silent -- audit record c7", audit_id="c7", sent="acknowledged",
|
||||
http_status=504)
|
||||
monkeypatch.setattr(srv, "_device_access_instance", Raises())
|
||||
with pytest.raises(HTTPException) as e:
|
||||
srv.device_monitor_start(**CH)
|
||||
assert e.value.status_code == 504
|
||||
assert "audit record c7" in e.value.detail
|
||||
|
||||
|
||||
def test_device_commands_normalises_the_serial(tmp_path, monkeypatch):
|
||||
db = SeismoDb(tmp_path / "seismo.db")
|
||||
db.begin_device_command(serial="UM20147", series=4, address="tcp:10.0.0.5:9034",
|
||||
action="start monitoring", tier="change", request={}, caller="test")
|
||||
monkeypatch.setattr(srv, "_get_db", lambda: db)
|
||||
assert len(srv.db_device_commands(serial=" um20147 ", limit=100)["commands"]) == 1
|
||||
Reference in new issue
Block a user