Skip to content

Commit c6262c0

Browse files
committed
feat(d5): summaries verb — deterministic MOS dump (roadmap stage 1, parity surface)
'python -m ownlang summaries facts.json' prints the solved Method Ownership Summaries plus the extern-boundary log as one deterministic JSON document: summaries sorted by method key, the unresolved log sorted by solve_with_log, fixed field order — byte-identical output under any functions[] input permutation (pinned by test). Two consumers, one contract: the debugging answer to 'why did this call stay plain/consume/fresh' without reading bridge code, and the frozen surface the Rust port of the inference layer will be diffed against — summary- level parity is finer than diffing final diagnostics, where an inference bug can hide behind an unrelated silence. Skeletons now carry the declaring file from the facts (merged overloads take the smallest (file, line) pair so the dump stays input-order- independent); a failed solve degrades exactly like the checking path — empty summaries with the reason in 'degraded', rc stays 0 (the surface reports state, it does not judge), rc 2 only for unreadable facts. Wiring into oracle_exact SURFACES rides with the Rust own-bridge consumer, which does not exist yet. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LBmDyLWHqoQUGqiydSxroi
1 parent 52b9c03 commit c6262c0

5 files changed

Lines changed: 140 additions & 8 deletions

File tree

‎docs/notes/interprocedural-roadmap.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,10 +149,11 @@ the full must/may/escape evidence regardless of mode»), не хватает п
149149

150150
- **OWN051** (OWN05x-band, как OWN050): `transfer:may` и honest-`unknown`
151151
показываются с `--verbosity normal`+, никогда не валят CI.
152-
- **Дамп сводок**: `MethodSummary.to_dict()` уже существует (сериализация
153-
`summaries[]` из d5 §6) — вывести таблицу MOS по флагу (`--dump-summaries`
154-
или в `explain`), плюс extern-границы из `solve_with_log`. Смотришь на метод —
155-
видишь, что решатель про него думает и почему вызов остался plain.
152+
- **Дамп сводок** ✅ *(shipped)*: глагол `python -m ownlang summaries facts.json`
153+
— один детерминированный JSON-документ (сводки по ключу метода + extern-лог +
154+
`degraded`), байт-стабильный под перестановкой входа; это и отладочная
155+
поверхность, и замороженный паритетный артефакт порта (ТЗ §5.4). Смотришь на
156+
метод — видишь, что решатель про него думает и почему вызов остался plain.
156157

157158
**Критерий готовности:** на любом прогоне можно ответить «почему этот вызов
158159
не consume/borrow/fresh» без чтения кода моста. С началом Rust-порта у этапа

‎docs/notes/interprocedural-tz.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,16 @@ Python-стороне — тот же ход, что уже сделан для
312312
(corpus hash + reference hash) поддерживает это без доработок. Это этап 1
313313
карты, переквалифицированный в артефакт порта.
314314

315+
> **Статус: Python-сторона заморожена.** Поверхность — глагол
316+
> `python -m ownlang summaries facts.json` (`dump_summaries` в `ownir.py`):
317+
> один детерминированный JSON-документ — сводки, отсортированные по ключу
318+
> метода (`file` наследуется из фактов; у слитых перегрузок — min по
319+
> (file, line), независимо от порядка входа), отсортированный extern-лог,
320+
> `degraded` с причиной при сбое решателя (rc остаётся 0 — поверхность
321+
> сообщает состояние, не судит). Байт-детерминизм под перестановкой
322+
> `functions[]` запиннен тестом. В `SURFACES` oracle_exact заводить вместе с
323+
> Rust-консюмером (`own-bridge`), которого ещё нет.
324+
315325
### 5.5 Порядок портирования внутри слоя
316326

