一个 npm 包,五十二个 Vitest 用例,零原生代码。这篇讲 leakscope-rn 怎么在 RNOH 工程里不带 HAR 地接进去:账本怎么记、Hook 怎么在卸载时把 owner 收干净,以及为什么图片账本记的是 45.8 MB,跟图片文件大小对不上。

仓库地址:https://atomgit.com/oh-react-native/leakscope-rn
版本地址:https://atomgit.com/oh-react-native/ohos_react_native/tree/0.84-main
三方库框架:https://atomgit.com/oh-react-native

0. 环境与实测设备

项版本/型号
React Nativepeer >=0.76;开发、类型检查与示例基线为 0.84.x
React19.2.3(devDependencies;仅 useLeakScope 的类型与测试使用)
RNOH参考基线 @rnoh/react-native-openharmony 0.84.4 / HarmonyOS SDK 26
DevEco Studio26.0.0.821(HarmonyOS SDK 26.0.0 Release / API 26)
语言与构建TypeScript 5.9.3、Babel 7、Vitest 3.2.7、Node.js 24.12.0、npm 11.12.1
leakscope-rn1.0.0(本仓库,纯 TS npm 包;无原生代码、无 HAR;react / react-native 为 optional peer)
测试Vitest 5 个文件、52 项;npm run verify 含 typecheck + 52 tests + CJS/ESM/types 构建
包形态npm pack 69 个文件、94,161 bytes;不含 __tests__/、example/、node_modules/
测试设备宿主 RNOH 2in1 示例页(设备型号未入库),HarmonyOS API 26;本仓库只有纯逻辑测试,截图来自宿主工程
端侧读数6 live / 6 candidates / 261.0 KB;图片 45.8 MB;通道活跃 1 / 孤儿 1;复现 LEAK(+5 / 5 轮)

52 项测试和 69 文件 / 94,161 bytes 的包形态分别来自验证记录与包检查记录;6 live / 261.0 KB / 45.8 MB 这组读数、以及第 2 节的截图,来自宿主 RNOH 工程里的示例页。仓库本身不构建 example/,也没有 RNOH 工程。

1. 6 条记录,没有一条来自堆快照

截图这一屏跑过 A1、A3、A4 和 A5:图片账本还保留着 A1 的 1 条 45.8 MB,说明 A2 的释放没有发生在这一屏。生命周期台账停在 6 条 live、261.0 KB、6 个候选,复现结论 LEAK(+5 / 5 轮)。这 6 条里有 A3 故意丢下的 256 KB closure,也有复现每轮 1 KB 的对象。它们不是从 Hermes 堆里找出来的,是页面调用 watch 登记进去的。

这个顺序跟常规排查相反。页面卸载后内存没回来,第一反应通常是打开 DevTools 的 Memory 面板,点几次 GC,对比对象数量。快照能看到对象,但回答不了两个业务问题:这个对象属于哪个页面、哪次请求、哪个 owner?它是这一次泄漏,还是缓存池本来就应该常驻?

RN 里最常见的泄漏也分散在好几处:页面卸载后仍被 closure 抓住的 JS 对象;忘记 remove() 的 EmitterSubscription;没清掉的 setTimeout / setInterval;被 <Image> 按解码尺寸占住的像素;RNOH / 原生侧回调与 ArkTS 侧任务。它们的共同点是分配和释放都发生在应用代码里,GC 看不到,日志也串不起来。console.log 记录的是「事件发生了」,泄漏记录的是「事件没有发生」——没有执行的 remove、没有执行的 clear、没有被释放的引用。

Hermes 的 FinalizationRegistry 回调时机又不保证,部分版本甚至不触发。拿它当判据不可靠,回调时机完全取决于调度器。所以这个库的判据全部是显式的:watch 声明开始持有,release 声明停止持有,scopeClose 声明页面结束。账本回答「谁还活着、活了多久、占了多少」,5 轮趋势回答「下一轮还会不会继续涨」。

约束定下来只有下面这些。定位交给 LeakWatch:它记录资源从 watch() 到 release() 的生命期,scopeClose(owner) 之后仍 live 的成为候选。复现交给 runLeakRepro:预热/测量多轮,用预算、容差、单调性和最小二乘斜率判定。度量交给图片和通道两个账本:ImageMemoryLedger 按解码字节记账,ChannelLedger 审计 open/close,renderLeakReport() 输出确定性的 markdown。

库本身是纯 TypeScript,RN 的 emitter、timer 只以结构化接口出现在适配层,纯逻辑测试全部在 Node 里跑,模拟器都不用开。

2. 宿主里跑出来的第一屏

示例页放在 RNOH 2in1 宿主里运行,宽屏窗口下是左右两栏:左边是生命周期、图片、通道三个账本,右边是泄漏复现和操作,报告在底部。页面标题是 LeakScope,副标题是「内存泄漏观测台 · 生命周期 / 图片 / 通道」:

LeakScope 示例页:生命周期、图片、通道三本账

顶部状态是 运行中,会话 demo-feed,读数 01:18:29。第一栏「生命周期台账」显示 存活资源 6、泄漏候选 6、已释放 0;脚注写着「owner demo-feed · 5s 判定未释放 · 页面退出后记录仍保留」。第二栏「图片账本」显示 当前占用 45.8 MB、峰值占用 45.8 MB,条目 1、重复引用 0、淘汰 0。第三栏「通道审计」显示活跃通道 1、孤儿通道 1、迟关闭 0。

右栏「泄漏复现」的结论是 检测到泄漏:增长 +5、斜率 1.00、归因 demo-feed / object,脚注是「5 个测量轮单调不减,增长 5 超过预算 0。」操作区是 A1 到 A5:

