ferrum-cli 0.8.2

CLI for Ferrum — a Rust-native LLM inference engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! G3 prefix-cache product smoke for `ferrum serve`.
//!
//!     ferrum pull qwen3:0.6b
//!     cargo test --release -p ferrum-cli --test server_prefix_cache_product -- --ignored --test-threads=1

use reqwest::Client;
use serde_json::{json, Value};
use std::fs::{self, File};
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

const DEFAULT_SMOKE_MODEL: &str = "qwen3:0.6b";
const STARTUP_TIMEOUT: Duration = Duration::from_secs(120);

fn smoke_model() -> String {
    std::env::var("FERRUM_G3_SMOKE_MODEL").unwrap_or_else(|_| DEFAULT_SMOKE_MODEL.to_string())
}

fn ferrum_bin() -> PathBuf {
    if let Ok(bin) = std::env::var("CARGO_BIN_EXE_ferrum") {
        return PathBuf::from(bin);
    }
    let current = std::env::current_exe().expect("test exe path");
    let dir = current
        .parent()
        .and_then(|p| p.parent())
        .expect("target dir");
    let mut bin = dir.join("ferrum");
    if cfg!(windows) {
        bin.set_extension("exe");
    }
    assert!(bin.exists(), "ferrum binary not found at {}", bin.display());
    bin
}

fn free_port() -> u16 {
    let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
    listener.local_addr().expect("local_addr").port()
}

fn unique_log_path(name: &str) -> PathBuf {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("clock")
        .as_nanos();
    std::env::temp_dir().join(format!("ferrum-g3-{name}-{}-{now}.log", std::process::id()))
}

fn workspace_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(|p| p.parent())
        .expect("workspace root")
        .to_path_buf()
}

fn log_tail(path: &PathBuf) -> String {
    const MAX_CHARS: usize = 16_000;
    let Ok(text) = fs::read_to_string(path) else {
        return format!("unable to read {}", path.display());
    };
    if text.chars().count() <= MAX_CHARS {
        return text;
    }
    let tail = text
        .chars()
        .rev()
        .take(MAX_CHARS)
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect::<String>();
    format!("... truncated ...\n{tail}")
}

fn spawn_diag(bin: &PathBuf) -> String {
    let env_value = |key: &str| std::env::var(key).unwrap_or_else(|_| "<unset>".to_string());
    format!(
        "ferrum_bin={}\nHOME={}\nHF_HOME={}\nXDG_CACHE_HOME={}\nCARGO_BIN_EXE_ferrum={}",
        bin.display(),
        env_value("HOME"),
        env_value("HF_HOME"),
        env_value("XDG_CACHE_HOME"),
        env_value("CARGO_BIN_EXE_ferrum")
    )
}

struct ServerFixture {
    base_url: String,
    child: Child,
    log_path: PathBuf,
}

impl ServerFixture {
    async fn spawn(extra_args: &[&str], name: &str) -> Self {
        let port = free_port();
        let base_url = format!("http://127.0.0.1:{port}");
        let log_path = unique_log_path(name);
        let log = File::create(&log_path).expect("create server log");
        let mut args = vec![
            "serve".to_string(),
            smoke_model(),
            "--host".to_string(),
            "127.0.0.1".to_string(),
            "--port".to_string(),
        ];
        let port_string = port.to_string();
        args.push(port_string);
        args.extend(extra_args.iter().map(|arg| (*arg).to_string()));
        let bin = ferrum_bin();
        let diag = spawn_diag(&bin);
        let mut child = Command::new(&bin)
            .args(&args)
            .current_dir(workspace_root())
            .env("NO_COLOR", "1")
            .stdout(Stdio::from(log.try_clone().expect("clone server log")))
            .stderr(Stdio::from(log))
            .spawn()
            .expect("spawn ferrum serve");

        let client = Client::new();
        let healthz = format!("{base_url}/health");
        let start = Instant::now();
        loop {
            if start.elapsed() > STARTUP_TIMEOUT {
                let _ = child.kill();
                let _ = child.wait();
                panic!(
                    "server did not become healthy within {STARTUP_TIMEOUT:?}\n{diag}\nlog:\n{}",
                    log_tail(&log_path)
                );
            }
            if let Some(status) = child.try_wait().expect("poll ferrum serve child") {
                panic!(
                    "server exited before healthy: {status}\n{diag}\nlog:\n{}",
                    log_tail(&log_path)
                );
            }
            let ok = client
                .get(&healthz)
                .timeout(Duration::from_secs(2))
                .send()
                .await
                .map(|r| r.status().is_success())
                .unwrap_or(false);
            if ok {
                break;
            }
            tokio::time::sleep(Duration::from_millis(500)).await;
        }

        Self {
            base_url,
            child,
            log_path,
        }
    }

