Skip to content

Commit 5ceb4b2

Browse files
committed
fix(core): loud loan-invariant raise + fail-loud on unknown diagnostic code
Track A (contract hardening), continued. - analysis.join(): the block-scoped-loan invariant was a bare `assert`, stripped by `python -O` (a silently-wrong merge if block-scoping is ever relaxed). Now an explicit `if … raise AssertionError`, mirroring _join_handle_rid. (N9) - Diagnostic now validates its code at construction: a code absent from TITLES raises ValueError instead of silently rendering an empty title. The full suite confirms every emitted code is registered; `title` indexes instead of `.get(..., "")`. Closes the one stringly-typed contract's silent-"" hole cheaply (a full StrEnum is the heavier follow-up). Pinned by test_diagnostics. (N6) - Register: mark N1/N4/N6/N9 done; re-scope N8 — a dedicated syntax-error code is NOT surgical (OWN020 is the suite-wide parse/lex-rejection code, entangled with the lexer's rejected-keyword mechanism and ~6 test helpers). Refs docs/notes/tech-debt-register.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FJSfUpRbRXegrwJNV1rx1X
1 parent 10d8c41 commit 5ceb4b2

4 files changed

Lines changed: 46 additions & 11 deletions

File tree

‎docs/notes/tech-debt-register.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -186,17 +186,21 @@ Python walkers (§2.1).
186186

187187
### Now (standalone value; days-scale; ordered by protection-per-effort)
188188

189+
> **Progress (branch `claude/ownir-contract-hardening`):** N1 ✅, N4 ✅ (spec
190+
> shipped; JSON Schema still pending), N6 ✅ (validation, not a full enum — see
191+
> below), N9 ✅. N8 re-scoped (not surgical — see note). The rest stand.
192+
189193
| # | Item | Where | Why now |
190194
|---|------|-------|---------|
191-
| N1 | `else: raise` on unknown flow ops (+ the five walkers) | `ownlang/ownir.py:1692-1836` | Silent fact-swallowing → fabricated/missed verdicts (§2.1) |
195+
| N1 ✅ | `else: raise` on unknown flow ops | `ownlang/ownir.py` `_lower_flow` | Silent fact-swallowing → fabricated/missed verdicts (§2.1). *Done: raises `OwnIRError`; pinned by test_ownir. The five read-only walkers legitimately ignore ops they don't consume, so the guard is scoped to `_lower_flow` (the only pass that must handle every op or lose facts).* |
192196
| N2 | Auto-discovery in the test runner | `tests/run_tests.py:1144-1149` | 25-term hand-rolled `or`; a forgotten `rc` silently stops gating |
193197
| N3 | Golden facts snapshots in CI + feed to `test_ownir.py` | `ci.yml` wpf-extractor job | The seam is never diffed at the facts level (§2.2) |
194-
| N4 | `spec/OwnIR.md` + JSON Schema + evolution policy | new; `ownir.py:1-97` is the source | §2.3–2.4 |
198+
| N4 ◑ | `spec/OwnIR.md` ✅ + JSON Schema (pending) + evolution policy ✅ | `spec/OwnIR.md` | §2.3–2.4. *Done: normative spec incl. the version evolution policy (IR1–IR6), registered in `spec/README.md`. Still to do: `spec/ownir.schema.json` + CI fixture validation.* |
195199
| N5 | DI001–005 + EFF001 into `spec/` + `Diagnostics.md` + `test_spec.py` | `ownlang/di.py`, `effects.py` | Second-largest analyzer has zero normative governance |
196-
| N6 | Diagnostic `Code` enum (replace bare string literals) | `ownlang/diagnostics.py:243` + emit sites | New codes land weekly; a typo'd code silently renders `""` |
200+
| N6 ✅ | Fail-loud on unknown diagnostic code | `ownlang/diagnostics.py` `Diagnostic.__post_init__` | New codes land weekly; a typo'd code silently rendered `""`. *Done: `Diagnostic` now rejects any code absent from `TITLES` at construction (full suite confirms every emitted code is registered), and `title` indexes instead of `.get(...,"")`. A full `StrEnum` is the heavier follow-up; this closes the silent-`""` hole cheaply.* |
197201
| N7 | Split `ownir.py` → `ownir/{render,load,lower,inference,check}` | `ownlang/ownir.py` (2430 lines) | Fastest-accreting file in the repo; `check_facts` grows a branch per resource kind; deferring = paying the god-file tax on every feature |
198-
| N8 | Dedicated syntax-error code (stop filing `ParseError` as OWN020) | `ownlang/__main__.py:80` | Miscategorized as "unsupported construct" |
199-
| N9 | Bare `assert` on the loan invariant → raise | `ownlang/analysis.py:200-203` | Stripped under `python -O`; silent wrong answer if block-scoping is ever relaxed |
202+
| N8 ⚠️ | Dedicated syntax-error code (stop filing `ParseError` as OWN020) | `ownlang/__main__.py:80` | **Re-scoped: not surgical.** OWN020 is the suite-wide code for *any* parse/lex rejection — `for`/`loop`/`async` are lexer-*rejected keywords* (LexError → OWN020 by design), and the corpus/gallery/wpf/rid/loops test helpers all treat OWN020 as "parse rejected". Splitting a genuine syntax error from an unsupported-construct rejection means distinguishing the two at the lexer/parser and updating ~6 test files + `Grammar.md`/`CLI.md`/`OwnCore.md`. A real UX win, but a small refactor, not a one-liner. |
203+
| N9 ✅ | Bare `assert` on the loan invariant → raise | `ownlang/analysis.py` `join()` | Stripped under `python -O`. *Done: mirrors the explicit-raise pattern already used at `_join_handle_rid`, so the invariant holds in every build.* |
200204
| N10 | Reconcile/document BCL table asymmetry | `Program.cs:2545-2568` vs `ownir.py:1179-1199` | Lockstep already quietly diverged (§2.6) |
201205

