Skip to main content

transport_receive_ab/
transport_receive_ab.rs

1//! br-frankenpandas-3nzz3 — A/B for `InMemoryTransport::receive`'s critical section.
2//!
3//! The structural change shipped long ago (07dcf4f96, repaired at 38df4882d):
4//! `receive` stores `Arc<EncodedArtifact>`, copies the `Arc` under the mutex, and
5//! performs the DEEP clone after unlocking. The bead stayed open because that is
6//! a SPEED claim with no number attached, and its own acceptance text demands a
7//! strict-remote release A/B with a null control before anything may be banked.
8//!
9//! This harness supplies the number. It is deliberately self-contained in
10//! `fp-runtime`: `fp-bench` is a vs-pandas harness and it depends on `fp-frame`,
11//! which is the wrong shape for an internal concurrency comparison.
12//!
13//! WHAT IS COMPARED
14//!
15//!   SHIPPED  `fp_runtime::asupersync::transport::InMemoryTransport`
16//!            Arc clone under the lock, deep clone (and `catch_unwind`) outside.
17//!   LEGACY   `LegacyInMemoryTransport` below — the pre-3nzz3 shape, reproduced
18//!            here as a CONTROL. It deep-clones the artifact WHILE HOLDING the
19//!            mutex, which is exactly the critical section the lever shortened.
20//!
21//! The control lives in this harness, never in production code, so the shipped
22//! path is measured exactly as it ships.
23//!
24//! WHY CONCURRENTLY, AND WHY A SEQUENTIAL ROW TOO
25//!
26//! Both shapes do the same total work per call; only the mutex HOLD TIME
27//! differs, so the lever can only pay off under CONTENTION. Threads all pull the
28//! same artifact id, which is maximum contention. The 1-thread row is the
29//! negative control: the lever should be invisible there, and if it is not, this
30//! harness is measuring something other than lock hold time.
31//!
32//! MEASUREMENT DISCIPLINE (campaign law)
33//!
34//!   * Both arms run in the SAME invocation on the SAME worker. A ratio built
35//!     from two invocations is not evidence — the same cell has read 1.2693x and
36//!     0.0093x on two workers with both A/A nulls passing.
37//!   * Arms are INTERLEAVED in a balanced square (ABBA / BAAB by round) so drift
38//!     cancels instead of loading onto whichever arm ran first.
39//!   * The A/A null is run THROUGH THE SAME SQUARE: four runs of the SHIPPED arm
40//!     placed in the same four slots, then scored exactly as the real ratio is.
41//!     It therefore answers the only question a null should — "if the two arms
42//!     were identical, what would this DESIGN report?" A null computed as
43//!     first-vs-second instead MEASURES the position effect the square exists to
44//!     remove, which is how the first version of this harness produced 0.7966x.
45//!   * Threads are spawned ONCE, outside every timed region. Per-call
46//!     `thread::scope` put a variable ~400us spawn cost inside a ~20ms
47//!     measurement and is a known way to break the null on parallel kernels.
48//!   * The row names the WORKER and the HARNESS (this file's SHA-256), because
49//!     two separately-sanctioned harnesses have disagreed ~2x on ONE worker with
50//!     both nulls green.
51//!
52//! Run:
53//!   RCH_REQUIRE_REMOTE=1 env -u CARGO_TARGET_DIR rch exec -- \
54//!     cargo run --release -p fp-runtime --features asupersync \
55//!       --example transport_receive_ab
56
57#![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/// The pre-br-frankenpandas-3nzz3 shape, reproduced as a control.
77///
78/// The ONLY intended difference from the shipped transport is WHERE the deep
79/// clone happens: here it is inside the `guard` scope, so the `Vec<u8>` copy is
80/// serialized across every concurrent caller.
81#[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        // THE CONTROL'S DEFINING PROPERTY: the deep clone is inside the guard.
110        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    // Size is the whole point: the lever moves a Vec<u8> copy out of the
129    // critical section, so any effect scales with how long that copy takes.
130    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
139/// Shared control block for the once-spawned worker pool.
140struct Control {
141    start: Barrier,
142    finish: Barrier,
143    arm: AtomicUsize,
144    active: AtomicUsize,
145    receives: AtomicUsize,
146    stop: AtomicBool,
147}
148
149/// Time ONE unit: `active` workers each performing `receives` receives on `arm`.
150/// The timed span is barrier-to-barrier and contains no thread management.
151fn 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
167/// Median of a set of durations, in nanoseconds.
168fn 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    // Hash THIS SOURCE FILE, not the binary: a binary hash moves with every
190    // dependency rebuild, while the question a harness sha must answer is
191    // "which measurement PROCEDURE produced this row".
192    let mut hasher = Sha256::new();
193    hasher.update(include_str!("transport_receive_ab.rs").as_bytes());
194    // sha2 0.11 returns a generic `Array`, which does not implement `LowerHex`,
195    // so the hex rendering is explicit rather than a `{:x}` format.
196    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
220/// Score four slot timings the way the ABBA square scores the real arms.
221/// Slots 0 and 3 belong to the arm that led the round; slots 1 and 2 to the
222/// other. Returns (leader_ns, follower_ns).
223fn 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    // Sized for signal, not for wall-clock: on rch nearly all of this example's
233    // runtime is COMPILING the asupersync dependency tree, so the measurement
234    // phase is effectively free and there is no reason to under-sample. At 400
235    // receives x 16 rounds the A/A null came in at 1.0853x on vmi1152480, which
236    // is too loose to sit under a 1.8x claim on a busy shared host.
237    let receives_per_thread: usize = 2_000;
238    let rounds: usize = 32;
239    // NOT CACHED, and correctly so (br-frankenpandas-q1evw): this sizes the A/B
240    // harness's worker count ONCE at startup, so the cgroup walk is paid a single
241    // time for the whole process rather than per call. The per-call cache that
242    // `fp_columnar::cached_available_parallelism` provides has nothing to win here.
243    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    // PARITY BEFORE TIMING. A faster arm that returns something different is not
257    // a faster arm, and the bead requires the error surfaces to be preserved.
258    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                            // Consume the result so neither arm can be optimized
326                            // away, and both pay the same read cost.
327                            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        // Warm both arms so the first timed round does not pay page-fault and
342        // allocator-growth costs that belong to neither.
343        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            // BALANCED SQUARE: the leader alternates, so each arm occupies each
350            // slot equally across any pair of rounds.
351            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            // A/A NULL THROUGH THE IDENTICAL SQUARE: four runs of the SHIPPED
376            // arm, scored exactly as above. This asks what the DESIGN reports
377            // when the two arms are the same code, which is the only thing a
378            // null can legitimately certify.
379            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            // SEQUENTIAL NEGATIVE CONTROL: one worker, no contention, same
388            // square. The lever only moves work out of a CONTENDED critical
389            // section, so this should land near 1.0.
390            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    // PROVENANCE SITE, DELIBERATELY NOT CACHED (br-frankenpandas-q1evw): the row
433    // records the live parallelism of the host that produced this A/B.
434    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}