oa/ml/rl/environment/
session.rs1use crate::{
4 Error, Event, Matrix, Result, Runtime,
5 runtime::{RecordingTransaction, RuntimeHandle},
6};
7
8use super::{EnvironmentSpec, EnvironmentTransition};
9
10#[must_use]
16pub struct EnvironmentExecution {
17 runtime: RuntimeHandle,
18 recording: Option<RecordingTransaction>,
19 pending: Option<Event>,
20 closed: bool,
21 submission_count: u64,
22}
23
24impl EnvironmentExecution {
25 pub fn new(runtime: &Runtime) -> Self {
27 Self {
28 runtime: runtime.handle(),
29 recording: None,
30 pending: None,
31 closed: false,
32 submission_count: 0,
33 }
34 }
35
36 fn begin(&mut self) -> Result<()> {
37 if self.closed {
38 return Err(Error::failed_precondition(
39 "environment execution session is closed",
40 ));
41 }
42 if self.pending.is_some() {
43 return Err(Error::failed_precondition(
44 "environment execution requires wait before another recording",
45 ));
46 }
47 if self.recording.is_none() {
48 self.recording = Some(RecordingTransaction::begin(self.runtime.clone())?);
49 }
50 Ok(())
51 }
52
53 fn submit(&mut self, timed: bool) -> Result<Event> {
54 let recording = self.recording.take().ok_or_else(|| {
55 Error::failed_precondition("environment submit requires an active recording")
56 })?;
57 let event = recording.submit(timed)?;
58 self.submission_count = self
59 .submission_count
60 .checked_add(1)
61 .ok_or_else(|| Error::resource_exhausted("environment submission count exhausted"))?;
62 self.pending = Some(event.clone());
63 Ok(event)
64 }
65
66 fn wait(&mut self, event: &Event) -> Result<()> {
67 let pending = self
68 .pending
69 .as_ref()
70 .ok_or_else(|| Error::failed_precondition("environment wait requires a submitted event"))?;
71 if !pending.same_as(event) {
72 return Err(Error::invalid_argument(
73 "environment wait event does not match its pending submission",
74 ));
75 }
76 event.wait()?;
77 self.pending = None;
78 Ok(())
79 }
80
81 fn cancel(&mut self) -> Result<()> {
82 if self.closed {
83 return Err(Error::failed_precondition(
84 "environment execution session is closed",
85 ));
86 }
87 if self.pending.is_some() {
88 return Err(Error::failed_precondition(
89 "environment cannot cancel submitted work",
90 ));
91 }
92 self.recording = None;
93 Ok(())
94 }
95
96 fn close(&mut self) -> Result<()> {
97 if self.closed {
98 return Ok(());
99 }
100 if let Some(event) = self.pending.clone() {
101 self.wait(&event)?;
102 }
103 self.recording = None;
104 self.closed = true;
105 Ok(())
106 }
107
108 pub const fn is_open(&self) -> bool {
110 !self.closed
111 }
112
113 pub const fn has_active_recording(&self) -> bool {
115 self.recording.is_some()
116 }
117
118 pub const fn has_pending_event(&self) -> bool {
120 self.pending.is_some()
121 }
122
123 pub const fn submission_count(&self) -> u64 {
125 self.submission_count
126 }
127}
128
129pub trait Environment {
136 fn runtime(&self) -> &Runtime;
138
139 fn spec(&self) -> &EnvironmentSpec;
141
142 fn environments(&self) -> u32;
144
145 fn observation(&self) -> &Matrix;
147
148 fn execution(&self) -> &EnvironmentExecution;
150
151 fn execution_mut(&mut self) -> &mut EnvironmentExecution;
153
154 fn record_reset(&mut self, seed: u64) -> Result<()>;
156
157 fn record_step(&mut self, action: &Matrix) -> Result<EnvironmentTransition>;
159
160 fn record_reset_completed(&mut self) -> Result<()>;
162
163 fn holds_committed_state(&self) -> bool {
173 false
174 }
175
176 fn commit_recorded_state(&mut self) {}
178
179 fn rollback_recorded_state(&mut self) {}
181
182 fn begin(&mut self) -> Result<()> {
189 self.execution_mut().begin()
190 }
191
192 fn reset(&mut self, seed: u64) -> Result<()> {
199 self.begin()?;
200 if let Err(error) = self.record_reset(seed) {
201 let _ = self.execution_mut().cancel();
202 self.rollback_recorded_state();
203 return Err(error);
204 }
205 if let Err(error) = self
206 .spec()
207 .validate_reset(self.observation(), self.environments())
208 {
209 let _ = self.execution_mut().cancel();
210 self.rollback_recorded_state();
211 return Err(error);
212 }
213 Ok(())
214 }
215
216 fn step(&mut self, action: &Matrix) -> Result<EnvironmentTransition> {
223 self.begin()?;
224 if let Err(error) = self.spec().validate_action(action, self.environments()) {
225 let _ = self.execution_mut().cancel();
226 self.rollback_recorded_state();
227 return Err(error);
228 }
229 let transition = match self.record_step(action) {
230 Ok(transition) => transition,
231 Err(error) => {
232 let _ = self.execution_mut().cancel();
233 self.rollback_recorded_state();
234 return Err(error);
235 }
236 };
237 if let Err(error) = self
238 .spec()
239 .validate_transition(action, &transition, self.environments())
240 {
241 let _ = self.execution_mut().cancel();
242 self.rollback_recorded_state();
243 return Err(error);
244 }
245 Ok(transition)
246 }
247
248 fn reset_completed(&mut self) -> Result<()> {
254 self.begin()?;
255 if let Err(error) = self.record_reset_completed() {
256 let _ = self.execution_mut().cancel();
257 self.rollback_recorded_state();
258 return Err(error);
259 }
260 Ok(())
261 }
262
263 fn submit(&mut self) -> Result<Event> {
270 submit_environment(self, false)
271 }
272
273 fn submit_timed(&mut self) -> Result<Event> {
282 submit_environment(self, true)
283 }
284
285 fn wait(&mut self, event: &Event) -> Result<()> {
291 self.execution_mut().wait(event)
292 }
293
294 fn cancel(&mut self) -> Result<()> {
300 self.execution_mut().cancel()?;
301 self.rollback_recorded_state();
302 Ok(())
303 }
304
305 fn close(&mut self) -> Result<()> {
311 self.execution_mut().close()?;
312 self.rollback_recorded_state();
313 Ok(())
314 }
315}
316
317fn submit_environment(environment: &mut (impl Environment + ?Sized), timed: bool) -> Result<Event> {
318 match environment.execution_mut().submit(timed) {
319 Ok(event) => {
320 environment.commit_recorded_state();
321 Ok(event)
322 }
323 Err(error) => {
324 environment.rollback_recorded_state();
325 Err(error)
326 }
327 }
328}