Skip to content

Commit 099e73c

Browse files
committed
fix(d5): don't crash on unknown callees; FQ factory keys; preserve call args (CI fix + Codex/CodeRabbit)
The extractor's new call ops surfaced calls to callees not in functions[] (BCL / extension methods like GetRequiredService), which crashed check_facts with OWN040. Plus three review items: - (CI crash) Gate the Call emission on a RESOLVABLE callee (in the MOS or a sink extern); an unknown callee is dropped (no claim), never lowered to a Call that raises OWN040. Add OWN040 to the bridge-artifact skip list belt-and-suspenders. Regression test: a call to an unknown callee makes no claim and does not crash. - (Codex P2) Fully-qualify the factory summary key on BOTH sides ({Namespace.Type}.{Method} via FlowFunctionName + ContainingType.ToDisplayString) so two same-named factories across namespaces never alias into a false OWN001. - (CodeRabbit Major) Preserve the call's tracked identifier args instead of Array.Empty, so the core can apply the callee's per-argument effects. - (CodeRabbit Minor) Anchor the CI assertion to FactoryLeakSample.cs:<line> at the call site, not just any match of 'factoryLeak'. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Fmwk5ruExKy5fQ77CJ2NtF
1 parent 5291fa9 commit 099e73c

4 files changed

Lines changed: 66 additions & 8 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -827,8 +827,8 @@ jobs:
827827
# caller that binds the result and drops it leaks at the CALL SITE — a finding the flat,
828828
# intra-procedural detectors cannot see. The disposed caller and the factory itself stay
829829
# silent (the factory transfers ownership out via its return).
830-
echo "$out" | grep -qE "OWN001.*'factoryLeak'" \
831-
|| { echo "FAIL: expected the interprocedural OWN001 on the dropped factory result"; exit 1; }
830+
echo "$out" | grep -qE "FactoryLeakSample\.cs:[0-9]+:.*\[OWN001\].*'factoryLeak'" \
831+
|| { echo "FAIL: expected the interprocedural OWN001 on the dropped factory result at its call site"; exit 1; }
832832
for ok in factoryOk made; do
833833
if echo "$out" | grep -q "'$ok'"; then echo "FAIL: D5.2 silent case '$ok' was reported"; exit 1; fi
834834
done

‎frontend/roslyn/OwnSharp.Extractor/Program.cs‎

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -578,10 +578,24 @@ static bool IsFirstPartyDisposableFactory(ExpressionSyntax? expr, SemanticModel
578578
return false; // void, or not first-party (no visible body to infer `fresh` from)
579579
if (!ImplementsIDisposable(m.ReturnType) || IsDisposeOptional(m.ReturnType))
580580
return false;
581-
callee = $"{m.ContainingType.Name}.{m.Name}";
581+
// Fully-qualified key (namespace + containing-type chain) so the call resolves to the
582+
// RIGHT summary: two `StreamFactory.Make` in different namespaces must not alias, or a
583+
// call to a non-fresh one could pick up a fresh one's summary and fabricate OWN001
584+
// (Codex). Must match the `functions[]` name built by `FlowFunctionName`.
585+
callee = $"{m.ContainingType.ToDisplayString()}.{m.Name}";
582586
return true;
583587
}
584588

