CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 消除性能分析脚本的类型检查错误
Bob55227a0f0e85
diff --git a/Docs/DeveloperGuide/app-server.md b/Docs/DeveloperGuide/app-server.mdindex 7f68142..37ee9c5 100644--- a/Docs/DeveloperGuide/app-server.md+++ b/Docs/DeveloperGuide/app-server.md@@ -220,7 +220,7 @@ ready手动重连、切换来源和连接到期重建都先关闭旧连接;新连接失败时保持断开。来源选择只在手动重连成功后保存。自动刷新和手动重连的错误都会更新 `CodexStatusViewModel.connectionErrorMessage`,关于页面直接展示该状态。-### 错误分类矩阵+### 错误分类| 错误 | 当前请求 | 当前连接 | 整轮刷新 || --- | --- | --- | --- |diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.mdindex 39e011d..661801f 100644--- a/Docs/DeveloperGuide/notifications.md+++ b/Docs/DeveloperGuide/notifications.md@@ -269,7 +269,7 @@ App 是 `LSUIElement`,通知中心 delegate 明确允许 App 在前台时继- TUI 设置失败不影响 App 通知状态- UI 必须清楚区分两个开关的作用域-## 手动验证矩阵+## 手动验证- 首次开启总开关时正确请求系统权限- 系统拒绝权限时设置页展示可理解状态diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.mdindex 5deeeaf..24bdc19 100644--- a/Docs/DeveloperGuide/sleep-prevention.md+++ b/Docs/DeveloperGuide/sleep-prevention.md@@ -419,7 +419,7 @@ App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 C- 更新后旧 owned 状态能够安全恢复- 更新前自动重置唤醒计划已取消,新 helper 就绪后按当前目标重新登记-## 手动验证矩阵+## 手动验证- 运行任务开始和结束时,App assertion 与 CodexBarHelper 租约同步切换- 等待批准设置关闭和开启时,有效任务判断正确diff --git a/Docs/DeveloperGuide/sync.md b/Docs/DeveloperGuide/sync.mdindex 9c8b69f..83d9bb2 100644--- a/Docs/DeveloperGuide/sync.md+++ b/Docs/DeveloperGuide/sync.md@@ -291,7 +291,7 @@ CloudKit 记录保留期与本地 Hook 历史一致,最长 210 天:临时错误保留最后一份可用远端缓存。账户切换或身份失效时不能继续把旧账户缓存当作当前账户数据。-## 手动验证矩阵+## 手动验证- 首次启用后上传保留期内本机聚合- 第二台设备能够合并显示,不重复当前设备贡献diff --git a/Docs/DeveloperGuide/ui-and-lifecycle.md b/Docs/DeveloperGuide/ui-and-lifecycle.mdindex 87a8101..006851f 100644--- a/Docs/DeveloperGuide/ui-and-lifecycle.md+++ b/Docs/DeveloperGuide/ui-and-lifecycle.md@@ -298,7 +298,7 @@ app-server 状态默认每 60 秒检查刷新。主面板的 0.24 秒淡入完发布脚本需要 Developer ID、签名和公证凭据,不属于日常本地构建流程。-## 手动验证矩阵+## 手动验证- 左键打开主面板,右键和 Control 点击打开上下文菜单- 多任务运行或等待批准期间,完成和终止触发 3 秒流光提示;连续结束及全部任务结束时颜色与到期时间正确diff --git a/Scripts/performance/__main__.py b/Scripts/performance/__main__.pyindex ed34f3c..02a75dc 100644--- a/Scripts/performance/__main__.py+++ b/Scripts/performance/__main__.py@@ -16,6 +16,8 @@ import tempfileimport timeimport xml.etree.ElementTree as ETfrom pathlib import Path+from types import FrameType+from typing import Literal, castsys.dont_write_bytecode = True@@ -27,10 +29,13 @@ from .analyze import (system_summary,)from .performance import write_report+from .models import (+ CommandResult, Comparison, Phase, PhasePlan, ProcessIdentity, Report, SchemaKey, Schemas, Target,+)VERSION = "1"ROOT = Path(__file__).resolve().parents[2]-SCHEMAS = (+SCHEMAS: tuple[SchemaKey, ...] = ("activity-monitor-process-live","time-profile","potential-hangs",@@ -45,15 +50,27 @@ PRESETS = {}-def now():+class Arguments(argparse.Namespace):+ app: Path+ pid: int | None+ preset: str+ output: Path | None+ workload: str+ baseline: Path | None+ cpu_mean_budget: float | None+ footprint_budget: float | None+ render: Path | None+++def now() -> str:return dt.datetime.now().astimezone().isoformat(timespec="seconds")-def status(message):+def status(message: str) -> None:print(f"[{now()}] {message}", flush=True)-def capture(args, timeout=20):+def capture(args: list[str], timeout: float = 20) -> str:result = subprocess.run(args, capture_output=True, timeout=timeout)if result.returncode:raise RuntimeError(@@ -62,14 +79,14 @@ def capture(args, timeout=20):return result.stdout.decode(errors="replace").strip()-def optional(args):+def optional(args: list[str]) -> str | None:try:return capture(args)except (OSError, RuntimeError, subprocess.TimeoutExpired):return None-def process_path(pid):+def process_path(pid: int) -> Path | None:lib = ctypes.CDLL("/usr/lib/libproc.dylib")lib.proc_pidpath.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]lib.proc_pidpath.restype = ctypes.c_int@@ -78,13 +95,13 @@ def process_path(pid):return Path(os.fsdecode(buffer.value)).resolve() if size > 0 else None-def identity(pid):+def identity(pid: int) -> ProcessIdentity:path = process_path(pid)started = optional(["/bin/ps", "-p", str(pid), "-o", "lstart="])return {"pid": pid, "path": str(path) if path else None, "started": started}-def inspect_target(app, pid):+def inspect_target(app: Path, pid: int | None) -> Target:info = plistlib.loads((app / "Contents/Info.plist").read_bytes())executable = (app / "Contents/MacOS" / info["CFBundleExecutable"]).resolve()if not executable.is_file():@@ -110,7 +127,7 @@ def inspect_target(app, pid):start = stream.find(b"<?xml")end = stream.find(b"</plist>")if 0 <= start <= end:- ent = plistlib.loads(stream[start : end + len(b"</plist>")])+ ent = plistlib.loads(stream[start: end + len(b"</plist>")])breakuuids = optional(["/usr/bin/xcrun", "dwarfdump", "--uuid", str(executable)])uuid_list = re.findall(r"UUID: ([A-Fa-f0-9-]+) \(([^)]+)\)", uuids or "")@@ -130,15 +147,19 @@ def inspect_target(app, pid):}-def load_schemas(developer):+def load_schemas(developer: str) -> Schemas:base = Path(developer).parent / "Applications/Instruments.app/Contents/Packages"- found = {}+ found: Schemas = {}for path in base.rglob("schemas.xml"):for schema in ET.parse(path).getroot().findall("schema"):- if schema.get("name") in SCHEMAS:- found[schema.get("name")] = [- c.get("mnemonic") for c in schema.findall("column")- ]+ name = schema.get("name")+ for known_name in SCHEMAS:+ if name != known_name:+ continue+ columns = [c.get("mnemonic") for c in schema.findall("column")]+ if any(column is None for column in columns):+ raise ValueError(f"Missing column mnemonic in schema: {name}")+ found[known_name] = [column for column in columns if column is not None]if "activity-monitor-process-live" not in found:raise RuntimeError("No Activity Monitor column schema found in the selected Xcode"@@ -146,13 +167,15 @@ def load_schemas(developer):return found-def run_command(args, logfile, timeout, expected=None):+def run_command(+ args: list[str], logfile: Path, timeout: float, expected: ProcessIdentity | None = None,+) -> CommandResult:began = time.monotonic()interrupted = Falsefailure = Nonedirectory = logfile.parent.stat()- def check_output():+ def check_output() -> None:try:current = logfile.parent.stat()if (current.st_dev, current.st_ino) == (directory.st_dev, directory.st_ino):@@ -189,7 +212,7 @@ def run_command(args, logfile, timeout, expected=None):os.killpg(process.pid, signal.SIGKILL)process.wait(timeout=10)check_output()- result = {+ result: CommandResult = {"argv": args,"exit_code": process.returncode,"elapsed_s": round(time.monotonic() - began, 2),@@ -202,7 +225,7 @@ def run_command(args, logfile, timeout, expected=None):return result-def save(data, output):+def save(data: Report, output: Path) -> None:temporary = output / "performance.json.tmp"temporary.write_text(json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False) + "\n"@@ -211,7 +234,7 @@ def save(data, output):write_report(data, output / "performance.html")-def analyze_phase(phase, output, schemas, pid):+def analyze_phase(phase: Phase, output: Path, schemas: Schemas, pid: int) -> None:for name, columns in schemas.items():file = output / f"{phase['id']}-{name}.xml"if not file.exists() or name not in phase.get("exported", []):@@ -229,14 +252,22 @@ def analyze_phase(phase, output, schemas, pid):table, pid if name in ("potential-hangs", "hang-risks") else None)except (ValueError, KeyError, ET.ParseError, TypeError) as error:- phase["errors"].append(f"{name}: {error}")+ phase.setdefault("errors", []).append(f"{name}: {error}")-def record_phase(phase, data, output, schemas):- target = data["target"]["identity"]+def record_phase(phase: Phase, data: Report, output: Path, schemas: Schemas) -> None:+ target = data["target"].get("identity")+ if target is None:+ raise RuntimeError("Target process identity is unavailable")if identity(target["pid"]) != target:raise RuntimeError("Target process changed before recording")- phase.update(started=now(), errors=[], commands=[], exported=[])+ phase["started"] = now()+ errors: list[str] = []+ commands: list[CommandResult] = []+ exported: list[SchemaKey] = []+ phase["errors"] = errors+ phase["commands"] = commands+ phase["exported"] = exportedphase["trace"] = phase["id"] + ".trace"args = ["/usr/bin/xcrun",@@ -257,18 +288,18 @@ def record_phase(phase, data, output, schemas):command = run_command(args, output / f"{phase['id']}-record.log", phase["seconds"] + 150, target)- phase["commands"].append(command)+ commands.append(command)if command["exit_code"] or command.get("error"):- phase["errors"].append(+ errors.append(command.get("error", "xctrace recording failed; see record log"))elif "[Error]" in (output / command["log"]).read_text(errors="replace"):- phase["errors"].append("xctrace reported an error despite a zero exit code")+ errors.append("xctrace reported an error despite a zero exit code")if identity(target["pid"]) != target:- phase["errors"].append("Target identity changed during recording")+ errors.append("Target identity changed during recording")trace = output / phase["trace"]if not trace.exists():- phase["errors"].append("No trace artifact was created")+ errors.append("No trace artifact was created")returntoc = output / f"{phase['id']}-toc.xml"cmd = run_command(@@ -285,19 +316,20 @@ def record_phase(phase, data, output, schemas):output / f"{phase['id']}-toc.log",120,)- phase["commands"].append(cmd)+ commands.append(cmd)if cmd["exit_code"] or cmd.get("error"):- phase["errors"].append("TOC export failed")+ errors.append("TOC export failed")returnroot = ET.parse(toc).getroot()- phase["recorded_s"] = float(root.findtext(".//summary/duration", "0"))+ duration = root.findtext(".//summary/duration", "0")+ phase["recorded_s"] = float(duration)phase["trace_started"] = root.findtext(".//summary/start-date")phase["hang_settings"] = [e.text for e in root.findall(".//instrument[@name='Hangs']//key")]phase["tables"] = [e.get("schema") for e in root.findall(".//data/table")]if phase["recorded_s"] < phase["seconds"] * 0.9:- phase["errors"].append("Recording duration below 90% of requested duration")+ errors.append("Recording duration below 90% of requested duration")for name in SCHEMAS:if name not in phase["tables"] or name not in schemas:continue@@ -317,33 +349,33 @@ def record_phase(phase, data, output, schemas):output / f"{phase['id']}-{name}.log",120,)- phase["commands"].append(cmd)+ commands.append(cmd)if cmd["exit_code"] or cmd.get("error"):- phase["errors"].append(f"{name}: export failed")+ errors.append(f"{name}: export failed")else:- phase["exported"].append(name)+ exported.append(name)analyze_phase(phase, output, schemas, target["pid"])if "resources" not in phase:- phase["errors"].append("No valid resource measurements")+ errors.append("No valid resource measurements")else:resource = phase["resources"]- phase["errors"].extend(resource["errors"])+ errors.extend(resource["errors"])if resource["span_s"] < phase["seconds"] * 0.8:- phase["errors"].append("Resource coverage below 80% of requested duration")+ errors.append("Resource coverage below 80% of requested duration")if resource["max_gap_s"] > 5:- phase["errors"].append("Resource sample gap exceeds 5 seconds")+ errors.append("Resource sample gap exceeds 5 seconds")if resource["cpu_coverage"] < 0.95:- phase["errors"].append("CPU sample coverage below 95%")+ errors.append("CPU sample coverage below 95%")if resource.get("footprint") is None:- phase["errors"].append("Physical footprint was not available")+ errors.append("Physical footprint was not available")if phase["template"] == "Time Profiler" and "profile" not in phase:- phase["errors"].append("No decoded CPU profile")+ errors.append("No decoded CPU profile")phase["ended"] = now()-def compare(data, path):- previous = json.loads(path.read_text())- keys = [+def compare(data: Report, path: Path) -> Comparison:+ previous = cast(Report, json.loads(path.read_text()))+ keys: list[tuple[Literal["target", "environment", "config"], str]] = [("target", "bundle_id"),("environment", "os"),("environment", "chip"),@@ -372,7 +404,7 @@ def compare(data, path):(p["id"], p["seconds"]) for p in previous.get("phases", [])]:differences.append("phase_plan")- result = {+ result: Comparison = {"baseline_version": previous.get("target", {}).get("version"),"compatible": not differences,"differences": differences,@@ -382,18 +414,21 @@ def compare(data, path):for current, old in zip(data["phases"], previous["phases"]):a, b = current.get("resources"), old.get("resources")if a and b and not current.get("errors") and not old.get("errors"):+ current_cpu, old_cpu = a["cpu_mean"], b["cpu_mean"]+ current_memory, old_memory = a["footprint"], b["footprint"]+ if current_cpu is None or old_cpu is None or current_memory is None or old_memory is None:+ raise ValueError("Complete phases must contain CPU and footprint measurements")result["deltas"].append({"phase": current["id"],- "cpu_pp": a["cpu_mean"] - b["cpu_mean"],- "footprint_mib": a["footprint"]["median"]- - b["footprint"]["median"],+ "cpu_pp": current_cpu - old_cpu,+ "footprint_mib": current_memory["median"] - old_memory["median"],})return result-def main():+def main() -> int:parser = argparse.ArgumentParser(prog="python3 -m Scripts.performance", description=__doc__)@@ -401,24 +436,16 @@ def main():parser.add_argument("--pid", type=int)parser.add_argument("--preset", choices=PRESETS, default="standard")parser.add_argument("--output", type=Path)- parser.add_argument(- "--workload", default="Natural workload; UI and active tasks uncontrolled"- )+ parser.add_argument("--workload", default="Natural workload; UI and active tasks uncontrolled")parser.add_argument("--baseline", type=Path)parser.add_argument("--cpu-mean-budget", type=float)- parser.add_argument(- "--footprint-budget", type=float, help="Physical footprint budget in MiB"- )- parser.add_argument(- "--render",- type=Path,- help="Regenerate HTML from an existing performance.json without profiling",- )- args = parser.parse_args()+ parser.add_argument("--footprint-budget", type=float, help="Physical footprint budget in MiB")+ parser.add_argument("--render", type=Path, help="Regenerate HTML from an existing performance.json without profiling")+ args = parser.parse_args(namespace=Arguments())if args.render:- data = json.loads(args.render.read_text())+ render_data = cast(Report, json.loads(args.render.read_text()))destination = args.output or args.render.parent / "performance.html"- write_report(data, destination)+ write_report(render_data, destination)print(destination)return 0for value in (args.cpu_mean_budget, args.footprint_budget):@@ -426,14 +453,14 @@ def main():parser.error("Budgets must be finite positive numbers")timestamp = dt.datetime.now().strftime("%Y%m%d/%H%M%S")output = (- args.output or ROOT / "Performance" / f"{timestamp}-{args.preset}"+ args.output or ROOT / "Performance" / f"{timestamp}-{args.preset}").resolve()try:output.mkdir(parents=True, exist_ok=False)except OSError as error:parser.error(f"Cannot create a new output directory: {error}")os.chmod(output, 0o700)- data = {+ data: Report = {"format_version": VERSION,"started": now(),"state": "running",@@ -450,7 +477,7 @@ def main():}exit_code = 0- def stop(signum, frame):+ def stop(_signum: int, _frame: FrameType | None) -> None:raise KeyboardInterruptsignal.signal(signal.SIGTERM, stop)@@ -461,17 +488,22 @@ def main():source_directory = output / "tool-source"source_directory.mkdir()for name in (- "__init__.py",- "__main__.py",- "analyze.py",- "performance.py",- "performance.html",+ "__init__.py",+ "__main__.py",+ "analyze.py",+ "models.py",+ "performance.py",+ "performance.html",):source = Path(__file__).with_name(name).read_bytes()(source_directory / name).write_bytes(source)data["tool_sha256"][name] = hashlib.sha256(source).hexdigest()status("Preflight: target, Xcode, templates, schemas")- data["target"] = inspect_target(args.app.resolve(), args.pid)+ target = inspect_target(args.app.resolve(), args.pid)+ data["target"] = target+ target_identity = target.get("identity")+ if target_identity is None:+ raise RuntimeError("Target process identity is unavailable")env = data["environment"]env["instruments"] = capture(["/usr/bin/xcrun", "xctrace", "version"])env["chip"] = optional(["/usr/sbin/sysctl", "-n", "machdep.cpu.brand_string"])@@ -480,9 +512,7 @@ def main():env["power"] = optional(["/usr/bin/pmset", "-g", "batt"])env["power_source"] = (env["power"] or "Unknown").splitlines()[0]env["load_before"] = list(os.getloadavg())- templates = capture(- ["/usr/bin/xcrun", "xctrace", "list", "templates"], timeout=60- )+ templates = capture(["/usr/bin/xcrun", "xctrace", "list", "templates"], timeout=60)for template in ("Time Profiler", "Activity Monitor"):if template not in templates.splitlines():raise RuntimeError(f"Missing Instruments template: {template}")@@ -490,7 +520,7 @@ def main():(output / "schemas.json").write_text(json.dumps(schemas, indent=2))warmup, sample, repeats, soak, settle = PRESETS[args.preset]data["config"]["warmup_s"] = warmup- data["plan"] = [+ plan: list[PhasePlan] = [{"id": f"cpu-{i + 1}","label": f"CPU repeat {i + 1}",@@ -498,7 +528,8 @@ def main():"template": "Time Profiler",}for i in range(repeats)- ] + [+ ]+ plan.extend([{"id": "soak","label": "Resource observation",@@ -511,21 +542,23 @@ def main():"seconds": settle,"template": "Activity Monitor",},- ]+ ])+ data["plan"] = plansave(data, output)status(- f"Warm-up {warmup}s; target PID {data['target']['identity']['pid']}; output {output}"+ f"Warm-up {warmup}s; target PID {target_identity['pid']}; output {output}")time.sleep(warmup)- for planned in data["plan"]:- phase = dict(planned)+ for planned in plan:+ phase: Phase = {"id": planned["id"], "label": planned["label"],+ "seconds": planned["seconds"], "template": planned["template"]}data["phases"].append(phase)status(f"Recording {phase['id']} ({phase['template']}, {phase['seconds']}s)")record_phase(phase, data, output, schemas)status(- f"Finished {phase['id']}: {'incomplete' if phase['errors'] else 'valid'}"+ f"Finished {phase['id']}: {'incomplete' if phase.get('errors') else 'valid'}")save(data, output)data["state"] = (@@ -536,20 +569,20 @@ def main():data["environment"]["load_after"] = list(os.getloadavg())if args.baseline:data["comparison"] = compare(data, args.baseline)- breached = []+ breached: list[str] = []for phase in data["phases"]:resource = phase.get("resources", {})if phase.get("errors"):continue- if (- args.cpu_mean_budget is not None- and resource.get("cpu_mean", 0) > args.cpu_mean_budget- ):- breached.append(phase["id"] + ": cpu_mean")- if (- args.footprint_budget is not None- and resource.get("footprint", {}).get("max", 0) > args.footprint_budget- ):+ if args.cpu_mean_budget is not None:+ cpu_mean = resource.get("cpu_mean", 0)+ if cpu_mean is None:+ raise ValueError("CPU budget requires a valid mean measurement")+ if cpu_mean > args.cpu_mean_budget:+ breached.append(phase["id"] + ": cpu_mean")+ footprint = resource.get("footprint")+ footprint_peak = footprint["max"] if footprint is not None else 0+ if args.footprint_budget is not None and footprint_peak > args.footprint_budget:breached.append(phase["id"] + ": footprint_peak")data["budget_breaches"] = breachedexit_code = 2 if data["state"] != "complete" else 3 if breached else 0@@ -564,6 +597,7 @@ def main():finally:data["ended"] = now()data["exit_code"] = exit_code+ report_output: Path | None = outputtry:save(data, output)except Exception as error:@@ -575,15 +609,15 @@ def main():for message in data["errors"]:status(message)try:- output = Path(tempfile.mkdtemp(prefix="codexbar-performance-recovery-"))- save(data, output)+ report_output = Path(tempfile.mkdtemp(prefix="codexbar-performance-recovery-"))+ save(data, report_output)except Exception as recovery_error:status(f"Recovery save failed: {type(recovery_error).__name__}: {recovery_error}")- output = None- if output is not None:- status(f"Report: {output / 'performance.html'}; exit {exit_code}")+ report_output = None+ if report_output is not None:+ status(f"Report: {report_output / 'performance.html'}; exit {exit_code}")return exit_codediff --git a/Scripts/performance/analyze.py b/Scripts/performance/analyze.pyindex 1d43c49..e0b4ed5 100644--- a/Scripts/performance/analyze.py+++ b/Scripts/performance/analyze.py@@ -4,9 +4,14 @@ import collectionsimport mathimport statisticsimport xml.etree.ElementTree as ET+from collections.abc import Iterator, Sequence+from pathlib import Path+from typing import IO, Literal, overload+from .models import Events, MetricKey, Profile, Resources, Sample, SystemSummary-def percentile(values, fraction):++def percentile(values: Sequence[float], fraction: float) -> float | None:if not values:return Nonevalues = sorted(values)@@ -17,95 +22,142 @@ def percentile(values, fraction):class Table:- def __init__(self, path, columns):+ def __init__(self, path: Path | IO[str], columns: Sequence[str]) -> None:self.root = ET.parse(path).getroot()- self.ids = {e.get("id"): e for e in self.root.iter() if e.get("id")}+ self.ids = {key: e for e in self.root.iter() if (key := e.get("id"))}self.columns = columns- def resolve(self, element):+ @overload+ def resolve(self, element: ET.Element) -> ET.Element:+ ...++ @overload+ def resolve(self, element: None) -> None:+ ...++ def resolve(self, element: ET.Element | None) -> ET.Element | None:if element is None:return None- return self.ids[element.get("ref")] if element.get("ref") else element+ reference = element.get("ref")+ return self.ids[reference] if reference else element- def number(self, element):+ def number(self, element: ET.Element | None) -> float | None:element = self.resolve(element)if element is None or element.tag == "sentinel":return None+ text = element.text+ if text is None:+ return Nonetry:- value = float(element.text)+ value = float(text)return value if math.isfinite(value) else Noneexcept (ValueError, TypeError):return None- def label(self, element):+ def label(self, element: ET.Element | None) -> str:element = self.resolve(element)return "" if element is None else element.get("fmt", element.text or "")- def rows(self):+ def rows(self) -> Iterator[dict[str, ET.Element]]:for row in self.root.iter("row"):if len(row) != len(self.columns):raise ValueError(f"Schema mismatch: expected {len(self.columns)} columns, got {len(row)}")yield dict(zip(self.columns, row))-def resource_summary(table, pid):- points = []+def resource_summary(table: Table, pid: int) -> Resources:+ points: list[tuple[float, dict[str, float | None]]] = []for row in table.rows():if table.number(row.get("pid")) != pid:continuepoint = {key: table.number(value) for key, value in row.items()}- if point.get("start") is not None:- points.append(point)- points.sort(key=lambda p: p["start"])+ start = point.get("start")+ if start is not None:+ points.append((start, point))+ points.sort(key=lambda p: p[0])if len(points) < 3:raise ValueError("Fewer than 3 target resource samples")- series, errors = [], []- interval_end = points[0]["start"]- for point in points:- timestamp = point["start"] / 1e9- item = {"t": timestamp, "cpu": None, "dt": None}- for source, destination in [("memory-physical-footprint", "footprint"),- ("memory-real", "rss"), ("memory-compressed", "compressed")]:+ series: list[Sample] = []+ errors: list[str] = []+ interval_end = points[0][0]+ memory_fields: list[tuple[str, MetricKey]] = [+ ("memory-physical-footprint", "footprint"),+ ("memory-real", "rss"), ("memory-compressed", "compressed"),+ ]+ for start, point in points:+ timestamp = start / 1e9+ item: Sample = {"t": timestamp, "cpu": None, "dt": None,+ "footprint": None, "rss": None, "compressed": None, "threads": None}+ for source, destination in memory_fields:value = point.get(source)item[destination] = value / 2 ** 20 if value is not None else Noneitem["threads"] = point.get("thread-count")duration, cpu = point.get("duration"), point.get("cpu-percent")if duration is None or duration <= 0:errors.append("Resource sample duration is missing or nonpositive")- elif point["start"] < interval_end:+ elif start < interval_end:errors.append("Resource sample intervals overlap")else:- interval_end = point["start"] + duration+ interval_end = start + duration# Instruments pairs each CPU percentage with the duration in the same rowif cpu is not None:if cpu < 0:errors.append("CPU percentage is negative")else:- item.update(cpu=cpu, dt=duration / 1e9)+ item["cpu"] = cpu+ item["dt"] = duration / 1e9series.append(item)span = series[-1]["t"] - series[0]["t"]if span <= 0:raise ValueError("Resource sample time did not advance")- cpu_points = [p for p in series if p["cpu"] is not None]- observed_seconds = sum(p["dt"] for p in cpu_points)- cpu_span = (max(interval_end, points[-1]["start"]) - points[0]["start"]) / 1e9- cpu = [p["cpu"] for p in cpu_points]- result = {"samples": len(series), "span_s": span, "series": series, "errors": errors,- "max_gap_s": max(b["t"] - a["t"] for a, b in zip(series, series[1:])),- "cpu_coverage": observed_seconds / cpu_span,- "cpu_mean": sum(p["cpu"] * p["dt"] for p in cpu_points) / observed_seconds if observed_seconds else None,- "cpu_p50": percentile(cpu, .5), "cpu_p95": percentile(cpu, .95),- "cpu_peak": max(cpu) if cpu else None}- for key in ["footprint", "rss", "compressed", "threads"]:- values = [p[key] for p in series if p[key] is not None]- result[key] = {"first": values[0], "last": values[-1], "min": min(values),- "max": max(values), "median": statistics.median(values)} if values else None- for key, name in [("idle-wakeups", "wakeups"), ("disk-bytes-read", "read_bytes"),- ("disk-bytes-written", "written_bytes")]:- first, last = points[0].get(key), points[-1].get(key)- result[name] = last - first if first is not None and last is not None and last >= first else None- result[name + "_per_s"] = result[name] / span if result[name] is not None else None- footprint = [(p["t"], p["footprint"]) for p in series if p["footprint"] is not None]+ cpu_points = [(p["cpu"], p["dt"]) for p in series if p["cpu"] is not None and p["dt"] is not None]+ observed_seconds = sum(duration for _, duration in cpu_points)+ cpu_span = (max(interval_end, points[-1][0]) - points[0][0]) / 1e9+ cpu_values = [value for value, _ in cpu_points]+ result: Resources = {+ "samples": len(series),+ "span_s": span,+ "series": series,+ "errors": errors,+ "max_gap_s": max(b["t"] - a["t"] for a, b in zip(series, series[1:])),+ "cpu_coverage": observed_seconds / cpu_span,+ "cpu_mean": sum(value * duration for value, duration in cpu_points) / observed_seconds if observed_seconds else None,+ "cpu_p50": percentile(cpu_values, .5),+ "cpu_p95": percentile(cpu_values, .95),+ "cpu_peak": max(cpu_values) if cpu_values else None,+ "footprint": None,+ "rss": None,+ "compressed": None,+ "threads": None,+ "wakeups": None,+ "wakeups_per_s": None,+ "read_bytes": None,+ "read_bytes_per_s": None,+ "written_bytes": None,+ "written_bytes_per_s": None+ }+ metric_keys: tuple[MetricKey, ...] = ("footprint", "rss", "compressed", "threads")+ for key in metric_keys:+ values = [value for p in series if (value := p[key]) is not None]+ result[key] = {+ "first": values[0],+ "last": values[-1],+ "min": min(values),+ "max": max(values),+ "median": statistics.median(values)+ } if values else None+ counters: tuple[tuple[str, Literal["wakeups", "read_bytes", "written_bytes"],+ Literal["wakeups_per_s", "read_bytes_per_s", "written_bytes_per_s"]], ...] = (+ ("idle-wakeups", "wakeups", "wakeups_per_s"),+ ("disk-bytes-read", "read_bytes", "read_bytes_per_s"),+ ("disk-bytes-written", "written_bytes", "written_bytes_per_s"),+ )+ for source_key, name, rate_name in counters:+ first, last = points[0][1].get(source_key), points[-1][1].get(source_key)+ difference = last - first if first is not None and last is not None and last >= first else None+ result[name] = difference+ result[rate_name] = difference / span if difference is not None else None+ footprint = [(p["t"], value) for p in series if (value := p["footprint"]) is not None]if len(footprint) >= 3:xs, ys = zip(*footprint)xmean, ymean = statistics.mean(xs), statistics.mean(ys)@@ -114,16 +166,27 @@ def resource_summary(table, pid):window = min(60, span / 4)head = [y for x, y in footprint if x <= xs[0] + window]tail = [y for x, y in footprint if x >= xs[-1] - window]- result["memory_trend"] = {"slope_mib_min": slope * 60, "window_s": window,- "head_median": statistics.median(head), "tail_median": statistics.median(tail),- "delta_mib": statistics.median(tail) - statistics.median(head),- "long_enough": span >= 240}+ result["memory_trend"] = {+ "slope_mib_min": slope * 60,+ "window_s": window,+ "head_median": statistics.median(head),+ "tail_median": statistics.median(tail),+ "delta_mib": statistics.median(tail) - statistics.median(head),+ "long_enough": span >= 240+ }return result-def profile_summary(table, pid):- total = main = missing = app_weight = app_named = 0- leaf, inclusive, binaries, seconds = (collections.Counter() for _ in range(4))+def profile_summary(table: Table, pid: int) -> Profile:+ total: float = 0+ main: float = 0+ missing: float = 0+ app_weight: float = 0+ app_named: float = 0+ leaf: collections.defaultdict[str, float] = collections.defaultdict(float)+ inclusive: collections.defaultdict[str, float] = collections.defaultdict(float)+ binaries: collections.defaultdict[str, float] = collections.defaultdict(float)+ seconds: collections.defaultdict[int, float] = collections.defaultdict(float)for row in table.rows():process = table.resolve(row.get("process"))process_pid = table.number(process.find("pid")) if process is not None else None@@ -156,7 +219,7 @@ def profile_summary(table, pid):inclusive[name] += weightbinary = table.resolve(first.find("binary"))binaries[binary.get("name", "Unknown") if binary is not None else "Unknown"] += weight- app_frames = []+ app_frames: list[str] = []for frame in frames:binary = table.resolve(frame.find("binary"))if binary is not None and ".app/Contents/MacOS/" in binary.get("path", ""):@@ -165,26 +228,33 @@ def profile_summary(table, pid):app_weight += weightif any(n and not n.startswith("0x") and n != "<deduplicated_symbol>" for n in app_frames):app_named += weight- return {"sampled_ms": total, "main_ms": main, "missing_stack_ms": missing,- "app_stack_ms": app_weight, "app_named_stack_ms": app_named,- "leaf": leaf.most_common(18), "inclusive": inclusive.most_common(35),- "binaries": binaries.most_common(15), "busiest_seconds": seconds.most_common(8)}+ return {+ "sampled_ms": total,+ "main_ms": main,+ "missing_stack_ms": missing,+ "app_stack_ms": app_weight,+ "app_named_stack_ms": app_named,+ "leaf": sorted(leaf.items(), key=lambda item: item[1], reverse=True)[:18],+ "inclusive": sorted(inclusive.items(), key=lambda item: item[1], reverse=True)[:35],+ "binaries": sorted(binaries.items(), key=lambda item: item[1], reverse=True)[:15],+ "busiest_seconds": sorted(seconds.items(), key=lambda item: item[1], reverse=True)[:8]+ }-def event_summary(table, pid=None):- rows = []+def event_summary(table: Table, pid: int | None = None) -> Events:+ rows: list[dict[str, str]] = []for row in table.rows():if pid is not None and "process" in row:process = table.resolve(row["process"])- if process is None or table.number(process.find("pid")) != pid:+ if table.number(process.find("pid")) != pid:continuerows.append({key: table.label(value) for key, value in row.items()if key not in ("backtrace", "process", "thread")})return {"count": len(rows), "events": rows[:100]}-def system_summary(table):- values = []+def system_summary(table: Table) -> SystemSummary:+ values: list[float] = []for row in table.rows():value = table.number(row.get("cpu-total-load"))if value is not None:diff --git a/Scripts/performance/models.py b/Scripts/performance/models.pynew file mode 100644index 0000000..10f2a5f--- /dev/null+++ b/Scripts/performance/models.py@@ -0,0 +1,197 @@+"""Types for the existing capture and report dictionaries"""++from typing import Literal, NotRequired, TypedDict++MetricKey = Literal["footprint", "rss", "compressed", "threads"]+SeriesKey = Literal["cpu", "footprint", "rss", "compressed", "threads"]+StatisticKey = Literal["first", "last", "min", "max", "median"]+ResourceValueKey = Literal[+ "cpu_mean", "cpu_p50", "cpu_p95", "cpu_peak", "wakeups", "wakeups_per_s",+ "read_bytes", "read_bytes_per_s", "written_bytes", "written_bytes_per_s",+]+EventKey = Literal["potential-hangs", "hang-risks", "device-thermal-state-intervals"]+SchemaKey = Literal[+ "activity-monitor-process-live", "time-profile", "potential-hangs", "hang-risks",+ "device-thermal-state-intervals", "activity-monitor-system",+]+Schemas = dict[SchemaKey, list[str]]+++class Sample(TypedDict):+ t: float+ cpu: float | None+ dt: float | None+ footprint: float | None+ rss: float | None+ compressed: float | None+ threads: float | None+++class Statistics(TypedDict):+ first: float+ last: float+ min: float+ max: float+ median: float+++class MemoryTrend(TypedDict):+ slope_mib_min: float+ window_s: float+ head_median: float+ tail_median: float+ delta_mib: float+ long_enough: bool+++class Resources(TypedDict):+ samples: int+ span_s: float+ series: list[Sample]+ errors: list[str]+ max_gap_s: float+ cpu_coverage: float+ cpu_mean: float | None+ cpu_p50: float | None+ cpu_p95: float | None+ cpu_peak: float | None+ footprint: Statistics | None+ rss: Statistics | None+ compressed: Statistics | None+ threads: Statistics | None+ wakeups: float | None+ wakeups_per_s: float | None+ read_bytes: float | None+ read_bytes_per_s: float | None+ written_bytes: float | None+ written_bytes_per_s: float | None+ memory_trend: NotRequired[MemoryTrend]+++class Profile(TypedDict):+ sampled_ms: float+ main_ms: float+ missing_stack_ms: float+ app_stack_ms: float+ app_named_stack_ms: float+ leaf: list[tuple[str, float]]+ inclusive: list[tuple[str, float]]+ binaries: list[tuple[str, float]]+ busiest_seconds: list[tuple[int, float]]+++class Events(TypedDict):+ count: int+ events: list[dict[str, str]]+++class SystemSummary(TypedDict):+ samples: int+ cpu_load_mean: float | None+ cpu_load_peak: float | None+++class ProcessIdentity(TypedDict):+ pid: int+ path: str | None+ started: str | None+++class Target(TypedDict):+ name: str+ bundle_id: NotRequired[str | None]+ version: NotRequired[str | None]+ build: NotRequired[str | None]+ binary_sha256: NotRequired[str]+ uuids: NotRequired[list[tuple[str, str]]]+ get_task_allow: NotRequired[bool | None]+ identity: NotRequired[ProcessIdentity]+++class CommandResult(TypedDict):+ argv: list[str]+ exit_code: int | None+ elapsed_s: float+ log: str+ error: NotRequired[str]+++class PhasePlan(TypedDict):+ id: str+ label: str+ seconds: int+ template: str+++PhaseEvents = TypedDict("PhaseEvents", {+ "potential-hangs": Events,+ "hang-risks": Events,+ "device-thermal-state-intervals": Events,+}, total=False)+++class Phase(PhasePlan, PhaseEvents):+ started: NotRequired[str]+ ended: NotRequired[str]+ errors: NotRequired[list[str]]+ commands: NotRequired[list[CommandResult]]+ exported: NotRequired[list[SchemaKey]]+ trace: NotRequired[str]+ recorded_s: NotRequired[float]+ trace_started: NotRequired[str | None]+ hang_settings: NotRequired[list[str | None]]+ tables: NotRequired[list[str | None]]+ resources: NotRequired[Resources]+ profile: NotRequired[Profile]+ system: NotRequired[SystemSummary]+++class Config(TypedDict):+ preset: str+ workload: str+ cpu_mean_budget: float | None+ footprint_budget: float | None+ warmup_s: NotRequired[int]+++class Environment(TypedDict):+ os: str+ arch: str+ instruments: NotRequired[str]+ chip: NotRequired[str | None]+ cores: NotRequired[str | None]+ memory_bytes: NotRequired[str | None]+ power: NotRequired[str | None]+ power_source: NotRequired[str]+ load_before: NotRequired[list[float]]+ load_after: NotRequired[list[float]]+++class Delta(TypedDict):+ phase: str+ cpu_pp: float+ footprint_mib: float+++class Comparison(TypedDict):+ baseline_version: str | None+ compatible: bool+ differences: list[str]+ deltas: list[Delta]+++class Report(TypedDict):+ format_version: str+ started: str+ state: str+ errors: list[str]+ config: Config+ phases: list[Phase]+ environment: Environment+ target: Target+ ended: NotRequired[str]+ exit_code: NotRequired[int]+ tool_sha256: NotRequired[dict[str, str]]+ plan: NotRequired[list[PhasePlan]]+ comparison: NotRequired[Comparison]+ budget_breaches: NotRequired[list[str]]diff --git a/Scripts/performance/performance.html b/Scripts/performance/performance.htmlindex 92308e0..5f24b73 100644--- a/Scripts/performance/performance.html+++ b/Scripts/performance/performance.html@@ -1093,7 +1093,7 @@</div><div class="overview-matrix"><div class="matrix-head">- <h3>阶段指标矩阵</h3>+ <h3>阶段指标</h3><span class="muted">FP = Footprint · N/A = 无数据 · CPU 100% = 1 个逻辑核心</span></div>@@MATRIX@@diff --git a/Scripts/performance/performance.py b/Scripts/performance/performance.pyindex 7f68424..b17dd9b 100644--- a/Scripts/performance/performance.py+++ b/Scripts/performance/performance.py@@ -3,108 +3,111 @@import htmlimport jsonimport math+from collections.abc import Sequencefrom pathlib import Path+from typing import cast+from .models import (+ EventKey,+ MetricKey,+ Report,+ ResourceValueKey,+ Sample,+ SeriesKey,+ StatisticKey,+)-def escape(value):+BarEntry = tuple[str, float | None, str]+BarGroup = tuple[str, Sequence[BarEntry]]+++def escape(value: object) -> str:return html.escape(str(value))-def number(value, digits=2, suffix=""):+def number(value: float | None, digits: int = 2, suffix: str = "") -> str:return "N/A" if value is None else f"{value:,.{digits}f}{suffix}"-def table(headers, rows):+def table(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:head = "".join(f"<th>{escape(h)}</th>" for h in headers)- body = "".join(- "<tr>" + "".join(f"<td>{escape(c)}</td>" for c in row) + "</tr>" for row in rows- )+ body = "".join("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in row) + "</tr>" for row in rows)if not body:body = f'<tr><td colspan="{len(headers)}" class="muted">无可用数据</td></tr>'return f'<div class="table-scroll"><table><thead><tr>{head}</tr></thead><tbody>{body}</tbody></table></div>'-def chart(series, key, label, color, unit, phase_index, ceiling=None, step=False):+def chart(+ series: Sequence[Sample], key: SeriesKey, label: str, color: str, unit: str,+ phase_index: int, ceiling: float | None = None, step: bool = False,+) -> str:width, height, left, right, top, bottom = 640, 240, 60, 24, 32, 40- points = [p for p in series if p.get(key) is not None]+ points = [(p["t"], value) for p in series if (value := p[key]) is not None]if not points:return '<div class="empty">无可用采样数据</div>'start, end = min(p["t"] for p in series), max(p["t"] for p in series)- peak = max(points, key=lambda p: p[key])- maximum = ceiling or nice_max(peak[key])- x = lambda t: left + (t - start) / max(end - start, 1) * (width - left - right)- y = lambda v: top + (1 - v / maximum) * (height - top - bottom)+ peak_time, peak_value = max(points, key=lambda p: p[1])+ maximum = ceiling or nice_max(peak_value)++ def x(t: float) -> float:+ return left + (t - start) / max(end - start, 1) * (width - left - right)++ def y(value: float) -> float:+ return top + (1 - value / maximum) * (height - top - bottom)+parts = [f'<div class="trend-chart" data-phase="{phase_index}" data-key="{escape(key)}" data-unit="{escape(unit)}">',- f'<div class="trend-stats"><b>{escape(label)}</b><span>最低 {number(min(p[key] for p in points))} · 峰值 {number(peak[key])} {escape(unit)}</span></div>',+ f'<div class="trend-stats"><b>{escape(label)}</b><span>最低 {number(min(value for _, value in points))} · 峰值 {number(peak_value)} {escape(unit)}</span></div>',f'<svg viewBox="0 0 {width} {height}" data-plot-left="{left}" data-plot-width="{width - left - right}" role="img" aria-label="{escape(label)}运行曲线">',]for index in range(5):value = maximum * index / 4yy = y(value)- parts.append(- f'<line class="grid" x1="{left}" x2="{width - right}" y1="{yy:.2f}" y2="{yy:.2f}"/>'- )- parts.append(- f'<text x="{left - 10}" y="{yy + 4:.2f}" text-anchor="end">{value:g}</text>'- )+ parts.append(f'<line class="grid" x1="{left}" x2="{width - right}" y1="{yy:.2f}" y2="{yy:.2f}"/>')+ parts.append(f'<text x="{left - 10}" y="{yy + 4:.2f}" text-anchor="end">{value:g}</text>')for index in range(6):t = start + (end - start) * index / 5- parts.append(- f'<text x="{x(t):.2f}" y="{height - 10}" text-anchor="middle">{t:.0f}s</text>'- )- segments, current = [], []+ parts.append(f'<text x="{x(t):.2f}" y="{height - 10}" text-anchor="middle">{t:.0f}s</text>')+ segments: list[list[tuple[float, float]]] = []+ current: list[tuple[float, float]] = []previous = Nonefor point in series:- if point.get(key) is None or (- previous is not None and point["t"] - previous > 5+ value = point[key]+ if value is None or (+ previous is not None and point["t"] - previous > 5):if current:segments.append(current)current = []- if point.get(key) is not None:- current.append(point)+ if value is not None:+ current.append((point["t"], value))previous = point["t"]if current:segments.append(current)for segment in segments:- path = f"M {x(segment[0]['t']):.2f} {y(segment[0][key]):.2f}"- for point in segment[1:]:+ path = f"M {x(segment[0][0]):.2f} {y(segment[0][1]):.2f}"+ for timestamp, value in segment[1:]:path += (- f" H {x(point['t']):.2f} V {y(point[key]):.2f}"+ f" H {x(timestamp):.2f} V {y(value):.2f}"if step- else f" L {x(point['t']):.2f} {y(point[key]):.2f}"+ else f" L {x(timestamp):.2f} {y(value):.2f}")- parts.append(- f'<path d="{path} L {x(segment[-1]["t"]):.2f} {y(0):.2f} L {x(segment[0]["t"]):.2f} {y(0):.2f} Z" fill="{color}" opacity=".10"/>'- )- parts.append(- f'<path d="{path}" fill="none" stroke="{color}" stroke-width="2"/>'- )+ parts.append(f'<path d="{path} L {x(segment[-1][0]):.2f} {y(0):.2f} L {x(segment[0][0]):.2f} {y(0):.2f} Z" fill="{color}" opacity=".10"/>')+ parts.append(f'<path d="{path}" fill="none" stroke="{color}" stroke-width="2"/>')if len(segment) == 1:- parts.append(- f'<circle cx="{x(segment[0]["t"]):.2f}" cy="{y(segment[0][key]):.2f}" r="3" fill="{color}"/>'- )- anchor = "end" if x(peak["t"]) > width / 2 else "start"- parts.append(- f'<circle cx="{x(peak["t"]):.2f}" cy="{y(peak[key]):.2f}" r="4" fill="{color}"/>'- )- parts.append(- f'<text x="{x(peak["t"]):.2f}" y="{y(peak[key]) - 10:.2f}" text-anchor="{anchor}">峰值 {peak[key]:.2f}</text>'- )- parts.append(- f'<line class="cursor" x1="{left}" x2="{left}" y1="{top}" y2="{height - bottom}" hidden/></svg>'- )- parts.append(- f'<div class="chart-control"><input aria-label="{escape(label)}采样点" type="range" min="0" max="{len(series) - 1}" value="0"><output></output></div></div>'- )+ parts.append(f'<circle cx="{x(segment[0][0]):.2f}" cy="{y(segment[0][1]):.2f}" r="3" fill="{color}"/>')+ anchor = "end" if x(peak_time) > width / 2 else "start"+ parts.append(f'<circle cx="{x(peak_time):.2f}" cy="{y(peak_value):.2f}" r="4" fill="{color}"/>')+ parts.append(f'<text x="{x(peak_time):.2f}" y="{y(peak_value) - 10:.2f}" text-anchor="{anchor}">峰值 {peak_value:.2f}</text>')+ parts.append(f'<line class="cursor" x1="{left}" x2="{left}" y1="{top}" y2="{height - bottom}" hidden/></svg>')+ parts.append(f'<div class="chart-control"><input aria-label="{escape(label)}采样点" type="range" min="0" max="{len(series) - 1}" value="0"><output></output></div></div>')return "".join(parts)-def nice_max(value):+def nice_max(value: float) -> float:if value <= 0:return 1- magnitude = 10 ** math.floor(math.log10(value))+ magnitude: float = 10 ** math.floor(math.log10(value))step = magnitude / 2return math.ceil(value * 1.1 / step) * step@@ -112,7 +115,7 @@ def nice_max(value):COLORS = ["var(--teal)", "var(--violet)", "var(--warn)", "var(--rose)"]-def bars(groups, unit="", digits=2):+def bars(groups: Sequence[BarGroup], unit: str = "", digits: int = 2) -> str:values = [value for _, entries in groups for _, value, _ in entries if value is not None]@@ -121,48 +124,43 @@ def bars(groups, unit="", digits=2):zero = -low / extent * 100parts = ['<div class="bar-chart">']for label, entries in groups:- parts.append(- f'<div class="bar-group"><div class="bar-label">{escape(label)}</div>'- )+ parts.append(f'<div class="bar-group"><div class="bar-label">{escape(label)}</div>')for name, value, color in entries:- parts.append(- f'<div class="bar-entry"><span class="bar-series">{escape(name)}</span>'- )+ parts.append(f'<div class="bar-entry"><span class="bar-series">{escape(name)}</span>')if value is None:- parts.append(- '<div class="bar-track missing"></div><b class="bar-value">N/A</b>'- )+ parts.append('<div class="bar-track missing"></div><b class="bar-value">N/A</b>')else:position = (min(0, value) - low) / extent * 100width = abs(value) / extent * 100- parts.append(- f'<div class="bar-track"><span class="zero" style="left:{zero:.4f}%"></span><i style="left:{position:.4f}%;width:{width:.4f}%;background:{color}" data-value="{value}"></i></div><b class="bar-value">{number(value, digits)} <small>{escape(unit)}</small></b>'- )+ parts.append(f'<div class="bar-track"><span class="zero" style="left:{zero:.4f}%"></span><i style="left:{position:.4f}%;width:{width:.4f}%;background:{color}" data-value="{value}"></i></div><b class="bar-value">{number(value, digits)} <small>{escape(unit)}</small></b>')parts.append("</div>")parts.append("</div>")return (- "".join(parts)- + ('<div class="empty">无采集数据</div>' if not groups else "")- + "</div>"+ "".join(parts)+ + ('<div class="empty">无采集数据</div>' if not groups else "")+ + "</div>")-def ranked(items, unit="ms", color=COLORS[0], digits=0):+def ranked(+ items: Sequence[tuple[str, float | None]], unit: str = "ms",+ color: str = COLORS[0], digits: int = 0,+) -> str:return bars([(label, [("", value, color)]) for label, value in items], unit, digits)-def panel(title, content, note=""):+def panel(title: str, content: str, note: str = "") -> str:return (- '<article class="panel"><h3>'- + escape(title)- + "</h3>"- + ('<p class="muted">' + escape(note) + "</p>" if note else "")- + content- + "</article>"+ '<article class="panel"><h3>'+ + escape(title)+ + "</h3>"+ + ('<p class="muted">' + escape(note) + "</p>" if note else "")+ + content+ + "</article>")-def distribution(main, total):+def distribution(main: float, total: float) -> str:if not total:return '<div class="empty">无 CPU 样本</div>'ratio = main / total * 100@@ -170,21 +168,27 @@ def distribution(main, total):<div class="share-values"><div><span>主线程</span><b>{ratio:.1f}%</b><small>{main:,.0f} ms</small></div><div><span>其他线程</span><b>{100 - ratio:.1f}%</b><small>{total - main:,.0f} ms</small></div></div></div>"""-def interval_chart(rows, paired=False):+def interval_chart(+ rows: Sequence[tuple[str, Sequence[float | None]]], paired: bool = False,+) -> str:values = [v for _, entries in rows for v in entries if v is not None]if not values:return '<div class="empty">无可用数据</div>'maximum = nice_max(max(values))- x = lambda value: 100 * value / maximum++ def x(value: float) -> float:+ return 100 * value / maximum+parts = ['<div class="interval-chart">','<div class="interval-axis"><span>0</span><span>'+ number(maximum, 0)+ " MiB</span></div>",]- for label, values in rows:+ for label, entries in rows:parts.append(f'<div class="interval-row"><b>{escape(label)}</b>')- if any(v is None for v in values):+ values = [value for value in entries if value is not None]+ if len(values) != len(entries):parts.append('<span class="muted">N/A</span></div>')continuefirst, last = values[0], values[-1]@@ -193,21 +197,15 @@ def interval_chart(rows, paired=False):if pairedelse f"最小 {first:.1f} · 中位 {values[1]:.1f} · 峰值 {last:.1f} MiB")- parts.append(- f'<div class="interval-track"><i class="interval-line" style="left:{x(min(first, last)):.4f}%;width:{x(abs(last - first)):.4f}%"></i>'- )+ parts.append(f'<div class="interval-track"><i class="interval-line" style="left:{x(min(first, last)):.4f}%;width:{x(abs(last - first)):.4f}%"></i>')for i, value in enumerate(values):kind = (("head" if i == 0 else "tail")if pairedelse ("median" if i == 1 else "bound"))- parts.append(- f'<i class="interval-point {kind}" style="left:{x(value):.4f}%" title="{value:.2f} MiB"></i>'- )- parts.append(- '</div><span class="interval-values">' + description + "</span></div>"- )+ parts.append(f'<i class="interval-point {kind}" style="left:{x(value):.4f}%" title="{value:.2f} MiB"></i>')+ parts.append('</div><span class="interval-values">' + description + "</span></div>")parts.append('<div class="interval-key">'+ ("○ 首段 ● 尾段" if paired else "┃ 最小值 / 峰值 ● 中位数")@@ -216,7 +214,7 @@ def interval_chart(rows, paired=False):return "".join(parts)-def write_report(data, destination):+def write_report(data: Report, destination: Path) -> None:import collectionsimport re@@ -224,22 +222,22 @@ def write_report(data, destination):valid = [p for p in phases if p.get("resources") and not p.get("errors")]target, env = data.get("target", {}), data.get("environment", {})measured = sum(p.get("recorded_s", 0) for p in phases)- cpu_phases = [p for p in valid if p["resources"].get("cpu_mean") is not None]+ resources = [(p, resource) for p in valid if (resource := p.get("resources")) is not None]+ cpu_phases = [(resource, mean) for _, resource in resources if (mean := resource["cpu_mean"]) is not None]cpu_durations = [- sum(point["dt"] for point in p["resources"]["series"] if point.get("cpu") is not None)- for p in cpu_phases+ sum(duration for point in resource["series"] if point["cpu"] is not None and (duration := point["dt"]) is not None)+ for resource, _ in cpu_phases]span = sum(cpu_durations)cpu_mean = (- sum(p["resources"]["cpu_mean"] * duration for p, duration in zip(cpu_phases, cpu_durations))+ sum(mean * duration for (_, mean), duration in zip(cpu_phases, cpu_durations))/ spanif spanelse None)footprints = [- p["resources"]["footprint"]["max"]- for p in valid- if p["resources"].get("footprint")+ footprint["max"] for _, resource in resources+ if (footprint := resource["footprint"]) is not None]hang_phases = [p for p in valid if "potential-hangs" in p]hangs = (@@ -255,27 +253,26 @@ def write_report(data, destination):if data.get("budget_breaches"):state, tone = "超过配置预算", "warn"- def resource_peak(key, nested=None):- values = [- (p["resources"].get(key) or {}).get(nested)- if nested- else p["resources"].get(key)- for p in valid- ]- return max((value for value in values if value is not None), default=None)+ def resource_peak(key: ResourceValueKey) -> float | None:+ values = [value for _, resource in resources if (value := resource[key]) is not None]+ return max(values, default=None)++ def metric_peak(key: MetricKey) -> float | None:+ values = [metric["max"] for _, resource in resources if (metric := resource[key]) is not None]+ return max(values, default=None)extra_kpis = [("CPU 采样峰值", number(resource_peak("cpu_peak")), "%", "有效阶段最高采样值"),- ("RSS 峰值", number(resource_peak("rss", "max"), 1), "MiB", "驻留物理内存"),+ ("RSS 峰值", number(metric_peak("rss"), 1), "MiB", "驻留物理内存"),("线程峰值",- number(resource_peak("threads", "max"), 0),+ number(metric_peak("threads"), 0),"个","有效阶段最大线程数",),("资源采样点",- number(sum(p["resources"].get("samples", 0) for p in valid), 0),+ number(sum(resource["samples"] for _, resource in resources), 0),"个","有效阶段累计样本",),@@ -284,8 +281,8 @@ def write_report(data, destination):f'<div class="kpi"><div class="label">{label}</div><div class="value">{value}<span class="unit">{unit}</span></div><small>{note}</small></div>'for label, value, unit, note in extra_kpis)- matrix_rows = []- phase_buttons = []+ matrix_rows: list[list[str]] = []+ phase_buttons: list[str] = []for index, phase in enumerate(phases):r = phase.get("resources", {})matrix_rows.append(@@ -295,13 +292,13 @@ def write_report(data, destination):number(r.get("cpu_p50")),number(r.get("cpu_p95")),number(r.get("cpu_peak")),- number((r.get("footprint") or {}).get("max"), 1),- number((r.get("rss") or {}).get("max"), 1),- number((r.get("threads") or {}).get("max"), 0),+ number(metric["max"] if (metric := r.get("footprint")) is not None else None, 1),+ number(metric["max"] if (metric := r.get("rss")) is not None else None, 1),+ number(metric["max"] if (metric := r.get("threads")) is not None else None, 0),number(r.get("wakeups_per_s")),number(- r.get("written_bytes") / 1024- if r.get("written_bytes") is not None+ written_bytes / 1024+ if (written_bytes := r.get("written_bytes")) is not Noneelse None,1,),@@ -328,11 +325,12 @@ def write_report(data, destination):matrix_rows,)- def resource_groups(specification, scale=1):- groups = []- for phase in valid:- r = phase["resources"]- entries = []+ def resource_groups(+ specification: Sequence[tuple[str, ResourceValueKey]], scale: float = 1,+ ) -> list[BarGroup]:+ groups: list[BarGroup] = []+ for phase, r in resources:+ entries: list[BarEntry] = []for index, (label, key) in enumerate(specification):value = r.get(key)entries.append(@@ -348,21 +346,22 @@ def write_report(data, destination):bars(resource_groups([("P95", "cpu_p95"), ("峰值", "cpu_peak")]), "%"),),]+ distribution_keys: tuple[StatisticKey, ...] = ("min", "median", "max")memory_rows = [(p["id"],[- (p["resources"].get("footprint") or {}).get(key)- for key in ("min", "median", "max")+ footprint.get(key) if footprint is not None else None+ for key in distribution_keys],)- for p in valid+ for p, resource in resources+ for footprint in [resource["footprint"]]]comparisons.append(panel("内存 footprint 分布", interval_chart(memory_rows)))trends = [- (p["id"], p["resources"]["memory_trend"])- for p in valid- if p["resources"].get("memory_trend")+ (p["id"], trend) for p, resource in resources+ if (trend := resource.get("memory_trend"))]comparisons.append(panel(@@ -422,12 +421,12 @@ def write_report(data, destination):(p["id"],[- ("均值", p["system"].get("cpu_load_mean"), COLORS[0]),- ("峰值", p["system"].get("cpu_load_peak"), COLORS[1]),+ ("均值", system.get("cpu_load_mean"), COLORS[0]),+ ("峰值", system.get("cpu_load_peak"), COLORS[1]),],)for p in valid- if p.get("system")+ if (system := p.get("system"))],"%",1,@@ -435,30 +434,35 @@ def write_report(data, destination):"各逻辑核心合计",),]- profiles = [p for p in valid if p.get("profile")]- total = sum(p["profile"]["sampled_ms"] for p in profiles)- main = sum(p["profile"]["main_ms"] for p in profiles)- libraries = collections.Counter()- for p in profiles:- for name, weight in p["profile"].get("binaries", []):+ profiles = [profile for p in valid if (profile := p.get("profile"))]+ total = sum(profile["sampled_ms"] for profile in profiles)+ main = sum(profile["main_ms"] for profile in profiles)+ libraries: collections.defaultdict[str, float] = collections.defaultdict(float)+ for profile in profiles:+ for name, weight in profile["binaries"]:libraries[name] += weighthot_overview = panel("主线程 CPU 样本分布", distribution(main, total)) + panel(- "叶节点所属库 · 已导出 Top 10", ranked(libraries.most_common(10))+ "叶节点所属库 · 已导出 Top 10", ranked(sorted(libraries.items(), key=lambda item: item[1], reverse=True)[:10]))- phase_html, hotspot_html, record_rows, event_rows = [], [], [], []+ phase_html: list[str] = []+ hotspot_html: list[str] = []+ record_rows: list[list[object]] = []+ event_rows: list[list[str]] = []+ series_keys: tuple[SeriesKey, ...] = ("cpu", "footprint", "rss", "compressed", "threads")+ memory_keys: tuple[MetricKey, ...] = ("footprint", "rss", "compressed")ceilings = {key: nice_max(max([- point[key]+ valuefor p in phasesfor point in p.get("resources", {}).get("series", [])- if point.get(key) is not None+ if (value := point[key]) is not None]or [0]))- for key in ("cpu", "footprint", "rss", "compressed", "threads")+ for key in series_keys}for index, phase in enumerate(phases):r = phase.get("resources", {})@@ -478,8 +482,8 @@ def write_report(data, destination):("CPU 采样覆盖",number(- r.get("cpu_coverage") * 100- if r.get("cpu_coverage") is not None+ coverage * 100+ if (coverage := r.get("cpu_coverage")) is not Noneelse None,1,"%",@@ -488,20 +492,20 @@ def write_report(data, destination):("最大采样间隔", number(r.get("max_gap_s"), 2, " s")),]content += (- '<div class="metric-strip">'- + "".join(- f"<div><span>{escape(label)}</span><b>{escape(value)}</b></div>"- for label, value in metrics- )- + "</div>"+ '<div class="metric-strip">'+ + "".join(+ f"<div><span>{escape(label)}</span><b>{escape(value)}</b></div>"+ for label, value in metrics+ )+ + "</div>")content += '<div class="chart-grid">' + chart(r["series"], "cpu", "CPU", COLORS[0], "%", index, ceilings["cpu"])for key, label, color in zip(- ["footprint", "rss", "compressed"],- ["Footprint", "RSS", "压缩内存"],- COLORS,+ memory_keys,+ ["Footprint", "RSS", "压缩内存"],+ COLORS,):content += chart(r["series"], key, label, color, "MiB", index, ceilings[key]@@ -516,27 +520,29 @@ def write_report(data, destination):ceilings["threads"],step=True,)- detail_rows = []- for key, label in [+ detail_rows: list[list[str]] = []+ memory_labels: tuple[tuple[MetricKey, str], ...] = (("footprint", "Footprint"),("rss", "RSS"),("compressed", "压缩内存"),- ]:- values = r.get(key) or {}+ )+ statistic_keys: tuple[StatisticKey, ...] = ("first", "last", "median")+ for key, label in memory_labels:+ values = r.get(key)detail_rows.append([label]- + [number(values.get(k), 2) for k in ("first", "last", "median")]+ + [number(values[k] if values is not None else None, 2) for k in statistic_keys])content += (- '<div class="sample-summary"><h4>内存采样明细 <span class="muted">MiB</span></h4>'- + table(["指标", "首值", "尾值", "中位数"], detail_rows)+ '<div class="sample-summary"><h4>内存采样明细 <span class="muted">MiB</span></h4>'+ + table(["指标", "首值", "尾值", "中位数"], detail_rows))content += '<p class="muted">CPU 为区间使用率. 内存与线程为采样时刻值. 拖动滑块或移动指针查看单点数据</p></div></div>'- if phase.get("errors"):+ if (phase_errors := phase.get("errors")):content += (- '<div class="notice warn">'- + "<br>".join(escape(e) for e in phase["errors"])- + "</div>"+ '<div class="notice warn">'+ + "<br>".join(escape(e) for e in phase_errors)+ + "</div>")phase_html.append(content + "</article>")profile = phase.get("profile")@@ -546,12 +552,12 @@ def write_report(data, destination):"叶节点热点 · Top 12", ranked(profile["leaf"][:12]))hot += (- panel(- "调用链热点 · Top 12",- ranked(profile["inclusive"][:12], color=COLORS[1]),- "权重包含子调用",- )- + "</div>"+ panel(+ "调用链热点 · Top 12",+ ranked(profile["inclusive"][:12], color=COLORS[1]),+ "权重包含子调用",+ )+ + "</div>")hot += '<div class="two">' + panel("高 CPU 采样权重的 1 秒区间",@@ -563,36 +569,36 @@ def write_report(data, destination):),)hot += (- panel(- "调用栈采样记录",- ranked(- [- (- "有调用栈",- profile["sampled_ms"] - profile["missing_stack_ms"],- ),- ("缺失调用栈", profile["missing_stack_ms"]),- ("含 App 帧", profile["app_stack_ms"]),- ("含命名 App 帧", profile["app_named_stack_ms"]),- ],- color=COLORS[2],- ),- )- + "</div>"+ panel(+ "调用栈采样记录",+ ranked(+ [+ (+ "有调用栈",+ profile["sampled_ms"] - profile["missing_stack_ms"],+ ),+ ("缺失调用栈", profile["missing_stack_ms"]),+ ("含 App 帧", profile["app_stack_ms"]),+ ("含命名 App 帧", profile["app_named_stack_ms"]),+ ],+ color=COLORS[2],+ ),+ )+ + "</div>")hot += "<details><summary>全部已导出热点</summary>" + table(["叶节点", "权重 / ms"],[(name, number(weight, 0)) for name, weight in profile["leaf"]],)hot += (- table(- ["调用链", "权重 / ms"],- [- (name, number(weight, 0))- for name, weight in profile["inclusive"]- ],- )- + "</details></details>"+ table(+ ["调用链", "权重 / ms"],+ [+ (name, number(weight, 0))+ for name, weight in profile["inclusive"]+ ],+ )+ + "</details></details>")hotspot_html.append(hot)record_rows.append(@@ -603,8 +609,8 @@ def write_report(data, destination):r.get("samples", "N/A"),number(r.get("max_gap_s"), 2, " s"),number(- r.get("cpu_coverage") * 100- if r.get("cpu_coverage") is not None+ coverage * 100+ if (coverage := r.get("cpu_coverage")) is not Noneelse None,1,"%",@@ -612,8 +618,9 @@ def write_report(data, destination):"已采集" if phase in valid else "部分数据",])- for key, label in [("potential-hangs", "Hangs"), ("hang-risks", "Hang risks")]:- for event in phase.get(key, {}).get("events", []):+ event_labels: tuple[tuple[EventKey, str], ...] = (("potential-hangs", "Hangs"), ("hang-risks", "Hang risks"))+ for event_key, label in event_labels:+ for event in phase.get(event_key, {}).get("events", []):event_rows.append([phase["id"],@@ -646,7 +653,7 @@ def write_report(data, destination):thermal += f'<div class="thermal-state {"nominal" if state_name.lower() == "nominal" else "elevated"}"><b>{escape(state_name)}</b><span>{escape(event.get("start", ""))} → {escape(event.get("end", ""))}</span></div>'thermal += "</div>"thermal += "</div>"- metadata = [+ metadata: list[list[object]] = [["App", target.get("name", "N/A")],["Bundle ID", target.get("bundle_id", "N/A")],[@@ -657,8 +664,8 @@ def write_report(data, destination):["芯片 / 逻辑核心", f"{env.get('chip', 'N/A')} / {env.get('cores', 'N/A')}"],["内存",- number(int(env["memory_bytes"]) / 2**30, 0, " GiB")- if env.get("memory_bytes")+ number(int(memory_bytes) / 2 ** 30, 0, " GiB")+ if (memory_bytes := env.get("memory_bytes"))else "N/A",],["Instruments", env.get("instruments", "N/A")],@@ -696,18 +703,18 @@ def write_report(data, destination):),)optional += (- panel(- "footprint 中位数差值",- ranked(- [- (r["phase"], r["footprint_mib"])- for r in comparison["deltas"]- ],- "MiB",- digits=2,- ),- )- + "</div>"+ panel(+ "footprint 中位数差值",+ ranked(+ [+ (r["phase"], r["footprint_mib"])+ for r in comparison["deltas"]+ ],+ "MiB",+ digits=2,+ ),+ )+ + "</div>")else:optional += table(@@ -717,24 +724,24 @@ def write_report(data, destination):optional += "</section>"budgets = data.get("config", {})if (- budgets.get("cpu_mean_budget") is not None- or budgets.get("footprint_budget") is not None+ budgets.get("cpu_mean_budget") is not None+ or budgets.get("footprint_budget") is not None):optional += (- '<section class="section"><h2>配置预算</h2>'- + table(- ["平均 CPU 上限", "footprint 峰值上限", "超出项"],+ '<section class="section"><h2>配置预算</h2>'+ + table(+ ["平均 CPU 上限", "footprint 峰值上限", "超出项"],+ [[- [- number(budgets.get("cpu_mean_budget"), 2, "%"),- number(budgets.get("footprint_budget"), 1, " MiB"),- ", ".join(data.get("budget_breaches", [])) or "0",- ]- ],- )- + "</section>"+ number(budgets.get("cpu_mean_budget"), 2, "%"),+ number(budgets.get("footprint_budget"), 1, " MiB"),+ ", ".join(data.get("budget_breaches", [])) or "0",+ ]+ ],+ )+ + "</section>")- portable = json.loads(json.dumps(data))+ portable = cast(Report, json.loads(json.dumps(data)))portable.get("target", {}).get("identity", {}).pop("path", None)for phase in portable.get("phases", []):phase.pop("commands", None)@@ -753,9 +760,7 @@ def write_report(data, destination):"STARTED": escape(data.get("started", "N/A")),"ENDED": escape(data.get("ended", "采集中")),"PRESET": escape(data.get("config", {}).get("preset", "N/A")),- "VERSION": escape(- f"{target.get('version', 'N/A')} ({target.get('build', 'N/A')})"- ),+ "VERSION": escape(f"{target.get('version', 'N/A')} ({target.get('build', 'N/A')})"),"MINUTES": number(measured / 60, 1),"CPU": number(cpu_mean, 2),"MEMORY": number(max(footprints) if footprints else None, 1),@@ -764,9 +769,7 @@ def write_report(data, destination):"MATRIX": matrix,"PHASE_BUTTONS": "".join(phase_buttons),"HANG_PHASES": str(len(hang_phases)),- "ERRORS": '<div class="notice warn">'- + "<br>".join(escape(e) for e in errors)- + "</div>"+ "ERRORS": '<div class="notice warn">' + "<br>".join(escape(e) for e in errors) + "</div>"if errorselse "","COMPARISONS": "".join(comparisons),