点一次「复现 5 轮」,账本上多出 7 条 card-1-*:2 轮预热加 5 轮测量,每条 2 MB,合计 14.0 MB;页面作用域一结束,这 7 条全都变成候选。Flutter 的 GC 只回答对象可不可达,不回答它为什么还被 StreamSubscription、Timer 或 ImageCache 牵着。这个工程把「谁登记、谁释放、页面什么时候结束」写成三本账,再用 5 轮复现和一份确定性 markdown 给出结论。2in1 模拟器上的读数、库里的真实函数和测试断言都在这篇记录里。

仓库地址:https://atomgit.com/oh-flutter/leakscope-flutter
版本地址:https://atomgit.com/CPF-Flutter/flutter_flutter/tree/oh-3.41.9-release
三方库框架:https://atomgit.com/oh-Flutter

0. 环境与实测设备

项版本/型号
DevEco Studio26.0.0(HarmonyOS SDK 26.0.0 Release / API 26),内置 hvigor 6.26.4
Flutter3.41.9+ohos-1.0.2(Dart 3.11.5)
鸿蒙 SDKOpenHarmony 7.0.0.107(API 26)
leakscope1.0.0(本仓库,纯 Dart package)
实测设备HarmonyOS 2in1 模拟器(127.0.0.1:5555),OpenHarmony 7.0.0.107(API 26),窗口 1100×697 @1.9x
示例宿主com.lqjmac.leakscope_flutter / EntryAbility,example/ohos/
验证flutter analyze 无 issue;库 50 用例 + 示例 1 个 widget 用例全过;dart pub publish --dry-run 通过校验,保留 1 条文档目录命名 warning(工作区有未提交修改时另加 1 条流程提示)
端侧结果复现 5 轮:7 live / 14.0 MB / LEAK;结束作用域后候选 7;手动通道后活跃 3;报告 55 行

命令输出和测试数字来自仓库的验证记录;没有跑过的部分,文末的边界说明里有交代。

1. dispose 之后,谁还拿着这块内存

Demo 里的 card-1-* 并没有真的分配 2 MB。它们是复现器登记的资源,bytes 是账面值,LeakScope 不抓堆,也不会替业务分配内存。这一点得先讲清楚,否则 14.0 MB 容易被误读成泄漏对象的真实大小。

页面下不来的原因在另一层。State.dispose() 执行时 widget 已经从树上摘掉,但下面这些引用还在:

StreamSubscription 的 _onData 闭包如果引用了 State 的字段或实例方法,订阅就会把 State 留在闭包里;State 又持有 _element,_element 牵着 render tree。Timer.periodic 的回调挂在事件循环上,没 cancel() 就一直等下一次触发,回调里的 setState 或 debugPrint 同样会带住页面对象。Isolate 的 ReceivePort 监听、Ticker 的回调、MethodChannel 的 Dart handler,都是「注册时创建闭包,注销时忘了摘」的形状。ImageCache 按 key 保存 ui.Image:图片文件可能只有 180 KiB,解码后按 宽 × 高 × 4 占内存,key 还是那个 ImageProvider。

DevTools 的 Memory 面板我也用过。flutter run --profile 起一遍,进两次详情页,heapUsed 涨了 80 MB;点一次 GC 能掉回去多少,取决于我点得快不快。debugPrint 能报出「涨了 80 MB」,报不出这 80 MB 里哪些是 ImageCache、哪些是没取消的订阅。堆快照能列 retainer,但它是手工分析,不进 CI,也受采样时机影响。

这个库换了个方向:不猜 GC,只记录业务能声明的事实。LeakWatch 记登记、释放和作用域结束;runLeakRepro 跑预热和测量轮,用增长、每轮增量和最小二乘斜率判趋势;ImageMemoryLedger 按解码尺寸记字节;ChannelLedger 记打开和关闭。所有账本共用一个可注入的 now,测试里没有 sleep。

先看设备上点出来的数字。

2. 设备上点出来的四个数字

Demo 是开发者工具风的单页应用:顶部四个按钮,下面四张指标卡,左边是生命周期 / 解码内存 / 通道审计三个账本,右边是 report.md 预览。设备是 HarmonyOS 2in1 模拟器,窗口 1100×697 @1.9x,顶部状态栏显示 owner=demo · OHOS 1100×697 @1.9x。

点一下「复现 5 轮」:

复现 5 轮后的指标卡

四张卡片依次是 存活资源 7、存活字节 14.0 MB、复现结论 LEAK、通道活跃 2。左栏的页面作用域还是「进行中」,泄漏候选是 0,report.md 显示「未生成」。底部状态栏是 scope=open · watch 7 · image 2 · channel 2。

按钮叫「复现 5 轮」,存活资源却是 7:runLeakRepro 默认预热 2 轮、测量 5 轮,一共 7 个 cycle;每个 cycle watch 一个 2 MB 的 card-$run-$round,7 条全留着,账面就是 7 × 2 MB = 14.0 MB。判定只看后 5 轮:baseline 是第 2 轮后的 2,末轮是 7,净增长 +5,报告里写 LEAK(+5 / 5 轮)。

接着按顺序点「结束页面作用域」→「打开未关闭通道」→「生成报告」:

结束作用域并打开通道后的报告

页面作用域变成「已结束」,泄漏候选从 0 跳到 7(7 条 card-1-* 都是 unreleased-after-scope);手动打开一个 MethodChannel 后通道活跃变成 3;report.md 变成 55 行,顶部主表是:

## LeakScope 报告 · 演示页面

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

Top offenders 默认列 5 行,能看到 card-1-0 … card-1-4,类型 image,owner demo,每条约 2.0 MB;报告里的图片内存是 2 条 / 16.0 MB;左栏的通道审计面板是活跃 3、孤儿 2、延迟关闭 0、手动打开 1。报告没有时间戳、没有随机排序,同样的输入会渲染出同样的字节。

