rust-logic-graph

Crates.iorust-logic-graph
lib.rsrust-logic-graph
version0.12.0
created_at2025-11-02 13:50:14.101411+00
updated_at2026-01-20 15:16:33.63604+00
descriptionReasoning engine for distributed backend & AI orchestration. Coordinate services, databases, and AI agents with business rules (GRL).
homepage
repository
max_upload_size
id1913140
size1,517,106
(tonthatvu)

documentation

README

🧠 Rust Logic Graph

Current Version: 0.12.0

Reasoning Engine for Distributed Backend & AI Orchestration

Rust License: MIT GitHub CI

A high-performance reasoning engine for distributed backend systems and AI orchestration. Build complex decision workflows, coordinate multiple services, and create intelligent agent systems with GRL (Grule Rule Language) support.

Not a no-code automation tool - Rust Logic Graph is an embeddable library for developers building distributed reasoning systems, not a UI-first workflow platform like n8n or Zapier.


🎯 What is Rust Logic Graph?

Rust Logic Graph is a reasoning engine library for building intelligent backend systems:

Core Capabilities

🧠 Distributed Reasoning

  • Connect decisions across multiple databases and services
  • Build complex decision trees with business rules (GRL)
  • Maintain context as data flows through your system
  • Explain how decisions were reached

πŸ€– AI Agent Orchestration

  • Coordinate multiple LLMs in reasoning chains
  • Build RAG (Retrieval-Augmented Generation) pipelines
  • Create multi-agent systems with tool calling
  • Native support for OpenAI, Claude, Ollama, and custom models

⚑ High-Performance Execution

  • Sub-millisecond latency (embedded library, not service)
  • Automatic parallel execution of independent operations
  • Memory-efficient context pooling
  • Async/await throughout

πŸ”§ Production-Ready Patterns

  • Circuit breakers for unstable services
  • Retry logic with exponential backoff
  • Try/catch error handling
  • Saga pattern for distributed transactions (v0.12.0)

✨ Key Features

  • πŸ”₯ GRL Support - rust-rule-engine v1.18.0-alpha with 50-100x faster parsing
  • πŸ”„ 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)
  • πŸ—„οΈ Multi-Database Orchestration - Parallel queries, correlation, distributed transactions (v0.10.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)
  • 🎯 Advanced Control Flow - Subgraphs, conditionals, loops, error handling (v0.9.0)
  • 🚨 Rich Error Messages - Unique error codes, actionable suggestions, full context (v0.10.0) πŸ†•
  • πŸ“Š Multiple Node Types - RuleNode, DBNode, AINode, ConditionalNode, LoopNode, TryCatchNode, RetryNode, CircuitBreakerNode
  • πŸ“ 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)
  • πŸ›‘οΈ Saga Pattern - Distributed transaction coordinator, compensation, state persistence, timeout/deadline (v0.12.0)
  • πŸ›’ E-commerce Saga Example - Real-world order flow with compensation and rollback (v0.12.0)

πŸš€ Quick Start

Installation

[dependencies]
rust-logic-graph = "0.12.0"

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

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

Example Use Cases

Saga Pattern (E-commerce order flow):

let mut saga = SagaCoordinator::new(Some(Duration::from_secs(10)));
saga.add_step(SagaStep {
    id: "reserve_inventory".to_string(),
    action: Box::new(|ctx| { /* ... */ Ok(()) }),
    compensation: Some(Box::new(|ctx| { /* ... */ Ok(()) })),
    status: SagaStepStatus::Pending,
    timeout: Some(Duration::from_secs(3)),
});
// ... more steps (charge_payment, create_shipment, send_confirmation)
saga.execute()?;

Financial risk assessment across multiple data sources

let risk_engine = Graph::new()
    .add_node("credit_history", DBNode::postgres(...))
    .add_node("transaction_analysis", DBNode::mongodb(...))
    .add_node("fraud_check", AINode::openai(...))
    .add_node("risk_rules", RuleNode::grl("risk_assessment.grl"))
    .add_node("decision", ConditionalNode::new(...));

Multi-step AI reasoning with tool calling

let ai_agent = Graph::new()
    .add_node("understand_query", AINode::claude(...))
    .add_node("search_knowledge", SubgraphNode::new(rag_pipeline))
    .add_node("reason", AINode::openai_gpt4(...))
    .add_node("validate", RuleNode::grl("validation.grl"))
    .add_retry("reason", max_attempts: 3);

Microservice coordination with fault tolerance

let order_flow = Graph::new()
    .add_node("inventory", GrpcNode::new("inventory-service"))
    .add_node("payment", GrpcNode::new("payment-service"))
    .add_node("shipping", GrpcNode::new("shipping-service"))
    .add_circuit_breaker("payment", threshold: 5)
    .add_saga_compensation(...);

πŸ“š Documentation

