22.1 KiB · text History 313874d
//! The lameness filter: scores a post's text for wall-of-junk shapes (one
//! phrase pasted 4,000 times, "!!!!!!!!", all caps, the same post again
//! and again) so the post can be held for staff review. Pure: no database.
//! The near-duplicate check takes the author's recent bodies as input.
//!
//! What is scored:
//! * **Prose** — the text outside fenced code (```/~~~), inline `code` and
//!   `>` quotes. Every signal applies to it.
//! * **Code and quotes** — legitimately repetitive (tables, logs, a quoted
//!   wall). They're left out of the prose signals and scored together only
//!   by compression, at a far stricter threshold and length, so 20k of one
//!   line inside a fence still trips but a real stack trace doesn't.
//!
//! Each signal that trips gives a reason a person can read; the post is
//! held when any does. Every measurement is kept (`signals`) for the queue
//! and `manage lameness score`.
use std::collections::{HashMap, HashSet};
use std::io::Write;

use serde::Serialize;

/// Thresholds, from `LAMENESS_*` (see the README for the reasoning).
#[derive(Clone, Debug)]
pub struct Config {
    pub enabled: bool,
    /// Longer posts are refused outright.
    pub max_chars: usize,
    /// zlib output ÷ input below this trips, for prose of `compress_min`+
    /// chars. Real prose of 1–20k chars compresses to 35–60%; 0.20 needs a
    /// lot of repetition.
    pub compress_ratio: f64,
    pub compress_min: usize,
    /// The same for code and quotes, needing `code_compress_min`+ chars.
    pub code_compress_ratio: f64,
    pub code_compress_min: usize,
    /// Distinct words ÷ words below this trips, for `words_min`+ words.
    pub distinct_ratio: f64,
    pub words_min: usize,
    /// Share of lines (of 10+ chars) that repeat an earlier one, for
    /// `lines_min`+ such lines.
    pub repeated_lines: f64,
    pub lines_min: usize,
    /// One character this many times in a row (not markdown rules), or a
    /// 2–8 char unit repeated over this many chars ("lolololol…").
    pub max_run: usize,
    /// One word sequence (3 words) appearing this many times.
    pub max_repeat: usize,
    /// Character entropy (bits) below this, for prose of `entropy_min`+.
    /// English runs 4.0–4.5 and a table of numbers ~3.2; under 2.5 is a
    /// handful of letters mashed.
    pub entropy_bits: f64,
    pub entropy_min: usize,
    /// Share of letters in capitals above this, for `caps_min`+ letters.
    pub caps_ratio: f64,
    pub caps_min: usize,
    /// This many earlier posts by the author with the same text (normalized)
    /// in `dup_hours` trips the next.
    pub dup_max: usize,
    pub dup_hours: i64,
    pub dup_min_chars: usize,
    /// Users below `links_trust` posting more than `links_max` links.
    pub links_max: usize,
    pub links_trust: i32,
    /// Escalation: upheld holds count for `strike_days`; the Nth strike
    /// applies `ladder[N-1]` (the last step repeats).
    pub strike_days: i64,
    pub ladder: Vec<Step>,
    /// `flood_holds` holds within `flood_window` → an immediate
    /// `flood_cooldown`, before anyone reviews them.
    pub flood_holds: usize,
    pub flood_window: chrono::Duration,
    pub flood_cooldown: chrono::Duration,
}

/// One rung of the ladder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Step {
    Nothing,
    Cooldown(chrono::Duration),
    /// Suspended until staff lift it.
    Suspend,
}

impl Step {
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim() {
            "" | "-" | "none" => Some(Self::Nothing),
            "suspend" => Some(Self::Suspend),
            d => parse_duration(d).map(Self::Cooldown),
        }
    }

    pub fn describe(&self) -> String {
        match self {
            Self::Nothing => "nothing (a warning)".into(),
            Self::Cooldown(d) => format!("{} read-only", human_duration(*d)),
            Self::Suspend => "suspension until staff review".into(),
        }
    }
}

