use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use core::fmt;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AdaptiveMode {
#[default]
Keep,
Shadow,
Active,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProposalState {
Observed,
RecordCommitted,
Applied,
Rejected,
Expired,
ReconciliationRequired,
Settled,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PolicySnapshot {
pub version: u64,
pub params: BTreeMap<String, f64>,
}
impl PolicySnapshot {
pub fn new(version: u64, params: BTreeMap<String, f64>) -> Result<Self, AdaptiveError> {
if params.values().any(|value| !value.is_finite()) {
return Err(AdaptiveError::NonFiniteInput);
}
Ok(Self { version, params })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdaptiveConfig {
pub mode: AdaptiveMode,
pub max_pending_active_proposals: usize,
pub completed_response_limit: usize,
}
impl Default for AdaptiveConfig {
fn default() -> Self {
Self {
mode: AdaptiveMode::Keep,
max_pending_active_proposals: 1,
completed_response_limit: 1024,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProposalDecision {
Keep,
KeepPending,
ShadowProposal,
ActiveProposal,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalRequest {
pub request_id: String,
pub proposal_id: String,
pub request_digest: String,
pub requested_mode: AdaptiveMode,
pub candidate_params: Option<BTreeMap<String, f64>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProposalResponse {
pub request_id: String,
pub proposal_id: Option<String>,
pub decision: ProposalDecision,
pub state: ProposalState,
pub confirmed_policy_version: u64,
pub candidate_snapshot: Option<PolicySnapshot>,
pub new_checkpoint_count: u64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecutionReceipt {
pub proposal_id: String,
pub execution_id: String,
pub applied_params: BTreeMap<String, f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum FeedbackOutcome {
Completed {
reward: f64,
error_delta: f64,
risk_delta: f64,
},
Unknown,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FeedbackRequest {
pub feedback_id: String,
pub proposal_id: String,
pub execution_id: String,
pub outcome: FeedbackOutcome,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FeedbackReceipt {
pub feedback_id: String,
pub proposal_id: String,
pub state: ProposalState,
pub learning_applied: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RecoveryRecommendation {
pub recovery_params: BTreeMap<String, f64>,
pub next_candidate_version: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JournalRecoveryInput {
pub journal_prepared: bool,
pub snapshot_revision: u64,
pub committed_marker: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum JournalRecoveryAction {
ReplayCommitted,
VerifyRevisionThenCompleteCommit,
None,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AdaptiveError {
StepIdConflict,
InvalidTransition,
PolicySnapshotMismatch,
NonFiniteInput,
Expired,
UnknownProposal,
ParameterOutOfBounds,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ParameterBound {
pub min: f64,
pub max: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_step_delta: Option<f64>,
}
impl ParameterBound {
pub fn new(min: f64, max: f64, max_step_delta: Option<f64>) -> Result<Self, AdaptiveError> {
if !min.is_finite() || !max.is_finite() || min > max {
return Err(AdaptiveError::NonFiniteInput);
}
if let Some(delta) = max_step_delta {
if !delta.is_finite() || delta < 0.0 {
return Err(AdaptiveError::NonFiniteInput);
}
}
Ok(Self {
min,
max,
max_step_delta,
})
}
pub fn allows(&self, current: Option<f64>, candidate: f64) -> bool {
if !candidate.is_finite() || candidate < self.min || candidate > self.max {
return false;
}
if let (Some(max_delta), Some(cur)) = (self.max_step_delta, current) {
if (candidate - cur).abs() > max_delta + 1e-12 {
return false;
}
}
true
}
}
impl fmt::Display for AdaptiveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::StepIdConflict => {
write!(f, "request or feedback id reused with conflicting payload")
}
Self::InvalidTransition => write!(f, "invalid adaptive proposal state transition"),
Self::PolicySnapshotMismatch => {
write!(f, "applied parameters do not match candidate snapshot")
}
Self::NonFiniteInput => write!(f, "non-finite floating-point value rejected"),
Self::Expired => write!(f, "expired request tombstone cannot be re-executed"),
Self::UnknownProposal => write!(f, "unknown adaptive proposal or execution identifier"),
Self::ParameterOutOfBounds => {
write!(f, "candidate parameter violates configured safety bounds")
}
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for AdaptiveError {}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PersistedRequestRecord {
pub digest: String,
pub response: ProposalResponse,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PersistedProposalRecord {
pub mode: AdaptiveMode,
pub state: ProposalState,
pub snapshot: PolicySnapshot,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub execution_id: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PersistedFeedbackRecord {
pub proposal_id: String,
pub execution_id: String,
pub outcome: FeedbackOutcome,
pub receipt: FeedbackReceipt,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdaptivePersistedState {
pub mode: AdaptiveMode,
pub confirmed_policy: PolicySnapshot,
pub next_candidate_version: u64,
pub revision: u64,
pub learning_updates: u64,
pub checkpoint_count: u64,
pub active_permission_granted: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pending_active_proposal_id: Option<String>,
pub reconciliation_required: bool,
#[serde(default)]
pub proposals: BTreeMap<String, PersistedProposalRecord>,
#[serde(default)]
pub requests: BTreeMap<String, PersistedRequestRecord>,
#[serde(default)]
pub feedbacks: BTreeMap<String, PersistedFeedbackRecord>,
#[serde(default)]
pub expired_tombstones: BTreeSet<String>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub parameter_bounds: BTreeMap<String, ParameterBound>,
}