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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! Source-qualified JSON envelope every veloq subcommand wraps its
//! response (and every CLI error) in.
//!
//! The envelope-level [`ResponseMeta`] block carries `applied_scope`
//! (uniform scope echo), `next_steps` (per-verb follow-up hints), and
//! `warnings` (silent-failure guardrail notices). The
//! meta block is the structural location every list verb populates
//! with the same shape, so an agent reads one address regardless of
//! source. Multi-device refusal: see the `meta` module.
//!
//! The envelope-level [`TraceSpan`] (`{origin_ns, span_ns}`) is the
//! per-second normalisation denominator for cross-capture diffs.

use crate::diagnostic::{ErrorCode, VeloqDiagnostic};
use crate::meta::ResponseMeta;
use serde::Serialize;
use std::borrow::Cow;
use std::error::Error;

/// Wire-format version emitted on `Envelope.schema`. Bumps with the
/// envelope itself (e.g. adding a top-level field). Source-specific
/// shape changes belong in [`SourceRef::version`] instead.
pub const ENVELOPE_VERSION: &str = "v1";

/// Trace-wide origin + span an agent uses as the normalization
/// denominator. `origin_ns` is the primary-table `MIN(start)`
/// (`summary.primary_time_range_ns.start`); `span_ns` is the same
/// table's `MAX(end) - MIN(start)`. Both are absolute nanoseconds.
///
/// Present when a source can compute a trace-wide normalization
/// window. Absent for sources without that concept, for meta verbs
/// (`schema`, `sources`, `info`), and for errors that fired before the
/// source opened the trace.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct TraceSpan {
    pub origin_ns: i64,
    pub span_ns: i64,
}

/// Source-qualified success envelope. Generic in `T` so each
/// subcommand emits its strongly-typed response struct directly;
/// agents can deserialize into a known shape after reading `command`.
#[derive(Debug, Serialize)]
pub struct Envelope<T: Serialize> {
    pub schema: &'static str,
    pub source: SourceRef,
    /// Qualified verb — `<source>.<verb>` for source-owned commands
    /// (`nsys.stats`, `ncu.summary`), or just `<verb>` for meta verbs
    /// (`info`, `sources`, `clean`).
    pub command: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace: Option<EnvelopeTraceRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_span: Option<TraceSpan>,
    /// Envelope metadata block: `applied_scope`,
    /// `next_steps`, `warnings`. Omitted from serialised JSON when
    /// every sub-field is empty. Required (non-None) on success
    /// envelopes from every list verb that accepts scope filters —
    /// `wire_format_smoke` enforces structurally.
    #[serde(skip_serializing_if = "meta_is_absent")]
    pub meta: Option<ResponseMeta>,
    pub data: T,
}

/// Serde filter — omit `meta` from the wire when it is None or has
/// every sub-field empty.
fn meta_is_absent(m: &Option<ResponseMeta>) -> bool {
    match m {
        None => true,
        Some(m) => m.is_empty(),
    }
}

/// Identifies which profile backend produced the response. `version`
/// bumps independently per-source so adding a field to `nsys.stats`
/// rolls `nsys.version` without affecting `ncu.version`.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct SourceRef {
    pub kind: &'static str,
    pub version: &'static str,
}

/// Trace artifact reference. `kind` matches the producing
/// [`SourceRef::kind`] except for meta verbs that accept a trace
/// without specifying a source, where it carries the auto-detected
/// kind.
#[derive(Debug, Clone, Serialize)]
pub struct EnvelopeTraceRef {
    pub kind: &'static str,
    pub path: String,
}

