veloq-core 0.4.1

Shared envelope, ProfileSource trait, and sort/time helpers for the VeloQ profile-query CLI.
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
440
441
442
443
444
445
446
447
448
449
450
//! Versioned bincode sidecar cache inside a report artifact directory.
//!
//! Multiple veloq subsystems cache derived state under the report's
//! `<report>.veloq/` root. They all want the same primitive:
//! serialize a typed payload with a `u32` version header and a
//! `(mtime, size)` fingerprint of the source file, decode lazily on
//! warm calls, and rebuild on any of (version mismatch, source
//! changed, decode failure).
//!
//! [`SidecarCache<T>`] is that primitive. Each call site picks the
//! path suffix, the version constant, the human-readable label that
//! appears in `log::info!` lines, and a payload type that derives
//! `serde::{Serialize, DeserializeOwned}`. On-disk layout:
//!
//! ```text
//! [u32 version][i64 source_mtime_secs][u64 source_size][bincode payload]
//! ```
//!
//!

//! Caches with bespoke on-disk formats (Parquet's TOML manifest, NCU's
//! JSON disasm cache) stay on their own; this helper is for the
//! "bincode blob with a version byte" case only.

use crate::{ErrorCode, VeloqDiagnostic};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::fs;
use std::marker::PhantomData;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
use thiserror::Error;

pub type SidecarResult<T> = Result<T, SidecarError>;

#[derive(Debug, Error)]
pub enum SidecarError {
    #[error("reading {label} at {path}")]
    Read {
        label: &'static str,
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("decoding {label} header")]
    DecodeHeader {
        label: &'static str,
        #[source]
        source: bincode::error::DecodeError,
    },
    #[error("decoding {label}")]
    Decode {
        label: &'static str,
        #[source]
        source: bincode::error::DecodeError,
    },
    #[error("encoding {label}")]
    Encode {
        label: &'static str,
        #[source]
        source: bincode::error::EncodeError,
    },
    #[error("creating {label} parent directory at {path}")]
    CreateParent {
        label: &'static str,
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("writing {label} temp file at {path}")]
    WriteTemp {
        label: &'static str,
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("renaming {label} temp into place at {path}")]
    Rename {
        label: &'static str,
        path: String,
        #[source]
        source: std::io::Error,
    },
}

impl VeloqDiagnostic for SidecarError {
    fn code(&self) -> ErrorCode {
        match self {
            Self::Read { .. } => ErrorCode::IO_READ,
            Self::DecodeHeader { .. } | Self::Decode { .. } => ErrorCode::SIDECAR_DECODE,
            Self::Encode { .. } => ErrorCode::SIDECAR_ENCODE,
            Self::CreateParent { .. } => ErrorCode::IO_CREATE_DIR,
            Self::WriteTemp { .. } => ErrorCode::IO_WRITE,
            Self::Rename { .. } => ErrorCode::IO_PUBLISH,
        }
    }
}

/// File-system fingerprint of the source artifact a sidecar covers.
/// Captures the two facts every cache invalidation depends on:
/// modification time (seconds since the Unix epoch) and size.
///
/// `mtime_secs == 0` on platforms where `Metadata::modified()` errors
/// out — the fallback is documented at the call site rather than
/// silently disabling invalidation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SourceFingerprint {
    pub mtime_secs: i64,
    pub size: u64,
}

impl SourceFingerprint {
    /// Read the fingerprint from `source`'s filesystem metadata.
    pub fn of_path(source: &Path) -> std::io::Result<Self> {
        let meta = fs::metadata(source)?;
        Ok(Self::of_metadata(&meta))
    }

    /// Build from already-read metadata (avoids a second `stat` when
    /// the caller already has it on hand).
    pub fn of_metadata(meta: &fs::Metadata) -> Self {
        let mtime_secs = meta
            .modified()
            .ok()
            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        Self {
            mtime_secs,
            size: meta.len(),
        }
    }
}

/// Sidecar payload reader/writer for type `T`.
///
/// Construct once with the on-disk path, a version constant, and a
/// label (the noun that appears in `"<label> version mismatch …"` /
/// `"wrote <label>: …"` log lines). [`try_load`] checks the version
/// header and source fingerprint before decoding; [`write`] serializes
/// then atomically renames the result into place.
///
/// [`try_load`]: SidecarCache::try_load
/// [`write`]: SidecarCache::write
pub struct SidecarCache<T> {
    path: PathBuf,
    version: u32,
    label: &'static str,
    _phantom: PhantomData<fn() -> T>,
}

impl<T> SidecarCache<T> {
    pub fn new(path: PathBuf, version: u32, label: &'static str) -> Self {
        Self {
            path,
            version,
            label,
            _phantom: PhantomData,
        }
    }