202206
### With next touch

‎ownlang/analysis.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -197,10 +197,14 @@ def join(a: State, b: State) -> State:
197197
# holds across loop back-edges too: a borrow opened inside a loop body closes
198198
# within the same iteration, so the loan set at the body exit equals the one on
199199
# the entry edge. Assert the invariant rather than paper over a builder bug.
200-
assert set(a.loans) == set(b.loans), (
201-
"active loans differ at a control-flow merge; this should be impossible "
202-
"for block-scoped borrows (they close within the scope that opened them)"
203-
)
200+
# An explicit raise, not `assert`: `python -O` strips asserts, and a silently
201+
# mismatched loan set at a merge would defeat the invariant this locks (same as
202+
# `_join_handle_rid` above). Keep it loud in every build.
203+
if set(a.loans) != set(b.loans):
204+
raise AssertionError(
205+
"active loans differ at a control-flow merge; this should be impossible "
206+
"for block-scoped borrows (they close within the scope that opened them)"
207+
)
204208
out.loans = dict(a.loans)
205209
out.handle_rid = _join_handle_rid(a.handle_rid, b.handle_rid)
206210
out.moved_at = _join_sites(a.moved_at, b.moved_at)

‎ownlang/diagnostics.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,9 +239,20 @@ class Diagnostic:
239239
# contract (code, message, line, severity, subject, resource_kind) is preserved.
240240
evidence: tuple[Evidence, ...] = ()
241241

242+
def __post_init__(self) -> None:
243+
# A code with no TITLES entry is a bug, not a blank finding: `title` used to
244+
# silently return "" for a typo'd or forgotten code. Fail loudly at
245+
# construction so a mis-typed code can never ship a titleless diagnostic —
246+
# the one stringly-typed contract in a --strict codebase.
247+
if self.code not in TITLES:
248+
raise ValueError(
249+
f"unknown diagnostic code {self.code!r} (not in diagnostics.TITLES); "
250+
f"a code and its title must be added together"
251+
)
252+
242253
@property
243254
def title(self) -> str:
244-
return TITLES.get(self.code, "")
255+
return TITLES[self.code]
245256

246257
def _kind_suffix(self) -> str:
247258
return f" [resource: {self.resource_kind}]" if self.resource_kind else ""

‎tests/test_diagnostics.py‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
3030

3131
from ownlang import evidence
32-
from ownlang.diagnostics import Diagnostic, Evidence
32+
from ownlang.diagnostics import TITLES, Diagnostic, Evidence
3333

3434
# a source whose line 3 names `b`, so render_pretty can place a caret under it.
3535
_SOURCE = "module M\nfn f() {\n use b;\n}\n"
@@ -146,12 +146,28 @@ def _evidence_builders() -> list[str]:
146146
return fails
147147

148148

149+
def _code_validation() -> list[str]:
150+
"""A Diagnostic must reject a code with no TITLES entry, so a typo can never
151+
ship a titleless finding (the stringly-typed-code contract)."""
152+
fails: list[str] = []
153+
try:
154+
Diagnostic(code="OWN999", message="typo", line=1)
155+
fails.append("an unknown diagnostic code was accepted (should raise ValueError)")
156+
except ValueError:
157+
pass
158+
# a known code still constructs and titles correctly.
159+
if Diagnostic(code="OWN001", message="m", line=1).title != TITLES["OWN001"]:
160+
fails.append("a known code lost its title")
161+
return fails
162+
163+
149164
def run() -> int:
150165
"""Run every diagnostics-rendering case; return 0/1."""
151166
fails: list[str] = []
152167
fails += _empty_evidence_invariant()
153168
fails += _evidence_slice()
154169
fails += _evidence_builders()
170+
fails += _code_validation()
155171
for f in fails:
156172
print(f"DIAGNOSTICS FAIL: {f}")
157173
print(f"diagnostics: {'PASS' if not fails else 'FAIL'} "

0 commit comments

Comments
 (0)