#!/usr/bin/env -S cargo +nightly -Zscript
---cargo
[package]
name = "fuzz"
version = "0.0.0"
edition = "2024"
publish = false

[dependencies]
postgres = "0.19.14"
rand = "0.10.3"
---

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License v3 (AGPLv3).
// See <https://www.gnu.org/licenses/agpl-3.0.html> for details.
//
// Copyright (c) 2025-2026 TensorChord Inc.
// Copyright (c) 2026 PGSTY PTE. LTD.
// Maintained by Ruohang Feng @ PGSTY (rh@vonng.com)

use std::collections::BTreeMap;
use std::fmt::Debug;

use rand::seq::IndexedRandom;
use rand::{RngExt, SeedableRng};

#[allow(unused)]
#[derive(Debug, Clone, Copy)]
enum Operation {
    Insert,
    Select,
    Delete,
    Vacuum,
}

const INIT_DOCUMENTS: u32 = 10000;
const DOCUMENT_MAX_TOKEN: u32 = 10000;
const DOCUMENT_LEN: u32 = 100;

const FUZZ_ITERATIONS: u32 = 5000;
const FUZZ_OPERATIONS: &[Operation] = &[
    Operation::Insert,
    Operation::Insert,
    Operation::Select,
    Operation::Select,
    Operation::Select,
    Operation::Select,
    Operation::Delete,
    Operation::Delete,
    Operation::Delete,
    Operation::Vacuum,
];

