SPB Git

Repository Public

main.rs 24.2 KB 341 lines rust

1//! Bancs reproductibles SPWEB.2//!3//!   spweb-bench ingest  <dossier> <documents> [positions]   corpus synthétique déterministe -> index ; débit, pic disque, octets/doc4//!   spweb-bench latency <url-search-api> <req/s> <secondes>  latence p50/p95/p99 de /v1/search à débit fixe5//!   spweb-bench shard-latency <dossier> <requêtes>            latence du moteur seul (sans HTTP) sur l'index du banc6//!   spweb-bench quality <dossier>                             NDCG@10, recall@20, MRR sur le corpus jugé FR/EN7//!8//! Tout est déterministe (générateur congruentiel à graine fixe) : deux exécutions donnent le même corpus.910use spweb_common::DocId;11use spweb_indexer::{IndexCfg, IndexNode};12use spweb_protocol::{IndexDoc, IngestStatus, SearchRequest};13use spweb_quota::{Governor, Limits};14use std::path::{Path, PathBuf};15use std::time::{Duration, Instant};1617struct Rng(u64);18impl Rng {19    fn next(&mut self) -> u64 {20        // SplitMix6421        self.0 = self.0.wrapping_add(0x9E3779B97F4A7C15);22        let mut z = self.0;23        z = (z ^ (z >> 30)).wrapping_mul(0xBF58476D1CE4E5B9);24        z = (z ^ (z >> 27)).wrapping_mul(0x94D049BB133111EB);25        z ^ (z >> 31)26    }27    fn f(&mut self) -> f64 {28        (self.next() >> 11) as f64 / (1u64 << 53) as f6429    }30    fn below(&mut self, n: usize) -> usize {31        (self.next() % n as u64) as usize32    }33}3435const SYL: &[&str] = &["ba", "co", "de", "fi", "ga", "lu", "mé", "no", "pi", "ra", "si", "tu", "vo", "ch", "an", "on", "el", "ar", "is", "ou", "tra", "ple", "gri", "sto", "ver", "min", "dor", "ket", "lam", "pur", "qui", "zen"];3637/// Vocabulaire de `n` pseudo-mots prononçables, stables d'une exécution à l'autre.38fn vocabulary(n: usize) -> Vec<String> {39    let mut rng = Rng(42);40    let mut seen = std::collections::HashSet::new();41    let mut v = Vec::with_capacity(n);42    while v.len() < n {43        let k = 2 + rng.below(3);44        let w: String = (0..k).map(|_| SYL[rng.below(SYL.len())]).collect();45        if seen.insert(w.clone()) {46            v.push(w);47        }48    }49    v50}5152/// Tirage zipfien (s ≈ 1) par inversion approchée : rang = exp(u · ln N).53fn zipf(rng: &mut Rng, n: usize) -> usize {54    (((n as f64).ln() * rng.f()).exp() as usize).clamp(1, n) - 155}5657fn limits(q: u64) -> Limits {58    Limits { quota_bytes: q, merge_reserve: q / 5, min_free_ratio: 0.0, min_free_bytes: 0, warn: 0.7, throttle: 0.8, suspend: 0.9, protect: 0.95, resume: 0.75 }59}6061fn open(dir: &Path, positions: bool, shards: u32) -> anyhow::Result<IndexNode> {62    std::fs::create_dir_all(dir)?;63    let q = 200_000_000_000;64    let gov = Governor::new(dir, limits(q), vec![("index".into(), dir.to_path_buf(), q)]);65    IndexNode::open(IndexCfg { dir: dir.to_path_buf(), shard_count: shards, positions, writer_heap_mb: 48, commit_docs: 2000, max_body_terms: 1500, snippet_max_chars: 240, title_max_chars: 160, near_dup_hamming: 3, max_documents: u64::MAX, test_mode: false }, gov)66}6768fn mk(url: &str, title: &str, body: &str, lang: &str, quality: f32, published: Option<i64>) -> IndexDoc {69    let n = spweb_urlnorm::normalize(url, None, Default::default()).expect("url");70    let text = format!("{}\n{}", title.to_lowercase(), body.to_lowercase());71    IndexDoc { doc_id: DocId::from_url(&n.url), url: n.url, domain: n.domain, title: title.into(), snippet: spweb_common::truncate_chars(body, 240), lang: lang.into(), body: body.into(), headings: String::new(), published_at: published, checked_at: spweb_common::now(), content_hash: spweb_common::b64url(&spweb_dedup::content_hash(&text)), simhash: spweb_dedup::simhash(&text), quality, bytes_fetched: 0, store_text: true, snippet_limit: None }72}7374fn ingest(dir: &Path, n: usize, positions: bool) -> anyhow::Result<()> {75    let _ = std::fs::remove_dir_all(dir);76    let node = open(dir, positions, 4)?;77    let vocab = vocabulary(60_000);78    let mut rng = Rng(7);79    let t0 = Instant::now();80    let mut peak = 0u64;81    let mut admitted = 0u64;82    let mut other = 0u64;83    let mut raw_text_bytes = 0u64;84    let mut batch = Vec::with_capacity(100);85    for i in 0..n {86        // Longueur de page réaliste : médiane ~350 mots, longue traîne.87        let words = 80 + (rng.f().powi(3) * 2200.0) as usize + rng.below(300);88        let mut body = String::with_capacity(words * 7);89        for _ in 0..words {90            body.push_str(&vocab[zipf(&mut rng, vocab.len())]);91            body.push(' ');92        }93        let title: String = (0..(4 + rng.below(6))).map(|_| vocab[zipf(&mut rng, vocab.len())].as_str()).collect::<Vec<_>>().join(" ");94        raw_text_bytes += body.len() as u64;95        let dom = zipf(&mut rng, 20_000);96        let url = format!("https://site{}.example/rubrique{}/page-{}", dom, rng.below(40), i);97        batch.push(mk(&url, &title, &body, if i % 3 == 0 { "en" } else { "fr" }, 0.3 + rng.f() as f32 * 0.6, None));98        if batch.len() == 100 || i + 1 == n {99            for a in node.ingest(std::mem::take(&mut batch)) {100                if a.status == IngestStatus::Admitted { admitted += 1 } else { other += 1 }101            }102        }103        if node.pending() >= 2000 {104            node.commit(true)?;105        }106        if i % 5000 == 4999 {107            let used = node.gov.measure().used_bytes;108            peak = peak.max(used);109            eprintln!("  {:>8} documents  {:>6.0} doc/s  {:>7.1} Mo sur disque", i + 1, (i + 1) as f64 / t0.elapsed().as_secs_f64(), used as f64 / 1e6);110        }111    }112    node.commit(true)?;113    let ingest_s = t0.elapsed().as_secs_f64();114    std::thread::sleep(Duration::from_secs(3)); // laisser finir les fusions de fond115    let before = node.gov.measure().used_bytes;116    peak = peak.max(before);117    let tc = Instant::now();118    // Pendant la compaction, l'ancien et le nouveau segment coexistent : on échantillonne le pic.119    let dirc = dir.to_path_buf();120    let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));121    let stop2 = stop.clone();122    let sampler = std::thread::spawn(move || {123        let mut p = 0u64;124        while !stop2.load(std::sync::atomic::Ordering::Relaxed) {125            p = p.max(spweb_quota::allocated_bytes(&dirc));126            std::thread::sleep(Duration::from_millis(200));127        }128        p129    });130    node.compact(None)?;131    stop.store(true, std::sync::atomic::Ordering::Relaxed);132    let peak_merge = sampler.join().unwrap_or(0);133    let compact_s = tc.elapsed().as_secs_f64();134    let after = node.gov.measure().used_bytes;135    let st = node.stats(spweb_common::now());136    println!("{}", serde_json::json!({137        "bench": "ingest", "documents_generated": n, "admitted": admitted, "not_admitted": other, "positions": positions, "shards": 4,138        "ingest_seconds": ingest_s, "docs_per_second": n as f64 / ingest_s,139        "raw_text_bytes": raw_text_bytes, "raw_text_bytes_per_doc": raw_text_bytes / n as u64,140        "disk_bytes_before_compaction": before, "disk_bytes_peak_during_ingest": peak, "disk_bytes_peak_during_compaction": peak_merge,141        "disk_bytes_after_compaction": after, "compaction_seconds": compact_s,142        "bytes_per_doc_after_compaction": after / st.documents.max(1), "bytes_per_doc_peak": peak.max(peak_merge) / st.documents.max(1),143        "index_to_text_ratio": after as f64 / raw_text_bytes as f64, "documents_in_index": st.documents,144        "rss_bytes": rss(),145    }));146    Ok(())147}148149fn rss() -> u64 {150    std::process::Command::new("ps").args(["-o", "rss=", "-p", &std::process::id().to_string()]).output().ok().and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse::<u64>().ok()).map(|k| k * 1024).unwrap_or(0)151}152153fn quantiles(mut v: Vec<f64>) -> (f64, f64, f64, f64) {154    v.sort_by(|a, b| a.partial_cmp(b).unwrap());155    let q = |p: f64| v[((v.len() as f64 * p) as usize).min(v.len() - 1)];156    (q(0.5), q(0.95), q(0.99), *v.last().unwrap())157}158159fn bench_queries(count: usize) -> Vec<String> {160    let vocab = vocabulary(60_000);161    let mut rng = Rng(99);162    (0..count)163        .map(|_| {164            // 1 à 3 termes ; mélange de termes fréquents et rares, comme de vraies requêtes165            let k = 1 + rng.below(3);166            (0..k).map(|_| vocab[zipf(&mut rng, 8000)].clone()).collect::<Vec<_>>().join(" ")167        })168        .collect()169}170171fn shard_latency(dir: &Path, count: usize) -> anyhow::Result<()> {172    let node = open(dir, false, 4)?;173    let qs = bench_queries(count);174    // échauffement175    for q in qs.iter().take(200) {176        let _ = node.search(&SearchRequest { query: spweb_query::parse(q).unwrap(), k: 200, explain: false, relax: true }, Instant::now() + Duration::from_secs(5));177    }178    let mut lat = Vec::with_capacity(count);179    let mut empty = 0;180    for q in &qs {181        let t = Instant::now();182        let r = node.search(&SearchRequest { query: spweb_query::parse(q).unwrap(), k: 200, explain: false, relax: true }, Instant::now() + Duration::from_secs(5));183        lat.push(t.elapsed().as_secs_f64() * 1000.0);184        if r.hits.is_empty() {185            empty += 1;186        }187    }188    let (p50, p95, p99, max) = quantiles(lat);189    println!("{}", serde_json::json!({"bench": "shard-latency", "queries": count, "k": 200, "p50_ms": p50, "p95_ms": p95, "p99_ms": p99, "max_ms": max, "no_results": empty, "documents": node.doc_count()}));190    Ok(())191}192193async fn latency(base: &str, qps: f64, secs: u64) -> anyhow::Result<()> {194    let client = reqwest::Client::builder().timeout(Duration::from_secs(10)).build()?;195    let total = (qps * secs as f64) as usize;196    let qs = bench_queries(total);197    let start = Instant::now();198    let mut handles = Vec::with_capacity(total);199    for (i, q) in qs.into_iter().enumerate() {200        // Débit fixe en boucle ouverte : une requête lente ne retarde pas les suivantes.201        let due = start + Duration::from_secs_f64(i as f64 / qps);202        tokio::time::sleep_until(tokio::time::Instant::from_std(due)).await;203        let c = client.clone();204        let url = format!("{}/v1/search", base);205        handles.push(tokio::spawn(async move {206            let t = Instant::now();207            let enc: String = q.bytes().map(|b| if b.is_ascii_alphanumeric() { (b as char).to_string() } else { format!("%{:02X}", b) }).collect();208            let r = c.get(format!("{}?q={}", url, enc)).send().await;209            let status = match r {210                Ok(resp) => {211                    let s = resp.status().as_u16();212                    let _ = resp.bytes().await;213                    s214                }215                Err(_) => 0,216            };217            (t.elapsed().as_secs_f64() * 1000.0, status)218        }));219    }220    let mut lat = Vec::new();221    let mut errors = std::collections::BTreeMap::new();222    for h in handles {223        let (ms, status) = h.await?;224        if status == 200 {225            lat.push(ms);226        } else {227            *errors.entry(status).or_insert(0u32) += 1;228        }229    }230    anyhow::ensure!(!lat.is_empty(), "aucune réponse 200 : {:?}", errors);231    let n = lat.len();232    let (p50, p95, p99, max) = quantiles(lat);233    println!("{}", serde_json::json!({"bench": "latency", "target_qps": qps, "seconds": secs, "ok": n, "errors": errors, "achieved_qps": n as f64 / start.elapsed().as_secs_f64(), "p50_ms": p50, "p95_ms": p95, "p99_ms": p99, "max_ms": max}));234    Ok(())235}236237// ------------------------------------------------------------------ qualité238239/// Corpus jugé : pour chaque sujet, un document de référence (gain 3), un document connexe (gain 1),240/// et des distracteurs qui partagent des mots sans traiter le sujet (gain 0).241const TOPICS: &[(&str, &str, &str, &str, &str, &str)] = &[242    // (langue, requête, titre de référence, corps de référence, titre connexe, corps connexe)243    ("fr", "recette tarte au sucre", "Recette de la tarte au sucre traditionnelle", "La tarte au sucre se prépare avec de la cassonade, de la crème épaisse et une pâte brisée. Faire cuire quarante minutes jusqu'à ce que la garniture soit prise. Cette recette de tarte vient du Québec et se sert tiède.", "Desserts d'érable du temps des fêtes", "Parmi les desserts servis aux fêtes, on trouve la bûche, le pouding chômeur et parfois une tarte au sucre. Le sirop d'érable parfume plusieurs de ces plats."),244    ("fr", "horaire déneigement stationnement hiver", "Déneigement : horaire et règles de stationnement en hiver", "Durant les opérations de déneigement, le stationnement de nuit est interdit dans les rues signalées. Consultez l'horaire de déneigement de votre secteur avant de garer votre voiture en hiver.", "Entretien des rues de la ville", "La ville entretient les rues toute l'année : nids-de-poule au printemps, balayage en été, et déneigement en hiver selon les priorités établies."),245    ("fr", "symptômes grippe traitement", "Grippe : symptômes et traitement", "Les symptômes de la grippe comprennent la fièvre, la toux, les courbatures et une grande fatigue. Le traitement repose sur le repos, l'hydratation et parfois un antiviral prescrit par un médecin.", "Vaccination saisonnière en pharmacie", "La campagne de vaccination débute à l'automne. Le vaccin réduit le risque de grippe et de complications chez les personnes vulnérables."),246    ("fr", "calcul impôt revenu déclaration", "Comment calculer son impôt sur le revenu", "Pour calculer l'impôt sur le revenu, additionnez vos revenus imposables, soustrayez les déductions, puis appliquez les taux par palier. La déclaration doit être produite avant la fin avril.", "Crédits pour les familles", "Plusieurs crédits réduisent l'impôt des familles. Ils sont demandés dans la déclaration annuelle de revenus."),247    ("fr", "histoire pont de québec effondrement", "L'histoire du pont de Québec et de ses effondrements", "Le pont de Québec s'est effondré deux fois pendant sa construction, en 1907 et en 1916. Cette histoire a marqué le génie civil et la formation des ingénieurs.", "Les ponts du Saint-Laurent", "Plusieurs ponts enjambent le fleuve : le pont Jacques-Cartier, le pont Laviolette et le pont de Québec, célèbre pour sa travée cantilever."),248    ("fr", "apprendre langage rust mémoire", "Apprendre Rust : la gestion de la mémoire", "Le langage Rust garantit la sûreté de la mémoire sans ramasse-miettes grâce à la propriété et aux emprunts. Pour apprendre Rust, commencez par ces notions de mémoire.", "Comparatif des langages système", "C, C++, Zig et Rust visent la programmation système. Chacun fait des compromis différents entre contrôle et sécurité."),249    ("fr", "randonnée parc national sentier", "Sentiers de randonnée du parc national", "Le parc national offre des sentiers de randonnée de tous niveaux. Le sentier des sommets demande six heures de marche et offre une vue sur la vallée.", "Camping en forêt", "Les terrains de camping en forêt sont ouverts de mai à octobre. Certains donnent accès à un sentier ou à un lac."),250    ("fr", "taux directeur banque centrale inflation", "La banque centrale maintient son taux directeur face à l'inflation", "La banque centrale a annoncé le maintien de son taux directeur. L'inflation ralentit, mais reste au-dessus de la cible de deux pour cent.", "Le marché hypothécaire ralentit", "Les ventes de maisons diminuent. Les acheteurs surveillent les taux d'intérêt et les décisions de la banque."),251    ("fr", "bibliothèque prêt livre numérique", "Emprunter un livre numérique à la bibliothèque", "La bibliothèque permet le prêt de livres numériques pour vingt et un jours. Il suffit d'une carte d'abonné et d'une liseuse compatible.", "Activités culturelles du mois", "Au programme : conférences, expositions et heure du conte à la bibliothèque du quartier."),252    ("fr", "panneaux solaires rendement toit", "Rendement des panneaux solaires sur un toit résidentiel", "Le rendement des panneaux solaires dépend de l'orientation du toit, de l'inclinaison et de l'ensoleillement. Un toit orienté au sud produit le plus d'énergie.", "Efficacité énergétique de la maison", "Isoler le toit, changer les fenêtres et installer une thermopompe réduisent la facture d'énergie."),253    ("en", "sourdough bread starter", "How to make a sourdough bread starter", "A sourdough starter is a culture of flour and water. Feed the starter every day for a week before baking your first loaf of sourdough bread.", "Baking basics for beginners", "Learn about yeast, kneading and proofing. Bread can be made with commercial yeast or a starter."),254    ("en", "bicycle tire puncture repair", "Repairing a punctured bicycle tire", "To repair a bicycle tire puncture, remove the wheel, find the hole in the tube, roughen the rubber and apply a patch. Check the tire for glass before refitting.", "Spring bicycle maintenance", "Clean the chain, check the brakes and inflate each tire to the recommended pressure before your first ride."),255    ("en", "volcano eruption warning signs", "Warning signs before a volcano eruption", "Before a volcano eruption, scientists observe swarms of small earthquakes, ground swelling and changes in gas emissions. These warning signs guide evacuation decisions.", "Natural hazards overview", "Earthquakes, floods, landslides and the occasional volcano threaten communities around the world."),256    ("en", "learn python list comprehension", "Python list comprehensions explained", "A list comprehension builds a list in a single expression. To learn Python idioms, start by rewriting simple loops as a list comprehension.", "Programming languages for data science", "Python, R and Julia are popular. Each offers libraries for statistics and plotting."),257    ("en", "mortgage interest rate fixed variable", "Fixed versus variable mortgage interest rates", "A fixed mortgage keeps the same interest rate for the whole term, while a variable rate moves with the central bank. Compare both before signing a mortgage.", "Buying your first home", "Save a down payment, check your credit and get pre-approved for a mortgage before visiting houses."),258    ("en", "telescope beginner planets", "Choosing a beginner telescope to observe planets", "A beginner telescope with a 100 mm aperture shows the rings of Saturn and the moons of Jupiter. Planets are best observed when they are high in the sky.", "Stargazing calendar", "This month brings a meteor shower and a lunar eclipse. No telescope is needed for either."),259    ("en", "vaccine clinical trial phases", "The phases of a vaccine clinical trial", "A vaccine clinical trial has three phases before approval: safety in a few volunteers, dosage in hundreds, and efficacy in thousands of participants.", "How medicines are regulated", "Regulators review manufacturing quality, clinical trial data and labelling before approving a medicine."),260    ("en", "railway history steam locomotive", "A history of the steam locomotive and the railway", "The steam locomotive transformed transport in the nineteenth century. The history of the railway is tied to coal, iron and the growth of cities.", "Museums to visit this summer", "The transport museum displays vintage cars, a tram and a restored steam locomotive."),261    ("en", "coral reef bleaching causes", "What causes coral reef bleaching", "Coral reef bleaching happens when warm water makes corals expel the algae living in their tissues. Prolonged heat is the main cause of mass bleaching.", "Ocean conservation projects", "Volunteers clean beaches, monitor turtles and help restore a damaged reef."),262    ("en", "public library card renewal", "Renewing your public library card", "A public library card must be renewed every two years. Renewal is free and can be done online or at any branch of the library.", "City services directory", "Find recycling schedules, parking permits, the library and recreation programs."),263];264265fn quality(dir: &Path) -> anyhow::Result<()> {266    let _ = std::fs::remove_dir_all(dir);267    let node = open(dir, false, 2)?;268    let mut docs = Vec::new();269    let mut judged: Vec<(String, Vec<(String, u32)>)> = Vec::new();270    let mut rng = Rng(5);271    for (i, (lang, query, t1, b1, t2, b2)) in TOPICS.iter().enumerate() {272        // Le document de référence vit sur une page profonde et de qualité moyenne ; les distracteurs sont273        // des pages d'accueil bien notées qui répètent les mots de la requête : un classement naïf se trompe.274        let main = format!("https://ref{}.example/guides/dossier/page-{}", i, i);275        let related = format!("https://connexe{}.example/articles/{}", i, i);276        docs.push(mk(&main, t1, &format!("{} {}", b1, b1.split('.').next().unwrap_or("")), lang, 0.75, Some(spweb_common::now() - 86_400 * 40)));277        docs.push(mk(&related, t2, b2, lang, 0.6, None));278        let words: Vec<&str> = query.split_whitespace().collect();279        for d in 0..4 {280            // distracteur : ferme de mots-clés (les termes de la requête bourrés, sans contenu)281            let stuffed: String = (0..60).map(|k| words[(k + d) % words.len()]).collect::<Vec<_>>().join(" ");282            let filler: String = (0..40).map(|_| SYL[rng.below(SYL.len())]).collect::<Vec<_>>().join(" ");283            docs.push(mk(&format!("https://ferme{}-{}.example/", i, d), &format!("{} {} pas cher", words[d % words.len()], words[(d + 1) % words.len()]), &format!("{} {}", stuffed, filler), lang, 0.12, None));284        }285        judged.push((query.to_string(), vec![(main, 3), (related, 1)]));286    }287    // bruit de fond288    let vocab = vocabulary(5000);289    for i in 0..400 {290        let body: String = (0..150).map(|_| vocab[zipf(&mut rng, vocab.len())].as_str()).collect::<Vec<_>>().join(" ");291        docs.push(mk(&format!("https://bruit{}.example/p{}", i % 50, i), &format!("{} {}", vocab[i], vocab[i + 1]), &body, "fr", 0.5, None));292    }293    let total = docs.len();294    for chunk in docs.chunks(100) {295        node.ingest(chunk.to_vec());296    }297    node.commit(true)?;298    let now = spweb_common::now();299    let mut agg = [[0f64; 3]; 2]; // [bm25 seul, classement complet] × [ndcg@10, recall@20, mrr]300    let mut per_lang: std::collections::BTreeMap<&str, ([f64; 3], u32)> = Default::default();301    for (i, (q, j)) in judged.iter().enumerate() {302        let parsed = spweb_query::parse(q).unwrap();303        let resp = node.search(&SearchRequest { query: parsed.clone(), k: 50, explain: false, relax: true }, Instant::now() + Duration::from_secs(5));304        let base: Vec<String> = resp.hits.iter().map(|h| h.url.clone()).collect();305        let terms = parsed.all_positive_terms();306        let ranked: Vec<String> = spweb_ranking::rank(resp.hits, &terms, None, None, now, &spweb_ranking::Weights::default()).into_iter().map(|r| r.hit.url).collect();307        for (k, list) in [&base, &ranked].iter().enumerate() {308            agg[k][0] += spweb_ranking::ndcg_at(list, j, 10);309            agg[k][1] += spweb_ranking::recall_at(list, j, 20);310            agg[k][2] += spweb_ranking::mrr(list, j);311        }312        let e = per_lang.entry(TOPICS[i].0).or_insert(([0.0; 3], 0));313        e.0[0] += spweb_ranking::ndcg_at(&ranked, j, 10);314        e.0[1] += spweb_ranking::recall_at(&ranked, j, 20);315        e.0[2] += spweb_ranking::mrr(&ranked, j);316        e.1 += 1;317    }318    let n = judged.len() as f64;319    let m = |a: [f64; 3]| serde_json::json!({"ndcg@10": a[0] / n, "recall@20": a[1] / n, "mrr": a[2] / n});320    let langs: serde_json::Map<String, serde_json::Value> = per_lang.into_iter().map(|(l, (a, c))| (l.to_string(), serde_json::json!({"queries": c, "ndcg@10": a[0] / c as f64, "recall@20": a[1] / c as f64, "mrr": a[2] / c as f64}))).collect();321    println!("{}", serde_json::json!({"bench": "quality", "corpus_documents": total, "judged_queries": judged.len(), "weights": spweb_ranking::WEIGHTS_VERSION,322        "baseline_bm25_fields_only": m(agg[0]), "full_ranking": m(agg[1]), "full_ranking_by_language": langs,323        "note": "corpus synthétique jugé par construction (référence = 3, connexe = 1, fermes de mots-clés = 0) : sert de base de non-régression, pas de mesure sur le Web réel"}));324    Ok(())325}326327#[tokio::main]328async fn main() -> anyhow::Result<()> {329    let a: Vec<String> = std::env::args().collect();330    match a.get(1).map(|s| s.as_str()) {331        Some("ingest") => ingest(&PathBuf::from(&a[2]), a[3].parse()?, a.get(4).map(|s| s == "positions").unwrap_or(false)),332        Some("shard-latency") => shard_latency(&PathBuf::from(&a[2]), a[3].parse()?),333        Some("latency") => latency(&a[2], a[3].parse()?, a[4].parse()?).await,334        Some("quality") => quality(&PathBuf::from(&a[2])),335        _ => {336            eprintln!("usage : spweb-bench ingest <dossier> <n> [positions] | shard-latency <dossier> <n> | latency <url> <req/s> <s> | quality <dossier>");337            std::process::exit(2);338        }339    }340}341
Files main
Menu

Theme