labstream-proto 0.2.0

The LSL protocol state machines. No input and no output.
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
451
452
453
454
455
456
457
458
//! Test the transcripts.
//!
//! A transcript corpus that replays perfectly proves nothing on its own. This
//! file holds deliberate defects in the negotiation. Each one must break at
//! least one transcript.
//!
//! A defect that no transcript catches means the corpus has a hole. The fix is
//! then a new transcript and not a weaker assertion.
//!
//! The same shape as `crates/labstream-wire/tests/mutants.rs`, applied to a state
//! machine instead of a codec.

use labstream_proto::header::{parse_block, Headers, StatusLine};
use labstream_proto::negotiate::{
    can_convert_endian, Accepted, FeedRequest, Outcome, ServerStream, LITTLE,
};
use labstream_wire::Format;
use serde_json::Value as J;
use std::path::Path;

const SERVER_ENDIAN_PERFORMANCE: f64 = 1.0;

fn load() -> Vec<J> {
    let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/transcripts");
    let mut paths: Vec<_> = match std::fs::read_dir(&dir) {
        Ok(e) => e
            .filter_map(|x| x.ok())
            .map(|x| x.path())
            .filter(|p| p.extension().is_some_and(|x| x == "json"))
            .collect(),
        Err(_) => return Vec::new(),
    };
    paths.sort();
    paths
        .iter()
        .map(|p| serde_json::from_str(&std::fs::read_to_string(p).unwrap()).unwrap())
        .collect()
}

fn format_of(name: &str) -> Format {
    match name {
        "float32" => Format::Float32,
        "double64" => Format::Double64,
        "string" => Format::String,
        "int32" => Format::Int32,
        "int16" => Format::Int16,
        "int8" => Format::Int8,
        "int64" => Format::Int64,
        o => panic!("unknown format {o}"),
    }
}

fn split_request(raw: &str) -> (i32, String, Headers) {
    let nl = raw.find('\n').expect("a request line");
    let line = raw[..nl].trim_end_matches('\r');
    let head = line
        .strip_prefix("LSL:streamfeed/")
        .expect("a feed request");
    let mut parts = head.splitn(2, ' ');
    let version: i32 = parts.next().unwrap().parse().unwrap();
    let uid = parts.next().unwrap_or("").trim().to_string();
    let (headers, _) = parse_block(&raw.as_bytes()[nl + 1..]).expect("a header block");
    (version, uid, headers)
}

/// A negotiation with a named defect.
///
/// Every mutant is a copy of the real function with one rule changed. Writing
/// them out in full keeps each defect visible in one place.
type Negotiator = fn(&FeedRequest, &ServerStream) -> Outcome;

struct Mutant {
    name: &'static str,
    why: &'static str,
    run: Negotiator,
}

fn refuse(version: i32, code: i32, message: &str) -> Outcome {
    Outcome::Refuse(StatusLine {
        version,
        code,
        message: message.to_string(),
    })
}

/// The shape that every mutant follows. The flags turn single rules off.
#[allow(clippy::too_many_arguments)]
fn negotiate_with(
    req: &FeedRequest,
    srv: &ServerStream,
    check_version: bool,
    check_uid: bool,
    version_pick_max: bool,
    downgrade_value_size: bool,
    downgrade_ieee: bool,
    swap_condition: fn(&FeedRequest, &ServerStream) -> bool,
    suppress_ignores_format: bool,
    version_code: i32,
    uid_code: i32,
) -> Outcome {
    if check_version && req.request_version / 100 > srv.configured_version / 100 {
        return refuse(
            srv.configured_version,
            version_code,
            "Version not supported",
        );
    }
    if check_uid && !req.request_uid.is_empty() && req.request_uid != srv.uid {
        return refuse(srv.configured_version, uid_code, "Not found");
    }
    if req.request_version < 110 {
        return Outcome::Accept(Accepted {
            data_protocol_version: 100,
            byte_order: srv.native_byte_order,
            reverse_byte_order: false,
            suppress_subnormals: false,
            max_buffer_length: req.max_buffer_length,
            max_chunk_length: req.max_chunk_length,
        });
    }

    let mut version = if version_pick_max {
        srv.configured_version.max(req.protocol_version)
    } else {
        srv.configured_version.min(req.protocol_version)
    };
    if downgrade_value_size && srv.format != Format::String && srv.channel_bytes != req.value_size {
        version = 100;
    }
    if downgrade_ieee && !req.has_ieee754_floats {
        version = 100;
    }

    let mut byte_order = srv.native_byte_order;
    let mut reverse = false;
    let mut suppress = false;
    if version >= 110 {
        if swap_condition(req, srv) {
            byte_order = req.native_byte_order;
            reverse = true;
        }
        suppress = (suppress_ignores_format || srv.format.is_float()) && !req.supports_subnormals;
    }

    Outcome::Accept(Accepted {
        data_protocol_version: version,
        byte_order,
        reverse_byte_order: reverse,
        suppress_subnormals: suppress,
        max_buffer_length: req.max_buffer_length,
        max_chunk_length: req.max_chunk_length,
    })
}

