rust-rule-engine 1.20.1

A blazing-fast Rust rule engine with RETE algorithm, backward chaining inference, and GRL (Grule Rule Language) syntax. Features: forward/backward chaining, pattern matching, unification, O(1) rule indexing, TMS, expression evaluation, method calls, streaming with Redis state backend, watermarking, and custom functions. Production-ready for business rules, expert systems, real-time stream processing, and decision automation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Working Memory for RETE-UL (Drools-style)
//!
//! This module implements a Working Memory system similar to Drools, providing:
//! - FactHandle for tracking inserted objects
//! - Insert, update, retract operations
//! - Type indexing for fast lookups
//! - Change tracking for incremental updates

use super::facts::TypedFacts;
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};

/// Unique handle for a fact in working memory (similar to Drools FactHandle)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FactHandle(u64);

impl FactHandle {
    /// Create a new fact handle with a unique ID
    pub fn new(id: u64) -> Self {
        Self(id)
    }

    /// Get the handle ID
    pub fn id(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for FactHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "FactHandle({})", self.0)
    }
}

/// A fact stored in working memory
#[derive(Debug, Clone)]
pub struct WorkingMemoryFact {
    /// The fact handle
    pub handle: FactHandle,
    /// Fact type (e.g., "Person", "Order")
    pub fact_type: String,
    /// The actual fact data
    pub data: TypedFacts,
    /// Metadata
    pub metadata: FactMetadata,
    /// Stream source (if this fact came from a stream)
    #[cfg(feature = "streaming")]
    pub stream_source: Option<String>,
    /// Stream event (if this fact came from a stream)
    #[cfg(feature = "streaming")]
    pub stream_event: Option<crate::streaming::event::StreamEvent>,
}

/// Metadata for a fact
#[derive(Debug, Clone)]
pub struct FactMetadata {
    /// When the fact was inserted
    pub inserted_at: std::time::Instant,
    /// When the fact was last updated
    pub updated_at: std::time::Instant,
    /// Number of updates
    pub update_count: usize,
    /// Is this fact retracted?
    pub retracted: bool,
}

impl Default for FactMetadata {
    fn default() -> Self {
        let now = std::time::Instant::now();
        Self {
            inserted_at: now,
            updated_at: now,
            update_count: 0,
            retracted: false,
        }
    }
}

/// Working Memory - stores and manages facts (Drools-style)
pub struct WorkingMemory {
    /// All facts by handle
    facts: HashMap<FactHandle, WorkingMemoryFact>,
    /// Type index: fact_type -> set of handles
    type_index: HashMap<String, HashSet<FactHandle>>,
    /// Next fact ID
    next_id: AtomicU64,
    /// Modified handles since last propagation
    modified_handles: HashSet<FactHandle>,
    /// Retracted handles since last propagation
    retracted_handles: HashSet<FactHandle>,
}

impl WorkingMemory {
    /// Create a new empty working memory
    pub fn new() -> Self {
        Self {
            facts: HashMap::new(),
            type_index: HashMap::new(),
            next_id: AtomicU64::new(1),
            modified_handles: HashSet::new(),
            retracted_handles: HashSet::new(),
        }
    }

    /// Insert a fact into working memory (returns FactHandle)
    pub fn insert(&mut self, fact_type: String, data: TypedFacts) -> FactHandle {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let handle = FactHandle::new(id);

        let fact = WorkingMemoryFact {
            handle,
            fact_type: fact_type.clone(),
            data,
            metadata: FactMetadata::default(),
            #[cfg(feature = "streaming")]
            stream_source: None,
            #[cfg(feature = "streaming")]
            stream_event: None,
        };

        self.facts.insert(handle, fact);
        self.type_index.entry(fact_type).or_default().insert(handle);
        self.modified_handles.insert(handle);

        handle
    }

