x0x 0.19.2

Agent-to-agent gossip network for AI systems — no winners, no losers, just cooperation
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
#![allow(clippy::unwrap_used, clippy::expect_used)]

//! Integration tests for the connectivity module.
//!
//! Tests ReachabilityInfo heuristics, ConnectOutcome behaviour, and the
//! `connect_to_agent()` / `reachability()` methods on `Agent`.

use tempfile::TempDir;
use x0x::connectivity::{ConnectOutcome, ReachabilityInfo};
use x0x::{network::NetworkConfig, Agent, DiscoveredAgent};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

async fn build_agent(dir: &TempDir) -> Agent {
    Agent::builder()
        .with_machine_key(dir.path().join("machine.key"))
        .with_agent_key_path(dir.path().join("agent.key"))
        .with_network_config(NetworkConfig::default())
        .build()
        .await
        .unwrap()
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
}

fn fake_discovered(
    id_byte: u8,
    addresses: Vec<std::net::SocketAddr>,
    nat_type: Option<&str>,
    can_receive_direct: Option<bool>,
    is_relay: Option<bool>,
    is_coordinator: Option<bool>,
) -> DiscoveredAgent {
    let now = now_secs();
    DiscoveredAgent {
        agent_id: x0x::identity::AgentId([id_byte; 32]),
        machine_id: x0x::identity::MachineId([id_byte + 100; 32]),
        user_id: None,
        addresses,
        announced_at: now,
        last_seen: now,
        machine_public_key: vec![],
        nat_type: nat_type.map(str::to_string),
        can_receive_direct,
        is_relay,
        is_coordinator,
        reachable_via: Vec::new(),
        relay_candidates: Vec::new(),
    }
}

// ---------------------------------------------------------------------------
// ReachabilityInfo unit tests
// ---------------------------------------------------------------------------

#[test]
fn likely_direct_with_can_receive_direct_true() {
    let da = fake_discovered(
        1,
        vec!["127.0.0.1:9000".parse().unwrap()],
        None,
        Some(true),
        None,
        None,
    );
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(info.likely_direct());
    assert!(!info.needs_coordination());
}

#[test]
fn not_likely_direct_with_can_receive_direct_false() {
    let da = fake_discovered(
        2,
        vec!["127.0.0.1:9000".parse().unwrap()],
        None,
        Some(false),
        None,
        None,
    );
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.likely_direct());
    assert!(info.needs_coordination());
}

#[test]
fn likely_direct_for_full_cone_nat_is_false_without_peer_verification() {
    let da = fake_discovered(
        3,
        vec!["127.0.0.1:9000".parse().unwrap()],
        Some("FullCone"),
        None,
        None,
        None,
    );
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.likely_direct());
    assert!(info.should_attempt_direct());
    assert!(info.needs_coordination());
}

#[test]
fn not_likely_direct_for_symmetric_nat() {
    let da = fake_discovered(
        4,
        vec!["127.0.0.1:9000".parse().unwrap()],
        Some("Symmetric"),
        None,
        None,
        None,
    );
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.likely_direct());
    assert!(info.needs_coordination());
}

#[test]
fn not_likely_direct_without_addresses() {
    let da = fake_discovered(5, vec![], None, Some(true), None, None);
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.likely_direct(), "no addresses means no direct path");
}

#[test]
fn unknown_reachability_still_attempts_direct() {
    let da = fake_discovered(
        6,
        vec!["192.168.1.1:9000".parse().unwrap()],
        None,
        None,
        None,
        None,
    );
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.likely_direct());
    assert!(
        info.should_attempt_direct(),
        "unknown peers still get a direct probe"
    );
    assert!(info.needs_coordination());
}

#[test]
fn is_relay_returns_false_when_none() {
    let da = fake_discovered(7, vec![], None, None, None, None);
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.is_relay());
}

#[test]
fn is_relay_returns_true_when_some_true() {
    let da = fake_discovered(8, vec![], None, None, Some(true), None);
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(info.is_relay());
}

