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 cd4f4addd..d74266b5e 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..0a927f839 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. @@ -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,45 @@ 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` | 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. | | `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 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 +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 +`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. @@ -1347,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` @@ -1914,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/cli/signoff.md b/docs/cli/signoff.md index f6569849d..8d378342c 100644 --- a/docs/cli/signoff.md +++ b/docs/cli/signoff.md @@ -4061,6 +4061,29 @@ 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. 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"` and `"false"`), numbers, arrays, and objects do not qualify. Malformed optional @@ -5675,7 +5698,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-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..f1c933c70 --- /dev/null +++ b/docs/design/runset-pex-net-correspondence.md @@ -0,0 +1,167 @@ +# 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 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 + +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 + 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 + post-rename, on the live `LayoutToNetlist`. The join reuses this machinery + wholesale; no new extraction-side API was added for it. +- **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) + +- **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 — 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 + +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 +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. +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, +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, 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` | + +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 +citation identifies an unmatched substrate return when one was used. + +## 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 adb52462d..b0c8ed257 100644 --- a/import-boundaries.json +++ b/import-boundaries.json @@ -633,6 +633,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/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_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/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/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 e77ffbdd7..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, ) @@ -286,6 +287,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 +297,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 +340,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 @@ -356,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( @@ -446,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.py b/src/klayout_tools/pex.py index 14e2d71fd..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 @@ -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..70021409f --- /dev/null +++ b/src/klayout_tools/pex_merged_leg.py @@ -0,0 +1,423 @@ +"""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 import defaultdict +from collections.abc import Iterator, Mapping, Sequence +from contextlib import contextmanager +from pathlib import Path +from typing import Any + +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, + 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" +) + + +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 _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 _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 _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, + *, + top: str, + all_runset_nets: Sequence[str], + curated_nets: Sequence[Mapping[str, Any]], + substrate: str, + parasitics: Mapping[str, Any], + deck_name: str, + report_block: dict[str, Any], +) -> int: + """Attach the per-cluster lumped network to the selected runset circuit.""" + matched = report_block["matched"] + renames = preferred_renames(matched, all_runset_nets) + 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() + } + 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[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["resistance_ohm"]) + capacitance = float(entry["capacitance_ff"]) + if resistance > 0.0: + hub = _fresh_node(f"{node}__kltph", used) + cards.append(f"R{node}_plr {node} {hub} {_format_number(resistance)}") + hubs[cluster] = hub + if capacitance > 0.0 and ground: + wrote_ground_cap = True + cards.append( + f"C{node}_plc {hub} {ground['node']} " + f"{_format_number(capacitance * 1e-15)}" + ) + 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{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 + ) + return len(cards) + + +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: Path, + lines: list[str], + top: str, + renames: Mapping[str, str], + cards: Sequence[str], + global_node: str | None, + deck_name: str, + report: Mapping[str, Any], +) -> None: + """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 _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") + + +# --------------------------------------------------------------------------- # +# The merged-route driver +# --------------------------------------------------------------------------- # + + +@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, + output: str | None, + 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, + 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 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 + + extract_runset.refuse_unsupported( + { + "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, + } + ) + + 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=str(staged), + 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, incomplete = build_probes( + lvsdb_out, + source.top_cell, + metals=source.deck.metals, + contact=source.deck.contact, + ) + curated = run_extract( + layout_path, + deck_name, + top=str(report["top"]), + parasitics=True, + probes=probes, + label_layers=label_layers, + no_netlist=True, + ) + + 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=source.deck.substrate_net, + all_runset_nets=[entry["name"] for entry in report["nets"]], + parasitics=parasitics, + deck_name=deck_name, + report_block=corr, + ) + 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 new file mode 100644 index 000000000..22c79cb1e --- /dev/null +++ b/src/klayout_tools/pex_net_correspondence.py @@ -0,0 +1,496 @@ +"""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 +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 + +import re +from collections import defaultdict +from collections.abc import Mapping, Sequence +from typing import Any + + +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 re.fullmatch(r"\$[0-9]+", name.removeprefix("\\")) is not None + + +# --------------------------------------------------------------------------- # +# 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) + + 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() + ) + + if strictly_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 strictly_inside(step): + return step + return None + + +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 the selected circuit, including subcircuit shapes.""" + 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 _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, + cluster: int, + 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 + for role in roles: + probes.append( + { + "name": f"{prefix}|{role}|{cluster}|{layer}-{index}", + "layer": role, + "x": point.x * dbu_um, + "y": point.y * dbu_um, + } + ) + 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" + 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 _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, + top_cell: Any, + *, + metals: Sequence[tuple[int, int]], + 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 = top_cell.layout() + top = top_cell.name + 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, 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(): + 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, + net.cluster_id, + layer, + candidates, + certain=layer in roles, + dbu_um=layout.dbu, + ) + probes.extend(points) + incomplete.extend(gaps) + return probes, incomplete + + +# --------------------------------------------------------------------------- # +# The join over probe results +# --------------------------------------------------------------------------- # + + +def _probe_hits( + probe_results: Sequence[Mapping[str, Any]], +) -> 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[int, set[tuple[str, int]]] = defaultdict(set) + possible: set[tuple[str, int]] = 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[cluster].add(hit) + else: + possible.add(hit) + elif parts[0] == "kltcorr": + missed.add(cluster) + return hits, possible, missed + + +def correspondence( + 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]: + """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) + 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_cluster_id": i, "runset_net": names[i], "reason": "unresolved_probe"} + for i in sorted(missed) + ) + 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[int]] = defaultdict(list) + for runset_net in names: + for hit in hits.get(runset_net, ()): + reverse[hit].append(runset_net) + 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(names[i] for i in fragments), + } + ) + 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": names[runset_net], + "runset_cluster_id": runset_net, + "curated": name, + "cluster_id": cluster, + } + ) + continue + unmatched_runset.append(names[runset_net]) + if len(net_hits) > 1: + disagreements.append( + { + "kind": "split", + "runset_net": names[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": [name for name, _ in unmatched], + "unmatched_curated_clusters": [ + {"curated": name, "cluster_id": cluster} for name, cluster in unmatched + ], + "disagreements": sorted( + disagreements, + key=lambda entry: ( + entry["kind"], + str(entry.get("runset_net") or entry.get("curated_net")), + ), + ), + "incomplete_geometry": gaps, + "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.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 + # 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 + adopted.add(curated_net.casefold()) + return renames diff --git a/src/klayout_tools/pex_runset.py b/src/klayout_tools/pex_runset.py index 742220457..aa51b76b7 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,133 @@ 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, + pdk_variant=pdk_variant, + pdk_root=pdk_root, + 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 8272e6c59..29d9197c6 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 @@ -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,29 +3220,27 @@ 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` runs before these checks. Within this gate, - ``nothing_checked`` comes first and the yield campaign check comes last. + :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 item_id == 7 and check_kind == "pex" and (refusal := _parasitic_free(envelope)): + return refusal, False rehash_unverifiable = False if check_kind == "lvs": refusal, rehash_unverifiable = check_runset(envelope) @@ -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 bd3afd720..0ede74a2c 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 @@ -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. @@ -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 @@ -103,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": ( @@ -112,3 +117,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/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.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_correspondence_geometry.py b/tests/test_pex_correspondence_geometry.py new file mode 100644 index 000000000..1b4c1ae5f --- /dev/null +++ b/tests/test_pex_correspondence_geometry.py @@ -0,0 +1,239 @@ +"""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.extract_report import _describe_nets +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, + 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") + 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: + 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 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) + 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", + 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( + [ + {"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_cluster_id": 3, "reason": "ambiguous_layer"}], + ) + assert corr["matched"] == [] + assert corr["disagreements"] == [] + 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_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 new file mode 100644 index 000000000..3b64f7f4d --- /dev/null +++ b/tests/test_pex_net_correspondence.py @@ -0,0 +1,495 @@ +"""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 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, + net_labels: dict | None = None, +) -> 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() + 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()) + 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"], + net_labels=state.get("net_labels"), + ) + 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", + pdk_variant=None, + pdk_root=None, + 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"] == [] + 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 + 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 + 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"): + # 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 + + +@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.""" + 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", "runset_cluster_id": 3, "curated": "A", "cluster_id": 3} + ] + assert corr["attached_card_count"] == 3 # A's R + C + the substrate tie + + +# --------------------------------------------------------------------------- # +# Unit layer: the pure join pieces +# --------------------------------------------------------------------------- # + + +def _probe(runset_cluster: int, curated: str, cluster: int, found: bool = True): + return { + "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( + _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 + {"name": "user-probe", "found": True, "net": "X", "cluster_id": 9}, + ], + [{"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"] + # 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_unmatched_same_label_and_overlapping_disagreements(): + corr = correspondence( + _nets("first", "bridged", "fragment"), + [ + _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", "runset_cluster_id": 1, "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( + _nets("\\$1"), [_probe(1, None, None, found=False)], [{"net": "A", "net_id": 3}] + ) + 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_probe_results_parse_only_kltcorr_names(): + corr = correspondence( + _nets("\\$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", "runset_cluster_id": 1, "curated": "A", "cluster_id": 1} + ] + + +# --------------------------------------------------------------------------- # +# 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", + pdk_variant=None, + pdk_root=None, + 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) + + +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.py b/tests/test_pex_runset.py index 8b278b53d..bcc4576cc 100644 --- a/tests/test_pex_runset.py +++ b/tests/test_pex_runset.py @@ -207,11 +207,52 @@ 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 + + +@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): diff --git a/tests/test_pex_runset_cli.py b/tests/test_pex_runset_cli.py index 87cbc54cd..1e931f222 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 ): @@ -181,10 +246,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", @@ -192,12 +260,91 @@ def test_cli_curated_deck_is_refused_by_name_under_the_runset_engine( "DECKFILE", "--deck", "sky130", + "--label-layer", + "metal0=none", "--extract-only", capsys=capsys, ) + 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" + 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", + [ + "--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 "cannot honour --deck" in err["error"]["message"] + 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( diff --git a/tests/test_pex_runset_signoff.py b/tests/test_pex_runset_signoff.py index c69aedfbe..bda54843c 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,31 @@ }, } +#: 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, + "substrate_return": { + "curated": "vsubs", + "node": "vsubs", + "runset": None, + "tie_resistance_ohm": 1e12, + }, + }, + }, +} + DISCLOSURE = { "engine": "klayout-runset", "parasitics_carried": False, @@ -51,17 +79,31 @@ 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, + "substrate_return": { + "curated": "vsubs", + "node": "vsubs", + "runset": None, + "tie_resistance_ohm": 1e12, + }, + "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 +114,36 @@ 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={"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" + 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 +168,32 @@ 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 "substrate return vsubs (runset unmatched)" 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")