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(workspace): a package-less gRPC stub meets its package-qualified proto, and a vendored proto copy serves nothing (#4537)

Raghav Chamadiya35a58fb3e512
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.md
index 77ac4b1d3..f1e017bf6 100644
--- a/docs/architecture/workspace.md
+++ b/docs/architecture/workspace.md
@@ -86,7 +86,7 @@ extensions, and hands the file list to every extractor. Each file becomes one
1. **Extension**, then **gate**: the file must hold one of the dialect's `requires`
tokens. `ScanContext.has_any` memoizes each token per file, so a token named by
several dialects or table rows is searched for once. A contract file format
- (`.proto`, `.sql`, `.prisma`) declares `EVERY_FILE`.
+ (`.sql`, `.prisma`) declares `EVERY_FILE`; `.proto` gates on `service`.
2. **Extract**: the dialect returns contracts built with `build_contract`, which
takes an `origin` and sets the confidence from it.
3. **Comment rule**: `run_dialect` drops a contract whose line is only a comment.
@@ -130,6 +130,11 @@ links are appended after it.
pattern subscription, `service_mapped` when the provider sits in the consumer's
resolved target. A target the map placed does not fall back to another repo that
serves the same path (`common.prefer_target_repo`).
+ A package-less gRPC stub id (`grpc::CurrencyService/*`) meets the package-qualified
+ proto id (`grpc::shop.CurrencyService/Convert`) on the service's last segment. A proto
+ declared in 2+ repos is served only by the repo that registers the service in code
+ (`common.shared_idl`); the other copies are vendored IDL, never linked or listed as
+ orphans. A .NET project's `<Protobuf GrpcServices="Client">` proto provides nothing.
4. **Type passes**, in `MATCHERS` order: HTTP `gateway_pass` (`gateway_route`),
`base_resolved_pass`, `candidate_pass` (`unique_path`, `ambiguous_path`, `prefix_stripped`) and `service_pass`; topic
`binding_pass` (`binding_routed`); data `shared_table_pass` (`shared_table`).
diff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.py
index 097ca6a96..2ce308b7d 100644
--- a/packages/core/src/repowise/core/workspace/diagnostics.py
+++ b/packages/core/src/repowise/core/workspace/diagnostics.py
@@ -30,6 +30,7 @@ from repowise.core.workspace.contracts import (
same_service,
)
from repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEX
+from repowise.core.workspace.matching.common import shared_idl
from repowise.core.workspace.network_probe import UNRECOGNISED_CALL_FILES_STAT
from repowise.core.workspace.signature_schema import SCHEMA_SOURCE
@@ -557,7 +558,9 @@ def build_diagnostics(
contract. Omitting it costs the coverage figures, not the rest.
"""
stats_by_repo = extraction_stats or {}
- providers = [c for c in contracts if c.role == "provider"]
+ # A vendored proto copy is counted with its repo's rows, never as an orphan.
+ vendored = shared_idl(contracts)
+ providers = [c for c in contracts if c.role == "provider" and id(c) not in vendored]
consumers = [c for c in contracts if c.role == "consumer"]
# Per-repo breakdown ----------------------------------------------------
diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc/proto.py b/packages/core/src/repowise/core/workspace/extractors/grpc/proto.py
index 532de1ddf..a020c32dd 100644
--- a/packages/core/src/repowise/core/workspace/extractors/grpc/proto.py
+++ b/packages/core/src/repowise/core/workspace/extractors/grpc/proto.py
@@ -14,13 +14,15 @@ as service parsing — no new parser.
from __future__ import annotations
+import posixpath
import re
+from fnmatch import fnmatchcase
from typing import TYPE_CHECKING, NamedTuple
from repowise.core.workspace.contract_schema import ContractSchema, SchemaField
from repowise.core.workspace.origins import ContractOrigin
-from ..dialect import EVERY_FILE, build_contract
+from ..dialect import build_contract
from ..langs import PROTO
if TYPE_CHECKING:
@@ -211,12 +213,70 @@ def _parse_proto_file(
return package, services, messages
+#: MSBuild projects, whose ``<Protobuf>`` items say which side a proto generates.
+_PROJECT_FILES = frozenset({".csproj", ".fsproj", ".vbproj"})
+_PROTOBUF_ITEM_RE = re.compile(r"<Protobuf\b([^>]*)>", re.IGNORECASE)
+_ITEM_PATH_RE = re.compile(r"""\b(?:Include|Update)\s*=\s*["']([^"']+)["']""", re.IGNORECASE)
+_GRPC_SERVICES_RE = re.compile(r"""\bGrpcServices\s*=\s*["'](\w+)["']""", re.IGNORECASE)
+
+
+def client_only_protos(project_rel_path: str, content: str) -> list[str]:
+ """Repo-relative path patterns of the protos a project compiles without a server.
+
+ ``<Protobuf Include="x.proto" GrpcServices="Client" />`` (or ``None``)
+ generates a client stub or messages only, so the project serves nothing
+ that proto declares. A path outside the repo is kept as written and
+ matches nothing.
+ """
+ base = posixpath.dirname(project_rel_path)
+ out: list[str] = []
+ content = re.sub(r"<!--.*?-->", "", content, flags=re.DOTALL)
+ for item in _PROTOBUF_ITEM_RE.finditer(content):
+ attrs = item.group(1)
+ side = _GRPC_SERVICES_RE.search(attrs)
+ path = _ITEM_PATH_RE.search(attrs)
+ if side is None or path is None or side.group(1).lower() not in ("client", "none"):
+ continue
+ out.append(posixpath.normpath(posixpath.join(base, path.group(1).replace("\\", "/"))))
+ return out
+
+
+class _ProtoPass:
+ """One repo's protos, less those a project file compiles as client-only."""
+
+ def __init__(self, dialect: ProtoDialect) -> None:
+ self._dialect = dialect
+ self._found: list[Contract] = []
+ self._client_only: list[str] = []
+
+ def scan(self, ctx: ScanContext) -> None:
+ if ctx.suffix in _PROJECT_FILES:
+ self._client_only.extend(client_only_protos(ctx.rel_path, ctx.content))
+ else:
+ self._found.extend(self._dialect.extract(ctx))
+
+ def finish(self) -> list[Contract]:
+ patterns = self._client_only
+ return [
+ c
+ for c in self._found
+ if not any(fnmatchcase(c.file_path.lower(), p.lower()) for p in patterns)
+ ]
+
+
class ProtoDialect:
name = "proto"
- extensions = PROTO
- requires = EVERY_FILE
+ extensions = PROTO | _PROJECT_FILES
+ #: A proto provides through a ``service`` block; a project file names the
+ #: client side with ``GrpcServices``.
+ requires = ("service", "GrpcServices")
+
+ def repo_pass(self) -> _ProtoPass:
+ return _ProtoPass(self)
def extract(self, ctx: ScanContext) -> list[Contract]:
+ if ctx.suffix not in PROTO:
+ return []
package, services, messages = _parse_proto_file(ctx.content)
out: list[Contract] = []
for svc in services:
diff --git a/packages/core/src/repowise/core/workspace/matching/common.py b/packages/core/src/repowise/core/workspace/matching/common.py
index e482460b2..31bcabe5f 100644
--- a/packages/core/src/repowise/core/workspace/matching/common.py
+++ b/packages/core/src/repowise/core/workspace/matching/common.py
@@ -38,12 +38,17 @@ class MatchState:
@classmethod
def build(cls, contracts: list[Contract]) -> MatchState:
- """Index providers by normalized id; consumers resolved to a third party are dropped."""
+ """Index providers by normalized id; consumers resolved to a third party are dropped.
+
+ A vendored ``.proto`` copy (see :func:`shared_idl`) is not indexed.
+ """
provider_index: dict[str, list[Contract]] = defaultdict(list)
consumers: list[Contract] = []
+ vendored = shared_idl(contracts)
for c in contracts:
if c.role == "provider":
- provider_index[normalize_contract_id(c.contract_id)].append(c)
+ if id(c) not in vendored:
+ provider_index[normalize_contract_id(c.contract_id)].append(c)
elif not c.meta.get("external"):
consumers.append(c)
return cls(provider_index, consumers)
@@ -150,7 +155,10 @@ def find_matching_keys(consumer_id: str, provider_index: dict[str, list[Contract
if wildcard_key in provider_index:
return [wildcard_key]
- # gRPC wildcard: grpc::service/* matches grpc::service/Method
+ if normalized.startswith("grpc::"):
+ return _grpc_keys(normalized, provider_index)
+
+ # Any other wildcard: kind::name/* matches kind::name/Member
if normalized.endswith("/*"):
prefix = normalized[:-1] # "grpc::service/"
return [k for k in provider_index if k.startswith(prefix)]
@@ -158,6 +166,80 @@ def find_matching_keys(consumer_id: str, provider_index: dict[str, list[Contract
return []
+def _same_grpc_service(provider: str, consumer: str) -> bool:
+ """Whether two lower-cased service names are one service.
+
+ A generated stub often names its service without the proto package
+ (``CurrencyService``) while the ``.proto`` names it with one
+ (``hipstershop.CurrencyService``): a bare name meets a qualified one on its
+ last segment. Two different packages are two services.
+ """
+ if provider == consumer:
+ return True
+ if "." in provider and "." in consumer:
+ return False
+ return provider.rpartition(".")[2] == consumer.rpartition(".")[2]
+
+
+def _grpc_keys(normalized: str, provider_index: dict[str, list[Contract]]) -> list[str]:
+ """gRPC index keys *normalized* reaches: the same method, or any for ``/*``."""
+ service, _, method = normalized[len("grpc::") :].rpartition("/")
+ if not service:
+ return []
+ keys = []
+ for k in provider_index:
+ if not k.startswith("grpc::"):
+ continue
+ k_service, _, k_method = k[len("grpc::") :].rpartition("/")
+ if (method == "*" or k_method == method) and _same_grpc_service(k_service, service):
+ keys.append(k)
+ return keys
+
+
+def _grpc_service(contract: Contract) -> str:
+ """The lower-cased service segment of a gRPC contract id."""
+ return normalize_contract_id(contract.contract_id)[len("grpc::") :].rpartition("/")[0]
+
+
+def shared_idl(contracts: list[Contract]) -> set[int]:
+ """The ``id()`` of each ``.proto`` provider row that is a vendored copy, not the server.
+
+ Services keep a copy of the protos they call (often the whole estate's
+ file), so a service declared in 2+ repos is served by whichever of them
+ registers it in code. With no code server anywhere, the one copy outside
+ the repos that call the service stands; when that is not exactly one,
+ no copy is trusted. A service declared in one repo is untouched.
+ """
+ copies: dict[str, list[Contract]] = defaultdict(list)
+ servers: dict[str, set[str]] = defaultdict(set)
+ callers: dict[str, set[str]] = defaultdict(set)
+ for c in contracts:
+ if c.contract_type != "grpc":
+ continue
+ service = _grpc_service(c)
+ bare = service.rpartition(".")[2]
+ if c.role == "provider" and c.meta.get("source") == "proto":
+ copies[service].append(c)
+ elif c.role == "provider":
+ servers[bare].add(c.repo)
+ elif c.role == "consumer":
+ callers[bare].add(c.repo)
+ vendored: set[int] = set()
+ for service, rows in copies.items():
+ repos = {c.repo for c in rows}
+ if len(repos) < 2:
+ continue
+ bare = service.rpartition(".")[2]
+ if servers.get(bare):
+ keep = repos & servers[bare]
+ else:
+ keep = repos - callers.get(bare, set())
+ if len(keep) != 1:
+ keep = set()
+ vendored.update(id(c) for c in rows if c.repo not in keep)
+ return vendored
+
+
def prefer_target_repo(providers: list[Contract], consumer: Contract) -> list[Contract]:
"""Narrow *providers* to the consumer's resolved ``target_repo`` when set.
diff --git a/tests/unit/workspace/test_grpc_shared_idl.py b/tests/unit/workspace/test_grpc_shared_idl.py
new file mode 100644
index 000000000..d32a34114
--- /dev/null
+++ b/tests/unit/workspace/test_grpc_shared_idl.py
@@ -0,0 +1,203 @@
+"""A package-less stub meets its package-qualified proto; a vendored proto copy serves nothing.
+
+Generated stubs name a service without its proto package (``CurrencyService``),
+the ``.proto`` names it with one (``shop.CurrencyService``). Services also keep
+copies of the protos they call, so once the two ids meet, every copy would read
+as a server. Only the repo that registers the service in code serves it, and a
+.NET project that compiles a proto with ``GrpcServices="Client"`` serves none of it.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.workspace.contracts import Contract
+from repowise.core.workspace.diagnostics import build_diagnostics
+from repowise.core.workspace.extractors.grpc import GrpcExtractor
+from repowise.core.workspace.matching import match_contracts
+from repowise.core.workspace.matching.common import find_matching_keys
+
+_PROTO = """\
+syntax = "proto3";
+package shop;
+
+service CurrencyService {
+ rpc Convert(ConvertRequest) returns (Money) {}
+}
+
+service PaymentService {
+ rpc Charge(ChargeRequest) returns (ChargeResponse) {}
+}
+"""
+
+_NODE_SERVER = """\
+const grpc = require('@grpc/grpc-js');
+const server = new grpc.Server();
+server.addService(shopPackage.CurrencyService.service, {convert});
+"""
+
+_GO_CLIENT = """\
+package main
+
+import pb "example.com/shop/genproto"
+
+func dial(conn *grpc.ClientConn) {
+ c := pb.NewCurrencyServiceClient(conn)
+ p := pb.NewPaymentServiceClient(conn)
+ _, _ = c, p
+}
+"""
+
+_NEST_SERVER = """\
+@Controller()
+export class PaymentController {
+ @GrpcMethod('PaymentService', 'Charge')
+ charge(req) {}
+}
+"""
+
+
+def _repo(root: Path, alias: str, files: dict[str, str]) -> list[Contract]:
+ repo = root / alias
+ for rel, text in files.items():
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ return GrpcExtractor().extract(repo, alias)
+
+
+def _pairs(contracts: list[Contract]) -> set[tuple[str, str, str]]:
+ return {(lk.consumer_repo, lk.provider_repo, lk.provider_file) for lk in match_contracts(contracts)}
+
+
+def _contract(repo: str, contract_id: str, role: str, source: str) -> Contract:
+ return Contract(
+ repo=repo,
+ contract_id=contract_id,
+ contract_type="grpc",
+ role=role,
+ file_path=f"{source}.x",
+ symbol_name=contract_id,
+ confidence=0.85,
+ meta={"source": source},
+ )
+
+
+class TestQualifiedIds:
+ def test_a_package_less_stub_reaches_the_only_proto(self) -> None:
+ contracts = [
+ _contract("currency", "grpc::shop.CurrencyService/Convert", "provider", "proto"),
+ _contract("frontend", "grpc::CurrencyService/*", "consumer", "go_client"),
+ ]
+ links = match_contracts(contracts)
+ assert [(lk.provider_repo, lk.consumer_contract_id) for lk in links] == [
+ ("currency", "grpc::CurrencyService/*")
+ ]
+
+ def test_a_qualified_stub_reaches_a_package_less_server(self) -> None:
+ index = {"grpc::currencyservice/*": []}
+ assert find_matching_keys("grpc::shop.CurrencyService/*", index) == ["grpc::currencyservice/*"]
+
+ def test_two_packages_are_two_services(self) -> None:
+ index = {"grpc::billing.currencyservice/Convert": []}
+ assert find_matching_keys("grpc::shop.CurrencyService/*", index) == []
+
+ def test_a_named_method_still_needs_that_method(self) -> None:
+ index = {"grpc::shop.currencyservice/Convert": [], "grpc::shop.currencyservice/List": []}
+ assert find_matching_keys("grpc::CurrencyService/List", index) == [
+ "grpc::shop.currencyservice/List"
+ ]
+
+ def test_http_and_topic_keys_are_unchanged(self) -> None:
+ index = {
+ "http::GET::/api/currency": [],
+ "topic::orders/created": [],
+ "grpc::shop.orders/Create": [],
+ }
+ assert find_matching_keys("http::*::/api/currency", index) == ["http::GET::/api/currency"]
+ assert find_matching_keys("topic::orders/*", index) == ["topic::orders/created"]
+ assert find_matching_keys("http::GET::/orders", index) == []
+
+
+class TestVendoredProtos:
+ def test_only_the_repo_that_serves_the_service_links(self, tmp_path: Path) -> None:
+ # Four repos vendor one proto; `currency` serves one service and
+ # `payment` the other, by method, so the stub reaches the proto ids too.
+ contracts = [
+ *_repo(tmp_path, "currency", {"proto/shop.proto": _PROTO, "server.js": _NODE_SERVER}),
+ *_repo(tmp_path, "payment", {"proto/shop.proto": _PROTO, "app.controller.ts": _NEST_SERVER}),
+ *_repo(tmp_path, "frontend", {"proto/shop.proto": _PROTO, "rpc.go": _GO_CLIENT}),
+ *_repo(tmp_path, "checkout", {"proto/shop.proto": _PROTO, "main.go": _GO_CLIENT}),
+ ]
+ assert _pairs(contracts) == {
+ ("frontend", "currency", "server.js"),
+ ("checkout", "currency", "server.js"),
+ ("frontend", "payment", "app.controller.ts"),
+ ("frontend", "payment", "proto/shop.proto"),
+ ("checkout", "payment", "app.controller.ts"),
+ ("checkout", "payment", "proto/shop.proto"),
+ }
+
+ def test_with_no_server_the_one_copy_outside_its_callers_stands(self) -> None:
+ contracts = [
+ _contract("idl", "grpc::shop.CurrencyService/Convert", "provider", "proto"),
+ _contract("frontend", "grpc::shop.CurrencyService/Convert", "provider", "proto"),
+ _contract("frontend", "grpc::CurrencyService/*", "consumer", "go_client"),
+ ]
+ assert {(c, p) for c, p, _ in _pairs(contracts)} == {("frontend", "idl")}
+
+ def test_with_no_server_and_two_candidates_no_copy_is_trusted(self) -> None:
+ contracts = [
+ _contract("ads", "grpc::shop.CurrencyService/Convert", "provider", "proto"),
+ _contract("payment", "grpc::shop.CurrencyService/Convert", "provider", "proto"),
+ _contract("frontend", "grpc::CurrencyService/*", "consumer", "go_client"),
+ ]
+ assert match_contracts(contracts) == []
+
+ def test_vendored_copies_are_not_orphans(self) -> None:
+ contracts = [
+ _contract("currency", "grpc::CurrencyService/*", "provider", "js_add_service"),
+ _contract("currency", "grpc::shop.CurrencyService/Convert", "provider", "proto"),
+ _contract("payment", "grpc::shop.CurrencyService/Convert", "provider", "proto"),
+ ]
+ orphans = build_diagnostics(contracts, []).orphan_providers
+ assert sorted(o.repo for o in orphans) == ["currency", "currency"]
+
+
+class TestProjectGrpcServices:
+ _CLIENT_PROJECT = (
+ "<Project>\n <ItemGroup>\n"
+ ' <Protobuf Include="Protos\\shop.proto" OutputDir="" GrpcServices="Client">\n'
+ " </Protobuf>\n </ItemGroup>\n</Project>\n"
+ )
+
+ def test_a_client_only_proto_provides_nothing(self, tmp_path: Path) -> None:
+ contracts = _repo(
+ tmp_path, "clientapp", {"ClientApp.csproj": self._CLIENT_PROJECT, "Protos/shop.proto": _PROTO}
+ )
+ assert contracts == []
+
+ def test_a_server_proto_still_provides(self, tmp_path: Path) -> None:
+ project = '<Project><ItemGroup><Protobuf Include="Proto\\shop.proto" GrpcServices="Server" /></ItemGroup></Project>'
+ contracts = _repo(tmp_path, "basket", {"Basket.csproj": project, "Proto/shop.proto": _PROTO})
+ assert sorted(c.contract_id for c in contracts) == [
+ "grpc::shop.CurrencyService/Convert",
+ "grpc::shop.PaymentService/Charge",
+ ]
+
+ def test_a_commented_out_item_is_not_read(self, tmp_path: Path) -> None:
+ project = f"<!--{self._CLIENT_PROJECT}-->"
+ contracts = _repo(tmp_path, "app", {"App.csproj": project, "Protos/shop.proto": _PROTO})
+ assert len(contracts) == 2
+
+ def test_paths_resolve_from_the_project_and_globs_match(self, tmp_path: Path) -> None:
+ project = (
+ '<Project><ItemGroup><Protobuf Update="..\\shared\\*.proto" GrpcServices="None" />'
+ "</ItemGroup></Project>"
+ )
+ contracts = _repo(
+ tmp_path,
+ "web",
+ {"src/Web/Web.csproj": project, "src/shared/shop.proto": _PROTO, "api/own.proto": _PROTO},
+ )
+ assert {c.file_path for c in contracts} == {"api/own.proto"}