stigmerge_peer 0.6.2

stigmerge p2p protocol and agent components
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
# Piece Lease Manager Design

## Overview

The Piece Lease Manager is a centralized coordination system for managing piece-level leases in the stigmerge fetcher. It replaces the previous block-based channel system (`pending_blocks_tx/pending_blocks_rx`) with a more sophisticated approach that provides exclusive access to pieces, peer ranking, and better failure handling.

## Problem Statement

The current fetcher architecture has several limitations:

1. **No piece-level coordination**: Individual blocks are distributed without considering piece boundaries, leading to potential race conditions
2. **No lease management**: Multiple fetch pools could work on the same piece simultaneously
3. **No peer ranking**: All peers are treated equally regardless of performance
4. **Inefficient retry logic**: Failed pieces are re-queued at block level, causing potential thrashing
5. **Lack of exclusivity**: No mechanism to prevent conflicting writes to the same piece

## Solution Architecture

### Core Components

#### PieceLeaseManager
The central coordinator that manages piece leases and peer rankings.

```rust
pub struct PieceLeaseManager {
    inner: Arc<Mutex<PieceLeaseManagerInner>>,
}

struct PieceLeaseManagerInner {
    /// Configuration for the lease manager
    config: LeaseManagerConfig,
    
    /// Pieces that still need to be downloaded
    wanted_pieces: PieceMap,
    
    /// Currently active leases by (file_index, piece_index)
    active_leases: HashMap<(usize, usize), PieceLease>,
    
    /// Peer performance rankings
    peer_rankings: HashMap<TypedRecordKey, PeerRanking>,
    
    /// Counter for generating unique request IDs
    request_id_counter: u64,
}
```

#### PieceLease
Represents exclusive rights to fetch blocks for a specific piece.

```rust
pub struct PieceLease {
    pub piece_index: usize,
    pub file_index: usize,
    pub lease_expiry: Instant,
    pub peer_key: TypedRecordKey,
    pub granted_at: Instant,
}

impl PieceLease {
    pub fn key(&self) -> (usize, usize) {
        (self.file_index, self.piece_index)
    }
    
    pub fn is_expired(&self) -> bool {
        Instant::now() > self.lease_expiry
    }
    
    pub fn time_remaining(&self) -> Duration {
        self.lease_expiry.saturating_duration_since(Instant::now())
    }
}
```

#### PeerRanking
Tracks peer performance and assigns priority scores.

```rust
pub struct PeerRanking {
    pub key: TypedRecordKey,
    pub successful_pieces: u32,
    pub failed_pieces: u32,
    pub current_leases: u32,
    pub score: f64,
    pub last_updated: Instant,
}

impl PeerRanking {
    pub fn new(key: TypedRecordKey) -> Self {
        Self {
            key,
            successful_pieces: 0,
            failed_pieces: 0,
            current_leases: 0,
            score: 1.0, // Start with neutral score
            last_updated: Instant::now(),
        }
    }
    
    pub fn record_success(&mut self, config: &LeaseManagerConfig) {
        self.successful_pieces += 1;
        self.update_score(config);
    }
    
    pub fn record_failure(&mut self, config: &LeaseManagerConfig) {
        self.failed_pieces += 1;
        self.update_score(config);
    }
    
    fn update_score(&mut self, config: &LeaseManagerConfig) {
        let success_rate = if self.successful_pieces + self.failed_pieces > 0 {
            self.successful_pieces as f64 / (self.successful_pieces + self.failed_pieces) as f64
        } else {
            1.0
        };
        
        // Apply exponential decay to old scores
        let time_factor = config.peer_ranking_decay.powf(
            self.last_updated.elapsed().as_secs_f64() / 3600.0 // hours
        );
        
        self.score = self.score * time_factor 
                   + (success_rate * config.success_bonus 
                      - (1.0 - success_rate) * config.failure_penalty);
        
        // Clamp score to reasonable bounds
        self.score = self.score.clamp(0.1, 10.0);
        self.last_updated = Instant::now();
    }
}
```

### Communication Protocols

#### Lease Request
```rust
pub struct LeaseRequest {
    pub peer_key: TypedRecordKey,
    pub have_map: PieceMap,
    pub max_leases: usize,
    pub requested_at: Instant,
}

impl LeaseRequest {
    pub fn can_fulfill(&self, wanted_pieces: &PieceMap) -> PieceMap {
        wanted_pieces.intersection(self.have_map.clone())
    }
}
```

