diff --git a/.gitignore b/.gitignore index b5111e9c..bc39480a 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,5 @@ /.pytest_cache/ /.mypy_cache/ /.ruff_cache/ +/.idea +uv.lock diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 00000000..de268a5e --- /dev/null +++ b/docs/README.md @@ -0,0 +1,13 @@ +# Documentation + +This directory contains project documentation, organized by stage and purpose: + +## Directories + +- **`brd/` (Business Requirements Documents)** + Ideas and high-level business requirements describing *what* needs to be built and *why*. + *Naming example:* `BRD001-runtime-metrics.md` + +- **`prd/` (Product Requirements Documents)** + Detailed product and technical requirements used as actionable input for coding agents describing *how* features should be implemented. + *Naming example:* `PRD001-metrics-collector.md` diff --git a/docs/brd/.sample-BRD001-runtime-metrics.md b/docs/brd/.sample-BRD001-runtime-metrics.md new file mode 100644 index 00000000..3e393c1b --- /dev/null +++ b/docs/brd/.sample-BRD001-runtime-metrics.md @@ -0,0 +1,16 @@ +# BRD001: SDK Runtime Metrics + +## Problem +Users running `proofline-sdk` in production have no built-in way to observe request latency, retry counts, or error rates without wrapping every client call manually. + +## Goal +Provide lightweight runtime metrics hooks in `ProoflineClient` and `AsyncProoflineClient` so applications can track SDK request performance and reliability. + +## Business Value +- Faster troubleshooting of slow or failing API calls. +- Easy integration with standard monitoring tools (Prometheus, OpenTelemetry, Datadog) without adding heavy SDK dependencies. + +## Success Criteria +- Users can pass an optional metrics callback/collector to the client. +- Every HTTP request records duration, status code, and retry count. +- Zero overhead when metrics collection is not configured. diff --git a/docs/brd/BRD001-runtime-metrics.md b/docs/brd/BRD001-runtime-metrics.md new file mode 100644 index 00000000..3e393c1b --- /dev/null +++ b/docs/brd/BRD001-runtime-metrics.md @@ -0,0 +1,16 @@ +# BRD001: SDK Runtime Metrics + +## Problem +Users running `proofline-sdk` in production have no built-in way to observe request latency, retry counts, or error rates without wrapping every client call manually. + +## Goal +Provide lightweight runtime metrics hooks in `ProoflineClient` and `AsyncProoflineClient` so applications can track SDK request performance and reliability. + +## Business Value +- Faster troubleshooting of slow or failing API calls. +- Easy integration with standard monitoring tools (Prometheus, OpenTelemetry, Datadog) without adding heavy SDK dependencies. + +## Success Criteria +- Users can pass an optional metrics callback/collector to the client. +- Every HTTP request records duration, status code, and retry count. +- Zero overhead when metrics collection is not configured. diff --git a/docs/prd/.sample-PRD001-metrics-collector.md b/docs/prd/.sample-PRD001-metrics-collector.md new file mode 100644 index 00000000..8918182c --- /dev/null +++ b/docs/prd/.sample-PRD001-metrics-collector.md @@ -0,0 +1,35 @@ +# PRD001: Metrics Collector + +**BRD:** [BRD001: SDK Runtime Metrics](../brd/.sample-BRD001-runtime-metrics.md) + +## Overview +Add an optional metrics collector interface to `ProoflineClient` and `AsyncProoflineClient` that receives a telemetry event after each HTTP request completes or fails. + +## Specification + +### 1. Data Model (`proofline/metrics.py`) +Define an immutable event and collector protocol: +- `RequestMetric(method: str, path: str, status_code: int | None, duration_ms: float, retries: int, error: str | None)` (frozen dataclass) +- `MetricsCollector`: `Protocol` with `record(self, metric: RequestMetric) -> None` + +### 2. Transport Integration (`proofline/_transport.py`, `proofline/client.py`) +- Accept `metrics: MetricsCollector | None = None` in `ProoflineClient.__init__` and `AsyncProoflineClient.__init__`. +- Measure request wall-clock time using `time.perf_counter()`. +- Emit `RequestMetric` via `metrics.record(...)` once per completed operation (including retries). +- Never let exceptions raised inside `metrics.record` break SDK calls (ignore or log safely). +- Redact API token from `error` if present. + +### 3. Public Exports (`proofline/__init__.py`) +- Export `RequestMetric` and `MetricsCollector` in `__all__`. + +## Target Files +- `proofline/metrics.py` (new) +- `proofline/_transport.py` +- `proofline/client.py` +- `proofline/__init__.py` +- `tests/test_metrics.py` (new) + +## Acceptance Criteria +- [ ] Sync and async clients emit `RequestMetric` with accurate status, retry count, and `duration_ms >= 0`. +- [ ] Faulty `MetricsCollector.record` raising an exception does not fail the client request. +- [ ] `pytest` and `mypy` pass with 100% type coverage on new code. diff --git a/docs/prd/PRD001-metrics-collector.md b/docs/prd/PRD001-metrics-collector.md new file mode 100644 index 00000000..055bda42 --- /dev/null +++ b/docs/prd/PRD001-metrics-collector.md @@ -0,0 +1,61 @@ +# PRD001: Metrics Collector + +**BRD:** [BRD001: SDK Runtime Metrics](../brd/BRD001-runtime-metrics.md) + +## Overview +Add a metrics collector and proxy architecture to `ProoflineClient` and `AsyncProoflineClient`. `MetricsCollector` captures runtime and caller metadata for each SDK operation and pushes events to a `MetricsProxy` backend. By default, `MetricsCollector` uses `LocalStorageMetricsProxy`, which appends records to a daily CSV report (`metrics/{date}.csv`). + +## Specification + +### 1. Data Model & Proxy Abstraction (`proofline/metrics.py`) +- **`RequestMetric` (frozen dataclass):** + - `timestamp: str` (ISO-8601 UTC) + - `file_path: str` (full path to the source file) + - `class_name: str | None` (enclosing class name if applicable, else `None`/empty) + - `method_name: str` (function or method name) + - `http_method: str` + - `path: str` + - `status_code: int | None` + - `duration_ms: float` + - `retries: int` + - `error: str | None` +- **`MetricsProxy` (abstract base class `ABC`):** + - Responsible for forwarding metrics to a concrete backend (e.g., Prometheus, OpenTelemetry, local storage). + - Defines `@abstractmethod def push(self, metric: RequestMetric) -> None`. +- **`LocalStorageMetricsProxy(MetricsProxy)`:** + - Only concrete proxy implemented in this PRD; used as the **default** proxy. + - Writes to `metrics/{date}.csv` (with `{date}` formatted as `YYYY-MM-DD`) in append-only mode (`"a"`). + - Automatically creates the `metrics/` directory and writes the CSV header row when creating a new file. + - CSV columns: `timestamp,file_path,class_name,method_name,http_method,path,status_code,duration_ms,retries,error`. +- **`MetricsCollector`:** + - Initialized with `proxy: MetricsProxy | None = None`, defaulting to `LocalStorageMetricsProxy()`. + - `record(self, metric: RequestMetric) -> None` pushes the collected metric to `self.proxy.push(metric)`. + +### 2. Transport & Client Integration (`proofline/_transport.py`, `proofline/client.py`) +- Accept `metrics: MetricsCollector | None = None` in `ProoflineClient.__init__` and `AsyncProoflineClient.__init__` (or default `MetricsCollector(LocalStorageMetricsProxy())` when enabled). +- Capture caller/execution context (`file_path` as full resolved path, `class_name` if called on a class instance, `method_name`) and measure request wall-clock time via `time.perf_counter()`. +- Emit `RequestMetric` via `metrics.record(...)` once per completed operation (including retries), which delegates to `proxy.push(...)`. +- Never let exceptions raised inside `metrics.record` or `proxy.push` break SDK calls (ignore or log safely). +- Redact API token from `error` if present. + +### 3. Public Exports (`proofline/__init__.py`) +- Export `RequestMetric`, `MetricsProxy`, `LocalStorageMetricsProxy`, and `MetricsCollector` in `__all__`. + +### 4. Testing (`tests/test_metrics.py`) +- Implement all metrics collector and proxy tests in a dedicated test file (`tests/test_metrics.py`), separate from existing client/transport test suites. + +## Target Files +- `proofline/metrics.py` (new) +- `proofline/_transport.py` +- `proofline/client.py` +- `proofline/__init__.py` +- `tests/test_metrics.py` (new, dedicated test file for metrics collector) + +## Acceptance Criteria +- [ ] `MetricsProxy` is defined as an `ABC` and `MetricsCollector` pushes metrics to its configured proxy. +- [ ] `MetricsCollector()` defaults to `LocalStorageMetricsProxy`. +- [ ] `LocalStorageMetricsProxy` appends metrics to `metrics/{date}.csv` with header and full file path, class (if applicable), method, and request metrics data. +- [ ] Sync and async clients emit `RequestMetric` with accurate status, retry count, and `duration_ms >= 0`. +- [ ] Faulty `MetricsProxy.push` raising an exception does not fail the client request. +- [ ] All metrics collector tests are isolated in their own test file (`tests/test_metrics.py`). +- [ ] `pytest` and `mypy` pass with 100% type coverage on new code. diff --git a/proofline/__init__.py b/proofline/__init__.py index 5704485b..f097f5b4 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -35,6 +35,7 @@ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters from .exports import ExportDataset, ExportFormat, ExportPage +from .metrics import LocalStorageMetricsProxy, MetricsCollector, MetricsProxy, RequestMetric from .outcomes import AssessmentGap, CheckGap, ReviewOutcome __all__ = [ @@ -55,6 +56,9 @@ "ExportPage", "FileReviewRequest", "FileReviewResponse", + "LocalStorageMetricsProxy", + "MetricsCollector", + "MetricsProxy", "PatchReviewRequest", "PatchReviewResponse", "PatchTriggerSource", @@ -62,6 +66,7 @@ "ProoflineError", "RepositoryGuidance", "RepositoryNames", + "RequestMetric", "RerunResponse", "ReviewFilters", "ReviewOutcome", diff --git a/proofline/_transport.py b/proofline/_transport.py index f7723032..f3630c34 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -12,7 +12,7 @@ from contextvars import ContextVar from datetime import UTC, datetime from email.utils import parsedate_to_datetime -from time import monotonic, sleep +from time import monotonic, perf_counter, sleep from typing import Any, TypeAlias, cast from urllib.parse import urlsplit @@ -37,6 +37,7 @@ from ._generated.types import Unset from ._sync_http import IO_DEADLINE from ._sync_http import Transport as SyncHTTPTransport +from .metrics import MetricsCollector, RequestMetric, resolve_call_context VERSION = "5.6.0" MAX_RESPONSE_BYTES = 8 * 1024 * 1024 @@ -428,103 +429,196 @@ async def aclose(self) -> None: await self._inner.aclose() +def _error_message(exc: BaseException, token: SecretStr) -> str: + if isinstance(exc, ProoflineError): + raw_text = exc.detail + elif isinstance(exc, httpx.HTTPError): + raw_text = str(exc) or network_error(exc).detail + else: + raw_text = str(exc) or type(exc).__name__ + return cast(str, redacted(raw_text, token.get_secret_value())) + + +def _emit_metric( + metrics: MetricsCollector | None, + *, + request: httpx.Request, + started: float, + status_code: int | None, + retries: int, + error_text: str | None, +) -> None: + if metrics is None: + return + duration_ms = max(0.0, (perf_counter() - started) * 1000.0) + file_path, class_name, method_name = resolve_call_context() + metrics.record( + RequestMetric( + timestamp=datetime.now(UTC).isoformat(), + file_path=file_path, + class_name=class_name, + method_name=method_name, + http_method=request.method, + path=request.url.path, + status_code=status_code, + duration_ms=duration_ms, + retries=retries, + error=error_text, + ) + ) + + class RetryTransport(httpx.BaseTransport): - def __init__(self, token: SecretStr, timeout: float) -> None: + def __init__( + self, + token: SecretStr, + timeout: float, + metrics: MetricsCollector | None = None, + ) -> None: self._token = token self._timeout = timeout + self._metrics = metrics self._inner = SyncHTTPTransport() def handle_request(self, request: httpx.Request) -> httpx.Response: - for attempt in range(4): - limit_timeout(request) - deadline = monotonic() + self._timeout - marker = IO_DEADLINE.set(io_deadline(deadline)) - try: - response = self._inner.handle_request(request) - finally: - IO_DEADLINE.reset(marker) - if 300 <= response.status_code < 400: - response.close() - raise redirect_error(response.status_code) from None - if encoded_response(response): - response.close() - raise encoding_error(response.status_code) from None - if not isinstance(response.stream, httpx.SyncByteStream): - response.close() - raise unreadable_problem(response.status_code) - response.stream = DeadlineStream(response.stream, response.status_code, deadline) - if 200 <= response.status_code < 300: - return response - try: - response.read() - error = problem(response, self._token) - except httpx.HTTPError: - if response.status_code in (429, 503): - raise - error = unreadable_problem(response.status_code) - finally: - response.close() - delay = retry_delay(response.headers.get("Retry-After"), attempt) - if ( - request.method != "GET" - or response.status_code not in (429, 503) - or attempt == 3 - or delay is None - ): - raise error from None - sleep(delay_within_deadline(delay)) - raise timeout_error() + started = perf_counter() + retries = 0 + status_code: int | None = None + error_text: str | None = None + try: + for attempt in range(4): + retries = attempt + status_code = None + limit_timeout(request) + deadline = monotonic() + self._timeout + marker = IO_DEADLINE.set(io_deadline(deadline)) + try: + response = self._inner.handle_request(request) + finally: + IO_DEADLINE.reset(marker) + status_code = response.status_code + if 300 <= response.status_code < 400: + response.close() + raise redirect_error(response.status_code) from None + if encoded_response(response): + response.close() + raise encoding_error(response.status_code) from None + if not isinstance(response.stream, httpx.SyncByteStream): + response.close() + raise unreadable_problem(response.status_code) + response.stream = DeadlineStream(response.stream, response.status_code, deadline) + if 200 <= response.status_code < 300: + return response + try: + response.read() + error = problem(response, self._token) + except httpx.HTTPError: + if response.status_code in (429, 503): + raise + error = unreadable_problem(response.status_code) + finally: + response.close() + delay = retry_delay(response.headers.get("Retry-After"), attempt) + if ( + request.method != "GET" + or response.status_code not in (429, 503) + or attempt == 3 + or delay is None + ): + raise error from None + sleep(delay_within_deadline(delay)) + raise timeout_error() + except Exception as exc: + error_text = _error_message(exc, self._token) + raise + finally: + _emit_metric( + self._metrics, + request=request, + started=started, + status_code=status_code, + retries=retries, + error_text=error_text, + ) def close(self) -> None: self._inner.close() class AsyncRetryTransport(httpx.AsyncBaseTransport): - def __init__(self, token: SecretStr, timeout: float) -> None: + def __init__( + self, + token: SecretStr, + timeout: float, + metrics: MetricsCollector | None = None, + ) -> None: self._token = token self._timeout = timeout + self._metrics = metrics self._inner = httpx.AsyncHTTPTransport() async def handle_async_request(self, request: httpx.Request) -> httpx.Response: - for attempt in range(4): - limit_timeout(request) - deadline = monotonic() + self._timeout - try: - with anyio.fail_after(io_budget(deadline)): - response = await self._inner.handle_async_request(request) - except TimeoutError: - raise httpx.ReadTimeout("The request deadline expired.") from None - if 300 <= response.status_code < 400: - await response.aclose() - raise redirect_error(response.status_code) from None - if encoded_response(response): - await response.aclose() - raise encoding_error(response.status_code) from None - if not isinstance(response.stream, httpx.AsyncByteStream): - await response.aclose() - raise unreadable_problem(response.status_code) - response.stream = AsyncDeadlineStream(response.stream, response.status_code, deadline) - if 200 <= response.status_code < 300: - return response - try: - await response.aread() - error = problem(response, self._token) - except httpx.HTTPError: - if response.status_code in (429, 503): - raise - error = unreadable_problem(response.status_code) - finally: - await response.aclose() - delay = retry_delay(response.headers.get("Retry-After"), attempt) - if ( - request.method != "GET" - or response.status_code not in (429, 503) - or attempt == 3 - or delay is None - ): - raise error from None - await async_sleep(delay_within_deadline(delay)) - raise timeout_error() + started = perf_counter() + retries = 0 + status_code: int | None = None + error_text: str | None = None + try: + for attempt in range(4): + retries = attempt + status_code = None + limit_timeout(request) + deadline = monotonic() + self._timeout + try: + with anyio.fail_after(io_budget(deadline)): + response = await self._inner.handle_async_request(request) + except TimeoutError: + raise httpx.ReadTimeout("The request deadline expired.") from None + status_code = response.status_code + if 300 <= response.status_code < 400: + await response.aclose() + raise redirect_error(response.status_code) from None + if encoded_response(response): + await response.aclose() + raise encoding_error(response.status_code) from None + if not isinstance(response.stream, httpx.AsyncByteStream): + await response.aclose() + raise unreadable_problem(response.status_code) + response.stream = AsyncDeadlineStream( + response.stream, response.status_code, deadline + ) + if 200 <= response.status_code < 300: + return response + try: + await response.aread() + error = problem(response, self._token) + except httpx.HTTPError: + if response.status_code in (429, 503): + raise + error = unreadable_problem(response.status_code) + finally: + await response.aclose() + delay = retry_delay(response.headers.get("Retry-After"), attempt) + if ( + request.method != "GET" + or response.status_code not in (429, 503) + or attempt == 3 + or delay is None + ): + raise error from None + await async_sleep(delay_within_deadline(delay)) + raise timeout_error() + except Exception as exc: + error_text = _error_message(exc, self._token) + raise + finally: + _emit_metric( + self._metrics, + request=request, + started=started, + status_code=status_code, + retries=retries, + error_text=error_text, + ) async def aclose(self) -> None: await self._inner.aclose() diff --git a/proofline/client.py b/proofline/client.py index 0a8239b4..bc7cdbe4 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -74,6 +74,7 @@ from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient +from .metrics import MetricsCollector from .outcomes import ReviewOutcome, outcome T = TypeVar("T") @@ -188,9 +189,11 @@ def __init__( *, base_url: str = "https://proofline.sh", timeout: float = 30, + metrics: MetricsCollector | None = None, ) -> None: self._api = _configuration(token, base_url, timeout) self._base_url = _transport.base_url(base_url) + self._metrics = metrics self._http = httpx.Client( base_url=self._base_url, auth=_transport.BearerAuth(self._api.token), @@ -201,7 +204,7 @@ def __init__( timeout=httpx.Timeout(timeout), follow_redirects=False, trust_env=False, - transport=_transport.RetryTransport(self._api.token, timeout), + transport=_transport.RetryTransport(self._api.token, timeout, metrics=metrics), ) self._api.set_httpx_client(self._http) self.mcp = McpClient(self._http) @@ -517,9 +520,11 @@ def __init__( *, base_url: str = "https://proofline.sh", timeout: float = 30, + metrics: MetricsCollector | None = None, ) -> None: self._api = _configuration(token, base_url, timeout) self._base_url = _transport.base_url(base_url) + self._metrics = metrics self._http = httpx.AsyncClient( base_url=self._base_url, auth=_transport.BearerAuth(self._api.token), @@ -530,7 +535,7 @@ def __init__( timeout=httpx.Timeout(timeout), follow_redirects=False, trust_env=False, - transport=_transport.AsyncRetryTransport(self._api.token, timeout), + transport=_transport.AsyncRetryTransport(self._api.token, timeout, metrics=metrics), ) self._api.set_async_httpx_client(self._http) self.mcp = AsyncMcpClient(self._http) diff --git a/proofline/metrics.py b/proofline/metrics.py new file mode 100644 index 00000000..9e24831d --- /dev/null +++ b/proofline/metrics.py @@ -0,0 +1,186 @@ +"""Runtime metrics collector and backend proxy abstractions.""" + +from __future__ import annotations + +import csv +import inspect +from abc import ABC, abstractmethod +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from types import FrameType + +CSV_COLUMNS: tuple[str, ...] = ( + "timestamp", + "file_path", + "class_name", + "method_name", + "http_method", + "path", + "status_code", + "duration_ms", + "retries", + "error", +) + +_PACKAGE_ROOT = Path(__file__).resolve().parent +_INTERNAL_FILES = { + str((_PACKAGE_ROOT / "metrics.py").resolve()), + str((_PACKAGE_ROOT / "_transport.py").resolve()), + str((_PACKAGE_ROOT / "_sync_http.py").resolve()), +} +_GENERATED_API_DIR = str((_PACKAGE_ROOT / "_generated" / "api" / "default").resolve()) + + +@dataclass(frozen=True) +class RequestMetric: + """Telemetry record emitted for a completed or failed SDK HTTP operation.""" + + timestamp: str + file_path: str + class_name: str | None + method_name: str + http_method: str + path: str + status_code: int | None + duration_ms: float + retries: int + error: str | None = None + + +class MetricsProxy(ABC): + """Abstract backend interface responsible for storing or exporting metrics.""" + + @abstractmethod + def push(self, metric: RequestMetric) -> None: + """Forward a single request metric to the underlying backend.""" + + +def _extract_date(timestamp: str) -> str: + if ( + len(timestamp) >= 10 + and timestamp[4] == "-" + and timestamp[7] == "-" + and timestamp[:4].isdigit() + and timestamp[5:7].isdigit() + and timestamp[8:10].isdigit() + ): + return timestamp[:10] + return datetime.now(UTC).strftime("%Y-%m-%d") + + +class LocalStorageMetricsProxy(MetricsProxy): + """Default metrics proxy that appends records to ``metrics/{date}.csv``.""" + + def __init__(self, directory: str | Path = "metrics") -> None: + self._directory = Path(directory) + + @property + def directory(self) -> Path: + return self._directory + + def report_path(self, date_str: str | None = None) -> Path: + day = date_str or datetime.now(UTC).strftime("%Y-%m-%d") + return self._directory / f"{day}.csv" + + def push(self, metric: RequestMetric) -> None: + day = _extract_date(metric.timestamp) + target = self.report_path(day) + target.parent.mkdir(parents=True, exist_ok=True) + write_header = not target.exists() or target.stat().st_size == 0 + with target.open("a", encoding="utf-8", newline="") as handle: + writer = csv.writer(handle) + if write_header: + writer.writerow(CSV_COLUMNS) + writer.writerow( + [ + metric.timestamp, + metric.file_path, + metric.class_name or "", + metric.method_name, + metric.http_method, + metric.path, + "" if metric.status_code is None else str(metric.status_code), + f"{metric.duration_ms:.3f}", + str(metric.retries), + metric.error or "", + ] + ) + + +class MetricsCollector: + """Collects SDK runtime metrics and pushes them to a configured MetricsProxy.""" + + def __init__(self, proxy: MetricsProxy | None = None) -> None: + self._proxy: MetricsProxy = proxy if proxy is not None else LocalStorageMetricsProxy() + + @property + def proxy(self) -> MetricsProxy: + return self._proxy + + def record(self, metric: RequestMetric) -> None: + try: + self._proxy.push(metric) + except Exception: + pass + + +def _frame_class_name(frame: FrameType) -> str | None: + instance = frame.f_locals.get("self") + if instance is not None: + return type(instance).__name__ + cls_obj = frame.f_locals.get("cls") + if isinstance(cls_obj, type): + return cls_obj.__name__ + qualname = getattr(frame.f_code, "co_qualname", "") + if "." in qualname: + prefix = qualname.rsplit(".", 1)[0] + if "" not in prefix: + return prefix.split(".")[-1] + return None + + +def _is_skip_frame(frame: FrameType) -> bool: + filename = str(Path(frame.f_code.co_filename).resolve()) + if filename in _INTERNAL_FILES: + return True + module_name = frame.f_globals.get("__name__", "") + if isinstance(module_name, str) and module_name.startswith( + ("httpx", "httpcore", "anyio", "asyncio", "contextlib") + ): + return True + if frame.f_code.co_name == "_call" and filename == str((_PACKAGE_ROOT / "client.py").resolve()): + return True + if filename.startswith(_GENERATED_API_DIR): + caller = frame.f_back + if caller is not None: + caller_file = str(Path(caller.f_code.co_filename).resolve()) + if caller_file.startswith(str(_PACKAGE_ROOT)): + return True + return False + + +def resolve_call_context() -> tuple[str, str | None, str]: + """Return ``(file_path, class_name, method_name)`` for the active SDK operation.""" + frame = inspect.currentframe() + try: + cursor = frame.f_back if frame is not None else None + fallback: FrameType | None = None + while cursor is not None: + fallback = cursor + if not _is_skip_frame(cursor): + return ( + str(Path(cursor.f_code.co_filename).resolve()), + _frame_class_name(cursor), + cursor.f_code.co_name, + ) + cursor = cursor.f_back + if fallback is not None: + return ( + str(Path(fallback.f_code.co_filename).resolve()), + _frame_class_name(fallback), + fallback.f_code.co_name, + ) + return ("", None, "") + finally: + del frame diff --git a/tests/test_metrics.py b/tests/test_metrics.py new file mode 100644 index 00000000..264986d6 --- /dev/null +++ b/tests/test_metrics.py @@ -0,0 +1,233 @@ +"""Dedicated test suite for the SDK runtime metrics collector and proxies.""" + +from __future__ import annotations + +import csv +from abc import ABC +from pathlib import Path + +import httpx +import pytest +from pydantic import SecretStr + +from proofline import ( + AsyncProoflineClient, + LocalStorageMetricsProxy, + MetricsCollector, + MetricsProxy, + ProoflineClient, + ProoflineError, + RequestMetric, + _transport, +) +from proofline.metrics import CSV_COLUMNS + +from .fixtures import FINDING, ORG, TOKEN, finding, page +from .http_server import Reply, Request, Server + + +class InMemoryMetricsProxy(MetricsProxy): + def __init__(self) -> None: + self.metrics: list[RequestMetric] = [] + + def push(self, metric: RequestMetric) -> None: + self.metrics.append(metric) + + +class FailingMetricsProxy(MetricsProxy): + def push(self, metric: RequestMetric) -> None: + raise RuntimeError("backend unavailable") + + +def test_metrics_proxy_is_abstract() -> None: + assert issubclass(MetricsProxy, ABC) + with pytest.raises(TypeError): + MetricsProxy() # type: ignore[abstract] + + +def test_metrics_collector_defaults_to_local_storage_proxy() -> None: + collector = MetricsCollector() + assert isinstance(collector.proxy, LocalStorageMetricsProxy) + assert collector.proxy.directory == Path("metrics") + + +def test_local_storage_metrics_proxy_appends_csv_report( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.chdir(tmp_path) + collector = MetricsCollector() + + first = RequestMetric( + timestamp="2026-11-14T09:30:00+00:00", + file_path="/opt/app/service.py", + class_name="ReviewRunner", + method_name="fetch_reviews", + http_method="GET", + path="/api/v1/organizations/123/reviews", + status_code=200, + duration_ms=12.345, + retries=0, + error=None, + ) + second = RequestMetric( + timestamp="2026-11-14T09:31:00+00:00", + file_path="/opt/app/cli.py", + class_name=None, + method_name="run_cli", + http_method="POST", + path="/api/v1/organizations/123/reviews", + status_code=503, + duration_ms=45.678, + retries=3, + error="Service unavailable", + ) + + collector.record(first) + collector.record(second) + + report_file = tmp_path / "metrics" / "2026-11-14.csv" + assert report_file.is_file() + + with report_file.open("r", encoding="utf-8", newline="") as handle: + rows = list(csv.reader(handle)) + + assert rows[0] == list(CSV_COLUMNS) + assert len(rows) == 3 + assert rows[1] == [ + "2026-11-14T09:30:00+00:00", + "/opt/app/service.py", + "ReviewRunner", + "fetch_reviews", + "GET", + "/api/v1/organizations/123/reviews", + "200", + "12.345", + "0", + "", + ] + assert rows[2] == [ + "2026-11-14T09:31:00+00:00", + "/opt/app/cli.py", + "", + "run_cli", + "POST", + "/api/v1/organizations/123/reviews", + "503", + "45.678", + "3", + "Service unavailable", + ] + + +def test_sync_client_emits_metrics_and_writes_csv(tmp_path: Path) -> None: + proxy = LocalStorageMetricsProxy(directory=tmp_path / "metrics") + collector = MetricsCollector(proxy=proxy) + + with Server(lambda _req, _n: Reply(body=page())) as peer: + with ProoflineClient(SecretStr(TOKEN), base_url=peer.url, metrics=collector) as client: + result = client.list_reviews(ORG) + assert len(result.items) == 1 + + csv_files = list((tmp_path / "metrics").glob("*.csv")) + assert len(csv_files) == 1 + with csv_files[0].open("r", encoding="utf-8", newline="") as handle: + rows = list(csv.DictReader(handle)) + + assert len(rows) == 1 + row = rows[0] + assert Path(row["file_path"]).is_absolute() + assert row["file_path"].endswith("proofline/client.py") + assert row["class_name"] == "ProoflineClient" + assert row["method_name"] == "list_reviews" + assert row["http_method"] == "GET" + assert row["path"] == f"/api/v1/organizations/{ORG}/reviews" + assert row["status_code"] == "200" + assert float(row["duration_ms"]) >= 0.0 + assert row["retries"] == "0" + assert row["error"] == "" + + +async def test_async_client_emits_metrics_with_retries_and_redacted_errors() -> None: + proxy = InMemoryMetricsProxy() + collector = MetricsCollector(proxy=proxy) + + def responder(req: Request, count: int) -> Reply: + if req.path.endswith("/reviews"): + if count < 2: + return Reply( + status=503, + headers={"Retry-After": "0"}, + body={"type": "unavailable", "detail": "Temporary overload"}, + ) + return Reply(body=page()) + return Reply( + status=403, + body={"type": "forbidden", "detail": f"Denied for token {TOKEN}"}, + ) + + with Server(responder) as peer: + async with AsyncProoflineClient( + SecretStr(TOKEN), base_url=peer.url, metrics=collector + ) as client: + reviews = await client.list_reviews(ORG) + assert len(reviews.items) == 1 + + with pytest.raises(ProoflineError) as exc_info: + await client.get_finding(ORG, FINDING) + assert exc_info.value.status == 403 + + assert len(proxy.metrics) == 2 + + first = proxy.metrics[0] + assert first.class_name == "AsyncProoflineClient" + assert first.method_name == "list_reviews" + assert first.http_method == "GET" + assert first.status_code == 200 + assert first.retries == 2 + assert first.duration_ms >= 0.0 + assert first.error is None + + second = proxy.metrics[1] + assert second.class_name == "AsyncProoflineClient" + assert second.method_name == "get_finding" + assert second.http_method == "GET" + assert second.status_code == 403 + assert second.retries == 0 + assert second.error == "Denied for token [redacted]" + assert TOKEN not in (second.error or "") + + +def test_function_call_without_class_records_none_class_name() -> None: + proxy = InMemoryMetricsProxy() + collector = MetricsCollector(proxy=proxy) + + def standalone_caller(url: str) -> int: + transport = _transport.RetryTransport(SecretStr(TOKEN), 5.0, metrics=collector) + with httpx.Client(base_url=url, transport=transport) as http_client: + response = http_client.get(f"/api/v1/organizations/{ORG}/findings/{FINDING}") + return response.status_code + + with Server(lambda _req, _n: Reply(body=finding())) as peer: + assert standalone_caller(peer.url) == 200 + + assert len(proxy.metrics) == 1 + metric = proxy.metrics[0] + assert metric.file_path == str(Path(__file__).resolve()) + assert metric.class_name is None + assert metric.method_name == "standalone_caller" + assert metric.status_code == 200 + + +async def test_faulty_metrics_proxy_does_not_break_client_requests() -> None: + collector = MetricsCollector(proxy=FailingMetricsProxy()) + + with Server(lambda _req, _n: Reply(body=finding())) as peer: + with ProoflineClient(SecretStr(TOKEN), base_url=peer.url, metrics=collector) as client: + sync_result = client.get_finding(ORG, FINDING) + assert sync_result.id == FINDING + + async with AsyncProoflineClient( + SecretStr(TOKEN), base_url=peer.url, metrics=collector + ) as async_client: + async_result = await async_client.get_finding(ORG, FINDING) + assert async_result.id == FINDING