Skip to main content

oa/ml/rl/environment/trading/
state.rs

1//! Explicit host checkpoint of environment state, never an execution owner.
2use super::*;
3
4/// Versioned complete analytical lane state, bound to source tables/config.
5/// Snapshot only at exact completion; consumers persist this alongside model,
6/// optimizer, PPO action cursor and their own source-receipt identity.
7#[derive(Clone, Debug)]
8pub struct TradingState {
9	pub(super) config: u64,
10	pub(super) source: crate::crypto::Hash,
11	pub(super) ledger: Vec<f32>,
12	pub(super) metadata: Vec<u32>,
13	pub(super) done: Vec<u8>,
14	pub(super) observation: Vec<f32>,
15}
16impl TradingState {
17	/// Encode exact FP32/U32 state with a versioned header and corruption digest.
18	pub fn to_bytes(&self) -> Vec<u8> {
19		let mut out = b"OATRAD04".to_vec();
20		out.extend(self.config.to_le_bytes());
21		out.extend(self.source.as_bytes());
22		for n in [
23			self.ledger.len(),
24			self.metadata.len(),
25			self.done.len(),
26			self.observation.len(),
27		] {
28			out.extend((n as u64).to_le_bytes());
29		}
30		for n in &self.ledger {
31			out.extend(n.to_bits().to_le_bytes());
32		}
33		for n in &self.metadata {
34			out.extend(n.to_le_bytes());
35		}
36		out.extend(&self.done);
37		for n in &self.observation {
38			out.extend(n.to_bits().to_le_bytes());
39		}
40		let digest = crate::crypto::hash(&out);
41		out.extend(digest.as_bytes());
42		out
43	}
44	/// # Errors
45	/// Rejects unknown versions, malformed extents, nonfinite state or corruption.
46	pub fn new_from_bytes(bytes: &[u8]) -> Result<Self> {
47		let bad = || Error::invalid_argument("invalid trading environment checkpoint");
48		if bytes.len() < 112 || bytes.len() > 256 * 1024 * 1024 || &bytes[..8] != b"OATRAD04" {
49			return Err(bad());
50		}
51		let payload = &bytes[..bytes.len() - 32];
52		if crate::crypto::hash(payload).as_bytes() != &bytes[bytes.len() - 32..] {
53			return Err(bad());
54		}
55		let word = |at| u64::from_le_bytes(bytes[at..at + 8].try_into().expect("checked header"));
56		let mut sizes = [0; 4];
57		for (i, n) in sizes.iter_mut().enumerate() {
58			*n = usize::try_from(word(48 + i * 8)).map_err(|_| bad())?;
59			if *n > super::TRADING_ELEMENT_BUDGET {
60				return Err(bad());
61			}
62		}
63		let expected = sizes[0]
64			.checked_add(sizes[1])
65			.and_then(|n| n.checked_add(sizes[3]))
66			.and_then(|n| n.checked_mul(4))
67			.and_then(|n| n.checked_add(sizes[2]))
68			.and_then(|n| n.checked_add(80))
69			.ok_or_else(bad)?;
70		if expected != payload.len() {
71			return Err(bad());
72		}
73		let mut at = 80;
74		let mut take = |count: usize| {
75			let slice = &payload[at..at + count];
76			at += count;
77			slice
78		};
79		let ledger = take(sizes[0] * 4)
80			.as_chunks::<4>()
81			.0
82			.iter()
83			.map(|v| f32::from_bits(u32::from_le_bytes(*v)))
84			.collect::<Vec<_>>();
85		let metadata = take(sizes[1] * 4)
86			.as_chunks::<4>()
87			.0
88			.iter()
89			.map(|v| u32::from_le_bytes(*v))
90			.collect();
91		let done = take(sizes[2]).to_vec();
92		let observation = take(sizes[3] * 4)
93			.as_chunks::<4>()
94			.0
95			.iter()
96			.map(|v| f32::from_bits(u32::from_le_bytes(*v)))
97			.collect::<Vec<_>>();
98		if ledger.iter().chain(&observation).any(|v| !v.is_finite()) || done.iter().any(|v| *v > 1) {
99			return Err(bad());
100		}
101		Ok(Self {
102			config: word(8),
103			source: crate::crypto::Hash::new_from_bytes(&bytes[16..48])?,
104			ledger,
105			metadata,
106			done,
107			observation,
108		})
109	}
110}
111
112pub(super) fn fingerprint(
113	tables: &TradingTables,
114	series: &[TradingSeries],
115) -> Result<crate::crypto::Hash> {
116	let mut hash = crate::crypto::Hasher::new();
117	hash.update(b"oa.trading.source.v3")?;
118	for values in [&tables.market, &tables.features, &tables.rules] {
119		hash.update(&(values.len() as u64).to_le_bytes())?;
120		for chunk in values.chunks(4096) {
121			let bytes = chunk
122				.iter()
123				.flat_map(|v| v.to_bits().to_le_bytes())
124				.collect::<Vec<_>>();
125			hash.update(&bytes)?;
126		}
127	}
128	for v in &tables.bounds {
129		hash.update(&v.to_le_bytes())?;
130	}
131	for s in series {
132		for t in &s.timestamps {
133			hash.update(&t.to_le_bytes())?;
134		}
135	}
136	Ok(hash.finalize())
137}
138impl TradingEnvironment<'_> {
139	/// Explicitly synchronize and read a portable exact environment snapshot.
140	/// # Errors
141	/// Requires healthy initialized state and no open environment transaction.
142	pub fn snapshot(&self) -> Result<TradingState> {
143		self.runtime.checkpoint()?.wait()?;
144		self.check_status()?;
145		Ok(TradingState {
146			config: self.config.identity(),
147			source: self.source,
148			ledger: self.ledger.read_f32()?,
149			metadata: self.meta.read::<u32>()?,
150			done: self.done.read::<u8>()?,
151			observation: self.observation.read_f32()?,
152		})
153	}
154	/// Restore into unchanged source/config and stable captured buffers.
155	/// # Errors
156	/// Rejects incompatible or unhealthy state before mutating any buffer.
157	pub fn restore(&mut self, state: &TradingState) -> Result<()> {
158		if self.execution.has_active_recording()
159			|| self.execution.has_pending_event()
160			|| state.config != self.config.identity()
161			|| state.source != self.source
162			|| state.ledger.len() != self.ledger.num_elements()
163			|| state.metadata.len() != self.meta.num_elements()
164			|| state.done.len() != self.done.num_elements()
165			|| state.observation.len() != self.observation.num_elements()
166		{
167			return Err(Error::invalid_argument(
168				"trading state/source/configuration mismatch",
169			));
170		}
171		let bounds = self.bounds.read::<u32>()?;
172		for (i, m) in state.metadata.as_chunks::<4>().0.iter().enumerate() {
173			if m[0] < bounds[i * 2] || m[0] > bounds[i * 2 + 1] || m[1] > self.config.horizon || m[3] != 0
174			{
175				return Err(Error::invalid_argument(
176					"invalid trading snapshot cursor/status",
177				));
178			}
179		}
180		self.runtime.checkpoint()?.wait()?;
181		self.committed = false;
182		self.ledger.write_values(&state.ledger)?;
183		self.meta.write_values(&state.metadata)?;
184		self.done.write_values(&state.done)?;
185		self.observation.write_values(&state.observation)?;
186		self.committed = true;
187		self.reset_pending = false;
188		self.rollback_observation = None;
189		Ok(())
190	}
191}