/// Error variant of [`Envelope`]. `source`, `command`, and `trace`
/// are optional because some errors fire before dispatch knows which
/// source/verb the user wanted (clap parse failures, unknown
/// subcommand): those fields are absent and the agent should treat
/// the failure as CLI-level rather than command-level.
///
/// `meta` is present only when the error itself carries
/// scope-resolution context (e.g. an ambiguity refusal
/// populates `meta.applied_scope.device: null` plus a
/// `multi-device-ambiguous` warning so the agent can read the refusal
/// in structured form). For all other error paths, `meta` is omitted.
#[derive(Debug, Serialize)]
pub struct EnvelopeError {
    pub schema: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<SourceRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace: Option<EnvelopeTraceRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trace_span: Option<TraceSpan>,
    #[serde(skip_serializing_if = "meta_is_absent")]
    pub meta: Option<ResponseMeta>,
    pub error: EnvelopeErrorDetails,
}

#[derive(Debug, Serialize)]
pub struct EnvelopeErrorDetails {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub code: Option<ErrorCode>,
    /// User-facing summary — what an agent should surface first.
    pub message: String,
    /// Additional source entries, ordered from the immediate source
    /// inward. Empty when the error has no source chain.
    pub chain: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

impl<T: Serialize> Envelope<T> {
    /// Construct an envelope. `meta = None` is the default for meta
    /// verbs and other paths that don't carry envelope metadata. List
    /// verbs that accept scope filters MUST pass `Some(ResponseMeta {
    /// applied_scope: Some(...), .. })` on success.
    pub fn new(
        source: SourceRef,
        command: impl Into<String>,
        trace: Option<EnvelopeTraceRef>,
        trace_span: Option<TraceSpan>,
        meta: Option<ResponseMeta>,
        data: T,
    ) -> Self {
        Self {
            schema: ENVELOPE_VERSION,
            source,
            command: command.into(),
            trace,
            trace_span,
            meta,
            data,
        }
    }

    /// Serialize to a single-line JSON string. Agents consume one
    /// document per CLI invocation, so a newline-terminated dump is
    /// the default; pretty-printing is reserved for human inspection.
    pub fn to_json(&self) -> serde_json::Result<String> {
        serde_json::to_string(self)
    }

    /// Pretty (indented) serialization. Use for human inspection only.
    pub fn to_json_pretty(&self) -> serde_json::Result<String> {
        serde_json::to_string_pretty(self)
    }
}

/// Build the success envelope and print it to stdout. The single
/// construct-and-print point every source's emit path shares (NSys
/// `output::emit*`, NCU `source`), so the schema/version/qualified-
/// command wrapping + the `to_json_pretty` + `println!` tail live once.
/// Sources keep their own trace-span resolution and
/// pass the result in.
pub fn emit_envelope<T: Serialize>(
    source: SourceRef,
    command: impl Into<String>,
    trace: Option<EnvelopeTraceRef>,
    trace_span: Option<TraceSpan>,
    meta: Option<ResponseMeta>,
    data: T,
) -> serde_json::Result<()> {
    let env = Envelope::new(source, command, trace, trace_span, meta, data);
    println!("{}", env.to_json_pretty()?);
    Ok(())
}

impl EnvelopeError {
    /// Construct an error envelope. `meta = None` is the default; a
    /// scope-ambiguity refusal passes
    /// `Some(ResponseMeta { warnings: vec![...], .. })` so the agent
    /// can read the refusal in structured form.
    pub fn new(
        source: Option<SourceRef>,
        command: Option<String>,
        trace: Option<EnvelopeTraceRef>,
        trace_span: Option<TraceSpan>,
        meta: Option<ResponseMeta>,
        message: impl Into<String>,
        chain: Vec<String>,
    ) -> Self {
        Self {
            schema: ENVELOPE_VERSION,
            source,
            command,
            trace,
            trace_span,
            meta,
            error: EnvelopeErrorDetails {
                code: None,
                message: message.into(),
                chain,
                hint: None,
            },
        }
    }