A1 加载一张封面      源图 4000×3000 · dpr 2 · rgba8888
A2 释放全部封面      release 全部引用并 evictTo(16 MB)
A3 制造一次泄漏      interval + closure · 故意丢弃 handle
A4 复现 5 轮         每轮 +1 对象 · 度量 live
A5 生成审计报告      markdown · 含复现结论

底部的报告是 A5 生成的:

# LeakScope 报告 · demo-feed 页面

| 指标 | 值 |
| --- | --- |
| 存活资源 | 6 |
| 存活字节 | 261.0 KB |
| 已释放 | 0 |
| 泄漏候选 | 6 |
| 复现结论 | LEAK(+5 / 5 轮) |
| 通道孤儿 | 1 |

这组数字可以逐项对上:A3 制造了一次 closure 泄漏(256 KB),A4 的 5 轮每轮 watch 一个 1 KB 的对象,于是 watch 台账是 1 + 5 = 6 条、256 KB + 5 × 1 KB = 261.0 KB;图片是 A1 加载的 4000×3000 @ dpr 2,planImageDecode 先把 8000×6000 按 sampleSize=2 降到 4000×3000,账本是 4000 × 3000 × 4 = 48,000,000 B ≈ 45.8 MB;通道是 A3 故意丢掉 handle 的 interval,5 秒后仍在 active 列表里;「活跃 1、孤儿 1」里的孤儿本来就属于 active,不构成另一个桶。

示例为了现场看到 5 轮增长,调用 scope.repro 时传 {warmup: 0, rounds: 5};库默认是预热 2 + 测量 5,生产建议用默认值。

注意这时页面还在 运行中,6 个候选来自 stale(超过 5 秒未释放),还没轮到 unreleased-after-scope。等页面卸载,useLeakScope 的 cleanup 会先 scopeClose('demo-feed') 再 dispose();同一批记录会升级为 unreleased-after-scope。watch 记录不会被 dispose 清掉——页面脚注写的「页面退出后记录仍保留」就是这个意思。

这张截图出自宿主 RNOH 工程;leakscope-rn 仓库自己构建不出这一屏。本仓库的 example/App.tsx 只提供页面源码,必须复制进宿主工程才能跑;原因在 示例说明 里写得很清楚:库本身不安装 react-native,把示例纳入构建会把整棵 RN 类型与 Metro 配置拖进库的依赖。

3. 账本不读堆,只按登记判定

三个账本的分工在代码里是固定的。LeakWatch 管生命周期,ImageMemoryLedger 管解码字节,ChannelLedger 管 open/close;三者共享同一个可注入时钟,最后汇入同一个报告:

useLeakScope('demo-feed')
  │  挂载时创建,卸载时 scopeClose + dispose
  ▼
LeakWatch          ImageMemoryLedger        ChannelLedger
  │ live/bytes       │ decoded bytes          │ active/orphans/late
  └──────────────────┴────────────────────────┘
                     │
                     ▼
             runLeakRepro(默认 2 轮预热 + 5 轮测量)
                     │ verdict / growth / slope / 归因
                     ▼
             renderLeakReport() → 固定 markdown

每条链路的输入、输出和失败形态:

链路输入输出失败长什么样
定位 + 复现watch(key, {kind, owner, bytes})、scopeClose(owner)、cycle + settleLeakSnapshot、candidates()、runLeakRepro 的 verdict / slope / 归因页面关闭后记录仍 live,reason: unreleased-after-scope;或每轮 +N 且无回落,判为 leak
图片内存源尺寸、dpr、格式、maxBytes / maxDimensionbytesFor、planImageDecode、ImageStats解码尺寸超过 4096 或超过预算;LRU 淘汰后 liveBytes 仍不降
通道审计open({kind, owner})、close(id)、scopeClose(owner)ChannelAudit 的 active / orphans / lateCloses打开时有记录、关闭时没有记录;或页面结束后才 close,计入 lateCloses

默认值与家族契约一致:预热 2 轮、测量 5 轮、staleAfterMs / orphanAfterMs 都是 5000 ms、图片预算 64 MiB、maxDimension=4096、watch 记录上限 4096(只淘汰最旧的已释放记录)。候选原因优先级是 unreleased-after-scope > stale > duplicate-key;scopeClose 只记录 owner 的结束时刻,不会替调用方释放任何东西。

LeakWatch 不做 GC 可达性推断,它只回答「显式登记的生命周期有没有闭合」。三个入口放在一起:

// src/watch.ts · LeakWatch 的三个方法
  watch(key: string, spec: LeakWatchSpec): void {
    if (key.length === 0) {
      throw new Error('LeakWatch.watch requires a non-empty key');
    }
    const at = this.now();
    const existing = this.findLive(key);
    if (existing) {
      existing.watchCount += 1;
      existing.lastWatchedAt = at;
      return;
    }

    const record: InternalRecord = {
      key,
      kind: spec.kind,
      label: spec.label ?? key,
      owner: spec.owner,
      bytes: Math.max(0, spec.bytes ?? 0),
      meta: spec.meta,
      createdAt: at,
      lastWatchedAt: at,
      watchCount: 1,
    };
    this.records.push(record);
    this.trim();
  }

  /**
   * Marks a live key as released. Idempotent: a missing or already released key
   * returns `false` and changes nothing.
   */
  release(key: string): boolean {
    const record = this.findLive(key);
    if (!record) {
      return false;
    }
    record.releasedAt = this.now();
    return true;
  }

  /**
   * Records the end of a page/component/window/scope.
   *
   * Later scans report every still-live record owned by `owner` as
   * `unreleased-after-scope`, the strongest local leak signal available to an
   * explicit ledger.
   */
  scopeClose(owner: string): void {
    this.scopeClosedAt.set(owner, this.now());
  }