#### Lease Response
```rust
pub struct LeaseResponse {
    pub request_id: u64,
    pub peer_key: TypedRecordKey,
    pub granted_leases: Vec<PieceLease>,
    pub rejected_reason: Option<RejectedReason>,
}

pub enum RejectedReason {
    NoAvailablePieces,
    PeerAtCapacity,
    PeerRankingTooLow,
    InvalidRequest,
}
```

#### Piece Completion
```rust
pub struct PieceCompletion {
    pub piece_index: usize,
    pub file_index: usize,
    pub peer_key: TypedRecordKey,
    pub result: CompletionResult,
    pub completed_at: Instant,
}

pub enum CompletionResult {
    Success,
    Failure(FailureReason),
    Expired,
}

pub enum FailureReason {
    VerificationFailed,
    NetworkError,
    Timeout,
    InvalidData,
}
```

### Configuration

```rust
pub struct LeaseManagerConfig {
    /// Duration for which a lease is valid
    pub lease_duration: Duration,
    
    /// Maximum number of concurrent leases per peer
    pub max_leases_per_peer: usize,
    
    /// Exponential decay factor for peer rankings (per hour)
    pub peer_ranking_decay: f64,
    
    /// Bonus applied to ranking for successful pieces
    pub success_bonus: f64,
    
    /// Penalty applied to ranking for failed pieces
    pub failure_penalty: f64,
    
    /// Interval for cleanup of expired leases
    pub cleanup_interval: Duration,
    
    /// Minimum peer score to be considered for leases
    pub min_peer_score: f64,
}

impl Default for LeaseManagerConfig {
    fn default() -> Self {
        Self {
            lease_duration: Duration::from_secs(300), // 5 minutes
            max_leases_per_peer: 4,
            peer_ranking_decay: 0.95,
            success_bonus: 0.5,
            failure_penalty: 1.0,
            cleanup_interval: Duration::from_secs(60),
            min_peer_score: 0.2,
        }
    }
}
```

## Lease Assignment Algorithm

### 1. Request Processing
1. Validate lease request (peer not at capacity, minimum score met)
2. Calculate available pieces by intersecting peer's have_map with wanted pieces
3. If no available pieces, return rejection

### 2. Peer Selection
1. Sort available peers by ranking score (descending)
2. For highest-ranking peers, allocate pieces up to their limits
3. Consider piece distribution to avoid concentration

### 3. Piece Selection Strategy
```rust
fn select_pieces_for_peer(
    available_pieces: &PieceMap,
    peer_ranking: &PeerRanking,
    max_leases: usize,
    active_leases: &HashMap<(usize, usize), PieceLease>
) -> Vec<usize> {
    // Strategy 1: Prefer pieces that no one else is working on
    // Strategy 2: Consider peer's historical success with specific piece ranges
    // Strategy 3: Round-robin to ensure fair distribution
    
    available_pieces
        .iter()
        .filter(|&piece_index| {
            !active_leases.contains_key(&(0, piece_index)) // TODO: support file_index
        })
        .take(max_leases)
        .collect()
}
```

### 4. Lease Creation
1. Create `PieceLease` objects with expiry times
2. Update peer's current lease count
3. Store in active leases map
4. Return lease response

## Lifecycle Management

### Lease Expiry
- Expired leases are cleaned up inline when new lease requests are processed
- Expired leases are removed and pieces returned to wanted set
- Peer rankings are penalized for expired leases
- No background task needed - cleanup happens on-demand

### Piece Completion
- Successful completion: piece removed from wanted set, peer ranking increased
- Failed completion: piece returned to wanted set, peer ranking decreased
- Invalid completion (no lease): error returned

### Inline Cleanup
```rust
impl PieceLeaseManagerInner {
    /// Clean up expired leases and return them to the wanted set
    fn cleanup_expired_leases(&mut self) {
        let now = Instant::now();
        let expired_leases: Vec<_> = self.active_leases
            .iter()
            .filter(|(_, lease)| lease.lease_expiry <= now)
            .map(|(key, lease)| (*key, lease.clone()))
            .collect();
        
        if expired_leases.is_empty() {
            return;
        }
        
        info!("Cleaning up {} expired leases", expired_leases.len());
        
        for (piece_key, lease) in expired_leases {
            // Remove expired lease
            self.active_leases.remove(&piece_key);
            
            // Return piece to wanted set
            self.wanted_pieces.set(lease.piece_index as u32);
            
            // Penalize peer
            if let Some(ranking) = self.peer_rankings.get_mut(&lease.peer_key) {
                ranking.current_leases = ranking.current_leases.saturating_sub(1);
                ranking.record_expiry(&self.config);
                debug!("Penalized peer {:?} for expired lease, new score: {}", 
                       lease.peer_key, ranking.score);
            }
        }
    }
}
```

