Debian Codegraph @

scripts/verify-anchors-codesearch.py

raw
1 #!/usr/bin/env python3
2 # Copyright: 2026, Maximiliano Curia <[email protected]>
3 #
4 # License: ISC
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8 # .
9 # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10 # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11 # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12 # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13 # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14 # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15 # PERFORMANCE OF THIS SOFTWARE.
16
17 """Verify decopy licence anchors against codesearch.debian.net.
18
19 Each anchor decopy adds to ``LICENSES_RES`` is scanned against *all* input text,
20 so a short/generic anchor can mislabel unrelated files. This tool queries Debian
21 Code Search -- the broadest corpus of "text that is NOT this licence but might
22 trip its anchor" -- and reports whether each anchor's hits are concentrated in
23 licence-bearing files. It is an offline audit aid (like
24 ``audit-license-coverage.py``); it is NOT part of the test suite and must never
25 run in CI.
26
27 It sources anchor patterns from ``decopy.licensing.res`` so it cannot drift from
28 the matchers it audits. The primary unit is each ``LICENSES_RES`` entry (the hot
29 path); ``*_SUBS`` sub-anchors only fire behind a gate, so they are secondary --
30 a stray result on a sub whose gate is clean is ``WEAK-behind-gate``, not a live
31 bug.
32
33 Politeness: one request at a time, never concurrent; a sleep
34 between live requests; on-disk response cache so re-runs do not re-hit the
35 service; a descriptive User-Agent; honours HTTP 429 / Retry-After. The v1 API
36 needs an ``x-dcs-apikey`` header (key from
37 https://codesearch.debian.net/apikeys/ via Salsa login), supplied via
38 ``$DCS_API_KEY`` or ``--key-file PATH`` (no default; the path is never hardcoded
39 and the key is never logged).
40
41 Run from the repository root, e.g. verify a batch's anchors::
42
43 # gates + standalone rules (primary) and their behind-gate subs (secondary)
44 scripts/verify-anchors-codesearch.py \\
45 --licenses CmuMach Ssh BoehmGc Adobe-Display-PostScript Adobe-Utopia \\
46 ssh-keyscan OpenVision \\
47 --subs CMU_MACH_SUBS SSH_SUBS BOEHM_SUBS
48
49 # every LICENSES_RES anchor added since a baseline commit
50 scripts/verify-anchors-codesearch.py --new-since ac025827
51
52 # offline: show what would be queried, no network
53 scripts/verify-anchors-codesearch.py --licenses CmuMach --list
54
55 Caveat: decopy anchors are written against ``clean_comments`` output (newlines,
56 tabs, comment-continuation prefixes, banners and quotes collapsed to single
57 spaces), but Code Search searches the RAW source. The default plain query joins
58 words with ``\\s+`` and so *under*-matches comment-wrapped text (it cannot bridge a
59 ``\\n * `` / ``# `` wrap or a stripped quote), making a low/zero-hit PASS weak
60 evidence. Code Search *does* match across newlines, so ``--comment-aware`` widens
61 each gap to tolerate those characters and recovers the real occurrences (favouring
62 recall; it can over-bridge). Use ``--comment-aware`` for a faithful check; pass
63 ``--query`` to override a single anchor's phrase or ``--max-query-len`` to shorten.
64 """
65
66 from __future__ import annotations
67
68 import argparse
69 import ast
70 import contextlib
71 import subprocess
72 import sys
73 from dataclasses import dataclass, field
74 from pathlib import Path
75
76 try:
77 import regex as rex
78 except ImportError:
79 import re as rex # type: ignore[no-redef]
80
81 ROOT = Path(__file__).resolve().parent.parent
82 sys.path.insert(0, str(ROOT))
83 sys.path.insert(0, str(Path(__file__).resolve().parent))
84
85 from dcs_client import ( # noqa: E402
86 DEFAULT_SLEEP,
87 MAX_RESPONSE_BYTES,
88 DcsClient,
89 DcsConfig,
90 SearchState,
91 load_key,
92 )
93
94 from decopy.common.re_types import ReSub, ReSubGroup # noqa: E402
95 from decopy.licensing import res # noqa: E402
96
97 USER_AGENT = "decopy-anchor-verify (+https://salsa.debian.org/debian/decopy)"
98 DEFAULT_CACHE = ROOT / ".cache" / "dcs-cache"
99 BASELINE_REF = "ac025827"
100
101 TRIGRAM_MIN = 3 # Code Search needs a literal run of at least this length
102 THIN_LEN = 24 # anchors with a shorter longest literal run are flagged risky
103 MAX_QUERY_LEN = 64 # cap the derived query so it tends to fit one source line
104 TINY_TOTAL = 5 # a handful of total hits -> verdict downgraded to manual review
105
106 # decopy matches on clean_comments() output, where newlines, tabs and comment
107 # punctuation are collapsed to single spaces. Code Search searches the RAW source,
108 # where the same gap between two words is often a line wrap with a comment
109 # continuation prefix (" * ", "# ", "// ", ";; ", "> "), a banner ("==="/"***") or
110 # a stripped quote. In --comment-aware mode each inter-word gap becomes this class
111 # so the query matches the same comment-wrapped text decopy would. Code Search
112 # matches across newlines, so this recovers occurrences a plain/\\s+ query misses.
113 # It deliberately favours recall (it can over-bridge), so it is opt-in.
114 COMMENT_GAP = r'[\s"*#;>%!/=~|-]+'
115
116 # A hit counts as licence-context if its path looks like a licence/notice file or
117 # its surrounding lines carry licence wording.
118 LICENCE_PATH_RE = rex.compile(
119 r"(copying|licen[sc]e|copyright|notice|readme|\.spdx|\.license|debian/)",
120 rex.IGNORECASE,
121 )
122 LICENCE_CTX_RE = rex.compile(
123 r"(permission|redistribut|warranty|royalty|copyright|granted|trademark|"
124 r"provided that|as is|disclaim|free of charge|all rights reserved)",
125 rex.IGNORECASE,
126 )
127
128 # Escapes that introduce a character class / anchor (they end a literal run);
129 # any other escaped char is a literal (e.g. \( \. \+ \)).
130 _CLASS_ESCAPES = set("sSdDwWbBAZGnrtfv0123456789")
131
132
133 @dataclass
134 class Anchor:
135 label: str
136 kind: str # "primary" (LICENSES_RES) or "sub" (behind a gate)
137 pattern: str
138 run: str = ""
139 query: str = ""
140 match_mode: str = "regexp"
141 note: str = ""
142
143
144 @dataclass
145 class Result:
146 anchor: Anchor
147 total: int = 0
148 licence: int = 0
149 stray: int = 0
150 strays: list[str] = field(default_factory=list)
151 verdict: str = ""
152
153
154 def longest_literal_run(pattern: str) -> str:
155 """Return the longest run of literal characters in a regex pattern.
156
157 Character classes, groups, quantifiers and class-escapes break a run;
158 ``\\x`` for a non-class ``x`` contributes the literal ``x``. The result is
159 the trigram seed Code Search indexes on -- an empty/short result means the
160 pattern is too generic to search (and so too generic to trust).
161 """
162 runs: list[str] = []
163 cur: list[str] = []
164 i, n = 0, len(pattern)
165 in_class = False
166
167 def flush() -> None:
168 if cur:
169 runs.append("".join(cur))
170 cur.clear()
171
172 while i < n:
173 ch = pattern[i]
174 if in_class:
175 if ch == "]":
176 in_class = False
177 i += 1
178 continue
179 if ch == "\\":
180 nxt = pattern[i + 1] if i + 1 < n else ""
181 if nxt and nxt not in _CLASS_ESCAPES:
182 cur.append(nxt)
183 else:
184 flush()
185 i += 2
186 continue
187 if ch == "[":
188 flush()
189 in_class = True
190 i += 1
191 continue
192 if ch in "()|^$.*+?{}":
193 flush()
194 i += 1
195 continue
196 cur.append(ch)
197 i += 1
198 flush()
199
200 trimmed = [r.strip(" \t:;,.\"'`-") for r in runs]
201 return max(trimmed, key=len) if trimmed else ""
202
203
204 def build_query(
205 run: str, max_len: int, *, literal: bool, comment_aware: bool = False
206 ) -> tuple[str, str]:
207 """Turn a literal run into a (query, match_mode) pair.
208
209 Truncated on a word boundary to ``max_len``. In regexp mode each whitespace
210 gap becomes ``\\s+`` (tolerant of varied spacing within a source line), or
211 ``COMMENT_GAP`` when ``comment_aware`` (also tolerant of comment-continuation
212 prefixes, banners, stripped quotes and line wraps); the words are regex-escaped
213 so punctuation kept from the anchor is literal.
214 """
215 words = run.split()
216 out: list[str] = []
217 length = 0
218 for w in words:
219 add = len(w) + (1 if out else 0)
220 if out and length + add > max_len:
221 break
222 out.append(w)
223 length += add
224 if not out:
225 return run[:max_len], "literal"
226 if literal:
227 return " ".join(out), "literal"
228 gap = COMMENT_GAP if comment_aware else r"\s+"
229 return gap.join(rex.escape(w) for w in out), "regexp"
230
231
232 def relicense_patterns(src: str) -> set[str]:
233 """Extract every ``LICENSES_RES`` ReLicense pattern (arg 0) from source.
234
235 Uses ``ast`` so it works on any checked-out revision without importing it
236 (implicit string concatenation is already merged by the parser).
237 """
238 tree = ast.parse(src)
239 patterns: set[str] = set()
240 for node in ast.walk(tree):
241 if isinstance(node, ast.Assign) and node.targets:
242 target = getattr(node.targets[0], "id", None)
243 value: ast.expr | None = node.value
244 elif isinstance(node, ast.AnnAssign):
245 target = getattr(node.target, "id", None)
246 value = node.value
247 else:
248 continue
249 if target != "LICENSES_RES" or not isinstance(value, ast.Tuple):
250 continue
251 for elt in value.elts:
252 if (
253 isinstance(elt, ast.Call)
254 and getattr(elt.func, "id", None) == "ReLicense"
255 and elt.args
256 ):
257 with contextlib.suppress(ValueError, SyntaxError):
258 patterns.add(ast.literal_eval(elt.args[0]))
259 return patterns
260
261
262 def _anchors_new_since(ref: str) -> list[Anchor]:
263 baseline_src = subprocess.run( # noqa: S603
264 ["git", "show", f"{ref}:decopy/res.py"], # noqa: S607
265 cwd=ROOT,
266 capture_output=True,
267 text=True,
268 check=True,
269 ).stdout
270 old = relicense_patterns(baseline_src)
271 seen: set[str] = set()
272 anchors: list[Anchor] = []
273 for entry in res.LICENSES_RES:
274 if entry.re not in old and entry.re not in seen:
275 seen.add(entry.re)
276 anchors.append(
277 Anchor(label=entry.license, kind="primary", pattern=entry.re)
278 )
279 return anchors
280
281
282 def _anchors_by_name(names: list[str]) -> list[Anchor]:
283 by_name: dict[str, list[str]] = {}
284 for entry in res.LICENSES_RES:
285 by_name.setdefault(entry.license, []).append(entry.re)
286 anchors: list[Anchor] = []
287 for name in names:
288 pats = by_name.get(name)
289 if not pats:
290 print(f"warning: no LICENSES_RES entry named {name!r}", file=sys.stderr)
291 continue
292 for j, pat in enumerate(pats):
293 label = name if len(pats) == 1 else f"{name}#{j + 1}"
294 anchors.append(Anchor(label=label, kind="primary", pattern=pat))
295 return anchors
296
297
298 def _flatten_subs(tup: tuple[ReSub | ReSubGroup, ...]) -> list[ReSub]:
299 """Flatten a *_SUBS tuple, expanding any ReSubGroup into its member ReSubs."""
300 out: list[ReSub] = []
301 for sub in tup:
302 if isinstance(sub, ReSubGroup):
303 out.extend(sub.subs)
304 else:
305 out.append(sub)
306 return out
307
308
309 def _anchors_from_subs(sub_names: list[str]) -> list[Anchor]:
310 anchors: list[Anchor] = []
311 for sub_name in sub_names:
312 tup = getattr(res, sub_name, None)
313 if tup is None:
314 print(f"warning: no SUBS tuple named {sub_name!r}", file=sys.stderr)
315 continue
316 anchors.extend(
317 Anchor(
318 label=f"{sub_name}:{sub.repl}",
319 kind="sub",
320 pattern=sub.pattern.pattern,
321 )
322 for sub in _flatten_subs(tup)
323 )
324 return anchors
325
326
327 def collect_anchors(args: argparse.Namespace) -> list[Anchor]:
328 anchors: list[Anchor] = []
329 if args.new_since:
330 anchors += _anchors_new_since(args.new_since)
331 anchors += _anchors_by_name(list(args.licenses) + list(args.positional))
332 anchors += _anchors_from_subs(args.subs)
333
334 for a in anchors:
335 a.run = longest_literal_run(a.pattern)
336 if len(a.run) < TRIGRAM_MIN:
337 a.note = "no-trigram"
338 continue
339 a.query, a.match_mode = build_query(
340 a.run,
341 args.max_query_len,
342 literal=args.literal,
343 comment_aware=args.comment_aware,
344 )
345 if len(a.run) < THIN_LEN:
346 a.note = "thin"
347 return anchors
348
349
350 def classify(results: list[dict]) -> tuple[int, int, int, list[str]]:
351 licence = stray = 0
352 strays: list[str] = []
353 for r in results:
354 ctx = " ".join(
355 [
356 *r.get("context_before", []),
357 r.get("context", ""),
358 *r.get("context_after", []),
359 ]
360 )
361 if LICENCE_PATH_RE.search(r.get("path", "")) or LICENCE_CTX_RE.search(ctx):
362 licence += 1
363 else:
364 stray += 1
365 strays.append(r.get("path", "?"))
366 return len(results), licence, stray, strays
367
368
369 def verdict(anchor: Anchor, total: int, stray: int) -> str:
370 if anchor.note == "no-trigram":
371 return "RED:no-trigram"
372 if stray == 0:
373 return "PASS"
374 if total <= TINY_TOTAL:
375 return "WEAK:tiny(review)"
376 return "WEAK-behind-gate" if anchor.kind == "sub" else "REVIEW"
377
378
379 def main() -> None:
380 ap = argparse.ArgumentParser(description=(__doc__ or "").splitlines()[0])
381 ap.add_argument("positional", nargs="*", help="LICENSES_RES group/licence names")
382 ap.add_argument(
383 "--licenses",
384 nargs="+",
385 default=[],
386 help="LICENSES_RES names (primary anchors)",
387 )
388 ap.add_argument(
389 "--subs",
390 nargs="+",
391 default=[],
392 help="*_SUBS tuple names (behind-gate anchors)",
393 )
394 ap.add_argument(
395 "--new-since",
396 nargs="?",
397 const=BASELINE_REF,
398 help=f"verify LICENSES_RES entries added since REF (default {BASELINE_REF})",
399 )
400 ap.add_argument(
401 "--list", action="store_true", help="show queries; do not hit network"
402 )
403 ap.add_argument("--refresh", action="store_true", help="ignore cache; re-query")
404 ap.add_argument(
405 "--literal", action="store_true", help="literal match_mode (no \\s+)"
406 )
407 ap.add_argument(
408 "--comment-aware",
409 action="store_true",
410 help="inter-word gaps tolerate comment-continuation/line-wrap (recall++)",
411 )
412 ap.add_argument("--query", help="override the derived query (single anchor only)")
413 ap.add_argument("--max-query-len", type=int, default=MAX_QUERY_LEN)
414 ap.add_argument("--sleep", type=float, default=DEFAULT_SLEEP)
415 ap.add_argument(
416 "--key-file",
417 type=Path,
418 default=None,
419 help="file holding the API key (or set $DCS_API_KEY)",
420 )
421 ap.add_argument("--cache-dir", type=Path, default=DEFAULT_CACHE)
422 ap.add_argument(
423 "--show-strays", type=int, default=5, help="sample stray paths to print"
424 )
425 args = ap.parse_args()
426
427 anchors = collect_anchors(args)
428 if not anchors:
429 msg = "No anchors selected. Pass names, --licenses, --subs or --new-since."
430 raise SystemExit(msg)
431 if args.query:
432 if len(anchors) != 1:
433 msg = "--query needs exactly one selected anchor."
434 raise SystemExit(msg)
435 anchors[0].query = args.query
436 anchors[0].match_mode = "literal" if args.literal else "regexp"
437 if anchors[0].note != "thin":
438 anchors[0].note = ""
439
440 mode = "literal" if args.literal else "regexp"
441 if args.comment_aware and not args.literal:
442 mode += "+comment-aware"
443 print(
444 f"# {len(anchors)} anchor(s); mode={mode} "
445 f"max_query_len={args.max_query_len} sleep={args.sleep}s"
446 )
447 if args.list:
448 for a in anchors:
449 tag = f" [{a.note}]" if a.note else ""
450 print(f"{a.kind:8} {a.label:32} run={len(a.run):3} q={a.query!r}{tag}")
451 return
452
453 client = DcsClient(
454 DcsConfig(
455 key=load_key(args.key_file),
456 user_agent=USER_AGENT,
457 cache_dir=args.cache_dir,
458 sleep=args.sleep,
459 refresh=args.refresh,
460 )
461 )
462 run_anchors(client, anchors, args.show_strays)
463
464
465 def run_anchors(client: DcsClient, anchors: list[Anchor], show_strays: int) -> None:
466 results: list[Result] = []
467 for a in anchors:
468 if a.note == "no-trigram":
469 r = Result(anchor=a, verdict="RED:no-trigram")
470 else:
471 outcome = client.search_live(a.query, a.match_mode)
472 if outcome.state is SearchState.BROAD:
473 cap = MAX_RESPONSE_BYTES // 1_000_000
474 r = Result(anchor=a, verdict=f"BROAD:>{cap}MB")
475 else:
476 total, lic, stray, strays = classify(outcome.hits)
477 r = Result(a, total, lic, stray, strays, verdict(a, total, stray))
478 results.append(r)
479 tag = f" [{a.note}]" if a.note else ""
480 print(
481 f"{r.verdict:18} {a.kind:8} {a.label:32}"
482 f" total={r.total:4} licence={r.licence:4} stray={r.stray:4}{tag}"
483 )
484 for p in r.strays[:show_strays]:
485 print(f" stray: {p}")
486
487 # BROAD anchors are broad-by-design (a common licence phrase), not an FP risk.
488 weak = [r for r in results if not r.verdict.startswith(("PASS", "BROAD"))]
489 broad = sum(r.verdict.startswith("BROAD") for r in results)
490 print(
491 f"\n# {len(results) - len(weak) - broad} PASS, {broad} BROAD (by design), "
492 f"{len(weak)} need review"
493 )
494 for r in weak:
495 print(f"# {r.verdict}: {r.anchor.label}")
496
497
498 if __name__ == "__main__":
499 main()