#[test]
fn is_coordinator_returns_false_when_none() {
    let da = fake_discovered(9, vec![], None, None, None, None);
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.is_coordinator());
}

#[test]
fn is_coordinator_returns_true_when_some_true() {
    let da = fake_discovered(10, vec![], None, None, None, Some(true));
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(info.is_coordinator());
}

// ---------------------------------------------------------------------------
// ConnectOutcome unit tests
// ---------------------------------------------------------------------------

#[test]
fn connect_outcome_display() {
    let addr: std::net::SocketAddr = "127.0.0.1:9000".parse().unwrap();
    assert_eq!(
        ConnectOutcome::Direct(addr).to_string(),
        format!("direct({addr})")
    );
    assert_eq!(
        ConnectOutcome::Coordinated(addr).to_string(),
        format!("coordinated({addr})")
    );
    assert_eq!(ConnectOutcome::Unreachable.to_string(), "unreachable");
    assert_eq!(ConnectOutcome::NotFound.to_string(), "not_found");
}

#[test]
fn connect_outcome_equality() {
    let addr: std::net::SocketAddr = "127.0.0.1:9000".parse().unwrap();
    assert_eq!(ConnectOutcome::Direct(addr), ConnectOutcome::Direct(addr));
    assert_eq!(ConnectOutcome::Unreachable, ConnectOutcome::Unreachable);
    assert_ne!(ConnectOutcome::Direct(addr), ConnectOutcome::Unreachable);
    assert_ne!(
        ConnectOutcome::Direct(addr),
        ConnectOutcome::Coordinated(addr)
    );
    assert_ne!(ConnectOutcome::NotFound, ConnectOutcome::Unreachable);
}

// ---------------------------------------------------------------------------
// Agent::connect_to_agent() integration tests
// ---------------------------------------------------------------------------

/// Connecting to a non-existent agent returns NotFound.
#[tokio::test]
async fn connect_to_unknown_agent_returns_not_found() {
    let dir = TempDir::new().unwrap();
    let agent = build_agent(&dir).await;

    let unknown_id = x0x::identity::AgentId([200u8; 32]);
    let outcome = agent.connect_to_agent(&unknown_id).await.unwrap();
    assert_eq!(outcome, ConnectOutcome::NotFound);
}

/// Connecting to a non-existent machine returns NotFound.
#[tokio::test]
async fn connect_to_unknown_machine_returns_not_found() {
    let dir = TempDir::new().unwrap();
    let agent = build_agent(&dir).await;

    let unknown_id = x0x::identity::MachineId([201u8; 32]);
    let outcome = agent.connect_to_machine(&unknown_id).await.unwrap();
    assert_eq!(outcome, ConnectOutcome::NotFound);
}

/// An agent with no addresses returns Unreachable.
#[tokio::test]
async fn connect_to_agent_with_no_addresses_returns_unreachable() {
    let dir = TempDir::new().unwrap();
    let agent = build_agent(&dir).await;

    let da = fake_discovered(100, vec![], None, Some(true), None, None);
    let target_id = da.agent_id;
    agent.insert_discovered_agent_for_testing(da).await;

    let outcome = agent.connect_to_agent(&target_id).await.unwrap();
    assert_eq!(
        outcome,
        ConnectOutcome::Unreachable,
        "no addresses means unreachable"
    );
}

/// Without a network started, connecting returns Unreachable (not an error).
#[tokio::test]
async fn connect_without_network_returns_unreachable() {
    let dir = TempDir::new().unwrap();
    // Build agent WITHOUT a bind address (no network)
    let agent = Agent::builder()
        .with_machine_key(dir.path().join("machine.key"))
        .with_agent_key_path(dir.path().join("agent.key"))
        // No network config = no network started
        .build()
        .await
        .unwrap();

    let da = fake_discovered(
        101,
        vec!["127.0.0.1:9999".parse().unwrap()],
        None,
        Some(true),
        None,
        None,
    );
    let target_id = da.agent_id;
    agent.insert_discovered_agent_for_testing(da).await;

    let outcome = agent.connect_to_agent(&target_id).await.unwrap();
    assert_eq!(
        outcome,
        ConnectOutcome::Unreachable,
        "no network started → Unreachable, not an error"
    );
}

