← Commit history

Merge PR #555: Fix real-board false positives in netclasses DRC sync and VIPPO/via-hygiene (#216, #217 follow-up) (fix/realboard-netclasses-vippo -> main) merge

Colby Knox ·efa17beee5 · ·parents a776a82, b0dd730

Showing changes introduced by the merge (against its first parent).

4 files changed +204−38
crates/adom-aiflow/src/netclasses.rs+119−23
@@ -83,10 +83,49 @@ fn is_gnd(name: &str) -> bool {     u == "GND" || u == "AGND" || u == "DGND" || u == "PGND" || u == "VSS" || u.contains("GND") } +/// Parse a spec width entry: either a scalar (`0.8` -> min 0.8, opt 0.8) or a width-ladder array+/// (`[1.2, 0.8, 0.5, 0.25]` -> min 0.25 neckdown floor, opt 1.2 preferred trunk width).+fn parse_width_ladder(v: &Value, default_w: f64, min_track: f64) -> (f64, f64) {+    if let Some(w) = v.as_f64() {+        let w = w.max(min_track);+        return (w, w);+    }+    if let Some(arr) = v.as_array() {+        let vals: Vec<f64> = arr.iter().filter_map(Value::as_f64).filter(|x| *x > 0.0 && x.is_finite()).collect();+        if !vals.is_empty() {+            let min_w = vals.iter().copied().fold(f64::INFINITY, f64::min).max(min_track);+            let max_w = vals.iter().copied().fold(0.0_f64, f64::max).max(min_w);+            return (min_w, max_w);+        }+    }+    let w = default_w.max(min_track);+    (w, w)+}++fn read_pro_default_clearance(board: Option<&Board>) -> Option<f64> {+    let b = board?;+    let pro = Path::new(&b.path).with_extension("kicad_pro");+    let raw = std::fs::read_to_string(pro).ok()?;+    let v: Value = serde_json::from_str(&raw).ok()?;+    v["net_settings"]["classes"].as_array()?+        .iter()+        .find(|c| c["name"] == "Default")+        .and_then(|c| c["clearance"].as_f64())+        .filter(|x| *x > 0.0 && x.is_finite())+}+ /// Derive canonical electrical net classes from `spec.json` (and `board` stackup when available). pub fn derive(board: Option<&Board>, spec: &Value) -> NetClassPlan {-    let base_clearance = spec["clearance"].as_f64().unwrap_or(0.2);-    let base_track = spec["track"].as_f64().unwrap_or(0.2);+    let pro_clr = read_pro_default_clearance(board);+    let base_clearance = match (spec["clearance"].as_f64(), pro_clr) {+        // Never silently inflate clearance above the board's existing Default net class+        // (e.g. a 4L QFN board whose .kicad_pro Default clearance is 0.10 mm).+        (Some(s), Some(p)) => s.min(p),+        (Some(s), None) => s,+        (None, Some(p)) => p,+        (None, None) => 0.15,+    };+    let base_track = spec["track"].as_f64().or_else(|| spec["trackWidth"].as_f64()).unwrap_or(0.2);     let min_track = spec["minTrackWidth"].as_f64().unwrap_or(0.127);     let mut classes: Vec<NetClassSpec> = Vec::new();     let mut inter_clearances: Vec<ClearancePair> = Vec::new();@@ -205,24 +244,30 @@ pub fn derive(board: Option<&Board>, spec: &Value) -> NetClassPlan {     }      // 3. Power classes from wideNets / midNets / loads-    let mut wide_groups: BTreeMap<i64, Vec<String>> = BTreeMap::new();+    // Group by (min_width_um) so width-ladder arrays like [1.2, 0.8, 0.5, 0.25] enforce the+    // declared neckdown floor (0.25 mm) in DRC while keeping the preferred trunk width (1.2 mm)+    // in KiCad's netclass track_width.+    let mut wide_groups: BTreeMap<i64, (f64, Vec<String>)> = BTreeMap::new();     if let Some(o) = spec["wideNets"].as_object() {         for (net, v) in o {             if assigned.contains(net) { continue; }-            let w = v.as_f64().unwrap_or(0.5).max(min_track);-            wide_groups.entry((w * 1000.0).round() as i64).or_default().push(net.clone());+            let (min_w, opt_w) = parse_width_ladder(v, 0.5, min_track);+            let entry = wide_groups.entry((min_w * 1000.0).round() as i64).or_insert((opt_w, Vec::new()));+            entry.0 = entry.0.max(opt_w);+            entry.1.push(net.clone());         }     } else if let Some(a) = spec["wideNets"].as_array() {         let def_w = spec["wideTrack"].as_f64().unwrap_or(0.5).max(min_track);         for n in a.iter().filter_map(|v| v.as_str()) {             if assigned.contains(n) { continue; }-            wide_groups.entry((def_w * 1000.0).round() as i64).or_default().push(n.to_string());+            let entry = wide_groups.entry((def_w * 1000.0).round() as i64).or_insert((def_w, Vec::new()));+            entry.1.push(n.to_string());         }     }     let multi_wide = wide_groups.len() > 1;-    for (w_um, mut nets) in wide_groups {+    for (w_um, (opt_w, mut nets)) in wide_groups {         nets.sort();-        let w = w_um as f64 / 1000.0;+        let min_w = w_um as f64 / 1000.0;         let name = if multi_wide { format!("POWER_{w_um}UM") } else { "POWER_WIDE".into() };         let clr = nets.iter()             .filter_map(|n| spec["netClearance"][n].as_f64())@@ -232,8 +277,8 @@ pub fn derive(board: Option<&Board>, spec: &Value) -> NetClassPlan {             name,             kind: "power".into(),             nets,-            min_width_mm: r4(w),-            opt_width_mm: Some(r4(w)),+            min_width_mm: r4(min_w),+            opt_width_mm: Some(r4(opt_w)),             max_width_mm: None,             clearance_mm: r4(clr),             via_diameter_mm: Some(0.8),@@ -247,29 +292,35 @@ pub fn derive(board: Option<&Board>, spec: &Value) -> NetClassPlan {         });     } -    let mut mid_nets: Vec<String> = Vec::new();-    let mut mid_w = spec["midTrack"].as_f64().unwrap_or(0.35);+    let mut mid_groups: BTreeMap<i64, (f64, Vec<String>)> = BTreeMap::new();+    let def_mid = spec["midTrack"].as_f64().unwrap_or(0.35).max(min_track);     if let Some(o) = spec["midNets"].as_object() {         for (net, v) in o {             if assigned.contains(net) { continue; }-            if let Some(w) = v.as_f64() { mid_w = mid_w.max(w); }-            mid_nets.push(net.clone());+            let (min_w, opt_w) = parse_width_ladder(v, def_mid, min_track);+            let entry = mid_groups.entry((min_w * 1000.0).round() as i64).or_insert((opt_w, Vec::new()));+            entry.0 = entry.0.max(opt_w);+            entry.1.push(net.clone());         }     } else if let Some(a) = spec["midNets"].as_array() {         for n in a.iter().filter_map(|v| v.as_str()) {             if assigned.contains(n) { continue; }-            mid_nets.push(n.to_string());+            let entry = mid_groups.entry((def_mid * 1000.0).round() as i64).or_insert((def_mid, Vec::new()));+            entry.1.push(n.to_string());         }     }-    if !mid_nets.is_empty() {-        mid_nets.sort();-        for n in &mid_nets { assigned.insert(n.clone()); }+    let multi_mid = mid_groups.len() > 1;+    for (w_um, (opt_w, mut nets)) in mid_groups {+        nets.sort();+        let min_w = w_um as f64 / 1000.0;+        let name = if multi_mid { format!("POWER_MID_{w_um}UM") } else { "POWER_MID".into() };+        for n in &nets { assigned.insert(n.clone()); }         classes.push(NetClassSpec {-            name: "POWER_MID".into(),+            name,             kind: "power-mid".into(),-            nets: mid_nets,-            min_width_mm: r4(mid_w.max(min_track)),-            opt_width_mm: Some(r4(mid_w.max(min_track))),+            nets,+            min_width_mm: r4(min_w),+            opt_width_mm: Some(r4(opt_w)),             max_width_mm: None,             clearance_mm: r4(base_clearance),             via_diameter_mm: Some(0.7),@@ -454,8 +505,14 @@ pub fn render_kicad_dru_block(plan: &NetClassPlan) -> String {                 ));             }         } else {+            // Power classes backed by a width-ladder array (e.g. [1.2, 0.8, 0.5, 0.25]) may still+            // have low-current sense/feedback taps routed at escape-neck width, so emit DRC warnings+            // rather than blocking errors; explicit scalar wideNets stay hard errors.+            let is_ladder = (c.kind == "power" || c.kind == "power-mid")+                && c.opt_width_mm.is_some_and(|o| o > c.min_width_mm + 1e-6);+            let sev = if is_ladder { "  (severity warning)\n" } else { "" };             s.push_str(&format!(-                "(rule \"aiflow_nc_{rbase}_width\"\n  (condition \"{cond}\")\n  (constraint track_width (min {:.4}mm))\n)\n",+                "(rule \"aiflow_nc_{rbase}_width\"\n  (condition \"{cond}\")\n{sev}  (constraint track_width (min {:.4}mm))\n)\n",                 c.min_width_mm             ));         }@@ -807,4 +864,43 @@ mod tests {         assert_eq!(drifted["pass"], false, "{drifted}");         let _ = std::fs::remove_dir_all(&td);     }++    #[test]+    fn width_ladder_arrays_preserve_neckdown_floor_and_inherit_pro_clearance() {+        // Real-board regression (argon-aiflow / astra-aiflow / opus-aiflow):+        // wideNets/midNets arrays like [1.2, 0.8, 0.5, 0.25] must enforce min 0.25 mm in DRU+        // (preferred 1.2 mm in .kicad_pro), and must not inflate clearance above .kicad_pro Default.+        let td = std::env::temp_dir().join(format!("aiflow-nc-ladder-{}", std::process::id()));+        let _ = std::fs::remove_dir_all(&td);+        std::fs::create_dir_all(&td).unwrap();+        let bp = td.join("opus.kicad_pcb");+        let pro_p = td.join("opus.kicad_pro");+        let pcb = r#"(kicad_pcb (version 20241229) (layers (0 "F.Cu" signal) (31 "B.Cu" signal) (44 "Edge.Cuts" user)) (gr_rect (start 0 0) (end 20 20) (layer "Edge.Cuts")))"#;+        std::fs::write(&bp, pcb).unwrap();+        std::fs::write(&pro_p, serde_json::to_string_pretty(&json!({+            "net_settings": {+                "classes": [{"name": "Default", "clearance": 0.1, "track_width": 0.1}]+            }+        })).unwrap()).unwrap();+        let b = Board::load(bp.to_str().unwrap()).unwrap();+        let spec = json!({+            "clearance": 0.15,+            "wideNets": {"VBUS": [0.8, 0.5, 0.3], "MOT_A1": [0.6, 0.4, 0.25]},+            "midNets": {"+3V3": [0.4, 0.25], "PD_DISCH": [0.3, 0.2]}+        });+        let plan = derive(Some(&b), &spec);+        assert!((plan.base_clearance_mm - 0.1).abs() < 1e-6, "must inherit tighter Default clearance 0.1 mm: {}", plan.base_clearance_mm);+        let vbus_cls = plan.classes.iter().find(|c| c.nets.contains(&"VBUS".to_string())).unwrap();+        assert!((vbus_cls.min_width_mm - 0.3).abs() < 1e-6, "VBUS neckdown min must be 0.3: {vbus_cls:?}");+        assert!((vbus_cls.opt_width_mm.unwrap() - 0.8).abs() < 1e-6, "VBUS preferred opt must be 0.8: {vbus_cls:?}");+        assert!((vbus_cls.clearance_mm - 0.1).abs() < 1e-6);+        let mot_cls = plan.classes.iter().find(|c| c.nets.contains(&"MOT_A1".to_string())).unwrap();+        assert!((mot_cls.min_width_mm - 0.25).abs() < 1e-6);+        let pdd_cls = plan.classes.iter().find(|c| c.nets.contains(&"PD_DISCH".to_string())).unwrap();+        assert!((pdd_cls.min_width_mm - 0.2).abs() < 1e-6);+        let dru = render_kicad_dru_block(&plan);+        assert!(dru.contains("(severity warning)"), "width-ladder DRU rule should emit severity warning: {dru}");+        crate::checks::dru_syntax(&format!("(version 1)\n{dru}")).unwrap();+        let _ = std::fs::remove_dir_all(&td);+    } }
crates/adom-aiflow/src/vippo.rs+49−7
@@ -49,12 +49,22 @@ pub fn pad_area_mm2(p: &Pad) -> f64 {     if a > 1e-6 { a } else { (2.0 * p.half_long) * (2.0 * p.half_short) } } +fn is_mechanical_mount_pad(p: &Pad) -> bool {+    let n = p.name.trim().to_ascii_uppercase();+    let r = p.reference.trim().to_ascii_uppercase();+    let is_conn = r.starts_with('J') || r.starts_with("CN") || r.starts_with("CON") || r.starts_with('H') || r.starts_with("MH");+    is_conn && (n == "MP" || n.starts_with("MP") || n == "SH" || n == "SHIELD" || n.starts_with("MH") || n.starts_with("S1") || n.starts_with("S2") || n.starts_with("S3") || n.starts_with("S4"))+}++/// True when the via's drilled barrel intersects the SMD pad copper (the condition that wicks+/// solder paste during reflow). Off-pad fanout vias whose outer copper annular ring merely kisses+/// the edge of the SMD pad while the drill hole sits cleanly outside the pad are NOT VIPPO. fn via_touches_smd_pad(v: &Via, p: &Pad) -> bool {     if p.thru { return false; }     // Through-hole vias pierce both F.Cu (depth 0) and B.Cu (COPPER_BOTTOM); blind vias check span.     let touches_layer = (p.on_f && v.span.0 == 0) || (p.on_b && v.span.1 >= aiflow_board::COPPER_BOTTOM);     if !touches_layer { return false; }-    let r = (v.size * 0.5).max(v.drill * 0.5);+    let r = (v.drill * 0.5).max(0.05);     if !p.polys.is_empty() {         p.polys.iter().any(|q| geom::point_in_poly(v.x, v.y, q) || geom::point_poly_distance(v.x, v.y, q) < r - 1e-4)     } else {@@ -95,7 +105,7 @@ pub fn audit_vippo(board: &Board, spec: &Value) -> Value {                 "padAreaMm2": r2(area),                 "layer": if p.on_f { "F.Cu" } else { "B.Cu" },             });-            if area >= EPAD_MIN_AREA_MM2 {+            if area >= EPAD_MIN_AREA_MM2 || is_mechanical_mount_pad(p) {                 epad_hits.push(entry);             } else {                 smd_hits.push(entry);@@ -243,12 +253,18 @@ pub fn via_hygiene(board: &Board, spec: &Value) -> Value {         if class == "signal-routing" && !v.net.is_empty() {             *signal_vias_by_net.entry(v.net.clone()).or_insert(0) += 1;         }-        if class != "thermal" {+        if class != "thermal" && class != "stitching" && !is_gnd(&v.net) {             non_thermal_vias.push((idx, v, class));         }     } -    // Count distinct routed signal nets (from tracks + signal vias)+    // Count distinct routed signal nets (from tracks + signal vias) and pad count per net+    let mut pads_by_net: BTreeMap<String, usize> = BTreeMap::new();+    for p in &board.pads {+        if !p.net.is_empty() {+            *pads_by_net.entry(p.net.clone()).or_insert(0) += 1;+        }+    }     let mut routed_signal_nets: BTreeSet<String> = BTreeSet::new();     for t in &tracks {         if !t.net.is_empty() && !is_gnd(&t.net) && !spec_pwr.contains(&t.net) && !crate::route_quality::power_like(&t.net) {@@ -260,11 +276,12 @@ pub fn via_hygiene(board: &Board, spec: &Value) -> Value {     let sig_nets = routed_signal_nets.len();     let avg_sig_vias = if sig_nets > 0 { sig_vias as f64 / sig_nets as f64 } else { 0.0 }; -    // Non-bus signal nets with > 2 vias+    // Non-bus signal nets with excessive vias: > 2 vias on a 2-pin net, or > (pads - 1) on multi-drop fanout nets     let mut high_via_nets = Vec::new();     for (net, &cnt) in &signal_vias_by_net {-        if cnt > MAX_VIAS_PER_NON_BUS_NET && !is_bus_net(net) {-            high_via_nets.push(json!({"net": net, "vias": cnt}));+        let pad_budget = pads_by_net.get(net).copied().unwrap_or(2).saturating_sub(1).max(MAX_VIAS_PER_NON_BUS_NET);+        if cnt > pad_budget && !is_bus_net(net) {+            high_via_nets.push(json!({"net": net, "vias": cnt, "budget": pad_budget}));         }     } @@ -406,4 +423,29 @@ mod tests {         assert_eq!(h["highViaSignalNets"].as_array().unwrap().len(), 1);         assert_eq!(h["denseClusters"].as_array().unwrap().len(), 1);     }++    #[test]+    fn off_pad_tangent_via_and_gnd_stitching_array_are_not_false_positives() {+        // Real-board regression (argon-aiflow C9.1/R12.2 + 24-via GND stitch array, opus-solo J3.MP):+        // 1. Off-pad fanout via (size 0.6, drill 0.3) whose drill sits 0.25 mm from R1.1 pad edge+        //    (annular ring kisses edge by 0.05 mm, drill cleanly outside pad) must NOT be flagged as VIPPO.+        // 2. A dense array of 6 GND stitching vias stitches the reference plane rather than perforating it.+        let l4 = "(0 \"F.Cu\" signal) (4 \"In1.Cu\" signal) (6 \"In2.Cu\" signal) (2 \"B.Cu\" signal)";+        // R1.1 is centered at (9.2, 10.0), size 0.8 x 0.9 -> left edge at x = 8.80.+        // Via at x = 8.55 has edgeDist = 0.25 mm > drill/2 (0.15 mm), < size/2 (0.30 mm).+        let vias = "(via (at 8.55 10.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 1)) \+                    (via (at 20.0 5.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4)) \+                    (via (at 20.8 5.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4)) \+                    (via (at 21.6 5.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4)) \+                    (via (at 20.0 5.8) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4)) \+                    (via (at 20.8 5.8) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4)) \+                    (via (at 21.6 5.8) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4))";+        let b = mk_board(vias, "", l4);+        let vp = audit_vippo(&b, &json!({"fab": {"rules": "jlcpcb-2L"}}));+        assert_eq!(vp["pass"], true, "off-pad tangent annular ring must not trigger VIPPO: {vp}");+        assert_eq!(vp["smdViaInPadCount"], 0);++        let vh = via_hygiene(&b, &json!({}));+        assert_eq!(vh["denseClusters"].as_array().unwrap().len(), 0, "GND stitching vias must not be flagged as plane perforation: {vh}");+    } }
tests/netclasses-drc-workflow.py+19−5
@@ -103,9 +103,23 @@ with tempfile.TemporaryDirectory(prefix='aiflow-netclasses-') as td:     print('  [3/5] rules check passes once native net classes are synced')      # 4. Real kicad-cli pcb drc catches narrow VIN and wide USB gap -> fixed board clears both-    if shutil.which('kicad-cli'):+    def runnable_kicad_cli():+        cand = os.environ.get('ADOM_AIFLOW_KICAD_CLI') or shutil.which('kicad-cli')+        if not cand:+            return None+        try:+            probe = subprocess.run([cand, '--version'], env=env, capture_output=True, text=True, timeout=15)+            out = probe.stdout + probe.stderr+            if probe.returncode == 0 and 'no KiCad found' not in out and out.strip():+                return cand+        except Exception:+            pass+        return None++    kicad_bin = runnable_kicad_cli()+    if kicad_bin:         drc_bad = p / 'drc-bad.json'-        subprocess.run(['kicad-cli', 'pcb', 'drc', '--format', 'json', '--output', str(drc_bad), str(b)], env=env, check=True, capture_output=True)+        subprocess.run([kicad_bin, 'pcb', 'drc', '--format', 'json', '--output', str(drc_bad), str(b)], env=env, check=True, capture_output=True)         v_bad = [v['type'] for v in json.loads(drc_bad.read_text()).get('violations', [])]         assert 'track_width' in v_bad and 'diff_pair_gap_out_of_range' in v_bad, v_bad @@ -114,12 +128,12 @@ with tempfile.TemporaryDirectory(prefix='aiflow-netclasses-') as td:         usb_g = cls_names['DIFF_USB']['diff_pair_gap']         make_board(b, vin_w=0.85, usb_w=usb_w, usb_gap=usb_g)         drc_good = p / 'drc-good.json'-        subprocess.run(['kicad-cli', 'pcb', 'drc', '--format', 'json', '--output', str(drc_good), str(b)], env=env, check=True, capture_output=True)+        subprocess.run([kicad_bin, 'pcb', 'drc', '--format', 'json', '--output', str(drc_good), str(b)], env=env, check=True, capture_output=True)         v_good = [v['type'] for v in json.loads(drc_good.read_text()).get('violations', [])]         assert 'track_width' not in v_good and 'diff_pair_gap_out_of_range' not in v_good, v_good-        print('  [4/5] real kicad-cli pcb drc caught narrow VIN + wrong USB gap, and cleared both when fixed')+        print(f'  [4/5] real kicad-cli pcb drc caught narrow VIN + wrong USB gap, and cleared both when fixed (via {kicad_bin})')     else:-        print('  [4/5] SKIP kicad-cli not on PATH')+        print('  [4/5] SKIP kicad-cli not runnable in this environment (set ADOM_AIFLOW_KICAD_CLI or install KiCad)')      # 5. Drift in .kicad_pro is caught by rules check     for c in pro['net_settings']['classes']:
tests/vippo-via-hygiene-workflow.py+17−3
@@ -94,15 +94,29 @@ with tempfile.TemporaryDirectory(prefix='aiflow-vippo-') as td:     assert call(run3, 'start', '--board', str(b_vip), '--spec', str(spec_app), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0     rg3 = call(run3, 'gate')     assert rg3.returncode == 0 and rg3.stdout.startswith('OK:'), rg3.stdout + rg3.stderr-    if shutil.which('kicad-cli'):+    def runnable_kicad_cli():+        cand = os.environ.get('ADOM_AIFLOW_KICAD_CLI') or shutil.which('kicad-cli')+        if not cand:+            return None+        try:+            probe = subprocess.run([cand, '--version'], env=env, capture_output=True, text=True, timeout=15)+            out = probe.stdout + probe.stderr+            if probe.returncode == 0 and 'no KiCad found' not in out and out.strip():+                return cand+        except Exception:+            pass+        return None++    kicad_bin = runnable_kicad_cli()+    if kicad_bin:         out_dir = p / 'mfg-vippo'         re = call(run3, 'export', '--out', str(out_dir))         assert re.returncode == 0, re.stdout + re.stderr         note_md = out_dir / 'vippo-fab-note.md'         assert note_md.exists() and 'IPC-4761 Type VII' in note_md.read_text(), list(out_dir.iterdir())-        print('  [3/5] approved VIPPO passed gate and export emitted IPC-4761 Type VII vippo-fab-note.md')+        print(f'  [3/5] approved VIPPO passed gate and export emitted IPC-4761 Type VII vippo-fab-note.md (via {kicad_bin})')     else:-        print('  [3/5] SKIP kicad-cli export check')+        print('  [3/5] SKIP kicad-cli not runnable in this environment (set ADOM_AIFLOW_KICAD_CLI or install KiCad)')      # 4. Dense via cluster (> 4 non-thermal vias within 3 mm) + > 2 vias on non-bus net caught in viaHygiene     vias_cluster = (