窗口拖窄到 1000 逻辑像素以下,页面自动切单栏:指标条从 1×4 变成 2×2,报告卡排到台账卡上面,仍然可读:

窄窗口下的单栏布局

四个按钮各调一个函数:复现 5 轮 调 runLeakRepro,结束页面作用域 调 LeakScope.scopeClose,打开未关闭通道 调 ChannelLedger.open,生成报告 调 LeakScope.report。按钮没有在前端演数字。

3. 纯 Dart package,宿主只负责装进去

库本体在 lib/,示例在 example/,example/ohos/ 只是 Flutter-OHOS 演示宿主,不算包的一部分:

leakscope-flutter/
├─ lib/
│  ├─ leakscope.dart             # 公共导出 + leakScopeVersion
│  └─ src/
│     ├─ types.dart              # 数据模型、枚举、默认常量
│     ├─ watch.dart              # 生命周期台账
│     ├─ repro.dart              # 场景复现器
│     ├─ image_memory.dart       # 解码内存账本与 DecodePlan
│     ├─ channel.dart            # 通道开闭账本
│     ├─ scope.dart              # LeakScope 门面
│     ├─ binding.dart            # WidgetsBindingObserver + ImageCache
│     └─ report.dart             # 确定性 markdown
├─ test/                         # 库测试(50 个用例)
├─ example/
│  ├─ lib/main.dart              # 单页演示:watch / repro / image / channel
│  ├─ test/leak_demo_test.dart   # 1 个 widget 用例
│  └─ ohos/                      # Flutter-OHOS 2in1 宿主(signing/ 不入库)
├─ docs/                         # 泄漏分类、验证记录、包检查
├─ pubspec.yaml
└── README.md / README.OpenHarmony_CN.md

工程结构

leakscope 没有 android/、ios/、ohos/ 原生目录,没有 MethodChannel 原生实现,也没有 flutter.plugin.platforms。所有逻辑都是 Dart:订阅、定时器、图片和通道都在 Dart 侧记账。所以它在 Android / iOS / Flutter-OHOS 上走完全相同的代码路径;example/ohos/ 只是把示例装进 2in1 模拟器验收样式与交互。

LeakScope 构造时把 now 同时传给 LeakWatch、ImageMemoryLedger 和 ChannelLedger;report() 连续取快照、候选、图片统计和通道审计,台账内部用 snapshot.at 对齐同一时刻,图片和通道各取一次当前时钟。LeakScopeBinding 再把 WidgetsBindingObserver 的 didHaveMemoryPressure 和 Flutter 的 ImageCache 接进来——图片报告可以同时给出「账本 liveBytes」与「引擎 cacheBytes / cacheLimitBytes」。

Demo 的 initState 和 dispose 就是接入形状:

// example/lib/main.dart

void initState() {
  super.initState();
  _scope = LeakScope(owner: 'demo');
  _binding = LeakScopeBinding(scope: _scope)..attach();

  _controller = StreamController<int>.broadcast();
  _subscription = _controller.stream.listen((int value) {});
  _scope.trackSubscription(_subscription!, label: 'demo-stream');

  _timer = Timer(const Duration(minutes: 10), () {});
  _scope.trackTimer(_timer!, label: 'demo-timer');

  _scope.image
    ..retain(
      'feed-cover',
      width: 1200,
      height: 800,
      dpr: 2,
      owner: 'demo',
    )
    ..retain('avatar', width: 200, height: 200, dpr: 3, owner: 'demo');
  _scope.image.evictTo(defaultImageBudget);
}


void dispose() {
  _binding.detach();
  _scope.dispose();
  unawaited(_controller.close());
  _scrollController.dispose();
  super.dispose();
}

dispose() 里先 binding.detach(),再 scope.dispose()。scope.dispose() 会关掉所有登记过的通道,trackSubscription 和 trackTimer 传入的真实 cancel() 就在这时候执行。watch 台账保留,所以页面销毁后还能渲一份报告,看哪些资源没有 release。

dispose() 里没有 scopeClose(),这是 demo 的刻意安排:把「页面结束」做成按钮,才能看到 7 个 unreleased-after-scope 候选。真实接入时,顺序是 scope.dispose() → scope.scopeClose() → super.dispose()。

四个按钮的方法也在这个文件里:_runRepro 调 runLeakRepro,_closeScope 调 _scope.scopeClose(),_openChannel 调 _scope.channel.open(kind: ChannelKind.methodChannel, label: 'demo-bridge', owner: 'demo'),_renderReport 把 _scope.report(title: '演示页面', repro: _repro) 赋给 _report。

4. 登记、销账、标记作用域:LeakWatch 的三件事

LeakWatch 不做 GC 可达性推断,它只记录业务声明的「我拥有什么」和「什么时候释放」。同一个 key 在 live 期间重复 watch 只累加 duplicates,返回 false;release 把记录从 _live 里摘掉,历史里保留释放时间,重复调用返回 false;scopeClose 只打时间戳,不会替你释放任何东西:

// lib/src/watch.dart
bool watch(
  String key, {
  required LeakKind kind,
  String? label,
  String? owner,
  int bytes = 0,
  Map<String, Object?>? meta,
}) {
  if (bytes < 0) {
    throw ArgumentError.value(bytes, 'bytes', 'must not be negative');
  }
  final _WatchEntry? existing = _live[key];
  if (existing != null) {
    existing.duplicates += 1;
    return false;
  }
  final int now = _now();
  final _WatchEntry entry = _WatchEntry(
    key: key,
    kind: kind,
    label: label ?? key,
    owner: owner,
    bytes: bytes,
    meta: meta ?? const <String, Object?>{},
    watchedAt: now,
  );
  _history.add(entry);
  _live[key] = entry;
  _trimReleased();
  return true;
}

bool release(String key) {
  final _WatchEntry? entry = _live.remove(key);
  if (entry == null) {
    return false;
  }
  entry.releasedAt = _now();
  _trimReleased();
  return true;
}

