apr-cli 0.35.0

CLI tool for APR model inspection, debugging, and operations
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
//! Token-selection explanation classifier (CRUX-F-19).
//!
//! Pure, deterministic classifiers that discharge FALSIFY-CRUX-F-19-{001,002,003}
//! at the PARTIAL_ALGORITHM_LEVEL — algorithm-level necessary conditions on
//! an already-captured `apr explain --format jsonl` body (one JSON object per
//! line, each describing a sampled token plus its candidate list):
//!
//!   * `classify_schema` — every line parses as a JSON object with the
//!     5 required keys (`step`, `sampled_id`, `candidates`, optional
//!     `token_id`, optional `token_str`); each candidate has
//!     `token_id`, `pre_prob`, `post_prob`, `rank`.
//!   * `classify_probs_normalize` — Σ post_prob across each step's
//!     candidates ≈ 1.0 within 1e-5.
//!   * `classify_sampled_in_candidates` — `sampled_id` appears in the
//!     candidates list for every step (the sampler cannot return a
//!     token that wasn't in the considered set).
//!   * `classify_greedy_picks_argmax` — when the caller asserts the
//!     trace was produced under `--temp 0 --top-k 1`, every step's
//!     `sampled_id` equals the argmax of `pre_prob` across candidates.
//!
//! Full discharge blocks on a live `apr explain` emitter wired to the
//! sampler — tracked as BLOCKER-UPSTREAM-MISSING.

use serde_json::Value;

/// Outcome of `classify_schema`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExplainSchemaOutcome {
    Ok {
        line_count: usize,
    },
    Empty,
    LineNotJson {
        line_no: usize,
        message: String,
    },
    LineNotAnObject {
        line_no: usize,
    },
    LineMissingField {
        line_no: usize,
        field: &'static str,
    },
    CandidatesNotArray {
        line_no: usize,
    },
    CandidatesEmpty {
        line_no: usize,
    },
    CandidateNotAnObject {
        line_no: usize,
        index: usize,
    },
    CandidateMissingField {
        line_no: usize,
        index: usize,
        field: &'static str,
    },
}

/// Outcome of `classify_probs_normalize`.
#[derive(Debug, Clone, PartialEq)]
pub enum ExplainProbsOutcome {
    Ok,
    NotNormalized {
        line_no: usize,
        step: i64,
        sum: f64,
        tolerance: f64,
    },
}

/// Outcome of `classify_sampled_in_candidates`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExplainSampledOutcome {
    Ok,
    SampledNotInCandidates {
        line_no: usize,
        step: i64,
        sampled_id: i64,
    },
}

/// Outcome of `classify_greedy_picks_argmax`.
#[derive(Debug, Clone, PartialEq)]
pub enum ExplainGreedyOutcome {
    Ok,
    NotArgmax {
        line_no: usize,
        step: i64,
        sampled_id: i64,
        sampled_pre_prob: f64,
        argmax_id: i64,
        argmax_pre_prob: f64,
    },
}

/// Parse a JSONL body into a list of (line_no, line, parsed) tuples.
/// Returns the schema outcome on the first error encountered.
fn parse_jsonl(body: &str) -> Result<Vec<(usize, Value)>, ExplainSchemaOutcome> {
    let mut out = Vec::new();
    let mut nonblank = 0usize;
    for (idx, raw) in body.lines().enumerate() {
        let line_no = idx + 1;
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            continue;
        }
        nonblank += 1;
        let v: Value =
            serde_json::from_str(trimmed).map_err(|e| ExplainSchemaOutcome::LineNotJson {
                line_no,
                message: e.to_string(),
            })?;
        if !v.is_object() {
            return Err(ExplainSchemaOutcome::LineNotAnObject { line_no });
        }
        out.push((line_no, v));
    }
    if nonblank == 0 {
        return Err(ExplainSchemaOutcome::Empty);
    }
    Ok(out)
}

/// Schema gate: every JSONL line is an object with `step`, `sampled_id`, and
/// a non-empty `candidates` array of `{token_id, pre_prob, post_prob, rank}`.
pub fn classify_schema(body: &str) -> ExplainSchemaOutcome {
    let parsed = match parse_jsonl(body) {
        Ok(p) => p,
        Err(e) => return e,
    };
    for (line_no, v) in &parsed {
        for f in ["step", "sampled_id", "candidates"] {
            if v.get(f).is_none() {
                return ExplainSchemaOutcome::LineMissingField {
                    line_no: *line_no,
                    field: match f {
                        "step" => "step",
                        "sampled_id" => "sampled_id",
                        _ => "candidates",
                    },
                };
            }
        }
        let Some(cands) = v.get("candidates").and_then(Value::as_array) else {
            return ExplainSchemaOutcome::CandidatesNotArray { line_no: *line_no };
        };
        if cands.is_empty() {
            return ExplainSchemaOutcome::CandidatesEmpty { line_no: *line_no };
        }
        for (i, c) in cands.iter().enumerate() {
            if !c.is_object() {
                return ExplainSchemaOutcome::CandidateNotAnObject {
                    line_no: *line_no,
                    index: i,
                };
            }
            for f in ["token_id", "pre_prob", "post_prob", "rank"] {
                if c.get(f).is_none() {
                    return ExplainSchemaOutcome::CandidateMissingField {
                        line_no: *line_no,
                        index: i,
                        field: match f {
                            "token_id" => "token_id",
                            "pre_prob" => "pre_prob",
                            "post_prob" => "post_prob",
                            _ => "rank",
                        },
                    };
                }
            }
        }
    }
    ExplainSchemaOutcome::Ok {
        line_count: parsed.len(),
    }
}

