Files
cutdex/tool/diagnostics/benchmark_diagnostic_store.dart
lingjhf 27e77fff39 feat: initial Cutdex application
Add the Flutter video editing application with project management, media
import, timeline editing, preview, AI assistance, diagnostics and settings.

Include shared UI and native host packages, platform runners, application
tests and release tooling.

Provide usage and contribution guides, the MIT license and third-party
notices. Exclude local credentials, build outputs and validation data.
2026-10-05 23:36:23 +08:00

191 lines
5.8 KiB
Dart

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:cutdex/diagnostics/diagnostic_store.dart';
const _usage =
'Usage: dart run tool/diagnostics/benchmark_diagnostic_store.dart [--samples=7]';
Future<void> main(List<String> args) async {
if (args.contains('--help') || args.contains('-h')) {
stdout.writeln(_usage);
return;
}
var samples = 7;
if (args.isNotEmpty) {
samples = args.length == 1 && args.single.startsWith('--samples=')
? int.tryParse(args.single.substring('--samples='.length)) ?? 0
: 0;
if (samples < 1 || samples > 100) {
stderr.writeln(_usage);
exitCode = 2;
return;
}
}
final root = await Directory.systemTemp.createTemp('cutdex-log-benchmark-');
try {
final output = <Object?>[];
for (final workload in ['edit', 'error']) {
final count = workload == 'edit' ? 256 : 64;
final measured = <String, List<Map<String, num>>>{
for (final mode in ['disabled', 'perEventFlush', 'batched']) mode: [],
};
// Warm the serializer and file APIs before collecting samples; alternate order.
for (var round = -2; round < samples; round++) {
final modes = measured.keys.toList();
if (round.isOdd) {
modes.setAll(0, modes.reversed.toList());
}
for (final mode in modes) {
final result = await _sample(
root,
'$workload-$mode-$round',
workload,
count,
mode,
);
if (round >= 0) measured[mode]!.add(result);
}
}
output.add({
'workload': workload,
'records': count,
'modes': {
for (final mode in measured.entries)
mode.key: {
for (final key in mode.value.first.keys)
key: _median(mode.value.map((sample) => sample[key]!).toList()),
},
},
});
}
stdout.writeln(
const JsonEncoder.withIndent(' ').convert({
'runtime': Platform.version,
'os': Platform.operatingSystem,
'samples': samples,
'warmupRounds': 2,
'maxPending': 320,
'errorReserveRecords': 40,
'maxPendingBytes': 1024 * 1024,
'errorReserveBytes': 256 * 1024,
'method': 'Synthetic diagnostic record bursts, same store with batchSize=1 versus defaults; disabled measures harness overhead. No Flutter frames or media decoding measured.',
'results': output,
}),
);
} catch (error) {
stderr.writeln('Diagnostic benchmark failed: $error');
exitCode = 1;
} finally {
await root.delete(recursive: true);
}
}
Future<Map<String, num>> _sample(
Directory root,
String id,
String workload,
int count,
String mode,
) async {
final directory = Directory('${root.path}/$id');
final store = mode == 'disabled'
? null
: DiagnosticStore(
directory,
maxPending: 320,
batchSize: mode == 'perEventFlush' ? 1 : 32,
);
final records = [
for (var i = 0; i < count; i++)
{
'at': '2026-10-05T00:00:00.000Z',
'sessionId': 'session',
'level': workload == 'edit' ? 'info' : 'error',
'component': 'editor',
'operation': 'split',
'environment': {
'platform': 'macos',
'appVersion': '1.0.0',
'buildMode': 'release',
},
'context': {
'operationId': 'operation-$i',
'timelineId': 'timeline',
'sequenceId': 'sequence',
'clipIds': ['clip'],
'playheadTick': 5000000,
'versionBefore': 'before',
'versionAfter': 'after',
},
if (workload == 'error') ...{
'error': {
'type': 'StateError',
'message': 'Decoder rejected the requested frame',
},
'stackTrace': List.generate(
24,
(line) => '#$line editor.dart:120',
).join('\n'),
'stderr': 'decoder failure at selected frame\n' * 256,
},
},
];
final clock = Stopwatch()..start();
var previousTick = 0;
var maxTimerGapUs = 0;
final timer = Timer.periodic(const Duration(milliseconds: 1), (_) {
final now = clock.elapsedMicroseconds;
maxTimerGapUs = math.max(maxTimerGapUs, now - previousTick);
previousTick = now;
});
final latencies = <int>[];
final enqueueStart = clock.elapsedMicroseconds;
for (final record in records) {
final start = clock.elapsedMicroseconds;
store?.record(record);
latencies.add(clock.elapsedMicroseconds - start);
}
final enqueueUs = clock.elapsedMicroseconds - enqueueStart;
final drainStart = clock.elapsedMicroseconds;
await store?.flush();
final drainUs = clock.elapsedMicroseconds - drainStart;
timer.cancel();
if (store != null) {
var persisted = 0;
await for (final entity in directory.list()) {
if (entity is File && entity.path.endsWith('.jsonl')) {
for (final line in await entity.readAsLines()) {
jsonDecode(line);
persisted++;
}
}
}
if (persisted != count || store.dropped != 0 || store.writeFailures != 0) {
throw StateError(
'Invalid sample: expected $count, persisted $persisted, dropped ${store.dropped}, failures ${store.writeFailures}',
);
}
}
latencies.sort();
return {
'enqueueUs': enqueueUs,
'recordP95Us': latencies[(count * .95).ceil() - 1],
'drainUs': drainUs,
'totalUs': enqueueUs + drainUs,
'maxTimerGapUs': maxTimerGapUs,
'durableEventAppends': store?.eventFlushes ?? 0,
'eventBytesWritten': store?.eventBytesWritten ?? 0,
};
}
num _median(List<num> values) {
values.sort();
final middle = values.length ~/ 2;
return values.length.isOdd
? values[middle]
: (values[middle - 1] + values[middle]) / 2;
}