use parking_lot::Mutex;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use symforge::live_index::LiveIndex;
use symforge::watcher::{WatcherInfo, WatcherState, run_watcher};
use tempfile::TempDir;
fn write_file(dir: &Path, name: &str, content: &str) {
let path = dir.join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(path, content).unwrap();
}
async fn spawn_watcher(
dir: &TempDir,
shared: &symforge::live_index::SharedIndex,
) -> Arc<Mutex<WatcherInfo>> {
let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
let root = dir.path().to_path_buf();
let index_clone = Arc::clone(shared);
let info_clone = Arc::clone(&watcher_info);
tokio::spawn(async move {
run_watcher(root, index_clone, info_clone).await;
});
tokio::time::sleep(Duration::from_millis(100)).await;
watcher_info
}
async fn wait_debounce() {
tokio::time::sleep(Duration::from_millis(500)).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_detects_modify_and_updates_index() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/hello.rs", "fn hello() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
{
let index = shared.read();
let file = index
.get_file("src/hello.rs")
.expect("src/hello.rs should be indexed");
let names: Vec<&str> = file.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(
names.contains(&"hello"),
"initial symbol 'hello' should exist: {names:?}"
);
}
let _watcher_info = spawn_watcher(&dir, &shared).await;
write_file(dir.path(), "src/hello.rs", "fn hello_world() {}");
wait_debounce().await;
{
let index = shared.read();
let file = index
.get_file("src/hello.rs")
.expect("src/hello.rs should still be in index");
let names: Vec<&str> = file.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(
names.contains(&"hello_world"),
"FRSH-01/03/06: updated symbol 'hello_world' should be in index after edit, got: {names:?}"
);
assert!(
!names.contains(&"hello"),
"FRSH-06: old symbol 'hello' must be gone after overwrite, got: {names:?}"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_indexes_new_file() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/existing.rs", "fn existing() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
let initial_count = shared.read().file_count();
let _watcher_info = spawn_watcher(&dir, &shared).await;
write_file(dir.path(), "src/new_file.rs", "fn new_function() {}");
wait_debounce().await;
{
let index = shared.read();
let new_count = index.file_count();
assert_eq!(
new_count,
initial_count + 1,
"FRSH-04: file_count should have increased by 1 after creating new_file.rs"
);
let file = index
.get_file("src/new_file.rs")
.expect("FRSH-04: src/new_file.rs should be in index after create");
let names: Vec<&str> = file.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(
names.contains(&"new_function"),
"FRSH-04: new file should have 'new_function' symbol, got: {names:?}"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_removes_deleted_file() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/to_delete.rs", "fn doomed() {}");
write_file(dir.path(), "src/stable.rs", "fn keeper() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
{
let index = shared.read();
assert_eq!(index.file_count(), 2, "should have 2 files initially");
assert!(
index.get_file("src/to_delete.rs").is_some(),
"src/to_delete.rs should be in index before delete"
);
}
let _watcher_info = spawn_watcher(&dir, &shared).await;
fs::remove_file(dir.path().join("src/to_delete.rs")).unwrap();
wait_debounce().await;
{
let index = shared.read();
assert!(
index.get_file("src/to_delete.rs").is_none(),
"FRSH-05: src/to_delete.rs should be removed from index after deletion"
);
assert_eq!(
index.file_count(),
1,
"FRSH-05: file_count should decrease to 1 after deletion"
);
assert!(
index.get_file("src/stable.rs").is_some(),
"src/stable.rs should still be in index after unrelated file was deleted"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_hash_skip_on_noop_write() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
let content = "fn stable() {}";
write_file(dir.path(), "src/stable.rs", content);
let shared = LiveIndex::load(dir.path()).unwrap();
let initial_symbols: Vec<String> = {
let index = shared.read();
let file = index.get_file("src/stable.rs").unwrap();
file.symbols.iter().map(|s| s.name.clone()).collect()
};
let watcher_info = spawn_watcher(&dir, &shared).await;
let events_before = watcher_info.lock().events_processed;
write_file(dir.path(), "src/stable.rs", content);
wait_debounce().await;
{
let index = shared.read();
let file = index
.get_file("src/stable.rs")
.expect("src/stable.rs should still be indexed after noop write");
let after_symbols: Vec<String> = file.symbols.iter().map(|s| s.name.clone()).collect();
assert_eq!(
initial_symbols, after_symbols,
"hash-skip: symbols should be unchanged after writing identical content"
);
}
let events_after = watcher_info.lock().events_processed;
let _ = events_before; let _ = events_after;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_enoent_handled_gracefully() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/fragile.rs", "fn at_risk() {}");
write_file(dir.path(), "src/anchor.rs", "fn anchor() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
let watcher_info = spawn_watcher(&dir, &shared).await;
fs::remove_file(dir.path().join("src/fragile.rs")).unwrap();
wait_debounce().await;
{
let index = shared.read();
assert!(
index.get_file("src/fragile.rs").is_none(),
"RELY-03: fragile.rs should be removed from index after deletion"
);
}
{
let info = watcher_info.lock();
assert_eq!(
info.state,
WatcherState::Active,
"RELY-03: watcher should remain Active after ENOENT; got: {:?}",
info.state
);
}
}
const FRSH_02_SOURCE: &str = r#"
/// A moderately complex function for benchmarking the parser.
pub fn compute_sum(items: &[u32]) -> u32 {
let mut total = 0u32;
for &item in items {
if item % 2 == 0 {
total += item;
} else {
total = total.saturating_add(item * 2);
}
}
total
}
pub struct Accumulator {
values: Vec<u32>,
threshold: u32,
}
impl Accumulator {
pub fn new(threshold: u32) -> Self {
Self { values: Vec::new(), threshold }
}
pub fn push(&mut self, val: u32) {
self.values.push(val);
}
pub fn result(&self) -> u32 {
self.values.iter().copied().sum()
}
}
"#;
#[test]
fn test_single_file_reparse_produces_expected_symbols() {
use symforge::domain::{FileOutcome, LanguageId};
use symforge::parsing;
let result = parsing::process_file("bench.rs", FRSH_02_SOURCE.as_bytes(), LanguageId::Rust);
assert!(
matches!(result.outcome, FileOutcome::Processed),
"FRSH-02: single-file re-parse must succeed cleanly, got {:?}",
result.outcome
);
assert!(
result.parse_diagnostic.is_none(),
"FRSH-02: clean source must not emit a parse diagnostic: {:?}",
result.parse_diagnostic
);
let names: Vec<&str> = result.symbols.iter().map(|s| s.name.as_str()).collect();
for expected in ["compute_sum", "Accumulator", "new", "push", "result"] {
assert!(
names.contains(&expected),
"FRSH-02: expected symbol `{expected}` in {names:?}"
);
}
}
#[test]
#[ignore = "perf smoke (FRSH-02): runs under scheduled/manual perf CI only"]
fn test_single_file_reparse_perf_smoke() {
use std::time::Instant;
use symforge::domain::LanguageId;
use symforge::parsing;
let bytes = FRSH_02_SOURCE.as_bytes();
for _ in 0..5 {
let _ = parsing::process_file("bench.rs", bytes, LanguageId::Rust);
}
const SAMPLES: usize = 11;
let mut timings: Vec<Duration> = Vec::with_capacity(SAMPLES);
for _ in 0..SAMPLES {
let start = Instant::now();
let _ = parsing::process_file("bench.rs", bytes, LanguageId::Rust);
timings.push(start.elapsed());
}
timings.sort_unstable();
let median = timings[timings.len() / 2];
assert!(
median < Duration::from_millis(250),
"FRSH-02: median single-file re-parse should stay well under 250ms, got {}ms (samples: {:?})",
median.as_millis(),
timings
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_state_reports_active() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/code.rs", "fn main() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
let watcher_info = spawn_watcher(&dir, &shared).await;
tokio::time::sleep(Duration::from_millis(200)).await;
let state = watcher_info.lock().state.clone();
assert_eq!(
state,
WatcherState::Active,
"watcher state should be Active after initialization, got: {:?}",
state
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_atomic_save_via_rename_replace() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/atomic.rs", "fn initial() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
{
let index = shared.read();
let file = index
.get_file("src/atomic.rs")
.expect("src/atomic.rs should be indexed");
let names: Vec<&str> = file.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(
names.contains(&"initial"),
"initial symbol 'initial' should exist: {names:?}"
);
}
let _watcher_info = spawn_watcher(&dir, &shared).await;
let target = dir.path().join("src/atomic.rs");
let tmp = dir.path().join("src/atomic.rs.tmp");
fs::write(&tmp, "fn replaced() {}").unwrap();
fs::rename(&tmp, &target).unwrap();
wait_debounce().await;
{
let index = shared.read();
let file = index
.get_file("src/atomic.rs")
.expect("rename-replace: src/atomic.rs should still be indexed");
let names: Vec<&str> = file.symbols.iter().map(|s| s.name.as_str()).collect();
assert!(
names.contains(&"replaced"),
"rename-replace: new symbol 'replaced' must be in index after atomic save, got: {names:?}"
);
assert!(
!names.contains(&"initial"),
"rename-replace: old symbol 'initial' must be gone after atomic save, got: {names:?}"
);
}
{
let index = shared.read();
assert!(
index.get_file("src/atomic.rs.tmp").is_none(),
"rename-replace: .tmp file must not appear in index"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_atomic_save_noop_content() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
let content = "fn unchanged() {}";
write_file(dir.path(), "src/noop.rs", content);
let shared = LiveIndex::load(dir.path()).unwrap();
let initial_symbols: Vec<String> = {
let index = shared.read();
let file = index.get_file("src/noop.rs").unwrap();
file.symbols.iter().map(|s| s.name.clone()).collect()
};
let _watcher_info = spawn_watcher(&dir, &shared).await;
let target = dir.path().join("src/noop.rs");
let tmp = dir.path().join("src/noop.rs.tmp");
fs::write(&tmp, content).unwrap();
fs::rename(&tmp, &target).unwrap();
wait_debounce().await;
{
let index = shared.read();
let file = index
.get_file("src/noop.rs")
.expect("rename-replace (noop): file should still be indexed");
let after: Vec<String> = file.symbols.iter().map(|s| s.name.clone()).collect();
assert_eq!(
initial_symbols, after,
"rename-replace (noop): symbols must be unchanged when bytes are identical"
);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn test_watcher_ignores_non_source_files() {
let dir = tempfile::tempdir().unwrap();
let src_dir = dir.path().join("src");
fs::create_dir_all(&src_dir).unwrap();
write_file(dir.path(), "src/code.rs", "fn main() {}");
let shared = LiveIndex::load(dir.path()).unwrap();
let initial_count = shared.read().file_count();
let _watcher_info = spawn_watcher(&dir, &shared).await;
write_file(dir.path(), "notes.txt", "some notes");
write_file(dir.path(), "data.csv", "a,b,c");
wait_debounce().await;
{
let index = shared.read();
assert_eq!(
index.file_count(),
initial_count,
"watcher should not index non-source files; count should remain {initial_count}, got {}",
index.file_count()
);
assert!(
index.get_file("notes.txt").is_none(),
"notes.txt should NOT be in the index (unsupported extension)"
);
assert!(
index.get_file("data.csv").is_none(),
"data.csv should NOT be in the index (unsupported extension)"
);
}
}