import 'dart:convert'; import 'dart:io'; import 'package:cutdex/diagnostics/diagnostic_store.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:uuid/uuid.dart'; void main() { late Directory root; setUp(() async { root = await Directory.systemTemp.createTemp('cutdex-diagnostics-'); }); tearDown(() => root.delete(recursive: true)); DiagnosticStore store({int pending = 256}) => DiagnosticStore( Directory('${root.path}/logs'), maxFileBytes: 1024, fileCount: 3, maxPending: pending, ); Future> bundle(DiagnosticStore value) async => jsonDecode( await (await value.export( Directory('${root.path}/out'), const {}, )).readAsString(), ) as Map; test( 'ordinary records wait for the deadline then share one durable append', () async { final value = DiagnosticStore( Directory('${root.path}/logs'), flushInterval: const Duration(milliseconds: 20), ); for (var i = 0; i < 8; i++) { value.record({'index': i}); } expect( File('${value.directory.path}/events-0.jsonl').existsSync(), isFalse, ); final deadline = Stopwatch()..start(); while (value.eventWriteBatches == 0 && deadline.elapsedMilliseconds < 5000) { await Future.delayed(const Duration(milliseconds: 5)); } expect(value.eventWriteBatches, 1); await value.flush(); expect(value.eventFlushes, 1); expect(value.pendingRecords, 0); expect(value.pendingEventBytes, 0); expect((await bundle(value))['events'], hasLength(8)); }, ); test( 'count threshold writes early and explicit flush drains the remaining tail', () async { final value = DiagnosticStore( Directory('${root.path}/logs'), batchSize: 32, flushInterval: const Duration(days: 1), ); for (var i = 0; i < 32; i++) { value.record({'index': i}); } final deadline = Stopwatch()..start(); while (value.pendingRecords != 0 && deadline.elapsedMilliseconds < 5000) { await Future.delayed(const Duration(milliseconds: 5)); } expect(value.pendingRecords, 0); expect(value.eventFlushes, 1); value.record({'index': 32}); await value.flush(); expect(value.eventFlushes, 2); expect((await bundle(value))['events'], hasLength(33)); }, ); test( 'encoded-byte threshold writes early even below the record count', () async { final value = DiagnosticStore( Directory('${root.path}/logs'), batchSize: 100, maxBatchBytes: 100, flushInterval: const Duration(days: 1), ); value.record({'index': 1, 'message': 'x' * 100}); final deadline = Stopwatch()..start(); while (value.pendingRecords != 0 && deadline.elapsedMilliseconds < 5000) { await Future.delayed(const Duration(milliseconds: 5)); } expect(value.pendingRecords, 0); expect(value.eventFlushes, 1); expect((await bundle(value))['events'], hasLength(1)); }, ); test( 'byte budget bounds accepted events and still allows immediate fatal logs', () async { final value = DiagnosticStore( Directory('${root.path}/logs'), maxPendingBytes: 100, errorReserveBytes: 0, ); value.record({'index': 1, 'message': 'x' * 50}); value.record({'index': 2, 'message': 'x' * 50}); expect(value.pendingRecords, 1); expect(value.pendingEventBytes, lessThanOrEqualTo(100)); expect(value.dropped, 1); value.record({'fatal': true}, immediate: true); expect( File('${value.directory.path}/fatal.jsonl').readAsStringSync(), contains('fatal'), ); final report = await bundle(value); expect(report['events'], hasLength(2)); expect(value.pendingRecords, 0); expect(value.pendingEventBytes, 0); }, ); test( 'full queues skip formatting instead of spending CPU on discarded records', () async { final value = store(pending: 1); value.record({'index': 1}); final probe = _FormattingProbe(); value.record({'value': probe}); expect(probe.calls, 0); expect(value.dropped, 1); await value.flush(); }, ); test( 'error slots survive an information burst including queued writes', () async { final value = DiagnosticStore( Directory('${root.path}/logs'), maxPending: 8, errorReserveRecords: 2, batchSize: 1, ); for (var i = 0; i < 8; i++) { value.record({'level': 'info', 'index': i}); } final rejectedRequest = value.saveRequest({ 'index': 1, }, const Uuid().v4()); // The rejected request must not consume either reserved slot. for (var i = 0; i < 3; i++) { value.record({'level': 'error', 'index': i}); } expect(value.pendingRecords, 8); expect(value.dropped, 4); expect(value.droppedErrors, 1); await rejectedRequest; final report = await bundle(value); final events = report['events'] as List; expect(events.where((e) => e['level'] == 'info'), hasLength(6)); expect(events.where((e) => e['level'] == 'error'), hasLength(2)); expect(report['requests'], isEmpty); expect(report['storage']['droppedErrors'], 1); expect(value.pendingRecords, 0); expect(value.pendingEventBytes, 0); }, ); test( 'byte reserve admits errors after warning traffic reaches its limit', () async { final value = DiagnosticStore( Directory('${root.path}/logs'), maxPendingBytes: 1000, errorReserveBytes: 500, flushInterval: const Duration(days: 1), ); value.record({'level': 'warning', 'message': 'x' * 300}); value.record({'level': 'warning', 'message': 'x' * 300}); value.record({'level': 'error', 'message': 'x' * 300}); value.record({'level': 'error', 'message': 'x' * 500}); expect(value.pendingRecords, 2); expect(value.pendingEventBytes, lessThanOrEqualTo(1000)); expect(value.dropped, 2); expect(value.droppedErrors, 1); value.record({'level': 'error', 'fatal': true}, immediate: true); final events = (await bundle(value))['events'] as List; expect(events, hasLength(3)); expect(events.where((e) => e['level'] == 'error'), hasLength(2)); expect(value.pendingEventBytes, 0); }, ); test( 'buffered values are copied and redacted before callers can mutate them', () async { final value = store(); final input = { 'context': {'name': 'original', 'apiKey': 'PRIVATE'}, }; value.record(input); input['context']!['name'] = 'changed'; input['context']!['apiKey'] = 'MUTATED SECRET'; final event = ((await bundle(value))['events'] as List).single; expect(event['context']['name'], 'original'); expect(event['context']['apiKey'], '[redacted]'); }, ); test('requests and exports drain earlier buffered logs without waiting for the timer', () async { final value = DiagnosticStore( Directory('${root.path}/logs'), flushInterval: const Duration(days: 1), ); value.record({'index': 1}); await value.saveRequest({'index': 1}, const Uuid().v4()); expect(value.pendingRecords, 0); value.record({'index': 2}); final report = await bundle(value); expect((report['events'] as List).map((e) => e['index']), [1, 2]); expect(report['requests'], hasLength(1)); expect(value.pendingRecords, 0); }); test( 'concurrent writes rotate within bounds and retain newest complete records', () async { final value = store(); for (var i = 0; i < 30; i++) { value.record({'index': i, 'message': 'x' * 250}); } await value.flush(); final files = await value.directory.list().cast().toList(); expect(files.length, 3); for (final file in files) { expect(await file.length(), lessThanOrEqualTo(1024)); } final events = (await bundle(value))['events'] as List; expect(events.last['index'], 29); expect( events.map((e) => e['index']).toList(), orderedEquals( List.generate(events.length, (i) => 30 - events.length + i), ), ); }, ); test( 'queue overload drops predictably without blocking or corrupting output', () async { final value = store(pending: 2); for (var i = 0; i < 10; i++) { value.record({'index': i}); } await value.flush(); expect(value.dropped, 8); expect((await bundle(value))['events'], hasLength(2)); }, ); test( 'unwritable store retains bounded fallback events that can be exported', () async { final blocked = File('${root.path}/blocked')..writeAsStringSync('file'); final value = DiagnosticStore(Directory(blocked.path)); for (var i = 0; i < 120; i++) { value.record({'index': i}); } await value.flush(); final report = await bundle(value); expect(value.writeFailures, 120); expect(report['fallbackEvents'], hasLength(100)); expect((report['fallbackEvents'] as List).last['index'], 119); expect(jsonEncode(report), isNot(contains(root.path))); }, ); test( 'request retention keeps the latest 20 and excludes conversation files', () async { final value = store(); await Future.wait( List.generate( 25, (i) => value.saveRequest({'index': i}, const Uuid().v4()), ), ); File('${value.directory.path}/conversation.json') .writeAsStringSync('PRIVATE CONVERSATION'); final report = await bundle(value); final requests = report['requests'] as List; expect(requests, hasLength(20)); expect( requests.map((r) => r['index']), orderedEquals(List.generate(20, (i) => 24 - i)), ); expect(jsonEncode(report), isNot(contains('PRIVATE CONVERSATION'))); }, ); test('exports redact secrets and skip an interrupted final append', () async { final value = store(); value.record({ 'token': 'PRIVATE TOKEN', 'url': 'https://user:secret@example.com/test?api_key=PRIVATE', 'path': '/Users/person/private.mov', 'message': 'Bearer SECRET', }); await value.flush(); File('${value.directory.path}/events-0.jsonl') .writeAsStringSync('{unfinished', mode: FileMode.append); value.record({'operation': 'afterInterruptedAppend'}); final report = await bundle(value); expect(report['events'], hasLength(2)); final encoded = jsonEncode(report); for (final secret in ['PRIVATE', 'SECRET', 'private.mov', 'user:secret']) { expect(encoded, isNot(contains(secret))); } }); test('failed export does not poison subsequent writes or exports', () async { final value = store(); final blocked = File('${root.path}/blocked')..writeAsStringSync('file'); await expectLater( value.export(Directory(blocked.path), const {}), throwsA(isA()), ); value.record({'operation': 'afterExportFailure'}); expect((await bundle(value))['events'], hasLength(1)); }); test( 'uncaught fatal records are flushed synchronously and bounded separately', () async { final value = store(); for (var i = 0; i < 8; i++) { value.record({'index': i, 'error': 'x' * 250}, immediate: true); } final file = File('${value.directory.path}/fatal.jsonl'); expect(file.existsSync(), isTrue); expect(file.lengthSync(), lessThanOrEqualTo(1024)); final events = (await bundle(value))['events'] as List; expect(events.last['index'], 7); }, ); } class _FormattingProbe { int calls = 0; @override String toString() { calls++; return 'value'; } }