ssapling 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. ssapling/__init__.py +12 -0
  2. ssapling/core/__init__.py +53 -0
  3. ssapling/core/_declarations.py +139 -0
  4. ssapling/core/_execution.py +155 -0
  5. ssapling/core/_plain.py +37 -0
  6. ssapling/core/_text.py +42 -0
  7. ssapling/core/errors.py +175 -0
  8. ssapling/core/loading.py +205 -0
  9. ssapling/core/registry.py +345 -0
  10. ssapling/core/settings.py +698 -0
  11. ssapling/core/spec.py +98 -0
  12. ssapling/data/__init__.py +89 -0
  13. ssapling/data/_matching.py +22 -0
  14. ssapling/data/batching.py +166 -0
  15. ssapling/data/collections.py +335 -0
  16. ssapling/data/encoding.py +107 -0
  17. ssapling/data/errors.py +104 -0
  18. ssapling/data/provenance.py +94 -0
  19. ssapling/data/records.py +546 -0
  20. ssapling/data/sampling.py +339 -0
  21. ssapling/data/storage.py +569 -0
  22. ssapling/environments/__init__.py +43 -0
  23. ssapling/environments/contracts.py +168 -0
  24. ssapling/environments/errors.py +53 -0
  25. ssapling/environments/runner.py +153 -0
  26. ssapling/environments/types.py +173 -0
  27. ssapling/evaluate/__init__.py +40 -0
  28. ssapling/evaluate/aggregation.py +173 -0
  29. ssapling/evaluate/assessment.py +429 -0
  30. ssapling/evaluate/measurement.py +165 -0
  31. ssapling/interaction/__init__.py +24 -0
  32. ssapling/interaction/episode.py +713 -0
  33. ssapling/interaction/errors.py +21 -0
  34. ssapling/interaction/hosting.py +287 -0
  35. ssapling/models/__init__.py +44 -0
  36. ssapling/models/buffering.py +189 -0
  37. ssapling/models/contracts.py +181 -0
  38. ssapling/models/errors.py +27 -0
  39. ssapling/models/types.py +75 -0
  40. ssapling/py.typed +0 -0
  41. ssapling/registries.py +37 -0
  42. ssapling/tasks/__init__.py +49 -0
  43. ssapling/tasks/contracts.py +137 -0
  44. ssapling/tasks/errors.py +37 -0
  45. ssapling/tasks/types.py +172 -0
  46. ssapling/teachers/__init__.py +34 -0
  47. ssapling/teachers/contracts.py +145 -0
  48. ssapling/teachers/errors.py +80 -0
  49. ssapling/teachers/runner.py +142 -0
  50. ssapling/teachers/types.py +178 -0
  51. ssapling/train/__init__.py +43 -0
  52. ssapling/train/components.py +194 -0
  53. ssapling/train/context.py +169 -0
  54. ssapling/train/errors.py +24 -0
  55. ssapling/train/procedure.py +316 -0
  56. ssapling/train/runner.py +398 -0
  57. ssapling/train/stages.py +463 -0
  58. ssapling-0.1.0.dist-info/METADATA +113 -0
  59. ssapling-0.1.0.dist-info/RECORD +61 -0
  60. ssapling-0.1.0.dist-info/WHEEL +4 -0
  61. ssapling-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,569 @@