fn real_swap(req: &FeedRequest, srv: &ServerStream) -> bool {
    srv.native_byte_order != req.native_byte_order
        && can_convert_endian(req.native_byte_order, req.value_size)
        && req.value_size > 1
        && srv.endian_performance > req.endian_performance
}

const MUTANTS: &[Mutant] = &[
    Mutant {
        name: "version_picks_the_higher",
        why: "takes the larger of the two versions instead of the smaller",
        run: |r, s| {
            negotiate_with(
                r, s, true, true, true, true, true, real_swap, false, 505, 404,
            )
        },
    },
    Mutant {
        name: "no_value_size_downgrade",
        why: "keeps 1.10 when the client value size differs from the channel width",
        run: |r, s| {
            negotiate_with(
                r, s, true, true, false, false, true, real_swap, false, 505, 404,
            )
        },
    },
    Mutant {
        name: "no_ieee754_downgrade",
        why: "keeps 1.10 when the client reports no IEEE-754 floats",
        run: |r, s| {
            negotiate_with(
                r, s, true, true, false, true, false, real_swap, false, 505, 404,
            )
        },
    },
    Mutant {
        name: "swaps_when_slower",
        why: "reverses the speed contest, so the slower side converts",
        run: |r, s| {
            negotiate_with(
                r,
                s,
                true,
                true,
                false,
                true,
                true,
                |q, v| {
                    v.native_byte_order != q.native_byte_order
                        && can_convert_endian(q.native_byte_order, q.value_size)
                        && q.value_size > 1
                        && v.endian_performance < q.endian_performance
                },
                false,
                505,
                404,
            )
        },
    },
    Mutant {
        name: "swaps_a_one_byte_value",
        why: "drops condition 3, so a one-byte format swaps",
        run: |r, s| {
            negotiate_with(
                r,
                s,
                true,
                true,
                false,
                true,
                true,
                |q, v| {
                    v.native_byte_order != q.native_byte_order
                        && can_convert_endian(q.native_byte_order, q.value_size)
                        && v.endian_performance > q.endian_performance
                },
                false,
                505,
                404,
            )
        },
    },
    Mutant {
        name: "accepts_any_byte_order",
        why: "drops the conversion test, so an unknown order still swaps",
        run: |r, s| {
            negotiate_with(
                r,
                s,
                true,
                true,
                false,
                true,
                true,
                |q, v| {
                    v.native_byte_order != q.native_byte_order
                        && q.value_size > 1
                        && v.endian_performance > q.endian_performance
                },
                false,
                505,
                404,
            )
        },
    },
    Mutant {
        name: "suppresses_for_every_format",
        why: "clears subnormal values for an integer format, which holds none",
        run: |r, s| {
            negotiate_with(
                r, s, true, true, false, true, true, real_swap, true, 505, 404,
            )
        },
    },
    Mutant {
        name: "skips_the_version_test",
        why: "accepts a newer major version instead of answering 505",
        run: |r, s| {
            negotiate_with(
                r, s, false, true, false, true, true, real_swap, false, 505, 404,
            )
        },
    },
    Mutant {
        name: "skips_the_uid_test",
        why: "accepts a UID that names another stream instead of answering 404",
        run: |r, s| {
            negotiate_with(
                r, s, true, false, false, true, true, real_swap, false, 505, 404,
            )
        },
    },
    Mutant {
        name: "wrong_code_for_a_new_version",
        why: "answers 400 instead of 505",
        run: |r, s| {
            negotiate_with(
                r, s, true, true, false, true, true, real_swap, false, 400, 404,
            )
        },
    },
    Mutant {
        name: "wrong_code_for_a_bad_uid",
        why: "answers 400 instead of 404, which changes what the client does",
        run: |r, s| {
            negotiate_with(
                r, s, true, true, false, true, true, real_swap, false, 505, 400,
            )
        },
    },
];