watch() 对同 key 仍 live 的记录只做 watchCount += 1 和 lastWatchedAt 更新,不把 createdAt 重置。年龄一重置,stale 和 liveForMs 都会被洗掉,泄漏看起来就像刚创建。release() 幂等,未知 key 和已释放 key 都返回 false。scopeClose() 只往 scopeClosedAt 写时间戳,不碰记录;如果它顺手 release,这个场景就永远抓不到。

3.1 候选:candidates() 的三级 reason

candidates() 遍历所有 live 记录,先判作用域,再判存活时长,最后判重复登记;排序按字节降序、key 升序,保证报告顺序稳定:

// src/watch.ts · LeakWatch#candidates
  candidates(): LeakCandidate[] {
    const at = this.now();
    const candidates: LeakCandidate[] = [];

    for (const record of this.records) {
      if (record.releasedAt !== undefined) {
        continue;
      }
      const liveForMs = Math.max(0, at - record.createdAt);
      let reason: LeakCandidate['reason'] | undefined;
      if (record.owner !== undefined && this.scopeClosedAt.has(record.owner)) {
        reason = 'unreleased-after-scope';
      } else if (liveForMs >= this.staleAfterMs) {
        reason = 'stale';
      } else if (record.watchCount > 1) {
        reason = 'duplicate-key';
      }
      if (!reason) {
        continue;
      }
      candidates.push({
        key: record.key,
        kind: record.kind,
        label: record.label,
        ...(record.owner !== undefined ? {owner: record.owner} : {}),
        reason,
        liveForMs,
        bytes: record.bytes,
        watchCount: record.watchCount,
      });
    }

    candidates.sort((a, b) => {
      if (a.bytes !== b.bytes) {
        return b.bytes - a.bytes;
      }
      return compareText(a.key, b.key);
    });
    return candidates;
  }

reason 的三个分支互斥,顺序不能反:owner 已经结束仍然 live,是最强的证据;stale 只说明活得太久;duplicate 只说明登记重复。排序里字节优先于 key,所以报告里最大的对象永远在第一行;同字节时用 key 兜底,同样输入不会因为 Map 迭代顺序不同而漂移。

duplicate-key 容易被误读。同一个 key 被 watch 两次,可能真的是引用计数多加了一次,也可能只是池化复用。它排在 stale 之后报告,就是为了不让「池化」把「作用域结束后仍存活」的强证据盖掉。如果 key 复用是正常设计,复用前先 release(),不要靠重复 watch 覆盖。

测试里覆盖了两个边界:staleAfterMs=1000 时,999 ms 候选为空,第 1000 ms 出现 stale;maxRecords=3 时先登记 a、b,释放 a,再登记 c、d,淘汰的是最旧的已释放记录 a,live 记录即使超过上限也不会被丢。这两个用例都在 __tests__/watch.test.ts 里。

它和常见观测路径的差别:

手段能看到什么在 RN 里的局限
RSS / top 曲线「涨了多少」没有 owner、没有轮次、单点噪声大
Hermes 堆快照对象图、Retainer手工分析、GC 时机影响、难进 CI
FinalizationRegistry「对象被回收了」回调时机不保证;不能回答「何时应该释放」
LeakScope(本库)显式台账 + 5 轮趋势 + 图片/通道账本 + 确定性报告依赖宿主登记,不读堆

能力边界也写清楚:本库不读取 Hermes 堆,不做对象图遍历,不保证「没登记 = 没泄漏」;图片账本记录的是计划值,原生 <Image> 缓存、纹理、ArkTS 侧分配都不在其中;报告里的字节是账本值,跟设备 RSS 是两套数;它能把问题缩到某个 owner、某一轮,剩下的仍要回原生侧看。

4. 页面卸载时,先 scopeClose 再 dispose

LeakScope 把三个账本接到同一个时钟上;useLeakScope 负责「挂载时创建、卸载时 scopeClose + dispose」:

// src/react.ts
export function useLeakScope(owner: string, options?: LeakScopeOptions | (() => number)): LeakScope {
  const ref = useRef<LeakScope | null>(null);
  const ownerRef = useRef(owner);
  ownerRef.current = owner;
  if (ref.current === null) {
    ref.current = new LeakScope(options);
  }
  const scope = ref.current;

  useEffect(
    () => () => {
      scope.scopeClose(ownerRef.current);
      scope.dispose();
    },
    [scope],
  );

  return scope;
}

scope 在首次渲染时就创建,不用等 useEffect 跑完。这样事件处理函数在挂载完成前就能拿到 scope,不会出现「按钮点了但账本还没建」的空窗。options 只在首次渲染读取,之后改 staleAfterMs / orphanAfterMs 不会重建 scope;需要不同阈值时直接 new LeakScope。ownerRef 每次渲染都更新,cleanup 读的是最新的 owner,页面改名不会把 scopeClose 打到旧名字上。

dispose() 的动作顺序是固定的:

// src/scope.ts · LeakScope#dispose
  dispose(): ChannelAudit {
    if (!this.disposed) {
      for (const cleanup of [...this.cleanups]) {
        cleanup();
      }
      this.cleanups.clear();
      this.channel.closeAll();
      this.disposed = true;
    }
    return this.audit();
  }

先跑 scope 自己登记的 cleanup(scope.timer / scope.emitter 创建的 timer、emitter),再清空集合,然后 channel.closeAll(),最后把 disposed 置真。dispose() 不清 watch 记录。 这是故意的:页面退出后仍 live 的资源,还要以 unreleased-after-scope 出现在报告里。要清空 watch 得显式 watchLedger.reset()。