void scopeClose(String owner) {
  _scopeClosedAt[owner] = _now();
}

bool isScopeClosed(String owner) => _scopeClosedAt.containsKey(owner);

int? scopeClosedAt(String owner) => _scopeClosedAt[owner];

候选原因在 _toCandidate 里按强度排序:owner 已 scopeClose、资源还 live,是 unreleased-after-scope;同一 key 在 live 时被重复 watch,是 duplicate-key;活过 staleAfterMs,是 stale。offenders() 还会把未到阈值的 live 资源按字节排出来,给 Top offenders 用。函数本身只有三十来行,优先级就是三个 if 的顺序:

// lib/src/watch.dart
LeakCandidate? _toCandidate(
  _WatchEntry entry,
  int at, {
  required bool includeFresh,
}) {
  final int liveMs = at - entry.watchedAt;
  final int safeLiveMs = liveMs < 0 ? 0 : liveMs;
  final int? scopeAt =
      entry.owner == null ? null : _scopeClosedAt[entry.owner];
  LeakReason reason;
  if (scopeAt != null) {
    reason = LeakReason.unreleasedAfterScope;
  } else if (entry.duplicates > 0) {
    reason = LeakReason.duplicateKey;
  } else if (safeLiveMs >= _staleAfterMs) {
    reason = LeakReason.stale;
  } else {
    reason = LeakReason.none;
  }
  if (reason == LeakReason.none && !includeFresh) {
    return null;
  }
  return LeakCandidate(
    key: entry.key,
    kind: entry.kind,
    label: entry.label,
    owner: entry.owner,
    bytes: entry.bytes,
    liveMs: safeLiveMs,
    reason: reason,
  );
}

at - watchedAt 可能是负数,比如测试把时钟往回拨,先归零再比较;scopeAt != null 只看 owner 是否结束,不看资源活了多少毫秒,所以页面刚退出也能立刻出候选。includeFresh 是给 offenders() 用的:candidates() 不要未到阈值的记录,offenders() 要,因为 Top offenders 表在页面还没结束时也要有内容。

maxRecords(默认 4096)超出时只淘汰已释放的历史,live 记录永不丢。4096 条记录每条只存 key、kind、owner、bytes、时间戳和 meta,开销很小;更容易把账本撑大的是 meta 里塞了 Bitmap 或完整 JSON,别这么干。scopeClose 不强制关闭,是因为它要抓的正是「页面结束了,资源还在」;如果它顺手把资源标成已释放,这个 bug 就被掩盖了。

如果先 release 再 scopeClose,候选会是 0。这不是漏报,资源确实还了;观测时把 scopeClose 放在页面销毁点,再决定哪些资源该在销毁前 release,账才对得上。test/watch_test.dart 的 9 个用例覆盖了登记、释放、幂等、scopeClose、stale、duplicate、重登记、offenders、历史上限和参数校验。

5. 五轮里怎么判出 LEAK

runLeakRepro 先跑 warmup 轮预热,不把这几轮算进测量;baseline 取最后一个预热轮的指标。第一轮常包含延迟初始化、首屏图片缓存填充和异步任务排队,2 轮预热是为了把一次性开销留在 baseline 之前。之后每轮执行 cycle、可选 settle、再采样台账。测量轮里记 delta,最后算 growth = 末轮 - baseline、perRound = growth / 测量轮数、slope 用测量轮对轮次做最小二乘。

判定顺序固定:测量轮少于 2 → insufficientData;growth <= budget + tolerance → stable;每轮增量都不低于 -tolerance → leak;否则 noisy。斜率只进报告,不参与判定。主函数把采样、baseline、判定和归因串在一起:

// lib/src/repro.dart
Future<ReproResult> runLeakRepro(
  FutureOr<void> Function(int round) cycle, {
  LeakWatch? watch,
  int warmup = defaultWarmupRounds,
  int rounds = defaultMeasureRounds,
  int budget = 0,
  int tolerance = 0,
  FutureOr<void> Function()? settle,
  int Function(LeakSnapshot)? metric,
  String metricName = 'live',
}) async {
  if (warmup < 0) {
    throw ArgumentError.value(warmup, 'warmup', 'must not be negative');
  }
  if (rounds < 0) {
    throw ArgumentError.value(rounds, 'rounds', 'must not be negative');
  }
  if (budget < 0) {
    throw ArgumentError.value(budget, 'budget', 'must not be negative');
  }
  if (tolerance < 0) {
    throw ArgumentError.value(tolerance, 'tolerance', 'must not be negative');
  }

  final LeakWatch ledger = watch ?? LeakWatch();
  final ReproOptions options = ReproOptions(
    warmup: warmup,
    rounds: rounds,
    budget: budget,
    tolerance: tolerance,
    metricName: metricName,
  );
  final int Function(LeakSnapshot) read =
      metric ?? (LeakSnapshot snapshot) => snapshot.live;

  // Baseline before any cycle. It is overwritten by the last warm-up round
  // when warmup > 0, and is the only baseline available when warmup == 0.
  LeakSnapshot baselineSnapshot = ledger.snapshot();
  int baseline = read(baselineSnapshot);
  LeakSnapshot? lastSnapshot;
  final List<int> measured = <int>[];
  final List<ReproRound> roundResults = <ReproRound>[];

  final int total = warmup + rounds;
  for (int i = 0; i < total; i++) {
    await cycle(i);
    if (settle != null) {
      await settle();
    }
    final LeakSnapshot snapshot = ledger.snapshot();
    final int value = read(snapshot);
    if (i < warmup) {
      baselineSnapshot = snapshot;
      baseline = value;
      continue;
    }
    final int previous = measured.isEmpty ? baseline : measured.last;
    measured.add(value);
    lastSnapshot = snapshot;
    roundResults.add(
      ReproRound(
        index: measured.length,
        metric: value,
        delta: value - previous,
        live: snapshot.live,
        liveBytes: snapshot.liveBytes,
      ),
    );
  }

  final int growth = measured.isEmpty ? 0 : measured.last - baseline;
  final double perRound = measured.isEmpty ? 0 : growth / measured.length;
  final double slope = _slope(measured);

  ReproVerdict verdict;
  String note;
  if (measured.length < 2) {
    verdict = ReproVerdict.insufficientData;
    note = 'need at least 2 measured rounds before judging a trend';
  } else if (growth <= budget + tolerance) {
    verdict = ReproVerdict.stable;
    note = 'growth is within budget + tolerance';
  } else {
    final bool monotonic = roundResults.every(
      (ReproRound round) => round.delta >= -tolerance,
    );
    if (monotonic) {
      verdict = ReproVerdict.leak;
      note = 'monotonic growth above budget + tolerance';
    } else {
      verdict = ReproVerdict.noisy;
      note = 'growth is above budget but not monotonic; '
          'check async settle and cache churn';
    }
  }

  LeakKind? suspiciousKind;
  String? suspiciousOwner;
  if (growth > 0 && lastSnapshot != null) {
    suspiciousKind = _fastestGrowingKind(
      baselineSnapshot.byKind,
      lastSnapshot.byKind,
    );
    suspiciousOwner = _fastestGrowingOwner(
      baselineSnapshot.byOwner,
      lastSnapshot.byOwner,
    );
  }

  return ReproResult(
    verdict: verdict,
    options: options,
    baseline: baseline,
    rounds: List<ReproRound>.unmodifiable(roundResults),
    growth: growth,
    perRound: perRound,
    slope: slope,
    suspiciousKind: suspiciousKind,
    suspiciousOwner: suspiciousOwner,
    note: note,
  );
}

