open-humanity
Privacy-first peer assistance network for sovereign autonomous agents
Brought by drakestapleton
open-humanity / crates / beacon-client / src / lib.rs
| 1 | pub mod network; |
| 2 | pub mod preflight; |
| 3 | pub mod relay; |
| 4 | pub mod storage; |
| 5 | |
| 6 | pub use network::*; |
| 7 | pub use preflight::*; |
| 8 | pub use storage::*; |
| 9 | |
| 10 | #[cfg(test)] |
| 11 | mod tests { |
| 12 | use super::*; |
| 13 | use beacon_core::crypto::Keypair; |
| 14 | use beacon_core::schema::{BeaconTopic, DistressNanobeacon, ErrorFingerprint}; |
| 15 | use rand::rngs::OsRng; |
| 16 | use std::sync::Arc; |
| 17 | use std::time::{SystemTime, UNIX_EPOCH}; |
| 18 | use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret}; |
| 19 | |
| 20 | #[test] |
| 21 | fn test_sqlite_wal_storage_and_sweep() { |
| 22 | let storage = BeaconStorage::open_in_memory().expect("in-memory db must open"); |
| 23 | |
| 24 | let keypair = Keypair::generate(); |
| 25 | let dh_secret = StaticSecret::random_from_rng(OsRng); |
| 26 | let dh_pubkey = *X25519PublicKey::from(&dh_secret).as_bytes(); |
| 27 | |
| 28 | let fp = ErrorFingerprint::from_error_str("test compiler error", Some(101), "aarch64"); |
| 29 | let beacon = DistressNanobeacon::new( |
| 30 | BeaconTopic::RustCompilation, |
| 31 | keypair.pubkey_bytes(), |
| 32 | dh_pubkey, |
| 33 | fp.clone(), |
| 34 | "Compilation failure".into(), |
| 35 | "Cannot borrow as mutable".into(), |
| 36 | ); |
| 37 | |
| 38 | storage.record_outbound_beacon(&beacon).expect("outbound record should succeed"); |
| 39 | storage.record_inbound_beacon(&beacon).expect("inbound record should succeed"); |
| 40 | |
| 41 | storage.insert_solved_entry(&fp.hash, BeaconTopic::RustCompilation, "use &mut instead") |
| 42 | .expect("insert solved entry should succeed"); |
| 43 | |
| 44 | let solved = storage.get_solved_entry(&fp.hash).expect("query should succeed"); |
| 45 | assert!(solved.is_some()); |
| 46 | let solved = solved.unwrap(); |
| 47 | assert_eq!(solved.solution_patch, "use &mut instead"); |
| 48 | assert!(!solved.promoted_to_cortex); |
| 49 | |
| 50 | storage.mark_promoted_to_cortex(&fp.hash).expect("mark promoted should succeed"); |
| 51 | let solved = storage.get_solved_entry(&fp.hash).unwrap().unwrap(); |
| 52 | assert!(solved.promoted_to_cortex); |
| 53 | |
| 54 | let swept = storage.sweep_expired(0).expect("sweep should succeed"); |
| 55 | assert_eq!(swept, 2); |
| 56 | } |
| 57 | |
| 58 | #[tokio::test] |
| 59 | async fn test_storage_concurrent_signal_insertions_tokio_contention() { |
| 60 | let temp_dir = tempfile::tempdir().expect("tempdir creation should succeed"); |
| 61 | let db_path = temp_dir.path().join("signal_contention.sqlite"); |
| 62 | |
| 63 | { |
| 64 | let init_storage = BeaconStorage::open(&db_path).expect("init db must succeed"); |
| 65 | assert_eq!(init_storage.count_outbound().unwrap(), 0); |
| 66 | } |
| 67 | |
| 68 | let num_tasks = 16; |
| 69 | let inserts_per_task = 5; |
| 70 | let path_arc = Arc::new(db_path.clone()); |
| 71 | let mut handles = Vec::new(); |
| 72 | |
| 73 | for task_idx in 0..num_tasks { |
| 74 | let path_clone = Arc::clone(&path_arc); |
| 75 | let handle = tokio::spawn(async move { |
| 76 | let storage = BeaconStorage::open(&*path_clone).expect("task db open must succeed"); |
| 77 | for i in 0..inserts_per_task { |
| 78 | let keypair = Keypair::generate(); |
| 79 | let dh_secret = StaticSecret::random_from_rng(OsRng); |
| 80 | let dh_pubkey = *X25519PublicKey::from(&dh_secret).as_bytes(); |
| 81 | let err_msg = format!("task-{}-iter-{}", task_idx, i); |
| 82 | let fp = ErrorFingerprint::from_error_str(&err_msg, Some(task_idx as u32), "aarch64"); |
| 83 | let signal = DistressNanobeacon::new( |
| 84 | BeaconTopic::RustCompilation, |
| 85 | keypair.pubkey_bytes(), |
| 86 | dh_pubkey, |
| 87 | fp, |
| 88 | format!("Task {} Signal {}", task_idx, i), |
| 89 | "Concurrent contention signal".into(), |
| 90 | ); |
| 91 | storage.record_outbound_beacon(&signal).expect("concurrent record must succeed"); |
| 92 | } |
| 93 | }); |
| 94 | handles.push(handle); |
| 95 | } |
| 96 | |
| 97 | for handle in handles { |
| 98 | handle.await.expect("task must join cleanly without error"); |
| 99 | } |
| 100 | |
| 101 | let verify_storage = BeaconStorage::open(&db_path).expect("verify db open must succeed"); |
| 102 | let total_count = verify_storage.count_outbound().expect("count query must succeed"); |
| 103 | assert_eq!( |
| 104 | total_count, |
| 105 | num_tasks * inserts_per_task, |
| 106 | "Exact count of concurrently inserted signals must match total attempts" |
| 107 | ); |
| 108 | } |
| 109 | |
| 110 | #[test] |
| 111 | fn test_storage_automated_sweep_and_expiry() { |
| 112 | let storage = BeaconStorage::open_in_memory().expect("in-memory db must open"); |
| 113 | let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); |
| 114 | |
| 115 | let keypair = Keypair::generate(); |
| 116 | let dh_secret = StaticSecret::random_from_rng(OsRng); |
| 117 | let dh_pubkey = *X25519PublicKey::from(&dh_secret).as_bytes(); |
| 118 | |
| 119 | let make_signal = |title: &str| { |
| 120 | let fp = ErrorFingerprint::from_error_str(title, None, "aarch64"); |
| 121 | DistressNanobeacon::new( |
| 122 | BeaconTopic::RustCompilation, |
| 123 | keypair.pubkey_bytes(), |
| 124 | dh_pubkey, |
| 125 | fp, |
| 126 | title.into(), |
| 127 | "summary".into(), |
| 128 | ) |
| 129 | }; |
| 130 | |
| 131 | let fresh1 = make_signal("Fresh signal 1"); |
| 132 | storage.record_outbound_beacon(&fresh1).unwrap(); |
| 133 | |
| 134 | let fresh2 = make_signal("Fresh signal 2"); |
| 135 | storage.record_outbound_beacon(&fresh2).unwrap(); |
| 136 | |
| 137 | let stale_created = now.saturating_sub(700_000); |
| 138 | { |
| 139 | let mut storage_test = BeaconStorage::open_in_memory().unwrap(); |
| 140 | let tx = storage_test.transaction().unwrap(); |
| 141 | |
| 142 | let sig1 = make_signal("Fresh A"); |
| 143 | let sig2 = make_signal("Fresh B"); |
| 144 | BeaconStorage::record_outbound_beacon_tx(&tx, &sig1).unwrap(); |
| 145 | BeaconStorage::record_outbound_beacon_tx(&tx, &sig2).unwrap(); |
| 146 | |
| 147 | for i in 0..3 { |
| 148 | let stale = make_signal(&format!("Stale {}", i)); |
| 149 | tx.execute( |
| 150 | "INSERT INTO beacons_out ( |
| 151 | id, timestamp, topic, sender_pubkey, fingerprint_hash, |
| 152 | compiler_code, arch, title, compact_summary, status, created_at |
| 153 | ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", |
| 154 | rusqlite::params![ |
| 155 | stale.beacon_id.to_string(), |
| 156 | stale.timestamp, |
| 157 | stale.topic as u8, |
| 158 | &stale.sender_pubkey[..], |
| 159 | &stale.fingerprint.hash[..], |
| 160 | stale.fingerprint.compiler_code, |
| 161 | stale.fingerprint.hardware_arch, |
| 162 | stale.title, |
| 163 | stale.compact_summary, |
| 164 | "pending", |
| 165 | stale_created, |
| 166 | ], |
| 167 | ).unwrap(); |
| 168 | } |
| 169 | tx.commit().unwrap(); |
| 170 | |
| 171 | assert_eq!(storage_test.count_outbound().unwrap(), 5); |
| 172 | let swept = storage_test.sweep_expired(604800).unwrap(); |
| 173 | assert_eq!(swept, 3, "Exactly 3 stale signals must be swept"); |
| 174 | assert_eq!(storage_test.count_outbound().unwrap(), 2, "2 fresh signals must remain"); |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | #[test] |
| 179 | fn test_storage_transaction_rollback_simulated_io_error() { |
| 180 | let mut storage = BeaconStorage::open_in_memory().expect("in-memory db must open"); |
| 181 | |
| 182 | let keypair = Keypair::generate(); |
| 183 | let dh_secret = StaticSecret::random_from_rng(OsRng); |
| 184 | let dh_pubkey = *X25519PublicKey::from(&dh_secret).as_bytes(); |
| 185 | |
| 186 | let fp1 = ErrorFingerprint::from_error_str("Baseline signal", None, "aarch64"); |
| 187 | let baseline = DistressNanobeacon::new( |
| 188 | BeaconTopic::RustCompilation, |
| 189 | keypair.pubkey_bytes(), |
| 190 | dh_pubkey, |
| 191 | fp1, |
| 192 | "Baseline signal".into(), |
| 193 | "Persisted before transaction".into(), |
| 194 | ); |
| 195 | |
| 196 | storage.record_outbound_beacon(&baseline).expect("baseline insert must succeed"); |
| 197 | assert_eq!(storage.count_outbound().unwrap(), 1); |
| 198 | |
| 199 | let simulated_error: Result<(), StorageError> = (|| { |
| 200 | let tx = storage.transaction()?; |
| 201 | |
| 202 | let fp2 = ErrorFingerprint::from_error_str("Uncommitted A", None, "aarch64"); |
| 203 | let sig_a = DistressNanobeacon::new( |
| 204 | BeaconTopic::RustCompilation, |
| 205 | keypair.pubkey_bytes(), |
| 206 | dh_pubkey, |
| 207 | fp2, |
| 208 | "Uncommitted A".into(), |
| 209 | "Should be rolled back".into(), |
| 210 | ); |
| 211 | BeaconStorage::record_outbound_beacon_tx(&tx, &sig_a)?; |
| 212 | |
| 213 | let fp3 = ErrorFingerprint::from_error_str("Uncommitted B", None, "aarch64"); |
| 214 | let sig_b = DistressNanobeacon::new( |
| 215 | BeaconTopic::RustCompilation, |
| 216 | keypair.pubkey_bytes(), |
| 217 | dh_pubkey, |
| 218 | fp3, |
| 219 | "Uncommitted B".into(), |
| 220 | "Should be rolled back".into(), |
| 221 | ); |
| 222 | BeaconStorage::record_outbound_beacon_tx(&tx, &sig_b)?; |
| 223 | |
| 224 | Err(StorageError::Io(std::io::Error::new( |
| 225 | std::io::ErrorKind::Other, |
| 226 | "Simulated disk IO error during transaction", |
| 227 | ))) |
| 228 | })(); |
| 229 | |
| 230 | assert!(simulated_error.is_err(), "Transaction closure must return IO error"); |
| 231 | assert_eq!( |
| 232 | storage.count_outbound().unwrap(), |
| 233 | 1, |
| 234 | "Database count must remain at 1 because aborted transaction rolled back all mutations" |
| 235 | ); |
| 236 | |
| 237 | { |
| 238 | let tx = storage.transaction().unwrap(); |
| 239 | let fp_committed = ErrorFingerprint::from_error_str("Committed B", None, "aarch64"); |
| 240 | let sig_c = DistressNanobeacon::new( |
| 241 | BeaconTopic::RustCompilation, |
| 242 | keypair.pubkey_bytes(), |
| 243 | dh_pubkey, |
| 244 | fp_committed, |
| 245 | "Committed B".into(), |
| 246 | "Should be committed".into(), |
| 247 | ); |
| 248 | BeaconStorage::record_outbound_beacon_tx(&tx, &sig_c).unwrap(); |
| 249 | tx.commit().unwrap(); |
| 250 | } |
| 251 | |
| 252 | assert_eq!( |
| 253 | storage.count_outbound().unwrap(), |
| 254 | 2, |
| 255 | "Database count must increase to 2 after successful commit" |
| 256 | ); |
| 257 | } |
| 258 | |
| 259 | #[test] |
| 260 | fn test_preflight_sandbox_execution() { |
| 261 | let sandbox = PreflightSandbox::new().expect("sandbox creation should succeed"); |
| 262 | assert!(sandbox.path().exists()); |
| 263 | |
| 264 | sandbox.write_file("test.txt", "verification payload").expect("file write should succeed"); |
| 265 | let target_file = sandbox.path().join("test.txt"); |
| 266 | assert!(target_file.exists()); |
| 267 | |
| 268 | let receipt = sandbox.run_check("echo", &["sandbox-verified"]).expect("check should pass"); |
| 269 | assert!(receipt.passed); |
| 270 | assert!(receipt.stdout.contains("sandbox-verified")); |
| 271 | |
| 272 | let path_to_clean = sandbox.path().to_path_buf(); |
| 273 | drop(sandbox); |
| 274 | assert!(!path_to_clean.exists(), "sandbox directory must be purged on drop"); |
| 275 | } |
| 276 | |
| 277 | #[tokio::test] |
| 278 | async fn test_network_udp_transport_loopback() { |
| 279 | let node_a = BeaconTransport::bind("127.0.0.1:0").await.expect("bind A should succeed"); |
| 280 | let node_b = BeaconTransport::bind("127.0.0.1:0").await.expect("bind B should succeed"); |
| 281 | |
| 282 | let addr_b = node_b.local_addr().expect("local addr B"); |
| 283 | |
| 284 | let keypair = Keypair::generate(); |
| 285 | let dh_secret = StaticSecret::random_from_rng(OsRng); |
| 286 | let dh_pubkey = *X25519PublicKey::from(&dh_secret).as_bytes(); |
| 287 | |
| 288 | let fp = ErrorFingerprint::from_error_str("udp network test error", Some(404), "aarch64"); |
| 289 | let beacon = DistressNanobeacon::new( |
| 290 | BeaconTopic::ProtocolCoordination, |
| 291 | keypair.pubkey_bytes(), |
| 292 | dh_pubkey, |
| 293 | fp, |
| 294 | "Network loopback test".into(), |
| 295 | "Testing 0-RTT broadcast".into(), |
| 296 | ); |
| 297 | |
| 298 | let sent = node_a.broadcast_beacon(&beacon, &[addr_b]).await.expect("send should succeed"); |
| 299 | assert_eq!(sent, 1); |
| 300 | |
| 301 | let (received_beacon, src) = node_b.recv_beacon().await.expect("recv should succeed"); |
| 302 | assert_eq!(received_beacon.title, "Network loopback test"); |
| 303 | assert_eq!(received_beacon.topic, BeaconTopic::ProtocolCoordination); |
| 304 | assert_eq!(src, node_a.local_addr().unwrap()); |
| 305 | } |
| 306 | } |