diff --git a/crdt_sync_flutter/test/app_errors_support.dart b/crdt_sync_flutter/test/app_errors_support.dart new file mode 100644 index 0000000..9fde0fc --- /dev/null +++ b/crdt_sync_flutter/test/app_errors_support.dart @@ -0,0 +1,33 @@ +/// Shared pieces of the app-errors tests: the RTDB sink fake and a config. +library; + +import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'; + +/// A sink recording every patch; [fail] makes the next ones throw. +class FakeSink { + final patches = >{}; + bool fail = false; + + Future call(String path, Map values) async { + if (fail) throw StateError('offline'); + (patches[path] ??= {}).addAll(values); + } + + List> get entries => [ + for (final v in patches.values.expand((m) => m.values)) + v! as Map, + ]; +} + +const config = AppErrorsConfig( + app: 'todo', + repo: 'kuhyx/todo', + build: 42, + version: '1.2.3', +); + +/// An error whose toString throws. +class ThrowingToString { + @override + String toString() => throw StateError('no'); +} diff --git a/crdt_sync_flutter/test/app_errors_test.dart b/crdt_sync_flutter/test/app_errors_test.dart index 65b3641..617d767 100644 --- a/crdt_sync_flutter/test/app_errors_test.dart +++ b/crdt_sync_flutter/test/app_errors_test.dart @@ -7,28 +7,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; -/// A sink recording every patch; [fail] makes the next ones throw. -class FakeSink { - final patches = >{}; - bool fail = false; - - Future call(String path, Map values) async { - if (fail) throw StateError('offline'); - (patches[path] ??= {}).addAll(values); - } - - List> get entries => [ - for (final v in patches.values.expand((m) => m.values)) - v! as Map, - ]; -} - -const config = AppErrorsConfig( - app: 'todo', - repo: 'kuhyx/todo', - build: 42, - version: '1.2.3', -); +import 'app_errors_support.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -90,7 +69,7 @@ void main() { }); test('never throws on an error whose toString throws', () { - reporter().report('k', _Throws()); + reporter().report('k', ThrowingToString()); expect(queue.entries, isEmpty); }); @@ -179,221 +158,6 @@ void main() { }); }); - group('ErrorUploader', () { - test('uploads to //errors// with the build', () async { - final sink = FakeSink(); - reporter().report('k', 'Bad state: token=abc123 me@x.org'); - final up = ErrorUploader( - queue, - config: config, - sink: () async => sink.call, - deviceId: () async => 'dev-1', - ); - expect(await up.flush(), isTrue); - expect(sink.patches.keys.single, 'todo/errors'); - final key = sink.patches['todo/errors']!.keys.single; - expect(key, startsWith('dev-1/')); - final e = sink.entries.single; - expect(e['build'], 42); - expect(e['version'], '1.2.3'); - expect(e['repo'], 'kuhyx/todo'); - expect(e['mark'], 'package:todo/'); - expect(e['error'], 'Bad state: token= '); - expect(queue.entries, isEmpty); - }); - - test('offline keeps the queue; back online sends it', () async { - final sink = FakeSink()..fail = true; - reporter().report('k', 'x'); - final up = ErrorUploader( - queue, - config: config, - sink: () async => sink.call, - deviceId: () async => 'd', - ); - expect(await up.flush(), isFalse); - expect(queue.entries, hasLength(1)); - sink.fail = false; - expect(await up.flush(), isTrue); - expect(sink.entries, hasLength(1)); - up.dispose(); - }); - - test('signed out (no sink) keeps the queue', () async { - reporter().report('k', 'x'); - final up = ErrorUploader( - queue, - config: config, - sink: () async => null, - deviceId: () async => 'd', - ); - expect(await up.flush(), isFalse); - expect(queue.entries, hasLength(1)); - up.dispose(); - }); - - test('nothing pending is a no-op', () async { - final up = ErrorUploader( - queue, - config: config, - sink: () async => throw StateError('never called'), - deviceId: () async => 'd', - ); - expect(await up.flush(), isTrue); - }); - - test('an append schedules a debounced flush', () async { - final sink = FakeSink(); - final up = ErrorUploader( - queue, - config: config, - sink: () async => sink.call, - deviceId: () async => 'd', - debounce: Duration.zero, - )..start(); - reporter().report('k', 'x'); - await Future.delayed(const Duration(milliseconds: 20)); - expect(sink.entries, hasLength(1)); - up.dispose(); - }); - }); - - group('installAppErrors', () { - late FlutterExceptionHandler? savedFlutter; - late ErrorCallback? savedAsync; - - setUp(() { - savedFlutter = FlutterError.onError; - savedAsync = PlatformDispatcher.instance.onError; - }); - - tearDown(() { - FlutterError.onError = savedFlutter; - PlatformDispatcher.instance.onError = savedAsync; - AppErrors.instance = null; - }); - - test('chains the framework and async hooks', () async { - final seen = []; - FlutterError.onError = (d) => seen.add(d.exception); - PlatformDispatcher.instance.onError = (e, s) { - seen.add(e); - return true; - }; - final errors = await installAppErrors( - config, - preferences: await SharedPreferences.getInstance(), - ); - expect(AppErrors.instance, same(errors)); - FlutterError.onError!( - FlutterErrorDetails(exception: StateError('framework')), - ); - FlutterError.onError!( - FlutterErrorDetails(exception: StateError('quiet'), silent: true), - ); - expect( - PlatformDispatcher.instance.onError!( - StateError('async'), - StackTrace.empty, - ), - isTrue, - ); - expect(seen, hasLength(3)); - expect(errors.queue.entries.map((e) => e.kind), [ - 'uncaught.flutter', - 'uncaught.async', - ]); - }); - - test('without prior hooks the async error is not handled', () async { - FlutterError.onError = null; - PlatformDispatcher.instance.onError = null; - final errors = await installAppErrors( - config, - preferences: await SharedPreferences.getInstance(), - ); - FlutterError.onError!(FlutterErrorDetails(exception: StateError('f'))); - expect( - PlatformDispatcher.instance.onError!('a', StackTrace.empty), - isFalse, - ); - expect(errors.queue.entries, hasLength(2)); - }); - - test('connect starts uploads; the route observer stamps routes', () async { - final errors = await installAppErrors( - config, - preferences: await SharedPreferences.getInstance(), - ); - final sink = FakeSink(); - final up = errors.connect( - sink: () async => sink.call, - deviceId: () async => 'd', - startDelay: Duration.zero, - ); - AppErrorsRouteObserver(errors).didPush( - MaterialPageRoute( - builder: (_) => const SizedBox(), - settings: const RouteSettings(name: '/settings'), - ), - null, - ); - errors.reporter.report('k', 'x'); - await Future.delayed(const Duration(milliseconds: 20)); - await up.flush(); - expect(sink.entries.single['route'], '/settings'); - up.dispose(); - }); - }); - - group('WaitWatch', () { - tearDown(() => AppErrors.instance = null); - - testWidgets('without AppErrors it only shows the child', (tester) async { - await tester.pumpWidget(const WaitWatch.centered('x')); - expect(find.byType(CircularProgressIndicator), findsOneWidget); - await tester.pumpWidget(const SizedBox()); - }); - - testWidgets('a spinner shown 2 s is a perf.slow entry', (tester) async { - var now = DateTime.utc(2026); - final errors = AppErrors.forTest(config, queue, now: () => now); - AppErrors.instance = errors; - await tester.pumpWidget( - const WaitWatch(operation: 'list.load', child: SizedBox()), - ); - now = now.add(const Duration(seconds: 2)); - await tester.pumpWidget(const SizedBox()); - expect(queue.entries.single.operation, 'list.load'); - }); - - testWidgets('backgrounding ends the wait, resuming starts one', ( - tester, - ) async { - var now = DateTime.utc(2026); - final errors = AppErrors.forTest(config, queue, now: () => now); - AppErrors.instance = errors; - await tester.pumpWidget( - const WaitWatch(operation: 'op', child: SizedBox()), - ); - tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); - now = now.add(const Duration(seconds: 30)); - tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); - now = now.add(const Duration(milliseconds: 100)); - await tester.pumpWidget(const SizedBox()); - expect(queue.entries, isEmpty, reason: 'background time is no wait'); - }); - }); - - test('install reads the default preferences', () async { - final saved = (FlutterError.onError, PlatformDispatcher.instance.onError); - final errors = await installAppErrors(config); - expect(errors.config.mark, 'package:todo/'); - FlutterError.onError = saved.$1; - PlatformDispatcher.instance.onError = saved.$2; - AppErrors.instance = null; - }); - test('config mark uses the package name, else the app', () { // ignore: prefer_const_constructors -- a runtime instance for coverage final named = AppErrorsConfig(app: 'a-b', repo: 'o/a', package: 'pkg'); @@ -402,29 +166,6 @@ void main() { expect(AppErrorsConfig(app: 'a-b', repo: 'o/a').mark, 'package:a_b/'); }); - test('route observer follows pop and replace', () { - final errors = AppErrors.forTest(config, queue); - final observer = AppErrorsRouteObserver(errors); - Route named(String name) => MaterialPageRoute( - builder: (_) => const SizedBox(), - settings: RouteSettings(name: name), - ); - observer.didPop(named('/b'), named('/a')); - expect(errors.reporter.route, '/a'); - observer.didReplace(newRoute: named('/c')); - expect(errors.reporter.route, '/c'); - observer.didPop(named('/c'), null); - expect(errors.reporter.route, '/c', reason: 'no name keeps the last'); - }); - - testWidgets('WaitWatch built at runtime', (tester) async { - // ignore: prefer_const_constructors - await tester.pumpWidget(WaitWatch.centered('x')); - // ignore: prefer_const_constructors - await tester.pumpWidget(WaitWatch(operation: 'y', child: SizedBox())); - expect(find.byType(SizedBox), findsOneWidget); - }); - test('redactForReport masks secrets', () { expect( redactForReport( @@ -453,8 +194,3 @@ void main() { expect(ErrorEntry.tryFromJson('nope'), isNull); }); } - -class _Throws { - @override - String toString() => throw StateError('no'); -} diff --git a/crdt_sync_flutter/test/app_errors_upload_test.dart b/crdt_sync_flutter/test/app_errors_upload_test.dart new file mode 100644 index 0000000..2f18b5b --- /dev/null +++ b/crdt_sync_flutter/test/app_errors_upload_test.dart @@ -0,0 +1,202 @@ +import 'dart:async'; +import 'dart:ui' show ErrorCallback, PlatformDispatcher; + +import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'; +import 'package:flutter/foundation.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'app_errors_support.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late DateTime clock; + late ErrorQueue queue; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + clock = DateTime.utc(2026, 11, 17, 10); + queue = await ErrorQueue.open(await SharedPreferences.getInstance()); + }); + + ErrorReporter reporter() => + ErrorReporter(queue, config: config, now: () => clock); + + group('ErrorUploader', () { + test('uploads to //errors// with the build', () async { + final sink = FakeSink(); + reporter().report('k', 'Bad state: token=abc123 me@x.org'); + final up = ErrorUploader( + queue, + config: config, + sink: () async => sink.call, + deviceId: () async => 'dev-1', + ); + expect(await up.flush(), isTrue); + expect(sink.patches.keys.single, 'todo/errors'); + final key = sink.patches['todo/errors']!.keys.single; + expect(key, startsWith('dev-1/')); + final e = sink.entries.single; + expect(e['build'], 42); + expect(e['version'], '1.2.3'); + expect(e['repo'], 'kuhyx/todo'); + expect(e['mark'], 'package:todo/'); + expect(e['error'], 'Bad state: token= '); + expect(queue.entries, isEmpty); + }); + + test('offline keeps the queue; back online sends it', () async { + final sink = FakeSink()..fail = true; + reporter().report('k', 'x'); + final up = ErrorUploader( + queue, + config: config, + sink: () async => sink.call, + deviceId: () async => 'd', + ); + expect(await up.flush(), isFalse); + expect(queue.entries, hasLength(1)); + sink.fail = false; + expect(await up.flush(), isTrue); + expect(sink.entries, hasLength(1)); + up.dispose(); + }); + + test('signed out (no sink) keeps the queue', () async { + reporter().report('k', 'x'); + final up = ErrorUploader( + queue, + config: config, + sink: () async => null, + deviceId: () async => 'd', + ); + expect(await up.flush(), isFalse); + expect(queue.entries, hasLength(1)); + up.dispose(); + }); + + test('nothing pending is a no-op', () async { + final up = ErrorUploader( + queue, + config: config, + sink: () async => throw StateError('never called'), + deviceId: () async => 'd', + ); + expect(await up.flush(), isTrue); + }); + + test('an append schedules a debounced flush', () async { + final sink = FakeSink(); + final up = ErrorUploader( + queue, + config: config, + sink: () async => sink.call, + deviceId: () async => 'd', + debounce: Duration.zero, + )..start(); + reporter().report('k', 'x'); + await Future.delayed(const Duration(milliseconds: 20)); + expect(sink.entries, hasLength(1)); + up.dispose(); + }); + }); + + group('installAppErrors', () { + late FlutterExceptionHandler? savedFlutter; + late ErrorCallback? savedAsync; + + setUp(() { + savedFlutter = FlutterError.onError; + savedAsync = PlatformDispatcher.instance.onError; + }); + + tearDown(() { + FlutterError.onError = savedFlutter; + PlatformDispatcher.instance.onError = savedAsync; + AppErrors.instance = null; + }); + + test('chains the framework and async hooks', () async { + final seen = []; + FlutterError.onError = (d) => seen.add(d.exception); + PlatformDispatcher.instance.onError = (e, s) { + seen.add(e); + return true; + }; + final errors = await installAppErrors( + config, + preferences: await SharedPreferences.getInstance(), + ); + expect(AppErrors.instance, same(errors)); + FlutterError.onError!( + FlutterErrorDetails(exception: StateError('framework')), + ); + FlutterError.onError!( + FlutterErrorDetails(exception: StateError('quiet'), silent: true), + ); + expect( + PlatformDispatcher.instance.onError!( + StateError('async'), + StackTrace.empty, + ), + isTrue, + ); + expect(seen, hasLength(3)); + expect(errors.queue.entries.map((e) => e.kind), [ + 'uncaught.flutter', + 'uncaught.async', + ]); + }); + + test('without prior hooks the async error is not handled', () async { + FlutterError.onError = null; + PlatformDispatcher.instance.onError = null; + final errors = await installAppErrors( + config, + preferences: await SharedPreferences.getInstance(), + ); + FlutterError.onError!(FlutterErrorDetails(exception: StateError('f'))); + expect( + PlatformDispatcher.instance.onError!('a', StackTrace.empty), + isFalse, + ); + expect(errors.queue.entries, hasLength(2)); + }); + + test('connect starts uploads; the route observer stamps routes', () async { + final errors = await installAppErrors( + config, + preferences: await SharedPreferences.getInstance(), + ); + final sink = FakeSink(); + final up = errors.connect( + sink: () async => sink.call, + deviceId: () async => 'd', + startDelay: Duration.zero, + ); + AppErrorsRouteObserver(errors).didPush( + MaterialPageRoute( + builder: (_) => const SizedBox(), + settings: const RouteSettings(name: '/settings'), + ), + null, + ); + errors.reporter.report('k', 'x'); + await Future.delayed(const Duration(milliseconds: 20)); + await up.flush(); + expect(sink.entries.single['route'], '/settings'); + up.dispose(); + }); + }); + + test('install reads the default preferences', () async { + final saved = (FlutterError.onError, PlatformDispatcher.instance.onError); + final errors = await installAppErrors(config); + expect(errors.config.mark, 'package:todo/'); + FlutterError.onError = saved.$1; + PlatformDispatcher.instance.onError = saved.$2; + AppErrors.instance = null; + }); +} diff --git a/crdt_sync_flutter/test/app_errors_wait_test.dart b/crdt_sync_flutter/test/app_errors_wait_test.dart new file mode 100644 index 0000000..46cacd2 --- /dev/null +++ b/crdt_sync_flutter/test/app_errors_wait_test.dart @@ -0,0 +1,88 @@ +import 'dart:async'; +import 'dart:ui' show ErrorCallback, PlatformDispatcher; + +import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'; +import 'package:flutter/foundation.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'app_errors_support.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late DateTime clock; + late ErrorQueue queue; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + clock = DateTime.utc(2026, 11, 17, 10); + queue = await ErrorQueue.open(await SharedPreferences.getInstance()); + }); + + ErrorReporter reporter() => + ErrorReporter(queue, config: config, now: () => clock); + + group('WaitWatch', () { + tearDown(() => AppErrors.instance = null); + + testWidgets('without AppErrors it only shows the child', (tester) async { + await tester.pumpWidget(const WaitWatch.centered('x')); + expect(find.byType(CircularProgressIndicator), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('a spinner shown 2 s is a perf.slow entry', (tester) async { + var now = DateTime.utc(2026); + final errors = AppErrors.forTest(config, queue, now: () => now); + AppErrors.instance = errors; + await tester.pumpWidget( + const WaitWatch(operation: 'list.load', child: SizedBox()), + ); + now = now.add(const Duration(seconds: 2)); + await tester.pumpWidget(const SizedBox()); + expect(queue.entries.single.operation, 'list.load'); + }); + + testWidgets('backgrounding ends the wait, resuming starts one', ( + tester, + ) async { + var now = DateTime.utc(2026); + final errors = AppErrors.forTest(config, queue, now: () => now); + AppErrors.instance = errors; + await tester.pumpWidget( + const WaitWatch(operation: 'op', child: SizedBox()), + ); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + now = now.add(const Duration(seconds: 30)); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + now = now.add(const Duration(milliseconds: 100)); + await tester.pumpWidget(const SizedBox()); + expect(queue.entries, isEmpty, reason: 'background time is no wait'); + }); + }); + + test('route observer follows pop and replace', () { + final errors = AppErrors.forTest(config, queue); + final observer = AppErrorsRouteObserver(errors); + Route named(String name) => MaterialPageRoute( + builder: (_) => const SizedBox(), + settings: RouteSettings(name: name), + ); + observer.didPop(named('/b'), named('/a')); + expect(errors.reporter.route, '/a'); + observer.didReplace(newRoute: named('/c')); + expect(errors.reporter.route, '/c'); + observer.didPop(named('/c'), null); + expect(errors.reporter.route, '/c', reason: 'no name keeps the last'); + }); + + testWidgets('WaitWatch built at runtime', (tester) async { + // ignore: prefer_const_constructors + await tester.pumpWidget(WaitWatch.centered('x')); + // ignore: prefer_const_constructors + await tester.pumpWidget(WaitWatch(operation: 'y', child: SizedBox())); + expect(find.byType(SizedBox), findsOneWidget); + }); +} diff --git a/gatelock/gatelock/_error_spool.py b/gatelock/gatelock/_error_spool.py new file mode 100644 index 0000000..6bbe47f --- /dev/null +++ b/gatelock/gatelock/_error_spool.py @@ -0,0 +1,239 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""The spool writer behind ``gatelock.error_report``: reports and timed waits. + +``Reporter`` writes one JSON line per report to +``$XDG_STATE_HOME/app-errors-spool/.jsonl`` (utils DOCS-app-errors.md), +deduplicating identical errors within ``WINDOW`` seconds and capping each +minute, and never raises into the app it watches. ``SlowWait`` is one timed +wait: written when it outlasts the threshold, or while it is still going. +""" + +from __future__ import annotations + +from contextlib import contextmanager +from dataclasses import dataclass, field +import datetime as dt +import json +import logging +import os +from pathlib import Path +import threading +import time +import traceback +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Callable, Iterator + from types import TracebackType + +#: The kind the board files as "bring this wait under 1 s". +SLOW_KIND = "perf.slow" +#: Seconds in the rate cap's window. +_MINUTE = 60.0 + +_logger = logging.getLogger(__name__) + + +def _default_spool() -> Path: + base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state") + return Path(base) / "app-errors-spool" + + +def _short(path: str, mark: str) -> str: + """Return ``path`` from the package that holds it: no home directory in a report.""" + for anchor in ("site-packages/", "dist-packages/"): + if anchor in path: + return path.rsplit(anchor, 1)[1] + if mark in path: + return mark + path.rsplit(mark, 1)[1] + return Path(path).name + + +#: What a report may fail with (a bad spool path, an error whose str() throws): +#: logged and dropped, never raised into the app being watched. +_REPORT_FAILURES = (OSError, ValueError, TypeError, RuntimeError, AttributeError) + + +@dataclass +class _Guard: + """A reporter's loop guards: recent errors, minute buckets, re-entry.""" + + seen: dict[str, float] = field(default_factory=dict) + minutes: dict[str, tuple[float, int]] = field(default_factory=dict) + busy: bool = False + serial: int = 0 + lock: threading.Lock = field(default_factory=threading.Lock) + + +@dataclass +class Reporter: + """Writes one app's error and slow-wait reports to the spool.""" + + #: Seconds an identical error stays suppressed. + WINDOW = 30.0 + #: Most error reports written per minute. + MAX_PER_MINUTE = 20 + #: Most slow-wait reports written per minute. + MAX_SLOW_PER_MINUTE = 30 + + app: str + repo: str + mark: str = "" + spool: Path = field(default_factory=_default_spool) + build: int = 0 + version: str | None = None + threshold: float = 1.0 + still_after: float = 5.0 + clock: Callable[[], float] = time.time + _guard: _Guard = field(default_factory=_Guard) + + def __post_init__(self) -> None: + """Default the frame mark to the app's module directory.""" + self.mark = self.mark or self.app.replace("-", "_") + "/" + + def _allowed(self, bucket: str, cap: int) -> bool: + now = self.clock() + start, count = self._guard.minutes.get(bucket, (now, 0)) + if now - start >= _MINUTE: + start, count = now, 0 + if count >= cap: + return False + self._guard.minutes[bucket] = (start, count + 1) + return True + + def _write(self, entry: dict[str, object]) -> None: + at = dt.datetime.fromtimestamp(self.clock(), dt.UTC) + entry |= { + "at": at.strftime("%Y-%m-%dT%H:%M:%S.") + f"{at.microsecond // 1000:03d}Z", + "repo": self.repo, + "mark": self.mark, + "build": self.build, + } + if self.version: + entry["version"] = self.version + line = json.dumps(entry, sort_keys=True) + "\n" + with self._guard.lock: + self.spool.mkdir(parents=True, exist_ok=True) + with (self.spool / f"{self.app}.jsonl").open("a", encoding="utf-8") as f: + f.write(line) + + def report(self, kind: str, error: object, tb: TracebackType | None = None) -> None: + """Record ``error`` (exception or message) as ``kind``, unless suppressed.""" + if self._guard.busy: + return + self._guard.busy = True + try: + text = ( + f"{type(error).__name__}: {error}" + if isinstance(error, BaseException) + else str(error) + ) + now = self.clock() + key = f"{kind}|{text}" + self._guard.seen = { + k: t for k, t in self._guard.seen.items() if now - t < self.WINDOW + } + if key in self._guard.seen or not self._allowed( + "error", self.MAX_PER_MINUTE + ): + return + self._guard.seen[key] = now + frames = traceback.extract_tb(tb) if tb is not None else [] + stack = [ + f"{_short(f.filename, self.mark)}:{f.lineno} in {f.name}" + for f in reversed(frames) + ] + self._write({"kind": kind, "error": text, "stack": stack}) + except _REPORT_FAILURES: + # Never raise into the app it watches; the log keeps the why. + _logger.exception("app-errors: report not written") + finally: + self._guard.busy = False + + def slow( + self, + operation: str, + ms: int, + *, + wait_id: str, + route: str | None = None, + still: bool = False, + ) -> None: + """Record one wait of ``ms`` milliseconds on ``operation``.""" + try: + if not self._allowed("slow", self.MAX_SLOW_PER_MINUTE): + return + entry: dict[str, object] = { + "kind": SLOW_KIND, + "error": f"{operation} waited {ms} ms", + "operation": operation, + "durationMs": ms, + "waitId": wait_id, + "still": still, + } + if route: + entry["route"] = route + self._write(entry) + except _REPORT_FAILURES: + _logger.exception("app-errors: slow wait not written") + + def begin(self, operation: str, *, route: str | None = None) -> SlowWait: + """Start timing a wait on ``operation`` (``coach.load``); ``end`` it after.""" + self._guard.serial += 1 + return SlowWait( + self, + operation, + route, + self.clock(), + f"{int(self.clock() * 1000):x}-{self._guard.serial}", + ) + + @contextmanager + def wait(self, operation: str, *, route: str | None = None) -> Iterator[SlowWait]: + """Time the ``with`` block as a wait on ``operation``.""" + handle = self.begin(operation, route=route) + try: + yield handle + finally: + handle.end() + + +@dataclass +class SlowWait: + """One timed wait: reported when it ends after the threshold, or is still going.""" + + reporter: Reporter + operation: str + route: str | None + started: float + id: str + _ended: bool = False + _reported_still: bool = False + _timer: threading.Timer = field(init=False) + + def __post_init__(self) -> None: + """Arm the still-waiting report (a hung load never ends).""" + self._timer = threading.Timer(self.reporter.still_after, self._still) + self._timer.daemon = True + self._timer.start() + + def _ms(self) -> int: + return round((self.reporter.clock() - self.started) * 1000) + + def _still(self) -> None: + if self._ended: + return + self._reported_still = True + self.reporter.slow( + self.operation, self._ms(), wait_id=self.id, route=self.route, still=True + ) + + def end(self) -> None: + """End the wait; write it if it outlasted the threshold; repeats do nothing.""" + if self._ended: + return + self._ended = True + self._timer.cancel() + ms = self._ms() + if self._reported_still or ms > self.reporter.threshold * 1000: + self.reporter.slow(self.operation, ms, wait_id=self.id, route=self.route) diff --git a/gatelock/gatelock/error_report.py b/gatelock/gatelock/error_report.py index 5601299..52dc636 100644 --- a/gatelock/gatelock/error_report.py +++ b/gatelock/gatelock/error_report.py @@ -9,229 +9,50 @@ which every root, ``GateRoot`` included, goes through), each chained to the hook it replaces. ``Reporter.begin``/``wait`` time a user-visible wait, and ``watch_stalls`` reports a frozen Tk loop with no call-site work. -A report is one JSON line in ``$XDG_STATE_HOME/app-errors-spool/.jsonl``. -The PC's ``app-errors`` ingest (utils ``app_errors/``) reads it, groups it by -signature and hands it to the board, which files a ticket. Reporting shows -nothing on screen, never raises and never reports from inside a report. -Identical errors within ``WINDOW`` seconds are dropped and at most -``MAX_PER_MINUTE`` are written per minute (an error loop cannot fill the disk). +A report is one JSON line in ``$XDG_STATE_HOME/app-errors-spool/.jsonl`` +(``gatelock._error_spool``). The PC's ``app-errors`` ingest (utils +``app_errors/``) groups it by signature and hands it to the board, which files +a ticket. Reporting shows nothing on screen and never raises. """ from __future__ import annotations -from contextlib import contextmanager -from dataclasses import dataclass, field -import datetime as dt -import json -import os -from pathlib import Path +from contextlib import suppress +from dataclasses import dataclass import sys import threading -import time import tkinter as tk -import traceback from typing import TYPE_CHECKING +from gatelock._error_spool import SLOW_KIND, Reporter, SlowWait + if TYPE_CHECKING: - from collections.abc import Callable, Iterator + from collections.abc import Callable from types import TracebackType -#: The kind the board files as "bring this wait under 1 s". -SLOW_KIND = "perf.slow" +__all__ = [ + "SLOW_KIND", + "STALL_TICK_MS", + "Reporter", + "SlowWait", + "install", + "watch_stalls", +] + #: How often the stall watch ticks, milliseconds. STALL_TICK_MS = 100 _TK_DOOR = "_report_exception" -_installed: Reporter | None = None - - -def _default_spool() -> Path: - base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state") - return Path(base) / "app-errors-spool" - - -def _short(path: str, mark: str) -> str: - """Return ``path`` from the package that holds it: no home directory in a report.""" - for anchor in ("site-packages/", "dist-packages/"): - if anchor in path: - return path.rsplit(anchor, 1)[1] - if mark in path: - return mark + path.rsplit(mark, 1)[1] - return Path(path).name - @dataclass -class Reporter: - """Writes one app's error and slow-wait reports to the spool.""" +class _Installed: + """The process's reporter once ``install`` ran (tests put their own here).""" - #: Seconds an identical error stays suppressed. - WINDOW = 30.0 - #: Most error reports written per minute. - MAX_PER_MINUTE = 20 - #: Most slow-wait reports written per minute. - MAX_SLOW_PER_MINUTE = 30 - - app: str - repo: str - mark: str = "" - spool: Path = field(default_factory=_default_spool) - build: int = 0 - version: str | None = None - threshold: float = 1.0 - still_after: float = 5.0 - clock: Callable[[], float] = time.time - _seen: dict[str, float] = field(default_factory=dict) - _minutes: dict[str, tuple[float, int]] = field(default_factory=dict) - _busy: bool = False - _serial: int = 0 - _lock: threading.Lock = field(default_factory=threading.Lock) - - def __post_init__(self) -> None: - """Default the frame mark to the app's module directory.""" - self.mark = self.mark or self.app.replace("-", "_") + "/" - - def _allowed(self, bucket: str, cap: int) -> bool: - now = self.clock() - start, count = self._minutes.get(bucket, (now, 0)) - if now - start >= 60: # noqa: PLR2004 -- one minute - start, count = now, 0 - if count >= cap: - return False - self._minutes[bucket] = (start, count + 1) - return True - - def _write(self, entry: dict[str, object]) -> None: - at = dt.datetime.fromtimestamp(self.clock(), dt.UTC) - entry |= { - "at": at.strftime("%Y-%m-%dT%H:%M:%S.") + f"{at.microsecond // 1000:03d}Z", - "repo": self.repo, - "mark": self.mark, - "build": self.build, - } - if self.version: - entry["version"] = self.version - line = json.dumps(entry, sort_keys=True) + "\n" - with self._lock: - self.spool.mkdir(parents=True, exist_ok=True) - with (self.spool / f"{self.app}.jsonl").open("a", encoding="utf-8") as f: - f.write(line) - - def report(self, kind: str, error: object, tb: TracebackType | None = None) -> None: - """Record ``error`` (exception or message) as ``kind``, unless suppressed.""" - if self._busy: - return - self._busy = True - try: - text = ( - f"{type(error).__name__}: {error}" - if isinstance(error, BaseException) - else str(error) - ) - now = self.clock() - key = f"{kind}|{text}" - self._seen = {k: t for k, t in self._seen.items() if now - t < self.WINDOW} - if key in self._seen or not self._allowed("error", self.MAX_PER_MINUTE): - return - self._seen[key] = now - frames = traceback.extract_tb(tb) if tb is not None else [] - stack = [ - f"{_short(f.filename, self.mark)}:{f.lineno} in {f.name}" - for f in reversed(frames) - ] - self._write({"kind": kind, "error": text, "stack": stack}) - except Exception: # noqa: BLE001, S110 -- never raise into the app it watches - pass - finally: - self._busy = False - - def slow( - self, - operation: str, - ms: int, - *, - wait_id: str, - route: str | None = None, - still: bool = False, - ) -> None: - """Record one wait of ``ms`` milliseconds on ``operation``.""" - try: - if not self._allowed("slow", self.MAX_SLOW_PER_MINUTE): - return - entry: dict[str, object] = { - "kind": SLOW_KIND, - "error": f"{operation} waited {ms} ms", - "operation": operation, - "durationMs": ms, - "waitId": wait_id, - "still": still, - } - if route: - entry["route"] = route - self._write(entry) - except Exception: # noqa: BLE001, S110 -- never raise into the app - pass - - def begin(self, operation: str, *, route: str | None = None) -> SlowWait: - """Start timing a wait on ``operation`` (``coach.load``); ``end`` it after.""" - self._serial += 1 - return SlowWait( - self, - operation, - route, - self.clock(), - f"{int(self.clock() * 1000):x}-{self._serial}", - ) - - @contextmanager - def wait(self, operation: str, *, route: str | None = None) -> Iterator[SlowWait]: - """Time the ``with`` block as a wait on ``operation``.""" - handle = self.begin(operation, route=route) - try: - yield handle - finally: - handle.end() + reporter: Reporter | None = None -@dataclass -class SlowWait: - """One timed wait: reported when it ends after the threshold, or is still going.""" - - reporter: Reporter - operation: str - route: str | None - started: float - id: str - _ended: bool = False - _reported_still: bool = False - _timer: threading.Timer = field(init=False) - - def __post_init__(self) -> None: - """Arm the still-waiting report (a hung load never ends).""" - self._timer = threading.Timer(self.reporter.still_after, self._still) - self._timer.daemon = True - self._timer.start() - - def _ms(self) -> int: - return round((self.reporter.clock() - self.started) * 1000) - - def _still(self) -> None: - if self._ended: - return - self._reported_still = True - self.reporter.slow( - self.operation, self._ms(), wait_id=self.id, route=self.route, still=True - ) - - def end(self) -> None: - """End the wait; write it if it outlasted the threshold; repeats do nothing.""" - if self._ended: - return - self._ended = True - self._timer.cancel() - ms = self._ms() - if self._reported_still or ms > self.reporter.threshold * 1000: - self.reporter.slow(self.operation, ms, wait_id=self.id, route=self.route) +INSTALLED = _Installed() def watch_stalls(root: tk.Misc, reporter: Reporter) -> None: @@ -247,10 +68,8 @@ def watch_stalls(root: tk.Misc, reporter: Reporter) -> None: last[0] = now if late > reporter.threshold * 1000: reporter.slow("tk.mainloop", late, wait_id=f"stall-{int(now * 1000):x}") - try: + with suppress(tk.TclError): # the window is gone: the watch ends root.after(STALL_TICK_MS, tick) - except tk.TclError: - return # the window is gone root.after(STALL_TICK_MS, tick) @@ -268,9 +87,10 @@ def install( The spool is ``$XDG_STATE_HOME/app-errors-spool``; tests build a ``Reporter`` with their own ``spool`` instead. """ - global _installed # noqa: PLW0603 -- one set of process-wide hooks - if _installed is not None: - return _installed + # One set of process-wide hooks; a test pre-installs its own reporter by + # setting INSTALLED.reporter, and no hook is touched. + if INSTALLED.reporter is not None: + return INSTALLED.reporter rep = Reporter( app=app, repo=repo, @@ -308,5 +128,5 @@ def install( sys.excepthook = sys_hook threading.excepthook = thread_hook setattr(tk.Misc, _TK_DOOR, tk_hook) - _installed = rep + INSTALLED.reporter = rep return rep diff --git a/gatelock/gatelock/tests/errorkit/__init__.py b/gatelock/gatelock/tests/errorkit/__init__.py new file mode 100644 index 0000000..46ea489 --- /dev/null +++ b/gatelock/gatelock/tests/errorkit/__init__.py @@ -0,0 +1,41 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""Shared pieces of the error reporter tests: a settable clock, spool lines.""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from pathlib import Path + + +class Clock: + """A settable wall + monotonic clock.""" + + def __init__(self) -> None: + self.t = 1_800_000_000.0 + + def __call__(self) -> float: + return self.t + + +def spool_lines(tmp_path: Path, app: str = "leetcode-guard") -> list[dict[str, object]]: + path = tmp_path / f"{app}.jsonl" + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text().splitlines()] + + +def _boom() -> None: + msg = "bad 12" + raise ValueError(msg) + + +def raised() -> BaseException: + """A ValueError carrying a real traceback.""" + try: + _boom() + except ValueError as e: + return e + raise AssertionError diff --git a/gatelock/gatelock/tests/test_error_report.py b/gatelock/gatelock/tests/test_error_report.py index 8e043ef..63e7f28 100644 --- a/gatelock/gatelock/tests/test_error_report.py +++ b/gatelock/gatelock/tests/test_error_report.py @@ -1,9 +1,8 @@ # Copyright (c) 2026 Krzysztof Rudnicki -"""The Tk app error and slow-wait reporter: hooks, dedup, spool lines, stalls.""" +"""The error reporter's process hooks: excepthooks, Tk callbacks, stalls.""" from __future__ import annotations -import json import sys import threading import tkinter as tk @@ -13,25 +12,14 @@ from unittest.mock import MagicMock import pytest from gatelock import error_report -from gatelock.error_report import Reporter - -DOOR = "_report_exception" +from gatelock._error_spool import Reporter +from gatelock.tests.errorkit import Clock, raised, spool_lines if TYPE_CHECKING: from collections.abc import Iterator from pathlib import Path -class Clock: - """A settable wall + monotonic clock.""" - - def __init__(self) -> None: - self.t = 1_800_000_000.0 - - def __call__(self) -> float: - return self.t - - @pytest.fixture def clock() -> Clock: return Clock() @@ -49,118 +37,12 @@ def reporter(tmp_path: Path, clock: Clock) -> Reporter: ) -def _lines(tmp_path: Path, app: str = "leetcode-guard") -> list[dict[str, object]]: - path = tmp_path / f"{app}.jsonl" - if not path.exists(): - return [] - return [json.loads(line) for line in path.read_text().splitlines()] +DOOR = "_report_exception" -def _raise() -> BaseException: - try: - raise ValueError("bad 12") # noqa: EM101, TRY003, TRY301 -- a real traceback for the test - except ValueError as e: - return e - - -def test_report_writes_one_entry(reporter: Reporter, tmp_path: Path) -> None: - exc = _raise() - reporter.report("uncaught.python", exc, exc.__traceback__) - (entry,) = _lines(tmp_path) - assert entry["kind"] == "uncaught.python" - assert entry["error"] == "ValueError: bad 12" - assert entry["repo"] == "kuhyx/leetcode-guard" - assert entry["mark"] == "leetcode_guard/" - assert entry["build"] == 5 - assert entry["version"] == "0.3.0" - assert entry["at"] == "2027-01-15T08:00:00.000Z" - stack = entry["stack"] - assert isinstance(stack, list) - assert "test_error_report.py" in stack[0] - assert " in _raise" in stack[0] - - -def test_identical_errors_within_window_are_dropped( - reporter: Reporter, tmp_path: Path, clock: Clock -) -> None: - for _ in range(5): - reporter.report("k", "same") - assert len(_lines(tmp_path)) == 1 - clock.t += Reporter.WINDOW + 1 - reporter.report("k", "same") - assert len(_lines(tmp_path)) == 2 - - -def test_rate_cap_per_minute(reporter: Reporter, tmp_path: Path, clock: Clock) -> None: - for i in range(Reporter.MAX_PER_MINUTE + 5): - reporter.report("k", f"e{i}") - assert len(_lines(tmp_path)) == Reporter.MAX_PER_MINUTE - clock.t += 61 - reporter.report("k", "later") - assert len(_lines(tmp_path)) == Reporter.MAX_PER_MINUTE + 1 - - -def test_report_never_raises(reporter: Reporter, tmp_path: Path) -> None: - class Bad: - def __str__(self) -> str: - raise RuntimeError - - reporter.report("k", Bad()) - (tmp_path / "leetcode-guard.jsonl").mkdir() # an unwritable spool file - reporter.report("k", "other") - assert True - - -def test_report_inside_report_is_ignored(reporter: Reporter, tmp_path: Path) -> None: - reporter._busy = True - reporter.report("k", "x") - assert _lines(tmp_path) == [] - - -def test_slow_wait_over_threshold_is_written( - reporter: Reporter, tmp_path: Path, clock: Clock -) -> None: - wait = reporter.begin("coach.load", route="coach") - clock.t += 2.0 - wait.end() - wait.end() # repeat ends do nothing - (entry,) = _lines(tmp_path) - assert entry["kind"] == "perf.slow" - assert entry["operation"] == "coach.load" - assert entry["durationMs"] == 2000 - assert entry["route"] == "coach" - assert entry["still"] is False - assert entry["error"] == "coach.load waited 2000 ms" - - -def test_fast_wait_writes_nothing( - reporter: Reporter, tmp_path: Path, clock: Clock -) -> None: - with reporter.wait("quick"): - clock.t += 0.5 - assert _lines(tmp_path) == [] - - -def test_still_waiting_is_written_then_the_end( - reporter: Reporter, tmp_path: Path, clock: Clock -) -> None: - wait = reporter.begin("hung") - clock.t += 6 - wait._still() - clock.t += 1 - wait.end() - still, end = _lines(tmp_path) - assert still["still"] is True - assert end["still"] is False - assert still["waitId"] == end["waitId"] - - -def test_slow_rate_cap(reporter: Reporter, tmp_path: Path, clock: Clock) -> None: - for _ in range(Reporter.MAX_SLOW_PER_MINUTE + 3): - w = reporter.begin("op") - clock.t += 1.5 - w.end() - assert len(_lines(tmp_path)) == Reporter.MAX_SLOW_PER_MINUTE +def _key_error() -> None: + key = "cb" + raise KeyError(key) @pytest.fixture @@ -169,7 +51,7 @@ def hooks() -> Iterator[None]: yield sys.excepthook, threading.excepthook = saved[:2] setattr(tk.Misc, DOOR, saved[2]) - error_report._installed = None + error_report.INSTALLED.reporter = None def _install(spool: Path) -> Reporter: @@ -185,7 +67,7 @@ def test_install_chains_sys_and_thread_hooks(hooks: None, tmp_path: Path) -> Non threading.excepthook = prior_thread rep = _install(tmp_path) assert _install(tmp_path) is rep # idempotent - exc = _raise() + exc = raised() sys.excepthook(ValueError, exc, exc.__traceback__) prior.assert_called_once() args = MagicMock( @@ -193,7 +75,7 @@ def test_install_chains_sys_and_thread_hooks(hooks: None, tmp_path: Path) -> Non ) threading.excepthook(args) prior_thread.assert_called_once_with(args) - kinds = [e["kind"] for e in _lines(tmp_path, "tk-app")] + kinds = [e["kind"] for e in spool_lines(tmp_path, "tk-app")] assert kinds == ["uncaught.python", "uncaught.thread"] @@ -203,7 +85,7 @@ def test_thread_hook_without_value(hooks: None, tmp_path: Path) -> None: threading.excepthook( MagicMock(exc_type=SystemExit, exc_value=None, exc_traceback=None) ) - assert _lines(tmp_path, "tk-app")[0]["error"] == "SystemExit" + assert spool_lines(tmp_path, "tk-app")[0]["error"] == "SystemExit" def test_install_reports_tk_callback_errors(hooks: None, tmp_path: Path) -> None: @@ -212,11 +94,11 @@ def test_install_reports_tk_callback_errors(hooks: None, tmp_path: Path) -> None _install(tmp_path) widget = MagicMock() try: - raise KeyError("cb") # noqa: EM101, TRY301 + _key_error() except KeyError: getattr(tk.Misc, DOOR)(widget) prior.assert_called_once_with(widget) - (entry,) = _lines(tmp_path, "tk-app") + (entry,) = spool_lines(tmp_path, "tk-app") assert entry["kind"] == "uncaught.tk" assert entry["error"] == "KeyError: 'cb'" @@ -225,18 +107,7 @@ def test_tk_hook_without_active_exception(hooks: None, tmp_path: Path) -> None: setattr(tk.Misc, DOOR, MagicMock()) _install(tmp_path) getattr(tk.Misc, DOOR)(MagicMock()) - assert _lines(tmp_path, "tk-app") == [] - - -def test_default_spool_and_mark( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path)) - rep = Reporter(app="diet-guard", repo="kuhyx/diet-guard") - assert rep.spool == tmp_path / "app-errors-spool" - assert rep.mark == "diet_guard/" - monkeypatch.delenv("XDG_STATE_HOME") - assert Reporter(app="a", repo="kuhyx/a").spool.name == "app-errors-spool" + assert spool_lines(tmp_path, "tk-app") == [] def test_stall_watch_reports_a_frozen_loop( @@ -249,7 +120,7 @@ def test_stall_watch_reports_a_frozen_loop( tick() # on time: nothing clock.t += 2.5 # the loop was blocked 2.5 s tick() - (entry,) = _lines(tmp_path) + (entry,) = spool_lines(tmp_path) assert entry["operation"] == "tk.mainloop" assert entry["durationMs"] == 2500 - error_report.STALL_TICK_MS @@ -261,30 +132,3 @@ def test_stall_watch_stops_with_the_window(reporter: Reporter, clock: Clock) -> root.after.side_effect = tk.TclError("destroyed") tick() # must not raise assert root.after.call_count == 2 - - -def test_frame_paths(reporter: Reporter) -> None: - assert ( - error_report._short("/x/lib/python3.15/site-packages/gatelock/a.py", "m/") - == "gatelock/a.py" - ) - assert error_report._short( - "/home/u/src/leetcode-guard/leetcode_guard/ui.py", "leetcode_guard/" - ) == ("leetcode_guard/ui.py") - assert error_report._short("/somewhere/else.py", "m/") == "else.py" - - -def test_slow_never_raises(reporter: Reporter, tmp_path: Path) -> None: - (tmp_path / "leetcode-guard.jsonl").mkdir() - reporter.slow("op", 2000, wait_id="w") - assert True - - -def test_still_after_end_does_nothing( - reporter: Reporter, tmp_path: Path, clock: Clock -) -> None: - wait = reporter.begin("op") - wait.end() - clock.t += 9 - wait._still() - assert _lines(tmp_path) == [] diff --git a/gatelock/gatelock/tests/test_error_spool.py b/gatelock/gatelock/tests/test_error_spool.py new file mode 100644 index 0000000..0809a9f --- /dev/null +++ b/gatelock/gatelock/tests/test_error_spool.py @@ -0,0 +1,170 @@ +# Copyright (c) 2026 Krzysztof Rudnicki +"""The error reporter's spool writer: entries, dedup, rate caps, waits.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pytest + +from gatelock import _error_spool +from gatelock._error_spool import Reporter +from gatelock.tests.errorkit import Clock, raised, spool_lines + +if TYPE_CHECKING: + from pathlib import Path + + +@pytest.fixture +def clock() -> Clock: + return Clock() + + +@pytest.fixture +def reporter(tmp_path: Path, clock: Clock) -> Reporter: + return Reporter( + app="leetcode-guard", + repo="kuhyx/leetcode-guard", + spool=tmp_path, + build=5, + version="0.3.0", + clock=clock, + ) + + +def test_report_writes_one_entry(reporter: Reporter, tmp_path: Path) -> None: + exc = raised() + reporter.report("uncaught.python", exc, exc.__traceback__) + (entry,) = spool_lines(tmp_path) + assert entry["kind"] == "uncaught.python" + assert entry["error"] == "ValueError: bad 12" + assert entry["repo"] == "kuhyx/leetcode-guard" + assert entry["mark"] == "leetcode_guard/" + assert entry["build"] == 5 + assert entry["version"] == "0.3.0" + assert entry["at"] == "2027-01-15T08:00:00.000Z" + stack = entry["stack"] + assert isinstance(stack, list) + assert stack[0].startswith("__init__.py:") + assert " in _boom" in stack[0] + + +def test_identical_errors_within_window_are_dropped( + reporter: Reporter, tmp_path: Path, clock: Clock +) -> None: + for _ in range(5): + reporter.report("k", "same") + assert len(spool_lines(tmp_path)) == 1 + clock.t += Reporter.WINDOW + 1 + reporter.report("k", "same") + assert len(spool_lines(tmp_path)) == 2 + + +def test_rate_cap_per_minute(reporter: Reporter, tmp_path: Path, clock: Clock) -> None: + for i in range(Reporter.MAX_PER_MINUTE + 5): + reporter.report("k", f"e{i}") + assert len(spool_lines(tmp_path)) == Reporter.MAX_PER_MINUTE + clock.t += 61 + reporter.report("k", "later") + assert len(spool_lines(tmp_path)) == Reporter.MAX_PER_MINUTE + 1 + + +def test_report_never_raises(reporter: Reporter, tmp_path: Path) -> None: + class Bad: + def __str__(self) -> str: + raise RuntimeError + + reporter.report("k", Bad()) + (tmp_path / "leetcode-guard.jsonl").mkdir() # an unwritable spool file + reporter.report("k", "other") + assert True + + +def test_report_inside_report_is_ignored(reporter: Reporter, tmp_path: Path) -> None: + reporter._guard.busy = True + reporter.report("k", "x") + assert spool_lines(tmp_path) == [] + + +def test_slow_wait_over_threshold_is_written( + reporter: Reporter, tmp_path: Path, clock: Clock +) -> None: + wait = reporter.begin("coach.load", route="coach") + clock.t += 2.0 + wait.end() + wait.end() # repeat ends do nothing + (entry,) = spool_lines(tmp_path) + assert entry["kind"] == "perf.slow" + assert entry["operation"] == "coach.load" + assert entry["durationMs"] == 2000 + assert entry["route"] == "coach" + assert entry["still"] is False + assert entry["error"] == "coach.load waited 2000 ms" + + +def test_fast_wait_writes_nothing( + reporter: Reporter, tmp_path: Path, clock: Clock +) -> None: + with reporter.wait("quick"): + clock.t += 0.5 + assert spool_lines(tmp_path) == [] + + +def test_still_waiting_is_written_then_the_end( + reporter: Reporter, tmp_path: Path, clock: Clock +) -> None: + wait = reporter.begin("hung") + clock.t += 6 + wait._still() + clock.t += 1 + wait.end() + still, end = spool_lines(tmp_path) + assert still["still"] is True + assert end["still"] is False + assert still["waitId"] == end["waitId"] + + +def test_slow_rate_cap(reporter: Reporter, tmp_path: Path, clock: Clock) -> None: + for _ in range(Reporter.MAX_SLOW_PER_MINUTE + 3): + w = reporter.begin("op") + clock.t += 1.5 + w.end() + assert len(spool_lines(tmp_path)) == Reporter.MAX_SLOW_PER_MINUTE + + +def test_default_spool_and_mark( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path)) + rep = Reporter(app="diet-guard", repo="kuhyx/diet-guard") + assert rep.spool == tmp_path / "app-errors-spool" + assert rep.mark == "diet_guard/" + monkeypatch.delenv("XDG_STATE_HOME") + assert Reporter(app="a", repo="kuhyx/a").spool.name == "app-errors-spool" + + +def test_frame_paths(reporter: Reporter) -> None: + assert ( + _error_spool._short("/x/lib/python3.15/site-packages/gatelock/a.py", "m/") + == "gatelock/a.py" + ) + assert _error_spool._short( + "/home/u/src/leetcode-guard/leetcode_guard/ui.py", "leetcode_guard/" + ) == ("leetcode_guard/ui.py") + assert _error_spool._short("/somewhere/else.py", "m/") == "else.py" + + +def test_slow_never_raises(reporter: Reporter, tmp_path: Path) -> None: + (tmp_path / "leetcode-guard.jsonl").mkdir() + reporter.slow("op", 2000, wait_id="w") + assert True + + +def test_still_after_end_does_nothing( + reporter: Reporter, tmp_path: Path, clock: Clock +) -> None: + wait = reporter.begin("op") + wait.end() + clock.t += 9 + wait._still() + assert spool_lines(tmp_path) == [] diff --git a/gatelock/pyproject.toml b/gatelock/pyproject.toml index ab96d42..f6a9b1f 100644 --- a/gatelock/pyproject.toml +++ b/gatelock/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "gatelock" -version = "0.15.0" +version = "0.15.1" description = "Shared per-output lock-window + HMAC log-integrity backend for blocking-overlay apps" requires-python = ">=3.14" dependencies = [] # pure stdlib — tkinter is bundled with Python diff --git a/rtdb_relay/dart/pubspec.lock b/rtdb_relay/dart/pubspec.lock index dd3257b..b1db713 100644 --- a/rtdb_relay/dart/pubspec.lock +++ b/rtdb_relay/dart/pubspec.lock @@ -70,11 +70,11 @@ packages: dependency: "direct main" description: path: crdt_sync_flutter - ref: "crdt_sync_flutter-v0.8.2" - resolved-ref: "1962d303336dfe260850466b8ee841033b9ad1ce" + ref: "crdt_sync_flutter-v0.9.0" + resolved-ref: dfc5d07f5225ed15609f9709748ed2efd6cc4d1d url: "https://github.com/kuhyx/utils" source: git - version: "0.8.2" + version: "0.9.0" crypto: dependency: transitive description: @@ -332,10 +332,10 @@ packages: dependency: transitive description: name: material_ui - sha256: "474c135fd46b56ff1d35ca982155e8863d28fbc6464d1192acf4ee53a738680e" + sha256: a6b19012df437a356cbc01f8ea22a105e07194c47c9a6009da0032a0ce35c4ab url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.11.1" meta: dependency: transitive description: diff --git a/rtdb_relay/dart/pubspec.yaml b/rtdb_relay/dart/pubspec.yaml index 480f30e..aae6d10 100644 --- a/rtdb_relay/dart/pubspec.yaml +++ b/rtdb_relay/dart/pubspec.yaml @@ -18,7 +18,7 @@ dependencies: crdt_sync_flutter: git: url: https://github.com/kuhyx/utils - ref: crdt_sync_flutter-v0.8.2 + ref: crdt_sync_flutter-v0.9.0 path: crdt_sync_flutter flutter: sdk: flutter