/// A defect that lives in the header reader and not in the negotiation.
///
/// The server reads `Protocol-Version`. A reimplementation that reads
/// `Data-Protocol-Version` instead looks correct in the source of the client.
/// SPEC.md 4.4.
fn request_reading_the_dead_header(
    version: i32,
    uid: &str,
    h: &Headers,
    bytes: i32,
) -> FeedRequest {
    let mut r = FeedRequest::from_headers(version, uid, h, bytes);
    r.protocol_version = h.get_int("data-protocol-version").unwrap_or(version as i64) as i32;
    r
}

fn answer_of(o: Outcome, srv: &ServerStream) -> String {
    match o {
        Outcome::Refuse(s) => s.to_wire(),
        Outcome::Accept(a) => a.to_wire(srv.configured_version, &srv.uid),
    }
}

fn server_for(t: &J) -> ServerStream {
    let format = format_of(t["format"].as_str().unwrap());
    let mut srv = ServerStream::new(
        t["stream_uid"].as_str().unwrap(),
        format,
        LITTLE,
        SERVER_ENDIAN_PERFORMANCE,
    );
    if format == Format::String {
        srv.channel_bytes = 0;
    }
    srv
}

#[test]
fn every_mutant_is_caught_by_at_least_one_transcript() {
    let all = load();
    if all.is_empty() {
        eprintln!("no transcripts; skipping. Run oracle/recordtranscripts.py first.");
        return;
    }

    let mut uncaught = Vec::new();
    let mut report = Vec::new();

    for m in MUTANTS {
        let mut caught = 0usize;
        let mut first = None;
        for t in &all {
            let srv = server_for(t);
            let (version, uid, headers) = split_request(t["request"].as_str().unwrap());
            let req = FeedRequest::from_headers(version, &uid, &headers, srv.channel_bytes);
            let ours = answer_of((m.run)(&req, &srv), &srv);
            let oracle = t["answer"].as_str().unwrap();
            if ours.trim() != oracle.trim() {
                caught += 1;
                if first.is_none() {
                    first = t["case"].as_str();
                }
            }
        }
        if caught == 0 {
            uncaught.push(format!("{}: {}", m.name, m.why));
        }
        report.push(format!(
            "  {:32} caught by {:2}/{} transcripts  first: {}",
            m.name,
            caught,
            all.len(),
            first.unwrap_or("-")
        ));
    }

    // The dead header defect lives in the reader, so it needs its own pass.
    {
        let mut caught = 0usize;
        let mut first = None;
        for t in &all {
            let srv = server_for(t);
            let (version, uid, headers) = split_request(t["request"].as_str().unwrap());
            let req = request_reading_the_dead_header(version, &uid, &headers, srv.channel_bytes);
            let ours = answer_of(labstream_proto::negotiate(&req, &srv), &srv);
            if ours.trim() != t["answer"].as_str().unwrap().trim() {
                caught += 1;
                if first.is_none() {
                    first = t["case"].as_str();
                }
            }
        }
        if caught == 0 {
            uncaught.push(
                "reads_data_protocol_version: reads the header that liblsl ignores".to_string(),
            );
        }
        report.push(format!(
            "  {:32} caught by {:2}/{} transcripts  first: {}",
            "reads_data_protocol_version",
            caught,
            all.len(),
            first.unwrap_or("-")
        ));
    }

    println!("mutation report over {} transcripts:", all.len());
    for line in &report {
        println!("{line}");
    }

    assert!(
        uncaught.is_empty(),
        "these defects slipped past every transcript. The corpus has a hole, \
         and the fix is a new transcript.\n  {}",
        uncaught.join("\n  ")
    );
}

/// The control. The real negotiation must match every transcript.
///
/// Without this, a report of "everything caught" also appears when the loader
/// is broken and every comparison differs.
#[test]
fn the_real_negotiation_is_not_caught() {
    let all = load();
    if all.is_empty() {
        return;
    }
    for t in &all {
        let srv = server_for(t);
        let (version, uid, headers) = split_request(t["request"].as_str().unwrap());
        let req = FeedRequest::from_headers(version, &uid, &headers, srv.channel_bytes);
        let ours = answer_of(labstream_proto::negotiate(&req, &srv), &srv);
        let oracle = t["answer"].as_str().unwrap();
        // The UID differs per run, and the answer carries it. Compare the
        // lines that hold no UID.
        let strip = |s: &str| {
            s.split("\r\n")
                .filter(|l| !l.to_ascii_lowercase().starts_with("uid:"))
                .collect::<Vec<_>>()
                .join("\r\n")
        };
        assert_eq!(
            strip(&ours).trim(),
            strip(oracle).trim(),
            "{}: the real negotiation differs from the oracle",
            t["case"].as_str().unwrap()
        );
    }
    println!("the real negotiation matches all {} transcripts", all.len());
}