ipfrs-tensorlogic 0.1.0

Zero-copy tensor operations and logic programming for content-addressed storage
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
//! Remote Knowledge Retrieval and Distributed Reasoning
//!
//! This module provides protocols and interfaces for distributed reasoning
//! across a network of IPFS nodes. It defines the abstractions needed for:
//!
//! - Remote predicate lookup
//! - Fact discovery from network peers
//! - Incremental fact loading
//! - Distributed goal resolution
//! - Proof assembly from distributed fragments
//!
//! # Architecture
//!
//! The remote reasoning system is designed to work with ipfrs-network once
//! integrated. The traits defined here provide the interface that network
//! implementations will satisfy.
//!
//! ## Example
//!
//! ```ignore
//! use ipfrs_tensorlogic::{RemoteKnowledgeProvider, QueryRequest};
//!
//! // Once ipfrs-network is integrated:
//! let provider = NetworkKnowledgeProvider::new(network_client);
//! let results = provider.query_predicate("parent", vec!["Alice"]).await?;
//! ```

use crate::ir::{KnowledgeBase, Predicate, Rule, Term};
use crate::proof_storage::{ProofFragment, ProofFragmentRef};
use crate::reasoning::{Proof, Substitution};
use async_trait::async_trait;
use ipfrs_core::Cid;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use thiserror::Error;

/// Errors that can occur during remote reasoning
#[derive(Debug, Error)]
pub enum RemoteReasoningError {
    #[error("Network error: {0}")]
    NetworkError(String),

    #[error("Timeout waiting for remote response")]
    Timeout,

    #[error("Invalid response from peer: {0}")]
    InvalidResponse(String),

    #[error("Peer not found: {0}")]
    PeerNotFound(String),

    #[error("No peers available for query")]
    NoPeersAvailable,

    #[error("Serialization error: {0}")]
    SerializationError(String),

    #[error("Remote query failed: {0}")]
    QueryFailed(String),
}

/// Query request for remote predicate lookup
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryRequest {
    /// Predicate name to query
    pub predicate_name: String,

    /// Ground arguments (constants only)
    pub ground_args: Vec<String>,

    /// Maximum number of results to return
    pub max_results: usize,

    /// Query depth limit
    pub max_depth: usize,

    /// Request ID for tracking
    pub request_id: String,
}

/// Query response containing facts from remote peer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryResponse {
    /// Request ID this response is for
    pub request_id: String,

    /// Predicates matching the query
    pub predicates: Vec<Predicate>,

    /// Rules matching the query
    pub rules: Vec<Rule>,

    /// Proof fragments (if proofs requested)
    pub proof_fragments: Vec<ProofFragmentRef>,

    /// Peer ID that responded
    pub peer_id: String,

    /// Whether more results are available
    pub has_more: bool,

    /// Continuation token for pagination
    pub continuation_token: Option<String>,
}

/// Fact discovery request for network-wide search
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FactDiscoveryRequest {
    /// Predicate name to discover
    pub predicate_name: String,

    /// Optional argument patterns (None = wildcard)
    pub arg_patterns: Vec<Option<String>>,

    /// Maximum hops for multi-hop search
    pub max_hops: usize,

    /// TTL for the request
    pub ttl: u32,

    /// Exclude peers already queried
    pub exclude_peers: HashSet<String>,
}

/// Fact discovery response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FactDiscoveryResponse {
    /// Discovered facts
    pub facts: Vec<Predicate>,

    /// Peer ID that provided each fact
    pub sources: HashMap<usize, String>, // fact index -> peer ID

    /// Number of peers queried
    pub peers_queried: usize,

    /// Hops taken to find facts
    pub hops: HashMap<usize, usize>, // fact index -> hops
}

/// Incremental loading request for streaming facts
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IncrementalLoadRequest {
    /// Predicate name to load
    pub predicate_name: String,

    /// Batch size for incremental loading
    pub batch_size: usize,

    /// Offset for pagination
    pub offset: usize,

    /// Filter criteria (optional)
    pub filter: Option<HashMap<String, String>>,
}