    pub fn path(&self) -> &Path {
        &self.path
    }
}

/// On-disk header peek: format version + source fingerprint, without
/// decoding the payload. Returned by [`SidecarCache::read_header`].
///
/// Useful for inspection verbs (`veloq prep --status`) that want to
/// report the on-disk format version next to the current expected
/// one, including for caches that fail fingerprint match — `try_load`
/// folds those down to `Ok(None)` so the version becomes invisible.
#[derive(Debug, Clone, Copy)]
pub struct SidecarHeader {
    pub version: u32,
    pub fingerprint: SourceFingerprint,
}

impl<T> SidecarCache<T> {
    /// Peek the on-disk header (version + source fingerprint) without
    /// reading the payload. `Ok(None)` for missing files; decode
    /// errors propagate so a corrupt sidecar is visible rather than
    /// silently treated as absent.
    pub fn read_header(&self) -> SidecarResult<Option<SidecarHeader>> {
        if !self.path.exists() {
            return Ok(None);
        }
        let bytes = fs::read(&self.path).map_err(|source| SidecarError::Read {
            label: self.label,
            path: path_string(&self.path),
            source,
        })?;
        // The header struct mirrors the leading three fields of
        // `CacheFile<T>` exactly. bincode's positional encoding means
        // decoding just the header from the start of the buffer
        // works — `decode_from_slice` doesn't require full
        // consumption of the input.
        #[derive(serde::Deserialize)]
        struct HeaderOnly {
            version: u32,
            source_mtime_secs: i64,
            source_size: u64,
        }
        let (h, _read): (HeaderOnly, _) =
            bincode::serde::decode_from_slice(&bytes, bincode::config::standard()).map_err(
                |source| SidecarError::DecodeHeader {
                    label: self.label,
                    source,
                },
            )?;
        Ok(Some(SidecarHeader {
            version: h.version,
            fingerprint: SourceFingerprint {
                mtime_secs: h.source_mtime_secs,
                size: h.source_size,
            },
        }))
    }
}

impl<T: DeserializeOwned> SidecarCache<T> {
    /// Decode the sidecar if it exists, matches the configured
    /// version, and matches `source_fp`. Returns `Ok(None)` for any
    /// "skip + rebuild" condition (missing, version mismatch, source
    /// changed) with an info-level log line explaining which check
    /// failed. Decode/I/O errors propagate as `Err` so the caller
    /// can decide whether to rebuild or surface.
    pub fn try_load(&self, source_fp: SourceFingerprint) -> SidecarResult<Option<T>> {
        if !self.path.exists() {
            return Ok(None);
        }
        let bytes = fs::read(&self.path).map_err(|source| SidecarError::Read {
            label: self.label,
            path: path_string(&self.path),
            source,
        })?;
        let (file, _read): (CacheFile<T>, _) =
            bincode::serde::decode_from_slice(&bytes, bincode::config::standard()).map_err(
                |source| SidecarError::Decode {
                    label: self.label,
                    source,
                },
            )?;
        if file.version != self.version {
            log::info!(
                "{} version mismatch ({} vs {}); rebuilding",
                self.label,
                file.version,
                self.version
            );
            return Ok(None);
        }
        if file.source_mtime_secs != source_fp.mtime_secs || file.source_size != source_fp.size {
            log::info!(
                "trace file changed since {} was written; rebuilding",
                self.label
            );
            return Ok(None);
        }
        Ok(Some(file.payload))
    }
}

impl<T: Serialize> SidecarCache<T> {
    /// Encode `payload` and atomically replace the sidecar. The on-disk
    /// header records `source_fp`, which `try_load` will match against
    /// the *current* fingerprint of the source file on the next open.
    ///
    /// Writes via a `<path>.tmp` sibling + `rename(2)` so a crashed
    /// write never leaves a half-corrupt sidecar in place.
    pub fn write(&self, source_fp: SourceFingerprint, payload: &T) -> SidecarResult<()> {
        let file = CacheFileRef {
            version: self.version,
            source_mtime_secs: source_fp.mtime_secs,
            source_size: source_fp.size,
            payload,
        };
        let bytes = bincode::serde::encode_to_vec(&file, bincode::config::standard()).map_err(
            |source| SidecarError::Encode {
                label: self.label,
                source,
            },
        )?;
        let mut tmp = self.path.as_os_str().to_owned();
        tmp.push(".tmp");
        let tmp_path = PathBuf::from(tmp);
        if let Some(parent) = self.path.parent() {
            fs::create_dir_all(parent).map_err(|source| SidecarError::CreateParent {
                label: self.label,
                path: path_string(parent),
                source,
            })?;
        }
        fs::write(&tmp_path, &bytes).map_err(|source| SidecarError::WriteTemp {
            label: self.label,
            path: path_string(&tmp_path),
            source,
        })?;
        fs::rename(&tmp_path, &self.path).map_err(|source| SidecarError::Rename {
            label: self.label,
            path: path_string(&self.path),
            source,
        })?;
        log::info!(
            "wrote {}: {} bytes → {}",
            self.label,
            bytes.len(),
            self.path.display()
        );
        Ok(())
    }
}