/// Verify Σ post_prob ≈ 1.0 (within `tolerance`) per step.
pub fn classify_probs_normalize(body: &str, tolerance: f64) -> ExplainProbsOutcome {
    let parsed = match parse_jsonl(body) {
        Ok(p) => p,
        Err(_) => return ExplainProbsOutcome::Ok, // schema gate handles malformed input
    };
    for (line_no, v) in parsed {
        let step = v.get("step").and_then(Value::as_i64).unwrap_or(0);
        let Some(cands) = v.get("candidates").and_then(Value::as_array) else {
            continue;
        };
        let sum: f64 = cands
            .iter()
            .filter_map(|c| c.get("post_prob").and_then(Value::as_f64))
            .sum();
        if (sum - 1.0).abs() > tolerance {
            return ExplainProbsOutcome::NotNormalized {
                line_no,
                step,
                sum,
                tolerance,
            };
        }
    }
    ExplainProbsOutcome::Ok
}

/// Verify `sampled_id` is in `candidates[*].token_id` for every step.
pub fn classify_sampled_in_candidates(body: &str) -> ExplainSampledOutcome {
    let parsed = match parse_jsonl(body) {
        Ok(p) => p,
        Err(_) => return ExplainSampledOutcome::Ok,
    };
    for (line_no, v) in parsed {
        let step = v.get("step").and_then(Value::as_i64).unwrap_or(0);
        let sampled = v.get("sampled_id").and_then(Value::as_i64).unwrap_or(-1);
        let Some(cands) = v.get("candidates").and_then(Value::as_array) else {
            continue;
        };
        let found = cands
            .iter()
            .filter_map(|c| c.get("token_id").and_then(Value::as_i64))
            .any(|id| id == sampled);
        if !found {
            return ExplainSampledOutcome::SampledNotInCandidates {
                line_no,
                step,
                sampled_id: sampled,
            };
        }
    }
    ExplainSampledOutcome::Ok
}

