Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(workspace): read Python HTTP consumers through their client bindings (#1890)
Raghav Chamadiya24f5411623a1
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.pyindex 5f0526fbb..8ac60a965 100644--- a/packages/core/src/repowise/core/workspace/contracts.py+++ b/packages/core/src/repowise/core/workspace/contracts.py@@ -1070,8 +1070,8 @@ async def run_contract_extraction(unresolved = stats.get("http_consumer_unresolved", 0)if unresolved:_log.info(- "%s: %d HTTP client call(s) reach a confirmed wrapper but their "- "path could not be resolved statically; counted, not extracted",+ "%s: %d HTTP client call(s) located but their path could not be "+ "resolved statically; counted, not extracted",alias,unresolved,)diff --git a/packages/core/src/repowise/core/workspace/extractors/from_index.py b/packages/core/src/repowise/core/workspace/extractors/from_index.pyindex a431b5416..bc906e8aa 100644--- a/packages/core/src/repowise/core/workspace/extractors/from_index.py+++ b/packages/core/src/repowise/core/workspace/extractors/from_index.py@@ -36,7 +36,7 @@ from typing import TYPE_CHECKINGfrom .http.dialect import build_provider_contractfrom .http.mounts import compose_prefix, router_prefixes-from .langs import JS_TS+from .langs import JS_TS, PYTHONif TYPE_CHECKING:from collections.abc import Sequence@@ -97,7 +97,7 @@ INDEX_SUFFIXES = frozenset({".py"})# counting braces. Kept separate from INDEX_SUFFIXES because the two passes read# different things off the same rows: providers read the declaration above a# span, consumers read the span itself.-CONSUMER_INDEX_SUFFIXES = frozenset(JS_TS)+CONSUMER_INDEX_SUFFIXES = frozenset(JS_TS) | frozenset(PYTHON)def _decorator_head_and_arg(decorator: str) -> tuple[str, str | None]:diff --git a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py b/packages/core/src/repowise/core/workspace/extractors/http/__init__.pyindex 49515ba92..dda0bfcf0 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/__init__.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/__init__.py@@ -120,10 +120,11 @@ class HttpExtractor:route in a comment becoming a contract and an empty path being lost.*stats* is an optional out-dict of counters. ``http_consumer_unresolved``- counts calls to a *confirmed* HTTP wrapper whose path argument could not- be resolved statically — real endpoint calls that were located but- cannot be named. They are counted rather than dropped, so a recall- figure built from these contracts states its own denominator.+ counts calls to a *confirmed* HTTP wrapper, or through a variable bound+ to an HTTP client instance, whose path argument could not be resolved+ statically — real endpoint calls that were located but cannot be named.+ They are counted rather than dropped, so a recall figure built from+ these contracts states its own denominator."""scanned = select_files(repo_path, self.source_extensions(), exclude, files)mounts = self._collect_mounts(scanned)@@ -138,7 +139,10 @@ class HttpExtractor:contracts: list[Contract] = []for rel_path, suffix, content in scanned:ctx = ScanContext(repo_alias, rel_path, suffix, content, mounts, repo_index)- indexed = suffix in PYTHON or suffix in CONSUMER_INDEX_SUFFIXES+ # Python sits in both sets now, so one test covers the provider+ # pass (which reads the declarations above a span) and the consumer+ # pass (which reads the span itself).+ indexed = suffix in CONSUMER_INDEX_SUFFIXES# Only spans that can still describe this file's text supersede the# regex; a missing or overrun entry leaves the dialect in charge.symbols = (diff --git a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.pyindex dfa8bbe81..ad2f20d24 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/index_clients.py@@ -12,6 +12,15 @@ bulk of the missing recall: the frontend spells every call``this.fetch<SnapshotResponse>(`/snapshots/${id}`)``, and the existing dialect's``fetch\\s*\\(`` cannot match across the ``<SnapshotResponse>`` type argument.+Python reaches its endpoints a second way no wrapper confirmation can see: the+call goes through a *variable* bound to a client instance+(``async with httpx.AsyncClient() as http`` … ``http.post(url)``), so its+receiver is neither absent nor ``self``. Those bindings come from+:func:`.wrappers.bound_clients` and count as sink calls in their own right.+Measured on a FastAPI service that calls its frontend: 42 such calls against 3+with a literal ``httpx.``/``requests.`` receiver, the only shape the text+dialect matches.+Unresolved paths are counted, never guessed and never silently dropped — see:func:`extract_consumers`' ``unresolved`` return value."""@@ -22,10 +31,13 @@ import refrom typing import TYPE_CHECKINGfrom ..base import line_at+from ..langs import PYTHONfrom .dialect import build_consumer_contract+from .python_urls import resolve_url_argument, string_constantsfrom .wrappers import (DEFAULT_HOP_BUDGET,GENERIC_ARGS,+ bound_clients,confirm_wrappers,mask_source,sink_call_names,@@ -49,6 +61,17 @@ _CALL_RE = re.compile(+ r"\(",)+# A method call through an instance receiver. Kept apart from ``_CALL_RE``+# rather than folded into it: widening that shared pattern would change what+# the JS/TS pass sees in every file.+_CLIENT_CALL_RE = re.compile(+ r"(?<![.\w])(?:self\s*\.\s*)?(?P<recv>[A-Za-z_]\w*)\s*\.\s*(?P<verb>\w+)\s*\(",+)++# ``request`` is absent on purpose: it takes the method as its first argument+# and the URL as its second, so this rule would record the verb as the path.+_HTTP_VERBS = frozenset({"get", "post", "put", "patch", "delete", "head", "options"})+# A first argument concrete enough to be a URL: a path, a base placeholder, or# an absolute URL. Mirrors the concreteness test the regex dialect already# applies, so both paths agree on what counts as a usable literal.@@ -164,6 +187,28 @@ def _literal_url(arg: str) -> str | None:return inner if _CONCRETE_URL_RE.match(inner) else None+def _first_arg_url(arg: str, is_python: bool, constants: dict[str, str]) -> str | None:+ """The URL a call's first argument names, or ``None`` if it is not one.++ Python additionally reads an f-string and folds a name bound to a string+ literal, then faces the same concreteness test as every other language.+ """+ if not is_python:+ return _literal_url(arg)+ url = resolve_url_argument(arg, constants)+ return url if url is not None and _CONCRETE_URL_RE.match(url) else None+++def _client_library(+ clients: list[tuple[str, str, int, int]], receiver: str, line: int+) -> str | None:+ """The client library *receiver* is bound to at *line*, or ``None``."""+ for var, lib, start, end in clients:+ if var == receiver and start <= line <= end:+ return lib+ return None++def _declaration_sites(symbols: Sequence[IndexedSymbol]) -> set[tuple[int, str]]:"""``(line, name)`` for each callable's own declaration.@@ -203,7 +248,9 @@ def extract_consumers(The second element counts call sites of a wrapper *known to take a URL path*— proven by another call site in the same file passing it a concrete literal- — whose own path argument could not be resolved statically. Those are real+ — whose own path argument could not be resolved statically, plus every+ unresolved call through a bound client instance (whose binding already+ proves the first argument is a URL, so no such gate applies). Those are realendpoint calls this layer cannot name; reporting the number is what keepsthe recall figure honest rather than flattering."""@@ -216,8 +263,6 @@ def extract_consumers(confirmed = confirm_wrappers(symbols, ctx.content, ctx.suffix, budget)sinks = sink_call_names(ctx.suffix)- if not confirmed and not sinks:- return [], 0# Comments are blanked (string bodies are not — the URL literal is what we# are here to read). This both stops a commented-out call becoming a@@ -225,6 +270,18 @@ def extract_consumers(# argument scanner. Masking preserves offsets and length, so slices taken# against this text are the real argument text.content = mask_source(ctx.content, ctx.suffix)+ # A second mask for Python, with string bodies blanked too. Offsets are+ # preserved, so this locates code positions while the text above supplies+ # their bytes. Everything Python-side is found through it, because a log+ # line reading ``"call foo.get('/api/x') to see"`` is prose, not a call, and+ # reading it off ``content`` would mint a contract for an unmade request.+ is_python = ctx.suffix in PYTHON+ code = mask_source(ctx.content, ctx.suffix, strings=True) if is_python else ""+ clients = bound_clients(code, ctx.suffix, symbols)+ if not confirmed and not sinks and not clients:+ return [], 0++ constants = string_constants(content, code) if is_python else {}declarations = _declaration_sites(symbols)# Pass 1: every call site of a confirmed wrapper, split into resolved@@ -265,7 +322,7 @@ def extract_consumers(parse_failures += 1continuefirst, rest = _split_first_arg(content[open_idx + 1 : close_idx])- url = _literal_url(first)+ url = _first_arg_url(first, is_python, constants)if url is None:# The wrapper's own plumbing — ``fetch(path)`` inside the very# function that wraps it — is not a lost endpoint. Whatever flows@@ -279,6 +336,32 @@ def extract_consumers(opt = _METHOD_OPT_RE.search(rest)resolved.append((name, url, opt.group(1).upper() if opt else "GET", line))+ # Pass 1b: calls through a variable bound to an HTTP client instance. No+ # wrapper confirmation applies — the binding already proves the receiver.+ client_unresolved = 0+ for m in _CLIENT_CALL_RE.finditer(code) if clients else ():+ verb = m.group("verb")+ if verb not in _HTTP_VERBS:+ continue+ line = line_at(content, m.start())+ lib = _client_library(clients, m.group("recv"), line)+ if lib is None:+ continue+ open_idx = m.end() - 1+ close_idx = _match_paren(content, open_idx)+ if close_idx < 0:+ parse_failures += 1+ continue+ first, _ = _split_first_arg(content[open_idx + 1 : close_idx])+ url = _first_arg_url(first, is_python, constants)+ if url is None:+ # Unconditional, unlike the wrapper tally above: a client's+ # ``.post`` takes a URL by definition, so ``path_taking`` has no+ # ambiguity to resolve and every miss here is a real endpoint call.+ client_unresolved += 1+ continue+ resolved.append((lib, url, verb.upper(), line))+from ..from_index import EXTRACTION_LAYER_KEY, LAYER_INDEXout: list[Contract] = []@@ -298,4 +381,4 @@ def extract_consumers(# API method, whose first argument is an id and never was a path — would be# reported as an unresolved endpoint, and the number would mean nothing.unresolved = sum(n for name, n in unresolved_by_callee.items() if name in path_taking)- return out, unresolved + parse_failures+ return out, unresolved + parse_failures + client_unresolveddiff --git a/packages/core/src/repowise/core/workspace/extractors/http/python_urls.py b/packages/core/src/repowise/core/workspace/extractors/http/python_urls.pynew file mode 100644index 000000000..bd33dcb41--- /dev/null+++ b/packages/core/src/repowise/core/workspace/extractors/http/python_urls.py@@ -0,0 +1,123 @@+"""Resolve a Python HTTP call's URL argument to text this package can normalize.++Python spells a client call's URL two ways the whole-literal test in+:mod:`.index_clients` cannot read: an f-string (``f"{base}/users"``), and a name+bound to one earlier (``url = f"..."`` then ``client.post(url)``). Both are+settled where they are written, so reading them is substitution rather than+analysis, and no dataflow is claimed by doing it.++**What folds and what is refused.** A name folds only when the file assigns it+exactly once, to a single string literal on one line. Assigned twice, or+assigned anything else anywhere in the file, it is left unresolved and the call+is *counted* as unresolved rather than guessed. File scope, not lexical scope: a+single static assignment means the same thing wherever it is read.++f-string interpolations come out in the ``${expr}`` form the rest of this+package already speaks, so :func:`.paths.strip_leading_base_expr` strips a+Python base placeholder and :func:`.paths.normalize_http_path` collapses a+Python path parameter with no per-language branch in either.+"""++from __future__ import annotations++import re++# A whole-argument string literal, prefix included. ``.*`` is greedy against an+# anchored end, so the quote-inside check below is what rejects a concatenation.+_LITERAL_RE = re.compile(+ r"^(?P<prefix>[A-Za-z]*)(?P<q>'''|\"\"\"|'|\")(?P<body>.*)(?P=q)$", re.DOTALL+)++_NAME_RE = re.compile(r"[A-Za-z_]\w*")++# ``NAME = <expr>`` at any indentation, RHS to end of line. The whitespace+# around ``=`` is required, which excludes the usual unspaced keyword argument+# on its own line (``url=str(resp.url),``) — that otherwise reads as a second+# assignment and retires the very name being folded. A *spaced* kwarg still+# retires it, so the guard is partial; either way the cost is a lost fold, never+# a fabricated path.+_ASSIGN_RE = re.compile(+ r"^[ \t]*([A-Za-z_]\w*)(?:[ \t]*:[^=\n]+)?[ \t]+=[ \t]+(.*)$", re.MULTILINE+)++# One ``{expr}`` interpolation.+_INTERP_RE = re.compile(r"(?<!\{)\{([^{}]+)\}(?!\})")++# ``{{`` / ``}}`` are an escaped brace, which no downstream step distinguishes+# from a path parameter: ``normalize_http_path`` would eat one half and leave+# the other dangling, and the surviving ``}`` passes the unusable-path check.+# A URL needing a literal brace is refused rather than corrupted.+_ESCAPED_BRACE_RE = re.compile(r"\{\{|\}\}")++# Dropped from a base expression (``settings.base.rstrip('/')``) so+# :func:`.paths.base_token_identifier` reads the attribute, not ``rstrip``.+_TRAILING_CALL_RE = re.compile(r"\.\s*\w+\s*\([^()]*\)\s*$")+++def _parse_literal(text: str) -> tuple[str, str] | None:+ """``(lowercased prefix, body)`` when *text* is exactly one string literal."""+ m = _LITERAL_RE.match(text.strip())+ if m is None:+ return None+ body = m.group("body")+ if m.group("q") in body:+ return None # the literal ended and something else followed it+ return m.group("prefix").lower(), body+++def string_constants(content: str, code: str) -> dict[str, str]:+ """Names this file assigns exactly once, to one string literal.++ The value is the literal's raw text with its prefix, so an f-string keeps+ its interpolations for :func:`resolve_url_argument` to fold.++ Assignments are located in *code* — the same text as *content* with comments+ and string bodies blanked — and their values are then read from *content* at+ the same offsets. Searching *content* directly would read the example code+ in a docstring (`` url = "/docs/example"``) as a real assignment.+ """+ seen: dict[str, str | None] = {}+ for m in _ASSIGN_RE.finditer(code):+ name, rhs = m.group(1), content[m.start(2) : m.end(2)].rstrip()+ # A second assignment retires the name whatever it assigns: the reader+ # cannot tell which one reaches the call site.+ seen[name] = None if name in seen or _parse_literal(rhs) is None else rhs.strip()+ return {name: text for name, text in seen.items() if text is not None}+++def _template(body: str, constants: dict[str, str]) -> str:+ """An f-string body as ``${expr}`` text, folding names bound to a plain string."""++ def sub(m: re.Match[str]) -> str:+ expr = m.group(1).strip()+ const = constants.get(expr)+ if const is not None:+ inner = _parse_literal(const)+ # Only a plain literal folds: an f-string constant would need its+ # own interpolations resolved, which no case in the corpus needs.+ if inner is not None and "f" not in inner[0]:+ return inner[1]+ return "${" + _TRAILING_CALL_RE.sub("", expr) + "}"++ return _INTERP_RE.sub(sub, body)+++def resolve_url_argument(arg: str, constants: dict[str, str]) -> str | None:+ """The URL text of *arg*, or ``None`` when it cannot be resolved."""+ text = arg.strip()+ parsed = _parse_literal(text)+ if parsed is None:+ # A bare name. Its folded value is a literal by construction, so one+ # step always reaches the text.+ if _NAME_RE.fullmatch(text) is None:+ return None+ folded = constants.get(text)+ parsed = _parse_literal(folded) if folded is not None else None+ if parsed is None:+ return None+ prefix, body = parsed+ if "b" in prefix:+ return None # bytes, not a URL this layer records+ if "f" not in prefix:+ return body+ return None if _ESCAPED_BRACE_RE.search(body) else _template(body, constants)diff --git a/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py b/packages/core/src/repowise/core/workspace/extractors/http/wrappers.pyindex 2cf65175c..c76c46f8a 100644--- a/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py+++ b/packages/core/src/repowise/core/workspace/extractors/http/wrappers.py@@ -109,6 +109,7 @@ _SINK_CALL_NAMES_BY_SUFFIX: dict[str, frozenset[str]] = {".js": frozenset({"fetch"}),".jsx": frozenset({"fetch"}),".mjs": frozenset({"fetch"}),+ ".py": frozenset({"urlopen"}), # stdlib, and its first argument is the URL}@@ -120,6 +121,17 @@ _JS_LIKE = frozenset({".ts", ".tsx", ".js", ".jsx", ".mjs"})_REGEX_PRECEDERS = frozenset("(,=:[!&|?{};+-*%~^<>")+def _string_prefix(text: str, quote_idx: int) -> str:+ """The ``rb``/``f``/``u`` prefix letters immediately before a quote, if any."""+ k = quote_idx+ while k > 0 and text[k - 1] in "rRbBuUfF":+ k -= 1+ # Preceded by more identifier means those letters end a name, not a prefix.+ if k > 0 and (text[k - 1].isalnum() or text[k - 1] == "_"):+ return ""+ return text[k:quote_idx]++def mask_source(text: str, suffix: str, *, strings: bool = False) -> str:"""Blank out comments — and optionally string bodies — preserving offsets.@@ -135,29 +147,44 @@ def mask_source(text: str, suffix: str, *, strings: bool = False) -> str:reappearing through the back door. The call-site scanner masks commentsonly, since it still has to read the URL literal it is looking for."""- if suffix.lower() not in _JS_LIKE:- # Python: ``#`` to end of line. Triple-quoted strings are left alone;- # no sink pattern here matches inside one without a call following it.- if suffix.lower() != ".py":- return text+ if suffix.lower() != ".py" and suffix.lower() not in _JS_LIKE:+ return text++ if suffix.lower() == ".py":+ # Python: ``#`` to end of line, plus string bodies when asked. Both the+ # triple-quoted delimiter and the ``r`` prefix are read, because getting+ # either wrong desynchronises the scan for the rest of the file — a+ # docstring containing a ``"`` would close early and leave real code+ # masked, and ``r"\"`` would swallow its own closing quote.out = list(text)- i, n, in_str = 0, len(text), ""+ i, n = 0, len(text)while i < n:ch = text[i]- if in_str:- if ch == "\\":- i += 2- continue- if ch == in_str:- in_str = ""- elif ch in "'\"":- in_str = ch- elif ch == "#":+ if ch == "#":while i < n and text[i] != "\n":out[i] = " "i += 1continue- i += 1+ if ch not in "'\"":+ i += 1+ continue+ delim = text[i : i + 3] if text[i : i + 3] in ("'''", '"""') else ch+ raw = "r" in _string_prefix(text, i).lower()+ i += len(delim)+ while i < n:+ if text[i] == "\\" and not raw:+ if strings:+ out[i] = " "+ if i + 1 < n and text[i + 1] != "\n":+ out[i + 1] = " "+ i += 2+ continue+ if text.startswith(delim, i):+ i += len(delim)+ break+ if strings and text[i] != "\n":+ out[i] = " "+ i += 1return "".join(out)out = list(text)@@ -269,6 +296,72 @@ def symbol_body(lines: list[str], symbol: IndexedSymbol) -> str:return "\n".join([head, *rest]) if head else "\n".join(rest)+# The module qualifier is required and is what makes this safe: a bare+# ``Session(`` is SQLAlchemy far more often than requests, and binding it would+# read every ``session.get(Model, pk)`` as an endpoint call.+_PY_CLIENT_CTOR = (+ r"(?P<lib>httpx|requests|aiohttp)\s*\.\s*"+ r"(?:AsyncClient|Client|ClientSession|Session)\s*\("+)++# ``client = httpx.AsyncClient(...)``, ``self._c = client or httpx.Client()``.+_PY_CLIENT_ASSIGN_RE = re.compile(+ r"^[ \t]*(?P<attr>self\s*\.\s*)?(?P<var>[A-Za-z_]\w*)\s*(?::[^=\n]+)?=\s*(?!=)"+ r"(?:[^\n=]*?\bor\s+)?(?:await\s+)?" + _PY_CLIENT_CTOR,+ re.MULTILINE,+)++# ``async with httpx.AsyncClient(...) as client:``+_PY_CLIENT_WITH_RE = re.compile(+ r"\bwith\s+(?:await\s+)?" + _PY_CLIENT_CTOR + r"[^\n]*?\bas\s+(?P<var>[A-Za-z_]\w*)"+)+++def bound_clients(+ content: str, suffix: str, symbols: Sequence[IndexedSymbol]+) -> list[tuple[str, str, int, int]]:+ """``(var, library, from_line, to_line)`` for each HTTP client instance bound.++ Python's dominant client shape binds the client to a variable+ (``async with httpx.AsyncClient() as http``) and calls the endpoint through+ it (``http.post(url)``). That receiver is neither absent nor ``self``, so+ :func:`confirm_wrappers` never sees the call — the sink *is* the call.++ The binding is scoped to the enclosing symbol, not to the file. Measured on+ ``backend/modal_app/content_engine_chain.py``: ``client`` is an+ ``httpx.AsyncClient`` in one function and a Supabase client in another, so a+ file-wide binding would read a database call as an endpoint call. An+ *attribute* binding (``self._client = httpx.Client()``) is file-scoped+ instead, since it is assigned in one method to be read from others.++ Empty for a language with no entry, like the sink tables.+ """+ if suffix.lower() != ".py":+ return []+ # Narrowest span first, so the first hit is the tightest enclosing scope.+ spans = sorted(+ ((s.start_line, s.end_line) for s in symbols if s.kind in _CALLABLE_KINDS),+ key=lambda se: se[1] - se[0],+ )+ whole_file = (1, content.count("\n") + 1)++ def scope(line: int, is_attr: bool) -> tuple[int, int]:+ if is_attr:+ return whole_file+ for start, end in spans:+ if start <= line <= end:+ return start, end+ return whole_file # module level: the client really is file-wide++ out: list[tuple[str, str, int, int]] = []+ for regex in (_PY_CLIENT_ASSIGN_RE, _PY_CLIENT_WITH_RE):+ for m in regex.finditer(content):+ line = content.count("\n", 0, m.start()) + 1+ start, end = scope(line, m.groupdict().get("attr") is not None)+ out.append((m.group("var"), m.group("lib"), start, end))+ return out++def _callable_symbols(symbols: Sequence[IndexedSymbol]) -> dict[str, list[IndexedSymbol]]:"""Callable symbols in this file, indexed by bare name.diff --git a/tests/unit/workspace/test_index_clients.py b/tests/unit/workspace/test_index_clients.pyindex 08416540f..90216fc60 100644--- a/tests/unit/workspace/test_index_clients.py+++ b/tests/unit/workspace/test_index_clients.py@@ -684,3 +684,216 @@ def test_literal_url_recognition(args: str, expected: str | None):from repowise.core.workspace.extractors.http.index_clients import _literal_urlassert _literal_url(args) == expected+++# ---------------------------------------------------------------------------+# Python: the client-instance receiver+# ---------------------------------------------------------------------------+++def _py_symbols(path: str, source: str) -> list[IndexedSymbol]:+ """Python symbols as the rows ingestion persists them."""+ info = FileInfo(+ path=path,+ abs_path=f"C:/fake/{path}",+ language="python",+ size_bytes=len(source),+ git_hash="",+ last_modified=datetime.now(UTC),+ is_test=False,+ is_config=False,+ is_api_contract=False,+ is_entry_point=False,+ )+ return [+ IndexedSymbol(+ symbol_id=sym.id,+ name=sym.name,+ qualified_name=sym.qualified_name,+ kind=sym.kind,+ signature=sym.signature,+ file_path=path,+ start_line=sym.start_line,+ end_line=sym.end_line,+ visibility=sym.visibility,+ )+ for sym in ASTParser().parse_file(info, source.encode()).symbols+ ]+++def _run_py(source: str, path: str = "app/services/caller.py"):+ ctx = ScanContext("backend", path, ".py", source, {})+ return extract_consumers(ctx, _py_symbols(path, source))+++# The shape backend/app/services/frontend_cache.py really uses: a module+# constant for the path, an f-string joining it to a configured base, and the+# call through the variable the async context manager binds.+PURGE_PY = """\+import httpx++_PURGE_PATH = "/api/revalidate/snapshot"+++async def _post_purge(short_id: str) -> bool:+ url = f"{settings.app_base_url.rstrip('/')}{_PURGE_PATH}"+ async with httpx.AsyncClient(follow_redirects=True) as http:+ resp = await http.post(url, json={"short_id": short_id})+ return resp.status_code // 100 == 2+"""+++class TestBoundClientReceiver:+ """``http.post(url)`` on an ``httpx.AsyncClient`` — the shape with no wrapper."""++ def test_the_call_becomes_a_contract(self):+ contracts, unresolved = _run_py(PURGE_PY)+ assert _ids(contracts) == {"http::POST::/api/revalidate/snapshot"}+ assert unresolved == 0++ def test_the_contract_names_the_library_and_strips_the_base(self):+ (contract,) = _run_py(PURGE_PY)[0]+ assert contract.meta["client"] == "httpx"+ assert contract.meta["base_stripped"] is True+ assert contract.meta["base_token"] == "app_base_url"+ assert contract.meta[EXTRACTION_LAYER_KEY] == LAYER_INDEX++ def test_the_verb_names_the_method(self):+ source = (+ "import httpx\n"+ "async def f():\n"+ " async with httpx.AsyncClient() as c:\n"+ " await c.patch('/things/1')\n"+ )+ assert _ids(_run_py(source)[0]) == {"http::PATCH::/things/1"}++ def test_request_is_not_read_as_a_path(self):+ """``client.request(method, url)`` puts the verb first, so it is skipped."""+ source = (+ "import httpx\n"+ "async def f():\n"+ " async with httpx.AsyncClient() as c:\n"+ " await c.request('GET', '/things')\n"+ )+ contracts, unresolved = _run_py(source)+ assert contracts == []+ assert unresolved == 0+++class TestBindingIsRequired:+ """A receiver is a client because the file constructs one, never by name."""++ def test_a_dict_named_client_yields_nothing(self):+ source = (+ "def register(client: dict) -> dict:\n"+ " return {\n"+ " 'name': client.get('/client_name'),\n"+ " 'uris': client.get('/redirect_uris'),\n"+ " }\n"+ )+ assert _run_py(source) == ([], 0)++ def test_a_binding_does_not_escape_its_function(self):+ """Measured on content_engine_chain.py: two objects, one name, one file."""+ source = (+ "import httpx\n"+ "async def notify():\n"+ " async with httpx.AsyncClient() as client:\n"+ " await client.post('/internal/notify')\n"+ "\n"+ "async def read(store):\n"+ " client = await store.get_supabase()\n"+ " return client.get('/rows/all')\n"+ )+ contracts, _ = _run_py(source)+ assert _ids(contracts) == {"http::POST::/internal/notify"}++ def test_an_attribute_binding_reaches_the_other_methods(self):+ source = (+ "import httpx\n"+ "class Osv:\n"+ " def __init__(self):\n"+ " self._client = httpx.Client(base_url='https://osv.dev')\n"+ "\n"+ " def query(self):\n"+ " return self._client.post('/v1/query')\n"+ )+ assert _ids(_run_py(source)[0]) == {"http::POST::/v1/query"}+++class TestPathsAreReadNeverGuessed:+ def test_a_call_shaped_string_is_not_a_call(self):+ """The masked scan is what keeps prose out; ``content`` still has the bytes."""+ source = (+ "import httpx\n"+ "async def f(log):\n"+ " c = httpx.AsyncClient()\n"+ " log.info(\"call c.get('/api/leak') to see\")\n"+ " await c.get('/api/real')\n"+ )+ assert _ids(_run_py(source)[0]) == {"http::GET::/api/real"}++ def test_an_example_in_a_docstring_is_not_an_assignment(self):+ source = (+ "import httpx\n"+ "async def f(build):\n"+ ' """Example:\n'+ "\n"+ ' url = "/docs/example"\n'+ ' """\n'+ " url = build()\n"+ " c = httpx.AsyncClient()\n"+ " await c.get(url)\n"+ )+ contracts, unresolved = _run_py(source)+ assert contracts == []+ assert unresolved == 1++ def test_a_docstring_quote_does_not_desynchronise_the_rest_of_the_file(self):+ """A ``"`` inside a docstring used to close it early and mask real code."""+ source = (+ "import httpx\n"+ "async def f():\n"+ ' """He said "hi" there."""\n'+ " async with httpx.AsyncClient() as c:\n"+ " await c.get('/after/the/docstring')\n"+ )+ assert _ids(_run_py(source)[0]) == {"http::GET::/after/the/docstring"}++ def test_a_name_assigned_twice_is_not_folded(self):+ source = (+ "import httpx\n"+ "async def f(flag):\n"+ " url = '/one'\n"+ " url = '/two'\n"+ " c = httpx.AsyncClient()\n"+ " await c.get(url)\n"+ )+ contracts, unresolved = _run_py(source)+ assert contracts == []+ assert unresolved == 1++ def test_an_unresolvable_call_is_counted_not_dropped(self):+ source = (+ "import httpx\n"+ "async def f(build):\n"+ " c = httpx.AsyncClient()\n"+ " await c.get(build('x'))\n"+ )+ assert _run_py(source) == ([], 1)++ def test_a_literal_brace_is_refused_rather_than_corrupted(self):+ """``{{`` survives normalization as a dangling ``}``, so it is not claimed."""+ source = (+ "import httpx\n"+ "async def f(v):\n"+ " c = httpx.AsyncClient()\n"+ ' await c.get(f"/q/{{literal}}/{v}")\n'+ )+ assert _run_py(source) == ([], 1)+++class TestPythonLeavesTheJsPassAlone:+ def test_a_python_file_with_no_client_yields_nothing(self):+ source = "import os\ndef f():\n return os.environ.get('/not/a/url')\n"+ assert _run_py(source) == ([], 0)