    /// Project a standard error into an error envelope. The error's
    /// top-level rendering lands in `error.message`; each source in
    /// the chain becomes an `error.chain` entry.
    pub fn from_error(
        source: Option<SourceRef>,
        command: Option<String>,
        trace: Option<EnvelopeTraceRef>,
        trace_span: Option<TraceSpan>,
        err: &(dyn Error + 'static),
    ) -> Self {
        let message = err.to_string();
        let chain = std_error_chain(err);
        Self::new(source, command, trace, trace_span, None, message, chain)
    }

    pub fn from_diagnostic<E>(
        source: Option<SourceRef>,
        command: Option<String>,
        trace: Option<EnvelopeTraceRef>,
        trace_span: Option<TraceSpan>,
        err: &E,
    ) -> Self
    where
        E: VeloqDiagnostic,
    {
        let mut env = Self::new(
            source,
            command,
            trace,
            trace_span,
            None,
            err.message(),
            std_error_chain(err),
        );
        env.error.code = Some(err.code());
        env.error.hint = err.hint().map(Cow::into_owned);
        env
    }

    pub fn to_json(&self) -> serde_json::Result<String> {
        serde_json::to_string(self)
    }

    pub fn to_json_pretty(&self) -> serde_json::Result<String> {
        serde_json::to_string_pretty(self)
    }
}

fn std_error_chain(err: &(dyn Error + 'static)) -> Vec<String> {
    let mut chain = Vec::new();
    let mut current = err.source();
    while let Some(source) = current {
        chain.push(source.to_string());
        current = source.source();
    }
    chain
}

/// Write a source-level error envelope.
///
/// In `--format=csv` / `--format=table` (human-targeted), a one-line
/// `veloq: <error>` mirror goes to stderr and the structured
/// [`EnvelopeError`] JSON goes to stdout. In `--format=json` (the
/// agent contract, also the default) the stderr line is *suppressed*:
/// the JSON envelope on stdout is the single source of truth and
/// agents shouldn't have to dedupe a "veloq: …" line that says the
/// same thing.
///
/// The qualified command is built as `"<source.kind>.<verb>"`; pass
/// `verb` as the bare verb name (`"stats"`, `"summary"`). Source
/// authors should call this from their [`crate::ProfileSource::run`]
/// impl when a verb fails, then return `Ok(1)` so the caller knows
/// the envelope is already on the wire.
///
/// JSON serialization errors are swallowed deliberately: if we
/// already failed to render the user's actual error, raising a second
/// error from the renderer is strictly less informative.
pub fn write_error_envelope(
    source: SourceRef,
    verb: &str,
    trace: Option<EnvelopeTraceRef>,
    trace_span: Option<TraceSpan>,
    err: &(dyn Error + 'static),
    fmt: crate::OutputFormat,
) {
    let env = EnvelopeError::from_error(
        Some(source),
        Some(format!("{}.{verb}", source.kind)),
        trace,
        trace_span,
        err,
    );
    if !matches!(fmt, crate::OutputFormat::Json) {
        eprintln!("veloq: {err}");
    }
    if let Ok(s) = env.to_json_pretty() {
        println!("{s}");
    }
}

pub fn write_diagnostic_error_envelope<E>(
    source: SourceRef,
    verb: &str,
    trace: Option<EnvelopeTraceRef>,
    trace_span: Option<TraceSpan>,
    err: &E,
    fmt: crate::OutputFormat,
) where
    E: VeloqDiagnostic,
{
    let env = EnvelopeError::from_diagnostic(
        Some(source),
        Some(format!("{}.{verb}", source.kind)),
        trace,
        trace_span,
        err,
    );
    if !matches!(fmt, crate::OutputFormat::Json) {
        eprintln!("veloq: {err}");
    }
    if let Ok(s) = env.to_json_pretty() {
        println!("{s}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;

    fn source() -> SourceRef {
        SourceRef {
            kind: "nsys",
            version: "v0",
        }
    }

    fn trace() -> EnvelopeTraceRef {
        EnvelopeTraceRef {
            kind: "nsys",
            path: "/tmp/trace.nsys-rep".into(),
        }
    }

    /// Pull a value by JSON Pointer, erroring out if the path isn't
    /// present. Tests use this rather than `value["foo"]` indexing
    /// because the workspace lints deny panicking index ops.
    fn at<'a>(v: &'a Value, ptr: &str) -> anyhow::Result<&'a Value> {
        v.pointer(ptr)
            .ok_or_else(|| anyhow::anyhow!("missing pointer `{ptr}` in {v}"))
    }

    fn at_str<'a>(v: &'a Value, ptr: &str) -> anyhow::Result<&'a str> {
        at(v, ptr)?
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("not a string at `{ptr}` in {v}"))
    }