5. 图片、通道、复现、报告:四段实现

A1/A2 的图片账、A3 的通道、A4 的 5 轮判定、A5 的报告,四段代码依次对应上面的操作。

5.1 图片:45.8 MB 是解码后的账

图片账本按 ceil(width × dpr) × ceil(height × dpr) × bpp 算。retain() 对同一个 key 只加引用计数,release() 到 0 才删除条目,evictTo() 按 LRU 淘汰。解码前先算计划:

// src/imageMemory.ts
export function planImageDecode(input: ImageDecodeInput): DecodePlan {
  const format = input.format ?? 'rgba8888';
  const dpr = Number.isFinite(input.dpr) && (input.dpr ?? 0) > 0 ? (input.dpr as number) : 1;
  const maxDimension = Math.max(1, Math.floor(input.maxDimension ?? DEFAULT_MAX_DIMENSION));
  const requestedMaxBytes = input.maxBytes ?? DEFAULT_IMAGE_BUDGET;
  const bpp = IMAGE_FORMAT_BPP[format];
  const maxBytes = Number.isFinite(requestedMaxBytes) ? Math.max(bpp, requestedMaxBytes) : Number.POSITIVE_INFINITY;

  const fullWidth = Math.ceil(Math.max(0, input.width) * dpr);
  const fullHeight = Math.ceil(Math.max(0, input.height) * dpr);
  const fullBytes = bytesFor(fullWidth, fullHeight, format);

  if (fullWidth === 0 || fullHeight === 0) {
    return {
      sampleSize: 1,
      targetWidth: 0,
      targetHeight: 0,
      bytes: 0,
      fullBytes: 0,
      downscaled: false,
      reason: 'fits',
    };
  }

  const dimensionSample = sampleSizeForDimension(fullWidth, fullHeight, maxDimension);
  const budgetSample = sampleSizeForBytes(fullWidth, fullHeight, format, maxBytes);
  const sampleSize = Math.max(dimensionSample, budgetSample);
  const targetWidth = Math.max(1, Math.ceil(fullWidth / sampleSize));
  const targetHeight = Math.max(1, Math.ceil(fullHeight / sampleSize));
  const bytes = bytesFor(targetWidth, targetHeight, format);

  const dimensionBound = fullWidth > maxDimension || fullHeight > maxDimension;
  const budgetBound = fullBytes > maxBytes;
  let reason: DecodeReason;
  if (!dimensionBound && !budgetBound) {
    reason = 'fits';
  } else if (budgetBound && budgetSample > dimensionSample) {
    reason = 'budget';
  } else {
    reason = 'dimension';
  }

  return {
    sampleSize,
    targetWidth,
    targetHeight,
    bytes,
    fullBytes,
    downscaled: sampleSize > 1,
    reason,
  };
}

sampleSize 只会是 2 的幂,因为它对应解码器的采样倍率,不能当任意缩放比例用。尺寸和预算各算一个 sampleSize,最后取较大的那个;reason 则看谁才是约束:尺寸超了记 dimension,预算逼着多降一档记 budget,两个都没超记 fits。

A1 那张封面就是这套公式的结果:4000×3000 先乘 dpr 2 变成 8000×6000,fullBytes 是 8000 × 6000 × 4 = 192,000,000;4096 的边上限要求 sampleSize=2,目标变成 4000×3000,bytes 是 48,000,000,也就是 45.8 MB。图片文件本身可能只有几百 KB,账本跟文件大小没有关系。

预算分支也有测试:1000×1000、maxBytes=1 MiB,全尺寸 4,000,000 超预算,sampleSize=2 后 500×500×4 = 1,000,000,刚好落在 1 MiB 以内,reason=budget。另一个用例遍历 [4, 1024, 512 KiB, 2 MiB] 四个预算,断言 sampleSize 是 2 的整数次幂、bytes <= maxBytes、目标宽高大于 0。

peakBytes 与 liveBytes 要分开看。peakBytes 是历史最高水位,release 和 evictTo 都不会把它降下来;liveBytes 才是当前占用。按下 A2 后,entries 与 liveBytes 会回落,peakBytes 仍停在 45.8 MB;这时 evictTo(16 MB) 已经没有可淘汰的条目,evictions 还是 0。

5.2 通道:孤儿是 active 的子集

通道账本把订阅、timer、emitter、原生事件、请求、observer、协程统一成一行记录。open 生成 id,close 记录时间,scopeClose 只记录 owner 结束;审计时 active 和 orphans 一起算:

// src/channel.ts · ChannelLedger#audit
  audit(options: ChannelAuditOptions = {}): ChannelAudit {
    const at = this.now();
    const orphanAfterMs = Math.max(0, options.orphanAfterMs ?? DEFAULT_ORPHAN_AFTER_MS);
    const active: ChannelRecord[] = [];
    const orphans: ChannelRecord[] = [];
    const byKind: Partial<Record<ChannelKind, number>> = {};
    let closed = 0;

    for (const record of this.records.values()) {
      if (record.closedAt !== undefined) {
        closed += 1;
        continue;
      }
      active.push({...record});
      byKind[record.kind] = (byKind[record.kind] ?? 0) + 1;
      if (at - record.openedAt >= orphanAfterMs) {
        orphans.push({...record});
      }
    }

    sortRecords(active);
    sortRecords(orphans);
    return {
      opened: this.records.size,
      closed,
      active,
      orphans,
      lateCloses: this.lateCloses,
      byKind,
    };
  }

orphans 是 active 的子集,不构成另一个桶:超过阈值的记录同时留在 active 里,也在 orphans 里。报告里「活跃 1、孤儿 1」就是这么来的:那个 interval 还没关,它既活跃,也已经是孤儿。lateCloses 是另一个计数器:close 发生在 scopeClose(owner) 之后才加一,跟当前是否 active 无关。

