fix(processes): 对齐活动监视器内存口径与显示单位
This commit is contained in:
@@ -10,7 +10,7 @@ Kymo 是 macOS 菜单栏资源监控工具。菜单栏常驻品牌图标,点
|
||||
- 存储:主目录所在卷容量、块设备读写速率、各本地卷容量、可读取的 SMART 寿命与通电时间。
|
||||
- 电池:电量、功率、电源状态、健康度、循环次数、放电时间估计,以及按系统 CPU 能量差分排序的前三个进程。
|
||||
- 网络:接口切换、收发速率与累计字节、路径状态、本地和公网 IP 及复制。
|
||||
- 进程:PID、名称、路径、CPU、RSS 和线程数;支持搜索、列排序及复制。
|
||||
- 进程:PID、名称、路径、CPU、内存 footprint 和线程数;支持搜索、列排序及复制。
|
||||
|
||||
面板支持固定显示、保持唤醒、暂停 / 恢复采样。默认保留数字滚动、曲线平滑移动和圆环连续变化,可在设置开启“减弱动画”;后台记录独立控制。面板刷新默认 2 秒;默认隐藏停止采样,可显式开启后台趋势并配置间隔(新配置 30 秒)。设置窗口提供系统 / 浅色 / 深色外观、简体中文 / 繁體中文 / English 和关于信息。
|
||||
|
||||
|
||||
@@ -52,3 +52,35 @@ nonisolated enum ProcessEnergyReader {
|
||||
return status == 0 ? info : nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Independent of energy capability: physical footprint is available on Intel and Apple silicon.
|
||||
nonisolated enum ProcessMemoryReader {
|
||||
private static let readLock = NSLock()
|
||||
static func read(_ data: Data) -> Data? {
|
||||
guard data.count <= ProcessMemoryRequest.byteLimit,
|
||||
let request = try? JSONDecoder().decode(ProcessMemoryRequest.self, from: data),
|
||||
request.identities.count <= ProcessMemoryRequest.limit,
|
||||
Set(request.identities.map(\.pid)).count == request.identities.count,
|
||||
readLock.try() else { return nil }
|
||||
defer { readLock.unlock() }
|
||||
let deadline = ProcessInfo.processInfo.systemUptime + 1
|
||||
let readings = request.identities.map { id -> ProcessMemoryReading in
|
||||
var info = rusage_info_v4()
|
||||
var bytes: UInt64?
|
||||
if ProcessInfo.processInfo.systemUptime < deadline, id.pid > 0, id.seconds > 0,
|
||||
matches(id) {
|
||||
let status = withUnsafeMutablePointer(to: &info) { pointer in
|
||||
pointer.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { proc_pid_rusage(id.pid, RUSAGE_INFO_V4, $0) }
|
||||
}
|
||||
if status == 0, matches(id) { bytes = info.ri_phys_footprint }
|
||||
}
|
||||
return ProcessMemoryReading(id: id, footprintBytes: bytes)
|
||||
}
|
||||
return try? JSONEncoder().encode(ProcessMemoryReply(token: request.token, readings: readings))
|
||||
}
|
||||
private static func matches(_ id: ProcessIdentity) -> Bool {
|
||||
var info = proc_bsdinfo()
|
||||
return proc_pidinfo(id.pid, PROC_PIDTBSDINFO, 0, &info, Int32(MemoryLayout.size(ofValue: info))) == MemoryLayout.size(ofValue: info)
|
||||
&& info.pbi_uid == getuid() && info.pbi_start_tvsec == id.seconds && info.pbi_start_tvusec == id.microseconds
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,10 @@ final class SMARTService: NSObject, SMARTServiceProtocol {
|
||||
}
|
||||
}
|
||||
|
||||
func readProcessMemory(_ request: Data, withReply reply: @escaping (Data?) -> Void) {
|
||||
Task.detached(priority: .utility) { reply(ProcessMemoryReader.read(request)) }
|
||||
}
|
||||
|
||||
func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void) {
|
||||
Task.detached(priority: .utility) { reply(ProcessEnergyReader.read(request)) }
|
||||
}
|
||||
|
||||
+1
-1
@@ -10,7 +10,7 @@
|
||||
| [测试与验证](testing.md) | 独立检查程序、执行方式和人工验收边界 |
|
||||
| [极致轻量化与进程能耗方案](extreme-efficiency-plan.md) | 实施中:性能预算、逻辑浪费审查、真实能量列表、包体积收敛及分阶段验收 |
|
||||
|
||||
首批实施证据见[轻量化实施记录](efficiency-first-batch.md);第二批见[能量列表与纯文字对照记录](efficiency-second-batch.md)。第三批见[原生绘制与进程表记录](efficiency-third-batch.md);第四批见[动效与效率排查](motion-and-efficiency-plan.md);其淡入实现已由[保留原动效的优化](motion-preservation-plan.md)替代。包体积已收敛,真实 CPU 能量列表已实现;内存与长期性能预算仍待通过。
|
||||
首批实施证据见[轻量化实施记录](efficiency-first-batch.md);第二批见[能量列表与纯文字对照记录](efficiency-second-batch.md)。第三批见[原生绘制与进程表记录](efficiency-third-batch.md);第四批见[动效与效率排查](motion-and-efficiency-plan.md);其淡入实现已由[保留原动效的优化](motion-preservation-plan.md)替代。进程内存显示修正见[footprint 口径与单位对齐](process-memory-alignment-plan.md)。包体积已收敛,真实 CPU 能量列表已实现;内存与长期性能预算仍待通过。
|
||||
|
||||
2026-11-03 依据当前源码重新整理;同日补充极致轻量化与进程能耗实施方案。此前清理的旧阶段计划、设计概念图和路线图可通过 Git 查询。主题文档描述当前实现,方案中的目标不代表已实现,也不以代码已实现代替运行验收。
|
||||
|
||||
|
||||
@@ -89,3 +89,9 @@ Store 将递增需求代次交给 SystemSampler;actor 在开始系统调用前
|
||||
ProcessEnergyMonitor 在相同身份、Mach 启动标记和连续有效计数间,以整数先相减再转浮点,得到 nJ / 秒 / 1e9 的 W;保留最大三项,不添加 CPU 代理。失败、缺失、计数回退、重建需求均使旧基线失效。普通间隔最长允许 30 秒差分;用户设置长采样间隔时放宽至两倍前台间隔、上限 3600 秒,并显示实际窗口。详情见监控口径。
|
||||
|
||||
网络展示和诊断文字窗口共用 PanelPublicIPRefresh,遵循同一可见 / 暂停 / 睡眠与缓存策略。出口键仍包含全部活动地址,L07 尚待修正。外观观察器在挂载后延迟初始化,避免每次 View 值构造就创建 KVO / 通知订阅者。
|
||||
|
||||
## 进程内存读取
|
||||
|
||||
ProcessMonitor 负责枚举、身份、CPU / 线程 / 路径;不把 RSS 写入进程内存列。SystemSampler 现有 processTask 在 utility 枚举后调用 Core/Services/ProcessMemoryServiceClient,经 SMARTServiceProtocol.readProcessMemory 请求现有签名认证的 SMARTService。ProcessMemoryReader(与能量读取器同文件编译)使用独立锁和 RUSAGE_INFO_V4,按同 UID、正 PID、启动时间及前后身份复核读取 footprint;不受 CPU 能量 arm64 能力门槛影响。
|
||||
|
||||
批量上限 256 项、请求 64 KiB、响应 256 KiB,客户端总截止 3 秒 / 单请求 1.5 秒,服务每批 1 秒;不增加权限、不扫描 VM、不新增周期任务。ProcessSnapshot.withMemory 以完整身份合并,缺失即 nil,随后才发布列表并触发原能量调度。保留单在途、隐藏 / 重开代际校验;列表显示及排序只消费 footprintBytes。XPC 失败仍发布 CPU 等其余指标,内存显示 --;不混用 RSS。细节及验证见[内存口径修正](process-memory-alignment-plan.md)。
|
||||
|
||||
+8
-2
@@ -21,9 +21,9 @@
|
||||
| 网络 | `NetworkMonitor`,`NET_RT_IFLIST2` 64 位计数与 `getifaddrs` | 累计收发计数不属于应用会话流量;速率按实际经过时间差分,回退或接口身份 / 地址变化时重建基线;本地地址保持系统 numeric formatter(含 scope),每轮共用缓冲、每接口最终排序一次 |
|
||||
| 网络路径 | `NetworkPathObserver`,NWPathMonitor | 可用 / 不可用 / 需连接;代码取 `availableInterfaces.first` 作为主接口候选,并非独立解析系统默认路由;路径可用不保证公网可达 |
|
||||
| 公网 IP | `PublicIPAddressService`,`https://api.ipify.org` | 外部 HTTPS 服务看到的出口地址,可受代理 / VPN 影响;不是所选接口的公网地址。请求会向该服务暴露出口 IP |
|
||||
| 进程 | `ProcessMonitor`,sysctl、`proc_pidinfo`、`proc_pidpath` | 进程身份用 PID + 启动时间防复用;CPU 用累计 user + system 纳秒差分,RSS 为驻留量,权限受限字段留空 |
|
||||
| 进程 | `ProcessMonitor` + 只读 XPC,sysctl、`proc_pidinfo`、`proc_pidpath`、`proc_pid_rusage` | 进程身份用 PID + 启动时间防复用;CPU 用累计 user + system Mach tick 差分并换算纳秒,内存使用 physical footprint,权限受限字段留空 |
|
||||
|
||||
内存容量使用 GiB / MiB 等二进制单位,存储容量与常规字节 / 速率采用十进制格式;进程 RSS 表列按 MB 展示。
|
||||
内存容量使用 GiB / MiB 等二进制单位,存储容量与常规字节 / 速率采用十进制格式;进程 footprint 表列按活动监视器习惯,以 1,048,576 字节折算并标为 MB。
|
||||
|
||||
## 需要明确区分的指标
|
||||
|
||||
@@ -63,3 +63,9 @@ AppleSMC 和 GPU 驱动字段不是稳定公开的跨机型指标接口,缺失
|
||||
按全部可测候选的有效能量差分排名。权限受限、进程退出和截止会降低覆盖率;UI 显示已形成差分数 / 枚举总数,首帧等待,失败或不支持明确显示状态。零增量只有连续两帧有效时才代表 0 W。身份变化、计数回退、无效时间和超过允许窗口均不形成排名。超大进程集合在总截止下可能只覆盖部分批次,尚未验证极端规模下的公平轮转。
|
||||
|
||||
进程 CPU 的 `pti_total_user` / `pti_total_system` 是 task absolute CPU 时间:累计值先做整数差分,经本机 `mach_timebase_info` 转为纳秒,再除以单调时钟间隔;单逻辑核满载为 100%,多线程可超过 100%。不按整机核心数再平均。曾直接按纳秒解释这些计数,在本轮 M4 Pro(125/3 timebase)上少报约 41.67 倍;受控 200 ms CPU 对照已复现,修复另有实际工作量回归。独立资源采集器此前已正确使用 timebase;真实 CPU 能量 nJ 差分不受此问题影响。
|
||||
|
||||
## 进程表内存口径
|
||||
|
||||
进程表“内存”与内存排序使用 proc_pid_rusage(RUSAGE_INFO_V4).ri_phys_footprint,按 1,048,576 字节折算并沿用活动监视器的 MB 标签;不使用 PROC_PIDTASKALLINFO.pti_resident_size(RSS)。[Apple WWDC22](https://developer.apple.com/videos/play/wwdc2022/10106/) 说明 Activity Monitor 使用 footprint。RSS 包括可回收的干净驻留页,而 footprint 包含压缩等归属账目,两者无固定换算比例。
|
||||
|
||||
沙盒主程序不能直接取得其他进程 rusage,因此通过原有签名认证只读 XPC、按完整 ProcessIdentity 请求同 UID footprint。数据合并在单在途进程任务结束前完成;读取失败显示 --,不回退 RSS 或沿用旧值。保护进程 / 其他 UID 可能不可读,辅助进程独立统计。刷新时刻不同仍允许短时波动。来源核对与边界见[修正记录](process-memory-alignment-plan.md)。系统总内存卡片口径不变。
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# 进程内存口径修正
|
||||
|
||||
2026-11-04。用户截图显示本应用进程列表约 415 MB,而活动监视器约 88 MB。代码读取 PROC_PIDTASKALLINFO.pti_resident_size(RSS);同 PID 实测 RSS 416,628,736 字节、ri_phys_footprint 93,193,608 字节,差异确实存在。两张截图不是同步采样,不能声称逐字节对应。Apple WWDC22 10106 说明 Activity Monitor 的 memory footprint 可由 proc_pid_rusage 获取。
|
||||
|
||||
## 目标与范围
|
||||
|
||||
只修复进程表内存来源和排序,不改变数字 / 曲线 / 圆环动效或采样频率。Core Models / Monitors / Services、MenuBar 列表、现有 SMARTService 只读服务与检查受影响。系统总内存统计不在此次范围。
|
||||
|
||||
## 实施
|
||||
|
||||
另用本轮独立稳定进程实测单位:68,370,840 字节,十进制 68.4 MB、二进制 65.2 MiB;活动监视器该 PID 显示 65.2 MB。因此同时修正进程列除数为 1,048,576,沿用系统的 MB 标签;不改其他指标单位。
|
||||
|
||||
1. 将进程模型明确命名为 footprintBytes,显示与排序统一使用 footprint,读取失败显示 --,不退回 RSS 或沿用旧值。
|
||||
2. 实测沙盒读取其他进程 rusage 返回 EPERM,而任务 RSS 可读。因此经现有签名校验 XPC 服务执行批量只读 RUSAGE_INFO_V4;每批上限 256、请求 64 KiB、回复 256 KiB、总截止 3 秒;同 UID、正 PID、完整启动时间、读取前后身份匹配。无需 root、不新增权限。
|
||||
3. 内存读取归入现有进程单在途任务,完成后一次发布,保留隐藏 / 重开代际检查,后台不读取。与 CPU 能量周期独立,不受 arm64 能量能力门槛影响。只传 footprint 标量,不扫描 VM 区域。
|
||||
4. 增加真实 rusage / task_info 核对、身份和输入边界、显示与排序回归;Debug 构建及原生窗口核对。记录失败 / 限制,不把此次数值修正称作实际内存降低。
|
||||
|
||||
风险:活动监视器与本应用刷新时刻不同仍有波动,辅助进程单独统计;其他 UID / 系统保护进程可能不可读。旧服务连接异常时显示 --。现有性能记录用的 self TASK_VM_INFO.phys_footprint 无需重写,历史进程表 RSS 不可与 footprint 混比。
|
||||
|
||||
## 验证结果
|
||||
|
||||
普通 Debug 与 KYMO_AUDIT Debug 构建通过;统一入口 35 项 Swift 检查、211 条目录与签名沙盒权限检查通过。单位修正后再跑 NativeProcessTableChecks / ProcessSelectionChecks / ProcessEnergyReaderChecks 三项均通过。不将独立检查称为 xcodebuild test(无 XCTest target)。
|
||||
|
||||
签名沙盒测试面板的真实 AX 列表已读到用户原有 PID 33363 的 footprint 约 94.5 MB(当时尚未修显示除数),系统查询约 93–96 MB 字节值;相同 PID 的 RSS 仍约 417 MB。活动监视器该 PID 显示约 90.9–91.8 MB,进一步稳定进程试验证明单位必须按二进制折算。该核对没有退出用户 Xcode 实例或改动活动监视器筛选。
|
||||
|
||||
最终单位修正后的签名沙盒面板按 PID 35638 搜索,显示 65.2 MB;活动监视器同 PID 35638 同样显示 65.2 MB,独立查询连续记录 footprint 68,370,840 字节。完成真实只读 XPC / 列表 / 单位端到端对照。普通与诊断 Debug 的最终构建均通过;相关三项检查和目录 / 权限复跑通过。此次未测长期 CPU / 内存开销或包大小收益;没有把统计值变小计作资源优化。
|
||||
@@ -321,3 +321,7 @@ Release 配置由各 Target 在签名前 strip,保留包外 dSYM;测量必
|
||||
当前默认数字沿用原 numericText + spring;曲线和圆环分别验证 transform 关键帧与 strokeEnd 中间值,明确禁止用 CATransition 淡入替代。NativeMetricDrawingChecks 检查网格不动、动画期间及悬浮不重建路径、满 60 点的出界渐变、真实断点、禁用与卸载取消。PanelCurveChecks 对增长 / 满历史 / 非均匀时间戳的中间横坐标逐项核对原时间域公式。图层位图检查不能替代滚动模糊和动态观感验收。
|
||||
|
||||
相同后端、2 秒刷新、后台关闭的三轮 Release 对照与未达标项见[保留动效的优化记录](motion-preservation-plan.md)。记录主进程与 XPC 的实际 CPU 时间,使用 Mach timebase 换算;CPU 百分比以单核为 100%,不以自有列表的瞬时值替代区间测量。未测实际瓦数或长时能耗。
|
||||
|
||||
## 进程内存口径回归
|
||||
|
||||
ProcessEnergyReaderChecks 同时验证独立于能量能力的 ProcessMemoryReader:真实 footprint 与 TASK_VM_INFO.phys_footprint 接近、错启动时间 / 零 PID / 其他 UID 拒绝、重复 PID / 大包 / 解码 / 批量上限、完整身份合并、缺失清空和有效零。ProcessSelectionChecks 检查 footprint 双向排序及缺失置后;NativeProcessTableChecks 在真实原生表格检查活动监视器一致的二进制 MB 显示。端到端签名沙盒 → XPC → 表格及同 PID 对照记录见[内存修正记录](process-memory-alignment-plan.md)。不同时间点的截图不能要求逐字节相等。
|
||||
|
||||
@@ -11,7 +11,7 @@ nonisolated struct ProcessMetrics: Identifiable, Sendable {
|
||||
let name: String
|
||||
let path: String?
|
||||
let cpu: Double? // One logical CPU = 100%; may exceed 1.
|
||||
let residentBytes: UInt64?
|
||||
let footprintBytes: UInt64? // Physical footprint; never RSS.
|
||||
let threads: Int?
|
||||
let restricted: Bool
|
||||
}
|
||||
@@ -41,3 +41,25 @@ nonisolated extension ProcessSnapshot {
|
||||
highestCPUProcesses(limit: 1).first
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated struct ProcessMemoryRequest: Codable, Sendable {
|
||||
let token: UUID
|
||||
let identities: [ProcessIdentity]
|
||||
static let limit = 256
|
||||
static let byteLimit = 65_536
|
||||
}
|
||||
nonisolated struct ProcessMemoryReading: Codable, Sendable {
|
||||
let id: ProcessIdentity
|
||||
let footprintBytes: UInt64?
|
||||
}
|
||||
nonisolated struct ProcessMemoryReply: Codable, Sendable {
|
||||
let token: UUID
|
||||
let readings: [ProcessMemoryReading]
|
||||
}
|
||||
nonisolated extension ProcessSnapshot {
|
||||
func withMemory(_ values: [ProcessIdentity: UInt64]) -> ProcessSnapshot {
|
||||
ProcessSnapshot(date: date, enumerated: enumerated, readable: readable,
|
||||
rows: rows.map { ProcessMetrics(id: $0.id, name: $0.name, path: $0.path, cpu: $0.cpu,
|
||||
footprintBytes: values[$0.id], threads: $0.threads, restricted: $0.restricted) }, failed: failed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ nonisolated struct ProcessMonitor: Sendable {
|
||||
}
|
||||
}
|
||||
rows.append(ProcessMetrics(id: id, name: name, path: path,
|
||||
cpu: usage, residentBytes: valid ? info.ptinfo.pti_resident_size : nil,
|
||||
cpu: usage, footprintBytes: nil,
|
||||
threads: valid ? Int(info.ptinfo.pti_threadnum) : nil, restricted: !valid))
|
||||
}
|
||||
// Recheck the enumeration identity after path reads; never attach a reused PID's path.
|
||||
@@ -76,7 +76,7 @@ nonisolated struct ProcessMonitor: Sendable {
|
||||
} else {
|
||||
paths = [:]
|
||||
rows = rows.map { ProcessMetrics(id: $0.id, name: $0.name, path: nil, cpu: $0.cpu,
|
||||
residentBytes: $0.residentBytes, threads: $0.threads, restricted: $0.restricted) }
|
||||
footprintBytes: $0.footprintBytes, threads: $0.threads, restricted: $0.restricted) }
|
||||
}
|
||||
let retained = Set(rows.map(\.id))
|
||||
previous = next.filter { retained.contains($0.key) }
|
||||
|
||||
@@ -161,7 +161,8 @@ actor SystemSampler {
|
||||
processTask = Task.detached(priority: .utility) { [self] in
|
||||
var worker = monitor
|
||||
let value = read(&worker)
|
||||
await finishProcesses(value, monitor: worker, generation: generation)
|
||||
let memory = await ProcessMemoryServiceClient.read(value.rows.map(\.id))
|
||||
await finishProcesses(value.withMemory(memory), monitor: worker, generation: generation)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated enum ProcessMemoryServiceClient {
|
||||
static func read(_ identities: [ProcessIdentity]) async -> [ProcessIdentity: UInt64] {
|
||||
var values: [ProcessIdentity: UInt64] = [:]
|
||||
let deadline = ProcessInfo.processInfo.systemUptime + 3
|
||||
for start in stride(from: 0, to: identities.count, by: ProcessMemoryRequest.limit) {
|
||||
let remaining = deadline - ProcessInfo.processInfo.systemUptime
|
||||
guard !Task.isCancelled, remaining > 0 else { break }
|
||||
let chunk = Array(identities[start..<min(start + ProcessMemoryRequest.limit, identities.count)])
|
||||
let request = ProcessMemoryRequest(token: UUID(), identities: chunk)
|
||||
guard let data = try? JSONEncoder().encode(request), data.count <= ProcessMemoryRequest.byteLimit else { continue }
|
||||
let reply: ProcessMemoryReply? = await ServiceRequest.perform(timeout: min(1.5, remaining)) { proxy, finish in
|
||||
proxy.readProcessMemory(data) { data in
|
||||
guard let data, data.count <= 262_144,
|
||||
let reply = try? JSONDecoder().decode(ProcessMemoryReply.self, from: data),
|
||||
reply.token == request.token, reply.readings.count == chunk.count,
|
||||
Set(reply.readings.map(\.id)) == Set(chunk) else { finish(nil); return }
|
||||
finish(reply)
|
||||
}
|
||||
}
|
||||
guard let reply else { continue }
|
||||
for reading in reply.readings { values[reading.id] = reading.footprintBytes }
|
||||
}
|
||||
return values
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import Foundation
|
||||
|
||||
/// Fixed read-only operation: no caller-supplied paths or commands.
|
||||
@objc protocol SMARTServiceProtocol {
|
||||
nonisolated func readProcessMemory(_ request: Data, withReply reply: @escaping (Data?) -> Void)
|
||||
nonisolated func readProcessEnergy(_ request: Data, withReply reply: @escaping (Data?) -> Void)
|
||||
nonisolated func readSensors(cpu: Bool, gpu: Bool, fans: Bool,
|
||||
withReply reply: @escaping (NSNumber?, NSNumber?, [NSNumber]?) -> Void)
|
||||
|
||||
@@ -147,7 +147,7 @@ import SwiftUI
|
||||
case "name": text = process.name
|
||||
case "path": text = process.path ?? "--"
|
||||
case "cpu": text = process.cpu.map { String(format: "%.1f", $0 * 100) } ?? "--"
|
||||
case "memory": text = process.residentBytes.map { String(format: "%.1f MB", Double($0) / 1_000_000) } ?? "--"
|
||||
case "memory": text = process.footprintBytes.map { String(format: "%.1f MB", Double($0) / 1_048_576) } ?? "--"
|
||||
default: text = process.threads.map(String.init) ?? "--"
|
||||
}
|
||||
if cell.textField?.stringValue != text { cell.textField?.stringValue = text }
|
||||
|
||||
@@ -45,7 +45,7 @@ nonisolated struct ProcessSort: SortComparator, Equatable {
|
||||
case .name: return directed(lhs.name.localizedStandardCompare(rhs.name))
|
||||
case .path: return directed((lhs.path ?? "").localizedStandardCompare(rhs.path ?? ""))
|
||||
case .cpu: return metric(lhs.cpu, rhs.cpu)
|
||||
case .memory: return metric(lhs.residentBytes.map { Double($0) }, rhs.residentBytes.map { Double($0) })
|
||||
case .memory: return metric(lhs.footprintBytes.map { Double($0) }, rhs.footprintBytes.map { Double($0) })
|
||||
case .threads: return metric(lhs.threads.map { Double($0) }, rhs.threads.map { Double($0) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ private struct TextReportHost: NSViewRepresentable {
|
||||
c.rows = ProcessTableProjection.rows(processes?.rows ?? [], query: "", sorting: [ProcessSort(key: .cpu)], order: [])
|
||||
}
|
||||
let heading = Self.resourceText(snapshot) + "\nHistory points retained: \(historyPoints)\nPublic IP: \(publicAddress ?? "--")\n\n" + Self.energyText(energy)
|
||||
+ "\nProcesses: \(processes?.readable ?? 0)/\(processes?.enumerated ?? 0), failed=\(processes?.failed ?? false)\nPID\tCPU %\tRSS bytes\tThreads\tRestricted\tName\tPath"
|
||||
+ "\nProcesses: \(processes?.readable ?? 0)/\(processes?.enumerated ?? 0), failed=\(processes?.failed ?? false)\nPID\tCPU %\tFootprint bytes\tThreads\tRestricted\tName\tPath"
|
||||
c.lines = heading.components(separatedBy: "\n")
|
||||
let origin = scroll.contentView.bounds.origin
|
||||
let oldCount = table.numberOfRows
|
||||
@@ -150,7 +150,7 @@ private struct TextReportHost: NSViewRepresentable {
|
||||
return "CPU energy: \(energy.state), measured/readable/enumerated=\(energy.measured)/\(energy.readable)/\(energy.candidates)\n" + energy.rows.map { "\($0.id.pid) \($0.process.name): \($0.formattedPower), interval \(number($0.seconds)) s" }.joined(separator: "\n") + "\n"
|
||||
}
|
||||
private static func processLine(_ process: ProcessMetrics) -> String {
|
||||
"\(process.id.pid)\t\(number(process.cpu.map { $0 * 100 }))\t\(bytes(process.residentBytes))\t\(process.threads.map(String.init) ?? "--")\t\(process.restricted)\t\(process.name)\t\(process.path ?? "--")"
|
||||
"\(process.id.pid)\t\(number(process.cpu.map { $0 * 100 }))\t\(bytes(process.footprintBytes))\t\(process.threads.map(String.init) ?? "--")\t\(process.restricted)\t\(process.name)\t\(process.path ?? "--")"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3581,19 +3581,19 @@
|
||||
"en" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "CPU: one core = 100%, may exceed 100% · Memory: physical resident size (RSS) · Restricted fields shown as --"
|
||||
"value" : "CPU: one core = 100%, may exceed 100% · Memory: physical footprint · Restricted fields shown as --"
|
||||
}
|
||||
},
|
||||
"zh-Hans" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "CPU:单核 100%,可超过 100% · 内存:实际驻留物理内存(RSS)· 受限字段显示 --"
|
||||
"value" : "CPU:单核 100%,可超过 100% · 内存:物理内存占用(footprint)· 受限字段显示 --"
|
||||
}
|
||||
},
|
||||
"zh-Hant" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "CPU:單核 100%,可超過 100% · 記憶體:實際駐留實體記憶體(RSS)· 受限欄位顯示 --"
|
||||
"value" : "CPU:單核 100%,可超過 100% · 記憶體:實體記憶體用量(footprint)· 受限欄位顯示 --"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import Observation
|
||||
rows = (0..<500).map { index in
|
||||
ProcessMetrics(id: ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0),
|
||||
name: "worker-\(index)", path: nil, cpu: Double(index) / 100,
|
||||
residentBytes: 10_000_000, threads: 2, restricted: true)
|
||||
footprintBytes: 10_000_000, threads: 2, restricted: true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,8 @@ private struct Host: View {
|
||||
precondition(table.numberOfRows == 500 && table.tableColumns.count == 6)
|
||||
precondition(table.frame.width >= table.enclosingScrollView!.contentSize.width - 1, "Native table must fill its viewport")
|
||||
precondition(coordinator.createdCells > 0 && coordinator.createdCells < 200, "Rows must be virtualized")
|
||||
let memoryCell = table.view(atColumn: 4, row: 0, makeIfNecessary: true) as! NSTableCellView
|
||||
precondition(memoryCell.textField?.stringValue == "9.5 MB", "Memory column must match Activity Monitor binary MB display")
|
||||
let chosen = state.rows[10].id
|
||||
table.selectRowIndexes(IndexSet(integer: 10), byExtendingSelection: false)
|
||||
precondition(state.selection == nil, "Native selection must be deferred")
|
||||
@@ -72,7 +74,7 @@ private struct Host: View {
|
||||
await until { table.selectedRow == 489 }
|
||||
precondition(state.selection == chosen, "Selection must follow identity after reordering")
|
||||
for index in 0..<12 {
|
||||
state.rows[0] = ProcessMetrics(id: state.rows[0].id, name: "updated-\(index)", path: nil, cpu: Double(index), residentBytes: nil, threads: nil, restricted: false)
|
||||
state.rows[0] = ProcessMetrics(id: state.rows[0].id, name: "updated-\(index)", path: nil, cpu: Double(index), footprintBytes: nil, threads: nil, restricted: false)
|
||||
try? await Task.sleep(for: .milliseconds(20))
|
||||
}
|
||||
let visible = table.rows(in: table.visibleRect)
|
||||
|
||||
@@ -32,7 +32,7 @@ import CoreGraphics
|
||||
let id = ProcessIdentity(pid: Int32(index + 1), seconds: 1, microseconds: 0)
|
||||
let path: String? = index == 42 ? "/test/needle" : nil
|
||||
return ProcessMetrics(id: id, name: "worker-\(index)",
|
||||
path: path, cpu: Double(index), residentBytes: UInt64(2000 - index), threads: 1, restricted: false)
|
||||
path: path, cpu: Double(index), footprintBytes: UInt64(2000 - index), threads: 1, restricted: false)
|
||||
}
|
||||
let cpu = ProcessTableProjection.rows(input, query: "", sorting: [ProcessSort(key: .cpu)], order: [])
|
||||
precondition(cpu.first?.id.pid == 2000 && cpu.count == 2000)
|
||||
@@ -46,7 +46,7 @@ import CoreGraphics
|
||||
let ascending = ProcessTableProjection.rows(input, query: "", sorting: [ProcessSort(key: .cpu, order: .forward)], order: [])
|
||||
precondition(ascending.first?.id.pid == 1)
|
||||
let missing = ProcessMetrics(id: ProcessIdentity(pid: 3000, seconds: 1, microseconds: 0), name: "missing", path: nil,
|
||||
cpu: nil, residentBytes: nil, threads: nil, restricted: true)
|
||||
cpu: nil, footprintBytes: nil, threads: nil, restricted: true)
|
||||
for direction in [SortOrder.forward, .reverse] {
|
||||
for key in [ProcessSort.Key.cpu, .memory, .threads] {
|
||||
let result = ProcessTableProjection.rows(input + [missing], query: "", sorting: [ProcessSort(key: key, order: direction)], order: [])
|
||||
|
||||
@@ -22,7 +22,7 @@ import Foundation
|
||||
precondition(ProcessEnergyMonitor.watts(current: invalid, previous: reading(5, at: 10)) == nil)
|
||||
}
|
||||
func row(_ id: ProcessIdentity, _ cpu: Double) -> ProcessMetrics {
|
||||
ProcessMetrics(id: id, name: "fixture", path: nil, cpu: cpu, residentBytes: nil, threads: nil, restricted: false)
|
||||
ProcessMetrics(id: id, name: "fixture", path: nil, cpu: cpu, footprintBytes: nil, threads: nil, restricted: false)
|
||||
}
|
||||
let id2 = ProcessIdentity(pid: 43, seconds: 100, microseconds: 2)
|
||||
let processes = ProcessSnapshot(date: Date(), enumerated: 3, readable: 2, rows: [row(id, 5), row(id2, 0.01)], failed: false)
|
||||
|
||||
@@ -13,6 +13,37 @@ import Darwin
|
||||
precondition(reply.token == request.token && reply.readings.count == ids.count)
|
||||
return reply
|
||||
}
|
||||
func memory(_ ids: [ProcessIdentity]) throws -> ProcessMemoryReply {
|
||||
let request = ProcessMemoryRequest(token: UUID(), identities: ids)
|
||||
let reply = try JSONDecoder().decode(ProcessMemoryReply.self, from: ProcessMemoryReader.read(try JSONEncoder().encode(request))!)
|
||||
precondition(reply.token == request.token && reply.readings.count == ids.count)
|
||||
return reply
|
||||
}
|
||||
var vm = task_vm_info_data_t()
|
||||
var count = mach_msg_type_number_t(MemoryLayout.size(ofValue: vm) / MemoryLayout<integer_t>.size)
|
||||
precondition(withUnsafeMutablePointer(to: &vm) { pointer in
|
||||
pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { task_info(mach_task_self_, task_flavor_t(TASK_VM_INFO), $0, &count) }
|
||||
} == KERN_SUCCESS)
|
||||
let memoryBytes = try memory([id]).readings[0].footprintBytes!
|
||||
precondition(abs(Double(memoryBytes) - Double(vm.phys_footprint)) < 4_000_000, "Must agree with task physical footprint, not RSS")
|
||||
let wrongMemoryID = ProcessIdentity(pid: id.pid, seconds: id.seconds + 1, microseconds: id.microseconds)
|
||||
let wrongMemory = try memory([wrongMemoryID]); precondition(wrongMemory.readings[0].footprintBytes == nil)
|
||||
let zeroPID = try memory([ProcessIdentity(pid: 0, seconds: 1, microseconds: 0)]); precondition(zeroPID.readings[0].footprintBytes == nil)
|
||||
let otherUID = try memory([ProcessIdentity(pid: 1, seconds: 1, microseconds: 0)]); precondition(otherUID.readings[0].footprintBytes == nil)
|
||||
let invalidMemory = try JSONEncoder().encode(ProcessMemoryRequest(token: UUID(), identities: [id, id]))
|
||||
precondition(ProcessMemoryReader.read(invalidMemory) == nil)
|
||||
precondition(ProcessMemoryReader.read(Data(repeating: 0, count: ProcessMemoryRequest.byteLimit + 1)) == nil)
|
||||
precondition(ProcessMemoryReader.read(Data("bad".utf8)) == nil)
|
||||
let tooManyMemory = try JSONEncoder().encode(ProcessMemoryRequest(token: UUID(), identities: (1...257).map {
|
||||
ProcessIdentity(pid: Int32($0), seconds: 1, microseconds: 0)
|
||||
}))
|
||||
precondition(ProcessMemoryReader.read(tooManyMemory) == nil)
|
||||
let snapshot = ProcessSnapshot(date: Date(), enumerated: 1, readable: 1, rows: [
|
||||
ProcessMetrics(id: id, name: "test", path: nil, cpu: nil, footprintBytes: 123, threads: nil, restricted: false)
|
||||
], failed: false)
|
||||
precondition(snapshot.withMemory([wrongMemoryID: 999]).rows[0].footprintBytes == nil, "Never attach reused PID memory or retain a stale value")
|
||||
precondition(snapshot.withMemory([id: 0]).rows[0].footprintBytes == 0, "Valid zero is distinct from unavailable")
|
||||
print("PASS: physical footprint matches TASK_VM_INFO; memory identity, request bounds, missing/zero and stale-value checks")
|
||||
usleep(10_000)
|
||||
let first = try read([id]).readings[0]
|
||||
#if arch(arm64)
|
||||
|
||||
@@ -4,7 +4,7 @@ import Foundation
|
||||
static func main() {
|
||||
let id = ProcessIdentity(pid: 42, seconds: 100, microseconds: 0)
|
||||
let row = ProcessMetrics(id: id, name: "worker", path: "/test/worker", cpu: 0.2,
|
||||
residentBytes: 10, threads: 1, restricted: false)
|
||||
footprintBytes: 10, threads: 1, restricted: false)
|
||||
let live = ProcessSnapshot(date: Date(), enumerated: 1, readable: 1, rows: [row], failed: false)
|
||||
let filtered = ProcessTableProjection.rows(live.rows, query: "does-not-match", sorting: [], order: [])
|
||||
precondition(filtered.isEmpty)
|
||||
@@ -17,10 +17,17 @@ import Foundation
|
||||
precondition(ProcessTableProjection.exitedSelection(id, in: exited) == id)
|
||||
let reused = ProcessIdentity(pid: 42, seconds: 101, microseconds: 0)
|
||||
let replacement = ProcessMetrics(id: reused, name: row.name, path: row.path, cpu: nil,
|
||||
residentBytes: nil, threads: nil, restricted: true)
|
||||
footprintBytes: nil, threads: nil, restricted: true)
|
||||
let recycled = ProcessSnapshot(date: Date(), enumerated: 1, readable: 0, rows: [replacement], failed: false)
|
||||
precondition(ProcessTableProjection.exitedSelection(id, in: recycled) == id, "PID reuse cannot keep the previous process alive")
|
||||
precondition(ProcessTableProjection.exitedSelection(reused, in: recycled) == nil)
|
||||
let large = ProcessMetrics(id: ProcessIdentity(pid: 43, seconds: 1, microseconds: 0), name: "large", path: nil,
|
||||
cpu: nil, footprintBytes: 1_000, threads: nil, restricted: false)
|
||||
for direction in [SortOrder.forward, .reverse] {
|
||||
let sorted = ProcessTableProjection.rows([replacement, row, large], query: "", sorting: [ProcessSort(key: .memory, order: direction)], order: [])
|
||||
precondition(sorted.last?.id == replacement.id, "Missing footprint sorts last in both directions")
|
||||
precondition(sorted.first?.id == (direction == .forward ? row.id : large.id))
|
||||
}
|
||||
print("PASS: filtered/live selection, absent selection/snapshot, failed enumeration, actual exit and PID reuse")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,10 +9,10 @@ import Foundation
|
||||
precondition(GPUMonitor.normalized(53) == 0.53)
|
||||
precondition(GPUMonitor.normalized(101) == nil && GPUMonitor.normalized(.nan) == nil)
|
||||
let processRows = [
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 1, seconds: 1, microseconds: 1), name: "unknown", path: nil, cpu: nil, residentBytes: nil, threads: nil, restricted: true),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 2, seconds: 1, microseconds: 2), name: "busy", path: nil, cpu: 2.5, residentBytes: nil, threads: nil, restricted: false),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 3, seconds: 1, microseconds: 3), name: "idle", path: nil, cpu: 0, residentBytes: nil, threads: nil, restricted: false),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 4, seconds: 1, microseconds: 4), name: "invalid", path: nil, cpu: -.infinity, residentBytes: nil, threads: nil, restricted: false)
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 1, seconds: 1, microseconds: 1), name: "unknown", path: nil, cpu: nil, footprintBytes: nil, threads: nil, restricted: true),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 2, seconds: 1, microseconds: 2), name: "busy", path: nil, cpu: 2.5, footprintBytes: nil, threads: nil, restricted: false),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 3, seconds: 1, microseconds: 3), name: "idle", path: nil, cpu: 0, footprintBytes: nil, threads: nil, restricted: false),
|
||||
ProcessMetrics(id: ProcessIdentity(pid: 4, seconds: 1, microseconds: 4), name: "invalid", path: nil, cpu: -.infinity, footprintBytes: nil, threads: nil, restricted: false)
|
||||
]
|
||||
let processSnapshot = ProcessSnapshot(date: Date(), enumerated: 4, readable: 3, rows: processRows, failed: false)
|
||||
precondition(processSnapshot.highestCPUProcess?.name == "busy")
|
||||
|
||||
Reference in New Issue
Block a user