/// `30m`, `1h`, `1d`, `2w`.
pub fn parse_duration(s: &str) -> Option<chrono::Duration> {
    let s = s.trim();
    let (n, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit())?);
    let n: i64 = n.parse().ok().filter(|n| *n > 0)?;
    match unit {
        "m" => Some(chrono::Duration::minutes(n)),
        "h" => Some(chrono::Duration::hours(n)),
        "d" => Some(chrono::Duration::days(n)),
        "w" => Some(chrono::Duration::weeks(n)),
        _ => None,
    }
}

pub fn human_duration(d: chrono::Duration) -> String {
    let m = d.num_minutes();
    let (n, unit) = if m % (60 * 24) == 0 {
        (m / (60 * 24), "day")
    } else if m % 60 == 0 {
        (m / 60, "hour")
    } else {
        (m, "minute")
    };
    format!("{n} {unit}{}", if n == 1 { "" } else { "s" })
}

pub const DEFAULT_LADDER: &str = "none,1h,1d,7d,30d,90d,suspend";

impl Default for Config {
    fn default() -> Self {
        Self {
            enabled: true,
            max_chars: 32_000,
            compress_ratio: 0.20,
            compress_min: 800,
            code_compress_ratio: 0.04,
            code_compress_min: 4_000,
            distinct_ratio: 0.12,
            words_min: 200,
            repeated_lines: 0.5,
            lines_min: 6,
            max_run: 25,
            max_repeat: 30,
            entropy_bits: 2.5,
            entropy_min: 300,
            caps_ratio: 0.75,
            caps_min: 150,
            dup_max: 2,
            dup_hours: 24,
            dup_min_chars: 40,
            links_max: 8,
            links_trust: 1,
            strike_days: 90,
            ladder: DEFAULT_LADDER.split(',').filter_map(Step::parse).collect(),
            flood_holds: 3,
            flood_window: chrono::Duration::hours(1),
            flood_cooldown: chrono::Duration::hours(1),
        }
    }
}

impl Config {
    pub fn from_env() -> Self {
        fn get<T: std::str::FromStr>(key: &str, default: T) -> T {
            std::env::var(key).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default)
        }
        fn dur(key: &str, default: chrono::Duration) -> chrono::Duration {
            std::env::var(key).ok().and_then(|v| parse_duration(&v)).unwrap_or(default)
        }
        let d = Self::default();
        let ladder = std::env::var("LAMENESS_LADDER")
            .ok()
            .and_then(|v| v.split(',').map(Step::parse).collect::<Option<Vec<_>>>())
            .filter(|l| !l.is_empty())
            .unwrap_or(d.ladder.clone());
        Self {
            enabled: get("LAMENESS_ENABLED", d.enabled),
            max_chars: get("MAX_POST_CHARS", d.max_chars),
            compress_ratio: get("LAMENESS_COMPRESS_RATIO", d.compress_ratio),
            compress_min: get("LAMENESS_COMPRESS_MIN", d.compress_min),
            code_compress_ratio: get("LAMENESS_CODE_COMPRESS_RATIO", d.code_compress_ratio),
            code_compress_min: get("LAMENESS_CODE_COMPRESS_MIN", d.code_compress_min),
            distinct_ratio: get("LAMENESS_DISTINCT_RATIO", d.distinct_ratio),
            words_min: get("LAMENESS_WORDS_MIN", d.words_min),
            repeated_lines: get("LAMENESS_REPEATED_LINES", d.repeated_lines),
            lines_min: get("LAMENESS_LINES_MIN", d.lines_min),
            max_run: get("LAMENESS_MAX_RUN", d.max_run),
            max_repeat: get("LAMENESS_MAX_REPEAT", d.max_repeat),
            entropy_bits: get("LAMENESS_ENTROPY_BITS", d.entropy_bits),
            entropy_min: get("LAMENESS_ENTROPY_MIN", d.entropy_min),
            caps_ratio: get("LAMENESS_CAPS_RATIO", d.caps_ratio),
            caps_min: get("LAMENESS_CAPS_MIN", d.caps_min),
            dup_max: get("LAMENESS_DUP_MAX", d.dup_max),
            dup_hours: get("LAMENESS_DUP_HOURS", d.dup_hours),
            dup_min_chars: d.dup_min_chars,
            links_max: get("LAMENESS_LINKS_MAX", d.links_max),
            links_trust: get("LAMENESS_LINKS_TRUST", d.links_trust),
            strike_days: get("LAMENESS_STRIKE_DAYS", d.strike_days),
            ladder,
            flood_holds: get("LAMENESS_FLOOD_HOLDS", d.flood_holds),
            flood_window: dur("LAMENESS_FLOOD_WINDOW", d.flood_window),
            flood_cooldown: dur("LAMENESS_FLOOD_COOLDOWN", d.flood_cooldown),
        }
    }

    /// The step for the `n`th strike (1-based); past the end, the last.
    pub fn step(&self, n: usize) -> Step {
        if n == 0 {
            return Step::Nothing;
        }
        self.ladder.get(n - 1).or(self.ladder.last()).copied().unwrap_or(Step::Nothing)
    }
}