baseline 先取运行前的快照,预热轮每轮覆盖它,所以有预热时 baseline 是最后一个预热轮的值;measured 只收测量轮,delta 用前一测量轮(第一轮用 baseline)来算。归因只在 growth > 0 时做,避免稳定场景里报一个没有增长的方向。

斜率单独抽成函数,轮次从 1 开始:

// lib/src/repro.dart
double _slope(List<int> values) {
  final int n = values.length;
  if (n < 2) {
    return 0;
  }
  final double meanX = (n + 1) / 2;
  int sum = 0;
  for (final int value in values) {
    sum += value;
  }
  final double meanY = sum / n;
  double numerator = 0;
  double denominator = 0;
  for (int i = 0; i < n; i++) {
    final double dx = (i + 1) - meanX;
    numerator += dx * (values[i] - meanY);
    denominator += dx * dx;
  }
  if (denominator == 0) {
    return 0;
  }
  return numerator / denominator;
}

按字节复现时把 metric 换成 (snapshot) => snapshot.liveBytes,metricName 传 liveBytes,报告就会按 MB 格式化。下面是 test/repro_test.dart 里按字节 metric 的那个用例,断言了 verdict、baseline、增长、每轮均值、斜率和末轮字节:

// test/repro_test.dart
test('supports a byte metric and computes per-round and slope', () async {
  final LeakWatch watch = LeakWatch(now: () => 0);
  const int oneMiB = 1024 * 1024;
  final ReproResult result = await runLeakRepro(
    (int round) {
      watch.watch(
        'image-$round',
        kind: LeakKind.image,
        owner: 'feed',
        bytes: oneMiB,
      );
    },
    watch: watch,
    metric: (LeakSnapshot snapshot) => snapshot.liveBytes,
    metricName: 'liveBytes',
  );

  expect(result.verdict, ReproVerdict.leak);
  expect(result.metricName, 'liveBytes');
  expect(result.baseline, 2 * oneMiB);
  expect(result.growth, 5 * oneMiB);
  expect(result.perRound, closeTo(oneMiB, 0.001));
  expect(result.slope, closeTo(oneMiB, 0.001));
  expect(result.rounds.last.liveBytes, 7 * oneMiB);
});

Demo 的数学和这个用例一样,只是单位换成 2 MB:7 个 cycle 是 2 预热 + 5 测量,baseline 2,末轮 7,growth = +5、perRound = 1、slope = 1,每轮增量都是 +1,所以判 LEAK,没降级成 NOISY。suspiciousKind / suspiciousOwner 取 byKind / byOwner 增长最大的项,报告里就是 image / demo。报告里的复现明细,就是这五行:

轮次指标增量
13+1
24+1
35+1
46+1
57+1

这里的指标记的是 live 条数;按字节复现时 metric 传 liveBytes,报告就会按字节格式化。斜率 1.0 和每轮 +1 是同一件事的两种读法:斜率对两端异常值更敏感,所以判定仍要看每一轮的 delta。

如果 settle 没等异步释放完成,采样看到的是过程:某一轮涨、某一轮跌,monotonic 不成立,结果会降级成 NOISY。settle 是宿主责任,Future<void>.delayed(const Duration(milliseconds: 80))、WidgetsBinding.instance.endOfFrame、或者等一次数据库清理都行,关键是它真的等到资源释放。test/repro_test.dart 的 9 个用例覆盖 leak、stable、noisy、tolerance、budget、insufficient-data、字节 metric + 斜率、cycle / settle 顺序和参数校验。

6. 图片账本:解码字节和缓存字节是两套数

文件大小和解码尺寸是两回事。bytesFor 的公式是 ceil(width × dpr) × ceil(height × dpr) × bytesPerPixel。Demo 的两张图:1200×800、dpr=2 是 2400×1600×4 = 15,360,000 B(约 14.6 MB);200×200、dpr=3 是 600×600×4 = 1,440,000 B(约 1.37 MB),合计约 16.0 MB。换成 3024×4032、dpr=3 的相机图,全量 9072 × 12096 × 4 = 438,939,648 字节(约 418.6 MB)。