// ---------------------------------------------------------------------------
// Agent::reachability() integration tests
// ---------------------------------------------------------------------------

/// reachability() returns None for an agent not in the cache.
#[tokio::test]
async fn reachability_none_for_unknown_agent() {
    let dir = TempDir::new().unwrap();
    let agent = build_agent(&dir).await;

    let unknown_id = x0x::identity::AgentId([201u8; 32]);
    assert!(agent.reachability(&unknown_id).await.is_none());
}

/// reachability() returns correct info for an agent in the cache.
#[tokio::test]
async fn reachability_returns_correct_info_from_cache() {
    let dir = TempDir::new().unwrap();
    let agent = build_agent(&dir).await;

    let da = fake_discovered(
        102,
        vec!["10.0.0.2:8080".parse().unwrap()],
        Some("FullCone"),
        Some(true),
        Some(false),
        Some(true),
    );
    let target_id = da.agent_id;
    agent.insert_discovered_agent_for_testing(da).await;

    let info = agent.reachability(&target_id).await;
    assert!(info.is_some());
    let info = info.unwrap();

    assert!(info.likely_direct());
    assert!(info.should_attempt_direct());
    assert!(!info.needs_coordination());
    assert!(!info.is_relay());
    assert!(info.is_coordinator());
    assert_eq!(info.addresses.len(), 1);
}

/// Inserting an agent discovery record also creates the machine endpoint link.
#[tokio::test]
async fn machine_for_agent_returns_linked_endpoint() {
    let dir = TempDir::new().unwrap();
    let agent = build_agent(&dir).await;

    let da = fake_discovered(
        103,
        vec!["10.0.0.3:8080".parse().unwrap()],
        Some("FullCone"),
        Some(true),
        Some(false),
        Some(true),
    );
    let target_id = da.agent_id;
    let target_machine = da.machine_id;
    agent.insert_discovered_agent_for_testing(da).await;

    let machine = agent
        .machine_for_agent(target_id)
        .await
        .unwrap()
        .expect("agent should resolve to a machine");
    assert_eq!(machine.machine_id, target_machine);
    assert!(machine.agent_ids.contains(&target_id));
    assert_eq!(machine.addresses.len(), 1);
}

// ---------------------------------------------------------------------------
// ReachabilityInfo: all NAT type heuristics
// ---------------------------------------------------------------------------

#[test]
fn nat_type_none_string_is_not_enough_without_peer_verification() {
    let da = fake_discovered(
        20,
        vec!["1.2.3.4:9000".parse().unwrap()],
        Some("None"),
        None,
        None,
        None,
    );
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.likely_direct());
    assert!(info.should_attempt_direct());
}

#[test]
fn nat_type_address_restricted_still_attempts_direct_but_is_not_verified() {
    let da = fake_discovered(
        21,
        vec!["1.2.3.4:9000".parse().unwrap()],
        Some("AddressRestricted"),
        None,
        None,
        None,
    );
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.likely_direct());
    assert!(info.should_attempt_direct());
    assert!(info.needs_coordination());
}

#[test]
fn nat_type_port_restricted_still_attempts_direct_but_is_not_verified() {
    let da = fake_discovered(
        22,
        vec!["1.2.3.4:9000".parse().unwrap()],
        Some("PortRestricted"),
        None,
        None,
        None,
    );
    let info = ReachabilityInfo::from_discovered(&da);
    assert!(!info.likely_direct());
    assert!(info.should_attempt_direct());
    assert!(info.needs_coordination());
}