1#![forbid(unsafe_code)]
58
59use std::{
60 collections::BTreeMap,
61 sync::{
62 Arc, Barrier, Mutex,
63 atomic::{AtomicBool, AtomicUsize, Ordering},
64 },
65 time::{Duration, Instant},
66};
67
68use fp_runtime::asupersync::{
69 codec::EncodedArtifact,
70 config::{AsupersyncConfig, CapabilitySet, CxCapability},
71 error::AsupersyncError,
72 transport::{InMemoryTransport, TransportLayer},
73 validate_capability_gate,
74};
75
76#[derive(Debug, Clone, Default)]
82struct LegacyInMemoryTransport {
83 storage: Arc<Mutex<BTreeMap<String, EncodedArtifact>>>,
84}
85
86impl LegacyInMemoryTransport {
87 fn required_capabilities() -> CapabilitySet {
88 CapabilitySet::for_capability(CxCapability::Io)
89 .union(CapabilitySet::for_capability(CxCapability::Remote))
90 }
91
92 fn store(&self, artifact: EncodedArtifact, config: &AsupersyncConfig) {
93 validate_capability_gate(config, Self::required_capabilities()).expect("capability gate");
94 self.storage
95 .lock()
96 .expect("legacy transport lock")
97 .insert(artifact.artifact_id.clone(), artifact);
98 }
99
100 fn receive(
101 &self,
102 artifact_id: &str,
103 config: &AsupersyncConfig,
104 ) -> Result<EncodedArtifact, AsupersyncError> {
105 validate_capability_gate(config, Self::required_capabilities())?;
106 let guard = self.storage.lock().map_err(|_| {
107 AsupersyncError::Transport("in-memory transport lock poisoned".to_string())
108 })?;
109 guard
111 .get(artifact_id)
112 .cloned()
113 .ok_or_else(|| AsupersyncError::ArtifactNotFound(artifact_id.to_string()))
114 }
115}
116
117const ARTIFACT_ID: &str = "transport-artifact-3nzz3";
118const ARM_SHIPPED: usize = 0;
119const ARM_LEGACY: usize = 1;
120
121#[derive(Clone, Copy, PartialEq, Eq, Debug)]
122enum Arm {
123 Shipped,
124 Legacy,
125}
126
127fn artifact(payload_bytes: usize) -> EncodedArtifact {
128 let encoded_bytes: Vec<u8> = (0..payload_bytes).map(|i| (i % 251) as u8).collect();
131 EncodedArtifact {
132 artifact_id: ARTIFACT_ID.to_string(),
133 source_len: payload_bytes,
134 encoded_bytes,
135 repair_symbols: 1,
136 }
137}
138
139struct Control {
141 start: Barrier,
142 finish: Barrier,
143 arm: AtomicUsize,
144 active: AtomicUsize,
145 receives: AtomicUsize,
146 stop: AtomicBool,
147}
148
149fn time_unit(control: &Control, arm: Arm, active: usize, receives: usize) -> Duration {
152 control.arm.store(
153 match arm {
154 Arm::Shipped => ARM_SHIPPED,
155 Arm::Legacy => ARM_LEGACY,
156 },
157 Ordering::SeqCst,
158 );
159 control.active.store(active, Ordering::SeqCst);
160 control.receives.store(receives, Ordering::SeqCst);
161 let started = Instant::now();
162 control.start.wait();
163 control.finish.wait();
164 started.elapsed()
165}
166
167fn median_ns(mut samples: Vec<Duration>) -> f64 {
169 samples.sort();
170 let n = samples.len();
171 if n == 0 {
172 return f64::NAN;
173 }
174 if n % 2 == 1 {
175 samples[n / 2].as_nanos() as f64
176 } else {
177 (samples[n / 2 - 1].as_nanos() as f64 + samples[n / 2].as_nanos() as f64) / 2.0
178 }
179}
180
181fn read_trimmed(path: &str) -> String {
182 std::fs::read_to_string(path)
183 .map(|s| s.trim().to_owned())
184 .unwrap_or_else(|_| "unknown".to_owned())
185}
186
187fn harness_sha256() -> String {
188 use sha2::{Digest, Sha256};
189 let mut hasher = Sha256::new();
193 hasher.update(include_str!("transport_receive_ab.rs").as_bytes());
194 hasher
197 .finalize()
198 .iter()
199 .map(|byte| format!("{byte:02x}"))
200 .collect()
201}
202
203fn isa_summary() -> String {
204 let mut features: Vec<&str> = Vec::new();
205 if cfg!(target_feature = "avx2") {
206 features.push("avx2");
207 }
208 if cfg!(target_feature = "avx512f") {
209 features.push("avx512f");
210 }
211 if cfg!(target_feature = "sse4.2") {
212 features.push("sse4.2");
213 }
214 if features.is_empty() {
215 features.push("baseline");
216 }
217 features.join("+")
218}
219
220fn score_square(slots: &[Duration; 4]) -> (f64, f64) {
224 (
225 median_ns(vec![slots[0], slots[3]]),
226 median_ns(vec![slots[1], slots[2]]),
227 )
228}
229
230fn main() {
231 let payload_bytes: usize = 64 * 1024;
232 let receives_per_thread: usize = 2_000;
238 let rounds: usize = 32;
239 let threads = std::thread::available_parallelism()
244 .map(std::num::NonZeroUsize::get)
245 .unwrap_or(4)
246 .min(8);
247
248 let config = AsupersyncConfig::default();
249 let shipped = InMemoryTransport::new();
250 shipped
251 .send(artifact(payload_bytes), &config)
252 .expect("seed shipped transport");
253 let legacy = LegacyInMemoryTransport::default();
254 legacy.store(artifact(payload_bytes), &config);
255
256 let a = shipped
259 .receive(ARTIFACT_ID, &config)
260 .expect("shipped receive");
261 let b = legacy
262 .receive(ARTIFACT_ID, &config)
263 .expect("legacy receive");
264 assert_eq!(a.artifact_id, b.artifact_id, "parity: artifact_id");
265 assert_eq!(a.source_len, b.source_len, "parity: source_len");
266 assert_eq!(a.repair_symbols, b.repair_symbols, "parity: repair_symbols");
267 assert_eq!(a.encoded_bytes, b.encoded_bytes, "parity: encoded_bytes");
268 let denied = AsupersyncConfig::default().with_capabilities(CapabilitySet::default());
269 assert!(
270 shipped.receive(ARTIFACT_ID, &denied).is_err(),
271 "parity: shipped must refuse a denied capability set"
272 );
273 assert!(
274 legacy.receive(ARTIFACT_ID, &denied).is_err(),
275 "parity: legacy control must refuse the same way"
276 );
277 assert!(
278 shipped.receive("no-such-artifact", &config).is_err(),
279 "parity: missing artifact must still error"
280 );
281 assert!(
282 legacy.receive("no-such-artifact", &config).is_err(),
283 "parity: legacy control must error the same way"
284 );
285
286 let control = Control {
287 start: Barrier::new(threads + 1),
288 finish: Barrier::new(threads + 1),
289 arm: AtomicUsize::new(ARM_SHIPPED),
290 active: AtomicUsize::new(threads),
291 receives: AtomicUsize::new(receives_per_thread),
292 stop: AtomicBool::new(false),
293 };
294
295 let mut ab_shipped: Vec<Duration> = Vec::new();
296 let mut ab_legacy: Vec<Duration> = Vec::new();
297 let mut null_leader: Vec<Duration> = Vec::new();
298 let mut null_follower: Vec<Duration> = Vec::new();
299 let mut seq_shipped: Vec<Duration> = Vec::new();
300 let mut seq_legacy: Vec<Duration> = Vec::new();
301
302 std::thread::scope(|scope| {
303 for worker in 0..threads {
304 let control = &control;
305 let shipped = &shipped;
306 let legacy = &legacy;
307 let config = &config;
308 scope.spawn(move || {
309 loop {
310 control.start.wait();
311 if control.stop.load(Ordering::SeqCst) {
312 break;
313 }
314 if worker < control.active.load(Ordering::SeqCst) {
315 let arm = control.arm.load(Ordering::SeqCst);
316 let receives = control.receives.load(Ordering::SeqCst);
317 let mut checksum: u64 = 0;
318 for _ in 0..receives {
319 let got = if arm == ARM_SHIPPED {
320 shipped.receive(ARTIFACT_ID, config)
321 } else {
322 legacy.receive(ARTIFACT_ID, config)
323 }
324 .expect("receive must succeed");
325 checksum = checksum
328 .wrapping_add(u64::from(got.encoded_bytes[0]))
329 .wrapping_add(u64::from(
330 got.encoded_bytes[got.encoded_bytes.len() - 1],
331 ))
332 .wrapping_add(got.source_len as u64);
333 }
334 std::hint::black_box(checksum);
335 }
336 control.finish.wait();
337 }
338 });
339 }
340
341 for _ in 0..3 {
344 time_unit(&control, Arm::Shipped, threads, receives_per_thread);
345 time_unit(&control, Arm::Legacy, threads, receives_per_thread);
346 }
347
348 for round in 0..rounds {
349 let (lead, follow) = if round % 2 == 0 {
352 (Arm::Shipped, Arm::Legacy)
353 } else {
354 (Arm::Legacy, Arm::Shipped)
355 };
356 let order = [lead, follow, follow, lead];
357 let mut slots = [Duration::ZERO; 4];
358 for (slot, arm) in order.iter().enumerate() {
359 slots[slot] = time_unit(&control, *arm, threads, receives_per_thread);
360 }
361 let (lead_ns, follow_ns) = score_square(&slots);
362 let lead_dur = Duration::from_nanos(lead_ns as u64);
363 let follow_dur = Duration::from_nanos(follow_ns as u64);
364 match lead {
365 Arm::Shipped => {
366 ab_shipped.push(lead_dur);
367 ab_legacy.push(follow_dur);
368 }
369 Arm::Legacy => {
370 ab_legacy.push(lead_dur);
371 ab_shipped.push(follow_dur);
372 }
373 }
374
375 let mut null_slots = [Duration::ZERO; 4];
380 for slot in &mut null_slots {
381 *slot = time_unit(&control, Arm::Shipped, threads, receives_per_thread);
382 }
383 let (null_lead_ns, null_follow_ns) = score_square(&null_slots);
384 null_leader.push(Duration::from_nanos(null_lead_ns as u64));
385 null_follower.push(Duration::from_nanos(null_follow_ns as u64));
386
387 let seq_order = [lead, follow, follow, lead];
391 let mut seq_slots = [Duration::ZERO; 4];
392 for (slot, arm) in seq_order.iter().enumerate() {
393 seq_slots[slot] = time_unit(&control, *arm, 1, receives_per_thread);
394 }
395 let (seq_lead_ns, seq_follow_ns) = score_square(&seq_slots);
396 let seq_lead = Duration::from_nanos(seq_lead_ns as u64);
397 let seq_follow = Duration::from_nanos(seq_follow_ns as u64);
398 match lead {
399 Arm::Shipped => {
400 seq_shipped.push(seq_lead);
401 seq_legacy.push(seq_follow);
402 }
403 Arm::Legacy => {
404 seq_legacy.push(seq_lead);
405 seq_shipped.push(seq_follow);
406 }
407 }
408 }
409
410 control.stop.store(true, Ordering::SeqCst);
411 control.start.wait();
412 });
413
414 let shipped_ns = median_ns(ab_shipped);
415 let legacy_ns = median_ns(ab_legacy);
416 let null_ratio = median_ns(null_follower) / median_ns(null_leader);
417 let seq_ratio = median_ns(seq_legacy) / median_ns(seq_shipped);
418 let ratio = legacy_ns / shipped_ns;
419
420 println!("=== br-frankenpandas-3nzz3 InMemoryTransport::receive A/B ===");
421 println!("harness : crates/fp-runtime/examples/transport_receive_ab.rs");
422 println!("harness_sha256 : {}", harness_sha256());
423 println!(
424 "worker : {}",
425 std::env::var("RCH_WORKER").unwrap_or_else(|_| read_trimmed("/proc/sys/kernel/hostname"))
426 );
427 println!(
428 "hostname : {}",
429 read_trimmed("/proc/sys/kernel/hostname")
430 );
431 println!("threads_used : {threads}");
432 println!(
435 "available_parallel : {:?}",
436 std::thread::available_parallelism().map(std::num::NonZeroUsize::get)
437 );
438 println!(
439 "governor : {}",
440 read_trimmed("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor")
441 );
442 println!("isa : {}", isa_summary());
443 println!("profile : release");
444 println!(
445 "shape : payload={payload_bytes}B receives/thread={receives_per_thread} rounds={rounds}"
446 );
447 println!("design : balanced square ABBA/BAAB, pool spawned once, same invocation");
448 println!("---");
449 println!("A/A null ratio : {null_ratio:.4}x (same code both sides; must be near 1.0)");
450 println!("sequential control : {seq_ratio:.4}x (1 thread; lever should NOT show here)");
451 println!("---");
452 println!("shipped (Arc) : {:.3} ms median", shipped_ns / 1.0e6);
453 println!("legacy (control) : {:.3} ms median", legacy_ns / 1.0e6);
454 println!("RATIO legacy/shipped: {ratio:.4}x (>1 means the shipped lever is faster)");
455}