    fn chat_url(&self) -> String {
        format!("{}/v1/chat/completions", self.base_url)
    }

    fn metrics_url(&self) -> String {
        format!("{}/metrics", self.base_url)
    }

    fn health_url(&self) -> String {
        format!("{}/health", self.base_url)
    }
}

impl Drop for ServerFixture {
    fn drop(&mut self) {
        let _ = self.child.kill();
        let _ = self.child.wait();
        if let Ok(text) = fs::read_to_string(&self.log_path) {
            for bad in [
                "panicked",
                "KV cache overflow",
                "failed to render model chat template",
                "<unk>",
                "[PAD]",
            ] {
                assert!(!text.contains(bad), "server log contains {bad}: {text}");
            }
        }
        let _ = fs::remove_file(&self.log_path);
    }
}

async fn chat(client: &Client, fx: &ServerFixture, content: &str) -> String {
    let response = client
        .post(fx.chat_url())
        .json(&json!({
            "model": smoke_model(),
            "messages": [{"role": "user", "content": content}],
            "temperature": 0.0,
            "max_tokens": 256
        }))
        .send()
        .await
        .expect("chat post");
    assert_eq!(response.status(), 200);
    let body: Value = response.json().await.expect("chat json");
    let message = &body["choices"][0]["message"];
    let content = message["content"].as_str().unwrap_or_default().trim();
    let reasoning = message["reasoning"].as_str().unwrap_or_default().trim();
    let output = [reasoning, content]
        .into_iter()
        .filter(|part| !part.is_empty())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(!output.is_empty(), "empty chat output: {body}");
    output
}

async fn strict_json_answer(
    client: &Client,
    fx: &ServerFixture,
    prompt: &str,
    expected: &str,
) -> Value {
    let response = client
        .post(fx.chat_url())
        .json(&json!({
            "model": smoke_model(),
            "messages": [{"role": "user", "content": prompt}],
            "temperature": 0.0,
            "max_tokens": 384,
            "response_format": strict_answer_schema()
        }))
        .send()
        .await
        .expect("strict answer post");
    let status = response.status();
    let raw = response.text().await.expect("strict answer body");
    assert_eq!(status, 200, "strict answer failed: {raw}");
    let body: Value = serde_json::from_str(&raw).expect("strict answer json");
    let content = body["choices"][0]["message"]["content"]
        .as_str()
        .unwrap_or_else(|| panic!("missing strict content: {body}"));
    let parsed: Value = serde_json::from_str(content)
        .unwrap_or_else(|e| panic!("invalid strict JSON {content:?}: {e}"));
    assert_eq!(parsed["answer"], expected, "body: {body}");
    parsed
}

async fn metrics(client: &Client, fx: &ServerFixture) -> String {
    client
        .get(fx.metrics_url())
        .send()
        .await
        .expect("metrics")
        .text()
        .await
        .expect("metrics text")
}

async fn health(client: &Client, fx: &ServerFixture) -> Value {
    client
        .get(fx.health_url())
        .send()
        .await
        .expect("health")
        .json()
        .await
        .expect("health json")
}

fn metric_value(metrics: &str, name: &str) -> f64 {
    metrics
        .lines()
        .filter(|line| !line.starts_with('#'))
        .find_map(|line| {
            let mut parts = line.split_whitespace();
            (parts.next()? == name)
                .then(|| parts.next()?.parse::<f64>().ok())
                .flatten()
        })
        .unwrap_or_else(|| panic!("missing metric {name}:\n{metrics}"))
}

fn strict_answer_schema() -> Value {
    json!({
        "type": "json_schema",
        "json_schema": {
            "name": "Answer",
            "strict": true,
            "schema": {
                "type": "object",
                "properties": {"answer": {"type": "string"}},
                "required": ["answer"]
            }
        }
    })
}

fn calc_tool() -> Value {
    json!({
        "type": "function",
        "function": {
            "name": "calc",
            "parameters": {
                "type": "object",
                "properties": {"expression": {"type": "string", "enum": ["123+456"]}},
                "required": ["expression"]
            }
        }
    })
}