/// Incremental loading response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IncrementalLoadResponse {
    /// Batch of predicates
    pub batch: Vec<Predicate>,

    /// Total count available
    pub total_count: usize,

    /// Next offset for continuation
    pub next_offset: Option<usize>,

    /// Whether this is the last batch
    pub is_last: bool,
}

/// Goal resolution request for distributed solving
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoalResolutionRequest {
    /// Goal to solve
    pub goal: Predicate,

    /// Current substitution
    pub substitution: HashMap<String, Term>,

    /// Depth in the proof tree
    pub depth: usize,

    /// Requesting peer ID
    pub requester: String,

    /// Request ID for tracking
    pub request_id: String,
}

/// Goal resolution response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoalResolutionResponse {
    /// Request ID this response is for
    pub request_id: String,

    /// Whether the goal was solved
    pub solved: bool,

    /// Substitutions that solve the goal
    pub solutions: Vec<HashMap<String, Term>>,

    /// Proof (if requested)
    pub proof: Option<Proof>,

    /// Proof fragments for assembly
    pub proof_fragments: Vec<ProofFragmentRef>,
}

/// Trait for remote knowledge retrieval
#[async_trait]
pub trait RemoteKnowledgeProvider: Send + Sync {
    /// Query a predicate from remote peers
    async fn query_predicate(
        &self,
        request: QueryRequest,
    ) -> Result<QueryResponse, RemoteReasoningError>;

    /// Discover facts across the network
    async fn discover_facts(
        &self,
        request: FactDiscoveryRequest,
    ) -> Result<FactDiscoveryResponse, RemoteReasoningError>;

    /// Load facts incrementally
    async fn load_incremental(
        &self,
        request: IncrementalLoadRequest,
    ) -> Result<IncrementalLoadResponse, RemoteReasoningError>;

    /// Resolve a goal using remote peers
    async fn resolve_goal(
        &self,
        request: GoalResolutionRequest,
    ) -> Result<GoalResolutionResponse, RemoteReasoningError>;

    /// Get available peers for querying
    async fn get_available_peers(&self) -> Result<Vec<String>, RemoteReasoningError>;
}

/// Distributed goal resolver
pub struct DistributedGoalResolver {
    /// Local knowledge base
    local_kb: Arc<KnowledgeBase>,

    /// Remote knowledge provider
    remote_provider: Option<Arc<dyn RemoteKnowledgeProvider>>,

    /// Maximum depth for distributed resolution
    max_depth: usize,

    /// Timeout for remote queries (milliseconds)
    timeout_ms: u64,

    /// Cache for remote facts
    remote_fact_cache: HashMap<String, Vec<Predicate>>,
}

impl DistributedGoalResolver {
    /// Create a new distributed goal resolver
    pub fn new(local_kb: Arc<KnowledgeBase>) -> Self {
        Self {
            local_kb,
            remote_provider: None,
            max_depth: 10,
            timeout_ms: 5000,
            remote_fact_cache: HashMap::new(),
        }
    }

    /// Set the remote knowledge provider
    pub fn with_provider(mut self, provider: Arc<dyn RemoteKnowledgeProvider>) -> Self {
        self.remote_provider = Some(provider);
        self
    }

    /// Set maximum depth
    pub fn with_max_depth(mut self, max_depth: usize) -> Self {
        self.max_depth = max_depth;
        self
    }

    /// Set timeout in milliseconds
    pub fn with_timeout(mut self, timeout_ms: u64) -> Self {
        self.timeout_ms = timeout_ms;
        self
    }

    /// Resolve a goal using both local and remote knowledge
    pub async fn resolve(
        &mut self,
        goal: &Predicate,
        substitution: &Substitution,
    ) -> Result<Vec<Substitution>, RemoteReasoningError> {
        // First, try local resolution
        let local_solutions = self.resolve_local(goal, substitution);

        if !local_solutions.is_empty() {
            return Ok(local_solutions);
        }

        // If no local solutions and remote provider available, try remote
        if let Some(provider) = self.remote_provider.clone() {
            let remote_solutions = self.resolve_remote(goal, substitution, &provider).await?;
            Ok(remote_solutions)
        } else {
            Ok(Vec::new())
        }
    }