planImageDecode 用 2 的幂 sampleSize 同时满足最长边(默认 4096)和字节预算。超 maxDimension 记 dimension,只超 maxBytes 记 budget,都满足为 fits。下面是完整函数,参数校验没有删:

// lib/src/image_memory.dart
DecodePlan planImageDecode({
  required int width,
  required int height,
  double dpr = 1.0,
  ImageFormat format = ImageFormat.argb8888,
  int? maxBytes,
  int maxDimension = defaultMaxDimension,
}) {
  if (width <= 0) {
    throw ArgumentError.value(width, 'width', 'must be positive');
  }
  if (height <= 0) {
    throw ArgumentError.value(height, 'height', 'must be positive');
  }
  if (dpr <= 0) {
    throw ArgumentError.value(dpr, 'dpr', 'must be positive');
  }
  if (maxDimension <= 0) {
    throw ArgumentError.value(
      maxDimension,
      'maxDimension',
      'must be positive',
    );
  }
  if (maxBytes != null && maxBytes <= 0) {
    throw ArgumentError.value(maxBytes, 'maxBytes', 'must be positive');
  }

  final int targetWidth = (width * dpr).ceil();
  final int targetHeight = (height * dpr).ceil();
  final int bpp = format.bytesPerPixel;
  final int fullBytes = targetWidth * targetHeight * bpp;
  final bool dimensionExceeded =
      targetWidth > maxDimension || targetHeight > maxDimension;

  int sampleSize = 1;
  while (true) {
    final int scaledWidth = _ceilDiv(targetWidth, sampleSize);
    final int scaledHeight = _ceilDiv(targetHeight, sampleSize);
    final int bytes = scaledWidth * scaledHeight * bpp;
    final bool tooWide =
        scaledWidth > maxDimension || scaledHeight > maxDimension;
    final bool tooLarge = maxBytes != null && bytes > maxBytes;
    if (!tooWide && !tooLarge) {
      break;
    }
    if (scaledWidth <= 1 && scaledHeight <= 1) {
      break;
    }
    sampleSize *= 2;
  }

  final int scaledWidth = _ceilDiv(targetWidth, sampleSize);
  final int scaledHeight = _ceilDiv(targetHeight, sampleSize);
  final int bytes = scaledWidth * scaledHeight * bpp;
  final bool downscaled = sampleSize > 1;
  final DecodeReason reason;
  if (!downscaled) {
    reason = DecodeReason.fits;
  } else if (dimensionExceeded) {
    reason = DecodeReason.dimension;
  } else {
    reason = DecodeReason.budget;
  }

  return DecodePlan(
    sampleSize: sampleSize,
    targetWidth: scaledWidth,
    targetHeight: scaledHeight,
    bytes: bytes,
    fullBytes: fullBytes,
    downscaled: downscaled,
    reason: reason,
  );
}

int _ceilDiv(int value, int divisor) => (value + divisor - 1) ~/ divisor;

循环每次都把 sampleSize 翻倍,最小是 1,且始终是 2 的幂;如果预算小到一个像素都放不下,循环会在 1×1 停住,返回 budget,不会死循环。targetWidth / targetHeight 是降采样后的尺寸,fullBytes 是全量成本,两个都留下,报告里才能看出省了多少。

ImageMemoryLedger 对同一个 key 做引用计数,重复 retain 只加 refs 和 duplicates,不重复计字节;evictTo 按 lastUsed 做 LRU,lastUsed 相同再按 key 排,保证确定性;ImageMemoryReport.fromImageCache(cache) 把 Flutter ImageCache 的 currentSizeBytes / liveImageCount / maximumSizeBytes 折成同一份报告结构,mergeCache 再把实时缓存附到账本统计上。

这里有两套统计:账本 liveBytes 只统计显式 retain 的 key,ImageCache.currentSizeBytes 是 Flutter 引擎按自己的策略统计的解码缓存。两个数不能直接相减,交叉核对要靠上面的 mergeCache;两个预算也要显式对齐,不能假设它们相等。

LeakScopeBinding 负责把两边折进同一份快照。它同时是 WidgetsBindingObserver,didHaveMemoryPressure 到达时只记一个时间戳,不主动清缓存;清不清、清多少,仍由业务决定:

// lib/src/binding.dart
void attach() {
  if (_attached) {
    return;
  }
  _bindingOrInstance.addObserver(this);
  _attached = true;
}

void detach() {
  if (!_attached) {
    return;
  }
  _bindingOrInstance.removeObserver(this);
  _attached = false;
}


void didHaveMemoryPressure() {
  _memoryPressureEvents.add(MemoryPressureEvent(at: _now()));
}

LeakBindingSnapshot snapshot() {
  final LeakSnapshot watchSnapshot = _scope.watch.snapshot();
  final ImageMemoryReport images = ImageMemoryReport.fromStats(
    _scope.image.stats(),
  ).mergeCache(PaintingBinding.instance.imageCache);
  return LeakBindingSnapshot(
    at: _now(),
    watch: watchSnapshot,
    images: images,
    memoryPressureEvents: _memoryPressureEvents.length,
  );
}

attach / detach 是幂等的,重复调用不会重复注册 observer;snapshot() 里 mergeCache 把 ImageCache 的 liveImageCount、currentSizeBytes、maximumSizeBytes 附到账本统计上,source 变成 merged。这样快照里既有账本自己的 16.0 MB,也有引擎缓存的实际读数;两个数差得远,就说明两套统计覆盖的 key 不一致。实际渲染报告时,LeakScope.report 仍用 image.stats(),要交叉核对得看 binding.snapshot().images。test/binding_test.dart 的 3 个用例覆盖 attach / detach、内存压力事件和 ImageCache 合并。

test/image_memory_test.dart 的 15 个用例覆盖 dpr / bpp、引用计数、重复引用、LRU 淘汰、峰值、清空、DecodePlan 的 fits / dimension / budget、2 的幂和 ImageCache 快照;其中 fits / dimension / budget 三个分支各有用例。

