Skip to main content

omega_cognitive_kernel/adaptive/
session.rs

1use std::boxed::Box;
2use std::collections::BTreeMap;
3
4use crate::adaptive::state::AdaptiveStateMachine;
5use crate::adaptive::types::{
6    AdaptiveConfig, AdaptiveError, AdaptiveMode, ExecutionReceipt, FeedbackReceipt,
7    FeedbackRequest, PolicySnapshot, ProposalRequest, ProposalResponse, RecoveryRecommendation,
8};
9use crate::error::{OmegaError, Result};
10use crate::persist::{KernelSnapshot, StateStore, CURRENT_SCHEMA_VERSION};
11
12/// Durable Phase 1 Adaptive Kernel Protocol v1 session backed by a [`StateStore`].
13///
14/// Phase 1 enforces **Keep / Shadow only** execution: no active parameter
15/// mutations are permitted, every transition persists through [`StateStore`]
16/// before committing in-memory state (fail-closed on storage errors), and
17/// legacy `schema v6` snapshots migrate to `v7` without gaining active rights.
18pub struct DurableAdaptiveSession {
19    store: Box<dyn StateStore>,
20    machine: AdaptiveStateMachine,
21    snapshot: KernelSnapshot,
22}
23
24impl DurableAdaptiveSession {
25    /// Opens a durable `Keep`-only adaptive session backed by `store`.
26    pub fn open_keep(store: Box<dyn StateStore>, baseline_policy: PolicySnapshot) -> Result<Self> {
27        Self::open_internal(
28            store,
29            AdaptiveConfig {
30                mode: AdaptiveMode::Keep,
31                ..AdaptiveConfig::default()
32            },
33            baseline_policy,
34        )
35    }
36
37    /// Opens a durable `Shadow`-mode adaptive session backed by `store`.
38    ///
39    /// Even if `config.mode` requests [`AdaptiveMode::Active`], Phase 1 clamps
40    /// the session to [`AdaptiveMode::Shadow`] so no executable parameter
41    /// mutation occurs.
42    pub fn open_shadow(
43        store: Box<dyn StateStore>,
44        config: AdaptiveConfig,
45        baseline_policy: PolicySnapshot,
46    ) -> Result<Self> {
47        Self::open_internal(
48            store,
49            AdaptiveConfig {
50                mode: AdaptiveMode::Shadow,
51                ..config
52            },
53            baseline_policy,
54        )
55    }
56
57    /// Opens a durable `Active`-mode adaptive session with explicit opt-in.
58    ///
59    /// Legacy snapshots (`schema < 7`) still fail closed with
60    /// `active_permission_granted == false` and emit only `Keep` until migrated.
61    pub fn open_active(
62        store: Box<dyn StateStore>,
63        config: AdaptiveConfig,
64        baseline_policy: PolicySnapshot,
65    ) -> Result<Self> {
66        Self::open_internal(
67            store,
68            AdaptiveConfig {
69                mode: AdaptiveMode::Active,
70                ..config
71            },
72            baseline_policy,
73        )
74    }
75
76    fn open_internal(
77        store: Box<dyn StateStore>,
78        config: AdaptiveConfig,
79        baseline_policy: PolicySnapshot,
80    ) -> Result<Self> {
81        let (snapshot, machine) = match store.load_snapshot()? {
82            Some(mut loaded) => {
83                let original_version = loaded.version;
84                loaded = loaded.migrate()?;
85                let machine = if let Some(persisted) = loaded.adaptive_state.clone() {
86                    AdaptiveStateMachine::from_persisted_state(config, persisted)
87                        .map_err(|e| OmegaError::Persist(e.to_string()))?
88                } else {
89                    // An existing snapshot with no adaptive_state (including migrated v0-v6
90                    // snapshots whose load_snapshot() already bumped version to v7) must
91                    // never gain active permission implicitly.
92                    let legacy_ver = original_version.min(CURRENT_SCHEMA_VERSION - 1);
93                    AdaptiveStateMachine::from_legacy_snapshot(legacy_ver, config, baseline_policy)
94                        .map_err(|e| OmegaError::Persist(e.to_string()))?
95                };
96                (loaded, machine)
97            }
98            None => {
99                let machine = AdaptiveStateMachine::new(config, baseline_policy)
100                    .map_err(|e| OmegaError::Persist(e.to_string()))?;
101                let snapshot = KernelSnapshot {
102                    adaptive_state: Some(machine.export_state()),
103                    ..Default::default()
104                };
105                (snapshot, machine)
106            }
107        };
108
109        Ok(Self {
110            store,
111            machine,
112            snapshot,
113        })
114    }
115
116    /// Returns a read-only view of the underlying protocol state machine.
117    pub fn machine(&self) -> &AdaptiveStateMachine {
118        &self.machine
119    }
120
121    /// Returns the loaded/migrated [`KernelSnapshot`] schema version.
122    pub fn schema_version(&self) -> u32 {
123        self.snapshot.version
124    }
125
126    /// Evaluates and durably persists a `propose` request (fail-closed on storage error).
127    pub fn propose(
128        &mut self,
129        req: ProposalRequest,
130    ) -> core::result::Result<ProposalResponse, AdaptiveSessionError> {
131        let mut candidate = self.machine.clone();
132        let response = candidate.propose(req)?;
133        self.commit_machine(candidate)?;
134        Ok(response)
135    }
136
137    /// Evaluates and durably persists an `acknowledge_applied` receipt.
138    pub fn acknowledge_applied(
139        &mut self,
140        receipt: ExecutionReceipt,
141    ) -> core::result::Result<PolicySnapshot, AdaptiveSessionError> {
142        let mut candidate = self.machine.clone();
143        let confirmed = candidate.acknowledge_applied(receipt)?;
144        self.commit_machine(candidate)?;
145        Ok(confirmed)
146    }
147
148    /// Evaluates and durably persists an external `feedback` request.
149    pub fn feedback(
150        &mut self,
151        req: FeedbackRequest,
152    ) -> core::result::Result<FeedbackReceipt, AdaptiveSessionError> {
153        let mut candidate = self.machine.clone();
154        let receipt = candidate.feedback(req)?;
155        self.commit_machine(candidate)?;
156        Ok(receipt)
157    }
158
159    /// Durably records an expired request tombstone so it can never re-execute across restarts.
160    pub fn record_expired_tombstone(
161        &mut self,
162        request_id: impl Into<String>,
163    ) -> core::result::Result<(), AdaptiveSessionError> {
164        let mut candidate = self.machine.clone();
165        candidate.record_expired_tombstone(request_id);
166        self.commit_machine(candidate)?;
167        Ok(())
168    }
169
170    /// Returns the currently confirmed parameter map (unchanged in Keep/Shadow modes).
171    pub fn confirmed_params(&self) -> &BTreeMap<String, f64> {
172        &self.machine.confirmed_policy().params
173    }
174
175    /// Returns the currently confirmed [`PolicySnapshot`].
176    pub fn confirmed_policy(&self) -> &PolicySnapshot {
177        self.machine.confirmed_policy()
178    }
179
180    /// Returns whether active adaptation permission is granted for this session.
181    pub fn active_permission_granted(&self) -> bool {
182        self.machine.active_permission_granted()
183    }
184
185    /// Produces a bounded recovery recommendation under a strictly newer version.
186    pub fn recommend_recovery(
187        &self,
188        recovery_params: BTreeMap<String, f64>,
189    ) -> core::result::Result<RecoveryRecommendation, AdaptiveSessionError> {
190        Ok(self.machine.recommend_recovery(recovery_params)?)
191    }
192
193    fn commit_machine(
194        &mut self,
195        next_machine: AdaptiveStateMachine,
196    ) -> core::result::Result<(), AdaptiveSessionError> {
197        let mut next_snapshot = self.snapshot.clone();
198        next_snapshot.version = CURRENT_SCHEMA_VERSION;
199        next_snapshot.adaptive_state = Some(next_machine.export_state());
200        self.store
201            .save_snapshot(&next_snapshot)
202            .map_err(|e| AdaptiveSessionError::Storage(e.to_string()))?;
203        self.snapshot = next_snapshot;
204        self.machine = next_machine;
205        Ok(())
206    }
207}
208
209/// Error returned by [`DurableAdaptiveSession`] distinguishing protocol and storage failures.
210#[derive(Debug, Clone, PartialEq, Eq)]
211#[non_exhaustive]
212pub enum AdaptiveSessionError {
213    /// Fail-closed protocol contract violation.
214    Protocol(AdaptiveError),
215    /// Underlying [`StateStore`] persistence failure; in-memory state was not mutated.
216    Storage(String),
217}
218
219impl From<AdaptiveError> for AdaptiveSessionError {
220    fn from(value: AdaptiveError) -> Self {
221        Self::Protocol(value)
222    }
223}
224
225impl std::fmt::Display for AdaptiveSessionError {
226    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227        match self {
228            Self::Protocol(err) => write!(f, "adaptive protocol error: {err}"),
229            Self::Storage(msg) => write!(f, "adaptive storage error: {msg}"),
230        }
231    }
232}
233
234impl std::error::Error for AdaptiveSessionError {}