/// One measurement.
#[derive(Clone, Debug, Serialize)]
pub struct Signal {
    pub name: &'static str,
    /// The measurement, for people ("0.5% of its length").
    pub value: String,
    /// Set when it trips: why, for staff and the author.
    pub reason: Option<String>,
}

#[derive(Clone, Debug, Default, Serialize)]
pub struct Score {
    pub signals: Vec<Signal>,
}

impl Score {
    pub fn tripped(&self) -> bool {
        self.signals.iter().any(|s| s.reason.is_some())
    }

    pub fn reasons(&self) -> Vec<String> {
        self.signals.iter().filter_map(|s| s.reason.clone()).collect()
    }

    fn add(&mut self, name: &'static str, value: String, reason: Option<String>) {
        self.signals.push(Signal { name, value, reason });
    }
}

/// What the author is posting, and what the check needs to know about them.
pub struct Input<'a> {
    pub text: &'a str,
    pub trust_level: i32,
    /// The author's other posts within `dup_hours` (not this one).
    pub recent: &'a [String],
}

/// The text split into prose and the code/quotes left out of prose signals.
pub struct Parts {
    pub prose: String,
    pub code: String,
}

/// Split markdown into prose and code-or-quote text.
pub fn split(text: &str) -> Parts {
    let mut prose = String::new();
    let mut code = String::new();
    let mut fence: Option<&str> = None;
    for line in text.lines() {
        let t = line.trim_start();
        if let Some(f) = fence {
            if t.starts_with(f) {
                fence = None;
            } else {
                code.push_str(line);
                code.push('\n');
            }
            continue;
        }
        if t.starts_with("```") || t.starts_with("~~~") {
            fence = Some(&t[..3]);
            continue;
        }
        if t.starts_with('>') {
            code.push_str(t.trim_start_matches('>').trim_start());
            code.push('\n');
            continue;
        }
        // Inline `code` spans.
        let mut rest = line;
        while let Some(a) = rest.find('`') {
            match rest[a + 1..].find('`') {
                Some(b) => {
                    prose.push_str(&rest[..a]);
                    code.push_str(&rest[a + 1..a + 1 + b]);
                    code.push('\n');
                    rest = &rest[a + 2 + b..];
                }
                None => break,
            }
        }
        prose.push_str(rest);
        prose.push('\n');
    }
    Parts { prose, code }
}

/// zlib -9 output size ÷ input size.
pub fn compression_ratio(s: &str) -> f64 {
    if s.is_empty() {
        return 1.0;
    }
    let mut e = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
    let _ = e.write_all(s.as_bytes());
    let out = e.finish().map(|v| v.len()).unwrap_or(s.len());
    out as f64 / s.len() as f64
}