测试里三个边界:orphanAfterMs=1000 时,999 ms 孤儿为 0,第 1000 ms 出现 1 条;先 close 再 scopeClose 不计迟关闭,先 scopeClose 再 close 计 1 次;close() 幂等,第二次返回 false,opened=1, closed=1。closeAll('feed') 只关该 owner 的通道,settings 的还留着。

trackInterval 和 trackTimer 的区别也在这里。一次性 timer 触发时自己 close,通道不会长期挂着;重复 interval 要等 cancel() 才 close。A3 故意丢掉 trackInterval 的 handle,5 秒后审计就把它算成孤儿。忘记 cancel 的 interval 正是这套账要暴露的形状。

5.3 复现:5 轮怎么把 +5 判成 LEAK

runLeakRepro 先跑 warmup 轮建立 baseline,再跑测量轮;每轮 cycle → settle → snapshot,baseline 取最后一个预热轮,slope 只对测量轮做最小二乘:

// src/repro.ts
export async function runLeakRepro(
  cycle: (round: number) => void | Promise<void>,
  options: ReproOptions,
): Promise<ReproResult> {
  const warmup = Math.max(0, Math.floor(options.warmup ?? DEFAULT_WARMUP_ROUNDS));
  const measureRounds = Math.max(0, Math.floor(options.rounds ?? DEFAULT_MEASURE_ROUNDS));
  const budget = options.budget ?? 0;
  const tolerance = Math.max(0, options.tolerance ?? 0);
  const metric = options.metric ?? ((snapshot: LeakSnapshot) => snapshot.live);
  const metricName = options.metricName ?? 'live';
  const settle = options.settle;

  let baselineSnapshot: LeakSnapshot | undefined;
  for (let index = 0; index < warmup; index += 1) {
    await cycle(index);
    if (settle) {
      await settle();
    }
    baselineSnapshot = options.snapshot();
  }
  if (baselineSnapshot === undefined) {
    baselineSnapshot = options.snapshot();
  }

  const baselineMetric = metric(baselineSnapshot);
  const measured: ReproRound[] = [];
  let previousMetric = baselineMetric;
  let lastSnapshot = baselineSnapshot;

  for (let index = 0; index < measureRounds; index += 1) {
    await cycle(warmup + index);
    if (settle) {
      await settle();
    }
    const snapshot = options.snapshot();
    const value = metric(snapshot);
    measured.push({
      index: measured.length + 1,
      metric: value,
      delta: value - previousMetric,
      live: snapshot.live,
      liveBytes: snapshot.liveBytes,
    });
    previousMetric = value;
    lastSnapshot = snapshot;
  }

  const lastMetric = measured.length > 0 ? (measured[measured.length - 1]?.metric ?? baselineMetric) : baselineMetric;
  const growth = lastMetric - baselineMetric;
  const perRound = measured.length > 0 ? growth / measured.length : 0;
  const slope = leastSquaresSlope(measured.map((round) => round.metric));
  const verdict = verdictFor(measured, growth, budget, tolerance);
  const attribution = attribute(baselineSnapshot, lastSnapshot);
  const note = noteFor(verdict, growth, budget, measured.length);

  return {
    verdict,
    metricName,
    baseline: baselineMetric,
    rounds: measured,
    growth,
    perRound,
    slope,
    budget,
    ...(attribution.suspiciousKind !== undefined ? {suspiciousKind: attribution.suspiciousKind} : {}),
    ...(attribution.suspiciousOwner !== undefined ? {suspiciousOwner: attribution.suspiciousOwner} : {}),
    note,
  };
}

判定和 note 被拆成两个小函数,逻辑很短,但边界都在这里:

// src/repro.ts
function verdictFor(measured: ReproRound[], growth: number, budget: number, tolerance: number): ReproVerdict {
  if (measured.length < 2) {
    return 'insufficient-data';
  }
  if (growth <= budget + tolerance) {
    return 'stable';
  }
  const monotonic = measured.every((round) => round.delta >= -tolerance);
  return monotonic ? 'leak' : 'noisy';
}

function noteFor(verdict: ReproVerdict, growth: number, budget: number, rounds: number): string {
  switch (verdict) {
    case 'insufficient-data':
      return `仅完成 ${rounds} 个测量轮,至少需要 2 轮才能判断趋势。`;
    case 'stable':
      return `增长 ${growth} 未超过预算 ${budget},按噪声处理。`;
    case 'leak':
      return `${rounds} 个测量轮单调不减,增长 ${growth} 超过预算 ${budget}。`;
    case 'noisy':
      return `整体有增长但存在回落,先检查异步 settle 与缓存抖动。`;
  }
}

verdictFor 的顺序是 insufficient-data → stable → leak / noisy。测量轮少于 2 直接数据不足;growth <= budget + tolerance 直接 stable,即使中途有回落;超过预算后还要每轮 delta >= -tolerance 才判 leak,否则 noisy。attribute 比较 baseline 与末轮的 byKind / byOwner,取增长最大的一项;报告里的「归因 demo-feed / object」就是这条路径来的。

测试里跑了五组序列。平坦序列判 stable,baseline 3、growth 0、5 个测量轮 delta 全 0;每轮 +2 判 leak,baseline 4、growth 10、perRound 2、slope 2,rounds[i].delta 是 [2, 2, 2, 2, 2];[10, 12, 11, 14, 13] 判 noisy,growth 13,rounds[2].delta = -1,note 里带「回落」;只跑 1 个测量轮判 insufficient-data,note 里写「至少需要 2 轮」;budget=5 时每轮 +1、跑 3 轮,growth 3 仍判 stable。