Document Description
�🏒 Case Study: Purchasing Flow Real production system with microservices & monolithic implementations
πŸ“‹ YAML Configuration Guide Declarative graph configuration with YAML (NEW in v0.8.5)
Graph Editor Guide Visual web-based graph editor with Next.js (NEW in v0.8.0)
Memory Optimization Guide Context pooling and allocation tracking (v0.7.0)
CLI Tool Guide Developer tools for validation, profiling, and visualization (v0.5.0)
Cache Guide Caching layer with TTL and eviction policies (v0.5.0)
Migration Guide Upgrade guide to v0.14.0 with RETE-UL (v0.5.0)
Integrations Guide Database & AI integrations (v0.2.0)
GRL Guide Complete GRL syntax and examples
Use Cases 33+ real-world applications
Extending Create custom nodes and integrations
Implementation 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 β†’


πŸ—οΈ Architecture Patterns

Pattern 1: Multi-Database Reasoning

Query multiple databases, apply business rules, make decisions:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  PostgreSQL │───▢│   MongoDB   │───▢│    Redis    β”‚
β”‚  (Users)    β”‚    β”‚ (Analytics) β”‚    β”‚   (Cache)   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚                   β”‚                   β”‚
       β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
                   β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”
                   β”‚  Rule Engine  │◀─── GRL Rules
                   β”‚  (Decision)   β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                           β”‚
                   β”Œβ”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”
                   β”‚    Actions    β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Pattern 2: AI Agent with Tools

LLM orchestration with tool calling and validation:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ User Query  β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ LLM (Claude)    │──────┐
β”‚ Understand      β”‚      β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚
       β”‚              Tool Calls
β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”‚
β”‚ RAG Subgraph    │◀──────
β”‚ (Vector Search) β”‚      β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β”‚
       β”‚              β”Œβ”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚ Database β”‚
β”‚ LLM (GPT-4)     │◀── Query    β”‚
β”‚ Reason          β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Validate (GRL)  β”‚
β”‚ Business Rules  β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚
β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Response        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Pattern 3: Saga Pattern for Distributed Transactions

Coordinate microservices with compensation logic:

Order Service ──▢ Inventory Service ──▢ Payment Service ──▢ Shipping Service
     β”‚                   β”‚                    β”‚                    β”‚
   Success            Success             Success              Success
     β”‚                   β”‚                    β”‚                    β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
                           β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”
                           β”‚  Complete   β”‚
                           β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

If Payment Fails:
     β”‚                   β”‚                    βœ—
     β”‚                   β”‚              Compensation
     β”‚                   β”‚β—€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
     β”‚            Release Inventory
     β”‚β—€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  Cancel Order

View 6 complete architecture patterns β†’


πŸ—οΈ System Architecture

Rust Logic Graph architecture diagram


πŸ”₯ GRL Example

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 β†’


πŸ“Š Performance

GRL Parsing Benchmark (v1.18.0-alpha)

Benchmark v1.18.0-alpha v1.3.0 Speedup
Simple Rule (1 rule) 2.95 Β΅s 298 Β΅s 101x faster
Complex Rule (1 rule) 10.27 Β΅s 305 Β΅s 30x faster
Purchasing Rules (11 rules) 71.6 Β΅s 3,500 Β΅s 49x faster
Rule Execution (11 rules) 32.66 Β΅s - -

Graph Execution Benchmark (vs dagrs)

Chain Size rust-logic-graph dagrs Speedup
5 nodes 271 Β΅s 1.7 ms 6.3x faster
10 nodes 526 Β΅s 1.8 ms 3.5x faster
20 nodes 996 Β΅s 2.1 ms 2.1x faster

Key Performance Features

  • RETE-UL Algorithm: Advanced pattern matching with unlinking
  • No-Regex Parser: v1.18.0-alpha uses hand-written parser (50-100x faster)
  • 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

# Run all tests
cargo test

# Build CLI tool (YAML-only support)
cargo build --release --bin rlg

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

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

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

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

Test Results: βœ… 74/74 tests passing
CLI Format: YAML only (.yaml or .yml files)

Learn more about CLI tools β†’


πŸ“¦ Project Status

Version: 0.11.0 (Latest) Status: Production-ready with YAML-driven multi-database orchestration

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)
  • βœ… Distributed Context Sharing - MessagePack serialization, shared context, versioning and stores (InMemory/Redis) (v0.11.0)
  • πŸ›‘οΈ βœ… Fault Tolerance - Circuit breakers, health monitoring, failover, graceful degradation (v0.11.0)
  • βœ… Stream operators (map, filter, fold)
  • βœ… Comprehensive documentation

Roadmap

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

See 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

Core 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

Advanced Control Flow Examples (v0.9.0) πŸ†•

Example Description Features Demonstrated
conditional_flow.rs If/else routing based on conditions ConditionalNode, branch selection
loop_flow.rs Foreach and while loop patterns LoopNode, iteration over arrays
retry_flow.rs Exponential backoff retry logic RetryNode, configurable attempts
error_handling_flow.rs Try/catch/finally patterns TryCatchNode, error recovery
circuit_breaker_flow.rs Circuit breaker fault tolerance CircuitBreakerNode, failure thresholds
subgraph_flow.rs Nested graph execution SubgraphNode, input/output mapping

Multi-Database Orchestration (v0.10.0) πŸ†•

