Skip to content

Commit f9e4f04

Browse files
committed
feat(d5): OWN051 + real optimistic silence — untrack a local at a may/unknown call (TZ D6)
d5 §5's optimistic default says an unverified-ownership call site resolves to 'the caller no longer owns' -> silence. The implementation lowered may/unknown contracts to a PLAIN arg instead — which is not silence: plain leaves the obligation with the caller, so DROPPING a local after a may-call fabricated OWN001. The channel predates D1 (conditional forwards), but the D1 fix widened it to every null-guard dispose helper: 'var r = new X(); Cleanup(r);' — the normal usage, Cleanup IS the disposer — read as a leak. Untrack makes the default real: _unverified_transfer_calls collects every arg at a may/unknown position of a summarized callee; such locals are not minted at all (acquire / fresh result / alias target skipped, branch-hoist excluded), so neither a missing nor a defensive dispose after the call can be charged. A call with may/unknown positions routes through the existing per-argument $consume/$borrow channel (the overload path, now shared) so an untracked name is never referenced in emitted code — the first run's loud OWN030 (map-or-raise doing its job) proved why. Verified contracts are untouched: borrow-drop keeps its true OWN001 (T3) and consume-reuse its OWN002 (T2), both pinned. The gap is now honest instead of silent-or-wrong: advisory OWN051 ('ownership transfer unverified — local not checked past this call') at the call site, gated on args that actually carry an obligation (acquired or fresh-factory locals — no noise for plain values), advisory like OWN050/052: warning, SARIF note, never the exit code, hidden at --verbosity quiet. explain OWN051 answers. Seven existing may-shape tests updated from 'empty' to 'exactly one OWN051 advisory'; three new tests pin the closed FP, the preserved T3 recall, and the owned-local gate. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBmDyLWHqoQUGqiydSxroi
1 parent c6262c0 commit f9e4f04

6 files changed

Lines changed: 253 additions & 48 deletions

File tree

‎docs/notes/interprocedural-roadmap.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,10 @@ d5-заметка ставит advisory в хвост (D5.x); эта карта
147147
и главный ответ на «непонятки». Вся фактура уже считается (§5 d5: «we compute
148148
the full must/may/escape evidence regardless of mode»), не хватает поверхности:
149149

150-
- **OWN051** (OWN05x-band, как OWN050): `transfer:may` и honest-`unknown`
151-
показываются с `--verbosity normal`+, никогда не валят CI.
150+
- **OWN051** ✅ *(shipped)*: владелец, переданный на `may`/`unknown`-позицию,
151+
оптимистично перестаёт отслеживаться (ТЗ D6 — настоящее «молчание», а не
152+
plain), и это честно фиксируется advisory OWN051 на месте вызова — warning в
153+
выводе, `note` в SARIF, никогда не rc; `--verbosity quiet` скрывает.
152154
- **Дамп сводок** ✅ *(shipped)*: глагол `python -m ownlang summaries facts.json`
153155
— один детерминированный JSON-документ (сводки по ключу метода + extern-лог +
154156
`degraded`), байт-стабильный под перестановкой входа; это и отладочная

‎docs/notes/interprocedural-tz.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,9 @@ OWN001 в самом хелпере. Это удар ровно по полу `o
173173
**Решение (принять до порта — иначе bit-parity заставит Rust воспроизводить
174174
баг как норму):**
175175

176+
- ⚠ Дополнение пост-фактум: вариант A сам по себе **расширяет** D6-канал
177+
(may-параметры множатся) — он полон только вместе с untrack-семантикой D6.
178+
Оба шага сделаны; см. D6 ниже.
176179
- **Вариант A (рекомендуемый): ветко-чувствительная деривация release.**
177180
Release на всех путях → `[dispose]`; на части путей → `[dispose, borrow]`
178181
(join ⇒ `may` ⇒ plain на call-site — молчание); прямая инференция
@@ -226,6 +229,27 @@ all-paths ⇒ may); release + throw-ветка (по политике `--flow-lo
226229
в ТЗ этапа 3 (§6.2) — как ограничение первого среза: применение `aliasOf:i`
227230
только на прямом вызове, без переиндексации через цепочку.
228231

