eventdispatch 0.2.31__tar.gz → 0.3.0__tar.gz

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 (25) hide show
  1. {eventdispatch-0.2.31/eventdispatch.egg-info → eventdispatch-0.3.0}/PKG-INFO +1 -1
  2. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch/common1.py +42 -0
  3. eventdispatch-0.3.0/eventdispatch/example_learning.py +174 -0
  4. eventdispatch-0.3.0/eventdispatch/learning.py +434 -0
  5. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch/sim.py +15 -33
  6. {eventdispatch-0.2.31 → eventdispatch-0.3.0/eventdispatch.egg-info}/PKG-INFO +1 -1
  7. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch.egg-info/SOURCES.txt +3 -1
  8. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/pyproject.toml +1 -1
  9. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/setup.py +1 -1
  10. eventdispatch-0.3.0/tests/test_recording.py +233 -0
  11. eventdispatch-0.2.31/eventdispatch/learning.py +0 -250
  12. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/LICENSE +0 -0
  13. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/NOTICE +0 -0
  14. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/README.md +0 -0
  15. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch/__init__.py +0 -0
  16. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch/composite_semaphore.py +0 -0
  17. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch/core.py +0 -0
  18. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch/example_core.py +0 -0
  19. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch/example_cs.py +0 -0
  20. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch/example_sim_mujoco.py +0 -0
  21. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch.egg-info/dependency_links.txt +0 -0
  22. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch.egg-info/entry_points.txt +0 -0
  23. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch.egg-info/requires.txt +0 -0
  24. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/eventdispatch.egg-info/top_level.txt +0 -0
  25. {eventdispatch-0.2.31 → eventdispatch-0.3.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: eventdispatch
3
- Version: 0.2.31
3
+ Version: 0.3.0
4
4
  Summary: Event Dispatch: discrete time synchronization
5
5
  Home-page: http://github.com/cyan-at/python-eventdispatch
6
6
  Author: Charlie Yan
@@ -156,6 +156,48 @@ class CommonEvent(Event):
156
156
 
157
157
  return (ed.reserve_event_id(), blackboard), tuple(tokens)
158
158
 
159
+ class ClockedEvent(CommonEvent):
160
+ '''
161
+ a CommonEvent that reads its dispatch's clock.
162
+
163
+ The shared base of SimEvent (eventdispatch.sim) and
164
+ RecordingEvent (eventdispatch.learning): the time stamps and
165
+ clock helpers both need, independent of how time passes.
166
+
167
+ The running dispatch provides the clock as its `now`
168
+ attribute: simulated time on SimClockCSBQCVED, monotonic
169
+ wall time on WallClockRecordingDispatch. The dispatch stamps
170
+ started_at when the event starts; quoted_duration is stamped
171
+ only by a dispatch that schedules on quotes (the sim clock).
172
+ '''
173
+ def __init__(self, event_id, *args, **kwargs):
174
+ super(ClockedEvent, self).__init__(event_id, *args, **kwargs)
175
+ # stamped by the running dispatch
176
+ self.started_at = None
177
+ self.quoted_duration = None
178
+
179
+ def now(self):
180
+ '''current time on the running dispatch's clock'''
181
+ if self.event_dispatch is None:
182
+ raise RuntimeError(
183
+ "{}.now(): event has not been dispatched".format(
184
+ type(self).__name__))
185
+ return self.event_dispatch.now
186
+
187
+ def elapsed(self):
188
+ '''time since this event started, or None before it starts'''
189
+ if self.started_at is None:
190
+ return None
191
+ return self.now() - self.started_at
192
+
193
+ def progress(self):
194
+ '''elapsed fraction of the quoted duration, in [0, 1] at
195
+ completion; None when the duration is 0 or unset (always
196
+ None on a wall clock, which takes no quote)'''
197
+ if not self.quoted_duration:
198
+ return None
199
+ return self.elapsed() / self.quoted_duration
200
+
159
201
  TIMERWAIT_TIMEOUT = -1
160
202
  TIMERWAIT_BAILED = 1
161
203
 
@@ -0,0 +1,174 @@
1
+ """Example learning: shake out the learning surface (learning.py).
2
+
3
+ Trivial RecordingEvents on both recording dispatches over a
4
+ Blackboard, following example_core / example_cs's shape. What this
5
+ demonstrates (RecordingEvent, SimClockRecordingDispatch and
6
+ WallClockRecordingDispatch from eventdispatch.learning):
7
+
8
+ 1. Sim clock: events quote durations; records land in the
9
+ dispatch's recordings field in duration order, not enqueue
10
+ order, and the harness drains them with take().
11
+ 2. A zero-arg event dispatches from the queue (RecordingEvent's
12
+ deserialize drops the non-empty-tail check).
13
+ 3. A quote is a commitment the outcome may settle short of: an
14
+ event whose run_outcome() sets actual_duration records it
15
+ beside the quote, and the sim clock settles to
16
+ started_at + actual_duration.
17
+ 4. Wall clock: the same kind of event runs run_outcome() on its
18
+ own thread in real time; the record carries real times and
19
+ no quote.
20
+ 5. Preemption: a cancelled event is recorded PREEMPTED. On the
21
+ wall clock it stops cooperatively and its partial outcome is
22
+ recorded; on_preempt() decides its wake.
23
+
24
+ Run: python -m eventdispatch.example_learning
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import threading
29
+ import time
30
+
31
+ from eventdispatch.core import Blackboard
32
+ from eventdispatch.learning import (
33
+ PREEMPTED, RecordingEvent, SimClockRecordingDispatch,
34
+ WallClockRecordingDispatch)
35
+
36
+
37
+ class WorkEvent(RecordingEvent):
38
+ """Quotes its duration. The outcome is DONE, or SETTLED when
39
+ an actual duration shorter than the quote is reported."""
40
+
41
+ def dispatch(self, ed, tag, duration, actual=None):
42
+ return float(duration)
43
+
44
+ def run_outcome(self, ed, tag, duration, actual=None):
45
+ if actual is not None:
46
+ self.actual_duration = float(actual)
47
+ return "SETTLED"
48
+ return "DONE"
49
+
50
+
51
+ class PingEvent(RecordingEvent):
52
+ """Zero-arg event: quotes 0.5, outcome PONG."""
53
+
54
+ def dispatch(self, ed):
55
+ return 0.5
56
+
57
+ def run_outcome(self, ed):
58
+ return "PONG"
59
+
60
+
61
+ class WaitEvent(RecordingEvent):
62
+ """Wall clock: waits up to `secs`, stopping early if preempted.
63
+ A preempt does not wake the policy (on_preempt)."""
64
+
65
+ def run_outcome(self, ed, secs):
66
+ if self.wait_preempt(float(secs)):
67
+ return "STOPPED_EARLY"
68
+ return "WAITED"
69
+
70
+ def on_preempt(self, ed):
71
+ self.wake = False
72
+
73
+
74
+ def enqueue(ed, blackboard, payloads):
75
+ blackboard[ed.cv_name].acquire()
76
+ blackboard[ed.queue_name].extend(payloads)
77
+ blackboard[ed.cv_name].notify(1)
78
+ blackboard[ed.cv_name].release()
79
+
80
+
81
+ def take(ed, n, timeout=10.0):
82
+ records = []
83
+ deadline = time.time() + timeout
84
+ while len(records) < n and time.time() < deadline:
85
+ records.extend(ed.recordings.take(timeout=1.0))
86
+ return records
87
+
88
+
89
+ def stop(ed, blackboard, thread):
90
+ blackboard[ed.hb_key] = False
91
+ with blackboard[ed.mutex_name]:
92
+ blackboard[ed.cv_name].notify_all()
93
+ thread.join()
94
+
95
+
96
+ def run_sim():
97
+ blackboard = Blackboard()
98
+ blackboard["WorkEvent"] = WorkEvent
99
+ blackboard["PingEvent"] = PingEvent
100
+
101
+ ed = SimClockRecordingDispatch(blackboard, "learning")
102
+ blackboard["learning"] = ed
103
+ thread = threading.Thread(
104
+ target=ed.run, args=(blackboard, "learning", None, None))
105
+ thread.start()
106
+
107
+ # out-of-order quotes, plus a zero-arg event
108
+ enqueue(ed, blackboard, [
109
+ ["WorkEvent", "slow", 2.0],
110
+ ["WorkEvent", "fast", 1.0],
111
+ ["PingEvent"],
112
+ ])
113
+ records = take(ed, 3)
114
+ assert [r["event"] for r in records] == [
115
+ "PingEvent", "WorkEvent", "WorkEvent"], records
116
+ assert [r["t"] for r in records] == [0.5, 1.0, 2.0], records
117
+ assert records[0]["outcome"] == "PONG", records
118
+ assert records[1]["args"][0] == "fast", records
119
+ assert records[2]["args"][0] == "slow", records
120
+ print("sim clock: duration order + zero-arg dispatch PASS")
121
+
122
+ # settling short of the quote (clock stands at 2.0 now)
123
+ enqueue(ed, blackboard, [["WorkEvent", "settles", 2.0, 0.5]])
124
+ (rec,) = take(ed, 1)
125
+ assert rec["started_at"] == 2.0, rec
126
+ assert rec["duration"] == 2.0, rec
127
+ assert rec["actual_duration"] == 0.5, rec
128
+ assert rec["outcome"] == "SETTLED", rec
129
+ assert ed.now == 2.5, ed.now
130
+ print("sim clock: clock settling PASS")
131
+
132
+ stop(ed, blackboard, thread)
133
+
134
+
135
+ def run_wall():
136
+ blackboard = Blackboard()
137
+ blackboard["WaitEvent"] = WaitEvent
138
+
139
+ ed = WallClockRecordingDispatch(blackboard, "wall")
140
+ blackboard["wall"] = ed
141
+ thread = threading.Thread(
142
+ target=ed.run, args=(blackboard, "wall", None, None))
143
+ thread.start()
144
+
145
+ enqueue(ed, blackboard, [["WaitEvent", 0.2]])
146
+ (rec,) = take(ed, 1)
147
+ assert rec["outcome"] == "WAITED" and "duration" not in rec, rec
148
+ assert rec["t"] - rec["started_at"] >= 0.15, rec
149
+ print("wall clock: real-time record PASS")
150
+
151
+ enqueue(ed, blackboard, [["WaitEvent", 30.0]])
152
+ deadline = time.time() + 5.0
153
+ while not ed._live and time.time() < deadline:
154
+ time.sleep(0.01)
155
+ (event_id,) = list(ed._live)
156
+ time.sleep(0.1)
157
+ ed.cancel(event_id)
158
+ (rec,) = take(ed, 1)
159
+ assert rec["outcome"] == PREEMPTED, rec
160
+ assert rec["partial_outcome"] == "STOPPED_EARLY", rec
161
+ assert rec["wake"] is False, rec
162
+ print("wall clock: cooperative preemption PASS")
163
+
164
+ stop(ed, blackboard, thread)
165
+
166
+
167
+ def main():
168
+ run_sim()
169
+ run_wall()
170
+ print("learning surface constructs and runs on both clocks")
171
+
172
+
173
+ if __name__ == "__main__":
174
+ main()
@@ -0,0 +1,434 @@
1
+ """Learning surface of the eventdispatch framework.
2
+
3
+ Every language implementation of the framework keeps one module like
4
+ this one: the surface that learning / training code programs against.
5
+ Training code imports from here, never from core internals.
6
+
7
+ Recording is what makes learning possible on this framework: an
8
+ event that opts in has its completion written as a record, and the
9
+ records are what a training or inference loop reads.
10
+
11
+ RecordingEvent -- the Event base class that opts in to recording.
12
+ A sibling of SimEvent (both are ClockedEvent,
13
+ eventdispatch.common1): it says nothing about
14
+ how time passes.
15
+ RecordingMixin -- the dispatch side: writes completion and
16
+ PREEMPTED records to the recordings field.
17
+ SimClockRecordingDispatch -- RecordingMixin on SimClockCSBQCVED
18
+ (eventdispatch.sim): quoted durations, a
19
+ simulated clock. Training runs here.
20
+ WallClockRecordingDispatch -- RecordingMixin on CSBQCVED
21
+ (eventdispatch.composite_semaphore): each
22
+ recording event's run_outcome() runs on its
23
+ own thread, in real time. Inference and
24
+ calibration on hardware run here.
25
+ RecordingLog -- the recordings field's type.
26
+
27
+ Events that do not inherit RecordingEvent run untouched on both
28
+ recording dispatches and are never recorded.
29
+
30
+ Recording protocol (the contract RecordingEvent subclasses follow):
31
+
32
+ dispatch(ed) -> scheduling only: stash the args, and return a
33
+ duration quote in the clock's units. No outcome sampling,
34
+ no mutation. The quote is required on the sim clock (it is
35
+ what the heap schedules on) and ignored on the wall clock.
36
+ run_outcome(ed) -> the outcome. The work: run the outcome model
37
+ (sim clock, at completion time, against fresh state) or do
38
+ the real work (wall clock, on the event's thread); apply the
39
+ event's effects; return what happened.
40
+ wake -> the event's own decision: class default True,
41
+ settable per outcome from run_outcome(). A record whose wake
42
+ is True always wakes the policy -- binding on the harness,
43
+ not a hint. The dispatch never decides wake.
44
+ on_preempt(ed) -> optional. Called when the event is preempted,
45
+ after run_outcome() on the wall clock (so it wins); it may
46
+ set self.wake and may return a dict of notes for the record.
47
+ It must not mutate world state: a preempted sim event never
48
+ ran, and must leave no effects.
49
+
50
+ The event does not record itself: the recording dispatch writes the
51
+ record. finish() is not part of the recording protocol; on a
52
+ dispatch that does not record, RecordingEvent.finish() runs
53
+ run_outcome() and returns the outcome, with no record.
54
+
55
+ The recordings field (blackboard key RECORDINGS_KEY) is a
56
+ RecordingLog the dispatch registers at construction. Records land
57
+ there in order: event id, class name, dispatch args, start / end
58
+ times, wake flag, outcome -- plus, on the sim clock, the quoted
59
+ duration, and actual_duration when the event set it. A preempted
60
+ recording event gets a record too, with outcome PREEMPTED, its
61
+ elapsed time (and, on the sim clock, its progress fraction), and on
62
+ the wall clock whatever run_outcome() returned as partial_outcome.
63
+ A training or inference loop consumes the log by take() -- block for
64
+ the next record, drain everything that has landed -- and engages the
65
+ policy on every record whose wake is set. Draining on use is the
66
+ field's hygiene: it has exactly one consumer, so the buffer never
67
+ holds more than one decision interval's records. The dispatch
68
+ itself never engages a policy; notification stops at the field.
69
+
70
+ Clock settling (sim clock only): a quote is a commitment the outcome
71
+ may settle short of. When run_outcome() sets self.actual_duration
72
+ below the quote (a navigation that blocks mid-plan is the canonical
73
+ case), SimClockRecordingDispatch settles the clock back to
74
+ started_at + actual_duration. Settling is only allowed while
75
+ step_world() is the base no-op -- i.e. when the events move the
76
+ world themselves. With an engine adapter (MuJoCo, PyBullet) the
77
+ world has already been stepped to the quote, and settling back
78
+ would step that interval twice, so it raises instead. An
79
+ actual_duration beyond the quote is recorded and ignored (the quote
80
+ is the commitment).
81
+
82
+ Preemption (cancel):
83
+ sim clock -- cancel(event_id) removes the pending completion; the
84
+ event never runs. The PREEMPTED record is written at cancel
85
+ time, with elapsed and progress.
86
+ wall clock -- cancel(event_id) asks the running event to stop: it
87
+ sets the event's preempt request and terminates its thread's
88
+ stop flag. Stopping is the event's job (thread cooperation):
89
+ run_outcome() polls preempt_requested() / waits on
90
+ wait_preempt(), or cancels its own action, then returns its
91
+ partial outcome. The PREEMPTED record is written when the
92
+ event actually returns, with the real elapsed time. There is
93
+ no timeout: an event that never returns writes no record.
94
+ """
95
+ from __future__ import annotations
96
+
97
+ import threading
98
+ import time
99
+
100
+ from eventdispatch.common1 import ClockedEvent
101
+ from eventdispatch.composite_semaphore import CSBQCVED
102
+ from eventdispatch.core import EventThread
103
+ from eventdispatch.sim import SimClockCSBQCVED
104
+
105
+ RECORDINGS_KEY = "recordings"
106
+
107
+ PREEMPTED = "PREEMPTED"
108
+
109
+
110
+ class RecordingLog:
111
+ """The recordings field: a condition-signalled buffer of
112
+ records, in order, drained on use.
113
+
114
+ Writers append (the recording dispatch, on whichever thread
115
+ the completion lands). The one reader -- the harness --
116
+ consumes by take(): records leave the buffer as they are read,
117
+ so the buffer stays bounded by one decision interval no matter
118
+ how long the run. snapshot() is a non-consuming peek, for tests
119
+ and diagnostics only; it is not a read path.
120
+ """
121
+
122
+ def __init__(self):
123
+ self._records = []
124
+ self._cv = threading.Condition()
125
+
126
+ def append(self, record):
127
+ with self._cv:
128
+ self._records.append(record)
129
+ self._cv.notify_all()
130
+
131
+ def take(self, timeout=None):
132
+ """Block until at least one record exists, then drain and
133
+ return everything buffered, in order. Returns [] on
134
+ timeout."""
135
+ with self._cv:
136
+ if not self._cv.wait_for(lambda: len(self._records) > 0,
137
+ timeout):
138
+ return []
139
+ records, self._records = self._records, []
140
+ return records
141
+
142
+ @property
143
+ def pending(self):
144
+ """Records buffered right now (not yet taken)."""
145
+ with self._cv:
146
+ return len(self._records)
147
+
148
+ def snapshot(self):
149
+ """Everything buffered, as a list copy. Does not drain."""
150
+ with self._cv:
151
+ return list(self._records)
152
+
153
+
154
+ class RecordingEvent(ClockedEvent):
155
+ """Event base class that opts in to recording (module
156
+ docstring). Subclasses override dispatch() and run_outcome(),
157
+ and optionally on_preempt(); never finish().
158
+
159
+ wake: class-level default True; run_outcome() / on_preempt()
160
+ may set self.wake. A record whose wake is True always wakes the
161
+ policy.
162
+
163
+ actual_duration: None unless the outcome consumed less than
164
+ quoted (sim clock settling, module docstring). Recorded when
165
+ set, on either clock.
166
+
167
+ deserialize drops CommonEvent's non-empty-tail check: a
168
+ zero-arg event (an empty tail) is dispatchable from the queue.
169
+ """
170
+
171
+ wake = True
172
+ actual_duration = None
173
+
174
+ def __init__(self, event_id, *args, **kwargs):
175
+ super(RecordingEvent, self).__init__(event_id, *args, **kwargs)
176
+ self._preempt = threading.Event()
177
+
178
+ @staticmethod
179
+ def deserialize(ed, blackboard, *args, **kwargs):
180
+ tokens = args[0] if args else []
181
+ return (ed.reserve_event_id(), blackboard), tuple(tokens)
182
+
183
+ def dispatch(self, ed, *args, **kwargs):
184
+ """Stash the args and return a duration quote. The default
185
+ quotes nothing, which only the wall clock accepts; events
186
+ that run on the sim clock override this."""
187
+ return None
188
+
189
+ def run_outcome(self, ed, *args, **kwargs):
190
+ raise NotImplementedError(
191
+ "recording protocol: run_outcome() does the work and "
192
+ "returns the outcome")
193
+
194
+ def on_preempt(self, ed):
195
+ """Optional preemption hook (module docstring). May set
196
+ self.wake; may return a dict of notes for the record; must
197
+ not mutate world state."""
198
+ return None
199
+
200
+ def finish(self, ed, *args, **kwargs):
201
+ """Only reached on a dispatch that does not record:
202
+ run the outcome, record nothing."""
203
+ return self.run_outcome(ed, *args, **kwargs)
204
+
205
+ # -- wall clock thread cooperation -----------------------------
206
+ def preempt_requested(self):
207
+ """True once the dispatch has asked this event to stop."""
208
+ return self._preempt.is_set()
209
+
210
+ def wait_preempt(self, timeout=None):
211
+ """Block until a preempt is requested or timeout passes;
212
+ True if requested. Use as an interruptible sleep."""
213
+ return self._preempt.wait(timeout)
214
+
215
+
216
+ class RecordingMixin:
217
+ """The dispatch side of recording (module docstring).
218
+
219
+ Mixed in ahead of a dispatch class that provides `now` and
220
+ the completion path (dispatch_finish). Recording events get
221
+ records; every other event passes through untouched. The
222
+ clock-specific parts are the hooks _outcome_of, _clock_fields
223
+ and _settle, implemented by each recording dispatch.
224
+ """
225
+
226
+ def __init__(self, blackboard, name):
227
+ super(RecordingMixin, self).__init__(blackboard, name)
228
+ if RECORDINGS_KEY not in blackboard:
229
+ blackboard[RECORDINGS_KEY] = RecordingLog()
230
+ self._last_finished = None
231
+
232
+ @property
233
+ def recordings(self) -> RecordingLog:
234
+ return self.blackboard[RECORDINGS_KEY]
235
+
236
+ # -- records ----------------------------------------------------
237
+ def _record(self, event, args, outcome, **fields):
238
+ record = {
239
+ "event_id": event.get_id(),
240
+ "event": type(event).__name__,
241
+ "args": [list(a) if isinstance(a, (list, tuple))
242
+ else a for a in args],
243
+ "started_at": event.started_at,
244
+ "t": self.now,
245
+ }
246
+ record.update(self._clock_fields(event))
247
+ record["wake"] = bool(event.wake)
248
+ record["outcome"] = outcome
249
+ if event.actual_duration is not None:
250
+ record["actual_duration"] = event.actual_duration
251
+ record.update(fields)
252
+ self.blackboard[RECORDINGS_KEY].append(record)
253
+ self._last_finished = self._note(type(event).__name__, outcome)
254
+ return record
255
+
256
+ def _record_preempted(self, event, args, **fields):
257
+ notes = event.on_preempt(self)
258
+ if isinstance(notes, dict) and notes:
259
+ fields["notes"] = notes
260
+ fields["elapsed"] = event.elapsed()
261
+ progress = event.progress()
262
+ if progress is not None:
263
+ fields["progress"] = progress
264
+ return self._record(event, args, PREEMPTED, **fields)
265
+
266
+ @staticmethod
267
+ def _note(name, outcome):
268
+ if isinstance(outcome, dict):
269
+ outcome = outcome.get("outcome")
270
+ if isinstance(outcome, str) and outcome:
271
+ return "{} {}".format(name, outcome)
272
+ return name
273
+
274
+ # -- the completion path ----------------------------------------
275
+ def dispatch_finish(self, event, *args, **kwargs):
276
+ if not isinstance(event, RecordingEvent):
277
+ return super(RecordingMixin, self).dispatch_finish(
278
+ event, *args, **kwargs)
279
+ event_id = event.get_id()
280
+ with self.dispatch_mutex:
281
+ self.thread_registry.pop(event_id, None)
282
+ outcome = self._outcome_of(event, *args, **kwargs)
283
+ if self._was_preempted(event):
284
+ self._record_preempted(event, args, partial_outcome=outcome)
285
+ else:
286
+ self._record(event, args, outcome)
287
+ self._settle(event)
288
+ self.release_event_id(event_id)
289
+ return outcome
290
+
291
+ # -- hooks (per clock) ------------------------------------------
292
+ def _outcome_of(self, event, *args, **kwargs):
293
+ raise NotImplementedError
294
+
295
+ def _clock_fields(self, event):
296
+ return {}
297
+
298
+ def _was_preempted(self, event):
299
+ return False
300
+
301
+ def _settle(self, event):
302
+ pass
303
+
304
+ # -- cycle annotation -------------------------------------------
305
+ def post_cb(self, blackboard):
306
+ """The base cycle marker, annotated with the recording
307
+ event whose record landed most recently (it may lag the
308
+ finish by one cycle); plain marker otherwise."""
309
+ note = getattr(self, "_last_finished", None)
310
+ if note is None:
311
+ super(RecordingMixin, self).post_cb(blackboard)
312
+ return
313
+ self._last_finished = None
314
+ self.internal_log("POST_CB! (finished: {})".format(note))
315
+
316
+
317
+ class SimClockRecordingDispatch(RecordingMixin, SimClockCSBQCVED):
318
+ """Recording on the simulated clock (module docstring).
319
+
320
+ Recording events must quote a duration; run_outcome() runs at
321
+ completion time on the driver thread. Records carry the quoted
322
+ duration. Settling is guarded: allowed only while step_world()
323
+ is the base no-op.
324
+ """
325
+
326
+ def _outcome_of(self, event, *args, **kwargs):
327
+ return event.run_outcome(self, *args, **kwargs)
328
+
329
+ def _clock_fields(self, event):
330
+ return {"duration": event.quoted_duration}
331
+
332
+ def _settle(self, event):
333
+ if event.actual_duration is None or event.started_at is None:
334
+ return
335
+ settled = event.started_at + event.actual_duration
336
+ if settled > self.now:
337
+ return # beyond the quote: recorded, never settled
338
+ if settled == self.now:
339
+ return
340
+ if (type(self).step_world
341
+ is not SimClockCSBQCVED.step_world):
342
+ raise RuntimeError(
343
+ "{}: cannot settle the clock for {} (event {}) back "
344
+ "from {} to {}: step_world() steps an engine, which "
345
+ "has already advanced to the quote. Quote shorter, "
346
+ "or keep settling to worlds the events move "
347
+ "themselves.".format(
348
+ type(self).__name__, type(event).__name__,
349
+ event.get_id(), self.now, settled))
350
+ if self._pending and settled > self._pending[0][0]:
351
+ return
352
+ self.now = settled
353
+ bb = event.blackboard
354
+ if bb is not None and "sim" in bb:
355
+ bb["sim"].t = settled
356
+
357
+ def cancel(self, event_id):
358
+ """Preempt a pending event: it never runs. A recording
359
+ event gets its PREEMPTED record now."""
360
+ entry = self._pending_map.get(event_id)
361
+ if entry is not None and isinstance(entry[0], RecordingEvent):
362
+ event, dispatch_args = entry
363
+ self._record_preempted(event, dispatch_args)
364
+ super(SimClockRecordingDispatch, self).cancel(event_id)
365
+
366
+
367
+ class WallClockRecordingDispatch(RecordingMixin, CSBQCVED):
368
+ """Recording on the wall clock (module docstring).
369
+
370
+ A recording event's dispatch() runs inline (it stashes the
371
+ args; its return is ignored), then run_outcome() runs on the
372
+ event's own thread; when it returns, the record is written.
373
+ Any other event is dispatched exactly as CSBQCVED does. `now`
374
+ is time.monotonic(), in seconds. No timeout, no quote.
375
+ """
376
+
377
+ def __init__(self, blackboard, name):
378
+ super(WallClockRecordingDispatch, self).__init__(blackboard, name)
379
+ self._live = {} # event_id -> event
380
+ self._cancelled = set()
381
+ self._live_lock = threading.Lock()
382
+
383
+ @property
384
+ def now(self):
385
+ return time.monotonic()
386
+
387
+ def dispatch(self, event, *args, **kwargs):
388
+ if not isinstance(event, RecordingEvent):
389
+ return super(WallClockRecordingDispatch, self).dispatch(
390
+ event, *args, **kwargs)
391
+ event.event_dispatch = self
392
+ event.dispatch(self, *args, **kwargs) # stash; quote ignored
393
+ event.started_at = self.now
394
+ event_id = event.get_id()
395
+ with self._live_lock:
396
+ self._live[event_id] = event
397
+
398
+ def work(event=event, args=args, kwargs=kwargs):
399
+ event._outcome = event.run_outcome(self, *args, **kwargs)
400
+
401
+ with self.dispatch_mutex:
402
+ self.thread_registry[event_id] = EventThread(
403
+ target=work,
404
+ callback=lambda event=event, args=args, kwargs=kwargs:
405
+ self.dispatch_finish(event, *args, **kwargs),
406
+ daemon=event.daemon)
407
+ self.thread_registry[event_id].start()
408
+
409
+ def _outcome_of(self, event, *args, **kwargs):
410
+ return getattr(event, "_outcome", None)
411
+
412
+ def _was_preempted(self, event):
413
+ event_id = event.get_id()
414
+ with self._live_lock:
415
+ self._live.pop(event_id, None)
416
+ if event_id in self._cancelled:
417
+ self._cancelled.discard(event_id)
418
+ return True
419
+ return False
420
+
421
+ def cancel(self, event_id):
422
+ """Ask a running recording event to stop (thread
423
+ cooperation); its PREEMPTED record is written when it
424
+ returns. A running plain event's thread gets its stop
425
+ flag set, as terminate() does."""
426
+ with self._live_lock:
427
+ event = self._live.get(event_id)
428
+ if event is not None:
429
+ self._cancelled.add(event_id)
430
+ event._preempt.set()
431
+ with self.dispatch_mutex:
432
+ thread = self.thread_registry.get(event_id)
433
+ if thread is not None:
434
+ thread.terminate()
@@ -59,11 +59,14 @@ runs that event in-sim like any other. Every other event
59
59
  lives within the sim: quoted, heaped, and finished in
60
60
  duration order.
61
61
 
62
- SimEvent is the Event base class for this dispatch: dispatch()
63
- quotes a duration, finish() is the completion step. The base
64
- stamps started_at / quoted_duration at dispatch and exposes the
65
- dispatch clock through the now() member function, so the same
66
- event interface is implemented against every simulator.
62
+ SimEvent is the plain Event base class for this dispatch:
63
+ dispatch() quotes a duration, finish() is the completion step.
64
+ The dispatch stamps started_at / quoted_duration on any event it
65
+ quotes, and ClockedEvent (eventdispatch.common1) exposes the
66
+ clock through now(), so the same event interface is implemented
67
+ against every simulator. Any event that quotes a duration runs
68
+ here -- a SimEvent, or a RecordingEvent (eventdispatch.learning)
69
+ on SimClockRecordingDispatch.
67
70
  Engine adapters subclass SimClockCSBQCVED and override
68
71
  step_world() only.
69
72
  """
@@ -72,12 +75,12 @@ from __future__ import annotations
72
75
  import heapq
73
76
  import itertools
74
77
 
75
- from eventdispatch.common1 import CommonEvent, bcolors, wrap_with_prints
78
+ from eventdispatch.common1 import ClockedEvent, bcolors, wrap_with_prints
76
79
  from eventdispatch.composite_semaphore import CSBQCVED, CSRelease, CSWait
77
80
  from eventdispatch.core import wrap_instance_method
78
81
 
79
82
 
80
- class SimEvent(CommonEvent):
83
+ class SimEvent(ClockedEvent):
81
84
  """Event base class for simulated-clock systems.
82
85
 
83
86
  Sim-time protocol (subclasses override both):
@@ -91,33 +94,12 @@ class SimEvent(CommonEvent):
91
94
 
92
95
  A cancelled event never reaches finish(): it never mutates
93
96
  state.
94
- """
95
97
 
96
- def __init__(self, event_id, *args, **kwargs):
97
- super(SimEvent, self).__init__(event_id, *args, **kwargs)
98
- # stamped by SimClockCSBQCVED.do_dispatch at quote time
99
- self.started_at = None
100
- self.quoted_duration = None
101
-
102
- def now(self):
103
- """Current simulated time, read from the running dispatch."""
104
- if self.event_dispatch is None:
105
- raise RuntimeError(
106
- "SimEvent.now(): event has not been dispatched")
107
- return self.event_dispatch.now
108
-
109
- def elapsed(self):
110
- """Simulated time since this event was dispatched."""
111
- if self.started_at is None:
112
- return None
113
- return self.now() - self.started_at
114
-
115
- def progress(self):
116
- """Elapsed fraction of the quoted duration, in [0, 1] at
117
- completion; None when the duration is 0 or unset."""
118
- if not self.quoted_duration:
119
- return None
120
- return self.elapsed() / self.quoted_duration
98
+ The clock stamps (started_at / quoted_duration) and helpers
99
+ (now / elapsed / progress) come from ClockedEvent
100
+ (eventdispatch.common1), shared with RecordingEvent
101
+ (eventdispatch.learning).
102
+ """
121
103
 
122
104
  def dispatch(self, ed, *args, **kwargs):
123
105
  raise NotImplementedError(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: eventdispatch
3
- Version: 0.2.31
3
+ Version: 0.3.0
4
4
  Summary: Event Dispatch: discrete time synchronization
5
5
  Home-page: http://github.com/cyan-at/python-eventdispatch
6
6
  Author: Charlie Yan
@@ -9,6 +9,7 @@ eventdispatch/composite_semaphore.py
9
9
  eventdispatch/core.py
10
10
  eventdispatch/example_core.py
11
11
  eventdispatch/example_cs.py
12
+ eventdispatch/example_learning.py
12
13
  eventdispatch/example_sim_mujoco.py
13
14
  eventdispatch/learning.py
14
15
  eventdispatch/sim.py
@@ -17,4 +18,5 @@ eventdispatch.egg-info/SOURCES.txt
17
18
  eventdispatch.egg-info/dependency_links.txt
18
19
  eventdispatch.egg-info/entry_points.txt
19
20
  eventdispatch.egg-info/requires.txt
20
- eventdispatch.egg-info/top_level.txt
21
+ eventdispatch.egg-info/top_level.txt
22
+ tests/test_recording.py
@@ -7,7 +7,7 @@ dependencies = [
7
7
  "argparse"
8
8
  ]
9
9
  name = "eventdispatch"
10
- version = "0.2.31"
10
+ version = "0.3.0"
11
11
  authors = [{name = "Charlie Yan", email = "cyanatg@gmail.com"}]
12
12
  dynamic = ["scripts"]
13
13
  description = "Event Dispatch: discrete time synchronization"
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name='eventdispatch',
5
- version='0.2.31',
5
+ version='0.3.0',
6
6
  description='Event Dispatch, a discrete time synchronizer',
7
7
  url='http://github.com/cyan-at/python-eventdispatch',
8
8
  author='Charlie Yan',
@@ -0,0 +1,233 @@
1
+ """Tests for the recording surface (eventdispatch.learning).
2
+
3
+ Run: python3 -m pytest tests/
4
+ """
5
+ import threading
6
+ import time
7
+
8
+ import pytest
9
+
10
+ from eventdispatch.common1 import CommonEvent
11
+ from eventdispatch.core import Blackboard
12
+ from eventdispatch.learning import (
13
+ PREEMPTED, RECORDINGS_KEY, RecordingEvent, RecordingLog,
14
+ SimClockRecordingDispatch, WallClockRecordingDispatch)
15
+ from eventdispatch.sim import SimClockCSBQCVED, SimEvent
16
+
17
+
18
+ # -- events -------------------------------------------------------------
19
+ class Move(RecordingEvent):
20
+ """Quotes args[0]; optionally reports an early finish args[1]."""
21
+ def dispatch(self, ed, quote, actual=None):
22
+ self.quote, self.actual = float(quote), actual
23
+ return self.quote
24
+
25
+ def run_outcome(self, ed, quote, actual=None):
26
+ self.blackboard["ran"].append(self.get_id())
27
+ if actual is not None:
28
+ self.actual_duration = float(actual)
29
+ self.wake = False
30
+ return "BLOCKED"
31
+ return "ARRIVED"
32
+
33
+
34
+ class QuietPreempt(Move):
35
+ def on_preempt(self, ed):
36
+ self.wake = False
37
+ return {"reason": "test"}
38
+
39
+
40
+ class Tick(SimEvent):
41
+ """A plain sim event: runs, never recorded."""
42
+ def dispatch(self, ed, *args):
43
+ return 1.0
44
+
45
+ def finish(self, ed, *args):
46
+ self.blackboard["ran"].append("tick")
47
+
48
+
49
+ class Sleep(RecordingEvent):
50
+ """Wall clock: sleeps args[0] s, cooperatively interruptible."""
51
+ def run_outcome(self, ed, secs):
52
+ if self.wait_preempt(float(secs)):
53
+ return "STOPPED_EARLY"
54
+ return "SLEPT"
55
+
56
+ def on_preempt(self, ed):
57
+ self.wake = False
58
+
59
+
60
+ class Plain(CommonEvent):
61
+ """A plain wall-clock event: runs on its thread, never recorded."""
62
+ def dispatch(self, ed, *args):
63
+ self.blackboard["ran"].append("plain")
64
+
65
+ def finish(self, ed, *args):
66
+ self.blackboard["plain_done"].set()
67
+
68
+
69
+ def make_bb(**classes):
70
+ bb = Blackboard()
71
+ bb["ran"] = []
72
+ bb["plain_done"] = threading.Event()
73
+ bb.update(classes)
74
+ return bb
75
+
76
+
77
+ def sim(cls=SimClockRecordingDispatch):
78
+ bb = make_bb(Move=Move, QuietPreempt=QuietPreempt, Tick=Tick)
79
+ return bb, cls(bb, "ed")
80
+
81
+
82
+ # -- sim clock ------------------------------------------------------------
83
+ def test_sim_records_completion_with_quote():
84
+ bb, ed = sim()
85
+ assert isinstance(bb[RECORDINGS_KEY], RecordingLog)
86
+ assert ed.do_dispatch(bb, ["Move", 3])
87
+ ed.advance_one()
88
+ (rec,) = ed.recordings.take(timeout=1)
89
+ assert rec["event"] == "Move" and rec["outcome"] == "ARRIVED"
90
+ assert rec["started_at"] == 0 and rec["t"] == 3 and rec["duration"] == 3
91
+ assert rec["wake"] is True and "actual_duration" not in rec
92
+
93
+
94
+ def test_sim_plain_event_runs_unrecorded():
95
+ bb, ed = sim()
96
+ assert ed.do_dispatch(bb, ["Tick", 0])
97
+ ed.advance_one()
98
+ assert bb["ran"] == ["tick"]
99
+ assert ed.recordings.pending == 0
100
+
101
+
102
+ def test_sim_requires_a_quote():
103
+ bb, ed = sim()
104
+
105
+ class NoQuote(RecordingEvent):
106
+ def run_outcome(self, ed):
107
+ return "X"
108
+ bb["NoQuote"] = NoQuote
109
+ assert not ed.do_dispatch(bb, ["NoQuote"])
110
+
111
+
112
+ def test_sim_settles_early_finish():
113
+ bb, ed = sim()
114
+ assert ed.do_dispatch(bb, ["Move", 5, 2])
115
+ ed.advance_one()
116
+ (rec,) = ed.recordings.take(timeout=1)
117
+ assert rec["outcome"] == "BLOCKED" and rec["actual_duration"] == 2
118
+ assert rec["wake"] is False
119
+ assert ed.now == 2 # settled back from the quote
120
+
121
+
122
+ def test_sim_actual_beyond_quote_is_not_settled():
123
+ bb, ed = sim()
124
+ assert ed.do_dispatch(bb, ["Move", 2, 5])
125
+ ed.advance_one()
126
+ (rec,) = ed.recordings.take(timeout=1)
127
+ assert rec["actual_duration"] == 5 and ed.now == 2
128
+
129
+
130
+ def test_sim_settle_refused_with_engine_adapter():
131
+ class Engine(SimClockRecordingDispatch):
132
+ def step_world(self, from_t, to_t):
133
+ pass # stands in for mj_step
134
+ bb, ed = sim(Engine)
135
+ assert ed.do_dispatch(bb, ["Move", 5, 2])
136
+ with pytest.raises(RuntimeError, match="cannot settle"):
137
+ ed.advance_one()
138
+
139
+
140
+ def test_sim_cancel_writes_preempted_and_never_runs():
141
+ bb, ed = sim()
142
+ assert ed.do_dispatch(bb, ["Move", 10])
143
+ assert ed.do_dispatch(bb, ["QuietPreempt", 4])
144
+ ids = list(ed._pending_map)
145
+ move_id, quiet_id = ids[0], ids[1]
146
+ ed.cancel(quiet_id)
147
+ (pre,) = ed.recordings.take(timeout=1)
148
+ assert pre["outcome"] == PREEMPTED and pre["event"] == "QuietPreempt"
149
+ assert pre["wake"] is False and pre["notes"] == {"reason": "test"}
150
+ assert pre["elapsed"] == 0 and pre["progress"] == 0
151
+ assert ed.advance_one() == move_id
152
+ assert bb["ran"] == [move_id] # the cancelled one never ran
153
+ (done,) = ed.recordings.take(timeout=1)
154
+ assert done["event"] == "Move"
155
+
156
+
157
+ def test_recording_event_on_plain_sim_dispatch_is_unrecorded():
158
+ bb = make_bb(Move=Move)
159
+ ed = SimClockCSBQCVED(bb, "ed")
160
+ assert ed.do_dispatch(bb, ["Move", 1])
161
+ ed.advance_one()
162
+ assert bb["ran"] and RECORDINGS_KEY not in bb
163
+
164
+
165
+ def test_sim_run_driver_end_to_end():
166
+ bb, ed = sim()
167
+ bb["ed_queue"].extend([["Move", 2], ["Tick", 0], ["Move", 1]])
168
+ t = threading.Thread(target=ed.run, args=(bb, "ed"), daemon=True)
169
+ t.start()
170
+ got = []
171
+ deadline = time.time() + 5
172
+ while len(got) < 2 and time.time() < deadline:
173
+ got += ed.recordings.take(timeout=0.5)
174
+ bb["ed_hb"] = False
175
+ with bb["ed_mutex"]:
176
+ bb["ed_cv"].notify_all()
177
+ t.join(timeout=2)
178
+ assert [r["t"] for r in got] == [1, 2]
179
+ assert "tick" in bb["ran"]
180
+
181
+
182
+ # -- wall clock -------------------------------------------------------------
183
+ def wall():
184
+ bb = make_bb(Sleep=Sleep, Plain=Plain)
185
+ return bb, WallClockRecordingDispatch(bb, "wed")
186
+
187
+
188
+ def test_wall_records_real_times_without_quote():
189
+ bb, ed = wall()
190
+ assert ed.do_dispatch(bb, ["Sleep", 0.05])
191
+ (rec,) = ed.recordings.take(timeout=5)
192
+ assert rec["outcome"] == "SLEPT" and rec["wake"] is True
193
+ assert "duration" not in rec
194
+ assert rec["t"] - rec["started_at"] >= 0.04
195
+
196
+
197
+ def test_wall_plain_event_runs_unrecorded():
198
+ bb, ed = wall()
199
+ assert ed.do_dispatch(bb, ["Plain", 0])
200
+ assert bb["plain_done"].wait(5)
201
+ assert bb["ran"] == ["plain"]
202
+ assert ed.recordings.pending == 0
203
+
204
+
205
+ def test_wall_cancel_is_cooperative_and_recorded_on_return():
206
+ bb, ed = wall()
207
+ assert ed.do_dispatch(bb, ["Sleep", 30])
208
+ event_id = next(iter(ed._live))
209
+ time.sleep(0.05)
210
+ t0 = time.monotonic()
211
+ ed.cancel(event_id)
212
+ (rec,) = ed.recordings.take(timeout=5)
213
+ assert time.monotonic() - t0 < 5 # stopped early, not after 30 s
214
+ assert rec["outcome"] == PREEMPTED
215
+ assert rec["partial_outcome"] == "STOPPED_EARLY"
216
+ assert rec["wake"] is False # on_preempt ran last and won
217
+ assert rec["elapsed"] >= 0.04 and "progress" not in rec
218
+ assert not ed._live and not ed._cancelled
219
+
220
+
221
+ def test_wall_dispatch_return_value_is_ignored():
222
+ bb, ed = wall()
223
+
224
+ class Quotes(RecordingEvent):
225
+ def dispatch(self, ed, *args):
226
+ return 123.0
227
+
228
+ def run_outcome(self, ed, *args):
229
+ return "OK"
230
+ bb["Quotes"] = Quotes
231
+ assert ed.do_dispatch(bb, ["Quotes"])
232
+ (rec,) = ed.recordings.take(timeout=5)
233
+ assert rec["outcome"] == "OK" and "duration" not in rec
@@ -1,250 +0,0 @@
1
- """Learning surface of the eventdispatch framework.
2
-
3
- Every language implementation of the framework keeps one module like
4
- this one: the pair that learning / training code programs against.
5
-
6
- TrainingEvent -- the Event base class for trainable systems:
7
- SimEvent (eventdispatch.sim) whose finish()
8
- records its completion (below).
9
- TrainingDispatch -- the Dispatch subclass that runs them:
10
- SimClockCSBQCVED (eventdispatch.sim) plus a
11
- registered blackboard asset, the completions
12
- field (below).
13
-
14
- Training code imports from here, never from core internals.
15
-
16
- Sim-time protocol (the contract TrainingEvent subclasses follow):
17
-
18
- dispatch(ed) -> duration in the clock's units. Scheduling only:
19
- quote the duration, stash the args. No outcome sampling, no
20
- mutation.
21
- run_outcome(ed) -> the outcome (the release). Called by finish()
22
- at completion time, against fresh state: run the outcome
23
- model, apply the event's effects, return what happened.
24
- finish(ed) -> the completion step, implemented by the base
25
- class: it calls run_outcome(), appends the completion record
26
- to the completions field, and returns the outcome. Subclasses
27
- override run_outcome(), never finish().
28
-
29
- A cancelled event never reaches finish(): it never mutates state.
30
-
31
- The completions field (blackboard key COMPLETIONS_KEY) is a
32
- CompletionLog the dispatch registers at construction. Every
33
- TrainingEvent completion lands there, in completion order: event
34
- id, class name, dispatch args, start / completion times, quoted
35
- duration, wake flag, outcome. That log is the signal board's first
36
- area and the harness's whole input: a training or inference loop
37
- consumes it by take() -- block for the next completion, drain
38
- everything that has landed -- and decides from the records; a
39
- record whose wake flag is set is a decision point. Draining on
40
- use is the field's hygiene: it has exactly one consumer, so the
41
- buffer never holds more than one decision interval's records.
42
- The dispatch itself never engages a policy; notification stops
43
- at the field. The wake flag is read after finish() runs, so an
44
- event can set it from its outcome (wake on failure, sleep on
45
- routine success).
46
-
47
- The dispatch drives the clock, and a quote is a commitment the
48
- outcome may settle short of: when an event's outcome model
49
- consumes less than it quoted (a navigation that blocks mid-plan
50
- is the canonical case), run_outcome() sets self.actual_duration
51
- to the ticks actually consumed, the mismatch is captured in the
52
- completion record, and TrainingDispatch settles the clock at
53
- finish to started_at + actual_duration. Settling only moves the
54
- clock back from the quote, and never across another pending
55
- completion; an actual_duration beyond the quote is ignored (the
56
- quote is the commitment).
57
- """
58
- from __future__ import annotations
59
-
60
- import threading
61
-
62
- from eventdispatch.sim import SimClockCSBQCVED, SimEvent
63
-
64
- COMPLETIONS_KEY = "training_completions"
65
-
66
-
67
- class CompletionLog:
68
- """The completions field: a condition-signalled buffer of
69
- completion records, in completion order, drained on use.
70
-
71
- Writers append (TrainingEvent.finish, on the dispatch's
72
- driver thread). The one reader -- the harness -- consumes by
73
- take(): records leave the buffer as they are read, so the
74
- buffer stays bounded by one decision interval no matter how
75
- long the run. snapshot() is a non-consuming peek, for tests
76
- and diagnostics only; it is not a read path.
77
- """
78
-
79
- def __init__(self):
80
- self._records = []
81
- self._cv = threading.Condition()
82
-
83
- def append(self, record):
84
- with self._cv:
85
- self._records.append(record)
86
- self._cv.notify_all()
87
-
88
- def take(self, timeout=None):
89
- """Block until at least one record exists, then drain and
90
- return everything buffered, in completion order. Returns
91
- [] on timeout."""
92
- with self._cv:
93
- if not self._cv.wait_for(lambda: len(self._records) > 0,
94
- timeout):
95
- return []
96
- records, self._records = self._records, []
97
- return records
98
-
99
- @property
100
- def pending(self):
101
- """Records buffered right now (not yet taken)."""
102
- with self._cv:
103
- return len(self._records)
104
-
105
- def snapshot(self):
106
- """Everything buffered, as a list copy. Does not drain."""
107
- with self._cv:
108
- return list(self._records)
109
-
110
-
111
- class TrainingEvent(SimEvent):
112
- """Event base class for trainable systems.
113
-
114
- Inherits the SimEvent time protocol (started_at /
115
- quoted_duration stamps, now() on the dispatch clock) and adds
116
- the completion record: finish() runs the subclass's
117
- run_outcome(), appends the record to the blackboard's
118
- completions field when the running dispatch registered one,
119
- and returns the outcome. On a dispatch without the field,
120
- finish() is SimEvent's completion step with no recording.
121
-
122
- wake: the harness's engagement hint, read after finish() --
123
- class-level default True; run_outcome() may set self.wake
124
- per outcome.
125
-
126
- actual_duration: None unless the outcome consumed less than
127
- quoted; run_outcome() sets it (ticks, the clock's units) and
128
- TrainingDispatch settles the clock at finish (module
129
- docstring). Captured in the completion record when set.
130
-
131
- deserialize drops CommonEvent's non-empty-tail check: a
132
- zero-arg event (an empty tail) is dispatchable from the queue.
133
- """
134
-
135
- wake = True
136
- actual_duration = None
137
-
138
- @staticmethod
139
- def deserialize(ed, blackboard, *args, **kwargs):
140
- tokens = args[0] if args else []
141
- return (ed.reserve_event_id(), blackboard), tuple(tokens)
142
-
143
- def run_outcome(self, ed, *args, **kwargs):
144
- raise NotImplementedError(
145
- "training protocol: run_outcome() runs the outcome "
146
- "model at completion and returns the outcome")
147
-
148
- def finish(self, ed, *args, **kwargs):
149
- outcome = self.run_outcome(ed, *args, **kwargs)
150
- bb = self.blackboard
151
- if bb is not None and COMPLETIONS_KEY in bb:
152
- record = {
153
- "event_id": self.get_id(),
154
- "event": type(self).__name__,
155
- "args": [list(a) if isinstance(a, (list, tuple))
156
- else a for a in args],
157
- "started_at": self.started_at,
158
- "t": self.now(),
159
- "duration": self.quoted_duration,
160
- "wake": bool(self.wake),
161
- "outcome": outcome,
162
- }
163
- if self.actual_duration is not None:
164
- record["actual_duration"] = self.actual_duration
165
- bb[COMPLETIONS_KEY].append(record)
166
- return outcome
167
-
168
-
169
- class TrainingDispatch(SimClockCSBQCVED):
170
- """Dispatch for trainable systems: SimClockCSBQCVED plus the
171
- completions field, registered on the blackboard at construction
172
- under COMPLETIONS_KEY (an existing CompletionLog there is kept),
173
- plus clock settling at finish (dispatch_finish, below).
174
-
175
- Nothing else is added yet: the training loop that steps world
176
- and iterables, the interrupt-with-accounting path, and policy
177
- engagement all belong to the harness that reads the field.
178
- """
179
-
180
- def __init__(self, blackboard, name):
181
- super(TrainingDispatch, self).__init__(blackboard, name)
182
- if COMPLETIONS_KEY not in blackboard:
183
- blackboard[COMPLETIONS_KEY] = CompletionLog()
184
- self._last_finished = None
185
-
186
- def dispatch_finish(self, event, *args, **kwargs):
187
- """The library's completion step, plus clock settling:
188
- when a TrainingEvent reports an actual_duration below its
189
- quote, the clock (and the blackboard's "sim" entry, when
190
- one is present) settles to started_at + actual_duration
191
- -- never forward past the quote, never back across
192
- another pending completion."""
193
- super(TrainingDispatch, self).dispatch_finish(
194
- event, *args, **kwargs)
195
- if (isinstance(event, TrainingEvent)
196
- and event.actual_duration is not None
197
- and event.started_at is not None):
198
- settled = event.started_at + event.actual_duration
199
- if settled <= self.now and (
200
- not self._pending
201
- or settled <= self._pending[0][0]):
202
- self.now = settled
203
- bb = event.blackboard
204
- if bb is not None and "sim" in bb:
205
- bb["sim"].t = settled
206
- self._last_finished = self._finished_note(event)
207
-
208
- def _finished_note(self, event):
209
- """'Name OUTCOME' for the event that just finished, for
210
- post_cb's annotation. The outcome is read back from the
211
- record finish() just appended, matched on event_id;
212
- an outcome carrying no name, or a record the harness
213
- already drained, degrades to the class name alone."""
214
- name = type(event).__name__
215
- try:
216
- records = self.blackboard[COMPLETIONS_KEY].snapshot()
217
- except Exception:
218
- return name
219
- for record in reversed(records):
220
- if record.get("event_id") != event.get_id():
221
- continue
222
- outcome = record.get("outcome")
223
- if isinstance(outcome, dict):
224
- outcome = outcome.get("outcome")
225
- if isinstance(outcome, str) and outcome:
226
- return "{} {}".format(name, outcome)
227
- return name
228
- return name
229
-
230
- def post_cb(self, blackboard):
231
- """The base cycle marker, annotated with the event whose
232
- finish woke this cycle. advance_one fires one completion
233
- per cycle, after post_cb, so the annotation lags the
234
- finish by exactly one cycle; a cycle no finish preceded
235
- prints the plain marker."""
236
- note = getattr(self, "_last_finished", None)
237
- if note is None:
238
- super(TrainingDispatch, self).post_cb(blackboard)
239
- return
240
- self._last_finished = None
241
- self.internal_log("POST_CB! (finished: {})".format(note))
242
-
243
- @property
244
- def completions(self) -> CompletionLog:
245
- return self.blackboard[COMPLETIONS_KEY]
246
-
247
-
248
- # Backwards-compatible names (the learning surface's first draft).
249
- LearningEvent = TrainingEvent
250
- LearningDispatch = TrainingDispatch
File without changes
File without changes
File without changes
File without changes