Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(contracts): classify what a signature change does to callers (#2620)

Raghav Chamadiyad3c68bf46834
diff --git a/docs/agent/CHANGE_REVIEW.md b/docs/agent/CHANGE_REVIEW.md
index e65fe45a0..9c93537dc 100644
--- a/docs/agent/CHANGE_REVIEW.md
+++ b/docs/agent/CHANGE_REVIEW.md
@@ -115,7 +115,7 @@ never render the way "these files have never broken" renders.
| `manifest` | `bundle.manifest` | Every counted path, its status, diff reliability and added line spans. The one counted universe — the request's extension and exclude filters are applied here, once. |
| `risk` | `bundle.risk` | Diff shape ranked against the repository's recent commits. Needs a checkout or a pre-scored result. |
| `health` | `bundle.health` | What the change newly made worse, each finding naming its attribution basis. |
-| `contracts` | `bundle.contracts` | Changed symbols whose callers sit outside the change. |
+| `contracts` | `bundle.contracts` | Changed symbols whose callers sit outside the change, split into test and production callers. A signature change carries `signature_effect` (`compatible`, `breaking`, `unknown`) and a `signature_reason` naming the parameter, judged from the indexed parameter list and return type only; a text-only change is not reported as one. |
| `tests` | `bundle.tests` | Impacted tests, measured coverage kept distinct from graph-inferred candidates. |
| `prior_fixes` | via `bundle.risk` | The bug-fix history the risk walk already read. |
| `independent_changes` | `bundle.independent_changes` | When the diff is several changes the index does not connect. |
diff --git a/packages/core/src/repowise/core/analysis/change_contracts.py b/packages/core/src/repowise/core/analysis/change_contracts.py
index 4de7bd5c6..aeffbf0ca 100644
--- a/packages/core/src/repowise/core/analysis/change_contracts.py
+++ b/packages/core/src/repowise/core/analysis/change_contracts.py
@@ -12,10 +12,14 @@ the narrower question, and the two are kept distinct on purpose:
The algorithm:
1. Diff a base parse against a head parse per changed file, classifying every
- symbol as added / removed / signature-changed / body-changed.
+ symbol as added / removed / signature-changed / body-changed. A signature
+ change also carries what it does to a caller
+ (:mod:`repowise.core.analysis.signature_effect`).
2. Walk the graph's ``calls`` edges to collect each changed symbol's callers,
- partitioned into inside-change (already under review) and outside-change.
-3. Outside callers of a *removed* or *signature-changed* symbol are the finding.
+ partitioned into inside-change (already under review) and outside-change,
+ and the outside ones again into tests and production code.
+3. Production callers outside the change of a *removed* symbol, or of a
+ signature change that is not known to be safe, are the finding.
Everything here is deterministic set/graph work over data the caller already
holds. No SQL, no network, no LLM.
@@ -38,8 +42,18 @@ explicitly rather than reimplementing the walk.
from __future__ import annotations
from dataclasses import dataclass, field
+from pathlib import PurePosixPath
from typing import Any
+from ..ingestion.models import EXTENSION_TO_LANGUAGE
+from ..test_paths import is_unambiguous_test_path
+from .signature_effect import (
+ EFFECT_COMPATIBLE,
+ EFFECT_NONE,
+ SignatureEffect,
+ classify_signature_change,
+)
+
# Symbol kinds worth reporting on. Constants and variables produce enormous,
# low-signal churn (every literal edit reads as a "signature change"), and the
# call graph does not resolve calls *to* them anyway.
@@ -71,7 +85,11 @@ class SymbolContractChange:
"""One symbol the change altered, with its resolved callers.
``outside_callers`` holds symbol ids (``path::Name``) of callers whose file
- is not part of this change -- the ones nobody is currently reviewing.
+ is not part of this change -- the ones nobody is currently reviewing --
+ production callers first. ``outside_test_callers`` and
+ ``outside_production_callers`` split the same population, under the same cap.
+ A caller counts as a test only when its path leaves no doubt; an ambiguous
+ one counts as production, so the doubt surfaces the finding.
"""
file: str
@@ -85,16 +103,32 @@ class SymbolContractChange:
inside_caller_count: int = 0
callers_total: int = 0
outside_callers_total: int = 0
+ outside_test_callers: list[str] = field(default_factory=list)
+ outside_production_callers: list[str] = field(default_factory=list)
+ outside_production_callers_total: int = 0
+ #: What the change does to a caller: ``compatible`` | ``breaking`` |
+ #: ``unknown``. ``None`` unless ``change`` is a signature change. A change
+ #: that reads ``none`` (same contract, different text) is not reported as a
+ #: signature change at all.
+ signature_effect: str | None = None
+ #: The specific difference, naming the parameter.
+ signature_reason: str | None = None
@property
def is_breaking(self) -> bool:
- """A contract change with callers nobody in this change is looking at.
+ """A contract change reaching production code nobody in this change is looking at.
Body-only changes are excluded on purpose: the caller's contract still
holds, so listing its callers is noise. Added symbols have no prior
- callers by construction.
+ callers by construction. A signature change known to be safe is not a
+ break, while ``unknown`` still is. Test callers alone are not enough: a
+ break they witness is reported by those tests failing.
"""
- return self.change in (CHANGE_REMOVED, CHANGE_SIGNATURE) and bool(self.outside_callers)
+ if self.change not in (CHANGE_REMOVED, CHANGE_SIGNATURE):
+ return False
+ if self.signature_effect in (EFFECT_NONE, EFFECT_COMPATIBLE):
+ return False
+ return bool(self.outside_production_callers)
@dataclass
@@ -251,6 +285,15 @@ def analyze_contract_impact(
for name, facts in sorted(head_syms.items()):
prior = base_syms.get(name)
+ effect = None
+ if prior is not None and prior.signature != facts.signature:
+ effect = classify_signature_change(
+ prior.signature, facts.signature, _language(path), facts.kind
+ )
+ # The text moved but the contract did not: fall through to the
+ # body check, so only a real edit inside the symbol is reported.
+ if effect.effect == EFFECT_NONE:
+ effect = None
if prior is None:
# A file with no base side at all (added by this change, or
# missing from the snapshot) would otherwise report every symbol
@@ -259,14 +302,14 @@ def analyze_contract_impact(
if not base_syms:
continue
change = CHANGE_ADDED
- elif prior.signature != facts.signature:
+ elif effect is not None:
change = CHANGE_SIGNATURE
elif _overlaps(facts.start_line, facts.end_line, ranges):
change = CHANGE_BODY
else:
continue
changes.append(
- _with_callers(path, facts, change, callers, changed_set, callers_per_symbol)
+ _with_callers(path, facts, change, callers, changed_set, callers_per_symbol, effect)
)
for name, facts in sorted(base_syms.items()):
@@ -290,10 +333,11 @@ _CHANGE_ORDER = {CHANGE_REMOVED: 0, CHANGE_SIGNATURE: 1, CHANGE_ADDED: 2, CHANGE
def _rank(c: SymbolContractChange) -> tuple:
- """Breaking changes first, then by how many outside callers they reach."""
+ """Breaking changes first, then by how much production code they reach."""
return (
not c.is_breaking,
_CHANGE_ORDER.get(c.change, 9),
+ -c.outside_production_callers_total,
-c.outside_callers_total,
c.file,
c.name,
@@ -307,15 +351,23 @@ def _with_callers(
callers: dict[str, list[str]],
changed_set: set[str],
cap: int | None,
+ effect: SignatureEffect | None = None,
) -> SymbolContractChange:
inside = 0
- outside: list[str] = []
+ tests: list[str] = []
+ production: list[str] = []
for caller in callers.get(facts.symbol_id, ()):
- if _containing_file(caller) in changed_set:
+ caller_file = _containing_file(caller)
+ if caller_file in changed_set:
inside += 1
+ elif is_unambiguous_test_path(caller_file):
+ tests.append(caller)
else:
- outside.append(caller)
- outside.sort()
+ production.append(caller)
+ tests.sort()
+ production.sort()
+ # Production first, so a surface cap can never keep only tests.
+ outside = production + tests
return SymbolContractChange(
file=path,
name=facts.name,
@@ -324,13 +376,22 @@ def _with_callers(
change=change,
start_line=facts.start_line,
end_line=facts.end_line,
- outside_callers=outside if cap is None else outside[:cap],
+ outside_callers=outside[:cap],
inside_caller_count=inside,
callers_total=inside + len(outside),
outside_callers_total=len(outside),
+ outside_test_callers=tests[:cap],
+ outside_production_callers=production[:cap],
+ outside_production_callers_total=len(production),
+ signature_effect=effect.effect if effect else None,
+ signature_reason=effect.reason if effect else None,
)
+def _language(path: str) -> str | None:
+ return EXTENSION_TO_LANGUAGE.get(PurePosixPath(path).suffix.lower())
+
+
def unavailable_contract_impact(reason: str) -> ContractImpact:
"""An honest empty result when the inputs for this lane were not supplied."""
return ContractImpact(changes=[], status="unavailable", reason=reason)
diff --git a/packages/core/src/repowise/core/analysis/signature_effect.py b/packages/core/src/repowise/core/analysis/signature_effect.py
new file mode 100644
index 000000000..08236243a
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/signature_effect.py
@@ -0,0 +1,713 @@
+"""What a signature change does to an existing caller.
+
+Comparing two signature strings says only *that* a signature changed. A
+reflowed parameter list, a trailing comma and an appended optional argument all
+differ as text, and none of them can break a caller. This module parses both
+parameter lists and asks the narrower question: could a call site written
+against the old signature stop working?
+
+The reading depends on the language. Where callers can name arguments (Python,
+C#, Kotlin), a rename breaks them; where they cannot (JavaScript, Go, Java),
+it does not. Where types are checked at the call (TypeScript, Rust, Go, Java),
+a retyped parameter or return breaks callers; where they are not (Python,
+JavaScript), it is only an annotation.
+
+It is conservative in one direction only. A form it cannot parse is reported as
+``unknown``, which consumers treat as breaking: not knowing is not the same as
+knowing it is safe.
+
+Pure string work over the indexed signatures. No source, no graph.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+
+#: Values for :attr:`SignatureEffect.effect`, loosest to strictest.
+EFFECT_NONE = "none" # same contract, different text
+EFFECT_COMPATIBLE = "compatible" # changed, but every existing call still works
+EFFECT_BREAKING = "breaking" # an existing call can stop working
+EFFECT_UNKNOWN = "unknown" # unparseable, or a change this module cannot judge
+
+# Callers can pass arguments by name, so a parameter's name is contract.
+# Unlisted languages (and ``None``) are treated as named: fail closed.
+_POSITIONAL_ONLY_LANGUAGES = frozenset(
+ {"javascript", "typescript", "go", "java", "c", "cpp", "rust"}
+)
+# Annotations are not checked at the call, so a retype is not a break.
+# Unlisted languages (and ``None``) are treated as typed: fail closed.
+_LENIENT_TYPE_LANGUAGES = frozenset({"python", "javascript", "ruby", "php"})
+# ``Type name`` rather than ``name: Type``.
+_TYPE_FIRST_LANGUAGES = frozenset({"java", "csharp", "c", "cpp", "dart", "php"})
+_HASH_COMMENT_LANGUAGES = frozenset({"python", "ruby", "php"})
+
+_PAIRS = {")": "(", "]": "[", "}": "{"}
+_ASYNC = re.compile(r"^\s*async\b")
+# A Go method signature leads with its receiver: ``func (r *T) Name(a int)``.
+_GO_RECEIVER = re.compile(r"^\s*func\s*\(")
+# ``operator()(int a)``: the first parentheses are the operator's name.
+_CALL_OPERATOR = re.compile(r"\boperator\s*\(\s*\)")
+_RUST_RECEIVER = re.compile(r"^&?\s*(?:'\w+\s+)?(?:mut\s+)?self\b")
+_PY_RECEIVERS = frozenset({"self", "cls"})
+# A user-defined type name, possibly an alias of the other one.
+_NAMED_TYPE = re.compile(r"^[A-Z][\w.]*$")
+_TYPE_FIRST_NAME = re.compile(r"^(?P<type>.*?[\s*&\]>])?(?P<name>\$?\w+)$")
+_LAMBDA_OPEN = re.compile(r"=\s*lambda\b[^:]*$")
+
+_VARIADIC_KINDS = ("args", "kwargs", "block")
+
+
+@dataclass(frozen=True, slots=True)
+class SignatureEffect:
+ """The verdict, and the specific difference behind it."""
+
+ effect: str
+ reason: str
+
+
+@dataclass(slots=True)
+class _Param:
+ name: str
+ #: ``param`` | ``args`` | ``kwargs`` | ``block`` | ``kw_marker`` (Python's
+ #: bare ``*``) | ``pos_marker`` (Python's ``/``).
+ kind: str = "param"
+ #: How the variadic was spelled (``*``, ``**``, ``...``, ``&``), for reasons.
+ prefix: str = ""
+ has_default: bool = False
+ default: str = ""
+ #: TypeScript's ``x?: T``: same caller-visible effect as a default.
+ optional: bool = False
+ #: Ruby's ``key:``, which no caller can pass by position.
+ keyword_only: bool = False
+ type: str = ""
+ # Filled in by ``_passability``.
+ position: int | None = None
+ by_keyword: bool = False
+
+ @property
+ def required(self) -> bool:
+ return self.kind == "param" and not (self.has_default or self.optional)
+
+
+@dataclass(slots=True)
+class _Signature:
+ params: list[_Param]
+ returns: str
+ receiver: str | None = None
+
+
+@dataclass
+class _Notes:
+ breaking: list[str] = field(default_factory=list)
+ unknown: list[str] = field(default_factory=list)
+ compatible: list[str] = field(default_factory=list)
+
+ def add(self, effect: str, reason: str) -> None:
+ bucket = {
+ EFFECT_BREAKING: self.breaking,
+ EFFECT_UNKNOWN: self.unknown,
+ EFFECT_COMPATIBLE: self.compatible,
+ }[effect]
+ if reason not in bucket:
+ bucket.append(reason)
+
+ def verdict(self) -> SignatureEffect:
+ for effect, reasons in (
+ (EFFECT_BREAKING, self.breaking),
+ (EFFECT_UNKNOWN, self.unknown),
+ (EFFECT_COMPATIBLE, self.compatible),
+ ):
+ if reasons:
+ return SignatureEffect(effect, _join(reasons))
+ return SignatureEffect(EFFECT_NONE, "only formatting changed; the parameters are the same")
+
+
+# ---------------------------------------------------------------------------
+# Lexing
+# ---------------------------------------------------------------------------
+
+
+def _quotes(lang: str | None) -> str:
+ # Rust's ``'a`` is a lifetime, never a string.
+ quotes = '"' if lang == "rust" else "\"'"
+ return quotes + "`" if lang in ("javascript", "typescript") else quotes
+
+
+def _strip_comments(text: str, lang: str | None) -> str:
+ """Drop comments outside strings, so an apostrophe in one cannot open a quote."""
+ quotes = _quotes(lang)
+ slash = lang not in ("python", "ruby")
+ hashed = lang in _HASH_COMMENT_LANGUAGES
+ out: list[str] = []
+ quote: str | None = None
+ i, n = 0, len(text)
+ while i < n:
+ ch = text[i]
+ if quote is not None:
+ out.append(text[i : i + 2] if ch == "\\" else ch)
+ if ch == quote:
+ quote = None
+ i += 2 if ch == "\\" else 1
+ continue
+ if ch in quotes:
+ quote = ch
+ elif slash and text.startswith("/*", i):
+ end = text.find("*/", i + 2)
+ i = n if end < 0 else end + 2
+ out.append(" ")
+ continue
+ elif (slash and text.startswith("//", i)) or (
+ hashed and ch == "#" and text[i + 1 : i + 2] != "["
+ ):
+ end = text.find("\n", i)
+ i = n if end < 0 else end
+ continue
+ out.append(ch)
+ i += 1
+ return "".join(out)
+
+
+def _normalize(signature: str, lang: str | None) -> str:
+ return re.sub(r"\s+", " ", _strip_comments(signature or "", lang)).strip()
+
+
+def _top_level(text: str, lang: str | None) -> list[bool] | None:
+ """Per character, whether it sits outside every bracket and string.
+
+ ``None`` when brackets or quotes do not balance. ``<`` opens a generic only
+ right after a name (``Map<``), never in Python, and never as ``<<``/``<=``,
+ so shifts and comparisons in a default value stay operators.
+ """
+ top = [False] * len(text)
+ stack: list[str] = []
+ quotes = _quotes(lang)
+ quote: str | None = None
+ i = 0
+ while i < len(text):
+ ch = text[i]
+ prev = text[i - 1] if i else ""
+ if quote is not None:
+ if ch == "\\":
+ i += 2
+ continue
+ if ch == quote:
+ quote = None
+ elif ch in quotes:
+ quote = ch
+ elif ch in "([{":
+ stack.append(ch)
+ elif (
+ ch == "<"
+ and lang != "python"
+ and (prev.isalnum() or prev in "_.$")
+ and text[i + 1 : i + 2] not in ("<", "=")
+ ):
+ stack.append("<")
+ elif ch == ">" and stack and stack[-1] == "<" and prev not in ("=", "-"):
+ stack.pop()
+ elif ch in _PAIRS:
+ if not stack or stack[-1] != _PAIRS[ch]:
+ return None
+ stack.pop()
+ else:
+ top[i] = not stack
+ i += 1
+ return None if stack or quote is not None else top
+
+
+def _split(text: str, lang: str | None, seps: str = ",") -> list[str] | None:
+ top = _top_level(text, lang)
+ if top is None:
+ return None
+ parts: list[str] = []
+ start = 0
+ for i, ch in enumerate(text):
+ if ch in seps and top[i]:
+ parts.append(text[start:i])
+ start = i + 1
+ parts.append(text[start:])
+ if lang == "python":
+ # ``key=lambda a, b: a`` holds a comma before its colon.
+ merged: list[str] = []
+ for part in parts:
+ if merged and _LAMBDA_OPEN.search(merged[-1]):
+ merged[-1] += "," + part
+ else:
+ merged.append(part)
+ parts = merged
+ return [p.strip() for p in parts if p.strip()]
+
+
+def _find_top(text: str, lang: str | None, needle: str) -> int | None:
+ top = _top_level(text, lang)
+ if top is None:
+ return None
+ for i, ch in enumerate(text):
+ if ch != needle or not top[i]:
+ continue
+ # ``==``, ``!=``, ``<=``, ``>=``, ``=>`` and ``:=`` are not defaults.
+ if needle == "=" and (
+ text[i - 1 : i] in ("=", "!", "<", ">", ":") or text[i + 1 : i + 2] in ("=", ">")
+ ):
+ continue
+ return i
+ return None
+
+
+def _close_paren(text: str, open_at: int, lang: str | None) -> int | None:
+ """Index of the ``)`` closing ``text[open_at]``, skipping strings."""
+ quotes = _quotes(lang)
+ quote: str | None = None
+ depth = 0
+ i = open_at
+ while i < len(text):
+ ch = text[i]
+ if quote is not None:
+ if ch == "\\":
+ i += 2
+ continue
+ if ch == quote:
+ quote = None
+ elif ch in quotes:
+ quote = ch
+ elif ch == "(":
+ depth += 1
+ elif ch == ")":
+ depth -= 1
+ if depth == 0:
+ return i
+ i += 1
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Parsing
+# ---------------------------------------------------------------------------
+
+
+def _parse_signature(sig: str, lang: str | None, kind: str | None) -> _Signature | None:
+ start = 0
+ receiver: str | None = None
+ if _GO_RECEIVER.match(sig):
+ open_at = sig.find("(")
+ close = _close_paren(sig, open_at, lang)
+ if close is None:
+ return None
+ receiver = sig[open_at + 1 : close].strip()
+ start = close + 1
+ elif (m := _CALL_OPERATOR.search(sig)) is not None:
+ start = m.end()
+ open_at = sig.find("(", start)
+ if open_at < 0:
+ return None
+ close = _close_paren(sig, open_at, lang)
+ if close is None:
+ return None
+ raw = _split(sig[open_at + 1 : close], lang)
+ if raw is None:
+ return None
+ if lang in ("c", "cpp") and raw == ["void"]:
+ raw = []
+ parse = (
+ _parse_go
+ if lang == "go"
+ else _parse_type_first
+ if lang in _TYPE_FIRST_LANGUAGES
+ else _parse_colon
+ )
+ params = [parse(text, n, lang) for n, text in enumerate(raw)]
+ if lang == "go":
+ _group_go(params)
+ if params and lang == "rust" and _RUST_RECEIVER.match(raw[0]):
+ receiver = raw[0]
+ params = params[1:]
+ elif params and lang == "python" and kind != "function" and params[0].name in _PY_RECEIVERS:
+ receiver = params[0].name
+ params = params[1:]
+ returns = re.sub(r"^(->|:)\s*", "", sig[close + 1 :].strip()).strip()
+ return _Signature(params=params, returns=returns, receiver=receiver)
+
+
+def _split_default(text: str, lang: str | None, param: _Param) -> str:
+ at = _find_top(text, lang, "=")
+ if at is None:
+ return text
+ param.has_default = True
+ param.default = text[at + 1 :].strip()
+ return text[:at].strip()
+
+
+def _parse_colon(text: str, position: int, lang: str | None) -> _Param:
+ """``name: Type = default``: Python, TypeScript, Rust, Kotlin, Swift, Scala, Ruby."""
+ param = _Param(name="")
+ if lang == "python" and text in ("*", "/"):
+ return _Param(name=text, kind="kw_marker" if text == "*" else "pos_marker")
+ for prefix, kind in (("**", "kwargs"), ("...", "args"), ("*", "args"), ("vararg ", "args")):
+ if text.startswith(prefix):
+ param.kind, param.prefix, text = kind, prefix.strip(), text[len(prefix) :]
+ break
+ else:
+ if text.startswith("&") and lang == "ruby":
+ param.kind, param.prefix, text = "block", "&", text[1:]
+
+ if lang == "ruby":
+ # Ruby's colon marks a keyword argument; what follows it is the default.
+ at = _find_top(text, lang, ":")
+ if at is not None:
+ param.keyword_only = True
+ param.default = text[at + 1 :].strip()
+ param.has_default = bool(param.default)
+ text = text[:at]
+ else:
+ text = _split_default(text, lang, param)
+ else:
+ text = _split_default(text, lang, param)
+ at = _find_top(text, lang, ":")
+ if at is not None:
+ param.type = text[at + 1 :].strip()
+ text = text[:at].strip()
+ if param.type.endswith(("*", "...")) and lang in ("scala", "swift"):
+ param.kind, param.prefix = "args", "..."
+
+ text = text.strip()
+ if lang == "rust":
+ text = re.sub(r"^mut\s+", "", text) # a local binding, not the contract
+ # A destructured parameter has no caller-visible name, so it is keyed by
+ # position: reading one more field out of it is not a contract change.
+ if text.startswith(("{", "[")):
+ param.name = f"<destructured:{position}>"
+ else:
+ param.optional = text.endswith("?")
+ param.name = text.rstrip("?").strip() or f"<anonymous:{position}>"
+ return param
+
+
+def _parse_type_first(text: str, position: int, lang: str | None) -> _Param:
+ """``Type name = default``: Java, C#, C, C++, Dart, PHP."""
+ param = _Param(name="")
+ if text.startswith(("{", "[")):
+ # Dart's named or optional group: any edit inside it is judged whole.
+ return _Param(name=f"<group:{position}>", type=text)
+ text = _split_default(text, lang, param)
+ text = re.sub(r"^(?:final|const)\s+", "", text)
+ if text.startswith("params "):
+ param.kind, text = "args", text[7:]
+ if text == "...":
+ return _Param(name=f"<varargs:{position}>", kind="args")
+ if "..." in text:
+ param.kind, text = "args", text.replace("...", " ")
+ m = _TYPE_FIRST_NAME.match(text.strip())
+ if m is not None and (m.group("type") or m.group("name").startswith("$") or lang == "dart"):
+ param.name = m.group("name")
+ param.type = _normalize(m.group("type") or "", lang)
+ else:
+ # C's unnamed ``int``: the type is all there is.
+ param.name = f"<anonymous:{position}>"
+ param.type = text.strip()
+ return param
+
+
+def _parse_go(text: str, position: int, lang: str | None) -> _Param:
+ """``name Type``, ``name ...Type``, or a bare ``Type``; grouping comes after."""
+ name, _, rest = text.partition(" ")
+ param = _Param(name=name, type=rest.strip())
+ if param.type.startswith("..."):
+ param.kind, param.type = "args", param.type[3:].strip()
+ elif name.startswith("..."):
+ param.kind, param.name, param.type = "args", f"<anonymous:{position}>", name[3:]
+ return param
+
+
+def _group_go(params: list[_Param]) -> None:
+ """``a, b int`` is ``a int, b int``; with no names at all, each bare token is a type."""
+ if not any(p.type for p in params):
+ for n, p in enumerate(params):
+ if p.kind == "param":
+ p.name, p.type = f"<anonymous:{n}>", p.name
+ return
+ pending: list[_Param] = []
+ for p in params:
+ if p.type:
+ for q in pending:
+ q.type = p.type
+ pending = []
+ else:
+ pending.append(p)
+
+
+def _passability(params: list[_Param], lang: str | None) -> list[_Param]:
+ """Stamp how a caller can pass each parameter; return the real parameters."""
+ named = lang not in _POSITIONAL_ONLY_LANGUAGES
+ slash = next((n for n, p in enumerate(params) if p.kind == "pos_marker"), None)
+ positional = True
+ index = 0
+ out: list[_Param] = []
+ for n, p in enumerate(params):
+ if p.kind in ("kw_marker", "args"):
+ positional = False
+ if p.kind != "param":
+ if p.kind not in ("kw_marker", "pos_marker"):
+ out.append(p)
+ continue
+ if positional and not p.keyword_only:
+ p.position = index
+ index += 1
+ p.by_keyword = named and (slash is None or n > slash)
+ out.append(p)
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Comparison
+# ---------------------------------------------------------------------------
+
+
+def classify_signature_change(
+ before: str, after: str, language: str | None = None, kind: str | None = None
+) -> SignatureEffect:
+ """Compare two indexed signatures of the same symbol, from a caller's side.
+
+ *language* is the repowise language name of the file; ``None`` reads it
+ strictly (names and types both count). *kind* is the symbol kind: a Python
+ ``function`` has no receiver, so a leading ``self`` there is a parameter.
+ """
+ lang = (language or "").lower() or None
+ lhs, rhs = _normalize(before, lang), _normalize(after, lang)
+ if lhs == rhs:
+ return SignatureEffect(EFFECT_NONE, "only whitespace or comments changed")
+
+ # ``async`` is a real contract: a caller that did not await now gets a
+ # coroutine, and one that did now awaits a plain value.
+ was_async, is_async = bool(_ASYNC.match(lhs)), bool(_ASYNC.match(rhs))
+ if was_async != is_async:
+ verb = "became async" if is_async else "is no longer async"
+ return SignatureEffect(EFFECT_BREAKING, f"{verb}, so its callers' await changes")
+
+ old, new = _parse_signature(lhs, lang, kind), _parse_signature(rhs, lang, kind)
+ if old is None or new is None:
+ return SignatureEffect(EFFECT_UNKNOWN, "the parameter list could not be parsed")
+
+ notes = _Notes()
+ _compare_receivers(old.receiver, new.receiver, lang, notes)
+ _compare_params(_passability(old.params, lang), _passability(new.params, lang), lang, notes)
+ _compare_type(old.returns, new.returns, lang, None, notes)
+ return notes.verdict()
+
+
+def _compare_receivers(old: str | None, new: str | None, lang: str | None, notes: _Notes) -> None:
+ if old == new:
+ return
+ if lang == "python":
+ # ``K.f(a)`` stops working once ``f`` needs an instance.
+ if new == "self":
+ notes.add(
+ EFFECT_BREAKING, "became an instance method, so calls through the class break"
+ )
+ else:
+ notes.add(EFFECT_COMPATIBLE, "no longer needs an instance")
+ elif lang in ("go", None):
+ # Only a Go receiver is ever extracted without a language.
+ was_ptr, is_ptr = "*" in (old or ""), "*" in (new or "")
+ if is_ptr and not was_ptr:
+ # A value of the type no longer satisfies interfaces through it.
+ notes.add(EFFECT_BREAKING, "moved to a pointer receiver")
+ elif was_ptr and not is_ptr:
+ notes.add(EFFECT_COMPATIBLE, "moved to a value receiver")
+ else:
+ notes.add(
+ EFFECT_BREAKING, f"changed its receiver from `{old or 'none'}` to `{new or 'none'}`"
+ )
+
+
+def _compare_params(
+ before: list[_Param], after: list[_Param], lang: str | None, notes: _Notes
+) -> None:
+ old_regular = {p.name: p for p in before if p.kind == "param"}
+ new_regular = {p.name: p for p in after if p.kind == "param"}
+ removed = [p for p in old_regular.values() if p.name not in new_regular]
+ added = [p for p in new_regular.values() if p.name not in old_regular]
+ pairs = [(p, new_regular[p.name]) for p in old_regular.values() if p.name in new_regular]
+
+ # A parameter gone and one arrived in the same slot is a rename.
+ for gone in list(removed):
+ arrived = next(
+ (q for q in added if gone.position is not None and q.position == gone.position), None
+ )
+ if arrived is None:
+ continue
+ removed.remove(gone)
+ added.remove(arrived)
+ pairs.append((gone, arrived))
+ if gone.by_keyword:
+ notes.add(EFFECT_BREAKING, f"renamed `{gone.name}` to `{arrived.name}`")
+ else:
+ notes.add(
+ EFFECT_COMPATIBLE,
+ f"renamed `{gone.name}` to `{arrived.name}`, which callers never name",
+ )
+
+ old_var = {p.kind: p for p in before if p.kind in _VARIADIC_KINDS}
+ new_var = {p.kind: p for p in after if p.kind in _VARIADIC_KINDS}
+
+ # Java's ``T[] a`` becoming ``T... a`` still accepts the array.
+ arrived_args = new_var.get("args")
+ if arrived_args is not None and "args" not in old_var:
+ for gone in removed:
+ if gone.type.replace(" ", "") == arrived_args.type.replace(" ", "") + "[]":
+ removed.remove(gone)
+ old_var["args"] = arrived_args
+ notes.add(EFFECT_COMPATIBLE, f"now takes `{gone.name}` as varargs")
+ break
+
+ for p in removed:
+ label = "the required " if p.required else ""
+ notes.add(EFFECT_BREAKING, f"removed {label}`{p.name}`")
+
+ for q in added:
+ if q.required:
+ notes.add(EFFECT_BREAKING, f"added the required `{q.name}`")
+ elif q.position is not None and "args" in old_var:
+ # Extra positional arguments used to land in the variadic.
+ notes.add(EFFECT_BREAKING, f"inserted `{q.name}` before `{_display(old_var['args'])}`")
+ else:
+ notes.add(EFFECT_COMPATIBLE, f"added optional `{q.name}`")
+
+ for p, q in pairs:
+ _compare_pair(p, q, added, removed, lang, notes)
+
+ for var_kind in _VARIADIC_KINDS:
+ p, q = old_var.get(var_kind), new_var.get(var_kind)
+ if p is not None and q is None:
+ notes.add(EFFECT_BREAKING, f"removed `{_display(p)}`")
+ elif p is None and q is not None:
+ notes.add(EFFECT_COMPATIBLE, f"added `{_display(q)}`")
+ elif p is not None and q is not None and p is not q:
+ _compare_type(p.type, q.type, lang, f"`{_display(q)}`", notes)
+
+
+def _compare_pair(
+ p: _Param,
+ q: _Param,
+ added: list[_Param],
+ removed: list[_Param],
+ lang: str | None,
+ notes: _Notes,
+) -> None:
+ name = q.name
+ if p.position is not None and q.position is None:
+ notes.add(EFFECT_BREAKING, f"made `{name}` keyword-only")
+ elif p.position is None and q.position is not None:
+ notes.add(EFFECT_COMPATIBLE, f"`{name}` can now be passed by position")
+ elif p.position is not None and q.position is not None and p.position != q.position:
+ inserted = [a for a in added if a.position is not None and a.position < q.position]
+ if inserted:
+ for a in inserted:
+ notes.add(EFFECT_BREAKING, f"inserted `{a.name}` before `{name}`")
+ elif not any(r.position is not None and r.position < p.position for r in removed):
+ notes.add(EFFECT_BREAKING, "reordered its parameters")
+ if p.by_keyword and not q.by_keyword:
+ notes.add(EFFECT_BREAKING, f"made `{name}` positional-only")
+ elif q.by_keyword and not p.by_keyword:
+ notes.add(EFFECT_COMPATIBLE, f"`{name}` can now be passed by name")
+ if p.required and not q.required:
+ notes.add(EFFECT_COMPATIBLE, f"`{name}` is now optional")
+ elif q.required and not p.required:
+ notes.add(EFFECT_BREAKING, f"`{name}` is now required")
+ elif p.has_default and q.has_default and p.default != q.default:
+ notes.add(EFFECT_COMPATIBLE, f"changed the default of `{name}`")
+ _compare_type(p.type, q.type, lang, _label(name), notes)
+
+
+def _compare_type(old: str, new: str, lang: str | None, subject: str | None, notes: _Notes) -> None:
+ """A parameter's type (``subject`` names it) or, with ``subject=None``, the return."""
+ if old == new:
+ return
+ if lang in _LENIENT_TYPE_LANGUAGES:
+ if subject is None:
+ notes.add(EFFECT_COMPATIBLE, "changed its return annotation")
+ else:
+ notes.add(EFFECT_COMPATIBLE, f"{'retyped' if old else 'annotated'} {subject}")
+ return
+ what = f"the type of {subject}" if subject else "its return type"
+ if not old or not new:
+ # An inferred type made explicit, or the reverse: it may be the same type.
+ notes.add(EFFECT_UNKNOWN, f"{'declared' if new else 'dropped'} {what}")
+ elif old.startswith("{") and old.endswith("}") and new.startswith("{") and new.endswith("}"):
+ _compare_members(old, new, lang, notes)
+ elif _widens(old, new, lang) if subject else _widens(new, old, lang):
+ # A parameter accepting more, or a return promising less, keeps every call.
+ verb = "widened" if subject else "narrowed"
+ notes.add(EFFECT_COMPATIBLE, f"{verb} {what} from `{old}` to `{new}`")
+ elif _NAMED_TYPE.match(old) and _NAMED_TYPE.match(new):
+ # Two type names may be aliases of one another; the text cannot say.
+ notes.add(EFFECT_UNKNOWN, f"changed {what} from `{old}` to `{new}`, which may be an alias")
+ else:
+ notes.add(EFFECT_BREAKING, f"changed {what} from `{old}` to `{new}`")
+
+
+def _widens(narrow: str, wide: str, lang: str | None) -> bool:
+ """Whether every member of the union *narrow* is a member of the union *wide*."""
+ lhs, rhs = _split(narrow, lang, seps="|"), _split(wide, lang, seps="|")
+ return lhs is not None and rhs is not None and set(lhs) < set(rhs)
+
+
+def _members(literal: str, lang: str | None) -> dict[str, tuple[bool, str]] | None:
+ """``{a: string; b?: number}`` as ``{name: (optional, type)}``."""
+ parts = _split(literal[1:-1], lang, seps=";,")
+ if parts is None:
+ return None
+ out: dict[str, tuple[bool, str]] = {}
+ for part in parts:
+ part = re.sub(r"^readonly\s+", "", part)
+ at = _find_top(part, lang, ":")
+ paren = part.find("(")
+ if paren >= 0 and (at is None or paren < at):
+ name, mtype = part[:paren].strip(), part[paren:].strip()
+ elif at is not None:
+ name, mtype = part[:at].strip(), part[at + 1 :].strip()
+ else:
+ name, mtype = part.strip(), ""
+ out[name.rstrip("?").strip()] = (name.endswith("?"), mtype)
+ return out
+
+
+def _compare_members(old: str, new: str, lang: str | None, notes: _Notes) -> None:
+ before, after = _members(old, lang), _members(new, lang)
+ if before is None or after is None:
+ notes.add(EFFECT_UNKNOWN, "changed an inline type it could not parse")
+ return
+ for name, (optional, _) in after.items():
+ if name not in before:
+ if optional:
+ notes.add(EFFECT_COMPATIBLE, f"added optional member `{name}`")
+ else:
+ notes.add(EFFECT_BREAKING, f"added the required member `{name}`")
+ for name, (was_optional, old_type) in before.items():
+ if name not in after:
+ notes.add(EFFECT_BREAKING, f"removed member `{name}`")
+ continue
+ is_optional, new_type = after[name]
+ if was_optional and not is_optional:
+ notes.add(EFFECT_BREAKING, f"member `{name}` is now required")
+ elif is_optional and not was_optional:
+ notes.add(EFFECT_COMPATIBLE, f"member `{name}` is now optional")
+ _compare_type(old_type, new_type, lang, f"member `{name}`", notes)
+
+
+def _display(p: _Param) -> str:
+ return f"{p.prefix or '...'}{p.name}"
+
+
+def _label(name: str) -> str:
+ if name.startswith("<destructured"):
+ return "the destructured parameter"
+ if name.startswith("<"):
+ return f"parameter {int(name.rsplit(':', 1)[1].rstrip('>')) + 1}"
+ return f"`{name}`"
+
+
+def _join(items: list[str]) -> str:
+ if len(items) == 1:
+ return items[0]
+ return ", ".join(items[:-1]) + f" and {items[-1]}"
diff --git a/packages/core/src/repowise/core/test_paths.py b/packages/core/src/repowise/core/test_paths.py
index 0c251c2b3..87ef8c5bb 100644
--- a/packages/core/src/repowise/core/test_paths.py
+++ b/packages/core/src/repowise/core/test_paths.py
@@ -363,6 +363,24 @@ def is_test_related_path(path: str, language: str | None = None) -> bool:
return _classify(path, language) != ""
+def is_unambiguous_test_path(path: str, language: str | None = None) -> bool:
+ """Whether *path* is test material beyond a naming coincidence.
+
+ For callers that *hide* something when the answer is yes, such as a
+ contract break whose only callers are tests. A test-shaped filename alone
+ does not qualify inside a ``src`` tree, where ``src/pkg/test_paths.py`` is a
+ production module named for what it does. It needs a test directory
+ (``tests/``, ``__tests__/``, ``src/test/java``) or to sit outside ``src``.
+ Ambiguous paths read as production, so the doubt surfaces the finding.
+ """
+ if not is_test_related_path(path, language):
+ return False
+ original, lowered = _parts(path)
+ if _is_test_dir(lowered[:-1], original[:-1], original[-1], language):
+ return True
+ return "src" not in lowered[:-1]
+
+
def is_test_to_production_pair(
code_path: str, partner_path: str, *, code_language: str | None = None
) -> bool:
diff --git a/tests/unit/analysis/test_change_contracts.py b/tests/unit/analysis/test_change_contracts.py
index dc4ee2b3b..88b8a2861 100644
--- a/tests/unit/analysis/test_change_contracts.py
+++ b/tests/unit/analysis/test_change_contracts.py
@@ -204,6 +204,123 @@ def test_breaking_changes_rank_first_and_by_reach():
assert [c.name for c in impact.changes] == ["wide", "narrow"]
+# ---------------------------------------------------------------------------
+# What a signature change does, and who witnesses it
+# ---------------------------------------------------------------------------
+
+
+def _signature_change(before: str, after: str, calls=(("app/b.py::main", "app/a.py::run"),)):
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig=before)])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig=after)])]
+ return _compute(base, head, calls=list(calls)).changes[0]
+
+
+def test_a_reflowed_signature_is_not_a_signature_change():
+ # Same contract, different text: it falls through to the body check, so
+ # it is reported only when the change edited inside the symbol.
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="def run(x, y)")])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig="def run(\n x,\n y,\n)")])]
+ calls = [("app/b.py::main", "app/a.py::run")]
+ assert _compute(base, head, calls=calls).changes == []
+ touched = _compute(base, head, calls=calls, ranges={"app/a.py": [(12, 14)]})
+ assert [c.change for c in touched.changes] == ["body"]
+ assert touched.changes[0].signature_effect is None
+
+
+def test_the_file_language_decides_whether_a_retype_breaks():
+ base = [_file("web/a.ts", [_sym("run", path="web/a.ts", sig="function run(x: string)")])]
+ head = [_file("web/a.ts", [_sym("run", path="web/a.ts", sig="function run(x: number)")])]
+ calls = [("web/b.ts::main", "web/a.ts::run")]
+ change = _compute(base, head, calls=calls, changed=("web/a.ts",)).changes[0]
+ assert change.signature_effect == "breaking"
+ assert change.is_breaking
+ # The same edit in Python is an annotation no caller is checked against.
+ assert not _signature_change("def run(x: str)", "def run(x: int)").is_breaking
+
+
+def test_an_appended_optional_argument_is_compatible_and_never_breaks():
+ change = _signature_change("def run(x)", "def run(x, y=None)")
+ assert change.signature_effect == "compatible"
+ assert change.signature_reason == "added optional `y`"
+ assert not change.is_breaking
+
+
+def test_a_removed_parameter_is_breaking_and_says_which():
+ change = _signature_change("def run(x, y)", "def run(x)")
+ assert change.signature_effect == "breaking"
+ assert change.signature_reason == "removed the required `y`"
+ assert change.is_breaking
+
+
+def test_an_unparseable_signature_is_unknown_and_stays_breaking():
+ change = _signature_change("def run(x)", "def run(x, y: Dict[str, int)")
+ assert change.signature_effect == "unknown"
+ assert change.is_breaking
+
+
+def test_only_signature_changes_carry_an_effect():
+ base = [_file("app/a.py", [_sym("gone", path="app/a.py", sig="gone()")])]
+ head = [_file("app/a.py", [_sym("kept", path="app/a.py", sig="kept()")])]
+ impact = _compute(base, head, calls=[("app/b.py::main", "app/a.py::gone")])
+ assert all(c.signature_effect is None and c.signature_reason is None for c in impact.changes)
+
+
+def test_a_break_witnessed_only_by_tests_is_not_breaking():
+ calls = [("tests/test_a.py::test_run", "app/a.py::run")]
+ change = _signature_change("def run(x, y)", "def run(x)", calls=calls)
+ assert change.signature_effect == "breaking"
+ assert change.outside_test_callers == ["tests/test_a.py::test_run"]
+ assert change.outside_production_callers == []
+ assert not change.is_breaking
+
+
+def test_a_removal_witnessed_only_by_tests_is_not_breaking():
+ base = [_file("app/a.py", [_sym("gone", path="app/a.py", sig="gone()")])]
+ calls = [("tests/test_a.py::t", "app/a.py::gone")]
+ impact = _compute(base, [_file("app/a.py", [])], calls=calls)
+ assert impact.changes[0].change == "removed"
+ assert impact.breaking == []
+
+
+def test_a_production_module_named_like_a_test_is_still_production():
+ # ``src/pkg/test_impact.py`` is named for what it does, not a test of it.
+ caller = "packages/core/src/repowise/core/analysis/test_impact.py::build"
+ change = _signature_change("def run(x, y)", "def run(x)", calls=[(caller, "app/a.py::run")])
+ assert change.outside_production_callers == [caller]
+ assert change.is_breaking
+
+
+def test_ranking_reads_production_reach_not_test_reach():
+ def syms(sig_suffix: str):
+ return [
+ _file(
+ "app/a.py",
+ [
+ _sym("tested", path="app/a.py", sig=f"def tested({sig_suffix})"),
+ _sym("used", path="app/a.py", sig=f"def used({sig_suffix})"),
+ ],
+ )
+ ]
+
+ calls = [(f"tests/test_{i}.py::t", "app/a.py::tested") for i in range(5)]
+ calls += [("app/b.py::main", "app/a.py::tested")]
+ calls += [(f"app/c{i}.py::main", "app/a.py::used") for i in range(2)]
+ impact = _compute(syms("x"), syms(""), calls=calls)
+ assert [c.name for c in impact.changes] == ["used", "tested"]
+
+
+def test_production_callers_come_first_so_a_cap_keeps_them():
+ base = [_file("app/a.py", [_sym("run", path="app/a.py", sig="def run(x, y)")])]
+ head = [_file("app/a.py", [_sym("run", path="app/a.py", sig="def run(x)")])]
+ calls = [(f"tests/test_{i}.py::t", "app/a.py::run") for i in range(3)]
+ calls.append(("app/z.py::main", "app/a.py::run"))
+ change = _compute(base, head, calls=calls, callers_per_symbol=2).changes[0]
+ assert change.outside_callers == ["app/z.py::main", "tests/test_0.py::t"]
+ assert change.outside_production_callers == ["app/z.py::main"]
+ assert change.outside_callers_total == 4
+ assert change.is_breaking
+
+
# ---------------------------------------------------------------------------
# Core owns the untruncated population; caps are surface policy
# ---------------------------------------------------------------------------
diff --git a/tests/unit/analysis/test_signature_effect.py b/tests/unit/analysis/test_signature_effect.py
new file mode 100644
index 000000000..b8f6a74e5
--- /dev/null
+++ b/tests/unit/analysis/test_signature_effect.py
@@ -0,0 +1,288 @@
+"""What a signature change does to a caller, decided from the two indexed signatures.
+
+Signatures are written the way the indexer emits them (``def f(...) -> T``,
+``function f(...) -> T``, ``fn f(...)``, ``func (r *T) M(...)``, ``f(int a) -> T``).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.signature_effect import (
+ EFFECT_BREAKING,
+ EFFECT_COMPATIBLE,
+ EFFECT_NONE,
+ EFFECT_UNKNOWN,
+ classify_signature_change,
+)
+
+BREAKS = {EFFECT_BREAKING, EFFECT_UNKNOWN}
+
+
+def _effect(before: str, after: str, lang: str | None, kind: str | None = "function"):
+ return classify_signature_change(before, after, lang, kind)
+
+
+ ("before", "after", "lang"),
+ [
+ ("def run(self, x, y) -> int", "def run(\n self,\n x,\n y\n) -> int", "python"),
+ ("def run(x, y)", "def run(x, y,)", "python"),
+ # Comments, including an inline one with an apostrophe.
+ ("def f(a, b=1)", "def f(\n a, # the drawer's row\n b=1,\n)", "python"),
+ ("def f(\n a, # it's\n b=1,\n)", "def f(\n a,\n # b's default\n b=1,\n)", "python"),
+ # Rust lifetimes are not string quotes.
+ ("fn f(x: &'a str) -> &'a str", "fn f(\n x: &'a str,\n) -> &'a str", "rust"),
+ # Go's grouped parameters are the same parameters.
+ ("function F(a, b int)", "function F(a int, b int)", "go"),
+ # Reordering keyword-only parameters moves nothing a caller passes by position.
+ ("def f(a, *, b=1, c=2)", "def f(a, *, c=2, b=1)", "python"),
+ ],
+)
+def test_text_only_changes_have_no_effect(before, after, lang):
+ assert _effect(before, after, lang).effect == EFFECT_NONE
+
+
+ ("before", "after", "lang", "reason"),
+ [
+ ("def run(x)", "def run(x, y=None)", "python", "added optional `y`"),
+ (
+ "function run(a: string)",
+ "function run(a: string, b?: number)",
+ "typescript",
+ "added optional `b`",
+ ),
+ ("def run(x, y)", "def run(x, y=1)", "python", "`y` is now optional"),
+ ("def run(x)", "def run(x: int)", "python", "annotated `x`"),
+ ("def run(x) -> int", "def run(x) -> str", "python", "changed its return annotation"),
+ ("def f(a, t=30)", "def f(a, t='30s')", "python", "changed the default of `t`"),
+ ("def f(mode='async')", "def f(mode='sync')", "python", "changed the default of `mode`"),
+ (
+ "def f(a, b, /)",
+ "def f(a, b)",
+ "python",
+ "`a` can now be passed by name and `b` can now be passed by name",
+ ),
+ # Callers of these languages never name an argument.
+ (
+ "function f(a)",
+ "function f(b)",
+ "javascript",
+ "renamed `a` to `b`, which callers never name",
+ ),
+ (
+ "function F(a int)",
+ "function F(b int)",
+ "go",
+ "renamed `a` to `b`, which callers never name",
+ ),
+ (
+ "f(int a) -> void",
+ "f(int b) -> void",
+ "java",
+ "renamed `a` to `b`, which callers never name",
+ ),
+ ("function F(a int)", "function F(a int, opts ...Opt)", "go", "added `...opts`"),
+ ("f(String[] a) -> void", "f(String... a) -> void", "java", "now takes `a` as varargs"),
+ (
+ "function C({a, b}: {a: string; b: number})",
+ "function C({a, b}: {a: string; b?: number})",
+ "typescript",
+ "member `b` is now optional",
+ ),
+ (
+ "function C({a}: {a: string})",
+ "function C({a}: {a: string; b?: number})",
+ "typescript",
+ "added optional member `b`",
+ ),
+ ("func (t *T) M(a int)", "func (t T) M(a int)", "go", "moved to a value receiver"),
+ ],
+)
+def test_changes_every_existing_call_survives_are_compatible(before, after, lang, reason):
+ effect = _effect(before, after, lang)
+ assert effect.effect == EFFECT_COMPATIBLE
+ assert effect.reason == reason
+
+
+ ("before", "after", "lang", "reason"),
+ [
+ ("def run(x, y)", "def run(x)", "python", "removed the required `y`"),
+ ("def run(x)", "def run(x, y)", "python", "added the required `y`"),
+ ("def run(x, y=1)", "def run(x, y)", "python", "`y` is now required"),
+ ("def run(x, y)", "def run(y, x)", "python", "reordered its parameters"),
+ (
+ "def f(a, timeout=1)",
+ "def f(a, deadline=1)",
+ "python",
+ "renamed `timeout` to `deadline`",
+ ),
+ ("F(int count) -> void", "F(int n) -> void", "csharp", "renamed `count` to `n`"),
+ (
+ "def run(x)",
+ "async def run(x)",
+ "python",
+ "became async, so its callers' await changes",
+ ),
+ # An optional parameter inserted ahead of one callers pass by position.
+ ("def f(a, b=1)", "def f(a, c=None, b=1)", "python", "inserted `c` before `b`"),
+ (
+ "function f(a: string, b?: number)",
+ "function f(a: string, c?: string, b?: number)",
+ "typescript",
+ "inserted `c` before `b`",
+ ),
+ ("def f(a, *args)", "def f(a, b=None, *args)", "python", "inserted `b` before `*args`"),
+ # Variadics are told apart by kind.
+ ("def f(a, *args, **kw)", "def f(a, **kw)", "python", "removed `*args`"),
+ ("def f(a, *args, **kw)", "def f(a, *args)", "python", "removed `**kw`"),
+ ("def f(a, *args)", "def f(a, **kw)", "python", "removed `*args`"),
+ ("def f(a, b=1)", "def f(a, *args, b=1)", "python", "made `b` keyword-only"),
+ ("def f(a, b=1)", "def f(a, *, b=1)", "python", "made `b` keyword-only"),
+ (
+ "def f(a, b)",
+ "def f(a, b, /)",
+ "python",
+ "made `a` positional-only and made `b` positional-only",
+ ),
+ # Shifts in a default value are operators, not generics.
+ ("def f(a=1 << 4, b=2, c=8 >> 1)", "def f(a=1 << 4, c=8 >> 1)", "python", "removed `b`"),
+ ("func (t T) M(a int)", "func (t *T) M(a int)", "go", "moved to a pointer receiver"),
+ # Typed languages: a retype or a new return type breaks the call.
+ (
+ "function f(x: string)",
+ "function f(x: number)",
+ "typescript",
+ "changed the type of `x` from `string` to `number`",
+ ),
+ (
+ "function f() -> Promise<void>",
+ "function f() -> void",
+ "typescript",
+ "changed its return type from `Promise<void>` to `void`",
+ ),
+ (
+ "fn f(x: &str)",
+ "fn f(x: &mut str)",
+ "rust",
+ "changed the type of `x` from `&str` to `&mut str`",
+ ),
+ (
+ "fn f(x: u32) -> u32",
+ "fn f(x: u32) -> Result<u32, E>",
+ "rust",
+ "changed its return type from `u32` to `Result<u32, E>`",
+ ),
+ (
+ "function F(a int) -> int",
+ "function F(a int) -> (int, error)",
+ "go",
+ "changed its return type from `int` to `(int, error)`",
+ ),
+ (
+ "func (s *S) F(a int) -> int",
+ "func (s *S) F(a int) -> (int, error)",
+ "go",
+ "changed its return type from `int` to `(int, error)`",
+ ),
+ (
+ "foo(int a) -> int",
+ "foo(int a) -> String",
+ "java",
+ "changed its return type from `int` to `String`",
+ ),
+ (
+ "Foo(int a) -> int",
+ "Foo(int a) -> string",
+ "csharp",
+ "changed its return type from `int` to `string`",
+ ),
+ (
+ "function C({a}: {a: string})",
+ "function C({a, b}: {a: string; b: number})",
+ "typescript",
+ "added the required member `b`",
+ ),
+ (
+ "operator()(int a) -> int",
+ "operator()(int a, int b) -> int",
+ "cpp",
+ "added the required `b`",
+ ),
+ ],
+)
+def test_changes_that_can_break_a_call_are_breaking(before, after, lang, reason):
+ effect = _effect(before, after, lang)
+ assert effect.effect == EFFECT_BREAKING
+ assert effect.reason == reason
+
+
+def test_a_static_method_gaining_self_breaks_calls_through_the_class():
+ effect = _effect("def f(a)", "def f(self, a)", "python", kind="method")
+ assert effect.effect == EFFECT_BREAKING
+ assert effect.reason == "became an instance method, so calls through the class break"
+
+
+def test_a_classmethod_becoming_static_is_compatible():
+ effect = _effect("def f(cls, a)", "def f(a)", "python", kind="method")
+ assert effect.effect == EFFECT_COMPATIBLE
+
+
+def test_a_leading_self_is_a_parameter_of_a_module_function():
+ effect = _effect("def f(self, a)", "def f(a)", "python", kind="function")
+ assert effect.effect == EFFECT_BREAKING
+
+
+def test_a_named_type_swapped_for_another_is_unknown_not_safe():
+ effect = _effect("function C({a}: OldProps)", "function C({a}: NewProps)", "typescript")
+ assert effect.effect == EFFECT_UNKNOWN
+
+
+def test_an_unbalanced_parameter_list_is_unknown_not_safe():
+ effect = _effect("def run(x, y)", "def run(x, y: Dict[str, int)", "python")
+ assert effect.effect == EFFECT_UNKNOWN
+
+
+def test_without_a_language_types_and_names_both_count():
+ assert _effect("f(x: A)", "f(x: B[])", None).effect in BREAKS
+ assert _effect("f(a)", "f(b)", None).effect in BREAKS
+
+
+def test_async_is_read_from_the_signature_prefix_only():
+ effect = _effect("def f(mode='async')", "def f(mode='async', x=1)", "python")
+ assert effect.effect == EFFECT_COMPATIBLE
+
+
+def test_an_arrow_type_does_not_unbalance_the_list():
+ before = "function run(cb: (a: number) => void)"
+ after = "function run(cb: (a: number) => void, opts?: Options)"
+ assert _effect(before, after, "typescript").effect == EFFECT_COMPATIBLE
+
+
+def test_a_lambda_default_does_not_split_the_list():
+ before = "def f(a, key=lambda x, y: x)"
+ after = "def f(a, key=lambda x, y: x, b=2)"
+ assert _effect(before, after, "python").reason == "added optional `b`"
+
+
+def test_a_block_comment_inside_the_signature_does_not_make_it_unparseable():
+ before = "function Drawer({\n row,\n}: {\n /** The drawer's row. */\n row: Row;\n})"
+ after = (
+ "function Drawer({\n row,\n onClose,\n}: {\n /** The drawer's row. */\n"
+ " row: Row;\n onClose?: () => void;\n})"
+ )
+ assert _effect(before, after, "typescript").effect == EFFECT_COMPATIBLE
+
+
+def test_a_widened_parameter_or_narrowed_return_type_is_compatible():
+ widened = _effect("function f(x: string)", "function f(x: string | null)", "typescript")
+ assert widened.effect == EFFECT_COMPATIBLE
+ narrowed = _effect("function f() -> string | null", "function f() -> string", "typescript")
+ assert narrowed.effect == EFFECT_COMPATIBLE
+ # The reverse promises callers something new to handle.
+ widened_return = _effect(
+ "function f() -> string", "function f() -> string | null", "typescript"
+ )
+ assert widened_return.effect == EFFECT_BREAKING
diff --git a/tests/unit/test_test_paths.py b/tests/unit/test_test_paths.py
index 7126e5b95..c24291d30 100644
--- a/tests/unit/test_test_paths.py
+++ b/tests/unit/test_test_paths.py
@@ -14,6 +14,7 @@ from repowise.core.test_paths import (
is_test_path,
is_test_related_path,
is_test_support_path,
+ is_unambiguous_test_path,
)
# (path, language or None, expected classification)
@@ -226,3 +227,25 @@ def test_camel_prefix_rule_mirrors_the_suffix_rule() -> None:
# leak onto an unrelated extension.
assert not is_test_path("src/testkeymap.dpr", "pascal")
assert not is_test_path("src/TestKeymap.txt", "pascal")
+
+
+ ("path", "expected"),
+ [
+ ("tests/unit/test_engine.py", True),
+ ("tests/conftest.py", True),
+ ("packages/ui/__tests__/table.test.tsx", True),
+ ("src/test/java/FooTest.java", True),
+ ("pkg/server/handler_test.go", True),
+ # Named like tests, but production modules inside a source tree.
+ ("packages/core/src/repowise/core/test_paths.py", False),
+ ("packages/core/src/repowise/core/analysis/test_impact.py", False),
+ ("packages/core/src/repowise/core/distill/filters/test_output.py", False),
+ ("src/app/lib/format.test.ts", False),
+ ("src/app/lib/format.py", False),
+ ],
+)
+def test_unambiguous_test_paths_need_more_than_a_test_shaped_name_under_src(
+ path: str, expected: bool
+) -> None:
+ assert is_unambiguous_test_path(path) is expected