异步这块还有两个用例:settle 在 7 个轮次(2 预热 + 5 测量)里各被调用一次;cycle 返回 Promise 时,snapshot 一定在 await 之后才读。settle 是宿主责任,库不替调用方等;异步回收没完成就采样,读到的是过程数据。

5.4 报告:固定顺序,能进 golden test

renderLeakReport 的目标是可归档、可比较、可进 CI:主表、Top offenders、复现明细、图片内存、通道审计、建议六块固定顺序;集合排序固定,没有数据时输出显式占位:

// src/report.ts
export function renderLeakReport(input: LeakReportInput): string {
  const title = input.title?.trim() || '未命名场景';
  const watch = input.watch;
  const candidates = input.candidates ?? [];
  const repro = input.repro;
  const image = input.image;
  const channel = input.channel;
  const now = input.now ?? watch?.at ?? 0;
  const lines: string[] = [];

  lines.push(`## LeakScope 报告 · ${title}`, '');
  lines.push('| 指标 | 值 |', '| --- | --- |');
  lines.push(`| 存活资源 | ${watch?.live ?? 0} |`);
  lines.push(`| 存活字节 | ${formatBytes(watch?.liveBytes ?? 0)} |`);
  lines.push(`| 已释放 | ${watch?.released ?? 0} |`);
  lines.push(`| 泄漏候选 | ${candidates.length} |`);
  lines.push(`| 复现结论 | ${repro ? reproSummary(repro) : '—'} |`);
  lines.push(`| 通道孤儿 | ${channel?.orphans.length ?? 0} |`, '');

  if (candidates.length > 0) {
    lines.push('### Top offenders', '');
    lines.push('| 资源 | 类型 | owner | 存活(ms) | 字节 |');
    lines.push('| --- | --- | --- | --- | --- |');
    for (const candidate of topOffenders(candidates)) {
      lines.push(
        `| ${escapeCell(candidate.key)} | ${candidate.kind} | ${escapeCell(candidate.owner ?? '—')} | ${Math.round(
          candidate.liveForMs,
        )} | ${formatBytes(candidate.bytes)} |`,
      );
    }
    lines.push('');
  }

  if (repro) {
    lines.push('### 复现明细', '');
    lines.push('| 轮次 | 指标 | 增量 |');
    lines.push('| --- | --- | --- |');
    for (const round of repro.rounds) {
      lines.push(
        `| ${round.index} | ${formatMetricValue(round.metric, repro.metricName)} | ${formatSignedMetric(
          round.delta,
          repro.metricName,
        )} |`,
      );
    }
    lines.push('');
  }

  if (image) {
    lines.push('### 图片内存', '');
    lines.push('| 指标 | 值 |');
    lines.push('| --- | --- |');
    lines.push(`| 条目 | ${image.entries} |`);
    lines.push(`| 存活 | ${formatBytes(image.liveBytes)} |`);
    lines.push(`| 峰值 | ${formatBytes(image.peakBytes)} |`);
    lines.push(`| 重复引用 | ${image.duplicates} |`);
    lines.push(`| 淘汰 | ${image.evictions} |`, '');
  }

  if (channel) {
    lines.push('### 通道审计', '');
    lines.push('| 通道 | 类型 | owner | 状态 | 存活(ms) |');
    lines.push('| --- | --- | --- | --- | --- |');
    const orphanIds = new Set(channel.orphans.map((record) => record.id));
    for (const record of channelRows(channel, now)) {
      const status = orphanIds.has(record.id) ? 'orphan' : 'active';
      lines.push(
        `| ${escapeCell(record.label || record.id)} | ${record.kind} | ${escapeCell(record.owner ?? '—')} | ${status} | ${Math.max(
          0,
          Math.round(now - record.openedAt),
        )} |`,
      );
    }
    lines.push('');
  }

  lines.push('### 建议', '');
  const suggestions = buildSuggestions(input, now);
  for (let index = 0; index < suggestions.length; index += 1) {
    lines.push(`${index + 1}. ${suggestions[index]}`);
  }

  return lines.join('\n');
}

排序逻辑分布在三个地方:topOffenders 按字节降序、key 升序;channelRows 把 orphan 排在 active 前面,再按年龄降序;buildSuggestions 最多保留 4 条。escapeCell 把 | 和换行转义,资源名里带竖线也不会把 markdown 表格撑坏。formatBytes 统一成 x.x KB / x.x MB / x.x GB,测试里 0 是 0.0 KB、3.2 MiB 是 3.2 MB、2.5 GiB 是 2.5 GB。

确定性由测试兜底:同一个 fixture 渲染两次,toBe 相等;报告里固定出现 | 存活资源 | 2 |、| 存活字节 | 14.0 MB |、| 复现结论 | LEAK(+64.0 MB / 5 轮) |;把 candidates 换成字节相同、key 不同的候选,Top offenders 里 a-large 排在 z-large 前,z-large 排在 z-small 前。空输入也有断言:| 存活资源 | 0 |、| 复现结论 | — |、建议区只保留一行,且不出现 ### Top offenders。

report.test.ts 的集成用例把这条链路走了一遍:scope.watch('initial', {kind: 'object', owner: 'feed', bytes: 1024}) 加 5 轮复现各 1 条,报告里是 存活资源 6、复现结论 LEAK(+5 / 5 轮);scopeClose('feed') 之后所有候选的 reason 都变成 unreleased-after-scope;dispose() 之后 isDisposed 为真,audit().active 为空,watch 记录仍然是 6 条。

6. 接入和运行时踩到的坑