/// Shannon entropy of the characters, in bits.
pub fn entropy(s: &str) -> f64 {
    let mut counts: HashMap<char, usize> = HashMap::new();
    let mut n = 0usize;
    for c in s.chars().filter(|c| !c.is_whitespace()) {
        *counts.entry(c).or_default() += 1;
        n += 1;
    }
    if n == 0 {
        return 0.0;
    }
    counts
        .values()
        .map(|&k| {
            let p = k as f64 / n as f64;
            -p * p.log2()
        })
        .sum()
}

/// Lowercased words (letters, digits, apostrophes).
fn words(s: &str) -> Vec<String> {
    s.split(|c: char| !(c.is_alphanumeric() || c == '\''))
        .filter(|w| !w.is_empty())
        .map(str::to_lowercase)
        .collect()
}

/// For the duplicate check: lowercase words joined by single spaces.
pub fn normalize(s: &str) -> String {
    words(s).join(" ")
}

/// The longest run of one character (markdown rule characters and
/// whitespace aside), and the longest stretch that repeats a 2–8 char unit.
fn runs(s: &str) -> (usize, char, usize, String) {
    let cs: Vec<char> = s.chars().collect();
    let (mut best, mut best_c, mut cur) = (0usize, ' ', 0usize);
    for i in 0..cs.len() {
        cur = if i > 0 && cs[i] == cs[i - 1] { cur + 1 } else { 1 };
        if cur > best && !cs[i].is_whitespace() && !"-=_*#~`|.".contains(cs[i]) {
            best = cur;
            best_c = cs[i];
        }
    }
    let (mut unit_best, mut unit) = (0usize, String::new());
    for p in 2..=8 {
        let mut len = 0usize;
        for i in p..cs.len() {
            if cs[i] == cs[i - p] && !cs[i].is_whitespace() {
                len += 1;
                if len + p > unit_best {
                    let u: String = cs[i + 1 - p..=i].iter().collect();
                    // A single repeated char is the run above, not a unit.
                    if u.chars().collect::<HashSet<_>>().len() > 1 {
                        unit_best = len + p;
                        unit = u;
                    }
                }
            } else {
                len = 0;
            }
        }
    }
    (best, best_c, unit_best, unit)
}

fn pct(x: f64) -> String {
    if x < 0.01 {
        format!("{:.2}%", x * 100.0)
    } else {
        format!("{:.0}%", x * 100.0)
    }
}