7. 通道账本:打开有记录,关闭没记录

StreamSubscription、Timer、Isolate、Ticker、MethodChannel / EventChannel 在这个库里都记成通道。open 登记,close 记录关闭时间并执行真实 cancel() / kill() / dispose();scopeClose(owner) 之后再关闭记为 lateClose;超过 orphanAfterMs 仍 active 就是 orphan。trackSubscription / trackTimer / trackIsolate / trackTicker 把「登记 + 真实取消」合成一个句柄:

// lib/src/channel.dart
ChannelHandle open({
  String? id,
  required ChannelKind kind,
  String? label,
  String? owner,
  Map<String, Object?>? meta,
  ChannelCloser? onClose,
}) {
  final String resolvedId = id ?? _nextId(kind);
  if (_records.containsKey(resolvedId)) {
    throw ArgumentError.value(resolvedId, 'id', 'already open');
  }
  final String resolvedLabel = label ?? resolvedId;
  final ChannelRecord record = ChannelRecord(
    id: resolvedId,
    kind: kind,
    label: resolvedLabel,
    owner: owner,
    openedAt: _now(),
    meta: meta ?? const <String, Object?>{},
  );
  _records[resolvedId] = record;
  if (onClose != null) {
    _closers[resolvedId] = onClose;
  }
  return ChannelHandle._(
    ledger: this,
    id: resolvedId,
    kind: kind,
    label: resolvedLabel,
    owner: owner,
  );
}

bool close(String id) {
  final ChannelRecord? record = _records[id];
  if (record == null || record.closedAt != null) {
    return false;
  }
  final int now = _now();
  final int? scopeAt =
      record.owner == null ? null : _scopeClosedAt[record.owner];
  final bool late = scopeAt != null && now >= scopeAt;
  _records[id] = record.copyWith(closedAt: now, lateClose: late);
  if (late) {
    _lateCloses += 1;
  }
  final ChannelCloser? closer = _closers.remove(id);
  if (closer != null) {
    closer();
  }
  return true;
}

void scopeClose(String owner) {
  _scopeClosedAt[owner] = _now();
}

open 的 id 必须唯一,重复打开会抛 ArgumentError;close 第一次生效,后续调用直接返回 false。onClose 在记录更新之后才执行,所以即使 cancel() 抛异常,账本已经记下了关闭;反过来,如果 cancel() 有异步副作用,账本不会 await 它。ChannelCloser 是同步回调,StreamSubscription.cancel() 的 Future 是 fire-and-forget,这和 Flutter widget 的常规 dispose 行为一致。

audit() 才把「谁还开着」变成数字。它取当前时钟、筛出存活时间达到阈值的记录,再按 ChannelKind 汇总:

// lib/src/channel.dart
ChannelAudit audit({int? orphanAfterMs}) {
  final int threshold = orphanAfterMs ?? _orphanAfterMs;
  if (threshold < 0) {
    throw ArgumentError.value(
      threshold,
      'orphanAfterMs',
      'must not be negative',
    );
  }
  final int now = _now();
  final List<ChannelRecord> open = active;
  final List<ChannelRecord> orphans = open
      .where((ChannelRecord record) => record.aliveMs(now) >= threshold)
      .toList();
  final Map<ChannelKind, int> byKind = <ChannelKind, int>{};
  for (final ChannelRecord record in open) {
    byKind.update(
      record.kind,
      (int value) => value + 1,
      ifAbsent: () => 1,
    );
  }
  return ChannelAudit(
    at: now,
    opened: _records.length,
    closed: _records.length - open.length,
    active: open,
    orphans: List<ChannelRecord>.unmodifiable(orphans),
    lateCloses: _lateCloses,
    byKind: Map<ChannelKind, int>.unmodifiable(byKind),
    orphanAfterMs: threshold,
  );
}

孤儿阈值可以每次审计时覆盖,audit(orphanAfterMs: 0) 在测试里很好用:任何仍 active 的通道立刻算孤儿,不用等 5 秒。opened 是历史打开总数,closed 是 总数 - active,lateCloses 单独累计;byKind 只看 active,不把已关闭的算进去。Demo 的通道活跃 3、孤儿 2,就是 active.length 和 orphans.length 两个字段。

staleAfterMs 和 orphanAfterMs 默认都是 5000 ms,前者看 LeakWatch 的 live 时长,后者看 ChannelLedger 的 active 时长。短生命周期页面可以把阈值调小,长驻页面要调大;这两个值只影响候选和孤儿,不影响 growth / slope 的判定。Demo 用的是默认值,设备上生成报告时这两个通道的存活时间已经超过 5 秒,所以孤儿是 2;如果点得太快,同一个页面会显示 0 个孤儿。想让 demo 每次都稳定出数,构造 LeakScope 时把 orphanAfterMs 调到 300 ms 即可。

Demo 里最初的 demo-stream 和 demo-timer 是两个真实资源,track* 打开时把真实的 cancel() 传进去;页面真正销毁时,scope.dispose() 会调 channel.closeAll(),把 timer 和 subscription 取消掉。报告生成时页面还活着,所以这两个仍在 active。手动打开的 demo-bridge 只登记 MethodChannel 的开闭,ArkTS 侧 handler 仍由宿主插件负责。

ChannelLedger 不做 GC 可达性推断,只记 Flutter 侧何时 open、何时 close。test/channel_test.dart 的 10 个用例覆盖孤儿、lateClose、提前关闭、closeAll(owner)、句柄幂等、id 唯一、reset、真实 Timer / StreamSubscription 和 dispose。

8. 报告为什么能做到 55 行不变

LeakScope.report() 是门面,负责把生命周期、图片和通道三个账本组装成一份报告,再传给 renderLeakReport。snapshot.at 会同时传给 candidates 和 offenders,让资源存活时长和候选判定用同一个时刻;图片的 stats() 和通道的 audit() 各读一次自己的时钟:

// lib/src/scope.dart
String report({
  String title = '泄漏观测',
  ReproResult? repro,
  int maxOffenders = 5,
}) {
  final LeakSnapshot snapshot = watch.snapshot();
  return renderLeakReport(
    LeakReportInput(
      title: title,
      snapshot: snapshot,
      candidates: watch.candidates(at: snapshot.at),
      topOffenders: watch.offenders(at: snapshot.at, limit: maxOffenders),
      repro: repro,
      imageStats: image.stats(),
      channelAudit: channel.audit(),
    ),
  );
}

renderLeakReport 不读时间、不读随机数、不做 locale 排序;所有表都显式排序,缺省数据按节处理:主表始终在,Top offenders 空时留占位,其余节按输入决定是否出现。同样的输入必须得到字节相同的 markdown,才能进 CI 的 golden test:

// lib/src/report.dart
String renderLeakReport(LeakReportInput input) {
  final StringBuffer buffer = StringBuffer();
  buffer.writeln('## LeakScope 报告 · ${input.title}');
  buffer.writeln();
  buffer.writeln('| 指标 | 值 |');
  buffer.writeln('| --- | --- |');
  buffer.writeln('| 存活资源 | ${input.snapshot.live} |');
  buffer.writeln('| 存活字节 | ${_formatBytes(input.snapshot.liveBytes)} |');
  buffer.writeln('| 已释放 | ${input.snapshot.released} |');
  buffer.writeln('| 泄漏候选 | ${input.candidates.length} |');
  buffer.writeln('| 复现结论 | ${_verdictValue(input.repro)} |');
  buffer.writeln(
    '| 通道孤儿 | ${input.channelAudit == null ? '—' : input.channelAudit!.orphans.length} |',
  );
  buffer.writeln();

  _writeTopOffenders(buffer, input);
  if (input.repro != null) {
    _writeRepro(buffer, input.repro!);
  }
  if (input.imageStats != null) {
    _writeImage(buffer, input.imageStats!);
  }
  if (input.channelAudit != null) {
    _writeChannels(buffer, input.channelAudit!, input.maxOffenders);
  }
  _writeSuggestions(buffer, input);
  return buffer.toString();
}

主表下面依次是 Top offenders、复现明细、图片内存、通道审计、建议;repro / imageStats / channelAudit 为 null 时,对应三节整节不渲染,Top offenders 为空时留一行占位,主表和建议始终存在。_formatBytes 按 < 1 MiB → KB、< 1 GiB → MB、否则 GB,保留 1 位小数;Top offenders 按字节降序、存活时间降序、key 升序;通道表按「orphan 优先、存活时间降序、id 升序」;建议按「LEAK / NOISY → 作用域结束后仍存活 → 图片重复 / 淘汰 / 超预算 → 通道 orphan / lateClose → stale / duplicate-key」生成,最多 maxSuggestions 条。

报告里没有 generatedAt 字段,这是刻意的:时间一进报告,两次运行的 diff 就会多出一行噪声。需要时间就由调用方在外部记,报告只对账本负责。建议默认最多 4 条,Top offenders 默认最多 5 行;这两个上限只影响展示,不改账本统计。Demo 的 report.md 是 55 行;test/report_test.dart 用另一组固定数据做逐字节比对(那组数据渲染出来 50 行),4 个用例覆盖逐字节比对、确定性排序、空数据占位和建议数量上限。

9. 报错、误判和一次写反的顺序

先 scopeClose() 再 dispose(),lateClose 全来了。我最初把「页面结束」理解成「先打标记,再清理」,结果所有在 dispose 里关闭的通道都被算成 lateClose,audit().lateCloses 直接非 0。scopeClose() 只写时间戳,真正取消资源的是后面的 dispose();顺序反过来,正常清理也会被算成页面结束之后才发生。清理发生在页面结束之后的,才是隐性泄漏。

debug HAP 覆盖安装沿用旧 flutter_assets,引擎直接报 Invalid vm isolate snapshot seen / FML KILL PROCESS。用 hdc install -r 覆盖安装时,设备可能保留上一次的 flutter_assets;先 hdc uninstall com.lqjmac.leakscope_flutter 再安装就恢复正常。这是调试 HAP 的资源缓存行为,跟库逻辑无关;CI 里装 debug 包时也建议先卸载。

dart pub publish --dry-run 报文档目录命名 warning。Pub 约定顶层文档目录用单数 doc/,而 LeakScope 家族规范要求每个仓库使用验证记录 / 包检查记录 / 泄漏分类文档,方便六个平台仓库的文档路径一致。当前保留文档目录并记录 1 条 warning(工作区有未提交修改时 dry-run 还会多 1 条流程提示),它不影响依赖、编译、运行,也不影响 Flutter-OHOS 接入。要么接受 warning,要么改目录并同步所有链接,别只改一半。

ImageCache.currentSizeBytes 和账本 liveBytes 是两套统计。有次拿 ImageCache 的字节数当账本,发现「账本 16.0 MB、缓存 100 MiB 上限」对不上。前者是 Flutter 引擎按自己的策略统计的解码缓存,后者只统计显式 retain 的 key;ImageMemoryReport.fromImageCache() / mergeCache() 才能把两边放在同一份报告里。另外 ImageCache.maximumSizeBytes 默认 100 MiB,而库的 defaultImageBudget 是 64 MiB,两个预算要显式对齐。

planImageDecode 只给计划,不会自动改 Image widget。我一度以为调用它之后就自动降采样了,结果图片还是按原尺寸解码。计划只是 targetWidth / targetHeight / bytes / reason;要生效,得把 targetWidth / targetHeight 传给 Image.network(url, cacheWidth: plan.targetWidth) 或 ResizeImage。算账和渲染是两件事,别把计划当执行。

