Skip to main content

qualia_core_db/inference/inference_agent/governed/
controller.rs

1#![allow(dead_code)]
2use super::{
3    policy_digest, ActorPolicyScope, InferenceAdmission, PolicyError, SignedPolicy, TokenProposal,
4};
5use crate::modalities::{
6    inference_guard::{evaluate_inference_guard, InferenceGuardAction},
7    logic::WebizenVM,
8};
9use crate::NQuin;
10use etalon_inference_contract as contract;
11use std::sync::{
12    atomic::{AtomicBool, AtomicU64, Ordering},
13    Arc, Mutex, MutexGuard,
14};
15
16pub(crate) struct AuthorityState {
17    pub gate: Mutex<()>,
18    pub generation: AtomicU64,
19    pub connected: AtomicBool,
20}
21impl AuthorityState {
22    pub fn lock(&self) -> Result<MutexGuard<'_, ()>, PolicyError> {
23        self.gate.lock().map_err(|_| {
24            self.connected.store(false, Ordering::Release);
25            PolicyError::Revoked
26        })
27    }
28    pub fn disconnect(&self) {
29        let _guard = self.gate.lock().unwrap_or_else(|e| e.into_inner());
30        self.connected.store(false, Ordering::Release);
31    }
32    pub fn new(generation: u64) -> Self {
33        Self {
34            gate: Mutex::new(()),
35            generation: AtomicU64::new(generation),
36            connected: AtomicBool::new(true),
37        }
38    }
39}
40
41pub(crate) struct InstalledController {
42    pub policy: SignedPolicy,
43    pub key: [u8; 32],
44    pub authority: Arc<AuthorityState>,
45    pub epoch: u64,
46}
47impl InstalledController {
48    pub(crate) fn live(&self, now: u64) -> Result<(), PolicyError> {
49        if !self.authority.connected.load(Ordering::Acquire)
50            || self.authority.generation.load(Ordering::Acquire) != self.epoch
51        {
52            return Err(PolicyError::Revoked);
53        }
54        self.policy.document.valid_at(now)
55    }
56    fn evaluate(
57        &self,
58        proposal: TokenProposal,
59        actor: ActorPolicyScope,
60        now: u64,
61    ) -> Result<contract::Decision, PolicyError> {
62        self.live(now)?;
63        if now >= actor.valid_until
64            || !self
65                .policy
66                .document
67                .rules
68                .actors
69                .as_slice()
70                .contains(&actor)
71        {
72            return Err(PolicyError::Scope);
73        }
74        let doc = &self.policy.document;
75        let rules = &doc.rules;
76        // Every proposal starts with empty registers. Preserve the actual VM's
77        // sequential flag semantics; use HaltIfFalse for conjunction, not an
78        // invented implicit AND across instructions.
79        let mut vm = WebizenVM::new();
80        for (dst, instruction) in vm.bytecode_buffer.iter_mut().zip(rules.program.as_slice()) {
81            *dst = Some(instruction.lower()?);
82        }
83        let vm_allowed = vm.execute_constraint(&proposal.observation);
84        let mut facts = [NQuin::default(); 256];
85        let n = rules.facts.as_slice().len();
86        facts[..n].copy_from_slice(rules.facts.as_slice());
87        facts[n] = proposal.observation;
88        let mut trace = [NQuin::default(); 256];
89        let t = rules.trace.as_slice().len();
90        trace[..t].copy_from_slice(rules.trace.as_slice());
91        trace[t] = proposal.observation;
92        let guard = evaluate_inference_guard(
93            rules.norms.as_slice(),
94            &facts[..n + 1],
95            rules.epistemic.as_slice(),
96            &trace[..t + 1],
97            actor.subject,
98            rules.required_claim,
99            rules.temporal_invariant,
100            now as u32,
101            rules.non_derogable,
102        );
103        Ok(
104            if !vm_allowed || guard.action == InferenceGuardAction::Deny {
105                contract::Decision::Deny
106            } else if guard.action == InferenceGuardAction::Steer {
107                contract::Decision::Steer {
108                    steering_digest: policy_digest(doc),
109                }
110            } else {
111                contract::Decision::Allow
112            },
113        )
114    }
115}
116
117struct SentinelVerifier {
118    controller: Arc<InstalledController>,
119    admission: InferenceAdmission,
120    config: contract::SessionConfig,
121    last_now: u64,
122    actor: ActorPolicyScope,
123}
124impl contract::HostVerifier for SentinelVerifier {
125    fn verify_admission(
126        &mut self,
127        request: &contract::AdmissionRequest,
128        evidence: &[u8],
129    ) -> Result<contract::ControllerBinding, contract::VerificationError> {
130        if request.config != self.config
131            || request.purpose != contract::GovernedPurpose::Application
132            || evidence != self.admission.request_digest
133        {
134            return Err(contract::VerificationError::Unauthenticated);
135        }
136        self.controller
137            .live(request.now_tick)
138            .map_err(verification_error)?;
139        let doc = &self.controller.policy.document;
140        Ok(contract::ControllerBinding {
141            identity: self.controller.key,
142            generation: doc.controller_generation,
143            purpose: request.purpose,
144            expires_at_tick: doc.expires_at,
145        })
146    }
147    fn verify_decision(
148        &mut self,
149        binding: &contract::ControllerBinding,
150        envelope: &contract::DecisionEnvelope,
151        evidence: &[u8],
152    ) -> Result<(), contract::VerificationError> {
153        let proposal = TokenProposal::decode(evidence).map_err(verification_error)?;
154        let expected_position = envelope
155            .candidate
156            .sequence
157            .checked_sub(1)
158            .and_then(|n| self.admission.first_position.checked_add(n));
159        if binding.identity != self.controller.key
160            || binding.generation != self.controller.policy.document.controller_generation
161            || envelope.candidate.identity != self.config.identity
162            || envelope.candidate.mode != contract::ExecutionMode::GovernedApplication
163            || Some(proposal.position) != expected_position
164            || proposal.observation.context != self.admission.graph_scope
165            || proposal.output().map_err(verification_error)? != envelope.candidate.output
166            || envelope.expires_at_tick != self.controller.policy.document.expires_at
167            || self
168                .controller
169                .evaluate(proposal, self.actor, self.last_now)
170                .map_err(verification_error)?
171                != envelope.decision
172        {
173            return Err(contract::VerificationError::Unauthenticated);
174        }
175        Ok(())
176    }
177    fn verify_liveness(
178        &mut self,
179        binding: &contract::ControllerBinding,
180        now: u64,
181    ) -> Result<(), contract::VerificationError> {
182        if binding.identity != self.controller.key
183            || binding.generation != self.controller.policy.document.controller_generation
184        {
185            return Err(contract::VerificationError::Unauthenticated);
186        }
187        self.controller.live(now).map_err(verification_error)?;
188        self.last_now = now;
189        Ok(())
190    }
191}
192fn verification_error(error: PolicyError) -> contract::VerificationError {
193    match error {
194        PolicyError::Expired => contract::VerificationError::Expired,
195        PolicyError::Revoked => contract::VerificationError::Disconnected,
196        _ => contract::VerificationError::Unauthenticated,
197    }
198}
199
200/// Private-key-bound admitted session. No public constructor from an enum or
201/// purported verifier exists; the native host creates it from installed policy.
202/// The caller must use a trusted clock. This API owns no numerical state.
203pub(crate) struct PolicyTokenSession {
204    inner: contract::GovernedSession<SentinelVerifier>,
205    pub(crate) controller: Arc<InstalledController>,
206    pub(crate) actor: ActorPolicyScope,
207}
208
209/// Decision for one exact proposal. Only an Allow can be committed; committing
210/// advances metadata, never publishes bytes or attests a numerical restoration.
211pub struct TokenDecision {
212    key: contract::CandidateKey,
213    proposal: TokenProposal,
214    decision: contract::Decision,
215}
216impl TokenDecision {
217    pub fn decision(&self) -> contract::Decision {
218        self.decision
219    }
220    pub fn proposal(&self) -> TokenProposal {
221        self.proposal
222    }
223    pub fn key(&self) -> contract::CandidateKey {
224        self.key
225    }
226}
227impl PolicyTokenSession {
228    pub(crate) fn admit(
229        controller: Arc<InstalledController>,
230        admission: InferenceAdmission,
231        actor: ActorPolicyScope,
232        session_id: u64,
233        now: u64,
234    ) -> Result<Self, PolicyError> {
235        let doc = &controller.policy.document;
236        controller.live(now)?;
237        actor.validate()?;
238        if now >= actor.valid_until || !doc.rules.actors.as_slice().contains(&actor) {
239            return Err(PolicyError::Scope);
240        }
241        if admission.request_digest == [0; 32]
242            || admission.model_digest == [0; 32]
243            || admission.device_id == 0
244            || !doc.rules.model.allows(admission.model_digest)
245            || !doc.rules.request.allows(admission.request_digest)
246            || (!doc.rules.graph_scopes.as_slice().is_empty()
247                && !doc
248                    .rules
249                    .graph_scopes
250                    .as_slice()
251                    .contains(&admission.graph_scope))
252        {
253            return Err(PolicyError::Scope);
254        }
255        let config = contract::SessionConfig {
256            identity: contract::SessionIdentity {
257                session_id,
258                session_generation: doc.policy_generation,
259                request_id: session_id,
260                request_generation: doc.policy_generation,
261                model_id: admission.model_digest,
262                model_generation: admission.model_generation,
263                device_id: admission.device_id,
264                device_generation: admission.device_generation,
265                policy_id: policy_digest(doc),
266                policy_generation: doc.policy_generation,
267            },
268            instrumentation: admission.instrumentation,
269            max_candidate_tokens: 1,
270        };
271        let verifier = SentinelVerifier {
272            controller: Arc::clone(&controller),
273            admission,
274            config,
275            last_now: now,
276            actor,
277        };
278        let inner = contract::GovernedSession::admit(
279            verifier,
280            contract::AdmissionRequest {
281                config,
282                purpose: contract::GovernedPurpose::Application,
283                profile: contract::GovernanceProfile::ApprovalBeforePublication,
284                now_tick: now,
285            },
286            &admission.request_digest,
287        )
288        .map_err(|_| PolicyError::Session)?;
289        Ok(Self {
290            inner,
291            controller,
292            actor,
293        })
294    }
295    pub fn prepare(
296        &mut self,
297        proposal: TokenProposal,
298        now: u64,
299    ) -> Result<TokenDecision, PolicyError> {
300        let evidence = match proposal.encode() {
301            Ok(evidence) => evidence,
302            Err(error) => {
303                self.inner.cancel();
304                return Err(error);
305            }
306        };
307        let key = self
308            .inner
309            .propose(proposal.output()?, now)
310            .map_err(|_| PolicyError::Session)?;
311        // Re-evaluation by the verifier binds the decision to exact evidence.
312        // Both passes use the same immutable policy, actual VM and graph guard.
313        let decision = match self.controller.evaluate(proposal, self.actor, now) {
314            Ok(decision) => decision,
315            Err(error) => {
316                self.inner.disconnect();
317                return Err(error);
318            }
319        };
320        self.inner
321            .decide(
322                contract::DecisionEnvelope {
323                    candidate: key,
324                    decision,
325                    expires_at_tick: self.controller.policy.document.expires_at,
326                },
327                &evidence,
328                now,
329            )
330            .map_err(|_| PolicyError::Session)?;
331        Ok(TokenDecision {
332            key,
333            proposal,
334            decision,
335        })
336    }
337    pub fn commit(&mut self, decision: &TokenDecision, now: u64) -> Result<(), PolicyError> {
338        self.inner
339            .commit(decision.key, now)
340            .map(|_| ())
341            .map_err(|_| PolicyError::Session)
342    }
343    pub fn cancel(&mut self) {
344        self.inner.cancel();
345    }
346    pub fn snapshot(&self) -> contract::SessionSnapshot {
347        self.inner.snapshot()
348    }
349}