    /// Resolve a goal locally
    fn resolve_local(&self, goal: &Predicate, _substitution: &Substitution) -> Vec<Substitution> {
        // Check if goal matches any facts in local KB
        let facts = self.local_kb.get_predicates(&goal.name);

        let mut solutions = Vec::new();
        for fact in facts {
            if let Some(subst) =
                crate::reasoning::unify_predicates(goal, fact, &Substitution::new())
            {
                solutions.push(subst);
            }
        }

        solutions
    }

    /// Resolve a goal remotely
    async fn resolve_remote(
        &mut self,
        goal: &Predicate,
        substitution: &Substitution,
        provider: &Arc<dyn RemoteKnowledgeProvider>,
    ) -> Result<Vec<Substitution>, RemoteReasoningError> {
        // Create goal resolution request
        let request = GoalResolutionRequest {
            goal: goal.clone(),
            substitution: substitution.clone(),
            depth: 0,
            requester: "local".to_string(),
            request_id: uuid::Uuid::new_v4().to_string(),
        };

        // Query remote peers
        let response = provider.resolve_goal(request).await?;

        // Convert solutions
        Ok(response.solutions)
    }

    /// Prefetch facts for a predicate from remote peers
    pub async fn prefetch_facts(
        &mut self,
        predicate_name: &str,
    ) -> Result<usize, RemoteReasoningError> {
        let Some(provider) = &self.remote_provider else {
            return Ok(0);
        };

        // Create discovery request
        let request = FactDiscoveryRequest {
            predicate_name: predicate_name.to_string(),
            arg_patterns: Vec::new(),
            max_hops: 3,
            ttl: 30,
            exclude_peers: HashSet::new(),
        };

        // Discover facts
        let response = provider.discover_facts(request).await?;

        // Cache the facts
        let count = response.facts.len();
        self.remote_fact_cache
            .insert(predicate_name.to_string(), response.facts);

        Ok(count)
    }

    /// Get cached remote facts
    pub fn get_cached_facts(&self, predicate_name: &str) -> Option<&[Predicate]> {
        self.remote_fact_cache
            .get(predicate_name)
            .map(|v| v.as_slice())
    }

    /// Clear the remote fact cache
    pub fn clear_cache(&mut self) {
        self.remote_fact_cache.clear();
    }
}

/// Proof assembler for distributed proofs
pub struct DistributedProofAssembler {
    /// Remote knowledge provider
    remote_provider: Arc<dyn RemoteKnowledgeProvider>,

    /// Cache of proof fragments
    fragment_cache: HashMap<Cid, ProofFragment>,

    /// Maximum proof depth
    #[allow(dead_code)]
    max_depth: usize,
}

impl DistributedProofAssembler {
    /// Create a new distributed proof assembler
    pub fn new(remote_provider: Arc<dyn RemoteKnowledgeProvider>) -> Self {
        Self {
            remote_provider,
            fragment_cache: HashMap::new(),
            max_depth: 100,
        }
    }

    /// Assemble a proof from distributed fragments
    pub async fn assemble_proof(
        &mut self,
        goal: &Predicate,
    ) -> Result<Option<Proof>, RemoteReasoningError> {
        // Request goal resolution with proof
        let request = GoalResolutionRequest {
            goal: goal.clone(),
            substitution: HashMap::new(),
            depth: 0,
            requester: "local".to_string(),
            request_id: uuid::Uuid::new_v4().to_string(),
        };

        let response = self.remote_provider.resolve_goal(request).await?;

        if response.solved {
            Ok(response.proof)
        } else {
            Ok(None)
        }
    }

    /// Fetch a proof fragment from the network
    pub async fn fetch_fragment(
        &mut self,
        cid: Cid,
    ) -> Result<ProofFragment, RemoteReasoningError> {
        // Check cache first
        if let Some(fragment) = self.fragment_cache.get(&cid) {
            return Ok(fragment.clone());
        }

        // In a real implementation, this would fetch from IPFS
        // For now, return an error
        Err(RemoteReasoningError::NetworkError(
            "Fragment fetch not yet implemented".to_string(),
        ))
    }
}

/// Mock implementation for testing (will be replaced with network implementation)
pub struct MockRemoteKnowledgeProvider {
    /// Mock knowledge base
    mock_kb: Arc<KnowledgeBase>,
}