optional peer 不等于「没有 React 依赖」。react / react-native 在 package.json 里是 optional peer,但根入口 src/index.ts re-export 了 useLeakScope;useLeakScope 又从 react 里 import useEffect / useRef。在 Node 服务里只 import 账本、却没装 react 时,解析根入口会报 Cannot find module 'react'。用 Hook 就装 react;纯 Node 场景也要给根入口一个 react 解析,或者把库拆成子路径导出;当前包只有根出口,这是已知边界。

别给纯 JS 包加 harmony.autolinking。 一开始想让 RNOH 识别这个包,差点在 package.json 里补上这个字段。一旦写了,RNOH CLI 会去壳层找 HAR 和 etsPackageClassName,而本库两者都没有,构建直接失败。正确做法是保持普通 npm 包形态:宿主 npm install leakscope-rn,Metro 读 src/index.ts,原生工程零改动。

Hermes 的 GC 不可观测,别拿 FinalizationRegistry 当判据。Hermes 不保证回调时机,部分版本/配置下根本不触发;即使触发,也只能说明对象被回收,不能说明它「何时应该被释放」。本库的判据全部是显式的:watch 声明开始持有、release 声明停止持有、scopeClose 声明页面结束。FinalizationRegistry 最多做兜底提示,不能替代 owner 与 scopeClose。

planImageDecode 只给计划,不会改 <Image>。 我一开始以为调用它之后图片就按目标尺寸解码了,结果 <Image> 仍按源图分配,账本里的 45.8 MB 和原生实际占用对不上。计划只是 sampleSize / targetWidth / targetHeight / bytes / reason;要让它生效,得把目标尺寸用于缩略图 URL、服务端裁剪参数或 resizeMultiplier。另外 <Image> 自带的原生缓存不在 JS 账本里,账本记录的是调用方给的计划值,跟原生实际分配是两码事。

ArkTS 侧的 emitter / TaskPool 不会自动出现在 JS 账本里。JS 只能看到桥接过来的事件,看不到 ArkTS 的 emitter、TaskPool、Worker 内部内存。原生事件如果已经通过 RNOH 的 NativeEventEmitter 暴露,用 trackEmitter;没有桥接的,就在 ArkTS 侧统计分配/释放,把差值通过已有回调上报,再在 JS 里 watch(key, {kind: 'native', bytes})。不要把 ArkTS 的 emitter 对象直接传给本库,它没有 addListener / removeListener 的 RN 形态。

useLeakScope 的 options 只在首次渲染读取。页面中途改 staleAfterMs / orphanAfterMs 不会重建 scope;需要不同阈值时直接 new LeakScope。同样,owner 必须由业务保证稳定;用随机 id 或组件实例 id,scopeClose 就失去意义,候选会永远对不上页面。

7. 包形态:一个 npm 包,不加 HAR

这是标准 React Native 三方库,跟 DevEco HAR 工程是两种形态;三个目录三种打开方式:

leakscope-rn/
├── src/                    # TypeScript 源码
│   ├── types.ts            # 数据模型与默认常量
│   ├── watch.ts            # LeakWatch
│   ├── repro.ts            # runLeakRepro
│   ├── imageMemory.ts      # bytesFor / ImageMemoryLedger / planImageDecode
│   ├── channel.ts          # ChannelLedger
│   ├── adapters.ts         # timer / emitter / promise 适配
│   ├── scope.ts            # LeakScope 门面
│   ├── report.ts           # 确定性 markdown
│   ├── react.ts            # useLeakScope Hook
│   └── index.ts            # 公共导出
├── lib/                    # 构建产物:commonjs / module / typescript
├── __tests__/              # 5 个 Vitest 文件、52 项
├── docs/                   # 分类、验证记录、包形态
├── example/
│   ├── App.tsx             # 宿主 RN / RNOH 工程里的示例页
│   └── README.md           # 运行前置条件
├── package.json
└── tsconfig.json

leakscope-rn 的目录与构建产物

这次设计的关键决定有三个。

纯 TS,零 RN 运行时依赖。核心账本不 import react-native;react / react-native 都是 optional peerDependency,只有 useLeakScope 需要 react。在 Node / Vitest 里可以只 import { LeakWatch, ImageMemoryLedger, ChannelLedger } 跑纯逻辑,不需要模拟器,也不需要 Metro。

没有 HAR,也不参与 RNOH autolinking:package.json 不写 harmony.autolinking,宿主把它当普通 npm 包安装,不需要改 oh-package.json5 或 EntryAbility;这个字段写错的后果见第 6 节。

示例是「可复制的页面」,不参与库的构建。example/App.tsx 直接 import react-native 与 leakscope-rn,它必须在宿主 RN / RNOH 工程里运行;tsconfig.json 把 example/ 排除掉,npm test 与 npm run build 都不会把它打进库里。这样库的构建不依赖宿主环境,示例又保留了完整的页面语义。

包形态的出口有三个:

{
  "source": "./src/index.ts",
  "main": "./lib/commonjs/index.js",
  "module": "./lib/module/index.js",
  "types": "./index.d.ts",
  "exports": {
    ".": {
      "react-native": "./src/index.ts",
      "import": { "types": "./lib/typescript/index.d.ts", "default": "./lib/module/index.js" },
      "require": { "types": "./lib/typescript/index.d.ts", "default": "./lib/commonjs/index.js" }
    }
  }
}

上面是 package.json 的入口字段,同一个文件里还有 scripts、files 与 devDependencies。Metro 走 react-native / source 字段直接读 TS;Node / 非 Metro 消费者走条件导出拿 CJS 或 ESM;类型由根 index.d.ts 指向 lib/typescript。npm pack 69 个文件、94,161 bytes,__tests__/、example/、node_modules/ 都不进 tarball。

