Repository navigation
Expand file tree
/
Copy pathbzlog.py
More file actions
2442 lines (2241 loc) · 111 KB
/
Copy pathbzlog.py
File metadata and controls
2442 lines (2241 loc) · 111 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""bzlog - collapse a Bazel Build Event Protocol stream into an agent-sized JSON container.
Usage:
bazel test //... --build_event_json_file=bep.json
bzlog bep.json > result.json
Design notes
------------
Unlike line-oriented compressors (rtk, sqz), this works on Bazel's *structured*
event stream. Two consequences:
1. Classification is read from the build system, not guessed with regexes.
ActionExecuted.type tells us "CppCompile"; FailureDetail gives a machine
category; TestResult carries an explicit status enum.
2. Root-cause collapsing. In a monorepo one broken header fails N targets with
byte-identical stderr. Line-based tools emit N copies. We emit one
diagnostic with affected_count=N. This is the main compression win and it
is only possible because the events carry target labels.
"""
from __future__ import annotations
import json
import os
import re
import sys
import hashlib
import argparse
import math
import time
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Iterator, Optional
from urllib.parse import urlparse, unquote
__version__ = "0.0.1"
SCHEMA = "bzlog/v2"
MAX_EVIDENCE_LINES = 40
MAX_EVIDENCE_BYTES = 4096
# Framework-extracted logs are already distilled, so they get a higher cap
# than the blind tail: cutting a distilled log loses signal, cutting a raw
# one loses noise.
MAX_EXTRACTED_LINES = 160
MAX_EXTRACTED_BYTES = 16384
MAX_DIAGNOSTICS = 25
MAX_TEST_ATTEMPTS = 10
FAILED_TEST_STATUSES = {"FAILED", "TIMEOUT", "REMOTE_FAILURE", "FAILED_TO_BUILD"}
DIAGNOSTIC_EVIDENCE_FIELDS = ("evidence", "invocation_evidence", "command_evidence", "failure_message_evidence")
# --------------------------------------------------------------------------
# diagnostic line parsers
# --------------------------------------------------------------------------
# gcc/clang: path/to/file.cc:42:7: error: 'bar' was not declared in this scope
_GCC = re.compile(
r"^(?P<file>[^\s:][^:]*):(?P<line>\d+):(?:(?P<col>\d+):)?\s*"
r"(?P<severity>error|warning|note|fatal error):\s*(?P<message>.*)$"
)
# go: ./pkg/foo.go:12:2: undefined: Bar
_GO = re.compile(
r"^(?P<file>\.?/?[\w./+-]+\.go):(?P<line>\d+):(?P<col>\d+):\s+(?P<message>.+)$"
)
# javac: pkg/Foo.java:12: error: cannot find symbol
_JAVAC = re.compile(
r"^(?P<file>[\w./$+-]+\.java):(?P<line>\d+):\s*"
r"(?P<severity>error|warning):\s*(?P<message>.*)$"
)
# rustc: error[E0433]: failed to resolve
_RUSTC = re.compile(r"^(?P<severity>error|warning)(\[(?P<code>E\d+)\])?:\s*(?P<message>.+)$")
_BAZEL = re.compile(
r"^ERROR:\s+(?P<file>[^:]+):(?P<line>\d+):(?:(?P<col>\d+):)?\s*(?P<message>.+)$"
)
_PARSERS = [
("bazel", _BAZEL),
("gcc", _GCC),
("javac", _JAVAC),
("go", _GO),
("rustc", _RUSTC),
]
# Noise that never helps an agent reason about the failure.
_NOISE = re.compile(
r"^(INFO:|Loading:|Analyzing:|\[\d+ / \d+\]|Computing main repo mapping|"
r"WARNING: Streamed test output|.*\bcompilation terminated\b.*|"
r"In file included from |\s+from |\s*\|\s*$|\s*\^~*\s*$)"
)
def parse_diagnostics(text: str, limit: int = 12) -> list[dict[str, Any]]:
"""Extract structured compiler diagnostics from a stderr blob."""
out: list[dict[str, Any]] = []
for raw in text.splitlines():
line = raw.rstrip()
if not line or _NOISE.match(line):
continue
for kind, rx in _PARSERS:
m = rx.match(line)
if not m:
continue
g = m.groupdict()
sev = g.get("severity") or "error"
if sev in ("note", "warning"):
break # keep only hard failures in the compact view
d: dict[str, Any] = {"severity": sev, "message": g["message"].strip()}
if g.get("file"):
path = g["file"]
d["file"] = path[2:] if path.startswith("./") else path
if g.get("line"):
d["line"] = int(g["line"])
if g.get("col"):
d["col"] = int(g["col"])
if g.get("code"):
d["code"] = g["code"]
d["parser"] = kind
out.append(d)
break
if len(out) >= limit:
break
return out
# --------------------------------------------------------------------------
# helpers
# --------------------------------------------------------------------------
def _dur_s(d: Any) -> float:
"""protobuf Duration in JSON is a string like '12.5s'; sometimes an object."""
if not d:
return 0.0
if isinstance(d, str):
try:
return float(d.rstrip("s"))
except ValueError:
return 0.0
if isinstance(d, dict):
return float(d.get("seconds", 0)) + float(d.get("nanos", 0)) / 1e9
return 0.0
def uri_to_path(uri: str) -> Optional[str]:
if not isinstance(uri, str) or not uri:
return None
if os.path.isabs(uri):
return uri
try:
parsed = urlparse(uri)
except ValueError:
return None
if (parsed.scheme and parsed.scheme != "file") or parsed.netloc not in ("", "localhost"):
return None # Remote references must never fall back to a local path.
# Resolve against --root before checking whether a relative path exists.
return unquote(parsed.path) if parsed.scheme == "file" else uri
def read_file_message(fm: dict[str, Any], root: Optional[str]) -> str:
"""A BEP `File` may inline its bytes or point at a URI."""
if not fm:
return ""
if "contents" in fm:
import base64
try:
return base64.b64decode(fm["contents"]).decode("utf-8", "replace")
except Exception:
return ""
path = uri_to_path(fm.get("uri", ""))
if path and root and not os.path.isabs(path):
path = os.path.join(root, path)
if path and os.path.isfile(path):
try:
with open(path, "r", errors="replace") as fh:
return fh.read()
except OSError:
return ""
return ""
def tail(text: str, lines: int = MAX_EVIDENCE_LINES, nbytes: int = MAX_EVIDENCE_BYTES):
"""Keep the tail: for build tools the useful part is almost always at the end."""
body = text.splitlines()
truncated = len(body) > lines
kept = "\n".join(body[-lines:])
if len(kept.encode()) > nbytes:
kept = kept.encode()[-nbytes:].decode("utf-8", "replace")
truncated = True
return kept, truncated
def bounded_log(text: str, nbytes: int = 65536) -> str:
"""Bound invocation context while retaining both early errors and final output."""
raw = text.encode("utf-8")
if len(raw) <= nbytes:
return text
marker = b"\n[... invocation output omitted ...]\n"
half = (nbytes - len(marker)) // 2
return (raw[:half].decode("utf-8", "ignore") + marker.decode() +
raw[-half:].decode("utf-8", "ignore"))
def invocation_error_context(text: str) -> str:
"""Prefer Bazel ERROR blocks and their tracebacks over warning fanout."""
lines = [line for line in text.splitlines() if not _NOISE.match(line)]
errors = []
in_error = False
for line in lines:
if line.startswith("ERROR:"):
in_error = True
elif line.startswith(("WARNING:", "DEBUG:", "[BEP progress]")):
in_error = False
if in_error:
errors.append(line)
return "\n".join(errors or lines).strip()
def parse_junit(xml_text: str, limit: int = 10) -> list[dict[str, Any]]:
"""Pull failing cases out of a JUnit test.xml."""
cases: list[dict[str, Any]] = []
try:
root = ET.fromstring(xml_text)
except ET.ParseError:
return cases
for tc in root.iter("testcase"):
for tag in ("failure", "error"):
node = tc.find(tag)
if node is None:
continue
msg = (node.get("message") or (node.text or "")).strip()
cases.append({
"case": tc.get("name", "?"),
"class": tc.get("classname", ""),
"type": tag,
"message": msg.splitlines()[0][:400] if msg else "",
})
break
if len(cases) >= limit:
break
return cases
# --------------------------------------------------------------------------
# framework-aware test log truncation
# --------------------------------------------------------------------------
# A registry of (name, detector, extractor) pairs. Detection is content-based:
# the rule mnemonic lies on custom test wrappers, the log itself does not.
# Each extractor returns the distilled text or None; anything unrecognized
# falls back to the blind tail() in Evidence.add.
#
# The main byte win is stack filtering: frames whose path lies outside the
# workspace are collapsed to a one-line marker.
# Paths that are framework internals regardless of where the workspace is.
_FRAMEWORK_DIRS = re.compile(
r"(site-packages|dist-packages|/usr/lib/python|/importlib/|/unittest/|"
r"/_pytest/|/pluggy/)"
)
def _in_workspace(path: str, workspace: Optional[str]) -> bool:
p = path.replace("\\", "/")
if _FRAMEWORK_DIRS.search(p):
return False
if not (p.startswith("/") or re.match(r"^[A-Za-z]:", p)):
return True # relative paths are workspace-relative in a sandbox
if workspace:
w = workspace.replace("\\", "/").rstrip("/") + "/"
return p.startswith(w)
return True # absolute, workspace unknown: keep rather than guess
# -- gtest -----------------------------------------------------------------
_GTEST_RUN = re.compile(r"^\[ RUN \] (\S+)")
_GTEST_FAILED = re.compile(r"^\[ FAILED \] (\S+)")
_GTEST_OK = re.compile(r"^\[ OK \] ")
_GTEST_SUMMARY = re.compile(r"^\[==========\] .*ran\.")
def _detect_gtest(text: str) -> bool:
return "[ RUN ]" in text
def _extract_gtest(text: str, workspace: Optional[str]) -> Optional[str]:
"""Block from [ RUN ] of a failing case to its [ FAILED ], plus the
trailing summary list."""
lines = text.splitlines()
out: list[str] = []
block: list[str] = []
in_block = False
summary_at = None
for i, ln in enumerate(lines):
if _GTEST_SUMMARY.match(ln):
summary_at = i
if _GTEST_RUN.match(ln):
block, in_block = [ln], True
continue
if in_block:
block.append(ln)
if _GTEST_FAILED.match(ln):
out.extend(block)
out.append("")
in_block = False
elif _GTEST_OK.match(ln):
in_block = False
if summary_at is not None:
out.extend(lines[summary_at:])
return "\n".join(out).strip("\n") if out else None
# -- go test ---------------------------------------------------------------
def _detect_go(text: str) -> bool:
return ("\n--- FAIL: " in text or text.startswith("--- FAIL: ")
or "\npanic: " in text or text.startswith("panic: "))
def _extract_go(text: str, workspace: Optional[str]) -> Optional[str]:
"""--- FAIL: block with its indented output; for panics the message and
the first ~5 frames; plus the trailing FAIL lines."""
lines = text.splitlines()
out: list[str] = []
i, n = 0, len(lines)
while i < n:
ln = lines[i]
if ln.startswith("--- FAIL: "):
out.append(ln)
i += 1
while i < n and lines[i].startswith((" ", "\t")):
out.append(lines[i])
i += 1
out.append("")
continue
if ln.startswith("panic: "):
out.append(ln)
i += 1
while i < n and not lines[i].startswith("goroutine "):
if lines[i].strip():
out.append(lines[i])
i += 1
if i < n:
out.append(lines[i]) # goroutine header
i += 1
frames = 0
while i < n and frames < 5 and lines[i].strip():
out.append(lines[i])
if lines[i].startswith("\t"):
frames += 1 # each frame is a func line + a \tfile:line
i += 1
out.append("")
continue
if ln.startswith("FAIL"):
out.append(ln)
i += 1
return "\n".join(out).strip("\n") if out else None
# -- pytest ----------------------------------------------------------------
_PYTEST_FAILURES = re.compile(r"^=+ FAILURES =+$")
_PYTEST_SECTION = re.compile(r"^=+ .* =+$")
_PYTEST_CASE = re.compile(r"^_+ .+ _+$")
_PYTEST_SUMMARY = re.compile(r"^=+ short test summary info =+$")
_PYTEST_LOC = re.compile(r"^\S.*:\d+: \w+")
def _detect_pytest(text: str) -> bool:
return any(_PYTEST_FAILURES.match(l) for l in text.splitlines())
def _extract_pytest(text: str, workspace: Optional[str]) -> Optional[str]:
"""The FAILURES section, each case cut at its first assertion block,
plus short test summary info."""
lines = text.splitlines()
start = next((i for i, ln in enumerate(lines) if _PYTEST_FAILURES.match(ln)), None)
if start is None:
return None
end = next((i for i in range(start + 1, len(lines))
if _PYTEST_SECTION.match(lines[i])), len(lines))
out = [lines[start]]
case: list[str] = []
def flush() -> None:
if not case:
return
out.append(case[0])
seen_assert = False
for k in range(1, len(case)):
ln = case[k]
if ln.startswith("E "):
seen_assert = True
out.append(ln)
elif seen_assert:
# assertion block over: keep the file:line marker, drop the rest
# (captured stdout/stderr is what bloats these logs)
loc = next((l for l in case[k:] if _PYTEST_LOC.match(l)), None)
if loc:
out.append(loc)
break
else:
out.append(ln)
out.append("")
for i in range(start + 1, end):
if _PYTEST_CASE.match(lines[i]):
flush()
case = [lines[i]]
elif case:
case.append(lines[i])
flush()
si = next((i for i in range(end, len(lines)) if _PYTEST_SUMMARY.match(lines[i])), None)
if si is not None:
out.extend(lines[si:])
return "\n".join(out).strip("\n") if len(out) > 1 else None
# -- python traceback (unittest et al.) ------------------------------------
_PY_TB = "Traceback (most recent call last):"
_PY_FRAME = re.compile(r'^\s+File "(?P<path>[^"]+)", line \d+')
_PYTB_KEEP = re.compile(r"^(FAIL: |ERROR: |FAILED|OK\b|Ran \d+ tests?)")
def _detect_pytb(text: str) -> bool:
return _PY_TB in text
def _extract_pytb(text: str, workspace: Optional[str]) -> Optional[str]:
"""Tracebacks with out-of-workspace frames collapsed, plus the FAIL/ERROR
headers and the runner's verdict lines."""
lines = text.splitlines()
out: list[str] = []
i, n = 0, len(lines)
while i < n:
ln = lines[i]
if _PY_TB in ln:
out.append(ln)
i += 1
dropped = 0
while i < n:
m = _PY_FRAME.match(lines[i])
if m:
frame = [lines[i]]
if i + 1 < n and lines[i + 1].startswith((" ", "\t")) \
and not _PY_FRAME.match(lines[i + 1]):
frame.append(lines[i + 1])
i += 1
i += 1
if _in_workspace(m.group("path"), workspace):
if dropped:
out.append(f" [... {dropped} frames outside workspace ...]")
dropped = 0
out.extend(frame)
else:
dropped += 1
continue
if dropped:
out.append(f" [... {dropped} frames outside workspace ...]")
dropped = 0
out.append(lines[i])
i += 1
if not lines[i - 1].startswith((" ", "\t")):
break # unindented line = the exception itself; traceback over
out.append("")
continue
if _PYTB_KEEP.match(ln):
out.append(ln)
i += 1
return "\n".join(out).strip("\n") if out else None
# -- JUnit / java stack traces ---------------------------------------------
_JAVA_FRAME = re.compile(r"^\s+at (?:app//|platform//)?(?P<cls>[\w.$/]+)\(")
_JAVA_FRAMEWORK = re.compile(
r"^(org\.junit|junit\.|org\.testng|org\.hamcrest|jdk\.|java\.|javax\.|"
r"sun\.|com\.sun\.|org\.gradle|com\.google\.testing|org\.apache\.maven)"
)
_PROGRESS_DOTS = re.compile(r"^[.EF]+$")
def _detect_junit(text: str) -> bool:
return ".java:" in text and re.search(r"^\s+at [\w.$/]+\(", text, re.M) is not None
def _extract_junit(text: str, workspace: Optional[str]) -> Optional[str]:
"""Keep the log but collapse runs of framework stack frames."""
out: list[str] = []
dropped = 0
changed = False
def flush() -> None:
nonlocal dropped
if dropped:
out.append(f"\tat [... {dropped} framework frames ...]")
dropped = 0
for ln in text.splitlines():
m = _JAVA_FRAME.match(ln)
if m:
cls = m.group("cls").split("/")[-1] # strip java.base/ and app// prefixes
if _JAVA_FRAMEWORK.match(cls):
dropped += 1
changed = True
continue
flush()
out.append(ln)
continue
flush()
if ln.startswith("exec ${PAGER") or re.match(r"^-{40,}$", ln) \
or _PROGRESS_DOTS.match(ln.strip() or "x"):
changed = True
continue
out.append(ln)
flush()
if not changed:
return None
return "\n".join(out).strip("\n")
# -- registry --------------------------------------------------------------
_EXTRACTORS = [
("gtest", _detect_gtest, _extract_gtest),
("go", _detect_go, _extract_go),
("pytest", _detect_pytest, _extract_pytest),
("python", _detect_pytb, _extract_pytb),
("junit", _detect_junit, _extract_junit),
]
def truncate_test_log(text: str, workspace: Optional[str] = None
) -> Optional[tuple[str, int, str]]:
"""Distill a test.log with the first matching framework extractor.
Returns (kept_text, kept_lines, framework) or None when no framework
matched -- the caller then falls back to the plain tail.
"""
if not text:
return None
for name, detect, extract in _EXTRACTORS:
try:
if not detect(text):
continue
kept = extract(text, workspace)
except Exception:
return None # an extractor bug must never lose the log
if kept and kept.strip():
return kept, len(kept.splitlines()), name
return None
# --------------------------------------------------------------------------
# container assembly
# --------------------------------------------------------------------------
@dataclass
class Evidence:
store: dict[str, dict[str, Any]] = field(default_factory=dict)
_by_hash: dict[str, str] = field(default_factory=dict)
def add(self, kind: str, text: str, framework: Optional[str] = None,
total_lines: Optional[int] = None) -> Optional[str]:
if not text.strip():
return None
if kind in ("command_line", "failure_message"):
# Flags, cwd, and environment can occur anywhere in a failed
# action's command. Keep these complete for on-demand retrieval.
body, truncated = text, False
elif kind == "invocation_log":
lines = invocation_error_context(text).splitlines()
if len(lines) > MAX_EVIDENCE_LINES:
lines = (lines[:MAX_EVIDENCE_LINES // 2] +
["[... invocation output omitted ...]"] +
lines[-MAX_EVIDENCE_LINES // 2:])
body = bounded_log("\n".join(lines), MAX_EVIDENCE_BYTES)
truncated = body != text
elif framework:
# already distilled by a framework extractor: generous cap only
body, truncated = tail(text, MAX_EXTRACTED_LINES, MAX_EXTRACTED_BYTES)
else:
body, truncated = tail(text)
# Different logs can have identical tails. Never dedupe on the excerpt.
h = hashlib.sha256((kind + "\0" + text).encode()).hexdigest()
if h in self._by_hash:
return self._by_hash[h]
ref = f"e{len(self.store) + 1}"
self._by_hash[h] = ref
entry: dict[str, Any] = {"kind": kind, "truncated": truncated, "text": body}
if framework:
entry["framework"] = framework
entry["distilled"] = True
entry["kept_lines"] = len(body.splitlines())
if total_lines is not None:
entry["total_lines"] = total_lines
entry["truncated"] |= entry["kept_lines"] < total_lines
self.store[ref] = entry
return ref
@dataclass
class StreamStatus:
"""Transport integrity, separate from Bazel's build/test outcome."""
events_read: int = 0
malformed_records: int = 0
skipped_events: int = 0
trailing_fragment: bool = False
finished: bool = False
last_message: bool = False
_seen: set[str] = field(default_factory=set)
_pending: set[str] = field(default_factory=set)
def observe(self, event: dict[str, Any]) -> None:
eid = event.get("id")
if isinstance(eid, dict) and eid:
key = json.dumps(eid, sort_keys=True, separators=(",", ":"))
self._seen.add(key)
self._pending.discard(key)
for child in event.get("children", []):
key = json.dumps(child, sort_keys=True, separators=(",", ":"))
if key not in self._seen:
self._pending.add(key)
def as_dict(self) -> dict[str, Any]:
damaged = self.malformed_records or self.skipped_events or self.trailing_fragment
status = ('degraded' if damaged else 'unavailable' if not self.events_read else
'complete' if self.finished and self.last_message and not self._pending else 'incomplete')
return {"status": status, "events_read": self.events_read,
"build_finished": self.finished, "last_message": self.last_message,
**({"malformed_records": self.malformed_records} if self.malformed_records else {}),
**({"skipped_events": self.skipped_events} if self.skipped_events else {}),
**({"unfulfilled_events": len(self._pending)} if self._pending else {}),
**({"trailing_fragment": True} if self.trailing_fragment else {})}
class Container:
def __init__(self, root: Optional[str] = None, audit_tests: bool = False,
bundle: Optional[InvocationBundle] = None):
self.root = root
self.bundle = bundle
self.ev = Evidence()
self.invocation: dict[str, Any] = {}
self.counts = {
"actions_failed": 0,
"targets_failed": 0,
}
self._diags: dict[str, dict[str, Any]] = {} # fingerprint -> diagnostic
self._order: list[str] = []
self._abort_events: dict[str, str] = {}
self._abort_children: dict[str, list[str]] = {}
self._progress_stderr = ""
self.console_output = ""
self._tests: dict[str, dict[str, Any]] = {}
self.audit_tests = audit_tests
self._audit_candidates: dict[str, dict[str, Any]] = {}
self._audit_completions: dict[str, bool] = {}
self._audit_aborts: dict[str, str] = {}
self.stream = StreamStatus()
def consume(self, ev: dict[str, Any]) -> None:
"""Keep a bad event from hiding the rest of the stream, and disclose it."""
try:
self.stream.observe(ev)
if self.bundle:
try:
ev = self.bundle.capture_event(ev, self.root)
except (OSError, ValueError, TypeError, AttributeError, KeyError) as exc:
# Optional archival must not hide a usable event from the report.
self.bundle.manifest["errors"].append(f"event capture: {exc}")
self.handle(ev)
except Exception as exc:
self.stream.skipped_events += 1
if self.stream.skipped_events <= 3:
print(f"bzlog: skipped event: {exc}", file=sys.stderr)
else:
self.stream.finished |= "finished" in ev
self.stream.last_message |= ev.get("lastMessage") is True
@staticmethod
def event_key(eid: dict[str, Any]) -> str:
return json.dumps(eid, sort_keys=True, separators=(",", ":"))
def _resolved_diagnostics(self) -> list[dict[str, Any]]:
"""Link empty analysis parents to descriptive causes, in either event order."""
diags = {fp: dict(d, _targets=list(d["_targets"]))
for fp, d in self._diags.items() if d["kind"] != "test_failure"}
dropped = set()
for event, fp in self._abort_events.items():
if diags[fp].get("description"):
continue
pending = list(self._abort_children.get(event, []))
visited = {event}
causes = set()
while pending:
child = pending.pop()
if child in visited:
continue
visited.add(child)
child_fp = self._abort_events.get(child)
if child_fp and diags[child_fp].get("description"):
causes.add(child_fp)
else:
pending.extend(self._abort_children.get(child, []))
if causes:
dropped.add(fp)
for cause in causes:
for target in diags[fp]["_targets"]:
if target not in diags[cause]["_targets"]:
diags[cause]["_targets"].append(target)
return ([diags[fp] for fp in self._order if fp in diags and fp not in dropped]
+ self._test_diagnostics())
def _test_record(self, tid: dict[str, Any]) -> dict[str, Any]:
identity = {"label": tid.get("label"), "configuration": tid.get("configuration")}
return self._tests.setdefault(self.event_key(identity), dict(identity, results={}))
def _test_diagnostics(self) -> list[dict[str, Any]]:
"""Reconcile attempts with each configured test's authoritative summary."""
grouped: dict[str, dict[str, Any]] = {}
for test in self._tests.values():
summary = test.get("summary", test.get("target_summary"))
status = summary.get("overallStatus", "NO_STATUS") if summary is not None else "UNKNOWN"
failures = [result for _, result in sorted(test["results"].items())
if result["status"] != "PASSED"]
if status == "PASSED" and not failures:
continue
kind = {"PASSED": "test_recovered", "FLAKY": "test_flaky"}.get(status)
if kind is None:
kind = "test_failure" if status in FAILED_TEST_STATUSES else (
"test_attempt_failure" if failures else "test_incomplete")
if not failures:
diagnostic = {
"kind": kind, "status": status, "overall_status": status,
"final": summary is not None, "configuration": test["configuration"],
"description": (f"Test summary: {status}; per-attempt diagnostics unavailable."
if summary is not None else
"Test results observed, but the final summary is unavailable."),
"_targets": [test["label"]] if test["label"] else [],
}
if test.get("summary_evidence"):
diagnostic["evidence"] = test["summary_evidence"]
grouped["summary:" + self.event_key({"label": test["label"],
"configuration": test["configuration"]})] = diagnostic
continue
for result in failures:
d = dict(result, kind=kind, overall_status=status, final=summary is not None)
# Equal messages without logs do not establish equivalent failures.
if d.get("evidence"):
key = self.event_key({"kind": kind, "overall_status": status,
"status": d["status"], "configuration": d["configuration"],
"evidence": d["evidence"], "cases": d.get("cases")})
else:
key = self.event_key({"label": test["label"], "configuration": test["configuration"],
"run": d["run"], "shard": d["shard"], "attempt": d["attempt"]})
if key not in grouped:
grouped[key] = dict(d, _targets=[], occurrences=0, attempts=[])
group = grouped[key]
label = test["label"]
if label and label not in group["_targets"]:
group["_targets"].append(label)
group["occurrences"] += 1
if len(group["attempts"]) < MAX_TEST_ATTEMPTS:
group["attempts"].append({"target": label, **{
field: d[field] for field in
("run", "shard", "attempt", "status", "cached_locally", "cached_remotely")
}})
else:
group["attempts_omitted"] = group["occurrences"] - MAX_TEST_ATTEMPTS
return list(grouped.values())
def _test_counts(self) -> dict[str, int]:
counts = {"tests_total": len(self._tests), "tests_passed": 0, "tests_flaky": 0,
"tests_failed": 0, "tests_incomplete": 0}
for test in self._tests.values():
status = test.get("summary", test.get("target_summary", {})).get("overallStatus", "NO_STATUS")
if status == "PASSED":
counts["tests_passed"] += 1
elif status == "FLAKY":
counts["tests_flaky"] += 1
elif status in FAILED_TEST_STATUSES:
counts["tests_failed"] += 1
else:
counts["tests_incomplete"] += 1
return counts
def _test_audit(self) -> dict[str, Any]:
"""Account for observed configured tests without treating a pass as execution."""
rows = []
counts = dict.fromkeys(("executed", "cached", "mixed", "not_run", "unknown"), 0)
tests = {**self._audit_candidates, **self._tests}
for key, test in sorted(tests.items()):
summary = test.get("summary", test.get("target_summary"))
status = summary.get("overallStatus", "NO_STATUS") if summary is not None else "UNKNOWN"
source = ("test_summary" if "summary" in test else
"target_summary" if summary is not None else "unavailable")
results = list(test.get("results", {}).values())
attempts = {"observed": len(results), "executed": 0, "cached": 0,
"cached_locally": 0, "cached_remotely": 0, "unknown": 0}
for result in results:
local, remote = result["cached_locally"], result["cached_remotely"]
attempts["cached_locally"] += bool(local)
attempts["cached_remotely"] += bool(remote)
if local or remote:
attempts["cached"] += 1
elif result["status"] in {"PASSED", "FAILED", "TIMEOUT", "FLAKY"}:
attempts["executed"] += 1
else:
attempts["unknown"] += 1
reason = self._audit_aborts.get(key)
if summary is None and not results:
if reason in {"SKIPPED", "NO_BUILD", "NO_ANALYZE"}:
status, source = reason, "aborted"
elif self._audit_completions.get(key) is False:
status, source = "FAILED_TO_BUILD", "target_completed"
issues = []
totals = {}
if "summary" in test:
# Defaults apply inside an existing TestSummary message only.
try:
total = int(summary.get("totalRunCount", 0))
cached = int(summary.get("totalNumCached", 0))
except (ValueError, TypeError, OverflowError):
total = cached = None
totals = {"attempts": total, "cached": cached}
if total is None or total < 0 or not 0 <= cached <= total:
issues.append("invalid_summary_counts")
if total != len(results):
issues.append("attempt_count_mismatch")
if len(results) == total and cached != attempts["cached"]:
issues.append("cache_count_mismatch")
execution = "unknown"
if results and not attempts["unknown"] and not issues:
execution = ("mixed" if attempts["executed"] and attempts["cached"] else
"cached" if attempts["cached"] else "executed")
elif not results:
if ("invalid_summary_counts" not in issues and totals.get("attempts", 0) > 0
and totals["cached"] == totals["attempts"]):
execution = "cached"
elif status in {"FAILED_TO_BUILD", "TOOL_HALTED_BEFORE_TESTING",
"SKIPPED", "NO_BUILD", "NO_ANALYZE"} and not issues:
execution = "not_run"
counts[execution] += 1
row = {"label": test["label"], "configuration": test["configuration"],
"status": status, "final": source != "unavailable", "status_source": source,
"execution": execution, "attempts": attempts}
if totals:
row["summary_counts"] = totals
if reason:
row["abort_reason"] = reason
if issues:
row["issues"] = issues
rows.append(row)
notices = []
if not rows:
notices.append("No tests are visible in this stream.")
elif not any(row["attempts"]["executed"] for row in rows):
notices.append("No fresh test execution observed; missing evidence does not prove nothing ran.")
return {"scope": "Tests identified in this BEP; tests filtered out before emission are unknown.",
"counts": {"total": len(rows), **counts}, "tests": rows, "notices": notices}
# -- fingerprinting is what collapses the fan-out ----------------------
@staticmethod
def fingerprint(kind: str, action_type: str, errors: list[dict], evidence_ref) -> str:
if errors:
key = "|".join(
f"{e.get('file','')}:{e.get('line','')}:{e.get('message','')}" for e in errors
)
else:
key = f"{evidence_ref}"
return hashlib.sha256(f"{kind}/{action_type}/{key}".encode()).hexdigest()[:12]
def add_diag(self, diag: dict[str, Any], target: Optional[str],
event_id: Optional[dict[str, Any]] = None) -> str:
if diag.get("kind") in ("analysis_error", "aborted", "test_failure") or not (
diag.get("errors") or diag.get("evidence")):
# Aborts are joined through BEP edges. Missing evidence proves no
# equivalence, even if both failures have the same action mnemonic.
fp = ("event:" + self.event_key(event_id) if event_id
else f"unknown:{len(self._order)}")
else:
fp = self.fingerprint(
diag["kind"], diag.get("action_type", ""),
diag.get("errors", []), diag.get("evidence")
) + self.event_key({"configuration": diag.get("configuration"),
"status": diag.get("status"),
"failure_category": diag.get("failure_category"),
"failure_code": diag.get("failure_code"),
"command_evidence": diag.get("command_evidence"),
"failure_message_evidence": diag.get("failure_message_evidence"),
"primary_output": diag.get("primary_output"),
"cases": diag.get("cases")})
existing = self._diags.get(fp)
if existing:
if target and target not in existing["_targets"]:
existing["_targets"].append(target)
return fp
diag["_targets"] = [target] if target else []
self._diags[fp] = diag
self._order.append(fp)
return fp
# -- event handlers ---------------------------------------------------
def handle(self, ev: dict[str, Any]) -> None:
eid = ev.get("id", {})
if self.audit_tests:
if ev.get("configured", {}).get("testSize") in {"SMALL", "MEDIUM", "LARGE", "ENORMOUS"}:
for child in ev.get("children", []):
tid = child.get("targetCompleted", {})
if tid.get("label") and not tid.get("aspect"):
identity = {"label": tid["label"], "configuration": tid.get("configuration")}
self._audit_candidates[self.event_key(identity)] = identity
tid = eid.get("targetCompleted", {})
if tid.get("label") and not tid.get("aspect"):
key = self.event_key({"label": tid["label"], "configuration": tid.get("configuration")})
if "completed" in ev:
self._audit_completions[key] = ev["completed"].get("success", False)
if "aborted" in ev:
self._audit_aborts[key] = ev["aborted"].get("reason", "UNKNOWN")
if (ev.get("structuredCommandLine", {}).get("commandLineLabel") == "original"
and "replay" in self.invocation):
replay = self.invocation["replay"]
try:
replay["layout"] = command_layout(replay["argv"], ev["structuredCommandLine"])
except ValueError as exc:
replay["rerun_error"] = str(exc)
if "pattern" in eid:
self.invocation["patterns"] = eid["pattern"].get("pattern", [])
if "progress" in ev:
self._progress_stderr = bounded_log(
self._progress_stderr + ev["progress"].get("stderr", ""))
if "started" in ev:
s = ev["started"]
self.invocation.update({
"uuid": s.get("uuid"),
"command": s.get("command"),
"bazel_version": s.get("buildToolVersion"),
"workspace": s.get("workspaceDirectory"),
})
if self.root is None:
self.root = s.get("workspaceDirectory")
elif "action" in ev:
a = ev["action"]
if a.get("success"):
return
self.counts["actions_failed"] += 1
label = eid.get("actionCompleted", {}).get("label") or a.get("label")
stderr = read_file_message(a.get("stderr", {}), self.root)
errors = parse_diagnostics(stderr)
atype = a.get("type", "")
kind = "compile_error" if errors and "Compile" in atype else "action_failure"
ref = self.ev.add("stderr", stderr)
diag: dict[str, Any] = {
"kind": kind,
"action_type": atype,
"exit_code": a.get("exitCode"),
"errors": errors,
"configuration": eid.get("actionCompleted", {}).get("configuration"),
}
fd = a.get("failureDetail")
if fd:
cat = next((k for k in fd if k != "message"), None)
diag["failure_category"] = cat
diag["failure_code"] = (fd.get(cat) or {}).get("code")
if fd.get("message"):
diag["failure_message"] = fd["message"][:300]
diag["failure_message_evidence"] = self.ev.add("failure_message", fd["message"])
argv = a.get("commandLine")
if isinstance(argv, list) and argv and all(isinstance(arg, str) for arg in argv):
diag["command_evidence"] = self.ev.add("command_line", json.dumps(argv, ensure_ascii=False))
primary_output = (a.get("primaryOutput", {}).get("name") or
eid.get("actionCompleted", {}).get("primaryOutput"))
if primary_output:
diag["primary_output"] = primary_output
if ref:
diag["evidence"] = ref
self.add_diag(diag, label, eid)
elif "testResult" in ev:
r = ev["testResult"]
status = r.get("status", "NO_STATUS")
tid = eid.get("testResult", {})
label = tid.get("label")
test = self._test_record(tid)
attempt_id = (int(tid.get("run", 1)), int(tid.get("shard", 1)),
int(tid.get("attempt", 1)))
if attempt_id in test["results"]:
return
ei = r.get("executionInfo", {})
diag = {
"kind": "test_failure", "status": status,
"run": attempt_id[0], "shard": attempt_id[1], "attempt": attempt_id[2],
"configuration": tid.get("configuration"),
"cached_locally": r.get("cachedLocally", False),
"cached_remotely": ei.get("cachedRemotely", False),
}