317327
1. **Решатель** (чистый, без зависимостей): порт + property-тесты (монотонность

‎ownlang/__main__.py‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
python -m ownlang report file.own # buffer storage report + .ownreport.json
1010
python -m ownlang ownir facts.json # check OwnIR facts extracted from C# (P-001)
1111
python -m ownlang ownir facts.json --format github|msbuild|human|sarif
12+
python -m ownlang summaries facts.json # dump solved method-ownership summaries
13+
# (MOS) + extern log — deterministic JSON
1214
python -m ownlang explain OWN001 [DI002 ...] # explain diagnostic code(s): what/why/fix
1315
python -m ownlang explain --json findings.json # explain every code in a findings/SARIF file
1416
@@ -300,6 +302,27 @@ def cmd_explain(codes: list[str], json_path: str | None) -> int:
300302
return 0
301303

302304

305+
def cmd_summaries(path: str) -> int:
306+
"""Dump the solved Method Ownership Summaries (MOS) + the extern-boundary
307+
log for an OwnIR facts file as one deterministic JSON document on stdout
308+
(roadmap stage 1). The debugging answer to "why did this call stay plain /
309+
consume / fresh?" — and the frozen parity surface the Rust port of the
310+
inference layer is diffed against, so its output contract is byte-stable:
311+
sorted method keys, sorted extern log, fixed field order. Exit code is 0
312+
even when the solve degraded (the `degraded` field carries the reason —
313+
this surface reports state, it does not judge); 2 only for unreadable
314+
facts, like `ownir`."""
315+
import json
316+
from .ownir import OwnIRError, dump_summaries, load
317+
try:
318+
doc = dump_summaries(load(path))
319+
except OwnIRError as e:
320+
print(f"{path}: error: {e}", file=sys.stderr)
321+
return 2
322+
print(json.dumps(doc, indent=2, sort_keys=True))
323+
return 0
324+
325+
303326
def cmd_ownir(path: str, fmt: str = "human", severity: str = "error",
304327
verbosity: str = "normal") -> int:
305328
"""Check OwnIR facts (extracted from real C# by the Roslyn frontend) through
@@ -372,7 +395,8 @@ def cmd_ownir(path: str, fmt: str = "human", severity: str = "error",
372395

373396

374397
def main(argv: list[str]) -> int:
375-
if not argv or argv[0] not in {"check", "emit", "cfg", "report", "ownir", "explain"}:
398+
if not argv or argv[0] not in {"check", "emit", "cfg", "report", "ownir",
399+
"summaries", "explain"}:
376400
print(__doc__)
377401
return 2
378402
cmd = argv[0]
@@ -475,7 +499,8 @@ def main(argv: list[str]) -> int:
475499
return cmd_check(path, fmt, severity)
476500
if cmd == "cfg":
477501
return cmd_cfg(path, fmt)
478-
return {"emit": cmd_emit, "report": cmd_report}[cmd](path)
502+
return {"emit": cmd_emit, "report": cmd_report,
503+
"summaries": cmd_summaries}[cmd](path)
479504

480505

481506
if __name__ == "__main__":

‎ownlang/ownir.py‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,7 @@
153153
ReturnSkeleton,
154154
Transfer,
155155
solve,
156+
solve_with_log,
156157
)
157158

158159
# The OwnIR schema version this core understands. Bump it whenever the fact
@@ -1473,7 +1474,11 @@ def _merge_skeletons(group: list[MethodSkeleton]) -> MethodSkeleton:
14731474
params = tuple(
14741475
ParamSkeleton(i, names[i], True, tuple(by_index[i])) for i in sorted(by_index)
14751476
)
1476-
return MethodSkeleton(group[0].key, params, _merge_returns([sk.ret for sk in group]))
1477+
# the merged location must not depend on `functions[]` input order (the summary
1478+
# dump is a deterministic parity surface): take the smallest (file, line) pair.
1479+
floc = min((sk.file, sk.line) for sk in group)
1480+
return MethodSkeleton(group[0].key, params,
1481+
_merge_returns([sk.ret for sk in group]), floc[0], floc[1])
14771482

14781483

14791484
def _build_skeletons(raw_fns: list[Any]) -> list[MethodSkeleton]:
@@ -1569,7 +1574,10 @@ def _build_skeletons(raw_fns: list[Any]) -> list[MethodSkeleton]:
15691574
params.append(ParamSkeleton(i, cname, True, paths))
15701575
pnames = {str(p.get("name", "")) for p in raw_params if isinstance(p, dict)}
15711576
ret = _infer_return_skeleton(body, pnames, first_party)
1572-
by_key.setdefault(key, []).append(MethodSkeleton(key, tuple(params), ret))
1577+
# carry the declaration file so the summary dump is navigable (functions[]
1578+
# entries carry no line of their own — params do; line stays 0).
1579+
by_key.setdefault(key, []).append(
1580+
MethodSkeleton(key, tuple(params), ret, str(fn.get("file", "?"))))
15731581
# one skeleton per name: solve() keys by name (a forward names its callee with no
15741582
# signature), so same-name overloads are joined into a single conservative summary.
15751583
return [_merge_skeletons(group) for group in by_key.values()]
@@ -2027,6 +2035,44 @@ def _flow_local_steps(sub: dict[str, Any], code: str, dline: int,
20272035
return ((f, acq, origin), (f, dline, viol))
20282036

20292037

2038+
def dump_summaries(facts: dict[str, Any]) -> dict[str, Any]:
2039+
"""The MOS observability / parity surface (roadmap stage 1, TZ §5.4): derive
2040+
the skeletons, run the solver, and return the solved summaries plus the
2041+
extern-boundary log as ONE deterministic document.
2042+
2043+
Two consumers, one contract:
2044+
- a human asking "why did this call stay plain?" reads the method's summary
2045+
(transfer per param, return kind) and the `unresolved` extern boundaries
2046+
without reading bridge code;
2047+
- the Rust port of the inference layer is diffed against this document
2048+
(`oracle_exact`-style), which checks the port at the summary level — finer
2049+
than diffing final diagnostics, where an inference bug can hide behind an
2050+
unrelated silence.
2051+
2052+
Determinism is the contract: summaries are sorted by method key, the
2053+
unresolved log arrives sorted from `solve_with_log`, and `to_dict` field
2054+
order is fixed — the same facts yield byte-identical JSON regardless of
2055+
`functions[]` input order. A failed solve degrades exactly like
2056+
`check_facts` (empty summaries), with the reason in `degraded` — the same
2057+
honesty OWN052 gives the checking path."""
2058+
raw_fns = facts.get("functions", [])
2059+
raw_fns = raw_fns if isinstance(raw_fns, list) else []
2060+
degraded: str | None = None
2061+
summaries: dict[str, Any] = {}
2062+
unresolved: list[str] = []
2063+
try:
2064+
summaries, unresolved = solve_with_log(_build_skeletons(raw_fns))
2065+
except Exception as exc:
2066+
degraded = f"{type(exc).__name__}: {exc}"
2067+
return {
2068+
"module": str(facts.get("module", "?")),
2069+
"ownir_version": OWNIR_VERSION,
2070+
"summaries": [summaries[k].to_dict() for k in sorted(summaries)],
2071+
"unresolved": unresolved,
2072+
"degraded": degraded,
2073+
}
2074+
2075+
20302076
def check_facts(facts: dict[str, Any]) -> list[Finding]:
20312077
"""Run the core checker over the lowered facts and return findings mapped
20322078
back to their original C# locations (v0: the `event += without -=` leak).

‎tests/test_ownir.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1630,6 +1630,56 @@ def _boom(_sk): # type: ignore[no-untyped-def]
16301630
if gotlit != [("hand", 10, "OWN002")]:
16311631
fails.append("TZ D5: healthy solve must carry no OWN052 and keep the true "
16321632
f"OWN002, got {gotlit}")
1633+
# --- roadmap stage 1: the `summaries` dump (dump_summaries / `python -m
1634+
# ownlang summaries`). One deterministic document: solved MOS per method
1635+
# (sorted by key), the extern-boundary log (sorted), a `degraded` reason.
1636+
# This is the parity surface the Rust port of the inference layer will be
1637+
# diffed against, so its byte-stability IS the contract.
1638+
from ownlang.ownir import dump_summaries
1639+
_dump_facts = {"module": "M", "functions": [
1640+
{"name": "B.Fwd", "file": "b.cs", "params": [{"name": "s", "line": 1}],
1641+
"body": [{"op": "call", "callee": "Extern.Gone", "args": ["s"], "line": 2}]},
1642+
{"name": "A.Make", "file": "a.cs",
1643+
"body": [{"op": "acquire", "var": "r", "line": 1},
1644+
{"op": "return", "var": "r", "line": 2}]},
1645+
{"name": "C.Sink", "file": "c.cs", "params": [{"name": "x", "line": 1}],
1646+
"body": [{"op": "release", "var": "x", "line": 2}]}]}
1647+
checks += 1
1648+
doc = dump_summaries(_dump_facts)
1649+
keys = [s["method"] for s in doc["summaries"]]
1650+
kinds = {s["method"]: s["returns"]["owned"] for s in doc["summaries"]}
1651+
transfers = {s["method"]: [p["transfer"] for p in s["params"]]
1652+
for s in doc["summaries"]}
1653+
files = {s["method"]: s["file"] for s in doc["summaries"]}
1654+
if (keys != ["A.Make", "B.Fwd", "C.Sink"] # sorted by method key
1655+
or kinds["A.Make"] != "fresh" or transfers["C.Sink"] != ["must"]
1656+
or transfers["B.Fwd"] != ["unknown"]
1657+
or doc["unresolved"] != ["Extern.Gone#0 (extern, no summary)"]
1658+
or files["A.Make"] != "a.cs" or doc["degraded"] is not None):
1659+
fails.append(f"summaries dump content wrong: {doc}")
1660+
# byte-determinism: permuting `functions[]` input order must not change one byte
1661+
# of the canonical dump — this is what makes it a parity artifact, not a debug log.
1662+
checks += 1
1663+
blob1 = json.dumps(doc, indent=2, sort_keys=True)
1664+
_dump_facts["functions"].reverse()
1665+
blob2 = json.dumps(dump_summaries(_dump_facts), indent=2, sort_keys=True)
1666+
if blob1 != blob2:
1667+
fails.append("summaries dump must be byte-identical under functions[] "
1668+
"input permutation")
1669+
# a failed solve degrades the dump exactly like the checking path: empty
1670+
# summaries + the reason in `degraded` — never a crash, never a half-document.
1671+
checks += 1
1672+
_real_swl = _oi.solve_with_log
1673+
def _boom2(_sk): # type: ignore[no-untyped-def]
1674+
raise RuntimeError("synthetic dump failure")
1675+
_oi.solve_with_log = _boom2 # type: ignore[assignment]
1676+
try:
1677+
darkdoc = dump_summaries(_dump_facts)
1678+
finally:
1679+
_oi.solve_with_log = _real_swl
1680+
if (darkdoc["summaries"] != [] or darkdoc["unresolved"] != []
1681+
or "synthetic dump failure" not in (darkdoc["degraded"] or "")):
1682+
fails.append(f"degraded summaries dump wrong: {darkdoc}")
16331683
# (§10 q2) same-name OVERLOADS are merged, not dropped: when EVERY overload of a
16341684
# name consumes the forwarded arg, a forward to that name resolves to `must`, so a
16351685
# caller using the local after the handoff is OWN002. Before the merge the name was

0 commit comments

Comments
 (0)