Skip to main content

rate_acceptance/
rate_acceptance.rs

1//! The silicon acceptance for #131 (docs/kdi_rate_and_validity.md §7): `rate_acceptance [serial]`,
2//! exit 0 = all checks passed. Every check runs after a `ConfigureFPGA` with **no other host
3//! action** — the defect is what a device does before configuration; every failed fix passed sims.
4
5use std::process::ExitCode;
6use std::time::{Duration, Instant};
7
8use kdi::{Acquisition, Cap, Device, Stream};
9
10/// The EXPLICIT table entry for 30 kS/s, not `0, 0`. Both reach the same state — an off-table pair
11/// falls through to the default — but the fall-through makes "which rate did we ask for" a second
12/// question inside a measurement about rates; the first run was read with that ambiguity in it.
13const M: u8 = 42;
14const D: u8 = 25;
15
16/// ONE LANE, bounded. All 32 lanes free-running measured a gap of 33750 vs a declared 3375 — not
17/// a rate defect: 32 x 35 rows x 2 B at 30 kS/s is ~66 MB/s, which this pipe cannot sustain, so
18/// survivors sit ten timesteps apart. `lost_before` is summed too: unprinted loss reads as a rate.
19const LANES: u32 = 1;
20
21/// One frame's `(timestamp, tick_num, tick_den)`. Named because clippy is right that the tuple was
22/// getting hard to read, and because the cadence pair travels WITH the timestamp on purpose: the
23/// reference for every ratio here comes off the wire, never from a host-side constant.
24type Sample = (u64, u32, u32);
25
26fn drain(
27    dev: &mut Device,
28    s: Stream,
29    want: usize,
30    budget: Duration,
31) -> Result<(Vec<Sample>, u64), String> {
32    let mut rd = dev
33        .start(
34            s,
35            &Acquisition {
36                lanes: LANES,
37                burst: Some(want as u16),
38            },
39        )
40        .map_err(|e| format!("start: {e}"))?;
41    let mut out = Vec::new();
42    let mut lost = 0u64;
43    let t0 = Instant::now();
44    while out.len() < want && t0.elapsed() < budget {
45        match rd.next(Duration::from_millis(200)) {
46            // Cadence is a SECTION property, not a frame one -- the timebase is what the contract
47            // makes normative, so the reference for every ratio below comes off the wire.
48            Ok(Some(r)) => {
49                if !out.is_empty() {
50                    lost += r.lost_before();
51                }
52                let (n, d) = r.blocks().next().map(|b| b.cadence()).unwrap_or((0, 1));
53                out.push((r.timestamp(), n, u32::from(d)))
54            }
55            Ok(None) => {}
56            Err(e) => return Err(format!("read: {e}")),
57        }
58    }
59    let _ = rd.stop();
60    Ok((out, lost))
61}
62
63fn main() -> ExitCode {
64    let serial = std::env::args().nth(1).unwrap_or_default();
65    let mut dev = match Device::open_usb3(&serial, None) {
66        Ok(d) => d,
67        Err(e) => {
68            eprintln!("open failed: {e}");
69            return ExitCode::FAILURE;
70        }
71    };
72
73    println!("gateware_sha  0x{:08x}", dev.gateware_sha());
74    let (maj, min) = dev.kdi();
75    println!("contract      {maj}.{min}");
76    if !dev.caps().has(Cap::RateControl) {
77        eprintln!(
78            "FAIL: this build does not advertise rate_control -- wrong bitstream for this check"
79        );
80        return ExitCode::FAILURE;
81    }
82
83    let mut fails = 0;
84    let mut check = |name: &str, ok: bool, detail: String| {
85        println!(
86            "  {:<26} {}   {detail}",
87            name,
88            if ok { "ok  " } else { "FAIL" }
89        );
90        if !ok {
91            fails += 1;
92        }
93    };
94
95    // 1. UNCONFIGURED EMITS NOTHING. Not "slow frames" -- none.
96    let ready0 = dev.rate_ready().unwrap_or(true);
97    let silent = drain(&mut dev, Stream::Samples, 4, Duration::from_secs(3));
98    match silent {
99        // start() is expected to refuse before it ever reaches the pipe; that IS the check.
100        Err(e) if e.contains("rate is not configured") => check(
101            "unconfigured is silent",
102            !ready0,
103            format!("rate_ready={ready0}, start refused: named set_rate"),
104        ),
105        Ok((v, _)) => check(
106            "unconfigured is silent",
107            !ready0 && v.is_empty(),
108            format!("rate_ready={ready0}, {} frames", v.len()),
109        ),
110        Err(e) => check("unconfigured is silent", false, e),
111    }
112
113    // 2. CONFIGURED IS CORRECT, and the frame's OWN declared cadence is the reference -- never a
114    //    host-side constant, which is what let #131 stand for so long.
115    if let Err(e) = dev.set_rate(M, D) {
116        check("set_rate", false, format!("{e}"));
117    } else {
118        let ready1 = dev.rate_ready().unwrap_or(false);
119        match drain(&mut dev, Stream::Samples, 24, Duration::from_secs(10)) {
120            Ok((v, lost)) if v.len() >= 8 => {
121                let declared = f64::from(v[0].1) / f64::from(v[0].2.max(1));
122                let mut gaps: Vec<f64> = v.windows(2).map(|w| (w[1].0 - w[0].0) as f64).collect();
123                gaps.sort_by(|a, b| a.partial_cmp(b).unwrap());
124                let med = gaps[gaps.len() / 2];
125                let ratio = med / declared;
126                check("configured is correct", ready1 && lost == 0 && (ratio - 1.0).abs() < 0.02,
127                      format!("rate_ready={ready1}, declared {declared:.1}, observed {med:.1}, ratio {ratio:.3}, lost {lost}"));
128            }
129            Ok((v, _)) => check(
130                "configured is correct",
131                false,
132                format!("only {} frames", v.len()),
133            ),
134            Err(e) => check("configured is correct", false, e),
135        }
136    }
137
138    // 3. THE PUBLISHED CADENCE IS THE MEASURED ONE, ACROSS THE TABLE. Judged against the cadence
139    //    THAT FRAME DECLARES, never a host-side constant: a constant is what let #131 stand, with
140    //    device and host agreeing and both wrong. This check would have caught it on day one.
141    for (m, d, label) in [
142        (7u8, 125u8, "1 kS/s"),
143        (14, 25, "10 kS/s"),
144        (42, 25, "30 kS/s"),
145    ] {
146        if let Err(e) = dev.set_rate(m, d) {
147            check("sweep", false, format!("{label}: set_rate: {e}"));
148            continue;
149        }
150        match drain(&mut dev, Stream::Samples, 16, Duration::from_secs(20)) {
151            Ok((v, lost)) if v.len() >= 8 => {
152                let declared = f64::from(v[0].1) / f64::from(v[0].2.max(1));
153                let mut gaps: Vec<f64> = v.windows(2).map(|w| (w[1].0 - w[0].0) as f64).collect();
154                gaps.sort_by(|a, b| a.partial_cmp(b).unwrap());
155                let med = gaps[gaps.len() / 2];
156                let ratio = med / declared;
157                check(
158                    &format!("sweep {label}"),
159                    lost == 0 && (ratio - 1.0).abs() < 0.02,
160                    format!(
161                        "declared {declared:.1}, observed {med:.1}, ratio {ratio:.3}, lost {lost}"
162                    ),
163                );
164            }
165            Ok((v, _)) => check(
166                &format!("sweep {label}"),
167                false,
168                format!("only {} frames", v.len()),
169            ),
170            Err(e) => check(&format!("sweep {label}"), false, e),
171        }
172    }
173
174    // 4. QUIESCE RETURNS TO UNCONFIGURED, and check 1 must hold again.
175    if let Err(e) = dev.quiesce() {
176        check("quiesce unconfigures", false, format!("{e}"));
177    } else {
178        let ready2 = dev.rate_ready().unwrap_or(true);
179        check(
180            "quiesce unconfigures",
181            !ready2,
182            format!("rate_ready={ready2}"),
183        );
184    }
185
186    // 5. THE DIGITAL STREAM IS UNTOUCHED by any of it -- it is self-clocked and was correct
187    //    throughout #131, so a change that disturbs it is a regression in the fix.
188    match drain(&mut dev, Stream::Digital, 8, Duration::from_secs(5)) {
189        Ok((v, _)) if v.len() >= 4 => {
190            let declared = f64::from(v[0].1) / f64::from(v[0].2.max(1));
191            let mut gaps: Vec<f64> = v.windows(2).map(|w| (w[1].0 - w[0].0) as f64).collect();
192            gaps.sort_by(|a, b| a.partial_cmp(b).unwrap());
193            let med = gaps[gaps.len() / 2];
194            check(
195                "digital unaffected",
196                (med / declared - 1.0).abs() < 0.05,
197                format!(
198                    "{} frames, declared {declared:.1}, observed {med:.1}",
199                    v.len()
200                ),
201            );
202        }
203        Ok((v, _)) => check(
204            "digital unaffected",
205            false,
206            format!("only {} frames", v.len()),
207        ),
208        Err(e) => check("digital unaffected", false, e),
209    }
210
211    let _ = dev.quiesce();
212    println!("\nRESULT: {}", if fails == 0 { "PASS" } else { "FAIL" });
213    if fails == 0 {
214        ExitCode::SUCCESS
215    } else {
216        ExitCode::FAILURE
217    }
218}