/// Score a post.
pub fn score(cfg: &Config, input: &Input<'_>) -> Score {
    let mut s = Score::default();
    let Parts { prose, code } = split(input.text);
    let prose_len = prose.chars().count();

    // Compression: the strongest single signal for pasted walls.
    if prose_len >= cfg.compress_min {
        let r = compression_ratio(&prose);
        s.add(
            "compression",
            format!("{} of {prose_len} chars", pct(r)),
            (r < cfg.compress_ratio).then(|| format!("it repeats itself: it compresses to {} of its length", pct(r))),
        );
    }
    let code_len = code.chars().count();
    if code_len >= cfg.code_compress_min {
        let r = compression_ratio(&code);
        s.add(
            "code_compression",
            format!("{} of {code_len} chars of code/quotes", pct(r)),
            (r < cfg.code_compress_ratio)
                .then(|| format!("its code or quotes repeat: they compress to {} of their length", pct(r))),
        );
    }

    // Vocabulary.
    let ws = words(&prose);
    if ws.len() >= cfg.words_min {
        let distinct = ws.iter().collect::<HashSet<_>>().len();
        let r = distinct as f64 / ws.len() as f64;
        s.add(
            "distinct_words",
            format!("{distinct} distinct of {} words", ws.len()),
            (r < cfg.distinct_ratio).then(|| format!("only {distinct} different words in {}", ws.len())),
        );
    }
    // One 3-word sequence over and over.
    if ws.len() >= 3 {
        let mut grams: HashMap<(&str, &str, &str), usize> = HashMap::new();
        for w in ws.windows(3) {
            *grams.entry((&w[0], &w[1], &w[2])).or_default() += 1;
        }
        if let Some(((a, b, c), n)) = grams.into_iter().max_by_key(|(g, n)| (*n, *g)) {
            s.add(
                "repeat",
                format!("“{a} {b} {c}” ×{n}"),
                (n >= cfg.max_repeat).then(|| format!("“{a} {b} {c}” appears {n} times")),
            );
        }
    }

    // Lines (or paragraphs) pasted again.
    let lines: Vec<String> = prose
        .lines()
        .map(|l| l.trim().to_lowercase())
        .filter(|l| l.chars().filter(|c| c.is_alphanumeric()).count() >= 10)
        .collect();
    if lines.len() >= cfg.lines_min {
        let mut seen = HashSet::new();
        let repeats = lines.iter().filter(|l| !seen.insert(l.as_str())).count();
        let r = repeats as f64 / lines.len() as f64;
        s.add(
            "repeated_lines",
            format!("{repeats} of {} lines repeat", lines.len()),
            (r >= cfg.repeated_lines).then(|| format!("{repeats} of its {} lines are repeats", lines.len())),
        );
    }

    // Runs: "aaaaaaaa", "!!!!!!!!", "lolololol".
    let (run, run_c, unit_len, unit) = runs(&prose);
    s.add(
        "runs",
        format!("{run}× “{run_c}”, “{unit}” over {unit_len} chars"),
        if run >= cfg.max_run {
            Some(format!("“{run_c}” {run} times in a row"))
        } else if unit_len >= cfg.max_run * 2 {
            Some(format!("“{unit}” repeated over {unit_len} characters"))
        } else {
            None
        },
    );

    // Character entropy and shouting.
    if prose_len >= cfg.entropy_min {
        let e = entropy(&prose);
        s.add(
            "entropy",
            format!("{e:.2} bits"),
            (e < cfg.entropy_bits).then(|| format!("very few different characters ({e:.2} bits)")),
        );
    }
    let letters: Vec<char> = prose.chars().filter(|c| c.is_alphabetic()).collect();
    if letters.len() >= cfg.caps_min {
        let upper = letters.iter().filter(|c| c.is_uppercase()).count();
        let r = upper as f64 / letters.len() as f64;
        s.add("caps", format!("{} capitals", pct(r)), (r > cfg.caps_ratio).then(|| format!("{} in capitals", pct(r))));
    }

    // The same post again (cross-posting).
    let norm = normalize(input.text);
    if norm.len() >= cfg.dup_min_chars {
        let same = input.recent.iter().filter(|r| normalize(r) == norm).count();
        s.add(
            "duplicate",
            format!("{same} recent identical post(s)"),
            (same >= cfg.dup_max).then(|| format!("you posted the same text {same} times in the last {} hours", cfg.dup_hours)),
        );
    }

    // Many links from a new account.
    let links = input.text.matches("http://").count() + input.text.matches("https://").count();
    if input.trust_level < cfg.links_trust {
        s.add(
            "links",
            format!("{links} links"),
            (links > cfg.links_max).then(|| format!("{links} links from a new account")),
        );
    }
    s
}

