Skip to content

Commit 76d29af

Browse files
committed
P-005 D5.3 / P1a: curated BCL fresh-factory table (producer side of Tier B)
C+D first slice — the producer half of the boundary contract. A leaked BCL factory result (`var s = File.OpenRead(p)`) was invisible because there is no first-party body to infer `fresh` from; now a curated table makes it owned. - ownir.py: `_BCL_FRESH_FACTORIES` (File.OpenRead/OpenText/OpenWrite/Open/Create/ CreateText/AppendText) + `_is_bcl_fresh_factory` (matches `Type.Method`, so a namespace-qualified callee resolves on its last two segments). New `_callee_returns_fresh` centralises the "does this call yield a fresh owned result?" decision (Tier A first-party summary OR Tier B BCL table) and is now the single source of truth shared by the leak pre-scan, the branch-hoist safety walk, and the flow lowering — so all three agree. - A leaked factory result is OWN001 at the call; disposed is clean; use-after-dispose is OWN002; it composes with the P-015 codeFlows slice (the finding anchors at the factory call). Pure factories only — overload-ambiguous wrappers that adopt an arg (`new StreamReader(stream)`) stay out (sink/T4). - The leaveOpen *sink* breadth rides the existing $consume/$borrow channel and is extractor-side (the bool literal is a per-call-site fact), so it is CI/C#-only; documented as the remaining half in d5-ownership-transfer.md §7. Tests: leak / disposed-clean / use-after-dispose / namespace-qualified / a non-disposable `File.ReadAllText` making no claim. ownir 174/174; ruff + mypy clean. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KkpSWNx7ARLpQeAs13kkyA
1 parent 1e8bb8b commit 76d29af

3 files changed

Lines changed: 95 additions & 7 deletions

File tree