    fn span() -> TraceSpan {
        TraceSpan {
            origin_ns: 1_000_000,
            span_ns: 5_000_000_000,
        }
    }

    #[test]
    fn envelope_shape_has_qualified_command_and_source() -> anyhow::Result<()> {
        let env = Envelope::new(
            source(),
            "nsys.stats",
            Some(trace()),
            Some(span()),
            None,
            serde_json::json!({"rows": []}),
        );
        let v: Value = serde_json::from_str(&env.to_json()?)?;
        assert_eq!(at_str(&v, "/schema")?, "v1");
        assert_eq!(at_str(&v, "/source/kind")?, "nsys");
        assert_eq!(at_str(&v, "/source/version")?, "v0");
        assert_eq!(at_str(&v, "/command")?, "nsys.stats");
        assert_eq!(at_str(&v, "/trace/kind")?, "nsys");
        assert_eq!(at_str(&v, "/trace/path")?, "/tmp/trace.nsys-rep");
        assert_eq!(at(&v, "/trace_span/origin_ns")?.as_i64(), Some(1_000_000));
        assert_eq!(at(&v, "/trace_span/span_ns")?.as_i64(), Some(5_000_000_000));
        assert!(
            v.get("meta").is_none(),
            "meta with None payload must be omitted: {v}"
        );
        assert!(at(&v, "/data/rows")?.is_array());
        Ok(())
    }

    #[test]
    fn envelope_trace_and_span_omitted_when_none() -> anyhow::Result<()> {
        let env = Envelope::new(source(), "sources", None, None, None, serde_json::json!({}));
        let v: Value = serde_json::from_str(&env.to_json()?)?;
        assert!(v.get("trace").is_none(), "got: {v}");
        assert!(v.get("trace_span").is_none(), "got: {v}");
        assert!(v.get("meta").is_none(), "got: {v}");
        Ok(())
    }

    #[test]
    fn envelope_meta_serialises_when_applied_scope_set() -> anyhow::Result<()> {
        use crate::meta::{AppliedScope, ResponseMeta};
        let meta = ResponseMeta {
            applied_scope: Some(AppliedScope {
                device: Some(0),
                kind: Some("kernel".into()),
                ..AppliedScope::default()
            }),
            ..ResponseMeta::default()
        };
        let env = Envelope::new(
            source(),
            "nsys.stats",
            Some(trace()),
            Some(span()),
            Some(meta),
            serde_json::json!({"rows": []}),
        );
        let v: Value = serde_json::from_str(&env.to_json()?)?;
        assert_eq!(at(&v, "/meta/applied_scope/device")?.as_i64(), Some(0));
        assert_eq!(at_str(&v, "/meta/applied_scope/kind")?, "kernel");
        // Empty sub-fields stay absent on the wire.
        assert!(v.pointer("/meta/next_steps").is_none(), "got: {v}");
        assert!(v.pointer("/meta/warnings").is_none(), "got: {v}");
        Ok(())
    }

    #[test]
    fn envelope_meta_omitted_when_every_subfield_empty() -> anyhow::Result<()> {
        use crate::meta::ResponseMeta;
        let env = Envelope::new(
            source(),
            "nsys.stats",
            Some(trace()),
            Some(span()),
            Some(ResponseMeta::default()),
            serde_json::json!({"rows": []}),
        );
        let v: Value = serde_json::from_str(&env.to_json()?)?;
        assert!(
            v.get("meta").is_none(),
            "Some(empty ResponseMeta) must serialise as absent: {v}"
        );
        Ok(())
    }

