fnx-classes 0.2.2

Core graph classes and data structures for FrankenNetworkX
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
#![forbid(unsafe_code)]

//! Minimal release harness for fnx-classes hot primitives.
//!
//! Build: cargo build -p fnx-classes --profile release --bin perf_harness

use fnx_classes::digraph::DiGraph;
use fnx_classes::{AttrMap, Graph};
use fnx_runtime::{CgseValue, CompatibilityMode};
use std::collections::hash_map::DefaultHasher;
use std::env;
use std::hash::{Hash, Hasher};
use std::hint::black_box;
use std::io::Write;
use std::process::{Command, Stdio, exit};
use std::time::Instant;

#[derive(Clone, Copy)]
enum Scenario {
    PathEdges,
    ShaPathEdges,
    ShaPathEdgesOracle,
    DiGraphDegreeLookupAb,
    IsWeightedEdgeScanAb,
}

struct Args {
    scenario: Scenario,
    n: usize,
    iters: usize,
    samples: usize,
}

fn make_labels(n: usize) -> Vec<String> {
    (0..n).map(|node| node.to_string()).collect()
}

fn graph_with_nodes(labels: &[String]) -> Graph {
    let mut graph = Graph::new(CompatibilityMode::Strict);
    for label in labels {
        graph.add_node(label.clone());
    }
    graph
}

fn build_current_path_graph(n: usize) -> Graph {
    let labels = make_labels(n);
    let mut graph = graph_with_nodes(&labels);
    let _ = graph.extend_edges_unrecorded(
        labels
            .iter()
            .zip(labels.iter().skip(1))
            .map(|(left, right)| (left.as_str(), right.as_str())),
    );
    graph
}

fn build_oracle_path_graph(n: usize) -> Graph {
    let labels = make_labels(n);
    let mut graph = graph_with_nodes(&labels);
    for (left, right) in labels.iter().zip(labels.iter().skip(1)) {
        graph
            .add_edge(left.clone(), right.clone())
            .expect("path edge should be valid");
    }
    graph
}

fn checksum_graph(graph: &Graph) -> u64 {
    let mut hasher = DefaultHasher::new();
    graph.nodes_ordered().hash(&mut hasher);
    for (left, right, attrs) in graph.edges_ordered_borrowed() {
        left.hash(&mut hasher);
        right.hash(&mut hasher);
        format!("{attrs:?}").hash(&mut hasher);
    }
    hasher.finish()
}

fn canonical_graph_text(graph: &Graph) -> String {
    let mut output = String::new();
    output.push_str("nodes\n");
    for node in graph.nodes_ordered() {
        output.push_str(node);
        output.push('\n');
    }
    output.push_str("edges\n");
    for (left, right, attrs) in graph.edges_ordered_borrowed() {
        output.push_str(left);
        output.push('\t');
        output.push_str(right);
        output.push('\t');
        output.push_str(&format!("{attrs:?}"));
        output.push('\n');
    }
    output
}

fn sha256_text(text: &str) -> String {
    let mut child = Command::new("sha256sum")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .expect("sha256sum should start");
    child
        .stdin
        .as_mut()
        .expect("sha256sum stdin should be open")
        .write_all(text.as_bytes())
        .expect("sha256sum stdin should accept graph text");
    let output = child.wait_with_output().expect("sha256sum should finish");
    assert!(output.status.success(), "sha256sum failed");
    String::from_utf8(output.stdout)
        .expect("sha256sum output should be utf8")
        .split_whitespace()
        .next()
        .expect("sha256sum output should contain digest")
        .to_owned()
}

fn run_path_edges(args: &Args) {
    let mut last_nodes = 0usize;
    let mut last_edges = 0usize;
    let mut last_checksum = 0u64;

    for sample in 0..args.samples {
        let started = Instant::now();
        for _ in 0..args.iters {
            let graph = build_current_path_graph(args.n);
            last_nodes = graph.node_count();
            last_edges = graph.edge_count();
            last_checksum = checksum_graph(&graph);
        }
        let elapsed = started.elapsed().as_secs_f64() * 1000.0;
        println!(
            "{{\"scenario\":\"path-edges\",\"sample\":{sample},\"n\":{},\"iters\":{},\"elapsed_ms\":{elapsed:.6},\"nodes\":{last_nodes},\"edges\":{last_edges},\"checksum\":\"{last_checksum:016x}\"}}",
            args.n, args.iters
        );
    }
}