‎docs/notes/d5-ownership-transfer.md‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,8 +333,24 @@ escape-without-transfer and all `unknown`/`may` lower to **silence** in the defa
333333
cumulative), and the early-return guard shape (`guard` — stays a loud OWN030 raise rather than a
334334
false positive). (Bridge branch-scope fix: Codex P2 on #116; loop exclusion Codex P1, hoist
335335
safety predicate + pool-kind preservation CodeRabbit on #120.)
336-
- **D5.3 — Tier B breadth.** The rest of the documented BCL ownership table + `fresh`
337-
factories.
336+
- **D5.3 — Tier B breadth.**
337+
- **Producer side — `fresh` factories (shipped, first slice).** A curated
338+
`_BCL_FRESH_FACTORIES` table in the OwnIR bridge (`ownir.py`) marks well-known BCL
339+
factories whose return the caller owns (`File.OpenRead/OpenText/OpenWrite/Open/Create/
340+
CreateText/AppendText`). A `call` to one binds a `fresh` result via the SAME `_callee_
341+
returns_fresh` path the first-party T1 inference uses (now the single source of truth for
342+
the leak pre-scan, branch-hoist safety, and lowering), so a leaked `var s =
343+
File.OpenRead(p)` surfaces as OWN001 *at the factory call* — invisible before (no body to
344+
infer from; see `corpus-benchmark.md`). Keyed by `Type.Method` (matches a namespace-
345+
qualified callee on its last two segments). Pure factories only — overload-ambiguous
346+
*wrappers* that adopt an arg (`new StreamReader(stream)`) are excluded (sink/T4). Tests in
347+
`test_ownir.py` (leak / disposed-clean / use-after-dispose / namespace-qualified / a
348+
non-disposable `File.ReadAllText` correctly making no claim).
349+
- **Sink side — `leaveOpen` breadth (remaining, extractor-side).** The documented
350+
consume/borrow table (`StreamReader`/`StreamWriter`/`CryptoStream`/… by the `leaveOpen`
351+
bool literal) rides the existing `$consume`/`$borrow` channel (D5.1b); its breadth is a
352+
C#-extractor table (the bool literal is a per-call-site fact the extractor sees), so it is
353+
CI/C#-only, not a pure-Python slice.
338354
- **D5.4 — T4 wrap/adopt** (the obligation-identity model, §11). Lands in a **three-commit
339355
cadence** so the core change is de-risked: **(step 0)** a *no-op identity refactor* —
340356
move resource state from per-binding to per-RID with a 1:1 binding↔RID mapping, behaviour

‎ownlang/ownir.py‎

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1095,6 +1095,42 @@ def _infer_return_skeleton(nodes: Any, param_names: set[str]) -> ReturnSkeleton:
10951095
_SINK_PATH_ACTION = {"$consume": "dispose", "$borrow": "borrow"}
10961096

10971097

1098+
# Tier B (P-005 D5.3 / P1a contracts): a curated table of well-known BCL *factories* whose
1099+
# return the caller OWNS — the producer half of the boundary contract (the consume/borrow
1100+
# *sink* half rides the `$consume`/`$borrow` channel above). These are pure factories: the
1101+
# result is a fresh owned `IDisposable` and the arguments are not resources, so a leaked
1102+
# `var s = File.OpenRead(p)` now surfaces as an OWN001 leak AT the factory call — it was
1103+
# invisible before (no body to infer `fresh` from; see docs/notes/corpus-benchmark.md).
1104+
# Overload-ambiguous *wrappers* that ADOPT an argument (e.g. `new StreamReader(stream)`) are
1105+
# deliberately excluded — that is the sink / T4 case, not a pure factory. Keyed by
1106+
# `Type.Method`; a callee matches on its last two dotted segments so a namespace-qualified
1107+
# `System.IO.File.OpenRead` resolves the same.
1108+
_BCL_FRESH_FACTORIES = frozenset({
1109+
"File.OpenRead", "File.OpenText", "File.OpenWrite",
1110+
"File.Open", "File.Create", "File.CreateText", "File.AppendText",
1111+
})
1112+
1113+
1114+
def _is_bcl_fresh_factory(callee: str) -> bool:
1115+
"""True if `callee` names a curated BCL factory whose return the caller owns. Matches
1116+
the bare `Type.Method` or any namespace-qualified form of it (its last two segments)."""
1117+
if not callee:
1118+
return False
1119+
return (callee in _BCL_FRESH_FACTORIES
1120+
or ".".join(callee.split(".")[-2:]) in _BCL_FRESH_FACTORIES)
1121+
1122+
1123+
def _callee_returns_fresh(callee: str, mos: dict[str, Any] | None) -> bool:
1124+
"""Whether a `call` to `callee` yields a fresh owned result the caller must release —
1125+
a first-party summary that returns `fresh` (Tier A) OR a curated BCL factory (Tier B).
1126+
The single source of truth shared by the leak pre-scan, the branch-hoist safety walk,
1127+
and the flow lowering, so all three agree on what counts as an acquire."""
1128+
if _is_bcl_fresh_factory(callee):
1129+
return True
1130+
summ = mos.get(callee) if (mos is not None and callee) else None
1131+
return summ is not None and getattr(summ, "returns", None) == "fresh"
1132+
1133+
10981134
def _param_signals(pname: str, nodes: Any) -> tuple[bool, bool, bool]:
10991135
"""Scan a flow body for how parameter `pname` is treated, returning
11001136
(released, handed-to-a-call, used). Recurses into if/while branches so a
@@ -1327,8 +1363,7 @@ def acquires(n: dict[str, Any]) -> bool:
13271363
if n.get("op") == "acquire" and str(n.get("var", "")) == name:
13281364
return True
13291365
if n.get("op") == "call" and str(n.get("result", "")) == name:
1330-
summ = mos.get(str(n.get("callee", ""))) if mos is not None else None
1331-
return summ is not None and getattr(summ, "returns", None) == "fresh"
1366+
return _callee_returns_fresh(str(n.get("callee", "")), mos)
13321367
return False
13331368

13341369
def analyze(seq: Any, acquired: bool) -> tuple[bool, bool]:
@@ -1396,8 +1431,7 @@ def fresh_result(n: dict[str, Any]) -> str | None:
13961431
callee, res = n.get("callee"), n.get("result")
13971432
if not (isinstance(res, str) and res and isinstance(callee, str) and callee):
13981433
return None
1399-
summ = mos.get(callee) if mos is not None else None
1400-
return res if (summ is not None and getattr(summ, "returns", None) == "fresh") else None
1434+
return res if _callee_returns_fresh(callee, mos) else None
14011435

14021436
def note_ref(name: str, depth: int) -> None:
14031437
if name not in ref_depth or depth < ref_depth[name]:
@@ -1561,7 +1595,7 @@ def _lower_flow(nodes: list[Any], ffile: str, fname: str,
15611595
if isinstance(result, str) and result and result not in hoisted:
15621596
localmap.pop(result, None)
15631597
if (isinstance(result, str) and result and result not in hoisted
1564-
and summ is not None and getattr(summ, "returns", None) == "fresh"):
1598+
and _callee_returns_fresh(callee, mos)):
15651599
handle = f"loc_{loc[0]}"
15661600
loc[0] += 1
15671601
localmap[result] = handle

‎tests/test_ownir.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1513,6 +1513,44 @@ def _sub(source: str | None) -> list[Finding]:
15131513
f"got {[(x.component, x.code) for x in unk]}")
15141514
except OwnIRError as e:
15151515
fails.append(f"D5.2: a call to an unknown callee must not crash (OWN040), got {e!r}")
1516+
# Tier B (D5.3 / P1a): a curated BCL *factory* (`File.OpenRead` &c.) returns an owned
1517+
# IDisposable even with no first-party body, so a leaked `var s = File.OpenRead(p)` is
1518+
# OWN001 AT the factory call (invisible before this table) — the producer half of the
1519+
# boundary contract. Contrast the unknown-callee case just above, which makes no claim.
1520+
def _bcl(body: list) -> list:
1521+
return check_facts({"module": "M", "functions": [
1522+
{"name": "Svc.Do", "file": "Bcl.cs", "body": body}]})
1523+
checks += 1
1524+
bleak = [(x.code, x.line, x.kind) for x in _bcl(
1525+
[{"op": "call", "callee": "File.OpenRead", "args": ["p"], "result": "s", "line": 5}])]
1526+
if bleak != [("OWN001", 5, "disposable")]:
1527+
fails.append(f"Tier B: a leaked BCL factory result must be OWN001@5 disposable, "
1528+
f"got {bleak}")
1529+
checks += 1
1530+
if _bcl([{"op": "call", "callee": "File.OpenRead", "args": ["p"], "result": "s", "line": 5},
1531+
{"op": "release", "var": "s", "line": 6}]):
1532+
fails.append("Tier B: a disposed BCL factory result must be clean (silent)")
1533+
checks += 1
1534+
buar = [(x.code, x.line) for x in _bcl(
1535+
[{"op": "call", "callee": "File.OpenRead", "args": ["p"], "result": "s", "line": 5},
1536+
{"op": "release", "var": "s", "line": 6},
1537+
{"op": "use", "var": "s", "line": 7}])]
1538+
if buar != [("OWN002", 5)]:
1539+
fails.append(f"Tier B: using a BCL factory result after dispose must be OWN002@5, "
1540+
f"got {buar}")
1541+
checks += 1
1542+
# a namespace-qualified callee resolves on its last two segments (`Type.Method`).
1543+
nsq = [(x.code, x.line) for x in _bcl(
1544+
[{"op": "call", "callee": "System.IO.File.Create", "args": ["p"],
1545+
"result": "s", "line": 9}])]
1546+
if nsq != [("OWN001", 9)]:
1547+
fails.append(f"Tier B: a namespace-qualified BCL factory must resolve, got {nsq}")
1548+
checks += 1
1549+
# a non-disposable BCL method (`File.ReadAllText` -> string) is NOT a factory — no false
1550+
# acquire of its result, stays silent (precision-first: the table is owned-returns only).
1551+
if _bcl([{"op": "call", "callee": "File.ReadAllText", "args": ["p"],
1552+
"result": "t", "line": 3}]):
1553+
fails.append("Tier B: a non-disposable BCL method must not be treated as a factory")
15161554
# OVERWRITE kills the prior binding (CodeRabbit): `acquire x; x = Unknown(); release x`
15171555
# — the call's result reuses an owned local and the call is dropped (unknown callee),
15181556
# so the ORIGINAL x leaks (its reference is lost), not read as clean. The release after

0 commit comments

Comments
 (0)