Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

14.5 KB
Raw Blame
//! End-to-end check that the in-process engine loads a real model and streams.
//!
//! Opt-in: set JAN_TEST_GGUF to a small model. It needs the `engine` feature
//! (so a compiled llama.cpp) and a few hundred MB of RAM, neither of which the
//! default test job has.
#![cfg(feature = "engine")]

use tauri_plugin_llamacpp::engine::{Engine, Route};

fn model_path() -> Option<String> {
    // Registering the ggml backends is the caller's job and has to happen
    // before any other ggml call. A test binary sits in target/<profile>/ with
    // no backend modules beside it, and with GGML_BACKEND_DL every backend
    // including the CPU one is a loadable module -- so without this, loading a
    // model fails with no backend registered at all. Called from here because
    // it gates every test in the file and is idempotent.
    tauri_plugin_llamacpp::engine::load_backend_modules();
    std::env::var("JAN_TEST_GGUF").ok().filter(|p| !p.is_empty())
}

fn start(model: &str) -> Engine {
    let args: Vec<String> = [
        "llama-server", "-m", model, "-c", "2048", "-ngl", "0",
        "--no-warmup", "-t", "4", "-fit", "off", "-np", "1",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();
    Engine::start(&args, None).expect("engine should start")
}

// `server_context::load_model` only returns a bool, so without the shim's log
// capture every failure reads as the same bare "failed to load model" and the
// desktop cannot tell a VRAM exhaustion from a bad path. Needs no model file:
// the point is that llama.cpp's own error text rides along.
#[test]
fn a_failed_load_reports_the_reason_llama_cpp_logged() {
    tauri_plugin_llamacpp::engine::load_backend_modules();
    let missing = std::env::temp_dir().join("jan-no-such-model.gguf");
    let args: Vec<String> = [
        "llama-server",
        "-m",
        &missing.to_string_lossy(),
        "--no-warmup",
        "-ngl",
        "0",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();

    let err = Engine::start(&args, None).expect_err("a missing model cannot load");
    let msg = err.to_string();

    assert!(msg.contains("failed to load model"), "{msg}");
    assert!(
        msg.len() > "could not start the llama.cpp engine: failed to load model".len(),
        "no captured log lines in: {msg}"
    );
}

#[test]
fn loads_a_model_and_answers_health_and_models() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    let engine = start(&model);

    let res = engine.request(Route::Health.as_shim_name(), "");
    assert_eq!(res.status(), 200, "health body: {}", res.body());
    assert!(res.body().contains("ok"));

    let res = engine.request(Route::Models.as_shim_name(), "");
    assert_eq!(res.status(), 200);
    let v: serde_json::Value = serde_json::from_str(&res.body()).unwrap();
    assert!(
        v.pointer("/data/0/meta/n_ctx").is_some(),
        "no model metadata: {}",
        res.body()
    );
}

#[test]
fn a_chat_completion_applies_the_template_and_reports_usage() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    let engine = start(&model);

    let res = engine.request(
        Route::ChatCompletions.as_shim_name(),
        r#"{"messages":[{"role":"user","content":"Say only: OK"}],
            "max_tokens":200,"temperature":0}"#,
    );
    assert_eq!(res.status(), 200, "body: {}", res.body());
    let v: serde_json::Value = serde_json::from_str(&res.body()).unwrap();

    // A response at all means the model's chat template was applied: without
    // it the prompt would not have been wrapped and there would be no message.
    assert!(
        v.pointer("/choices/0/message/role").is_some(),
        "no assistant message: {}",
        res.body()
    );
    assert!(
        v.pointer("/usage/completion_tokens")
            .and_then(|t| t.as_u64())
            .unwrap_or(0)
            > 0,
        "no tokens generated: {}",
        res.body()
    );
}

#[test]
fn a_streaming_completion_yields_sse_chunks_then_finishes() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    let engine = start(&model);

    let mut res = engine.request(
        Route::ChatCompletions.as_shim_name(),
        r#"{"messages":[{"role":"user","content":"Count to five."}],
            "max_tokens":80,"temperature":0,"stream":true}"#,
    );
    assert_eq!(res.status(), 200);
    assert!(res.is_stream(), "expected a streaming response");
    assert_eq!(res.content_type(), "text/event-stream");

    // The first frame arrives in the body; the rest through next_chunk().
    let mut frames = res.body().matches("data: ").count();
    let mut guard = 0;
    while let Some(chunk) = res.next_chunk().expect("generator threw") {
        frames += chunk.matches("data: ").count();
        guard += 1;
        assert!(guard < 10_000, "stream did not terminate");
    }
    assert!(frames > 1, "expected multiple SSE frames, got {frames}");
    // Draining past the end must stay terminated rather than restart.
    assert_eq!(res.next_chunk().unwrap(), None);
}