fn print_sha(args: &Args, oracle: bool) {
    let graph = if oracle {
        build_oracle_path_graph(args.n)
    } else {
        build_current_path_graph(args.n)
    };
    let text = canonical_graph_text(&graph);
    println!(
        "{{\"scenario\":\"{}\",\"n\":{},\"nodes\":{},\"edges\":{},\"bytes\":{},\"sha256\":\"{}\"}}",
        if oracle {
            "sha-path-edges-oracle"
        } else {
            "sha-path-edges"
        },
        args.n,
        graph.node_count(),
        graph.edge_count(),
        text.len(),
        sha256_text(&text)
    );
}

fn build_degree_graph(n: usize) -> (DiGraph, Vec<String>) {
    assert!(n >= 3, "degree A/B requires at least three nodes");
    let labels = (0..n)
        .map(|node| format!("node-{node:08}-degree-probe"))
        .collect::<Vec<_>>();
    let mut graph = DiGraph::strict();
    for label in &labels {
        graph.add_node(label.clone());
    }
    for node in 0..n {
        graph
            .add_edge(labels[node].clone(), labels[(node + 1) % n].clone())
            .expect("cycle edge should be valid");
        if node % 17 == 0 {
            graph
                .add_edge(labels[node].clone(), labels[(node + 13) % n].clone())
                .expect("chord edge should be valid");
        }
    }
    graph
        .add_edge(labels[n / 2].clone(), labels[n / 2].clone())
        .expect("self-loop should be valid");
    (graph, labels)
}

fn time_degree_route(
    graph: &DiGraph,
    labels: &[String],
    iters: usize,
    frozen_two_lookup: bool,
) -> (f64, usize) {
    let started = Instant::now();
    let mut checksum = 0usize;
    for _ in 0..iters {
        for label in labels {
            let node = black_box(label.as_str());
            let degree = if frozen_two_lookup {
                graph.in_degree(node) + graph.out_degree(node)
            } else {
                graph.degree(node)
            };
            checksum = checksum.wrapping_add(black_box(degree));
        }
    }
    (started.elapsed().as_secs_f64() * 1_000_000.0, checksum)
}

fn median(values: &mut [f64]) -> f64 {
    values.sort_by(f64::total_cmp);
    values[values.len() / 2]
}

fn run_digraph_degree_lookup_ab(args: &Args) {
    let (graph, labels) = build_degree_graph(args.n);
    for label in &labels {
        assert_eq!(
            graph.degree(label),
            graph.in_degree(label) + graph.out_degree(label)
        );
    }
    assert_eq!(graph.degree("missing-node"), 0);
    assert_eq!(
        graph.in_degree("missing-node") + graph.out_degree("missing-node"),
        0
    );

    let mut speedups = Vec::with_capacity(args.samples);
    let mut null_ratios = Vec::with_capacity(args.samples);
    let mut candidate_wins = 0usize;
    let mut checksum = None;

    for sample in 0..args.samples {
        let ((candidate_us, candidate_sum), (reference_us, reference_sum)) = if sample % 2 == 0 {
            (
                time_degree_route(&graph, &labels, args.iters, false),
                time_degree_route(&graph, &labels, args.iters, true),
            )
        } else {
            let reference = time_degree_route(&graph, &labels, args.iters, true);
            let candidate = time_degree_route(&graph, &labels, args.iters, false);
            (candidate, reference)
        };
        let (null_a_us, null_a_sum) = time_degree_route(&graph, &labels, args.iters, false);
        let (null_b_us, null_b_sum) = time_degree_route(&graph, &labels, args.iters, false);
        assert_eq!(candidate_sum, reference_sum);
        assert_eq!(candidate_sum, null_a_sum);
        assert_eq!(candidate_sum, null_b_sum);
        checksum = Some(candidate_sum);
        candidate_wins += usize::from(candidate_us < reference_us);
        speedups.push(reference_us / candidate_us);
        null_ratios.push(null_a_us / null_b_us);
        println!(
            "{{\"scenario\":\"digraph-degree-lookup-ab\",\"sample\":{sample},\"n\":{},\"iters\":{},\"candidate_us\":{candidate_us:.3},\"reference_us\":{reference_us:.3},\"speedup\":{:.6},\"null_ratio\":{:.6},\"checksum\":{candidate_sum}}}",
            args.n,
            args.iters,
            reference_us / candidate_us,
            null_a_us / null_b_us
        );
    }

    println!(
        "{{\"scenario\":\"digraph-degree-lookup-summary\",\"samples\":{},\"candidate_wins\":{candidate_wins},\"median_speedup\":{:.6},\"median_null_ratio\":{:.6},\"checksum\":{}}}",
        args.samples,
        median(&mut speedups),
        median(&mut null_ratios),
        checksum.expect("at least one sample is required")
    );
}