fn path_string(path: &Path) -> String {
    path.display().to_string()
}

/// Owned on-disk shape used during decode. Field names are
/// load-bearing because bincode uses serde and serde tags field
/// indices on `T: Serialize` derived structs; renaming would break
/// compatibility with caches written before this helper landed.
#[derive(Serialize, Deserialize)]
struct CacheFile<T> {
    version: u32,
    source_mtime_secs: i64,
    source_size: u64,
    payload: T,
}

/// Borrowed-payload variant for write. Bincode-with-standard-config
/// produces byte-identical output to [`CacheFile<T>`] because the
/// fields are positional + serialized in declaration order. Lets the
/// caller pass `&T` without cloning.
#[derive(Serialize)]
struct CacheFileRef<'a, T> {
    version: u32,
    source_mtime_secs: i64,
    source_size: u64,
    payload: &'a T,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};
    use std::error::Error;
    use std::fs;
    use std::path::PathBuf;

    type TestResult<T> = Result<T, Box<dyn Error>>;

    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
    struct Demo {
        n: u32,
        s: String,
    }

    fn tmpdir() -> TestResult<PathBuf> {
        let d = std::env::temp_dir().join(format!(
            "veloq-sidecar-test-{}",
            std::process::id() as u64 * 1_000_000
                + std::time::SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_nanos() as u64)
                    .unwrap_or(0)
        ));
        fs::create_dir_all(&d)?;
        Ok(d)
    }

    fn fp(mtime: i64, size: u64) -> SourceFingerprint {
        SourceFingerprint {
            mtime_secs: mtime,
            size,
        }
    }

    #[test]
    fn round_trip_load_returns_written_payload() -> TestResult<()> {
        let dir = tmpdir()?;
        let path = dir.join("demo.cache");
        let cache: SidecarCache<Demo> = SidecarCache::new(path, 7, "demo cache");
        let payload = Demo {
            n: 42,
            s: "hello".into(),
        };
        cache.write(fp(1234, 999), &payload)?;
        let back = cache
            .try_load(fp(1234, 999))?
            .ok_or_else(|| std::io::Error::other("just-written cache should load"))?;
        assert_eq!(back, payload);
        Ok(())
    }

    #[test]
    fn try_load_missing_returns_none() -> TestResult<()> {
        let dir = tmpdir()?;
        let path = dir.join("does-not-exist.cache");
        let cache: SidecarCache<Demo> = SidecarCache::new(path, 1, "demo cache");
        assert!(cache.try_load(fp(0, 0))?.is_none());
        Ok(())
    }

    #[test]
    fn version_mismatch_rebuilds() -> TestResult<()> {
        let dir = tmpdir()?;
        let path = dir.join("demo.cache");
        let writer: SidecarCache<Demo> = SidecarCache::new(path.clone(), 1, "demo cache");
        writer.write(
            fp(1, 1),
            &Demo {
                n: 1,
                s: "x".into(),
            },
        )?;
        let reader: SidecarCache<Demo> = SidecarCache::new(path, 2, "demo cache");
        assert!(reader.try_load(fp(1, 1))?.is_none());
        Ok(())
    }

    #[test]
    fn source_changed_rebuilds() -> TestResult<()> {
        let dir = tmpdir()?;
        let path = dir.join("demo.cache");
        let cache: SidecarCache<Demo> = SidecarCache::new(path, 1, "demo cache");
        cache.write(
            fp(1, 100),
            &Demo {
                n: 1,
                s: "x".into(),
            },
        )?;
        assert!(cache.try_load(fp(2, 100))?.is_none(), "mtime change");
        assert!(cache.try_load(fp(1, 200))?.is_none(), "size change");
        assert!(cache.try_load(fp(1, 100))?.is_some(), "matching fp");
        Ok(())
    }

    #[test]
    fn fingerprint_from_real_file_round_trips() -> TestResult<()> {
        let dir = tmpdir()?;
        let src = dir.join("source.bin");
        fs::write(&src, b"hello world")?;
        let fp1 = SourceFingerprint::of_path(&src)?;
        assert_eq!(fp1.size, 11);
        // mtime_secs varies — just check it isn't an obvious sentinel.
        assert!(fp1.mtime_secs > 1_000_000_000);
        Ok(())
    }
}