/// Verify that under greedy decoding (`temp == 0`, `top_k == 1`) the
/// sampled token is the argmax of `pre_prob`.
pub fn classify_greedy_picks_argmax(body: &str) -> ExplainGreedyOutcome {
    let parsed = match parse_jsonl(body) {
        Ok(p) => p,
        Err(_) => return ExplainGreedyOutcome::Ok,
    };
    for (line_no, v) in parsed {
        let step = v.get("step").and_then(Value::as_i64).unwrap_or(0);
        let sampled = v.get("sampled_id").and_then(Value::as_i64).unwrap_or(-1);
        let Some(cands) = v.get("candidates").and_then(Value::as_array) else {
            continue;
        };
        let mut best: Option<(i64, f64)> = None;
        let mut sampled_pre: f64 = f64::NAN;
        for c in cands {
            let id = c.get("token_id").and_then(Value::as_i64).unwrap_or(-1);
            let pre = c.get("pre_prob").and_then(Value::as_f64).unwrap_or(0.0);
            if id == sampled {
                sampled_pre = pre;
            }
            match best {
                None => best = Some((id, pre)),
                Some((_, b)) if pre > b => best = Some((id, pre)),
                _ => {}
            }
        }
        let Some((argmax_id, argmax_pre)) = best else {
            continue;
        };
        if argmax_id != sampled {
            return ExplainGreedyOutcome::NotArgmax {
                line_no,
                step,
                sampled_id: sampled,
                sampled_pre_prob: sampled_pre,
                argmax_id,
                argmax_pre_prob: argmax_pre,
            };
        }
    }
    ExplainGreedyOutcome::Ok
}

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

    fn good_body() -> String {
        // Two steps with normalized probs and the sampled id present.
        let l0 = r#"{"step":0,"sampled_id":7,"candidates":[
            {"token_id":7,"pre_prob":0.6,"post_prob":0.7,"rank":0},
            {"token_id":3,"pre_prob":0.3,"post_prob":0.2,"rank":1},
            {"token_id":5,"pre_prob":0.1,"post_prob":0.1,"rank":2}
        ]}"#;
        let l1 = r#"{"step":1,"sampled_id":3,"candidates":[
            {"token_id":3,"pre_prob":0.5,"post_prob":0.5,"rank":0},
            {"token_id":7,"pre_prob":0.4,"post_prob":0.5,"rank":1}
        ]}"#;
        // Strip the embedded newlines/indentation so each line is one record.
        let mut out = String::new();
        out.push_str(&l0.split_whitespace().collect::<String>());
        out.push('\n');
        out.push_str(&l1.split_whitespace().collect::<String>());
        out.push('\n');
        out
    }

    #[test]
    fn schema_ok_on_good_body() {
        let out = classify_schema(&good_body());
        assert_eq!(out, ExplainSchemaOutcome::Ok { line_count: 2 });
    }

    #[test]
    fn schema_rejects_empty_body() {
        assert_eq!(classify_schema(""), ExplainSchemaOutcome::Empty);
    }

    #[test]
    fn schema_rejects_non_json_line() {
        let body = "not json\n";
        assert!(matches!(
            classify_schema(body),
            ExplainSchemaOutcome::LineNotJson { line_no: 1, .. }
        ));
    }

    #[test]
    fn schema_rejects_non_object_line() {
        let body = "[1,2,3]\n";
        assert_eq!(
            classify_schema(body),
            ExplainSchemaOutcome::LineNotAnObject { line_no: 1 }
        );
    }

    #[test]
    fn schema_rejects_missing_field() {
        let body =
            r#"{"step":0,"candidates":[{"token_id":1,"pre_prob":1.0,"post_prob":1.0,"rank":0}]}"#;
        assert!(matches!(
            classify_schema(body),
            ExplainSchemaOutcome::LineMissingField {
                line_no: 1,
                field: "sampled_id"
            }
        ));
    }

    #[test]
    fn schema_rejects_candidate_missing_field() {
        let body =
            r#"{"step":0,"sampled_id":1,"candidates":[{"token_id":1,"pre_prob":1.0,"rank":0}]}"#;
        assert!(matches!(
            classify_schema(body),
            ExplainSchemaOutcome::CandidateMissingField {
                line_no: 1,
                index: 0,
                field: "post_prob"
            }
        ));
    }

    #[test]
    fn schema_rejects_empty_candidates() {
        let body = r#"{"step":0,"sampled_id":1,"candidates":[]}"#;
        assert!(matches!(
            classify_schema(body),
            ExplainSchemaOutcome::CandidatesEmpty { line_no: 1 }
        ));
    }

    #[test]
    fn probs_normalize_ok_on_good_body() {
        assert_eq!(
            classify_probs_normalize(&good_body(), 1e-5),
            ExplainProbsOutcome::Ok
        );
    }

    #[test]
    fn probs_normalize_reports_violation() {
        let body = r#"{"step":0,"sampled_id":1,"candidates":[
            {"token_id":1,"pre_prob":0.5,"post_prob":0.6,"rank":0},
            {"token_id":2,"pre_prob":0.5,"post_prob":0.6,"rank":1}
        ]}"#;
        // Strip whitespace so it's one JSONL line.
        let body = body.split_whitespace().collect::<String>();
        assert!(matches!(
            classify_probs_normalize(&body, 1e-5),
            ExplainProbsOutcome::NotNormalized { .. }
        ));
    }

    #[test]
    fn sampled_in_candidates_ok_on_good_body() {
        assert_eq!(
            classify_sampled_in_candidates(&good_body()),
            ExplainSampledOutcome::Ok
        );
    }

    #[test]
    fn sampled_in_candidates_reports_missing() {
        let body = r#"{"step":0,"sampled_id":99,"candidates":[
            {"token_id":1,"pre_prob":1.0,"post_prob":1.0,"rank":0}
        ]}"#;
        let body = body.split_whitespace().collect::<String>();
        assert!(matches!(
            classify_sampled_in_candidates(&body),
            ExplainSampledOutcome::SampledNotInCandidates { sampled_id: 99, .. }
        ));
    }

    #[test]
    fn greedy_picks_argmax_ok_on_good_body() {
        assert_eq!(
            classify_greedy_picks_argmax(&good_body()),
            ExplainGreedyOutcome::Ok
        );
    }

    #[test]
    fn greedy_picks_argmax_reports_non_argmax() {
        // sampled_id=3 but argmax pre_prob is token 7
        let body = r#"{"step":0,"sampled_id":3,"candidates":[
            {"token_id":7,"pre_prob":0.9,"post_prob":1.0,"rank":0},
            {"token_id":3,"pre_prob":0.1,"post_prob":0.0,"rank":1}
        ]}"#;
        let body = body.split_whitespace().collect::<String>();
        match classify_greedy_picks_argmax(&body) {
            ExplainGreedyOutcome::NotArgmax {
                sampled_id,
                argmax_id,
                ..
            } => {
                assert_eq!(sampled_id, 3);
                assert_eq!(argmax_id, 7);
            }
            other => panic!("expected NotArgmax, got {other:?}"),
        }
    }
}