Skip to main content

oa/ml/rl/environment/
session.rs

1//! Explicit execution lifecycle shared by native OA environments.
2
3use crate::{
4	Error, Event, Matrix, Result, Runtime,
5	runtime::{RecordingTransaction, RuntimeHandle},
6};
7
8use super::{EnvironmentSpec, EnvironmentTransition};
9
10/// Private command transaction and exact completion state for one environment.
11///
12/// Native environments embed this value and expose it through [`Environment`].
13/// It borrows the canonical Runtime recorder for each active transaction; it
14/// does not own another queue, allocator, scheduler, or execution graph.
15#[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	/// Construct an idle execution lifecycle over one Runtime.
26	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	/// Return whether the session accepts lifecycle commands.
109	pub const fn is_open(&self) -> bool {
110		!self.closed
111	}
112
113	/// Return whether an unsubmitted command transaction is active.
114	pub const fn has_active_recording(&self) -> bool {
115		self.recording.is_some()
116	}
117
118	/// Return whether one exact completion must be waited.
119	pub const fn has_pending_event(&self) -> bool {
120		self.pending.is_some()
121	}
122
123	/// Return the number of accepted submissions.
124	pub const fn submission_count(&self) -> u64 {
125		self.submission_count
126	}
127}
128
129/// Stateful native vector-environment behavior.
130///
131/// Implementations own semantic environment state and embed exactly one
132/// [`EnvironmentExecution`]. Public default methods own transaction state,
133/// validation boundaries, submission, and rollback; implementations only
134/// author reset/step/reset-completed commands and transactional host metadata.
135pub trait Environment {
136	/// Return the sole Runtime borrowed by this session.
137	fn runtime(&self) -> &Runtime;
138
139	/// Return the structural environment contract.
140	fn spec(&self) -> &EnvironmentSpec;
141
142	/// Return the positive vector-environment lane count.
143	fn environments(&self) -> u32;
144
145	/// Return the current device-resident observation.
146	fn observation(&self) -> &Matrix;
147
148	/// Return the embedded execution lifecycle.
149	fn execution(&self) -> &EnvironmentExecution;
150
151	/// Mutably return the embedded execution lifecycle.
152	fn execution_mut(&mut self) -> &mut EnvironmentExecution;
153
154	/// Record implementation-specific reset commands.
155	fn record_reset(&mut self, seed: u64) -> Result<()>;
156
157	/// Record one implementation-specific step.
158	fn record_step(&mut self, action: &Matrix) -> Result<EnvironmentTransition>;
159
160	/// Record reset of lanes that ended on the previous step.
161	fn record_reset_completed(&mut self) -> Result<()>;
162
163	/// Whether the environment currently holds committed episode state.
164	///
165	/// Drivers use this query to decide whether the initial training reset is
166	/// required: a freshly constructed environment without committed state
167	/// needs the seeded reset, while an environment whose state was restored
168	/// from a snapshot must not be reset again — a full reset would silently
169	/// discard the restored episode positions and corrupt exact resume. The
170	/// default preserves the construction-time contract: state arrives through
171	/// an explicit reset.
172	fn holds_committed_state(&self) -> bool {
173		false
174	}
175
176	/// Commit host metadata after queue submission accepts the transaction.
177	fn commit_recorded_state(&mut self) {}
178
179	/// Roll back host metadata after an unsubmitted transaction is discarded.
180	fn rollback_recorded_state(&mut self) {}
181
182	/// Begin or retain an idempotent command transaction.
183	///
184	/// # Errors
185	///
186	/// Returns an error when closed, awaiting completion, or the Runtime recorder
187	/// is unavailable.
188	fn begin(&mut self) -> Result<()> {
189		self.execution_mut().begin()
190	}
191
192	/// Record a full environment reset into the active transaction.
193	///
194	/// # Errors
195	///
196	/// Returns a lifecycle or implementation recording error. Failure cancels
197	/// the entire unsubmitted transaction and rolls back host metadata.
198	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	/// Record one environment step into the active transaction.
217	///
218	/// # Errors
219	///
220	/// Returns a lifecycle, action, transition, or implementation error. Failure
221	/// cancels the complete transaction and rolls back host metadata.
222	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	/// Record reset of completed lanes into the active transaction.
249	///
250	/// # Errors
251	///
252	/// Returns a lifecycle or implementation error and cancels on failure.
253	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	/// Submit the exact active command transaction without waiting.
264	///
265	/// # Errors
266	///
267	/// Returns an error without active work or when plan construction/queue
268	/// submission fails. Host metadata is committed only after acceptance.
269	fn submit(&mut self) -> Result<Event> {
270		submit_environment(self, false)
271	}
272
273	/// Submit the active transaction with device timestamps around its complete
274	/// command batch. The returned Event exposes the exact device duration;
275	/// explicit `wait` still releases this environment's pending lifecycle state.
276	///
277	/// # Errors
278	///
279	/// Returns the errors from `submit`, including unavailable device timestamps.
280	/// Failed submission rolls back host metadata just like untimed submission.
281	fn submit_timed(&mut self) -> Result<Event> {
282		submit_environment(self, true)
283	}
284
285	/// Wait for this environment's exact pending event.
286	///
287	/// # Errors
288	///
289	/// Returns an error for a foreign/stale event or completion failure.
290	fn wait(&mut self, event: &Event) -> Result<()> {
291		self.execution_mut().wait(event)
292	}
293
294	/// Discard only the unsubmitted command transaction.
295	///
296	/// # Errors
297	///
298	/// Returns an error when closed or after submission.
299	fn cancel(&mut self) -> Result<()> {
300		self.execution_mut().cancel()?;
301		self.rollback_recorded_state();
302		Ok(())
303	}
304
305	/// Explicitly complete submitted work, discard unsubmitted work, and close.
306	///
307	/// # Errors
308	///
309	/// Returns an exact completion failure. Repeated close is idempotent.
310	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}