gioser
⎇ a4fa42c781d76852355931d82a28e80230855af8 crates/ente-brain/src/introspect.rs Rust · 379 líneas · 15.3 KB Historia Quién tocó qué crudo

Audit→CAS, reload rules, time-decay y forma canónica del hash chain a4fa42c78 · Sergio ·

1//! Introspect API. Unix Domain Socket + framing length-prefijo + bincode.
2//!
3//! Una herramienta externa (ej. `brainctl`) puede consultar el estado del
4//! cerebro sin tocar el bus interno del fractal. Esto separa observación de
5//! ejecución — la introspección es read-only por diseño.
6
7use crate::crystallize::{detect_crystals, Crystal, CrystallizationParams};
8use crate::engine::RuleEngine;
9use crate::observer::Observer;
10use crate::rules::Rule;
11use serde::{Deserialize, Serialize};
12use std::io::Write;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use tokio::io::{AsyncReadExt, AsyncWriteExt};
16use tokio::net::{UnixListener, UnixStream};
17use tokio::sync::RwLock;
18use tracing::{debug, info, trace, warn};
19use ulid::Ulid;
20
21const MAX_FRAME: usize = 4 * 1024 * 1024; // 4 MiB — correlation matrices crecen
22
23/// Estado compartido entre el bucle del Init y el servidor de introspección.
24/// `Arc<RwLock<...>>` permite muchos lectores concurrentes (introspect) y
25/// un escritor (el dispatcher de eventos en el bucle primordial).
26#[derive(Clone)]
27pub struct BrainState {
28    pub engine: Arc<RwLock<RuleEngine>>,
29    pub observer: Arc<RwLock<Observer>>,
30    pub params: CrystallizationParams,
31    /// Path opcional donde apendear reglas promovidas como KCL. Si Some,
32    /// cada PromoteCrystal añade el snippet al archivo (append-only).
33    pub rules_out: Option<Arc<PathBuf>>,
34    /// Audit log en memoria. Cada promote/remove deja huella aquí.
35    pub audit: Arc<RwLock<crate::audit::AuditLog>>,
36}
37
38impl BrainState {
39    pub fn new(window_size: usize) -> Self {
40        Self::with_params(window_size, CrystallizationParams::default())
41    }
42
43    pub fn with_params(window_size: usize, params: CrystallizationParams) -> Self {
44        Self {
45            engine: Arc::new(RwLock::new(RuleEngine::empty())),
46            observer: Arc::new(RwLock::new(Observer::new(window_size))),
47            params,
48            rules_out: None,
49            audit: Arc::new(RwLock::new(crate::audit::AuditLog::new())),
50        }
51    }
52
53    pub fn with_rules_out(mut self, path: PathBuf) -> Self {
54        self.rules_out = Some(Arc::new(path));
55        self
56    }
57}
58
59/// Append-only writer del KCL snippet a `rules_out`. Crea el archivo con
60/// header si no existe; en caso contrario sólo apendea.
61pub fn append_kcl_snippet(path: &Path, snippet: &str) -> std::io::Result<()> {
62    if let Some(parent) = path.parent() {
63        std::fs::create_dir_all(parent)?;
64    }
65    let exists = path.exists();
66    let mut file = std::fs::OpenOptions::new()
67        .create(true)
68        .append(true)
69        .open(path)?;
70    if !exists {
71        writeln!(file, "# Reglas promovidas automáticamente desde cristales.")?;
72        writeln!(file, "# Cada bloque proviene de PromoteCrystal vía brainctl.")?;
73        writeln!(file)?;
74    }
75    writeln!(file, "{snippet}")?;
76    Ok(())
77}
78
79#[derive(Debug, Serialize, Deserialize)]
80pub enum IntrospectRequest {
81    /// Lista resumida de reglas vivas.
82    ListRules,
83    /// Detalle de una regla concreta.
84    GetRule(Ulid),
85    /// Snapshot de la entropía y conteos básicos.
86    EntropySnapshot,
87    /// Top N pares (a, b) por co-ocurrencia.
88    TopCorrelations { n: usize },
89    /// Cristales detectados con los parámetros del BrainState.
90    Crystals,
91    /// Genera el snippet KCL de un cristal específico (índice tras Crystals).
92    CrystalKcl { index: usize },
93    /// Promueve el cristal #index a regla viva en el motor. Devuelve el
94    /// rule_id asignado y el snippet KCL para auditoría/persistencia.
95    PromoteCrystal { index: usize },
96    /// Elimina una regla viva por id. Útil para revertir un promote.
97    RemoveRule { id: Ulid },
98    /// Lista las últimas N entradas del audit log. limit=0 = todas.
99    ListAudit { limit: usize },
100    /// Persiste todas las entries pendientes al CAS y actualiza el head
101    /// pointer si el log lo tiene configurado.
102    FlushAudit,
103    /// Recarga reglas desde el archivo configurado por --rules-out (o el
104    /// path provisto). Vacía el engine antes de cargar.
105    ReloadRules { path: Option<String> },
106}
107
108#[derive(Debug, Serialize, Deserialize)]
109pub enum IntrospectResponse {
110    Rules(Vec<RuleSummary>),
111    Rule(Option<Rule>),
112    Entropy { value_bits: f64, sample_size: u64, distinct_kinds: usize, window_full: bool },
113    Correlations(Vec<CorrelationEntry>),
114    Crystals(Vec<Crystal>),
115    Kcl(String),
116    /// Resultado de PromoteCrystal: id de la regla creada + snippet KCL para
117    /// que el operador lo persista en disco si quiere.
118    Promoted { rule_id: Ulid, kcl_snippet: String },
119    /// Resultado de RemoveRule: true si existía, false si ya no.
120    Removed(bool),
121    /// Entradas del audit log (más recientes al final).
122    AuditEntries(Vec<crate::audit::AuditEntry>),
123    /// Resultado de FlushAudit: cuántas entries se escribieron y SHA del head.
124    Flushed { written: usize, head_sha: Option<[u8; 32]>, total_flushed: u64 },
125    /// Resultado de ReloadRules: número total de reglas tras el reload.
126    Reloaded { count: usize },
127    Error(String),
128}
129
130#[derive(Debug, Serialize, Deserialize)]
131pub struct RuleSummary {
132    pub id: Ulid,
133    pub priority: u8,
134    pub event_kind_tag: String,
135    pub action_count: usize,
136    pub scope_wildcard: bool,
137}
138
139#[derive(Debug, Serialize, Deserialize)]
140pub struct CorrelationEntry {
141    pub a: String,
142    pub b: String,
143    pub joint_count: u64,
144    pub conditional_prob: f64,
145    pub pmi_bits: f64,
146}
147
148pub struct IntrospectServer {
149    state: BrainState,
150}
151
152impl IntrospectServer {
153    pub fn new(state: BrainState) -> Self { Self { state } }
154
155    /// Spawn del listener. Devuelve cuando bind() falla; en caso contrario
156    /// corre indefinidamente.
157    pub async fn serve(self, path: &Path) -> anyhow::Result<()> {
158        let _ = std::fs::remove_file(path);
159        if let Some(parent) = path.parent() {
160            let _ = std::fs::create_dir_all(parent);
161        }
162        let listener = UnixListener::bind(path)?;
163        info!(path = %path.display(), "brain introspect escuchando");
164        let arc_self = Arc::new(self);
165        loop {
166            match listener.accept().await {
167                Ok((stream, _)) => {
168                    trace!("introspect conn aceptada");
169                    let me = arc_self.clone();
170                    tokio::spawn(async move {
171                        if let Err(e) = me.handle(stream).await {
172                            warn!(?e, "introspect conn ended");
173                        }
174                    });
175                }
176                Err(e) => {
177                    warn!(?e, "introspect accept failed");
178                    return Ok(());
179                }
180            }
181        }
182    }
183
184    async fn handle(self: Arc<Self>, mut stream: UnixStream) -> anyhow::Result<()> {
185        loop {
186            let mut len_buf = [0u8; 4];
187            if stream.read_exact(&mut len_buf).await.is_err() {
188                return Ok(()); // EOF
189            }
190            let len = u32::from_be_bytes(len_buf) as usize;
191            if len > MAX_FRAME {
192                anyhow::bail!("frame oversize: {len}");
193            }
194            let mut buf = vec![0u8; len];
195            stream.read_exact(&mut buf).await?;
196            let req: IntrospectRequest = bincode::deserialize(&buf)?;
197            debug!(?req, "introspect request");
198
199            let resp = self.dispatch(req).await;
200
201            let out = bincode::serialize(&resp)?;
202            stream.write_u32(out.len() as u32).await?;
203            stream.write_all(&out).await?;
204        }
205    }
206
207    async fn dispatch(&self, req: IntrospectRequest) -> IntrospectResponse {
208        match req {
209            IntrospectRequest::ListRules => {
210                let engine = self.state.engine.read().await;
211                let rules = engine.rules()
212                    .map(|r| RuleSummary {
213                        id: r.id,
214                        priority: r.priority,
215                        event_kind_tag: format!("{:?}", r.when),
216                        action_count: r.then.len(),
217                        scope_wildcard: r.scope.is_wildcard(),
218                    })
219                    .collect();
220                IntrospectResponse::Rules(rules)
221            }
222            IntrospectRequest::GetRule(id) => {
223                let engine = self.state.engine.read().await;
224                let found = engine.rules()
225                    .find(|r| r.id == id)
226                    .map(|r| Rule::clone(r));
227                IntrospectResponse::Rule(found)
228            }
229            IntrospectRequest::EntropySnapshot => {
230                let obs = self.state.observer.read().await;
231                IntrospectResponse::Entropy {
232                    value_bits: obs.shannon_entropy(),
233                    sample_size: obs.total(),
234                    distinct_kinds: obs.marginals().len(),
235                    window_full: obs.current_window() >= obs.window_size(),
236                }
237            }
238            IntrospectRequest::TopCorrelations { n } => {
239                let obs = self.state.observer.read().await;
240                let mut entries: Vec<CorrelationEntry> = obs.cooccurrences().iter()
241                    .map(|((a, b), &joint)| CorrelationEntry {
242                        a: format!("{:?}", a),
243                        b: format!("{:?}", b),
244                        joint_count: joint,
245                        conditional_prob: obs.conditional_prob(a, b),
246                        pmi_bits: obs.pmi(a, b),
247                    })
248                    .collect();
249                entries.sort_by(|x, y| y.joint_count.cmp(&x.joint_count));
250                entries.truncate(n);
251                IntrospectResponse::Correlations(entries)
252            }
253            IntrospectRequest::Crystals => {
254                let obs = self.state.observer.read().await;
255                let crystals = detect_crystals(&obs, &self.state.params);
256                IntrospectResponse::Crystals(crystals)
257            }
258            IntrospectRequest::CrystalKcl { index } => {
259                let obs = self.state.observer.read().await;
260                let crystals = detect_crystals(&obs, &self.state.params);
261                match crystals.get(index) {
262                    Some(c) => IntrospectResponse::Kcl(crate::crystallize::crystal_to_kcl(c)),
263                    None => IntrospectResponse::Error(format!("no crystal at index {index}")),
264                }
265            }
266            IntrospectRequest::PromoteCrystal { index } => {
267                let crystals = {
268                    let obs = self.state.observer.read().await;
269                    detect_crystals(&obs, &self.state.params)
270                };
271                match crystals.get(index) {
272                    Some(c) => {
273                        let rule = crate::crystallize::crystal_to_rule(c);
274                        let snippet = crate::crystallize::crystal_to_kcl(c);
275                        let rule_id = rule.id;
276                        self.state.engine.write().await.insert(rule);
277                        // Persistencia opcional al archivo KCL.
278                        if let Some(path) = self.state.rules_out.as_ref() {
279                            if let Err(e) = append_kcl_snippet(path, &snippet) {
280                                warn!(?e, path = %path.display(), "rules_out append falló");
281                            } else {
282                                info!(path = %path.display(), %rule_id, "regla persistida a .k");
283                            }
284                        }
285                        // Audit entry
286                        self.state.audit.write().await.append(
287                            crate::audit::AuditAction::PromoteCrystal {
288                                rule_id, crystal: c.clone(),
289                            }
290                        );
291                        IntrospectResponse::Promoted { rule_id, kcl_snippet: snippet }
292                    }
293                    None => IntrospectResponse::Error(format!("no crystal at index {index}")),
294                }
295            }
296            IntrospectRequest::RemoveRule { id } => {
297                let removed = self.state.engine.write().await.remove(id);
298                if removed {
299                    self.state.audit.write().await.append(
300                        crate::audit::AuditAction::RemoveRule { rule_id: id }
301                    );
302                }
303                IntrospectResponse::Removed(removed)
304            }
305            IntrospectRequest::ListAudit { limit } => {
306                let audit = self.state.audit.read().await;
307                IntrospectResponse::AuditEntries(audit.recent(limit).cloned().collect())
308            }
309            IntrospectRequest::FlushAudit => {
310                let mut audit = self.state.audit.write().await;
311                match audit.flush_to_cas() {
312                    Ok(written) => IntrospectResponse::Flushed {
313                        written,
314                        head_sha: audit.last_flushed_sha(),
315                        total_flushed: audit.flushed_count(),
316                    },
317                    Err(e) => IntrospectResponse::Error(format!("flush_to_cas: {e}")),
318                }
319            }
320            IntrospectRequest::ReloadRules { path } => {
321                // Path explícito gana sobre el rules_out configurado.
322                let resolved = path.map(std::path::PathBuf::from)
323                    .or_else(|| self.state.rules_out.as_ref().map(|p| p.as_path().to_path_buf()));
324                let path = match resolved {
325                    Some(p) => p,
326                    None => return IntrospectResponse::Error(
327                        "ReloadRules sin path y sin rules_out configurado".into()
328                    ),
329                };
330                let rules = match crate::kcl_loader::load_rules_file(&path) {
331                    Ok(r) => r,
332                    Err(e) => return IntrospectResponse::Error(format!("load: {e}")),
333                };
334                // Vaciamos el engine antes de re-cargar — semántica clean-slate.
335                let mut engine = self.state.engine.write().await;
336                *engine = crate::engine::RuleEngine::empty();
337                let count = rules.len();
338                for r in rules { engine.insert(r); }
339                drop(engine);
340                self.state.audit.write().await.append(
341                    crate::audit::AuditAction::LoadRulesFile {
342                        path: path.to_string_lossy().into_owned(),
343                        count,
344                    }
345                );
346                IntrospectResponse::Reloaded { count }
347            }
348        }
349    }
350}
351
352// Cliente helper para tools externos (brainctl).
353pub async fn call(path: &Path, req: IntrospectRequest) -> anyhow::Result<IntrospectResponse> {
354    let mut stream = UnixStream::connect(path).await?;
355    let buf = bincode::serialize(&req)?;
356    stream.write_u32(buf.len() as u32).await?;
357    stream.write_all(&buf).await?;
358
359    let mut len_buf = [0u8; 4];
360    stream.read_exact(&mut len_buf).await?;
361    let len = u32::from_be_bytes(len_buf) as usize;
362    if len > MAX_FRAME {
363        anyhow::bail!("response oversize: {len}");
364    }
365    let mut buf = vec![0u8; len];
366    stream.read_exact(&mut buf).await?;
367    Ok(bincode::deserialize(&buf)?)
368}
369
370/// Consume la lista marginal del observer para humanos. Suprime el detalle
371/// crudo de `EventKind` (ej. payloads largos en BusInvokeOf).
372pub fn marginal_summary(obs: &Observer) -> Vec<(String, u64)> {
373    let mut entries: Vec<(String, u64)> = obs.marginals().iter()
374        .map(|(k, &c)| (format!("{:?}", k), c))
375        .collect();
376    entries.sort_by(|x, y| y.1.cmp(&x.1));
377    entries
378}
379