-
Notifications
You must be signed in to change notification settings - Fork 175
/
run_store.py
599 lines (495 loc) · 19.9 KB
/
run_store.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
"""Runs' on-db store."""
import logging
from collections import defaultdict
from dataclasses import dataclass
from datetime import datetime
from functools import lru_cache
from typing import Dict, List, Optional, Literal, Union
import sqlalchemy
from pydantic import ValidationError
from opentrons.util.helpers import utc_now
from opentrons.protocol_engine import StateSummary, CommandSlice
from opentrons.protocol_engine.commands import Command
from opentrons.protocol_engine.types import RunTimeParameter
from opentrons_shared_data.errors.exceptions import (
EnumeratedError,
PythonException,
InvalidStoredData,
)
from robot_server.persistence.database import sqlite_rowid
from robot_server.persistence.tables import (
run_table,
run_command_table,
action_table,
)
from robot_server.persistence.pydantic import (
json_to_pydantic,
pydantic_to_json,
json_to_pydantic_list,
pydantic_list_to_json,
)
from robot_server.protocols.protocol_store import ProtocolNotFoundError
from .action_models import RunAction, RunActionType
from .run_models import RunNotFoundError
log = logging.getLogger(__name__)
_CACHE_ENTRIES = 32
@dataclass(frozen=True)
class RunResource:
"""An entry in the run store, used to construct response models.
This represents all run data that cannot be derived from another
location, such as a ProtocolEngine instance.
"""
ok: Literal[True]
run_id: str
protocol_id: Optional[str]
created_at: datetime
actions: List[RunAction]
@dataclass(frozen=True)
class BadRunResource:
"""A representation for an action in the run store that cannot be loaded.
This will get created, for instance, when loading a run made in a future
version with an action that does not exist in the current version. This should
never happen in released versions, but it does sometimes during development,
and without handling like this it would cause any list-all request to fail.
The ok field is a union discriminator. Other elements will be filled in as they
can be with whatever data was recoverable and should not be relied upon.
"""
ok: Literal[False]
run_id: str
protocol_id: Optional[str]
created_at: datetime
actions: List[RunAction]
error: EnumeratedError
@dataclass(frozen=True)
class BadStateSummary:
"""A representation for a state summary that could not be loaded."""
dataError: EnumeratedError
class CommandNotFoundError(ValueError):
"""Error raised when a given command ID is not found in the store."""
def __init__(self, command_id: str) -> None:
"""Initialize the error message from the missing ID."""
super().__init__(f"Command {command_id} was not found.")
class RunStore:
"""Methods for storing and retrieving run resources."""
def __init__(
self,
sql_engine: sqlalchemy.engine.Engine,
) -> None:
"""Initialize a RunStore with sql engine and notification client."""
self._sql_engine = sql_engine
def update_run_state(
self,
run_id: str,
summary: StateSummary,
commands: List[Command],
run_time_parameters: List[RunTimeParameter],
) -> RunResource:
"""Update the run's state summary and commands list.
Args:
run_id: The run to update
summary: The run's equipment and status summary.
commands: The run's commands.
run_time_parameters: The run's run time parameters, if any.
Returns:
The run resource.
Raises:
RunNotFoundError: Run ID was not found in the database.
"""
update_run = (
sqlalchemy.update(run_table)
.where(run_table.c.id == run_id)
.values(
_convert_state_to_sql_values(
run_id=run_id,
state_summary=summary,
engine_status=summary.status,
run_time_parameters=run_time_parameters,
)
)
)
delete_existing_commands = sqlalchemy.delete(run_command_table).where(
run_command_table.c.run_id == run_id
)
insert_command = sqlalchemy.insert(run_command_table)
select_run_resource = sqlalchemy.select(*_run_columns).where(
run_table.c.id == run_id
)
select_actions = (
sqlalchemy.select(action_table)
.where(action_table.c.run_id == run_id)
.order_by(sqlite_rowid)
)
with self._sql_engine.begin() as transaction:
if not self._run_exists(run_id, transaction):
raise RunNotFoundError(run_id=run_id)
transaction.execute(update_run)
transaction.execute(delete_existing_commands)
for command_index, command in enumerate(commands):
transaction.execute(
insert_command,
{
"run_id": run_id,
"index_in_run": command_index,
"command_id": command.id,
"command": pydantic_to_json(command),
},
)
run_row = transaction.execute(select_run_resource).one()
action_rows = transaction.execute(select_actions).all()
self._clear_caches()
maybe_run_resource = _convert_row_to_run(row=run_row, action_rows=action_rows)
if not maybe_run_resource.ok:
raise maybe_run_resource.error
return maybe_run_resource
def insert_action(self, run_id: str, action: RunAction) -> None:
"""Insert a run action into the store.
Args:
run_id: Run to add the action to.
action: Action payload to persist.
Raises:
RunNotFoundError: The given run ID was not found in the store.
"""
insert = sqlalchemy.insert(action_table).values(
_convert_action_to_sql_values(run_id=run_id, action=action),
)
with self._sql_engine.begin() as transaction:
if not self._run_exists(run_id, transaction):
raise RunNotFoundError(run_id=run_id)
transaction.execute(insert)
self._clear_caches()
def insert(
self,
run_id: str,
created_at: datetime,
protocol_id: Optional[str],
) -> RunResource:
"""Insert run resource in the db.
Args:
run_id: Unique identifier to use for the run.
created_at: Run creation timestamp.
protocol_id: Protocol resource used by the run, if any.
Returns:
The resource that was added to the store.
Raises:
ProtocolNotFoundError: The given protocol ID was not
found in the store.
"""
run = RunResource(
ok=True,
run_id=run_id,
created_at=created_at,
protocol_id=protocol_id,
actions=[],
)
insert = sqlalchemy.insert(run_table).values(
_convert_run_to_sql_values(run=run)
)
with self._sql_engine.begin() as transaction:
try:
transaction.execute(insert)
except sqlalchemy.exc.IntegrityError:
assert (
run.protocol_id is not None
), "Insert run failed due to unexpected IntegrityError"
raise ProtocolNotFoundError(protocol_id=run.protocol_id)
self._clear_caches()
return run
@lru_cache(maxsize=_CACHE_ENTRIES)
def has(self, run_id: str) -> bool:
"""Whether a given run exists in the store."""
with self._sql_engine.begin() as transaction:
return self._run_exists(run_id, transaction)
@lru_cache(maxsize=_CACHE_ENTRIES)
def get(self, run_id: str) -> Union[RunResource, BadRunResource]:
"""Get a specific run entry by its identifier.
Args:
run_id: Unique identifier of run entry to retrieve.
Returns:
The retrieved run entry.
Raises:
RunNotFoundError: The given run ID was not found.
"""
select_run_resource = sqlalchemy.select(*_run_columns).where(
run_table.c.id == run_id
)
select_actions = (
sqlalchemy.select(action_table)
.where(action_table.c.run_id == run_id)
.order_by(sqlite_rowid)
)
with self._sql_engine.begin() as transaction:
try:
run_row = transaction.execute(select_run_resource).one()
except sqlalchemy.exc.NoResultFound as e:
raise RunNotFoundError(run_id) from e
action_rows = transaction.execute(select_actions).all()
return _convert_row_to_run(run_row, action_rows)
@lru_cache(maxsize=_CACHE_ENTRIES)
def get_all(
self, length: Optional[int] = None
) -> List[Union[RunResource, BadRunResource]]:
"""Get all known run resources.
Results are ordered from oldest to newest.
Params:
length: If `None`, return all runs. Otherwise, return the newest n runs.
"""
select_actions = sqlalchemy.select(action_table).order_by(sqlite_rowid.asc())
actions_by_run_id = defaultdict(list)
with self._sql_engine.begin() as transaction:
if length is not None:
select_runs = (
sqlalchemy.select(*_run_columns)
.order_by(sqlite_rowid.desc())
.limit(length)
)
# need to select the last inserted runs and return by asc order
runs = list(reversed(transaction.execute(select_runs).all()))
else:
select_runs = sqlalchemy.select(*_run_columns).order_by(
sqlite_rowid.asc()
)
runs = transaction.execute(select_runs).all()
actions = transaction.execute(select_actions).all()
for action_row in actions:
actions_by_run_id[action_row.run_id].append(action_row)
return [
_convert_row_to_run(
row=run_row,
action_rows=actions_by_run_id[run_row.id],
)
for run_row in runs
]
@lru_cache(maxsize=_CACHE_ENTRIES)
def get_state_summary(self, run_id: str) -> Union[StateSummary, BadStateSummary]:
"""Get the archived run state summary.
This is a summary of run's ProtocolEngine state,
captured when the run was archived. It contains
status, equipment, and error information.
"""
select_run_data = sqlalchemy.select(run_table.c.state_summary).where(
run_table.c.id == run_id
)
with self._sql_engine.begin() as transaction:
row = transaction.execute(select_run_data).one()
try:
return (
json_to_pydantic(StateSummary, row.state_summary)
if row.state_summary is not None
else BadStateSummary(
dataError=InvalidStoredData(
message="There was no engine state data for this run."
)
)
)
except ValidationError as e:
log.warning(f"Error retrieving state summary for {run_id}", exc_info=True)
return BadStateSummary(
dataError=InvalidStoredData(
message="Could not load stored StateSummary",
wrapping=[PythonException(e)],
)
)
@lru_cache(maxsize=_CACHE_ENTRIES)
def get_run_time_parameters(self, run_id: str) -> List[RunTimeParameter]:
"""Get the archived run time parameters.
This is a list of the run's parameter definitions (if any),
including the values used in the run itself, along with the default value,
constraints and associated names and descriptions.
"""
select_run_data = sqlalchemy.select(run_table.c.run_time_parameters).where(
run_table.c.id == run_id
)
with self._sql_engine.begin() as transaction:
row = transaction.execute(select_run_data).one()
try:
return (
json_to_pydantic_list(RunTimeParameter, row.run_time_parameters) # type: ignore[arg-type]
if row.run_time_parameters is not None
else []
)
except ValidationError:
log.warning(
f"Error retrieving run time parameters for {run_id}", exc_info=True
)
return []
def get_commands_slice(
self,
run_id: str,
length: int,
cursor: Optional[int],
) -> CommandSlice:
"""Get a slice of run commands from the store.
Args:
run_id: Run ID to pull commands from.
length: Number of commands to return.
cursor: The starting index of the slice in the whole collection.
If `None`, up to `length` elements at the end of the collection will
be returned.
Returns:
A collection of commands as well as the actual cursor used and
the total length of the collection.
Raises:
RunNotFoundError: The given run ID was not found.
"""
with self._sql_engine.begin() as transaction:
if not self._run_exists(run_id, transaction):
raise RunNotFoundError(run_id=run_id)
select_count = sqlalchemy.select(sqlalchemy.func.count()).where(
run_command_table.c.run_id == run_id
)
count_result: int = transaction.execute(select_count).scalar_one()
actual_cursor = cursor if cursor is not None else count_result - length
# Clamp to [0, count_result).
actual_cursor = max(0, min(actual_cursor, count_result - 1))
select_slice = (
sqlalchemy.select(
run_command_table.c.index_in_run, run_command_table.c.command
)
.where(
run_command_table.c.run_id == run_id,
run_command_table.c.index_in_run >= actual_cursor,
run_command_table.c.index_in_run < actual_cursor + length,
)
.order_by(run_command_table.c.index_in_run)
)
slice_result = transaction.execute(select_slice).all()
sliced_commands: List[Command] = [
json_to_pydantic(Command, row.command) # type: ignore[arg-type]
for row in slice_result
]
return CommandSlice(
cursor=actual_cursor,
total_length=count_result,
commands=sliced_commands,
)
@lru_cache(maxsize=_CACHE_ENTRIES)
def get_command(self, run_id: str, command_id: str) -> Command:
"""Get run command by id.
Args:
run_id: The run to pull the command from.
command_id: The specific command to pull.
Returns:
The command.
Raises:
RunNotFoundError: The given run ID was not found in the store.
CommandNotFoundError: The given command ID was not found in the store.
"""
select_command = sqlalchemy.select(run_command_table.c.command).where(
run_command_table.c.run_id == run_id,
run_command_table.c.command_id == command_id,
)
with self._sql_engine.begin() as transaction:
if not self._run_exists(run_id, transaction):
raise RunNotFoundError(run_id=run_id)
command = transaction.execute(select_command).scalar_one_or_none()
if command is None:
raise CommandNotFoundError(command_id=command_id)
return json_to_pydantic(Command, command) # type: ignore[arg-type]
def remove(self, run_id: str) -> None:
"""Remove a run by its unique identifier.
Arguments:
run_id: The run's unique identifier.
Raises:
RunNotFoundError: The specified run ID was not found.
"""
delete_run = sqlalchemy.delete(run_table).where(run_table.c.id == run_id)
delete_actions = sqlalchemy.delete(action_table).where(
action_table.c.run_id == run_id
)
delete_commands = sqlalchemy.delete(run_command_table).where(
run_command_table.c.run_id == run_id
)
with self._sql_engine.begin() as transaction:
transaction.execute(delete_actions)
transaction.execute(delete_commands)
result = transaction.execute(delete_run)
if result.rowcount < 1:
raise RunNotFoundError(run_id)
self._clear_caches()
def _run_exists(
self, run_id: str, connection: sqlalchemy.engine.Connection
) -> bool:
result: bool = connection.execute(
sqlalchemy.select(sqlalchemy.exists().where(run_table.c.id == run_id))
).scalar_one()
return result
def _clear_caches(self) -> None:
self.has.cache_clear()
self.get.cache_clear()
self.get_all.cache_clear()
self.get_state_summary.cache_clear()
self.get_command.cache_clear()
self.get_run_time_parameters.cache_clear()
# The columns that must be present in a row passed to _convert_row_to_run().
_run_columns = [run_table.c.id, run_table.c.protocol_id, run_table.c.created_at]
def _convert_row_to_run(
row: sqlalchemy.engine.Row,
action_rows: List[sqlalchemy.engine.Row],
) -> Union[RunResource, BadRunResource]:
run_id = row.id
protocol_id = row.protocol_id
created_at = row.created_at
# Checking the fundamental data types here are not covered by the error handling
# because if they fire, the only thing we can do to address the issue is immediately
# delete the row while we still have a handle on it from sql - we won't have any
# other way to delete it. It's also unclear how it could happen without the table schema
# changing out from under us.
assert isinstance(run_id, str), f"Run ID {run_id} is not a string"
assert protocol_id is None or isinstance(
protocol_id, str
), f"Protocol ID {protocol_id} is not a string or None"
try:
actions = [
RunAction(
id=action_row.id,
createdAt=action_row.created_at,
actionType=RunActionType(action_row.action_type),
)
for action_row in action_rows
]
except Exception as be:
log.warning("Error reading actions for run ID {run_id}:", exc_info=True)
return BadRunResource(
ok=False,
run_id=run_id,
created_at=created_at,
protocol_id=protocol_id,
actions=[],
error=InvalidStoredData(
message="This run has invalid or unknown actions. It has likely been saved in a future version of software.",
detail={"kind": "bad-actions"},
wrapping=[PythonException(be)],
),
)
return RunResource(
ok=True,
run_id=run_id,
created_at=created_at,
protocol_id=protocol_id,
actions=actions,
)
def _convert_run_to_sql_values(run: RunResource) -> Dict[str, object]:
return {
"id": run.run_id,
"created_at": run.created_at,
"protocol_id": run.protocol_id,
}
def _convert_action_to_sql_values(action: RunAction, run_id: str) -> Dict[str, object]:
return {
"id": action.id,
"created_at": action.createdAt,
"action_type": action.actionType.value,
"run_id": run_id,
}
def _convert_state_to_sql_values(
run_id: str,
state_summary: StateSummary,
engine_status: str,
run_time_parameters: List[RunTimeParameter],
) -> Dict[str, object]:
return {
"state_summary": pydantic_to_json(state_summary),
"engine_status": engine_status,
"_updated_at": utc_now(),
"run_time_parameters": pydantic_list_to_json(run_time_parameters),
}