    #[derive(Debug, thiserror::Error)]
    #[error("disk full")]
    struct DiskFull;

    #[derive(Debug, thiserror::Error)]
    #[error("writing parquet sidecar")]
    struct SidecarWriteError(#[source] DiskFull);

    #[derive(Debug, thiserror::Error)]
    #[error("caching trace summary")]
    struct TraceSummaryError(#[source] SidecarWriteError);

    #[test]
    fn envelope_error_carries_chain_from_std_error() -> anyhow::Result<()> {
        let wrapped = TraceSummaryError(SidecarWriteError(DiskFull));
        let env = EnvelopeError::from_error(
            Some(source()),
            Some("nsys.stats".into()),
            None,
            None,
            &wrapped,
        );
        let v: Value = serde_json::from_str(&env.to_json()?)?;
        assert_eq!(at_str(&v, "/schema")?, "v1");
        assert_eq!(at_str(&v, "/error/message")?, "caching trace summary");
        let chain = at(&v, "/error/chain")?
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("chain not an array"))?;
        let msgs: Vec<&str> = chain.iter().filter_map(|c| c.as_str()).collect();
        assert!(msgs.contains(&"writing parquet sidecar"), "got: {msgs:?}");
        assert!(msgs.contains(&"disk full"), "got: {msgs:?}");
        Ok(())
    }

    #[derive(Debug, thiserror::Error)]
    #[error("demo failed")]
    struct DemoDiagnostic {
        #[source]
        source: std::io::Error,
    }

    impl VeloqDiagnostic for DemoDiagnostic {
        fn code(&self) -> ErrorCode {
            ErrorCode::new("demo.failed")
        }
    }

    #[test]
    fn envelope_error_carries_code_from_diagnostic() -> anyhow::Result<()> {
        let err = DemoDiagnostic {
            source: std::io::Error::other("inner cause"),
        };
        let env = EnvelopeError::from_diagnostic(
            Some(source()),
            Some("nsys.stats".into()),
            None,
            None,
            &err,
        );
        let v: Value = serde_json::from_str(&env.to_json()?)?;
        assert_eq!(at_str(&v, "/error/code")?, "demo.failed");
        assert_eq!(at_str(&v, "/error/message")?, "demo failed");
        let chain = at(&v, "/error/chain")?
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("chain not an array"))?;
        let msgs: Vec<&str> = chain.iter().filter_map(|c| c.as_str()).collect();
        assert!(msgs.contains(&"inner cause"), "got: {msgs:?}");
        Ok(())
    }

    #[test]
    fn envelope_error_omits_optional_fields_when_unset() -> anyhow::Result<()> {
        let env = EnvelopeError::new(None, None, None, None, None, "boom", Vec::new());
        let v: Value = serde_json::from_str(&env.to_json()?)?;
        assert!(v.get("source").is_none());
        assert!(v.get("command").is_none());
        assert!(v.get("trace").is_none());
        assert!(v.get("trace_span").is_none());
        assert_eq!(at_str(&v, "/error/message")?, "boom");
        Ok(())
    }

    #[test]
    fn envelope_error_emits_trace_span_when_set() -> anyhow::Result<()> {
        let env = EnvelopeError::new(
            Some(source()),
            Some("nsys.stats".into()),
            Some(trace()),
            Some(span()),
            None,
            "boom",
            Vec::new(),
        );
        let v: Value = serde_json::from_str(&env.to_json()?)?;
        assert_eq!(at(&v, "/trace_span/origin_ns")?.as_i64(), Some(1_000_000));
        assert_eq!(at(&v, "/trace_span/span_ns")?.as_i64(), Some(5_000_000_000));
        Ok(())
    }
}