rust-logic-graph 0.8.6

A modular reasoning graph framework for distributed logic orchestration
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
# 🧠 Rust Logic Graph

[![Rust](https://img.shields.io/badge/rust-1.70%2B-orange.svg)](https://www.rust-lang.org/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![GitHub](https://img.shields.io/badge/github-KSD--CO%2Frust--logic--graph-blue.svg)](https://github.com/KSD-CO/rust-logic-graph)
[![CI](https://github.com/KSD-CO/rust-logic-graph/actions/workflows/rust.yml/badge.svg)](https://github.com/KSD-CO/rust-logic-graph/actions)

A high-performance **reasoning graph framework** for Rust with **GRL (Grule Rule Language)** support. Build complex workflows with conditional execution, topological ordering, and async processing.

---

## ✨ Key Features

- 🔥 **GRL Support** - [rust-rule-engine v0.14.0]https://crates.io/crates/rust-rule-engine with RETE-UL algorithm (2-24x faster)
- 🔄 **Topological Execution** - Automatic DAG-based node ordering
-**Async Runtime** - Built on Tokio for high concurrency
-**Parallel Execution** - Automatic parallel execution of independent nodes (v0.5.0)
- 💾 **Caching Layer** - High-performance result caching with TTL, eviction policies, and memory limits (v0.5.0)
- 🧠 **Memory Optimization** - Context pooling and allocation tracking (v0.7.0)
- 🛠️ **CLI Developer Tools** - Graph validation, dry-run, profiling, and visualization (v0.5.0)
- 🎨 **Web Graph Editor** - Next.js visual editor with drag-and-drop interface (v0.8.0)
-**YAML Configuration** - Declarative graph definitions with external config files (v0.8.5)
- �📊 **Multiple Node Types** - RuleNode, DBNode, AINode
- 📝 **JSON/YAML Configuration** - Simple workflow definitions
- 🎯 **98% Drools Compatible** - Easy migration from Java
- 🌊 **Streaming Processing** - Stream-based execution with backpressure (v0.3.0)
- 🗄️ **Database Integrations** - PostgreSQL, MySQL, Redis, MongoDB (v0.2.0)
- 🤖 **AI/LLM Integrations** - OpenAI, Claude, Ollama (v0.2.0)

---

## 🚀 Quick Start

### Installation

```toml
[dependencies]
rust-logic-graph = "0.8.5"

# With specific integrations
rust-logic-graph = { version = "0.8.5", features = ["postgres", "openai"] }

# With all integrations
rust-logic-graph = { version = "0.8.5", features = ["all-integrations"] }
```

### Simple Example

```rust
use rust_logic_graph::{RuleEngine, GrlRule};

let grl = r#"
rule "Discount" {
    when
        cart_total > 100 && is_member == true
    then
        discount = 0.15;
}
"#;

let mut engine = RuleEngine::new();
engine.add_grl_rule(grl)?;
```

## 🏢 Real-World Case Study: Purchasing Flow System

See a complete production implementation in **[case_study/](case_study/)** - A full-featured purchasing automation system built with Rust Logic Graph.

### 📊 System Overview

**Problem**: Automate purchasing decisions for inventory replenishment across multiple products, warehouses, and suppliers.

**Solution**: Business rules in GRL decide when/how much to order. Orchestrator executes the workflows.

### 🎯 Two Architecture Implementations

**1. Microservices (v4.0)** - 7 services with gRPC
- Orchestrator (port 8080) - Workflow coordination
- OMS Service (port 50051) - Order management data
- Inventory Service (port 50052) - Stock levels
- Supplier Service (port 50053) - Supplier information
- UOM Service (port 50054) - Unit conversions
- Rule Engine (port 50055) - GRL business rules
- PO Service (port 50056) - Purchase order management

**2. Monolithic (Clean Architecture)** - Single HTTP service with dynamic configuration
- Same business logic as microservices (shared GRL rules)
- Single process on port 8080
- **Multi-database architecture** - 4 separate PostgreSQL databases (oms_db, inventory_db, supplier_db, uom_db)
- **YAML-driven workflow** - Graph structure defined in `purchasing_flow_graph.yaml`
- **Dynamic field mapping** - Config-driven data extraction from context
- **Zero hardcoded fields** - All field names configurable via YAML
- Direct in-process execution (no network calls)

### 🔥 GRL Business Rules (15 Rules)

```grl
rule "CalculateShortage" salience 120 no-loop {
  when
    required_qty > 0
  then
    Log("Calculating shortage...");
    shortage = required_qty - available_qty;
    Log("Shortage calculated");
}

rule "OrderMOQWhenShortageIsLess" salience 110 no-loop {
  when
    shortage > 0 && shortage < moq && is_active == true
  then
    Log("Shortage less than MOQ, ordering MOQ");
    order_qty = moq;
}
```

**See full rules**: [purchasing_rules.grl](case_study/microservices/services/rule-engine-service/rules/purchasing_rules.grl)

### YAML Configuration (NEW in v0.8.5)

Both Monolithic and Microservices implementations support **YAML-based graph configuration**:

**Monolithic YAML Example** (`purchasing_flow_graph.yaml`):
```yaml
nodes:
  oms_history:
    type: DBNode
    database: "oms_db"  # Multi-database routing
    query: "SELECT product_id, avg_daily_demand::float8, trend FROM oms_history WHERE product_id = $1"
  
  inventory_levels:
    type: DBNode
    database: "inventory_db"
    query: "SELECT product_id, available_qty::float8, reserved_qty::float8 FROM inventory WHERE product_id = $1"
  
  rule_engine:
    type: RuleNode
    description: "Evaluate business rules with dynamic field mapping"
    dependencies:
      - oms_history
      - inventory_levels
      - supplier_info
      - uom_conversion
    field_mappings:  # Dynamic field extraction (NEW)
      avg_daily_demand: "oms_history.avg_daily_demand"
      available_qty: "inventory_levels.available_qty"
      lead_time: "supplier_info.lead_time"
      moq: "supplier_info.moq"

  create_po:
    type: RuleNode
    dependencies:
      - rule_engine
    field_mappings:
      should_order: "rule_engine.should_order"
      recommended_qty: "rule_engine.recommended_qty"
      product_id: "supplier_info.product_id"

edges:
  - from: oms_history
    to: rule_engine
  - from: inventory_levels
    to: rule_engine
  - from: rule_engine
    to: create_po
```

**Microservices YAML Example** (`purchasing_flow_graph.yaml`):
```yaml
nodes:
  oms_grpc:
    type: DBNode
    description: "Fetch order management data via gRPC"
  
  inventory_grpc:
    type: DBNode
    description: "Fetch inventory levels via gRPC"
  
  rule_engine_grpc:
    type: RuleNode
    description: "Evaluate business rules"
    dependencies:
      - oms_grpc
      - inventory_grpc

edges:
  - from: oms_grpc
    to: rule_engine_grpc
  - from: inventory_grpc
    to: rule_engine_grpc
```

**Benefits:**
- **70% less code** - Graph definition moves from Rust to YAML
-**No recompile** - Change workflows without rebuilding
-**Dynamic field mapping** - Zero hardcoded field names in Rust code
-**Multi-database routing** - Each node specifies its database
-**Multiple workflows** - Easy variants (urgent, standard, approval)
-**Better readability** - Clear, declarative graph structure
-**Easy testing** - Test with different configurations

**Usage:**
```rust
// Monolithic - Default config with multi-database
executor.execute("PROD-001").await?;

// Monolithic - Custom workflow
executor.execute_with_config("PROD-001", "urgent_flow.yaml").await?;

// Microservices - Default config with gRPC nodes
orchestrator.execute("PROD-001").await?;
```

**Key Architecture Differences:**

| Feature | Monolithic | Microservices |
|---------|-----------|---------------|
| **Database Access** | Direct SQL queries to 4 DBs | gRPC calls to services |
| **Field Mapping** | YAML `field_mappings` config | Hardcoded in gRPC nodes |
| **Rule Engine** | In-process RuleEngine call | gRPC to rule-engine-service |
| **Communication** | Function calls | gRPC (network) |
| **Graph Executor** | `PurchasingGraphExecutor` | `OrchestratorExecutor` |
| **Node Types** | `DynamicDBNode`, `DynamicRuleNode` | `OmsGrpcNode`, `RuleEngineGrpcNode` |

**Documentation**: See [YAML_CONFIGURATION_SUMMARY.md](case_study/YAML_CONFIGURATION_SUMMARY.md)

### Microservices Communication Flow

After v0.8.0 refactor, the Orchestrator now uses **rust-logic-graph's Graph/Executor pattern** to coordinate microservices:

- The Orchestrator receives a purchasing request (HTTP) and creates a **Graph** with 6 custom **gRPC Nodes**.
- Each Node wraps a gRPC call to a service: `OmsGrpcNode`, `InventoryGrpcNode`, `SupplierGrpcNode`, `UomGrpcNode`, `RuleEngineGrpcNode`, `PoGrpcNode`.
- The **Executor** runs the graph in topological order:
  1. **Data Collection Phase** (parallel): OMS, Inventory, Supplier, UOM nodes execute simultaneously via gRPC
  2. **Rule Evaluation Phase**: RuleEngineGrpcNode waits for all data, then evaluates GRL rules
  3. **Execution Phase**: PoGrpcNode creates/sends PO based on rule decisions
- All business logic (decision flags, calculations) comes from GRL rules. The Orchestrator is a pure executor.

**Graph Topology**:
```
OMS Node ────┐
Inventory ───┼──→ RuleEngine Node ──→ PO Node
Supplier ────┤
UOM Node ────┘
```

**Benefits of Graph/Executor Pattern**:
- **Declarative**: Define workflow as nodes + edges instead of imperative code
-**Parallel Execution**: Data nodes run concurrently automatically
-**Type Safety**: Custom Node implementations with Rust's type system
-**Testable**: Each node can be tested in isolation
-**Consistent**: Same pattern used in monolithic and microservices

```
┌─────────────────────────────────────────────────────────────────────┐
│                         CLIENT (HTTP REST)                          │
└────────────────────────────────┬────────────────────────────────────┘
                                 │ POST /purchasing/flow
        ┌────────────────────────────────────────────────────────────┐
        │            Orchestrator Service (Port 8080)                │
        │  ┌─────────────────────────────────────────────────────┐   │
        │  │          rust-logic-graph Graph Executor            │   │
        │  │                                                     │   │
        │  │  Creates Graph with 6 gRPC Nodes:                   │   │
        │  │  • OmsGrpcNode      → gRPC to OMS :50051            │   │
        │  │  • InventoryGrpcNode → gRPC to Inventory :50052     │   │
        │  │  • SupplierGrpcNode → gRPC to Supplier :50053       │   │
        │  │  • UomGrpcNode      → gRPC to UOM :50054            │   │
        │  │  • RuleEngineGrpcNode → gRPC to Rules :50055        │   │
        │  │  • PoGrpcNode       → gRPC to PO :50056             │   │
        │  │                                                     │   │
        │  │  Graph Topology:                                    │   │
        │  │  OMS ───────┐                                       │   │
        │  │  Inventory ─┼─→ RuleEngine ──→ PO                   │   │
        │  │  Supplier ──┤                                       │   │
        │  │  UOM ───────┘                                       │   │
        │  └─────────────────────────────────────────────────────┘   │
        └────────┬───────────────────────────────────────────────────┘
   ┌─────────────┼──────────────────┬────────────────┬──────────────┐
   │ (Parallel)  │  (Parallel)      │   (Parallel)   │  (Parallel)  │
   ▼             ▼                  ▼                ▼              │
┌──────────┐  ┌────────────┐  ┌─────────────┐  ┌───────────┐        │
│OMS :50051│  │Inventory   │  │Supplier     │  │UOM :50054 │        │
│          │  │:50052      │  │:50053       │  │           │        │
│• History │  │• Levels    │  │• Pricing    │  │• Convert  │        │
│• Demand  │  │• Available │  │• Lead Time  │  │• Factors  │        │
└────┬─────┘  └─────┬──────┘  └──────┬──────┘  └─────┬─────┘        │
     │              │                │               │              │
     └──────────────┴────────────────┴───────────────┘              │
                          │                                         │
                          │ Data stored in Graph Context            │
                          ▼                                         │
                   ┌─────────────────┐                              │
                   │ Rule Engine     │ (Port 50055 - gRPC)          │
                   │     :50055      │                              │
                   │                 │                              │
                   │ • GRL Rules     │ • Evaluates 15 rules         │
                   │ • Calculations  │ • Returns decision flags     │
                   │ • Decision Flags│ • NO side effects            │
                   └────────┬────────┘                              │
                            │                                       │
                            │ Flags stored in Graph Context         │
                            ▼                                       │
                   ┌─────────────────┐                              │
                   │ PO Service      │ (Port 50056 - gRPC)          │
                   │    :50056       │◄─────────────────────────────┘
                   │                 │
                   │ • Create PO     │ • Reads flags from context
                   │ • Send to       │ • Executes based on rules
                   │   Supplier      │ • Email/API delivery
                   └─────────────────┘
```
**Note**: The Rule Engine service returns decision flags and calculations to the Graph Context. The PoGrpcNode then reads these flags from the context to determine whether to create/send the PO.

### Where rust-logic-graph is Used

**Monolithic App** (`case_study/monolithic/`):
- Uses `Graph`, `Executor`, and custom `Node` implementations
- **Multi-database architecture**: 4 separate PostgreSQL databases (oms_db, inventory_db, supplier_db, uom_db)
- **Dynamic field mapping**: YAML-configured field extraction with zero hardcoded field names
- **Config-driven nodes**: `DynamicDBNode` and `DynamicRuleNode` read behavior from YAML
- Database routing via `database` field in YAML (e.g., `database: "oms_db"`)
- Field mappings via `field_mappings` in YAML (e.g., `avg_daily_demand: "oms_history.avg_daily_demand"`)
- `RuleEngineService` accepts `HashMap<String, Value>` for complete flexibility
- Graph structure defined in `purchasing_flow_graph.yaml`
- Single process, no network calls

**Orchestrator Microservice** (`case_study/microservices/services/orchestrator-service/`):
- Uses `Graph`, `Executor`, and custom gRPC `Node` implementations  
- 6 gRPC nodes make network calls to remote services
- Same graph topology as monolithic
- Distributed across multiple processes

**Rule Engine Service** (`case_study/microservices/services/rule-engine-service/`):
- Uses `RuleEngine` for GRL evaluation
- Exposed via gRPC endpoint
- Stateless service (no graph execution)

**Other Microservices** (OMS, Inventory, Supplier, UOM, PO):
- Standard gRPC services with database access
- Do NOT use rust-logic-graph directly
- Called by Orchestrator's Graph Executor

**Architecture Highlights:**

**Monolithic Clean Architecture:**
```
┌─────────────────────────────────────────────────────────────────────────┐
│                   HTTP REST API (Port 8080)                             │
│                 POST /purchasing/flow {product_id}                      │
└──────────────────────────────┬──────────────────────────────────────────┘
        ┌──────────────────────────────────────────────────────────────┐
        │         PurchasingGraphExecutor (Clean Architecture)          │
        │                                                               │
        │  ┌────────────────────────────────────────────────────────┐  │
        │  │       rust-logic-graph Graph/Executor Engine           │  │
        │  │                                                        │  │
        │  │  1. Load purchasing_flow_graph.yaml                    │  │
        │  │  2. Parse nodes + edges + field_mappings               │  │
        │  │  3. Create DynamicDBNode per database config           │  │
        │  │  4. Create DynamicRuleNode with field mappings         │  │
        │  │  5. Execute graph in topological order                 │  │
        │  │                                                        │  │
        │  │  Graph Topology:                                       │  │
        │  │  oms_history ────────┐                                 │  │
        │  │  inventory_levels ───┼──→ rule_engine ──→ create_po    │  │
        │  │  supplier_info ──────┤                                 │  │
        │  │  uom_conversion ─────┘                                 │  │
        │  └────────────────────────────────────────────────────────┘  │
        └──────────────┬───────────────────────────────────────────────┘
    ┌──────────────────┼──────────────────┬──────────────────┬──────────┐
    │ (Parallel DBs)   │  (Parallel DBs)  │  (Parallel DBs)  │ (Parallel)
    ▼                  ▼                  ▼                  ▼          │
┌──────────────┐  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐ │
│  oms_db      │  │ inventory_db │  │ supplier_db  │  │   uom_db     │ │
│ PostgreSQL   │  │ PostgreSQL   │  │ PostgreSQL   │  │ PostgreSQL   │ │
│              │  │              │  │              │  │              │ │
│ • history    │  │ • levels     │  │ • info       │  │ • conversion │ │
│ • demand     │  │ • available  │  │ • pricing    │  │ • factors    │ │
│ • trends     │  │ • reserved   │  │ • lead_time  │  │              │ │
└──────┬───────┘  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘ │
       │                 │                 │                 │         │
       │ Query with      │ Query with      │ Query with      │ Query   │
       │ database:"oms"  │ database:"inv"  │ database:"sup"  │ with DB │
       └─────────────────┴─────────────────┴─────────────────┴─────────┘
                         Data stored in Graph Context
                         with path notation (e.g., "oms_history.avg_daily_demand")
                  ┌──────────────────────────────────────────┐
                  │        DynamicRuleNode (rule_engine)     │
                  │                                          │
                  │  YAML field_mappings config:             │
                  │  ┌────────────────────────────────────┐  │
                  │  │ avg_daily_demand:                  │  │
                  │  │   "oms_history.avg_daily_demand"   │  │
                  │  │ available_qty:                     │  │
                  │  │   "inventory_levels.available_qty" │  │
                  │  │ lead_time:                         │  │
                  │  │   "supplier_info.lead_time"        │  │
                  │  │ ... (9 total mappings)             │  │
                  │  └────────────────────────────────────┘  │
                  │                                          │
                  │  extract_rule_inputs() loop:             │
                  │  • Reads field_mappings from YAML        │
                  │  • Uses get_value_by_path() for parsing  │
                  │  • Returns HashMap<String, Value>        │
                  │  • ZERO hardcoded field names!           │
                  └──────────────┬───────────────────────────┘
                  ┌──────────────────────────────────────────┐
                  │      RuleEngineService (In-Process)      │
                  │                                          │
                  │  evaluate(HashMap<String, Value>)        │
                  │                                          │
                  │  • Loads purchasing_rules.grl            │
                  │  • 15 business rules (GRL)               │
                  │  • Accepts dynamic HashMap input         │
                  │  • No struct, no hardcoded fields        │
                  │  • Pure functional evaluation            │
                  │                                          │
                  │  Rules calculate:                        │
                  │  ✓ shortage = required_qty - available   │
                  │  ✓ order_qty (respects MOQ)              │
                  │  ✓ total_amount with discounts           │
                  │  ✓ requires_approval flag                │
                  │  ✓ should_create_po flag                 │
                  └──────────────┬───────────────────────────┘
                      Decision flags returned to Context
                  ┌──────────────────────────────────────────┐
                  │    DynamicRuleNode (create_po)           │
                  │                                          │
                  │  YAML field_mappings config:             │
                  │  ┌────────────────────────────────────┐  │
                  │  │ should_order:                      │  │
                  │  │   "rule_engine.should_order"       │  │
                  │  │ recommended_qty:                   │  │
                  │  │   "rule_engine.recommended_qty"    │  │
                  │  │ product_id:                        │  │
                  │  │   "supplier_info.product_id"       │  │
                  │  │ ... (6 total mappings)             │  │
                  │  └────────────────────────────────────┘  │
                  │                                          │
                  │  • Reads rule_engine output from context │
                  │  • Dynamic field extraction via YAML     │
                  │  • Creates PO if should_order == true    │
                  │  • Returns PO JSON or null               │
                  └──────────────────────────────────────────┘
```

**Key Design Principles:**

1. **Multi-Database Routing** - Each node specifies its database in YAML:
   ```yaml
   oms_history:
     database: "oms_db"  # Routes to oms_db pool
   ```

2. **Dynamic Field Mapping** - Zero hardcoded fields in Rust code:
   ```yaml
   field_mappings:
     avg_daily_demand: "oms_history.avg_daily_demand"
   ```
   ```rust
   // Code is 100% generic
   for (key, path) in &self.field_mappings {
       inputs.insert(key.clone(), get_value_by_path(ctx, path));
   }
   ```

3. **Config-Driven Execution** - Graph structure in YAML, not Rust:
   ```rust
   executor.execute_with_config("PROD-001", "purchasing_flow_graph.yaml")?;
   ```

4. **HashMap-Based RuleEngine** - Accepts any fields:
   ```rust
   pub fn evaluate(&mut self, inputs: HashMap<String, Value>) -> Result<Output>
   ```

**Microservices Communication Flow**

1. **Multi-Database Routing** (`graph_executor.rs`):
```rust
// YAML config specifies database per node
oms_history:
  database: "oms_db"
  query: "SELECT ..."

// Executor routes to correct pool
let pool = self.get_pool(node_config.database.as_deref());
```

2. **Dynamic Field Mapping** (`graph_executor.rs`):
```rust
// YAML config defines field mappings
field_mappings:
  avg_daily_demand: "oms_history.avg_daily_demand"
  available_qty: "inventory_levels.available_qty"

// Code extracts dynamically (zero hardcoding)
fn extract_inputs(&self, ctx: &Context) -> HashMap<String, Value> {
    for (key, path) in &self.field_mappings {
        if let Some(value) = self.get_value_by_path(ctx, path) {
            inputs.insert(key.clone(), value);
        }
    }
}
```

3. **Config-Driven RuleEngine** (`rule_service.rs`):
```rust
// Accepts HashMap instead of struct - 100% flexible
pub fn evaluate(&mut self, inputs: HashMap<String, Value>) -> Result<Output> {
    // Uses any fields present in HashMap
    // No hardcoded field requirements
}
```

### Web Graph Editor (NEW in v0.8.0)

**🌐 Online Editor**: [https://logic-graph-editor.amalthea.cloud/](https://logic-graph-editor.amalthea.cloud/)

Try the visual graph editor online - no installation required! Create workflows, define rules, and visualize your logic graphs with drag-and-drop.

### CLI Tools (v0.5.0)

```bash
# Build the CLI tool
cargo build --release --bin rlg

# Validate a graph
./target/release/rlg validate --file examples/sample_graph.json

# Visualize graph structure
./target/release/rlg visualize --file examples/sample_graph.json --details

# Profile performance
./target/release/rlg profile --file examples/sample_graph.json --iterations 100

# Dry-run without execution
./target/release/rlg dry-run --file examples/sample_graph.json --verbose
```

**[Full CLI Documentation →](docs/CLI_TOOL.md)**

### Run Examples

```bash
# Basic workflow
cargo run --example simple_flow

# GRL rules
cargo run --example grl_rules

# Advanced integration
cargo run --example grl_graph_flow
```

---


---

## 📚 Documentation

| Document | Description |
|----------|-------------|
| **[🏢 Case Study: Purchasing Flow]case_study/docs/README.md** | Real production system with microservices & monolithic implementations |
| **[📋 YAML Configuration Guide]case_study/YAML_CONFIGURATION_SUMMARY.md** | Declarative graph configuration with YAML (NEW in v0.8.5) |
| **[Graph Editor Guide]graph-editor/README.md** | Visual web-based graph editor with Next.js (NEW in v0.8.0) |
| **[Memory Optimization Guide]docs/MEMORY_OPTIMIZATION.md** | Context pooling and allocation tracking (v0.7.0) |
| **[CLI Tool Guide]docs/CLI_TOOL.md** | Developer tools for validation, profiling, and visualization (v0.5.0) |
| **[Cache Guide]docs/CACHE_IMPLEMENTATION.md** | Caching layer with TTL and eviction policies (v0.5.0) |
| **[Migration Guide]docs/MIGRATION_GUIDE.md** | Upgrade guide to v0.14.0 with RETE-UL (v0.5.0) |
| **[Integrations Guide]docs/INTEGRATIONS.md** | Database & AI integrations (v0.2.0) |
| **[GRL Guide]docs/GRL.md** | Complete GRL syntax and examples |
| **[Use Cases]docs/USE_CASES.md** | 33+ real-world applications |
| **[Extending]docs/EXTENDING.md** | Create custom nodes and integrations |
| **[Implementation]docs/IMPLEMENTATION_SUMMARY.md** | Technical details |

---

## 🎯 Use Cases

Rust Logic Graph powers applications in:

- 💰 **Finance** - Loan approval, fraud detection, risk assessment
- 🛒 **E-commerce** - Dynamic pricing, recommendations, fulfillment
- 🏥 **Healthcare** - Patient triage, clinical decisions, monitoring
- 🏭 **Manufacturing** - Predictive maintenance, QC automation
- 🛡️ **Insurance** - Claims processing, underwriting
- 📊 **Marketing** - Lead scoring, campaign optimization
- ⚖️ **Compliance** - AML monitoring, GDPR automation

**[View all 33+ use cases →](docs/USE_CASES.md)**

---

## 🏗️ Architecture

![Rust Logic Graph architecture diagram](https://raw.githubusercontent.com/KSD-CO/rust-logic-graph/main/docs/images/rust-logic-graph-architect.png)


---

## 🔥 GRL Example

```grl
rule "HighValueLoan" salience 100 {
    when
        loan_amount > 100000 &&
        credit_score < 750
    then
        requires_manual_review = true;
        approval_tier = "senior";
}

rule "AutoApproval" salience 50 {
    when
        credit_score >= 700 &&
        income >= loan_amount * 3 &&
        debt_ratio < 0.4
    then
        auto_approve = true;
        interest_rate = 3.5;
}
```

**[Learn more about GRL →](docs/GRL.md)**

---

## 📊 Performance

- **RETE-UL Algorithm**: Advanced pattern matching with unlinking (v0.14.0)
- **2-24x Faster**: Than v0.10 at 50+ rules
- **98% Drools Compatible**: Easy migration path
- **Async by Default**: High concurrency support
- **Parallel Execution**: Automatic layer-based parallelism
- **Smart Caching**: Result caching with TTL and eviction policies

---

## 🧪 Testing & CLI Tools

```bash
# Run all tests
cargo test

# Build CLI tool
cargo build --release --bin rlg

# Validate graph
./target/release/rlg validate --file examples/sample_graph.json

# Visualize graph structure
./target/release/rlg visualize --file examples/sample_graph.json

# Profile performance
./target/release/rlg profile --file examples/sample_graph.json --iterations 100

# Dry-run execution
./target/release/rlg dry-run --file examples/sample_graph.json --verbose
```

**Test Results**: ✅ 32/32 tests passing

**[Learn more about CLI tools →](docs/CLI_TOOL.md)**

---

## 📦 Project Status

**Version**: 0.8.5 (Latest)
**Status**: Production-ready with YAML configuration, web graph editor, and real-world case study

### What's Working
- ✅ Core graph execution engine
-**RETE-UL algorithm** (v0.14.0) - 2-24x faster
- ✅ Three node types (Rule, DB, AI)
- ✅ Topological sorting
- ✅ Async execution
- ✅ JSON I/O
-**Database integrations** (PostgreSQL, MySQL, Redis, MongoDB)
-**AI integrations** (OpenAI, Claude, Ollama)
-**Streaming processing** with backpressure and chunking
-**Parallel execution** with automatic layer detection
-**Caching layer** with TTL, eviction policies, memory limits (v0.5.0)
-**Memory optimization** with context pooling (v0.7.0)
-**CLI Developer Tools** - validate, profile, visualize, dry-run (v0.5.0)
-**Web Graph Editor** - Next.js visual editor with drag-and-drop (v0.8.0)
-**Production Case Study** - Purchasing flow with microservices & monolithic (v0.8.0)
-**YAML Configuration** - Declarative graph definitions (v0.8.5)
- ✅ Stream operators (map, filter, fold)
- ✅ Comprehensive documentation

### Roadmap
- [x] Streaming processing (v0.3.0) - COMPLETED ✅
- [x] Parallel node execution (v0.4.0) - COMPLETED ✅
- [x] Caching layer (v0.5.0) - COMPLETED ✅
- [x] CLI Developer Tools (v0.5.0) - COMPLETED ✅
- [x] RETE-UL upgrade (v0.5.0) - COMPLETED ✅
- [x] Memory Optimization (v0.7.0) - COMPLETED ✅
- [x] Web Graph Editor (v0.8.0) - COMPLETED ✅
- [x] Production Case Study (v0.8.0) - COMPLETED ✅
- [x] YAML Configuration (v0.8.5) - COMPLETED ✅
- [ ] GraphQL API (v0.9.0)
- [ ] Production release (v1.0.0)

**See [ROADMAP.md](ROADMAP.md) for details**

---

## 🤝 Contributing

Contributions welcome! Please:

1. Fork the repository
2. Create your feature branch
3. Write tests for new features
4. Submit a pull request

---

## 📖 Examples

| Example | Description | Lines |
|---------|-------------|-------|
| `simple_flow.rs` | Basic 3-node pipeline | 36 |
| `advanced_flow.rs` | Complex 6-node workflow | 120 |
| `grl_rules.rs` | GRL rule examples | 110 |
| `grl_graph_flow.rs` | GRL + Graph integration | 140 |
| `postgres_flow.rs` | PostgreSQL integration | 100 |
| `openai_flow.rs` | OpenAI GPT integration | 150 |
| `streaming_flow.rs` | Streaming with backpressure | 200 |
| `parallel_execution.rs` | Parallel node execution | 250 |

### CLI Tool Examples (v0.5.0)

| File | Description |
|------|-------------|
| `examples/sample_graph.json` | Linear workflow with 5 nodes |
| `examples/cyclic_graph.json` | Graph with cycle for testing |
| `examples/sample_context.json` | Sample input data |

**See [CLI_TOOL.md](docs/CLI_TOOL.md) for usage examples**

---

## 🌟 Why Rust Logic Graph?

### vs. Traditional Rule Engines
- **Async by default** - No blocking I/O
-**Type safety** - Rust's type system
-**Modern syntax** - GRL support
-**Graph-based** - Complex workflows

### vs. Workflow Engines
- **Embedded** - No external services
-**Fast** - Compiled Rust code
-**Flexible** - Custom nodes
-**Rule-based** - Business logic in rules

---

## 📝 Changelog

### v0.8.5 (2025-11-20) - YAML Configuration Release

**New Features:**
- 📋 **YAML Configuration Support** - Declarative graph definitions
  - Load graph structure from YAML files instead of hardcoded
  - `GraphConfig` module for parsing YAML configurations
  - Support for both JSON and YAML formats
  - 70% code reduction in graph executors
  - See [YAML Configuration Guide]case_study/YAML_CONFIGURATION_SUMMARY.md
- 🔧 **Enhanced Graph Executor API**
  - `execute()` - Use default configuration
  - `execute_with_config(config_path)` - Load custom YAML config
  - Dynamic node registration from config
- 📝 **Multiple Workflow Support**
  - Standard flow (full process)
  - Simplified flow (skip optional steps)
  - Urgent flow (fast-track)
  - Easy to create custom workflows
- 🏗️ **Monolithic Clean Architecture** (NEW)
  - Multi-database architecture with 4 PostgreSQL databases
  - Dynamic field mapping via YAML configuration
  - Zero hardcoded field names in code
  - Database routing per node via config
  - `field_mappings` for flexible data extraction
  - `RuleEngineService` accepts `HashMap<String, Value>`
  - Config-driven `DynamicDBNode` and `DynamicRuleNode`
- 📚 **Comprehensive Documentation**
  - YAML configuration guide with examples
  - Before/After comparison showing improvements
  - Multiple workflow examples
  - Integration guides for both architectures
  - Clean architecture patterns documentation

**Improvements:**
- Monolithic and Microservices both support YAML configs
- Reduced boilerplate code by 70% in executors
- Better separation of concerns (config vs. code)
- Easier testing with multiple configurations
- No recompilation needed for workflow changes
- Complete flexibility in field naming and mapping

**Examples:**
```yaml
# Monolithic with multi-database
nodes:
  oms_history:
    database: "oms_db"
    query: "SELECT ..."
  rule_engine:
    field_mappings:
      avg_daily_demand: "oms_history.avg_daily_demand"
```

```rust
// Dynamic field extraction (no hardcoding)
let inputs = self.extract_rule_inputs(ctx);
rule_service.evaluate(inputs)?;  // HashMap<String, Value>
```

**Compatibility:**
- All tests passing
- API backward compatible
- Existing hardcoded graphs still work

### v0.8.0 (2025-11-20) - Web Editor & Production Case Study Release

**New Features:**
- 🎨 **Web Graph Editor** - Next.js visual editor with drag-and-drop
  - Online version: https://logic-graph-editor.amalthea.cloud/
  - React Flow-based graph visualization
  - Real-time node editing and validation
  - Export/import JSON workflows
  - See [Graph Editor Guide]graph-editor/README.md
- 🏢 **Production Case Study** - Complete purchasing flow system
  - Microservices architecture (7 services with gRPC)
  - Monolithic architecture (single HTTP service)
  - 15 GRL business rules for purchasing decisions
  - Kubernetes deployment manifests
  - Docker Compose for local development
  - Shared GRL rules proving portability
  - See [Case Study Documentation]case_study/docs/README.md

**Improvements:**
- Updated README with case study section
- Added online graph editor link
- Comprehensive production examples

**Compatibility:**
- All tests passing
- API backward compatible

### v0.5.0 (2025-11-06) - Performance & Developer Tools Release

**Breaking Changes:**
- **Upgraded rust-rule-engine** from v0.10 → v0.14.0
  - Now uses RETE-UL algorithm (2-24x faster)
  - Better memory efficiency
  - Improved conflict resolution
  - See [Migration Guide]docs/MIGRATION_GUIDE.md

**New Features:**
- 🛠️ **CLI Developer Tools** (`rlg` binary)
  - Graph validation with comprehensive checks
  - Dry-run execution mode
  - Performance profiling with statistics
  - ASCII graph visualization
  - See [CLI Tool Guide]docs/CLI_TOOL.md
- 💾 **Caching Layer** - High-performance result caching
  - TTL-based expiration
  - Multiple eviction policies (LRU, LFU, FIFO)
  - Memory limits and statistics
  - See [Cache Guide]docs/CACHE_IMPLEMENTATION.md
-**Parallel Node Execution** - Automatic detection and parallel execution
  - Layer detection algorithm using topological sort
  - Concurrent execution within layers
  - Parallelism analysis and statistics
- 📊 **ParallelExecutor** - New executor with parallel capabilities
- 📝 **New Examples** - CLI examples and test graphs
-**32 Tests** - Comprehensive test coverage

**Improvements:**
- Updated documentation with CLI tools, caching, and migration guides
- Performance benchmarking utilities
- Example graph files for testing

**Compatibility:**
- All 32 tests passing
- API is backward compatible (100%)
- Performance: 2-24x faster rule matching

### v0.3.0 (2025-11-03) - Streaming & Performance Release

**New Features:**
- 🌊 **Streaming Processing** - Stream-based node execution
  - Backpressure handling with bounded channels
  - Large dataset support with chunking
  - Stream operators (map, filter, fold, async map)
- 📝 **New Example** - `streaming_flow.rs` with 6 demonstrations
-**8 New Tests** - Streaming module testing

**Performance:**
- Processed 10,000 items in chunks
- ~432 items/sec throughput with backpressure

### v0.2.0 (2025-11-02) - Integrations Release

**New Features:**
- 🗄️ **Database Integrations** - PostgreSQL, MySQL, Redis, MongoDB
- 🤖 **AI/LLM Integrations** - OpenAI GPT-4, Claude 3.5, Ollama
- 📝 **Integration Examples** - `postgres_flow.rs`, `openai_flow.rs`
- 📚 **INTEGRATIONS.md** - Comprehensive integration guide
- 🎛️ **Feature Flags** - Optional dependencies for integrations

### v0.1.0 (2025-11-01) - Initial Release

**Core Features:**
- 🧠 Core graph execution engine
- 🔥 GRL (Grule Rule Language) integration
- 🔄 Topological sorting
- ⚡ Async execution with Tokio
- 📊 Three node types (Rule, DB, AI)
- 📝 JSON I/O for graphs
- 📚 4 working examples
- ✅ 6/6 tests passing

---

## 📄 License

MIT License - see [LICENSE](LICENSE) for details.

---

## 🔗 Links

- **Repository**: https://github.com/KSD-CO/rust-logic-graph
- **rust-rule-engine**: https://crates.io/crates/rust-rule-engine
- **Documentation**: [docs/]docs/
- **Issues**: [GitHub Issues]https://github.com/KSD-CO/rust-logic-graph/issues

---

## 👥 Authors

**James Vu** - Initial work

---

## 🙏 Acknowledgments

Built with:
- [rust-rule-engine v0.14.0]https://crates.io/crates/rust-rule-engine - GRL support with RETE-UL
- [Tokio]https://tokio.rs/ - Async runtime
- [Petgraph]https://github.com/petgraph/petgraph - Graph algorithms
- [Serde]https://serde.rs/ - Serialization
- [Clap]https://github.com/clap-rs/clap - CLI framework

---

<div align="center">

**⭐ Star us on GitHub if you find this useful! ⭐**

[Documentation](docs/) • [Examples](examples/) • [Use Cases](docs/USE_CASES.md) • [YAML Config Guide](case_study/YAML_CONFIGURATION_SUMMARY.md)

</div>