From 445221eb52ffc59c2364c918e551e1af50b09825 Mon Sep 17 00:00:00 2001 From: "loom-fleet-dispatch[bot]" <313063438+loom-fleet-dispatch[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:11:53 +0000 Subject: [PATCH 1/6] feat: join runset pex devices with curated parasitics by geometric net correspondence klt pex --engine klayout-runset --deck runs a second, curated-deck extraction with parasitics, joins the two extractions on strictly interior metal-geometry probe points (layer-identity matched against the original stream), and merges the curated lumped R/C network into the runset leg. Unmatched nets and split/merge disagreements are disclosed in extraction.net_correspondence, never silently dropped or merged. klt signoff now refuses a parasitic-free pex leg for item 7 (unmet, no_parasitics); a merged leg that attached cards grades as a curated one. The measured decision and the refuted alternatives (boundary-point probing, device-layer roles, name-based joins) are recorded in docs/design/runset-pex-net-correspondence.md. Closes #6606 --- .../6606-pex-runset-net-correspondence.md | 2 + docs/cli/extract.md | 21 +- docs/cli/pex.md | 84 +++- docs/cli/signoff.md | 20 + docs/design-evidence-tiers.md | 11 +- docs/design/runset-pex-net-correspondence.md | 136 ++++++ import-boundaries.json | 2 + src/klayout_tools/cli/pex_cmd.py | 7 +- src/klayout_tools/extract_runset.py | 8 + src/klayout_tools/pex.py | 25 +- src/klayout_tools/pex_merged_leg.py | 353 ++++++++++++++ src/klayout_tools/pex_net_correspondence.py | 361 ++++++++++++++ src/klayout_tools/pex_runset.py | 180 ++++++- src/klayout_tools/signoff.py | 10 +- src/klayout_tools/signoff_pex_disclosure.py | 29 +- tests/test_pex.py | 10 +- tests/test_pex_net_correspondence.py | 444 ++++++++++++++++++ tests/test_pex_runset.py | 25 +- tests/test_pex_runset_cli.py | 13 +- tests/test_pex_runset_signoff.py | 93 +++- 20 files changed, 1730 insertions(+), 104 deletions(-) create mode 100644 changelog.d/6606-pex-runset-net-correspondence.md create mode 100644 docs/design/runset-pex-net-correspondence.md create mode 100644 src/klayout_tools/pex_merged_leg.py create mode 100644 src/klayout_tools/pex_net_correspondence.py create mode 100644 tests/test_pex_net_correspondence.py diff --git a/changelog.d/6606-pex-runset-net-correspondence.md b/changelog.d/6606-pex-runset-net-correspondence.md new file mode 100644 index 000000000..3ece9557b --- /dev/null +++ b/changelog.d/6606-pex-runset-net-correspondence.md @@ -0,0 +1,2 @@ +- **`klt pex --engine klayout-runset --deck ` joins runset devices with curated parasitics by geometric net correspondence** (#6606, 2026-11-20). The runset leg is re-extracted as usual, a curated deck runs with parasitics, and the two are joined on strictly interior metal-geometry probe points (layer-identity matched, ≥99% by area); the curated lumped R/C network is merged into the leg. Unmatched nets and split/merge disagreements between the two engines are disclosed in `extraction.net_correspondence`, never silently dropped or merged. The measured decision and the refuted alternatives: `docs/design/runset-pex-net-correspondence.md`. +- **`klt signoff` refuses a parasitic-free pex leg for item 7** (#6606, 2026-11-20). A citation whose envelope discloses `extraction.parasitics_carried: false` (a plain `--engine klayout-runset` run) renders `unmet` with the new reason `no_parasitics` — the remedy is re-running the same artifact with `--deck`; a merged leg grades exactly as a curated one. The `pex_extraction` disclosure itself is unchanged. diff --git a/docs/cli/extract.md b/docs/cli/extract.md index 895099816..acf660991 100644 --- a/docs/cli/extract.md +++ b/docs/cli/extract.md @@ -699,16 +699,19 @@ rather than silently ignored. **No parasitics.** The result is a device-level netlist with `parasitics: null`. Combining runset devices with curated-deck parasitics -would need a geometric net correspondence between two independent extractions +needs a geometric net correspondence between two independent extractions that number their unlabelled nets independently (`\$1` above; see "Anonymous -net numbering" below) — nothing in this repo provides that today -([#6606](https://github.com/2AMLogic/klayout-tools/issues/6606)). -[`klt pex --engine klayout-runset`](pex.md) (issue #6559) does use this engine -for its extracted leg, as a **device-level, parasitic-free** leg whose envelope -says so (`extraction.parasitics_carried: false`, `extraction.params_not_carried`). -That route does **not** by itself make `docs/design-evidence-tiers.md` T1 item -7 citable for such a block: item 7 is parasitic verification, and a runset leg -carries none. #6606 is what closes that. +net numbering" below) — this engine stays device-only, and `klt extract +--engine klayout-runset --deck` is refused as ever. +[`klt pex --engine klayout-runset --deck `](pex.md) (issues #6559, +#6606) is where that correspondence lives: it runs this engine for devices, +a curated deck for parasitics, joins the two by measured geometric rules +([`../design/runset-pex-net-correspondence.md`](../design/runset-pex-net-correspondence.md)), +and merges the parasitic network into the leg it re-simulates. A `klt pex` +report from that route can satisfy `docs/design-evidence-tiers.md` T1 item +7's intent when its envelope says `extraction.parasitics_carried: true`; +a parasitic-free leg (either runset shape) is refused by `klt signoff` +(`no_parasitics`, issue #6606). **Report.** Additive fields only, so `SCHEMA_VERSION` is unchanged (4): the report carries a top-level `engine`, `deck_file`, `deck_vars`, `deck: null`, diff --git a/docs/cli/pex.md b/docs/cli/pex.md index 387a33b16..7117bf17e 100644 --- a/docs/cli/pex.md +++ b/docs/cli/pex.md @@ -1074,35 +1074,61 @@ klt pex pnpMPA.gds --engine klayout-runset --deck-file sg13cmos5l.lvs \ --top pnpMPA_lvs --extract-only --format json ``` -**This is a device-level extraction with no parasitics — and a report from this -route therefore does not, by itself, satisfy T1 item 7's intent.** +**Without `--deck`, this is a device-level extraction with no parasitics — +and a report from that route does not satisfy T1 item 7: `klt signoff` +refuses it (`unmet`, reason `no_parasitics`).** [`design-evidence-tiers.md`](../design-evidence-tiers.md) item 7 is parasitic -verification; a runset leg has no R/C cards, so its `delta[]` is a -device-representation delta. The route makes that gap *visible in the -envelope* instead of unreachable. Joining the runset's devices with the curated -deck's parasitics needs a net correspondence between two independently-numbered -extractions, which nothing in this repo provides yet — that is -[#6606](https://github.com/2AMLogic/klayout-tools/issues/6606), and it is what -closes the gap. Until then `klt signoff` reports the disclosure below on the -item-7 citation and does not grade on it. +verification; a parasitic-free runset leg has no R/C cards, so its `delta[]` +is a device-representation delta. **`--deck ` (issue #6606) is the +route that closes the gap**: it additionally runs that curated deck with +parasitics and joins the two extractions by a measured geometric net +correspondence +([`../design/runset-pex-net-correspondence.md`](../design/runset-pex-net-correspondence.md) +records the decision and the refuted alternatives), attaching the curated +parasitic network to the runset devices: + +``` +klt pex pnpMPA.gds --engine klayout-runset --deck-file sg13cmos5l.lvs \ + --deck sg13cmos5l --top pnpMPA_lvs --extract-only --format json +``` + +A net the correspondence cannot match 1:1 is **listed, never silently +dropped or silently merged** (`extraction.net_correspondence`: +`matched` / `unmatched_runset_nets` / `unmatched_curated_nets` / +`disagreements` — a net split or merged *between the two engines* is +detected and reported, not compared), and such a leg's `delta[]` is a real +parasitic delta over the nets that did match. `parasitics_carried` is +`true` exactly when at least one parasitic card attached — on a layout the +curated deck cannot read (labels off its `.pin` layers, PCell vias the pip +`klayout.db` engine cannot resolve — IHP's own `pnpMPA` testcase is the +measured example) the merged run honestly degenerates to the device-only +leg and item 7 still refuses it. **Flags.** `--deck-file ` is required under the engine and a usage error (exit 2) under any other; `--deck-var`, `--device-param` and `--runset-timeout` are runset-only and likewise usage errors otherwise (the spelling, validation and error text are `klt extract`'s own). -`--device-model` is honoured. `--deck` is not a runset flag and is refused by -name, as on `klt extract`. `--device-param` matters: without it every `X` card -is parameter-free and the devices simulate at the PDK subcircuit's own -defaults, so a delta over them is not a delta over the drawn sizes — it is the -only way measured parameters reach the cards (issue #5513). +`--device-model` is honoured. `--deck` under this engine is the merged +route above (it selects the curated *parasitic* deck and is never forwarded +to the runset extraction itself); without the engine it is the curated-deck +selector as always. `--label-layer` is honoured by the merged route's +curated leg (it is how a layout labelled off the deck's own `.pin` layers +still names its nets); without `--deck` it stays refused. `--device-param` +matters: without it every `X` card is parameter-free and the devices +simulate at the PDK subcircuit's own defaults, so a delta over them is not +a delta over the drawn sizes — it is the only way measured parameters reach +the cards (issue #5513). **Refused by name, never silently ignored.** Every option that only makes sense -with parasitics or the curated deck is refused with the flag spelled out +with a richer curated parasitic model is refused with the flag spelled out (`engine 'klayout-runset' cannot honour --critical-net, --distributed-rc …`), -exit 1: `--critical-net*`, `--distributed-rc`, `--resistance-graph*`, +exit 1 — under the merged route too, which serves the curated deck's default +lumped model only: `--critical-net*`, `--distributed-rc`, `--resistance-graph*`, `--mom-rlc-*`, `--parasitic-variant`, `--substrate-tie-ohms`, `--deck-option`, -`--pins`, `--rename-declared-pins`, `--tie-declared-pins`, `--label-layer`, -`--pdk`, `--pdk-root` (the same table `klt extract` refuses them from), plus +`--pins`, `--rename-declared-pins`, `--tie-declared-pins`, `--pdk`, +`--pdk-root` (the same table `klt extract` refuses them from), plus +`--label-layer` *without* `--deck` (with `--deck` it routes to the curated +leg, above), `--device-only-leg` (the runset leg *is* already the parasitic-free one) and `--tie-net` (it ties nets the curated deck reports as unbiased PMOS bodies, which this engine never computes). `--dry-run` is refused too: its preflight @@ -1110,7 +1136,8 @@ models the curated deck and parasitics; use `--extract-only` to exercise the extraction without a measurement leg. `--backend batch` is **not** refused: `klt extract` refuses it because that verb would ship the extraction off-host, where the standalone `klayout` binary is not, but `klt pex --backend` only -reaches the `klt sim` legs — the extraction always runs here. +reaches the `klt sim` legs — the extraction always runs here (both legs of +the merged route included). **What the envelope says.** Additive `extraction` fields, present **only** under this engine (a default-engine envelope is byte-identical to one produced before @@ -1119,15 +1146,24 @@ the route existed; `schema_version` stays `2`): | Field | Meaning | |---|---| | `extraction.engine` | `"klayout-runset"`. | -| `extraction.parasitics_carried` | Always `false`: the extracted leg has no R/C cards. Reported, never graded on. | +| `extraction.parasitics_carried` | `false` for a plain runset leg (no R/C cards). For a merged leg (`--deck`, issue #6606): `true` exactly when the net correspondence attached at least one parasitic card; `klt signoff` refuses a `false` for item 7 (`no_parasitics`). | +| `extraction.net_correspondence` | Present only on a merged leg (issue #6606): `matched` (`[{runset, curated}]`), `unmatched_runset_nets`, `unmatched_curated_nets`, `disagreements` (`{kind: split\|merge, …}` — a connectivity disagreement between the two engines, reported never guessed), `probe_count`, `deck`, `attached_card_count`. A net that cannot be matched is listed, never silently dropped or silently merged. | | `extraction.params_not_carried` | `{class: [PARAM, …]}` — the measured parameters the `X` cards do **not** carry, per device class, copied from `klt extract`'s own `params_not_carried`. `{}` once every parameter is declared with `--device-param`. | | `extraction.device_counts` | `{class: count}` — what the runset recognised, so a reader sees a family is present (or absent) without the extract JSON. Counted over the **instantiated hierarchy**, not the selected circuit alone: a hierarchical runset's top often holds no device itself (its devices sit in called cells), and the selected circuit's own count would read `{}` for a design full of them. Equal to `klt extract`'s `device_counts` for a flat runset, and to its `instantiated_device_counts` always. | | `extraction.device_count` | The total of `extraction.device_counts` — under this engine it replaces the echo of `klt extract`'s selected-circuit `device_count`, so the two never disagree. | | `extraction.extra_circuits` | `[circuit, …]` — the circuits the runset wrote besides the selected one; `[]` for a flat runset. A non-empty list is how a reader knows the extraction is hierarchical and that `extraction.net_count` still describes the selected circuit alone (nets inside a called cell are not summed: a net is not a per-instance quantity). | -`extraction.deck` is `null` (no curated deck ran), `extraction.model` is -`null` (no parasitic model), and `provenance.runset` carries the runset's -`deck_file`, `content_hash` and `klayout_application_version`. +`extraction.deck` is `null` and `extraction.model` is `null` on a plain +runset leg (no curated deck ran); on a merged leg `extraction.deck` is the +curated deck's name, `extraction.model`/`parasitic_integrity` describe the +curated parasitics actually attached, and `provenance.runset` carries the +runset's `deck_file`, `content_hash` and `klayout_application_version` +either way. The merged leg's own netlist header names the deck and the +match counts, and its written cards are the curated lumped model (one +series `R` per matched net, a ground `C`, matched coupling, the substrate +DC tie) — see +[`../design/runset-pex-net-correspondence.md`](../design/runset-pex-net-correspondence.md) +for why it is coarser than the curated engine's own star. `body_bias.status` is **`"not_assessed"`** (with `null` counts): the runset engine never runs the curated deck's floating-PMOS-body check, so `"biased"` would state a clean result nothing measured. diff --git a/docs/cli/signoff.md b/docs/cli/signoff.md index c6622b68b..353f807a4 100644 --- a/docs/cli/signoff.md +++ b/docs/cli/signoff.md @@ -4041,6 +4041,26 @@ extraction-only report can never render item 7 `"met"`; see "A check that checked nothing is refused, not reported" above for the shared rule and both routes into it. +**`no_parasitics` vs. all of them** (issue #6606, AC 4). A fourth thing can +be wrong with an item-7 citation: the cited `klt pex` report's own +extraction disclosure states the extracted leg carried **no parasitics** +(`extraction.parasitics_carried: false` — a plain +`--engine klayout-runset` leg, issue #6559). Item 7 is parasitic +verification, and such a leg's `delta[]` rows are device-representation +deltas, so the verdict does not establish the item no matter that every row +met tolerance: it renders `"unmet"` with `reason: "no_parasitics"`, whose +remedy is "re-run *this* artifact with parasitics attached" +(`klt pex --engine klayout-runset --deck `, which joins the curated +deck's parasitics onto the runset devices by geometric net correspondence — +[`../design/runset-pex-net-correspondence.md`](../design/runset-pex-net-correspondence.md)). +A merged leg that attached cards discloses +`extraction.parasitics_carried: true` and grades exactly as a curated one; +an envelope with no engine statement (every curated-deck run, and every +record predating the route) carries parasitics by construction and is never +refused here. Before issue #6606 this disclosure was reported-only; the +check's own `passed` status and the aggregation-mode `pex_extraction` +disclosure are unchanged — the gate is item 7's alone. + Only the literal JSON boolean `true` in `environment.sdf.annotated` grants annotation credit. False, null, missing fields, strings (including `"true"` and `"false"`), numbers, arrays, and objects do not qualify. Malformed optional diff --git a/docs/design-evidence-tiers.md b/docs/design-evidence-tiers.md index 3bcfacd29..3854c7bb7 100644 --- a/docs/design-evidence-tiers.md +++ b/docs/design-evidence-tiers.md @@ -480,7 +480,16 @@ written to every block. proof" section) — every `delta[]` row is explainable directly from the extracted netlist's own added R/C, not merely reported, including the (measured, not assumed) no-degradation rows that canary's current - topology produces. + topology produces. For a block whose core device family only the PDK's + own LVS runset recognises (the case `klt pex --engine + klayout-runset` exists for, #6559), the citation must carry parasitics: + `klt signoff` refuses a `parasitics_carried: false` leg with + `no_parasitics` (#6606) — the merged route (`klt pex --engine + klayout-runset --deck `, which attaches the curated deck's + parasitics to the runset devices through the measured geometric net + correspondence of + `docs/design/runset-pex-net-correspondence.md`) is the runset-engine + shape that grades. - *Digital* — the functional test suite re-run against the post-route gate-level netlist with back-annotated SDF timing, not only the pre-layout RTL/gate simulation. The machine-checkable evidence is a diff --git a/docs/design/runset-pex-net-correspondence.md b/docs/design/runset-pex-net-correspondence.md new file mode 100644 index 000000000..d943eb107 --- /dev/null +++ b/docs/design/runset-pex-net-correspondence.md @@ -0,0 +1,136 @@ +# Runset–curated net correspondence for `klt pex` (issue #6606) + +**Status: decided and landed** (`klt pex --engine klayout-runset --deck +`, 2026-11-20). This document records the measured decision issue +#6606 asked for: how the runset-engine leg's nets and a curated deck's +parasitic nets are put in correspondence, which alternatives were **measured** +rather than argued, and what `klt signoff` does with a parasitic-free pex leg +(AC 4). + +Measurements ran on `ihp-sg13cmos5l` (IHP SG13CMOS5L install at +`~/share/pdk/ihp-sg13cmos5l`, KLayout 0.30.12) against two layouts: the PDK's +own `pnpMPA` LVS testcase and the repo's `tests/test_extract_body_nets_sg13cmos5l.py` +inverter fixture. Every number below is from those runs. + +## The gap + +The runset engine (`klt extract --engine klayout-runset`, #5481) and a +curated deck extract the same layout independently and number their +unlabelled nets independently (`$1`, `…`; `docs/cli/extract.md`'s "Anonymous +net numbering" — deliberately *not* a contract even within one engine). A +name-based join is therefore impossible by construction, and `klt pex +--engine klayout-runset` (#6559) could only disclose `parasitics_carried: +false`. + +## Measured: what each side can give the join + +- **M1 — the runset `.lvsdb` carries per-net geometry.** Read back with + `kdb.LayoutVsSchematic.read()`, `polygons_of_net(net, layer, True)` + returns real per-net shapes over the database's *internal* layout + (`pnpMPA`: net `$1` holds 62 polygons on one internal layer; the inverter + fixture: each net 3–4 polygons across cont/metal/sd-like layers). The + internal layers are **anonymous** (no GDS layer info), a fact that forces + the layer-identity rule below. +- **M2 — the curated side already has a point→net oracle.** `klt extract + --probe` (#2986) resolves a point on a conductor role (`metal0`…, + `poly`, `well`) to the *final* net name and `cluster_id`, post-purge and + post-rename, on the live `LayoutToNetlist`. The join reuses this machinery + wholesale; no new extraction-side API was added for it. +- **M3 — coordinates agree.** Both engines' per-net polygons land in the + original stream's coordinate space (the inverter fixture's shapes compare + equal, dbu 0.001 both sides), so a geometric join needs no transforms. + +## Measured refutations (why the rule is what it is) + +- **R1 — probing every point on every role is unsound.** The naive join + (sample any point of a runset net, probe every curated conductor role) + matched *every* net to the gate net on the inverter fixture: a + source/drain polygon's hull vertex lies exactly on the poly bar's edge + (the sd region is `activ − poly`, cut at the bar), and the channel zone + (`activ ∧ poly`) is *inside* both the gate and the S/D clusters of either + engine by construction. Device layers overlap; wells *contain* the + diffusion they host. **Rule: the join runs on the metal routing stack + only, and only on points strictly interior to the runset polygon.** +- **R2 — boundary points produce false matches even on metal.** The + substrate cluster's bbox centre (a whole-die polygon) landed exactly on + the gate metal's top edge and probed the gate net. **Rule: sample points + are strictly interior** (bbox centre when strictly inside, otherwise an + inward bisector step from a convex hull vertex); a probe hit then implies + genuine area overlap, not edge-touching. +- **R3 — anonymous internal layers cannot be trusted by index.** The + runset database's metal-ish layers are anonymous, and a derived layer + (e.g. `gate = activ ∧ poly`) would happily donate points that overlap the + wrong curated role. **Rule: an internal layer joins one metal role only + when ≥ 99 % of its own area lies inside that role's GDS layer in the + original stream** (measured: original metal handles are single-source, so + real layers identify at 100 %; anything mixed is derived and joins + nothing). + +## The landed rule + +For each net of the runset's selected circuit: sample strictly interior +points of its polygons on internal layers identified (R3) with one of the +curated deck's metals, and probe that one role per point (M2). Exactly one +distinct curated net hit → **match**; more than one → **split +disagreement** (the runset net spans several curated nets); a curated net +hit by several runset nets → **merge disagreement** (its parasitics attach +to *neither* fragment); no hit → **unmatched**. Every outcome lands in the +envelope's `extraction.net_correspondence` (`matched`, +`unmatched_runset_nets`, `unmatched_curated_nets`, `disagreements`, +`probe_count`, `deck`, `attached_card_count`); parasitics attach only to +1:1 matches. Sampling is capped (16 points/layer, 64/net, strided), so +split detection is exact within the cap and best-effort beyond it. + +The merged leg is the runset leg's own netlist rewritten in place: matched +nodes renamed (a named runset net keeps its name — device-side truth; an +anonymous one adopts its curated counterpart's label, never onto a +colliding name), plus one lumped series `R` (node→hub), one ground `C`, +matched coupling capacitors, and the deck's substrate DC tie. This is +deliberately **coarser than the curated engine's own star** — the curated +netlist distributes a net's R across its *curated* device terminals, +terminals that do not exist in a runset leg; the merged writer collapses to +the single-lumped form `parasitics.nets[]` already publishes +(`rc_model: "lumped"`). + +### Measured outcomes + +| Layout | Result | +|---|---| +| inverter fixture (both engines driven for real) | 5/8 runset nets matched (VGND, Y, VPWR, Y, A — all anonymous runset nets adopting labels), 3 body clusters unmatched, 0 disagreements, 9 parasitic cards; the leg's device cards sit on the same nodes as the cards | +| inverter fixture, metal joins removed (deliberate split) | every labelled curated net reported as a merge over exactly its 2 fragments; 0 matches; no cards — and no stray ground tie | +| inverter fixture, diffusion bridged to gate (deliberate wrong join) | 2 split disagreements naming the curated nets each bridged cluster spans; the one cluster left whole still matches | +| `pnpMPA` PDK testcase (the flagship gap) | curated leg extracts **nothing but `vsubs`** — its labels sit on `10/25` (the deck reads `.pin` `10/2`) and its vias are KLayout PCell instances the pip `klayout.db` curated engine cannot resolve — so all four runset nets are reported (PAD/VDD unmatched, `$1`+`VSS` a merge onto `vsubs`), 0 cards, `parasitics_carried: false` | + +The `pnpMPA` row is the honest boundary of this route, not a failure of +the correspondence: the join is sound wherever the curated leg has coverage +of the layout's conventions (labels on the deck's `.pin` layers — +`klt`-generated blocks and `klt place-and-route` output, per #1385 — and +explicit via geometry). On a layout the curated deck cannot read, the +merged run degrades to exactly the disclosed device-only leg. + +## AC 4: the item-7 grading policy + +**A parasitic-free pex leg is refused for item 7** (`unmet`, reason +`no_parasitics`), decided in `signoff_pex_disclosure.parasitic_free_refusal` +and gated in `signoff._kind_gated_check`. Until #6606 the disclosure was +reported-only; with a route that *can* carry parasitics, a leg that does +not never establishes "post-layout parasitic verification" — its `delta[]` +rows are device-representation deltas. The remedy is re-running *this* +artifact with `--deck ` (the same artifact-kind discipline as +`not_post_layout`); a merged leg that attached cards discloses +`parasitics_carried: true` and grades exactly as a curated one. The +disclosure itself stays beside the verdict, unchanged. + +## What is deliberately still not carried + +- Measured device parameters on runset `X` cards (#5513, `--device-param`) + — orthogonal; declare them as on the parasitic-free route. +- The richer curated parasitic models (`--critical-net`, `--distributed-rc`, + `--resistance-graph*`, `--mom-rlc-*`, `--parasitic-variant`, + `--substrate-tie-ohms`, `--deck-option`, `--pins`) are refused by name + under the merged route too: the merged writer serves the default lumped + model only. +- `klt extract` itself still extracts devices-and-connectivity only under + the runset engine; the merged leg is a `klt pex` concern (the leg `klt + pex` re-simulates), and `klt extract --engine klayout-runset --deck` + remains refused. diff --git a/import-boundaries.json b/import-boundaries.json index ac48d8a93..f4e904ae5 100644 --- a/import-boundaries.json +++ b/import-boundaries.json @@ -627,6 +627,8 @@ "klayout_tools.cli.pex_cmd", "klayout_tools.pex", "klayout_tools.pex_async", + "klayout_tools.pex_merged_leg", + "klayout_tools.pex_net_correspondence", "klayout_tools.pex_netlist_text", "klayout_tools.pex_resistance_graph", "klayout_tools.pex_asap7", diff --git a/src/klayout_tools/cli/pex_cmd.py b/src/klayout_tools/cli/pex_cmd.py index a4dfec9ba..c4bb16078 100644 --- a/src/klayout_tools/cli/pex_cmd.py +++ b/src/klayout_tools/cli/pex_cmd.py @@ -174,9 +174,10 @@ def run(args: argparse.Namespace) -> int: ): _rehydrate_bare_attach(args) # Issue #6559: `--engine klayout-runset` -- usage errors (exit 2) use - # `klt extract`'s own validation and text. `--deck` belongs to the - # curated engine, so it is not required here (and, if given, is - # refused by name by `run_extract` as on `klt extract`). + # `klt extract`'s own validation and text. `--deck` is not required + # here; given, it selects the curated deck whose parasitics are + # joined onto the runset devices by geometric net correspondence + # (issue #6606) -- never forwarded to the runset extraction itself. try: runset = pex_runset.runset_from_args( args.engine, diff --git a/src/klayout_tools/extract_runset.py b/src/klayout_tools/extract_runset.py index e77ffbdd7..d8a5908b4 100644 --- a/src/klayout_tools/extract_runset.py +++ b/src/klayout_tools/extract_runset.py @@ -286,6 +286,7 @@ def run_extract_klayout_runset( runset_timeout_s: float | None = None, klayout_binary: str | None = None, request_dir: str | None = None, + lvsdb_out: str | None = None, ) -> dict[str, Any]: """Extract ``path`` by running the PDK runset ``deck_file`` and return the ``klt extract`` report. See this module's docstring for the mechanism and @@ -295,6 +296,11 @@ def run_extract_klayout_runset( binary, a runset that wrote no database, a timeout, an unreadable database -- reusing ``klt lvs``'s own message text wherever the shared launcher produces it. + + ``lvsdb_out`` (issue #6606, internal -- no CLI flag) copies the runset's + ``.lvsdb`` to that path before the scratch work directory is removed, so + a caller (:mod:`klayout_tools.pex_net_correspondence`) can read the + database's per-net geometry back after this function returns. """ from . import lvs_runset from .extract import _build_metrics, _normalized_netlist_sha256, _staged @@ -333,6 +339,8 @@ def run_extract_klayout_runset( timeout_s=timeout_s, work_dir=work_dir, ) + if lvsdb_out is not None: + shutil.copy2(lvsdb_path, lvsdb_out) with stage("lvsdb_read"): # `lvsdb` is the owner of `netlist`; it must stay referenced for diff --git a/src/klayout_tools/pex.py b/src/klayout_tools/pex.py index 14e2d71fd..aa5fcbd5c 100644 --- a/src/klayout_tools/pex.py +++ b/src/klayout_tools/pex.py @@ -2852,47 +2852,36 @@ def run_pex( ) try: - extract_report = run_extract( + # Issue #6559/#6606: the engine dispatch (curated / runset / the + # `--deck`-under-runset merged route) and the option mapping live in + # `pex_runset.run_extract_leg` -- the module that owns them. + extract_report = pex_runset.run_extract_leg( layout_path, deck_name, + runset=runset, output=output, top=top, pdk_variant=pdk_variant, pdk_root=pdk_root, - # Issue #6559: the runset engine has no parasitics; every other - # option passes through and is refused by name by `run_extract`. - parasitics=runset is None, - # Issue #1558: `--deck-option`/`--pins` passthrough. `None` for - # both whenever the flags were never given, which is the exact - # `run_extract` call this module made before they existed. + label_layers=label_layers, + device_models=device_models, deck_options=deck_options, declared_pins=declared_pins, - # Issue #2854: `--rename-declared-pins` passthrough. `False` - # whenever the flag was never given, which is the exact - # `run_extract` call this module made before it existed. rename_declared_pins=rename_declared_pins, tie_declared_pins=tie_declared_pins, - # Issue #2686: `--label-layer` passthrough. `None` when the flag - # was never given -- the exact `run_extract` call made before it. - label_layers=label_layers, - device_models=device_models, critical_nets=critical_nets, critical_net_patterns=critical_net_patterns, critical_net_all=critical_net_all, critical_net_excludes=critical_net_excludes, distributed_rc=distributed_rc, - # Issue #4037: `False`/`None` whenever the flags were never given, - # which is the exact `run_extract` call made before they existed. resistance_graph=resistance_graph, resistance_graph_r_cut_ohm=resistance_graph_r_cut_ohm, - emit_selected_resistance=resistance_graph, parasitic_variants=parasitic_variants, substrate_tie_ohms=substrate_tie_ohms, mom_rlc_net=mom_rlc_net, mom_rlc_resistance_ohm=mom_rlc_resistance_ohm, mom_rlc_capacitance_ff=mom_rlc_capacitance_ff, mom_rlc_inductance_nh=mom_rlc_inductance_nh, - **pex_runset.extract_options(runset), ) except ExtractError as exc: raise PexError(f"extraction failed: {exc}") from exc diff --git a/src/klayout_tools/pex_merged_leg.py b/src/klayout_tools/pex_merged_leg.py new file mode 100644 index 000000000..cf018f589 --- /dev/null +++ b/src/klayout_tools/pex_merged_leg.py @@ -0,0 +1,353 @@ +"""The merged ``klt pex --engine klayout-runset --deck `` leg +(issue #6606): the runset leg's own netlist with the curated deck's +parasitic network attached through the geometric net correspondence of +:mod:`klayout_tools.pex_net_correspondence`. + +The merged leg is the runset leg rewritten in place: matched nodes renamed +to their correspondence-preferred name (a named runset net keeps its own +name -- device-side truth; an anonymous runset net adopts its curated +counterpart's label when it has one, never onto a colliding name), plus the +curated deck's lumped parasitic network appended for the matched nets -- +one series ``R`` per net (node -> hub), one ground ``C`` per hub, coupling +capacitors between matched hubs, and the deck's substrate DC tie. This is +**coarser than the curated engine's own star**: the curated netlist +distributes a net's series R across its *curated* device terminals, +terminals that do not exist in a runset leg, so the merged writer collapses +to the single-lumped-R form the ``parasitics.nets[]`` report already +publishes (``rc_model: "lumped"``). Unmatched nets get no parasitics -- +listed in the envelope, never silently dropped or silently merged. + +:func:`merged_runset_extract` drives the whole route: the runset leg +exactly as the parasitic-free one runs it, a second curated-deck extraction +**with** parasitics, the join, the merge, and the report enrichment. It +runs under ``klt pex`` only when the caller gave ``--deck`` under +``--engine klayout-runset``; without it the runset route is byte-identical +to before this module existed. +""" + +from __future__ import annotations + +import os +import re +import tempfile +from collections.abc import Mapping, Sequence +from typing import Any + +from .extract import run_extract +from .pex_net_correspondence import ( + build_probes, + correspondence, + preferred_renames, +) + +#: The leg header line the merged writer replaces when it attaches cards. +_HEADER_NO_PARASITICS = ( + "* no parasitics: this engine extracts devices and connectivity only\n" +) + +_CARD_LINE = re.compile(r"^\s*[XRCMLDQ]") + + +# --------------------------------------------------------------------------- # +# The merged leg writer +# --------------------------------------------------------------------------- # + + +def _ground_net(parasitics: Mapping[str, Any]) -> str | None: + """The curated parasitic network's ground/substrate node -- the DC-tie + block names it, and every ground capacitor lands on it.""" + nets = (parasitics.get("substrate_dc_tie") or {}).get("nets") or [] + return str(nets[0]["net"]) if nets else None + + +def _format_number(value: float) -> str: + """SPICE number formatting in the curated writer's own style + (``0.055``, ``8.738e-17``).""" + return f"{value:.6g}" + + +def merge_parasitics( + netlist_path: str, + *, + matched: Sequence[Mapping[str, Any]], + all_runset_nets: Sequence[str], + parasitics: Mapping[str, Any], + deck_name: str, + report_block: Mapping[str, Any], +) -> int: + """Rewrite the runset leg at ``netlist_path`` in place -- rename matched + nodes, append the curated lumped parasitic network for the matched nets, + replace the leg's own "no parasitics" header line -- and return the + number of parasitic cards written (series R, ground C, coupling C, tie). + + Never touches unmatched nets: a node no card references stays exactly as + the runset wrote it; the correspondence block in the envelope, not a + guessed attachment, is where unmatched nets are stated.""" + renames = preferred_renames(matched, all_runset_nets) + merged_name = { + entry["curated"]: renames.get(entry["runset"], entry["runset"]) + for entry in matched + } + matched_curated = set(merged_name) + parasitic_nets = { + str(entry["net"]): entry for entry in parasitics.get("nets") or [] + } + coupled: dict[tuple[str, str], float] = {} + for entry in parasitic_nets.values(): + for other in entry.get("coupled") or []: + net_a, net_b = sorted((str(entry["net"]), str(other["net"]))) + coupled[(net_a, net_b)] = max( + coupled.get((net_a, net_b), 0.0), float(other["capacitance_ff"]) + ) + + ground_net = _ground_net(parasitics) + if ground_net is not None: + ground_net = merged_name.get(ground_net, ground_net) + cards: list[str] = [] + hubs: dict[str, str] = {} + for curated_net in sorted(matched_curated & set(parasitic_nets)): + entry = parasitic_nets[curated_net] + node = merged_name[curated_net] + hub = node + resistance = float(entry.get("resistance_ohm") or 0.0) + capacitance = float(entry.get("capacitance_ff") or 0.0) + if resistance > 0.0: + hub = f"{node}__kltph" + cards.append(f"R{node}_plr {node} {hub} {_format_number(resistance)}") + hubs[curated_net] = hub + if capacitance > 0.0 and ground_net is not None: + cards.append( + f"C{node}_plc {hub} {ground_net} {_format_number(capacitance * 1e-15)}" + ) + for (net_a, net_b), capacitance_ff in sorted(coupled.items()): + if net_a in hubs and net_b in hubs: + cards.append( + f"C{merged_name[net_a]}_{merged_name[net_b]}_plcc " + f"{hubs[net_a]} {hubs[net_b]} " + f"{_format_number(capacitance_ff * 1e-15)}" + ) + tie = parasitics.get("substrate_dc_tie") or {} + if ( + ground_net is not None + and tie.get("nets") + and any(ground_net in card.split(" ")[1:] for card in cards) + ): + # The DC tie rides along only with parasitics that need the ground + # node: a leg nothing matched keeps no stray global + resistor. + cards.append( + f"R{ground_net}_dctie {ground_net} 0 " + f"{_format_number(float(tie.get('resistance_ohm') or 0.0))}" + ) + + _rewrite_netlist( + netlist_path, + renames, + cards, + ground_net, + deck_name, + len(matched), + report_block, + ) + return len(cards) + + +def _rename_tokens(line: str, renames: Mapping[str, str]) -> str: + """Replace whole whitespace-delimited tokens that name a renamed node, + preserving the original whitespace (comments untouched).""" + parts = re.split(r"(\s+)", line) + return "".join(renames.get(part, part) for part in parts) + + +def _rewrite_netlist( + path: str, + renames: Mapping[str, str], + cards: Sequence[str], + ground_net: str | None, + deck_name: str, + matched_count: int, + report_block: Mapping[str, Any], +) -> None: + """Apply the node renames to every card/pin token, emit the ``.GLOBAL`` + the parasitic network needs, insert the parasitic cards before + ``.ENDS``, and replace the "no parasitics" header line -- in place, + preserving line order and pin order.""" + with open(path, encoding="utf-8") as handle: + lines = handle.readlines() + + out: list[str] = [] + rewrote_header = False + pending = list(cards) + for line in lines: + if line == _HEADER_NO_PARASITICS and cards: + rewrote_header = True + unmatched = report_block.get("unmatched_runset_nets") or [] + disagreements = report_block.get("disagreements") or [] + out.append( + f"* parasitics attached from curated deck '{deck_name}' via " + f"geometric net correspondence (issue #6606): {matched_count} " + f"net(s) matched, {len(unmatched)} unmatched runset net(s), " + f"{len(disagreements)} disagreement(s) -- see the report's " + "extraction.net_correspondence\n" + ) + continue + if pending and line.strip().upper().startswith(".ENDS"): + out.extend(f"{card}\n" for card in pending) + pending = [] + out.append( + _rename_tokens(line, renames) + if not line.lstrip().startswith("*") and line.strip() + else line + ) + out.extend(f"{card}\n" for card in pending) + if not rewrote_header and cards: + out.insert( + 0, f"* parasitics attached from curated deck '{deck_name}' (issue #6606)\n" + ) + if ground_net is not None and not any( + line.strip().upper().startswith(".GLOBAL") and ground_net in line.split() + for line in out + ): + first = next( + ( + i + for i, line in enumerate(out) + if _CARD_LINE.match(line) or line.strip().upper().startswith(".SUBCKT") + ), + len(out), + ) + out.insert(first, f".GLOBAL {ground_net}\n") + with open(path, "w", encoding="utf-8") as handle: + handle.writelines(out) + + +# --------------------------------------------------------------------------- # +# The merged-route driver +# --------------------------------------------------------------------------- # + + +def merged_runset_extract( + *, + layout_path: str, + output: str | None, + top: str | None, + runset: Any, + deck_name: str, + label_layers: Mapping[str, tuple[int, int] | None] | None, + device_models: Mapping[str, str] | None, + deck_options: Mapping[str, str] | None, + declared_pins: frozenset[str] | None, + rename_declared_pins: bool, + tie_declared_pins: bool, + critical_nets: Sequence[str] | None, + critical_net_patterns: Sequence[str] | None, + critical_net_all: bool, + critical_net_excludes: Sequence[str] | None, + distributed_rc: bool, + resistance_graph: bool, + resistance_graph_r_cut_ohm: float | None, + parasitic_variants: Sequence[str] | None, + substrate_tie_ohms: float | None, + mom_rlc_net: str | None, + mom_rlc_resistance_ohm: float | None, + mom_rlc_capacitance_ff: float | None, + mom_rlc_inductance_nh: float | None, +) -> dict[str, Any]: + """``klt pex --engine klayout-runset --deck `` (issue #6606): + run the runset leg exactly as the parasitic-free route does, run a + second, curated-deck extraction **with** parasitics, join the two by + geometry, and merge the curated parasitic network into the runset leg. + + Returns the runset extract report, enriched in memory with the + ``net_correspondence`` block, the curated ``parasitics`` (so the pex + envelope's model/integrity disclosures describe the parasitics actually + attached), and re-hashed netlist digests. Every pex option only a + richer curated parasitic model could serve is refused by name here, + from the same table ``klt extract`` refuses them by -- minus the two + this route honours (``--deck`` selects the curated deck; + ``--label-layer`` its label layers).""" + from . import extract_runset + from .decks import get_extraction_deck + + extract_runset.refuse_unsupported( + { + key: value + for key, value in { + "deck_options": deck_options, + "declared_pins": declared_pins, + "rename_declared_pins": rename_declared_pins or None, + "tie_declared_pins": tie_declared_pins or None, + "critical_nets": critical_nets, + "critical_net_patterns": critical_net_patterns, + "critical_net_all": critical_net_all or None, + "critical_net_excludes": critical_net_excludes, + "distributed_rc": distributed_rc or None, + "resistance_graph": resistance_graph or None, + "resistance_graph_r_cut_ohm": resistance_graph_r_cut_ohm, + "parasitic_variants": parasitic_variants, + "substrate_tie_ohms": substrate_tie_ohms, + "mom_net": mom_rlc_net, + "mom_rlc_resistance_ohm": mom_rlc_resistance_ohm, + "mom_rlc_capacitance_ff": mom_rlc_capacitance_ff, + "mom_rlc_inductance_nh": mom_rlc_inductance_nh, + }.items() + if value + } + ) + + deck = get_extraction_deck(deck_name) + with tempfile.TemporaryDirectory(prefix="klt-pex-correspondence-") as work: + lvsdb_out = os.path.join(work, "runset.lvsdb") + report = extract_runset.run_extract_klayout_runset( + layout_path, + deck_file=runset.deck_file, + output=output, + top=top, + deck_vars=runset.deck_vars, + device_models=device_models, + device_params=runset.device_params, + runset_timeout_s=runset.runset_timeout, + lvsdb_out=lvsdb_out, + ) + probes, positions = build_probes( + lvsdb_out, + layout_path, + top=str(report["top"]), + metals=list(deck.metals), + dbu_um=float(report["dbu_um"]), + ) + curated = run_extract( + layout_path, + deck_name, + top=str(report["top"]), + parasitics=True, + probes=probes, + label_layers=label_layers, + no_netlist=True, + ) + + corr = correspondence( + [str(entry["name"]) for entry in report["nets"]], + curated.get("probes") or [], + (curated.get("parasitics") or {}).get("nets") or [], + ) + corr["deck"] = deck_name + corr["attached_card_count"] = ( + merge_parasitics( + report["netlist_path"], + matched=corr["matched"], + all_runset_nets=[str(entry["name"]) for entry in report["nets"]], + parasitics=curated.get("parasitics") or {}, + deck_name=deck_name, + report_block=corr, + ) + if report.get("netlist_path") + else 0 + ) + report["net_correspondence"] = corr + if curated.get("parasitics"): + report["parasitics"] = curated["parasitics"] + if report.get("netlist_path"): + from ._provenance import sha256_file + + report["netlist_sha256"] = sha256_file(report["netlist_path"]) + return report diff --git a/src/klayout_tools/pex_net_correspondence.py b/src/klayout_tools/pex_net_correspondence.py new file mode 100644 index 000000000..8f8fef57f --- /dev/null +++ b/src/klayout_tools/pex_net_correspondence.py @@ -0,0 +1,361 @@ +"""The geometric net correspondence joining a runset-engine ``klt pex`` +leg's nets with a curated deck's parasitic extraction (issue #6606). + +``klt pex --engine klayout-runset`` (issue #6559) extracts its leg with the +PDK's own LVS runset, so the device set is the right one -- but with no +parasitics: the runset and a curated deck number their unlabelled nets +independently (``\\$1``, ``docs/cli/extract.md``'s "Anonymous net +numbering"), so curated parasitics cannot be attached to runset devices by +name. This module puts the two extractions in correspondence **by +geometry**; :mod:`klayout_tools.pex_merged_leg` builds the merged leg on +top of it. The measured decision -- why this rule and not the alternatives +-- is ``docs/design/runset-pex-net-correspondence.md``; this docstring +records the rule itself. + +The join, in one paragraph +-------------------------- + +Both extractions cluster the *same original shapes* (the same GDS) into +nets. For each net of the runset's selected circuit, sample strictly +interior points of its per-net polygons on the runset database's *metal* +layers only, and ask the curated extraction which net each point belongs to +(``klt extract --probe``'s own point-to-net machinery, evaluated on the +curated run's live ``LayoutToNetlist``). Exactly one distinct curated net +hit -> a match. More than one -> the runset net spans several curated nets +(a **split** disagreement). A curated net hit by several runset nets -> a +**merge** disagreement. No hit -> unmatched. Every outcome is reported in +the envelope's ``extraction.net_correspondence``; parasitics attach only to +1:1 matches, and a disagreement is reported, never guessed (issue #6606 +AC 2/3). + +Three restrictions the measurements forced (the decision doc carries the +numbers): sample points are **strictly interior** (a boundary point of one +net's polygon can lie exactly on another net's shape -- measured: a +substrate cluster's bbox centre landing on a gate-metal edge probed the +gate net), the join runs on **metal layers only** (device layers overlap by +construction -- the channel zone is inside both the source/drain and the +gate clusters of either engine; a well *contains* the devices' diffusion), +and a runset-internal layer joins one metal role only when **>= 99% of its +area lies inside that role's own GDS layer** (the runset database's layer +indices are anonymous; shape-set identity against the original stream is +what says "this internal layer *is* metal1"). +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import Any + +MAX_POINTS_PER_LAYER = 16 +MAX_POINTS_PER_NET = 64 + +#: An internal layer joins a metal role when at least this fraction of its +#: own area lies inside the role's GDS layer. Original metal layers are +#: single-source handles, so the real figure is 100%; anything mixed is a +#: derived layer and joins nothing. +_LAYER_IDENTITY_AREA_FRACTION = 0.99 + + +def _pex_error(message: str) -> Exception: + """A ``PexError`` built lazily, so importing this module never imports + ``pex`` (which imports this module's caller's pieces at load time).""" + from .pex import PexError + + return PexError(message) + + +def _is_anonymous(name: str) -> bool: + """Whether a net name is KLayout's own ``$N`` placeholder -- either + spelling: bare in memory, backslash-escaped in the written netlist.""" + return name.lstrip("\\").startswith("$") + + +def _escaped_net_name(raw: str) -> str: + """The report/netlist node spelling of a net name (issue #1162's + backslash-escaped ``\\$N``) -- the spelling both the curated probe + results and the runset leg's own node tokens use.""" + return "\\" + raw if raw.startswith("$") else raw + + +# --------------------------------------------------------------------------- # +# Geometry: layer-role matching and strictly-interior point sampling +# --------------------------------------------------------------------------- # + + +def _interior_point(poly: Any) -> Any | None: + """A point strictly inside ``poly``, or ``None``. + + The bbox centre when it is strictly interior; otherwise an inward + bisector step from the first hull vertex whose step lands inside (a + convex vertex's bisector is locally interior for a simple polygon). + Strictly interior is what the join's soundness rests on: a point on a + polygon's boundary can lie exactly on a *different* net's shape. + """ + import klayout.db as kdb + + box = poly.bbox() + centre = kdb.Point((box.left + box.right) // 2, (box.bottom + box.top) // 2) + if not any( + ( + centre.x == box.left, + centre.x == box.right, + centre.y == box.bottom, + centre.y == box.top, + ) + ) and poly.inside(centre): + return centre + hull = list(poly.each_point_hull()) + for index, vertex in enumerate(hull): + prev_p, next_p = hull[index - 1], hull[(index + 1) % len(hull)] + sum_x = (prev_p.x - vertex.x) + (next_p.x - vertex.x) + sum_y = (prev_p.y - vertex.y) + (next_p.y - vertex.y) + if sum_x == 0 and sum_y == 0: + continue + reach = max( + 1, + min( + abs(prev_p.x - vertex.x) + abs(prev_p.y - vertex.y), + abs(next_p.x - vertex.x) + abs(next_p.y - vertex.y), + ) + // 4, + ) + norm = max(1, abs(sum_x) + abs(sum_y)) + step = kdb.Point( + vertex.x + sum_x * reach // norm, vertex.y + sum_y * reach // norm + ) + if step != vertex and poly.inside(step): + return step + return None + + +def _flat_region(layout: Any, top_cell: Any, layer: int, datatype: int) -> Any: + """The flattened original-stream shapes of one GDS layer, or an empty + region when the stream does not draw it.""" + import klayout.db as kdb + + index = layout.find_layer(layer, datatype) + if index is None: + return kdb.Region() + return kdb.Region(top_cell.begin_shapes_rec(index)) + + +def _union_of_net_regions(lvs: Any, nets: Sequence[Any], layer_index: int) -> Any: + """The runset database's whole per-layer region, accumulated over every + net of every circuit it carries.""" + import klayout.db as kdb + + region: Any = None + for net in nets: + part = lvs.polygons_of_net(net, layer_index, True) + if part is not None and not part.is_empty(): + region = part if region is None else region + part + return kdb.Region() if region is None else region + + +def metal_role_map( + lvs: Any, layout: Any, top_cell: Any, metals: Sequence[tuple[int, int]] +) -> dict[int, str]: + """``{internal layer index: metal role}`` for the runset database's own + layers whose shape set is (>= 99% by area) one of the curated deck's + metal GDS layers -- the layer identity that lets a sampled point probe + exactly the role it is real geometry of.""" + nets = [net for c in lvs.netlist().each_circuit() for net in c.each_net()] + gds_regions = { + f"metal{index}": _flat_region(layout, top_cell, layer, datatype) + for index, (layer, datatype) in enumerate(metals) + } + roles: dict[int, str] = {} + for layer_index in lvs.internal_layout().layer_indexes(): + region = _union_of_net_regions(lvs, nets, layer_index) + if region.is_empty(): + continue + area = region.area() + for role in sorted(gds_regions): + inside = (region & gds_regions[role]).area() + if inside >= area * _LAYER_IDENTITY_AREA_FRACTION: + roles[layer_index] = role + break + return roles + + +def _net_probe_points( + lvs: Any, net: Any, roles: Mapping[int, str] +) -> dict[str, list[Any]]: + """``{role: [kdb.Point, ...]}`` -- strictly interior sample points of + ``net``'s polygons, per matched metal role, capped per layer and net.""" + points: dict[str, list[Any]] = {} + total = 0 + for layer_index, role in sorted(roles.items()): + region = lvs.polygons_of_net(net, layer_index, True) + if region is None: + continue + polygons = list(region.each()) + stride = max(1, len(polygons) // MAX_POINTS_PER_LAYER + 1) + for poly in polygons[::stride]: + if total >= MAX_POINTS_PER_NET: + return points + point = _interior_point(poly) + if point is not None: + points.setdefault(role, []).append(point) + total += 1 + return points + + +def build_probes( + lvsdb_path: str, + layout_path: str, + *, + top: str, + metals: Sequence[tuple[int, int]], + dbu_um: float, +) -> tuple[list[dict[str, Any]], dict[str, list[tuple[float, float]]]]: + """The ``run_extract`` ``probes`` list for the correspondence -- one + probe per runset-net sample point, on the metal role its layer matched + -- plus ``{runset net name: [(x_um, y_um), ...]}`` keyed in the + report's escaped ``nets[].name`` spelling, so the join's keys line up + with the curated probe results and the written netlist's node tokens.""" + import klayout.db as kdb + + layout = kdb.Layout() + layout.read(layout_path) + top_cell = layout.cell(top) + if top_cell is None: + raise _pex_error( + f"net correspondence: layout '{layout_path}' has no cell '{top}' " + "to read the curated deck's metal layers from" + ) + lvs = kdb.LayoutVsSchematic() + lvs.read(lvsdb_path) + circuit = lvs.netlist().circuit_by_name(top) + if circuit is None: + raise _pex_error( + "net correspondence: the runset database carries no circuit named " + f"'{top}', so its nets cannot be joined with the curated deck's" + ) + roles = metal_role_map(lvs, layout, top_cell, metals) + probes: list[dict[str, Any]] = [] + positions: dict[str, list[tuple[float, float]]] = {} + for net in circuit.each_net(): + name = _escaped_net_name(net.expanded_name()) + for role, pts in _net_probe_points(lvs, net, roles).items(): + entries = positions.setdefault(name, []) + for index, point in enumerate(pts): + probes.append( + { + "name": f"kltcorr|{role}|{name}|{index}", + "layer": role, + "x": point.x * dbu_um, + "y": point.y * dbu_um, + } + ) + entries.append((point.x * dbu_um, point.y * dbu_um)) + return probes, positions + + +# --------------------------------------------------------------------------- # +# The join over probe results +# --------------------------------------------------------------------------- # + + +def correspondence( + runset_net_names: Sequence[str], + probe_results: Sequence[Mapping[str, Any]], + curated_parasitic_nets: Sequence[Mapping[str, Any]], +) -> dict[str, Any]: + """The ``net_correspondence`` envelope block (issue #6606 AC 2/3). + + ``probe_results`` is the curated run's ``probes[]`` (a ``found`` entry + carries the final curated ``net`` name and ``cluster_id`` -- identity, + robust to two nets sharing one label); ``runset_net_names`` the selected + circuit's nets in the report's escaped spelling; + ``curated_parasitic_nets`` the curated ``parasitics.nets[]`` entries, so + a curated parasitic net nobody matched is listed even though it never + probes anything itself. + """ + hits: dict[str, set[tuple[str, int]]] = {} + for result in probe_results: + if not result.get("found"): + continue + parts = str(result.get("name") or "").split("|") + if len(parts) != 4 or parts[0] != "kltcorr": + continue + hit = (str(result["net"]), int(result["cluster_id"])) + hits.setdefault(parts[2], set()).add(hit) + + matched: list[dict[str, Any]] = [] + unmatched_runset: list[str] = [] + disagreements: list[dict[str, Any]] = [] + reverse: dict[tuple[str, int], list[str]] = {} + for runset_net in runset_net_names: + net_hits = sorted(hits.get(runset_net, ())) + if len(net_hits) == 1: + reverse.setdefault(net_hits[0], []).append(runset_net) + else: + unmatched_runset.append(runset_net) + if net_hits: + disagreements.append( + { + "kind": "split", + "runset_net": runset_net, + "curated_nets": [name for name, _ in net_hits], + } + ) + for curated_hit, runset_nets in sorted(reverse.items()): + if len(runset_nets) > 1: + # A curated net several runset nets reach is a merge + # disagreement: its parasitics attach to neither fragment, so + # every fragment is unmatched too -- never silently merged. + unmatched_runset.extend(runset_nets) + disagreements.append( + { + "kind": "merge", + "curated_net": curated_hit[0], + "runset_nets": sorted(runset_nets), + } + ) + else: + matched.append({"runset": runset_nets[0], "curated": curated_hit[0]}) + matched_curated = {entry["curated"] for entry in matched} + return { + "matched": sorted(matched, key=lambda entry: entry["runset"]), + "unmatched_runset_nets": sorted(unmatched_runset), + "unmatched_curated_nets": sorted( + { + str(entry["net"]) + for entry in curated_parasitic_nets + if str(entry["net"]) not in matched_curated + } + ), + "disagreements": sorted( + disagreements, + key=lambda entry: ( + entry["kind"], + str(entry.get("runset_net") or entry.get("curated_net")), + ), + ), + "probe_count": len(probe_results), + } + + +def preferred_renames( + matched: Sequence[Mapping[str, Any]], all_runset_nets: Sequence[str] +) -> dict[str, str]: + """``{runset name: merged name}``: a named runset net keeps its own name + (device-side truth); an anonymous one adopts its curated counterpart's + label when that has one -- unless that label collides with any other + net's kept name (a runset net already called that, or a second anonymous + net adopting the same label), in which case the anonymous spelling + stands. Mirrors the curated writer's own duplicate-label discipline + (its ``_dup`` suffixing) with the runset's own fallback: no rename.""" + kept = {net for net in all_runset_nets if not _is_anonymous(net)} + renames: dict[str, str] = {} + adopted: set[str] = set() + for entry in sorted(matched, key=lambda item: item["runset"]): + runset_net, curated_net = entry["runset"], entry["curated"] + if not _is_anonymous(runset_net) or _is_anonymous(curated_net): + continue + if curated_net in kept or curated_net in adopted: + continue + renames[runset_net] = curated_net + adopted.add(curated_net) + return renames diff --git a/src/klayout_tools/pex_runset.py b/src/klayout_tools/pex_runset.py index 742220457..0797e7f83 100644 --- a/src/klayout_tools/pex_runset.py +++ b/src/klayout_tools/pex_runset.py @@ -1,4 +1,5 @@ -"""``klt pex --engine klayout-runset`` (issue #6559): the runset-engine route. +"""``klt pex --engine klayout-runset`` (issues #6559/#6606): the runset-engine +route. ``klt pex`` always extracted through a curated ``--deck``. For a block whose core device family only the PDK's own KLayout LVS runset recognises (IHP's @@ -7,22 +8,28 @@ ``klt extract --engine klayout-runset`` instead, so the device set is the right one. -**What the route is, and is not.** The extracted leg is a *device-level* -netlist with **no parasitics**: nothing here joins the runset's devices with -the curated deck's parasitics (that needs a net correspondence between two -independently-numbered extractions, which nothing in this repo provides -- -issue #6606). A runset-engine ``klt pex`` report therefore does **not** by -itself satisfy ``docs/design-evidence-tiers.md`` T1 item 7's intent; it makes -the gap visible in the envelope instead of unreachable. Every ``extraction`` -field this module adds says so in machine-readable form, and is present -**only** under this engine, so a default-engine envelope is byte-identical to -one produced before the route existed. +**What the route is, and is not.** A plain runset leg is a *device-level* +netlist with **no parasitics**: nothing in that leg joins the runset's +devices with the curated deck's parasitics (that needs a net correspondence +between two independently-numbered extractions). ``--deck `` is +the **merged** route (issue #6606, :mod:`klayout_tools.pex_net_correspondence`): +it also runs that curated deck with parasitics, joins the two extractions by +measured geometric rules, and attaches the curated parasitic network to the +runset devices -- unmatched nets and split/merge disagreements disclosed in +``extraction.net_correspondence``, never silently dropped or merged. A +plain runset leg still does **not** by itself satisfy +``docs/design-evidence-tiers.md`` T1 item 7's intent, and ``klt signoff`` +now refuses it for item 7 (``no_parasitics``); every ``extraction`` field +this module adds says which shape the leg is in machine-readable form, and +is present **only** under this engine, so a default-engine envelope is +byte-identical to one produced before the route existed. What lives here rather than in :mod:`klayout_tools.pex` (size ratchet): the argument bundle, the ``run_extract`` option mapping, the refusal of the two ``klt pex`` options the extraction-side refusal table cannot see, and the ``extraction`` disclosure fields. Every *other* parasitic-only option is -refused by name inside ``run_extract`` itself, from the same +refused by name inside ``run_extract`` itself (and, on the merged route, by +the correspondence module), from the same ``REFUSED_FLAG_BY_PARAM`` table ``klt extract`` uses -- ``klt pex`` passes them through unchanged, so the two verbs cannot disagree about what the runset engine cannot honour. @@ -34,6 +41,7 @@ from dataclasses import dataclass from typing import Any +from .extract import run_extract from .extract_runset_flags import ( RUNSET_ENGINE, parse_deck_vars, @@ -152,10 +160,13 @@ def extraction_fields(extract_report: Mapping[str, Any]) -> dict[str, Any]: byte-identical. - ``engine`` -- ``"klayout-runset"``. - - ``parasitics_carried`` -- always ``false`` here: the extracted leg has no - R/C cards, so a ``delta[]`` over it is a device-representation delta, - not a parasitic one. Reported, never graded on (policy for a - parasitic-free leg is issue #6606's). + - ``parasitics_carried`` -- ``false`` for a plain runset leg (no R/C + cards, so a ``delta[]`` over it is a device-representation delta, not + a parasitic one). ``true`` only for a merged leg + (``--deck ``, issue #6606) whose correspondence actually + attached at least one parasitic card; the grading policy this field + feeds is ``klt signoff``'s ``no_parasitics`` refusal (issue #6606 + AC 4 -- ``signoff_pex_disclosure.parasitic_free_refusal``). - ``params_not_carried`` -- per device class, the measured parameters the ``X`` cards do **not** carry, so those devices simulate at the PDK subcircuit's own defaults. ``{}`` once every parameter is declared with @@ -173,6 +184,12 @@ def extraction_fields(extract_report: Mapping[str, Any]) -> dict[str, Any]: - ``extra_circuits`` -- the circuits written besides the selected one (``[]`` for a flat runset). ``net_count`` still describes the selected circuit alone; a non-empty list is how a reader knows that. + - ``net_correspondence`` -- present only on a merged leg (issue #6606): + ``matched`` / ``unmatched_runset_nets`` / ``unmatched_curated_nets`` / + ``disagreements`` (``split`` / ``merge``) / ``probe_count`` / + ``deck`` / ``attached_card_count``. A net that cannot be matched is + listed here, never silently dropped or silently merged; a connectivity + disagreement between the two engines is reported, not compared. """ if extract_report.get("engine") != RUNSET_ENGINE: return {} @@ -180,9 +197,8 @@ def extraction_fields(extract_report: Mapping[str, Any]) -> dict[str, Any]: counts = extract_report.get("instantiated_device_counts") if counts is None: # an extract report predating the hierarchy-aware count counts = extract_report.get("device_counts") or {} - return { + fields: dict[str, Any] = { "engine": RUNSET_ENGINE, - "parasitics_carried": False, "params_not_carried": { name: list(uncarried[name]) for name in sorted(uncarried) }, @@ -190,3 +206,131 @@ def extraction_fields(extract_report: Mapping[str, Any]) -> dict[str, Any]: "device_count": sum(counts.values()), "extra_circuits": list(extract_report.get("extra_circuits") or []), } + correspondence = extract_report.get("net_correspondence") + if correspondence is None: + fields["parasitics_carried"] = False + else: + fields["parasitics_carried"] = bool(correspondence.get("attached_card_count")) + fields["net_correspondence"] = dict(correspondence) + return fields + + +def run_extract_leg( + layout_path: str, + deck_name: str | None, + *, + runset: PexRunset | None, + output: str | None = None, + top: str | None = None, + pdk_variant: str | None = None, + pdk_root: str | None = None, + label_layers: Mapping[str, tuple[int, int] | None] | None = None, + device_models: Mapping[str, str] | None = None, + deck_options: Mapping[str, str] | None = None, + declared_pins: frozenset[str] | None = None, + rename_declared_pins: bool = False, + tie_declared_pins: bool = False, + critical_nets: Sequence[str] | None = None, + critical_net_patterns: Sequence[str] | None = None, + critical_net_all: bool = False, + critical_net_excludes: Sequence[str] | None = None, + distributed_rc: bool = False, + resistance_graph: bool = False, + resistance_graph_r_cut_ohm: float | None = None, + parasitic_variants: Sequence[str] | None = None, + substrate_tie_ohms: float | None = None, + mom_rlc_net: str | None = None, + mom_rlc_resistance_ohm: float | None = None, + mom_rlc_capacitance_ff: float | None = None, + mom_rlc_inductance_nh: float | None = None, +) -> dict[str, Any]: + """``klt pex``'s extracted leg, in whichever of its three shapes this + run's engine selection asks for (issues #6559/#6606): + + - ``runset is None`` -- the curated-deck engine, ``run_extract`` with + the parasitics path on: the only shape before the runset route + existed, and the exact call this module's callers made then. + - ``runset is not None`` and no ``deck_name`` -- the runset engine's + device-only leg (``extract_options(runset)``). + - ``runset is not None`` **and** ``deck_name`` -- the merged route + (issue #6606): :func:`klayout_tools.pex_merged_leg.merged_runset_extract` + runs the runset leg *and* a curated parasitic extraction, joins them + by the geometric net correspondence, and attaches the curated + parasitic network to the runset devices. ``deck_name``/``label_layers`` + route to the curated leg here; every other option only a richer + curated parasitic model could serve is refused by name in there. + + Raises :class:`ExtractError` (the caller wraps it into a ``PexError``) + for every extraction-side failure and usage refusal. + """ + if runset is not None and deck_name: + from .pex_merged_leg import merged_runset_extract + + return merged_runset_extract( + layout_path=layout_path, + output=output, + top=top, + runset=runset, + deck_name=deck_name, + label_layers=label_layers, + device_models=device_models, + deck_options=deck_options, + declared_pins=declared_pins, + rename_declared_pins=rename_declared_pins, + tie_declared_pins=tie_declared_pins, + critical_nets=critical_nets, + critical_net_patterns=critical_net_patterns, + critical_net_all=critical_net_all, + critical_net_excludes=critical_net_excludes, + distributed_rc=distributed_rc, + resistance_graph=resistance_graph, + resistance_graph_r_cut_ohm=resistance_graph_r_cut_ohm, + parasitic_variants=parasitic_variants, + substrate_tie_ohms=substrate_tie_ohms, + mom_rlc_net=mom_rlc_net, + mom_rlc_resistance_ohm=mom_rlc_resistance_ohm, + mom_rlc_capacitance_ff=mom_rlc_capacitance_ff, + mom_rlc_inductance_nh=mom_rlc_inductance_nh, + ) + return run_extract( + layout_path, + deck_name, + output=output, + top=top, + pdk_variant=pdk_variant, + pdk_root=pdk_root, + # Issue #6559: the runset engine has no parasitics; every other + # option passes through and is refused by name by `run_extract`. + parasitics=runset is None, + # Issue #1558: `--deck-option`/`--pins` passthrough. `None` for + # both whenever the flags were never given, which is the exact + # `run_extract` call this mapping made before they existed. + deck_options=deck_options, + declared_pins=declared_pins, + # Issue #2854: `--rename-declared-pins` passthrough. `False` + # whenever the flag was never given, which is the exact + # `run_extract` call this mapping made before it existed. + rename_declared_pins=rename_declared_pins, + tie_declared_pins=tie_declared_pins, + # Issue #2686: `--label-layer` passthrough. `None` when the flag + # was never given -- the exact `run_extract` call made before it. + label_layers=label_layers, + device_models=device_models, + critical_nets=critical_nets, + critical_net_patterns=critical_net_patterns, + critical_net_all=critical_net_all, + critical_net_excludes=critical_net_excludes, + distributed_rc=distributed_rc, + # Issue #4037: `False`/`None` whenever the flags were never given, + # which is the exact `run_extract` call made before they existed. + resistance_graph=resistance_graph, + resistance_graph_r_cut_ohm=resistance_graph_r_cut_ohm, + emit_selected_resistance=resistance_graph, + parasitic_variants=parasitic_variants, + substrate_tie_ohms=substrate_tie_ohms, + mom_rlc_net=mom_rlc_net, + mom_rlc_resistance_ohm=mom_rlc_resistance_ohm, + mom_rlc_capacitance_ff=mom_rlc_capacitance_ff, + mom_rlc_inductance_nh=mom_rlc_inductance_nh, + **extract_options(runset), + ) diff --git a/src/klayout_tools/signoff.py b/src/klayout_tools/signoff.py index 26cb82229..3fc25b230 100644 --- a/src/klayout_tools/signoff.py +++ b/src/klayout_tools/signoff.py @@ -230,10 +230,10 @@ _na_statistical_detail, ) -# The cited `klt pex` envelope's extraction disclosures (issues #1983, #6559), -# split out of this file for its size-ratchet ceiling and re-imported by name so -# `signoff.` keeps resolving. +# The cited `klt pex` envelope's extraction disclosures (issues #1983/#6559) +# and its item-7 parasitics gate (#6606), split out for the size-ratchet ceiling. from .signoff_pex_disclosure import _pex_body_bias_disclosure, _pex_engine_disclosure +from .signoff_pex_disclosure import parasitic_free_refusal as _parasitic_free # T1 item 11's ("Power delivery (structural)") grading subsystem lives in its # own module (issue #2626, split out of this one at ~7600 lines), following @@ -3234,14 +3234,14 @@ def _kind_gated_check( estimate is not sized, or its own declared negative control did not detect the seeded degradation. See :func:`_yield_campaign_refusal`. - :func:`_check_passed` runs before these checks. Within this gate, - ``nothing_checked`` comes first and the yield campaign check comes last. """ if not _kind_is_accepted(check_kind, allowed_kinds): return None, False refusal = _coverage_refusal(check_kind, envelope) if refusal is not None: return refusal, False + if check_kind == "pex" and (refusal := _parasitic_free(envelope)): + return refusal, False rehash_unverifiable = False if check_kind == "lvs": refusal, rehash_unverifiable = check_runset(envelope) diff --git a/src/klayout_tools/signoff_pex_disclosure.py b/src/klayout_tools/signoff_pex_disclosure.py index bd3afd720..08076dd9d 100644 --- a/src/klayout_tools/signoff_pex_disclosure.py +++ b/src/klayout_tools/signoff_pex_disclosure.py @@ -94,8 +94,10 @@ def _pex_engine_disclosure( every curated-deck run, and every record committed before the route existed, which therefore renders exactly as it did before. - Grading policy for a parasitic-free leg is deliberately not decided here - (issue #6606): this is disclosure only. + Grading policy for a parasitic-free leg is **refused** (issue #6606 + AC 4): :func:`parasitic_free_refusal` is the gate ``klt signoff`` + consults, rendering item 7 ``"unmet"``/``no_parasitics`` -- this + function stays the disclosure half, quoted beside the verdict. """ if kind != "pex": return None @@ -112,3 +114,26 @@ def _pex_engine_disclosure( ), } } + + +def parasitic_free_refusal(envelope: Mapping[str, Any]) -> str | None: + """The item-7 refusal reason for a pex envelope whose own extraction + disclosure says the extracted leg carried no parasitics (issue #6606 + AC 4) -- ``"no_parasitics"``, or ``None`` when the leg carries them (or + makes no engine statement, which every curated-deck run does not). + + Purely a read of the envelope's own ``extraction`` block, quoted from + the ``klt pex`` run that wrote it, never re-derived: a plain + ``--engine klayout-runset`` leg discloses ``parasitics_carried: false`` + (its ``delta[]`` rows are device-representation deltas), while a merged + leg (``--deck ``) flips the field to ``true`` exactly when the + net correspondence attached at least one parasitic card. An envelope + with no ``extraction.engine`` (every curated-deck run, and every record + predating the route) carries parasitics by construction and is never + refused here.""" + extraction = envelope.get("extraction") + if not isinstance(extraction, dict) or not extraction.get("engine"): + return None + if extraction.get("parasitics_carried") is False: + return "no_parasitics" + return None diff --git a/tests/test_pex.py b/tests/test_pex.py index 33be68e76..2ac0cc06d 100644 --- a/tests/test_pex.py +++ b/tests/test_pex.py @@ -3003,7 +3003,7 @@ def strip_integrity(*args, **kwargs): entry.pop("integrity", None) return report - monkeypatch.setattr(pex_module, "run_extract", strip_integrity) + monkeypatch.setattr(pex_module.pex_runset, "run_extract", strip_integrity) dut = _write_schematic_dut(tmp_path / "schematic_dut.spice") tb = _write_testbench(tmp_path / "testbench.spice", dut) @@ -3084,7 +3084,7 @@ def _spy(*args, **kwargs): seen.append(kwargs.get("substrate_tie_ohms", "missing")) return real_run_extract(*args, **kwargs) - monkeypatch.setattr(pex_module, "run_extract", _spy) + monkeypatch.setattr(pex_module.pex_runset, "run_extract", _spy) dut = _write_schematic_dut(tmp_path / "schematic_dut.spice") tb = _write_testbench(tmp_path / "testbench.spice", dut) request = _write_request(tmp_path / "request.json", tb) @@ -5061,8 +5061,8 @@ def resistor_layout_unread_purpose(tmp_path): def _capture_run_extract_kwargs(monkeypatch) -> list[dict]: - """Wrap `pex.run_extract` (still calling the real one) and record every - call's keyword arguments.""" + """Wrap the extracted leg's `run_extract` (still calling the real one) + and record its kwargs -- dispatched via `pex_runset` since #6606.""" import klayout_tools.pex as pex_module real = pex_module.run_extract @@ -5072,7 +5072,7 @@ def _recording_run_extract(*args, **kwargs): calls.append(kwargs) return real(*args, **kwargs) - monkeypatch.setattr(pex_module, "run_extract", _recording_run_extract) + monkeypatch.setattr(pex_module.pex_runset, "run_extract", _recording_run_extract) return calls diff --git a/tests/test_pex_net_correspondence.py b/tests/test_pex_net_correspondence.py new file mode 100644 index 000000000..b3dd30a86 --- /dev/null +++ b/tests/test_pex_net_correspondence.py @@ -0,0 +1,444 @@ +"""The geometric net correspondence and the merged ``klt pex --engine +klayout-runset --deck `` leg (issue #6606). + +Same faked-subprocess layer as ``tests/test_extract_runset.py``: the runset +subprocess is stubbed and writes a *real* ``.lvsdb`` built with the pip +``klayout.db`` API over the repo's own sg13cmos5l inverter fixture, while the +curated leg runs for real in-process -- so the join, the merged netlist +writer and the envelope fields are exercised end to end with no PDK install. +The fake builder's ``connect`` table has knobs that deliberately disagree +with the curated deck, which is what the disagreement reporting is asserted +on (issue #6606's Test Plan: "a deliberately-split net"). + +Real-PDK numbers (the measured outcomes the decision doc records) are pinned +by one skip-gated test at the end, against IHP's own ``pnpMPA`` testcase. +""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess + +import klayout.db as kdb +import pytest + +from klayout_tools.pex_merged_leg import merge_parasitics, merged_runset_extract +from klayout_tools.pex_net_correspondence import ( + correspondence, + preferred_renames, +) +from klayout_tools.pex_runset import PexRunset +from test_extract_body_nets_sg13cmos5l import ( + _make_sg13cmos5l_inverter_layout, +) + +#: The fixture's own layers (see ``_make_sg13cmos5l_inverter_layout``): +#: activ 1/0, gatpoly 5/0, cont 6/0, metal1 8/0, nwell 31/0, labels 8/2. +ACTIV, GATPOLY, CONT, METAL1 = (1, 0), (5, 0), (6, 0), (8, 0) + + +def _write_fixture(path: str) -> None: + _make_sg13cmos5l_inverter_layout().write(path) + + +def _write_lvsdb( + gds: str, + schem: str, + out: str, + *, + isolate_metals: bool = False, + bridge_terminals: bool = False, +) -> None: + """Stand in for the PDK runset on the cmos5l inverter fixture. + + ``isolate_metals`` drops every metal1 join (cont no longer bridges + activ to metal1), so each electrical net the curated deck sees becomes + two runset clusters -- a **merge** disagreement per labelled net. + ``bridge_terminals`` additionally connects diffusion to the gate + (something no engine should do), so one runset cluster spans several + curated nets -- a **split** disagreement. + """ + ly = kdb.Layout() + ly.read(gds) + l2n = kdb.LayoutVsSchematic(kdb.RecursiveShapeIterator(ly, ly.top_cell(), [])) + activ = l2n.make_layer(ly.layer(*ACTIV), "activ") + poly = l2n.make_layer(ly.layer(*GATPOLY), "gatpoly") + cont = l2n.make_layer(ly.layer(*CONT), "cont") + metal1 = l2n.make_layer(ly.layer(*METAL1), "metal1") + gate, sd = activ & poly, activ - poly + l2n.extract_devices( + kdb.DeviceExtractorMOS4Transistor("NMOS"), + {"SD": sd, "G": gate, "tG": poly, "W": poly}, + ) + for region in (sd, poly, gate, cont, metal1): + l2n.connect(region) + if bridge_terminals: + l2n.connect(sd, gate) + if not isolate_metals: + l2n.connect(metal1, cont) + l2n.connect(cont, sd) + l2n.extract_netlist() + l2n.netlist().make_top_level_pins() + ref = kdb.Netlist() + ref.read(schem, kdb.NetlistSpiceReader()) + l2n.reference = ref + l2n.compare(kdb.NetlistComparer()) + l2n.write(out) + + +@pytest.fixture +def fake_klayout(monkeypatch, tmp_path): + """Replace the runset subprocess; ``state`` controls the fake database.""" + state: dict = {"isolate_metals": False, "bridge_terminals": False} + fake_bin = tmp_path / "klayout" + fake_bin.write_text("#!/bin/sh\n") + fake_bin.chmod(0o755) + monkeypatch.setenv("KLT_KLAYOUT_BINARY", str(fake_bin)) + real_run = subprocess.run + + def fake_run(cmd, *a, **kw): + if cmd[0] != str(fake_bin): + return real_run(cmd, *a, **kw) + if cmd[1:] == ["-v"]: + return subprocess.CompletedProcess(cmd, 0, "KLayout 0.30.12\n", "") + args = dict(c.split("=", 1) for c in cmd if "=" in c and c != "-rd") + _write_lvsdb( + args["input"], + args["schematic"], + args["report"], + isolate_metals=state["isolate_metals"], + bridge_terminals=state["bridge_terminals"], + ) + return subprocess.CompletedProcess(cmd, 0, "", "") + + monkeypatch.setattr(subprocess, "run", fake_run) + return state + + +def _merged(tmp_path, fake_klayout): + gds = tmp_path / "inv.gds" + _write_fixture(str(gds)) + deck_file = tmp_path / "pdk.lvs" + deck_file.write_text("# runset\n") + return merged_runset_extract( + layout_path=str(gds), + output=str(tmp_path / "leg.spice"), + top="TOP", + runset=PexRunset(deck_file=str(deck_file)), + deck_name="sg13cmos5l", + label_layers=None, + device_models=None, + deck_options=None, + declared_pins=None, + rename_declared_pins=False, + tie_declared_pins=False, + critical_nets=None, + critical_net_patterns=None, + critical_net_all=False, + critical_net_excludes=None, + distributed_rc=False, + resistance_graph=False, + resistance_graph_r_cut_ohm=None, + parasitic_variants=None, + substrate_tie_ohms=None, + mom_rlc_net=None, + mom_rlc_resistance_ohm=None, + mom_rlc_capacitance_ff=None, + mom_rlc_inductance_nh=None, + ) + + +def test_labelled_and_unlabelled_nets_both_match_and_get_parasitics( + tmp_path, fake_klayout +): + """Issue #6606's Test Plan: a device on a labelled and an unlabelled + net -- the correspondence lists both, and parasitics reach the devices. + + The runset leg's nets are all anonymous (the fake reads no labels); + the curated leg names A/VGND/VPWR/Y from the fixture's 8/2 labels, so + every match pairs an anonymous runset net with a labelled curated one, + and the merged netlist adopts the labels -- exactly the case the old + "independent ``\\$N`` numbering" gap closed off.""" + report = _merged(tmp_path, fake_klayout) + corr = report["net_correspondence"] + + # The whole labelled routing stack matches -- each pairing an anonymous + # runset net (the fake reads no labels) with its labelled curated net. + assert [entry["curated"] for entry in corr["matched"]] == [ + "VGND", + "Y", + "VPWR", + "Y", + "A", + ] + # Every matched runset net is the fixture's own anonymous \$N spelling. + assert all(entry["runset"].startswith("\\$") for entry in corr["matched"]) + # What the runset saw that the curated leg did not: the well/substrate + # body clusters, which carry no metal -- listed, never silently dropped. + assert corr["unmatched_runset_nets"] + assert corr["disagreements"] == [] + assert corr["attached_card_count"] == 9 # 4 parasitic nets x (R + C) + tie + + text = open(str(tmp_path / "leg.spice")).read() + assert "parasitics attached from curated deck 'sg13cmos5l'" in text + assert "no parasitics: this engine extracts devices" not in text + assert ".GLOBAL vsubs" in text + # The parasitic cards land on the *adopted label* nodes, and the device + # cards reference the same nodes -- one netlist, not two views. + assert "RVGND_plr VGND VGND__kltph" in text + assert "CVGND_plc VGND__kltph vsubs" in text + assert "X$1 " in text # the runset device card survived the rewrite + for line in text.splitlines(): + if line.startswith("X$1"): + # the device card sits on the adopted-label nodes too + assert "VPWR" in line + # DC bias path for the substrate the caps land on, exactly as a curated + # netlist ties it. + assert "Rvsubs_dctie vsubs 0 1e+12" in text + + +def test_a_merge_disagreement_is_reported_never_guessed(tmp_path, fake_klayout): + """A net the runset splits but the curated deck joins: the parasitics + of the joined curated net cannot attach to either fragment -- the + disagreement is reported and the fragments stay parasitic-free.""" + fake_klayout["isolate_metals"] = True + report = _merged(tmp_path, fake_klayout) + corr = report["net_correspondence"] + + merges = [d for d in corr["disagreements"] if d["kind"] == "merge"] + assert {m["curated_net"] for m in merges} == {"A", "VGND", "VPWR", "Y"} + for merge in merges: + # exactly the two fragments: the metal side and the diffusion side + assert len(merge["runset_nets"]) == 2 + assert all(net.startswith("\\$") for net in merge["runset_nets"]) + # Nothing matched, so nothing attached: the leg keeps its own honest + # header and carries no cards. + assert corr["matched"] == [] + assert corr["attached_card_count"] == 0 + text = open(str(tmp_path / "leg.spice")).read() + assert "no parasitics: this engine extracts devices" in text + assert "_plr " not in text + + +def test_a_split_disagreement_is_reported_not_compared(tmp_path, fake_klayout): + """A runset cluster spanning several curated nets is refused both ways: + reported as a split, its curated nets left unmatched, no cards.""" + fake_klayout["bridge_terminals"] = True + report = _merged(tmp_path, fake_klayout) + corr = report["net_correspondence"] + + splits = sorted( + (d for d in corr["disagreements"] if d["kind"] == "split"), + key=lambda d: d["runset_net"], + ) + assert [s["curated_nets"] for s in splits] == [["VGND", "Y"], ["VPWR", "Y"]] + # The one cluster the bridge left whole still matches and attaches. + assert corr["matched"] == [{"runset": "\\$3", "curated": "A"}] + assert corr["attached_card_count"] == 3 # A's R + C + the substrate tie + + +# --------------------------------------------------------------------------- # +# Unit layer: the pure join pieces +# --------------------------------------------------------------------------- # + + +def _probe(runset_net: str, curated: str, cluster: int, found: bool = True): + return { + "name": f"kltcorr|metal0|{runset_net}|0", + "found": found, + "net": curated if found else None, + "cluster_id": cluster if found else None, + } + + +def test_correspondence_classifies_every_outcome(): + corr = correspondence( + ["\\$1", "\\$2", "\\$3", "\\$4"], + [ + _probe("\\$1", "A", 3), + _probe("\\$2", "B", 1), + _probe("\\$2", "C", 2), # \$2 spans two curated nets: split + _probe("\\$4", "A", 3), # A also hit by \$1: merge with \$1 + {"name": "user-probe", "found": True, "net": "X", "cluster_id": 9}, + ], + [{"net": "D"}, {"net": "A"}], + ) + assert corr["matched"] == [] # A's merge poisons both of its fragments + assert corr["unmatched_runset_nets"] == ["\\$1", "\\$2", "\\$3", "\\$4"] + # Only parasitic curated nets are listed unmatched -- B/C were probe + # hits, not parasitic nets, and D never matched anything. + assert corr["unmatched_curated_nets"] == ["A", "D"] + kinds = { + (d["kind"], d.get("runset_net") or d.get("curated_net")) + for d in corr["disagreements"] + } + assert ("split", "\\$2") in kinds + assert ("merge", "A") in kinds + # A caller's own probes never leak into the join. + assert corr["probe_count"] == 5 + + +def test_unfound_probes_are_not_matches(): + corr = correspondence( + ["\\$1"], [_probe("\\$1", None, None, found=False)], [{"net": "A"}] + ) + assert corr["matched"] == [] + assert corr["unmatched_runset_nets"] == ["\\$1"] + assert corr["unmatched_curated_nets"] == ["A"] + + +def test_preferred_renames_adopt_labels_and_refuse_collisions(): + matched = [ + {"runset": "\\$1", "curated": "A"}, + {"runset": "\\$2", "curated": "B"}, + {"runset": "\\$3", "curated": "A"}, # second A: collision, no rename + ] + renames = preferred_renames(matched, ["\\$1", "\\$2", "\\$3", "PAD"]) + assert renames == {"\\$1": "A", "\\$2": "B"} + # A label already owned by a named runset net is never adopted. + renames = preferred_renames([{"runset": "\\$4", "curated": "PAD"}], ["\\$4", "PAD"]) + assert renames == {} + + +def test_merge_writer_preserves_pin_order_and_untouched_nets(tmp_path): + leg = tmp_path / "leg.spice" + leg.write_text( + "* extracted by klt extract --engine klayout-runset --deck-file p.lvs\n" + "* no parasitics: this engine extracts devices and connectivity only\n" + "* cell TOP\n" + ".SUBCKT TOP \\$1 \\$2 keepme\n" + "X$1 \\$1 \\$2 keepme nmos\n" + ".ENDS TOP\n" + ) + cards = merge_parasitics( + str(leg), + matched=[{"runset": "\\$1", "curated": "A"}], + all_runset_nets=["\\$1", "\\$2", "keepme"], + parasitics={ + "nets": [ + { + "net": "A", + "resistance_ohm": 0.5, + "capacitance_ff": 2.0, + "coupled": [], + }, + { # unmatched curated net: its card is dropped, not guessed + "net": "B", + "resistance_ohm": 9.0, + "capacitance_ff": 9.0, + "coupled": [], + }, + ], + "substrate_dc_tie": { + "resistance_ohm": 1e12, + "nets": [{"net": "vsubs", "device": "Rvsubs_dctie"}], + }, + }, + deck_name="sg13cmos5l", + report_block={"unmatched_runset_nets": ["\\$2"]}, + ) + text = leg.read_text() + assert cards == 3 # R + C + the substrate tie; B contributed none + assert ".SUBCKT TOP A \\$2 keepme\n" in text # renamed in place, order kept + assert "X$1 A \\$2 keepme nmos" in text + assert "keepme" in text.split(".SUBCKT")[1].splitlines()[0] + assert "RA_plr A A__kltph 0.5" in text + assert "CA_plc A__kltph vsubs 2e-15" in text + assert "Rvsubs_dctie vsubs 0 1e+12" in text + assert ".GLOBAL vsubs" in text + assert not any( + line.startswith(("R", "C")) and " 9" in line for line in text.splitlines() + ) + + +def test_probe_results_parse_only_kltcorr_names(): + corr = correspondence( + ["\\$1"], + [ + _probe("\\$1", "A", 1), + { + "name": "kltcorr|metal0|broken", + "found": True, + "net": "X", + "cluster_id": 2, + }, + {"name": "kltcorr|a|b|c|d", "found": True, "net": "Y", "cluster_id": 3}, + ], + [], + ) + assert corr["matched"] == [{"runset": "\\$1", "curated": "A"}] + + +# --------------------------------------------------------------------------- # +# Real-PDK layer: the measured pnpMPA outcome, pinned +# --------------------------------------------------------------------------- # + + +def _pnpmpa_inputs(): + from klayout_tools import pdk + + try: + root = pdk.find_pdk(variant="ihp-sg13cmos5l")["assets"]["klayout"] + except Exception: + pytest.skip("no ihp-sg13cmos5l PDK install") + lvs_dir = os.path.join(root, "tech", "lvs") + case = os.path.join(lvs_dir, "testing", "testcases", "unit", "bjt_devices") + paths = ( + os.path.join(lvs_dir, "sg13cmos5l.lvs"), + os.path.join(case, "layout", "pnpMPA.gds"), + ) + if not all(os.path.isfile(p) for p in paths): + pytest.skip("ihp-sg13cmos5l install lacks the pnpMPA LVS testcase") + return paths + + +@pytest.mark.skipif(shutil.which("klayout") is None, reason="klayout binary absent") +def test_real_pnpmpa_merged_run_reports_the_measured_mismatch(tmp_path): + """The decision doc's headline measurement, pinned: on IHP's own + testcase the curated leg is empty (labels on 10/25 and PCell vias the + pip ``klayout.db`` curated engine cannot see), so the merged run + reports the total mismatch instead of attaching anything -- the honest + degeneration that keeps ``no_parasitics`` the item-7 verdict there.""" + deck, gds = _pnpmpa_inputs() + report = merged_runset_extract( + layout_path=gds, + output=str(tmp_path / "pnpMPA.spice"), + top="pnpMPA_lvs", + runset=PexRunset(deck_file=deck), + deck_name="sg13cmos5l", + label_layers=None, + device_models=None, + deck_options=None, + declared_pins=None, + rename_declared_pins=False, + tie_declared_pins=False, + critical_nets=None, + critical_net_patterns=None, + critical_net_all=False, + critical_net_excludes=None, + distributed_rc=False, + resistance_graph=False, + resistance_graph_r_cut_ohm=None, + parasitic_variants=None, + substrate_tie_ohms=None, + mom_rlc_net=None, + mom_rlc_resistance_ohm=None, + mom_rlc_capacitance_ff=None, + mom_rlc_inductance_nh=None, + ) + corr = report["net_correspondence"] + assert report["device_counts"] == {"pnpMPA": 1, "ptap1": 1} + assert corr["matched"] == [] + assert corr["attached_card_count"] == 0 + # Both measured disagreement shapes: the substrate merge (runset $1 and + # VSS both reach metal1 the curated leg folded into vsubs) and the + # pad/power nets with no curated counterpart at all. + assert {"PAD", "VDD"} <= set(corr["unmatched_runset_nets"]) + merges = [d for d in corr["disagreements"] if d["kind"] == "merge"] + assert merges and merges[0]["curated_net"] == "vsubs" + assert {"\\$1", "VSS"} <= set(merges[0]["runset_nets"]) + # The envelope this produces refuses item 7 (no_parasitics), which the + # signoff tests in test_pex_runset_signoff.py grade separately. + assert json.dumps(corr) diff --git a/tests/test_pex_runset.py b/tests/test_pex_runset.py index 8b278b53d..90161316b 100644 --- a/tests/test_pex_runset.py +++ b/tests/test_pex_runset.py @@ -207,11 +207,30 @@ def test_parasitic_only_option_is_refused_by_name(tmp_path, fake_klayout, kwargs assert "cmd" not in fake_klayout -def test_curated_deck_name_is_refused_by_name_under_the_runset_engine( +def test_curated_deck_under_the_runset_engine_is_the_merged_route( tmp_path, fake_klayout ): - with pytest.raises(PexError, match=r"cannot honour --deck\b"): - _extract_only(tmp_path, deck="sky130") + """Issue #6606: `--deck` under the runset engine is no longer refused -- + it runs the curated leg and reports the correspondence. On this sky130- + invisible fixture (arbitrary layer numbers, no labels) nothing can + match, which the envelope states rather than guessing: no cards, so the + leg still carries no parasitics, and every runset net is listed + unmatched -- never silently dropped.""" + report = _extract_only(tmp_path, deck="sky130") + + extraction = report["extraction"] + assert extraction["deck"] == "sky130" + assert extraction["parasitics_carried"] is False + correspondence = extraction["net_correspondence"] + assert correspondence["deck"] == "sky130" + assert correspondence["attached_card_count"] == 0 + assert correspondence["matched"] == [] + assert correspondence["unmatched_runset_nets"] # the fixture's \$N nets + assert correspondence["disagreements"] == [] + # A leg nothing attached keeps its own honest header line. + text = open(str(tmp_path / "out.spice")).read() + assert "no parasitics: this engine extracts devices and connectivity" in text + assert "parasitics attached" not in text def test_every_refusal_is_named_at_once(tmp_path, fake_klayout): diff --git a/tests/test_pex_runset_cli.py b/tests/test_pex_runset_cli.py index 87cbc54cd..2c159c159 100644 --- a/tests/test_pex_runset_cli.py +++ b/tests/test_pex_runset_cli.py @@ -181,10 +181,13 @@ def test_cli_default_engine_still_requires_a_deck(tmp_path, fake_klayout, capsys assert "--deck" in err["error"]["message"] -def test_cli_curated_deck_is_refused_by_name_under_the_runset_engine( +def test_cli_curated_deck_under_the_runset_engine_runs_the_merged_route( tmp_path, fake_klayout, capsys ): - code, _out, err = _cli( + """Issue #6606: `--deck` under the runset engine selects the merged + route instead of exiting 1 -- the CLI envelope carries the + correspondence even when (as on this fixture) nothing matches.""" + code, out, _err = _cli( tmp_path, "--engine", "klayout-runset", @@ -196,8 +199,10 @@ def test_cli_curated_deck_is_refused_by_name_under_the_runset_engine( capsys=capsys, ) - assert code == 1 - assert "cannot honour --deck" in err["error"]["message"] + assert code == 4 # extract-only's own `not_checked`, not a refusal + extraction = json.loads(out)["extraction"] + assert extraction["deck"] == "sky130" + assert extraction["net_correspondence"]["deck"] == "sky130" def test_cli_parasitic_only_flag_is_refused_by_name_under_the_runset_engine( diff --git a/tests/test_pex_runset_signoff.py b/tests/test_pex_runset_signoff.py index c69aedfbe..8ea361eb6 100644 --- a/tests/test_pex_runset_signoff.py +++ b/tests/test_pex_runset_signoff.py @@ -1,6 +1,9 @@ """``klt signoff`` surfaces ``klt pex --engine klayout-runset``'s extraction -disclosure (issue #6559) like it surfaces ``body_bias`` -- reported, never -graded on -- in aggregation-mode ``detail`` and on an item-7 citation. +disclosure (issue #6559) like it surfaces ``body_bias`` -- in aggregation- +mode ``detail`` and on an item-7 citation -- and, since issue #6606 AC 4, +**refuses** a parasitic-free leg for item 7 (``no_parasitics``): item 7 is +parasitic verification, and a merged leg (``--deck ``, which +attached cards) is the runset route that grades. Split out of ``tests/test_pex_runset.py`` (file-size ratchet), reusing ``tests/test_signoff.py``'s envelope fixtures. @@ -28,6 +31,25 @@ }, } +#: The same leg with parasitics attached (issue #6606's merged route: +#: ``--deck ``), which is the runset-engine shape item 7 accepts. +PEX_RUNSET_MERGED_PASS_ENVELOPE = { + **PEX_RUNSET_PASS_ENVELOPE, + "extraction": { + **PEX_RUNSET_PASS_ENVELOPE["extraction"], + "parasitics_carried": True, + "net_correspondence": { + "matched": [{"runset": "\\$3", "curated": "VGND"}], + "unmatched_runset_nets": [], + "unmatched_curated_nets": [], + "disagreements": [], + "probe_count": 6, + "deck": "sg13cmos5l", + "attached_card_count": 7, + }, + }, +} + DISCLOSURE = { "engine": "klayout-runset", "parasitics_carried": False, @@ -51,17 +73,25 @@ def test_signoff_detail_surfaces_the_runset_engine_disclosure(tmp_path): def test_signoff_citation_surfaces_the_runset_engine_disclosure(tmp_path): - path = _write(tmp_path, "pex.json", PEX_RUNSET_PASS_ENVELOPE) + """A *merged* leg (issue #6606) is the runset-engine citation item 7 + accepts; its disclosure rides the citation exactly as a parasitic-free + one's did before the grading policy landed.""" + path = _write(tmp_path, "pex.json", PEX_RUNSET_MERGED_PASS_ENVELOPE) report = build_tier_report(_manifest(evidence={"7": path})) item_7 = next(item for item in report["items"] if item["id"] == 7) - assert item_7["citation"]["pex_extraction"] == DISCLOSURE + assert item_7["status"] == "met" + assert item_7["citation"]["pex_extraction"] == { + "engine": "klayout-runset", + "parasitics_carried": True, + "params_not_carried": {"pnpMPA": ["A", "P"]}, + } def test_signoff_does_not_grade_on_the_runset_disclosure(tmp_path): - """Reported, never graded: grading policy for a parasitic-free leg is - issue #6606's. The verdict is exactly the curated envelope's.""" + """The *check* stays pass either way (the gate is item 7's, not the + check's); the item verdict is what the parasitics disclosure decides.""" runset = _write(tmp_path, "runset.json", PEX_RUNSET_PASS_ENVELOPE) curated = _write(tmp_path, "curated.json", PEX_PASS_ENVELOPE) @@ -72,6 +102,34 @@ def test_signoff_does_not_grade_on_the_runset_disclosure(tmp_path): assert runset_result["checks"][0]["passed"] is True +def test_item_7_refuses_a_parasitic_free_runset_leg(tmp_path): + """Issue #6606 AC 4: a runset leg that carries no parasitics cannot + establish item 7 -- its delta rows are device-representation deltas -- + so a passing envelope renders `unmet` with the distinct `no_parasitics` + remedy ("re-run *this* artifact with `--deck`"), never `check_failed`.""" + path = _write(tmp_path, "pex.json", PEX_RUNSET_PASS_ENVELOPE) + + report = build_tier_report(_manifest(evidence={"7": path})) + + item_7 = next(item for item in report["items"] if item["id"] == 7) + assert item_7["status"] == "unmet" + assert item_7["reason"] == "no_parasitics" + # Refused items carry no citation -- the disclosure stays on the check. + assert item_7["citation"] is None + + +def test_item_7_accepts_a_merged_runset_leg(tmp_path): + """The same envelope with `parasitics_carried: true` (a merged leg whose + correspondence attached cards) grades exactly as a curated one does.""" + path = _write(tmp_path, "pex.json", PEX_RUNSET_MERGED_PASS_ENVELOPE) + + report = build_tier_report(_manifest(evidence={"7": path})) + + item_7 = next(item for item in report["items"] if item["id"] == 7) + assert item_7["status"] == "met" + assert item_7["reason"] is None + + def test_signoff_omits_the_disclosure_for_a_curated_pex_envelope(tmp_path): path = _write(tmp_path, "pex.json", PEX_PASS_ENVELOPE) @@ -96,20 +154,31 @@ def _item_7_text_lines(tmp_path, capsys, envelope): def test_text_output_states_the_runset_leg_carries_no_parasitics(tmp_path, capsys): """The human-readable item 7 is the artifact a reviewer actually reads: - the runset disclosure must be there, not only in the JSON citation.""" - lines = _item_7_text_lines(tmp_path, capsys, PEX_RUNSET_PASS_ENVELOPE) + a *merged* leg's disclosure must be there, not only in the JSON + citation.""" + lines = _item_7_text_lines(tmp_path, capsys, PEX_RUNSET_MERGED_PASS_ENVELOPE) line = next(line for line in lines if "pex extraction:" in line) assert "engine=klayout-runset" in line - assert "parasitics_carried=false" in line + assert "parasitics_carried=true" in line assert "params_not_carried=[pnpMPA: A, P]" in line - assert "no parasitics" in line + + +def test_text_output_names_the_no_parasitics_refusal(tmp_path, capsys): + """A parasitic-free leg's item 7 states its own reason, the same way + `not_post_layout` does -- the remedy is re-running this artifact with + `--deck`, not a different kind of artifact.""" + lines = _item_7_text_lines(tmp_path, capsys, PEX_RUNSET_PASS_ENVELOPE) + + assert any("no_parasitics" in line for line in lines) def test_text_output_reports_no_count_for_a_not_assessed_body_bias(tmp_path, capsys): """`not_assessed` carries `null` counts; the text line must not turn that - back into a measured `0` or hand over the floating-body explanation.""" - lines = _item_7_text_lines(tmp_path, capsys, PEX_RUNSET_PASS_ENVELOPE) + back into a measured `0` or hand over the floating-body explanation. + Rides a *merged* citation since the AC 4 gate (a refused item carries no + citation lines at all).""" + lines = _item_7_text_lines(tmp_path, capsys, PEX_RUNSET_MERGED_PASS_ENVELOPE) line = next(line for line in lines if "body bias:" in line) assert line.split("body bias:")[1].strip().startswith("not_assessed") From 88b5913c9677f83d754adfff7ab3efaa4d89b9b7 Mon Sep 17 00:00:00 2001 From: "loom-fleet-dispatch[bot]" <313063438+loom-fleet-dispatch[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:40:18 +0000 Subject: [PATCH 2/6] Preserve curated cluster identity and scope merged PEX cards to the selected circuit --- docs/cli/pex.md | 14 +- docs/cli/signoff.md | 11 +- docs/design/runset-pex-net-correspondence.md | 12 +- src/klayout_tools/pex_merged_leg.py | 329 +++++++++++-------- src/klayout_tools/pex_net_correspondence.py | 99 +++--- src/klayout_tools/signoff.py | 16 +- src/klayout_tools/signoff_details.py | 6 + src/klayout_tools/signoff_pex_disclosure.py | 7 +- tests/test_pex_merged_leg.py | 127 +++++++ tests/test_pex_net_correspondence.py | 104 +++--- tests/test_pex_runset_signoff.py | 17 +- 11 files changed, 486 insertions(+), 256 deletions(-) create mode 100644 tests/test_pex_merged_leg.py diff --git a/docs/cli/pex.md b/docs/cli/pex.md index 7117bf17e..c0069d01a 100644 --- a/docs/cli/pex.md +++ b/docs/cli/pex.md @@ -1147,7 +1147,7 @@ the route existed; `schema_version` stays `2`): |---|---| | `extraction.engine` | `"klayout-runset"`. | | `extraction.parasitics_carried` | `false` for a plain runset leg (no R/C cards). For a merged leg (`--deck`, issue #6606): `true` exactly when the net correspondence attached at least one parasitic card; `klt signoff` refuses a `false` for item 7 (`no_parasitics`). | -| `extraction.net_correspondence` | Present only on a merged leg (issue #6606): `matched` (`[{runset, curated}]`), `unmatched_runset_nets`, `unmatched_curated_nets`, `disagreements` (`{kind: split\|merge, …}` — a connectivity disagreement between the two engines, reported never guessed), `probe_count`, `deck`, `attached_card_count`. A net that cannot be matched is listed, never silently dropped or silently merged. | +| `extraction.net_correspondence` | Merged legs only. Each `matched[]` row gives the runset node, curated label and `cluster_id` (the curated parasitic row’s `net_id`). `unmatched_runset_nets` and `unmatched_curated_nets` list names. `unmatched_curated_clusters[]` identifies each unmatched parasitic island by `{curated, cluster_id}`. Split disagreements include `curated_cluster_ids` in the same order as `curated_nets`. Merge disagreements include the curated `cluster_id`. The block also gives `probe_count`, `deck` and `attached_card_count`. | | `extraction.params_not_carried` | `{class: [PARAM, …]}` — the measured parameters the `X` cards do **not** carry, per device class, copied from `klt extract`'s own `params_not_carried`. `{}` once every parameter is declared with `--device-param`. | | `extraction.device_counts` | `{class: count}` — what the runset recognised, so a reader sees a family is present (or absent) without the extract JSON. Counted over the **instantiated hierarchy**, not the selected circuit alone: a hierarchical runset's top often holds no device itself (its devices sit in called cells), and the selected circuit's own count would read `{}` for a design full of them. Equal to `klt extract`'s `device_counts` for a flat runset, and to its `instantiated_device_counts` always. | | `extraction.device_count` | The total of `extraction.device_counts` — under this engine it replaces the echo of `klt extract`'s selected-circuit `device_count`, so the two never disagree. | @@ -1164,6 +1164,18 @@ series `R` per matched net, a ground `C`, matched coupling, the substrate DC tie) — see [`../design/runset-pex-net-correspondence.md`](../design/runset-pex-net-correspondence.md) for why it is coarser than the curated engine's own star. +Renames and parasitic cards apply only inside the selected subcircuit. +Each same-labelled island retains its own R/C values. Curated coupling rows +identify endpoints by label. The writer records each skipped pair in +`omitted_couplings[]` with its two `curated_nets` and a reason of +`ambiguous_label` or `unmatched_endpoint`. + +When ground capacitors are written, `substrate_return` records their actual +SPICE `node`, the `curated` substrate name, its original `runset` match and +`tie_resistance_ohm`. A null `runset` means the caps return to a separate +substrate node with a DC tie to SPICE ground. Its connection to a runset +device body is unverified. The signoff citation carries this disclosure. + `body_bias.status` is **`"not_assessed"`** (with `null` counts): the runset engine never runs the curated deck's floating-PMOS-body check, so `"biased"` would state a clean result nothing measured. diff --git a/docs/cli/signoff.md b/docs/cli/signoff.md index 353f807a4..06254c327 100644 --- a/docs/cli/signoff.md +++ b/docs/cli/signoff.md @@ -4057,9 +4057,12 @@ A merged leg that attached cards discloses `extraction.parasitics_carried: true` and grades exactly as a curated one; an envelope with no engine statement (every curated-deck run, and every record predating the route) carries parasitics by construction and is never -refused here. Before issue #6606 this disclosure was reported-only; the -check's own `passed` status and the aggregation-mode `pex_extraction` -disclosure are unchanged — the gate is item 7's alone. +refused here. The gate applies only to item 7. The check keeps its own +`passed` status in aggregation mode. A merged citation also quotes the +ground capacitors’ `substrate_return` when present. A null `runset` identifies +a separate DC-tied return whose connection to a runset device body is +unverified. Item 7 grades the simulated leg with that disclosed return. +Item 2 (Layout) keeps its existing treatment of either leg. Only the literal JSON boolean `true` in `environment.sdf.annotated` grants annotation credit. False, null, missing fields, strings (including `"true"` @@ -5675,7 +5678,7 @@ resolved hash renders `unmet`/`unverifiable_provenance`. | `runset_rehash_status` | string | `"unverifiable"` appears on a pinned PDK-runset LVS citation when signoff cannot hash the report's top-level `deck_file` (issue #6452). Look for it in item 4's `citation` or in the LVS entry in item 11's `citation.parts`. Signoff resolves relative deck paths from its own working directory. A missing, non-string, or unreadable path allows an otherwise valid item to remain `met` with this disclosure. | | `content_hash_unresolved` | object | Present when a `yield` report names a samples document and signoff cannot resolve its hash (issues #2197 and #5963). `samples` is the report's reference and `searched` lists the disk paths tried, in order. If a declared store manifest also fails to supply the digest, `artifact_manifest` names its path and `reason` is one of `manifest_unreadable`, `manifest_invalid`, `member_missing`, `duplicate_member`, or `ambiguous_member`. A passing unpinned entry carries the object on its citation. For a pinned unmet item it appears in `detail.content_hash_unresolved`. The field is absent when a digest resolves or the report names no samples document. | | `exit_status` | integer | `0`, *inferred*, for a file-backed entry (a readable, passing envelope implies its producing command exited zero); the subprocess's *actually observed* return code, for a command-backed entry. | -| `body_bias` | object | **`pex` citations only**, and only when the cited envelope carries a `body_bias` block (issue #1983): `{"status", "unbiased_device_count", "unbiased_nets"}`, reduced from it — whether the extracted netlist these post-layout numbers were measured on had a DC bias path for every device body. `status: "not_assessed"` (issue #6559: a `klt pex --engine klayout-runset` leg, which never runs the check) carries `null` for both `unbiased_device_count` and `unbiased_nets` — not `0` / `[]` — and the text rendering prints no count for it; the same citation then also carries `pex_extraction` (`{"engine", "parasitics_carried", "params_not_carried"}`, quoted from the cited envelope's `extraction`; absent for a curated-deck run), rendered as a `pex extraction:` text line beside `body bias:`. **Absent** for any other kind, and for `pex` evidence committed before `klt pex` reported it — an absent `body_bias` means "this artifact made no body-bias statement", never "every device body was biased". See "Device-body bias is reported, not graded" above. | +| `body_bias` | object | **`pex` citations only**, and only when the cited envelope carries a `body_bias` block (issue #1983): `{"status", "unbiased_device_count", "unbiased_nets"}`, reduced from it — whether the extracted netlist these post-layout numbers were measured on had a DC bias path for every device body. `status: "not_assessed"` (issue #6559: a `klt pex --engine klayout-runset` leg, which never runs the check) carries `null` for both `unbiased_device_count` and `unbiased_nets` — not `0` / `[]` — and the text rendering prints no count for it; the same citation then also carries `pex_extraction` (`{"engine", "parasitics_carried", "params_not_carried"}` plus `substrate_return` when present, quoted from the cited envelope's `extraction`; absent for a curated-deck run), rendered as a `pex extraction:` text line beside `body bias:`. **Absent** for any other kind, and for `pex` evidence committed before `klt pex` reported it — an absent `body_bias` means "this artifact made no body-bias statement", never "every device body was biased". See "Device-body bias is reported, not graded" above. | | `parts` | array\ | **Item 11 citations only** (issue #2025): every artifact of the compound cited set, each in this same citation shape (minus `parts`/`power_delivery`), in `erc`/`lvs`/`place-and-route` order. The top-level fields above describe the *leading* (`erc`) part, so a consumer written before item 11 existed still reads a well-formed citation; nothing a reader needs is reachable only through `parts`. For a **grouped** citation (issue #5597) these are the *leading group's* parts, and every group's own parts live in the item-level `citations` array (one compound citation per group, in manifest order) beside `citations_graded` and `members_covered`/`members_total` — see "Item 11 is compound" above. **Absent** for every other item. | | `power_delivery`| object | **Item 11 citations only** (issue #2025): `{"partition_kind", "supply_nets", "pdn", "strap_layers", "tapcell_master", "power_connectivity_status", "ties_checked_by_assertion", "ties_checked_by_well_assertion", "supply_unlabelled_islands"}`, plus `tapless: true` (issue #4199) only when the cited P&R response states a tapless library (`tapcell_master` is then null by design), plus `disclosed_undeclared_tie_classes` when present, plus `power_ports` (issue #2839) only when the provisional port-accessibility half was graded (see "Item 11 port accessibility") — what the grading actually resolved, so a `met` verdict states which supplies were declared and which branch proved them. `pdn` is `false` (with `strap_layers: []`, `tapcell_master: null`) for an analog or full-custom block that cited no `place-and-route` response — "no PDN citation", not "a PDN was checked and found missing", which renders `unmet`/`no_pdn` instead. `ties_checked_by_assertion` (array\, issue #2234) quotes the cited ERC run's own `erc_coverage.checked_by_assertion`: the `erc.missing_tie` work identities whose tap region came from a caller assertion (`ties[].tap_boxes`) rather than PDK-marker narrowing — `[]` for a purely marker-derived run, and for ERC evidence produced before that field existed. It does not change the verdict (an asserted tie is graded `met` exactly as a marker-derived one, and a degenerate or unmatched assertion is rejected by `klt erc` itself); it states which taps rested on the caller's word, without re-opening the cited envelope. `ties_checked_by_well_assertion` (array\, issues #2255 and #2540) quotes that run's `erc_coverage.checked_by_well_assertion` the same way, for the **well** side: the work identities whose well side rested on caller-named coordinates, in either of two forms — the substrate region itself asserted (`ties[].well_layer: null` + `ties[].well_boxes`) because the block draws no well/tub layer at all (the native-substrate case), or a *drawn* well whose class selection was named in boxes (`ties[].well_requires_boxes` / `ties[].well_excludes_boxes`) because no drawn layer separates the tub's two bias classes. `[]` for a run using neither, and for ERC evidence produced before those fields existed. Kept as a separate list because it is a separate, weaker claim: one says which drawn geometry is the tap, the other says how the well side was named. It does not change the verdict either — `klt erc` rejects an assertion indistinguishable from the whole top-cell extent as `degenerate_well_assertion`, and a box selection that kept every shape of the drawn layer or none of them as `degenerate_well_selection`, both landing in `erc_coverage.skipped` where this item already refuses to read them as a clean missing-tie verdict. A purely marker-layer selection (`well_requires`/`well_excludes`) stays out of this list: the stream draws its own partition. `supply_unlabelled_islands` (object, issue #2524) is the **severed-rail negative** this item could not previously state: `{: }` for each cited supply whose ERC spec declared the `stackup` roles it owns (`nets[].roles`, issue #2510), every value `0` for a met item. `erc.unconnected_net` counts islands *carrying the declared label*, so a single-label rail severed into a labelled piece and an unlabelled orphan grades clean — this key is what says the clean read was measured over the whole conductor on the owned roles, not only over what carried a label (its non-zero counterpart is `erc.unlabelled_conductor`, already an `unmet`/`supply_not_continuous` blocker in the table above). `{}` when no cited supply declared `roles`, and for every ERC envelope produced before those keys existed — the honest "not measured", never a fabricated zero, so a grader can tell "checked, and it is zero" from "nobody asked". Like the two assertion lists, it does not change the verdict; it states the negative the verdict rests on. `disclosed_undeclared_tie_classes` (array\, issue #2623) is the **partial-declaration** counterpart of `detail.ties_disclosure_reason` below: `[{"class", "reason"}, …]`, one entry per `erc.missing_tie:[""]` the cited ERC run recorded in `erc_coverage.inapplicable` with a disclosed reason (`ties_disclosure.undeclared_classes`, issue #2541) — a well class the spec names as inexpressible or tool-limited *alongside* at least one other tie it did declare and get checked (the `tie_count > 0` path this item is already `met` on). It does not change the verdict — the declared, checked tie(s) already carry the item to `met` on their own merits, and a disclosure is never a substitute for a computed result — it only states, in the report of record, that a second class was considered and why it could not be checked. **Absent** (not an empty list) whenever the cited run disclosed no named class, so a run predating #2541 or naming none renders this citation exactly as it did before this key existed. These are **per-stream facts** (issue #5597): on a grouped citation every group's `citations` entry carries its own `power_delivery` block, and the values are never merged across groups — each stream proves its own grid. | | `coverage` | object | **`drc` citations only**, and only when the cited envelope carries a `coverage` block (issue #2002): `{"layers_in_stream_without_rules", "rules_skipped", "deck_scope"}`, quoted verbatim from it — the three fields [`design-evidence-tiers.md`](../design-evidence-tiers.md) item 3 requires a DRC claim to disclose. **Absent** for any other kind, and for DRC evidence committed before `klt drc` reported coverage — an absent `coverage` means "this artifact reported no coverage", never "this deck has no gaps". See "DRC coverage is reported, not graded" above. | diff --git a/docs/design/runset-pex-net-correspondence.md b/docs/design/runset-pex-net-correspondence.md index d943eb107..cbdbfe7df 100644 --- a/docs/design/runset-pex-net-correspondence.md +++ b/docs/design/runset-pex-net-correspondence.md @@ -92,11 +92,19 @@ terminals that do not exist in a runset leg; the merged writer collapses to the single-lumped form `parasitics.nets[]` already publishes (`rc_model: "lumped"`). +The selected subcircuit owns these cards. A cluster ID joins each probe match +to the curated R/C row even when disconnected islands share a label. +Coupling rows identify their endpoints by label alone. Ambiguous pairs appear +in `omitted_couplings`. Ground capacitors use the runset substrate match when +one exists. Otherwise they use a separate node with the deck's DC tie, and +`substrate_return.runset` is null. The tie resistance and the actual return +node accompany the item-7 citation so a reader can assess the return path. + ### Measured outcomes | Layout | Result | |---|---| -| inverter fixture (both engines driven for real) | 5/8 runset nets matched (VGND, Y, VPWR, Y, A — all anonymous runset nets adopting labels), 3 body clusters unmatched, 0 disagreements, 9 parasitic cards; the leg's device cards sit on the same nodes as the cards | +| inverter fixture (both engines driven for real) | 5/8 runset nets matched (VGND, Y, VPWR, Y, A — five distinct curated cluster IDs), 3 body clusters unmatched, 0 disagreements, 11 cards (5 R/C pairs and the substrate tie). Both Y islands carry their own pair. The substrate return has no runset match | | inverter fixture, metal joins removed (deliberate split) | every labelled curated net reported as a merge over exactly its 2 fragments; 0 matches; no cards — and no stray ground tie | | inverter fixture, diffusion bridged to gate (deliberate wrong join) | 2 split disagreements naming the curated nets each bridged cluster spans; the one cluster left whole still matches | | `pnpMPA` PDK testcase (the flagship gap) | curated leg extracts **nothing but `vsubs`** — its labels sit on `10/25` (the deck reads `.pin` `10/2`) and its vias are KLayout PCell instances the pip `klayout.db` curated engine cannot resolve — so all four runset nets are reported (PAD/VDD unmatched, `$1`+`VSS` a merge onto `vsubs`), 0 cards, `parasitics_carried: false` | @@ -119,7 +127,7 @@ rows are device-representation deltas. The remedy is re-running *this* artifact with `--deck ` (the same artifact-kind discipline as `not_post_layout`); a merged leg that attached cards discloses `parasitics_carried: true` and grades exactly as a curated one. The -disclosure itself stays beside the verdict, unchanged. +citation identifies an unmatched substrate return when one was used. ## What is deliberately still not carried diff --git a/src/klayout_tools/pex_merged_leg.py b/src/klayout_tools/pex_merged_leg.py index cf018f589..72bae48c8 100644 --- a/src/klayout_tools/pex_merged_leg.py +++ b/src/klayout_tools/pex_merged_leg.py @@ -30,11 +30,14 @@ import os import re import tempfile +from collections import defaultdict from collections.abc import Mapping, Sequence +from pathlib import Path from typing import Any from .extract import run_extract from .pex_net_correspondence import ( + _pex_error, build_probes, correspondence, preferred_renames, @@ -45,179 +48,227 @@ "* no parasitics: this engine extracts devices and connectivity only\n" ) -_CARD_LINE = re.compile(r"^\s*[XRCMLDQ]") +def _format_number(value: float) -> str: + """SPICE number formatting in the curated writer's own style + (``0.055``, ``8.738e-17``).""" + return f"{value:.6g}" -# --------------------------------------------------------------------------- # -# The merged leg writer -# --------------------------------------------------------------------------- # + +def _fresh_node(preferred: str, used: set[str]) -> str: + """Reserve a node in SPICE's case-insensitive namespace.""" + node = preferred + index = 1 + while node.casefold() in used: + node = f"{preferred}_{index}" + index += 1 + used.add(node.casefold()) + return node -def _ground_net(parasitics: Mapping[str, Any]) -> str | None: - """The curated parasitic network's ground/substrate node -- the DC-tie - block names it, and every ground capacitor lands on it.""" - nets = (parasitics.get("substrate_dc_tie") or {}).get("nets") or [] - return str(nets[0]["net"]) if nets else None +def _substrate_return( + substrate: str, + curated_nets: Sequence[Mapping[str, Any]], + parasitics: Mapping[str, Any], + matched: Sequence[Mapping[str, Any]], + merged_name: Mapping[int, str], + used: set[str], +) -> dict[str, Any] | None: + tie = parasitics.get("substrate_dc_tie") or {} + if not any(entry["net"] == substrate for entry in tie.get("nets", [])): + return None + clusters = [entry["net_id"] for entry in curated_nets if entry["name"] == substrate] + matches = {m["cluster_id"]: m["runset"] for m in matched} + cluster = clusters[0] if len(clusters) == 1 else None + runset = matches.get(cluster) + return { + "curated": substrate, + "runset": runset, + "node": merged_name[cluster] + if cluster is not None and runset is not None + else _fresh_node(substrate, used), + "tie_resistance_ohm": tie["resistance_ohm"], + } -def _format_number(value: float) -> str: - """SPICE number formatting in the curated writer's own style - (``0.055``, ``8.738e-17``).""" - return f"{value:.6g}" +def _coupling_cards( + parasitic_nets: Sequence[Mapping[str, Any]], + hubs: Mapping[int, str], + nodes: Mapping[int, str], +) -> tuple[list[str], list[dict[str, Any]]]: + """Coupling rows name labels only. Both ends must resolve uniquely across + the full curated report, including islands outside the matched set.""" + ids: dict[str, list[int]] = defaultdict(list) + pairs: dict[tuple[str, str], float] = {} + for entry in parasitic_nets: + name = entry["net"] + ids[name].append(entry["net_id"]) + for other in entry.get("coupled", []): + a, b = sorted((name, other["net"])) + pairs[a, b] = float(other["capacitance_ff"]) + + cards = [] + omitted = [] + for (a, b), capacitance in sorted(pairs.items()): + if len(ids[a]) != 1 or len(ids[b]) != 1: + reason = "ambiguous_label" + elif ids[a][0] not in hubs or ids[b][0] not in hubs: + reason = "unmatched_endpoint" + else: + i, j = ids[a][0], ids[b][0] + cards.append( + f"C{nodes[i]}_{nodes[j]}_plcc {hubs[i]} {hubs[j]} " + f"{_format_number(capacitance * 1e-15)}" + ) + continue + omitted.append({"curated_nets": [a, b], "reason": reason}) + return cards, omitted def merge_parasitics( netlist_path: str, *, - matched: Sequence[Mapping[str, Any]], + top: str, all_runset_nets: Sequence[str], + curated_nets: Sequence[Mapping[str, Any]], + substrate: str, parasitics: Mapping[str, Any], deck_name: str, - report_block: Mapping[str, Any], + report_block: dict[str, Any], ) -> int: - """Rewrite the runset leg at ``netlist_path`` in place -- rename matched - nodes, append the curated lumped parasitic network for the matched nets, - replace the leg's own "no parasitics" header line -- and return the - number of parasitic cards written (series R, ground C, coupling C, tie). - - Never touches unmatched nets: a node no card references stays exactly as - the runset wrote it; the correspondence block in the envelope, not a - guessed attachment, is where unmatched nets are stated.""" + """Attach the per-cluster lumped network to the selected runset circuit.""" + matched = report_block["matched"] renames = preferred_renames(matched, all_runset_nets) - merged_name = { - entry["curated"]: renames.get(entry["runset"], entry["runset"]) - for entry in matched - } - matched_curated = set(merged_name) - parasitic_nets = { - str(entry["net"]): entry for entry in parasitics.get("nets") or [] + nodes = {m["cluster_id"]: renames.get(m["runset"], m["runset"]) for m in matched} + path = Path(netlist_path) + lines = path.read_text(encoding="utf-8").splitlines(keepends=True) + # A fresh global return must not globalize an existing node in any circuit. + used = { + token.casefold() + for line in lines + if not line.lstrip().startswith("*") + for token in line.split() } - coupled: dict[tuple[str, str], float] = {} - for entry in parasitic_nets.values(): - for other in entry.get("coupled") or []: - net_a, net_b = sorted((str(entry["net"]), str(other["net"]))) - coupled[(net_a, net_b)] = max( - coupled.get((net_a, net_b), 0.0), float(other["capacitance_ff"]) - ) - - ground_net = _ground_net(parasitics) - if ground_net is not None: - ground_net = merged_name.get(ground_net, ground_net) + used.update(net.casefold() for net in (*all_runset_nets, *nodes.values())) + ground = _substrate_return( + substrate, curated_nets, parasitics, matched, nodes, used + ) cards: list[str] = [] - hubs: dict[str, str] = {} - for curated_net in sorted(matched_curated & set(parasitic_nets)): - entry = parasitic_nets[curated_net] - node = merged_name[curated_net] + hubs: dict[int, str] = {} + wrote_ground_cap = False + parasitic_nets = parasitics.get("nets") or [] + for entry in parasitic_nets: + cluster = entry["net_id"] + if cluster not in nodes: + continue + node = nodes[cluster] hub = node - resistance = float(entry.get("resistance_ohm") or 0.0) - capacitance = float(entry.get("capacitance_ff") or 0.0) + resistance = float(entry["resistance_ohm"]) + capacitance = float(entry["capacitance_ff"]) if resistance > 0.0: - hub = f"{node}__kltph" + hub = _fresh_node(f"{node}__kltph", used) cards.append(f"R{node}_plr {node} {hub} {_format_number(resistance)}") - hubs[curated_net] = hub - if capacitance > 0.0 and ground_net is not None: - cards.append( - f"C{node}_plc {hub} {ground_net} {_format_number(capacitance * 1e-15)}" - ) - for (net_a, net_b), capacitance_ff in sorted(coupled.items()): - if net_a in hubs and net_b in hubs: + hubs[cluster] = hub + if capacitance > 0.0 and ground: + wrote_ground_cap = True cards.append( - f"C{merged_name[net_a]}_{merged_name[net_b]}_plcc " - f"{hubs[net_a]} {hubs[net_b]} " - f"{_format_number(capacitance_ff * 1e-15)}" + f"C{node}_plc {hub} {ground['node']} " + f"{_format_number(capacitance * 1e-15)}" ) - tie = parasitics.get("substrate_dc_tie") or {} - if ( - ground_net is not None - and tie.get("nets") - and any(ground_net in card.split(" ")[1:] for card in cards) - ): - # The DC tie rides along only with parasitics that need the ground - # node: a leg nothing matched keeps no stray global + resistor. + coupled, omitted = _coupling_cards(parasitic_nets, hubs, nodes) + cards.extend(coupled) + report_block["omitted_couplings"] = omitted + global_node = None + if ground and wrote_ground_cap: + node = ground["node"] + if ground["runset"] is None: + global_node = node cards.append( - f"R{ground_net}_dctie {ground_net} 0 " - f"{_format_number(float(tie.get('resistance_ohm') or 0.0))}" + f"R{node}_dctie {node} 0 {_format_number(ground['tie_resistance_ohm'])}" + ) + report_block["substrate_return"] = ground + if cards or renames: + _rewrite_netlist( + path, lines, top, renames, cards, global_node, deck_name, report_block ) - - _rewrite_netlist( - netlist_path, - renames, - cards, - ground_net, - deck_name, - len(matched), - report_block, - ) return len(cards) -def _rename_tokens(line: str, renames: Mapping[str, str]) -> str: - """Replace whole whitespace-delimited tokens that name a renamed node, - preserving the original whitespace (comments untouched).""" - parts = re.split(r"(\s+)", line) - return "".join(renames.get(part, part) for part in parts) +def _circuit_bounds(lines: Sequence[str], top: str) -> tuple[int, int]: + start = None + for i, line in enumerate(lines): + words = line.split() + if not words: + continue + if words[0].upper() == ".SUBCKT": + if start is not None: + break + if len(words) > 1 and words[1].casefold() == top.casefold(): + start = i + elif words[0].upper() == ".ENDS" and start is not None: + return start, i + raise _pex_error(f"merged leg: missing complete .SUBCKT block for '{top}'") + + +def _rename_nodes(card: str, renames: Mapping[str, str]) -> str: + """Rewrite node tokens on a KLayout header or device card, across continuations.""" + tokens = [m for m in re.finditer(r"\S+", card) if m[0] != "+"] + if not tokens or tokens[0][0].startswith("*"): + return card + start = 1 + end = next((i for i, token in enumerate(tokens) if "=" in token[0]), len(tokens)) + if tokens[0][0].upper() == ".SUBCKT": + start = 2 # skip the circuit name + elif tokens[0][0][0].upper() == "X": + end -= 1 # the final positional argument is the called circuit + elif tokens[0][0].startswith("."): + return card + chunks: list[str] = [] + offset = 0 + for token in tokens[start:end]: + chunks.extend((card[offset : token.start()], renames.get(token[0], token[0]))) + offset = token.end() + return "".join(chunks) + card[offset:] def _rewrite_netlist( - path: str, + path: Path, + lines: list[str], + top: str, renames: Mapping[str, str], cards: Sequence[str], - ground_net: str | None, + global_node: str | None, deck_name: str, - matched_count: int, - report_block: Mapping[str, Any], + report: Mapping[str, Any], ) -> None: - """Apply the node renames to every card/pin token, emit the ``.GLOBAL`` - the parasitic network needs, insert the parasitic cards before - ``.ENDS``, and replace the "no parasitics" header line -- in place, - preserving line order and pin order.""" - with open(path, encoding="utf-8") as handle: - lines = handle.readlines() - - out: list[str] = [] - rewrote_header = False - pending = list(cards) - for line in lines: - if line == _HEADER_NO_PARASITICS and cards: - rewrote_header = True - unmatched = report_block.get("unmatched_runset_nets") or [] - disagreements = report_block.get("disagreements") or [] - out.append( - f"* parasitics attached from curated deck '{deck_name}' via " - f"geometric net correspondence (issue #6606): {matched_count} " - f"net(s) matched, {len(unmatched)} unmatched runset net(s), " - f"{len(disagreements)} disagreement(s) -- see the report's " - "extraction.net_correspondence\n" - ) - continue - if pending and line.strip().upper().startswith(".ENDS"): - out.extend(f"{card}\n" for card in pending) - pending = [] - out.append( - _rename_tokens(line, renames) - if not line.lstrip().startswith("*") and line.strip() - else line - ) - out.extend(f"{card}\n" for card in pending) - if not rewrote_header and cards: - out.insert( - 0, f"* parasitics attached from curated deck '{deck_name}' (issue #6606)\n" + """Preserve other circuits byte-for-byte and insert cards at this circuit's end.""" + start, end = _circuit_bounds(lines, top) + i = start + while i < end: + following = i + 1 + while following < end and lines[following].lstrip().startswith("+"): + following += 1 + lines[i:following] = _rename_nodes( + "".join(lines[i:following]), renames + ).splitlines(keepends=True) + i = following + lines[end:end] = [f"{card}\n" for card in cards] + if global_node: + lines.insert(start, f".GLOBAL {global_node}\n") + if cards: + header = ( + f"* parasitics attached from curated deck '{deck_name}' via " + f"geometric net correspondence (issue #6606): {len(report['matched'])} " + f"net(s) matched, {len(report['unmatched_runset_nets'])} unmatched " + "runset net(s), " + f"{len(report['disagreements'])} disagreement(s) -- see the report's " + "extraction.net_correspondence\n" ) - if ground_net is not None and not any( - line.strip().upper().startswith(".GLOBAL") and ground_net in line.split() - for line in out - ): - first = next( - ( - i - for i, line in enumerate(out) - if _CARD_LINE.match(line) or line.strip().upper().startswith(".SUBCKT") - ), - len(out), - ) - out.insert(first, f".GLOBAL {ground_net}\n") - with open(path, "w", encoding="utf-8") as handle: - handle.writelines(out) + if _HEADER_NO_PARASITICS in lines: + lines[lines.index(_HEADER_NO_PARASITICS)] = header + else: + lines.insert(0, header) + path.write_text("".join(lines), encoding="utf-8") # --------------------------------------------------------------------------- # @@ -334,7 +385,9 @@ def merged_runset_extract( corr["attached_card_count"] = ( merge_parasitics( report["netlist_path"], - matched=corr["matched"], + top=str(report["top"]), + curated_nets=curated["nets"], + substrate=deck.substrate_net, all_runset_nets=[str(entry["name"]) for entry in report["nets"]], parasitics=curated.get("parasitics") or {}, deck_name=deck_name, diff --git a/src/klayout_tools/pex_net_correspondence.py b/src/klayout_tools/pex_net_correspondence.py index 8f8fef57f..75be33e9c 100644 --- a/src/klayout_tools/pex_net_correspondence.py +++ b/src/klayout_tools/pex_net_correspondence.py @@ -43,6 +43,7 @@ from __future__ import annotations +from collections import defaultdict from collections.abc import Mapping, Sequence from typing import Any @@ -257,6 +258,22 @@ def build_probes( # --------------------------------------------------------------------------- # +def _probe_hits( + probe_results: Sequence[Mapping[str, Any]], +) -> dict[str, set[tuple[str, int]]]: + """Curated cluster identities reached by each runset net's geometry probes.""" + hits: dict[str, set[tuple[str, int]]] = {} + for result in probe_results: + if not result.get("found"): + continue + parts = str(result.get("name") or "").split("|") + if len(parts) != 4 or parts[0] != "kltcorr": + continue + hit = (str(result["net"]), int(result["cluster_id"])) + hits.setdefault(parts[2], set()).add(hit) + return hits + + def correspondence( runset_net_names: Sequence[str], probe_results: Sequence[Mapping[str, Any]], @@ -272,60 +289,56 @@ def correspondence( a curated parasitic net nobody matched is listed even though it never probes anything itself. """ - hits: dict[str, set[tuple[str, int]]] = {} - for result in probe_results: - if not result.get("found"): - continue - parts = str(result.get("name") or "").split("|") - if len(parts) != 4 or parts[0] != "kltcorr": - continue - hit = (str(result["net"]), int(result["cluster_id"])) - hits.setdefault(parts[2], set()).add(hit) - + hits = _probe_hits(probe_results) matched: list[dict[str, Any]] = [] unmatched_runset: list[str] = [] disagreements: list[dict[str, Any]] = [] - reverse: dict[tuple[str, int], list[str]] = {} + reverse: dict[tuple[str, int], list[str]] = defaultdict(list) for runset_net in runset_net_names: - net_hits = sorted(hits.get(runset_net, ())) - if len(net_hits) == 1: - reverse.setdefault(net_hits[0], []).append(runset_net) - else: - unmatched_runset.append(runset_net) - if net_hits: - disagreements.append( - { - "kind": "split", - "runset_net": runset_net, - "curated_nets": [name for name, _ in net_hits], - } - ) - for curated_hit, runset_nets in sorted(reverse.items()): + for hit in hits.get(runset_net, ()): + reverse[hit].append(runset_net) + for (name, cluster), runset_nets in sorted(reverse.items()): if len(runset_nets) > 1: - # A curated net several runset nets reach is a merge - # disagreement: its parasitics attach to neither fragment, so - # every fragment is unmatched too -- never silently merged. - unmatched_runset.extend(runset_nets) disagreements.append( { "kind": "merge", - "curated_net": curated_hit[0], + "curated_net": name, + "cluster_id": cluster, "runset_nets": sorted(runset_nets), } ) - else: - matched.append({"runset": runset_nets[0], "curated": curated_hit[0]}) - matched_curated = {entry["curated"] for entry in matched} + for runset_net in runset_net_names: + net_hits = sorted(hits.get(runset_net, ())) + if len(net_hits) == 1 and len(reverse[net_hits[0]]) == 1: + name, cluster = net_hits[0] + matched.append( + {"runset": runset_net, "curated": name, "cluster_id": cluster} + ) + continue + unmatched_runset.append(runset_net) + if len(net_hits) > 1: + disagreements.append( + { + "kind": "split", + "runset_net": runset_net, + "curated_nets": [name for name, _ in net_hits], + "curated_cluster_ids": [cluster for _, cluster in net_hits], + } + ) + + matched_clusters = {entry["cluster_id"] for entry in matched} + unmatched = sorted( + (entry["net"], entry["net_id"]) + for entry in curated_parasitic_nets + if entry["net_id"] not in matched_clusters + ) return { "matched": sorted(matched, key=lambda entry: entry["runset"]), "unmatched_runset_nets": sorted(unmatched_runset), - "unmatched_curated_nets": sorted( - { - str(entry["net"]) - for entry in curated_parasitic_nets - if str(entry["net"]) not in matched_curated - } - ), + "unmatched_curated_nets": [name for name, _ in unmatched], + "unmatched_curated_clusters": [ + {"curated": name, "cluster_id": cluster} for name, cluster in unmatched + ], "disagreements": sorted( disagreements, key=lambda entry: ( @@ -347,15 +360,15 @@ def preferred_renames( net adopting the same label), in which case the anonymous spelling stands. Mirrors the curated writer's own duplicate-label discipline (its ``_dup`` suffixing) with the runset's own fallback: no rename.""" - kept = {net for net in all_runset_nets if not _is_anonymous(net)} + kept = {net.casefold() for net in all_runset_nets if not _is_anonymous(net)} renames: dict[str, str] = {} adopted: set[str] = set() for entry in sorted(matched, key=lambda item: item["runset"]): runset_net, curated_net = entry["runset"], entry["curated"] if not _is_anonymous(runset_net) or _is_anonymous(curated_net): continue - if curated_net in kept or curated_net in adopted: + if curated_net.casefold() in kept or curated_net.casefold() in adopted: continue renames[runset_net] = curated_net - adopted.add(curated_net) + adopted.add(curated_net.casefold()) return renames diff --git a/src/klayout_tools/signoff.py b/src/klayout_tools/signoff.py index 3fc25b230..e4476c351 100644 --- a/src/klayout_tools/signoff.py +++ b/src/klayout_tools/signoff.py @@ -3211,6 +3211,7 @@ def _kind_is_accepted(check_kind: str, allowed_kinds: set[str] | None) -> bool: def _kind_gated_check( + item_id: int | None, check_kind: str, envelope: dict[str, Any], *, @@ -3219,28 +3220,26 @@ def _kind_gated_check( ) -> tuple[str | None, bool]: """Return ``(refusal, runset_rehash_unverifiable)`` for a passing envelope. - These checks apply only to kinds the item accepts - (:func:`_kind_is_accepted`): + Checks on accepted kinds (:func:`_kind_is_accepted`) run in this order: - - :data:`_REASON_NOTHING_CHECKED` (issue #1996) -- the envelope's own - ``coverage`` block reports ``nothing_checked: true``, so its passing - ``status`` was measured over nothing at all. + - :data:`_REASON_NOTHING_CHECKED` for vacuous coverage (issue #1996). + - Item 7 refuses a pex leg that carried no parasitics. - :func:`check_runset` -- the pinned-runset check for LVS evidence. - - :data:`_REASON_NOT_POST_LAYOUT` -- the run is not the post-layout run - the item requires. + - :data:`_REASON_NOT_POST_LAYOUT` when the item requires a post-layout run. - :data:`_REASON_UNDERSIZED_SAMPLE` / :data:`_REASON_NEGATIVE_CONTROL_NOT_DETECTED` (issue #2467) -- the cited `klt yield` campaign's own ``sample_size.verdict`` says its estimate is not sized, or its own declared negative control did not detect the seeded degradation. See :func:`_yield_campaign_refusal`. + :func:`_check_passed` precedes this gate. Coverage is first and yield is last. """ if not _kind_is_accepted(check_kind, allowed_kinds): return None, False refusal = _coverage_refusal(check_kind, envelope) if refusal is not None: return refusal, False - if check_kind == "pex" and (refusal := _parasitic_free(envelope)): + if item_id == 7 and check_kind == "pex" and (refusal := _parasitic_free(envelope)): return refusal, False rehash_unverifiable = False if check_kind == "lvs": @@ -5312,6 +5311,7 @@ def _grade_evidence( return sta_refusal kind_gated, rehash_unverifiable = _kind_gated_check( + item_id, check_kind, envelope, allowed_kinds=allowed_kinds, diff --git a/src/klayout_tools/signoff_details.py b/src/klayout_tools/signoff_details.py index 7c4be1eb3..8d7f0e624 100644 --- a/src/klayout_tools/signoff_details.py +++ b/src/klayout_tools/signoff_details.py @@ -230,6 +230,12 @@ def _format_pex_extraction(pex_extraction: dict) -> str: for device_class, params in uncarried.items() ) parts.append(f"params_not_carried=[{shown}]") + substrate = pex_extraction.get("substrate_return") + if substrate: + match = substrate.get("runset") + parts.append( + f"substrate return {substrate.get('node')} (runset {match or 'unmatched'})" + ) line = ", ".join(parts) if carried is False: line += ( diff --git a/src/klayout_tools/signoff_pex_disclosure.py b/src/klayout_tools/signoff_pex_disclosure.py index 08076dd9d..bbcece5ed 100644 --- a/src/klayout_tools/signoff_pex_disclosure.py +++ b/src/klayout_tools/signoff_pex_disclosure.py @@ -4,8 +4,8 @@ functions over an envelope dict, importing nothing from the module they were split out of, re-imported there by name so ``signoff.`` keeps resolving. -Both are **reported, never graded on**: item 7's verdict is still -``status == "pass"`` alone. +Item 7 checks whether a passing runset leg carried parasitics. Its body-bias +and substrate-return disclosures travel with the citation. """ from __future__ import annotations @@ -105,8 +105,11 @@ def _pex_engine_disclosure( if not isinstance(extraction, dict) or not extraction.get("engine"): return None uncarried = extraction.get("params_not_carried") + corr = extraction.get("net_correspondence") + substrate = corr.get("substrate_return") if isinstance(corr, dict) else None return { "pex_extraction": { + **({"substrate_return": substrate} if isinstance(substrate, dict) else {}), "engine": extraction.get("engine"), "parasitics_carried": extraction.get("parasitics_carried"), "params_not_carried": ( diff --git a/tests/test_pex_merged_leg.py b/tests/test_pex_merged_leg.py new file mode 100644 index 000000000..b424328fa --- /dev/null +++ b/tests/test_pex_merged_leg.py @@ -0,0 +1,127 @@ +"""SPICE card placement and cluster identity in the merged runset leg.""" + +from klayout_tools.pex_merged_leg import merge_parasitics + + +def test_merge_writer_preserves_pin_order_and_untouched_nets(tmp_path): + child = ".SUBCKT CHILD \\$1 A vsubs\nXsub \\$1 A vsubs nmos\n.ENDS CHILD\n" + other = ".subckt OTHER \\$1\nXo \\$1 G nmos\n.ends\n" + leg = tmp_path / "leg.spice" + leg.write_text( + "* extracted by klt extract --engine klayout-runset --deck-file p.lvs\n" + "* no parasitics: this engine extracts devices and connectivity only\n" + + child + + "* cell TOP\n" + ".SUBCKT TOP \\$1 \\$2 keepme\n" + "X$1 \\$1 \\$2 keepme nmos\n" + "Xsub \\$1\n+ keepme \\$1 p=1\n" + ".ENDS TOP\n" + other + ) + cards = merge_parasitics( + str(leg), + top="TOP", + substrate="vsubs", + curated_nets=[{"name": "A", "net_id": 1}], + all_runset_nets=["\\$1", "\\$2", "keepme"], + parasitics={ + "nets": [ + { + "net": "A", + "net_id": 1, + "resistance_ohm": 0.5, + "capacitance_ff": 2.0, + "coupled": [], + }, + { # unmatched curated net: its card is dropped, not guessed + "net": "B", + "net_id": 2, + "resistance_ohm": 9.0, + "capacitance_ff": 9.0, + "coupled": [], + }, + ], + "substrate_dc_tie": { + "resistance_ohm": 1e12, + "nets": [{"net": "vsubs", "device": "Rvsubs_dctie"}], + }, + }, + deck_name="sg13cmos5l", + report_block={ + "matched": [{"runset": "\\$1", "curated": "A", "cluster_id": 1}], + "unmatched_runset_nets": ["\\$2"], + "disagreements": [], + }, + ) + text = leg.read_text() + assert child in text and other in text + assert text.index(child) < text.index("RA_plr") < text.index(".ENDS TOP") + assert cards == 3 # R + C + the substrate tie; B contributed none + assert ".SUBCKT TOP A \\$2 keepme\n" in text # renamed in place, order kept + assert "X$1 A \\$2 keepme nmos" in text + assert "Xsub A\n+ keepme \\$1 p=1\n" in text + assert "RA_plr A A__kltph 0.5" in text + assert "CA_plc A__kltph vsubs_1 2e-15" in text + assert "Rvsubs_1_dctie vsubs_1 0 1e+12" in text + assert ".GLOBAL vsubs_1\n" in text + assert not any( + line.startswith(("R", "C")) and " 9" in line for line in text.splitlines() + ) + + +def test_writer_uses_cluster_rc_and_only_unambiguous_couplings(tmp_path): + leg = tmp_path / "leg.spice" + leg.write_text(".subckt TOP body left right a b\n.ends\n") + matches = [ + ("right", "Y", 12), + ("left", "Y", 11), + ("body", "vsubs", 13), + ("a", "A", 14), + ("b", "B", 15), + ] + corr = { + "matched": [ + {"runset": node, "curated": label, "cluster_id": i} + for node, label, i in matches + ], + "unmatched_runset_nets": [], + "disagreements": [], + } + nets = [ + { + "net": label, + "net_id": i, + "resistance_ohm": i, + "capacitance_ff": 10 * i, + "coupled": [{"net": "B", "capacitance_ff": 5}] + if label in ("A", "Y") + else [], + } + for _, label, i in reversed(matches) + if label != "vsubs" + ] + count = merge_parasitics( + str(leg), + top="TOP", + all_runset_nets=[m[0] for m in matches], + curated_nets=[{"name": label, "net_id": i} for _, label, i in matches], + substrate="vsubs", + deck_name="fixture", + report_block=corr, + parasitics={ + "nets": nets, + "substrate_dc_tie": {"nets": [{"net": "vsubs"}], "resistance_ohm": 1e12}, + }, + ) + text = leg.read_text() + assert count == 10 # four R/C pairs, one coupling and one substrate tie + assert "Rleft_plr left left__kltph 11\n" in text + assert "Rright_plr right right__kltph 12\n" in text + assert "Cleft_plc left__kltph body 1.1e-13\n" in text + assert "Cright_plc right__kltph body 1.2e-13\n" in text + assert "Ca_b_plcc a__kltph b__kltph 5e-15\n" in text + assert corr["omitted_couplings"] == [ + {"curated_nets": ["B", "Y"], "reason": "ambiguous_label"} + ] + assert corr["substrate_return"]["runset"] == "body" + assert "Rbody_dctie body 0 1e+12" in text + assert ".GLOBAL" not in text diff --git a/tests/test_pex_net_correspondence.py b/tests/test_pex_net_correspondence.py index b3dd30a86..de955448b 100644 --- a/tests/test_pex_net_correspondence.py +++ b/tests/test_pex_net_correspondence.py @@ -24,7 +24,7 @@ import klayout.db as kdb import pytest -from klayout_tools.pex_merged_leg import merge_parasitics, merged_runset_extract +from klayout_tools.pex_merged_leg import merged_runset_extract from klayout_tools.pex_net_correspondence import ( correspondence, preferred_renames, @@ -179,7 +179,15 @@ def test_labelled_and_unlabelled_nets_both_match_and_get_parasitics( # body clusters, which carry no metal -- listed, never silently dropped. assert corr["unmatched_runset_nets"] assert corr["disagreements"] == [] - assert corr["attached_card_count"] == 9 # 4 parasitic nets x (R + C) + tie + y_matches = [m for m in corr["matched"] if m["curated"] == "Y"] + assert len({m["cluster_id"] for m in y_matches}) == 2 + assert corr["attached_card_count"] == 11 # 5 parasitic nets x (R + C) + tie + assert corr["substrate_return"] == { + "curated": "vsubs", + "runset": None, + "node": "vsubs", + "tie_resistance_ohm": 1e12, + } text = open(str(tmp_path / "leg.spice")).read() assert "parasitics attached from curated deck 'sg13cmos5l'" in text @@ -189,6 +197,14 @@ def test_labelled_and_unlabelled_nets_both_match_and_get_parasitics( # cards reference the same nodes -- one netlist, not two views. assert "RVGND_plr VGND VGND__kltph" in text assert "CVGND_plc VGND__kltph vsubs" in text + for node in ("Y", y_matches[1]["runset"]): + assert f"R{node}_plr {node} {node}__kltph" in text + assert f"C{node}_plc {node}__kltph vsubs" in text + assert any( + node in line.split()[1:-1] + for line in text.splitlines() + if line.startswith("X") + ) assert "X$1 " in text # the runset device card survived the rewrite for line in text.splitlines(): if line.startswith("X$1"): @@ -235,7 +251,7 @@ def test_a_split_disagreement_is_reported_not_compared(tmp_path, fake_klayout): ) assert [s["curated_nets"] for s in splits] == [["VGND", "Y"], ["VPWR", "Y"]] # The one cluster the bridge left whole still matches and attaches. - assert corr["matched"] == [{"runset": "\\$3", "curated": "A"}] + assert corr["matched"] == [{"runset": "\\$3", "curated": "A", "cluster_id": 3}] assert corr["attached_card_count"] == 3 # A's R + C + the substrate tie @@ -263,7 +279,7 @@ def test_correspondence_classifies_every_outcome(): _probe("\\$4", "A", 3), # A also hit by \$1: merge with \$1 {"name": "user-probe", "found": True, "net": "X", "cluster_id": 9}, ], - [{"net": "D"}, {"net": "A"}], + [{"net": "D", "net_id": 4}, {"net": "A", "net_id": 3}], ) assert corr["matched"] == [] # A's merge poisons both of its fragments assert corr["unmatched_runset_nets"] == ["\\$1", "\\$2", "\\$3", "\\$4"] @@ -280,9 +296,34 @@ def test_correspondence_classifies_every_outcome(): assert corr["probe_count"] == 5 +def test_unmatched_same_label_and_overlapping_disagreements(): + corr = correspondence( + ["first", "bridged", "fragment"], + [ + _probe("first", "Y", 1), + _probe("bridged", "Y", 2), + _probe("bridged", "B", 3), + _probe("fragment", "Y", 2), + ], + [{"net": "Y", "net_id": i} for i in [1, 2, 4]], + ) + assert corr["matched"] == [{"runset": "first", "curated": "Y", "cluster_id": 1}] + assert corr["unmatched_curated_clusters"] == [ + {"curated": "Y", "cluster_id": 2}, + {"curated": "Y", "cluster_id": 4}, + ] + assert corr["unmatched_runset_nets"] == ["bridged", "fragment"] + assert corr["disagreements"][0] == { + "kind": "merge", + "curated_net": "Y", + "cluster_id": 2, + "runset_nets": ["bridged", "fragment"], + } + + def test_unfound_probes_are_not_matches(): corr = correspondence( - ["\\$1"], [_probe("\\$1", None, None, found=False)], [{"net": "A"}] + ["\\$1"], [_probe("\\$1", None, None, found=False)], [{"net": "A", "net_id": 3}] ) assert corr["matched"] == [] assert corr["unmatched_runset_nets"] == ["\\$1"] @@ -302,57 +343,6 @@ def test_preferred_renames_adopt_labels_and_refuse_collisions(): assert renames == {} -def test_merge_writer_preserves_pin_order_and_untouched_nets(tmp_path): - leg = tmp_path / "leg.spice" - leg.write_text( - "* extracted by klt extract --engine klayout-runset --deck-file p.lvs\n" - "* no parasitics: this engine extracts devices and connectivity only\n" - "* cell TOP\n" - ".SUBCKT TOP \\$1 \\$2 keepme\n" - "X$1 \\$1 \\$2 keepme nmos\n" - ".ENDS TOP\n" - ) - cards = merge_parasitics( - str(leg), - matched=[{"runset": "\\$1", "curated": "A"}], - all_runset_nets=["\\$1", "\\$2", "keepme"], - parasitics={ - "nets": [ - { - "net": "A", - "resistance_ohm": 0.5, - "capacitance_ff": 2.0, - "coupled": [], - }, - { # unmatched curated net: its card is dropped, not guessed - "net": "B", - "resistance_ohm": 9.0, - "capacitance_ff": 9.0, - "coupled": [], - }, - ], - "substrate_dc_tie": { - "resistance_ohm": 1e12, - "nets": [{"net": "vsubs", "device": "Rvsubs_dctie"}], - }, - }, - deck_name="sg13cmos5l", - report_block={"unmatched_runset_nets": ["\\$2"]}, - ) - text = leg.read_text() - assert cards == 3 # R + C + the substrate tie; B contributed none - assert ".SUBCKT TOP A \\$2 keepme\n" in text # renamed in place, order kept - assert "X$1 A \\$2 keepme nmos" in text - assert "keepme" in text.split(".SUBCKT")[1].splitlines()[0] - assert "RA_plr A A__kltph 0.5" in text - assert "CA_plc A__kltph vsubs 2e-15" in text - assert "Rvsubs_dctie vsubs 0 1e+12" in text - assert ".GLOBAL vsubs" in text - assert not any( - line.startswith(("R", "C")) and " 9" in line for line in text.splitlines() - ) - - def test_probe_results_parse_only_kltcorr_names(): corr = correspondence( ["\\$1"], @@ -368,7 +358,7 @@ def test_probe_results_parse_only_kltcorr_names(): ], [], ) - assert corr["matched"] == [{"runset": "\\$1", "curated": "A"}] + assert corr["matched"] == [{"runset": "\\$1", "curated": "A", "cluster_id": 1}] # --------------------------------------------------------------------------- # diff --git a/tests/test_pex_runset_signoff.py b/tests/test_pex_runset_signoff.py index 8ea361eb6..bda54843c 100644 --- a/tests/test_pex_runset_signoff.py +++ b/tests/test_pex_runset_signoff.py @@ -46,6 +46,12 @@ "probe_count": 6, "deck": "sg13cmos5l", "attached_card_count": 7, + "substrate_return": { + "curated": "vsubs", + "node": "vsubs", + "runset": None, + "tie_resistance_ohm": 1e12, + }, }, }, } @@ -85,6 +91,12 @@ def test_signoff_citation_surfaces_the_runset_engine_disclosure(tmp_path): assert item_7["citation"]["pex_extraction"] == { "engine": "klayout-runset", "parasitics_carried": True, + "substrate_return": { + "curated": "vsubs", + "node": "vsubs", + "runset": None, + "tie_resistance_ohm": 1e12, + }, "params_not_carried": {"pnpMPA": ["A", "P"]}, } @@ -109,7 +121,9 @@ def test_item_7_refuses_a_parasitic_free_runset_leg(tmp_path): remedy ("re-run *this* artifact with `--deck`"), never `check_failed`.""" path = _write(tmp_path, "pex.json", PEX_RUNSET_PASS_ENVELOPE) - report = build_tier_report(_manifest(evidence={"7": path})) + report = build_tier_report(_manifest(evidence={"2": path, "7": path})) + item_2 = next(item for item in report["items"] if item["id"] == 2) + assert item_2["status"] == "met" item_7 = next(item for item in report["items"] if item["id"] == 7) assert item_7["status"] == "unmet" @@ -161,6 +175,7 @@ def test_text_output_states_the_runset_leg_carries_no_parasitics(tmp_path, capsy line = next(line for line in lines if "pex extraction:" in line) assert "engine=klayout-runset" in line assert "parasitics_carried=true" in line + assert "substrate return vsubs (runset unmatched)" in line assert "params_not_carried=[pnpMPA: A, P]" in line From 859891ade97b960c4d2c8d638620510a979a39d7 Mon Sep 17 00:00:00 2001 From: "loom-fleet-dispatch[bot]" <313063438+loom-fleet-dispatch[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:27:10 +0000 Subject: [PATCH 3/6] Address review: render merged-leg parasitics, refuse --pdk/--pdk-root, refresh --engine help Fixes the three findings of the re-review of 2c5532381: 1. `klt pex --format text` hard-coded `parasitics: none` for any runset leg. The line now renders the envelope's own `parasitics_carried` (`carried (N cards, M nets matched)`, plus the substrate return) and keeps `none` for a plain runset leg or a merged leg that attached nothing. Extracted into `_print_runset_engine`. 2. `--pdk`/`--pdk-root` were silently dropped on the merged route: `run_extract_leg` did not forward them and `merged_runset_extract`'s hand-built refusal dict had no keys for them. Both are now forwarded and refused by name, as docs/cli/pex.md already promised. 3. `--engine` help (and its tracked snapshot) still said the leg has no parasitics and that `--deck` is refused. Reworded, with the same correction to the `--deck` and `--label-layer` help, which changed meaning under this engine, and to two developer docstrings that repeated the pre-#6606 statement. Tests written first and observed red: merged-route refusal of `--pdk`/`--pdk-root` (with `--deck-option`/`--critical-net` as controls) and the three text-line cases. Co-Authored-By: Claude Sonnet 5.5 --- src/klayout_tools/cli/parser_pex.py | 5 +- src/klayout_tools/cli/parser_pex_extract.py | 26 +++++--- src/klayout_tools/cli/pex_text.py | 44 +++++++++++--- src/klayout_tools/pex.py | 8 +-- src/klayout_tools/pex_merged_leg.py | 4 ++ src/klayout_tools/pex_runset.py | 2 + src/klayout_tools/signoff_pex_disclosure.py | 8 +-- tests/data/cli_help/pex.txt | 6 +- tests/test_pex_net_correspondence.py | 4 ++ tests/test_pex_runset.py | 22 +++++++ tests/test_pex_runset_cli.py | 67 ++++++++++++++++++++- 11 files changed, 166 insertions(+), 30 deletions(-) diff --git a/src/klayout_tools/cli/parser_pex.py b/src/klayout_tools/cli/parser_pex.py index ded2f8d66..e1961abf6 100644 --- a/src/klayout_tools/cli/parser_pex.py +++ b/src/klayout_tools/cli/parser_pex.py @@ -224,7 +224,10 @@ def add_pex_parser( help=( f"extraction deck to run (currently: {_deck_names_str()}), " "passed through to `klt extract --parasitics`. Required unless " - "--attach is given alone (issue #4692)." + "--attach is given alone (issue #4692), or --engine " + "klayout-runset is given: there --deck is optional, and given it " + "attaches that curated deck's parasitic network to the runset " + "leg through geometric net correspondence (issue #6606)." ), ) pex_parser.add_argument( diff --git a/src/klayout_tools/cli/parser_pex_extract.py b/src/klayout_tools/cli/parser_pex_extract.py index fbc814155..f44cc84b5 100644 --- a/src/klayout_tools/cli/parser_pex_extract.py +++ b/src/klayout_tools/cli/parser_pex_extract.py @@ -93,7 +93,9 @@ def add_pex_extraction_args( "(e.g. IHP `Metal1.text` 8/25 under `sg13cmos5l`, which reads " "`Metal1.pin` 8/2) -- otherwise extraction promotes no top-level " "pins and the extracted DUT cannot bind. An unknown ROLE is an " - "error. Omitted by default -- byte-identical to today's " + "error. Under --engine klayout-runset it reads labels for the " + "curated leg of --deck and is refused without --deck (issue " + "#6606). Omitted by default -- byte-identical to today's " "behavior. The applied mapping is echoed in the JSON response's " "`extraction.label_layers`. See docs/cli/pex.md." ), @@ -323,15 +325,21 @@ def _add_runset_engine_args(pex_parser: argparse.ArgumentParser) -> None: "parasitics, unchanged by this flag's existence. 'klayout-runset' " "extracts through the PDK's own KLayout LVS runset (--deck-file; " "`klt extract --engine klayout-runset`) -- the only way to reach " - "a device family the curated deck declares no class for. The leg " - "is a device-level netlist with NO parasitics, so the report does " - "not by itself satisfy docs/design-evidence-tiers.md T1 item 7; " + "a device family the curated deck declares no class for. Without " + "--deck the leg is a device-level netlist with NO parasitics, so " + "the report does not by itself satisfy " + "docs/design-evidence-tiers.md T1 item 7. With --deck (issue " + "#6606) the curated deck's lumped parasitic network is attached " + "to the runset devices through a geometric net correspondence; " + "nets that cannot be matched are listed in " + "`extraction.net_correspondence`, never dropped. " "`extraction.engine`/`parasitics_carried`/`params_not_carried` " - "say so. Every option only the parasitic-annotated engine can " - "honour (--critical-net*, --distributed-rc, --resistance-graph*, " - "--mom-rlc-*, --parasitic-variant, --substrate-tie-ohms, " - "--device-only-leg, --tie-net, --deck, --pdk, ...) is refused by " - "name. See docs/cli/pex.md, 'Runset engine'." + "say which leg this is. Every option only the parasitic-annotated " + "engine can honour (--critical-net*, --distributed-rc, " + "--resistance-graph*, --mom-rlc-*, --parasitic-variant, " + "--substrate-tie-ohms, --device-only-leg, --tie-net, --pdk, " + "--pdk-root, ...) is refused by name, with or without --deck. " + "See docs/cli/pex.md, 'Runset engine'." ), ) pex_parser.add_argument( diff --git a/src/klayout_tools/cli/pex_text.py b/src/klayout_tools/cli/pex_text.py index 644990cef..d1280f8b5 100644 --- a/src/klayout_tools/cli/pex_text.py +++ b/src/klayout_tools/cli/pex_text.py @@ -64,6 +64,40 @@ def _print_mismatch(mismatch: dict | None, name: str) -> None: print(f" {mismatch['detail']}") +def _print_runset_engine(extraction: dict) -> None: + """The additive runset-engine line(s) (issues #6559, #6606): nothing for + the curated engine. + + ``parasitics:`` renders the envelope's own ``parasitics_carried`` rather + than a constant: a plain runset leg carries none, but a merged leg + (``--deck ``, issue #6606) attaches the curated parasitic network + to the runset devices, and its ``extraction.deck`` is that curated deck. + The substrate return is the one fact of that attachment a reader of the + cards cannot see from the leg's own nets, so it is named here as the + ``klt signoff`` citation names it.""" + if not extraction.get("engine"): + return + uncarried = extraction.get("params_not_carried") or {} + correspondence = extraction.get("net_correspondence") or {} + if extraction.get("parasitics_carried"): + parasitics = ( + f"carried ({correspondence.get('attached_card_count', 0)} cards, " + f"{len(correspondence.get('matched') or [])} nets matched)" + ) + else: + parasitics = "none" + print( + f"engine: {extraction['engine']} parasitics: {parasitics} " + f"params_not_carried: {', '.join(sorted(uncarried)) or 'none'}" + ) + substrate = correspondence.get("substrate_return") + if extraction.get("parasitics_carried") and substrate: + print( + f"substrate_return: {substrate.get('node')} " + f"(runset {substrate.get('runset') or 'unmatched'})" + ) + + def _print_schematic_flatten(block: dict | None) -> None: """One ``schematic_flatten:`` line (issue #2889), or nothing when ``--flatten-schematic`` was not given.""" @@ -146,14 +180,8 @@ def _print_text(report: dict) -> None: f"extraction: deck={extraction['deck']} " f"devices={extraction['device_count']} nets={extraction['net_count']}" ) - # Additive (issue #6559): only printed for a runset-engine leg, which has - # no curated deck and no parasitics. - if extraction.get("engine"): - uncarried = extraction.get("params_not_carried") or {} - print( - f"engine: {extraction['engine']} parasitics: none " - f"params_not_carried: {', '.join(sorted(uncarried)) or 'none'}" - ) + # Additive (issues #6559, #6606): only printed for a runset-engine leg. + _print_runset_engine(extraction) # Additive (issue #2686): only printed when --label-layer was given. _print_label_layers(extraction.get("label_layers")) # Additive (issue #976): only printed when --critical-net was given. diff --git a/src/klayout_tools/pex.py b/src/klayout_tools/pex.py index aa5fcbd5c..5ea2a833d 100644 --- a/src/klayout_tools/pex.py +++ b/src/klayout_tools/pex.py @@ -2793,10 +2793,10 @@ def run_pex( ``device_cards_match``. Without it the report is byte-identical. Incompatible with ``measure_command`` (:class:`PexError`). - **``runset`` (issue #6559)** swaps the curated-deck extraction for ``klt - extract --engine klayout-runset`` (``deck_name`` is then ``None``): a - device-level leg with **no parasitics**, reported in ``extraction.engine``/ - ``parasitics_carried``/``params_not_carried`` (see :mod:`.pex_runset`). + **``runset`` (issues #6559/#6606)** swaps the curated-deck extraction for + ``klt extract --engine klayout-runset``: no parasitics when ``deck_name`` is + ``None``, else that curated deck's parasitics attached by net correspondence; + ``extraction.engine``/``parasitics_carried`` say which (see :mod:`.pex_runset`). ``None`` -- the curated route -- leaves the envelope byte-identical. **Output-directory ownership (issue #2770).** The run owns its artifact diff --git a/src/klayout_tools/pex_merged_leg.py b/src/klayout_tools/pex_merged_leg.py index 72bae48c8..d33f7541b 100644 --- a/src/klayout_tools/pex_merged_leg.py +++ b/src/klayout_tools/pex_merged_leg.py @@ -283,6 +283,8 @@ def merged_runset_extract( top: str | None, runset: Any, deck_name: str, + pdk_variant: str | None, + pdk_root: str | None, label_layers: Mapping[str, tuple[int, int] | None] | None, device_models: Mapping[str, str] | None, deck_options: Mapping[str, str] | None, @@ -323,6 +325,8 @@ def merged_runset_extract( { key: value for key, value in { + "pdk_variant": pdk_variant, + "pdk_root": pdk_root, "deck_options": deck_options, "declared_pins": declared_pins, "rename_declared_pins": rename_declared_pins or None, diff --git a/src/klayout_tools/pex_runset.py b/src/klayout_tools/pex_runset.py index 0797e7f83..aa51b76b7 100644 --- a/src/klayout_tools/pex_runset.py +++ b/src/klayout_tools/pex_runset.py @@ -272,6 +272,8 @@ def run_extract_leg( top=top, runset=runset, deck_name=deck_name, + pdk_variant=pdk_variant, + pdk_root=pdk_root, label_layers=label_layers, device_models=device_models, deck_options=deck_options, diff --git a/src/klayout_tools/signoff_pex_disclosure.py b/src/klayout_tools/signoff_pex_disclosure.py index bbcece5ed..0ede74a2c 100644 --- a/src/klayout_tools/signoff_pex_disclosure.py +++ b/src/klayout_tools/signoff_pex_disclosure.py @@ -77,10 +77,10 @@ def _pex_engine_disclosure( quote. ``klt pex --engine klayout-runset`` extracts a device-level netlist with - **no parasitics** (``docs/cli/pex.md``, "Runset engine"), so its - ``delta[]`` rows are device-representation deltas, not parasitic ones: a - passing report does not by itself earn T1 item 7's intent. The envelope - says so in ``extraction.engine``/``parasitics_carried``/ + **no parasitics** unless ``--deck`` attaches some (issue #6606), so its + ``delta[]`` rows are, absent them, device-representation deltas, not + parasitic ones: a passing report does not by itself earn T1 item 7's + intent. The envelope says so in ``extraction.engine``/``parasitics_carried``/ ``params_not_carried``; this quotes them verbatim, never re-deriving them, so a reader of the citation sees the caveat beside the verdict. diff --git a/tests/data/cli_help/pex.txt b/tests/data/cli_help/pex.txt index b2ff33306..7e967f43f 100644 --- a/tests/data/cli_help/pex.txt +++ b/tests/data/cli_help/pex.txt @@ -23,7 +23,7 @@ options: --flatten-schematic flatten the schematic DUT to PDK leaf devices before the schematic-side run (issue #2889): every subcircuit the DUT netlist defines is inlined (instance-path- prefixed device/node names, parameter and m= overrides propagated, .global nets kept), written to /schematic-dut.flat.spice, and each testbench's DUT .include is re-pointed at it -- so a hierarchical schematic compares like with like against the always-flat extraction and model_mismatch stops firing on hierarchy alone. A cycle, an X-call pin- count mismatch or a card the flattener cannot rename safely is an error (error.code schematic_flatten_*), never a partial flatten. Off by default -- byte- identical to today's behavior. Reported as `flatten_schematic` plus the `schematic_flatten` block (path, sha256, inlining summary). The klt pex counterpart of klt lvs's options.flatten_reference. --device-only-leg also measure a parasitic-free third leg (issue #3298): the same layout extracted again without parasitics (same devices and AS/AD/PS/PD, no R/C cards or star nodes), written beside the extracted netlist as .device-only, and every testbench re-run against it. Each delta[] row then also carries device_only_value, representation_delta_pct (device- only vs schematic) and parasitic_delta_pct (extracted vs device-only), splitting device-representation effects from parasitics. With --measure-command the command is run a third time on the parasitic-free netlist ($KLT_PEX_SIDE=device-only). Off by default -- byte-identical to today's behavior. --extract-only extract and report without any measurement leg (issue #3739): no testbench or --measure-command is needed, so no placeholder measurement lands in delta[]. The response carries extraction/body_bias/provenance as usual, testbenches and delta are empty, measurement.mode is "extract-only" and status is not_checked (exit 4). Cannot be combined with testbenches, --measure-command, --measure-timeout-s, --device-only-leg or --flatten-schematic. May be combined with --reference-netlist (issue #5477) to compute model_mismatch -- a device-set comparison over both netlists' text, which needs no measurement leg -- so an extraction missing a whole device family is named rather than silently absent; status and the exit code are unchanged by it. Off by default. - --deck DECK extraction deck to run (currently: asap7, gf180mcu, sg13cmos5l, sg13g2, sky130), passed through to `klt extract --parasitics`. Required unless --attach is given alone (issue #4692). + --deck DECK extraction deck to run (currently: asap7, gf180mcu, sg13cmos5l, sg13g2, sky130), passed through to `klt extract --parasitics`. Required unless --attach is given alone (issue #4692), or --engine klayout-runset is given: there --deck is optional, and given it attaches that curated deck's parasitic network to the runset leg through geometric net correspondence (issue #6606). -o, --output OUTPUT path to write the extracted SPICE netlist (default: with its extension replaced by .spice) --top TOP top cell to extract when the stream has more than one (required in that case; optional otherwise) --pdk PDK PDK variant to resolve (e.g. sky130A); overrides $PDK. Optional -- extraction runs from --deck alone when omitted. @@ -42,7 +42,7 @@ options: --deck-option KEY=VALUE select a caller-visible flavour of a deck's shared- geometry device family (issue #1558), as KEY=VALUE; repeatable, passed through verbatim to `klt extract --deck-option`. Today's recognised keys are gf180mcu's `poly_res` (values `1k` (default), `2k`, `3k`) and `mim_cap` (values `cap_mim_1f0_m4m5_noshield`, `cap_mim_1f5_m4m5_noshield`, `cap_mim_2f0_m4m5_noshield` (default)) and `mim_option` (`B` (default), `A`; MIM option A is the Metal2/Metal3 stack). Without this flag `klt pex` extracts against whatever the deck's own default flavour is, which is not necessarily the one the design uses -- and reports a delta computed from the wrong parasitics. An unrecognised key or value is an error, not a silently-kept default. Omitted by default, which resolves every deck exactly as before this flag existed. The resolved mapping is echoed in the JSON response's `provenance.deck.options`. See docs/cli/extract.md's 'Selecting a shared-geometry resistor flavour' section. --pins PINS comma-separated declared pin set (e.g. 'A,B,VDD,VSS'), passed through to `klt extract --pins` (issue #1558). Every named net not in this set keeps its name but is demoted to an internal node instead of being promoted to a top-level pin -- use it when flat extraction would otherwise promote more pins than the schematic DUT declares (the `pin_count_mismatch` shape below). Off by default -- every named net still promotes to a pin, byte-identical to today's behavior. See docs/cli/extract.md. --rename-declared-pins passed through to `klt extract --rename-declared-pins` (issue #2854): each surviving promoted pin net whose component labels contain exactly one --pins name is renamed to it, so the extracted DUT's .SUBCKT header carries the declared names the schematic DUT declares (required whenever a boundary net carries extra drawn labels and its declared name is only one component of KLayout's joined net name). Requires --pins. Off by default -- byte-identical to today's behavior. The effective value is echoed in the JSON response's `extraction.rename_declared_pins`. - --label-layer ROLE=LAYER/DATATYPE read net/pin name text for one label ROLE from the given GDS layer/datatype instead of the one this --deck's curated default picked (issue #2686), as ROLE=LAYER/DATATYPE; repeatable, passed through to `klt extract --label-layer`. ROLE is `well`, `poly`, or `metal` (0-based); the value `none` reads no label layer for that role. A later entry for the same ROLE wins. Use it when the layout's names sit on a text purpose the deck does not read (e.g. IHP `Metal1.text` 8/25 under `sg13cmos5l`, which reads `Metal1.pin` 8/2) -- otherwise extraction promotes no top-level pins and the extracted DUT cannot bind. An unknown ROLE is an error. Omitted by default -- byte- identical to today's behavior. The applied mapping is echoed in the JSON response's `extraction.label_layers`. See docs/cli/pex.md. + --label-layer ROLE=LAYER/DATATYPE read net/pin name text for one label ROLE from the given GDS layer/datatype instead of the one this --deck's curated default picked (issue #2686), as ROLE=LAYER/DATATYPE; repeatable, passed through to `klt extract --label-layer`. ROLE is `well`, `poly`, or `metal` (0-based); the value `none` reads no label layer for that role. A later entry for the same ROLE wins. Use it when the layout's names sit on a text purpose the deck does not read (e.g. IHP `Metal1.text` 8/25 under `sg13cmos5l`, which reads `Metal1.pin` 8/2) -- otherwise extraction promotes no top-level pins and the extracted DUT cannot bind. An unknown ROLE is an error. Under --engine klayout- runset it reads labels for the curated leg of --deck and is refused without --deck (issue #6606). Omitted by default -- byte-identical to today's behavior. The applied mapping is echoed in the JSON response's `extraction.label_layers`. See docs/cli/pex.md. --tie-net EXTRACTED_NET=SCHEMATIC_NET merge one reported-unbiased well/body net of the extracted netlist into a schematic net (issue #4245), as EXTRACTED_NET=SCHEMATIC_NET, before the extracted leg is simulated; repeatable. EXTRACTED_NET must be one of the report's `body_bias.unbiased_nets` (anonymous names such as `\$5`, valid for one extraction only); any other name is an error that lists the valid ones. Each tie is stated in `body_bias.tied[]` with `source: "declared"`, and a run whose every unbiased net is tied reports `body_bias.status: "tied"` (never `biased`). Omitted by default -- byte-identical to today's behavior. See docs/cli/pex.md. --device-model CLASS=SUBCKT write the bipolar device CLASS as an `X` call to the named PDK subcircuit SUBCKT (issue #4234), repeatable, passed through to `klt extract --device-model`. Needed under --pdk for a deck whose recognised bipolar has no curated PDK binding (gf180mcu's `bjt`), which otherwise stays a bare `Q` card ngspice cannot load. A CLASS the deck does not declare, or that already has a curated binding, is an error. Omitted by default -- byte-identical to today's behavior. The applied mapping is echoed in the JSON response's `extraction.device_models`. See docs/cli/pex.md. --critical-net NET scope the lateral (same-layer, sidewall) coupling- capacitance pass onto this net (issue #976, Epic #709 Phase 2a), passed through to `klt extract --critical- net`; repeatable. Off by default -- byte-identical to today's behavior. See docs/cli/extract.md's '-- critical-net' section. @@ -58,7 +58,7 @@ options: --mom-rlc-resistance-ohm OHM the --mom-rlc-net net's substituted total series resistance, ohms. Requires --mom-rlc-net. --mom-rlc-capacitance-ff FF the --mom-rlc-net net's substituted total ground capacitance, femtofarads. Requires --mom-rlc-net. --mom-rlc-inductance-nh NH add one series inductor between the --mom-rlc-net net's hub and its ground capacitor, nanohenries. Purely additive. Requires --mom-rlc-net. - --engine {klayout,klayout-runset} which extractor produces the extracted leg (issue #6559). 'klayout' (the default) is the curated --deck with lumped-RC parasitics, unchanged by this flag's existence. 'klayout-runset' extracts through the PDK's own KLayout LVS runset (--deck-file; `klt extract --engine klayout-runset`) -- the only way to reach a device family the curated deck declares no class for. The leg is a device-level netlist with NO parasitics, so the report does not by itself satisfy docs/design- evidence-tiers.md T1 item 7; `extraction.engine`/`para sitics_carried`/`params_not_carried` say so. Every option only the parasitic-annotated engine can honour (--critical-net*, --distributed-rc, --resistance- graph*, --mom-rlc-*, --parasitic-variant, --substrate- tie-ohms, --device-only-leg, --tie-net, --deck, --pdk, ...) is refused by name. See docs/cli/pex.md, 'Runset engine'. + --engine {klayout,klayout-runset} which extractor produces the extracted leg (issue #6559). 'klayout' (the default) is the curated --deck with lumped-RC parasitics, unchanged by this flag's existence. 'klayout-runset' extracts through the PDK's own KLayout LVS runset (--deck-file; `klt extract --engine klayout-runset`) -- the only way to reach a device family the curated deck declares no class for. Without --deck the leg is a device-level netlist with NO parasitics, so the report does not by itself satisfy docs/design-evidence-tiers.md T1 item 7. With --deck (issue #6606) the curated deck's lumped parasitic network is attached to the runset devices through a geometric net correspondence; nets that cannot be matched are listed in `extraction.net_correspondence`, never dropped. `extra ction.engine`/`parasitics_carried`/`params_not_carried ` say which leg this is. Every option only the parasitic-annotated engine can honour (--critical- net*, --distributed-rc, --resistance-graph*, --mom- rlc-*, --parasitic-variant, --substrate-tie-ohms, --device-only-leg, --tie-net, --pdk, --pdk-root, ...) is refused by name, with or without --deck. See docs/cli/pex.md, 'Runset engine'. --deck-file PATH path to the PDK's KLayout LVS runset for --engine klayout-runset (issue #6559), spelled as on `klt extract` and `klt lvs`. Required under that engine, a usage error (exit 2) under any other. Recorded as an absolute path in a --submit-only manifest. --deck-var NAME=VALUE extra '-rd NAME=VALUE' global passed to the runset (--engine klayout-runset only; issue #6559). Repeatable. A usage error (exit 2) under any other engine, or for a name the engine sets itself (input, schematic, report, top, topcell). --device-param CLASS:PARAM=NAME[:SUFFIX] with --engine klayout-runset, carry the measured KLayout parameter PARAM of device CLASS onto every `X` call of that class as `NAME=` (issues #5513, #6559); repeatable, e.g. `--device-param sg13_hv_nmos:W=w:u`. Passed through verbatim to `klt extract --device-param`. Without it each device simulates at the PDK subcircuit's own defaults, and `extraction.params_not_carried` names what is missing -- a delta over default-sized devices is not a parasitic delta. A usage error (exit 2) under any other engine. diff --git a/tests/test_pex_net_correspondence.py b/tests/test_pex_net_correspondence.py index de955448b..5717b2702 100644 --- a/tests/test_pex_net_correspondence.py +++ b/tests/test_pex_net_correspondence.py @@ -128,6 +128,8 @@ def _merged(tmp_path, fake_klayout): top="TOP", runset=PexRunset(deck_file=str(deck_file)), deck_name="sg13cmos5l", + pdk_variant=None, + pdk_root=None, label_layers=None, device_models=None, deck_options=None, @@ -398,6 +400,8 @@ def test_real_pnpmpa_merged_run_reports_the_measured_mismatch(tmp_path): top="pnpMPA_lvs", runset=PexRunset(deck_file=deck), deck_name="sg13cmos5l", + pdk_variant=None, + pdk_root=None, label_layers=None, device_models=None, deck_options=None, diff --git a/tests/test_pex_runset.py b/tests/test_pex_runset.py index 90161316b..bcc4576cc 100644 --- a/tests/test_pex_runset.py +++ b/tests/test_pex_runset.py @@ -233,6 +233,28 @@ def test_curated_deck_under_the_runset_engine_is_the_merged_route( assert "parasitics attached" not in text +@pytest.mark.parametrize( + ("kwargs", "flag"), + [ + ({"pdk_variant": "sky130A"}, "--pdk"), + ({"pdk_root": "/nonexistent"}, "--pdk-root"), + ({"deck_options": {"poly_res": "2k"}}, "--deck-option"), + ({"critical_nets": ["n1"]}, "--critical-net"), + ], +) +def test_merged_route_refuses_what_the_docs_say_it_refuses( + tmp_path, fake_klayout, kwargs, flag +): + """Issue #6606: `docs/cli/pex.md` promises the refusals hold "under the + merged route too" -- `--pdk`/`--pdk-root` included. The merged branch + builds its refusal dict by hand, so a key missing there is a flag silently + dropped (the curated leg would run at the default PDK resolution).""" + with pytest.raises(PexError, match=rf"cannot honour .*{flag}\b"): + _extract_only(tmp_path, deck="sky130", **kwargs) + # Refused before either extraction launched. + assert "cmd" not in fake_klayout + + def test_every_refusal_is_named_at_once(tmp_path, fake_klayout): with pytest.raises(PexError) as excinfo: _extract_only(tmp_path, distributed_rc=True, critical_nets=["n1"]) diff --git a/tests/test_pex_runset_cli.py b/tests/test_pex_runset_cli.py index 2c159c159..cff7dbb19 100644 --- a/tests/test_pex_runset_cli.py +++ b/tests/test_pex_runset_cli.py @@ -14,7 +14,7 @@ from klayout_tools.cli import main, pex_cmd from klayout_tools.cli.parser import create_parser -from klayout_tools.pex_runset import runset_from_args +from klayout_tools.pex_runset import extraction_fields, runset_from_args from test_extract_runset import _inputs from test_extract_runset import fake_klayout as fake_klayout @@ -80,6 +80,71 @@ def test_cli_text_output_names_the_engine(tmp_path, fake_klayout, capsys): assert "engine: klayout-runset parasitics: none" in capsys.readouterr().out +def _runset_text_line(capsys, report): + """The `engine:` line(s) `klt pex --format text` prints for ``report``'s + extract report, through the real `extraction_fields` producer.""" + from klayout_tools.cli.pex_text import _print_runset_engine + + _print_runset_engine(extraction_fields(report)) + return capsys.readouterr().out + + +def _runset_report(**extra): + return { + "engine": "klayout-runset", + "device_counts": {"NMOS": 2}, + "params_not_carried": {}, + "extra_circuits": [], + **extra, + } + + +def test_text_output_for_a_plain_runset_leg_still_says_parasitics_none(capsys): + out = _runset_text_line(capsys, _runset_report()) + + assert out == "engine: klayout-runset parasitics: none params_not_carried: none\n" + + +def test_text_output_for_a_merged_leg_states_what_the_envelope_carries(capsys): + """Issue #6606: a merged leg sets `engine` *and* `parasitics_carried: + true`; the default (text) format must not print the plain route's + constant `parasitics: none` beside an envelope saying the opposite.""" + out = _runset_text_line( + capsys, + _runset_report( + net_correspondence={ + "deck": "sg13cmos5l", + "attached_card_count": 11, + "matched": [{"runset": f"n{i}", "curated": "A"} for i in range(5)], + "substrate_return": { + "curated": "vsubs", + "runset": None, + "node": "vsubs", + "tie_resistance_ohm": 1e12, + }, + } + ), + ) + + assert "parasitics: none" not in out + assert "parasitics: carried (11 cards, 5 nets matched)" in out + assert "substrate_return: vsubs (runset unmatched)" in out + + +def test_text_output_for_a_merged_leg_that_attached_nothing_says_none(capsys): + """The correspondence ran but matched nothing (`attached_card_count` 0): + `parasitics_carried` is false, and the line must agree with it.""" + out = _runset_text_line( + capsys, + _runset_report( + net_correspondence={"deck": "sg13cmos5l", "attached_card_count": 0} + ), + ) + + assert "parasitics: none" in out + assert "parasitics: carried" not in out + + def test_cli_device_param_reaches_the_cards_and_the_disclosure( tmp_path, fake_klayout, capsys ): From f395ee8aad3a986d9cf188b6a356d42a7fe46cfa Mon Sep 17 00:00:00 2001 From: Loom Judge Date: Fri, 20 Nov 2026 12:40:19 +0000 Subject: [PATCH 4/6] docs(pex): --deck is optional, not refused, under the runset engine The options list still carried the pre-#6606 rule ("--deck ... under --engine klayout-runset, where it is refused by name") and the unconditional "no parasitics" pointer, both of which this PR makes false and which contradict the file's own "Runset engine" section. Measured at this head: `klt pex --engine klayout-runset --deck sg13cmos5l --deck-file ` is accepted and runs the merged route; only --pdk/--pdk-root are refused by name. Fixed during evaluation (docs only, no behavior change). Co-Authored-By: Claude Opus 5 --- docs/cli/pex.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/cli/pex.md b/docs/cli/pex.md index c0069d01a..d3070a4e1 100644 --- a/docs/cli/pex.md +++ b/docs/cli/pex.md @@ -45,12 +45,12 @@ klt pex ... --engine klayout-runset --deck-file invocation (there are two per run, one per side). Default `1800`, the same cap [`signoff.md`](signoff.md) puts on a command-backed evidence entry. Requires `--measure-command`. -- `--deck` — required (except for a bare `--attach`, and under `--engine klayout-runset`, where it is refused by name), passed through to `klt extract --parasitics`. +- `--deck` — required (except for a bare `--attach`; optional under `--engine klayout-runset`, where giving it selects the merged route of issue #6606), passed through to `klt extract --parasitics`. - `--engine`, `--deck-file`, `--deck-var`, `--device-param`, `--runset-timeout` — select and drive the runset-engine route (issue #6559); same spelling and validation as [`klt extract`](extract.md)'s. See ["Runset engine"](#runset-engine-a-device-family-only-the-pdk-runset-recognises---engine-klayout-runset) - below, including what it does **not** give you: **no parasitics**. + below, including what that route gives you only with `--deck`: **parasitics**. - `--output` / `-o` — path to write the extracted SPICE netlist. Same default as `klt extract`: `` with its extension replaced by `.spice`, next to the input. From 74e4170eaeee960ff7c9104d118c52c3c6d18883 Mon Sep 17 00:00:00 2001 From: "loom-fleet-dispatch[bot]" <313063438+loom-fleet-dispatch[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:56:50 +0000 Subject: [PATCH 5/6] Require complete, layer-identified geometry for merged PEX matches Probe every runset metal polygon, reject boundary probes, and disclose ambiguous layers and incomplete coverage. Preserve the deck's contact landing when checking for split connectivity. Pass explicit zero-valued options through shared validation and record the curated label-layer overrides. --- docs/cli/pex.md | 2 +- docs/design/runset-pex-net-correspondence.md | 70 ++-- src/klayout_tools/pex_merged_leg.py | 49 ++- src/klayout_tools/pex_net_correspondence.py | 344 +++++++++++-------- tests/test_pex_correspondence_geometry.py | 166 +++++++++ tests/test_pex_runset_cli.py | 32 ++ 6 files changed, 474 insertions(+), 189 deletions(-) create mode 100644 tests/test_pex_correspondence_geometry.py diff --git a/docs/cli/pex.md b/docs/cli/pex.md index d3070a4e1..4687394e4 100644 --- a/docs/cli/pex.md +++ b/docs/cli/pex.md @@ -1147,7 +1147,7 @@ the route existed; `schema_version` stays `2`): |---|---| | `extraction.engine` | `"klayout-runset"`. | | `extraction.parasitics_carried` | `false` for a plain runset leg (no R/C cards). For a merged leg (`--deck`, issue #6606): `true` exactly when the net correspondence attached at least one parasitic card; `klt signoff` refuses a `false` for item 7 (`no_parasitics`). | -| `extraction.net_correspondence` | Merged legs only. Each `matched[]` row gives the runset node, curated label and `cluster_id` (the curated parasitic row’s `net_id`). `unmatched_runset_nets` and `unmatched_curated_nets` list names. `unmatched_curated_clusters[]` identifies each unmatched parasitic island by `{curated, cluster_id}`. Split disagreements include `curated_cluster_ids` in the same order as `curated_nets`. Merge disagreements include the curated `cluster_id`. The block also gives `probe_count`, `deck` and `attached_card_count`. | +| `extraction.net_correspondence` | Merged legs only. Each `matched[]` row gives the runset node, curated label and `cluster_id` (the curated parasitic row’s `net_id`). `unmatched_runset_nets` and `unmatched_curated_nets` list names. `unmatched_curated_clusters[]` identifies each unmatched parasitic island by `{curated, cluster_id}`. Split disagreements include `curated_cluster_ids` in the same order as `curated_nets`. Merge disagreements include the curated `cluster_id`. `incomplete_geometry[]` names each affected `runset_net` and the reason (`ambiguous_layer`, `unidentified_layer`, `no_interior_probe` or `unresolved_probe`). Layer-specific entries also give the runset database's `layer_index` and `candidate_roles`. These nets receive no parasitic cards. The block also gives `probe_count`, `deck` and `attached_card_count`. | | `extraction.params_not_carried` | `{class: [PARAM, …]}` — the measured parameters the `X` cards do **not** carry, per device class, copied from `klt extract`'s own `params_not_carried`. `{}` once every parameter is declared with `--device-param`. | | `extraction.device_counts` | `{class: count}` — what the runset recognised, so a reader sees a family is present (or absent) without the extract JSON. Counted over the **instantiated hierarchy**, not the selected circuit alone: a hierarchical runset's top often holds no device itself (its devices sit in called cells), and the selected circuit's own count would read `{}` for a design full of them. Equal to `klt extract`'s `device_counts` for a flat runset, and to its `instantiated_device_counts` always. | | `extraction.device_count` | The total of `extraction.device_counts` — under this engine it replaces the echo of `klt extract`'s selected-circuit `device_count`, so the two never disagree. | diff --git a/docs/design/runset-pex-net-correspondence.md b/docs/design/runset-pex-net-correspondence.md index cbdbfe7df..ea2b26aa9 100644 --- a/docs/design/runset-pex-net-correspondence.md +++ b/docs/design/runset-pex-net-correspondence.md @@ -7,10 +7,10 @@ parasitic nets are put in correspondence, which alternatives were **measured** rather than argued, and what `klt signoff` does with a parasitic-free pex leg (AC 4). -Measurements ran on `ihp-sg13cmos5l` (IHP SG13CMOS5L install at -`~/share/pdk/ihp-sg13cmos5l`, KLayout 0.30.12) against two layouts: the PDK's -own `pnpMPA` LVS testcase and the repo's `tests/test_extract_body_nets_sg13cmos5l.py` -inverter fixture. Every number below is from those runs. +Measurements used KLayout 0.30.12 with the IHP SG13CMOS5L `pnpMPA` LVS +testcase and the inverter fixture in `tests/test_extract_body_nets_sg13cmos5l.py`. +The table identifies runs using the PDK runset and runs using controlled +connectivity changes. Separate pad layouts test split detection and stacked metals. ## The gap @@ -29,8 +29,9 @@ false`. returns real per-net shapes over the database's *internal* layout (`pnpMPA`: net `$1` holds 62 polygons on one internal layer; the inverter fixture: each net 3–4 polygons across cont/metal/sd-like layers). The - internal layers are **anonymous** (no GDS layer info), a fact that forces - the layer-identity rule below. + IHP runset stores anonymous layers. A runset that registers an original + stream layer can preserve its GDS layer and datatype in the same database + format. KLayout's `layer_info(index)` retrieves that provenance after reload. - **M2 — the curated side already has a point→net oracle.** `klt extract --probe` (#2986) resolves a point on a conductor role (`metal0`…, `poly`, `well`) to the *final* net name and `cluster_id`, post-purge and @@ -57,29 +58,41 @@ false`. are strictly interior** (bbox centre when strictly inside, otherwise an inward bisector step from a convex hull vertex); a probe hit then implies genuine area overlap, not edge-touching. -- **R3 — anonymous internal layers cannot be trusted by index.** The - runset database's metal-ish layers are anonymous, and a derived layer - (e.g. `gate = activ ∧ poly`) would happily donate points that overlap the - wrong curated role. **Rule: an internal layer joins one metal role only - when ≥ 99 % of its own area lies inside that role's GDS layer in the - original stream** (measured: original metal handles are single-source, so - real layers identify at 100 %; anything mixed is derived and joins - nothing). +- **R3 — layer index and one-sided area overlap can both misidentify a + metal.** In the inverter fixture, a Metal2 pad on 10/0 placed inside the + VGND Metal1 pad on 8/0 has 100 % area overlap with both masks. With no + via, the curated probe at (0.2, 0.5) µm returns VGND on Metal1 and UPPER + on Metal2. The saved stream layer/datatype identifies both correctly. + Removing provenance from two coincident metal masks leaves both layer + assignments ambiguous. ## The landed rule -For each net of the runset's selected circuit: sample strictly interior -points of its polygons on internal layers identified (R3) with one of the -curated deck's metals, and probe that one role per point (M2). Exactly one -distinct curated net hit → **match**; more than one → **split -disagreement** (the runset net spans several curated nets); a curated net -hit by several runset nets → **merge disagreement** (its parasitics attach -to *neither* fragment); no hit → **unmatched**. Every outcome lands in the -envelope's `extraction.net_correspondence` (`matched`, -`unmatched_runset_nets`, `unmatched_curated_nets`, `disagreements`, -`probe_count`, `deck`, `attached_card_count`); parasitics attach only to -1:1 matches. Sampling is capped (16 points/layer, 64/net, strided), so -split detection is exact within the cap and best-effort beyond it. +Use the runset layer's original GDS layer and datatype when available. For +anonymous layers, compare the selected circuit's per-layer union with the +complete overlapping islands of each original mask. This comparison allows +the circuit to omit whole islands. Containment of at least 99 % of the +runset area identifies *candidate* metal roles. A match requires exactly one +candidate, equal island geometry, and no equally good non-metal source. +This distinguishes a via inside a pad from the metal that surrounds it. +The deck also connects its contact layer directly to the first metal. +For a runset contact with known stream provenance, probe the intersection +of the contact and that metal landing. This exposes a missing contact +connection on the runset side, including a fragment with only a contact. + +Probe one strictly interior grid point on **every** polygon of each identified +metal layer. Both the hull and hole edges are excluded. A 16-pad runset net +whose last pad belongs to a different curated net gives a split even when +the first 15 belong to the same net. The 17- and 65-pad regressions exercise +the same case beyond the former sampling limits. + +Confirmed hits on several curated clusters establish a **split**. Confirmed +hits from several runset nets on one curated cluster establish a **merge**. +A unique pairing with complete probe coverage earns a **match**. A polygon +without a usable interior point, an unresolved probe, or an ambiguous metal +assignment leaves the affected runset net unmatched. Probes of candidate +roles on uncertain layers can rule out exclusive ownership by another net. +Only confirmed geometry contributes to split and merge reports. The merged leg is the runset leg's own netlist rewritten in place: matched nodes renamed (a named runset net keeps its name — device-side truth; an @@ -104,8 +117,9 @@ node accompany the item-7 citation so a reader can assess the return path. | Layout | Result | |---|---| -| inverter fixture (both engines driven for real) | 5/8 runset nets matched (VGND, Y, VPWR, Y, A — five distinct curated cluster IDs), 3 body clusters unmatched, 0 disagreements, 11 cards (5 R/C pairs and the substrate tie). Both Y islands carry their own pair. The substrate return has no runset match | -| inverter fixture, metal joins removed (deliberate split) | every labelled curated net reported as a merge over exactly its 2 fragments; 0 matches; no cards — and no stray ground tie | +| inverter fixture, controlled runset with Metal1 contacts | 5/8 runset nets matched (VGND, Y, VPWR, Y, A — five distinct curated cluster IDs), 3 body clusters unmatched, 0 disagreements, 11 cards (5 R/C pairs and the substrate tie). Both Y islands carry their own pair. The substrate return has no runset match | +| inverter fixture, IHP PDK runset | 3 of 4 runset nets matched (VGND, Y and A), 0 disagreements, 7 cards | +| inverter fixture, runset contact-to-metal joins omitted | every labelled curated net reported as a merge over exactly its 2 fragments; 0 matches; no cards — and no stray ground tie | | inverter fixture, diffusion bridged to gate (deliberate wrong join) | 2 split disagreements naming the curated nets each bridged cluster spans; the one cluster left whole still matches | | `pnpMPA` PDK testcase (the flagship gap) | curated leg extracts **nothing but `vsubs`** — its labels sit on `10/25` (the deck reads `.pin` `10/2`) and its vias are KLayout PCell instances the pip `klayout.db` curated engine cannot resolve — so all four runset nets are reported (PAD/VDD unmatched, `$1`+`VSS` a merge onto `vsubs`), 0 cards, `parasitics_carried: false` | diff --git a/src/klayout_tools/pex_merged_leg.py b/src/klayout_tools/pex_merged_leg.py index d33f7541b..82ee3096b 100644 --- a/src/klayout_tools/pex_merged_leg.py +++ b/src/klayout_tools/pex_merged_leg.py @@ -323,29 +323,25 @@ def merged_runset_extract( extract_runset.refuse_unsupported( { - key: value - for key, value in { - "pdk_variant": pdk_variant, - "pdk_root": pdk_root, - "deck_options": deck_options, - "declared_pins": declared_pins, - "rename_declared_pins": rename_declared_pins or None, - "tie_declared_pins": tie_declared_pins or None, - "critical_nets": critical_nets, - "critical_net_patterns": critical_net_patterns, - "critical_net_all": critical_net_all or None, - "critical_net_excludes": critical_net_excludes, - "distributed_rc": distributed_rc or None, - "resistance_graph": resistance_graph or None, - "resistance_graph_r_cut_ohm": resistance_graph_r_cut_ohm, - "parasitic_variants": parasitic_variants, - "substrate_tie_ohms": substrate_tie_ohms, - "mom_net": mom_rlc_net, - "mom_rlc_resistance_ohm": mom_rlc_resistance_ohm, - "mom_rlc_capacitance_ff": mom_rlc_capacitance_ff, - "mom_rlc_inductance_nh": mom_rlc_inductance_nh, - }.items() - if value + "pdk_variant": pdk_variant, + "pdk_root": pdk_root, + "deck_options": deck_options, + "declared_pins": declared_pins, + "rename_declared_pins": rename_declared_pins, + "tie_declared_pins": tie_declared_pins, + "critical_nets": critical_nets, + "critical_net_patterns": critical_net_patterns, + "critical_net_all": critical_net_all, + "critical_net_excludes": critical_net_excludes, + "distributed_rc": distributed_rc, + "resistance_graph": resistance_graph, + "resistance_graph_r_cut_ohm": resistance_graph_r_cut_ohm, + "parasitic_variants": parasitic_variants, + "substrate_tie_ohms": substrate_tie_ohms, + "mom_net": mom_rlc_net, + "mom_rlc_resistance_ohm": mom_rlc_resistance_ohm, + "mom_rlc_capacitance_ff": mom_rlc_capacitance_ff, + "mom_rlc_inductance_nh": mom_rlc_inductance_nh, } ) @@ -363,11 +359,12 @@ def merged_runset_extract( runset_timeout_s=runset.runset_timeout, lvsdb_out=lvsdb_out, ) - probes, positions = build_probes( + probes, incomplete = build_probes( lvsdb_out, layout_path, top=str(report["top"]), - metals=list(deck.metals), + metals=deck.metals, + contact=deck.contact, dbu_um=float(report["dbu_um"]), ) curated = run_extract( @@ -384,6 +381,7 @@ def merged_runset_extract( [str(entry["name"]) for entry in report["nets"]], curated.get("probes") or [], (curated.get("parasitics") or {}).get("nets") or [], + incomplete, ) corr["deck"] = deck_name corr["attached_card_count"] = ( @@ -400,6 +398,7 @@ def merged_runset_extract( if report.get("netlist_path") else 0 ) + report["label_layers"] = curated["label_layers"] report["net_correspondence"] = corr if curated.get("parasitics"): report["parasitics"] = curated["parasitics"] diff --git a/src/klayout_tools/pex_net_correspondence.py b/src/klayout_tools/pex_net_correspondence.py index 75be33e9c..ab6ac4101 100644 --- a/src/klayout_tools/pex_net_correspondence.py +++ b/src/klayout_tools/pex_net_correspondence.py @@ -12,33 +12,12 @@ -- is ``docs/design/runset-pex-net-correspondence.md``; this docstring records the rule itself. -The join, in one paragraph --------------------------- - -Both extractions cluster the *same original shapes* (the same GDS) into -nets. For each net of the runset's selected circuit, sample strictly -interior points of its per-net polygons on the runset database's *metal* -layers only, and ask the curated extraction which net each point belongs to -(``klt extract --probe``'s own point-to-net machinery, evaluated on the -curated run's live ``LayoutToNetlist``). Exactly one distinct curated net -hit -> a match. More than one -> the runset net spans several curated nets -(a **split** disagreement). A curated net hit by several runset nets -> a -**merge** disagreement. No hit -> unmatched. Every outcome is reported in -the envelope's ``extraction.net_correspondence``; parasitics attach only to -1:1 matches, and a disagreement is reported, never guessed (issue #6606 -AC 2/3). - -Three restrictions the measurements forced (the decision doc carries the -numbers): sample points are **strictly interior** (a boundary point of one -net's polygon can lie exactly on another net's shape -- measured: a -substrate cluster's bbox centre landing on a gate-metal edge probed the -gate net), the join runs on **metal layers only** (device layers overlap by -construction -- the channel zone is inside both the source/drain and the -gate clusters of either engine; a well *contains* the devices' diffusion), -and a runset-internal layer joins one metal role only when **>= 99% of its -area lies inside that role's own GDS layer** (the runset database's layer -indices are anonymous; shape-set identity against the original stream is -what says "this internal layer *is* metal1"). +Every metal polygon of the selected runset circuit contributes a strictly +interior probe to the curated extractor. The layer comes from the source +GDS layer/datatype or, for an anonymous layer, an unambiguous comparison +with complete stream polygons. Confirmed hits on multiple curated clusters +show a split. Hits by multiple runset nets on one cluster show a merge. +Only a unique match with complete coverage receives parasitics. """ from __future__ import annotations @@ -47,15 +26,6 @@ from collections.abc import Mapping, Sequence from typing import Any -MAX_POINTS_PER_LAYER = 16 -MAX_POINTS_PER_NET = 64 - -#: An internal layer joins a metal role when at least this fraction of its -#: own area lies inside the role's GDS layer. Original metal layers are -#: single-source handles, so the real figure is 100%; anything mixed is a -#: derived layer and joins nothing. -_LAYER_IDENTITY_AREA_FRACTION = 0.99 - def _pex_error(message: str) -> Exception: """A ``PexError`` built lazily, so importing this module never imports @@ -96,14 +66,14 @@ def _interior_point(poly: Any) -> Any | None: box = poly.bbox() centre = kdb.Point((box.left + box.right) // 2, (box.bottom + box.top) // 2) - if not any( - ( - centre.x == box.left, - centre.x == box.right, - centre.y == box.bottom, - centre.y == box.top, + + def strictly_inside(point: Any) -> bool: + # Polygon.inside includes edges. each_edge visits the hull and holes. + return poly.inside(point) and not any( + e.contains(point) for e in poly.each_edge() ) - ) and poly.inside(centre): + + if strictly_inside(centre): return centre hull = list(poly.each_point_hull()) for index, vertex in enumerate(hull): @@ -124,25 +94,14 @@ def _interior_point(poly: Any) -> Any | None: step = kdb.Point( vertex.x + sum_x * reach // norm, vertex.y + sum_y * reach // norm ) - if step != vertex and poly.inside(step): + if strictly_inside(step): return step return None -def _flat_region(layout: Any, top_cell: Any, layer: int, datatype: int) -> Any: - """The flattened original-stream shapes of one GDS layer, or an empty - region when the stream does not draw it.""" - import klayout.db as kdb - - index = layout.find_layer(layer, datatype) - if index is None: - return kdb.Region() - return kdb.Region(top_cell.begin_shapes_rec(index)) - - def _union_of_net_regions(lvs: Any, nets: Sequence[Any], layer_index: int) -> Any: """The runset database's whole per-layer region, accumulated over every - net of every circuit it carries.""" + net of the selected circuit, including subcircuit shapes.""" import klayout.db as kdb region: Any = None @@ -153,53 +112,146 @@ def _union_of_net_regions(lvs: Any, nets: Sequence[Any], layer_index: int) -> An return kdb.Region() if region is None else region -def metal_role_map( - lvs: Any, layout: Any, top_cell: Any, metals: Sequence[tuple[int, int]] -) -> dict[int, str]: - """``{internal layer index: metal role}`` for the runset database's own - layers whose shape set is (>= 99% by area) one of the curated deck's - metal GDS layers -- the layer identity that lets a sampled point probe - exactly the role it is real geometry of.""" - nets = [net for c in lvs.netlist().each_circuit() for net in c.each_net()] - gds_regions = { - f"metal{index}": _flat_region(layout, top_cell, layer, datatype) - for index, (layer, datatype) in enumerate(metals) - } - roles: dict[int, str] = {} - for layer_index in lvs.internal_layout().layer_indexes(): - region = _union_of_net_regions(lvs, nets, layer_index) - if region.is_empty(): - continue - area = region.area() - for role in sorted(gds_regions): - inside = (region & gds_regions[role]).area() - if inside >= area * _LAYER_IDENTITY_AREA_FRACTION: - roles[layer_index] = role - break - return roles - - -def _net_probe_points( - lvs: Any, net: Any, roles: Mapping[int, str] -) -> dict[str, list[Any]]: - """``{role: [kdb.Point, ...]}`` -- strictly interior sample points of - ``net``'s polygons, per matched metal role, capped per layer and net.""" - points: dict[str, list[Any]] = {} - total = 0 - for layer_index, role in sorted(roles.items()): - region = lvs.polygons_of_net(net, layer_index, True) - if region is None: +def _anonymous_role( + region: Any, metal_masks: Mapping[str, Any], other_masks: Sequence[Any] +) -> tuple[str | None, list[str]]: + """An anonymous layer can omit islands absent from the selected circuit. + Compare complete overlapping islands, so a via cut inside a pad cannot + identify the pad's metal. Coincident masks leave the source ambiguous.""" + if region.is_empty(): + return None, [] + area = region.area() + candidates = [] + for role, mask in metal_masks.items(): + overlap = region & mask + if not overlap.is_empty() and overlap.area() >= 0.99 * area: + candidates.append(role) + if not candidates: + return None, [] + + def same_islands(mask: Any) -> bool: + return (mask.overlapping(region) ^ region).is_empty() + + exact = [role for role in candidates if same_islands(metal_masks[role])] + other = any(same_islands(mask) for mask in other_masks) + if len(candidates) == 1 and exact and not other: + return exact[0], [] + if other and not exact: + return None, [] # identified contact, via or other non-metal mask + return None, candidates + + +def _stream_masks( + layout: Any, cell: Any, role_by_gds: Mapping[tuple[int, int], str] +) -> tuple[dict[str, Any], list[Any]]: + """Merge each source mask so touching shapes form complete conductor islands.""" + import klayout.db as kdb + + metal_masks = {} + other_masks = [] + for layer in layout.layer_indexes(): + mask = kdb.Region(cell.begin_shapes_rec(layer)).merged() + info = layout.get_info(layer) + role = role_by_gds.get((info.layer, info.datatype)) + if role is not None: + metal_masks[role] = mask + elif not mask.is_empty(): + other_masks.append(mask) + return metal_masks, other_masks + + +def _layer_roles( + lvs: Any, + circuit: Any, + layout: Any, + top_cell: Any, + metals: Sequence[tuple[int, int]], +) -> tuple[dict[int, str], dict[int, list[str]]]: + """Use the stream layer/datatype first, then compare anonymous layers.""" + + role_by_gds = {pair: f"metal{i}" for i, pair in enumerate(metals)} + roles = {} + anonymous = [] + for layer in lvs.layer_indexes(): + info = lvs.layer_info(layer) + if info.layer < 0: + anonymous.append(layer) + elif (info.layer, info.datatype) in role_by_gds: + roles[layer] = role_by_gds[info.layer, info.datatype] + uncertain = {} + if anonymous: + metal_masks, other_masks = _stream_masks(layout, top_cell, role_by_gds) + nets = list(circuit.each_net()) + for layer in anonymous: + region = _union_of_net_regions(lvs, nets, layer) + role, candidates = _anonymous_role(region, metal_masks, other_masks) + if role is not None: + roles[layer] = role + elif candidates: + uncertain[layer] = candidates + return roles, uncertain + + +def _layer_probes( + region: Any, + name: str, + layer: int, + roles: Sequence[str], + *, + certain: bool, + dbu_um: float, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + probes = [] + missing_point = False + prefix = "kltcorr" if certain else "kltmaybe" + for index, polygon in enumerate(region.each()): + point = _interior_point(polygon) + if point is None: + missing_point = True continue - polygons = list(region.each()) - stride = max(1, len(polygons) // MAX_POINTS_PER_LAYER + 1) - for poly in polygons[::stride]: - if total >= MAX_POINTS_PER_NET: - return points - point = _interior_point(poly) - if point is not None: - points.setdefault(role, []).append(point) - total += 1 - return points + for role in roles: + probes.append( + { + "name": f"{prefix}|{role}|{name}|{layer}-{index}", + "layer": role, + "x": point.x * dbu_um, + "y": point.y * dbu_um, + } + ) + details = {"runset_net": name, "layer_index": layer, "candidate_roles": list(roles)} + incomplete = [] + if not certain: + reason = "ambiguous_layer" if len(roles) > 1 else "unidentified_layer" + incomplete.append({**details, "reason": reason}) + if missing_point: + incomplete.append({**details, "reason": "no_interior_probe"}) + return probes, incomplete + + +def _contact_landings( + lvs: Any, + layout: Any, + cell: Any, + contact: tuple[int, int] | None, + metals: Sequence[tuple[int, int]], +) -> dict[int, Any]: + """The curated deck connects its contact layer directly to metal0. + Intersect a proven runset contact with that landing metal to detect a + runset missing the contact-to-metal connection. An unrelated overlying + metal cannot witness this connection.""" + import klayout.db as kdb + + if not metals or contact is None: + return {} + first_metal = layout.find_layer(*metals[0]) + if first_metal is None: + return {} + landings = {} + for index in lvs.layer_indexes(): + info = lvs.layer_info(index) + if (info.layer, info.datatype) == contact: + landings[index] = kdb.Region(cell.begin_shapes_rec(first_metal)) + return landings def build_probes( @@ -209,12 +261,13 @@ def build_probes( top: str, metals: Sequence[tuple[int, int]], dbu_um: float, -) -> tuple[list[dict[str, Any]], dict[str, list[tuple[float, float]]]]: - """The ``run_extract`` ``probes`` list for the correspondence -- one - probe per runset-net sample point, on the metal role its layer matched - -- plus ``{runset net name: [(x_um, y_um), ...]}`` keyed in the - report's escaped ``nets[].name`` spelling, so the join's keys line up - with the curated probe results and the written netlist's node tokens.""" + contact: tuple[int, int] | None = None, +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Probe every identified metal polygon and record gaps in net coverage. + + Probes of candidate roles on an unidentified layer can rule out another + net's exclusive match. They never establish a match or disagreement. + """ import klayout.db as kdb layout = kdb.Layout() @@ -233,24 +286,27 @@ def build_probes( "net correspondence: the runset database carries no circuit named " f"'{top}', so its nets cannot be joined with the curated deck's" ) - roles = metal_role_map(lvs, layout, top_cell, metals) - probes: list[dict[str, Any]] = [] - positions: dict[str, list[tuple[float, float]]] = {} + roles, uncertain = _layer_roles(lvs, circuit, layout, top_cell, metals) + landings = _contact_landings(lvs, layout, top_cell, contact, metals) + roles.update(dict.fromkeys(landings, "metal0")) + layers = sorted(roles.keys() | uncertain.keys()) + probes = [] + incomplete = [] for net in circuit.each_net(): name = _escaped_net_name(net.expanded_name()) - for role, pts in _net_probe_points(lvs, net, roles).items(): - entries = positions.setdefault(name, []) - for index, point in enumerate(pts): - probes.append( - { - "name": f"kltcorr|{role}|{name}|{index}", - "layer": role, - "x": point.x * dbu_um, - "y": point.y * dbu_um, - } - ) - entries.append((point.x * dbu_um, point.y * dbu_um)) - return probes, positions + for layer in layers: + region = lvs.polygons_of_net(net, layer, True) + if region is None or region.is_empty(): + continue + if layer in landings: + region = region & landings[layer] + candidates = [roles[layer]] if layer in roles else uncertain[layer] + points, gaps = _layer_probes( + region, name, layer, candidates, certain=layer in roles, dbu_um=dbu_um + ) + probes.extend(points) + incomplete.extend(gaps) + return probes, incomplete # --------------------------------------------------------------------------- # @@ -260,24 +316,31 @@ def build_probes( def _probe_hits( probe_results: Sequence[Mapping[str, Any]], -) -> dict[str, set[tuple[str, int]]]: - """Curated cluster identities reached by each runset net's geometry probes.""" - hits: dict[str, set[tuple[str, int]]] = {} +) -> tuple[dict[str, set[tuple[str, int]]], set[tuple[str, int]], set[str]]: + """Return confirmed hits, possible cluster hits and nets with a probe miss.""" + hits: dict[str, set[tuple[str, int]]] = defaultdict(set) + possible: set[tuple[str, int]] = set() + missed: set[str] = set() for result in probe_results: - if not result.get("found"): - continue parts = str(result.get("name") or "").split("|") - if len(parts) != 4 or parts[0] != "kltcorr": + if len(parts) != 4 or parts[0] not in {"kltcorr", "kltmaybe"}: continue - hit = (str(result["net"]), int(result["cluster_id"])) - hits.setdefault(parts[2], set()).add(hit) - return hits + if result.get("found"): + hit = (str(result["net"]), int(result["cluster_id"])) + if parts[0] == "kltcorr": + hits[parts[2]].add(hit) + else: + possible.add(hit) + elif parts[0] == "kltcorr": + missed.add(parts[2]) + return hits, possible, missed def correspondence( runset_net_names: Sequence[str], probe_results: Sequence[Mapping[str, Any]], curated_parasitic_nets: Sequence[Mapping[str, Any]], + incomplete_geometry: Sequence[Mapping[str, Any]] = (), ) -> dict[str, Any]: """The ``net_correspondence`` envelope block (issue #6606 AC 2/3). @@ -289,7 +352,12 @@ def correspondence( a curated parasitic net nobody matched is listed even though it never probes anything itself. """ - hits = _probe_hits(probe_results) + hits, possible, missed = _probe_hits(probe_results) + gaps = list(incomplete_geometry) + gaps.extend( + {"runset_net": net, "reason": "unresolved_probe"} for net in sorted(missed) + ) + incomplete = {entry["runset_net"] for entry in gaps} matched: list[dict[str, Any]] = [] unmatched_runset: list[str] = [] disagreements: list[dict[str, Any]] = [] @@ -309,7 +377,12 @@ def correspondence( ) for runset_net in runset_net_names: net_hits = sorted(hits.get(runset_net, ())) - if len(net_hits) == 1 and len(reverse[net_hits[0]]) == 1: + if ( + len(net_hits) == 1 + and len(reverse[net_hits[0]]) == 1 + and net_hits[0] not in possible + and runset_net not in incomplete + ): name, cluster = net_hits[0] matched.append( {"runset": runset_net, "curated": name, "cluster_id": cluster} @@ -346,6 +419,7 @@ def correspondence( str(entry.get("runset_net") or entry.get("curated_net")), ), ), + "incomplete_geometry": gaps, "probe_count": len(probe_results), } diff --git a/tests/test_pex_correspondence_geometry.py b/tests/test_pex_correspondence_geometry.py new file mode 100644 index 000000000..2109ff8a3 --- /dev/null +++ b/tests/test_pex_correspondence_geometry.py @@ -0,0 +1,166 @@ +"""Geometric counterexamples for the runset–curated PEX correspondence.""" + +import klayout.db as kdb +import pytest + +from klayout_tools.extract import run_extract +from klayout_tools.pex_net_correspondence import ( + _interior_point, + build_probes, + correspondence, +) +from test_extract_body_nets_sg13cmos5l import _make_sg13cmos5l_inverter_layout + + +def _join(tmp_path, layout, *, join_first_metal=False, anonymous=False): + """Serialize a runset DB, then probe the independent sg13cmos5l extraction.""" + cell = layout.top_cell() + gds = str(tmp_path / "routing.gds") + db = str(tmp_path / "routing.lvsdb") + layout.write(gds) + lvs = kdb.LayoutVsSchematic(kdb.RecursiveShapeIterator(layout, cell, [])) + metal_layers = (8,) if join_first_metal else (8, 10) + for layer in metal_layers: + region = lvs.make_layer(layout.layer(layer, 0), f"conductor{layer}") + if anonymous: + region = region & region + lvs.register(region, f"derived{layer}") + lvs.connect(region) + if join_first_metal: + lvs.connect_global(region, "JOINED") + lvs.extract_netlist() + lvs.write(db) + nets = [ + net.expanded_name().replace("$", "\\$") + for net in lvs.netlist().circuit_by_name(cell.name).each_net() + ] + probes, coverage = build_probes( + db, gds, top=cell.name, metals=[(8, 0), (10, 0)], dbu_um=layout.dbu + ) + curated = run_extract( + gds, + "sg13cmos5l", + top=cell.name, + parasitics=True, + probes=probes, + no_netlist=True, + ) + return correspondence( + nets, curated["probes"] or [], curated["parasitics"]["nets"], coverage + ) + + +def _draw(layout, layer, shape, datatype=0): + layout.top_cell().shapes(layout.layer(layer, datatype)).insert(shape) + + +@pytest.mark.parametrize("pad_count", [16, 17, 65]) +def test_last_pad_exposes_a_split_at_and_above_old_caps(tmp_path, pad_count): + layout = kdb.Layout() + layout.create_cell("TOP") + for i in range(pad_count): + x = i * 2000 + _draw(layout, 8, kdb.Box(x, 0, x + 500, 500)) + if i < pad_count - 1: + _draw(layout, 19, kdb.Box(x + 100, 100, x + 300, 300)) + _draw(layout, 10, kdb.Box(0, 0, (pad_count - 2) * 2000 + 500, 500)) + _draw(layout, 8, kdb.Text("BUS", kdb.Trans(200, 200)), 2) + _draw(layout, 8, kdb.Text("OTHER", kdb.Trans((pad_count - 1) * 2000 + 200, 200)), 2) + corr = _join(tmp_path, layout, join_first_metal=True) + assert not any(m["runset"] == "JOINED" for m in corr["matched"]) + (split,) = [d for d in corr["disagreements"] if d["kind"] == "split"] + assert split["runset_net"] == "JOINED" + assert split["curated_nets"] == ["BUS", "OTHER"] + assert corr["probe_count"] == pad_count + + +def test_stacked_metals_without_a_via_keep_their_own_roles(tmp_path): + layout = _make_sg13cmos5l_inverter_layout() + _draw(layout, 10, kdb.Box(75, 350, 325, 650)) + _draw(layout, 10, kdb.Text("UPPER", kdb.Trans(200, 500)), 2) + corr = _join(tmp_path, layout) + assert {"VGND", "UPPER"} <= {m["curated"] for m in corr["matched"]} + assert corr["disagreements"] == [] + + # After stripping provenance, the upper pad fits either mask. It cannot + # claim UPPER or establish VGND's exclusivity. Other pads still match. + corr = _join(tmp_path, layout, anonymous=True) + assert {m["curated"] for m in corr["matched"]} == {"A", "VPWR", "Y"} + assert corr["disagreements"] == [] + assert any( + e["candidate_roles"] == ["metal0", "metal1"] + for e in corr["incomplete_geometry"] + ) + + +def test_anonymous_identical_metal_masks_are_disclosed_as_ambiguous(tmp_path): + layout = kdb.Layout() + layout.create_cell("TOP") + for layer, label in [(8, "LOWER"), (10, "UPPER")]: + _draw(layout, layer, kdb.Box(0, 0, 500, 500)) + _draw(layout, layer, kdb.Text(label, kdb.Trans(200, 200)), 2) + corr = _join(tmp_path, layout, anonymous=True) + assert corr["matched"] == [] + assert corr["disagreements"] == [] + ambiguous = [ + e for e in corr["incomplete_geometry"] if e["reason"] == "ambiguous_layer" + ] + assert {e["runset_net"] for e in ambiguous} == set(corr["unmatched_runset_nets"]) + assert all(e["candidate_roles"] == ["metal0", "metal1"] for e in ambiguous) + + +def test_interior_probe_avoids_hull_and_hole_edges(): + elbow = kdb.Polygon( + [ + kdb.Point(x, y) + for x, y in [(0, 0), (0, 100), (50, 100), (50, 50), (100, 50), (100, 0)] + ] + ) + holed = kdb.Polygon(kdb.Box(0, 0, 100, 100)) + holed.insert_hole(kdb.Box(50, 25, 75, 75)) + for polygon in [elbow, holed]: + point = _interior_point(polygon) + assert point is not None and polygon.inside(point) + assert not any(edge.contains(point) for edge in polygon.each_edge()) + assert _interior_point(kdb.Polygon(kdb.Box(0, 0, 1, 10))) is None + + +def test_polygon_without_an_interior_grid_point_withholds_the_partial_match(tmp_path): + layout = kdb.Layout() + layout.create_cell("TOP") + _draw(layout, 8, kdb.Box(0, 0, 500, 500)) + _draw(layout, 8, kdb.Text("BUS", kdb.Trans(200, 200)), 2) + _draw(layout, 8, kdb.Box(2000, 0, 2001, 500)) + corr = _join(tmp_path, layout, join_first_metal=True) + assert corr["probe_count"] == 1 + assert corr["matched"] == [] + assert corr["unmatched_runset_nets"] == ["JOINED"] + (gap,) = corr["incomplete_geometry"] + assert (gap["runset_net"], gap["reason"]) == ("JOINED", "no_interior_probe") + + +def test_probe_misses_and_uncertain_layer_hits_prevent_exclusive_matches(): + def hit(prefix, net, cluster): + return { + "name": f"{prefix}|metal0|{net}|1-0", + "found": cluster is not None, + "net": "BUS", + "cluster_id": cluster, + } + + corr = correspondence( + ["partial", "confirmed", "ambiguous"], + [ + hit("kltcorr", "partial", 1), + hit("kltcorr", "partial", None), + hit("kltcorr", "confirmed", 2), + hit("kltmaybe", "ambiguous", 2), + ], + [], + [{"runset_net": "ambiguous", "reason": "ambiguous_layer"}], + ) + assert corr["matched"] == [] + assert corr["disagreements"] == [] + assert {"runset_net": "partial", "reason": "unresolved_probe"} in corr[ + "incomplete_geometry" + ] diff --git a/tests/test_pex_runset_cli.py b/tests/test_pex_runset_cli.py index cff7dbb19..6d54fb63e 100644 --- a/tests/test_pex_runset_cli.py +++ b/tests/test_pex_runset_cli.py @@ -260,6 +260,8 @@ def test_cli_curated_deck_under_the_runset_engine_runs_the_merged_route( "DECKFILE", "--deck", "sky130", + "--label-layer", + "metal0=none", "--extract-only", capsys=capsys, ) @@ -268,6 +270,36 @@ def test_cli_curated_deck_under_the_runset_engine_runs_the_merged_route( extraction = json.loads(out)["extraction"] assert extraction["deck"] == "sky130" assert extraction["net_correspondence"]["deck"] == "sky130" + assert extraction["label_layers"] == {"metal0": None} + + +@pytest.mark.parametrize( + "flag", + [ + "--resistance-graph-r-cut", + "--substrate-tie-ohms", + "--mom-rlc-resistance-ohm", + "--mom-rlc-capacitance-ff", + "--mom-rlc-inductance-nh", + ], +) +def test_merged_route_refuses_explicit_zero(tmp_path, fake_klayout, capsys, flag): + code, _, err = _cli( + tmp_path, + "--engine", + "klayout-runset", + "--deck-file", + "DECKFILE", + "--deck", + "sky130", + flag, + "0", + "--extract-only", + capsys=capsys, + ) + assert code == 1 + assert flag in err["error"]["message"] + assert "cmd" not in fake_klayout def test_cli_parasitic_only_flag_is_refused_by_name_under_the_runset_engine( From ed9d2c52885414f524eae5e963527eea4ae0026d Mon Sep 17 00:00:00 2001 From: "loom-fleet-dispatch[bot]" <313063438+loom-fleet-dispatch[bot]@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:01:18 +0000 Subject: [PATCH 6/6] Verify runset geometry and cluster identity before publishing merged PEX --- docs/cli/pex.md | 20 ++- docs/design/runset-pex-net-correspondence.md | 29 +-- src/klayout_tools/extract_netlist_target.py | 6 +- src/klayout_tools/extract_runset.py | 3 + src/klayout_tools/extract_runset_spice.py | 48 +++++ src/klayout_tools/pex_merged_leg.py | 94 +++++----- src/klayout_tools/pex_net_correspondence.py | 176 ++++++++++++------- tests/test_pex_correspondence_geometry.py | 109 ++++++++++-- tests/test_pex_net_correspondence.py | 93 ++++++++-- tests/test_pex_runset_cli.py | 45 +++++ 10 files changed, 467 insertions(+), 156 deletions(-) diff --git a/docs/cli/pex.md b/docs/cli/pex.md index 4687394e4..0a927f839 100644 --- a/docs/cli/pex.md +++ b/docs/cli/pex.md @@ -1147,7 +1147,7 @@ the route existed; `schema_version` stays `2`): |---|---| | `extraction.engine` | `"klayout-runset"`. | | `extraction.parasitics_carried` | `false` for a plain runset leg (no R/C cards). For a merged leg (`--deck`, issue #6606): `true` exactly when the net correspondence attached at least one parasitic card; `klt signoff` refuses a `false` for item 7 (`no_parasitics`). | -| `extraction.net_correspondence` | Merged legs only. Each `matched[]` row gives the runset node, curated label and `cluster_id` (the curated parasitic row’s `net_id`). `unmatched_runset_nets` and `unmatched_curated_nets` list names. `unmatched_curated_clusters[]` identifies each unmatched parasitic island by `{curated, cluster_id}`. Split disagreements include `curated_cluster_ids` in the same order as `curated_nets`. Merge disagreements include the curated `cluster_id`. `incomplete_geometry[]` names each affected `runset_net` and the reason (`ambiguous_layer`, `unidentified_layer`, `no_interior_probe` or `unresolved_probe`). Layer-specific entries also give the runset database's `layer_index` and `candidate_roles`. These nets receive no parasitic cards. The block also gives `probe_count`, `deck` and `attached_card_count`. | +| `extraction.net_correspondence` | Merged legs only. Each `matched[]` row gives the runset node and `runset_cluster_id`, plus the curated label and `cluster_id` (the curated parasitic row’s `net_id`). `unmatched_runset_nets` and `unmatched_curated_nets` list names. `unmatched_curated_clusters[]` identifies each unmatched parasitic island by `{curated, cluster_id}`. Split disagreements include `curated_cluster_ids` in the same order as `curated_nets`. Merge disagreements include the curated `cluster_id`. `incomplete_geometry[]` names each affected `runset_net` and the reason (`ambiguous_layer`, `unidentified_layer`, `no_interior_probe`, `unresolved_probe` or `coordinate_mismatch`). Layer-specific entries also give the runset database's `layer_index` and `candidate_roles`. These nets receive no parasitic cards. The block also gives `probe_count`, `deck` and `attached_card_count`. | | `extraction.params_not_carried` | `{class: [PARAM, …]}` — the measured parameters the `X` cards do **not** carry, per device class, copied from `klt extract`'s own `params_not_carried`. `{}` once every parameter is declared with `--device-param`. | | `extraction.device_counts` | `{class: count}` — what the runset recognised, so a reader sees a family is present (or absent) without the extract JSON. Counted over the **instantiated hierarchy**, not the selected circuit alone: a hierarchical runset's top often holds no device itself (its devices sit in called cells), and the selected circuit's own count would read `{}` for a design full of them. Equal to `klt extract`'s `device_counts` for a flat runset, and to its `instantiated_device_counts` always. | | `extraction.device_count` | The total of `extraction.device_counts` — under this engine it replaces the echo of `klt extract`'s selected-circuit `device_count`, so the two never disagree. | @@ -1155,8 +1155,9 @@ the route existed; `schema_version` stays `2`): `extraction.deck` is `null` and `extraction.model` is `null` on a plain runset leg (no curated deck ran); on a merged leg `extraction.deck` is the -curated deck's name, `extraction.model`/`parasitic_integrity` describe the -curated parasitics actually attached, and `provenance.runset` carries the +curated deck's name and `extraction.model` identifies the curated model. +`extraction.parasitic_integrity` is `null` because the merged network has no +integrity assessment. `provenance.runset` carries the runset's `deck_file`, `content_hash` and `klayout_application_version` either way. The merged leg's own netlist header names the deck and the match counts, and its written cards are the curated lumped model (one @@ -1164,7 +1165,15 @@ series `R` per matched net, a ground `C`, matched coupling, the substrate DC tie) — see [`../design/runset-pex-net-correspondence.md`](../design/runset-pex-net-correspondence.md) for why it is coarser than the curated engine's own star. +The merged extraction publishes the SPICE file after both extractions and the +merge succeed. A coordinate mismatch with the source geometry withholds all +matches. A metal fragment without an interior grid point also withholds all +matches because the fragment could share a curated cluster with another net. + Renames and parasitic cards apply only inside the selected subcircuit. +When a runset label needs a different SPICE spelling or collides with another +node, `runset_node_renames[]` records its `original` label, `runset_cluster_id` +and resulting `node`. Geometry matching uses the cluster ID for every spelling. Each same-labelled island retains its own R/C values. Curated coupling rows identify endpoints by label. The writer records each skipped pair in `omitted_couplings[]` with its two `curated_nets` and a reason of @@ -1395,7 +1404,8 @@ the network it emits; this command carries those diagnostics through as self-describing about the health of the network its numbers were measured on. -The block is `null` only for an extraction report predating issue #2764. +The block is `null` for a runset leg (including a merged leg) and for an +extraction report predating issue #2764. Otherwise it is `klt extract`'s own integrity summary verbatim (check settings and aggregate counts — see [`extract.md`](extract.md)'s "Parasitic network integrity" for the field list and the model limits), plus a `nets` @@ -1962,7 +1972,7 @@ full `repo`/`external`/`absent` scope meanings. | `layout` | object | `{path, scope}` — `` normalised via `env_provenance.repo_relative_path` (issue #1261): `scope: "repo"` with a repo-relative `path` when `` sits inside the invocation's repo, else `{"path": null, "scope": "external"}`. The absolute path is never echoed. | | `netlist` | object | `{path, scope}` — the extracted (parasitic-annotated) netlist `klt extract` wrote, normalised the same way as `layout`. | | `reference_netlist` | object | `{path, scope}` — the schematic DUT file every testbench `.include`d (see "The DUT `.include` swap" above), normalised the same way as `layout`. `{path: null, scope: "absent"}` for a bare `--extract-only` (issue #3739), which has no schematic side — or the caller's own `--reference-netlist` when `--extract-only` is given one (issue #5477), which still measures nothing and is used only to compute `model_mismatch`. | -| `extraction` | object | `deck`, `netlist_adaptation` (issue #5128 — the simulator adaptation applied to the extracted and `--device-only-leg` legs' DUT netlist: `"asap7_bsimcmg.adapt_extracted_netlist"` for `--deck asap7`, `null` otherwise; see the asap7 section above), `device_count`, `net_count`, `netlist_sha256` (echoed from `klt extract`'s own report), `model` (`extract.py`'s `PARASITIC_MODEL_SCOPE`, verbatim — what the extracted side's R/C model does and does not account for), `critical_nets` (issue #976 — the `--critical-net` request echoed back, `[]` when the flag was never given), `distributed_rc` (issue #977 — `true` only when `--distributed-rc` was given, `false` otherwise), `parasitic_variant` (issue #3056 — the `--parasitic-variant` request echoed back; present only when the flag was given), `mom_rlc_override` (issue #988 — `null` unless `--mom-rlc-net` was given, in which case `klt extract`'s own substitution report; see [`extract.md`](extract.md)'s "Substitute a caller-supplied `klt mom` R/L/C for a critical net" section for the field list), `label_layers` (issue #2686 — `null` unless `--label-layer` was given, in which case `klt extract`'s own `label_layers` echo: `{"": [layer, datatype] | null}`, sorted by role, `null` for a role cleared with `none`), `device_models` (issue #4234 — `null` unless `--device-model` was given, in which case the applied `{"": ""}` mapping), `device_classes` and `unsupported_devices` (issue #5477 — `klt extract`'s own device-coverage disclosure, forwarded verbatim in every mode: the device classes the resolved deck can recognise at all (issue #221), and the deck-declared `UnsupportedDeviceMarker` geometry the layout draws on (issue #2919, `[]` when there is none). Neither can see a family the deck declares no class for **and** whose recognition region the PDK derives rather than drawing a marker for — for that, see `model_mismatch` and `--extract-only --reference-netlist` above), `resistance_graph` (issue #4037 — present only with `--resistance-graph`: `{r_cut_ohm, nets[]}` where each `nets[]` entry is `{net, net_id, resistance_source, selected_resistance_ohm, legacy_resistance_ohm, fallback_reason}`; `resistance_source` says which value the extracted netlist's lumped R used, and `fallback_reason` (issue #5747, additive) says why it was not the graph value: `null` when `resistance_source` is `graph`, otherwise the first diagnostic `code` of an `unsupported` graph (e.g. `via_resistance_unknown`, `graph_too_large`, `unsupported_geometry`) or else `klt extract`'s `resistance_source_reason` (`terminal_count_not_two`, `graph_status_skipped`, `pair_resistance_unavailable`) — never `null` for a `legacy` net), and `parasitic_integrity` (issue #2764 — the extraction's own per-net parasitic RC network integrity diagnostics; see below). Pins the extraction method alongside `provenance.deck`'s content-hash version pin. **Runset engine only** (issue #6559, additive): `engine`, `parasitics_carried` (`false`), `params_not_carried`, `device_counts` and `extra_circuits` — see "Runset engine" above; `deck` and `model` are `null` there, and `device_count`/`device_counts` there count the instantiated hierarchy rather than the selected circuit alone. | +| `extraction` | object | `deck`, `netlist_adaptation` (issue #5128 — the simulator adaptation applied to the extracted and `--device-only-leg` legs' DUT netlist: `"asap7_bsimcmg.adapt_extracted_netlist"` for `--deck asap7`, `null` otherwise; see the asap7 section above), `device_count`, `net_count`, `netlist_sha256` (echoed from `klt extract`'s own report), `model` (`extract.py`'s `PARASITIC_MODEL_SCOPE`, verbatim — what the extracted side's R/C model does and does not account for), `critical_nets` (issue #976 — the `--critical-net` request echoed back, `[]` when the flag was never given), `distributed_rc` (issue #977 — `true` only when `--distributed-rc` was given, `false` otherwise), `parasitic_variant` (issue #3056 — the `--parasitic-variant` request echoed back; present only when the flag was given), `mom_rlc_override` (issue #988 — `null` unless `--mom-rlc-net` was given, in which case `klt extract`'s own substitution report; see [`extract.md`](extract.md)'s "Substitute a caller-supplied `klt mom` R/L/C for a critical net" section for the field list), `label_layers` (issue #2686 — `null` unless `--label-layer` was given, in which case `klt extract`'s own `label_layers` echo: `{"": [layer, datatype] | null}`, sorted by role, `null` for a role cleared with `none`), `device_models` (issue #4234 — `null` unless `--device-model` was given, in which case the applied `{"": ""}` mapping), `device_classes` and `unsupported_devices` (issue #5477 — `klt extract`'s own device-coverage disclosure, forwarded verbatim in every mode: the device classes the resolved deck can recognise at all (issue #221), and the deck-declared `UnsupportedDeviceMarker` geometry the layout draws on (issue #2919, `[]` when there is none). Neither can see a family the deck declares no class for **and** whose recognition region the PDK derives rather than drawing a marker for — for that, see `model_mismatch` and `--extract-only --reference-netlist` above), `resistance_graph` (issue #4037 — present only with `--resistance-graph`: `{r_cut_ohm, nets[]}` where each `nets[]` entry is `{net, net_id, resistance_source, selected_resistance_ohm, legacy_resistance_ohm, fallback_reason}`; `resistance_source` says which value the extracted netlist's lumped R used, and `fallback_reason` (issue #5747, additive) says why it was not the graph value: `null` when `resistance_source` is `graph`, otherwise the first diagnostic `code` of an `unsupported` graph (e.g. `via_resistance_unknown`, `graph_too_large`, `unsupported_geometry`) or else `klt extract`'s `resistance_source_reason` (`terminal_count_not_two`, `graph_status_skipped`, `pair_resistance_unavailable`) — never `null` for a `legacy` net), and `parasitic_integrity` (issue #2764 — the extraction's own per-net parasitic RC network integrity diagnostics; see below). Pins the extraction method alongside `provenance.deck`'s content-hash version pin. **Runset engine only** (issue #6559, additive): `engine`, `parasitics_carried` (whether cards were attached), `params_not_carried`, `device_counts` and `extra_circuits` — see "Runset engine" above; `deck` and `model` are `null` on a plain runset leg, and `device_count`/`device_counts` there count the instantiated hierarchy rather than the selected circuit alone. | | `body_bias` | object | Issue #1983 (additive field). Whether the extracted netlist this run re-simulated actually had a **DC bias path for every device body**: `status` (`"biased"`/`"unbiased"`, or `"tied"` when every unbiased net was declared tied with `--tie-net`, or — issue #6559 — `"not_assessed"` for a `--engine klayout-runset` leg, which never runs the floating-body check and reports `null` counts), `unbiased_device_count`, `unbiased_nets` (the distinct synthesized net names, sorted), and `unbiased_pmos_body_nets` (`klt extract`'s own `{"device", "net"}` entries, verbatim), and — only with `--tie-net` (issue #4245) — `tied[]` (`{extracted_net, schematic_net, source: "declared"}`). See "Unbiased device bodies invalidate the comparison" above. Reduced from the extraction this command drove itself; it never changes `status`. | | `measurement` | object | Issue #2478 (additive field, always present). How this run's two legs were measured, so a reader of a committed record never has to infer it from the presence/absence of `testbenches[]`. `mode` is `"testbench"` (the default path — `command`/`timeout_s`/`sides` are then all `null`) `"command"` (a caller-supplied `--measure-command` produced both legs) or `"extract-only"` (issue #3739: `--extract-only` measured nothing — `testbenches` and `delta` are empty, `status` is `not_checked`, and `command`/`timeout_s`/`sides` are `null`). For `"command"`: `command` is the argv **list** verbatim (never a shell string — it is never run through a shell), `timeout_s` the per-invocation cap in force, and `sides` an object keyed `schematic`/`extracted`, each carrying `netlist` (`{path, scope}`, the exact netlist that side was measured on), `exit_status`, `corner_count` and `measurement_names`. See "Measuring with a caller-supplied command" above. | | `testbenches` | array\ | One entry per ``: `request` (`{path, scope}` — the `` argument, normalised the same way as `layout`; issue #1261), `request_sha256`, `netlist` (`{path, scope}` — the simulation body the request names), `netlist_sha256`, `schematic_netlist` (`{path, scope}` — the resolved DUT path it `.include`d, normalised the same way), `schematic_netlist_sha256`, `corner_count`, `measurement_names`, and the issue #2872 `sides` / `nothing_simulated_corners` execution evidence (see "Per-side execution evidence" below). The `*_sha256` fields are the issue #2875 content identities, see "Schematic-side content identity" below. Informational — the full per-corner detail lives in `delta[]`. **Empty (`[]`) for a `--measure-command` run**, which has no testbenches at all; `measurement.sides` carries the equivalent per-leg detail there. | diff --git a/docs/design/runset-pex-net-correspondence.md b/docs/design/runset-pex-net-correspondence.md index ea2b26aa9..f1c933c70 100644 --- a/docs/design/runset-pex-net-correspondence.md +++ b/docs/design/runset-pex-net-correspondence.md @@ -37,9 +37,12 @@ false`. `poly`, `well`) to the *final* net name and `cluster_id`, post-purge and post-rename, on the live `LayoutToNetlist`. The join reuses this machinery wholesale; no new extraction-side API was added for it. -- **M3 — coordinates agree.** Both engines' per-net polygons land in the - original stream's coordinate space (the inverter fixture's shapes compare - equal, dbu 0.001 both sides), so a geometric join needs no transforms. +- **M3 — the runset can change the coordinate grid.** The IHP inverter + uses 0.001 µm/DBU on both sides and its metal islands overlay the source. + In a 0.002 µm/DBU GDS, setting `dbu(0.001)` in the runset doubled the + persisted integer coordinates. Both saved databases advertised 0.002. + A point at x = 1 µm then landed on the neighbouring pad at x = 2 µm. + The join checks the saved geometry against the source before probing. ## Measured refutations (why the rule is what it is) @@ -68,7 +71,10 @@ false`. ## The landed rule -Use the runset layer's original GDS layer and datatype when available. For +Use the runset layer's original GDS layer and datatype when available. +Verify that each identified layer reproduces the complete source islands it +overlaps. Either the full circuit bounding box or a whole nonempty source +mask must agree in source coordinates. A mismatch withholds every pairing. For anonymous layers, compare the selected circuit's per-layer union with the complete overlapping islands of each original mask. This comparison allows the circuit to omit whole islands. Containment of at least 99 % of the @@ -92,12 +98,15 @@ A unique pairing with complete probe coverage earns a **match**. A polygon without a usable interior point, an unresolved probe, or an ambiguous metal assignment leaves the affected runset net unmatched. Probes of candidate roles on uncertain layers can rule out exclusive ownership by another net. -Only confirmed geometry contributes to split and merge reports. - -The merged leg is the runset leg's own netlist rewritten in place: matched -nodes renamed (a named runset net keeps its name — device-side truth; an -anonymous one adopts its curated counterpart's label, never onto a -colliding name), plus one lumped series `R` (node→hub), one ground `C`, +When a fragment has no interior grid point its possible curated owners are +unknown. In that case every pairing is withheld. Confirmed probe hits still +contribute to split and merge reports. Runset cluster IDs identify the probe +owners throughout, including nets with multiple labels or punctuation. + +The merged leg is staged privately until the merge succeeds. A named runset +net keeps its SPICE spelling after escaping and collision resolution. An +anonymous net can adopt a unique, SPICE-safe curated label. The writer +adds one lumped series `R` (node→hub), one ground `C`, matched coupling capacitors, and the deck's substrate DC tie. This is deliberately **coarser than the curated engine's own star** — the curated netlist distributes a net's R across its *curated* device terminals, diff --git a/src/klayout_tools/extract_netlist_target.py b/src/klayout_tools/extract_netlist_target.py index 989d5bfa6..667f58b54 100644 --- a/src/klayout_tools/extract_netlist_target.py +++ b/src/klayout_tools/extract_netlist_target.py @@ -31,7 +31,7 @@ def _default_output_path(path: str) -> str: return f"{stem}.spice" -def _resolve_netlist_target( +def resolve_netlist_target( path: str, output: str | None, no_netlist: bool ) -> tuple[str, str | None]: """Where the netlist is written, plus the scratch dir to delete after (or @@ -50,6 +50,10 @@ def _resolve_netlist_target( return netlist_path, None +# Preserve the original extract helper import as well as the shared entry point. +_resolve_netlist_target = resolve_netlist_target + + def _finish_netlist_write( netlist_path: str, scratch_dir: str | None ) -> tuple[str | None, str | None]: diff --git a/src/klayout_tools/extract_runset.py b/src/klayout_tools/extract_runset.py index d8a5908b4..eadd00ad3 100644 --- a/src/klayout_tools/extract_runset.py +++ b/src/klayout_tools/extract_runset.py @@ -132,6 +132,7 @@ class name -- see :mod:`klayout_tools.extract_runset_spice` for why KLayout's _device_params_echo, _dropped_parameter_warnings, _instantiated_device_counts, + _prepare_merged_node_names, _uncarried_parameters, _write_netlist, ) @@ -364,6 +365,7 @@ def run_extract_klayout_runset( # Checked before anything is written: an unknown `--device-param` # parameter is an error, never a device silently left at its default. + aliases = _prepare_merged_node_names(circuit) if lvsdb_out else [] declared_warnings = _check_device_params(netlist, declared) uncarried = _uncarried_parameters(netlist, declared) reported_netlist_path, netlist_sha256 = _write_netlist( @@ -454,6 +456,7 @@ def run_extract_klayout_runset( "device_classes": sorted(device_counts), "devices": devices, "nets": nets, + **({"runset_node_renames": aliases} if aliases else {}), "device_models": dict(sorted(models.items())) if models else None, # Additive (issue #5513): present only when `--device-param` was given. **_device_params_echo(declared), diff --git a/src/klayout_tools/extract_runset_spice.py b/src/klayout_tools/extract_runset_spice.py index ea2b29fe2..7d1e1c50b 100644 --- a/src/klayout_tools/extract_runset_spice.py +++ b/src/klayout_tools/extract_runset_spice.py @@ -42,6 +42,7 @@ from __future__ import annotations +import re import shutil from collections.abc import Mapping from typing import Any @@ -229,6 +230,53 @@ def _netlist_description( return description +def _prepare_merged_node_names(circuit: Any) -> list[dict[str, Any]]: + """Give the SPICE writer and the appended R/C cards one node namespace. + + KLayout prints a comma as a pipe but escapes a literal pipe. Dots in + reports become underscores. Resolve these differences on the actual nets + before writing and reserve names case-insensitively, including duplicates. + The saved LVS database keeps the original labels and cluster IDs. + """ + from .extract_parasitics import spice_safe_net_name + + candidates = [] + for net in circuit.each_net(): + raw = net.expanded_name() + candidate = re.sub( + r"[^a-zA-Z0-9_$,]", + lambda match: f"_{ord(match[0]):x}_", + raw.replace(".", "_").replace("|", ","), + ) + if candidate.startswith(","): + candidate = "n_" + candidate + candidates.append((net, raw, candidate)) + # An existing spelling has priority over a label that normalizes onto it. + candidates.sort(key=lambda row: (row[1] != row[2], row[0].cluster_id)) + reserved = {candidate.casefold() for _, _, candidate in candidates} + used = set() + aliases = [] + for net, raw, candidate in candidates: + node = candidate + if candidate.casefold() in used: + suffix = 1 + while f"{candidate}_{suffix}".casefold() in reserved: + suffix += 1 + node = f"{candidate}_{suffix}" + reserved.add(node.casefold()) + used.add(node.casefold()) + if node != raw: + net.name = node + aliases.append( + { + "runset_cluster_id": net.cluster_id, + "original": raw, + "node": spice_safe_net_name(node), + } + ) + return aliases + + def _write_netlist( *, netlist: Any, diff --git a/src/klayout_tools/pex_merged_leg.py b/src/klayout_tools/pex_merged_leg.py index 82ee3096b..70021409f 100644 --- a/src/klayout_tools/pex_merged_leg.py +++ b/src/klayout_tools/pex_merged_leg.py @@ -31,11 +31,15 @@ import re import tempfile from collections import defaultdict -from collections.abc import Mapping, Sequence +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager from pathlib import Path from typing import Any -from .extract import run_extract +from ._provenance import sha256_file +from .extract import ExtractError, run_extract +from .extract_netlist_target import resolve_netlist_target +from .extract_preflight import preflight_layout from .pex_net_correspondence import ( _pex_error, build_probes, @@ -276,6 +280,20 @@ def _rewrite_netlist( # --------------------------------------------------------------------------- # +@contextmanager +def _staged_netlist(target: str) -> Iterator[Path]: + """Publish the finished leg by atomic rename after the merge.""" + try: + with tempfile.TemporaryDirectory( + prefix=".klt-pex-", dir=Path(target).parent + ) as work: + staged = Path(work) / "extracted.spice" + yield staged + os.replace(staged, target) + except OSError as exc: + raise ExtractError(f"cannot write merged netlist '{target}': {exc}") from exc + + def merged_runset_extract( *, layout_path: str, @@ -311,15 +329,12 @@ def merged_runset_extract( geometry, and merge the curated parasitic network into the runset leg. Returns the runset extract report, enriched in memory with the - ``net_correspondence`` block, the curated ``parasitics`` (so the pex - envelope's model/integrity disclosures describe the parasitics actually - attached), and re-hashed netlist digests. Every pex option only a - richer curated parasitic model could serve is refused by name here, + ``net_correspondence`` block, the curated model name, and the final netlist hash. + Options requiring a richer parasitic model are refused by name here, from the same table ``klt extract`` refuses them by -- minus the two this route honours (``--deck`` selects the curated deck; ``--label-layer`` its label layers).""" from . import extract_runset - from .decks import get_extraction_deck extract_runset.refuse_unsupported( { @@ -345,13 +360,16 @@ def merged_runset_extract( } ) - deck = get_extraction_deck(deck_name) - with tempfile.TemporaryDirectory(prefix="klt-pex-correspondence-") as work: - lvsdb_out = os.path.join(work, "runset.lvsdb") + source = preflight_layout( + layout_path, deck_name, top=top, label_layers=label_layers + ) + target, _ = resolve_netlist_target(layout_path, output, False) + with _staged_netlist(target) as staged: + lvsdb_out = str(staged.with_name("runset.lvsdb")) report = extract_runset.run_extract_klayout_runset( layout_path, deck_file=runset.deck_file, - output=output, + output=str(staged), top=top, deck_vars=runset.deck_vars, device_models=device_models, @@ -361,11 +379,9 @@ def merged_runset_extract( ) probes, incomplete = build_probes( lvsdb_out, - layout_path, - top=str(report["top"]), - metals=deck.metals, - contact=deck.contact, - dbu_um=float(report["dbu_um"]), + source.top_cell, + metals=source.deck.metals, + contact=source.deck.contact, ) curated = run_extract( layout_path, @@ -377,33 +393,31 @@ def merged_runset_extract( no_netlist=True, ) - corr = correspondence( - [str(entry["name"]) for entry in report["nets"]], - curated.get("probes") or [], - (curated.get("parasitics") or {}).get("nets") or [], - incomplete, - ) - corr["deck"] = deck_name - corr["attached_card_count"] = ( - merge_parasitics( - report["netlist_path"], + parasitics = curated.get("parasitics") or {} + corr = correspondence( + report["nets"], + curated.get("probes") or [], + parasitics.get("nets") or [], + incomplete, + ) + corr["deck"] = deck_name + if "runset_node_renames" in report: + corr["runset_node_renames"] = report.pop("runset_node_renames") + corr["attached_card_count"] = merge_parasitics( + str(staged), top=str(report["top"]), curated_nets=curated["nets"], - substrate=deck.substrate_net, - all_runset_nets=[str(entry["name"]) for entry in report["nets"]], - parasitics=curated.get("parasitics") or {}, + substrate=source.deck.substrate_net, + all_runset_nets=[entry["name"] for entry in report["nets"]], + parasitics=parasitics, deck_name=deck_name, report_block=corr, ) - if report.get("netlist_path") - else 0 - ) - report["label_layers"] = curated["label_layers"] - report["net_correspondence"] = corr - if curated.get("parasitics"): - report["parasitics"] = curated["parasitics"] - if report.get("netlist_path"): - from ._provenance import sha256_file - - report["netlist_sha256"] = sha256_file(report["netlist_path"]) + report["label_layers"] = curated["label_layers"] + report["net_correspondence"] = corr + # The curated integrity rows describe its own star, while this writer + # emits a lumped network over just the matched clusters. + report["parasitics"] = {"model": parasitics.get("model")} + report["netlist_sha256"] = sha256_file(str(staged)) + report["netlist_path"] = target return report diff --git a/src/klayout_tools/pex_net_correspondence.py b/src/klayout_tools/pex_net_correspondence.py index ab6ac4101..22c79cb1e 100644 --- a/src/klayout_tools/pex_net_correspondence.py +++ b/src/klayout_tools/pex_net_correspondence.py @@ -1,16 +1,8 @@ -"""The geometric net correspondence joining a runset-engine ``klt pex`` -leg's nets with a curated deck's parasitic extraction (issue #6606). - -``klt pex --engine klayout-runset`` (issue #6559) extracts its leg with the -PDK's own LVS runset, so the device set is the right one -- but with no -parasitics: the runset and a curated deck number their unlabelled nets -independently (``\\$1``, ``docs/cli/extract.md``'s "Anonymous net -numbering"), so curated parasitics cannot be attached to runset devices by -name. This module puts the two extractions in correspondence **by -geometry**; :mod:`klayout_tools.pex_merged_leg` builds the merged leg on -top of it. The measured decision -- why this rule and not the alternatives --- is ``docs/design/runset-pex-net-correspondence.md``; this docstring -records the rule itself. +"""Geometric correspondence between runset and curated PEX nets (issue #6606). + +Both engines allocate anonymous net numbers independently. The merged writer +uses this join to attach curated parasitics to the runset device nodes. +See docs/design/runset-pex-net-correspondence.md for the measured decision. Every metal polygon of the selected runset circuit contributes a strictly interior probe to the curated extractor. The layer comes from the source @@ -22,6 +14,7 @@ from __future__ import annotations +import re from collections import defaultdict from collections.abc import Mapping, Sequence from typing import Any @@ -38,14 +31,7 @@ def _pex_error(message: str) -> Exception: def _is_anonymous(name: str) -> bool: """Whether a net name is KLayout's own ``$N`` placeholder -- either spelling: bare in memory, backslash-escaped in the written netlist.""" - return name.lstrip("\\").startswith("$") - - -def _escaped_net_name(raw: str) -> str: - """The report/netlist node spelling of a net name (issue #1162's - backslash-escaped ``\\$N``) -- the spelling both the curated probe - results and the runset leg's own node tokens use.""" - return "\\" + raw if raw.startswith("$") else raw + return re.fullmatch(r"\$[0-9]+", name.removeprefix("\\")) is not None # --------------------------------------------------------------------------- # @@ -194,7 +180,7 @@ def _layer_roles( def _layer_probes( region: Any, - name: str, + cluster: int, layer: int, roles: Sequence[str], *, @@ -212,13 +198,17 @@ def _layer_probes( for role in roles: probes.append( { - "name": f"{prefix}|{role}|{name}|{layer}-{index}", + "name": f"{prefix}|{role}|{cluster}|{layer}-{index}", "layer": role, "x": point.x * dbu_um, "y": point.y * dbu_um, } ) - details = {"runset_net": name, "layer_index": layer, "candidate_roles": list(roles)} + details = { + "runset_cluster_id": cluster, + "layer_index": layer, + "candidate_roles": list(roles), + } incomplete = [] if not certain: reason = "ambiguous_layer" if len(roles) > 1 else "unidentified_layer" @@ -254,13 +244,52 @@ def _contact_landings( return landings +def _coordinates_agree( + lvs: Any, + circuit: Any, + cell: Any, + metals: Sequence[tuple[int, int]], + roles: Mapping[int, str], + landings: Mapping[int, Any], +) -> bool: + """Check the frame and the actual islands before interpreting integer points.""" + import klayout.db as kdb + + layout = cell.layout() + # A runset DBU override can rescale even the saved circuit boundary while + # the LVS file still advertises the input DBU. Some circuits omit whole + # source islands, so either the boundary or a whole mask must anchor them. + boundary = circuit.boundary.bbox().to_itype(layout.dbu) + if (boundary & cell.bbox()) != boundary: + return False + anchored = boundary == cell.bbox() + nets = list(circuit.each_net()) + for layer in roles.keys() | landings.keys(): + info = lvs.layer_info(layer) + pair = ( + (info.layer, info.datatype) + if info.layer >= 0 + else metals[int(roles[layer][5:])] + ) + stream_layer = layout.find_layer(*pair) + region = _union_of_net_regions(lvs, nets, layer) + if region.is_empty(): + continue + if stream_layer is None: + return False + source = kdb.Region(cell.begin_shapes_rec(stream_layer)).merged() + if (source ^ region).is_empty(): + anchored = True + elif not (source.overlapping(region) ^ region).is_empty(): + return False + return anchored or not (roles or landings) + + def build_probes( lvsdb_path: str, - layout_path: str, + top_cell: Any, *, - top: str, metals: Sequence[tuple[int, int]], - dbu_um: float, contact: tuple[int, int] | None = None, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """Probe every identified metal polygon and record gaps in net coverage. @@ -270,14 +299,8 @@ def build_probes( """ import klayout.db as kdb - layout = kdb.Layout() - layout.read(layout_path) - top_cell = layout.cell(top) - if top_cell is None: - raise _pex_error( - f"net correspondence: layout '{layout_path}' has no cell '{top}' " - "to read the curated deck's metal layers from" - ) + layout = top_cell.layout() + top = top_cell.name lvs = kdb.LayoutVsSchematic() lvs.read(lvsdb_path) circuit = lvs.netlist().circuit_by_name(top) @@ -288,12 +311,16 @@ def build_probes( ) roles, uncertain = _layer_roles(lvs, circuit, layout, top_cell, metals) landings = _contact_landings(lvs, layout, top_cell, contact, metals) + if not _coordinates_agree(lvs, circuit, top_cell, metals, roles, landings): + return [], [ + {"runset_cluster_id": net.cluster_id, "reason": "coordinate_mismatch"} + for net in circuit.each_net() + ] roles.update(dict.fromkeys(landings, "metal0")) layers = sorted(roles.keys() | uncertain.keys()) probes = [] incomplete = [] for net in circuit.each_net(): - name = _escaped_net_name(net.expanded_name()) for layer in layers: region = lvs.polygons_of_net(net, layer, True) if region is None or region.is_empty(): @@ -302,7 +329,12 @@ def build_probes( region = region & landings[layer] candidates = [roles[layer]] if layer in roles else uncertain[layer] points, gaps = _layer_probes( - region, name, layer, candidates, certain=layer in roles, dbu_um=dbu_um + region, + net.cluster_id, + layer, + candidates, + certain=layer in roles, + dbu_um=layout.dbu, ) probes.extend(points) incomplete.extend(gaps) @@ -316,84 +348,96 @@ def build_probes( def _probe_hits( probe_results: Sequence[Mapping[str, Any]], -) -> tuple[dict[str, set[tuple[str, int]]], set[tuple[str, int]], set[str]]: +) -> tuple[dict[int, set[tuple[str, int]]], set[tuple[str, int]], set[int]]: """Return confirmed hits, possible cluster hits and nets with a probe miss.""" - hits: dict[str, set[tuple[str, int]]] = defaultdict(set) + hits: dict[int, set[tuple[str, int]]] = defaultdict(set) possible: set[tuple[str, int]] = set() - missed: set[str] = set() + missed: set[int] = set() for result in probe_results: parts = str(result.get("name") or "").split("|") if len(parts) != 4 or parts[0] not in {"kltcorr", "kltmaybe"}: continue + if not parts[2].isdecimal(): + continue + cluster = int(parts[2]) if result.get("found"): hit = (str(result["net"]), int(result["cluster_id"])) if parts[0] == "kltcorr": - hits[parts[2]].add(hit) + hits[cluster].add(hit) else: possible.add(hit) elif parts[0] == "kltcorr": - missed.add(parts[2]) + missed.add(cluster) return hits, possible, missed def correspondence( - runset_net_names: Sequence[str], + runset_nets: Sequence[Mapping[str, Any]], probe_results: Sequence[Mapping[str, Any]], curated_parasitic_nets: Sequence[Mapping[str, Any]], incomplete_geometry: Sequence[Mapping[str, Any]] = (), ) -> dict[str, Any]: - """The ``net_correspondence`` envelope block (issue #6606 AC 2/3). - - ``probe_results`` is the curated run's ``probes[]`` (a ``found`` entry - carries the final curated ``net`` name and ``cluster_id`` -- identity, - robust to two nets sharing one label); ``runset_net_names`` the selected - circuit's nets in the report's escaped spelling; - ``curated_parasitic_nets`` the curated ``parasitics.nets[]`` entries, so - a curated parasitic net nobody matched is listed even though it never - probes anything itself. + """Classify the two extractions by cluster ID on each side. + + Runset report rows provide display names. Curated probe results identify + hits, and the parasitic rows enumerate even clusters with no probe hit. """ hits, possible, missed = _probe_hits(probe_results) - gaps = list(incomplete_geometry) + names = {entry["net_id"]: entry["name"] for entry in runset_nets} + gaps = [ + {**gap, "runset_net": names[gap["runset_cluster_id"]]} + for gap in incomplete_geometry + ] gaps.extend( - {"runset_net": net, "reason": "unresolved_probe"} for net in sorted(missed) + {"runset_cluster_id": i, "runset_net": names[i], "reason": "unresolved_probe"} + for i in sorted(missed) ) - incomplete = {entry["runset_net"] for entry in gaps} + incomplete = {entry["runset_cluster_id"] for entry in gaps} + # A fragment with no probe can belong to any curated cluster, including + # one reached from another metal through vias. No peer can prove exclusivity. + unbounded = any(gap["reason"] == "no_interior_probe" for gap in gaps) matched: list[dict[str, Any]] = [] unmatched_runset: list[str] = [] disagreements: list[dict[str, Any]] = [] - reverse: dict[tuple[str, int], list[str]] = defaultdict(list) - for runset_net in runset_net_names: + reverse: dict[tuple[str, int], list[int]] = defaultdict(list) + for runset_net in names: for hit in hits.get(runset_net, ()): reverse[hit].append(runset_net) - for (name, cluster), runset_nets in sorted(reverse.items()): - if len(runset_nets) > 1: + for (name, cluster), fragments in sorted(reverse.items()): + if len(fragments) > 1: disagreements.append( { "kind": "merge", "curated_net": name, "cluster_id": cluster, - "runset_nets": sorted(runset_nets), + "runset_nets": sorted(names[i] for i in fragments), } ) - for runset_net in runset_net_names: + for runset_net in names: net_hits = sorted(hits.get(runset_net, ())) if ( len(net_hits) == 1 and len(reverse[net_hits[0]]) == 1 and net_hits[0] not in possible + and not unbounded and runset_net not in incomplete ): name, cluster = net_hits[0] matched.append( - {"runset": runset_net, "curated": name, "cluster_id": cluster} + { + "runset": names[runset_net], + "runset_cluster_id": runset_net, + "curated": name, + "cluster_id": cluster, + } ) continue - unmatched_runset.append(runset_net) + unmatched_runset.append(names[runset_net]) if len(net_hits) > 1: disagreements.append( { "kind": "split", - "runset_net": runset_net, + "runset_net": names[runset_net], "curated_nets": [name for name, _ in net_hits], "curated_cluster_ids": [cluster for _, cluster in net_hits], } @@ -441,6 +485,10 @@ def preferred_renames( runset_net, curated_net = entry["runset"], entry["curated"] if not _is_anonymous(runset_net) or _is_anonymous(curated_net): continue + # A curated display label can contain spaces or SPICE syntax. Only + # adopt labels that form one unambiguous node token in a written card. + if not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_$|]*", curated_net): + continue if curated_net.casefold() in kept or curated_net.casefold() in adopted: continue renames[runset_net] = curated_net diff --git a/tests/test_pex_correspondence_geometry.py b/tests/test_pex_correspondence_geometry.py index 2109ff8a3..1b4c1ae5f 100644 --- a/tests/test_pex_correspondence_geometry.py +++ b/tests/test_pex_correspondence_geometry.py @@ -4,6 +4,7 @@ import pytest from klayout_tools.extract import run_extract +from klayout_tools.extract_report import _describe_nets from klayout_tools.pex_net_correspondence import ( _interior_point, build_probes, @@ -12,12 +13,21 @@ from test_extract_body_nets_sg13cmos5l import _make_sg13cmos5l_inverter_layout -def _join(tmp_path, layout, *, join_first_metal=False, anonymous=False): +def _join( + tmp_path, + layout, + *, + join_first_metal=False, + anonymous=False, + labels=False, + source=None, +): """Serialize a runset DB, then probe the independent sg13cmos5l extraction.""" cell = layout.top_cell() gds = str(tmp_path / "routing.gds") db = str(tmp_path / "routing.lvsdb") - layout.write(gds) + source = layout if source is None else source + source.write(gds) lvs = kdb.LayoutVsSchematic(kdb.RecursiveShapeIterator(layout, cell, [])) metal_layers = (8,) if join_first_metal else (8, 10) for layer in metal_layers: @@ -26,17 +36,16 @@ def _join(tmp_path, layout, *, join_first_metal=False, anonymous=False): region = region & region lvs.register(region, f"derived{layer}") lvs.connect(region) + if labels and layer == 8: + lvs.connect(region, lvs.make_text_layer(layout.layer(8, 2), "labels")) if join_first_metal: lvs.connect_global(region, "JOINED") lvs.extract_netlist() lvs.write(db) - nets = [ - net.expanded_name().replace("$", "\\$") - for net in lvs.netlist().circuit_by_name(cell.name).each_net() - ] - probes, coverage = build_probes( - db, gds, top=cell.name, metals=[(8, 0), (10, 0)], dbu_um=layout.dbu - ) + saved = kdb.LayoutVsSchematic() + saved.read(db) + nets = _describe_nets(saved.netlist().circuit_by_name(cell.name)) + probes, coverage = build_probes(db, source.top_cell(), metals=[(8, 0), (10, 0)]) curated = run_extract( gds, "sg13cmos5l", @@ -149,18 +158,82 @@ def hit(prefix, net, cluster): } corr = correspondence( - ["partial", "confirmed", "ambiguous"], [ - hit("kltcorr", "partial", 1), - hit("kltcorr", "partial", None), - hit("kltcorr", "confirmed", 2), - hit("kltmaybe", "ambiguous", 2), + {"name": name, "net_id": i} + for i, name in enumerate(["partial", "confirmed", "ambiguous"], 1) + ], + [ + hit("kltcorr", 1, 1), + hit("kltcorr", 1, None), + hit("kltcorr", 2, 2), + hit("kltmaybe", 3, 2), ], [], - [{"runset_net": "ambiguous", "reason": "ambiguous_layer"}], + [{"runset_cluster_id": 3, "reason": "ambiguous_layer"}], ) assert corr["matched"] == [] assert corr["disagreements"] == [] - assert {"runset_net": "partial", "reason": "unresolved_probe"} in corr[ - "incomplete_geometry" - ] + assert { + "runset_net": "partial", + "runset_cluster_id": 1, + "reason": "unresolved_probe", + } in corr["incomplete_geometry"] + + +def _pads(second_labels, *, narrow=False, joined=False): + layout = kdb.Layout() + layout.dbu = 0.002 + layout.create_cell("TOP") + for x, width, labels in [ + (500, 200, ["BUS"]), + (1000, 1 if narrow else 400, second_labels), + ]: + pad = kdb.Box(x, 0, x + width, 400) + _draw(layout, 8, pad) + for label in labels: + _draw(layout, 8, kdb.Text(label, kdb.Trans(x, 100)), 2) + if joined: + _draw(layout, 19, pad) + if joined: + _draw(layout, 10, kdb.Box(500, 0, 1400, 400)) + return layout + + +@pytest.mark.parametrize("labels", [["ALIAS", "SECOND"], ["XBIAS.vb1"], ["A|B"]]) +def test_spelling_cannot_hide_one_part_of_a_merge(tmp_path, labels): + corr = _join(tmp_path, _pads(labels, joined=True), labels=True) + assert corr["matched"] == [] + (merge,) = corr["disagreements"] + assert merge["kind"] == "merge" + assert "BUS" in merge["runset_nets"] + assert len(merge["runset_nets"]) >= 2 + + +def test_unprobeable_peer_withholds_the_shared_curated_network(tmp_path): + corr = _join(tmp_path, _pads(["OTHER"], narrow=True, joined=True), labels=True) + assert corr["matched"] == [] + assert {"BUS", "OTHER"} <= set(corr["unmatched_runset_nets"]) + assert any( + g["runset_net"] == "OTHER" and g["reason"] == "no_interior_probe" + for g in corr["incomplete_geometry"] + ) + + +def test_saved_coordinates_must_agree_with_source_masks(tmp_path): + source = _pads(["OTHER"]) + control = _join(tmp_path, source, labels=True) + assert {m["runset"]: m["curated"] for m in control["matched"]} == { + "BUS": "BUS", + "OTHER": "OTHER", + } + runset = source.dup() + runset.transform(kdb.ICplxTrans(2)) + # Include an unrelated source mask extending beyond the runset, so the + # circuit boundary alone would accept both coordinate frames. + _draw(source, 233, kdb.Box(0, 0, 5000, 5000)) + corr = _join(tmp_path, runset, labels=True, source=source) + assert corr["matched"] == [] + assert corr["unmatched_runset_nets"] == ["BUS", "OTHER"] + assert {gap["reason"] for gap in corr["incomplete_geometry"]} == { + "coordinate_mismatch" + } diff --git a/tests/test_pex_net_correspondence.py b/tests/test_pex_net_correspondence.py index 5717b2702..3b64f7f4d 100644 --- a/tests/test_pex_net_correspondence.py +++ b/tests/test_pex_net_correspondence.py @@ -50,6 +50,7 @@ def _write_lvsdb( *, isolate_metals: bool = False, bridge_terminals: bool = False, + net_labels: dict | None = None, ) -> None: """Stand in for the PDK runset on the cmos5l inverter fixture. @@ -80,6 +81,9 @@ def _write_lvsdb( l2n.connect(metal1, cont) l2n.connect(cont, sd) l2n.extract_netlist() + for net in l2n.netlist().top_circuit().each_net(): + if net_labels and net.expanded_name() in net_labels: + net.name = net_labels[net.expanded_name()] l2n.netlist().make_top_level_pins() ref = kdb.Netlist() ref.read(schem, kdb.NetlistSpiceReader()) @@ -110,6 +114,7 @@ def fake_run(cmd, *a, **kw): args["report"], isolate_metals=state["isolate_metals"], bridge_terminals=state["bridge_terminals"], + net_labels=state.get("net_labels"), ) return subprocess.CompletedProcess(cmd, 0, "", "") @@ -240,6 +245,31 @@ def test_a_merge_disagreement_is_reported_never_guessed(tmp_path, fake_klayout): assert "_plr " not in text +@pytest.mark.parametrize("isolate,expected_cards", [(True, 0), (False, 11)]) +def test_merged_envelope_only_reports_integrity_for_an_assessed_network( + tmp_path, fake_klayout, isolate, expected_cards +): + from klayout_tools.pex import run_pex + + fake_klayout["isolate_metals"] = isolate + gds = tmp_path / "inv.gds" + _write_fixture(str(gds)) + deck = tmp_path / "test.lvs" + deck.touch() + envelope = run_pex( + str(gds), + [], + "sg13cmos5l", + runset=PexRunset(deck_file=str(deck)), + extract_only=True, + ) + extraction = envelope["extraction"] + assert extraction["net_correspondence"]["attached_card_count"] == expected_cards + assert extraction["parasitic_integrity"] is None + assert extraction["model"] + assert (tmp_path / "inv.spice").exists() + + def test_a_split_disagreement_is_reported_not_compared(tmp_path, fake_klayout): """A runset cluster spanning several curated nets is refused both ways: reported as a split, its curated nets left unmatched, no cards.""" @@ -253,7 +283,9 @@ def test_a_split_disagreement_is_reported_not_compared(tmp_path, fake_klayout): ) assert [s["curated_nets"] for s in splits] == [["VGND", "Y"], ["VPWR", "Y"]] # The one cluster the bridge left whole still matches and attaches. - assert corr["matched"] == [{"runset": "\\$3", "curated": "A", "cluster_id": 3}] + assert corr["matched"] == [ + {"runset": "\\$3", "runset_cluster_id": 3, "curated": "A", "cluster_id": 3} + ] assert corr["attached_card_count"] == 3 # A's R + C + the substrate tie @@ -262,23 +294,27 @@ def test_a_split_disagreement_is_reported_not_compared(tmp_path, fake_klayout): # --------------------------------------------------------------------------- # -def _probe(runset_net: str, curated: str, cluster: int, found: bool = True): +def _probe(runset_cluster: int, curated: str, cluster: int, found: bool = True): return { - "name": f"kltcorr|metal0|{runset_net}|0", + "name": f"kltcorr|metal0|{runset_cluster}|0", "found": found, "net": curated if found else None, "cluster_id": cluster if found else None, } +def _nets(*names): + return [{"net_id": i, "name": name} for i, name in enumerate(names, 1)] + + def test_correspondence_classifies_every_outcome(): corr = correspondence( - ["\\$1", "\\$2", "\\$3", "\\$4"], + _nets("\\$1", "\\$2", "\\$3", "\\$4"), [ - _probe("\\$1", "A", 3), - _probe("\\$2", "B", 1), - _probe("\\$2", "C", 2), # \$2 spans two curated nets: split - _probe("\\$4", "A", 3), # A also hit by \$1: merge with \$1 + _probe(1, "A", 3), + _probe(2, "B", 1), + _probe(2, "C", 2), # \$2 spans two curated nets: split + _probe(4, "A", 3), # A also hit by \$1: merge with \$1 {"name": "user-probe", "found": True, "net": "X", "cluster_id": 9}, ], [{"net": "D", "net_id": 4}, {"net": "A", "net_id": 3}], @@ -300,16 +336,18 @@ def test_correspondence_classifies_every_outcome(): def test_unmatched_same_label_and_overlapping_disagreements(): corr = correspondence( - ["first", "bridged", "fragment"], + _nets("first", "bridged", "fragment"), [ - _probe("first", "Y", 1), - _probe("bridged", "Y", 2), - _probe("bridged", "B", 3), - _probe("fragment", "Y", 2), + _probe(1, "Y", 1), + _probe(2, "Y", 2), + _probe(2, "B", 3), + _probe(3, "Y", 2), ], [{"net": "Y", "net_id": i} for i in [1, 2, 4]], ) - assert corr["matched"] == [{"runset": "first", "curated": "Y", "cluster_id": 1}] + assert corr["matched"] == [ + {"runset": "first", "runset_cluster_id": 1, "curated": "Y", "cluster_id": 1} + ] assert corr["unmatched_curated_clusters"] == [ {"curated": "Y", "cluster_id": 2}, {"curated": "Y", "cluster_id": 4}, @@ -325,7 +363,7 @@ def test_unmatched_same_label_and_overlapping_disagreements(): def test_unfound_probes_are_not_matches(): corr = correspondence( - ["\\$1"], [_probe("\\$1", None, None, found=False)], [{"net": "A", "net_id": 3}] + _nets("\\$1"), [_probe(1, None, None, found=False)], [{"net": "A", "net_id": 3}] ) assert corr["matched"] == [] assert corr["unmatched_runset_nets"] == ["\\$1"] @@ -347,9 +385,9 @@ def test_preferred_renames_adopt_labels_and_refuse_collisions(): def test_probe_results_parse_only_kltcorr_names(): corr = correspondence( - ["\\$1"], + _nets("\\$1"), [ - _probe("\\$1", "A", 1), + _probe(1, "A", 1), { "name": "kltcorr|metal0|broken", "found": True, @@ -360,7 +398,9 @@ def test_probe_results_parse_only_kltcorr_names(): ], [], ) - assert corr["matched"] == [{"runset": "\\$1", "curated": "A", "cluster_id": 1}] + assert corr["matched"] == [ + {"runset": "\\$1", "runset_cluster_id": 1, "curated": "A", "cluster_id": 1} + ] # --------------------------------------------------------------------------- # @@ -436,3 +476,20 @@ def test_real_pnpmpa_merged_run_reports_the_measured_mismatch(tmp_path): # The envelope this produces refuses item 7 (no_parasitics), which the # signoff tests in test_pex_runset_signoff.py grade separately. assert json.dumps(corr) + + +def test_merged_device_and_parasitic_cards_use_the_same_spice_names( + tmp_path, fake_klayout +): + labels = {"$1": "XBIAS.vb1", "$2": "A|B", "$3": "A,B", "$4": "XBIAS_vb1"} + fake_klayout["net_labels"] = labels + corr = _merged(tmp_path, fake_klayout)["net_correspondence"] + nodes = {m["runset"] for m in corr["matched"]} + assert {"A|B", "A|B_1", "XBIAS_vb1", "XBIAS_vb1_1"} <= nodes + cards = [line.split() for line in (tmp_path / "leg.spice").read_text().splitlines()] + for node in ("A|B", "A|B_1", "XBIAS_vb1", "XBIAS_vb1_1"): + assert any( + card and card[0].startswith("X") and node in card[1:-1] for card in cards + ) + assert any(card[:2] == [f"R{node}_plr", node] for card in cards) + assert {r["original"] for r in corr["runset_node_renames"]} == {"XBIAS.vb1", "A|B"} diff --git a/tests/test_pex_runset_cli.py b/tests/test_pex_runset_cli.py index 6d54fb63e..1e931f222 100644 --- a/tests/test_pex_runset_cli.py +++ b/tests/test_pex_runset_cli.py @@ -273,6 +273,51 @@ def test_cli_curated_deck_under_the_runset_engine_runs_the_merged_route( assert extraction["label_layers"] == {"metal0": None} +@pytest.mark.parametrize( + "options,needle", + [ + (["--deck", "misspelled"], "misspelled"), + (["--deck", "sky130", "--label-layer", "bogus=1/0"], "bogus"), + (["--deck", "sky130"], "merge interrupted"), + ], +) +def test_merged_failure_preserves_output_and_writes_error_envelope( + tmp_path, fake_klayout, capsys, monkeypatch, options, needle +): + from klayout_tools import pex_merged_leg + from klayout_tools.pex import PexError + + target = tmp_path / "out.spice" + target.write_bytes(b"* previous extraction\n") + envelope = tmp_path / "error.json" + + def fail_after_device_extraction(staged, **kwargs): + assert target.read_bytes() == b"* previous extraction\n" + assert staged != str(target) + raise PexError("merge interrupted") + + monkeypatch.setattr( + pex_merged_leg, "merge_parasitics", fail_after_device_extraction + ) + code, _, err = _cli( + tmp_path, + "--engine", + "klayout-runset", + "--deck-file", + "DECKFILE", + *options, + "--extract-only", + "--envelope-out", + str(envelope), + capsys=capsys, + ) + assert code == 1 + assert needle in err["error"]["message"] + assert json.loads(envelope.read_text()) == err + assert target.read_bytes() == b"* previous extraction\n" + assert not list(tmp_path.glob(".klt-pex-*")) + + @pytest.mark.parametrize( "flag", [