1
+ """Storage: saving records and collections, and reading them back.
2
+
3
+ ``Store`` is the storage interface the rest of SSAPling uses. ``RecordStore``
4
+ is the built-in store: a directory of JSON-lines files that uses only the
5
+ standard library. A project that needs another storage system implements
6
+ ``Store`` itself.
7
+
8
+ The store owns the structure: the file layout, appending to a record while
9
+ it is being written, reading back, reservations, provenance, and schema
10
+ versions. It never interprets payloads: a codec turns them into JSON-ready
11
+ values and back, and every file names the codec it was written with, so it
12
+ is read back with the right one.
13
+ """
14
+
15
+ import dataclasses
16
+ import gzip
17
+ import json
18
+ import os
19
+ from collections.abc import Iterator, Mapping
20
+ from contextlib import contextmanager
21
+ from pathlib import Path
22
+ from typing import Any, Protocol
23
+ from urllib.parse import quote, unquote
24
+
25
+ from ..core._declarations import check_identifier
26
+ from ..environments.types import ResetResult, StepResult
27
+ from ..tasks import Instance
28
+ from ..teachers.types import TeacherResponse
29
+ from .collections import Collections, Drawn
30
+ from .encoding import Codec, codecs
31
+ from .errors import StoreError, UnknownDocumentError, UnknownRecordError
32
+ from .provenance import Provenance
33
+ from .records import AgentTiming, Record, RecordBuilder, RecordHeader, RecordStep, RecordSummary
34
+
35
+ __all__ = ["STORE_FORMAT", "STORE_VERSION", "RecordStore", "Store"]
36
+
37
+ STORE_FORMAT = "ssapling-store"
38
+ """The format name in a store's manifest."""
39
+
40
+ STORE_VERSION = 1
41
+ """The version of the store layout this SSAPling writes and reads."""
42
+
43
+ _SUFFIX = ".jsonl"
44
+ _COMPRESSED = ".jsonl.gz" # a finished record, with compress=True
45
+
46
+
47
+ class Store(Protocol):
48
+ """What a store provides: records written step by step, collections, and documents.
49
+
50
+ A record is begun with its header, appended to step by step, and
51
+ finished with its summary; it can be read back at any point, finished or
52
+ not. Collections are saved one at a time and loaded back together, with
53
+ their reservations. A document is anything else saved whole by name,
54
+ such as assessment results.
55
+ """
56
+
57
+ def begin(self, header: RecordHeader) -> None:
58
+ """Start a new record."""
59
+ ...
60
+
61
+ def append(self, record_id: str, step: RecordStep) -> None:
62
+ """Add the next step to a record that is not finished."""
63
+ ...
64
+
65
+ def finish(self, record_id: str, summary: RecordSummary) -> None:
66
+ """Say how a record's attempt ended; it takes no more steps."""
67
+ ...
68
+
69
+ def read(self, record_id: str) -> Record:
70
+ """The record as written so far."""
71
+ ...
72
+
73
+ def record_ids(self) -> tuple[str, ...]:
74
+ """The ids of every record in the store."""
75
+ ...
76
+
77
+ def save_collection(self, collections: Collections, name: str) -> None:
78
+ """Save one collection, held out or not, with its items' provenance."""
79
+ ...
80
+
81
+ def load_collections(
82
+ self,
83
+ source: object,
84
+ *,
85
+ source_name: str | None = None,
86
+ source_settings: Mapping[str, Any] | None = None,
87
+ ) -> Collections:
88
+ """Every saved collection, drawn from ``source``, with its reservations."""
89
+ ...
90
+
91
+ def save_document(self, name: str, document: Mapping[str, Any]) -> None:
92
+ """Save ``document`` under ``name``."""
93
+ ...
94
+
95
+ def load_document(self, name: str) -> dict[str, Any]:
96
+ """The document saved under ``name``."""
97
+ ...
98
+
99
+ def document_names(self) -> tuple[str, ...]:
100
+ """The names of every document in the store."""
101
+ ...
102
+
103
+
104
+ class RecordStore:
105
+ """The built-in store: a directory of JSON-lines files, standard library only.
106
+
107
+ Example::
108
+
109
+ store = RecordStore("runs/baseline")
110
+ store.begin(header)
111
+ store.append(header.id, step) # one line per step, written at once
112
+ store.finish(header.id, RecordSummary.terminated())
113
+ store.read(header.id) # a Record, also before it is finished
114
+
115
+ Layout::
116
+
117
+ runs/baseline/
118
+ manifest.json # the store's format and version
119
+ records/<record id>.jsonl # a header line, one line per step, a summary line
120
+ collections/<name>.jsonl # a header line, one line per item
121
+ documents/<name>.jsonl # a header line, then the document
122
+
123
+ Each step is checked as it is appended, by the same rules as
124
+ ``RecordBuilder``, and written straight away, so a record survives an
125
+ interrupted run. Reading back ignores a last line that was only partly
126
+ written. Ids and names are written into file names with
127
+ percent-encoding, so any string is safe. Only the store that began a
128
+ record appends to it and finishes it; a record left unfinished by an
129
+ interrupted run stays as it was written.
130
+
131
+ With ``compress=True``, each record's file is gzip-compressed when the
132
+ record finishes (``records/<record id>.jsonl.gz``), which makes a long
133
+ record about thirty times smaller; until then it is written plain, step by
134
+ step, as always, so an interrupted run loses nothing. Every store reads
135
+ plain and compressed records alike. Collections and documents are never
136
+ compressed.
137
+
138
+ Args:
139
+ root: The store's directory. It is created if missing; an existing
140
+ directory must be a store already, or empty.
141
+ codec: The registered codec new files are written with.
142
+ ``"json"`` by default.
143
+ compress: Compress each record's file when the record finishes.
144
+
145
+ Raises:
146
+ StoreError: ``root`` is not empty and not a store, or was written by
147
+ a newer SSAPling.
148
+ UnknownComponentError: ``codec`` is not a registered codec.
149
+ """
150
+
151
+ def __init__(
152
+ self, root: str | os.PathLike[str], *, codec: str = "json", compress: bool = False
153
+ ) -> None:
154
+ self.root = Path(root)
155
+ self._codec_name = codec
156
+ self._compress = compress
157
+ self._codecs: dict[str, Codec] = {}
158
+ self._codec(codec)
159
+ _open(self.root)
160
+ self._building: dict[str, RecordBuilder] = {} # records begun here and not finished
161
+
162
+ # Records
163
+
164
+ def begin(self, header: RecordHeader) -> None:
165
+ """Start a new record, writing its header.
166
+
167
+ Raises:
168
+ ValueError: The store already holds a record with this id.
169
+ TypeError: ``header`` is not a ``RecordHeader``, or the codec
170
+ cannot encode one of its payloads.
171
+ """
172
+ if not isinstance(header, RecordHeader):
173
+ raise TypeError(f"header must be a RecordHeader, got {header!r}")
174
+ path = self._record_path(header.id)
175
+ if path.exists() or _compressed(path).exists():
176
+ raise ValueError(f"the store at {self.root} already holds a record {header.id!r}")
177
+ line = self._line({"kind": "header", "codec": self._codec_name, **_header_doc(header)})
178
+ path.parent.mkdir(exist_ok=True)
179
+ with path.open("xb") as file:
180
+ file.write(line)
181
+ self._building[header.id] = RecordBuilder(header)
182
+
183
+ def append(self, record_id: str, step: RecordStep) -> None:
184
+ """Add the next step to a record, checking it as ``RecordBuilder.append`` does.
185
+
186
+ Raises:
187
+ UnknownRecordError: The store holds no such record.
188
+ ValueError: This store did not begin the record, or it is
189
+ finished, or the step breaks one of the builder's checks.
190
+ Nothing is written.
191
+ TypeError: The codec cannot encode one of the step's payloads.
192
+ Nothing is written.
193
+ """
194
+ builder = self._builder(record_id)
195
+ if not isinstance(step, RecordStep):
196
+ raise TypeError(f"step must be a RecordStep, got {step!r}")
197
+ line = self._line({"kind": "step", **_step_doc(step)})
198
+ builder.append(step)
199
+ self._write(record_id, line)
200
+
201
+ def finish(self, record_id: str, summary: RecordSummary) -> None:
202
+ """Write how the record's attempt ended; it takes no more steps.
203
+
204
+ Raises:
205
+ UnknownRecordError: The store holds no such record.
206
+ ValueError: This store did not begin the record, or it is
207
+ already finished.
208
+ """
209
+ builder = self._builder(record_id)
210
+ if not isinstance(summary, RecordSummary):
211
+ raise TypeError(f"summary must be a RecordSummary, got {summary!r}")
212
+ line = self._line({"kind": "summary", **_fields(summary)})
213
+ builder.finish(summary)
214
+ self._write(record_id, line)
215
+ del self._building[record_id]
216
+ if self._compress:
217
+ path = self._record_path(record_id)
218
+ packed = _compressed(path)
219
+ partial = packed.with_name(packed.name + ".partial")
220
+ partial.write_bytes(gzip.compress(path.read_bytes(), mtime=0)) # no time: same bytes
221
+ partial.replace(packed)
222
+ path.unlink()
223
+
224
+ def write(self, record: Record) -> None:
225
+ """Store a whole record at once: ``begin``, ``append`` each step, and ``finish``."""
226
+ self.begin(record.header)
227
+ for step in record.steps:
228
+ self.append(record.header.id, step)
229
+ if record.summary is not None:
230
+ self.finish(record.header.id, record.summary)
231
+
232
+ def read(self, record_id: str) -> Record:
233
+ """The record as written so far: finished or not.
234
+
235
+ Raises:
236
+ UnknownRecordError: The store holds no such record.
237
+ StoreError: The file is not what SSAPling writes.
238
+ """
239
+ path = self._record_path(record_id)
240
+ if not path.exists():
241
+ path = _compressed(path)
242
+ if not path.exists():
243
+ raise UnknownRecordError(record_id, str(self.root))
244
+ header, *rest = self._read_docs(path)
245
+ if header.pop("kind", None) != "header":
246
+ raise StoreError(f"{path}: the first line is not a record header")
247
+ del header["codec"]
248
+ with _reading(path):
249
+ steps: list[RecordStep] = []
250
+ summary = None
251
+ for doc in rest:
252
+ kind = doc.pop("kind", None)
253
+ if summary is not None:
254
+ raise StoreError(f"{path}: a line follows the summary")
255
+ if kind == "step":
256
+ steps.append(_step(doc))
257
+ elif kind == "summary":
258
+ summary = RecordSummary(**doc)
259
+ else:
260
+ raise StoreError(f"{path}: unknown kind of line {kind!r}")
261
+ return Record(header=_header(header), steps=tuple(steps), summary=summary)
262
+
263
+ def record_ids(self) -> tuple[str, ...]:
264
+ """The ids of every record in the store, sorted."""
265
+ return tuple(
266
+ sorted(
267
+ {*_names_in(self.root / "records"), *_names_in(self.root / "records", _COMPRESSED)}
268
+ )
269
+ )
270
+
271
+ # Collections
272
+
273
+ def save_collection(self, collections: Collections, name: str) -> None:
274
+ """Save the collection ``name``, held out or not, with its items' provenance.
275
+
276
+ Raises:
277
+ ValueError: The store already holds a collection with this name.
278
+ UnknownCollectionError: ``collections`` has no such collection.
279
+ """
280
+ held_out = collections.held_out(name)
281
+ items = collections.get(name, purpose="evaluation") # saved whether held out or not
282
+ directory = self.root / "collections"
283
+ path = directory / _file_name(name)
284
+ if path.exists():
285
+ raise ValueError(f"the store at {self.root} already holds a collection {name!r}")
286
+ header = {
287
+ "kind": "collection",
288
+ "codec": self._codec_name,
289
+ "name": name,
290
+ "held_out": held_out,
291
+ "index": len(_names_in(directory)),
292
+ }
293
+ lines = [self._line(header)]
294
+ lines += [self._line(_drawn_doc(drawn)) for drawn in items]
295
+ directory.mkdir(exist_ok=True)
296
+ with path.open("xb") as file:
297
+ file.write(b"".join(lines))
298
+
299
+ def load_collections(
300
+ self,
301
+ source: object,
302
+ *,
303
+ source_name: str | None = None,
304
+ source_settings: Mapping[str, Any] | None = None,
305
+ ) -> Collections:
306
+ """Every saved collection, as ``Collections`` drawing from ``source``.
307
+
308
+ Loading restores each collection's items, whether it is held out,
309
+ and its reservations, so the remainder and any new collection still
310
+ avoid every saved problem. The collections keep the order they were
311
+ saved in. ``source_name`` and ``source_settings`` are as for
312
+ ``Collections``.
313
+
314
+ Raises:
315
+ StoreError: A collection file is not what SSAPling writes.
316
+ """
317
+ collections = Collections(source, source_name=source_name, source_settings=source_settings)
318
+ loaded = []
319
+ for path in (self.root / "collections").glob(f"*{_SUFFIX}"):
320
+ header, *items = self._read_docs(path)
321
+ if header.get("kind") != "collection":
322
+ raise StoreError(f"{path}: the first line is not a collection header")
323
+ loaded.append((header.get("index", 0), header, items, path))
324
+ for _, header, items, path in sorted(loaded, key=lambda entry: entry[0]):
325
+ with _reading(path):
326
+ drawn = [_drawn(doc) for doc in items]
327
+ collections.add(header["name"], drawn, held_out=header["held_out"])
328
+ return collections
329
+
330
+ # Documents
331
+
332
+ def save_document(self, name: str, document: Mapping[str, Any]) -> None:
333
+ """Save ``document``, a mapping of payloads the codec can encode, under ``name``.
334
+
335
+ A saved name is never overwritten.
336
+
337
+ Raises:
338
+ ValueError: The store already holds a document with this name.
339
+ TypeError: The codec cannot encode part of the document.
340
+ """
341
+ path = self._document_path(name)
342
+ if path.exists():
343
+ raise ValueError(f"the store at {self.root} already holds a document {name!r}")
344
+ lines = self._line({"kind": "document", "codec": self._codec_name, "name": name})
345
+ lines += self._line({"document": dict(document)})
346
+ path.parent.mkdir(exist_ok=True)
347
+ with path.open("xb") as file:
348
+ file.write(lines)
349
+
350
+ def load_document(self, name: str) -> dict[str, Any]:
351
+ """The document saved under ``name``.
352
+
353
+ Raises:
354
+ UnknownDocumentError: The store holds no such document.
355
+ StoreError: The file is not what SSAPling writes.
356
+ """
357
+ path = self._document_path(name)
358
+ if not path.exists():
359
+ raise UnknownDocumentError(name, str(self.root))
360
+ docs = self._read_docs(path)
361
+ if docs[0].get("kind") != "document" or len(docs) != 2:
362
+ raise StoreError(f"{path}: not a document file")
363
+ document: dict[str, Any] = docs[1]["document"]
364
+ return document
365
+
366
+ def document_names(self) -> tuple[str, ...]:
367
+ """The names of every document in the store, sorted."""
368
+ return _names_in(self.root / "documents")
369
+
370
+ # Internals
371
+
372
+ def _codec(self, name: str) -> Codec:
373
+ if name not in self._codecs:
374
+ self._codecs[name] = codecs.create(name)
375
+ return self._codecs[name]
376
+
377
+ def _line(self, document: Mapping[str, Any]) -> bytes:
378
+ """One line of a file: ``document`` encoded with the store's codec, as JSON."""
379
+ encoded = self._codec(self._codec_name).encode(dict(document))
380
+ text = json.dumps(encoded, ensure_ascii=False, separators=(",", ":"))
381
+ return text.encode("utf-8") + b"\n"
382
+
383
+ def _write(self, record_id: str, line: bytes) -> None:
384
+ with self._record_path(record_id).open("ab") as file:
385
+ file.write(line)
386
+
387
+ def _builder(self, record_id: str) -> RecordBuilder:
388
+ """The builder of a record this store began and has not finished."""
389
+ if record_id in self._building:
390
+ return self._building[record_id]
391
+ path = self._record_path(record_id)
392
+ if not path.exists() and not _compressed(path).exists():
393
+ raise UnknownRecordError(record_id, str(self.root))
394
+ raise ValueError(
395
+ f"record {record_id!r} takes no more steps here: it is finished, or another "
396
+ "RecordStore began it. Only the store that begins a record writes to it."
397
+ )
398
+
399
+ def _read_docs(self, path: Path) -> list[dict[str, Any]]:
400
+ """Every complete line of ``path``, decoded with the codec its first line names.
401
+
402
+ A last line without its newline was only partly written, so it is
403
+ ignored.
404
+ """
405
+ data = path.read_bytes()
406
+ if path.name.endswith(_COMPRESSED):
407
+ data = gzip.decompress(data)
408
+ complete = data.split(b"\n")[:-1]
409
+ raw = []
410
+ for number, line in enumerate(complete, 1):
411
+ try:
412
+ raw.append(json.loads(line))
413
+ except json.JSONDecodeError as error:
414
+ raise StoreError(f"{path}, line {number}: not valid JSON ({error.msg})") from None
415
+ if not raw or not isinstance(raw[0], dict) or "codec" not in raw[0]:
416
+ raise StoreError(f"{path}: the first line does not name a codec")
417
+ codec = self._codec(raw[0]["codec"])
418
+ return [codec.decode(doc) for doc in raw]
419
+
420
+ def _record_path(self, record_id: str) -> Path:
421
+ check_identifier(record_id, "a record id")
422
+ return self.root / "records" / _file_name(record_id)
423
+
424
+ def _document_path(self, name: str) -> Path:
425
+ check_identifier(name, "a document name")
426
+ return self.root / "documents" / _file_name(name)
427
+
428
+ def __repr__(self) -> str:
429
+ packed = ", compress=True" if self._compress else ""
430
+ return f"RecordStore({str(self.root)!r}, codec={self._codec_name!r}{packed})"
431
+
432
+
433
+ # The manifest
434
+
435
+
436
+ def _open(root: Path) -> None:
437
+ """Check that ``root`` is a store, or make it one."""
438
+ manifest = root / "manifest.json"
439
+ if manifest.exists():
440
+ try:
441
+ content = json.loads(manifest.read_text(encoding="utf-8"))
442
+ except json.JSONDecodeError as error:
443
+ raise StoreError(f"{manifest}: not valid JSON ({error.msg})") from None
444
+ if not isinstance(content, dict) or content.get("format") != STORE_FORMAT:
445
+ raise StoreError(f"{manifest} is not an SSAPling store manifest")
446
+ version = content.get("version")
447
+ if not isinstance(version, int) or version > STORE_VERSION:
448
+ raise StoreError(
449
+ f"the store at {root} has version {version!r}, but this version of SSAPling "
450
+ f"reads up to {STORE_VERSION}; upgrade SSAPling to read it"
451
+ )
452
+ return
453
+ if root.exists() and any(root.iterdir()):
454
+ raise StoreError(
455
+ f"{root} is not empty and has no SSAPling manifest, so it is not a store; "
456
+ "use a new or empty directory"
457
+ )
458
+ root.mkdir(parents=True, exist_ok=True)
459
+ content = {"format": STORE_FORMAT, "version": STORE_VERSION}
460
+ manifest.write_text(json.dumps(content) + "\n", encoding="utf-8")
461
+
462
+
463
+ # File names
464
+
465
+
466
+ def _file_name(name: str) -> str:
467
+ return quote(name, safe="") + _SUFFIX
468
+
469
+
470
+ def _names_in(directory: Path, suffix: str = _SUFFIX) -> tuple[str, ...]:
471
+ if not directory.exists():
472
+ return ()
473
+ found = (path.name for path in directory.iterdir() if path.name.endswith(suffix))
474
+ return tuple(sorted(unquote(name[: -len(suffix)]) for name in found))
475
+
476
+
477
+ def _compressed(path: Path) -> Path:
478
+ """Where a record's file goes once it is compressed."""
479
+ return path.with_name(path.name[: -len(_SUFFIX)] + _COMPRESSED)
480
+
481
+
482
+ @contextmanager
483
+ def _reading(path: Path) -> Iterator[None]:
484
+ """Add the file being read to any error raised while its contents are rebuilt."""
485
+ try:
486
+ yield
487
+ except Exception as error:
488
+ error.add_note(f"While reading {path}.")
489
+ raise
490
+
491
+
492
+ # Records and collections as documents, and back
493
+
494
+
495
+ def _fields(obj: Any) -> dict[str, Any]:
496
+ return {field.name: getattr(obj, field.name) for field in dataclasses.fields(obj)}
497
+
498
+
499
+ def _header_doc(header: RecordHeader) -> dict[str, Any]:
500
+ return {
501
+ **_fields(header),
502
+ "participants": list(header.participants),
503
+ "reset": None if header.reset is None else _fields(header.reset),
504
+ "provenance": None if header.provenance is None else _fields(header.provenance),
505
+ }
506
+
507
+
508
+ def _header(doc: dict[str, Any]) -> RecordHeader:
509
+ reset, provenance = doc["reset"], doc["provenance"]
510
+ return RecordHeader(
511
+ **{
512
+ **doc,
513
+ "participants": tuple(doc["participants"]),
514
+ "reset": None if reset is None else ResetResult(**reset),
515
+ "provenance": None if provenance is None else Provenance(**provenance),
516
+ }
517
+ )
518
+
519
+
520
+ def _step_doc(step: RecordStep) -> dict[str, Any]:
521
+ transition = step.transition
522
+ return {
523
+ **_fields(step),
524
+ "acting": list(step.acting),
525
+ "teacher_responses": [_fields(response) for response in step.teacher_responses],
526
+ "transition": None if transition is None else _transition_doc(transition),
527
+ "timing": {agent: _fields(timing) for agent, timing in step.timing.items()},
528
+ }
529
+
530
+
531
+ def _step(doc: dict[str, Any]) -> RecordStep:
532
+ transition = doc["transition"]
533
+ return RecordStep(
534
+ **{
535
+ **doc,
536
+ "acting": tuple(doc["acting"]),
537
+ "teacher_responses": [TeacherResponse(**r) for r in doc["teacher_responses"]],
538
+ "transition": None if transition is None else _transition(transition),
539
+ "timing": {agent: AgentTiming(**t) for agent, t in doc["timing"].items()},
540
+ }
541
+ )
542
+
543
+
544
+ def _transition_doc(result: StepResult) -> dict[str, Any]:
545
+ responses = result.teacher_responses
546
+ return {
547
+ **_fields(result),
548
+ "teacher_responses": None if responses is None else [_fields(r) for r in responses],
549
+ }
550
+
551
+
552
+ def _transition(doc: dict[str, Any]) -> StepResult:
553
+ responses = doc["teacher_responses"]
554
+ return StepResult(
555
+ **{
556
+ **doc,
557
+ "teacher_responses": None
558
+ if responses is None
559
+ else [TeacherResponse(**r) for r in responses],
560
+ }
561
+ )
562
+
563
+
564
+ def _drawn_doc(drawn: Drawn) -> dict[str, Any]:
565
+ return {"instance": _fields(drawn.instance), "provenance": _fields(drawn.provenance)}
566
+
567
+
568
+ def _drawn(doc: dict[str, Any]) -> Drawn:
569
+ return Drawn(Instance(**doc["instance"]), Provenance(**doc["provenance"]))
@@ -0,0 +1,43 @@
1
+ """SSAPling environments.
2
+
3
+ Responsibility: The contract for agents, actions, observations, transitions,
4
+ and turn order.
5
+
6
+ Not its responsibility: Choosing instances, scoring, teaching strategies.
7
+
8
+ May import: core, and the response types of teachers. Enforced by
9
+ tests/test_layering.py.
10
+ """
11
+
12
+ from collections.abc import Callable
13
+
14
+ from ..core import Registry
15
+ from .contracts import (
16
+ CAPABILITIES,
17
+ Environment,
18
+ active_agents,
19
+ agents,
20
+ next_agents,
21
+ supports,
22
+ )
23
+ from .errors import EnvironmentCommunicationError, UnsupportedCapabilityError
24
+ from .runner import EnvironmentRunner
25
+ from .types import ResetResult, StepResult
26
+
27
+ registry: Registry[Callable[..., Environment]] = Registry("environment")
28
+ """Registered environments. Also available as ``ssapling.registries.environments``."""
29
+
30
+ __all__ = [
31
+ "CAPABILITIES",
32
+ "Environment",
33
+ "EnvironmentCommunicationError",
34
+ "EnvironmentRunner",
35
+ "ResetResult",
36
+ "StepResult",
37
+ "UnsupportedCapabilityError",
38
+ "active_agents",
39
+ "agents",
40
+ "next_agents",
41
+ "registry",
42
+ "supports",
43
+ ]