impl MockRemoteKnowledgeProvider {
    /// Create a new mock provider
    pub fn new(mock_kb: Arc<KnowledgeBase>) -> Self {
        Self { mock_kb }
    }
}

#[async_trait]
impl RemoteKnowledgeProvider for MockRemoteKnowledgeProvider {
    async fn query_predicate(
        &self,
        request: QueryRequest,
    ) -> Result<QueryResponse, RemoteReasoningError> {
        let predicates = self
            .mock_kb
            .get_predicates(&request.predicate_name)
            .into_iter()
            .take(request.max_results)
            .cloned()
            .collect();

        let rules = self
            .mock_kb
            .get_rules(&request.predicate_name)
            .into_iter()
            .take(request.max_results)
            .cloned()
            .collect();

        Ok(QueryResponse {
            request_id: request.request_id,
            predicates,
            rules,
            proof_fragments: Vec::new(),
            peer_id: "mock_peer".to_string(),
            has_more: false,
            continuation_token: None,
        })
    }

    async fn discover_facts(
        &self,
        request: FactDiscoveryRequest,
    ) -> Result<FactDiscoveryResponse, RemoteReasoningError> {
        let facts: Vec<Predicate> = self
            .mock_kb
            .get_predicates(&request.predicate_name)
            .into_iter()
            .cloned()
            .collect();

        let sources: HashMap<usize, String> = (0..facts.len())
            .map(|i| (i, "mock_peer".to_string()))
            .collect();

        let hops: HashMap<usize, usize> = (0..facts.len()).map(|i| (i, 0)).collect();

        Ok(FactDiscoveryResponse {
            facts,
            sources,
            peers_queried: 1,
            hops,
        })
    }

    async fn load_incremental(
        &self,
        request: IncrementalLoadRequest,
    ) -> Result<IncrementalLoadResponse, RemoteReasoningError> {
        let all_facts: Vec<Predicate> = self
            .mock_kb
            .get_predicates(&request.predicate_name)
            .into_iter()
            .cloned()
            .collect();

        let total_count = all_facts.len();
        let start = request.offset;
        let end = (start + request.batch_size).min(total_count);

        let batch = all_facts[start..end].to_vec();
        let is_last = end >= total_count;
        let next_offset = if is_last { None } else { Some(end) };

        Ok(IncrementalLoadResponse {
            batch,
            total_count,
            next_offset,
            is_last,
        })
    }

    async fn resolve_goal(
        &self,
        request: GoalResolutionRequest,
    ) -> Result<GoalResolutionResponse, RemoteReasoningError> {
        // Simple fact matching
        let facts = self.mock_kb.get_predicates(&request.goal.name);
        let mut solutions = Vec::new();

        for fact in facts {
            if let Some(subst) =
                crate::reasoning::unify_predicates(&request.goal, fact, &Substitution::new())
            {
                solutions.push(subst);
            }
        }

        let solved = !solutions.is_empty();
        let proof = if solved {
            Some(Proof::fact(request.goal.clone()))
        } else {
            None
        };

        Ok(GoalResolutionResponse {
            request_id: request.request_id,
            solved,
            solutions,
            proof,
            proof_fragments: Vec::new(),
        })
    }