#[test]
fn an_unknown_route_is_a_404_not_a_crash() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    let engine = start(&model);
    let res = engine.request("post_does_not_exist", "{}");
    assert_eq!(res.status(), 404, "body: {}", res.body());
}

/// Two engines in one process, concurrently. This is the property that made
/// `server_context` the right level to link: `llama_server()` keeps its
/// shutdown handler in a file-scope global (server.cpp:25), so a second
/// instance would steal the first one's teardown -- which is why multi-model
/// upstream means multi-*process*. Driving server_context directly does not
/// have that limit, so models_max can be served in-process.
#[test]
fn two_engines_coexist_in_one_process() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    let a = start(&model);
    let b = start(&model);

    for (name, engine) in [("a", &a), ("b", &b)] {
        let res = engine.request(Route::Health.as_shim_name(), "");
        assert_eq!(res.status(), 200, "engine {name} unhealthy: {}", res.body());
    }

    // And both can generate, so they are not sharing one queue.
    for (name, engine) in [("a", &a), ("b", &b)] {
        let res = engine.request(
            Route::ChatCompletions.as_shim_name(),
            r#"{"messages":[{"role":"user","content":"hi"}],"max_tokens":16,"temperature":0}"#,
        );
        assert_eq!(res.status(), 200, "engine {name} failed: {}", res.body());
    }

    // Dropping one must not disturb the other.
    drop(a);
    let res = b.request(Route::Health.as_shim_name(), "");
    assert_eq!(res.status(), 200, "engine b died with a: {}", res.body());
}

/// Regression: stopping an engine that never served a request used to hang
/// forever. `server_queue::start_loop` sets `running = true` at its top
/// (server-queue.cpp:279), so a `terminate()` issued before the loop thread
/// reaches that line is erased and the loop blocks. In the app that is a
/// shutdown hang after loading a model the user never used.
#[test]
fn an_engine_stops_promptly_even_if_it_never_served_a_request() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    // Repeat: the failure is a race, so one pass proves little.
    for attempt in 0..5 {
        let started = std::time::Instant::now();
        let engine = start(&model);
        drop(engine); // immediate stop, no request in between
        let elapsed = started.elapsed();
        assert!(
            elapsed < std::time::Duration::from_secs(20),
            "attempt {attempt}: start+stop took {elapsed:?}, which means the \
             loop missed its terminate"
        );
    }
}

/// The preset path starts from a default-constructed `common_params`, so the
/// per-example defaults `common_params_parser_init` applies for
/// `LLAMA_EXAMPLE_SERVER` -- and the `n_parallel < 0` resolution in
/// `server.cpp`'s `main`, which nothing here goes through -- have to be
/// applied by the shim. Without them an ini with no `parallel` key gets one
/// slot instead of llama-server's four.
#[test]
fn a_preset_without_parallel_gets_the_server_side_auto_default() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    let dir = tempfile::tempdir().expect("tempdir");
    let ini = dir.path().join("router.preset.ini");
    std::fs::write(
        &ini,
        format!(
            "[*]\nfit = off\nctx-size = 2048\nno-warmup = true\n\n\
             [m]\nmodel = {model}\nn-gpu-layers = 0\n"
        ),
    )
    .expect("write ini");

    let engine = Engine::start_from_preset(&ini.to_string_lossy(), "m", None)
        .expect("engine should start from the preset");

    let res = engine.request(Route::Props.as_shim_name(), "");
    assert_eq!(res.status(), 200, "props body: {}", res.body());
    let v: serde_json::Value = serde_json::from_str(&res.body()).unwrap();
    assert_eq!(
        v.pointer("/total_slots").and_then(|s| s.as_i64()),
        Some(4),
        "props: {}",
        res.body()
    );
}

