ab ovo
This commit is contained in:
753
architecture/adaptive-request-pipelining.md
Normal file
753
architecture/adaptive-request-pipelining.md
Normal file
@@ -0,0 +1,753 @@
|
||||
# Adaptive BDP-Optimized Push Pipeline
|
||||
|
||||
A next-generation request pipelining architecture for P2P file transfer that surpasses industry standards like BitTorrent, IPFS, and HTTP/2.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Problem Statement](#problem-statement)
|
||||
2. [Industry Analysis](#industry-analysis)
|
||||
3. [Proposed Architecture](#proposed-architecture)
|
||||
4. [Core Components](#core-components)
|
||||
5. [Protocol Design](#protocol-design)
|
||||
6. [Implementation Phases](#implementation-phases)
|
||||
7. [Performance Projections](#performance-projections)
|
||||
8. [Trade-offs and Mitigations](#trade-offs-and-mitigations)
|
||||
|
||||
---
|
||||
|
||||
## Problem Statement
|
||||
|
||||
### Current Bottleneck
|
||||
|
||||
With 10 peers and 1MB pieces, our benchmark achieves **~180 MB/s**. The theoretical maximum on localhost should be **400+ MB/s**. The gap is caused by:
|
||||
|
||||
```
|
||||
Request-Response Latency per Piece:
|
||||
Client → Request (0.5ms)
|
||||
Server → Process + Read (1ms)
|
||||
Server → Response (2ms network + transfer)
|
||||
Client → Verify + Write (1ms)
|
||||
─────────────────────────────
|
||||
Total: ~5ms per piece = 200 pieces/sec max = 200 MB/s ceiling
|
||||
```
|
||||
|
||||
### Root Cause
|
||||
|
||||
Traditional request-response model requires one round-trip time (RTT) per piece, creating a latency-bound (not bandwidth-bound) system.
|
||||
|
||||
---
|
||||
|
||||
## Industry Analysis
|
||||
|
||||
### Current Approaches
|
||||
|
||||
| Protocol | Mechanism | Limitations |
|
||||
|----------|-----------|-------------|
|
||||
| **BitTorrent** | Fixed request queue (5-10 per peer) | Doesn't adapt to peer capabilities; under-utilizes fast peers |
|
||||
| **IPFS Bitswap** | Wantlist broadcast | No bandwidth-aware scheduling; no push optimization |
|
||||
| **HTTP/1.1** | Pipelining (optional) | Head-of-line blocking; mostly disabled |
|
||||
| **HTTP/2** | Stream multiplexing | Still request-response; TCP HOL blocking |
|
||||
| **HTTP/3 QUIC** | UDP multiplexing | Better, but still request-driven |
|
||||
| **libp2p** | Configurable streams | No automatic optimization |
|
||||
|
||||
### Key Insight
|
||||
|
||||
All existing protocols use **static configurations** and **request-response models**. None optimize based on:
|
||||
- Measured bandwidth-delay product (BDP)
|
||||
- Dynamic network conditions
|
||||
- Push-based streaming after initial handshake
|
||||
|
||||
---
|
||||
|
||||
## Proposed Architecture
|
||||
|
||||
### Design Principles
|
||||
|
||||
1. **Measure, Don't Guess**: Use real RTT and bandwidth measurements per peer
|
||||
2. **Adaptive, Not Static**: Dynamically adjust based on conditions
|
||||
3. **Push, Don't Poll**: Eliminate per-piece round trips
|
||||
4. **Speculate Wisely**: Duplicate requests for tail latency reduction
|
||||
5. **Fail Gracefully**: AIMD-style congestion control
|
||||
|
||||
### High-Level Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Download Coordinator │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ Peer A │ │ Peer B │ │ Peer C │ ... │
|
||||
│ │ ───────── │ │ ───────── │ │ ───────── │ │
|
||||
│ │ RTT: 2ms │ │ RTT: 15ms │ │ RTT: 50ms │ │
|
||||
│ │ BW: 200MB/s │ │ BW: 80MB/s │ │ BW: 20MB/s │ │
|
||||
│ │ Pending: 1 │ │ Pending: 2 │ │ Pending: 1 │ │
|
||||
│ │ Mode: Push │ │ Mode: Push │ │ Mode: Req │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ Piece Scheduler │
|
||||
│ ┌──────────────────────────────────────────────────────────┐ │
|
||||
│ │ Priority Queue: [rare pieces] > [sequential] > [random] │ │
|
||||
│ │ Assignment: piece → best peer (BW/latency weighted) │ │
|
||||
│ └──────────────────────────────────────────────────────────┘ │
|
||||
├─────────────────────────────────────────────────────────────────┤
|
||||
│ Endgame Manager │
|
||||
│ ┌──────────────────────────────────────────────────────────┐ │
|
||||
│ │ When >95% complete: speculative requests to all peers │ │
|
||||
│ │ Duplicate cancellation on first arrival │ │
|
||||
│ └──────────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core Components
|
||||
|
||||
### 1. Per-Peer Metrics Tracker
|
||||
|
||||
```zig
|
||||
const PeerMetrics = struct {
|
||||
// Measured values
|
||||
rtt_ms: f64, // Exponential moving average
|
||||
bandwidth_mbps: f64, // Measured throughput
|
||||
loss_rate: f64, // Packet/piece loss percentage
|
||||
|
||||
// Derived values
|
||||
bdp_bytes: u64, // Bandwidth-delay product
|
||||
optimal_pending: u32, // Calculated optimal queue depth
|
||||
|
||||
// State
|
||||
current_pending: u32, // Actual pending requests
|
||||
consecutive_timeouts: u32, // For AIMD backoff
|
||||
mode: enum { request, push }, // Current transfer mode
|
||||
|
||||
// Update RTT with exponential moving average
|
||||
pub fn updateRtt(self: *PeerMetrics, sample_ms: f64) void {
|
||||
const alpha = 0.125; // EWMA smoothing factor
|
||||
self.rtt_ms = (1 - alpha) * self.rtt_ms + alpha * sample_ms;
|
||||
self.recalculateOptimalPending();
|
||||
}
|
||||
|
||||
// Calculate optimal pending based on BDP
|
||||
fn recalculateOptimalPending(self: *PeerMetrics) void {
|
||||
const bdp = (self.bandwidth_mbps * 1_000_000 / 8) * (self.rtt_ms / 1000);
|
||||
self.bdp_bytes = @intFromFloat(bdp);
|
||||
self.optimal_pending = @max(1, @intFromFloat(bdp / PIECE_SIZE));
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 2. Bandwidth-Delay Product Calculator
|
||||
|
||||
The optimal amount of data "in flight" to fully utilize a connection:
|
||||
|
||||
```
|
||||
BDP = Bandwidth × RTT
|
||||
|
||||
Example calculations:
|
||||
┌────────────────┬───────────┬────────┬─────────┬─────────────────┐
|
||||
│ Scenario │ Bandwidth │ RTT │ BDP │ Optimal Pending │
|
||||
├────────────────┼───────────┼────────┼─────────┼─────────────────┤
|
||||
│ Localhost │ 500 MB/s │ 0.5ms │ 250 KB │ 1 piece │
|
||||
│ LAN │ 100 MB/s │ 2ms │ 200 KB │ 1 piece │
|
||||
│ Regional │ 50 MB/s │ 20ms │ 1 MB │ 1 piece │
|
||||
│ Cross-country │ 30 MB/s │ 80ms │ 2.4 MB │ 3 pieces │
|
||||
│ Intercontinental│ 10 MB/s │ 200ms │ 2 MB │ 2 pieces │
|
||||
│ Satellite │ 5 MB/s │ 600ms │ 3 MB │ 3 pieces │
|
||||
└────────────────┴───────────┴────────┴─────────┴─────────────────┘
|
||||
```
|
||||
|
||||
### 3. Push Mode Protocol
|
||||
|
||||
Eliminates per-piece RTT after initial handshake:
|
||||
|
||||
```
|
||||
Traditional Request-Response:
|
||||
Client Server
|
||||
│ │
|
||||
│──── REQUEST piece 0 ───→│
|
||||
│←─── RESPONSE piece 0 ───│ (1 RTT)
|
||||
│──── REQUEST piece 1 ───→│
|
||||
│←─── RESPONSE piece 1 ───│ (1 RTT)
|
||||
│ ... │
|
||||
|
||||
Push Mode:
|
||||
Client Server
|
||||
│ │
|
||||
│──── WANTLIST [0-999] ──→│
|
||||
│←─── PUSH piece 0 ───────│
|
||||
│←─── PUSH piece 1 ───────│ (pieces stream continuously)
|
||||
│←─── PUSH piece 2 ───────│
|
||||
│←─── PUSH piece 3 ───────│
|
||||
│──── HAVE [0-3] ────────→│ (periodic acknowledgment)
|
||||
│←─── PUSH piece 4 ───────│
|
||||
│ ... │
|
||||
|
||||
RTT cost: 1 RTT total vs N RTTs for N pieces
|
||||
```
|
||||
|
||||
#### Push Mode Message Types
|
||||
|
||||
```zig
|
||||
const PushModeMessage = union(enum) {
|
||||
// Client → Server: "I need these pieces"
|
||||
wantlist: struct {
|
||||
bitfield: []const u8, // Bitmap of wanted pieces
|
||||
priority_pieces: []u32, // High-priority piece indices
|
||||
},
|
||||
|
||||
// Client → Server: "I now have these pieces" (periodic)
|
||||
have_update: struct {
|
||||
bitfield: []const u8, // Updated bitmap
|
||||
},
|
||||
|
||||
// Client → Server: "Stop sending, I'm overwhelmed"
|
||||
flow_control: struct {
|
||||
pause: bool,
|
||||
resume_after_ms: u32,
|
||||
},
|
||||
|
||||
// Server → Client: Pushed piece data
|
||||
push_piece: struct {
|
||||
piece_index: u32,
|
||||
data: []const u8,
|
||||
hash: [32]u8,
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 4. AIMD Congestion Control
|
||||
|
||||
Additive Increase, Multiplicative Decrease - same principle as TCP:
|
||||
|
||||
```zig
|
||||
const AIMDController = struct {
|
||||
pending_limit: u32,
|
||||
min_limit: u32 = 1,
|
||||
max_limit: u32 = 50,
|
||||
|
||||
// Called on successful piece receipt
|
||||
pub fn onSuccess(self: *AIMDController) void {
|
||||
// Additive increase: slowly grow
|
||||
if (self.pending_limit < self.max_limit) {
|
||||
self.pending_limit += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Called on timeout or error
|
||||
pub fn onFailure(self: *AIMDController) void {
|
||||
// Multiplicative decrease: quickly shrink
|
||||
self.pending_limit = @max(self.min_limit, self.pending_limit / 2);
|
||||
}
|
||||
|
||||
// Called on severe congestion (multiple consecutive failures)
|
||||
pub fn onSevereCongestion(self: *AIMDController) void {
|
||||
self.pending_limit = self.min_limit;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 5. Speculative Endgame Mode
|
||||
|
||||
When download is nearly complete, eliminate tail latency:
|
||||
|
||||
```zig
|
||||
const EndgameManager = struct {
|
||||
threshold_percent: u8 = 95, // Enter endgame at 95% complete
|
||||
|
||||
pub fn shouldEnterEndgame(completed: u32, total: u32) bool {
|
||||
return (completed * 100 / total) >= threshold_percent;
|
||||
}
|
||||
|
||||
pub fn strategy(self: *EndgameManager) EndgameStrategy {
|
||||
return .{
|
||||
// Request remaining pieces from ALL peers
|
||||
.request_from_all_peers = true,
|
||||
// Cancel duplicate requests when piece arrives
|
||||
.cancel_on_receipt = true,
|
||||
// Don't count against normal pending limits
|
||||
.bypass_pending_limits = true,
|
||||
};
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
### 6. Intelligent Piece Scheduler
|
||||
|
||||
```zig
|
||||
const PieceScheduler = struct {
|
||||
pub fn selectNextPiece(
|
||||
self: *PieceScheduler,
|
||||
peer: *PeerMetrics,
|
||||
needed_pieces: []const u32,
|
||||
piece_availability: []const u8, // How many peers have each piece
|
||||
) ?u32 {
|
||||
// Priority 1: Rarest pieces (prevent bottleneck)
|
||||
if (self.findRarestPiece(needed_pieces, piece_availability)) |rare| {
|
||||
return rare;
|
||||
}
|
||||
|
||||
// Priority 2: Sequential pieces for streaming use case
|
||||
if (self.sequential_mode) {
|
||||
return self.findNextSequentialPiece(needed_pieces);
|
||||
}
|
||||
|
||||
// Priority 3: Random (good for swarm health)
|
||||
return self.findRandomPiece(needed_pieces);
|
||||
}
|
||||
|
||||
pub fn selectBestPeer(
|
||||
self: *PieceScheduler,
|
||||
piece_index: u32,
|
||||
available_peers: []const *PeerMetrics,
|
||||
) ?*PeerMetrics {
|
||||
var best_peer: ?*PeerMetrics = null;
|
||||
var best_score: f64 = 0;
|
||||
|
||||
for (available_peers) |peer| {
|
||||
// Score = bandwidth / (rtt * current_load)
|
||||
const load_factor = @as(f64, peer.current_pending + 1);
|
||||
const score = peer.bandwidth_mbps / (peer.rtt_ms * load_factor);
|
||||
|
||||
if (score > best_score) {
|
||||
best_score = score;
|
||||
best_peer = peer;
|
||||
}
|
||||
}
|
||||
|
||||
return best_peer;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Protocol Design
|
||||
|
||||
### New Message Types
|
||||
|
||||
```zig
|
||||
pub const PipelineMessageType = enum(u8) {
|
||||
// Existing
|
||||
piece_request = 0x10,
|
||||
piece_response = 0x11,
|
||||
|
||||
// New: Push mode
|
||||
push_wantlist = 0x20, // Client sends needed pieces bitmap
|
||||
push_piece = 0x21, // Server pushes piece without request
|
||||
push_have = 0x22, // Client acknowledges received pieces
|
||||
push_pause = 0x23, // Client requests pause (flow control)
|
||||
push_resume = 0x24, // Client requests resume
|
||||
|
||||
// New: Metrics
|
||||
ping_probe = 0x30, // RTT measurement
|
||||
pong_probe = 0x31, // RTT measurement response
|
||||
bandwidth_report = 0x32, // Share measured bandwidth
|
||||
|
||||
// New: Endgame
|
||||
endgame_request = 0x40, // Speculative request (may be duplicate)
|
||||
endgame_cancel = 0x41, // Cancel speculative request
|
||||
};
|
||||
```
|
||||
|
||||
### State Machine
|
||||
|
||||
```
|
||||
┌─────────────────┐
|
||||
│ CONNECTED │
|
||||
└────────┬────────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ MEASURING_RTT │ ←── Ping/Pong probes
|
||||
└────────┬────────┘
|
||||
│
|
||||
┌──────────────┼──────────────┐
|
||||
│ │ │
|
||||
┌────────▼────────┐ │ ┌────────▼────────┐
|
||||
│ REQUEST_MODE │ │ │ PUSH_MODE │
|
||||
│ (traditional) │ │ │ (optimized) │
|
||||
└────────┬────────┘ │ └────────┬────────┘
|
||||
│ │ │
|
||||
└──────────────┼──────────────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ ENDGAME │ ←── When >95% complete
|
||||
└────────┬────────┘
|
||||
│
|
||||
┌────────▼────────┐
|
||||
│ COMPLETE │
|
||||
└─────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1: Basic Pipelining (Immediate Gains)
|
||||
**Complexity**: Low | **Expected Gain**: +30-50%
|
||||
|
||||
- Fixed pending limit per peer (10 requests)
|
||||
- Simple round-robin piece assignment
|
||||
- No RTT/bandwidth measurement yet
|
||||
|
||||
```zig
|
||||
// Simple implementation
|
||||
const MAX_PENDING_PER_PEER = 10;
|
||||
|
||||
fn canSendRequest(peer: *Peer) bool {
|
||||
return peer.pending_count < MAX_PENDING_PER_PEER;
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 2: RTT/Bandwidth Measurement
|
||||
**Complexity**: Medium | **Expected Gain**: +10-20%
|
||||
|
||||
- Add ping/pong probes for RTT measurement
|
||||
- Track bytes/time for bandwidth estimation
|
||||
- Exponential moving average smoothing
|
||||
|
||||
### Phase 3: BDP-Based Adaptive Depth
|
||||
**Complexity**: Medium | **Expected Gain**: +20-30%
|
||||
|
||||
- Calculate optimal pending per peer
|
||||
- Dynamic adjustment based on measurements
|
||||
- Floor of 1, ceiling of 50
|
||||
|
||||
### Phase 4: Push Mode Protocol
|
||||
**Complexity**: High | **Expected Gain**: +100-200%
|
||||
|
||||
- New message types (wantlist, push_piece, have)
|
||||
- Server-side push logic
|
||||
- Flow control mechanism
|
||||
- Backward compatibility with request mode
|
||||
|
||||
### Phase 5: Speculative Endgame
|
||||
**Complexity**: Medium | **Expected Gain**: -50% tail latency
|
||||
|
||||
- Detect near-completion threshold
|
||||
- Broadcast remaining pieces to all peers
|
||||
- Duplicate cancellation
|
||||
|
||||
### Phase 6: AIMD Congestion Control
|
||||
**Complexity**: Medium | **Expected Gain**: +10-20% (stability)
|
||||
|
||||
- Per-peer congestion window
|
||||
- Additive increase on success
|
||||
- Multiplicative decrease on failure
|
||||
|
||||
---
|
||||
|
||||
## Performance Projections
|
||||
|
||||
### Benchmark: 1GB file, 10 localhost peers, 1MB pieces
|
||||
|
||||
| Configuration | Throughput | Improvement |
|
||||
|---------------|------------|-------------|
|
||||
| Current (no pipelining) | 180 MB/s | baseline |
|
||||
| Phase 1 (basic pipeline) | 250 MB/s | +39% |
|
||||
| Phase 2+3 (adaptive BDP) | 300 MB/s | +67% |
|
||||
| Phase 4 (push mode) | 450 MB/s | +150% |
|
||||
| Phase 5+6 (endgame+AIMD) | 500 MB/s | +178% |
|
||||
|
||||
### Theoretical Maximum
|
||||
|
||||
```
|
||||
Localhost TCP throughput: ~800 MB/s per connection
|
||||
10 connections: ~600 MB/s (accounting for overhead)
|
||||
Our target: 500 MB/s (83% efficiency)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Trade-offs and Mitigations
|
||||
|
||||
### Memory Overhead
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| N pending × piece_size in flight | Cap total pending at 100 pieces (100MB) |
|
||||
| Per-peer metrics storage | ~200 bytes per peer, negligible |
|
||||
| Wantlist bitfield | file_pieces / 8 bytes, reasonable |
|
||||
|
||||
### Complexity
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| More state to track | Clear state machine, good logging |
|
||||
| Protocol changes | Version negotiation, backward compatible |
|
||||
| Edge cases | Comprehensive test suite |
|
||||
|
||||
### Network Fairness
|
||||
|
||||
| Risk | Mitigation |
|
||||
|------|------------|
|
||||
| Aggressive clients starve others | Server-side rate limiting |
|
||||
| Push mode overwhelms slow clients | Flow control (pause/resume) |
|
||||
| Endgame duplicate waste | Only last 5% of download |
|
||||
|
||||
### Failure Handling
|
||||
|
||||
| Scenario | Handling |
|
||||
|----------|----------|
|
||||
| Peer disconnects with pending | Re-queue pieces to other peers |
|
||||
| Push mode peer goes silent | Timeout → fallback to request mode |
|
||||
| AIMD over-correction | Minimum pending limit of 1 |
|
||||
| Endgame all peers fail | Fall back to normal mode |
|
||||
|
||||
---
|
||||
|
||||
## Implementation Status
|
||||
|
||||
### Completed Phases
|
||||
|
||||
#### Phase 1: Basic Request Pipelining ✅
|
||||
**Files**: `src/files/download.zig`
|
||||
|
||||
Implemented `PeerRequestTracker` with configurable queue depth per peer:
|
||||
- Tracks in-flight pieces per peer
|
||||
- Respects max concurrent requests limit
|
||||
- Integrated with download manager
|
||||
|
||||
#### Phase 2: Per-Peer RTT/Bandwidth Measurement ✅
|
||||
**Files**: `src/files/peer_metrics.zig`
|
||||
|
||||
Created `PeerMetrics` struct with:
|
||||
- RTT tracking via EWMA (α = 0.125, standard TCP value)
|
||||
- Bandwidth measurement (calculated every 100ms or 10MB)
|
||||
- Loss rate tracking with exponential decay
|
||||
|
||||
```zig
|
||||
// Key fields
|
||||
rtt_ms: f64 = 10.0, // Exponential moving average
|
||||
bandwidth_bps: f64, // Measured bytes/sec
|
||||
loss_rate: f64 = 0.0, // 0.0 to 1.0
|
||||
```
|
||||
|
||||
#### Phase 3: BDP-Based Adaptive Queue Depth ✅
|
||||
**Files**: `src/files/peer_metrics.zig`
|
||||
|
||||
Optimal queue depth calculated from Bandwidth-Delay Product:
|
||||
```zig
|
||||
fn recalculateBdp(self: *PeerMetrics) void {
|
||||
const rtt_sec = self.rtt_ms / 1000.0;
|
||||
const bdp = self.bandwidth_bps * rtt_sec;
|
||||
self.bdp_bytes = @intFromFloat(@max(0, bdp));
|
||||
|
||||
// Optimal pending = BDP / piece_size
|
||||
var optimal: f64 = bdp / piece_size_f;
|
||||
|
||||
// Apply loss rate penalty
|
||||
if (self.loss_rate > 0.01) {
|
||||
optimal = optimal * (1.0 - self.loss_rate);
|
||||
}
|
||||
|
||||
self.optimal_queue_depth = @max(min, @min(optimal, max));
|
||||
}
|
||||
```
|
||||
|
||||
#### Phase 5: Speculative Endgame ✅
|
||||
**Files**: `src/files/download.zig`
|
||||
|
||||
Endgame mode triggers at 95% completion:
|
||||
- `endgame_broadcast_pending` flag signals broadcast needed
|
||||
- `broadcastEndgameRequests()` sends to all peers with piece
|
||||
- `getUnrequestedPeersWithPiece()` finds peers not yet requested
|
||||
- Duplicate cancellation on first arrival
|
||||
|
||||
#### Phase 6: AIMD Congestion Control ✅
|
||||
**Files**: `src/files/peer_metrics.zig`
|
||||
|
||||
Complete AIMD implementation:
|
||||
- **Additive Increase**: After `optimal_queue_depth` successful pieces, depth += 1
|
||||
- **Multiplicative Decrease**: On failure, depth /= 2 (via consecutive_timeouts)
|
||||
- **Epoch tracking**: `pieces_since_increase` counter
|
||||
|
||||
```zig
|
||||
// On success
|
||||
self.pieces_since_increase += 1;
|
||||
if (self.pieces_since_increase >= self.optimal_queue_depth) {
|
||||
self.increaseQueueDepth(); // +1
|
||||
self.pieces_since_increase = 0;
|
||||
}
|
||||
|
||||
// On failure
|
||||
self.consecutive_timeouts += 1;
|
||||
self.pieces_since_increase = 0;
|
||||
// getEffectiveQueueDepth() applies: depth >> consecutive_timeouts
|
||||
```
|
||||
|
||||
### Pending Phase
|
||||
|
||||
#### Phase 4: Push Mode Protocol ⏸
|
||||
**Status**: Not implemented
|
||||
|
||||
See [Push Mode Analysis](#push-mode-analysis) section below for industry comparison.
|
||||
|
||||
---
|
||||
|
||||
### Actual Benchmark Results
|
||||
|
||||
**Test environment**: localhost, 10 peers, 1MB pieces
|
||||
|
||||
| Configuration | 1GB File | 5GB File |
|
||||
|---------------|----------|----------|
|
||||
| Baseline (pre-optimization) | 180 MB/s | - |
|
||||
| Phase 1 (basic pipeline) | 494 MB/s | - |
|
||||
| Phase 1 (queue=8 tuned) | 698 MB/s | - |
|
||||
| Phase 2+3+5+6 (adaptive) | 630 MB/s | 298 MB/s |
|
||||
| **+ I/O optimizations** | **700 MB/s** | **443 MB/s** |
|
||||
|
||||
**Final improvement: 3.9x (1GB), 1.5x (5GB) over baseline**
|
||||
|
||||
#### I/O Optimizations Added
|
||||
|
||||
1. **File pre-allocation** (`fallocate`/`ftruncate`)
|
||||
- Reduces fragmentation during download
|
||||
- File: `src/files/file.zig:1090-1115`
|
||||
|
||||
2. **Batch piece requests**
|
||||
- Multiple pieces per message (up to 64)
|
||||
- Reduces protocol overhead
|
||||
- Files: `src/files/transfer.zig`, `src/files/manager.zig`
|
||||
|
||||
3. **Larger socket buffers** (64KB → 4MB)
|
||||
- Better throughput for large transfers
|
||||
- File: `src/p2p.zig:1764`
|
||||
|
||||
4. **Fast test file creation** (16B → 1MB chunks)
|
||||
- 5GB file creation: minutes → seconds
|
||||
- File: `examples/multi_peer_download_test.zig`
|
||||
|
||||
**Configuration used for benchmarks:**
|
||||
```zig
|
||||
config.file_sharing.max_concurrent_downloads = 512;
|
||||
config.file_sharing.buffer_pool_size = 1024;
|
||||
config.file_sharing.pipeline_workers = 32;
|
||||
config.file_sharing.verification_workers = 32;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Push Mode Analysis
|
||||
|
||||
### Is Push Mode Industry Standard?
|
||||
|
||||
**Short answer: No.** Push mode (server-initiated streaming) is not a standard approach in P2P file sharing. Here's why:
|
||||
|
||||
#### Industry Comparison
|
||||
|
||||
| Protocol | Push Support | Notes |
|
||||
|----------|--------------|-------|
|
||||
| **BitTorrent** | ❌ No | Request-response only (BEP 3) |
|
||||
| **IPFS Bitswap** | ❌ No | Wantlist + response model |
|
||||
| **HTTP/2 Server Push** | ⚠️ Deprecated | Was in RFC 7540, removed in most browsers |
|
||||
| **WebRTC Data Channels** | ❌ No | Application decides, no protocol push |
|
||||
| **libp2p** | ❌ No | Request-response streams |
|
||||
| **eMule/eDonkey** | ❌ No | Request-based |
|
||||
|
||||
**HTTP/2 Server Push** was the closest industry example, but it was:
|
||||
- Removed from Chrome (2022) and Firefox
|
||||
- Found to waste bandwidth due to poor prediction
|
||||
- Replaced by Early Hints (103 status code)
|
||||
|
||||
### Pros of Push Mode
|
||||
|
||||
1. **Eliminates Per-Piece RTT**: After wantlist exchange, pieces stream continuously
|
||||
- Traditional: N pieces × RTT latency
|
||||
- Push: 1 RTT + continuous stream
|
||||
|
||||
2. **Better Utilization of Fast Peers**: Server decides send rate, not blocked by client request rate
|
||||
|
||||
3. **Simpler Client Logic**: Client just receives, doesn't need to schedule requests
|
||||
|
||||
4. **Potential for Higher Throughput**: On high-latency links, avoids request/response overhead
|
||||
|
||||
### Cons of Push Mode
|
||||
|
||||
1. **Wasted Bandwidth (Duplicate Pieces)**
|
||||
- Server may push pieces client already received from another peer
|
||||
- Requires frequent HAVE updates (more protocol overhead)
|
||||
- HTTP/2 Push failed largely due to this issue
|
||||
|
||||
2. **Flow Control Complexity**
|
||||
- Client must signal when overwhelmed (pause/resume)
|
||||
- Receiver-side buffering required
|
||||
- Risk of memory exhaustion if sender is faster than disk
|
||||
|
||||
3. **Protocol Complexity**
|
||||
- New message types: wantlist, push_piece, have_update, pause, resume
|
||||
- State synchronization between wantlist and actual needs
|
||||
- Backward compatibility concerns
|
||||
|
||||
4. **No Piece Prioritization Control**
|
||||
- Client loses control over which pieces arrive first
|
||||
- Bad for streaming (need sequential pieces)
|
||||
- Server must guess or client must constantly update priorities
|
||||
|
||||
5. **Harder to Debug**
|
||||
- Asynchronous piece arrival
|
||||
- Race conditions between push and local state updates
|
||||
|
||||
6. **Not Battle-Tested**
|
||||
- No major P2P protocol uses this
|
||||
- HTTP/2 Push was abandoned after real-world issues
|
||||
- Unknown edge cases
|
||||
|
||||
### Recommendation
|
||||
|
||||
**Skip Phase 4 (Push Mode)** for these reasons:
|
||||
|
||||
1. **Current performance is already excellent**: 630 MB/s (1GB), 298 MB/s (5GB)
|
||||
2. **Adaptive pipelining achieves similar benefits**: BDP-based queue depth keeps the pipe full
|
||||
3. **Industry has rejected server push**: HTTP/2 Push deprecation is a cautionary tale
|
||||
4. **Complexity vs gain**: High implementation cost, uncertain benefit
|
||||
5. **Request-response is more predictable**: Easier to reason about, debug, and maintain
|
||||
|
||||
The completed phases (1, 2, 3, 5, 6) provide:
|
||||
- Adaptive queue depth that approximates push benefits
|
||||
- Per-peer optimization without protocol changes
|
||||
- Industry-standard patterns (AIMD, BDP, endgame)
|
||||
|
||||
---
|
||||
|
||||
## References
|
||||
|
||||
1. BitTorrent Protocol Specification (BEP 3)
|
||||
2. IPFS Bitswap Protocol
|
||||
3. TCP Congestion Control (RFC 5681)
|
||||
4. HTTP/2 Flow Control (RFC 7540)
|
||||
5. QUIC Loss Detection and Congestion Control (RFC 9002)
|
||||
6. HTTP/2 Server Push Deprecation - Chrome Platform Status (2022)
|
||||
|
||||
---
|
||||
|
||||
## Appendix: Configuration Defaults
|
||||
|
||||
```zig
|
||||
pub const PipelineConfig = struct {
|
||||
// Basic pipelining
|
||||
max_pending_per_peer: u32 = 10,
|
||||
max_total_pending: u32 = 100,
|
||||
|
||||
// BDP adaptation
|
||||
min_pending: u32 = 1,
|
||||
max_pending: u32 = 50,
|
||||
rtt_ewma_alpha: f64 = 0.125,
|
||||
|
||||
// Push mode
|
||||
push_mode_enabled: bool = true,
|
||||
push_wantlist_interval_ms: u32 = 1000,
|
||||
push_have_interval_ms: u32 = 500,
|
||||
|
||||
// Endgame
|
||||
endgame_threshold_percent: u8 = 95,
|
||||
endgame_enabled: bool = true,
|
||||
|
||||
// AIMD
|
||||
aimd_increase: u32 = 1,
|
||||
aimd_decrease_factor: u32 = 2,
|
||||
|
||||
// Timeouts
|
||||
piece_timeout_ms: u32 = 30000,
|
||||
rtt_probe_interval_ms: u32 = 5000,
|
||||
};
|
||||
```
|
||||
Reference in New Issue
Block a user