/// A one-line summary of the measurements for the queue and logs.
pub fn summary(s: &Score) -> String {
    s.signals.iter().map(|x| format!("{}: {}", x.name, x.value)).collect::<Vec<_>>().join(" · ")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn held(text: &str) -> Score {
        score(&Config::default(), &Input { text, trust_level: 2, recent: &[] })
    }

    fn assert_clean(name: &str, text: &str) {
        let s = held(text);
        eprintln!("{name}: {}", summary(&s));
        assert!(!s.tripped(), "{name} tripped: {:?}\n{}", s.reasons(), summary(&s));
    }

    #[test]
    fn the_reported_wall_is_held() {
        let text = include_str!("../tests/fixtures/lameness_too_long.txt");
        assert_eq!(text.chars().count(), 22_050);
        let s = held(text);
        let names: Vec<_> = s.signals.iter().filter(|x| x.reason.is_some()).map(|x| x.name).collect();
        for n in ["compression", "distinct_words", "repeat"] {
            assert!(names.contains(&n), "{n}: {}", summary(&s));
        }
    }

    #[test]
    fn real_writing_is_not_held() {
        for (name, text) in [
            ("README.md", include_str!("../README.md")),
            ("docs/api.md", include_str!("../docs/api.md")),
            ("docs/android.md", include_str!("../docs/android.md")),
            ("this file, as a code block", &format!("Here's the filter:\n\n```rust\n{}\n```\n", include_str!("lameness.rs"))),
            ("Cargo.lock in a fence", &format!("```\n{}\n```", include_str!("../Cargo.lock"))),
            ("seed demo posts", &crate::seed::demo_post_bodies().join("\n\n")),
            ("the seeded welcome", crate::seed::WELCOME_BODY),
        ] {
            assert_clean(name, text);
        }
        for body in crate::seed::demo_post_bodies() {
            assert_clean("a seed post", &body);
        }
        assert_clean("a short shout", "THIS IS GREAT!!!");
        assert_clean("hahaha", "hahahaha that's brilliant");
        let rows: String = (1..=40).map(|i| format!("| {i} | {} | ok |\n", i * i)).collect();
        assert_clean("a table", &format!("| n | n² | status |\n|---|---|---|\n{rows}"));
        assert_clean("a log in a fence", &format!("```\n{}```", (0..300).map(|i| format!("2026-12-02T10:{:02}:{:02}Z INFO request id={i} status=200 path=/t/{}\n", i / 60, i % 60, i * 7)).collect::<String>()));
    }

    #[test]
    fn classic_spam_is_held() {
        let cases = [
            ("char run", format!("first {}", "!".repeat(60))),
            ("keysmash unit", format!("lol {}", "lo".repeat(60))),
            ("shouting", "BUY NOW CHEAP PILLS BEST PRICE GUARANTEED ".repeat(8)),
            ("same line", "Visit my channel for free stuff today\n".repeat(12)),
            ("fenced wall", format!("```\n{}```", "spam spam spam spam spam\n".repeat(400))),
            ("quoted wall", "> repeat after me repeat after me\n".repeat(300)),
            ("one letter", "a ".repeat(600)),
        ];
        for (name, text) in cases {
            let s = held(&text);
            assert!(s.tripped(), "{name} wasn't held: {}", summary(&s));
        }
    }

    #[test]
    fn duplicates_and_links() {
        let text = "Check out my new project, it does everything you need and more!";
        let cfg = Config::default();
        let once = [text.to_string()];
        assert!(!score(&cfg, &Input { text, trust_level: 2, recent: &once }).tripped());
        let twice = [text.to_string(), text.to_uppercase()];
        let s = score(&cfg, &Input { text, trust_level: 2, recent: &twice });
        assert!(s.reasons()[0].contains("same text 2 times"), "{:?}", s.reasons());
        let links = (0..9).map(|i| format!("https://example.com/{i}")).collect::<Vec<_>>().join("\n");
        assert!(score(&cfg, &Input { text: &links, trust_level: 0, recent: &[] }).tripped());
        assert!(!score(&cfg, &Input { text: &links, trust_level: 2, recent: &[] }).tripped());
    }

    #[test]
    fn ladder_and_durations() {
        let c = Config::default();
        assert_eq!(c.step(1), Step::Nothing);
        assert_eq!(c.step(2), Step::Cooldown(chrono::Duration::hours(1)));
        assert_eq!(c.step(6), Step::Cooldown(chrono::Duration::days(90)));
        assert_eq!(c.step(7), Step::Suspend);
        assert_eq!(c.step(12), Step::Suspend);
        assert_eq!(human_duration(chrono::Duration::days(7)), "7 days");
        assert_eq!(Step::parse("bogus"), None);
    }
}