#[tokio::test(flavor = "current_thread")]
#[ignore = "loads qwen3:0.6b real model"]
async fn g3_prefix_cache_product_real_model_smoke() {
    let client = Client::new();
    let enabled = ServerFixture::spawn(
        &[
            "--enable-prefix-cache",
            "--session-cache",
            "off",
            "--session-cache-max-entries",
            "32",
        ],
        "prefix-enabled",
    )
    .await;

    let prompt = concat!(
        "Ferrum prefix-cache verification prompt. The shared prefix is intentionally long ",
        "and stable so it crosses at least two paged-KV blocks before the requested answer. ",
        "alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu nu xi omicron ",
        "pi rho sigma tau upsilon phi chi psi omega. Reply with exactly: ferrum-cache-ok"
    );
    let first = chat(&client, &enabled, prompt).await;
    let second = chat(&client, &enabled, prompt).await;
    assert_eq!(first, second, "greedy output changed with prefix cache");
    let repeated_metrics = metrics(&client, &enabled).await;
    assert!(
        metric_value(&repeated_metrics, "ferrum_prefix_cache_hits_total") > 0.0,
        "repeating an identical long prompt did not hit prefix cache:\n{repeated_metrics}"
    );
    assert!(
        metric_value(
            &repeated_metrics,
            "ferrum_prefix_cache_saved_prefill_tokens_total"
        ) > 0.0,
        "repeating an identical long prompt did not save prefill tokens:\n{repeated_metrics}"
    );

    let alpha = strict_json_answer(
        &client,
        &enabled,
        "Shared prefix: marker request. Return exactly this JSON object and nothing else: {\"answer\":\"alpha-token\"}",
        "alpha-token",
    )
    .await;
    let beta = strict_json_answer(
        &client,
        &enabled,
        "Shared prefix: marker request. Return exactly this JSON object and nothing else: {\"answer\":\"beta-token\"}",
        "beta-token",
    )
    .await;
    assert_ne!(
        alpha["answer"], beta["answer"],
        "shared-prefix outputs cross-talked"
    );

    let strict = client
        .post(enabled.chat_url())
        .json(&json!({
            "model": smoke_model(),
            "messages": [{"role": "user", "content": "Return exactly this JSON object and nothing else: {\"answer\":\"cache-ok\"}"}],
            "temperature": 0.0,
            "max_tokens": 384,
            "response_format": strict_answer_schema()
        }))
        .send()
        .await
        .expect("strict post");
    assert_eq!(strict.status(), 200);
    let strict_body: Value = strict.json().await.expect("strict json");
    let strict_content = strict_body["choices"][0]["message"]["content"]
        .as_str()
        .unwrap();
    assert!(serde_json::from_str::<Value>(strict_content).is_ok());

    let tool = client
        .post(enabled.chat_url())
        .json(&json!({
            "model": smoke_model(),
            "messages": [{"role": "user", "content": "Use the calc tool. Return only JSON arguments: {\"expression\":\"123+456\"}"}],
            "tools": [calc_tool()],
            "tool_choice": "required",
            "temperature": 0.0,
            "max_tokens": 128
        }))
        .send()
        .await
        .expect("tool post");
    assert_eq!(tool.status(), 200);
    let tool_body: Value = tool.json().await.expect("tool json");
    assert_eq!(tool_body["choices"][0]["finish_reason"], "tool_calls");

    let enabled_metrics = metrics(&client, &enabled).await;
    assert!(metric_value(&enabled_metrics, "ferrum_prefix_cache_hits_total") > 0.0);
    assert!(
        metric_value(
            &enabled_metrics,
            "ferrum_prefix_cache_saved_prefill_tokens_total"
        ) > 0.0
    );
    let enabled_health = health(&client, &enabled).await;
    let prefix = &enabled_health["cache"]["prefix_cache"];
    assert_eq!(prefix["enabled"], true);
    assert_eq!(prefix["position"], "real-kv-reuse");
    assert!(
        prefix["saved_prefill_tokens"].as_u64().unwrap_or(0) > 0,
        "real KV prefix cache did not report saved tokens: {enabled_health}"
    );
    drop(enabled);

    let disabled = ServerFixture::spawn(
        &["--disable-prefix-cache", "--session-cache", "off"],
        "prefix-disabled",
    )
    .await;
    let _ = chat(&client, &disabled, prompt).await;
    let _ = chat(&client, &disabled, prompt).await;
    let disabled_metrics = metrics(&client, &disabled).await;
    assert_eq!(
        metric_value(&disabled_metrics, "ferrum_prefix_cache_hits_total"),
        0.0
    );
    let disabled_health = health(&client, &disabled).await;
    assert_eq!(disabled_health["cache"]["prefix_cache"]["enabled"], false);
}