589+
// The fully-qualified `functions[]` key for a method — `{Namespace.Containing.Type}.{Name}` —
590+
// used both as the flow-function name and as a D5.2 call callee, so the two always agree (a
591+
// simple `{Type}.{Name}` would alias same-named types across namespaces). Falls back to the
592+
// syntactic class name only if the symbol cannot be resolved.
593+
static string FlowFunctionName(BaseMethodDeclarationSyntax method, string fallbackType,
594+
SemanticModel model) =>
595+
model.GetDeclaredSymbol(method) is IMethodSymbol ms
596+
? $"{ms.ContainingType.ToDisplayString()}.{ms.Name}"
597+
: $"{fallbackType}.{MethodName(method)}";
598+
585599
// A `Dispose()`/`Close()`/`DisposeAsync()` call — through member access (`x.Dispose()`)
586600
// or member binding (`x?.Dispose()`), and seen through a trailing `.ConfigureAwait(false)`
587601
// (the idiomatic `await x.DisposeAsync().ConfigureAwait(false)` is the release, not a
@@ -785,8 +799,22 @@ or ImplicitObjectCreationExpressionSyntax
785799
// `fresh`, so a non-fresh first-party call is never falsely owned.
786800
else if (tracked.Contains(v.Identifier.Text)
787801
&& IsFirstPartyDisposableFactory(v.Initializer?.Value, model, out var fpCallee))
788-
nodes.Add(new { op = "call", callee = fpCallee, args = Array.Empty<string>(),
802+
{
803+
// Preserve the call's TRACKED identifier args (CodeRabbit) so the core
804+
// can apply the callee's per-argument ownership effects (consume/borrow)
805+
// to a `var r = Wrap(stream)` — not just the fresh return. Untracked /
806+
// non-identifier args are dropped (no local to attribute an effect to).
807+
var fpArgs = v.Initializer?.Value is InvocationExpressionSyntax fpInv
808+
? fpInv.ArgumentList.Arguments
809+
.Select(a => a.Expression)
810+
.OfType<IdentifierNameSyntax>()
811+
.Select(id => id.Identifier.Text)
812+
.Where(tracked.Contains)
813+
.ToArray()
814+
: Array.Empty<string>();
815+
nodes.Add(new { op = "call", callee = fpCallee, args = fpArgs,
789816
result = v.Identifier.Text, line = LineOf(v) });
817+
}
790818
// POOL005: a full-length view in the initializer — `var copy = buf.AsSpan().ToArray();`
791819
// — over-reads the pooled tail just as `Emit(buf.AsSpan());` does. EmitFlowExpr is not
792820
// called on a non-acquire initializer, so scan it here for the overspan (Codex review).
@@ -3355,7 +3383,7 @@ or ImplicitObjectCreationExpressionSyntax } init
33553383
statMethodsAnalysed++;
33563384
flowFunctions.Add(new
33573385
{
3358-
name = $"{cls.Identifier.Text}.{MethodName(method)}",
3386+
name = FlowFunctionName(method, cls.Identifier.Text, model),
33593387
file,
33603388
body = fbody,
33613389
});

‎ownlang/ownir.py‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,6 +1075,11 @@ def _infer_return_skeleton(nodes: Any, param_names: set[str]) -> ReturnSkeleton:
10751075
ExternDecl("$borrow_mut",
10761076
[EffectParam(Effect.BORROW_MUT, "Disposable", 0)], None, 0),
10771077
)
1078+
# The callee names a `call` op may resolve against in `lower_call` WITHOUT being a
1079+
# first-party function summary — the fixed sink externs. A call to any other callee
1080+
# that is not in the solved MOS is unresolvable (no signature) and must NOT be lowered
1081+
# to a `Call` (it would raise OWN040); see the `call` handler in `_lower_flow`.
1082+
_SINK_EXTERN_NAMES = frozenset(e.name for e in _OWNERSHIP_SINK_EXTERNS)
10781083