232+
### D6 (обнаружено при реализации OWN051): `may`/`unknown` → plain — это не молчание
233+
234+
Политика §5 d5 требует: неизвестный контракт ⇒ optimistic ⇒ **тишина**. Но
235+
реализация опускала `may`/`unknown` в plain-эффект — а plain оставляет
236+
обязательство у вызывающего: **брошенный** после `may`-вызова ресурс давал
237+
OWN001. Канал существовал до D1 (условные forward'ы), а фикс D1 его расширил:
238+
нормальное использование null-guard-хелпера (`Cleanup(r)` без dispose после —
239+
хелпер и есть освободитель) стало ложным OWN001.
240+
241+
> **Статус: исправлено (untrack).** Аргумент на `may`/`unknown`-позиции
242+
> суммаризированного callee **прекращает отслеживаться** в вызывающем
243+
> (`_unverified_transfer_calls` + гейты в лоуэринге: acquire/fresh/alias не
244+
> минтятся, hoist исключён): ни пропущенный, ни защитный dispose после такого
245+
> вызова не наказуем. Вызов с `may`/`unknown`-позициями эмитится через
246+
> по-аргументные `$`-каналы (расширение M3-маршрутизации) — untracked-имя не
247+
> упоминается в эмитируемом коде (иначе map-or-raise OWN030, что и поймал
248+
> первый прогон). Проверенные контракты не тронуты: borrow-drop (T3 OWN001) и
249+
> consume-reuse (T2 OWN002) запиннены тестами. `$`-синки и несуммаризированные
250+
> callee не затронуты (первые — проверенные контракты, вторые экстрактор
251+
> escape-дропает сам).
252+
229253
### D5: сбой решателя молчит
230254

231255
`except Exception: mos = {}` (`ownir.py:906-909`) гасит **весь** межпроцедурный

‎ownlang/__main__.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,10 @@
2828
`--severity` (ownir only) picks how the host shows a finding — `error` (default,
2929
fails a build / red check) or `warning` (advisory). It is a presentation choice;
3030
the finding is still the core's verdict.
31-
`--verbosity` (ownir only) is `quiet` (errors only — hide the advisory OWN050
32-
"leakage analysis skipped" notes, P-014 Tier A), `normal` (default), or `verbose`
33-
(also print a per-code breakdown).
31+
`--verbosity` (ownir only) is `quiet` (errors only — hide the advisory notes:
32+
OWN050 "leakage analysis skipped", OWN051 "ownership transfer unverified",
33+
OWN052 "summaries skipped"), `normal` (default), or `verbose` (also print a
34+
per-code breakdown).
3435
3536
Exit code is non-zero if any error-level diagnostic was produced.
3637
"""
@@ -330,7 +331,7 @@ def cmd_ownir(path: str, fmt: str = "human", severity: str = "error",
330331
selects the surface: human (CLI), github (CI annotations), msbuild (VS),
331332
sarif (SARIF 2.1.0 log);
332333
`severity` picks how the host shows them (error/warning); `verbosity` is
333-
`quiet` (errors only — hide the advisory OWN050 notes), `normal` (default), or
334+
`quiet` (errors only — hide the advisory OWN05x notes), `normal` (default), or
334335
`verbose` (also print a per-code breakdown)."""
335336
from .ownir import OwnIRError, build_sarif, check_facts, load, render_finding
336337
try:

‎ownlang/diagnostics.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ class Severity(Enum):
8080
"OWN041": "call argument mismatch",
8181
# ---- C# front-end resolution coverage (P-014; advisory) ----
8282
"OWN050": "declaring type unresolved -- leakage analysis skipped",
83+
"OWN051": "ownership transfer unverified -- local not checked past this call",
8384
"OWN052": "interprocedural summary inference failed -- method summaries skipped",
8485
# ---- DI container lifetimes (P-006; emitted by the OwnIR bridge) ----
8586
"DI001": "captive dependency: a shorter-lived service is captured by a longer-lived one",
@@ -152,6 +153,18 @@ class Severity(Enum):
152153
"Fix (to check it): give the extractor the type's assembly via `--ref-dir <bin>` so the "
153154
"SemanticModel can bind the event."
154155
),
156+
"OWN051": (
157+
"Advisory, not a leak verdict: an owned local was passed to a method whose ownership "
158+
"contract for that argument could not be verified — the inferred transfer is `may` "
159+
"(the callee disposes it on some paths only) or `unknown` (the evidence crosses an "
160+
"unanalyzable boundary). Per the optimistic default (own-only 0) the checker assumes "
161+
"ownership left the caller and stops tracking the local at that call: a missing "
162+
"dispose after it is NOT reported, and neither is a defensive one. This note is the "
163+
"honest record of that gap. It never fails a build.\n"
164+
"Fix (to make it checkable): make the callee's contract definite — dispose the "
165+
"parameter on every path (or none), or annotate the intended contract when "
166+
"annotations land (P-005 Tier C)."
167+
),
155168
"OWN052": (
156169
"Advisory, not a leak verdict: computing the method ownership summaries (the "
157170
"interprocedural pass that resolves cross-method ownership transfer) failed, so the "

0 commit comments

Comments
 (0)