Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions INVARIANTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2117,6 +2117,70 @@ Rust uses `Rc<T>`, Go uses `*T`, Python has reference semantics by
default. This is ONE cross-language fact with per-language syntax —
not three independent implementations in three emitters.

### E-5: Clean-emission contract is satisfied by construction (2026-04-17)

For every target T and program P, the emission pipeline produces
source code that passes T's declared clean-code verifier without
modification. The verifier is named in the target's
`CleanEmissionContract.post_emit_verifier` (e.g., `rustc --edition=2021
-D warnings` for Rust). A diagnostic from the verifier is an emission
bug, not a formatting difference — the fix is structural, not
suppression.

**What "no escape hatches" means.** The contract GROWS by adding
typed rules to `CleanEmissionContract` when new warning categories
surface. It does NOT grow by adding `#[allow(...)]` / `# noqa` /
pragma suppression. E-5's commitment is to CONSTRUCTIVE emission —
"we've covered every category by SHAPE, not by silencing" — so new
targets that surface new warnings (Kotlin's null-safety lints,
Verilog's unused-regs, etc.) land as new typed rules, not as new
suppressed categories. Every rule's dispatch in the emitter removes
(or narrows) a corresponding entry from the test-wrapper
`#[allow(...)]` umbrella; umbrellas only shrink.

**The contract.** Eight rules cover the warning classes currently
observed. See `docs/design-clean-emission-contract.md` (DB-4) for
the full type table and
`src/v3/std/clean_emission.dag` for the declarations.

| Rule | Concern (rustc lint) |
|---|---|
| `expression_wrapping` | `unused_parens` on wrapped expressions |
| `pattern_bindings` | `unused_variables` in match arm payloads |
| `imports` | `unused_imports` |
| `block_return` | `unused_parens` around block terminal value |
| `variable_bindings` | `unused_variables` at let bindings |
| `match_arm_body` | `unused_parens` around match arm body |
| `correction_style` | surface-level fix rendering (DB-1) |
| `post_emit_verifier` | declared verifier command + args |

**Why in INVARIANTS.md.** Once E-5 lands, every emitter change must
justify compliance. A future emitter PR adding a new warning
category without either (a) structurally fixing the cause or (b)
adding a typed rule to the contract is an E-5 violation. The
invariant is the mechanism that prevents "ship now, allow-suppress
later, forget forever."

**Staged rollout (Lane 1 Stage 1c).** E-5 is declared structurally
(rule type system + per-target contract + invariant entry) at the
same time as the first pilot rule (Rust's `PatternBindingRule::
EmitUnderscoreWhenUnused`). Remaining rule dispatches land in
Stage 1c PR 2 (Go + Python pilots) and Stage 1d/1e (consolidation
sweep for parens, imports, etc.). Each PR that wires a new rule
removes the matching lint from the test-wrapper allow umbrella.

**Structural prevention:** the rule dispatch lives inside the
emitter. Emitted text is derived from `contract.<rule>` by match,
not by string rewrites over already-emitted source.

**Test:** each rule's dispatch ships with at least one pilot test
that compiles the emitted code under `#[deny(<rustc-lint>)]` and
asserts compilation succeeds.

**Origin:** DB-4 + Lane 1 Stage 1c. Replaces the band-aid
`#[allow(warnings)]` approach that accumulated around emitted
wrapper modules through M1.

### E-6: No target-spec field without a same-PR consumer (2026-04-16)

A field declared on a target spec (`CallableRealization`,
Expand Down
232 changes: 145 additions & 87 deletions docs/phase1-lane2-clean-emission-invariant.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

**Lane:** 1 (Emission unification)
**Stage:** 1c (after substrate keyed-lookup; before consolidation build plan)
**Size:** M
**Status:** Plan. No code changes yet.
**Size:** M (split across PRs — see §2 Scope split)
**Status:** In progress. PR 1 (Rust pilot + contract type system) in flight.

> Role in the plan: establishes E-5 invariant (warnings-by-construction)
> as the contract that Stage 1e's consolidation dispatches on. The
Expand Down Expand Up @@ -42,12 +42,15 @@ the pilot implementation that proves the shape.

## Scope

Three deliverables, plus evaluation of three candidate invariants from Half B audit (see bottom of this doc):
Three deliverables.

### 1. Design doc: the invariant

Output: this file's successor becomes authoritative (`docs/clean-emission-invariant.md`),
plus an `INVARIANTS.md` entry.
Output: this file plus an `INVARIANTS.md` E-5 entry. Concrete contract
shape is pinned in [`design-clean-emission-contract.md`](./design-clean-emission-contract.md)
(DB-4) and is load-bearing for this stage — the 8-rule contract shape
below is authoritative; any drift between this sketch and DB-4 gets
reconciled against DB-4.

**The invariant (E-5):**
> For every target T and program P, the emission pipeline produces
Expand All @@ -63,35 +66,38 @@ plus an `INVARIANTS.md` entry.
> category" — new targets will surface new categories, and each
> lands as a structural rule, not a silenced warning.

Per-target spec extension:
Per-target spec extension (DB-4 carries the full 8-rule field set;
this sketch names the fields, not their rule-variant dispatch):

```
// in spec/rust.dag (analogous for go.dag, python.dag, etc.)
data rust_clean_emission: CleanEmissionContract = {
expression_wrapping: WrapOnlyInOperandPosition
pattern_bindings: EmitUnderscoreWhenUnused
imports: IncludeOnlyReferenced
block_return: NoRedundantWrapping
block_return: NoWrappingOnTerminalExpression
variable_bindings: EmitUnderscoreWhenUnused
match_arm_body: NoWrappingOnNonComplexBody
correction_style: rust_correction_style
post_emit_verifier: {
command: "rustc"
args: ["--edition=2021", "-D", "warnings", "..."]
args: ["--edition=2021", "-D", "warnings"]
syntax_only: false
expected_exit_code: 0
}
}
```

type CleanEmissionContract {
expression_wrapping: ExpressionWrappingRule
pattern_bindings: PatternBindingRule
imports: ImportRule
block_return: BlockReturnRule
post_emit_verifier: PostEmitVerifier
}
`CleanEmissionContract` itself (8 fields) and the per-rule coproducts
(closed enums with `NotApplicable` variants where relevant) live in
`std/clean_emission.dag`. See DB-4 for the complete type table.

type ExpressionWrappingRule
= WrapEverything // current behavior — rejected
| WrapOnlyInOperandPosition // correct
```
**Explicitly out of the E-5 surface:** emitted-struct dead-code.
Removed from DB-4 per codex feedback on PR #491 — that's a
publicity/visibility concern, not a clean-emission one. E-5 covers
constructive rendering rules only.

### 2. Pilot implementation: unused pattern bindings
### 2. Pilot implementation: unused pattern bindings (Rust first)

Pick **one** clean-code rule and solve it structurally end-to-end.
Choice: `pattern_bindings: EmitUnderscoreWhenUnused`.
Expand All @@ -102,41 +108,67 @@ Choice: `pattern_bindings: EmitUnderscoreWhenUnused`.
- No test wrapper changes (imports do)
- Clean test: pattern match arms with unused bindings must emit `_`

**Implementation sketch:**
1. Add `CleanEmissionContract` type in `src/v3/spec/clean_emission.dag` (new file)
2. Add `pattern_bindings` field to each target's spec (`rust.dag`, `go.dag`, `python.dag`)
3. In `emit_rust.rs` `render_branch_pattern`:
- Walk the arm body to collect referenced PortIds
- For each payload binding in the pattern: emit `_` if its port is
not in the referenced set, else emit the binding name
4. In `emit_go.rs` / `emit_python.rs`: analogous using Go's `_` and
Python's `_var_name` conventions per each target's rule
5. Add a `render_locals_analysis` helper (target-agnostic) that
computes the referenced-ports set for a body — this is the
"port liveness" primitive P2 will also consume

### 3. CI gate: post_emit_verifier as a hard check
**Scope split across PRs.** The stage originally sketched "all three
current targets (Rust/Go/Python) in one sweep." Practical scope split:

- **PR 1 (this PR):** Rust pilot — `std/clean_emission.dag` type
system; `rust_clean_emission` data item in `spec/rust.dag`;
`render_branch_pattern` dispatch; targeted test under
`#[deny(unused_variables)]` proving the rule fires; E-5 entry in
`INVARIANTS.md`.
- **PR 2 (follow-up):** Go + Python pilots — `go_clean_emission` /
`python_clean_emission` data items and per-emitter dispatch.
Deferred because Go's binding surface is `{x} := {expr};` (blank
identifier path) and Python's pattern-bind doesn't emit the binding
as part of the pattern at all — two distinct structural proofs,
separate from Rust's `render_branch_pattern` path. E-6 holds in PR 1
because each target's spec item lands only when its emitter
consumer lands.
- **PR 3 (follow-up):** Wire `post_emit_verifier` into the test
harness (rustc `-D warnings` hard gate, test-wrapper
`#[allow(unused_variables)]` strike). Deferred because the test
harness change is a distinct chunk that doesn't gate correctness
of the rule dispatch.

**Implementation sketch (PR 1):**
1. `std/clean_emission.dag` — new file; declares
`CleanEmissionContract` (8 fields per DB-4) and the coproduct
rule types.
2. `spec/rust.dag` — adds `rust_clean_emission` data item with
concrete rule variants.
3. `dag.rs` — caches `rust_clean_emission` in `TargetSyntaxCache`
(name-lookup at bootstrap end, same pattern as `rust_rendering`).
4. `emit_rust.rs` — parses `CleanEmissionContract` into a typed
binding; `render_branch_pattern` dispatches on
`contract.pattern_bindings`. Port-liveness walk answers "is the
binding's payload_port consumed by anything reachable from
`path.output`?" — if not, emit `_`; else emit the binding name.
5. Targeted test — `#[deny(unused_variables)]` on a single fixture
containing a match arm whose payload binding is unused; asserts
compilation succeeds (i.e. emission produced `_`).

### 3. CI gate: post_emit_verifier as a hard check (follow-up PR)

Each emitter test suite adds a step: after emission, invoke the target's
declared `post_emit_verifier`. If it reports any diagnostic (warning or
error), the test fails.

**Today's rustc roundtrip tests do this partially** — they invoke rustc
but without `-D warnings`. After L2, `-D warnings` is declared IN THE
SPEC and the test harness reads it from there.
but without `-D warnings`. After Stage 1c's follow-up PR, `-D warnings`
is declared IN THE SPEC and the test harness reads it from there.

**Transition plan:**
- Keep `#[allow(warnings)]` attributes in emitted modules during this
lane's pilot implementation
- As each warning category is structurally fixed, remove the
corresponding lint from the allow list
- When the pilot (unused pattern bindings) ships: remove
`unused_variables` from the allow list
- P2 consolidates the remaining categories (parens, imports, etc.)
- Keep `#[allow(warnings)]` attributes in emitted modules during PR 1
(pilot proves contract dispatch via a narrow `#[deny(unused_variables)]`
test, not by stripping the umbrella allow).
- PR 3 strikes `unused_variables` from the test-wrapper allow list
(once Rust + Go + Python all dispatch the rule).
- Lane 1d/1e consolidates the remaining categories (parens, imports,
etc.) and strikes those as they land.

**Do NOT attempt to fix all four warning categories in this lane.** The
pilot validates the contract shape. The rest are structural work that
folds into P2's emitter consolidation.
folds into Lane 1d/1e's emitter consolidation.

---

Expand Down Expand Up @@ -200,21 +232,56 @@ Stop work and surface if:

## Acceptance gates

Lane is done when all four hold:

- `docs/clean-emission-invariant.md` exists with the E-5 invariant,
`CleanEmissionContract` type definition, per-target rule table, and
the "reject post-emission cleanup" rationale.
- `INVARIANTS.md` has an E-5 entry referencing the design doc.
- `spec/clean_emission.dag` (or equivalent) declares the contract
type; each of `spec/rust.dag`, `spec/go.dag`, `spec/python.dag` has
a populated `clean_emission` field.
- The unused-pattern-binding rule fires end-to-end: a test program
with `match x { Value(v) => 0, ... }` produces Rust with
`Behavior::Value(_) => 0` (not `Value(v)`), and `unused_variables`
is removed from the test-wrapper allow list for that specific case.
- Zero new `#[allow(...)]` attributes added anywhere in the codebase
during this lane.
Stage 1c is done when the following hold across its PRs.

**PR 1 (Rust pilot + contract type system) — gates:**

- DB-4 (`docs/design-clean-emission-contract.md`) exists with the
E-5 invariant framing, the 8-rule `CleanEmissionContract` type
table, per-target rule choices, and the "reject post-emission
cleanup" rationale. (Already landed; referenced here.)
- `INVARIANTS.md` has an E-5 entry referencing DB-4 and this stage
doc.
- `std/clean_emission.dag` declares the 8-rule contract type plus
each rule's coproduct (with `NotApplicable` variants where
relevant).
- `spec/rust.dag` declares `rust_clean_emission: CleanEmissionContract`
populated with concrete rule variants per DB-4.
- `dag.rs` caches `rust_clean_emission` in `TargetSyntaxCache` with
an accessor on `Dag`.
- `emit_rust.rs` parses the contract into a typed binding and
dispatches `PatternBindingRule::EmitUnderscoreWhenUnused` in
`render_branch_pattern`. Port-liveness walk determines binding use.
- A targeted test under `#[deny(unused_variables)]` compiles a
match-with-unused-payload and asserts rustc accepts the emitted
code (i.e. the pilot emits `_` and no unused-variable warning
fires).
- Zero new `#[allow(...)]` attributes added in this PR.

**PR 2 (Go + Python pilots) — gates:**

- `spec/go.dag` / `spec/python.dag` each declare their
`*_clean_emission` data item.
- `emit_go.rs` / `emit_python.rs` each dispatch their
`pattern_bindings` rule. Per-target surface: Go emits `_` for the
blank-identifier path; Python dispatches
`EmitPrefixedUnderscoreWhenUnused` (`_v` convention).
- Targeted tests per target mirror the Rust pilot.

**PR 3 (post_emit_verifier CI gate) — gates:**

- Test harness reads `post_emit_verifier` from each target's
contract and invokes it (Rust: rustc with `-D warnings`; Go:
gofmt; Python: py_compile).
- `unused_variables` removed from each test-wrapper
`#[allow(warnings, clippy::all)]` umbrella (replaced with an
explicit residual list naming only the not-yet-structurally-fixed
categories).
- CI fails on any warning diagnostic the verifier emits.

**Cross-stage gate:** zero new `#[allow(...)]` attributes added
anywhere during Stage 1c. Existing umbrella allow lists narrow
monotonically as each rule lands.

---

Expand Down Expand Up @@ -260,31 +327,22 @@ designing toward.

---

## Candidate companion invariants (E-6, E-7, E-8)

Half B's principle audit proposed three additional invariants that
predate Lane 1e consolidation. Evaluate for INVARIANTS.md inclusion
alongside E-5:

**E-6 — No target-spec field lands without a same-PR consumer.** If
`rust_foo: FooType` is added to `src/v3/spec/rust.dag`, the emitter
change that CONSUMES `rust_foo` lands in the same PR. Prevents
"declared-facts-not-wired" drift (the pattern that produced B-NEW-2
and B-NEW-3 as Half B follow-up commits).

**E-7 — No target-private realization schema lands without a
dissolution ratchet.** If a target-specific type (e.g.,
`PythonPatternRealization`) is added, the PR lists the path to
dissolve it into a target-agnostic substrate fact. Permanent
per-target types are allowed with explicit receipt.

**E-8 — Unsupported core behaviors fail closed; never collapse
semantically.** When an emitter encounters a core Behavior variant
it doesn't support, it returns `EmitError::UnsupportedBehavior` —
not a semantic approximation (like rendering `Loop` as its body's
result port). Half B just enforced this for Loop in emit_go /
emit_python.

Lane 1c evaluates these alongside E-5. Each has a mechanical gate
path (grep / PR-review-checklist / test-based). Adoption
individually decided; the three form a coherent set with E-5.
## Companion invariants (historical — already landed)

Half B proposed three emission-discipline invariants that were
originally listed here as "candidates to evaluate alongside E-5."
All three landed in `INVARIANTS.md` ahead of this stage:

- **E-6** — No target-spec field lands without a same-PR consumer.
(PR #493, 2026-04-16.)
- **E-7** — No target-private realization schema lands without a
dissolution ratchet. (PR #493, 2026-04-16.)
- **E-8** — Unsupported core behaviors fail closed; never collapse
semantically. (PR #493, 2026-04-16.)

**E-9** — External realization lives on `Arrow.body` — landed in
PR #497, 2026-04-17.

This section is retained as a pointer so readers of the original
stage doc know these invariants are load-bearing and already
enforced; Stage 1c does not re-evaluate them.
6 changes: 6 additions & 0 deletions src/v3/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,12 @@ Sub-stage status (as of 2026-04-17):

**Deferral: 1b full implementation (M).** 1b's first attempt escalated (PR #495 shipped 1a; 1b code was reverted). Root cause: `.dag` linear-walk bodies for substrate accessors polluted every user DAG. DB-14 codifies the correct pattern (ExternalRealization mirroring pipeline.dag). Unblocked once DB-14 (PR #497) lands. Design: [design-substrate-external-primitives.md](../../docs/design-substrate-external-primitives.md) (DB-14). Acceptance in DB-14 §Acceptance.

### Lane 1 Stage 1c

**Deferral: 1c Go + Python pilots (S).** Stage 1c PR 1 shipped the Rust pilot (`PatternBindingRule::EmitUnderscoreWhenUnused`), the `CleanEmissionContract` type system (8 rules in `src/v3/std/clean_emission.dag`), `rust_clean_emission` in `spec/rust.dag`, and E-5 in `INVARIANTS.md`. Remaining: add `go_clean_emission` / `python_clean_emission` data items and wire each emitter's `pattern_bindings` dispatch (Go: blank-identifier `_`; Python: prefixed `_v` convention). Separate PR because emit_go and emit_python render bindings on different surface (`{x} := {expr};` and implicit local respectively) — structurally distinct from Rust's `render_branch_pattern`. **Yellow-flag threshold: 1 week.** Design: [phase1-lane2-clean-emission-invariant.md §Scope split](../../docs/phase1-lane2-clean-emission-invariant.md).

**Deferral: 1c post_emit_verifier CI gate (S).** Wire test harness to read `post_emit_verifier.args` from each target's contract and invoke it as a hard gate (Rust: `rustc -D warnings`; Go: `gofmt -l`; Python: `python3 -m py_compile`). Also narrow the test-wrapper `#[allow(warnings, clippy::all)]` umbrella to strike `unused_variables` once Rust + Go + Python pilots all dispatch the rule. Separate PR because the harness change is distinct infrastructure; correctness of rule dispatch is already proved by the pilot's `#[deny(unused_variables)]` test. **Yellow-flag threshold: 2 weeks.** Design: [phase1-lane2-clean-emission-invariant.md §Acceptance gates](../../docs/phase1-lane2-clean-emission-invariant.md).

### Cross-cutting — performance

**Deferral: self-compile perf ratchet investigation (M, not on any critical path but compounding).** Self-compile time drifted from ~60s to ~70s in recent cycles (~16% growth). The ratchet keeps getting bumped without a root-cause investigation; each bump normalizes the regression. Scope: (1) profile a single `cargo test -p v3-compiler-tests` run, identify the top hot paths; (2) measure where the 10s came from across recent PRs (bisect across #479, #489, #490 if signal is unclear); (3) either fix the regression or document it as an accepted cost with a new ratchet ceiling. **Yellow-flag threshold: 90s.** If self-compile exceeds that before this deferral is scheduled, it preempts other work. No design doc needed; profiling is a data-gathering exercise.
Expand Down
Loading
Loading