Example Description Features Demonstrated
real_multi_db_orchestration.rs Query multiple databases in parallel with real data ParallelDBExecutor, QueryCorrelator, DistributedTransaction

Demo 1: Parallel Queries - Execute queries across 4 databases concurrently
Demo 2: Query Correlation - JOIN results from different databases (Inner/Left/Right/Full)
Demo 3: Distributed Transactions - Two-Phase Commit (2PC) for atomic operations

use rust_logic_graph::multi_db::{ParallelDBExecutor, QueryCorrelator, JoinStrategy};

// Execute queries in parallel across multiple databases
let mut executor = ParallelDBExecutor::new();
executor
    .add_query("oms_db", "get_user", || async { /* query */ })
    .add_query("orders_db", "get_orders", || async { /* query */ });

let results = executor.execute_all().await?;

// Correlate results with SQL-like JOINs
let correlator = QueryCorrelator::new();
let joined = correlator.join(
    &users_data, 
    &orders_data,
    "user_id", 
    "user_id",
    JoinStrategy::Inner
)?;

Run examples:

# Conditional routing
cargo run --example conditional_flow

# Loop over products
cargo run --example loop_flow

# Retry with backoff
cargo run --example retry_flow

# Error handling
cargo run --example error_handling_flow

# Circuit breaker
cargo run --example circuit_breaker_flow

# Nested subgraphs
cargo run --example subgraph_flow

# Rich error messages (v0.10.0) πŸ†•
cargo run --example error_messages_demo

# Multi-database orchestration (v0.10.0) πŸ†•
cargo run --example multi_db_orchestration

Error Handling (v0.10.0) πŸ†•

Production-grade error messages with unique codes, actionable suggestions, and full context:

use rust_logic_graph::error::{RustLogicGraphError, ErrorContext};

// Rich error with context
let err = RustLogicGraphError::database_connection_error(
    "Failed to connect to PostgreSQL"
).with_context(
    ErrorContext::new()
        .with_node("fetch_orders")
        .with_graph("order_processing")
        .add_metadata("database", "orders_db")
);

// Output:
// [E002] Failed to connect to PostgreSQL
//   Graph: order_processing
//   Node: fetch_orders
//   database: orders_db
//
// πŸ’‘ Suggestion: Verify database connection string, credentials, 
//                and network connectivity.
// πŸ“– Documentation: https://docs.rust-logic-graph.dev/errors/E002

// Automatic retry strategy
if err.is_retryable() {
    retry_with_backoff(operation).await?;
}

12 Error Types: Node execution (E001), Database (E002), Rules (E003), Config (E004), Timeout (E005), Validation (E006), Serialization (E007), AI (E008), Cache (E009), Context (E010), Distributed (E011), Transaction (E012)

See docs/ERRORS.md for complete error reference

CLI Tool Examples (v0.5.0)

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

See CLI_TOOL.md for usage examples


🌟 What Makes Rust Logic Graph Unique?

🧠 Reasoning-First Architecture

Traditional workflow engines execute tasks. Rust Logic Graph reasons through decisions:

  • Business Rule Engine - GRL integration for complex decision logic
  • Context-Aware Execution - Decisions based on accumulated knowledge
  • Multi-Step Reasoning - Chain decisions across multiple nodes
  • Explainable Decisions - Trace how conclusions were reached

🌐 Built for Distributed Systems

Not a monolithic workflow runner - designed for microservices from day one:

  • Multi-Database Orchestration - Query PostgreSQL, MySQL, MongoDB, Redis in one flow
  • Service Coordination - Orchestrate gRPC, REST, and internal services
  • Fault Tolerance - Circuit breakers, retries, saga patterns
  • Distributed Context - Share state across services seamlessly

πŸ€– AI-Native Orchestration

LLMs are first-class citizens, not afterthoughts:

  • Multi-Model Workflows - Combine OpenAI, Claude, Ollama in one reasoning chain
  • RAG Pipeline Ready - Vector DB integration, embedding generation
  • Agent Coordination - Build multi-agent systems with shared context
  • Tool Calling Framework - LLMs can invoke graph nodes as tools

⚑ Performance Without Compromise

Embedded library architecture means zero network overhead:

  • Sub-Millisecond Latency - Direct function calls, not HTTP
  • Memory Efficient - Context pooling, zero-copy where possible
  • Parallel by Default - Automatic detection of independent operations
  • Async Everything - Built on Tokio for maximum concurrency

πŸ”§ Developer Experience

Designed for developers who write code, not click buttons:

  • Type-Safe - Rust's type system catches errors at compile time
  • YAML + Code - Declarative when possible, programmatic when needed
  • Embeddable - Library, not service - runs in your process
  • Testable - Unit test your workflows like any other code

πŸ“„ License

MIT License - see LICENSE for details.


πŸ”— Links


πŸ‘₯ Authors

James Vu - Initial work


πŸ™ Acknowledgments

Built with:


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

Documentation β€’ Examples β€’ Use Cases β€’ YAML Config Guide

Commit count: 0

cargo fmt