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): count unread messaging SDK calls in the network probe and unresolved topic names in diagnostics (#4667)

Raghav Chamadiya226a02269d36
diff --git a/docs/architecture/workspace.md b/docs/architecture/workspace.md
index 968c46891..ba5730c93 100644
--- a/docs/architecture/workspace.md
+++ b/docs/architecture/workspace.md
@@ -105,7 +105,10 @@ After the dialects, `code_api.py` adds published-package contracts,
`merge_openapi_providers` folds an OpenAPI operation into the code route it
describes, `bind_symbol_ids` binds each contract to a symbol in the repo's index,
and `network_probe.count_unrecognised_call_files` counts the files that call out
-with no consumer contract read from them.
+with no consumer contract read from them. It runs again over `MESSAGE_PROBE_ROWS`
+for files on a messaging SDK with no topic contract, kept apart from the HTTP
+figure. A topic dialect that locates a call but cannot settle its name records it
+with `ScanContext.note_unresolved`, summed into `topic_names_unresolved`.
### Matching
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
index 9f163e0df..05f876acc 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd/diagnostics.py
@@ -130,6 +130,8 @@ def _emit_diagnostics_json(
"http_consumers_linked": diag.http_consumers_linked,
"http_link_coverage": diag.http_link_coverage,
"unrecognised_call_files": diag.unrecognised_call_files,
+ "topic_names_unresolved": diag.topic_names_unresolved,
+ "unrecognised_message_files": diag.unrecognised_message_files,
"evidence": graph_evidence(graph).to_dict(),
}
)
@@ -182,6 +184,7 @@ def _print_extraction_coverage(diag: ExtractionDiagnostics) -> None:
layers = _layers(diag.consumers_by_layer)
console.print(f" Consumers {diag.total_consumers} ({layers})")
_print_call_coverage(diag)
+ _print_topic_coverage(diag)
console.print(
" [dim]'index' contracts come from the parsed symbol table, 'regex' "
"from a text dialect.[/dim]"
@@ -234,6 +237,32 @@ def _print_call_coverage(diag: ExtractionDiagnostics) -> None:
)
+def _print_topic_coverage(diag: ExtractionDiagnostics) -> None:
+ """Topic contracts read, broker calls not named, and files on a messaging SDK no dialect reads.
+
+ Counts only: a file on an unread SDK is a floor of one call, not a call
+ count, so no share is claimed. Silent on an artifact older than the probe.
+ """
+ missed = diag.unrecognised_message_file_count
+ if missed is None:
+ return
+ read = diag.topic_contracts_read
+ unresolved = diag.topic_names_unresolved
+ if not (read or unresolved or missed):
+ return
+ console.print(
+ f" Topic calls {read} read, {unresolved} located but the name not statically "
+ f"resolvable, {missed} file(s) using a messaging SDK no dialect reads."
+ )
+ by_repo = [(repo, n) for repo, n in (diag.unrecognised_message_files or {}).items() if n]
+ if by_repo:
+ console.print(
+ " [dim]unread messaging calls: "
+ + ", ".join(f"{repo} {n}" for repo, n in by_repo)
+ + "[/dim]"
+ )
+
+
def _unlinked_http_split(diag: ExtractionDiagnostics) -> str:
"""Where the read but unlinked HTTP calls went, workspace wide."""
counts, in_service = diag.http_unlinked()
diff --git a/packages/core/src/repowise/core/report/sections/estate_contracts.py b/packages/core/src/repowise/core/report/sections/estate_contracts.py
index 431b33d33..321112d0e 100644
--- a/packages/core/src/repowise/core/report/sections/estate_contracts.py
+++ b/packages/core/src/repowise/core/report/sections/estate_contracts.py
@@ -159,6 +159,40 @@ def _http_coverage(graph: Any) -> dict[str, Any]:
)
+def _topic_coverage(graph: Any) -> dict[str, Any] | None:
+ """Topic contracts read beside the broker calls not named and the files on an unread SDK.
+
+ None on an artifact older than the messaging probe, which cannot say what it missed.
+ """
+ diag = graph.diagnostics
+ missed = diag.unrecognised_message_file_count
+ if missed is None:
+ return None
+ read = diag.topic_contracts_read
+ unresolved = diag.topic_names_unresolved
+ by_repo = [
+ f"{repo}: {n} file(s)"
+ for repo, n in sorted((diag.unrecognised_message_files or {}).items())
+ if n
+ ]
+ return check(
+ "topic-calls",
+ reason=(
+ f"{read} topic publish or subscribe call(s) read as contracts, {unresolved} located "
+ f"but the name not resolvable, {missed} file(s) using a messaging SDK no extractor reads"
+ if read or unresolved or missed
+ else "no broker call located, and no file uses a recognisable messaging SDK"
+ ),
+ details=capped(by_repo),
+ method=(
+ "topic contracts read, beside broker calls located whose topic or queue name is not "
+ "settled in the file and files importing a messaging SDK that yielded no topic contract"
+ ),
+ basis="measured",
+ data={"read": read, "unresolved": unresolved, "unrecognised_message_files": missed},
+ )
+
+
def _dangling(graph: Any, store: Any) -> dict[str, Any]:
rows = dangling_calls(graph, store)
external = [r for r in rows if r["external"]]
@@ -198,7 +232,13 @@ async def collect(ctx: WorkspaceReportContext) -> list[dict[str, Any]]:
if graph is None:
return missing_graph("contracts", _METHOD)
store = ctx.contract_store()
- return [_contracts(graph, store), _http_coverage(graph), _dangling(graph, store)]
+ topics = _topic_coverage(graph)
+ return [
+ _contracts(graph, store),
+ _http_coverage(graph),
+ *([topics] if topics else []),
+ _dangling(graph, store),
+ ]
report_sections.register(
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index 645d5891e..44a1d5d31 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -98,6 +98,9 @@ TOPIC_KIND_BINDING = "binding"
#: Set on a publish or binding whose routing key the file does not settle; the
#: topic matcher refuses to route through it rather than read it as match-all.
TOPIC_ROUTING_KEY_UNRESOLVED = "routing_key_unresolved"
+#: ``extraction_stats`` key: broker calls located whose destination name the
+#: file does not settle (an env var, a constant in another file), so no contract.
+TOPIC_NAMES_UNRESOLVED_STAT = "topic_names_unresolved"
#: ``meta`` key of a consumer subscribed by pattern (``orders.*``); its value
#: names the pattern syntax.
TOPIC_PATTERN = "pattern"
@@ -853,11 +856,11 @@ def _extractor_kwargs(
extractor: Any, repo_index: RepoIndex | None, stats: dict[str, int], message_types: Any
) -> dict[str, Any]:
"""Extra keyword arguments an extractor's ``extract`` takes."""
- from .extractors import HttpExtractor, MassTransitExtractor, OpenApiExtractor
+ from .extractors import HttpExtractor, MassTransitExtractor, OpenApiExtractor, TopicExtractor
if isinstance(extractor, HttpExtractor):
return {"repo_index": repo_index, "stats": stats}
- if isinstance(extractor, OpenApiExtractor):
+ if isinstance(extractor, (OpenApiExtractor, TopicExtractor)):
return {"stats": stats}
if isinstance(extractor, MassTransitExtractor):
return {"message_types": message_types, "stats": stats}
@@ -875,7 +878,6 @@ async def _extract_one_repo(
from .extractors import assign_service, detect_service_boundaries, merge_openapi_providers
from .extractors.base import iter_source_files
from .extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEX
- from .network_probe import UNRECOGNISED_CALL_FILES_STAT, count_unrecognised_call_files
code_surface = extraction.code_surface
contracts: list[Contract] = []
@@ -934,9 +936,10 @@ async def _extract_one_repo(
stats.update(attach_signature_schemas(contracts, repo_index))
# The calls no dialect read, the miss half of any coverage figure.
- consumer_files = {c.file_path for c in contracts if c.role == "consumer"}
- stats[UNRECOGNISED_CALL_FILES_STAT] = await asyncio.to_thread(
- count_unrecognised_call_files, files, consumer_files
+ stats.update(
+ await asyncio.to_thread(
+ _probe_misses, files, contracts, extraction.contract_config.detect_topics
+ )
)
unresolved = stats.get("http_consumer_unresolved", 0)
@@ -950,6 +953,28 @@ async def _extract_one_repo(
return contracts, stats
+def _probe_misses(
+ files: list[Any], contracts: list[Contract], detect_topics: bool
+) -> dict[str, int]:
+ """The network probe's counts: HTTP calls, then messaging SDK calls, no dialect read."""
+ from .network_probe import (
+ MESSAGE_PROBE_ROWS,
+ UNRECOGNISED_CALL_FILES_STAT,
+ UNRECOGNISED_MESSAGE_FILES_STAT,
+ count_unrecognised_call_files,
+ )
+
+ consumer_files = {c.file_path for c in contracts if c.role == "consumer"}
+ out = {UNRECOGNISED_CALL_FILES_STAT: count_unrecognised_call_files(files, consumer_files)}
+ if detect_topics:
+ # A publish is a provider, so any topic contract excuses a messaging file.
+ topic_files = {c.file_path for c in contracts if c.contract_type == "topic"}
+ out[UNRECOGNISED_MESSAGE_FILES_STAT] = count_unrecognised_call_files(
+ files, topic_files, MESSAGE_PROBE_ROWS
+ )
+ return out
+
+
def _merge_repo_results(
repo_paths: dict[str, Path],
fresh: dict[str, tuple[list[Contract], dict[str, int]]],
diff --git a/packages/core/src/repowise/core/workspace/diagnostics.py b/packages/core/src/repowise/core/workspace/diagnostics.py
index f59a00ffe..f9e4511da 100644
--- a/packages/core/src/repowise/core/workspace/diagnostics.py
+++ b/packages/core/src/repowise/core/workspace/diagnostics.py
@@ -24,6 +24,7 @@ from typing import Any
from repowise.core.workspace.code_api import CODE_CONTRACT_TYPE
from repowise.core.workspace.contracts import (
TOPIC_KIND_BINDING,
+ TOPIC_NAMES_UNRESOLVED_STAT,
Contract,
ContractLink,
normalize_contract_id,
@@ -31,7 +32,11 @@ from repowise.core.workspace.contracts import (
)
from repowise.core.workspace.extractors.from_index import EXTRACTION_LAYER_KEY, LAYER_REGEX
from repowise.core.workspace.matching.common import AMBIGUOUS_PROVIDER, shared_idl
-from repowise.core.workspace.network_probe import UNRECOGNISED_CALL_FILES_STAT, outside_runtime
+from repowise.core.workspace.network_probe import (
+ UNRECOGNISED_CALL_FILES_STAT,
+ UNRECOGNISED_MESSAGE_FILES_STAT,
+ outside_runtime,
+)
from repowise.core.workspace.signature_schema import SCHEMA_SOURCE
# ---------------------------------------------------------------------------
@@ -98,6 +103,8 @@ class RepoDiagnostics:
#: Calls that reached a confirmed HTTP wrapper but whose path could not be
#: resolved statically. Real endpoint calls, located and then not named.
http_consumers_unresolved: int = 0
+ #: Broker calls located whose topic or queue name the file does not settle.
+ topic_names_unresolved: int = 0
def to_dict(self) -> dict[str, Any]:
return asdict(self)
@@ -352,6 +359,17 @@ class ExtractionDiagnostics:
#: HTTP consumers that formed a cross-repo link. None on an artifact
#: written before this count, which only knew which calls were read.
http_consumers_linked: int | None = None
+ #: Broker calls located whose topic or queue name could not be settled.
+ topic_names_unresolved: int = 0
+ #: Per repo, files using a messaging SDK that produced no topic contract
+ #: (:data:`.network_probe.MESSAGE_PROBE_ROWS`). None when no repo was probed.
+ unrecognised_message_files: dict[str, int] | None = None
+
+ @property
+ def unrecognised_message_file_count(self) -> int | None:
+ if self.unrecognised_message_files is None:
+ return None
+ return sum(self.unrecognised_message_files.values())
@property
def unrecognised_call_file_count(self) -> int | None:
@@ -381,6 +399,14 @@ class ExtractionDiagnostics:
"""HTTP consumer contracts read, linked or not."""
return sum(r.consumers_by_type.get("http", 0) for r in self.repo_breakdown)
+ @property
+ def topic_contracts_read(self) -> int:
+ """Topic contracts read, publishes and subscriptions both."""
+ return sum(
+ r.providers_by_type.get("topic", 0) + r.consumers_by_type.get("topic", 0)
+ for r in self.repo_breakdown
+ )
+
@property
def http_calls_seen(self) -> int | None:
"""The coverage denominator: calls read, calls located, unread files.
@@ -446,6 +472,9 @@ class ExtractionDiagnostics:
"openapi": self.openapi.to_dict(),
"unrecognised_call_files": self.unrecognised_call_files,
"unrecognised_call_file_count": self.unrecognised_call_file_count,
+ "topic_names_unresolved": self.topic_names_unresolved,
+ "unrecognised_message_files": self.unrecognised_message_files,
+ "unrecognised_message_file_count": self.unrecognised_message_file_count,
}
@classmethod
@@ -476,6 +505,7 @@ class ExtractionDiagnostics:
providers_by_layer=r.get("providers_by_layer", {}),
consumers_by_layer=r.get("consumers_by_layer", {}),
http_consumers_unresolved=r.get("http_consumers_unresolved", 0),
+ topic_names_unresolved=r.get("topic_names_unresolved", 0),
)
for r in data.get("repo_breakdown", [])
],
@@ -522,6 +552,8 @@ class ExtractionDiagnostics:
openapi=OpenApiCoverage.from_dict(openapi),
unrecognised_call_files=data.get("unrecognised_call_files"),
http_consumers_linked=data.get("http_consumers_linked"),
+ topic_names_unresolved=data.get("topic_names_unresolved", 0),
+ unrecognised_message_files=data.get("unrecognised_message_files"),
)
@@ -622,6 +654,9 @@ def build_diagnostics(
http_consumers_unresolved=stats_by_repo.get(repo, {}).get(
"http_consumer_unresolved", 0
),
+ topic_names_unresolved=stats_by_repo.get(repo, {}).get(
+ TOPIC_NAMES_UNRESOLVED_STAT, 0
+ ),
)
)
@@ -705,13 +740,17 @@ def build_diagnostics(
schema_coverage=schema,
code_api=code_api,
openapi=OpenApiCoverage.from_stats(stats_by_repo),
- unrecognised_call_files=_unrecognised_call_files(stats_by_repo),
+ unrecognised_call_files=_probe_counts(stats_by_repo, UNRECOGNISED_CALL_FILES_STAT),
http_consumers_linked=sum(
1
for c in consumers
if c.contract_type == "http"
and _contract_key(c.repo, c.file_path, c.contract_id) in matched_consumers
),
+ topic_names_unresolved=sum(
+ s.get(TOPIC_NAMES_UNRESOLVED_STAT, 0) for s in stats_by_repo.values()
+ ),
+ unrecognised_message_files=_probe_counts(stats_by_repo, UNRECOGNISED_MESSAGE_FILES_STAT),
)
@@ -810,13 +849,9 @@ def _orphan_providers(
return orphans
-def _unrecognised_call_files(
- stats_by_repo: dict[str, dict[str, int]],
-) -> dict[str, int] | None:
- """The probe's per-repo counts, or None when no repo carries one."""
+def _probe_counts(stats_by_repo: dict[str, dict[str, int]], key: str) -> dict[str, int] | None:
+ """A probe's per-repo counts under *key*, or None when no repo carries one."""
counts = {
- repo: stats[UNRECOGNISED_CALL_FILES_STAT]
- for repo, stats in sorted(stats_by_repo.items())
- if UNRECOGNISED_CALL_FILES_STAT in stats
+ repo: stats[key] for repo, stats in sorted(stats_by_repo.items()) if key in stats
}
return counts or None
diff --git a/packages/core/src/repowise/core/workspace/extractors/base.py b/packages/core/src/repowise/core/workspace/extractors/base.py
index 3730abb74..96876957f 100644
--- a/packages/core/src/repowise/core/workspace/extractors/base.py
+++ b/packages/core/src/repowise/core/workspace/extractors/base.py
@@ -94,15 +94,17 @@ def _comment_mask(suffix: str, content: str) -> str | None:
class _FileMemo:
- """What one file's dialects share: each gate token's presence, and the comment mask."""
+ """What one file's dialects share: each gate token's presence, the comment mask,
+ and the offsets of calls located but not named."""
- __slots__ = ("lines", "mask", "masked", "tokens")
+ __slots__ = ("lines", "mask", "masked", "tokens", "unresolved")
def __init__(self) -> None:
self.tokens: dict[str, bool] = {}
self.masked = False
self.mask: str | None = None
self.lines: tuple[list[str], list[str]] | None = None
+ self.unresolved: set[int] = set()
@dataclass(frozen=True)
@@ -144,6 +146,15 @@ class ScanContext:
return True
return False
+ def note_unresolved(self, offset: int) -> None:
+ """Record a call at *offset* whose destination this file cannot settle."""
+ self._memo.unresolved.add(offset)
+
+ @property
+ def unresolved_calls(self) -> int:
+ """Calls :meth:`note_unresolved` recorded: one per site, however many dialects read it."""
+ return len(self._memo.unresolved)
+
def _mask(self) -> str | None:
memo = self._memo
if not memo.masked:
diff --git a/packages/core/src/repowise/core/workspace/extractors/dialect.py b/packages/core/src/repowise/core/workspace/extractors/dialect.py
index 07f4303c1..4f890d6ff 100644
--- a/packages/core/src/repowise/core/workspace/extractors/dialect.py
+++ b/packages/core/src/repowise/core/workspace/extractors/dialect.py
@@ -164,11 +164,14 @@ class DialectExtractor:
Subclasses set ``dialects``. ``identity``, when set, keeps the first
contract per key within a file, for contract types whose many call sites
- of one name are one fact.
+ of one name are one fact. ``unresolved_stat``, when set, is the *stats*
+ key that counts the calls a dialect located but could not name
+ (:meth:`..base.ScanContext.note_unresolved`).
"""
dialects: tuple[ContractDialect, ...] = ()
identity: Callable[[Contract], Hashable] | None = None
+ unresolved_stat: str | None = None
@classmethod
def source_extensions(cls) -> frozenset[str]:
@@ -181,9 +184,14 @@ class DialectExtractor:
repo_alias: str = "",
exclude: Callable[[str], bool] | None = None,
files: Sequence[SourceFile] | None = None,
+ stats: dict[str, int] | None = None,
) -> list[Contract]:
- """Scan *repo_path* (or the already-walked *files*) for contracts."""
+ """Scan *repo_path* (or the already-walked *files*) for contracts.
+
+ *stats* is an optional out-dict that ``unresolved_stat`` is added to.
+ """
contracts: list[Contract] = []
+ unresolved = 0
passes: dict[int, RepoPass] = {
id(d): d.repo_pass() for d in self.dialects if hasattr(d, "repo_pass")
}
@@ -201,6 +209,9 @@ class DialectExtractor:
repo_pass.scan(ctx)
passed[rel_path] = ctx
contracts.extend(found if self.identity is None else dedupe(found, self.identity))
+ unresolved += ctx.unresolved_calls
+ if stats is not None and self.unresolved_stat and unresolved:
+ stats[self.unresolved_stat] = stats.get(self.unresolved_stat, 0) + unresolved
for repo_pass in passes.values():
found = [
c for c in repo_pass.finish()
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
index 3cb234465..81bac93a8 100644
--- a/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/__init__.py
@@ -8,6 +8,8 @@ downstream in :mod:`repowise.core.workspace.matching`.
from __future__ import annotations
+from repowise.core.workspace.contracts import TOPIC_NAMES_UNRESOLVED_STAT
+
from ..dialect import ContractDialect, DialectExtractor
from .aws import SNS, SQS
from .bullmq import BULLMQ
@@ -44,6 +46,7 @@ class TopicExtractor(DialectExtractor):
dialects = DIALECTS
identity = staticmethod(topic_identity)
+ unresolved_stat = TOPIC_NAMES_UNRESOLVED_STAT
__all__ = ["DIALECTS", "TopicExtractor"]
diff --git a/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py b/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py
index 813728d74..da10ed984 100644
--- a/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py
+++ b/packages/core/src/repowise/core/workspace/extractors/topic/dialect.py
@@ -148,8 +148,13 @@ def call_contracts(
args: list[str],
offset: int,
strings: FileStrings,
+ site: int,
) -> list[Contract]:
- """The contracts one call site of *call* yields."""
+ """The contracts one call site of *call* yields; *offset* is where its head starts.
+
+ A call whose name is refused is recorded by *site*, where its argument list
+ opens, which every dialect reading the call shares wherever its head begins.
+ """
keys, key_refused = (
strings.resolve(args, call.routing_key) if call.routing_key else ([], False)
)
@@ -161,9 +166,11 @@ def call_contracts(
queues = call.declared.queues(ctx, args, call.queue, strings)
if not queues:
return [] # a binding with no readable queue binds nothing we can name
- names, _ = strings.resolve(args, call.name, call.normalize)
+ names, refused = strings.resolve(args, call.name, call.normalize)
if not names and call.declared is not None and call.queue is None:
names = call.declared.queues(ctx, args, call.name, strings)
+ if refused and not names:
+ ctx.note_unresolved(site)
out: list[Contract] = []
for name in names:
kind, key, unresolved = call.kind, routing_key, key_refused
@@ -233,7 +240,7 @@ class TopicDialect:
# Typed rows first: a call both read is kept with the typed row's origin.
calls = [*self._typed_calls(ctx), *self.calls]
for call, args, m, strings in call_sites(ctx, calls):
- out.extend(call_contracts(ctx, self.name, call, args, m.start(), strings))
+ out.extend(call_contracts(ctx, self.name, call, args, m.start(), strings, m.end() - 1))
return out
diff --git a/packages/core/src/repowise/core/workspace/network_probe.py b/packages/core/src/repowise/core/workspace/network_probe.py
index 8bdb914d9..261c43960 100644
--- a/packages/core/src/repowise/core/workspace/network_probe.py
+++ b/packages/core/src/repowise/core/workspace/network_probe.py
@@ -15,7 +15,13 @@ not resolved can be counted here and in ``http_consumer_unresolved`` both.
Tooling and build files (:func:`outside_runtime`) are skipped: a script calling
a dev server is not a call the running system misses.
-Adding a client library or a language is one entry in :data:`PROBE_ROWS`.
+:data:`MESSAGE_PROBE_ROWS` is the same probe for messaging SDKs (a broker
+client, a cloud queue), counted apart so a Kafka file never enters the HTTP
+denominator. A file there is excused by a topic contract of either role, since
+a publish is a provider. A file that only builds a client others call counts.
+
+Adding a client library or a language is one entry in :data:`PROBE_ROWS` or
+:data:`MESSAGE_PROBE_ROWS`.
"""
from __future__ import annotations
@@ -32,6 +38,8 @@ from repowise.core.workspace.extractors.base import SourceFile
#: The ``extraction_stats`` key the probe writes, per repo.
UNRECOGNISED_CALL_FILES_STAT = "call_files_unrecognised"
+#: The ``extraction_stats`` key the messaging probe writes, per repo.
+UNRECOGNISED_MESSAGE_FILES_STAT = "message_files_unrecognised"
#: Origins whose code runs at development or build time, never in the deployed
#: system: a script calling a dev server is no missed service call.
@@ -158,11 +166,103 @@ PROBE_ROWS: tuple[ProbeRow, ...] = (
)
+_JS_MESSAGING = (
+ r"kafkajs|node-rdkafka|@confluentinc/kafka-javascript|@aws-sdk/client-sqs|@aws-sdk/client-sns"
+ r"|sqs-consumer|sqs-producer|@google-cloud/pubsub|@azure/service-bus|@azure/event-hubs"
+ r"|amqplib|amqp-connection-manager|nats|mqtt|@dapr/dapr|@temporalio/client|@temporalio/worker"
+)
+_PY_MESSAGING = (
+ r"kafka|confluent_kafka|aiokafka|pika|aio_pika|nats|paho\.mqtt|aiomqtt"
+ r"|google\.cloud\.pubsub(?:_v1)?|azure\.servicebus|azure\.eventhub|dapr\.clients|temporalio"
+)
+_JVM_MESSAGING = (
+ r"org\.apache\.kafka|org\.springframework\.kafka|org\.springframework\.cloud\.stream"
+ r"|software\.amazon\.awssdk\.services\.(?:sqs|sns)|com\.amazonaws\.services\.(?:sqs|sns)"
+ r"|io\.awspring\.cloud\.(?:sqs|sns)|com\.google\.cloud\.pubsub|com\.google\.cloud\.spring\.pubsub"
+ r"|com\.azure\.messaging\.(?:servicebus|eventhubs)|com\.rabbitmq\.client|org\.springframework\.amqp"
+ r"|(?:javax|jakarta)\.jms|io\.nats|org\.eclipse\.paho|io\.dapr|io\.temporal"
+)
+_GO_MESSAGING = (
+ r"github\.com/(?:segmentio/kafka-go|confluentinc/confluent-kafka-go|IBM/sarama|Shopify/sarama"
+ r"|twmb/franz-go|nats-io/nats\.go|eclipse/paho\.mqtt\.golang|rabbitmq/amqp091-go|streadway/amqp"
+ r"|dapr/go-sdk|aws/aws-sdk-go(?:-v2)?/service/(?:sqs|sns)"
+ r"|Azure/azure-sdk-for-go/sdk/messaging/(?:azservicebus|azeventhubs))"
+ r"|cloud\.google\.com/go/pubsub|go\.temporal\.io/sdk"
+)
+
+#: Messaging SDK tokens, one row per language: Kafka, SQS/SNS, Pub/Sub, Service
+#: Bus, Event Hubs, RabbitMQ, JMS, NATS, MQTT, Redis streams, Dapr, Temporal.
+#: Imports, mostly, so a word in prose does not count; Redis appears only by
+#: its stream verbs, since a Redis cache is no message.
+MESSAGE_PROBE_ROWS: tuple[ProbeRow, ...] = (
+ ProbeRow(
+ "csharp",
+ langs.CSHARP | langs.VBNET,
+ (
+ r"\b(?:using|Imports)\s+(?:Confluent\.Kafka|Amazon\.SQS|Amazon\.SimpleNotificationService"
+ r"|Google\.Cloud\.PubSub|Azure\.Messaging\.(?:ServiceBus|EventHubs)|RabbitMQ\.Client"
+ r"|NATS\.(?:Client|Net)|MQTTnet|Dapr\.Client|Temporalio)\b",
+ r"\bStream(?:Add|ReadGroup)(?:Async)?\s*\(",
+ ),
+ ),
+ ProbeRow(
+ "go",
+ langs.GO,
+ (rf"\"(?:{_GO_MESSAGING})[/\"]", r"\.(?:XAdd|XReadGroup)\s*\("),
+ ),
+ ProbeRow(
+ "java",
+ langs.JAVA | langs.KOTLIN,
+ (rf"\bimport\s+(?:{_JVM_MESSAGING})\b", r"\bopsForStream\s*\("),
+ ),
+ ProbeRow(
+ "javascript",
+ langs.JS_TS,
+ (
+ rf"(?:\brequire\(\s*|\bfrom\s+|\bimport\s+)['\"](?:{_JS_MESSAGING})(?:/[^'\"\n]*)?['\"]",
+ r"\bnew\s+(?:AWS\.)?(?:SQS|SNS)\s*\(",
+ r"\.(?:xadd|xreadgroup|xAdd|xReadGroup)\s*\(",
+ ),
+ ),
+ ProbeRow(
+ "php",
+ langs.PHP,
+ (r"\b(?:PhpAmqpLib|RdKafka|Aws\\Sqs|Aws\\Sns|Google\\Cloud\\PubSub)\\",),
+ hash_comments=True,
+ ),
+ ProbeRow(
+ "python",
+ langs.PYTHON,
+ (
+ rf"(?m:^[ \t]*(?:from|import)[ \t]+(?:{_PY_MESSAGING})\b)",
+ r"(?m:^[ \t]*from[ \t]+google\.cloud[ \t]+import[ \t][^\n]*\bpubsub)",
+ r"\bboto3\.(?:client|resource)\(\s*['\"](?:sqs|sns)['\"]",
+ r"\.(?:xadd|xreadgroup)\s*\(",
+ ),
+ hash_comments=True,
+ ),
+ ProbeRow(
+ "ruby",
+ langs.RUBY,
+ (
+ r"\brequire\s*\(?\s*['\"](?:kafka|rdkafka|bunny|aws-sdk-sqs|aws-sdk-sns"
+ r"|google/cloud/pubsub|nats/client|mqtt)['\"]",
+ ),
+ hash_comments=True,
+ ),
+ ProbeRow(
+ "rust",
+ langs.RUST,
+ (r"\b(?:rdkafka|lapin|async_nats|rumqttc|google_cloud_pubsub|aws_sdk_sqs|aws_sdk_sns)::",),
+ ),
+)
+
+
@cache
-def _by_extension() -> dict[str, tuple[re.Pattern[str], bool]]:
- """One compiled alternation per extension, built once per process."""
+def _by_extension(rows: tuple[ProbeRow, ...]) -> dict[str, tuple[re.Pattern[str], bool]]:
+ """One compiled alternation per extension of *rows*, built once per process."""
table: dict[str, tuple[re.Pattern[str], bool]] = {}
- for row in PROBE_ROWS:
+ for row in rows:
pattern = re.compile("|".join(f"(?:{t})" for t in row.tokens))
for ext in row.extensions:
table[ext] = (pattern, row.hash_comments)
@@ -170,17 +270,20 @@ def _by_extension() -> dict[str, tuple[re.Pattern[str], bool]]:
def count_unrecognised_call_files(
- files: Sequence[SourceFile], consumer_files: Collection[str]
+ files: Sequence[SourceFile],
+ consumer_files: Collection[str],
+ rows: tuple[ProbeRow, ...] = PROBE_ROWS,
) -> int:
- """Files in *files* with a network-call token and no consumer contract.
+ """Files in *files* with a token of *rows* and no contract read from them.
Tooling and build files (:func:`outside_runtime`) are not counted.
- *consumer_files* are the paths a consumer contract came from. One regex
- search per remaining file of a probed language; only a hit pays for the
- comment mask that confirms it.
+ *consumer_files* are the paths that excuse a file: a consumer contract's
+ for :data:`PROBE_ROWS`, any topic contract's for :data:`MESSAGE_PROBE_ROWS`.
+ One regex search per remaining file of a probed language; only a hit pays
+ for the comment mask that confirms it.
"""
- table = _by_extension()
+ table = _by_extension(rows)
count = 0
for rel_path, suffix, content in files:
entry = table.get(suffix)
diff --git a/packages/server/src/repowise/server/schemas/workspace.py b/packages/server/src/repowise/server/schemas/workspace.py
index 6e777f5c1..1f8cab1e8 100644
--- a/packages/server/src/repowise/server/schemas/workspace.py
+++ b/packages/server/src/repowise/server/schemas/workspace.py
@@ -372,6 +372,7 @@ class WorkspaceRepoDiagnostics(BaseModel):
providers_by_layer: dict[str, int] = {}
consumers_by_layer: dict[str, int] = {}
http_consumers_unresolved: int = 0
+ topic_names_unresolved: int = 0
class WorkspaceUnmatchedConsumer(BaseModel):
@@ -461,6 +462,12 @@ class WorkspaceExtractionDiagnostics(BaseModel):
#: ``None`` on an artifact written before the count existed.
unrecognised_call_files: dict[str, int] | None = None
unrecognised_call_file_count: int | None = None
+ #: Broker calls located whose topic or queue name could not be settled.
+ topic_names_unresolved: int = 0
+ #: Per repo, files using a messaging SDK and no topic contract.
+ #: ``None`` on an artifact written before the count existed.
+ unrecognised_message_files: dict[str, int] | None = None
+ unrecognised_message_file_count: int | None = None
symbol_identity: dict[str, WorkspaceSymbolIdentity] = {}
schema_coverage: WorkspaceSchemaCoverage = WorkspaceSchemaCoverage()
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 2fd30cfb8..40546aa35 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -4749,6 +4749,9 @@ export interface WorkspaceExtractionDiagnostics {
http_link_coverage?: number | null;
unrecognised_call_files?: Record<string, number> | null;
unrecognised_call_file_count?: number | null;
+ topic_names_unresolved?: number;
+ unrecognised_message_files?: Record<string, number> | null;
+ unrecognised_message_file_count?: number | null;
symbol_identity?: Record<string, WorkspaceSymbolIdentity>;
schema_coverage?: WorkspaceSchemaCoverage;
code_api?: WorkspaceCodeApiCoverage;
@@ -4893,6 +4896,7 @@ export interface WorkspaceRepoDiagnostics {
providers_by_layer?: Record<string, number>;
consumers_by_layer?: Record<string, number>;
http_consumers_unresolved?: number;
+ topic_names_unresolved?: number;
}
export interface WorkspaceRepoEntry {
diff --git a/packages/types/src/workspace.ts b/packages/types/src/workspace.ts
index 5d178bc92..bd9a9879c 100644
--- a/packages/types/src/workspace.ts
+++ b/packages/types/src/workspace.ts
@@ -316,6 +316,8 @@ export interface RepoDiagnostics {
consumers_by_layer: Record<string, number>;
/** Calls that reached a confirmed HTTP wrapper but resolved to no path. */
http_consumers_unresolved: number;
+ /** Broker calls located whose topic or queue name could not be settled. */
+ topic_names_unresolved?: number;
}
export interface UnmatchedConsumer {
@@ -363,6 +365,11 @@ export interface ExtractionDiagnostics {
/** Per repo, files with a network-call token and no consumer contract; `null` before the count existed. */
unrecognised_call_files?: Record<string, number> | null;
unrecognised_call_file_count?: number | null;
+ /** Broker calls located whose topic or queue name could not be settled. */
+ topic_names_unresolved?: number;
+ /** Per repo, files using a messaging SDK and no topic contract; `null` before the count existed. */
+ unrecognised_message_files?: Record<string, number> | null;
+ unrecognised_message_file_count?: number | null;
}
/** One reason a graph's evidence is short of measured. */
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 04bc12921..11433a277 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -1703,6 +1703,7 @@
"architecture": "Architecture",
"contracts": "Contracts",
"http-calls": "HTTP calls",
+ "topic-calls": "Topic calls",
"dangling-calls": "Dangling calls",
"health": "Health",
"churn-hotspots": "Churn hotspots",
@@ -1809,7 +1810,9 @@
"orphansSub": "in this workspace; not the same as unused",
"httpRead": "HTTP calls read",
"httpUnresolved": "{count} located but not resolvable",
- "httpSub": "of the client calls extraction located"
+ "httpSub": "of the client calls extraction located",
+ "topicRead": "Topic calls read",
+ "topicSub": "{unresolved} names not resolvable, {files} files on a messaging SDK no extractor reads"
},
"reasons": {
"no_provider": "no provider found",
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 7274342df..564c55409 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -1703,6 +1703,7 @@
"architecture": "架构",
"contracts": "契约",
"http-calls": "HTTP 调用",
+ "topic-calls": "主题调用",
"dangling-calls": "悬空调用",
"health": "健康度",
"churn-hotspots": "变更热点",
@@ -1809,7 +1810,9 @@
"orphansSub": "仅限本工作区;与「未使用」不同",
"httpRead": "已读取的 HTTP 调用",
"httpUnresolved": "定位到 {count} 个但无法解析",
- "httpSub": "占提取定位到的客户端调用"
+ "httpSub": "占提取定位到的客户端调用",
+ "topicRead": "已读取的主题调用",
+ "topicSub": "{unresolved} 个名称无法解析,{files} 个文件使用了无提取器读取的消息 SDK"
},
"reasons": {
"no_provider": "未找到提供方",
diff --git a/packages/web/src/app/workspace/contracts/page.tsx b/packages/web/src/app/workspace/contracts/page.tsx
index 142ff6106..23e216a26 100644
--- a/packages/web/src/app/workspace/contracts/page.tsx
+++ b/packages/web/src/app/workspace/contracts/page.tsx
@@ -158,6 +158,7 @@ export default async function ContractsPage({ searchParams }: Props) {
})
: t("ribbon.httpSub"),
},
+ ...topicStat(t, diagnostics),
];
return (
@@ -299,3 +300,29 @@ function unmatchedReasonSub(
.map(([reason, n]) => `${n} ${t(REASON_KEYS[reason] ?? "reasons.unknown")}`)
.join(", ");
}
+
+/**
+ * Topic calls read, beside the broker calls not named and the files on a
+ * messaging SDK no extractor reads. Counts only, like the CLI line; absent on
+ * an artifact older than the messaging probe and on a workspace with no messaging.
+ */
+function topicStat(t: Translator, diagnostics: ExtractionDiagnostics | null): RibbonStat[] {
+ const files = diagnostics?.unrecognised_message_file_count;
+ if (!diagnostics || files == null) return [];
+ const read = diagnostics.repo_breakdown.reduce(
+ (n, r) => n + (r.providers_by_type.topic ?? 0) + (r.consumers_by_type.topic ?? 0),
+ 0,
+ );
+ const unresolved = diagnostics.topic_names_unresolved ?? 0;
+ if (read + unresolved + files === 0) return [];
+ return [
+ {
+ label: t("ribbon.topicRead"),
+ value: formatNumber(read),
+ sub: t("ribbon.topicSub", {
+ unresolved: formatNumber(unresolved),
+ files: formatNumber(files),
+ }),
+ },
+ ];
+}
diff --git a/tests/unit/cli/test_workspace_cmd.py b/tests/unit/cli/test_workspace_cmd.py
index ddc003a8e..3eeb469e6 100644
--- a/tests/unit/cli/test_workspace_cmd.py
+++ b/tests/unit/cli/test_workspace_cmd.py
@@ -722,6 +722,25 @@ class TestWorkspaceDiagnosticsReport:
assert "HTTP calls 1 of 4 linked to another service (25%); 3 read (75%)" in out
assert "read, not linked: 1 match no declared route, 1 served inside their own service" in out
assert "web http::GET::/none (b.ts)" in out
+ assert "Topic calls" not in out # an artifact before the messaging probe
+
+ def test_topic_calls_line_names_the_unread_messaging_files(self, runner, tmp_path):
+ from repowise.core.workspace.contracts import Contract
+ from repowise.core.workspace.diagnostics import build_diagnostics
+ from repowise.core.workspace.system_graph import SystemGraph, save_system_graph
+
+ _write_workspace_config(tmp_path, repos=[{"path": "orders", "alias": "orders"}])
+ contracts = [
+ Contract(repo="orders", contract_id="topic::orders", contract_type="topic",
+ role="provider", file_path="p.py", symbol_name="f", confidence=0.8),
+ ]
+ stats = {"orders": {"topic_names_unresolved": 2, "message_files_unrecognised": 3}}
+ diag = build_diagnostics(contracts, [], stats)
+ save_system_graph(SystemGraph(diagnostics=diag, generated_at="t"), tmp_path)
+
+ out = runner.invoke(cli, ["workspace", "diagnostics", str(tmp_path)]).output
+ assert "Topic calls 1 read, 2 located but the name not statically resolvable, " in out
+ assert "unread messaging calls: orders 3" in out
def test_tables_collapse_to_one_line_per_repo(self, runner, tmp_path):
from repowise.core.workspace.diagnostics import OrphanProvider, UnmatchedConsumer
diff --git a/tests/unit/core/test_report_estate.py b/tests/unit/core/test_report_estate.py
index 8b864152f..f10573a2c 100644
--- a/tests/unit/core/test_report_estate.py
+++ b/tests/unit/core/test_report_estate.py
@@ -295,3 +295,24 @@ def test_cli_estate_reads_the_stored_artifacts(tmp_path: Path, monkeypatch) -> N
assert [r.get("indexed", True) for r in doc["repos"]] == [False] * 4 # no member is indexed
md = CliRunner().invoke(cli, ["report", "estate", str(ws), "--sections", "estate-map"])
assert md.exit_code == 0 and "# Estate: ws" in md.output and "## Estate summary" not in md.output
+
+
+async def test_topic_calls_name_what_the_messaging_probe_missed(tmp_path):
+ from repowise.core.workspace.system_graph import load_system_graph
+
+ root = _workspace(tmp_path)
+ assert "topic-calls" not in (await _estate(_ctx(root)))["estate-contracts"] # older artifact
+ graph = load_system_graph(root)
+ graph.diagnostics.repo_breakdown.append(
+ RepoDiagnostics("worker", providers_by_type={"topic": 1}, provider_count=1)
+ )
+ graph.diagnostics.topic_names_unresolved = 2
+ graph.diagnostics.unrecognised_message_files = {"photos": 3, "web": 0}
+ save_system_graph(graph, root)
+ topics = (await _estate(_ctx(root)))["estate-contracts"]["topic-calls"]
+ assert topics["reason"] == (
+ "1 topic publish or subscribe call(s) read as contracts, 2 located but the name not "
+ "resolvable, 3 file(s) using a messaging SDK no extractor reads"
+ )
+ assert topics["details"] == ["photos: 3 file(s)"]
+ assert topics["data"] == {"read": 1, "unresolved": 2, "unrecognised_message_files": 3}
diff --git a/tests/unit/workspace/test_diagnostics.py b/tests/unit/workspace/test_diagnostics.py
index 115badd2d..c7952120e 100644
--- a/tests/unit/workspace/test_diagnostics.py
+++ b/tests/unit/workspace/test_diagnostics.py
@@ -358,3 +358,34 @@ def test_a_linked_call_from_a_script_still_counts():
diag = build_diagnostics(contracts, [link])
assert diag.http_consumers_linked == 1
assert diag.http_consumers_read == 1
+
+
+def test_topic_misses_reach_the_diagnostics_apart_from_http():
+ from repowise.core.workspace.diagnostics import ExtractionDiagnostics
+
+ contracts = [
+ _provider("orders", "topic::orders", ctype="topic"),
+ _consumer("billing", "topic::orders", ctype="topic"),
+ _consumer("web", "http::GET::/u"),
+ ]
+ stats = {
+ "orders": {"topic_names_unresolved": 2, "message_files_unrecognised": 0},
+ "photos": {"message_files_unrecognised": 3, "call_files_unrecognised": 0},
+ "web": {"call_files_unrecognised": 0},
+ }
+ diag = build_diagnostics(contracts, [], stats)
+ assert diag.topic_contracts_read == 2
+ assert diag.topic_names_unresolved == 2
+ assert diag.unrecognised_message_files == {"orders": 0, "photos": 3}
+ assert diag.unrecognised_message_file_count == 3
+ assert {r.repo: r.topic_names_unresolved for r in diag.repo_breakdown}["orders"] == 2
+ assert diag.http_consumer_coverage == 1.0 # a messaging file never lowers HTTP
+ restored = ExtractionDiagnostics.from_dict(diag.to_dict())
+ assert restored.to_dict() == diag.to_dict()
+
+
+def test_topic_misses_are_none_before_the_messaging_probe_ran():
+ diag = build_diagnostics([_consumer("web", "http::GET::/u")], [], {"web": {}})
+ assert diag.unrecognised_message_files is None
+ assert diag.unrecognised_message_file_count is None
+ assert diag.topic_names_unresolved == 0
diff --git a/tests/unit/workspace/test_network_probe.py b/tests/unit/workspace/test_network_probe.py
index 1326ebc8c..0ffd0cfef 100644
--- a/tests/unit/workspace/test_network_probe.py
+++ b/tests/unit/workspace/test_network_probe.py
@@ -4,29 +4,36 @@ from __future__ import annotations
import re
+import pytest
+
from repowise.core.ingestion.languages.registry import REGISTRY
-from repowise.core.workspace.network_probe import PROBE_ROWS, count_unrecognised_call_files
+from repowise.core.workspace.network_probe import (
+ MESSAGE_PROBE_ROWS,
+ PROBE_ROWS,
+ count_unrecognised_call_files,
+)
-def test_every_row_declares_what_the_probe_needs():
[email protected]("rows", [PROBE_ROWS, MESSAGE_PROBE_ROWS], ids=["http", "messaging"])
+def test_every_row_declares_what_the_probe_needs(rows):
"""A new row cannot skip a known language, its extensions or a compiling token."""
- languages = [row.language for row in PROBE_ROWS]
+ languages = [row.language for row in rows]
assert languages == sorted(languages)
assert len(set(languages)) == len(languages)
- for row in PROBE_ROWS:
+ for row in rows:
assert REGISTRY.extensions_for([row.language]), row.language
assert row.extensions, row.language
assert all(ext.startswith(".") and ext == ext.lower() for ext in row.extensions)
assert row.tokens, row.language
for token in row.tokens:
re.compile(token)
- claimed = [ext for row in PROBE_ROWS for ext in row.extensions]
+ claimed = [ext for row in rows for ext in row.extensions]
assert len(claimed) == len(set(claimed)), "one extension, one row"
-def _count(files: dict[str, str], consumers: set[str] | None = None) -> int:
- rows = [(path, "." + path.rsplit(".", 1)[1], text) for path, text in files.items()]
- return count_unrecognised_call_files(rows, consumers or set())
+def _count(files: dict[str, str], consumers: set[str] | None = None, rows=PROBE_ROWS) -> int:
+ walked = [(path, "." + path.rsplit(".", 1)[1], text) for path, text in files.items()]
+ return count_unrecognised_call_files(walked, consumers or set(), rows)
def test_a_client_library_no_dialect_reads_is_counted():
@@ -88,3 +95,49 @@ def test_tooling_and_build_files_are_not_counted():
"src/client.js": "fetch(url);\n",
}
assert _count(files) == 1
+
+
+def test_a_messaging_sdk_no_dialect_reads_is_counted_apart_from_http():
+ files = {
+ "photos/index.js": "const { PubSub } = require('@google-cloud/pubsub');\n",
+ "thumbs/main.py": "from google.cloud import pubsub_v1\n",
+ "bus/Sender.cs": "using Azure.Messaging.ServiceBus;\n",
+ "events/pub.go": 'import (\n\t"cloud.google.com/go/pubsub"\n)\n',
+ "Orders.kt": "import org.springframework.cloud.stream.function.StreamBridge\n",
+ "stream.ts": "await redis.xadd('orders', '*', 'id', id);\n",
+ "Kernel.php": "<?php\nuse PhpAmqpLib\\Connection\\AMQPStreamConnection;\n",
+ }
+ assert _count(files, rows=MESSAGE_PROBE_ROWS) == 7
+ assert _count(files) == 0 # never in the HTTP denominator
+
+
+def test_a_messaging_file_a_topic_contract_came_from_is_not_counted():
+ files = {"queue.py": "import pika\n", "worker.py": "from kafka import KafkaConsumer\n"}
+ assert _count(files, {"queue.py", "worker.py"}, MESSAGE_PROBE_ROWS) == 0
+
+
+def test_messaging_words_in_prose_comments_or_caches_are_not_counted():
+ files = {
+ "log.py": "# from kafka import KafkaProducer\nprint('read from nats')\n",
+ "cache.js": "const Redis = require('ioredis');\nredis.get('k');\n",
+ "natsy.py": "import natsort\n",
+ "Notes.java": "// import org.apache.kafka.clients.producer.KafkaProducer;\nclass N {}\n",
+ }
+ assert _count(files, rows=MESSAGE_PROBE_ROWS) == 0
+
+
+def test_the_extraction_counts_both_probes_and_only_messaging_when_topics_are_read():
+ from repowise.core.workspace.contracts import Contract, _probe_misses
+
+ files = [
+ ("pub.py", ".py", "import pika\n"),
+ ("sub.py", ".py", "from kafka import KafkaConsumer\n"),
+ ("api.py", ".py", "import requests\nrequests.get(url)\n"),
+ ]
+ topic = Contract(repo="r", contract_id="topic::orders", contract_type="topic",
+ role="provider", file_path="pub.py", symbol_name="f", confidence=0.8)
+ assert _probe_misses(files, [topic], True) == {
+ "call_files_unrecognised": 1,
+ "message_files_unrecognised": 1,
+ }
+ assert _probe_misses(files, [topic], False) == {"call_files_unrecognised": 1}
diff --git a/tests/unit/workspace/test_system_graph.py b/tests/unit/workspace/test_system_graph.py
index a9d2780d9..8fdb16986 100644
--- a/tests/unit/workspace/test_system_graph.py
+++ b/tests/unit/workspace/test_system_graph.py
@@ -358,6 +358,9 @@ def test_system_graph_json_shape_is_locked():
"code_api",
"unrecognised_call_files",
"unrecognised_call_file_count",
+ "topic_names_unresolved",
+ "unrecognised_message_files",
+ "unrecognised_message_file_count",
}
diff --git a/tests/unit/workspace/test_topic_dialects.py b/tests/unit/workspace/test_topic_dialects.py
index 8f80d09b6..3e9c80d02 100644
--- a/tests/unit/workspace/test_topic_dialects.py
+++ b/tests/unit/workspace/test_topic_dialects.py
@@ -491,6 +491,35 @@ class TestAws:
src = "new SendMessageCommand({ QueueUrl: process.env.QUEUE_URL, MessageBody: b });\n"
assert _extract(tmp_path, "q.ts", src) == []
+ def test_a_refused_name_is_counted_once_per_call_site(self, tmp_path: Path) -> None:
+ (tmp_path / "q.ts").write_text(
+ "new SendMessageCommand({ QueueUrl: process.env.QUEUE_URL, MessageBody: b });\n"
+ "new SendMessageCommand({ QueueUrl: 'https://sqs.x/1/orders', MessageBody: b });\n"
+ "// new SendMessageCommand({ QueueUrl: process.env.OLD_URL });\n",
+ encoding="utf-8",
+ )
+ # One client.publish read alike by Redis and NATS is still one call.
+ (tmp_path / "pub.js").write_text(
+ "const redis = require('redis');\nconst nats = require('nats');\n"
+ "client.publish(channelFor(user), msg);\n",
+ encoding="utf-8",
+ )
+ stats: dict[str, int] = {}
+ rows = TopicExtractor().extract(tmp_path, "svc", stats=stats)
+ assert [c.contract_id for c in rows] == ["topic::orders"]
+ assert stats == {"topic_names_unresolved": 2}
+
+ def test_brace_headed_refusals_count_apart(self, tmp_path: Path) -> None:
+ (tmp_path / "main.go").write_text(
+ 'import "github.com/segmentio/kafka-go"\n'
+ "w := &kafka.Writer{Topic: os.Getenv(\"A\")}\n"
+ "r := kafka.NewReader(kafka.ReaderConfig{Topic: os.Getenv(\"B\")})\n",
+ encoding="utf-8",
+ )
+ stats: dict[str, int] = {}
+ assert TopicExtractor().extract(tmp_path, "svc", stats=stats) == []
+ assert stats == {"topic_names_unresolved": 2}
+
def test_sns_topic_arn_names_its_last_field(self, tmp_path: Path) -> None:
src = "new PublishCommand({ TopicArn: 'arn:aws:sns:eu-west-1:123:orders', Message: m });\n"
c = _one(_extract(tmp_path, "p.ts", src), "provider")