sourcecode 5.2.0__py3-none-any.whl → 5.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sourcecode/timeline.py ADDED
@@ -0,0 +1,459 @@
1
+ """timeline.py — since when, and in which window (F-BJ).
2
+
3
+ `data-exposure` answers *"2 453 routes reach labelled data and nothing decides
4
+ access to them"*. The question that follows is the one nobody can answer today
5
+ and the one a regulator asks first: **since when**. A finding without a date is
6
+ an argument; a finding with a date and a commit window is a work item.
7
+
8
+ Nothing here is a new analysis. Every metric below is a projection of a payload
9
+ this product already emits, taken over a series of tree states the repository
10
+ already records, and published as **transitions** rather than as a per-commit
11
+ dump — the value of a series is where it moved.
12
+
13
+ Why this is buildable now and was not before: the analyses it samples cost
14
+ seconds rather than tens of minutes, and eleven consecutive rounds of
15
+ byte-identical payloads on one commit mean a difference between two samples is a
16
+ difference in the *code*, not in the tool. Without that determinism a time series
17
+ is noise with dates on it.
18
+
19
+ Three rules this module holds to, all of them the same rule the rest of the
20
+ product holds to:
21
+
22
+ * **A sample that could not be measured is `null` with a reason** — never 0, and
23
+ never dropped. A commit that does not build a model is a hole in the series
24
+ and says so.
25
+ * **A transition is attributed to the window it was observed in, not to a commit
26
+ it was not proven in.** With sampling on, the honest claim is *"the value
27
+ differs at C, and the change is in one of the N commits between B and C"*.
28
+ Sample every commit (`--max-commits` large enough that the stride is 1) and
29
+ the window closes to a single commit, which the payload then says outright.
30
+ * **The cost is published**, because a series over 100 commits is a nightly job
31
+ and a reader deciding whether to run one needs the per-sample seconds this run
32
+ actually measured.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import subprocess
37
+ import time
38
+ from dataclasses import dataclass, field
39
+ from pathlib import Path
40
+ from typing import Any, Callable, Optional
41
+
42
+ SCHEMA_VERSION = "timeline-v1"
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Metric:
47
+ """One watchable series: a name, what it means, and how to read it off a tree."""
48
+
49
+ name: str
50
+ axes: tuple[str, ...]
51
+ reads: str
52
+ describe: str
53
+ measure: Callable[[Path], dict]
54
+
55
+
56
+ def _posture_metrics(root: Path) -> dict:
57
+ """Access under the profile set the tree itself decides — no profile named.
58
+
59
+ The same default `posture` answers with, so a series compares like with like:
60
+ naming a profile set here would measure the reviewer's hypothesis rather than
61
+ the repository's own trajectory.
62
+ """
63
+ from sourcecode.posture import access_verdict, build_posture
64
+
65
+ payload = build_posture(root, set())
66
+ endpoints = payload.get("endpoints") or {}
67
+ summary = ((endpoints.get("effective_access") or {}).get("summary")) or {}
68
+ counts = {"open": 0, "unknown": 0, "protected": 0}
69
+ for decision, count in summary.items():
70
+ counts[access_verdict(decision)] = counts.get(access_verdict(decision), 0) + int(count)
71
+ return {
72
+ "endpoints": endpoints.get("total"),
73
+ "open_by_rule": counts["open"],
74
+ "access_not_decided": counts["unknown"],
75
+ "protected": counts["protected"],
76
+ }
77
+
78
+
79
+ def _data_exposure_metrics(root: Path) -> dict:
80
+ """Routes that can carry a declared label, and how many nothing protects.
81
+
82
+ A repository with no `.ask/data-labels.yml` at this commit answers `null` on
83
+ every axis: the question was not asked yet at that point in history, which is
84
+ a different fact from "nothing was exposed".
85
+ """
86
+ from sourcecode.data_exposure import build_data_exposure
87
+
88
+ payload = build_data_exposure(root)
89
+ if not payload.get("answered"):
90
+ return {"routes": None, "coverage_unknown": None, "labels": None}
91
+ summary = payload.get("summary") or {}
92
+ verdicts = summary.get("by_security_verdict") or {}
93
+ return {
94
+ "routes": len(payload.get("routes") or []),
95
+ "coverage_unknown": int(verdicts.get("coverage_unknown", 0) or 0),
96
+ "labels": summary.get("labels"),
97
+ }
98
+
99
+
100
+ def _endpoint_metrics(root: Path) -> dict:
101
+ """The HTTP surface itself — the denominator every other series moves against."""
102
+ from sourcecode.canonical_ir import build_canonical_ir
103
+ from sourcecode.repository_ir import find_java_files
104
+
105
+ cir = build_canonical_ir(find_java_files(root), root)
106
+ return {"endpoints": len(getattr(cir, "endpoints", []) or [])}
107
+
108
+
109
+ def _audit_metrics(root: Path) -> dict:
110
+ """Findings and defects, over the rule families that ship."""
111
+ from sourcecode.canonical_ir import build_canonical_ir
112
+ from sourcecode.repository_ir import find_java_files
113
+ from sourcecode.spring_findings import SpringAuditResult
114
+ from sourcecode.spring_model import SpringSemanticModel
115
+ from sourcecode.spring_security_audit import run_security_audit
116
+ from sourcecode.spring_tx_analyzer import run_tx_audit
117
+
118
+ cir = build_canonical_ir(find_java_files(root), root)
119
+ model = SpringSemanticModel.build(cir)
120
+ merged = SpringAuditResult.merge(
121
+ [
122
+ run_tx_audit(cir, root=root, model=model),
123
+ run_security_audit(cir, root=root, model=model),
124
+ ],
125
+ scope="all",
126
+ )
127
+ return {
128
+ "findings": merged.summary.get("total_findings"),
129
+ "defects": merged.summary.get("total_defects"),
130
+ }
131
+
132
+
133
+ #: The watchable population, one authority. A metric is admissible here only if
134
+ #: it is a projection of a payload this product already publishes — the series
135
+ #: must be re-derivable by running that command at that commit, or the timeline
136
+ #: becomes a second source of truth for the same fact.
137
+ METRICS: dict[str, Metric] = {
138
+ "posture": Metric(
139
+ name="posture",
140
+ axes=("endpoints", "open_by_rule", "access_not_decided", "protected"),
141
+ reads="ask posture <tree>",
142
+ describe=(
143
+ "Requests a readable rule permits unauthenticated, under the profile "
144
+ "set the tree itself decides"
145
+ ),
146
+ measure=_posture_metrics,
147
+ ),
148
+ "data-exposure": Metric(
149
+ name="data-exposure",
150
+ axes=("routes", "coverage_unknown", "labels"),
151
+ reads="ask data-exposure <tree>",
152
+ describe=(
153
+ "Routes that reach a declared label, and how many of them nothing "
154
+ "protects"
155
+ ),
156
+ measure=_data_exposure_metrics,
157
+ ),
158
+ "endpoints": Metric(
159
+ name="endpoints",
160
+ axes=("endpoints",),
161
+ reads="ask endpoints <tree>",
162
+ describe="The declared HTTP surface",
163
+ measure=_endpoint_metrics,
164
+ ),
165
+ "spring-audit": Metric(
166
+ name="spring-audit",
167
+ axes=("findings", "defects"),
168
+ reads="ask spring-audit <tree>",
169
+ describe="Findings and the defects they witness",
170
+ measure=_audit_metrics,
171
+ ),
172
+ }
173
+
174
+
175
+ class TimelineError(ValueError):
176
+ """The series could not be built — a bad ref, an unwatchable metric."""
177
+
178
+ def __init__(self, code: str, message: str, **context: Any) -> None:
179
+ super().__init__(message)
180
+ self.code = code
181
+ self.message = message
182
+ self.context = context
183
+
184
+
185
+ @dataclass
186
+ class Sample:
187
+ sha: str
188
+ short: str
189
+ date: str
190
+ author: str
191
+ subject: str
192
+ metrics: Optional[dict] = None
193
+ unmeasured: str = ""
194
+ seconds: float = 0.0
195
+
196
+ def to_dict(self) -> dict:
197
+ out: dict = {
198
+ "sha": self.sha,
199
+ "short": self.short,
200
+ "date": self.date,
201
+ "author": self.author,
202
+ "subject": self.subject,
203
+ "metrics": self.metrics,
204
+ "seconds": round(self.seconds, 2),
205
+ }
206
+ if self.unmeasured:
207
+ # I-3 / R9: a sample that failed is a hole in the series, not a zero.
208
+ out["unmeasured"] = self.unmeasured
209
+ return out
210
+
211
+
212
+ def _git(repo: Path, *args: str) -> subprocess.CompletedProcess:
213
+ return subprocess.run(
214
+ ["git", "-C", str(repo), *args], capture_output=True, text=True, check=False,
215
+ )
216
+
217
+
218
+ def commit_series(repo: Path, since: str, *, first_parent: bool = True) -> list[dict]:
219
+ """Every commit from *since* (exclusive) to HEAD, oldest first.
220
+
221
+ First-parent by default: a merge's second parent is another branch's history,
222
+ and walking into it produces a series whose x-axis is not the trunk.
223
+ """
224
+ args = ["log", "--reverse", "--date=short",
225
+ "--pretty=format:%H%x1f%h%x1f%ad%x1f%an%x1f%s"]
226
+ if first_parent:
227
+ args.append("--first-parent")
228
+ args.append(f"{since}..HEAD")
229
+ result = _git(repo, *args)
230
+ if result.returncode != 0:
231
+ raise TimelineError(
232
+ "git_ref_not_found",
233
+ f"{since!r} does not resolve in this repository, or has no path to HEAD.",
234
+ ref=since,
235
+ )
236
+ rows: list[dict] = []
237
+ for line in result.stdout.splitlines():
238
+ parts = line.split("\x1f")
239
+ if len(parts) != 5:
240
+ continue
241
+ rows.append({
242
+ "sha": parts[0], "short": parts[1], "date": parts[2],
243
+ "author": parts[3], "subject": parts[4],
244
+ })
245
+ return rows
246
+
247
+
248
+ def stride_for(total: int, max_samples: int) -> int:
249
+ """The sampling stride, and why a series of 100 commits is not 100 analyses."""
250
+ if max_samples <= 0 or total <= max_samples:
251
+ return 1
252
+ return -(-total // max_samples) # ceil
253
+
254
+
255
+ def _select(rows: list[dict], max_samples: int) -> tuple[list[dict], int]:
256
+ """The sampled subset, always including the newest commit.
257
+
258
+ The newest is included unconditionally: a series whose last point is three
259
+ commits before HEAD answers about a tree nobody has.
260
+ """
261
+ stride = stride_for(len(rows), max_samples)
262
+ if stride == 1:
263
+ return list(rows), 1
264
+ picked = rows[::stride]
265
+ if rows and picked[-1]["sha"] != rows[-1]["sha"]:
266
+ picked.append(rows[-1])
267
+ return picked, stride
268
+
269
+
270
+ def build_timeline(
271
+ repo: Path,
272
+ since: str,
273
+ watch: list[str],
274
+ *,
275
+ max_samples: int = 10,
276
+ first_parent: bool = True,
277
+ progress: Optional[Callable[[str], None]] = None,
278
+ ) -> dict:
279
+ """Walk the commit series and publish where the watched metrics moved."""
280
+ from sourcecode.git_checkout import RefError, materialize_ref, repo_root
281
+
282
+ try:
283
+ root = repo_root(Path(repo))
284
+ except RefError as exc:
285
+ # A series is a fact about a history; a directory without one has no
286
+ # series, and saying so is the answer rather than a stack trace.
287
+ raise TimelineError(exc.code, exc.message, ref=since) from exc
288
+ unknown = [name for name in watch if name not in METRICS]
289
+ if unknown:
290
+ raise TimelineError(
291
+ "unknown_metric",
292
+ f"Not a watchable metric: {', '.join(sorted(unknown))}. "
293
+ f"Available: {', '.join(sorted(METRICS))}.",
294
+ available=sorted(METRICS),
295
+ )
296
+
297
+ rows = commit_series(root, since, first_parent=first_parent)
298
+ if not rows:
299
+ raise TimelineError(
300
+ "empty_range",
301
+ f"No commits between {since!r} and HEAD — there is no series to build.",
302
+ ref=since,
303
+ )
304
+ selected, stride = _select(rows, max_samples)
305
+
306
+ samples: list[Sample] = []
307
+ for index, row in enumerate(selected, start=1):
308
+ if progress is not None:
309
+ progress(f"sampling {index}/{len(selected)} — {row['short']} ({row['date']})")
310
+ sample = Sample(
311
+ sha=row["sha"], short=row["short"], date=row["date"],
312
+ author=row["author"], subject=row["subject"],
313
+ )
314
+ started = time.perf_counter()
315
+ try:
316
+ with materialize_ref(root, row["sha"]) as tree:
317
+ measured: dict = {}
318
+ for name in watch:
319
+ try:
320
+ measured[name] = METRICS[name].measure(tree)
321
+ except Exception as exc: # one metric failing is not the series failing
322
+ measured[name] = None
323
+ sample.unmeasured = (
324
+ f"{name}: {type(exc).__name__} — this axis is unknown at "
325
+ "this commit, not zero"
326
+ )
327
+ sample.metrics = measured
328
+ except RefError as exc:
329
+ sample.unmeasured = f"{exc.code}: {exc.message}"
330
+ except Exception as exc:
331
+ sample.unmeasured = f"{type(exc).__name__}: {exc}"
332
+ sample.seconds = time.perf_counter() - started
333
+ samples.append(sample)
334
+
335
+ return {
336
+ "schema_version": SCHEMA_VERSION,
337
+ "range": {
338
+ "since": since,
339
+ "commits_in_range": len(rows),
340
+ "oldest": rows[0]["short"],
341
+ "newest": rows[-1]["short"],
342
+ "first_parent": first_parent,
343
+ },
344
+ "sampling": _sampling_block(rows, selected, stride, max_samples),
345
+ "watch": list(watch),
346
+ "metrics_read": {
347
+ name: {"reads": METRICS[name].reads, "measures": METRICS[name].describe,
348
+ "axes": list(METRICS[name].axes)}
349
+ for name in watch
350
+ },
351
+ "samples": [s.to_dict() for s in samples],
352
+ "transitions": transitions(samples, watch, stride),
353
+ "cost": _cost_block(samples),
354
+ "basis": (
355
+ "Every value here is a projection of a payload this product already "
356
+ "publishes, measured on a read-only materialisation of that commit "
357
+ "(nothing is written to the repository). Re-run the command named in "
358
+ "`metrics_read` at that commit and you get the same number — that is "
359
+ "what makes the series comparable across points."
360
+ ),
361
+ }
362
+
363
+
364
+ def _sampling_block(
365
+ rows: list[dict], selected: list[dict], stride: int, max_samples: int
366
+ ) -> dict:
367
+ return {
368
+ "requested_max": max_samples,
369
+ "sampled": len(selected),
370
+ "stride": stride,
371
+ "strategy": (
372
+ "every commit in the range" if stride == 1
373
+ else f"every {stride}th commit, plus the newest"
374
+ ),
375
+ "attribution": (
376
+ "Each transition names the commit it was first observed at, and that "
377
+ "commit is the change."
378
+ if stride == 1 else
379
+ f"Each transition names the commit it was first observed at. With a "
380
+ f"stride of {stride}, the change happened in one of the {stride} "
381
+ f"commits ending there — the window is published per transition and "
382
+ f"is NOT narrowed by guessing. Re-run with --max-commits "
383
+ f"{len(rows)} to close it to a single commit."
384
+ ),
385
+ }
386
+
387
+
388
+ def _cost_block(samples: list[Sample]) -> dict:
389
+ measured = [s.seconds for s in samples if s.metrics is not None]
390
+ total = sum(s.seconds for s in samples)
391
+ return {
392
+ "seconds_total": round(total, 2),
393
+ "seconds_per_sample_median": (
394
+ round(sorted(measured)[len(measured) // 2], 2) if measured else None
395
+ ),
396
+ "samples_measured": len(measured),
397
+ "samples_unmeasured": len(samples) - len(measured),
398
+ "basis": (
399
+ "Measured on this run, on this machine. A longer series costs this "
400
+ "per sample: the analyses are re-run per commit and nothing is shared "
401
+ "between them, because two commits are two trees."
402
+ ),
403
+ }
404
+
405
+
406
+ def transitions(samples: list[Sample], watch: list[str], stride: int) -> list[dict]:
407
+ """Where a watched axis changed value, in the window it changed in.
408
+
409
+ The first sample establishes the baseline and is never a transition: a series
410
+ that opens with "0 → 2 453" would attribute the whole history to whichever
411
+ commit the caller happened to start at.
412
+ """
413
+ out: list[dict] = []
414
+ previous: dict[tuple[str, str], Any] = {}
415
+ previous_sample: Optional[Sample] = None
416
+ for sample in samples:
417
+ if sample.metrics is None:
418
+ continue
419
+ for metric_name in watch:
420
+ axes = sample.metrics.get(metric_name)
421
+ if not isinstance(axes, dict):
422
+ continue
423
+ for axis, value in axes.items():
424
+ key = (metric_name, axis)
425
+ if key not in previous:
426
+ previous[key] = value
427
+ continue
428
+ before = previous[key]
429
+ if before == value:
430
+ continue
431
+ previous[key] = value
432
+ row: dict = {
433
+ "metric": f"{metric_name}.{axis}",
434
+ "from": before,
435
+ "to": value,
436
+ "delta": (
437
+ value - before
438
+ if isinstance(before, (int, float)) and isinstance(value, (int, float))
439
+ else None
440
+ ),
441
+ "observed_at": {
442
+ "sha": sample.sha, "short": sample.short, "date": sample.date,
443
+ "author": sample.author, "subject": sample.subject,
444
+ },
445
+ }
446
+ if stride > 1 and previous_sample is not None:
447
+ row["window"] = {
448
+ "after": previous_sample.short,
449
+ "through": sample.short,
450
+ "commits": stride,
451
+ "note": (
452
+ "The change is in one of these commits. It is not "
453
+ "attributed to a single one, because it was not "
454
+ "measured at a single one."
455
+ ),
456
+ }
457
+ out.append(row)
458
+ previous_sample = sample
459
+ return out
@@ -264,6 +264,15 @@ def _audit_findings(cir: Any, root: "Optional[Path]" = None) -> list[Any]:
264
264
  )
265
265
  for f in result.findings
266
266
  ]
267
+ # F-BI: a finding this repository adjudicated as not-a-defect-here does not
268
+ # hold the gate red. That is the whole point of a waiver — a gate that is
269
+ # always red trains a team to ignore it — and the adjudication itself is
270
+ # published by `spring-audit`, which is the surface that answers *what was
271
+ # waived and why*. A malformed waivers file raises rather than filtering
272
+ # nothing: it must not decide a gate by being broken.
273
+ from sourcecode.waivers import apply_waivers as _apply_waivers
274
+
275
+ findings = _apply_waivers(findings, root).kept
267
276
  try:
268
277
  object.__setattr__(cir, key, findings)
269
278
  except Exception: