Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,15 @@ text is grouped as `other (text omitted)` and never copied; raw snippets stay in
`aliased` or `not aliased` field. Those lines are not counted as unhandled; they are counted by
outcome (`aliased`, `not_aliased`, `failed`) in a separate table, and a line with an HRESULT other than 0
(or an uncommitted address) still counts as `failed` and as an unhandled `Device::slot133` event.

The `Run End-Point` section says how far a run got and how it ended, so that reports of runs with different
memory caps can be told apart. It gives the largest `commit peak=` value of the `x2w-dstorage heartbeat` lines (not
the last one), the highest heartbeat second, the counts of the last `failed requests by cause` heartbeat line (the
eight fixed cause names, each with its decimal count, and the second of that line), and the first and last stop event of
`events.txt` as a 32-bit exception code with `first` or `second` chance. Exceptions that `debug_launch.py` steps over
(the loader and assertion breakpoints, single step, thread names, debug prints) are not stop events. A value the log
does not carry is reported as `not reported`. Nothing else of those lines is copied: no module name, path, address or
exception parameter.
Check with `python3 -B tests/startup_triage_run_check.py` (ctest
`startup_triage_run`).

Expand Down
152 changes: 152 additions & 0 deletions tests/startup_triage_run_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,157 @@ def check_cli_invocation(failures: list[str]) -> None:
failures.append(f"CLI output missing expected row: {proc.stdout!r}")


HEARTBEAT_FAILURES = (
"x2w-dstorage heartbeat {second} s: failed requests by cause read-at-or-past-eof={a} read-crossing-eof=0 "
"read-other={b} destination-capacity=3 destination-not-writable=0 zlib=11 bcpack=0 other=1\n"
)
HEARTBEAT_COMMIT = (
"x2w-dstorage heartbeat {second} s: requests done=10, commit peak={peak} MiB current={current} MiB, "
"live physical-page sections=4\n"
)
ENDPOINT_EVENTS = """\
0.120 module load C:\\Users\\alice\\secret\\game.exe base=0x00007ff700000000
1.500 exception 0x80000003 breakpoint at ntdll.dll+0x1234 first-chance params=[]
2.000 exception 0x406d1388 thread name at game.exe+0x10 first-chance params=['0x1']
250.250 exception 0xE06D7363 C++ exception at C:\\Users\\alice\\secret\\game.exe+0x55 first-chance params=['0x19930520', '0x00007ff7deadbeef']
299.900 exception 0xC0000005 access violation at KERNELBASE.dll+0x9000 second-chance params=['0x0', '0x00007ff7cafebabe']
"""
ENDPOINT_FORBIDDEN = [
"alice", "secret", "game.exe", "KERNELBASE", "ntdll", "deadbeef", "cafebabe", "0x19930520", "00007ff", "params",
]


def _endpoint_report(logs: dict[str, str]) -> str:
with tempfile.TemporaryDirectory() as tmp:
logdir = Path(tmp)
for name, text in logs.items():
(logdir / name).write_text(text, encoding="utf-8")
return triage_run.triage_run(logdir)


def _check_endpoint_complete(failures: list[str]) -> None:
report = _endpoint_report(
{
"stderr.txt": HEARTBEAT_COMMIT.format(second=20, peak=900, current=800)
+ HEARTBEAT_FAILURES.format(second=20, a=1, b=2)
+ HEARTBEAT_COMMIT.format(second=290, peak=16208, current=15000)
+ HEARTBEAT_COMMIT.format(second=299, peak=14000, current=13000) # a lower peak after a higher one
+ HEARTBEAT_FAILURES.format(second=299, a=7, b=9),
"events.txt": ENDPOINT_EVENTS,
}
)
for want in [
"### Run End-Point",
"| Peak commit (maximum of the `commit peak=` values) | `16208` MiB |",
"| Last heartbeat | `299` s |",
"| First stop event | `0xe06d7363` (first-chance) |",
"| Last stop event | `0xc0000005` (second-chance) |",
"| Stop events | `2` |",
"at heartbeat second `299`",
"| read-at-or-past-eof | 7 |",
"| read-other | 9 |",
"| destination-capacity | 3 |",
"| zlib | 11 |",
]:
if want not in report:
failures.append(f"run end-point: missing {want!r}\n{report}")
for secret in ENDPOINT_FORBIDDEN:
if secret in report:
failures.append(f"run end-point leaked {secret!r}")
for stepped_over in ("0x80000003", "0x406d1388"):
if stepped_over in report.lower():
failures.append(f"run end-point reported a stepped-over exception {stepped_over}")


def _check_endpoint_without_commit(failures: list[str]) -> None:
report = _endpoint_report({"stderr.txt": HEARTBEAT_FAILURES.format(second=40, a=0, b=0)})
for want in [
"| Peak commit (maximum of the `commit peak=` values) | not reported |",
"| Last heartbeat | `40` s |",
"| First stop event | not reported |",
"| Stop events | `0` |",
"at heartbeat second `40`",
]:
if want not in report:
failures.append(f"run end-point without commit line: missing {want!r}")
report = _endpoint_report({"stderr.txt": "x2w-dstorage heartbeat 12 s: requests done=1, commit unknown, live physical-page sections=unknown\n"})
if "| Peak commit (maximum of the `commit peak=` values) | not reported |" not in report or "| Last heartbeat | `12` s |" not in report:
failures.append("run end-point: a 'commit unknown' heartbeat was not handled")
if "_No failed-requests-by-cause heartbeat line._" not in report:
failures.append("run end-point: missing the note for a run with no cause line")
report = _endpoint_report({})
if "| Last heartbeat | not reported |" not in report:
failures.append("run end-point: an empty run must report no heartbeat")


def _check_endpoint_second_stop(failures: list[str]) -> None:
events = (
" 10.000 exception 0xC0000005 access violation at a.dll+0x1 first-chance params=[]\n"
" 11.000 exception 0xC0000005 access violation at a.dll+0x1 second-chance params=[]\n"
)
report = _endpoint_report({"events.txt": events})
for want in [
"| First stop event | `0xc0000005` (first-chance) |",
"| Last stop event | `0xc0000005` (second-chance) |",
"| Stop events | `2` |",
]:
if want not in report:
failures.append(f"run end-point with a second stop: missing {want!r}")


def _check_endpoint_private_lines(failures: list[str]) -> None:
hostile = (
" 5.000 exception 0xE06D7363deadbeef C++ exception at X first-chance params=[]\n" # not a 32-bit code
" 6.000 exception 0xZZ00ZZ00 junk at Y second-chance\n"
" 7.000 exception 0xC0000005 at C:\\Users\\alice\\x.dll+0x1 [secret](https://acme.example/leak) second-chance\n"
"x2w-dstorage heartbeat 30 s: failed requests by cause read-other=5 acme_widget=99 zlib=0x7ff7deadbeef other=2\n"
"x2w-dstorage heartbeat 31 s: requests done=1, commit peak=0x00007ff7deadbeef MiB current=1 MiB, live physical-page sections=1\n"
)
report = _endpoint_report({"events.txt": hostile})
for needle in ["alice", "secret", "acme", "widget", "deadbeef", "leak", "http", "99 |"]:
if needle in report:
failures.append(f"run end-point copied hostile text {needle!r}\n{report}")
if "| Stop events | `1` |" not in report or "`0xc0000005` (second-chance)" not in report:
failures.append("run end-point: only the well-formed 32-bit code should be reported")
if "| Peak commit (maximum of the `commit peak=` values) | not reported |" not in report:
failures.append("run end-point: a non-decimal peak must not be reported")


def _endpoint_failures() -> list[str]:
failures: list[str] = []
for check in (
_check_endpoint_complete,
_check_endpoint_without_commit,
_check_endpoint_second_stop,
_check_endpoint_private_lines,
):
check(failures)
return failures


def check_run_endpoint(failures: list[str]) -> None:
failures.extend(_endpoint_failures())
# Mutations: each wrong behaviour must make the end-point checks fail.
mutations = {
"peak taken from the last line instead of the maximum": ("_keep_peak", lambda old, new: new),
"an earlier cause line replaces a later one": ("_is_later_sample", lambda old, new: old is None),
"the exception code is not limited to 32 bits": (
"RE_STOP_EVENT",
re.compile(r"^\s*\d+\.\d+\s+exception\s+(0x[0-9a-fA-F]+)\b.*?\b(first|second)-chance\b"),
),
"every exception is a stop, including stepped-over ones": ("NON_STOP_EXCEPTIONS", set()),
}
for label, (name, replacement) in mutations.items():
original = getattr(triage_run, name)
setattr(triage_run, name, replacement)
try:
caught = bool(_endpoint_failures())
finally:
setattr(triage_run, name, original)
if not caught:
failures.append(f"mutation not caught by the run end-point checks: {label}")


def main() -> int:
failures: list[str] = []
check_aggregation_and_redaction(failures)
Expand All @@ -295,6 +446,7 @@ def main() -> int:
check_empty_and_missing_dirs(failures)
check_cli_invocation(failures)
check_slot133_outcomes(failures)
check_run_endpoint(failures)
for item in failures:
print("FAIL", item)
print(f"startup triage_run checks: {len(failures)} failed")
Expand Down
116 changes: 112 additions & 4 deletions tools/startup/triage_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@

import argparse
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path
import re
import sys
from typing import Iterable
from typing import Any, Iterable


LOG_EXTENSIONS = {".txt", ".log", ".out"}
Expand Down Expand Up @@ -82,6 +83,75 @@
]


# Run end-point: how far a run got and how it ended. Only decimal counts, the fixed failure-cause names of the
# DirectStorage heartbeat and the 32-bit exception code with its chance are copied; the rest of those lines (module
# names, paths, addresses, exception parameters) is dropped.
FAILURE_CAUSES = (
"read-at-or-past-eof",
"read-crossing-eof",
"read-other",
"destination-capacity",
"destination-not-writable",
"zlib",
"bcpack",
"other",
)
# Codes debug_launch.py logs as exceptions but steps over (loader breakpoint, assertion continuation, single step,
# thread names, debug prints); they are not run stops.
NON_STOP_EXCEPTIONS = {"0x80000003", "0x80000004", "0x406d1388", "0x40010006"}
RE_HEARTBEAT_SECOND = re.compile(r"x2w-dstorage heartbeat (\d{1,10}) s:")
RE_COMMIT_PEAK = re.compile(r"x2w-dstorage heartbeat \d{1,10} s: .*?\bcommit peak=(\d{1,10}) MiB\b")
RE_FAILURE_CAUSES = re.compile(r"x2w-dstorage heartbeat (\d{1,10}) s: failed requests by cause ((?:[a-z-]+=\d{1,10}(?:\s+|$))+)")
RE_CAUSE_COUNT = re.compile(r"([a-z-]+)=(\d{1,10})")
# debug_launch.py events.txt: "<seconds> exception <code> <name> at <where> first|second-chance params=[...]".
RE_STOP_EVENT = re.compile(r"^\s*\d+\.\d+\s+exception\s+(0x[0-9a-fA-F]{8})\b.*?\b(first|second)-chance\b")


def _keep_peak(old: int | None, new: int) -> int:
return new if old is None else max(old, new)


def _is_later_sample(old_second: int | None, new_second: int) -> bool:
return old_second is None or new_second >= old_second


@dataclass
class RunEndpoint:
"""Where a run got to, built only from allowlisted values."""

peak_commit_mib: int | None = None
last_heartbeat_s: int | None = None
failure_second: int | None = None
failure_counts: dict[str, int] = field(default_factory=dict)
first_stop: tuple[str, str] | None = None
last_stop: tuple[str, str] | None = None
stop_events: int = 0

