diff --git a/backend/app/services/integration_config_service.py b/backend/app/services/integration_config_service.py index bf48c55ac..cb99f2d73 100644 --- a/backend/app/services/integration_config_service.py +++ b/backend/app/services/integration_config_service.py @@ -40,6 +40,7 @@ from app.core.integration_values import valid_splunk_index from app.core.sample_values import configured_value from app.models.postgres import AppSetting, Project +from app.services.prometheus_policy import prometheus_offline_reason from app.services.secret_service import read_secret logger = structlog.get_logger("services.integration_config") @@ -324,8 +325,9 @@ def prometheus_unavailable_reason(self) -> Optional[str]: """offline_mode | disabled | not_configured | None (offline read LIVE, D19: no offline exception). The egress host check is separate (``url_safety.egress_block_reason``, async).""" - if settings.AI_OFFLINE_MODE: - return "offline_mode" + offline_reason = prometheus_offline_reason() + if offline_reason is not None: + return offline_reason if not self.prometheus_enabled: return "disabled" if not _text(self.prometheus_base_url): diff --git a/backend/app/services/integration_probe_service.py b/backend/app/services/integration_probe_service.py index 8d17152ed..7aa816955 100644 --- a/backend/app/services/integration_probe_service.py +++ b/backend/app/services/integration_probe_service.py @@ -27,6 +27,7 @@ from typing import TYPE_CHECKING, Any, Optional from app.core.http_client import get_http_client, get_integration_http_client +from app.services.prometheus_policy import prometheus_offline_reason from app.services.url_safety import egress_block_reason if TYPE_CHECKING: # pragma: no cover - typing only @@ -499,9 +500,10 @@ async def probe_prometheus(config: dict | None = None) -> ProbeResult: """ from app.services.prometheus_vocab import PROBE_SENTENCES - refused = _offline_hard_gate("prometheus") - if refused: - return refused + if prometheus_offline_reason() is not None: + return ProbeResult( + "prometheus", "skipped", message="AI_OFFLINE_MODE=true -- outbound prometheus calls are disabled" + ) config = config or {} base_url = (config.get("prometheus_base_url") or "").strip().rstrip("/") token = config.get("prometheus_bearer_token") diff --git a/backend/app/services/observed_performance.py b/backend/app/services/observed_performance.py index df1620465..e54e7086a 100644 --- a/backend/app/services/observed_performance.py +++ b/backend/app/services/observed_performance.py @@ -39,6 +39,7 @@ from starlette.types import ASGIApp, Message, Receive, Scope, Send from app.core.config import settings +from app.services.prometheus_policy import prometheus_offline_reason logger = logging.getLogger(__name__) @@ -317,6 +318,9 @@ async def _in_app_counts(redis: Any, window_seconds: int, now: Optional[float] = async def _prometheus_rows(budgets: list, window: str) -> Optional[dict[str, dict[str, Any]]]: """Per operation ``{p50, p95, p99, count}`` from Prometheus, or None when it cannot answer.""" + if prometheus_offline_reason() is not None: + return None + import httpx from app.core.http_client import http_verify diff --git a/backend/app/services/prometheus_policy.py b/backend/app/services/prometheus_policy.py new file mode 100644 index 000000000..fb12458ba --- /dev/null +++ b/backend/app/services/prometheus_policy.py @@ -0,0 +1,9 @@ +"""Shared egress policy for every Prometheus integration.""" +from typing import Optional + +from app.core.config import settings + + +def prometheus_offline_reason() -> Optional[str]: + """Return the live offline block reason, or ``None`` when lookups are allowed.""" + return "offline_mode" if settings.AI_OFFLINE_MODE else None diff --git a/backend/tests/regression/test_observed_performance.py b/backend/tests/regression/test_observed_performance.py index b435af36a..9f2401be4 100644 --- a/backend/tests/regression/test_observed_performance.py +++ b/backend/tests/regression/test_observed_performance.py @@ -231,12 +231,32 @@ def handler(request: httpx.Request) -> httpx.Response: real = httpx.AsyncClient monkeypatch.setattr(httpx, "AsyncClient", lambda **k: real(transport=httpx.MockTransport(handler), **k)) + monkeypatch.setattr(op.settings, "AI_OFFLINE_MODE", False) monkeypatch.setattr(op.settings, "PROMETHEUS_URL", "http://prometheus.internal:9090") result = asyncio.run(op.observed("1h", redis=FakeRedis())) row = next(r for r in result["budgets"] if r["operation"] == "run_list") assert result["source"] == "prometheus" and row["observed_p95_ms"] == 140.0 and row["count"] == 812 +def test_offline_mode_never_queries_prometheus_and_keeps_in_app_counts(monkeypatch): + import httpx + + def unexpected_client(**_kwargs): + pytest.fail("offline observation constructed a Prometheus HTTP client") + + redis = FakeRedis() + now = 1_800_000_000.0 + op.record_latency("run_list", 120, now=now) + asyncio.run(op.flush(redis)) + monkeypatch.setattr(httpx, "AsyncClient", unexpected_client) + monkeypatch.setattr(op.settings, "AI_OFFLINE_MODE", True) + monkeypatch.setattr(op.settings, "PROMETHEUS_URL", "http://prometheus.internal:9090") + + result = asyncio.run(op.observed("1h", redis=redis, now=now + 1)) + row = next(r for r in result["budgets"] if r["operation"] == "run_list") + assert result["source"] == "in_app" and row["count"] == 1 and row["measured"] is True + + def test_route_roles(): from app.main import app diff --git a/docs/operations/configuration.md b/docs/operations/configuration.md index 15e9d16ba..b15450f35 100644 --- a/docs/operations/configuration.md +++ b/docs/operations/configuration.md @@ -331,7 +331,7 @@ TestLookup works without any model (`ANALYSIS_MODE=rules`). With a model, it is | `GITHUB_TOKEN` | str (optional) | unset | Instance-wide GitHub token, used only by the deployment-wide GitHub row of Integration health (`api.github.com/rate_limit`); a token saved at `/settings/integrations` comes first. Since W10 no commit lookup reads it: the run Changes tab, the regression diff and the build-changes agent tool list commits through each project's own GitHub integration (`/settings/github`), offline-gated. **Secret.** | | `GITHUB_APP_API_BASE_URL` | str | `https://api.github.com` | The one GitHub API base the deployment's GitHub App signs in at. Set it to `https:///api/v3` for GitHub Enterprise Server. A project integration whose API base differs gets no App token; a project's own base URL never chooses where the App's sign-in request goes. Does not affect personal access tokens. | | `GITHUB_REPO` | str (optional) | unset | Accepted for compatibility, not used (it named the repository of the former instance-wide commit lookups). | -| `PROMETHEUS_URL` | str (optional) | unset | Prometheus base URL (for example `http://prometheus:9090`) for the agents' application-metrics tool and, when set, the observed latency on Settings › Performance. Unset disables the tool; Performance then measures in-app. | +| `PROMETHEUS_URL` | str (optional) | unset | Base URL for TestLookup’s self-monitoring Prometheus (for example `http://prometheus:9090`). Settings › Performance uses this server when it answers and `AI_OFFLINE_MODE=false`. Performance uses Redis-backed in-app counters when offline mode is enabled, the URL is unset, or Prometheus cannot answer. | | `SLOW_QUERY_MS` | int | `500` | Statements at least this slow (ms) are captured, as their shape only (no values), for Settings › Performance › Slow queries. | #### Anomaly detection