    /// Insert a fact from a stream event
    #[cfg(feature = "streaming")]
    pub fn insert_from_stream(
        &mut self,
        stream_name: String,
        event: crate::streaming::event::StreamEvent,
    ) -> FactHandle {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let handle = FactHandle::new(id);

        // Convert event data to TypedFacts
        let mut typed_facts = super::facts::TypedFacts::new();
        for (key, value) in &event.data {
            let fact_value: super::facts::FactValue = value.clone().into();
            typed_facts.set(key.clone(), fact_value);
        }

        let fact = WorkingMemoryFact {
            handle,
            fact_type: event.event_type.clone(),
            data: typed_facts,
            metadata: FactMetadata::default(),
            stream_source: Some(stream_name.clone()),
            stream_event: Some(event),
        };

        self.facts.insert(handle, fact);
        self.type_index
            .entry(stream_name)
            .or_default()
            .insert(handle);
        self.modified_handles.insert(handle);

        handle
    }

    /// Update a fact in working memory
    pub fn update(&mut self, handle: FactHandle, data: TypedFacts) -> Result<(), String> {
        let fact = self
            .facts
            .get_mut(&handle)
            .ok_or_else(|| format!("FactHandle {} not found", handle))?;

        if fact.metadata.retracted {
            return Err(format!("FactHandle {} is retracted", handle));
        }

        fact.data = data;
        fact.metadata.updated_at = std::time::Instant::now();
        fact.metadata.update_count += 1;
        self.modified_handles.insert(handle);

        Ok(())
    }

    /// Retract (delete) a fact from working memory
    pub fn retract(&mut self, handle: FactHandle) -> Result<(), String> {
        let fact = self
            .facts
            .get_mut(&handle)
            .ok_or_else(|| format!("FactHandle {} not found", handle))?;

        if fact.metadata.retracted {
            return Err(format!("FactHandle {} already retracted", handle));
        }

        fact.metadata.retracted = true;
        self.retracted_handles.insert(handle);

        // Remove from type index
        if let Some(handles) = self.type_index.get_mut(&fact.fact_type) {
            handles.remove(&handle);
        }

        Ok(())
    }

    /// Get a fact by handle
    pub fn get(&self, handle: &FactHandle) -> Option<&WorkingMemoryFact> {
        self.facts.get(handle).filter(|f| !f.metadata.retracted)
    }

    /// Get all facts of a specific type
    pub fn get_by_type(&self, fact_type: &str) -> Vec<&WorkingMemoryFact> {
        if let Some(handles) = self.type_index.get(fact_type) {
            handles
                .iter()
                .filter_map(|h| self.facts.get(h))
                .filter(|f| !f.metadata.retracted)
                .collect()
        } else {
            Vec::new()
        }
    }

    /// Get all facts
    pub fn get_all_facts(&self) -> Vec<&WorkingMemoryFact> {
        self.facts
            .values()
            .filter(|f| !f.metadata.retracted)
            .collect()
    }

    /// Get all fact handles
    pub fn get_all_handles(&self) -> Vec<FactHandle> {
        self.facts
            .values()
            .filter(|f| !f.metadata.retracted)
            .map(|f| f.handle)
            .collect()
    }

    /// Get modified handles since last clear
    pub fn get_modified_handles(&self) -> &HashSet<FactHandle> {
        &self.modified_handles
    }

    /// Get retracted handles since last clear
    pub fn get_retracted_handles(&self) -> &HashSet<FactHandle> {
        &self.retracted_handles
    }

    /// Clear modification tracking (after propagation)
    pub fn clear_modification_tracking(&mut self) {
        self.modified_handles.clear();
        self.retracted_handles.clear();
    }

    /// Get statistics
    pub fn stats(&self) -> WorkingMemoryStats {
        let active_facts = self
            .facts
            .values()
            .filter(|f| !f.metadata.retracted)
            .count();
        let retracted_facts = self.facts.values().filter(|f| f.metadata.retracted).count();

        WorkingMemoryStats {
            total_facts: self.facts.len(),
            active_facts,
            retracted_facts,
            types: self.type_index.len(),
            modified_pending: self.modified_handles.len(),
            retracted_pending: self.retracted_handles.len(),
        }
    }

    /// Clear all facts
    pub fn clear(&mut self) {
        self.facts.clear();
        self.type_index.clear();
        self.modified_handles.clear();
        self.retracted_handles.clear();
    }