fn weighted_attrs() -> AttrMap {
    let mut attrs = AttrMap::new();
    attrs.insert("weight".to_owned(), CgseValue::from(1_i64));
    attrs
}

fn build_weighted_scan_graph(n: usize) -> Graph {
    assert!(n > 16, "weighted scan A/B requires more than 16 nodes");
    let labels = (0..n)
        .map(|node| format!("node-{node:08}-weighted-predicate"))
        .collect::<Vec<_>>();
    let mut graph = graph_with_nodes(&labels);
    let mut edges = Vec::with_capacity(n * 8 + 1);
    for node in 0..n {
        for offset in 1..=8 {
            edges.push((
                labels[node].clone(),
                labels[(node + offset) % n].clone(),
                weighted_attrs(),
            ));
        }
    }
    edges.push((
        labels[n / 2].clone(),
        labels[n / 2].clone(),
        weighted_attrs(),
    ));
    let inserted = graph.extend_edges_with_attrs_unrecorded(edges);
    assert_eq!(inserted, n * 8 + 1);
    graph
}

fn is_weighted_frozen_adjacency(graph: &Graph, weight_attr: &str) -> bool {
    let nodes = graph.nodes_ordered();
    let mut has_edges = false;
    for &left in &nodes {
        if let Some(neighbors) = graph.neighbors_iter(left) {
            for right in neighbors {
                has_edges = true;
                if graph
                    .edge_attrs(left, right)
                    .and_then(|attrs| attrs.get(weight_attr))
                    .is_none()
                {
                    return false;
                }
            }
        }
    }
    has_edges
}

fn is_weighted_direct_storage(graph: &Graph, weight_attr: &str) -> bool {
    let mut has_edges = false;
    for (_, _, attrs) in graph.edges_storage_order_index_iter() {
        has_edges = true;
        if !attrs.contains_key(weight_attr) {
            return false;
        }
    }
    has_edges
}

fn time_is_weighted_route(graph: &Graph, iters: usize, frozen_adjacency: bool) -> (f64, usize) {
    let started = Instant::now();
    let mut checksum = 0usize;
    for _ in 0..iters {
        let weighted = if frozen_adjacency {
            is_weighted_frozen_adjacency(graph, black_box("weight"))
        } else {
            is_weighted_direct_storage(graph, black_box("weight"))
        };
        checksum = checksum.wrapping_add(usize::from(black_box(weighted)));
    }
    (started.elapsed().as_secs_f64() * 1_000_000.0, checksum)
}