10791084
# A forward to a sink extern is a *known* transfer, so a skeleton can record the
10801085
# resolved path action directly — `$consume` is ownership leaving (a must-transfer),
@@ -1530,7 +1535,14 @@ def _lower_flow(nodes: list[Any], ffile: str, fname: str,
15301535
# extractor (it is an escape, surfaced separately).
15311536
callee = str(n.get("callee", ""))
15321537
raw_args = n.get("args", [])
1533-
if callee and isinstance(raw_args, list):
1538+
summ = mos.get(callee) if (mos is not None and callee) else None
1539+
# Only emit the `Call` when the callee is RESOLVABLE — a first-party function
1540+
# with a summary, or a fixed ownership-sink extern. A real extraction surfaces
1541+
# calls to callees we did not lower as functions (BCL / extension methods like
1542+
# `GetRequiredService`); those have no signature, so `lower_call` would raise
1543+
# OWN040. Drop them (no effect, no claim) — precision-safe, never a crash.
1544+
if (summ is not None or callee in _SINK_EXTERN_NAMES) \
1545+
and callee and isinstance(raw_args, list):
15341546
arg_refs: list[Expr] = [VarRef(localmap.get(str(a), str(a)), line)
15351547
for a in raw_args]
15361548
body.append(Call(callee, arg_refs, line))
@@ -1540,7 +1552,6 @@ def _lower_flow(nodes: list[Any], ffile: str, fname: str,
15401552
# above; this models the return). A non-fresh / unknown return makes no
15411553
# claim, so the result is never falsely owned (precision-first).
15421554
result = n.get("result")
1543-
summ = mos.get(callee) if (mos is not None and callee) else None
15441555
if (isinstance(result, str) and result and result not in hoisted
15451556
and summ is not None and getattr(summ, "returns", None) == "fresh"):
15461557
handle = f"loc_{loc[0]}"
@@ -1600,7 +1611,11 @@ def check_facts(facts: dict[str, Any]) -> list[Finding]:
16001611
# parameter's contract could not be inferred (an ambiguous pass-through
16011612
# stays plain) -- a "needs annotation / transitive inference" gap, not a
16021613
# leak. Surfacing these properly (with a subject) is a later step.
1603-
if d.code in ("OWN033", "OWN034", "OWN035", "OWN041"):
1614+
# - OWN040: a `call` to a callee the bridge did not lower as a function
1615+
# (an extension/BCL method surfaced by the extractor). The `call` handler
1616+
# already drops unresolvable callees, so this is belt-and-suspenders — a
1617+
# synthetic-call artifact, never a real C# bug (C# already binds the call).
1618+
if d.code in ("OWN033", "OWN034", "OWN035", "OWN040", "OWN041"):
16041619
continue
16051620
sub = handles.get(_handle_of(d) or "")
16061621
if sub is None:

‎tests/test_ownir.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1471,6 +1471,21 @@ def _sub(source: str | None) -> list[Finding]:
14711471
gotpr = [(x.component, x.code) for x in pr]
14721472
fails.append("D5.2 T1: returning a parameter is not `fresh` (no false acquire of "
14731473
f"the result, no consume of the arg), got {gotpr}")
1474+
# ROBUSTNESS (real extraction): a `call` to a callee NOT in functions[] — a BCL /
1475+
# extension method the extractor surfaced (e.g. `GetRequiredService`) — has no
1476+
# signature, so it must be dropped (no Call, no acquire), NEVER raise OWN040. The
1477+
# bridge gates the Call on a resolvable callee and skips OWN040 belt-and-suspenders.
1478+
checks += 1
1479+
try:
1480+
unk = check_facts({"module": "M", "functions": [
1481+
{"name": "Caller.Use", "file": "T1.cs",
1482+
"body": [{"op": "call", "callee": "Ext.GetRequiredService", "args": [],
1483+
"result": "svc", "line": 5}]}]})
1484+
if unk:
1485+
fails.append("D5.2: a call to an unknown callee must make no claim (no finding), "
1486+
f"got {[(x.component, x.code) for x in unk]}")
1487+
except OwnIRError as e:
1488+
fails.append(f"D5.2: a call to an unknown callee must not crash (OWN040), got {e!r}")
14741489
# the factory acquire must fire inside CONTROL FLOW too: a fresh-returning call in
14751490
# an `if` branch whose result is never disposed leaks, exactly like a top-level one.
14761491
# (Codex P2: the recursive _lower_flow calls must thread `mos` into nested bodies,

0 commit comments

Comments
 (0)