    async fn get_available_peers(&self) -> Result<Vec<String>, RemoteReasoningError> {
        Ok(vec!["mock_peer".to_string()])
    }
}

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

    #[tokio::test]
    async fn test_query_request_serialization() {
        let request = QueryRequest {
            predicate_name: "parent".to_string(),
            ground_args: vec!["Alice".to_string()],
            max_results: 10,
            max_depth: 5,
            request_id: "test_123".to_string(),
        };

        let json = serde_json::to_string(&request).unwrap();
        let decoded: QueryRequest = serde_json::from_str(&json).unwrap();

        assert_eq!(request.predicate_name, decoded.predicate_name);
        assert_eq!(request.ground_args, decoded.ground_args);
    }

    #[tokio::test]
    async fn test_mock_provider_query() {
        let mut kb = KnowledgeBase::new();
        kb.add_fact(Predicate::new(
            "parent".to_string(),
            vec![
                Term::Const(Constant::String("Alice".to_string())),
                Term::Const(Constant::String("Bob".to_string())),
            ],
        ));

        let provider = MockRemoteKnowledgeProvider::new(Arc::new(kb));

        let request = QueryRequest {
            predicate_name: "parent".to_string(),
            ground_args: vec![],
            max_results: 10,
            max_depth: 5,
            request_id: "test_123".to_string(),
        };

        let response = provider.query_predicate(request).await.unwrap();
        assert_eq!(response.predicates.len(), 1);
        assert_eq!(response.predicates[0].name, "parent");
    }

    #[tokio::test]
    async fn test_distributed_resolver() {
        let mut local_kb = KnowledgeBase::new();
        local_kb.add_fact(Predicate::new(
            "parent".to_string(),
            vec![
                Term::Const(Constant::String("Alice".to_string())),
                Term::Const(Constant::String("Bob".to_string())),
            ],
        ));

        let mut resolver = DistributedGoalResolver::new(Arc::new(local_kb));

        let goal = Predicate::new(
            "parent".to_string(),
            vec![
                Term::Const(Constant::String("Alice".to_string())),
                Term::Var("X".to_string()),
            ],
        );

        let solutions = resolver.resolve(&goal, &Substitution::new()).await.unwrap();
        assert!(!solutions.is_empty());
    }

    #[tokio::test]
    async fn test_fact_discovery() {
        let mut kb = KnowledgeBase::new();
        kb.add_fact(Predicate::new(
            "parent".to_string(),
            vec![
                Term::Const(Constant::String("Alice".to_string())),
                Term::Const(Constant::String("Bob".to_string())),
            ],
        ));
        kb.add_fact(Predicate::new(
            "parent".to_string(),
            vec![
                Term::Const(Constant::String("Bob".to_string())),
                Term::Const(Constant::String("Charlie".to_string())),
            ],
        ));

        let provider = MockRemoteKnowledgeProvider::new(Arc::new(kb));

        let request = FactDiscoveryRequest {
            predicate_name: "parent".to_string(),
            arg_patterns: vec![],
            max_hops: 3,
            ttl: 30,
            exclude_peers: HashSet::new(),
        };

        let response = provider.discover_facts(request).await.unwrap();
        assert_eq!(response.facts.len(), 2);
        assert_eq!(response.peers_queried, 1);
    }

    #[tokio::test]
    async fn test_incremental_loading() {
        let mut kb = KnowledgeBase::new();
        for i in 0..10 {
            kb.add_fact(Predicate::new(
                "number".to_string(),
                vec![Term::Const(Constant::Int(i))],
            ));
        }

        let provider = MockRemoteKnowledgeProvider::new(Arc::new(kb));

        // Load first batch
        let request = IncrementalLoadRequest {
            predicate_name: "number".to_string(),
            batch_size: 3,
            offset: 0,
            filter: None,
        };

        let response = provider.load_incremental(request).await.unwrap();
        assert_eq!(response.batch.len(), 3);
        assert_eq!(response.total_count, 10);
        assert!(!response.is_last);
        assert_eq!(response.next_offset, Some(3));
    }

    #[tokio::test]
    async fn test_goal_resolution() {
        let mut kb = KnowledgeBase::new();
        kb.add_fact(Predicate::new(
            "parent".to_string(),
            vec![
                Term::Const(Constant::String("Alice".to_string())),
                Term::Const(Constant::String("Bob".to_string())),
            ],
        ));

        let provider = MockRemoteKnowledgeProvider::new(Arc::new(kb));

        let goal = Predicate::new(
            "parent".to_string(),
            vec![
                Term::Const(Constant::String("Alice".to_string())),
                Term::Var("X".to_string()),
            ],
        );

        let request = GoalResolutionRequest {
            goal,
            substitution: HashMap::new(),
            depth: 0,
            requester: "test".to_string(),
            request_id: "test_123".to_string(),
        };

        let response = provider.resolve_goal(request).await.unwrap();
        assert!(response.solved);
        assert!(!response.solutions.is_empty());
        assert!(response.proof.is_some());
    }
}