def observe(self, line: str) -> None:
m = RE_HEARTBEAT_SECOND.search(line)
if m:
second = int(m.group(1))
if self.last_heartbeat_s is None or second > self.last_heartbeat_s:
self.last_heartbeat_s = second
peak = RE_COMMIT_PEAK.search(line)
if peak:
self.peak_commit_mib = _keep_peak(self.peak_commit_mib, int(peak.group(1)))
causes = RE_FAILURE_CAUSES.search(line)
if causes and _is_later_sample(self.failure_second, int(causes.group(1))):
self.failure_second = int(causes.group(1))
self.failure_counts = {
name: int(count) for name, count in RE_CAUSE_COUNT.findall(causes.group(2)) if name in FAILURE_CAUSES
}
return
m = RE_STOP_EVENT.match(line)
if m and m.group(1).lower() not in NON_STOP_EXCEPTIONS:
stop = (m.group(1).lower(), m.group(2))
self.stop_events += 1
if self.first_stop is None:
self.first_stop = stop
self.last_stop = stop


def _dec(text: str | None) -> str:
return text if text is not None and RE_DEC.match(text) else "?"

Expand Down Expand Up @@ -193,7 +263,7 @@ def iter_log_files(log_target: Path) -> list[Path]:
return files


def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]:
def summarize_lines(lines: Iterable[str]) -> dict[str, Any]:
"""Aggregate startup telemetry counters from an iterable of log lines."""
slot70_refusals: Counter[tuple[str, str, str, str, str, str, str]] = Counter()
d3d12_unhandled: Counter[str] = Counter()
Expand All @@ -202,11 +272,13 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]:
dstorage_failures: Counter[str] = Counter()
dstorage_hresults: Counter[str] = Counter()
runtime_failures: Counter[tuple[str, str]] = Counter()
endpoint = RunEndpoint()

for raw_line in lines:
line = raw_line.strip()
if not line:
continue
endpoint.observe(line) # reads only; the line is still classified below

# 1. slot70 memory SRV refusals
m = RE_SLOT70.search(line)
Expand Down Expand Up @@ -341,6 +413,7 @@ def summarize_lines(lines: Iterable[str]) -> dict[str, Counter]:
"dstorage_failures": dstorage_failures,
"dstorage_hresults": dstorage_hresults,
"runtime_failures": runtime_failures,
"endpoint": endpoint,
}


Expand Down Expand Up @@ -389,8 +462,40 @@ def _format_table(
return lines


def _stop_text(stop: tuple[str, str] | None) -> str:
return "not reported" if stop is None else f"`{stop[0]}` ({stop[1]}-chance)"


def format_endpoint(endpoint: RunEndpoint) -> list[str]:
"""Render the run end-point section."""
peak = "not reported" if endpoint.peak_commit_mib is None else f"`{endpoint.peak_commit_mib}` MiB"
beat = "not reported" if endpoint.last_heartbeat_s is None else f"`{endpoint.last_heartbeat_s}` s"
out = [
"### Run End-Point",
"",
"| Item | Value |",
"| --- | --- |",
f"| Peak commit (maximum of the `commit peak=` values) | {peak} |",
f"| Last heartbeat | {beat} |",
f"| First stop event | {_stop_text(endpoint.first_stop)} |",
f"| Last stop event | {_stop_text(endpoint.last_stop)} |",
f"| Stop events | `{endpoint.stop_events}` |",
"",
]
if endpoint.failure_second is None:
out.extend(["_No failed-requests-by-cause heartbeat line._", ""])
return out
out.extend([f"Failed requests by cause at heartbeat second `{endpoint.failure_second}`:", ""])
out.extend(["| Cause | Count |", "| --- | --- |"])
for cause in FAILURE_CAUSES:
count = endpoint.failure_counts.get(cause)
out.append(f"| {cause} | {'?' if count is None else count} |")
out.append("")
return out


def format_markdown(
summary: dict[str, Counter],
summary: dict[str, Any],
shader_failures: Counter[str],
files_scanned: int,
shader_cache_provided: bool,
Expand Down Expand Up @@ -512,7 +617,10 @@ def format_markdown(
)
)

# 6. X2W_SHADER_CACHE .fail reasons
# 6. Run end-point
out.extend(format_endpoint(summary["endpoint"]))

# 7. X2W_SHADER_CACHE .fail reasons
if shader_cache_provided:
out.extend(["### `X2W_SHADER_CACHE` `.fail` Reasons", ""])
sh_rows = [[count, f"`{reason}`"] for reason, count in shader_failures.most_common()]
Expand Down
Loading