Skip to main content

qualia_core_db/inference/inference_agent/governed/
associated.rs

1//! Native actor and policy acceptance share one explicit linearization boundary.
2use super::{
3    controller::{InstalledController, PolicyTokenSession},
4    ActorPolicyScope, InferenceAdmission, PolicyError, TokenDecision, TokenProposal,
5};
6use crate::poet_host::native_authority::{
7    inference::AuthenticatedInferenceAssociation, NativeAuthority,
8};
9use std::sync::Arc;
10
11/// Receipt of an accepted record, not a reusable permission or restored state.
12#[derive(Clone, Copy, Debug)]
13pub struct AcceptedToken {
14    pub proposal: TokenProposal,
15    pub key: etalon_inference_contract::CandidateKey,
16}
17
18/// Created only from installed policy AND an actual current native association.
19/// No public constructor accepts copied evidence. This owns no numerical state.
20pub struct GovernedTokenSession {
21    inner: PolicyTokenSession,
22    owner: Arc<NativeAuthority>,
23    association: AuthenticatedInferenceAssociation,
24    terminal: bool,
25}
26impl GovernedTokenSession {
27    pub(crate) fn admit(
28        controller: Arc<InstalledController>,
29        request: InferenceAdmission,
30        session_id: u64,
31        clock_override: Option<u64>,
32        owner: Arc<NativeAuthority>,
33        association: AuthenticatedInferenceAssociation,
34    ) -> Result<Self, PolicyError> {
35        let inner = owner
36            .with_inference_association_guard(&association, |view| {
37                let _gate = controller.authority.lock()?;
38                let e = view
39                    .revalidate_current()
40                    .map_err(|_| PolicyError::Revoked)?;
41                let real_now = clock(None)?;
42                PolicyTokenSession::admit(
43                    Arc::clone(&controller),
44                    request,
45                    ActorPolicyScope::from_evidence(e),
46                    session_id,
47                    clock_override.unwrap_or(real_now),
48                )
49            })
50            .map_err(|_| PolicyError::Revoked)??;
51        Ok(Self {
52            inner,
53            owner,
54            association,
55            terminal: false,
56        })
57    }
58    pub fn prepare(&mut self, proposal: TokenProposal) -> Result<TokenDecision, PolicyError> {
59        self.prepare_clock(proposal, None)
60    }
61    #[cfg(test)]
62    pub(super) fn prepare_at(
63        &mut self,
64        proposal: TokenProposal,
65        now: u64,
66    ) -> Result<TokenDecision, PolicyError> {
67        self.prepare_clock(proposal, Some(now))
68    }
69    fn prepare_clock(
70        &mut self,
71        proposal: TokenProposal,
72        clock_override: Option<u64>,
73    ) -> Result<TokenDecision, PolicyError> {
74        if self.terminal {
75            return Err(PolicyError::Revoked);
76        }
77        self.terminal = true;
78        let controller = Arc::clone(&self.inner.controller);
79        let result = self
80            .owner
81            .with_inference_association_guard(&self.association, |view| {
82                let _gate = controller.authority.lock()?;
83                let e = view
84                    .revalidate_current()
85                    .map_err(|_| PolicyError::Revoked)?;
86                if ActorPolicyScope::from_evidence(e) != self.inner.actor {
87                    return Err(PolicyError::Scope);
88                }
89                let now = clock(clock_override)?;
90                self.inner.prepare(proposal, now)
91            })
92            .map_err(|_| PolicyError::Revoked)
93            .and_then(|r| r);
94        if result.is_err() {
95            self.cancel();
96        } else {
97            self.terminal = false;
98        }
99        result
100    }
101    /// Enqueue exactly one accepted record under NativeAuthority -> policy gate.
102    /// The caller drains UI/user callbacks AFTER this returns, outside all locks.
103    /// Revocation linearizes before refusal or after this accepted record; it
104    /// cannot retroactively retract an earlier acceptance. Occupied output refuses.
105    pub fn accept_into(
106        &mut self,
107        decision: &TokenDecision,
108        out: &mut Option<AcceptedToken>,
109    ) -> Result<(), PolicyError> {
110        self.accept_into_clock(decision, None, out)
111    }
112    #[cfg(test)]
113    pub(super) fn accept_into_at(
114        &mut self,
115        decision: &TokenDecision,
116        now: u64,
117        out: &mut Option<AcceptedToken>,
118    ) -> Result<(), PolicyError> {
119        self.accept_into_clock(decision, Some(now), out)
120    }
121    fn accept_into_clock(
122        &mut self,
123        decision: &TokenDecision,
124        clock_override: Option<u64>,
125        out: &mut Option<AcceptedToken>,
126    ) -> Result<(), PolicyError> {
127        if out.is_some() {
128            self.cancel();
129            return Err(PolicyError::Capacity);
130        }
131        self.accept_clock(decision, clock_override, || {
132            *out = Some(AcceptedToken {
133                proposal: decision.proposal(),
134                key: decision.key(),
135            });
136            Ok(())
137        })
138    }
139    /// Internal bounded state/record enqueue only, NEVER arbitrary user callbacks,
140    /// host/vault calls, I/O, await, or reentrant authority operations. Failure or
141    /// unwind leaves this session terminal; the caller must restore enrolled
142    /// state or discard it. Already published effects cannot be retracted here.
143    #[cfg(test)]
144    pub(super) fn accept_with_at(
145        &mut self,
146        decision: &TokenDecision,
147        now: u64,
148        enqueue: impl FnOnce() -> Result<(), PolicyError>,
149    ) -> Result<(), PolicyError> {
150        self.accept_clock(decision, Some(now), enqueue)
151    }
152    fn accept_clock(
153        &mut self,
154        decision: &TokenDecision,
155        clock_override: Option<u64>,
156        enqueue: impl FnOnce() -> Result<(), PolicyError>,
157    ) -> Result<(), PolicyError> {
158        if self.terminal {
159            return Err(PolicyError::Revoked);
160        }
161        // Sticky before entering any fallible code; also survives unwinding.
162        self.terminal = true;
163        let controller = Arc::clone(&self.inner.controller);
164        let result = self
165            .owner
166            .with_inference_association_guard(&self.association, |view| {
167                let _gate = controller.authority.lock()?;
168                let e = view
169                    .revalidate_current()
170                    .map_err(|_| PolicyError::Revoked)?;
171                if ActorPolicyScope::from_evidence(e) != self.inner.actor {
172                    return Err(PolicyError::Scope);
173                }
174                let now = clock(clock_override)?;
175                controller.live(now)?;
176                if now >= self.inner.actor.valid_until {
177                    return Err(PolicyError::Expired);
178                }
179                self.inner.commit(decision, now)?;
180                enqueue()
181            })
182            .map_err(|_| PolicyError::Revoked)
183            .and_then(|r| r);
184        match result {
185            Ok(()) => {
186                self.terminal = false;
187                Ok(())
188            }
189            Err(error) => {
190                self.inner.cancel();
191                Err(error)
192            }
193        }
194    }
195    pub fn cancel(&mut self) {
196        self.terminal = true;
197        self.inner.cancel();
198    }
199    pub fn is_terminal(&self) -> bool {
200        self.terminal
201    }
202    pub fn snapshot(&self) -> etalon_inference_contract::SessionSnapshot {
203        self.inner.snapshot()
204    }
205}
206
207// Production callers cannot supply time. Read after acquiring both acceptance
208// locks so waiting on a lock cannot extend an expired policy window.
209fn clock(test_override: Option<u64>) -> Result<u64, PolicyError> {
210    if let Some(now) = test_override {
211        return Ok(now);
212    }
213    std::time::SystemTime::now()
214        .duration_since(std::time::UNIX_EPOCH)
215        .map(|d| d.as_secs())
216        .map_err(|_| PolicyError::Clock)
217}