docs: sample run-history backend handoff for the DB team

Consolidates the data-source analysis (aareDB Sample.events), the tested mapping
module reference, draft backend additions (aaredb/daq/server/daq_worker), and the
open questions (beamtime_id resolution, whether the WS payload already carries
events, event->stage mapping confirmation).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
appleb_mandClaude Opus 4.8 committed 2026-06-26 11:47:46 +02:00
1 parent 161ddfc759
commit b4a4cb2d61
1 file changed
+89
+89
View File
@@ -0,0 +1,89 @@
# Sample run-history — backend handoff (DRAFT)
Goal: let the GUI show, per sample, its previous runs as a 6-stage LED strip
(Mount · Center · Raster · XRF · Collect · Process) with errors, and a per-row
LED summary of the **latest** run.
## Data source — no aareDB schema change needed
The history is the sample's **event stream**, already in aareDB:
- `SamplesRunnerApi.get_samples_by_beamtime(beamtime_id) -> List[Sample]`
- `Sample.events: List[SampleEventResponse]` with `event_type`, `comment`, `timestamp`
- Relevant `SampleEventType`s (already emitted by the DAQ): `Mounting/Mounted/MountFailed`,
`Centering/Centered/ALCFailed/AXCFailed`, `Rastering/Rastered/RasteringFailed`,
`FScan`, `Collecting/Collected/CollectionFailed`, `Characterizing/Characterized`,
`Unmounting/Unmounted`, `AutomationStart/End/Failed`.
**Gap today:** samples reach the GUI via the WebSocket puck feed
(`spreadsheetupdater.py`), which maps to `SampleShortInfo` and **drops `events`**;
`get_samples_by_beamtime` is not called anywhere yet. So a read path is needed.
## Done & tested: the mapping
`src/aare/common/sample_history.py` — `build_sample_history(sample_id, name, events)`
groups events into runs (mount cycles), maps each to per-stage outcomes, surfaces
errors, and returns `latest_stages` for the per-row LEDs. Pure + unit-tested.
Transport models (`SampleHistory` / `SampleRunRecord` / `SampleRunStage`) are
shared by server and GUI.
## Draft additions (untested against live aareDB)
**aaredb.py (AareWrapper):**
```python
def get_sample_events(self, sample_id: int, beamtime_id: int):
samples = self.__sample_api.get_samples_by_beamtime(beamtime_id)
s = next((x for x in samples if x.id == sample_id), None)
return (s.sample_name if s else ""), ((s.events or []) if s else [])
```
**daq.py (AareDAQ):**
```python
def get_sample_history(self, sample_id: int):
from aare.common.sample_history import build_sample_history
beamtime_id = self._current_beamtime_id() # TODO: how is this resolved?
name, events = self.__aare.get_sample_events(sample_id, beamtime_id)
return build_sample_history(sample_id, name, events)
```
**server.py:**
```python
@app.get("/sample/{sample_id}/history")
async def sample_history(sample_id: int, token: str = Depends(oauth2_scheme)):
auth.check_jwt_ro(cfg, auth.parse_token(token))
return await run_in_threadpool(daq.get_sample_history, sample_id) # -> SampleHistory
```
**daq_worker.py (GUI) — matches `load_spreadsheet`:**
```python
sample_history_loaded = Signal(object) # SampleHistory
@Slot(int)
def sample_history(self, db_id: int):
if self.__base_url is None:
logger.info(f"GET /sample/{db_id}/history"); return
req = QNetworkRequest(QUrl(f"{self.__base_url}/sample/{db_id}/history"))
req.setRawHeader(b"Authorization", f"Bearer {self.__token}".encode())
reply = self.__net_manager.get(req)
reply.finished.connect(lambda: self._handle_sample_history(reply))
def _handle_sample_history(self, reply):
from aare.common.sample_history import SampleHistory
try:
self.sample_history_loaded.emit(
SampleHistory.model_validate_json(bytes(reply.readAll().data())))
except Exception as e:
logger.warning(f"sample history parse failed: {e}")
```
## Open questions for the DB team
1. **`beamtime_id` resolution** — where does the current beamtime id live (config /
session / Redis)? `get_samples_by_beamtime` requires it.
2. **Cheaper path?** — does the WebSocket puck payload's sample object already carry
`.events`? If so, pass them through `spreadsheetupdater.py` into the cache and
skip the per-request aareDB read (drops the need for the endpoint above).
3. Confirm the event→stage mapping in `sample_history.py::_STAGE_EVENTS` matches how
the DAQ actually emits events (esp. XRF=`FScan`, Process=`Characterized`).
## GUI side (ready when the above lands)
- `widgets/sample_history.py` renders the run cards + LED strips (mockup approved).
- Wiring plan: row click → `daq.sample_history(db_id)`; `sample_history_loaded` →
set the row's compact LEDs from `latest_stages` + inline-expand `runs`.