## Integration Points

### With Fetcher
```rust
// In Fetcher::new()
let lease_manager = PieceLeaseManager::new(LeaseManagerConfig::default());

// Replace pending_blocks channel
// OLD:
// let (pending_blocks_tx, pending_blocks_rx) = flume::unbounded();

// NEW:
let lease_manager = Arc::new(lease_manager);
```

### With FetchPool
```rust
impl FetchPool {
    async fn request_leases(&self) -> Result<Vec<PieceLease>> {
        let request = LeaseRequest {
            peer_key: self.remote_share.key,
            have_map: self.remote_share.have_map.clone(),
            max_leases: Self::MAX_LEASES,
            requested_at: Instant::now(),
        };
        
        let response = self.lease_manager.request_lease(request).await?;
        
        match response.granted_leases.len() {
            0 => warn!("No leases granted: {:?}", response.rejected_reason),
            n => info!("Granted {} leases to peer {:?}", n, self.remote_share.key),
        }
        
        Ok(response.granted_leases)
    }
}
```

### With PieceVerifier
```rust
// In piece verification completion handler
async fn handle_piece_verification(&self, status: PieceStatus) -> Result<()> {
    match status {
        PieceStatus::ValidPiece { file_index, piece_index, .. } => {
            let completion = PieceCompletion {
                piece_index,
                file_index,
                peer_key: self.current_lease_peer_key, // Track which peer had the lease
                result: CompletionResult::Success,
                completed_at: Instant::now(),
            };
            
            self.lease_manager.complete_piece(completion).await?;
        }
        PieceStatus::InvalidPiece { file_index, piece_index } => {
            let completion = PieceCompletion {
                piece_index,
                file_index,
                peer_key: self.current_lease_peer_key,
                result: CompletionResult::Failure(FailureReason::VerificationFailed),
                completed_at: Instant::now(),
            };
            
            self.lease_manager.complete_piece(completion).await?;
        }
        PieceStatus::IncompletePiece { .. } => {
            // Lease remains active, continue fetching
        }
    }
    
    Ok(())
}
```

## Performance Considerations

### Computational Complexity
- **Lease Assignment**: O(P + L) where P = available pieces, L = current leases
- **Peer Ranking Updates**: O(1) per update
- **Cleanup Operations**: O(L) per cleanup interval
- **Memory Usage**: O(P + N) where N = number of peers

### Optimizations
1. **Batch Operations**: Process multiple lease requests in batches
2. **Lazy Ranking Updates**: Only recalculate scores when needed
3. **Efficient Bitmap Operations**: Use PieceMap's optimized intersection
4. **Peer Caching**: Cache frequently accessed peer rankings

### Scalability
- Supports thousands of concurrent pieces
- Handles hundreds of simultaneous peers
- Efficient memory usage through bitmap operations
- Asynchronous processing prevents blocking

## Testing Strategy

### Unit Tests
- Lease assignment and expiry logic
- Peer ranking calculations
- Piece selection algorithms
- Configuration validation

### Integration Tests
- End-to-end lease lifecycle
- Multi-peer coordination
- Failure recovery scenarios
- Performance under load

### Property-Based Tests
- Lease exclusivity invariants
- Peer ranking monotonicity
- Piece set conservation
- Configuration parameter bounds

## Migration Path

### Phase 1: Standalone Implementation
- Implement PieceLeaseManager as independent component
- Comprehensive test coverage
- Performance benchmarking

### Phase 2: Parallel Integration
- Run lease manager alongside existing block channel
- Gradual migration of FetchPool instances
- A/B testing of performance

### Phase 3: Full Replacement
- Remove pending_blocks channels entirely
- Update all fetcher components to use leases
- Performance optimization and tuning

## Benefits

### Immediate
- Eliminates race conditions for piece access
- Better peer selection based on performance
- Cleaner separation of concerns

### Long-term
- More efficient resource utilization
- Better handling of unreliable peers
- Foundation for advanced strategies (e.g., piece rarity, peer specialization)

### Operational
- Reduced network overhead through better coordination
- Improved download reliability
- Better metrics and observability

## Future Enhancements

### Advanced Peer Selection
- Piece rarity-based prioritization
- Network topology awareness
- Bandwidth capacity estimation

### Adaptive Strategies
- Dynamic lease duration based on peer performance
- Machine learning for peer reputation
- Predictive piece selection

### Monitoring & Observability
- Detailed metrics collection
- Performance dashboards
- Automated alerting for anomalous behavior