不带 HAR 的接入点落在适配层。RN 的 DeviceEventEmitter、NativeEventEmitter、AppState 都只有结构化的 addListener,本库不 import 它们,只约定这个形状:

// src/adapters.ts
/**
 * Subscribes to an emitter and closes the channel when the returned handle is
 * removed.
 *
 * Accepts any object with `addListener`; the subscription's own `remove()` is
 * preferred, with `removeListener(event, listener)` used as a fallback. This is
 * the structural bridge that keeps RN emitters out of the compile graph.
 */
export function trackEmitter(
  ledger: ChannelLedger,
  emitter: EmitterLike,
  event: string,
  listener: EmitterListener,
  owner?: string,
): EmitterHandle {
  const handle = ledger.open({kind: 'emitter', label: event, ...(owner !== undefined ? {owner} : {})});
  let subscription: EmitterSubscriptionLike | void;
  try {
    subscription = emitter.addListener(event, listener);
  } catch (error) {
    ledger.close(handle.id);
    throw error;
  }

  let removed = false;
  return {
    remove: () => {
      if (removed) {
        return;
      }
      removed = true;
      try {
        if (subscription && typeof subscription.remove === 'function') {
          subscription.remove();
        } else {
          emitter.removeListener?.(event, listener);
        }
      } finally {
        ledger.close(handle.id);
      }
    },
  };
}

EmitterLike 只要求 addListener,removeListener 是可选的;remove() 优先用订阅自带的,没有才回退到 removeListener(event, listener)。try/finally 保证无论移除是否抛错,通道都会 close。宿主传进来的是 RN 的 emitter 实例,库这边拿到的只是一个普通对象,编译期不需要 react-native 的类型。

对使用方来说,三种用法各取所需:

// 单本账
const watch = new LeakWatch({now: () => 1000});
watch.watch('cover', {kind: 'image', owner: 'feed', bytes: 12 * 1024 * 1024});

// 三本账 + Hook
const scope = useLeakScope('feed');
scope.image.retain({key: 'cover', width: 1200, height: 800, dpr: 2, owner: 'feed'});
scope.channel.open({kind: 'timer', label: 'feed-refresh', owner: 'feed'});

// 复现 + 报告
const repro = await scope.repro((round) => {
  scope.watch(`round-${round}`, {kind: 'object', owner: 'feed', bytes: 1024});
}, {warmup: 2, rounds: 5});
console.log(scope.report('feed 页面', repro));

四段可以拆开用:只做生命周期就 new LeakWatch,只算图片就 new ImageMemoryLedger;useLeakScope 把三个账本和 owner 接在一起,不要求一次接全。

8. 从 npm install 到 RNOH 2in1

这个工程是「纯 TS 账本 + Hook + 可复制示例页」三件套(npm 包名 leakscope-rn,版本 1.0.0,Apache-2.0)。安装即用,不需要 link / autolinking / 原生工程改动:

npm install leakscope-rn
# 使用 useLeakScope 时(宿主 RN 工程本来就有 react)
npm install leakscope-rn react

跑库自测:

npm install
npm run verify
# tsc --noEmit 通过
# 5 files / 52 tests passed
# Babel 10 modules → lib/commonjs + lib/module;tsc → lib/typescript
npm pack --json
# 69 files / 94,161 bytes

npm run verify 的真实输出是 report 7、imageMemory 13、repro 9、watch 10、channel 13,合计 52 项;Babel 两次各编译 10 个模块,tsc -p tsconfig.types.json 生成 10 个声明文件。prepare 让 npm install 阶段就完成一次构建,新克隆的仓库不用先手动 build。

示例页要放进宿主 RN / RNOH 工程:

# 在 leakscope-rn 根目录
npm pack
# 在宿主工程根目录
npm install /absolute/path/to/leakscope-rn-1.0.0.tgz

把 example/App.tsx 复制为宿主页面(例如 src/pages/LeakScopeDemo.tsx),挂到导航或 App.tsx,然后按宿主的方式启动 Metro / 构建 HAP。示例页里的 setInterval、Pressable、ScrollView 都来自 RN 运行时;本库没有原生模块,也没有 ArkTS 代码。

2in1 宿主里的实测结果就是第 2 节那张图:A1 加载封面后图片账本 45.8 MB;A3 制造一次泄漏后通道活跃 1 / 孤儿 1;A4 复现 5 轮得到 增长 +5 / 斜率 1.00 / 归因 demo-feed / object;A5 生成报告,6 live / 261.0 KB / 6 candidates / LEAK(+5 / 5 轮)。页面卸载时 useLeakScope 执行 scopeClose + dispose,watch 记录保留,泄漏候选仍然可读。

仓库文档按用途分开:仓库说明是 API 全表和报告格式,OpenHarmony 接入说明写 RNOH 接入、Hermes 限制与 ArkTS emitter / TaskPool 上报,泄漏分类文档把 RN 泄漏分成订阅、timer、图片、原生回调、闭包等类型,验证与包检查记录列出 52 项测试与 69 文件 / 94,161 bytes 的结果。

边界也写清楚:本仓库只在 Node.js 24.12.0 + Vitest 上验证纯逻辑,不构建 example/,也不包含 RNOH 模拟器或真机截图;第 2 节截图来自宿主 RNOH 工程。报告不读取 Hermes 堆,不采集 RSS、原生图片缓存、GPU 纹理或 ArkTS 侧分配;react-native 的 Image 实际解码尺寸以原生上报为准。

这个包目前能回答「谁没释放、活了几轮、占了多少账本字节」;回答不了 ArkTS 堆和原生图片缓存。接下来想把它接进宿主的调试面板,让每次页面退出都留一份报告,先看一周的候选数能不能归零。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