MethodChannel / EventChannel 的 ArkTS handler 不在 Dart 账本里。库只记录 Flutter 侧何时 open、何时 close;如果 ArkTS 侧的 handler 没释放,Dart 账本看不到。Demo 手动打开的 demo-bridge 只是一个开闭记录,原生 handler 本身仍要宿主插件自己实现、自己释放。跨端账本要两边都记,别拿 Dart 的 0 orphan 当成原生侧没问题。

onClose 里的 cancel() 返回 Future,但账本不会 await。ChannelCloser 是同步回调,StreamSubscription.cancel() 的 Future 是 fire-and-forget,这和 Flutter widget 的常规 dispose 行为一致;如果取消有异步副作用(比如关文件、断连接),要在业务侧自己等,或者在 settle 里等。账本负责「登记关闭」,不负责「等异步清理完成」。

scopeClose() 不会替你释放资源。它只记录 owner 的结束时刻,让仍 live 的资源变成 unreleased-after-scope 候选。释放要靠 dispose() / closeAll() / 业务自己的 release;dispose() 之后仍 track* 会抛 StateError,这是刻意设计,用来抓「页面销毁后仍创建资源」。观测工具不能替业务做释放决定,否则它会把要抓的 bug 一起掩盖掉。

10. 现在怎么接、验证到哪一步

这个工程是一个标准 Flutter package(包名 leakscope,版本 1.0.0,Apache-2.0),示例在 example/。包尚未发布到 pub.dev,当前用 path 或 git 依赖;发布后可以直接 flutter pub add leakscope:

dependencies:
  leakscope:
    path: ../leakscope-flutter
    # 或者:
    # leakscope:
    #   git:
    #     url: https://atomgit.com/oh-flutter/leakscope-flutter.git
    #     ref: main
flutter pub get
flutter analyze      # No issues found!
flutter test         # 50 个用例
cd example && flutter pub get && flutter analyze && flutter test

库和示例的真实输出:

$ flutter analyze
No issues found! (ran in 1.1s)

$ flutter test
00:00 +50: All tests passed!

$ cd example && flutter test
00:00 +1: All tests passed!

flutter pub get 还会提示 7 个传递依赖有新版本与当前 SDK 约束不兼容(clock 1.1.2、matcher 0.12.19、material_color_utilities 0.13.0 等),这是 Flutter SDK 锁定版本,不是本包的问题。dart pub publish --dry-run 打包 53 KB,只有文档目录目录命名 1 条 warning;加入截图和 2in1 宿主后压缩包变成 287 KB,warning 变成 2 条(后出现的那个是工作区未提交修改的流程提示)。

50 个用例按文件分布:watch_test.dart 9 个、repro_test.dart 9 个、image_memory_test.dart 15 个、channel_test.dart 10 个、report_test.dart 4 个、binding_test.dart 3 个。所有时间相关用例都注入 int Function() now,复现轮次使用同步 cycle / 异步 settle,没有 sleep、没有网络、没有随机数。

示例自测会跑 5 轮复现并看到 LEAK、结束页面作用域、打开一个未关闭通道、滚动到报告并检查 ## LeakScope 报告 · 演示页面 与固定结论行 LEAK(+5 / 5 轮);最后卸载页面,触发 LeakScope.dispose() 取消真实 Timer / StreamSubscription。

Flutter-OHOS 的 2in1 宿主在 example/ohos/,构建、签名与安装步骤:

export DEVECO_SDK_HOME="<DevEco SDK 路径>"
export PATH="<DevEco Studio 安装目录>/tools/hvigor/bin:$PATH"

cd example
flutter build hap --debug --no-codesign
# 用本地 debug profile 签名,材料不入库
hdc uninstall com.lqjmac.leakscope_flutter
hdc install leakscope-flutter-signed.hap
hdc shell aa start -b com.lqjmac.leakscope_flutter -a EntryAbility

在 2in1 模拟器上的实际结果:复现 5 轮 → 7 live / 14.0 MB / LEAK(+5 / 5 轮) / 通道活跃 2;结束页面作用域 → 泄漏候选 7;打开未关闭通道 → 通道活跃 3;生成报告 → 55 行 markdown,Top offenders、图片内存、通道审计与固定结论行都正常渲染。窗口拖窄到 1000 逻辑像素以下自动切单栏,指标条变 2×2。设备侧命令的输出是 install bundle successfully、start ability successfully、first-frame fired。

更完整的 API、阈值与误报说明、Flutter-OHOS 接入边界在仓库文档里:

  • 仓库说明:完整 API、快速开始、报告格式、阈值与误报;
  • OpenHarmony 接入说明:Flutter-OHOS 接入、MethodChannel 边界、生命周期建议;
  • 泄漏分类文档:Flutter 泄漏的症状 / 定位 / 修复;
  • 验证与包检查记录:flutter analyze / flutter test / dart pub publish --dry-run 的结果;
  • 2in1 宿主说明:构建、签名与安装。

边界写在这里:本库是纯 Dart package,不覆盖 Flutter 引擎的 native 分配、ArkTS 侧对象、图片解码器的临时缓冲区和 GPU 显存;ImageCache.currentSizeBytes 与账本 liveBytes 是两套统计;onClose 的异步 cancel 不会被 await;报告不替代 DevTools、flutter run --profile 与真机内存曲线。本次只验证了 HarmonyOS 2in1 模拟器(API 26),不是鸿蒙真机;Android / iOS / 桌面宿主共用同一份 Dart 源码,但没有逐平台截图。

当前版本在 Flutter 3.41.9+ohos-1.0.2 / Dart 3.11.5 / OpenHarmony 7.0.0.107(API 26)上验证:flutter analyze 无 issue,库 50 个用例、示例 1 个 widget 用例全过;2in1 模拟器上 hdc install、aa start、first-frame fired 均正常,复现、作用域、通道与报告都跑通了。设备上点出来的报告是 55 行,测试里逐字节比对的是另一组固定数据;还缺一份业务页面的数据,ArkTS 侧 handler 与引擎 native 分配也没有读数。

Logo

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

更多推荐