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
//! What the server actually knows about the model it loaded.
//!
//! `/realize/model` and the Ollama discovery endpoints (`/api/tags`,
//! `/api/show`) report model metadata. Before this type existed they reported
//! *constants*: `size_bytes: 0`, `context_length: 4096`,
//! `quantization: "Q4_K_M"`, `format: "gguf"` and a `content_hash` of
//! `"blake3:0".repeat(16)` — a 128-character string shaped exactly like a real
//! BLAKE3 digest, which a consumer will happily store and compare as
//! provenance. Every one of those was wrong for at least one shipped model,
//! and the hash was wrong for all of them.
//!
//! The rule this type enforces: **every field is either measured or absent.**
//! Each accessor returns `Option`, `None` means "this server does not know",
//! and the handlers omit unknown fields from the JSON rather than substituting
//! a plausible-looking default. An absent field is a fact a client can act on;
//! a fabricated one is not.
use std::path::Path;
/// Measured provenance/metadata for the model this server is serving.
///
/// Built by the process that loaded the model (`apr serve run`), attached to
/// [`super::AppState`] via `with_model_source`, and read by the metadata
/// handlers. Construct with [`ModelSourceInfo::from_path`] so `size_bytes` and
/// `format` come from the file itself; layer on what the loader learned with
/// the `with_*` builders.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ModelSourceInfo {
path: Option<String>,
size_bytes: Option<u64>,
format: Option<String>,
quantization: Option<String>,
architecture: Option<String>,
/// Context length this server was CONFIGURED with (`--context-length`),
/// NOT the model's advertised maximum — a server started with
/// `--context-length 128` must not report 4096, and must not report the
/// model's 32768 either. These are three different facts.
context_length: Option<usize>,
/// Model's own advertised maximum context, when the loader read one.
model_max_context_length: Option<usize>,
content_hash: Option<String>,
parameter_count: Option<u64>,
}
/// Identify a model container from its leading bytes.
///
/// Returns `None` rather than guessing: an unrecognised container is reported
/// as unknown, never as "gguf".
#[must_use]
pub fn detect_format_from_magic(magic: &[u8]) -> Option<&'static str> {
if magic.starts_with(b"GGUF") {
return Some("gguf");
}
// APR v2 is "APR\0", v1 is "APRN"; both share the 3-byte "APR" prefix.
if magic.starts_with(&crate::apr::MAGIC_PREFIX) {
return Some("apr");
}
// SafeTensors: 8-byte little-endian header length, then a JSON object.
if magic.len() > 8 && magic[8] == b'{' {
return Some("safetensors");
}
None
}
impl ModelSourceInfo {
/// Measure what the file itself tells us: absolute path, byte size, and
/// container format (from magic bytes, not the extension).
///
/// Unreadable metadata leaves the corresponding field `None`; this never
/// fails, because a missing metadata field must not stop the server from
/// serving.
#[must_use]
pub fn from_path(path: &Path) -> Self {
let size_bytes = std::fs::metadata(path).ok().map(|m| m.len());
let format = read_magic(path)
.as_deref()
.and_then(detect_format_from_magic)
.map(str::to_string);
let path_str = std::fs::canonicalize(path)
.unwrap_or_else(|_| path.to_path_buf())
.to_string_lossy()
.into_owned();
Self {
path: Some(path_str),
size_bytes,
format,
..Self::default()
}
}
/// Record the quantization actually present in the loaded weights.
#[must_use]
pub fn with_quantization(mut self, quantization: impl Into<String>) -> Self {
self.quantization = Some(quantization.into());
self
}
/// Record the model architecture the loader identified (e.g. `qwen2`).
#[must_use]
pub fn with_architecture(mut self, architecture: impl Into<String>) -> Self {
self.architecture = Some(architecture.into());
self
}
/// Record the context length this server was configured with.
#[must_use]
pub fn with_context_length(mut self, context_length: usize) -> Self {
self.context_length = Some(context_length);
self
}
/// Record the model's own advertised maximum context length.
#[must_use]
pub fn with_model_max_context_length(mut self, context_length: usize) -> Self {
self.model_max_context_length = Some(context_length);
self
}
/// Record a **computed** content hash, e.g. `blake3:<hex>`.
///
/// Only call this with a digest that was actually computed over the model
/// bytes. There is deliberately no default.
#[must_use]
pub fn with_content_hash(mut self, content_hash: impl Into<String>) -> Self {
self.content_hash = Some(content_hash.into());
self
}
/// Record the parameter count the loader derived from the weights.
#[must_use]
pub fn with_parameter_count(mut self, parameter_count: u64) -> Self {
self.parameter_count = Some(parameter_count);
self
}
/// Absolute path of the served model file, if it came from a file.
#[must_use]
pub fn path(&self) -> Option<&str> {
self.path.as_deref()
}
/// Size of the model file in bytes.
#[must_use]
pub fn size_bytes(&self) -> Option<u64> {
self.size_bytes
}
/// Container format (`gguf`, `apr`, `safetensors`).
#[must_use]
pub fn format(&self) -> Option<&str> {
self.format.as_deref()
}
/// Quantization of the loaded weights.
#[must_use]
pub fn quantization(&self) -> Option<&str> {
self.quantization.as_deref()
}
/// Model architecture.
#[must_use]
pub fn architecture(&self) -> Option<&str> {
self.architecture.as_deref()
}
/// Context length this server was configured with.
#[must_use]
pub fn context_length(&self) -> Option<usize> {
self.context_length
}
/// Model's advertised maximum context length.
#[must_use]
pub fn model_max_context_length(&self) -> Option<usize> {
self.model_max_context_length
}
/// Computed content hash of the model bytes.
#[must_use]
pub fn content_hash(&self) -> Option<&str> {
self.content_hash.as_deref()
}
/// Parameter count.
#[must_use]
pub fn parameter_count(&self) -> Option<u64> {
self.parameter_count
}
}
/// Read the first 16 bytes of a file for format detection.
fn read_magic(path: &Path) -> Option<Vec<u8>> {
use std::io::Read;
let mut file = std::fs::File::open(path).ok()?;
let mut buf = [0u8; 16];
let n = file.read(&mut buf).ok()?;
Some(buf[..n].to_vec())
}
/// Human-readable name for a GGUF quantization type id.
///
/// Derived from the qtype actually stored in the loaded tensors, which is the
/// ground truth — `general.file_type` in GGUF metadata is advisory and is
/// known to go stale when a file is requantized. The names come from the ggml type
/// table; the hand-typed copy this replaced knew 15 ids and reported no quantization
/// at all for every IQ type (#3662).
#[must_use]
pub fn gguf_qtype_name(qtype: u32) -> Option<&'static str> {
trueno_quant::GgmlType::from_id(qtype).map(trueno_quant::GgmlType::as_str)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_source_knows_nothing_and_admits_it() {
// The point of the type: an empty source reports absence, not defaults.
let src = ModelSourceInfo::default();
assert_eq!(src.size_bytes(), None);
assert_eq!(src.format(), None);
assert_eq!(src.quantization(), None);
assert_eq!(src.context_length(), None);
assert_eq!(src.content_hash(), None, "never invent a content hash");
}
#[test]
fn detect_format_recognises_the_three_containers() {
assert_eq!(detect_format_from_magic(b"GGUF\0\0\0\0"), Some("gguf"));
assert_eq!(detect_format_from_magic(b"APR\0____"), Some("apr"));
assert_eq!(detect_format_from_magic(b"APRN____"), Some("apr"));
// SafeTensors: u64 header length then '{'.
let st = [8u8, 0, 0, 0, 0, 0, 0, 0, b'{', b'"'];
assert_eq!(detect_format_from_magic(&st), Some("safetensors"));
}
#[test]
fn unrecognised_magic_is_unknown_not_gguf() {
// The shipped defect reported "gguf" for every model regardless.
assert_eq!(detect_format_from_magic(b"\x7fELF\0\0\0\0"), None);
assert_eq!(detect_format_from_magic(b""), None);
}
#[test]
fn from_path_measures_size_and_format_of_a_real_file() {
let dir = std::env::temp_dir().join(format!(
"apr-model-source-{}-{}",
std::process::id(),
line!()
));
std::fs::create_dir_all(&dir).expect("mkdir");
let path = dir.join("tiny.gguf");
// 4-byte magic + 12 bytes of payload = 16 bytes on disk.
std::fs::write(&path, b"GGUF\x03\0\0\0\0\0\0\0\0\0\0\0").expect("write");
let src = ModelSourceInfo::from_path(&path);
assert_eq!(
src.size_bytes(),
Some(16),
"size must be the real file size"
);
assert_eq!(src.format(), Some("gguf"));
assert!(src.path().is_some_and(|p| p.ends_with("tiny.gguf")));
assert_eq!(src.content_hash(), None);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn from_path_on_a_missing_file_reports_absence_not_zero() {
let src = ModelSourceInfo::from_path(Path::new("/nonexistent/model.gguf"));
assert_eq!(src.size_bytes(), None, "a missing file is unknown, not 0");
assert_eq!(src.format(), None);
}
#[test]
fn builders_record_measured_values() {
let src = ModelSourceInfo::default()
.with_quantization("Q4_K")
.with_architecture("qwen2")
.with_context_length(128)
.with_model_max_context_length(32768)
.with_content_hash("blake3:deadbeef")
.with_parameter_count(1_500_000_000);
assert_eq!(src.quantization(), Some("Q4_K"));
assert_eq!(src.architecture(), Some("qwen2"));
assert_eq!(src.context_length(), Some(128));
assert_eq!(src.model_max_context_length(), Some(32768));
assert_eq!(src.content_hash(), Some("blake3:deadbeef"));
assert_eq!(src.parameter_count(), Some(1_500_000_000));
}
#[test]
fn qtype_names_cover_the_shipped_quantizations() {
assert_eq!(gguf_qtype_name(12), Some("Q4_K"));
assert_eq!(gguf_qtype_name(14), Some("Q6_K"));
assert_eq!(gguf_qtype_name(0), Some("F32"));
// Unknown ids must not be reported as some plausible quantization.
assert_eq!(gguf_qtype_name(9999), None);
}
/// #3662: the hand-typed table knew 15 ids, so every IQ quantization reported
/// no quantization at all.
#[test]
fn qtype_names_cover_every_live_family() {
assert_eq!(gguf_qtype_name(10), Some("Q2_K"));
assert_eq!(gguf_qtype_name(16), Some("IQ2_XXS"));
assert_eq!(gguf_qtype_name(23), Some("IQ4_XS"));
assert_eq!(gguf_qtype_name(30), Some("BF16"));
// Removed upstream (Q4_2, Q4_3): not a quantization anything can hold.
assert_eq!(gguf_qtype_name(4), None);
assert_eq!(gguf_qtype_name(5), None);
}
}