/// llama.cpp's router starts every child with `--alias <section name>`
/// (`server-models.cpp`, `update_args`), so its responses name the model by its
/// id. The preset path applies the section to `common_params` itself and has no
/// router to do that, and an unset alias makes `server_context` fall back to the
/// model *file path* -- which API clients then read back as the `model` of every
/// response (`\\?\C:\...\model.gguf` on Windows, #9471).
#[test]
fn a_preset_engine_names_the_model_by_its_section_not_its_file_path() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    let dir = tempfile::tempdir().expect("tempdir");
    let ini = dir.path().join("router.preset.ini");
    std::fs::write(
        &ini,
        format!(
            "[*]\nfit = off\nctx-size = 2048\nno-warmup = true\n\n\
             [jan-model-id]\nmodel = {model}\nn-gpu-layers = 0\n"
        ),
    )
    .expect("write ini");
    let engine = Engine::start_from_preset(&ini.to_string_lossy(), "jan-model-id", None)
        .expect("engine should start from the preset");

    let res = engine.request(
        Route::ChatCompletions.as_shim_name(),
        r#"{"messages":[{"role":"user","content":"hi"}],"max_tokens":8,"temperature":0}"#,
    );
    assert_eq!(res.status(), 200, "body: {}", res.body());
    let v: serde_json::Value = serde_json::from_str(&res.body()).unwrap();
    assert_eq!(
        v.pointer("/model").and_then(|m| m.as_str()),
        Some("jan-model-id"),
        "completion: {}",
        res.body()
    );

    // A stream carries the name on every chunk, from the first.
    let mut res = engine.request(
        Route::ChatCompletions.as_shim_name(),
        r#"{"messages":[{"role":"user","content":"hi"}],"max_tokens":8,"temperature":0,"stream":true}"#,
    );
    assert!(res.is_stream(), "expected a streaming response");
    // The first frame may sit in the body or arrive through the generator.
    let mut text = res.body();
    while !text.contains("data: {") {
        match res.next_chunk().expect("generator threw") {
            Some(more) => text.push_str(&more),
            None => break,
        }
    }
    let frame = text
        .lines()
        .filter_map(|l| l.strip_prefix("data: "))
        .find(|f| f.starts_with('{'))
        .expect("a JSON data frame");
    let chunk: serde_json::Value = serde_json::from_str(frame).unwrap();
    assert_eq!(
        chunk.pointer("/model").and_then(|m| m.as_str()),
        Some("jan-model-id"),
        "first chunk: {frame}"
    );
    drop(res);

    let res = engine.request(Route::Models.as_shim_name(), "");
    let v: serde_json::Value = serde_json::from_str(&res.body()).unwrap();
    assert_eq!(
        v.pointer("/data/0/id").and_then(|m| m.as_str()),
        Some("jan-model-id"),
        "models: {}",
        res.body()
    );
}

/// `server_context` is the only source of real load progress: it reports it
/// through `set_state_callback` and there is nothing to poll for it. Without
/// the shim installing that callback the desktop's whole progress chain --
/// `/models/sse` -> `parse_load_progress_event` -> `PromptProgress` -- sits
/// idle on a plain spinner, which is what it did.
#[test]
fn a_load_reports_its_progress_through_the_state_callback() {
    let Some(model) = model_path() else {
        eprintln!("skipping: set JAN_TEST_GGUF to run");
        return;
    };
    use std::sync::{Arc, Mutex};

    let samples: Arc<Mutex<Vec<(String, f64)>>> = Arc::new(Mutex::new(Vec::new()));
    let sink = Arc::clone(&samples);
    let args: Vec<String> = [
        "llama-server", "-m", &model, "-c", "2048", "-ngl", "0",
        "--no-warmup", "-t", "4", "-fit", "off", "-np", "1",
    ]
    .iter()
    .map(|s| s.to_string())
    .collect();

    let engine = Engine::start(
        &args,
        Some(Arc::new(move |state: &str, payload: &str| {
            let v: serde_json::Value = match serde_json::from_str(payload) {
                Ok(v) => v,
                Err(_) => return,
            };
            if let Some(value) = v.get("value").and_then(|v| v.as_f64()) {
                let stage = v
                    .get("current")
                    .and_then(|s| s.as_str())
                    .unwrap_or_default()
                    .to_string();
                sink.lock().unwrap().push((format!("{state}:{stage}"), value));
            }
        })),
    )
    .expect("engine should start");

    let seen = samples.lock().unwrap().clone();
    assert!(!seen.is_empty(), "no progress samples arrived");
    assert!(
        seen.iter().all(|(s, _)| s.starts_with("loading:")),
        "a sample carried a value outside the loading state: {seen:?}"
    );
    // The callback always emits the first and the last sample, whatever the
    // 200ms throttle drops in between.
    assert_eq!(seen.first().map(|(_, v)| *v), Some(0.0), "{seen:?}");
    assert!(
        seen.iter().any(|(s, v)| *v >= 1.0 && s == "loading:text_model"),
        "the text model never reported completion: {seen:?}"
    );

    // And the engine is usable, i.e. installing the callback did not disturb
    // the load it observes.
    let res = engine.request(Route::Health.as_shim_name(), "");
    assert_eq!(res.status(), 200, "health body: {}", res.body());
}