fn test(mut clients: Vec<postgres::Client>, iterations: u32) {
    let seed = rand::rng().random_range(0..u64::MAX);
    let mut rng = rand::rngs::StdRng::seed_from_u64(seed);
    println!("Seed: {}", seed); // for reproducibility

    clients[0]
        .execute(
            r#"
        CREATE TABLE documents (
            id SERIAL PRIMARY KEY,
            embedding tsvector
        ) WITH (autovacuum_enabled = off);
        "#,
            &[],
        )
        .unwrap();

    // Insert initial documents
    for _ in 0..INIT_DOCUMENTS {
        let tsvector = random_tsvector(&mut rng);
        clients[0]
            .execute(
                r#"INSERT INTO documents (embedding) VALUES ($1::text::tsvector);"#,
                &[&tsvector],
            )
            .unwrap();
    }

    // Create index
    clients[0]
        .execute(
            r#"CREATE INDEX documents_embedding_bm25 ON documents USING bm25 (embedding bm25_ops);"#,
            &[],
        )
        .unwrap();

    if clients.len() == 1 {
        for _ in 0..iterations {
            {
                let restuple = clients[0]
                    .query(
                        r#"SELECT pg_relation_size('documents_embedding_bm25')"#,
                        &[],
                    )
                    .unwrap();
                let relation_size = restuple[0].get::<_, i64>(0);
                println!("relation_size = {relation_size}");
            }
            let operation = FUZZ_OPERATIONS.choose(&mut rng).unwrap();
            println!("operation = {operation:?}");
            match operation {
                Operation::Insert => fuzz_insert(&mut clients[0], &mut rng),
                Operation::Select => fuzz_select(&mut clients[0], &mut rng, true),
                Operation::Delete => fuzz_delete(&mut clients[0], &mut rng),
                Operation::Vacuum => fuzz_vacuum(&mut clients[0], &mut rng),
            }
        }
    } else {
        let n = clients.len();
        let threads = clients
            .into_iter()
            .map(|mut client| {
                std::thread::spawn(move || {
                    let mut rng = rand::rng();
                    for _ in 0..iterations {
                        let operation = FUZZ_OPERATIONS.choose(&mut rng).unwrap();
                        static LOCK: std::sync::RwLock<()> = std::sync::RwLock::new(());
                        match operation {
                            Operation::Insert => {
                                let _guard = LOCK.read().unwrap();
                                fuzz_insert(&mut client, &mut rng);
                            }
                            Operation::Select => {
                                use std::sync::TryLockError;
                                // Physical statistics are frozen per execution,
                                // not per MVCC transaction. Exact comparisons of
                                // two statements require pausing all mutations.
                                // If busy, still check each live concurrent scan.
                                let guard = match LOCK.try_write() {
                                    Ok(r) => Ok(Some(r)),
                                    Err(TryLockError::Poisoned(e)) => Err(e),
                                    Err(TryLockError::WouldBlock) => Ok(None),
                                }
                                .unwrap();
                                fuzz_select(&mut client, &mut rng, guard.is_some())
                            }
                            Operation::Delete => {
                                let _guard = LOCK.read().unwrap();
                                fuzz_delete(&mut client, &mut rng);
                            }
                            Operation::Vacuum => {
                                if rng.random_range(0..n) == 0 {
                                    let _guard = LOCK.read().unwrap();
                                    fuzz_vacuum(&mut client, &mut rng);
                                }
                            }
                        }
                    }
                    client
                })
            })
            .collect::<Vec<_>>();
        clients = threads
            .into_iter()
            .map(|thread| thread.join().unwrap())
            .collect();
    }

    // final check
    clients[0]
        .execute(r#"VACUUM (ANALYZE, INDEX_CLEANUP ON) documents;"#, &[])
        .unwrap();
    fuzz_select(&mut clients[0], &mut rng, true);
    // REINDEX may remove tombstones and change physical corpus statistics.
    // Check each corpus independently, outside a read-only transaction.
    clients[0]
        .execute("REINDEX INDEX documents_embedding_bm25", &[])
        .unwrap();
    fuzz_select(&mut clients[0], &mut rng, true);

    clients[0].execute(r#"DROP TABLE documents;"#, &[]).unwrap();
}

fn random_tsvector(rng: &mut impl RngExt) -> String {
    pub fn from_ids(ids: impl Iterator<Item = u32>) -> String {
        use std::fmt::Write;
        let mut map: BTreeMap<u32, u32> = BTreeMap::new();
        for term_id in ids {
            *map.entry(term_id).or_insert(0) += 1;
        }
        let mut doc_len: u32 = 0;
        let mut indexes = Vec::with_capacity(map.len());
        let mut values = Vec::with_capacity(map.len());
        for (index, value) in map {
            indexes.push(index);
            values.push(value);
            doc_len = doc_len.checked_add(value).expect("overflow");
        }
        let mut buffer = String::new();
        let mut need_splitter = false;
        for (&index, &value) in indexes.iter().zip(values.iter()) {
            let mut positions = String::new();
            for i in 1..=value {
                if i != 1 {
                    positions.push(',');
                }
                positions.push_str(&format!("{i}"));
            }
            match need_splitter {
                false => {
                    write!(buffer, "{index}:{positions}").unwrap();
                    need_splitter = true;
                }
                true => write!(buffer, " {index}:{positions}").unwrap(),
            }
        }
        buffer
    }
    let ids = (0..DOCUMENT_LEN).map(|_| rng.random_range(0..DOCUMENT_MAX_TOKEN));
    from_ids(ids)
}

fn fuzz_insert(client: &mut postgres::Client, rng: &mut impl RngExt) {
    let tsvector = random_tsvector(rng);
    client
        .execute(
            r#"INSERT INTO documents (embedding) VALUES ($1::text::tsvector);"#,
            &[&tsvector],
        )
        .unwrap();
}

fn fuzz_select(client: &mut postgres::Client, rng: &mut impl RngExt, check: bool) {
    let mut client = client
        .build_transaction()
        .isolation_level(postgres::IsolationLevel::RepeatableRead)
        .read_only(true)
        .start()
        .unwrap();

    let query_vector = random_tsvector(rng);

    client
        .execute("SET LOCAL enable_seqscan = off", &[])
        .unwrap();
    client
        .execute("SET LOCAL bm25.enable_scan = on", &[])
        .unwrap();
    client
        .execute("SET LOCAL \"bm25.limit\" = 200", &[])
        .unwrap();
    client
        .execute("SET LOCAL bm25.prefilter = on", &[])
        .unwrap();

    let restuple = client
        .query(
            r#"
            SELECT id, embedding <&> to_bm25query($1::text::tsvector, 'documents_embedding_bm25') AS rank
            FROM documents
            ORDER BY rank
            LIMIT 100"#,
            &[&query_vector],
        )
        .unwrap();
    let mut index_results: Vec<i32> = Vec::new();
    let mut index_result_ranks: Vec<f64> = Vec::new();
    for row in restuple {
        index_results.push(row.get::<_, i32>(0));
        index_result_ranks.push(row.get::<_, f64>(1));
    }

    assert!(
        index_result_ranks.windows(2).all(|w| w[0] <= w[1]),
        "index order disagrees with displayed scores"
    );
    assert_eq!(
        index_results.iter().collect::<std::collections::HashSet<_>>().len(),
        index_results.len(),
        "duplicate indexed results"
    );

    client
        .execute("SET LOCAL enable_seqscan = on", &[])
        .unwrap();
    client
        .execute("SET LOCAL bm25.enable_scan = off", &[])
        .unwrap();

    let restuple = client
        .query(
            r#"
            SELECT id, embedding <&> to_bm25query($1::text::tsvector, 'documents_embedding_bm25') AS rank
            FROM documents
            ORDER BY rank
            LIMIT 100"#,
            &[&query_vector],
        )
        .unwrap();
    let mut seq_results: Vec<i32> = Vec::new();
    let mut seq_result_ranks: Vec<f64> = Vec::new();
    for row in restuple {
        seq_results.push(row.get::<_, i32>(0));
        seq_result_ranks.push(row.get::<_, f64>(1));
    }

    assert_eq!(
        index_results.len(),
        seq_results.len(),
        "incomplete indexed results"
    );
    // Tied IDs may differ. Exact ordered scores must agree for a stable corpus.
    if check && index_result_ranks != seq_result_ranks {
        use std::io::Write;
        let mut stdout = std::io::stdout().lock();
        writeln!(stdout, "Query = {query_vector}").unwrap();
        writeln!(stdout, "Index =").unwrap();
        for (id, rank) in std::iter::zip(index_results, index_result_ranks) {
            writeln!(stdout, "  | {id} | {rank}").unwrap();
        }
        writeln!(stdout, "Seq =").unwrap();
        for (id, rank) in std::iter::zip(seq_results, seq_result_ranks) {
            writeln!(stdout, "  | {id} | {rank}").unwrap();
        }
        panic!("Index and Seq results do not match");
    }

    client.commit().unwrap();
}

fn fuzz_delete(client: &mut postgres::Client, rng: &mut impl RngExt) {
    let id = rng.random_range(1..INIT_DOCUMENTS) as i32;
    client
        .execute(r#"DELETE FROM documents WHERE id = $1"#, &[&id])
        .unwrap();
}

fn fuzz_vacuum(client: &mut postgres::Client, _rng: &mut impl RngExt) {
    client
        .execute(r#"VACUUM (ANALYZE, INDEX_CLEANUP ON) documents;"#, &[])
        .unwrap();
}

fn main() {
    let params = std::env::args().nth(1).unwrap();
    let num_threads = std::env::args()
        .nth(2)
        .and_then(|x| x.parse::<usize>().ok())
        .unwrap_or(1);
    let iterations = std::env::args()
        .nth(3)
        .map(|x| x.parse::<u32>().expect("iterations must be a positive integer"))
        .unwrap_or(FUZZ_ITERATIONS);
    assert!(num_threads > 0 && iterations > 0);
    let clients = (0..num_threads)
        .map(|_| postgres::Client::connect(&params, postgres::tls::NoTls).unwrap())
        .collect::<Vec<_>>();
    test(clients, iterations);
}
