@ohos-perf/core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +344 -4
  2. package/dist/index.js +1557 -146
  3. package/package.json +48 -40
package/dist/index.js CHANGED
@@ -1773,6 +1773,10 @@ var RULES = [
1773
1773
  { id: "trace.binder", collector: "hitrace", binary: "hitrace" },
1774
1774
  { id: "trace.thread_state", collector: "hitrace", binary: "hitrace" },
1775
1775
  { id: "render.vsync", collector: "hitrace", binary: "hitrace" },
1776
+ // Ark-runtime trace events (GC phases, CustomNode builds). The hitrace
1777
+ // categories `ark` and `ace` are already in HITRACE_DEFAULT_CATEGORIES, so
1778
+ // this row is about the trace content, not about a collector to add.
1779
+ { id: "trace.ark", collector: "hitrace", binary: "hitrace" },
1776
1780
  { id: "perf.samples", collector: "hiperf", binary: "hiperf" },
1777
1781
  {
1778
1782
  id: "perf.pmu",
@@ -3369,6 +3373,13 @@ FROM callstack c
3369
3373
  LEFT JOIN args a ON c.argsetid = a.argset
3370
3374
  LEFT JOIN data_dict kd ON a.key = kd.id
3371
3375
  LEFT JOIN data_dict vd ON a.value = vd.id AND a.datatype = 1`;
3376
+ function pushIpidScope(where, params, ipids) {
3377
+ if (ipids === void 0) return;
3378
+ where.push(
3379
+ `callid IN (SELECT id FROM thread WHERE ipid IN (${ipids.map(() => "?").join(", ")}))`
3380
+ );
3381
+ params.push(...ipids);
3382
+ }
3372
3383
  function toCallstack(row) {
3373
3384
  const cookie = num(row["cookie"]);
3374
3385
  return {
@@ -3411,14 +3422,22 @@ var CallstackQuery = class {
3411
3422
  * quotes or a `--` comment is matched as text. The result is capped by
3412
3423
  * `opts.limit` (default {@link DEFAULT_MATCH_LIMIT}), and `opts.range`
3413
3424
  * restricts `ts` inclusively.
3425
+ *
3426
+ * `opts.ipids` restricts the result to rows emitted by a thread of one of
3427
+ * those processes. **An empty array matches nothing** — an empty app
3428
+ * identity means no process was identified, and widening to device-wide is
3429
+ * the attribution bug `MemoryMeasureAnalyzer` guards against. `undefined`
3430
+ * leaves the query unscoped.
3414
3431
  */
3415
3432
  matching(pattern, opts = {}) {
3433
+ if (opts.ipids !== void 0 && opts.ipids.length === 0) return [];
3416
3434
  const where = ["name LIKE ?"];
3417
3435
  const params = [pattern];
3418
3436
  if (opts.range) {
3419
3437
  where.push("ts >= ?", "ts <= ?");
3420
3438
  params.push(opts.range.startNs, opts.range.endNs);
3421
3439
  }
3440
+ pushIpidScope(where, params, opts.ipids);
3422
3441
  params.push(opts.limit ?? DEFAULT_MATCH_LIMIT);
3423
3442
  return this.db.query(
3424
3443
  `${SELECT_CALLSTACK} WHERE ${where.join(" AND ")} ORDER BY ts, id LIMIT ?`,
@@ -3429,15 +3448,18 @@ var CallstackQuery = class {
3429
3448
  * Rows `matching()` would return without its `opts.limit` cap.
3430
3449
  *
3431
3450
  * Uses the same `WHERE` as `matching()`, so the pair can report a true
3432
- * match count while the fetched rows stay bounded.
3451
+ * match count while the fetched rows stay bounded. An empty `opts.ipids`
3452
+ * counts zero, for the same reason `matching()` returns nothing.
3433
3453
  */
3434
3454
  countMatching(pattern, opts = {}) {
3455
+ if (opts.ipids !== void 0 && opts.ipids.length === 0) return 0;
3435
3456
  const where = ["name LIKE ?"];
3436
3457
  const params = [pattern];
3437
3458
  if (opts.range) {
3438
3459
  where.push("ts >= ?", "ts <= ?");
3439
3460
  params.push(opts.range.startNs, opts.range.endNs);
3440
3461
  }
3462
+ pushIpidScope(where, params, opts.ipids);
3441
3463
  const [row] = this.db.query(
3442
3464
  `SELECT COUNT(*) AS n FROM callstack WHERE ${where.join(" AND ")}`,
3443
3465
  params
@@ -3530,6 +3552,54 @@ var PerfQuery = class {
3530
3552
  pids
3531
3553
  ).map(toPerfThread);
3532
3554
  }
3555
+ /**
3556
+ * The `thread_id`s of the threads named `threadName` in one of `pids`.
3557
+ *
3558
+ * Exists for the GC analyzer, which attributes samples to `OS_GC_Thread`.
3559
+ * Ordering is by `thread_id` so the result is byte-stable (D5); an empty
3560
+ * `pids` or an absent `perf_thread` table returns `[]`.
3561
+ */
3562
+ threadIdsNamed(pids, threadName) {
3563
+ if (pids.length === 0 || !this.hasTable("perf_thread")) return [];
3564
+ return this.db.query(
3565
+ `SELECT thread_id FROM perf_thread
3566
+ WHERE process_id IN (${placeholders(pids.length)}) AND thread_name = ?
3567
+ ORDER BY thread_id`,
3568
+ [...pids, threadName]
3569
+ ).map((row) => num(row.thread_id));
3570
+ }
3571
+ /**
3572
+ * The summed weight of the samples recorded by `threadIds`.
3573
+ *
3574
+ * `perf_sample.event_count` is the sample's weight — the number of events
3575
+ * the sample stands for — not 1. Summing rows instead of this column makes
3576
+ * every share computed from it wrong by the sampling period. `threadIds`
3577
+ * omitted sums the whole database; an empty array returns 0.
3578
+ *
3579
+ * `range` restricts the sum to samples whose `timestamp_trace` falls inside
3580
+ * it, which is what a windowed share needs: summing the whole table while the
3581
+ * stacks are windowed makes the share describe a different population.
3582
+ */
3583
+ eventCount(threadIds, range) {
3584
+ if (threadIds !== void 0 && threadIds.length === 0) return 0;
3585
+ if (!this.hasTable("perf_sample")) return 0;
3586
+ const conditions = [];
3587
+ const params = [];
3588
+ if (threadIds !== void 0) {
3589
+ conditions.push(`thread_id IN (${placeholders(threadIds.length)})`);
3590
+ params.push(...threadIds);
3591
+ }
3592
+ if (range !== void 0) {
3593
+ conditions.push("timestamp_trace >= ? AND timestamp_trace <= ?");
3594
+ params.push(range.startNs, range.endNs);
3595
+ }
3596
+ const where = conditions.length === 0 ? "" : ` WHERE ${conditions.join(" AND ")}`;
3597
+ const [row] = this.db.query(
3598
+ `SELECT COALESCE(SUM(event_count), 0) AS n FROM perf_sample${where}`,
3599
+ params
3600
+ );
3601
+ return row == null ? 0 : num(row.n);
3602
+ }
3533
3603
  /**
3534
3604
  * Samples of `threadIds` whose `timestamp_trace` is in `[startNs, endNs]`.
3535
3605
  *
@@ -3584,13 +3654,85 @@ ORDER BY thread_id, callchain_id`,
3584
3654
  ...new Set(uniqueThreadIds.flatMap((id) => chainIdsByThread.get(id) ?? []))
3585
3655
  ].sort((a, b) => a - b);
3586
3656
  if (allChainIds.length === 0) return [];
3587
- if (!this.hasTable("perf_callchain") || !this.hasTable("perf_files")) return [];
3657
+ const functionsByChain = this.chainFunctions(allChainIds);
3658
+ const chains = [];
3659
+ const limit = Math.max(0, maxChainsPerThread);
3660
+ for (const threadId of uniqueThreadIds) {
3661
+ const chainIds = (chainIdsByThread.get(threadId) ?? []).slice(0, limit);
3662
+ for (const callchainId of chainIds) {
3663
+ const functions = functionsByChain.get(callchainId);
3664
+ if (functions === void 0 || functions.length === 0) continue;
3665
+ chains.push({ threadId, callchainId, functions });
3666
+ }
3667
+ }
3668
+ return chains;
3669
+ }
3670
+ /**
3671
+ * Folds every sample of `threadIds` in `range` into semicolon-joined stacks.
3672
+ *
3673
+ * Deliberately **not** built on {@link callchains}: that method caps at 50
3674
+ * chain ids and 20 chains per thread (HapRay's UI budget), which would
3675
+ * silently drop samples from an aggregate. This reads every distinct
3676
+ * `callchain_id` the samples reference and weights each by `event_count` —
3677
+ * the sample's weight, not 1 row.
3678
+ *
3679
+ * Stacks are sorted by `samples` descending then `stack` ascending, so equal
3680
+ * weights never fall back to row order, and sliced to `top` — omit `top` to
3681
+ * get every distinct stack, which is what a count of stacks needs. A chain
3682
+ * with no frames contributes nothing. An empty `threadIds`, a missing
3683
+ * `perf_callchain`/`perf_files`, or no samples in range yields `[]`.
3684
+ */
3685
+ foldedStacks(threadIds, range, top) {
3686
+ if (threadIds.length === 0 || !this.hasTable("perf_sample")) return [];
3687
+ const uniqueThreadIds = [...new Set(threadIds)];
3688
+ const samples = this.db.query(
3689
+ `SELECT callchain_id, SUM(event_count) AS weight
3690
+ FROM perf_sample
3691
+ WHERE thread_id IN (${placeholders(uniqueThreadIds.length)})
3692
+ AND timestamp_trace >= ? AND timestamp_trace <= ?
3693
+ AND callchain_id IS NOT NULL
3694
+ GROUP BY callchain_id
3695
+ ORDER BY callchain_id`,
3696
+ [...uniqueThreadIds, range.startNs, range.endNs]
3697
+ );
3698
+ const chainIds = samples.map((row) => num(row.callchain_id));
3699
+ if (chainIds.length === 0) return [];
3700
+ const functionsByChain = this.chainFunctions(chainIds);
3701
+ const weights = /* @__PURE__ */ new Map();
3702
+ for (const row of samples) {
3703
+ weights.set(num(row.callchain_id), num(row.weight));
3704
+ }
3705
+ const folded = /* @__PURE__ */ new Map();
3706
+ for (const callchainId of chainIds) {
3707
+ const functions = functionsByChain.get(callchainId);
3708
+ if (functions === void 0 || functions.length === 0) continue;
3709
+ const stack = functions.map((fn) => fn.symbol).join(";");
3710
+ folded.set(stack, (folded.get(stack) ?? 0) + (weights.get(callchainId) ?? 0));
3711
+ }
3712
+ return [...folded.entries()].map(([stack, samples2]) => ({
3713
+ stack,
3714
+ leaf: stack.slice(stack.lastIndexOf(";") + 1),
3715
+ samples: samples2
3716
+ })).sort((a, b) => a.samples !== b.samples ? b.samples - a.samples : a.stack < b.stack ? -1 : a.stack > b.stack ? 1 : 0).slice(0, top === void 0 ? void 0 : Math.max(0, top));
3717
+ }
3718
+ /**
3719
+ * Resolves each chain id to its frames, ordered by `depth`.
3720
+ *
3721
+ * Symbols resolve through `perf_files` by the exact `(file_id, serial_id)`
3722
+ * pair first and by `file_id` alone as the fallback; a frame with neither
3723
+ * keeps its raw `perf_callchain.name`. A missing `perf_callchain` or
3724
+ * `perf_files` yields an empty map (nothing can be resolved).
3725
+ */
3726
+ chainFunctions(chainIds) {
3727
+ const resolved = /* @__PURE__ */ new Map();
3728
+ if (chainIds.length === 0) return resolved;
3729
+ if (!this.hasTable("perf_callchain") || !this.hasTable("perf_files")) return resolved;
3588
3730
  const frames = this.db.query(
3589
3731
  `SELECT callchain_id, depth, file_id, symbol_id, name
3590
3732
  FROM perf_callchain
3591
- WHERE callchain_id IN (${placeholders(allChainIds.length)})
3733
+ WHERE callchain_id IN (${placeholders(chainIds.length)})
3592
3734
  ORDER BY callchain_id, depth, id`,
3593
- allChainIds
3735
+ [...chainIds]
3594
3736
  );
3595
3737
  const framesByChain = /* @__PURE__ */ new Map();
3596
3738
  for (const frame of frames) {
@@ -3613,41 +3755,34 @@ ORDER BY id`,
3613
3755
  const exactSymbols = /* @__PURE__ */ new Map();
3614
3756
  const fileSymbols = /* @__PURE__ */ new Map();
3615
3757
  for (const file of files) {
3616
- const resolved = {
3758
+ const symbol = {
3617
3759
  symbol: str(file.symbol).trim(),
3618
3760
  name: str(file.symbol).trim(),
3619
3761
  filePath: str(file.path).trim()
3620
3762
  };
3621
3763
  const fileId = num(file.file_id);
3622
- if (!fileSymbols.has(fileId)) fileSymbols.set(fileId, resolved);
3764
+ if (!fileSymbols.has(fileId)) fileSymbols.set(fileId, symbol);
3623
3765
  const key = `${fileId}:${num(file.serial_id)}`;
3624
- if (!exactSymbols.has(key)) exactSymbols.set(key, resolved);
3625
- }
3626
- const chains = [];
3627
- const limit = Math.max(0, maxChainsPerThread);
3628
- for (const threadId of uniqueThreadIds) {
3629
- const chainIds = (chainIdsByThread.get(threadId) ?? []).slice(0, limit);
3630
- for (const callchainId of chainIds) {
3631
- const chainFrames = framesByChain.get(callchainId) ?? [];
3632
- if (chainFrames.length === 0) continue;
3633
- const functions = [];
3634
- for (const frame of chainFrames) {
3635
- const rawSymbol = str(frame.name).trim();
3636
- let functionName = rawSymbol;
3637
- let filePath = "";
3638
- if (frame.file_id != null && frame.symbol_id != null) {
3639
- const resolved = exactSymbols.get(`${num(frame.file_id)}:${num(frame.symbol_id)}`) ?? fileSymbols.get(num(frame.file_id));
3640
- if (resolved) {
3641
- functionName = resolved.symbol;
3642
- filePath = resolved.filePath;
3643
- }
3766
+ if (!exactSymbols.has(key)) exactSymbols.set(key, symbol);
3767
+ }
3768
+ for (const [callchainId, chainFrames] of framesByChain) {
3769
+ const functions = [];
3770
+ for (const frame of chainFrames) {
3771
+ const rawSymbol = str(frame.name).trim();
3772
+ let functionName = rawSymbol;
3773
+ let filePath = "";
3774
+ if (frame.file_id != null && frame.symbol_id != null) {
3775
+ const match = exactSymbols.get(`${num(frame.file_id)}:${num(frame.symbol_id)}`) ?? fileSymbols.get(num(frame.file_id));
3776
+ if (match) {
3777
+ functionName = match.symbol;
3778
+ filePath = match.filePath;
3644
3779
  }
3645
- functions.push({ symbol: functionName, name: functionName, filePath });
3646
3780
  }
3647
- chains.push({ threadId, callchainId, functions });
3781
+ functions.push({ symbol: functionName, name: functionName, filePath });
3648
3782
  }
3783
+ resolved.set(callchainId, functions);
3649
3784
  }
3650
- return chains;
3785
+ return resolved;
3651
3786
  }
3652
3787
  hasTable(name) {
3653
3788
  const rows = this.db.query(
@@ -6250,7 +6385,7 @@ var FrameAnalyzer = class {
6250
6385
  const rendered = actual.filter((frame) => frame.flag !== 2);
6251
6386
  const empty = actual.filter((frame) => frame.flag === 2);
6252
6387
  const stuttered = rendered.filter((frame) => frame.flag === 1);
6253
- const noData = actual.length === 0 ? noDataEvidence(ctx, expect.length, frames.length) : void 0;
6388
+ const noData2 = actual.length === 0 ? noDataEvidence(ctx, expect.length, frames.length) : void 0;
6254
6389
  const first = actual[0];
6255
6390
  const last = actual[actual.length - 1];
6256
6391
  const spanNs = first && last ? last.ts + last.dur - first.ts : 0;
@@ -6314,7 +6449,7 @@ var FrameAnalyzer = class {
6314
6449
  const name = processNames?.get(frame.ipid) ?? "";
6315
6450
  return jankEvidence(frame, name === "" ? `ipid:${frame.ipid}` : name, originNs);
6316
6451
  });
6317
- if (noData !== void 0) evidenceItems.push(noData);
6452
+ if (noData2 !== void 0) evidenceItems.push(noData2);
6318
6453
  metrics.sort(byMetricId4);
6319
6454
  evidenceItems.sort(byEvidenceOrder4);
6320
6455
  return { metrics, evidence: evidenceItems };
@@ -7007,17 +7142,20 @@ var MemoryAnalyzer = class {
7007
7142
  }
7008
7143
  };
7009
7144
 
7010
- // src/analyze/mem-measure.ts
7011
- var RSS_FILTER = "mem.rss";
7012
- var BYTES_PER_KIB = 1024;
7013
- function appProcessName5(ctx) {
7014
- return ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
7145
+ // src/analyze/context.ts
7146
+ function resolveAppIdentity(processes, packageName) {
7147
+ const process2 = processes.byName(packageName);
7148
+ return {
7149
+ packageName,
7150
+ pids: process2 === void 0 ? [] : [process2.pid],
7151
+ processNames: [packageName]
7152
+ };
7015
7153
  }
7016
- function appIpids(ctx) {
7154
+ function resolveAppIpids(processes, pids) {
7017
7155
  const ipids = [];
7018
7156
  const seen = /* @__PURE__ */ new Set();
7019
- for (const pid of ctx.app.pids) {
7020
- const ipid = ctx.processes.byPid(pid)?.ipid;
7157
+ for (const pid of pids) {
7158
+ const ipid = processes.byPid(pid)?.ipid;
7021
7159
  if (ipid === void 0 || !Number.isInteger(ipid) || ipid <= 0) continue;
7022
7160
  if (seen.has(ipid)) continue;
7023
7161
  seen.add(ipid);
@@ -7025,6 +7163,16 @@ function appIpids(ctx) {
7025
7163
  }
7026
7164
  return ipids;
7027
7165
  }
7166
+
7167
+ // src/analyze/mem-measure.ts
7168
+ var RSS_FILTER = "mem.rss";
7169
+ var BYTES_PER_KIB = 1024;
7170
+ function appProcessName5(ctx) {
7171
+ return ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
7172
+ }
7173
+ function appIpids(ctx) {
7174
+ return resolveAppIpids(ctx.processes, ctx.app.pids);
7175
+ }
7028
7176
  function degradedResult(ctx, reason) {
7029
7177
  const metrics = [
7030
7178
  metric({
@@ -7138,18 +7286,7 @@ function appProcessName6(ctx) {
7138
7286
  return ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
7139
7287
  }
7140
7288
  function appIpids2(ctx) {
7141
- const ipids = [];
7142
- const seen = /* @__PURE__ */ new Set();
7143
- for (const pid of ctx.app.pids) {
7144
- const ipid = ctx.processes.byPid(pid)?.ipid;
7145
- if (ipid === void 0 || !Number.isInteger(ipid) || ipid <= 0) {
7146
- continue;
7147
- }
7148
- if (seen.has(ipid)) continue;
7149
- seen.add(ipid);
7150
- ipids.push(ipid);
7151
- }
7152
- return ipids;
7289
+ return resolveAppIpids(ctx.processes, ctx.app.pids);
7153
7290
  }
7154
7291
  function startMarkerNs(ctx) {
7155
7292
  const startedAtNs = ctx.metadata?.startedAtNs;
@@ -7258,117 +7395,1352 @@ var StartupAnalyzer = class {
7258
7395
  }
7259
7396
  };
7260
7397
 
7261
- // src/analyze/engine.ts
7262
- function byAnalyzerId(a, b) {
7263
- if (a.id < b.id) return -1;
7264
- if (a.id > b.id) return 1;
7265
- return 0;
7266
- }
7267
- function byMetricId8(a, b) {
7268
- if (a.id < b.id) return -1;
7269
- if (a.id > b.id) return 1;
7270
- return 0;
7398
+ // src/analyze/gc.ts
7399
+ var GC_PATTERNS = [
7400
+ { pattern: "%H:FullGC::RunPhases%", key: "full" },
7401
+ { pattern: "%H:PartialGC::RunPhases%", key: "partial" },
7402
+ { pattern: "%H:SharedFullGC::RunPhases%", key: "sharedFull" },
7403
+ { pattern: "%H:SharedGC::RunPhases%", key: "shared" }
7404
+ ];
7405
+ var MAX_INVOCATIONS = 10;
7406
+ var MAX_PERF_SHARE_PCT = 15;
7407
+ var GC_THREAD_NAME = "OS_GC_Thread";
7408
+ function computeGc(db, opts) {
7409
+ const counts = { full: 0, partial: 0, sharedFull: 0, shared: 0 };
7410
+ for (const { pattern, key } of GC_PATTERNS) {
7411
+ counts[key] = countMatches(db, pattern, opts.ipids);
7412
+ }
7413
+ const invocations = counts.full + counts.partial + counts.sharedFull + counts.shared;
7414
+ const spanNs = callstackSpan(db);
7415
+ const spanSeconds = spanNs / 1e9;
7416
+ const rate = spanSeconds > 0 ? invocations / spanSeconds : 0;
7417
+ return {
7418
+ ...counts,
7419
+ invocations,
7420
+ spanNs,
7421
+ rate,
7422
+ tooMany: invocations > spanSeconds && invocations > MAX_INVOCATIONS
7423
+ };
7271
7424
  }
7272
- function byEvidenceOrder7(a, b) {
7273
- if (a.kind < b.kind) return -1;
7274
- if (a.kind > b.kind) return 1;
7275
- if (a.window.startNs < b.window.startNs) return -1;
7276
- if (a.window.startNs > b.window.startNs) return 1;
7277
- if (a.id < b.id) return -1;
7278
- if (a.id > b.id) return 1;
7279
- return 0;
7425
+ function countMatches(db, pattern, ipids) {
7426
+ if (ipids.length === 0) return 0;
7427
+ const [row] = db.query(
7428
+ `SELECT COUNT(*) AS n FROM callstack
7429
+ WHERE name LIKE ?
7430
+ AND callid IN (SELECT id FROM thread WHERE ipid IN (${ipids.map(() => "?").join(", ")}))`,
7431
+ [pattern, ...ipids]
7432
+ );
7433
+ return row?.n == null ? 0 : Number(row.n);
7280
7434
  }
7281
- function degradedReason(missing) {
7282
- const ids = missing.map((state) => state.id).join(", ");
7283
- const reasons = missing.map((state) => state.reason ?? "unavailable").join("; ");
7284
- return `missing ${ids}: ${reasons}`;
7435
+ function callstackSpan(db) {
7436
+ const [row] = db.query(
7437
+ "SELECT MIN(ts) AS s, MAX(ts) AS e FROM callstack"
7438
+ );
7439
+ if (row?.s == null || row.e == null) return 0;
7440
+ return Number(row.e) - Number(row.s);
7285
7441
  }
7286
- function degradedMetric(analyzer, ctx, missing) {
7287
- return metric({
7288
- id: `${analyzer.id}.degraded`,
7289
- value: 0,
7290
- unit: "count",
7291
- fidelity: "proxy",
7292
- degraded: { reason: degradedReason(missing), fallback: "analyzer skipped" },
7293
- provenance: { collector: "capability-matrix", device: ctx.deviceId }
7294
- });
7442
+ function appProcessName7(ctx) {
7443
+ return ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
7295
7444
  }
7296
- function degradedEvidence(analyzer, ctx, missing) {
7297
- const ids = missing.map((state) => state.id);
7298
- const process2 = ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
7299
- return evidence({
7300
- kind: "degraded_capability",
7301
- severity: "warn",
7302
- subject: { process: process2 },
7303
- window: ctx.window,
7304
- signals: { missing: ids.join(",") },
7305
- explain: `${analyzer.id} skipped: ${degradedReason(missing)}`,
7306
- drillDown: [
7307
- {
7308
- label: "Capability matrix",
7309
- tool: "caps.get",
7310
- args: { ids },
7311
- returns: "CapabilityState[]",
7312
- estRows: ids.length
7313
- }
7445
+ function degradedResult2(ctx, reason) {
7446
+ return {
7447
+ metrics: [
7448
+ metric({
7449
+ id: "gc.degraded",
7450
+ value: 0,
7451
+ unit: "count",
7452
+ fidelity: "proxy",
7453
+ degraded: { reason, fallback: "no GC measurement" },
7454
+ provenance: { collector: "hitrace", device: ctx.deviceId }
7455
+ })
7314
7456
  ],
7315
- key: analyzer.id
7316
- });
7457
+ evidence: [
7458
+ evidence({
7459
+ kind: "no_data",
7460
+ severity: "info",
7461
+ subject: { process: appProcessName7(ctx) },
7462
+ window: ctx.window,
7463
+ signals: {},
7464
+ explain: reason,
7465
+ drillDown: [],
7466
+ key: "gc:no-data"
7467
+ })
7468
+ ]
7469
+ };
7317
7470
  }
7318
- async function runAnalyzers(analyzers, ctx) {
7319
- const ordered = [...analyzers].sort(byAnalyzerId);
7320
- const metrics = [];
7321
- const evidenceItems = [];
7322
- for (const analyzer of ordered) {
7323
- const check = ctx.caps.satisfies(analyzer.requires);
7324
- if (!check.ok) {
7325
- metrics.push(degradedMetric(analyzer, ctx, check.missing));
7326
- evidenceItems.push(degradedEvidence(analyzer, ctx, check.missing));
7327
- continue;
7471
+ function share(part, total) {
7472
+ return total > 0 ? part / total * 100 : 0;
7473
+ }
7474
+ function fmtRate(rate) {
7475
+ return rate.toFixed(2);
7476
+ }
7477
+ function fmtSpan(spanNs) {
7478
+ return (spanNs / 1e9).toFixed(2);
7479
+ }
7480
+ var GcAnalyzer = class {
7481
+ id = "gc";
7482
+ requires = ["trace.ark"];
7483
+ async run(ctx) {
7484
+ if (ctx.db === void 0) {
7485
+ return degradedResult2(ctx, "the trace database handle is not available");
7328
7486
  }
7329
- const result = await analyzer.run(ctx);
7330
- metrics.push(...result.metrics);
7331
- evidenceItems.push(...result.evidence);
7487
+ const ipids = resolveAppIpids(ctx.processes, ctx.app.pids);
7488
+ if (ipids.length === 0) {
7489
+ return degradedResult2(
7490
+ ctx,
7491
+ "no app process was identified in this trace, so GC events cannot be attributed"
7492
+ );
7493
+ }
7494
+ const signals = computeGc(ctx.db, { ipids });
7495
+ const metrics = [
7496
+ metric({
7497
+ id: "gc.full.count",
7498
+ value: signals.full,
7499
+ unit: "count",
7500
+ provenance: { collector: "hitrace", table: "callstack", rows: signals.invocations, device: ctx.deviceId },
7501
+ fidelity: "exact",
7502
+ window: ctx.window
7503
+ }),
7504
+ metric({
7505
+ id: "gc.invocations.count",
7506
+ value: signals.invocations,
7507
+ unit: "count",
7508
+ provenance: { collector: "hitrace", table: "callstack", rows: signals.invocations, device: ctx.deviceId },
7509
+ fidelity: "exact",
7510
+ window: ctx.window
7511
+ }),
7512
+ metric({
7513
+ id: "gc.partial.count",
7514
+ value: signals.partial,
7515
+ unit: "count",
7516
+ provenance: { collector: "hitrace", table: "callstack", rows: signals.invocations, device: ctx.deviceId },
7517
+ fidelity: "exact",
7518
+ window: ctx.window
7519
+ }),
7520
+ metric({
7521
+ id: "gc.shared.count",
7522
+ value: signals.shared,
7523
+ unit: "count",
7524
+ provenance: { collector: "hitrace", table: "callstack", rows: signals.invocations, device: ctx.deviceId },
7525
+ fidelity: "exact",
7526
+ window: ctx.window
7527
+ }),
7528
+ metric({
7529
+ id: "gc.shared_full.count",
7530
+ value: signals.sharedFull,
7531
+ unit: "count",
7532
+ provenance: { collector: "hitrace", table: "callstack", rows: signals.invocations, device: ctx.deviceId },
7533
+ fidelity: "exact",
7534
+ window: ctx.window
7535
+ })
7536
+ ];
7537
+ if (signals.spanNs > 0) {
7538
+ metrics.push(
7539
+ metric({
7540
+ id: "gc.rate",
7541
+ value: signals.rate,
7542
+ unit: "none",
7543
+ provenance: { collector: "hitrace", table: "callstack", device: ctx.deviceId },
7544
+ fidelity: "exact",
7545
+ window: ctx.window
7546
+ })
7547
+ );
7548
+ }
7549
+ const perf = this.perfShare(ctx);
7550
+ metrics.push(perf.metric);
7551
+ return {
7552
+ metrics,
7553
+ evidence: [this.pressureEvidence(ctx, signals, perf.sharePct)]
7554
+ };
7332
7555
  }
7333
- metrics.sort(byMetricId8);
7334
- for (let i = 1; i < metrics.length; i++) {
7335
- if (metrics[i].id === metrics[i - 1].id) {
7336
- throw new OhosPerfError("DUPLICATE_METRIC_ID", { code: "DUPLICATE_METRIC_ID" });
7556
+ /**
7557
+ * `gc.perf.share` plus the number behind it, or a degraded proxy and
7558
+ * `undefined`.
7559
+ *
7560
+ * HapRay computes the share over the app's own perf threads, so the
7561
+ * denominator is the app's sample weight — not the device's. The caller
7562
+ * needs the number, not just the metric: HapRay's second pressure clause is
7563
+ * `perf_percentage > 0.15`.
7564
+ */
7565
+ perfShare(ctx) {
7566
+ const degraded = (reason) => ({
7567
+ metric: metric({
7568
+ id: "gc.perf.degraded",
7569
+ value: 0,
7570
+ unit: "%",
7571
+ fidelity: "proxy",
7572
+ degraded: { reason, fallback: "no GC perf share" },
7573
+ provenance: { collector: "hiperf", table: "perf_sample", device: ctx.deviceId },
7574
+ window: ctx.window
7575
+ }),
7576
+ sharePct: void 0
7577
+ });
7578
+ const perf = ctx.perf;
7579
+ if (perf === void 0) {
7580
+ return degraded("no perf database was provided, so the GC perf share cannot be measured");
7337
7581
  }
7582
+ if (!perf.hasSamples()) {
7583
+ return degraded(
7584
+ "perf_sample holds no samples (capture with --hiperf on a debuggable app to measure the GC perf share)"
7585
+ );
7586
+ }
7587
+ const appThreadIds = perf.threads([...ctx.app.pids]).map((thread) => thread.threadId);
7588
+ if (appThreadIds.length === 0) {
7589
+ return degraded("perf_thread has no threads for the app, so the GC perf share cannot be measured");
7590
+ }
7591
+ const total = perf.eventCount(appThreadIds, ctx.window);
7592
+ if (total === 0) {
7593
+ return degraded("the app perf threads carry no samples, so the GC perf share cannot be measured");
7594
+ }
7595
+ const gcThreadIds = perf.threadIdsNamed([...ctx.app.pids], GC_THREAD_NAME);
7596
+ if (gcThreadIds.length === 0) {
7597
+ return degraded(
7598
+ `perf_thread has no ${GC_THREAD_NAME} for the app, so the GC perf share cannot be measured`
7599
+ );
7600
+ }
7601
+ const gcSamples = perf.eventCount(gcThreadIds, ctx.window);
7602
+ const value = share(gcSamples, total);
7603
+ return {
7604
+ metric: metric({
7605
+ id: "gc.perf.share",
7606
+ value,
7607
+ unit: "%",
7608
+ fidelity: "exact",
7609
+ provenance: { collector: "hiperf", table: "perf_sample", rows: gcSamples, device: ctx.deviceId },
7610
+ window: ctx.window
7611
+ }),
7612
+ sharePct: value
7613
+ };
7338
7614
  }
7339
- evidenceItems.sort(byEvidenceOrder7);
7340
- for (let i = 1; i < evidenceItems.length; i++) {
7341
- if (evidenceItems[i].id === evidenceItems[i - 1].id) {
7342
- throw new OhosPerfError("DUPLICATE_EVIDENCE_ID", {
7343
- code: "DUPLICATE_EVIDENCE_ID"
7344
- });
7615
+ pressureEvidence(ctx, signals, sharePct) {
7616
+ const shareFires = sharePct !== void 0 && sharePct > MAX_PERF_SHARE_PCT;
7617
+ const pressure = signals.tooMany || shareFires;
7618
+ const thresholds = `> ${MAX_INVOCATIONS} invocations and > 1/s (${fmtRate(signals.rate)}/s over ${fmtSpan(signals.spanNs)}s)`;
7619
+ const countClause = `the app invoked GC ${signals.invocations} times, ${thresholds}`;
7620
+ const shareClause = sharePct === void 0 ? "the GC perf share was not measured" : `the GC thread's perf share is ${fmtRate(sharePct)}% of the app's samples (threshold > ${MAX_PERF_SHARE_PCT}%)`;
7621
+ let explain;
7622
+ if (pressure) {
7623
+ const fired = shareFires && !signals.tooMany ? `the GC thread's perf share is ${fmtRate(sharePct)}% of the app's samples, above ${MAX_PERF_SHARE_PCT}%` : shareFires ? `${countClause} and ${shareClause}` : countClause;
7624
+ explain = `${fired}: GC pressure is high`;
7625
+ } else if (signals.tooMany) {
7626
+ explain = `${countClause}: GC pressure is high`;
7627
+ } else {
7628
+ explain = `the app invoked GC ${signals.invocations} times over ${fmtSpan(signals.spanNs)}s (${fmtRate(signals.rate)}/s), below ${thresholds}; ${shareClause}`;
7345
7629
  }
7630
+ return evidence({
7631
+ kind: "gc_pressure",
7632
+ severity: pressure ? "warn" : "info",
7633
+ subject: { process: appProcessName7(ctx) },
7634
+ window: ctx.window,
7635
+ signals: {
7636
+ full: signals.full,
7637
+ partial: signals.partial,
7638
+ shared: signals.shared,
7639
+ sharedFull: signals.sharedFull,
7640
+ invocations: signals.invocations,
7641
+ rate: Number(fmtRate(signals.rate)),
7642
+ spanSeconds: Number(fmtSpan(signals.spanNs)),
7643
+ // Percent, matching the `gc.perf.share` metric's unit, and only when
7644
+ // the share was actually measured.
7645
+ ...sharePct === void 0 ? {} : { perfSharePct: sharePct },
7646
+ perfShareThresholdPct: MAX_PERF_SHARE_PCT
7647
+ },
7648
+ explain,
7649
+ // No `estRows`: `callstack.matching` has no ipid argument, so it returns
7650
+ // every process's matches, not the app's count. Promising the app's count
7651
+ // would understate the rows a caller actually gets back.
7652
+ drillDown: GC_PATTERNS.map(({ pattern, key }) => ({
7653
+ label: `${key} GC phases`,
7654
+ tool: "callstack.matching",
7655
+ args: { pattern, startNs: ctx.window.startNs, endNs: ctx.window.endNs },
7656
+ returns: "CallstackEvent[]"
7657
+ }))
7658
+ });
7346
7659
  }
7347
- return { metrics, evidence: evidenceItems };
7348
- }
7349
- function defaultAnalyzers() {
7350
- return [
7351
- new FrameAnalyzer(),
7352
- new FaultTreeAnalyzer(),
7353
- new BinderAnalyzer(),
7354
- new ThreadAnalyzer(),
7355
- new MemoryAnalyzer(),
7356
- new MemoryMeasureAnalyzer(),
7357
- new StartupAnalyzer(),
7358
- new RenderAnalyzer()
7359
- ];
7360
- }
7660
+ };
7361
7661
 
7362
- // src/analyze/context.ts
7363
- function resolveAppIdentity(processes, packageName) {
7364
- const process2 = processes.byName(packageName);
7662
+ // src/analyze/components.ts
7663
+ var BUILD_ITEM_PATTERN = /^H:CustomNode:BuildItem\s*\[([^\]]*)\]/;
7664
+ var RECYCLE_PREFIX = "H:CustomNode:BuildRecycle";
7665
+ var BUILD_LIKE = "%H:CustomNode:Build%";
7666
+ function round2HalfEven(value) {
7667
+ if (!Number.isFinite(value)) return value;
7668
+ const negative = value < 0;
7669
+ const { mantissa, exponent } = decompose(Math.abs(value));
7670
+ const scaled = mantissa * 100n;
7671
+ let rounded;
7672
+ if (exponent >= 0) {
7673
+ rounded = scaled << BigInt(exponent);
7674
+ } else {
7675
+ const denominator = 1n << BigInt(-exponent);
7676
+ const quotient = scaled / denominator;
7677
+ const remainder = scaled % denominator;
7678
+ const doubled = remainder * 2n;
7679
+ if (doubled > denominator) rounded = quotient + 1n;
7680
+ else if (doubled < denominator) rounded = quotient;
7681
+ else rounded = quotient % 2n === 0n ? quotient : quotient + 1n;
7682
+ }
7683
+ const result = Number(rounded) / 100;
7684
+ return negative ? -result : result;
7685
+ }
7686
+ function decompose(value) {
7687
+ const view = new DataView(new ArrayBuffer(8));
7688
+ view.setFloat64(0, value);
7689
+ const high = view.getUint32(0);
7690
+ const low = view.getUint32(4);
7691
+ const exponentBits = high >>> 20 & 2047;
7692
+ let mantissa = BigInt(high & 1048575) << 32n | BigInt(low);
7693
+ if (exponentBits === 0) return { mantissa, exponent: -1074 };
7694
+ mantissa |= 1n << 52n;
7695
+ return { mantissa, exponent: exponentBits - 1075 };
7696
+ }
7697
+ function componentName(name) {
7698
+ const match = BUILD_ITEM_PATTERN.exec(name);
7699
+ if (match) return match[1];
7700
+ if (name.startsWith(RECYCLE_PREFIX)) {
7701
+ const token = name.split(" ")[1];
7702
+ return token === void 0 ? "Unknown" : token;
7703
+ }
7704
+ return "Unknown";
7705
+ }
7706
+ function computeComponentReuse(db, opts) {
7707
+ const scope = opts.ipids.length === 0 ? "" : ` AND callid IN (SELECT id FROM thread WHERE ipid IN (${opts.ipids.map(() => "?").join(", ")}))`;
7708
+ const rows = db.query(
7709
+ `SELECT name FROM callstack WHERE name LIKE ?${scope} ORDER BY ts, id`,
7710
+ [BUILD_LIKE, ...opts.ipids]
7711
+ );
7712
+ const counts = /* @__PURE__ */ new Map();
7713
+ for (const row of rows) {
7714
+ const name = row.name ?? "";
7715
+ const component = componentName(name);
7716
+ const entry = counts.get(component);
7717
+ if (entry === void 0) counts.set(component, [1, name.startsWith(RECYCLE_PREFIX) ? 1 : 0]);
7718
+ else {
7719
+ entry[0] += 1;
7720
+ if (name.startsWith(RECYCLE_PREFIX)) entry[1] += 1;
7721
+ }
7722
+ }
7723
+ let maxComponent = "";
7724
+ let totalBuilds = 0;
7725
+ let recycledBuilds = 0;
7726
+ for (const [component, [builds, recycled]] of counts) {
7727
+ if (builds > totalBuilds) {
7728
+ maxComponent = component;
7729
+ totalBuilds = builds;
7730
+ recycledBuilds = recycled;
7731
+ }
7732
+ }
7365
7733
  return {
7366
- packageName,
7367
- pids: process2 === void 0 ? [] : [process2.pid],
7368
- processNames: [packageName]
7734
+ max_component: maxComponent,
7735
+ total_builds: totalBuilds,
7736
+ recycled_builds: recycledBuilds,
7737
+ reusability_ratio: totalBuilds > 0 ? round2HalfEven(recycledBuilds / totalBuilds) : 0,
7738
+ details: Object.fromEntries(counts)
7739
+ };
7740
+ }
7741
+ function byMetricId8(a, b) {
7742
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
7743
+ }
7744
+ var ComponentReuseAnalyzer = class {
7745
+ id = "components";
7746
+ requires = ["trace.ark"];
7747
+ async run(ctx) {
7748
+ if (ctx.db === void 0) {
7749
+ return {
7750
+ metrics: [
7751
+ metric({
7752
+ id: "components.degraded",
7753
+ value: 0,
7754
+ unit: "count",
7755
+ fidelity: "proxy",
7756
+ degraded: {
7757
+ reason: "the trace database handle is not available",
7758
+ fallback: "no component measurement"
7759
+ },
7760
+ provenance: { collector: "hitrace", device: ctx.deviceId }
7761
+ })
7762
+ ],
7763
+ evidence: []
7764
+ };
7765
+ }
7766
+ const ipids = resolveAppIpids(ctx.processes, ctx.app.pids);
7767
+ if (ipids.length === 0) {
7768
+ return {
7769
+ metrics: [
7770
+ metric({
7771
+ id: "components.degraded",
7772
+ value: 0,
7773
+ unit: "count",
7774
+ fidelity: "proxy",
7775
+ degraded: {
7776
+ reason: "no app process was identified in this trace, so component builds cannot be attributed",
7777
+ fallback: "no component measurement"
7778
+ },
7779
+ provenance: { collector: "hitrace", device: ctx.deviceId }
7780
+ })
7781
+ ],
7782
+ evidence: []
7783
+ };
7784
+ }
7785
+ const result = computeComponentReuse(ctx.db, { ipids });
7786
+ const prov = {
7787
+ collector: "hitrace",
7788
+ table: "callstack",
7789
+ rows: result.total_builds,
7790
+ device: ctx.deviceId
7791
+ };
7792
+ const metrics = [
7793
+ metric({
7794
+ id: "components.builds.count",
7795
+ value: result.total_builds,
7796
+ unit: "count",
7797
+ provenance: prov,
7798
+ fidelity: "exact",
7799
+ window: ctx.window
7800
+ }),
7801
+ metric({
7802
+ id: "components.recycled.count",
7803
+ value: result.recycled_builds,
7804
+ unit: "count",
7805
+ provenance: prov,
7806
+ fidelity: "exact",
7807
+ window: ctx.window
7808
+ })
7809
+ ];
7810
+ if (result.total_builds > 0) {
7811
+ metrics.push(
7812
+ metric({
7813
+ id: "components.reuse.rate",
7814
+ value: round2HalfEven(result.reusability_ratio * 100),
7815
+ unit: "%",
7816
+ provenance: prov,
7817
+ fidelity: "exact",
7818
+ window: ctx.window
7819
+ }),
7820
+ metric({
7821
+ id: "components.top.name",
7822
+ value: result.max_component,
7823
+ unit: "none",
7824
+ provenance: prov,
7825
+ fidelity: "exact",
7826
+ window: ctx.window
7827
+ })
7828
+ );
7829
+ }
7830
+ metrics.sort(byMetricId8);
7831
+ return { metrics, evidence: [] };
7832
+ }
7833
+ };
7834
+
7835
+ // src/analyze/vsync.ts
7836
+ var NORMAL_MIN_NS = 8.33 * 1e6;
7837
+ var NORMAL_MAX_NS = 33.3 * 1e6;
7838
+ var MIN_PERIOD_INTERVALS = 3;
7839
+ function round22(value) {
7840
+ return round2HalfEven(value);
7841
+ }
7842
+ function groupByVsync(frames) {
7843
+ const groups = /* @__PURE__ */ new Map();
7844
+ for (const frame of frames) {
7845
+ if (!Number.isFinite(frame.vsync) || frame.vsync <= 0) continue;
7846
+ const group = groups.get(frame.vsync);
7847
+ if (group === void 0) {
7848
+ groups.set(frame.vsync, {
7849
+ vsync: frame.vsync,
7850
+ minTs: frame.ts,
7851
+ actual: frame.type === 0 ? 1 : 0,
7852
+ expect: frame.type === 1 ? 1 : 0
7853
+ });
7854
+ continue;
7855
+ }
7856
+ group.minTs = Math.min(group.minTs, frame.ts);
7857
+ if (frame.type === 0) group.actual += 1;
7858
+ else if (frame.type === 1) group.expect += 1;
7859
+ }
7860
+ return [...groups.values()].sort((a, b) => a.minTs !== b.minTs ? a.minTs - b.minTs : a.vsync - b.vsync);
7861
+ }
7862
+ function intervalsOf(groups) {
7863
+ const intervals = [];
7864
+ for (let i = 1; i < groups.length; i++) {
7865
+ const previous = groups[i - 1];
7866
+ const current = groups[i];
7867
+ intervals.push({
7868
+ prevVsync: previous.vsync,
7869
+ vsync: current.vsync,
7870
+ ns: current.minTs - previous.minTs,
7871
+ startNs: previous.minTs
7872
+ });
7873
+ }
7874
+ return intervals;
7875
+ }
7876
+ function highSeverity(avgHz, durationMs) {
7877
+ if (avgHz > 200 || durationMs > 100) return "high";
7878
+ if (avgHz > 150 || durationMs > 50) return "medium";
7879
+ return "low";
7880
+ }
7881
+ function lowSeverity(avgHz, durationMs) {
7882
+ if (avgHz < 15 || durationMs > 200) return "high";
7883
+ if (avgHz < 20 || durationMs > 100) return "medium";
7884
+ return "low";
7885
+ }
7886
+ function findPeriods(intervals, kind) {
7887
+ const high = kind === "high_frequency";
7888
+ const periods = [];
7889
+ let run;
7890
+ const flush = () => {
7891
+ if (run === void 0 || run.count < MIN_PERIOD_INTERVALS) {
7892
+ run = void 0;
7893
+ return;
7894
+ }
7895
+ const avgIntervalNs = run.total / run.count;
7896
+ const avgFrequencyHz = 1e9 / avgIntervalNs;
7897
+ const startNs = run.start.startNs;
7898
+ const endNs = run.end.startNs + run.end.ns;
7899
+ const durationMs = (endNs - startNs) / 1e6;
7900
+ periods.push({
7901
+ kind,
7902
+ startVsync: run.start.prevVsync,
7903
+ endVsync: run.end.vsync,
7904
+ startNs,
7905
+ endNs,
7906
+ intervalCount: run.count,
7907
+ avgIntervalNs,
7908
+ avgFrequencyHz,
7909
+ severity: high ? highSeverity(avgFrequencyHz, durationMs) : lowSeverity(avgFrequencyHz, durationMs)
7910
+ });
7911
+ run = void 0;
7912
+ };
7913
+ for (const interval of intervals) {
7914
+ const anomalous = high ? interval.ns < NORMAL_MIN_NS : interval.ns > NORMAL_MAX_NS;
7915
+ if (anomalous) {
7916
+ if (run === void 0) {
7917
+ run = { start: interval, end: interval, total: interval.ns, count: 1 };
7918
+ } else {
7919
+ run.end = interval;
7920
+ run.total += interval.ns;
7921
+ run.count += 1;
7922
+ }
7923
+ continue;
7924
+ }
7925
+ flush();
7926
+ }
7927
+ flush();
7928
+ return periods;
7929
+ }
7930
+ function computeVsyncAnomalies(frames) {
7931
+ const groups = groupByVsync(frames);
7932
+ const signals = groups.length;
7933
+ if (signals === 0) return { signals: 0, mismatches: 0, periods: [], anomalyRate: 0 };
7934
+ const intervals = intervalsOf(groups);
7935
+ const periods = [
7936
+ ...findPeriods(intervals, "high_frequency"),
7937
+ ...findPeriods(intervals, "low_frequency")
7938
+ ];
7939
+ let mismatches = 0;
7940
+ for (const group of groups) {
7941
+ if (group.actual === 0) mismatches += 1;
7942
+ if (group.expect === 0) mismatches += 1;
7943
+ }
7944
+ return {
7945
+ signals,
7946
+ mismatches,
7947
+ periods,
7948
+ anomalyRate: round22((periods.length + mismatches) / signals * 100)
7949
+ };
7950
+ }
7951
+ function appProcessName8(ctx) {
7952
+ return ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
7953
+ }
7954
+ function evidenceSeverity(severity) {
7955
+ if (severity === "high") return "critical";
7956
+ if (severity === "medium") return "warn";
7957
+ return "info";
7958
+ }
7959
+ var VsyncAnalyzer = class {
7960
+ id = "vsync";
7961
+ requires = ["render.vsync"];
7962
+ async run(ctx) {
7963
+ const ipids = resolveAppIpids(ctx.processes, ctx.app.pids);
7964
+ const all = ctx.frames.all(ctx.window);
7965
+ const frames = ipids.length === 0 ? [] : all.filter((frame) => ipids.includes(frame.ipid));
7966
+ if (frames.length === 0) {
7967
+ const reason = ipids.length === 0 ? "no app process was identified in this trace, so VSync cadence cannot be attributed" : "the app rendered no frames in this window, so there is no VSync cadence to analyze";
7968
+ return {
7969
+ metrics: [],
7970
+ evidence: [
7971
+ evidence({
7972
+ kind: "no_data",
7973
+ severity: "info",
7974
+ subject: { process: appProcessName8(ctx) },
7975
+ window: ctx.window,
7976
+ signals: {},
7977
+ explain: reason,
7978
+ drillDown: [],
7979
+ key: "vsync:no-frames"
7980
+ })
7981
+ ]
7982
+ };
7983
+ }
7984
+ const analysis = computeVsyncAnomalies(frames);
7985
+ const metrics = [
7986
+ metric({
7987
+ id: "vsync.anomaly.rate",
7988
+ value: analysis.anomalyRate,
7989
+ unit: "%",
7990
+ provenance: { collector: "hitrace", table: "frame_slice", rows: frames.length, device: ctx.deviceId },
7991
+ fidelity: "exact",
7992
+ window: ctx.window
7993
+ }),
7994
+ metric({
7995
+ id: "vsync.mismatch.count",
7996
+ value: analysis.mismatches,
7997
+ unit: "count",
7998
+ provenance: { collector: "hitrace", table: "frame_slice", rows: frames.length, device: ctx.deviceId },
7999
+ fidelity: "exact",
8000
+ window: ctx.window
8001
+ }),
8002
+ metric({
8003
+ id: "vsync.periods.count",
8004
+ value: analysis.periods.length,
8005
+ unit: "count",
8006
+ provenance: { collector: "hitrace", table: "frame_slice", rows: frames.length, device: ctx.deviceId },
8007
+ fidelity: "exact",
8008
+ window: ctx.window
8009
+ }),
8010
+ metric({
8011
+ id: "vsync.signals.count",
8012
+ value: analysis.signals,
8013
+ unit: "count",
8014
+ provenance: { collector: "hitrace", table: "frame_slice", rows: frames.length, device: ctx.deviceId },
8015
+ fidelity: "exact",
8016
+ window: ctx.window
8017
+ })
8018
+ ];
8019
+ const process2 = appProcessName8(ctx);
8020
+ const items = analysis.periods.map((period) => evidence({
8021
+ kind: "vsync_anomaly",
8022
+ severity: evidenceSeverity(period.severity),
8023
+ subject: { process: process2 },
8024
+ window: { startNs: period.startNs, endNs: period.endNs },
8025
+ signals: {
8026
+ kind: period.kind,
8027
+ intervalCount: period.intervalCount,
8028
+ avgFrequencyHz: round22(period.avgFrequencyHz),
8029
+ startVsync: period.startVsync,
8030
+ endVsync: period.endVsync,
8031
+ severity: period.severity
8032
+ },
8033
+ explain: explainPeriod(period),
8034
+ drillDown: [
8035
+ {
8036
+ label: "Frames in the period",
8037
+ tool: "frames.all",
8038
+ args: { window: { startNs: period.startNs, endNs: period.endNs } },
8039
+ returns: "Frame[]",
8040
+ estRows: period.intervalCount + 1
8041
+ }
8042
+ ]
8043
+ }));
8044
+ return { metrics, evidence: items };
8045
+ }
8046
+ };
8047
+ function explainPeriod(period) {
8048
+ const label = period.kind === "high_frequency" ? "high" : "low";
8049
+ const durationMs = (period.endNs - period.startNs) / 1e6;
8050
+ return `${label}-frequency VSync period: ${period.intervalCount} intervals, ${period.avgFrequencyHz.toFixed(1)}Hz average, ${durationMs.toFixed(1)}ms long (vsync ${period.startVsync}..${period.endVsync}, severity ${period.severity})`;
8051
+ }
8052
+
8053
+ // src/analyze/empty-frame.ts
8054
+ var BUFFER_PATTERNS = [
8055
+ "%RequestBuffer%",
8056
+ "%FlushBuffer%",
8057
+ "%DoFlushBuffer%",
8058
+ "%NativeWindow%"
8059
+ ];
8060
+ var SYSTEM_PROCESSES = ["render_service", "rmrenderservice", "ohos.sceneboard"];
8061
+ function ruleOneFrames(db, frames) {
8062
+ const windows = frames.filter((frame) => frame.dur > 0);
8063
+ if (windows.length === 0) return /* @__PURE__ */ new Set();
8064
+ const minTs = Math.min(...windows.map((frame) => frame.ts));
8065
+ const maxTs = Math.max(...windows.map((frame) => frame.ts + frame.dur));
8066
+ const patterns = BUFFER_PATTERNS.map(() => "c.name LIKE ?").join(" OR ");
8067
+ const exclusions = SYSTEM_PROCESSES.map(() => "?").join(", ");
8068
+ const rows = db.query(
8069
+ `SELECT c.callid AS itid, c.ts AS ts
8070
+ FROM callstack c
8071
+ JOIN thread t ON c.callid = t.id
8072
+ JOIN process p ON t.ipid = p.ipid
8073
+ WHERE c.ts >= ? AND c.ts <= ?
8074
+ AND p.name NOT IN (${exclusions})
8075
+ AND p.name NOT LIKE 'system_%'
8076
+ AND p.name NOT LIKE 'com.ohos.%'
8077
+ AND (${patterns})
8078
+ ORDER BY c.ts`,
8079
+ [minTs, maxTs, ...SYSTEM_PROCESSES, ...BUFFER_PATTERNS]
8080
+ );
8081
+ const byThread = /* @__PURE__ */ new Map();
8082
+ for (const row of rows) {
8083
+ if (row.itid === null || row.ts === null) continue;
8084
+ const list = byThread.get(row.itid);
8085
+ if (list === void 0) byThread.set(row.itid, [row.ts]);
8086
+ else list.push(row.ts);
8087
+ }
8088
+ const dropped = /* @__PURE__ */ new Set();
8089
+ for (const frame of windows) {
8090
+ const timestamps = byThread.get(frame.itid);
8091
+ if (timestamps === void 0) continue;
8092
+ const end = frame.ts + frame.dur;
8093
+ let low = 0;
8094
+ let high = timestamps.length;
8095
+ while (low < high) {
8096
+ const mid = low + high >>> 1;
8097
+ if (timestamps[mid] < frame.ts) low = mid + 1;
8098
+ else high = mid;
8099
+ }
8100
+ if (low < timestamps.length && timestamps[low] <= end) dropped.add(frame);
8101
+ }
8102
+ return dropped;
8103
+ }
8104
+ function ruleTwoFrames(db, frames) {
8105
+ const vsyncs = [...new Set(frames.map((frame) => frame.vsync).filter((v) => v > 0))];
8106
+ const itids = [...new Set(frames.map((frame) => frame.itid).filter((id) => id > 0))];
8107
+ if (vsyncs.length === 0 || itids.length === 0) return /* @__PURE__ */ new Set();
8108
+ const rows = db.query(
8109
+ `SELECT DISTINCT vsync, itid FROM frame_slice
8110
+ WHERE type = 0 AND flag IS NOT NULL AND flag != 2
8111
+ AND vsync IN (${vsyncs.map(() => "?").join(", ")})
8112
+ AND itid IN (${itids.map(() => "?").join(", ")})`,
8113
+ [...vsyncs, ...itids]
8114
+ );
8115
+ const drawn = new Set(
8116
+ rows.map((row) => `${row.vsync ?? ""}:${row.itid ?? ""}`)
8117
+ );
8118
+ const dropped = /* @__PURE__ */ new Set();
8119
+ for (const frame of frames) {
8120
+ if (frame.vsync <= 0) continue;
8121
+ if (drawn.has(`${frame.vsync}:${frame.itid}`)) dropped.add(frame);
8122
+ }
8123
+ return dropped;
8124
+ }
8125
+ function filterEmptyFrames(db, frames) {
8126
+ const rule1 = ruleOneFrames(db, frames);
8127
+ const rule2 = ruleTwoFrames(db, frames);
8128
+ return {
8129
+ confirmed: frames.filter((frame) => !rule1.has(frame) && !rule2.has(frame)),
8130
+ filtered: frames.filter((frame) => rule1.has(frame) || rule2.has(frame)),
8131
+ rule1: frames.filter((frame) => rule1.has(frame)),
8132
+ rule2: frames.filter((frame) => rule2.has(frame))
8133
+ };
8134
+ }
8135
+ function byMetricId9(a, b) {
8136
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
8137
+ }
8138
+ function byEvidenceOrder7(a, b) {
8139
+ if (a.kind < b.kind) return -1;
8140
+ if (a.kind > b.kind) return 1;
8141
+ if (a.window.startNs < b.window.startNs) return -1;
8142
+ if (a.window.startNs > b.window.startNs) return 1;
8143
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
8144
+ }
8145
+ function appProcessName9(ctx) {
8146
+ return ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
8147
+ }
8148
+ function degradedResult3(ctx, reason) {
8149
+ return {
8150
+ metrics: [
8151
+ metric({
8152
+ id: "empty_frame.degraded",
8153
+ value: 0,
8154
+ unit: "count",
8155
+ fidelity: "proxy",
8156
+ degraded: { reason, fallback: "no empty-frame measurement" },
8157
+ provenance: { collector: "hitrace", device: ctx.deviceId }
8158
+ })
8159
+ ],
8160
+ evidence: [
8161
+ evidence({
8162
+ kind: "no_data",
8163
+ severity: "info",
8164
+ subject: { process: appProcessName9(ctx) },
8165
+ window: ctx.window,
8166
+ signals: {},
8167
+ explain: reason,
8168
+ drillDown: [],
8169
+ key: "empty-frame:no-data"
8170
+ })
8171
+ ]
8172
+ };
8173
+ }
8174
+ var WARN_RATE = 10;
8175
+ var EmptyFrameAnalyzer = class {
8176
+ id = "empty-frame";
8177
+ requires = ["trace.frames", "trace.ark"];
8178
+ async run(ctx) {
8179
+ if (ctx.db === void 0) {
8180
+ return degradedResult3(ctx, "the trace database handle is not available");
8181
+ }
8182
+ const ipids = resolveAppIpids(ctx.processes, ctx.app.pids);
8183
+ if (ipids.length === 0) {
8184
+ return degradedResult3(
8185
+ ctx,
8186
+ "no app process was identified in this trace, so empty frames cannot be attributed"
8187
+ );
8188
+ }
8189
+ const all = ctx.frames.all(ctx.window);
8190
+ const appFrames = all.filter((frame) => ipids.includes(frame.ipid));
8191
+ const actual = appFrames.filter((frame) => frame.type === 0);
8192
+ const empties = actual.filter((frame) => frame.flag === 2);
8193
+ if (actual.length === 0) {
8194
+ return {
8195
+ metrics: [],
8196
+ evidence: [
8197
+ evidence({
8198
+ kind: "no_data",
8199
+ severity: "info",
8200
+ subject: { process: appProcessName9(ctx) },
8201
+ window: ctx.window,
8202
+ signals: {},
8203
+ explain: "the app rendered no actual frames in this window, so there is no empty-frame rate to report",
8204
+ drillDown: [
8205
+ {
8206
+ label: "All frames in window",
8207
+ tool: "frames.all",
8208
+ args: { window: ctx.window },
8209
+ returns: "Frame[]",
8210
+ estRows: all.length
8211
+ }
8212
+ ],
8213
+ key: "empty-frame:no-frames"
8214
+ })
8215
+ ]
8216
+ };
8217
+ }
8218
+ const filter = empties.length > 0 ? filterEmptyFrames(ctx.db, empties) : { confirmed: [], filtered: [], rule1: [], rule2: [] };
8219
+ const rate = filter.confirmed.length / actual.length * 100;
8220
+ const process2 = appProcessName9(ctx);
8221
+ const prov = {
8222
+ collector: "hitrace",
8223
+ table: "frame_slice",
8224
+ rows: actual.length,
8225
+ device: ctx.deviceId
8226
+ };
8227
+ const metrics = [
8228
+ metric({
8229
+ id: "empty_frame.count",
8230
+ value: filter.confirmed.length,
8231
+ unit: "count",
8232
+ provenance: prov,
8233
+ fidelity: "exact",
8234
+ window: ctx.window
8235
+ }),
8236
+ metric({
8237
+ id: "empty_frame.filtered.count",
8238
+ value: filter.filtered.length,
8239
+ unit: "count",
8240
+ provenance: prov,
8241
+ fidelity: "exact",
8242
+ window: ctx.window
8243
+ }),
8244
+ metric({
8245
+ id: "empty_frame.rate",
8246
+ value: rate,
8247
+ unit: "%",
8248
+ provenance: prov,
8249
+ fidelity: "exact",
8250
+ window: ctx.window
8251
+ })
8252
+ ];
8253
+ const filteredByGroup = /* @__PURE__ */ new Map();
8254
+ for (const frame of filter.filtered) {
8255
+ const key = `${frame.vsync}:${frame.itid}`;
8256
+ filteredByGroup.set(key, (filteredByGroup.get(key) ?? 0) + 1);
8257
+ }
8258
+ const evidenceItems = filter.confirmed.map((frame) => evidence({
8259
+ kind: "empty_frame",
8260
+ severity: rate >= WARN_RATE ? "warn" : "info",
8261
+ subject: { process: process2, frameNo: frame.id },
8262
+ // The frame's own interval: `frame_no` is 0 on every real row, so the
8263
+ // window is what makes the id unique (see `frames.ts`).
8264
+ window: { startNs: frame.ts, endNs: frame.ts + frame.dur },
8265
+ signals: {
8266
+ vsync: frame.vsync,
8267
+ filtered: filteredByGroup.get(`${frame.vsync}:${frame.itid}`) ?? 0
8268
+ },
8269
+ explain: `${process2} frame at vsync ${frame.vsync} drew nothing (flag 2, dur ${(frame.dur / 1e6).toFixed(1)}ms) and no buffer was submitted for it`,
8270
+ drillDown: [
8271
+ { label: "Frame detail", tool: "frames.get", args: { id: frame.id }, returns: "Frame" }
8272
+ ]
8273
+ }));
8274
+ metrics.sort(byMetricId9);
8275
+ evidenceItems.sort(byEvidenceOrder7);
8276
+ return { metrics, evidence: evidenceItems };
8277
+ }
8278
+ };
8279
+
8280
+ // src/analyze/rs-skip.ts
8281
+ var BUFFER_PATTERNS2 = [
8282
+ "%AcquireBuffer%",
8283
+ "%DoFlushBuffer%",
8284
+ "%ConsumeAndUpdateAllNodes%"
8285
+ ];
8286
+ var SKIP_PATTERN = "%DisplayNode skip%";
8287
+ var EVENT_LOOKBACK_NS = 5e8;
8288
+ var APP_LOOKAHEAD_NS = 1e7;
8289
+ var MAX_EVENTS = 5;
8290
+ var MAX_APP_FRAMES = 10;
8291
+ function nearest(values, anchor, before, after, limit) {
8292
+ return values.filter((value) => value >= anchor - before && value <= anchor + after).sort((a, b) => {
8293
+ const distance = Math.abs(a - anchor) - Math.abs(b - anchor);
8294
+ return distance !== 0 ? distance : a - b;
8295
+ }).slice(0, limit);
8296
+ }
8297
+ function renderServiceIpids(processes) {
8298
+ const ipids = [];
8299
+ for (const process2 of processes.all()) {
8300
+ if (process2.name === "render_service" && !ipids.includes(process2.ipid)) {
8301
+ ipids.push(process2.ipid);
8302
+ }
8303
+ }
8304
+ return ipids;
8305
+ }
8306
+ function computeRsSkip(db, opts) {
8307
+ if (opts.rsIpids.length === 0) return { frames: [], totalEvents: 0 };
8308
+ const rsMarks = opts.rsIpids.map(() => "?").join(", ");
8309
+ const rows = db.query(
8310
+ `SELECT fs.id AS frame_id, c.ts AS skip_ts
8311
+ FROM callstack c
8312
+ JOIN thread t ON c.callid = t.id
8313
+ JOIN frame_slice fs ON fs.ipid = t.ipid
8314
+ WHERE c.name LIKE ?
8315
+ AND t.ipid IN (${rsMarks})
8316
+ AND fs.type = 0
8317
+ AND fs.flag IS NOT NULL
8318
+ AND fs.ts >= ? AND fs.ts <= ?
8319
+ AND c.ts >= ? AND c.ts <= ?
8320
+ AND fs.ts <= c.ts
8321
+ AND fs.ts + COALESCE(fs.dur, 0) >= c.ts
8322
+ ORDER BY fs.ts, fs.id, c.ts`,
8323
+ [
8324
+ SKIP_PATTERN,
8325
+ ...opts.rsIpids,
8326
+ opts.window.startNs,
8327
+ opts.window.endNs,
8328
+ opts.window.startNs,
8329
+ opts.window.endNs
8330
+ ]
8331
+ );
8332
+ if (rows.length === 0) return { frames: [], totalEvents: 0 };
8333
+ const skipsByFrame = /* @__PURE__ */ new Map();
8334
+ for (const row of rows) {
8335
+ if (row.frame_id === null) continue;
8336
+ skipsByFrame.set(row.frame_id, (skipsByFrame.get(row.frame_id) ?? 0) + 1);
8337
+ }
8338
+ const rsFrames = allFrames(db, opts.window).filter(
8339
+ (frame) => frame.type === 0 && opts.rsIpids.includes(frame.ipid)
8340
+ );
8341
+ const frames = rsFrames.filter((frame) => skipsByFrame.has(frame.id)).map((frame) => ({ frame, events: skipsByFrame.get(frame.id) ?? 0 }));
8342
+ if (frames.length === 0 || opts.appIpids.length === 0) {
8343
+ return {
8344
+ frames: frames.map((entry) => ({ ...entry })),
8345
+ totalEvents: rows.length
8346
+ };
8347
+ }
8348
+ const minNs = Math.min(...frames.map((entry) => entry.frame.ts)) - EVENT_LOOKBACK_NS;
8349
+ const maxNs = Math.max(...frames.map((entry) => entry.frame.ts + entry.frame.dur));
8350
+ const bufferPatterns = BUFFER_PATTERNS2.map(() => "c.name LIKE ?").join(" OR ");
8351
+ const bufferRows = db.query(
8352
+ `SELECT c.ts AS ts
8353
+ FROM callstack c
8354
+ JOIN thread t ON c.callid = t.id
8355
+ WHERE t.ipid IN (${rsMarks})
8356
+ AND (${bufferPatterns})
8357
+ AND c.ts >= ? AND c.ts <= ?
8358
+ ORDER BY c.ts`,
8359
+ [...opts.rsIpids, ...BUFFER_PATTERNS2, minNs, maxNs]
8360
+ );
8361
+ const bufferTs = bufferRows.map((row) => row.ts).filter((ts) => ts !== null);
8362
+ const appFrames = allFrames(db, opts.window).filter(
8363
+ (frame) => frame.type === 0 && opts.appIpids.includes(frame.ipid)
8364
+ );
8365
+ const appByTs = /* @__PURE__ */ new Map();
8366
+ for (const frame of appFrames) {
8367
+ const existing = appByTs.get(frame.ts);
8368
+ if (existing === void 0 || frame.id < existing.id) appByTs.set(frame.ts, frame);
8369
+ }
8370
+ const appTs = [...appByTs.keys()].sort((a, b) => a - b);
8371
+ const traced = frames.map((entry) => {
8372
+ const frame = entry.frame;
8373
+ const candidates = nearest(bufferTs, frame.ts, EVENT_LOOKBACK_NS, frame.dur, MAX_EVENTS);
8374
+ let best;
8375
+ for (const eventNs of candidates) {
8376
+ const near = nearest(appTs, eventNs, EVENT_LOOKBACK_NS, APP_LOOKAHEAD_NS, MAX_APP_FRAMES);
8377
+ for (const ts of near) {
8378
+ const timeDiffNs = Math.abs(ts - eventNs);
8379
+ if (best !== void 0 && timeDiffNs >= best.timeDiffNs) continue;
8380
+ const match = appByTs.get(ts);
8381
+ if (match === void 0) continue;
8382
+ best = { frame: match, eventNs, timeDiffNs };
8383
+ }
8384
+ }
8385
+ return { ...entry, ...best === void 0 ? {} : { traced: best } };
8386
+ });
8387
+ return { frames: traced, totalEvents: rows.length };
8388
+ }
8389
+ function allFrames(db, window) {
8390
+ return new FrameQuery(db).all(window);
8391
+ }
8392
+ function byMetricId10(a, b) {
8393
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
8394
+ }
8395
+ function byEvidenceOrder8(a, b) {
8396
+ if (a.kind < b.kind) return -1;
8397
+ if (a.kind > b.kind) return 1;
8398
+ if (a.window.startNs < b.window.startNs) return -1;
8399
+ if (a.window.startNs > b.window.startNs) return 1;
8400
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
8401
+ }
8402
+ function appProcessName10(ctx) {
8403
+ return ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
8404
+ }
8405
+ var RsSkipAnalyzer = class {
8406
+ id = "rs-skip";
8407
+ requires = ["trace.frames", "trace.ark"];
8408
+ async run(ctx) {
8409
+ if (ctx.db === void 0) {
8410
+ return noData(ctx, "the trace database handle is not available");
8411
+ }
8412
+ const rsIpids = renderServiceIpids(ctx.processes);
8413
+ if (rsIpids.length === 0) {
8414
+ return noData(ctx, "the trace has no render_service process, so there is no RS skip to trace");
8415
+ }
8416
+ const appIpids3 = resolveAppIpids(ctx.processes, ctx.app.pids);
8417
+ const appKnown = appIpids3.length > 0;
8418
+ const result = computeRsSkip(ctx.db, { window: ctx.window, appIpids: appIpids3, rsIpids });
8419
+ if (result.frames.length === 0) {
8420
+ return noData(
8421
+ ctx,
8422
+ "no DisplayNode skip event fell inside a render_service frame in this window, so no frame was skipped by RenderService"
8423
+ );
8424
+ }
8425
+ const traced = result.frames.filter((entry) => entry.traced !== void 0).length;
8426
+ const prov = {
8427
+ collector: "hitrace",
8428
+ table: "frame_slice",
8429
+ rows: result.frames.length,
8430
+ device: ctx.deviceId
8431
+ };
8432
+ const metrics = [
8433
+ metric({
8434
+ id: "rs_skip.events.count",
8435
+ value: result.totalEvents,
8436
+ unit: "count",
8437
+ provenance: prov,
8438
+ fidelity: "exact",
8439
+ window: ctx.window
8440
+ }),
8441
+ metric({
8442
+ id: "rs_skip.frames.count",
8443
+ value: result.frames.length,
8444
+ unit: "count",
8445
+ provenance: prov,
8446
+ fidelity: "exact",
8447
+ window: ctx.window
8448
+ })
8449
+ ];
8450
+ if (appKnown) {
8451
+ metrics.push(
8452
+ metric({
8453
+ id: "rs_skip.trace.accuracy",
8454
+ value: traced / result.frames.length * 100,
8455
+ unit: "%",
8456
+ provenance: prov,
8457
+ fidelity: "exact",
8458
+ window: ctx.window
8459
+ }),
8460
+ metric({
8461
+ id: "rs_skip.traced.count",
8462
+ value: traced,
8463
+ unit: "count",
8464
+ provenance: prov,
8465
+ fidelity: "exact",
8466
+ window: ctx.window
8467
+ })
8468
+ );
8469
+ } else {
8470
+ metrics.push(
8471
+ metric({
8472
+ id: "rs_skip.trace.degraded",
8473
+ value: 0,
8474
+ unit: "count",
8475
+ fidelity: "proxy",
8476
+ degraded: {
8477
+ reason: "no app process was identified in this trace, so a skip cannot be traced back to one of its frames",
8478
+ fallback: "no reverse trace"
8479
+ },
8480
+ provenance: { collector: "hitrace", device: ctx.deviceId },
8481
+ window: ctx.window
8482
+ })
8483
+ );
8484
+ }
8485
+ const items = result.frames.map((entry) => {
8486
+ const { frame, traced: match } = entry;
8487
+ const startNs = frame.ts;
8488
+ const endNs = frame.ts + frame.dur;
8489
+ const drillDown = [
8490
+ {
8491
+ label: "Skip events in frame",
8492
+ tool: "callstack.matching",
8493
+ args: { pattern: SKIP_PATTERN, startNs, endNs },
8494
+ returns: "CallstackEvent[]",
8495
+ estRows: entry.events
8496
+ }
8497
+ ];
8498
+ if (match !== void 0) {
8499
+ drillDown.push({
8500
+ label: "Traced app frame",
8501
+ tool: "frames.get",
8502
+ args: { id: match.frame.id },
8503
+ returns: "Frame"
8504
+ });
8505
+ }
8506
+ return evidence({
8507
+ kind: "rs_skip",
8508
+ severity: "warn",
8509
+ // RS decided not to composite, so the frame is RenderService's own.
8510
+ subject: { process: "render_service" },
8511
+ window: { startNs, endNs },
8512
+ signals: match === void 0 ? { skipEvents: entry.events } : {
8513
+ skipEvents: entry.events,
8514
+ appFrameId: match.frame.id,
8515
+ appFrameFlag: match.frame.flag,
8516
+ timeDiffMs: match.timeDiffNs / 1e6,
8517
+ method: "nativewindow"
8518
+ },
8519
+ explain: match === void 0 ? `render_service skipped ${entry.events} frame(s) at vsync ${frame.vsync}; no app frame could be traced back to it` : `render_service skipped the frame at vsync ${frame.vsync}; ${appProcessName10(ctx)} frame ${match.frame.id} fed it (${(match.timeDiffNs / 1e6).toFixed(2)}ms from its buffer event)`,
8520
+ drillDown
8521
+ });
8522
+ });
8523
+ metrics.sort(byMetricId10);
8524
+ items.sort(byEvidenceOrder8);
8525
+ return { metrics, evidence: items };
8526
+ }
8527
+ };
8528
+ function noData(ctx, explain) {
8529
+ return {
8530
+ metrics: [],
8531
+ evidence: [
8532
+ evidence({
8533
+ kind: "no_data",
8534
+ severity: "info",
8535
+ subject: { process: appProcessName10(ctx) },
8536
+ window: ctx.window,
8537
+ signals: {},
8538
+ explain,
8539
+ drillDown: [],
8540
+ key: "rs-skip:no-data"
8541
+ })
8542
+ ]
7369
8543
  };
7370
8544
  }
7371
8545
 
8546
+ // src/analyze/flamegraph.ts
8547
+ var FlamegraphAnalyzer = class {
8548
+ id = "flamegraph";
8549
+ requires = ["perf.samples"];
8550
+ async run(ctx) {
8551
+ if (ctx.perf === void 0 || !ctx.perf.hasSamples()) {
8552
+ return {
8553
+ metrics: [
8554
+ metric({
8555
+ id: "flamegraph.degraded",
8556
+ value: 0,
8557
+ unit: "count",
8558
+ fidelity: "proxy",
8559
+ degraded: {
8560
+ reason: "no perf samples: the scene was captured without --hiperf, or the app was not debuggable so perf recorded nothing",
8561
+ fallback: "no flamegraph"
8562
+ },
8563
+ provenance: { collector: "hiperf", device: ctx.deviceId }
8564
+ })
8565
+ ],
8566
+ evidence: []
8567
+ };
8568
+ }
8569
+ const threads = ctx.perf.threads(ctx.app.pids);
8570
+ const threadIds = [...new Set(threads.map((thread) => thread.threadId))].sort((a, b) => a - b);
8571
+ const samples = ctx.perf.eventCount(threadIds, ctx.window);
8572
+ const total = ctx.perf.eventCount(void 0, ctx.window);
8573
+ const allStacks = ctx.perf.foldedStacks(threadIds, ctx.window);
8574
+ const stacks = allStacks.slice(0, TOP_STACKS);
8575
+ const prov = {
8576
+ collector: "hiperf",
8577
+ table: "perf_sample",
8578
+ rows: threadIds.length,
8579
+ device: ctx.deviceId
8580
+ };
8581
+ const metrics = [
8582
+ metric({
8583
+ id: "flamegraph.app.share",
8584
+ value: total > 0 ? samples / total * 100 : 0,
8585
+ unit: "%",
8586
+ provenance: prov,
8587
+ fidelity: "exact",
8588
+ window: ctx.window
8589
+ }),
8590
+ metric({
8591
+ id: "flamegraph.samples.count",
8592
+ value: samples,
8593
+ unit: "count",
8594
+ provenance: prov,
8595
+ fidelity: "exact",
8596
+ window: ctx.window
8597
+ }),
8598
+ metric({
8599
+ id: "flamegraph.stacks.count",
8600
+ value: allStacks.length,
8601
+ unit: "count",
8602
+ provenance: prov,
8603
+ fidelity: "exact",
8604
+ window: ctx.window
8605
+ })
8606
+ ];
8607
+ const top = stacks[0];
8608
+ if (top !== void 0) {
8609
+ metrics.push(
8610
+ metric({
8611
+ id: "flamegraph.top.samples",
8612
+ value: top.samples,
8613
+ unit: "count",
8614
+ provenance: prov,
8615
+ fidelity: "exact",
8616
+ window: ctx.window
8617
+ }),
8618
+ metric({
8619
+ id: "flamegraph.top.symbol",
8620
+ value: top.leaf,
8621
+ unit: "none",
8622
+ provenance: prov,
8623
+ fidelity: "exact",
8624
+ window: ctx.window
8625
+ })
8626
+ );
8627
+ }
8628
+ metrics.sort(byMetricId11);
8629
+ return { metrics, evidence: [] };
8630
+ }
8631
+ };
8632
+ var TOP_STACKS = 20;
8633
+ function byMetricId11(a, b) {
8634
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
8635
+ }
8636
+
8637
+ // src/analyze/engine.ts
8638
+ function byAnalyzerId(a, b) {
8639
+ if (a.id < b.id) return -1;
8640
+ if (a.id > b.id) return 1;
8641
+ return 0;
8642
+ }
8643
+ function byMetricId12(a, b) {
8644
+ if (a.id < b.id) return -1;
8645
+ if (a.id > b.id) return 1;
8646
+ return 0;
8647
+ }
8648
+ function byEvidenceOrder9(a, b) {
8649
+ if (a.kind < b.kind) return -1;
8650
+ if (a.kind > b.kind) return 1;
8651
+ if (a.window.startNs < b.window.startNs) return -1;
8652
+ if (a.window.startNs > b.window.startNs) return 1;
8653
+ if (a.id < b.id) return -1;
8654
+ if (a.id > b.id) return 1;
8655
+ return 0;
8656
+ }
8657
+ function degradedReason(missing) {
8658
+ const ids = missing.map((state) => state.id).join(", ");
8659
+ const reasons = missing.map((state) => state.reason ?? "unavailable").join("; ");
8660
+ return `missing ${ids}: ${reasons}`;
8661
+ }
8662
+ function degradedMetric(analyzer, ctx, missing) {
8663
+ return metric({
8664
+ id: `${analyzer.id}.degraded`,
8665
+ value: 0,
8666
+ unit: "count",
8667
+ fidelity: "proxy",
8668
+ degraded: { reason: degradedReason(missing), fallback: "analyzer skipped" },
8669
+ provenance: { collector: "capability-matrix", device: ctx.deviceId }
8670
+ });
8671
+ }
8672
+ function degradedEvidence(analyzer, ctx, missing) {
8673
+ const ids = missing.map((state) => state.id);
8674
+ const process2 = ctx.app.processNames.find((name) => name !== "") ?? ctx.app.packageName;
8675
+ return evidence({
8676
+ kind: "degraded_capability",
8677
+ severity: "warn",
8678
+ subject: { process: process2 },
8679
+ window: ctx.window,
8680
+ signals: { missing: ids.join(",") },
8681
+ explain: `${analyzer.id} skipped: ${degradedReason(missing)}`,
8682
+ drillDown: [
8683
+ {
8684
+ label: "Capability matrix",
8685
+ tool: "caps.get",
8686
+ args: { ids },
8687
+ returns: "CapabilityState[]",
8688
+ estRows: ids.length
8689
+ }
8690
+ ],
8691
+ key: analyzer.id
8692
+ });
8693
+ }
8694
+ async function runAnalyzers(analyzers, ctx) {
8695
+ const ordered = [...analyzers].sort(byAnalyzerId);
8696
+ const metrics = [];
8697
+ const evidenceItems = [];
8698
+ for (const analyzer of ordered) {
8699
+ const check = ctx.caps.satisfies(analyzer.requires);
8700
+ if (!check.ok) {
8701
+ metrics.push(degradedMetric(analyzer, ctx, check.missing));
8702
+ evidenceItems.push(degradedEvidence(analyzer, ctx, check.missing));
8703
+ continue;
8704
+ }
8705
+ const result = await analyzer.run(ctx);
8706
+ metrics.push(...result.metrics);
8707
+ evidenceItems.push(...result.evidence);
8708
+ }
8709
+ metrics.sort(byMetricId12);
8710
+ for (let i = 1; i < metrics.length; i++) {
8711
+ if (metrics[i].id === metrics[i - 1].id) {
8712
+ throw new OhosPerfError("DUPLICATE_METRIC_ID", { code: "DUPLICATE_METRIC_ID" });
8713
+ }
8714
+ }
8715
+ evidenceItems.sort(byEvidenceOrder9);
8716
+ for (let i = 1; i < evidenceItems.length; i++) {
8717
+ if (evidenceItems[i].id === evidenceItems[i - 1].id) {
8718
+ throw new OhosPerfError("DUPLICATE_EVIDENCE_ID", {
8719
+ code: "DUPLICATE_EVIDENCE_ID"
8720
+ });
8721
+ }
8722
+ }
8723
+ return { metrics, evidence: evidenceItems };
8724
+ }
8725
+ function defaultAnalyzers() {
8726
+ return [
8727
+ new FrameAnalyzer(),
8728
+ new FaultTreeAnalyzer(),
8729
+ new BinderAnalyzer(),
8730
+ new ThreadAnalyzer(),
8731
+ new MemoryAnalyzer(),
8732
+ new MemoryMeasureAnalyzer(),
8733
+ new StartupAnalyzer(),
8734
+ new RenderAnalyzer(),
8735
+ new GcAnalyzer(),
8736
+ new VsyncAnalyzer(),
8737
+ new EmptyFrameAnalyzer(),
8738
+ new RsSkipAnalyzer(),
8739
+ new FlamegraphAnalyzer(),
8740
+ new ComponentReuseAnalyzer()
8741
+ ];
8742
+ }
8743
+
7372
8744
  // src/report/compare.ts
7373
8745
  var METRIC_DIRECTIONS = {
7374
8746
  "frame.avg.duration": "lower",
@@ -7398,7 +8770,33 @@ var METRIC_DIRECTIONS = {
7398
8770
  "startup.count": "lower",
7399
8771
  "startup.duration": "lower",
7400
8772
  "render.fps.live": "higher",
7401
- "render.hitch.count": "lower"
8773
+ "render.hitch.count": "lower",
8774
+ "gc.full.count": "lower",
8775
+ "gc.invocations.count": "lower",
8776
+ "gc.partial.count": "lower",
8777
+ "gc.perf.share": "lower",
8778
+ "gc.rate": "lower",
8779
+ "gc.shared.count": "lower",
8780
+ "gc.shared_full.count": "lower",
8781
+ // `vsync.signals.count` has no direction: more signals is neither better nor
8782
+ // worse, it only changes the denominator of the anomaly rate.
8783
+ "vsync.anomaly.rate": "lower",
8784
+ "vsync.mismatch.count": "lower",
8785
+ "vsync.periods.count": "lower",
8786
+ "empty_frame.count": "lower",
8787
+ "empty_frame.filtered.count": "lower",
8788
+ "empty_frame.rate": "lower",
8789
+ "rs_skip.events.count": "lower",
8790
+ "rs_skip.frames.count": "lower",
8791
+ // A higher trace accuracy means more of the skipped frames were explained.
8792
+ "rs_skip.trace.accuracy": "higher",
8793
+ "rs_skip.traced.count": "higher",
8794
+ // Fewer builds of the busiest component is the goal, and a higher reuse
8795
+ // rate means more of them came from the recycle pool. `components.top.name`
8796
+ // is a label, not a quantity, so it has no direction.
8797
+ "components.builds.count": "lower",
8798
+ "components.recycled.count": "higher",
8799
+ "components.reuse.rate": "higher"
7402
8800
  };
7403
8801
  var STATUSES = [
7404
8802
  "improved",
@@ -7477,16 +8875,20 @@ export {
7477
8875
  BinderQuery,
7478
8876
  CallstackQuery,
7479
8877
  CapabilityMatrix,
8878
+ ComponentReuseAnalyzer,
7480
8879
  DEFAULT_QUERY_LIMIT,
7481
8880
  DEVICE_PERF_PATH,
7482
8881
  DEVICE_UI_PATH,
7483
8882
  Device,
7484
8883
  DeviceNotFoundError,
8884
+ EmptyFrameAnalyzer,
7485
8885
  FPS_COMMAND,
7486
8886
  FTRACE_CATEGORIES,
7487
8887
  FaultTreeAnalyzer,
8888
+ FlamegraphAnalyzer,
7488
8889
  FrameAnalyzer,
7489
8890
  FrameQuery,
8891
+ GcAnalyzer,
7490
8892
  HIPROFILER_PLUGIN_NAMES,
7491
8893
  HITCH_COMMAND,
7492
8894
  HITRACE_DEFAULT_CATEGORIES,
@@ -7510,6 +8912,7 @@ export {
7510
8912
  ProcessQuery,
7511
8913
  ProcfsCollector,
7512
8914
  RenderAnalyzer,
8915
+ RsSkipAnalyzer,
7513
8916
  Scene,
7514
8917
  SchedQuery,
7515
8918
  StartupAnalyzer,
@@ -7520,17 +8923,23 @@ export {
7520
8923
  ThreadQuery,
7521
8924
  ThreadStateQuery,
7522
8925
  UitestCollector,
8926
+ VsyncAnalyzer,
7523
8927
  analyzeThreadWakeup,
7524
8928
  buildHiprofilerConfig,
7525
8929
  buildMatrix,
7526
8930
  compareResults,
7527
8931
  computeBinderAnalysis,
8932
+ computeComponentReuse,
7528
8933
  computeFaultTree,
8934
+ computeGc,
8935
+ computeRsSkip,
7529
8936
  computeThreadAnalysis,
8937
+ computeVsyncAnomalies,
7530
8938
  connect,
7531
8939
  createSceneLayout,
7532
8940
  defaultAnalyzers,
7533
8941
  evidence,
8942
+ filterEmptyFrames,
7534
8943
  flattenUiTree,
7535
8944
  ftracePlugin,
7536
8945
  gpuPlugin,
@@ -7552,7 +8961,9 @@ export {
7552
8961
  readSceneMetadata,
7553
8962
  readUiTree,
7554
8963
  resolveAppIdentity,
8964
+ resolveAppIpids,
7555
8965
  resolveQueryLimit,
8966
+ round2HalfEven,
7556
8967
  runAnalyzers,
7557
8968
  runDrillDown,
7558
8969
  runNamedQuery,