fn run_is_weighted_edge_scan_ab(args: &Args) {
    let graph = build_weighted_scan_graph(args.n);
    assert!(is_weighted_frozen_adjacency(&graph, "weight"));
    assert!(is_weighted_direct_storage(&graph, "weight"));
    assert!(!is_weighted_frozen_adjacency(&graph, "missing"));
    assert!(!is_weighted_direct_storage(&graph, "missing"));
    let empty = Graph::strict();
    assert_eq!(
        is_weighted_frozen_adjacency(&empty, "weight"),
        is_weighted_direct_storage(&empty, "weight")
    );

    let mut speedups = Vec::with_capacity(args.samples);
    let mut null_ratios = Vec::with_capacity(args.samples);
    let mut candidate_wins = 0usize;
    let mut checksum = None;

    for sample in 0..args.samples {
        let ((candidate_us, candidate_sum), (reference_us, reference_sum)) = if sample % 2 == 0 {
            (
                time_is_weighted_route(&graph, args.iters, false),
                time_is_weighted_route(&graph, args.iters, true),
            )
        } else {
            let reference = time_is_weighted_route(&graph, args.iters, true);
            let candidate = time_is_weighted_route(&graph, args.iters, false);
            (candidate, reference)
        };
        let (null_a_us, null_a_sum) = time_is_weighted_route(&graph, args.iters, false);
        let (null_b_us, null_b_sum) = time_is_weighted_route(&graph, args.iters, false);
        assert_eq!(candidate_sum, reference_sum);
        assert_eq!(candidate_sum, null_a_sum);
        assert_eq!(candidate_sum, null_b_sum);
        checksum = Some(candidate_sum);
        candidate_wins += usize::from(candidate_us < reference_us);
        speedups.push(reference_us / candidate_us);
        null_ratios.push(null_a_us / null_b_us);
        println!(
            "{{\"scenario\":\"is-weighted-edge-scan-ab\",\"sample\":{sample},\"n\":{},\"m\":{},\"iters\":{},\"candidate_us\":{candidate_us:.3},\"reference_us\":{reference_us:.3},\"speedup\":{:.6},\"null_ratio\":{:.6},\"checksum\":{candidate_sum}}}",
            args.n,
            graph.edge_count(),
            args.iters,
            reference_us / candidate_us,
            null_a_us / null_b_us
        );
    }

    println!(
        "{{\"scenario\":\"is-weighted-edge-scan-summary\",\"samples\":{},\"candidate_wins\":{candidate_wins},\"median_speedup\":{:.6},\"median_null_ratio\":{:.6},\"checksum\":{}}}",
        args.samples,
        median(&mut speedups),
        median(&mut null_ratios),
        checksum.expect("at least one sample is required")
    );
}

fn parse_args() -> Args {
    let mut args = Args {
        scenario: Scenario::PathEdges,
        n: 100_000,
        iters: 3,
        samples: 5,
    };

    for raw in env::args().skip(1) {
        let Some((key, value)) = raw.split_once('=') else {
            continue;
        };
        match key {
            "--scenario" => {
                args.scenario = match value {
                    "path-edges" => Scenario::PathEdges,
                    "sha-path-edges" => Scenario::ShaPathEdges,
                    "sha-path-edges-oracle" => Scenario::ShaPathEdgesOracle,
                    "digraph-degree-lookup-ab" => Scenario::DiGraphDegreeLookupAb,
                    "is-weighted-edge-scan-ab" => Scenario::IsWeightedEdgeScanAb,
                    other => {
                        eprintln!("unknown scenario {other}");
                        exit(2);
                    }
                };
            }
            "--n" => args.n = value.parse().expect("--n must be a usize"),
            "--iters" => args.iters = value.parse().expect("--iters must be a usize"),
            "--samples" => args.samples = value.parse().expect("--samples must be a usize"),
            _ => {}
        }
    }
    args
}

fn main() {
    let args = parse_args();
    match args.scenario {
        Scenario::PathEdges => run_path_edges(&args),
        Scenario::ShaPathEdges => print_sha(&args, false),
        Scenario::ShaPathEdgesOracle => print_sha(&args, true),
        Scenario::DiGraphDegreeLookupAb => run_digraph_degree_lookup_ab(&args),
        Scenario::IsWeightedEdgeScanAb => run_is_weighted_edge_scan_ab(&args),
    }
}