SPB Git

Repository Public

fuzz.rs 14.6 KB 463 lines rust

1//! ORIX Sonata2//! File: crates/sonata-compiler/tests/fuzz.rs3//! Description: Seeded fuzzing of the whole frontend: random bytes, token soup and mutated4//! valid programs go through lexing, parsing, formatting, compilation and the language5//! services. Nothing may panic, hang or produce an invalid artefact. Runs off the audio path.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use sonata_compiler::services::{highlight, Services};11use sonata_compiler::{compile, format, CompileOptions, DirLoader, NoLoader, Quotas};12use std::path::Path;13use std::time::{Duration, Instant};1415struct Rng(u64);16impl Rng {17    fn next(&mut self) -> u64 {18        self.0 ^= self.0 << 13;19        self.0 ^= self.0 >> 7;20        self.0 ^= self.0 << 17;21        self.022    }23    fn below(&mut self, n: usize) -> usize {24        if n == 0 {25            026        } else {27            (self.next() % n as u64) as usize28        }29    }30    fn pick<'a>(&mut self, items: &[&'a str]) -> &'a str {31        items[self.below(items.len())]32    }33}3435const VOCABULARY: &[&str] = &[36    "composition",37    "\"t\"",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    "\n",64    "\n",65    "\n",66    "instrument",67    "audio",68    "bus",69    "master",70    "play",71    "chord",72    "rest",73    "sequence",74    "voice",75    "parallel",76    "at",77    "repeat",78    "for",79    "in",80    "if",81    "then",82    "else",83    "tuplet",84    "transpose",85    "swing",86    "tempo",87    "key",88    "signature",89    "seed",90    "tuning",91    "marker",92    "effects",93    "automate",94    "send",95    "default",96    "graph",97    "node",98    "out",99    "model",100    "preset",101    "import",102    "const",103    "let",104    "fn",105    "pattern",106    "return",107    "true",108    "false",109    "and",110    "or",111    "not",112    "duration",113    "velocity",114    "tie",115    "bend",116    "staccato",117    "legato",118    "gain",119    "pan",120    "mute",121    "solo",122    "output",123    "clip",124    "D4",125    "F#3",126    "Bb2",127    "C-1",128    "D",129    "Bb",130    "120bpm",131    "-8dB",132    "48000Hz",133    "5ms",134    "2s",135    "7st",136    "25cents",137    "60%",138    "2bars",139    "1beat",140    "1/4",141    "3/8",142    "0.75",143    "42",144    "0",145    "x",146    "y",147    "root",148    "GrandPiano",149    "Kick",150    "piano",151    "synth",152    "patch",153    "reverb",154    "hall",155    "delay",156    "mix",157    "scale",158    "chord",159    "minor",160    "random",161    "choose",162    "len",163    "note",164    "freq",165    "saw",166    "adsr",167    "lowpass",168    "std",169    "music",170    "Pitch",171    "Number",172    "Duration",173    "List",174    "é",175    "𝄞",176    "\"open",177    "/*",178    "*/",179    "//",180    "@",181    "#",182    "\t",183    "999999999999999999999",184];185186/// Small quotas keep every input fast while still exercising the limits.187fn options() -> CompileOptions {188    CompileOptions { quotas: Quotas { max_events: 5_000, max_steps: 100_000, max_list_len: 2_000, ..Quotas::default() }, ..CompileOptions::default() }189}190191/// Everything the frontend can do with one input. Returns the time it took.192fn exercise(source: &str, rng: &mut Rng, with_services: bool) -> Duration {193    let started = Instant::now();194    let out = compile("fuzz.sonata", source, &NoLoader, &options());195    // Invariants of a result.196    for d in out.diagnostics.iter() {197        if d.span.file == 0 {198            assert!(199                d.span.start <= d.span.end && d.span.end as usize <= source.len(),200                "diagnostic span {:?} outside the source ({} bytes): {}",201                d.span,202                source.len(),203                d.message204            );205            assert!(206                source.is_char_boundary(d.span.start as usize) && source.is_char_boundary(d.span.end as usize),207                "diagnostic span {:?} splits a character: {}",208                d.span,209                d.message210            );211        }212        assert!(!d.code.is_empty() && !d.message.is_empty());213        if let Some(fix) = &d.fix {214            assert!(fix.span.end as usize <= out.sources.file(fix.span.file).map(|f| f.text.len()).unwrap_or(0));215        }216    }217    let _ = out.render_diagnostics();218    let _ = out.diagnostics_json();219    match (&out.program, &out.graph) {220        (Some(program), Some(graph)) => {221            assert!(!out.has_errors());222            graph.validate().unwrap();223            program.tempo_map.validate().unwrap();224            for t in &program.tracks {225                for n in &t.notes {226                    assert!(227                        n.start_sec.is_finite()228                            && n.end_sec.is_finite()229                            && n.end_sec >= n.start_sec230                            && n.pitch.is_finite()231                            && (0.0..=1.0).contains(&n.velocity)232                    );233                }234                assert!(t.notes.windows(2).all(|w| w[0].start <= w[1].start), "notes are sorted");235                if let Some(patch) = t.instrument.as_ref().and_then(|i| i.patch.as_ref()) {236                    patch.validate().unwrap();237                }238            }239        }240        (None, None) => {}241        (Some(_), None) => panic!("a program without a graph"),242        (None, Some(_)) => panic!("a graph without a program"),243    }244    if let Ok(formatted) = format(source) {245        let again = format(&formatted).expect("formatted source parses");246        assert_eq!(again, formatted, "formatter is not idempotent on:\n{source}");247    }248    let mut end = 0;249    for (start, len, _) in highlight(source) {250        assert!(start >= end && source.is_char_boundary(start as usize));251        end = start + len;252    }253    if with_services {254        let services = Services::new();255        let mut offset = rng.below(source.len() + 1);256        while !source.is_char_boundary(offset) {257            offset -= 1;258        }259        let offset = offset as u32;260        let _ = services.completions("fuzz.sonata", source, offset, &NoLoader);261        let _ = services.hover("fuzz.sonata", source, offset, &NoLoader);262        let _ = services.definition("fuzz.sonata", source, offset, &NoLoader);263        let _ = services.references("fuzz.sonata", source, offset, &NoLoader);264        let _ = services.signature_help("fuzz.sonata", source, offset, &NoLoader);265        let _ = services.document_symbols("fuzz.sonata", source, &NoLoader);266    }267    started.elapsed()268}269270fn check_time(elapsed: Duration, source: &str) {271    assert!(elapsed < Duration::from_secs(5), "one input took {elapsed:?}:\n{source}");272}273274#[test]275fn random_bytes_never_panic() {276    let mut rng = Rng(0x5EED_0001);277    for _ in 0..1500 {278        let len = rng.below(200);279        let bytes: Vec<u8> = (0..len).map(|_| (rng.next() >> 16) as u8).collect();280        let (text, lexed) = sonata_lexer::lex_bytes(&bytes, 0);281        assert!(matches!(lexed.tokens.last().map(|t| &t.kind), Some(sonata_lexer::TokenKind::Eof)));282        let t = exercise(&text, &mut rng, false);283        check_time(t, &text);284    }285}286287#[test]288fn token_soup_never_panics() {289    let mut rng = Rng(0x5EED_0002);290    for i in 0..2500 {291        let len = 1 + rng.below(90);292        let mut src = String::new();293        for _ in 0..len {294            src.push_str(rng.pick(VOCABULARY));295            if rng.below(8) != 0 {296                src.push(' ');297            }298        }299        let t = exercise(&src, &mut rng, i % 10 == 0);300        check_time(t, &src);301    }302}303304#[test]305fn plausible_programs_never_panic() {306    // Structured soup: a valid skeleton with random statements, far more likely to reach the307    // evaluator, the instrument builder and the graph builder than raw token soup.308    let statements = [309        "play D4 duration 1/4",310        "chord [D3, A3, D4] duration 1/2",311        "rest 1/4",312        "repeat 3 { play x }",313        "let x = D4",314        "x = x + 2st",315        "for n in scale(D4, minor) { play n duration 1/8 }",316        "tuplet 3 in 2 { play D4 duration 1/8 }",317        "transpose 12st { play D4 }",318        "swing 60%",319        "tempo 90bpm",320        "tempo 60bpm ramp 1bar",321        "signature 3/4",322        "at 2bars { play A4 }",323        "voice { play D5 }",324        "parallel { play D4; play F4 }",325        "gain -6dB",326        "pan 0.3",327        "mute",328        "solo",329        "effects { reverb hall(mix: 0.2) }",330        "effects { delay(time: 1/8) }",331        "automate gain { 0bars: -6dB, 1bar: 0dB }",332        "send hall -6dB",333        "output hall",334        "play choose([D4, F4]) velocity random()",335        "play D4 tie",336        "play D4 bend { 0ms: 0st, 9ms: 1st }",337        "if random() > 0.5 { play D4 } else { rest 1/4 }",338        "play midi(60 + random_int(0, 12))",339        "default duration 1/8",340        "articulation staccato",341        "play degree(3)",342        "play x[9]",343        "play 1/0",344        "rest -1/4",345        "play D4 duration 1s",346        "marker \"m\"",347        "play D4 duration 100000bars",348        "repeat 100000 { rest 1/64 }",349        "loop()",350        "arpeggio(chord(D3, min7))",351        "automate reverb.mix { 0bars: 0.5 }",352        "automate instrument.brightness { 0bars: 0.5 }",353    ];354    let types = ["GrandPiano", "Kick", "SynthLead", "Violin", "Marimba", "Own", "Patch", "Missing", "piano"];355    let mut rng = Rng(0x5EED_0003);356    let mut compiled = 0;357    for i in 0..1200 {358        let mut src = String::from("instrument Own { model plucked_string\n damping 0.02 }\ninstrument Patch { model patch\n graph { node o = saw(freq: note.freq)\n node e = adsr()\n out o * e } }\npattern loop() { loop() }\ncomposition \"f\" {\n");359        if rng.below(2) == 0 {360            src.push_str(" key D minor\n seed 5\n bus hall { effects { reverb } }\n");361        }362        for t in 0..1 + rng.below(3) {363            src.push_str(&format!(" instrument t{t}: {} {{\n", rng.pick(&types)));364            for _ in 0..rng.below(8) {365                src.push_str("  ");366                src.push_str(rng.pick(&statements));367                src.push('\n');368            }369            src.push_str(" }\n");370        }371        src.push_str("}\n");372        let out = compile("fuzz.sonata", &src, &NoLoader, &options());373        compiled += usize::from(out.program.is_some());374        let t = exercise(&src, &mut rng, i % 20 == 0);375        check_time(t, &src);376    }377    assert!(compiled > 50, "only {compiled} of 1200 plausible programs compiled: the generator is not reaching the back end");378}379380#[test]381fn mutated_examples_never_panic() {382    let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Examples");383    let mut files: Vec<_> =384        std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok().map(|e| e.path())).filter(|p| p.extension().map(|e| e == "sonata").unwrap_or(false)).collect();385    files.sort();386    let mut rng = Rng(0x5EED_0004);387    let mut total = Duration::ZERO;388    for path in &files {389        let original: Vec<char> = std::fs::read_to_string(path).unwrap().chars().collect();390        for i in 0..60 {391            let mut chars = original.clone();392            for _ in 0..1 + rng.below(3) {393                let at = rng.below(chars.len().max(1));394                match rng.below(6) {395                    0 => {396                        let n = (1 + rng.below(12)).min(chars.len() - at.min(chars.len()));397                        chars.drain(at..(at + n).min(chars.len()));398                    }399                    1 => {400                        let n = 1 + rng.below(40);401                        let piece: Vec<char> = chars[at..(at + n).min(chars.len())].to_vec();402                        let to = rng.below(chars.len().max(1));403                        chars.splice(to..to, piece);404                    }405                    2 => {406                        let token: Vec<char> = format!(" {} ", rng.pick(VOCABULARY)).chars().collect();407                        chars.splice(at..at, token);408                    }409                    3 => {410                        if at < chars.len() {411                            chars[at] = ['{', '}', '(', ')', '"', '\n', '0', '9', '-', '/', ' '][rng.below(11)];412                        }413                    }414                    4 => chars.truncate(at),415                    _ => {416                        // Swap two lines.417                        let text: String = chars.iter().collect();418                        let mut lines: Vec<&str> = text.lines().collect();419                        if lines.len() > 2 {420                            let (a, b) = (rng.below(lines.len()), rng.below(lines.len()));421                            lines.swap(a, b);422                        }423                        chars = lines.join("\n").chars().collect();424                    }425                }426            }427            let src: String = chars.into_iter().collect();428            // Mutants of the module example need its import to resolve.429            let started = Instant::now();430            let _ = compile("fuzz.sonata", &src, &DirLoader::new(&dir), &options());431            total += started.elapsed();432            let t = exercise(&src, &mut rng, i % 6 == 0);433            check_time(t, &src);434            total += t;435        }436    }437    assert!(total < Duration::from_secs(120), "the mutation corpus took {total:?}");438}439440#[test]441fn pathological_nesting_and_recursion_are_bounded() {442    let mut rng = Rng(1);443    // Mutual recursion of patterns through deep blocks, and of functions through deep expressions.444    let blocks = format!("pattern p() {{ {} p() {} }}\ncomposition \"x\" {{ instrument a: GrandPiano {{ p() }} }}", "repeat 1 { ".repeat(60), "}".repeat(60));445    let out = compile("deep.sonata", &blocks, &NoLoader, &CompileOptions::default());446    assert!(out.errors().any(|d| d.code == "Q6003"), "{}", out.render_diagnostics());447    let exprs = format!("fn f(n: Number) -> Number {{ return {}f(n){} }}\ncomposition \"x\" {{ let v = f(1) }}", "(1 + ".repeat(60), ")".repeat(60));448    let out = compile("deep.sonata", &exprs, &NoLoader, &CompileOptions::default());449    assert!(out.errors().any(|d| d.code == "Q6003"), "{}", out.render_diagnostics());450    // The same from a thread with a small stack, as the app and the LSP will call it.451    let handle = std::thread::Builder::new()452        .stack_size(256 * 1024)453        .spawn(move || compile("deep.sonata", &blocks, &NoLoader, &CompileOptions::default()).errors().count())454        .unwrap();455    assert!(handle.join().unwrap() >= 1);456    let deep_parens = format!("const x = {}1{}", "(".repeat(100_000), ")".repeat(100_000));457    let t = exercise(&deep_parens, &mut rng, true);458    check_time(t, "100000 nested parentheses");459    let long_line = format!("composition \"x\" {{ instrument a: GrandPiano {{ play [{}] }} }}", "D4, ".repeat(50_000));460    let t = exercise(&long_line, &mut rng, false);461    check_time(t, "a 50000-note chord");462}463
Files main
Menu

Theme