    /// Flatten all facts into a single TypedFacts for evaluation
    /// Each fact's fields are prefixed with "type.handle."
    pub fn to_typed_facts(&self) -> TypedFacts {
        let mut result = TypedFacts::new();

        for fact in self.get_all_facts() {
            let prefix = format!("{}.{}", fact.fact_type, fact.handle.id());
            for (key, value) in fact.data.get_all() {
                result.set(format!("{}.{}", prefix, key), value.clone());
            }

            // Also add without prefix for simple access (last fact of this type wins)
            for (key, value) in fact.data.get_all() {
                result.set(format!("{}.{}", fact.fact_type, key), value.clone());
            }

            // Store handle for this fact type (last fact wins, but better than nothing)
            // Actions can use Type._handle to get the handle
            result.set_fact_handle(fact.fact_type.clone(), fact.handle);
        }

        result
    }
}

impl Default for WorkingMemory {
    fn default() -> Self {
        Self::new()
    }
}

/// Working memory statistics
#[derive(Debug, Clone)]
pub struct WorkingMemoryStats {
    pub total_facts: usize,
    pub active_facts: usize,
    pub retracted_facts: usize,
    pub types: usize,
    pub modified_pending: usize,
    pub retracted_pending: usize,
}

impl std::fmt::Display for WorkingMemoryStats {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "WM Stats: {} active, {} retracted, {} types, {} modified, {} pending retraction",
            self.active_facts,
            self.retracted_facts,
            self.types,
            self.modified_pending,
            self.retracted_pending
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_insert_and_get() {
        let mut wm = WorkingMemory::new();
        let mut person_data = TypedFacts::new();
        person_data.set("name", "John");
        person_data.set("age", 25i64);

        let handle = wm.insert("Person".to_string(), person_data);

        let fact = wm.get(&handle).unwrap();
        assert_eq!(fact.fact_type, "Person");
        assert_eq!(fact.data.get("name").unwrap().as_string(), "John");
    }

    #[test]
    fn test_update() {
        let mut wm = WorkingMemory::new();
        let mut data = TypedFacts::new();
        data.set("age", 25i64);

        let handle = wm.insert("Person".to_string(), data);

        let mut updated_data = TypedFacts::new();
        updated_data.set("age", 26i64);
        wm.update(handle, updated_data).unwrap();

        let fact = wm.get(&handle).unwrap();
        assert_eq!(fact.data.get("age").unwrap().as_integer(), Some(26));
        assert_eq!(fact.metadata.update_count, 1);
    }

    #[test]
    fn test_retract() {
        let mut wm = WorkingMemory::new();
        let data = TypedFacts::new();
        let handle = wm.insert("Person".to_string(), data);

        wm.retract(handle).unwrap();

        assert!(wm.get(&handle).is_none());
        assert_eq!(wm.get_all_facts().len(), 0);
    }

    #[test]
    fn test_type_index() {
        let mut wm = WorkingMemory::new();

        for i in 0..5 {
            let mut data = TypedFacts::new();
            data.set("id", i as i64);
            wm.insert("Person".to_string(), data);
        }

        for i in 0..3 {
            let mut data = TypedFacts::new();
            data.set("id", i as i64);
            wm.insert("Order".to_string(), data);
        }

        assert_eq!(wm.get_by_type("Person").len(), 5);
        assert_eq!(wm.get_by_type("Order").len(), 3);
        assert_eq!(wm.get_by_type("Unknown").len(), 0);
    }

    #[test]
    fn test_modification_tracking() {
        let mut wm = WorkingMemory::new();
        let data = TypedFacts::new();
        let h1 = wm.insert("Person".to_string(), data.clone());
        let h2 = wm.insert("Person".to_string(), data.clone());

        assert_eq!(wm.get_modified_handles().len(), 2);

        wm.clear_modification_tracking();
        assert_eq!(wm.get_modified_handles().len(), 0);

        wm.update(h1, data.clone()).unwrap();
        assert_eq!(wm.get_modified_handles().len(), 1);

        wm.retract(h2).unwrap();
        assert_eq!(wm.get_retracted_handles().len(), 1);
    }
}