From 30edfba5a96f4a1537735dea93d5a241b7882999 Mon Sep 17 00:00:00 2001
From: Anand Topu
Date: Thu, 26 Nov 2026 22:30:44 -0600
Subject: [PATCH 01/13] fix: harden observability and upload failure handling
Start iteration 1 on one shared branch and preserve the upstream main/MFA
changes. Track all eight epics and 43 stories in the maintainer delivery
ledger; advance 13 stories without claiming production acceptance.
Sanitize all configured trace sinks, bound browser telemetry bytes, preserve
core error correlation, reset worker context/readiness, and keep ambiguous
upload publication off the API loop without deleting its payload.
Expose bounded collection freshness and durable SQL workflow outcomes.
Correct quiet-webhook alert semantics, filter stale replicas before shared
state aggregation, and run checksum-pinned semantic fixtures in existing CI.
Require trusted exact-SHA scan evidence for publication/release and scan raw
candidate blobs in addition to history. Keep synthetic fixture exceptions
narrow and remove the former SDK-directory exemption.
Validation: 371 focused backend cases; 18 frontend telemetry cases; production
build, type and bundle checks; 501 release/docs/quality contracts; pinned
Python 3.14 / SDK 1.45.2 trace and Celery 5.7 upload checks; 38 Prometheus rules
and 12 semantic fixture groups. Generated references and source/CR parity pass.
Durable upload reconciliation, deployed signal delivery, persistent logs and
traces, audit archival, SLO/capacity work and hosted gate acceptance remain
tracked. No deployment, push or workflow dispatch is part of this iteration.
Signed-off-by: Anand Topu
---
.github/workflows/ci.yml | 44 ++
.github/workflows/require-verified-sha.yml | 13 +
.github/workflows/secret-scan.yml | 23 +-
.gitleaks.toml | 76 ++-
CHANGELOG.md | 6 +
backend/app/bootstrap.py | 26 +-
backend/app/core/analytics_errors.py | 22 +-
backend/app/core/metrics.py | 39 ++
backend/app/core/tracing.py | 246 ++++++++-
backend/app/routers/ingest.py | 102 +++-
.../app/services/agent_operational_metrics.py | 7 +-
backend/app/services/compliance_signing.py | 2 +-
.../downstream_operational_metrics.py | 82 +++
backend/app/services/metric_collection.py | 98 ++++
.../app/services/password_reset_service.py | 2 +-
backend/app/worker/celery_app.py | 68 ++-
backend/app/worker/tasks.py | 13 +-
backend/app/worker/upload_dispatch.py | 72 +++
.../test_compose_queue_delivery_redis.py | 6 +-
.../test_http_exchanges_postgres_mongo.py | 2 +-
.../integration/test_ingest_admission_http.py | 4 +-
backend/tests/integration/test_ingest_api.py | 18 +-
.../integration/test_shadow_pairs_postgres.py | 2 +-
.../test_alert_rules_are_deployable.py | 28 +-
.../test_ci_run_url_is_http_only.py | 2 +-
.../regression/test_core_error_correlation.py | 92 ++++
backend/tests/regression/test_demo_compose.py | 2 +-
.../regression/test_json_batch_lifecycle.py | 8 +-
.../regression/test_jwt_is_pyjwt_not_jose.py | 4 +-
.../test_live_ingestion_sanitization.py | 4 +-
.../test_operational_metric_collection.py | 305 +++++++++++
.../test_prompt_sanitizer_authorization.py | 2 +-
.../regression/test_trace_export_boundary.py | 264 ++++++++++
.../test_upload_dispatch_boundary.py | 322 ++++++++++++
.../test_worker_readiness_sentinel.py | 35 ++
.../test_worker_task_log_context.py | 132 +++++
.../test_agent_operational_metrics.py | 5 +
.../services/test_shadow_pair_service.py | 4 +-
.../services/test_tier_comparison_service.py | 2 +-
.../test_agent_invocation_idempotency.py | 4 +-
backend/tests/test_agent_reliability.py | 8 +-
backend/tests/test_api_key_auth.py | 2 +-
backend/tests/test_bulk_trigger_job.py | 2 +-
backend/tests/test_cluster_epic_routes.py | 4 +-
backend/tests/test_cluster_epic_service.py | 2 +-
.../tests/test_compliance_pack_routes_w11.py | 2 +-
.../tests/test_embedding_generation_task.py | 2 +-
backend/tests/test_evidence_confidence.py | 2 +-
backend/tests/test_global_search.py | 2 +-
backend/tests/test_http_exchange_redaction.py | 2 +-
backend/tests/test_http_exchange_store.py | 2 +-
backend/tests/test_phase4_safety.py | 8 +-
backend/tests/test_privacy_redaction.py | 2 +-
backend/tests/test_prometheus_settings.py | 2 +-
backend/tests/test_rag_services.py | 2 +-
.../tests/test_run_context_ingest_paths.py | 4 +-
.../python/http_capture_demo/test_products.py | 2 +-
.../TestLookupRestAssuredFilterTest.java | 2 +-
client/js/tests/auth-and-config.test.mjs | 8 +-
client/tests/test_http_capture.py | 2 +-
docs/architecture/codebase-map.md | 2 +-
docs/maintainers/README.md | 2 +
docs/maintainers/observability-delivery.md | 127 +++++
docs/reference/api/ingest.md | 56 +-
docs/reference/openapi.json | 46 ++
docs/reference/worker-operations.md | 198 +++----
.../components/agents/TryAgentPanel.test.tsx | 2 +-
.../charts/__fixtures__/wave2Fixtures.ts | 4 +-
.../src/pages/settings/apiKeysCurl.test.ts | 2 +-
.../src/pages/settings/oneTimeValues.test.tsx | 2 +-
frontend/src/services/agentService.test.ts | 2 +-
frontend/src/utils/errorReporting.test.ts | 481 +++++++++++-------
frontend/src/utils/errorReporting.ts | 359 +++++++------
.../visual/production/fixtures-in-page-b.ts | 8 +-
.../prometheus-rules/testlookup-alerts.yml | 54 +-
infra/monitoring/tests/operational-alerts.yml | 348 +++++++++++++
k8s/monitoring/prometheusrule.yaml | 32 +-
samples/README.md | 2 +-
scripts/release/scan_secret_snapshot.py | 165 ++++++
.../tests/test_scan_secret_snapshot.py | 211 ++++++++
.../release/tests/test_verify_secret_scan.py | 271 ++++++++++
scripts/release/verify_secret_scan.py | 178 +++++++
scripts/test_ci_security.py | 10 +-
83 files changed, 4237 insertions(+), 575 deletions(-)
create mode 100644 backend/app/services/downstream_operational_metrics.py
create mode 100644 backend/app/services/metric_collection.py
create mode 100644 backend/app/worker/upload_dispatch.py
create mode 100644 backend/tests/regression/test_core_error_correlation.py
create mode 100644 backend/tests/regression/test_operational_metric_collection.py
create mode 100644 backend/tests/regression/test_trace_export_boundary.py
create mode 100644 backend/tests/regression/test_upload_dispatch_boundary.py
create mode 100644 backend/tests/regression/test_worker_task_log_context.py
create mode 100644 docs/maintainers/observability-delivery.md
create mode 100644 infra/monitoring/tests/operational-alerts.yml
create mode 100644 scripts/release/scan_secret_snapshot.py
create mode 100644 scripts/release/tests/test_scan_secret_snapshot.py
create mode 100644 scripts/release/tests/test_verify_secret_scan.py
create mode 100644 scripts/release/verify_secret_scan.py
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f33648f4f..642c8e165 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -516,6 +516,28 @@ jobs:
- name: Lint with ruff
run: ruff check app/ tests/
+ # Same version as docker-compose.monitoring.yml. The SHA is from the
+ # immutable official v3.16.0 sha256sums.txt, checked before extracting or
+ # executing the tool. Run within this existing job, without a new matrix.
+ - name: Verify alert semantics with checksum-pinned promtool
+ working-directory: infra/monitoring/tests
+ env:
+ PROMETHEUS_VERSION: "3.16.0"
+ PROMETHEUS_ARCHIVE_SHA256: 68727009472a2c02e1ff7f062fd5b3e637285bffc8fc2d340c76fb449d6e0f34
+ run: |
+ set -euo pipefail
+ scratch="$(mktemp -d)"
+ trap 'rm -rf "$scratch"' EXIT
+ archive="$scratch/prometheus.tar.gz"
+ curl --fail --location --silent --show-error --retry 3 --max-time 180 \
+ --output "$archive" \
+ "https://github.com/prometheus/prometheus/releases/download/v${PROMETHEUS_VERSION}/prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz"
+ printf '%s %s\n' "$PROMETHEUS_ARCHIVE_SHA256" "$archive" | sha256sum --check --strict
+ tar -xzf "$archive" -C "$scratch" "prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool"
+ tool="$scratch/prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool"
+ "$tool" check rules ../prometheus-rules/testlookup-alerts.yml
+ "$tool" test rules operational-alerts.yml
+
# Blocking, as a ratchet (re-audit M24). mypy reports 391 pre-existing
# errors in 117 files; backend/mypy-baseline.txt holds the per-file
# counts and a file whose count goes UP fails here. Fixing errors lowers
@@ -1882,6 +1904,27 @@ jobs:
--exit-code 1 --ignorefile .trivyignore.yaml --timeout 10m
testlookup-scan/${{ matrix.name }}:${{ github.sha }}
+ verify-secret-scan:
+ name: Security — Require exact-SHA main secret scan
+ runs-on: ubuntu-latest
+ timeout-minutes: 17
+ if: github.ref == 'refs/heads/main' && github.event_name == 'push'
+ permissions:
+ contents: read
+ actions: read
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - name: Require existing successful secret-scan evidence before publication
+ env:
+ GH_TOKEN: ${{ github.token }}
+ SOURCE_SHA: ${{ github.sha }}
+ run: |
+ python3 scripts/release/verify_secret_scan.py \
+ --repository "$GITHUB_REPOSITORY" --source-sha "$SOURCE_SHA" \
+ --timeout-seconds 900 --poll-seconds 10
+
build-images:
name: Build & Push Images
runs-on: ubuntu-latest
@@ -1912,6 +1955,7 @@ jobs:
e2e-hermetic,
visual-regression,
security-deps,
+ verify-secret-scan,
]
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
diff --git a/.github/workflows/require-verified-sha.yml b/.github/workflows/require-verified-sha.yml
index 2ab95b997..1bf05db57 100644
--- a/.github/workflows/require-verified-sha.yml
+++ b/.github/workflows/require-verified-sha.yml
@@ -23,6 +23,7 @@ jobs:
require:
name: Require successful CI and immutable image manifest
runs-on: ubuntu-latest
+ timeout-minutes: 20
outputs:
source_sha: ${{ steps.verify.outputs.source_sha }}
ci_run_id: ${{ steps.verify.outputs.ci_run_id }}
@@ -48,3 +49,15 @@ jobs:
[[ "${#matches[@]}" -eq 1 ]] || { echo "Expected exactly one successful main ci.yml run for $SOURCE_SHA" >&2; exit 1; }
ci_run_id="${matches[0]}"
printf 'source_sha=%s\nci_run_id=%s\nartifact_name=%s\n' "$SOURCE_SHA" "$ci_run_id" "$artifact_name" >> "$GITHUB_OUTPUT"
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ ref: ${{ inputs.source_sha }}
+ persist-credentials: false
+ - name: Require successful exact-SHA secret scan before release authorization
+ env:
+ GH_TOKEN: ${{ github.token }}
+ SOURCE_SHA: ${{ inputs.source_sha }}
+ run: |
+ python3 scripts/release/verify_secret_scan.py \
+ --repository "$GITHUB_REPOSITORY" --source-sha "$SOURCE_SHA" \
+ --timeout-seconds 900 --poll-seconds 10
diff --git a/.github/workflows/secret-scan.yml b/.github/workflows/secret-scan.yml
index 108d15d55..430b218d5 100644
--- a/.github/workflows/secret-scan.yml
+++ b/.github/workflows/secret-scan.yml
@@ -9,8 +9,10 @@ name: Secret scan
# Its own workflow, not a ci.yml job: ci.yml skips Markdown-only changes, and a
# token pasted into a README or a runbook is exactly what this is for.
#
-# Only added lines are scanned, so the fake tokens in existing redaction tests
-# do not fire. A new deliberate fake value: make it obviously fake, or end the
+# Added history AND the full tracked candidate are scanned. Otherwise a failed
+# push followed by an unrelated push could leave the first push's secret in an
+# image while scanning only the second diff. A deliberate fake value: make it
+# obviously fake, or end the
# line with a `gitleaks:allow` comment and say why in the PR. A real secret
# that reached a pushed commit is public: rotate it, then remove it.
@@ -31,7 +33,7 @@ jobs:
gitleaks:
name: Security — Secret scan (gitleaks)
runs-on: ubuntu-latest
- timeout-minutes: 10
+ timeout-minutes: 15
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -50,6 +52,11 @@ jobs:
sudo install -m 0755 gitleaks /usr/local/bin/gitleaks
rm -f gitleaks gitleaks.tar.gz
+ - name: Prove full candidate coverage and raw-blob isolation
+ env:
+ GITLEAKS_TEST_BINARY: /usr/local/bin/gitleaks
+ run: python3 -m unittest discover -s scripts/release/tests -p test_scan_secret_snapshot.py
+
- name: Scan the added commits
env:
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
@@ -68,4 +75,12 @@ jobs:
fi
echo "Scanning: git log $log_opts"
gitleaks git --config .gitleaks.toml --redact --no-banner --exit-code 1 \
- --log-opts="$log_opts" .
+ --timeout 300 --log-opts="$log_opts" .
+
+ - name: Scan the full tracked candidate snapshot
+ if: github.event_name == 'push'
+ run: |
+ set -euo pipefail
+ python3 scripts/release/scan_secret_snapshot.py \
+ --source-sha "$GITHUB_SHA" --gitleaks /usr/local/bin/gitleaks \
+ --timeout-seconds 300
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 7352794d1..36e563a08 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -33,11 +33,79 @@ description = "Cloudflare tunnel token (base64 JSON with a/t/s keys)"
regex = '''eyJhIjoi[A-Za-z0-9+/=_\-]{40,}'''
keywords = ["eyjhijoi"]
-[[allowlists]]
-description = "Cross-SDK redaction vectors: they hold token-shaped fake values on purpose, to prove every SDK masks them"
-paths = ['''^sdk-vectors/''']
-
[[allowlists]]
description = "Chart axis keys such as p95_duration_ms read as high-entropy generic keys"
targetRules = ["generic-api-key"]
stopwords = ["_duration_ms"]
+
+# These exact golden chart-metadata lines are deterministic test labels, not
+# credentials. The AND condition permits no other value anywhere in this file.
+[[allowlists]]
+description = "Exact synthetic chart metadata in the analytics parity golden fixture"
+condition = "AND"
+targetRules = ["generic-api-key"]
+paths = ['''^backend/tests/integration/golden/analytics_parity_characterisation\.json$''']
+regexTarget = "line"
+regexes = [
+ '''^\s*"membership_key": "395524f698eb9382943f84f87782ca2b",\s*$''', # gitleaks:allow -- exact synthetic golden metadata
+ '''^\s*"membership_key": "398fa42ff77ee0c8119dd3749c780d3f",\s*$''', # gitleaks:allow -- exact synthetic golden metadata
+ '''^\s*"membership_key": "5a28a10db27b29653db1c73983d33b16",\s*$''', # gitleaks:allow -- exact synthetic golden metadata
+]
+
+# Shared SDK conformance vectors deliberately contain fixed synthetic canaries.
+# Match the exact recorded lines AND file AND detector, never the directory.
+
+[[allowlists]]
+description = "Exact synthetic cross-SDK redaction vector for aws-access-token"
+condition = "AND"
+targetRules = ["aws-access-token"]
+paths = ['''^sdk\-vectors/http_exchange\.json$''']
+regexTarget = "line"
+regexes = [
+ '''^\s*"X\-Debug": "key AKIAW23DSAMPLEKEYQZX",\s*$''', # gitleaks:allow -- exact synthetic conformance input
+]
+
+[[allowlists]]
+description = "Exact synthetic cross-SDK redaction vector for generic-api-key"
+condition = "AND"
+targetRules = ["generic-api-key"]
+paths = ['''^sdk\-vectors/http_exchange\.json$''']
+regexTarget = "line"
+regexes = [
+ '''^\s*"Sec\-WebSocket\-Key": "dGhlIHNhbXBsZSBub25jZQ==",\s*$''', # gitleaks:allow -- exact synthetic conformance input
+]
+
+[[allowlists]]
+description = "Exact synthetic cross-SDK redaction vector for github-pat"
+condition = "AND"
+targetRules = ["github-pat"]
+paths = ['''^sdk\-vectors/http_exchange\.json$''']
+regexTarget = "line"
+regexes = [
+ '''^\s*"X\-GitHub\-Token": "ghp_w23dSamplePatValueQxZkLmNoPqRsTuVwXy",\s*$''', # gitleaks:allow -- exact synthetic conformance input
+ '''^\s*"X\-Trace": "pat ghp_w23dSamplePatValueQxZkLmNoPqRsTuVwXy"\s*$''', # gitleaks:allow -- exact synthetic conformance input
+ '''^\s*"body": "\{\\"note\\": \\"sample ghp_w23dSamplePatValueQxZkLmNoPqRsTuVwXy\\", \\"id\\": 11\}"\s*$''', # gitleaks:allow -- exact synthetic conformance input
+ '''^\s*"url": "https://api\.example\.test/api/hooks/ghp_w23dSamplePatValueQxZkLmNoPqRsTuVwXy/deliveries",\s*$''', # gitleaks:allow -- exact synthetic conformance input
+ '''^\s*"url": "https://api\.example\.test/api/search\?q=ghp_w23dSamplePatValueQxZkLmNoPqRsTuVwXy\&limit=5",\s*$''', # gitleaks:allow -- exact synthetic conformance input
+]
+
+[[allowlists]]
+description = "Exact synthetic cross-SDK redaction vector for jwt"
+condition = "AND"
+targetRules = ["jwt"]
+paths = ['''^sdk\-vectors/http_exchange\.json$''']
+regexTarget = "line"
+regexes = [
+ '''^\s*"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\.eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9\.c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x",\s*$''', # gitleaks:allow -- exact synthetic conformance input
+ '''^\s*"body": "\{\\"session\\": \\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\.eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9\.c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x\\"\}"\s*$''', # gitleaks:allow -- exact synthetic conformance input
+]
+
+[[allowlists]]
+description = "Exact synthetic cross-SDK redaction vector for jwt"
+condition = "AND"
+targetRules = ["jwt"]
+paths = ['''^sdk\-vectors/run_context\.json$''']
+regexTarget = "line"
+regexes = [
+ '''^\s*"BUILD_IMAGE": "eyJSentinelSentinelSenti\.eyJPayloadSentinelPayloa\.SignatureSentinelSignatu"\s*$''', # gitleaks:allow -- exact synthetic conformance input
+]
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc4e6a739..a4e5ea1ad 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,10 +9,16 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).
### Added
+- Operational metrics expose collector freshness and durable downstream-outbox failure/overdue state, including alerts that avoid counting the same SQL rows across API replicas.
+
- Release verification: journey **TL-AUTH-003** (one account per browser profile, P1, disposable stack) checks the D-0019 fix on the live stack. In two tabs of one browser, a sign-in as a viewer moves the admin's tab onto the viewer with the note, a new tab opens as the viewer, and the viewer's sign-out signs the other tab out (`frontend/tests/release/session.spec.ts`, `e2e-runner/catalogue.yaml`).
### Changed
+- Upload publication uses bounded background threads; uncertain queue confirmation retains the payload and returns polling identifiers so callers can check before resubmitting.
+- Trace exporters sanitize exception events and custom text as well as URL attributes. Browser error batches use UTF-8 byte limits; unexpected core API errors return a correlated request identifier. Worker task context and startup readiness markers are reset between executions.
+- Image publication and release authorization require trusted successful secret-scan evidence for the exact main commit. Main pushes scan the full tracked candidate tree as well as added history, so an unchanged secret from an earlier failed push still blocks publication. Webhook failure alerts detect failures at low traffic volumes.
+
- Wording: the app, the in-app guide, the README and the user guide say "release" where they said "ship". Home's verdict banner reads "release cleared", "review before release" or "release blocked by unresolved failures"; Run intelligence reads "release cleared" or "release blocked"; the Releases page counts "Ready to release", says a GO release "is ready to release", and its "Shipping this week" panel is "Due this week". The escape rate counts defects filed after a release "went live". The README tagline is "Know why your software tests fail. Know when your release is ready." API fields keep their names (`ready_to_ship` is unchanged).
- Releases: the "Offline bundle" workflow takes a release version (`gh workflow run offline-bundle.yml -f version=X.Y.Z`) and bundles the image digests that release promoted instead of rebuilding them, refusing if they are not CI's images of the tagged commit. Every bundle run also produces `SHA256SUMS` for `install.sh` and the files it downloads.
- Tests: the integration suite runs clean as one process against real Postgres, Valkey, MongoDB and S3 (2,612 passed locally, was 4 failed and 6 errors). The integration conftest closes the cached MongoDB client and drops the cached Valkey pool at every module boundary, as the worker loop runner does after each loop, so a file that leaves one bound to its event loop no longer breaks the next. The LLM cost-cap tests keep the circuit breaker's keys per test (a tripped breaker failed every rerun of the file); the live-protocol and cost-cap tests release the shared Valkey pool; the decision-report supersession tests create the failing test case they need instead of skipping on a fresh database. `backend/tests/integration/conftest.py` and four test files.
diff --git a/backend/app/bootstrap.py b/backend/app/bootstrap.py
index 3a7c60a71..6b8bf9bd7 100644
--- a/backend/app/bootstrap.py
+++ b/backend/app/bootstrap.py
@@ -1,4 +1,5 @@
from __future__ import annotations
+import asyncio
import hmac
import inspect
@@ -357,7 +358,7 @@ def configure_middlewares(app: FastAPI) -> None:
# be a full payload) and the cache header would be invisible exactly
# where it is read. ``Retry-After`` -- the 429 and the 503
# ``analytics_timeout`` -- is already here.
- expose_headers=["X-Refresh-Retry-Safe", "Retry-After", "X-TestLookup-AI-Generated", "X-TestLookup-Review-State", "X-Request-ID", "X-Analytics-Meta", "ETag", "X-Analytics-Cache", "Content-Disposition", "X-Total-Count"],
+ expose_headers=["X-Refresh-Retry-Safe", "Retry-After", "X-TestLookup-AI-Generated", "X-TestLookup-Review-State", "X-Request-ID", "X-Analytics-Meta", "ETag", "X-Analytics-Cache", "Content-Disposition", "X-Total-Count", "Location", "X-Upload-Task-ID", "X-Upload-Run-ID"],
)
# Import locally so middleware setup stays close to other app wiring.
@@ -453,7 +454,7 @@ def register_routers(app: FastAPI) -> None:
)
-async def _refresh_celery_queue_depths() -> None:
+async def _refresh_celery_queue_depths() -> bool:
"""Read pending task counts straight off the Redis broker.
Celery queues are Redis lists keyed by queue name, so LLEN is the depth.
@@ -465,22 +466,26 @@ async def _refresh_celery_queue_depths() -> None:
from app.db.redis_client import get_redis
from app.worker.ingestion_routing import LEGACY_INGESTION_QUEUE, all_shard_queues
- queues = ["critical", "ai_analysis", "default", LEGACY_INGESTION_QUEUE]
+ queues = ["critical", "ai_analysis", "default", "agent_children", LEGACY_INGESTION_QUEUE]
queues += list(all_shard_queues())
redis = get_redis()
- for name in queues:
+ async def refresh_queue(name: str) -> bool:
try:
depth = await redis.llen(name)
except Exception: # noqa: BLE001 — one bad queue must not hide the rest
- continue
+ return False
celery_queue_length.labels(queue_name=name).set(float(depth or 0))
+ return True
+
+ return all(await asyncio.gather(*(refresh_queue(name) for name in queues)))
except Exception as exc: # noqa: BLE001
import structlog
structlog.get_logger(__name__).debug(
"celery_queue_depth_collection_failed", error=str(exc)
)
+ return False
def _metrics_scrape_refusal(request):
@@ -542,12 +547,19 @@ async def _endpoint(*args, __orig=original, **kwargs):
refusal = _metrics_scrape_refusal(request) if request is not None else None
if refusal is not None:
return refusal
- await _refresh_celery_queue_depths()
from app.services.agent_operational_metrics import (
refresh_agent_operational_metrics,
)
+ from app.services.downstream_operational_metrics import (
+ refresh_downstream_operational_metrics,
+ )
+ from app.services.metric_collection import collect_bounded
- await refresh_agent_operational_metrics()
+ await asyncio.gather(
+ collect_bounded("queues", _refresh_celery_queue_depths),
+ collect_bounded("agents", refresh_agent_operational_metrics),
+ collect_bounded("downstream", refresh_downstream_operational_metrics),
+ )
result = __orig(*args, **kwargs)
if inspect.isawaitable(result):
result = await result
diff --git a/backend/app/core/analytics_errors.py b/backend/app/core/analytics_errors.py
index e138e5a6d..6b40523d1 100644
--- a/backend/app/core/analytics_errors.py
+++ b/backend/app/core/analytics_errors.py
@@ -29,7 +29,7 @@
from fastapi.responses import JSONResponse, PlainTextResponse, Response
from starlette.exceptions import HTTPException as StarletteHTTPException
-from app.core.request_path import routed_path
+from app.core.request_path import telemetry_path
from app.core.scim_errors import (
scim_http_exception_handler,
scim_validation_exception_handler,
@@ -239,19 +239,27 @@ async def http_exception_handler(request: Request, exc: Exception) -> Response:
async def unhandled_exception_handler(request: Request, exc: Exception) -> Response:
- """The last resort. For analytics routes a JSON body carrying the request id
- and no trace; everywhere else exactly Starlette's non-debug default."""
- if not uses_analytics_contract(request):
- return PlainTextResponse("Internal Server Error", status_code=500)
+ """Correlated diagnostics for all routes, preserving their response bodies."""
+ from app.middleware.telemetry import accepted_request_id
+
+ request.state.request_id = accepted_request_id(request_id_of(request) or None)
+ analytics = uses_analytics_contract(request)
# The body tells the caller to quote this id, so the log line must carry
# the same one -- and the trace, which the body deliberately does not.
logger.error(
- "analytics_unhandled_error",
+ "analytics_unhandled_error" if analytics else "http_unhandled_error",
request_id=request_id_of(request),
error_type=type(exc).__name__,
- path=routed_path(request),
+ path=telemetry_path(request),
+ method=request.method,
+ status_code=500,
exc_info=exc,
)
+ if not analytics:
+ return PlainTextResponse(
+ "Internal Server Error", status_code=500,
+ headers={"X-Request-ID": request_id_of(request)},
+ )
body = error_body(
request,
code="internal_error",
diff --git a/backend/app/core/metrics.py b/backend/app/core/metrics.py
index 8cb97ad89..5db16db0a 100644
--- a/backend/app/core/metrics.py
+++ b/backend/app/core/metrics.py
@@ -843,3 +843,42 @@
"Fraction of candidate workflow steps measured by the replay corpus",
["project_id", "workflow_id"],
)
+
+# Operational collection is bounded; a previous gauge value is not proof that
+# its dependency was observed during the current scrape. Shared-state gauges
+# use mostrecent within a pod and max (not sum) across API replicas in rules.
+metric_collection_success = Gauge(
+ "testlookup_metric_collection_success",
+ "Whether the latest bounded collection completed successfully",
+ ["collector"],
+ multiprocess_mode="mostrecent",
+)
+metric_collection_last_success = Gauge(
+ "testlookup_metric_collection_last_success_timestamp_seconds",
+ "Unix timestamp of the latest complete successful collection",
+ ["collector"],
+ multiprocess_mode="mostrecent",
+)
+metric_collection_errors_total = Counter(
+ "testlookup_metric_collection_errors_total",
+ "Failed or timed-out operational collections",
+ ["collector"],
+)
+downstream_outbox_entries = Gauge(
+ "testlookup_downstream_outbox_entries",
+ "Durable downstream operations by bounded operation and lifecycle state",
+ ["operation", "status"],
+ multiprocess_mode="mostrecent",
+)
+downstream_outbox_oldest_age_seconds = Gauge(
+ "testlookup_downstream_outbox_oldest_age_seconds",
+ "Age of the oldest non-completed operation in the current SQL snapshot",
+ ["operation", "status"],
+ multiprocess_mode="mostrecent",
+)
+downstream_outbox_overdue_seconds = Gauge(
+ "testlookup_downstream_outbox_overdue_seconds",
+ "Seconds past the oldest retry or lease deadline for nonterminal work",
+ ["operation", "status"],
+ multiprocess_mode="mostrecent",
+)
diff --git a/backend/app/core/tracing.py b/backend/app/core/tracing.py
index 61aa88e63..ffc5435b1 100644
--- a/backend/app/core/tracing.py
+++ b/backend/app/core/tracing.py
@@ -6,17 +6,19 @@
- BatchSpanProcessor for low-overhead async export
- Auto-instrumentation for FastAPI, SQLAlchemy, httpx, Redis
-- A span processor, ahead of every exporter, that takes the query string and
- the path of a webhook URL out of the URL attributes (see ``add_url_redaction``)
+- Export-boundary sanitization of span attributes, events, status and metadata;
+ the original finished span is never modified by the exporter wrapper.
Exports get_tracer() and get_current_trace_id() helpers for use across the codebase.
"""
import logging
+import re
from collections.abc import Mapping
from typing import Any, Optional
from urllib.parse import urlsplit
from app.core.request_path import redact_path_credentials
+from app.services.redaction_service import is_log_secret_name, redact_log_message
logger = logging.getLogger(__name__)
@@ -76,13 +78,15 @@ def _redact_full_url(value: str) -> str:
"""
parts = urlsplit(value)
host = parts.hostname or ""
- if not parts.scheme or not host:
+ if parts.scheme and not host:
+ return REDACTED
+ if not host:
# Not something we can take apart: keep what precedes any query.
head = value.split("?", 1)[0].split("#", 1)[0]
return redact_path_credentials(head) + ("?" + REDACTED if "?" in value else "")
if ":" in host: # an IPv6 literal
host = "[" + host + "]"
- origin = parts.scheme + "://" + host + (":" + str(parts.port) if parts.port else "")
+ origin = (parts.scheme + "://" if parts.scheme else "//") + host + (":" + str(parts.port) if parts.port else "")
if _is_webhook_host(parts.hostname):
return origin + "/" + REDACTED
return origin + redact_path_credentials(parts.path) + ("?" + REDACTED if parts.query else "")
@@ -165,13 +169,243 @@ def on_end(self, span: Any) -> None:
def _add_exporter(provider: Any, exporter: Any) -> None:
- """Add a batching exporter, with the URL redaction in front of the first one."""
+ """Every configured exporter receives only sanitized span snapshots."""
from opentelemetry.sdk.trace.export import BatchSpanProcessor
processors = getattr(getattr(provider, "_active_span_processor", None), "_span_processors", ())
if not any(is_url_redaction(p) for p in processors):
add_url_redaction(provider)
- provider.add_span_processor(BatchSpanProcessor(exporter))
+ provider.add_span_processor(BatchSpanProcessor(redacting_span_exporter(exporter)))
+
+
+# Match references inside exception messages/stacks and custom diagnostic text,
+# not just attributes with a semantic-convention URL name. URL parsing removes
+# every query/fragment regardless of its parameter spelling or encoding.
+_TEXT_URL = re.compile(r"(?:[a-z][a-z0-9+.-]{0,31}:)?//[^\s\"'<>]+", re.IGNORECASE)
+_TEXT_SECRET = re.compile(
+ r"(?P(? str:
+ # Bound the shared operational-text scrubbers' work. Omit an oversized
+ # field completely: truncating first could leave an unrecognized fragment
+ # of a credential, and giant exception text must not monopolize export.
+ if len(value) > _MAX_TRACE_TEXT_CHARS:
+ return "[REDACTED_OVERSIZED_TRACE_TEXT]"
+
+ def reference(match: re.Match[str]) -> str:
+ address = match.group()
+ # JSON encoding escapes the surrounding quote, not the URL itself.
+ # Preserve that delimiter's backslashes when replacing a URL so the
+ # following assignment scan can still locate the encoded value's end.
+ trailing = len(address) - len(address.rstrip("\\"))
+ suffix = address[-trailing:] if trailing else ""
+ try:
+ return _redact_full_url(address[:-trailing] if trailing else address) + suffix
+ except (ValueError, TypeError):
+ return REDACTED + suffix
+
+ value = _TEXT_URL.sub(reference, value)
+ value = _redact_secret_assignments(value)
+ value = _TEXT_CREDENTIAL.sub(lambda match: match[1] + " " + REDACTED, value)
+ value = _TEXT_OPAQUE_TOKEN.sub(REDACTED, value)
+ return redact_log_message(value)
+
+
+def _redact_secret_assignments(value: str) -> str:
+ """Replace credential values without decoding surrounding diagnostic text.
+
+ A quoted JSON value can itself be encoded into another JSON string. Its
+ delimiter then has 1, 3, 7, ... preceding backslashes. Quotes inside that
+ value have a different escape parity. Recognizing the delimiter locally
+ handles both forms and passwords containing escaped quotes/backslashes.
+ """
+ pieces = []
+ cursor = 0
+ while match := _TEXT_SECRET.search(value, cursor):
+ start = match.end()
+ pieces.append(value[cursor:start])
+ opening = re.match(r"(\\*)([\"'])", value[start:])
+ if opening:
+ slashes, quote = opening.groups()
+ search_at = start + opening.end()
+ end = len(value)
+ replacement = opening.group() + REDACTED
+ while (position := value.find(quote, search_at)) >= 0:
+ before = position
+ while before > start and value[before - 1] == "\\":
+ before -= 1
+ if (position - before) % (2 * (len(slashes) + 1)) == len(slashes):
+ end = position + 1
+ replacement += slashes + quote
+ break
+ search_at = position + 1
+ # Malformed/unclosed credentials lose the remaining value, rather
+ # than leaving part of a secret in a recoverable alternate form.
+ pieces.append(replacement)
+ else:
+ unquoted = re.match(r"[^\s,;}\]]*", value[start:])
+ assert unquoted is not None # This expression always matches, including an empty value.
+ end = start + unquoted.end()
+ pieces.append(REDACTED)
+ cursor = end
+ pieces.append(value[cursor:])
+ return "".join(pieces)
+
+
+def _redact_trace_value(key: str, value: Any, *, depth: int = 0) -> Any:
+ normalized = key.lower().replace("-", "_")
+ if normalized == "url.query" and value:
+ return REDACTED
+ if (
+ normalized in _PAYLOAD_ATTRIBUTES
+ or is_log_secret_name(normalized.replace(".", "_"))
+ or is_log_secret_name(normalized.rsplit(".", 1)[-1])
+ ):
+ return value if value is None or isinstance(value, bool) else REDACTED
+ if isinstance(value, str):
+ return _redact_span_text(value)
+ if depth >= 10:
+ return REDACTED
+ if isinstance(value, Mapping):
+ return _redact_trace_attributes(value, depth=depth + 1)
+ if isinstance(value, (list, tuple)):
+ return tuple(_redact_trace_value(key, item, depth=depth + 1) for item in value)
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ # Never stringify an unsupported value after sanitization: its repr may
+ # contain exactly the sensitive input that the exporter must not receive.
+ return REDACTED
+
+
+def _redact_trace_attributes(attributes: Optional[Mapping[str, Any]], *, depth: int = 0) -> dict[str, Any]:
+ current = attributes or {}
+ try:
+ current = redact_span_attributes(current) or current
+ except (TypeError, ValueError):
+ current = {
+ key: value for key, value in current.items()
+ if key not in (*_FULL_URL_ATTRIBUTES, "url.query", "http.target", "url.path")
+ }
+ return {
+ _redact_span_text(key): _redact_trace_value(key, value, depth=depth)
+ for key, value in current.items() if isinstance(key, str)
+ }
+
+
+def _sanitized_span(span: Any) -> Any:
+ """Copy public SDK data into an export-only snapshot, including all copies.
+
+ Event/status objects remain untouched on the original ReadableSpan. This
+ boundary is shared by OTLP, console and test exporters, rather than relying
+ on mutating the SDK's private event/status storage from an on_end processor.
+ """
+ from opentelemetry.attributes import BoundedAttributes
+ from opentelemetry.sdk.resources import Resource
+ from opentelemetry.sdk.trace import Event, ReadableSpan
+ from opentelemetry.sdk.util.instrumentation import InstrumentationScope
+ from opentelemetry.trace import Link, SpanContext, Status, TraceState
+
+ def attributes(original):
+ copied = BoundedAttributes(
+ attributes=_redact_trace_attributes(original), maxlen=None, immutable=True,
+ )
+ copied.dropped = getattr(original, "dropped", 0)
+ return copied
+
+ def context(original):
+ if original is None:
+ return None
+ return SpanContext(
+ trace_id=original.trace_id, span_id=original.span_id,
+ is_remote=original.is_remote, trace_flags=original.trace_flags,
+ trace_state=TraceState([
+ (key, _redact_trace_value(key, value))
+ for key, value in original.trace_state.items()
+ ]),
+ )
+
+ scope = span.instrumentation_scope
+ safe_scope = None if scope is None else InstrumentationScope(
+ name=_redact_span_text(scope.name),
+ version=_redact_span_text(scope.version) if scope.version else scope.version,
+ schema_url=_redact_span_text(scope.schema_url) if scope.schema_url else scope.schema_url,
+ attributes=attributes(scope.attributes),
+ )
+ dropped = (span.dropped_attributes, span.dropped_events, span.dropped_links)
+
+ class _SanitizedSpan(ReadableSpan):
+ # Preserve SDK loss accounting while building ordinary immutable input
+ # containers, without reading or changing any SDK private storage.
+ @property
+ def dropped_attributes(self):
+ return dropped[0]
+
+ @property
+ def dropped_events(self):
+ return dropped[1]
+
+ @property
+ def dropped_links(self):
+ return dropped[2]
+
+ return _SanitizedSpan(
+ name=_redact_span_text(span.name), context=context(span.context), parent=context(span.parent),
+ kind=span.kind, start_time=span.start_time, end_time=span.end_time,
+ attributes=attributes(span.attributes),
+ events=tuple(Event(
+ name=_redact_span_text(event.name), timestamp=event.timestamp,
+ attributes=attributes(event.attributes),
+ limit=None,
+ ) for event in span.events),
+ links=tuple(Link(context(link.context), attributes(link.attributes)) for link in span.links),
+ status=Status(span.status.status_code, _redact_span_text(span.status.description) if span.status.description else None),
+ resource=Resource(
+ attributes(span.resource.attributes),
+ _redact_span_text(span.resource.schema_url) if span.resource.schema_url else span.resource.schema_url,
+ ),
+ instrumentation_scope=safe_scope,
+ )
+
+
+def redacting_span_exporter(exporter: Any) -> Any:
+ """Wrap an exporter with the complete privacy boundary; fail closed per span."""
+ from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
+
+ class _RedactingExporter(SpanExporter):
+ def export(self, spans):
+ safe = []
+ for span in spans:
+ try:
+ safe.append(_sanitized_span(span))
+ except Exception as exc: # noqa: BLE001 -- never export raw on failure
+ logger.warning("trace span omitted: sanitization failed (%s)", type(exc).__name__)
+ return exporter.export(tuple(safe)) if safe else SpanExportResult.FAILURE
+
+ def shutdown(self):
+ return exporter.shutdown()
+
+ def force_flush(self, timeout_millis=30000):
+ return exporter.force_flush(timeout_millis=timeout_millis)
+
+ return _RedactingExporter()
def setup_tracing(
diff --git a/backend/app/routers/ingest.py b/backend/app/routers/ingest.py
index fd4b826a9..90fa8a031 100644
--- a/backend/app/routers/ingest.py
+++ b/backend/app/routers/ingest.py
@@ -34,6 +34,20 @@
MAX_FILE_SIZE = 50 * 1024 * 1024 # 50 MB
_READ_CHUNK_SIZE = 1 * 1024 * 1024 # 1 MB chunks when streaming uploads
+_DISPATCH_RESPONSES = {
+ 503: {
+ "description": (
+ "Upload admission or queue confirmation unavailable. If Location and "
+ "X-Upload-Task-ID are present, processing may still start: poll the "
+ "existing upload before resubmitting."
+ ),
+ "headers": {
+ "Location": {"description": "Existing upload status URL, when dispatch is unconfirmed", "schema": {"type": "string"}},
+ "X-Upload-Task-ID": {"description": "Existing upload task identifier, when dispatch is unconfirmed", "schema": {"type": "string"}},
+ "X-Upload-Run-ID": {"description": "Existing run identifier, when dispatch is unconfirmed", "schema": {"type": "string"}},
+ },
+ },
+}
async def _read_upload_bounded(file: UploadFile, max_size: int) -> bytes:
@@ -88,11 +102,48 @@ def _parse_project_uuid(raw: str) -> uuid.UUID:
)
+def _unconfirmed_dispatch(task_id: str, run_id: str) -> HTTPException:
+ """Keep the existing 503/string-detail contract and expose the polling ID.
+
+ The broker may have accepted the task. Do not tell a caller to submit a
+ second manual upload before checking the first one's status.
+ """
+ status_url = f"/api/v1/ingest/uploads/{task_id}"
+ return HTTPException(
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
+ detail=(
+ "Upload queue confirmation is unavailable; processing may still start. "
+ f"Check {status_url} before resubmitting."
+ ),
+ headers={
+ "Location": status_url,
+ "X-Upload-Task-ID": task_id,
+ "X-Upload-Run-ID": run_id,
+ },
+ )
+
+
+async def _discard_unpublished_upload(storage_key: str, task_id: str) -> None:
+ """Clean up only when bounded admission proves no publish was submitted."""
+ from app.db.storage import get_storage_provider
+ from app.services import upload_status
+
+ await upload_status.clear_pending_status(task_id)
+ try:
+ await get_storage_provider().delete_object(storage_key)
+ except Exception as exc: # noqa: BLE001 — cleanup must preserve the refusal
+ logger.warning(
+ "unpublished_upload_cleanup_failed", task_id=task_id,
+ error_type=type(exc).__name__,
+ )
+
+
@router.post(
"",
response_model=IngestResponse,
status_code=status.HTTP_202_ACCEPTED,
summary="Ingest test results (JSON batch)",
+ responses=_DISPATCH_RESPONSES,
)
async def ingest_batch(
payload: IngestPayload,
@@ -178,8 +229,11 @@ async def ingest_batch(
task_id, run_id=run_id, project_id=str(target_project_id),
state=upload_status.STATE_PENDING,
)
+ from app.worker.upload_dispatch import UploadPublisherBusy, publish_upload
+
try:
- ingest_uploaded_results.apply_async(
+ await publish_upload(
+ ingest_uploaded_results,
kwargs=dict(
run_id=run_id,
payload_storage_key=batch_storage_key,
@@ -187,18 +241,23 @@ async def ingest_batch(
),
task_id=task_id,
)
- except Exception as exc: # noqa: BLE001 — normalize broker errors for clients
- await upload_status.clear_pending_status(task_id)
- # Nothing will read the stored batch now (S-C-6): do not leave it behind.
- try:
- await get_storage_provider().delete_object(batch_storage_key)
- except Exception: # noqa: BLE001 — cleanup is best effort
- pass
- logger.error("batch_ingest_dispatch_failed", run_id=run_id, error=str(exc))
+ except UploadPublisherBusy as exc:
+ # The helper did not submit a call, so no late message can need these.
+ await _discard_unpublished_upload(batch_storage_key, task_id)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
- detail="Upload could not be queued",
+ detail="Upload publisher is busy; try again later.",
+ headers={"Retry-After": "1"},
) from exc
+ except Exception as exc: # noqa: BLE001 — publication may already have succeeded
+ # Keep both the payload and pending seed. A timeout cannot cancel the
+ # publisher thread, and even an immediate error can follow acceptance.
+ # Only the worker may advance this task's monotonic business status.
+ logger.warning(
+ "batch_ingest_dispatch_unconfirmed", run_id=run_id, task_id=task_id,
+ error_type=type(exc).__name__,
+ )
+ raise _unconfirmed_dispatch(task_id, run_id) from exc
logger.info(
"batch_ingest_accepted",
@@ -381,6 +440,7 @@ def _parse_form_commit_range(raw: str | None) -> tuple[object, bool]:
response_model=IngestResponse,
status_code=status.HTTP_202_ACCEPTED,
summary="Upload test result file (JUnit/TestNG XML, Allure/Cypress/Playwright JSON)",
+ responses=_DISPATCH_RESPONSES,
)
async def ingest_file(
file: UploadFile = File(...),
@@ -638,17 +698,25 @@ async def ingest_file(
# Sent only when true, so a task queued here still binds a worker that
# predates the field (the run_context rule above).
task_kwargs["commit_range_truncated"] = True
+ from app.worker.upload_dispatch import UploadPublisherBusy, publish_upload
+
try:
- ingest_uploaded_file.apply_async(kwargs=task_kwargs, task_id=task_id)
- except Exception as exc: # noqa: BLE001 — normalize broker errors for clients
- # Publish failures can be ambiguous. Delete only a record that is still
- # pending; an already-started worker's parsing/terminal status survives.
- await upload_status.clear_pending_status(task_id)
- logger.error("file_ingest_dispatch_failed", run_id=run_id, error=str(exc))
+ await publish_upload(ingest_uploaded_file, kwargs=task_kwargs, task_id=task_id)
+ except UploadPublisherBusy as exc:
+ await _discard_unpublished_upload(queued_storage_key, task_id)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
- detail="Upload could not be queued",
+ detail="Upload publisher is busy; try again later.",
+ headers={"Retry-After": "1"},
) from exc
+ except Exception as exc: # noqa: BLE001 — publication may already have succeeded
+ # Retain the original object and polling identity even if the worker
+ # has not started yet. A late accepted publish still needs both.
+ logger.warning(
+ "file_ingest_dispatch_unconfirmed", run_id=run_id, task_id=task_id,
+ error_type=type(exc).__name__,
+ )
+ raise _unconfirmed_dispatch(task_id, run_id) from exc
logger.info(
"file_ingest_accepted",
diff --git a/backend/app/services/agent_operational_metrics.py b/backend/app/services/agent_operational_metrics.py
index 1871b2e4d..e09be32fd 100644
--- a/backend/app/services/agent_operational_metrics.py
+++ b/backend/app/services/agent_operational_metrics.py
@@ -24,12 +24,14 @@ def _age_seconds(value: datetime | None, now: datetime) -> float:
return max(0.0, (now - value).total_seconds())
-async def refresh_agent_operational_metrics(*, now: datetime | None = None) -> None:
+async def refresh_agent_operational_metrics(*, now: datetime | None = None) -> bool:
"""Refresh durable agent state without ever failing the metrics scrape."""
from app.db.postgres import AsyncSessionLocal
from app.models.postgres import AgentPipelineRun, ReviewRequest
observed_at = now or datetime.now(timezone.utc)
+ db_ok = False
+ dlq_ok = False
try:
async with AsyncSessionLocal() as db:
oldest_run = (
@@ -58,6 +60,7 @@ async def refresh_agent_operational_metrics(*, now: datetime | None = None) -> N
pending_review_oldest_age_seconds.set(
_age_seconds(oldest_review, observed_at)
)
+ db_ok = True
except Exception as exc: # noqa: BLE001
logger.debug("agent_operational_db_metrics_failed", error=str(exc))
@@ -68,5 +71,7 @@ async def refresh_agent_operational_metrics(*, now: datetime | None = None) -> N
stream_depth = await get_stream_dlq_count()
if persist_depth is not None and stream_depth is not None:
agent_dlq_depth.set(float(persist_depth + stream_depth))
+ dlq_ok = True
except Exception as exc: # noqa: BLE001
logger.debug("agent_operational_dlq_metric_failed", error=str(exc))
+ return db_ok and dlq_ok
diff --git a/backend/app/services/compliance_signing.py b/backend/app/services/compliance_signing.py
index e92518b72..549f411ee 100644
--- a/backend/app/services/compliance_signing.py
+++ b/backend/app/services/compliance_signing.py
@@ -74,7 +74,7 @@ class SigningKey:
key_id: str
public_key_pem: str
- private_key: Ed25519PrivateKey = field(repr=False, compare=False)
+ private_key: Ed25519PrivateKey = field(repr=False, compare=False) # gitleaks:allow -- field/event identifier, not credential material
# ── Pure helpers (the CLI's offline verifier restates key_id_for / statement) ──
diff --git a/backend/app/services/downstream_operational_metrics.py b/backend/app/services/downstream_operational_metrics.py
new file mode 100644
index 000000000..a86f9f21c
--- /dev/null
+++ b/backend/app/services/downstream_operational_metrics.py
@@ -0,0 +1,82 @@
+"""SQL outbox outcomes, independent of broker depth and Celery SUCCESS."""
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from sqlalchemy import and_, case, func, select
+
+from app.core.metrics import (
+ downstream_outbox_entries,
+ downstream_outbox_oldest_age_seconds,
+ downstream_outbox_overdue_seconds,
+)
+
+STATUSES = ("waiting", "pending", "sending", "published", "processing", "completed", "failed")
+LEASE_STATUSES = ("sending", "published", "processing")
+
+
+def _age(value: datetime | None, now: datetime) -> float:
+ if value is None:
+ return 0.0
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=timezone.utc)
+ return max(0.0, (now - value).total_seconds())
+
+
+async def refresh_downstream_operational_metrics(*, now: datetime | None = None) -> bool:
+ """Publish one complete snapshot only after its grouped query succeeds.
+
+ next_attempt_at and lease_expires_at already encode the relay's actual
+ backoff/lease contract. No payload, run, project or task ID is a label.
+ Call through collect_bounded to enforce the scrape deadline/freshness.
+ """
+ from app.db.postgres import AsyncSessionLocal
+ from app.models.postgres import RunDownstreamOutbox
+ from app.services.run_downstream_outbox import _OPERATIONS
+
+ operations = tuple(sorted(_OPERATIONS)) + ("other",)
+ observed_at = now or datetime.now(timezone.utc)
+ due = case(
+ (
+ RunDownstreamOutbox.status.in_(("waiting", "pending")),
+ func.coalesce(RunDownstreamOutbox.next_attempt_at, RunDownstreamOutbox.created_at),
+ ),
+ (RunDownstreamOutbox.status.in_(LEASE_STATUSES), RunDownstreamOutbox.lease_expires_at),
+ else_=None,
+ )
+ missing_lease = and_(
+ RunDownstreamOutbox.status.in_(LEASE_STATUSES),
+ RunDownstreamOutbox.lease_expires_at.is_(None),
+ )
+ statement = select(
+ RunDownstreamOutbox.operation,
+ RunDownstreamOutbox.status,
+ func.count().label("count"),
+ func.min(RunDownstreamOutbox.created_at).label("oldest"),
+ func.min(due).label("due"),
+ func.sum(case((missing_lease, 1), else_=0)).label("missing_lease_count"),
+ ).group_by(RunDownstreamOutbox.operation, RunDownstreamOutbox.status)
+ async with AsyncSessionLocal() as db:
+ rows = (await db.execute(statement)).all()
+
+ snapshot: dict[tuple[str, str], tuple[int, float, float]] = {}
+ for operation, status, count, oldest, deadline, missing_lease_count in rows:
+ if status not in STATUSES:
+ raise ValueError("unknown downstream lifecycle state")
+ if missing_lease_count:
+ # The relay cannot recover a lease state with a NULL expiry.
+ # Do not turn malformed/legacy state into a fresh healthy zero.
+ raise ValueError("downstream lease state has no lease deadline")
+ operation = operation if operation in _OPERATIONS else "other"
+ key = (operation, status)
+ previous = snapshot.get(key, (0, 0.0, 0.0))
+ age = 0.0 if status == "completed" else _age(oldest, observed_at)
+ overdue = 0.0 if status in {"completed", "failed"} else _age(deadline, observed_at)
+ snapshot[key] = (previous[0] + count, max(previous[1], age), max(previous[2], overdue))
+ for operation in operations:
+ for status in STATUSES:
+ count, age, overdue = snapshot.get((operation, status), (0, 0.0, 0.0))
+ downstream_outbox_entries.labels(operation=operation, status=status).set(count)
+ downstream_outbox_oldest_age_seconds.labels(operation=operation, status=status).set(age)
+ downstream_outbox_overdue_seconds.labels(operation=operation, status=status).set(overdue)
+ return True
diff --git a/backend/app/services/metric_collection.py b/backend/app/services/metric_collection.py
new file mode 100644
index 000000000..1497b6e1b
--- /dev/null
+++ b/backend/app/services/metric_collection.py
@@ -0,0 +1,98 @@
+"""Finite scrape work with explicit failed/stale observation state."""
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Callable, Coroutine
+from dataclasses import dataclass
+from typing import Any
+
+import structlog
+
+from app.core.metrics import (
+ metric_collection_errors_total,
+ metric_collection_last_success,
+ metric_collection_success,
+)
+
+logger = structlog.get_logger(__name__)
+COLLECTION_TIMEOUT_SECONDS = 1.0
+COLLECTORS = ("queues", "agents", "downstream")
+
+
+@dataclass
+class _Attempt:
+ task: asyncio.Task[bool]
+ deadline: float
+ abandoned: bool = False
+ recorded: bool = False
+ success: bool = False
+
+
+_IN_FLIGHT: dict[str, _Attempt] = {}
+for _collector in COLLECTORS:
+ metric_collection_success.labels(collector=_collector)
+ metric_collection_last_success.labels(collector=_collector)
+ metric_collection_errors_total.labels(collector=_collector)
+
+
+async def collect_bounded(
+ collector: str, refresh: Callable[[], Coroutine[Any, Any, bool]],
+) -> bool:
+ """Keep exposition available; failed reads never advance freshness."""
+ if collector not in COLLECTORS:
+ raise ValueError("unknown metric collector")
+ # wait_for waits for cancellation cleanup, which can itself block on a
+ # failed database connection. Bound the foreground wait instead. Share
+ # healthy work across overlapping scrapers, and retain timed-out work
+ # until it really ends so abandoned reads cannot pile up.
+ loop = asyncio.get_running_loop()
+ attempt = _IN_FLIGHT.get(collector)
+ if attempt is None:
+ attempt = _Attempt(asyncio.create_task(refresh()), loop.time() + COLLECTION_TIMEOUT_SECONDS)
+ _IN_FLIGHT[collector] = attempt
+
+ def record(success: bool, error_type: str | None = None) -> None:
+ if attempt.recorded:
+ return
+ attempt.recorded = True
+ attempt.success = success
+ metric_collection_success.labels(collector=collector).set(int(success))
+ if success:
+ metric_collection_last_success.labels(collector=collector).set(time.time())
+ else:
+ metric_collection_errors_total.labels(collector=collector).inc()
+ logger.warning(
+ "metric_collection_failed", collector=collector,
+ error_type=error_type or "IncompleteCollection",
+ )
+
+ def expire() -> None:
+ if not attempt.task.done() and not attempt.abandoned:
+ attempt.abandoned = True
+ record(False, "TimeoutError")
+ attempt.task.cancel()
+
+ deadline_handle = loop.call_at(attempt.deadline, expire)
+
+ def completed(task: asyncio.Task[bool]) -> None:
+ deadline_handle.cancel()
+ error = None if task.cancelled() else task.exception()
+ record(
+ not attempt.abandoned and not task.cancelled() and error is None and task.result() is True,
+ type(error).__name__ if error else None,
+ )
+ if _IN_FLIGHT.get(collector) is attempt:
+ _IN_FLIGHT.pop(collector)
+
+ attempt.task.add_done_callback(completed)
+ if attempt.abandoned:
+ return False
+ # Cancelling one HTTP request does not cancel a shared healthy read. Its
+ # independent deadline still cancels it even if all callers disconnect.
+ await asyncio.wait({attempt.task}, timeout=max(0, attempt.deadline - loop.time()))
+ if not attempt.recorded:
+ # Timer and task callbacks may be queued for the next event-loop turn.
+ # Let those callbacks publish the single authoritative outcome.
+ await asyncio.sleep(0)
+ return attempt.recorded and attempt.success
diff --git a/backend/app/services/password_reset_service.py b/backend/app/services/password_reset_service.py
index b9137c0fe..8356e90c9 100644
--- a/backend/app/services/password_reset_service.py
+++ b/backend/app/services/password_reset_service.py
@@ -117,7 +117,7 @@ async def stage_forgot_token(db: AsyncSession, email: str, request_ip: Optional[
logger.info("forgot_password_skipped: reason=smtp_off")
return None
if not await _within_mailbox_limit(email):
- logger.info("forgot_password_skipped: reason=rate_limited")
+ logger.info("forgot_password_skipped: reason=rate_limited") # gitleaks:allow -- field/event identifier, not credential material
return None
user = (
await db.execute(select(User).where(func.lower(User.email) == email.lower()))
diff --git a/backend/app/worker/celery_app.py b/backend/app/worker/celery_app.py
index d9a7b2a9e..79a312b9f 100644
--- a/backend/app/worker/celery_app.py
+++ b/backend/app/worker/celery_app.py
@@ -1,6 +1,8 @@
"""Celery application configuration."""
from datetime import timedelta
from pathlib import Path
+import re
+from collections.abc import Mapping
from celery import Celery, Task
from celery.signals import (
@@ -780,6 +782,50 @@ def _reset_db_pool_after_fork(**_kwargs: object) -> None:
_TASK_STARTED_AT: dict[str, float] = {}
+def _task_log_context(task=None, task_id=None) -> dict[str, object]:
+ """Canonical task identity and allowlisted diagnostic correlation only.
+
+ Headers and task arguments are not an authority boundary. In particular,
+ never copy arbitrary broker headers or payload fields into log context.
+ """
+ request = getattr(task, "request", None)
+ retries = getattr(request, "retries", 0)
+ context: dict[str, object] = {
+ "celery_task_id": task_id or getattr(request, "id", None) or "unknown",
+ "celery_task_name": getattr(task, "name", None) or "unknown",
+ "celery_retry": retries if isinstance(retries, int) and retries >= 0 else 0,
+ }
+ headers = getattr(request, "headers", None)
+ if not isinstance(headers, Mapping):
+ headers = {}
+ candidates = {
+ "request_id": (
+ headers.get("request_id"), headers.get("x-request-id"), headers.get("X-Request-ID"),
+ ),
+ "correlation_id": (headers.get("correlation_id"), getattr(request, "correlation_id", None)),
+ }
+ for field, values in candidates.items():
+ for value in values:
+ if isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", value):
+ context[field] = value
+ break
+ return context
+
+
+@task_prerun.connect
+def _bind_task_log_context(task_id=None, task=None, **_kwargs: object) -> None:
+ """Start every execution with fresh context, including retries/reused children."""
+ from structlog.contextvars import bind_contextvars, clear_contextvars, get_contextvars
+
+ request = getattr(task, "request", None)
+ if getattr(request, "is_eager", False):
+ # Eager tasks run inside the caller's request/context rather than a
+ # worker child. Restore that caller after this execution completes.
+ request._testlookup_parent_log_context = get_contextvars()
+ clear_contextvars()
+ bind_contextvars(**_task_log_context(task=task, task_id=task_id))
+
+
@celeryd_init.connect
def _prepare_worker_metrics_directory(**_kwargs: object) -> None:
"""Remove metrics from an earlier worker parent before it forks children.
@@ -871,8 +917,21 @@ def _record_task_outcome(task_id=None, task=None, state=None, **_kwargs: object)
pass
+@task_postrun.connect
+def _clear_task_log_context(task=None, **_kwargs: object) -> None:
+ """Postrun runs for success, failure and retry; none may leak into the next task."""
+ from structlog.contextvars import bind_contextvars, clear_contextvars
+
+ clear_contextvars()
+ request = getattr(task, "request", None)
+ parent_context = getattr(request, "_testlookup_parent_log_context", None)
+ if getattr(request, "is_eager", False) and isinstance(parent_context, dict):
+ del request._testlookup_parent_log_context
+ bind_contextvars(**parent_context)
+
+
#: Readiness sentinel. Written once the worker has booted and connected to the
-#: broker; removed on shutdown.
+#: broker; removed before replacement startup and on shutdown.
READY_SENTINEL = "/tmp/celery-worker-ready"
@@ -905,9 +964,14 @@ def _mark_worker_ready(**_kwargs: object) -> None:
pass
+@celeryd_init.connect
@worker_shutdown.connect
def _clear_worker_ready(**_kwargs: object) -> None:
- """Drop the sentinel so a draining worker stops reporting Ready."""
+ """A previous worker's marker must not make its replacement Ready.
+
+ SIGKILL/OOM skips worker_shutdown, and a pod's emptyDir survives a
+ container restart. celeryd_init clears it before this consumer starts.
+ """
import os
try:
diff --git a/backend/app/worker/tasks.py b/backend/app/worker/tasks.py
index 4f06ff2c5..6fb158cfa 100644
--- a/backend/app/worker/tasks.py
+++ b/backend/app/worker/tasks.py
@@ -215,14 +215,13 @@ def __call__(self, *args, **kwargs):
def _bind_task_context(task, **extra):
- """Bind structured logging context for a Celery task (observability improvement)."""
+ """Enrich the current execution without discarding its canonical correlation."""
+ from app.worker.celery_app import _task_log_context
+
+ context = dict(extra)
+ context.update(_task_log_context(task=task))
clear_contextvars()
- bind_contextvars(
- celery_task_id=task.request.id,
- celery_task_name=task.name,
- celery_retry=task.request.retries,
- **extra,
- )
+ bind_contextvars(**context)
def _exponential_backoff(attempt: int, base: int = 30, cap: int = 600) -> int:
diff --git a/backend/app/worker/upload_dispatch.py b/backend/app/worker/upload_dispatch.py
new file mode 100644
index 000000000..da4d7266f
--- /dev/null
+++ b/backend/app/worker/upload_dispatch.py
@@ -0,0 +1,72 @@
+"""Bound synchronous upload publication without discarding ambiguous work.
+
+The upload status endpoint, rather than Celery's result backend, reports the
+business outcome. A publish error or request timeout cannot establish whether
+the broker accepted the message. Callers must retain its object and status
+seed, including when a timed-out publication finishes later.
+
+This is not a durable dispatch outbox: API exit can interrupt publication and
+unconfirmed uploads still need reconciliation. The finite executor and slots
+bound outstanding publications even when broker calls outlive their callers.
+"""
+from __future__ import annotations
+
+import asyncio
+import contextvars
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from functools import partial
+from typing import Any
+
+
+UPLOAD_PUBLISH_TIMEOUT_SECONDS = 3.0
+_MAX_PENDING_PUBLISHES = 4
+_PUBLISH_EXECUTOR = ThreadPoolExecutor(
+ max_workers=_MAX_PENDING_PUBLISHES, thread_name_prefix="upload-publish"
+)
+_PUBLISH_SLOTS = threading.BoundedSemaphore(_MAX_PENDING_PUBLISHES)
+
+
+class UploadPublisherBusy(RuntimeError):
+ """All bounded publisher slots are still occupied; no call was submitted."""
+
+
+def _consume_result(future: asyncio.Future[Any]) -> None:
+ # A shielded publication can fail after its HTTP caller has timed out or
+ # disconnected. Retrieve that exception without an unhandled-future warning;
+ # the caller has already reported the unconfirmed dispatch with its task ID.
+ if not future.cancelled():
+ future.exception()
+
+
+async def publish_upload(
+ task: Any, *, kwargs: dict[str, Any], task_id: str
+) -> None:
+ """Wait a bounded time for publication, leaving late work running safely.
+
+ No automatic publish retry is requested: an error can follow broker
+ acceptance. Avoid the result-backend subscription entirely; upload workers
+ write the dedicated, monotonic status record that clients already poll.
+ A slot is released only when the real synchronous call ends, never when
+ the request's wait expires, so repeated timeouts cannot grow a thread queue.
+ """
+ if not _PUBLISH_SLOTS.acquire(blocking=False):
+ raise UploadPublisherBusy("upload publisher is busy")
+ try:
+ publish = partial(
+ task.apply_async,
+ kwargs=kwargs,
+ task_id=task_id,
+ ignore_result=True,
+ retry=False,
+ )
+ future = _PUBLISH_EXECUTOR.submit(contextvars.copy_context().run, publish)
+ except BaseException:
+ _PUBLISH_SLOTS.release()
+ raise
+ future.add_done_callback(lambda _finished: _PUBLISH_SLOTS.release())
+ pending = asyncio.wrap_future(future)
+ pending.add_done_callback(_consume_result)
+ await asyncio.wait_for(
+ asyncio.shield(pending), timeout=UPLOAD_PUBLISH_TIMEOUT_SECONDS
+ )
diff --git a/backend/tests/integration/test_compose_queue_delivery_redis.py b/backend/tests/integration/test_compose_queue_delivery_redis.py
index 33e8b4d22..4fc31720f 100644
--- a/backend/tests/integration/test_compose_queue_delivery_redis.py
+++ b/backend/tests/integration/test_compose_queue_delivery_redis.py
@@ -81,7 +81,7 @@ def _write_override(
CELERY_RESULT_BACKEND: redis://redis:6379/1
REDIS_URL: redis://redis:6379/0
APP_SECRET_KEY: h07-compose-secret
- JWT_SECRET_KEY: h07-compose-jwt
+ JWT_SECRET_KEY: h07-compose-jwt # gitleaks:allow -- synthetic test credential, never production authority
AI_OFFLINE_MODE: "true"
worker-children:
image: {image}
@@ -95,7 +95,7 @@ def _write_override(
CELERY_RESULT_BACKEND: redis://redis:6379/1
REDIS_URL: redis://redis:6379/0
APP_SECRET_KEY: h07-compose-secret
- JWT_SECRET_KEY: h07-compose-jwt
+ JWT_SECRET_KEY: h07-compose-jwt # gitleaks:allow -- synthetic test credential, never production authority
AI_OFFLINE_MODE: "true"
"""
for service in sorted(env_file_services - {"worker", "worker-children"}):
@@ -152,7 +152,7 @@ def test_supported_compose_topology_delivers_one_task_per_queue(
"MINIO_SECRET_KEY": "h07-compose-minio-secret",
"FLOWER_PASSWORD": "h07-compose-flower",
"APP_SECRET_KEY": "h07-compose-secret",
- "JWT_SECRET_KEY": "h07-compose-jwt",
+ "JWT_SECRET_KEY": "h07-compose-jwt", # gitleaks:allow -- synthetic test credential, never production authority
"TESTLOOKUP_IMAGE": "testlookup-h07",
"TESTLOOKUP_VERSION": source_sha[:12],
"TESTLOOKUP_REGISTRY": "testlookup-h07",
diff --git a/backend/tests/integration/test_http_exchanges_postgres_mongo.py b/backend/tests/integration/test_http_exchanges_postgres_mongo.py
index 2357ac70a..a2236a470 100644
--- a/backend/tests/integration/test_http_exchanges_postgres_mongo.py
+++ b/backend/tests/integration/test_http_exchanges_postgres_mongo.py
@@ -55,7 +55,7 @@ def _dsn() -> str:
def _samples() -> dict[str, str]:
"""The §2.1 P-2 REAL-LOOKING samples (non-hex, never a real secret), built here."""
return {
- "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9.c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x",
+ "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9.c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x", # gitleaks:allow -- synthetic test credential, never production authority
"basic": "dzIzZDpzYW1wbGUtcGFzcw==",
"cookie": "w23dSampleSessionValue",
"csrf": "w23dcsrfSample",
diff --git a/backend/tests/integration/test_ingest_admission_http.py b/backend/tests/integration/test_ingest_admission_http.py
index 61fc7c7fa..fbfd12c5a 100644
--- a/backend/tests/integration/test_ingest_admission_http.py
+++ b/backend/tests/integration/test_ingest_admission_http.py
@@ -73,11 +73,11 @@ async def delete_object(self, key, bucket=None):
async def get_object_content(self, key, bucket=None):
return self.last[1]
- def _batch_apply_async(*, kwargs, task_id):
+ def _batch_apply_async(*, kwargs, task_id, **_options):
queued.append("batch")
return SimpleNamespace(id=task_id)
- def _apply_async(*, kwargs, task_id):
+ def _apply_async(*, kwargs, task_id, **_options):
queued.append("file")
return SimpleNamespace(id=task_id)
diff --git a/backend/tests/integration/test_ingest_api.py b/backend/tests/integration/test_ingest_api.py
index d17752911..0e2bb6ea3 100644
--- a/backend/tests/integration/test_ingest_api.py
+++ b/backend/tests/integration/test_ingest_api.py
@@ -28,7 +28,7 @@ def mock_celery_dispatch():
Stub the two Celery entry points the ingest router calls so tests don't
need a running broker. Returns the mocks so callers can assert on them.
"""
- def _queued(*, kwargs, task_id):
+ def _queued(*, kwargs, task_id, **_options):
"""Stand-in for ``apply_async``: the router reads only ``.id``."""
return type("T", (), {"id": task_id})()
@@ -231,7 +231,7 @@ def _finish_immediately(task_id: str):
task = MagicMock()
task.delay.side_effect = lambda **_kwargs: _finish_immediately("legacy-task")
task.apply_async.side_effect = (
- lambda *, kwargs, task_id: _finish_immediately(task_id)
+ lambda *, kwargs, task_id, **_options: _finish_immediately(task_id)
)
with (
@@ -252,7 +252,7 @@ def _finish_immediately(task_id: str):
assert task.apply_async.call_args.kwargs["task_id"] == resp.json()["task_id"]
-async def test_ingest_file_dispatch_failure_clears_pending_status(client, auth_as):
+async def test_ingest_file_unconfirmed_dispatch_preserves_pending_status(client, auth_as):
project_id = uuid.uuid4()
auth_as(accessible_projects={project_id})
events: list[tuple[str, str]] = []
@@ -283,9 +283,9 @@ async def _clear_pending(task_id):
)
assert resp.status_code == 503
- assert resp.json()["detail"] == "Upload could not be queued"
- assert events[0] == ("set", "pending")
- assert events[1][0] == "clear"
+ assert "processing may still start" in resp.json()["detail"]
+ assert resp.headers["Location"] == f'/api/v1/ingest/uploads/{resp.headers["X-Upload-Task-ID"]}'
+ assert events == [("set", "pending")], "an unconfirmed publish must keep its polling identity"
async def test_manual_upload_mints_fresh_run_when_build_label_exists(
@@ -422,7 +422,7 @@ async def test_ingest_file_zip_routes_to_archive(client, auth_as, requested_form
captured: dict = {}
- def _apply_async(*, kwargs, task_id):
+ def _apply_async(*, kwargs, task_id, **_options):
captured.update(kwargs)
return type("T", (), {"id": task_id})()
@@ -456,7 +456,7 @@ async def test_ingest_file_run_ai_flag_forwarded(client, auth_as):
captured: dict = {}
file_task = AsyncMock()
file_task.apply_async = (
- lambda *, kwargs, task_id: captured.update(kwargs)
+ lambda *, kwargs, task_id, **_options: captured.update(kwargs)
or type("T", (), {"id": task_id})()
)
with patch("app.worker.tasks.ingest_uploaded_file", file_task), \
@@ -508,7 +508,7 @@ async def test_ingest_file_run_ai_defaults_true(client, auth_as):
captured: dict = {}
file_task = AsyncMock()
file_task.apply_async = (
- lambda *, kwargs, task_id: captured.update(kwargs)
+ lambda *, kwargs, task_id, **_options: captured.update(kwargs)
or type("T", (), {"id": task_id})()
)
with patch("app.worker.tasks.ingest_uploaded_file", file_task), \
diff --git a/backend/tests/integration/test_shadow_pairs_postgres.py b/backend/tests/integration/test_shadow_pairs_postgres.py
index 68a69efb9..56d186f6d 100644
--- a/backend/tests/integration/test_shadow_pairs_postgres.py
+++ b/backend/tests/integration/test_shadow_pairs_postgres.py
@@ -193,7 +193,7 @@ async def test_the_list_pages_counts_and_resolves_sources_inside_the_project(env
async with sessions() as db:
stored = await store_shadow_pair(
db, project_id=w["P"], agent_id=ROOT, sample_key=f"root_cause:{w['tc3']}", incumbent_tier="llm",
- candidate_tier="slm", incumbent_output={"root_cause_summary": "Use token=Gh7Jk8Lm9Np0 to log in"},
+ candidate_tier="slm", incumbent_output={"root_cause_summary": "Use token=Gh7Jk8Lm9Np0 to log in"}, # gitleaks:allow -- synthetic test credential, never production authority
candidate_output={"failure_category": "TEST_DATA"}, incumbent_tokens=5, candidate_tokens=5,
daily_token_budget=10_000,
)
diff --git a/backend/tests/regression/test_alert_rules_are_deployable.py b/backend/tests/regression/test_alert_rules_are_deployable.py
index ee24bdeaa..abae86937 100644
--- a/backend/tests/regression/test_alert_rules_are_deployable.py
+++ b/backend/tests/regression/test_alert_rules_are_deployable.py
@@ -10,9 +10,9 @@
created at import with value 0.
And there was no PrometheusRule under ``k8s/``, so on a cluster nothing fired
-at all. promtool is not available offline, so the rules are validated here:
-parsed, their metric names checked against the declarations, and the k8s
-resource compared with the one source file.
+at all. These offline checks validate declarations and generated-rule parity.
+The existing backend CI job also runs semantic fixtures with checksum-pinned
+promtool matching the reference monitoring runtime.
"""
from __future__ import annotations
@@ -139,3 +139,25 @@ def test_the_rule_is_opt_in_not_in_base() -> None:
assert kustomization["resources"] == ["prometheusrule.yaml", "podmonitors.yaml"]
base = yaml.safe_load((REPO_ROOT / "k8s" / "base" / "kustomization.yaml").read_text(encoding="utf-8"))
assert not any("monitoring" in str(r) or "prometheusrule" in str(r) for r in base["resources"])
+
+
+def test_semantic_fixtures_execute_in_the_existing_backend_ci_job() -> None:
+ """A fixture outside the runtime glob must be executed, not merely committed."""
+ workflow = yaml.safe_load((REPO_ROOT / ".github/workflows/ci.yml").read_text(encoding="utf-8"))
+ job = workflow["jobs"]["backend-test"]
+ step = next(s for s in job["steps"] if s.get("name") == "Verify alert semantics with checksum-pinned promtool")
+ assert not step.get("continue-on-error") and not step.get("if")
+ assert step["working-directory"] == "infra/monitoring/tests"
+ compose = yaml.safe_load((REPO_ROOT / "docker-compose.monitoring.yml").read_text(encoding="utf-8"))
+ runtime_version = compose["services"]["prometheus"]["image"].rsplit(":", 1)[1].lstrip("v")
+ assert step["env"]["PROMETHEUS_VERSION"] == runtime_version
+ assert re.fullmatch(r"[0-9a-f]{64}", step["env"]["PROMETHEUS_ARCHIVE_SHA256"])
+ commands = step["run"]
+ assert commands.index("sha256sum --check --strict") < commands.index("tar -xzf")
+ assert '"$tool" check rules ../prometheus-rules/testlookup-alerts.yml' in commands
+ assert '"$tool" test rules operational-alerts.yml' in commands
+ fixture = REPO_ROOT / step["working-directory"] / "operational-alerts.yml"
+ assert not fixture.is_relative_to(ALERTS.parent), "fixture would be loaded as a production rule file"
+ data = yaml.safe_load(fixture.read_text(encoding="utf-8"))
+ assert data["tests"] and len(data["rule_files"]) == 1
+ assert (fixture.parent / data["rule_files"][0]).resolve() == ALERTS.resolve()
diff --git a/backend/tests/regression/test_ci_run_url_is_http_only.py b/backend/tests/regression/test_ci_run_url_is_http_only.py
index c4d49f125..54cadf1f2 100644
--- a/backend/tests/regression/test_ci_run_url_is_http_only.py
+++ b/backend/tests/regression/test_ci_run_url_is_http_only.py
@@ -105,7 +105,7 @@ async def _open(*_a, **_kw):
storage.put_object = AsyncMock()
storage.delete_object = AsyncMock()
task = MagicMock()
- task.apply_async = lambda *, kwargs, task_id: queued.append(kwargs) or SimpleNamespace(id=task_id)
+ task.apply_async = lambda *, kwargs, task_id, **_options: queued.append(kwargs) or SimpleNamespace(id=task_id)
async def _user():
return user
diff --git a/backend/tests/regression/test_core_error_correlation.py b/backend/tests/regression/test_core_error_correlation.py
new file mode 100644
index 000000000..a5e1e11a2
--- /dev/null
+++ b/backend/tests/regression/test_core_error_correlation.py
@@ -0,0 +1,92 @@
+"""Unexpected errors retain diagnostics without changing route body contracts."""
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi import FastAPI, HTTPException
+from fastapi.testclient import TestClient
+from starlette.requests import Request
+from structlog.contextvars import get_contextvars
+
+from app.core import analytics_errors
+from app.middleware.telemetry import REQUEST_ID_CTX, TelemetryMiddleware
+
+
+def _app():
+ app = FastAPI()
+ app.add_middleware(TelemetryMiddleware)
+ app.add_exception_handler(Exception, analytics_errors.unhandled_exception_handler)
+
+ async def fail():
+ raise RuntimeError("fake-internal-error")
+
+ app.add_api_route("/core", fail)
+ app.add_api_route("/api/v1/scim/Users", fail)
+
+ @app.get("/analytics")
+ @analytics_errors.analytics_error_contract
+ async def analytics():
+ return await fail()
+
+ @app.get("/healthy")
+ async def healthy():
+ return {"ok": True}
+
+ @app.get("/refused")
+ async def refused():
+ raise HTTPException(403, "Access denied")
+
+ return app
+
+
+@pytest.mark.parametrize("path", ["/core", "/api/v1/scim/Users", "/analytics"])
+def test_unexpected_error_has_one_correlated_log_and_preserves_body(path, monkeypatch):
+ logger = MagicMock()
+ monkeypatch.setattr(analytics_errors, "logger", logger)
+ client = TestClient(_app(), raise_server_exceptions=False)
+ response = client.get(path, headers={"X-Request-ID": "review-request-42"})
+ assert response.status_code == 500
+ assert response.headers["X-Request-ID"] == "review-request-42"
+ assert "fake-internal-error" not in response.text
+ if path == "/analytics":
+ assert response.json()["request_id"] == "review-request-42"
+ event = "analytics_unhandled_error"
+ else:
+ assert response.text == "Internal Server Error"
+ event = "http_unhandled_error"
+ logger.error.assert_called_once()
+ assert logger.error.call_args.args == (event,)
+ assert logger.error.call_args.kwargs["request_id"] == "review-request-42"
+ assert logger.error.call_args.kwargs["status_code"] == 500
+ assert isinstance(logger.error.call_args.kwargs["exc_info"], RuntimeError)
+ assert REQUEST_ID_CTX.get() == ""
+ assert not get_contextvars()
+
+
+def test_healthy_and_expected_refusal_keep_contract_and_do_not_log_exceptions(monkeypatch):
+ logger = MagicMock()
+ monkeypatch.setattr(analytics_errors, "logger", logger)
+ client = TestClient(_app(), raise_server_exceptions=False)
+ assert client.get("/core").status_code == 500
+ logger.reset_mock()
+ healthy = client.get("/healthy", headers={"X-Request-ID": "next-request"})
+ refused = client.get("/refused", headers={"X-Request-ID": "refused-request"})
+ assert healthy.json() == {"ok": True}
+ assert healthy.headers["X-Request-ID"] == "next-request"
+ assert refused.json() == {"detail": "Access denied"}
+ assert refused.headers["X-Request-ID"] == "refused-request"
+ logger.error.assert_not_called()
+
+
+@pytest.mark.asyncio
+async def test_error_before_routing_never_logs_shared_report_path_credential(monkeypatch):
+ logger = MagicMock()
+ monkeypatch.setattr(analytics_errors, "logger", logger)
+ request = Request({
+ "type": "http", "method": "GET", "headers": [],
+ "path": "/api/v1/shared/reports/fake-private-report-token",
+ "query_string": b"", "scheme": "https",
+ })
+ response = await analytics_errors.unhandled_exception_handler(request, RuntimeError("fake-error"))
+ assert response.status_code == 500
+ assert "fake-private-report-token" not in logger.error.call_args.kwargs["path"]
+ assert response.headers["X-Request-ID"]
diff --git a/backend/tests/regression/test_demo_compose.py b/backend/tests/regression/test_demo_compose.py
index ad33d3835..5cefdc8e2 100644
--- a/backend/tests/regression/test_demo_compose.py
+++ b/backend/tests/regression/test_demo_compose.py
@@ -257,7 +257,7 @@ def test_a_key_missing_from_env_reads_as_empty(tmp_path):
assert "missing=[] present=[yes]" in result.stdout
-FAKE_TOKEN = "eyJhIjoiZGVtby10ZXN0In0" + "Q" * 40
+FAKE_TOKEN = "eyJhIjoiZGVtby10ZXN0In0" + "Q" * 40 # gitleaks:allow -- synthetic test credential, never production authority
@needs_bash
diff --git a/backend/tests/regression/test_json_batch_lifecycle.py b/backend/tests/regression/test_json_batch_lifecycle.py
index 9f7dfc03c..01d55d82a 100644
--- a/backend/tests/regression/test_json_batch_lifecycle.py
+++ b/backend/tests/regression/test_json_batch_lifecycle.py
@@ -231,15 +231,17 @@ def _run():
assert published["kwargs"]["payload_storage_key"] in world.storage.deleted
-async def test_a_broker_failure_is_a_503_and_leaves_nothing_behind(world, monkeypatch):
+async def test_an_unconfirmed_publish_is_a_503_with_a_retained_payload_and_poll_id(world, monkeypatch):
def _broken(*_a, **_k):
raise ConnectionError("broker down")
monkeypatch.setattr(tasks.ingest_uploaded_results, "apply_async", _broken)
resp = await _post("/api/v1/ingest", json=_batch(world.project_id))
assert resp.status_code == 503, resp.text
- assert world.storage.objects == {}, "the stored batch must not outlive a failed publish"
- assert world.store == {}, "the pending seed must not outlive a failed publish"
+ assert len(world.storage.objects) == 1, "an accepted message may still need its batch"
+ task_id = resp.headers["X-Upload-Task-ID"]
+ assert _status(world, task_id)["state"] == "pending"
+ assert resp.headers["Location"] == f"/api/v1/ingest/uploads/{task_id}"
# ── D-05 / S-C-6: terminal refusals in the worker ───────────────────────────
diff --git a/backend/tests/regression/test_jwt_is_pyjwt_not_jose.py b/backend/tests/regression/test_jwt_is_pyjwt_not_jose.py
index 04b76ce59..7f60e752e 100644
--- a/backend/tests/regression/test_jwt_is_pyjwt_not_jose.py
+++ b/backend/tests/regression/test_jwt_is_pyjwt_not_jose.py
@@ -54,7 +54,7 @@
# Minted by python-jose 3.5.0 with this secret (2026-10-12), exp 2099-01-01:
# jwt.encode({"sub": SUB, "iat": <2026-10-11T12:00:00.123456Z as a float>,
# "exp": datetime(2099, 1, 1), "type": "access", "jti": ...}, ...)
-JOSE_SECRET = "jose-era-test-secret-0123456789abcdef"
+JOSE_SECRET = "jose-era-test-secret-0123456789abcdef" # gitleaks:allow -- synthetic test credential, never production authority
JOSE_SUB = "7b0c6a2e-4f3d-4a59-9d6e-0d5b8f1a2c33"
JOSE_ACCESS = (
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9."
@@ -73,7 +73,7 @@
@pytest.fixture(autouse=True)
def _hs256(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(settings, "JWT_SECRET_KEY", "pyjwt-regression-secret-0123456789abcdef")
+ monkeypatch.setattr(settings, "JWT_SECRET_KEY", "pyjwt-regression-secret-0123456789abcdef") # gitleaks:allow -- synthetic test credential, never production authority
monkeypatch.setattr(settings, "JWT_ALGORITHM", "HS256")
diff --git a/backend/tests/regression/test_live_ingestion_sanitization.py b/backend/tests/regression/test_live_ingestion_sanitization.py
index bf653edfc..c3d99bdb6 100644
--- a/backend/tests/regression/test_live_ingestion_sanitization.py
+++ b/backend/tests/regression/test_live_ingestion_sanitization.py
@@ -15,7 +15,7 @@
RAW_ERROR = (
"Auth failed for admin@corp.example with password=Admin123! "
- "and api_key=sk_live_abcdefghijklmnop"
+ "and api_key=sk_live_abcdefghijklmnop" # gitleaks:allow -- synthetic test credential, never production authority
)
RAW_STACK = (
"Authorization: Bearer abcdefghijklmnopqrstuvwxyz0123456789\n"
@@ -39,7 +39,7 @@ def _assert_no_raw_canaries(payload: object) -> None:
for secret in (
"admin@corp.example",
"Admin123!",
- "sk_live_abcdefghijklmnop",
+ "sk_live_abcdefghijklmnop", # gitleaks:allow -- synthetic test credential, never production authority
"abcdefghijklmnopqrstuvwxyz0123456789",
"192.168.50.10",
"nested@example.com",
diff --git a/backend/tests/regression/test_operational_metric_collection.py b/backend/tests/regression/test_operational_metric_collection.py
new file mode 100644
index 000000000..3c6a214bd
--- /dev/null
+++ b/backend/tests/regression/test_operational_metric_collection.py
@@ -0,0 +1,305 @@
+"""Freshness and SQL business outcomes remain observable during dependency failure."""
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+import asyncio
+
+import pytest
+import pytest_asyncio
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.core import metrics
+from app.services import metric_collection as collection
+from app.services.downstream_operational_metrics import refresh_downstream_operational_metrics
+
+NOW = datetime(2026, 11, 26, 12, tzinfo=timezone.utc)
+
+
+@pytest_asyncio.fixture
+async def outbox_db(monkeypatch):
+ from app.db import postgres
+
+ engine = create_async_engine("sqlite+aiosqlite://")
+ async with engine.begin() as connection:
+ await connection.execute(text(
+ "CREATE TABLE run_downstream_outbox (operation VARCHAR(60), status VARCHAR(20), "
+ "created_at DATETIME, next_attempt_at DATETIME, lease_expires_at DATETIME)"
+ ))
+ monkeypatch.setattr(postgres, "AsyncSessionLocal", async_sessionmaker(engine))
+ yield engine
+ await engine.dispose()
+
+
+async def _insert(engine, operation, status, created, due=None, *, lease=None):
+ async with engine.begin() as connection:
+ await connection.execute(text(
+ "INSERT INTO run_downstream_outbox VALUES (:operation, :status, :created, :due, :lease)"
+ ), {"operation": operation, "status": status, "created": created.isoformat(),
+ "due": due.isoformat() if due else None,
+ "lease": lease.isoformat() if lease else None})
+
+
+@pytest.mark.asyncio
+async def test_terminal_sql_failures_are_visible_with_no_pending_broker_work(outbox_db):
+ for _ in range(2):
+ await _insert(outbox_db, "agent_pipeline", "failed", NOW - timedelta(days=3))
+ await _insert(outbox_db, "agent_pipeline", "completed", NOW - timedelta(days=4))
+ await refresh_downstream_operational_metrics(now=NOW)
+ values = metrics.downstream_outbox_entries
+ assert values.labels(operation="agent_pipeline", status="failed")._value.get() == 2
+ assert values.labels(operation="agent_pipeline", status="pending")._value.get() == 0
+ assert values.labels(operation="agent_pipeline", status="completed")._value.get() == 1
+ assert metrics.downstream_outbox_oldest_age_seconds.labels(
+ operation="agent_pipeline", status="failed",
+ )._value.get() == 3 * 86400
+ # Fresh empty storage resets a prior failed snapshot, rather than leaving
+ # historical in-process values after an authorized recovery.
+ async with outbox_db.begin() as connection:
+ await connection.execute(text("DELETE FROM run_downstream_outbox"))
+ await refresh_downstream_operational_metrics(now=NOW)
+ assert values.labels(operation="agent_pipeline", status="failed")._value.get() == 0
+
+
+@pytest.mark.asyncio
+async def test_actual_retry_deadlines_and_bounded_unknown_operation_labels(outbox_db):
+ await _insert(outbox_db, "agent_pipeline", "published", NOW - timedelta(hours=1),
+ NOW - timedelta(seconds=301), lease=NOW - timedelta(seconds=301))
+ await _insert(outbox_db, "agent_pipeline", "pending", NOW - timedelta(hours=2), NOW + timedelta(minutes=1))
+ await _insert(outbox_db, "untrusted-operation-a", "failed", NOW)
+ await _insert(outbox_db, "untrusted-operation-b", "failed", NOW)
+ await refresh_downstream_operational_metrics(now=NOW)
+ assert metrics.downstream_outbox_overdue_seconds.labels(operation="agent_pipeline", status="published")._value.get() == 301
+ assert metrics.downstream_outbox_overdue_seconds.labels(operation="agent_pipeline", status="pending")._value.get() == 0
+ samples = [s for f in metrics.downstream_outbox_entries.collect() for s in f.samples]
+ assert not any(s.labels["operation"].startswith("untrusted-") for s in samples)
+ assert metrics.downstream_outbox_entries.labels(operation="other", status="failed")._value.get() == 2
+
+
+@pytest.mark.asyncio
+async def test_deadlines_follow_state_specific_relay_contract_despite_conflicting_legacy_fields(outbox_db):
+ for status in ("waiting", "pending"):
+ # A stale lease must not make a future retry/recovery slot overdue.
+ await _insert(outbox_db, "agent_pipeline", status, NOW - timedelta(hours=2),
+ NOW + timedelta(minutes=1), lease=NOW - timedelta(minutes=5))
+ for status in ("sending", "published", "processing"):
+ # The relay consults lease expiry for these states, not next_attempt.
+ await _insert(outbox_db, "agent_pipeline", status, NOW - timedelta(hours=2),
+ NOW - timedelta(minutes=5), lease=NOW + timedelta(minutes=1))
+ await refresh_downstream_operational_metrics(now=NOW)
+ overdue = metrics.downstream_outbox_overdue_seconds
+ for status in ("waiting", "pending", "sending", "published", "processing"):
+ assert overdue.labels(operation="agent_pipeline", status=status)._value.get() == 0
+
+ async with outbox_db.begin() as connection:
+ await connection.execute(text("DELETE FROM run_downstream_outbox"))
+ for status in ("waiting", "pending"):
+ await _insert(outbox_db, "agent_pipeline", status, NOW - timedelta(hours=2),
+ NOW - timedelta(seconds=61), lease=NOW + timedelta(minutes=1))
+ for status in ("sending", "published", "processing"):
+ await _insert(outbox_db, "agent_pipeline", status, NOW - timedelta(hours=2),
+ NOW + timedelta(minutes=1), lease=NOW - timedelta(seconds=61))
+ await refresh_downstream_operational_metrics(now=NOW)
+ for status in ("waiting", "pending", "sending", "published", "processing"):
+ assert overdue.labels(operation="agent_pipeline", status=status)._value.get() == 61
+
+
+@pytest.mark.asyncio
+async def test_missing_lease_among_other_valid_rows_fails_collection_without_publishing_snapshot(outbox_db):
+ await _insert(outbox_db, "agent_pipeline", "processing", NOW, lease=NOW + timedelta(minutes=1))
+ await refresh_downstream_operational_metrics(now=NOW)
+ gauge = metrics.downstream_outbox_entries.labels(operation="agent_pipeline", status="processing")
+ assert gauge._value.get() == 1
+ await _insert(outbox_db, "agent_pipeline", "processing", NOW - timedelta(hours=1),
+ NOW - timedelta(minutes=5))
+ async def refresh():
+ return await refresh_downstream_operational_metrics(now=NOW)
+
+ assert not await collection.collect_bounded("downstream", refresh)
+ assert metrics.metric_collection_success.labels(collector="downstream")._value.get() == 0
+ assert gauge._value.get() == 1 # Previous snapshot is explicitly stale, not replaced with a healthy zero.
+
+
+@pytest.mark.asyncio
+async def test_slow_cancel_cleanup_does_not_block_scrape_or_spawn_repeated_refreshes(monkeypatch):
+ monkeypatch.setattr(collection, "COLLECTION_TIMEOUT_SECONDS", 0.02)
+ cleanup_started = asyncio.Event()
+ release_cleanup = asyncio.Event()
+ calls = 0
+
+ async def slow_cleanup():
+ nonlocal calls
+ calls += 1
+ try:
+ await asyncio.Event().wait()
+ finally:
+ cleanup_started.set()
+ await release_cleanup.wait()
+
+ try:
+ started = asyncio.get_running_loop().time()
+ assert not await asyncio.wait_for(collection.collect_bounded("downstream", slow_cleanup), timeout=0.3)
+ assert asyncio.get_running_loop().time() - started < 0.2
+ await asyncio.wait_for(cleanup_started.wait(), timeout=0.2)
+ pending = collection._IN_FLIGHT["downstream"]
+ assert pending.abandoned
+ assert not pending.task.done()
+ assert not await asyncio.wait_for(collection.collect_bounded("downstream", slow_cleanup), timeout=0.3)
+ assert calls == 1
+ assert collection._IN_FLIGHT["downstream"] is pending
+ finally:
+ release_cleanup.set()
+ pending = collection._IN_FLIGHT.get("downstream")
+ if pending is not None:
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(asyncio.shield(pending.task), timeout=0.3)
+ await asyncio.sleep(0)
+ assert "downstream" not in collection._IN_FLIGHT
+
+
+@pytest.mark.asyncio
+async def test_cancellation_suppression_cannot_publish_late_success_as_fresh(monkeypatch):
+ monkeypatch.setattr(collection, "COLLECTION_TIMEOUT_SECONDS", 0.02)
+ assert await collection.collect_bounded("downstream", AsyncMock(return_value=True))
+ last = metrics.metric_collection_last_success.labels(collector="downstream")._value.get()
+ release_late_success = asyncio.Event()
+
+ async def ignores_cancellation():
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ await release_late_success.wait()
+ return True
+
+ pending = None
+ try:
+ assert not await asyncio.wait_for(collection.collect_bounded("downstream", ignores_cancellation), timeout=0.3)
+ pending = collection._IN_FLIGHT["downstream"]
+ assert pending.abandoned
+ assert not pending.task.done()
+ assert metrics.metric_collection_success.labels(collector="downstream")._value.get() == 0
+ assert metrics.metric_collection_last_success.labels(collector="downstream")._value.get() == last
+ finally:
+ release_late_success.set()
+ if pending is not None:
+ assert await asyncio.wait_for(asyncio.shield(pending.task), timeout=0.3) is True
+ await asyncio.sleep(0)
+ assert "downstream" not in collection._IN_FLIGHT
+ assert metrics.metric_collection_success.labels(collector="downstream")._value.get() == 0
+ assert metrics.metric_collection_last_success.labels(collector="downstream")._value.get() == last
+
+
+@pytest.mark.asyncio
+async def test_overlapping_healthy_scrapes_share_one_successful_collection(monkeypatch):
+ monkeypatch.setattr(collection, "COLLECTION_TIMEOUT_SECONDS", 0.5)
+ started = asyncio.Event()
+ release = asyncio.Event()
+ calls = 0
+ before = metrics.metric_collection_errors_total.labels(collector="downstream")._value.get()
+
+ async def refresh():
+ nonlocal calls
+ calls += 1
+ started.set()
+ await release.wait()
+ return True
+
+ waiters = []
+ try:
+ waiters.append(asyncio.create_task(collection.collect_bounded("downstream", refresh)))
+ await asyncio.wait_for(started.wait(), timeout=0.3)
+ waiters.append(asyncio.create_task(collection.collect_bounded("downstream", refresh)))
+ await asyncio.sleep(0)
+ assert calls == 1
+ assert not waiters[1].done(), "a healthy in-flight collection must not become a failed second scrape"
+ release.set()
+ assert await asyncio.wait_for(asyncio.gather(*waiters), timeout=0.3) == [True, True]
+ finally:
+ release.set()
+ await asyncio.wait_for(asyncio.gather(*waiters, return_exceptions=True), timeout=0.3)
+ assert metrics.metric_collection_errors_total.labels(collector="downstream")._value.get() == before
+ assert metrics.metric_collection_success.labels(collector="downstream")._value.get() == 1
+ assert "downstream" not in collection._IN_FLIGHT
+
+
+@pytest.mark.asyncio
+async def test_cancelled_first_waiter_does_not_cancel_shared_collection_or_fail_other_scrape(monkeypatch):
+ monkeypatch.setattr(collection, "COLLECTION_TIMEOUT_SECONDS", 0.5)
+ assert await collection.collect_bounded("downstream", AsyncMock(return_value=True))
+ started = asyncio.Event()
+ release = asyncio.Event()
+ calls = 0
+ before = metrics.metric_collection_errors_total.labels(collector="downstream")._value.get()
+
+ async def refresh():
+ nonlocal calls
+ calls += 1
+ started.set()
+ await release.wait()
+ return True
+
+ waiters = []
+ try:
+ waiters.append(asyncio.create_task(collection.collect_bounded("downstream", refresh)))
+ await asyncio.wait_for(started.wait(), timeout=0.3)
+ waiters.append(asyncio.create_task(collection.collect_bounded("downstream", refresh)))
+ await asyncio.sleep(0)
+ attempt = collection._IN_FLIGHT["downstream"]
+ waiters[0].cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await waiters[0]
+ assert not attempt.abandoned
+ assert attempt.task.cancelling() == 0
+ assert not attempt.task.done()
+ assert metrics.metric_collection_success.labels(collector="downstream")._value.get() == 1
+ release.set()
+ assert await asyncio.wait_for(waiters[1], timeout=0.3) is True
+ assert calls == 1
+ finally:
+ release.set()
+ await asyncio.wait_for(asyncio.gather(*waiters, return_exceptions=True), timeout=0.3)
+ assert metrics.metric_collection_errors_total.labels(collector="downstream")._value.get() == before
+ assert metrics.metric_collection_success.labels(collector="downstream")._value.get() == 1
+ assert "downstream" not in collection._IN_FLIGHT
+
+
+@pytest.mark.asyncio
+async def test_slow_collector_is_bounded_and_does_not_advance_freshness(monkeypatch):
+ monkeypatch.setattr(collection, "COLLECTION_TIMEOUT_SECONDS", 0.02)
+ healthy = AsyncMock(return_value=True)
+ assert await collection.collect_bounded("downstream", healthy)
+ last = metrics.metric_collection_last_success.labels(collector="downstream")._value.get()
+ before = metrics.metric_collection_errors_total.labels(collector="downstream")._value.get()
+ stalled = asyncio.Event()
+ start = asyncio.get_running_loop().time()
+ assert not await collection.collect_bounded("downstream", stalled.wait)
+ assert asyncio.get_running_loop().time() - start < 0.5
+ assert metrics.metric_collection_success.labels(collector="downstream")._value.get() == 0
+ assert metrics.metric_collection_last_success.labels(collector="downstream")._value.get() == last
+ assert metrics.metric_collection_errors_total.labels(collector="downstream")._value.get() == before + 1
+
+
+@pytest.mark.asyncio
+async def test_immediate_failure_and_explicit_partial_result_are_not_success():
+ for failed in (AsyncMock(side_effect=ConnectionError), AsyncMock(return_value=False), AsyncMock(return_value=None)):
+ assert not await collection.collect_bounded("agents", failed)
+ assert metrics.metric_collection_success.labels(collector="agents")._value.get() == 0
+ assert await collection.collect_bounded("agents", AsyncMock(return_value=True))
+ assert metrics.metric_collection_success.labels(collector="agents")._value.get() == 1
+
+
+@pytest.mark.asyncio
+async def test_child_queue_is_observed_and_partial_failure_is_reported(monkeypatch):
+ from app import bootstrap
+ from app.db import redis_client
+
+ seen = []
+ async def length(queue):
+ seen.append(queue)
+ if queue == "critical":
+ raise ConnectionError("fake-down")
+ return 7
+ monkeypatch.setattr(redis_client, "get_redis", lambda: SimpleNamespace(llen=length))
+ assert await bootstrap._refresh_celery_queue_depths() is False
+ assert "agent_children" in seen
+ assert metrics.celery_queue_length.labels(queue_name="agent_children")._value.get() == 7
diff --git a/backend/tests/regression/test_prompt_sanitizer_authorization.py b/backend/tests/regression/test_prompt_sanitizer_authorization.py
index b1558620f..a0978d61a 100644
--- a/backend/tests/regression/test_prompt_sanitizer_authorization.py
+++ b/backend/tests/regression/test_prompt_sanitizer_authorization.py
@@ -12,7 +12,7 @@
from app.services.input_sanitizer import sanitize_tool_output
-CREDENTIAL = "dXNlcjpwYXNzd29yZA=="
+CREDENTIAL = "dXNlcjpwYXNzd29yZA==" # gitleaks:allow -- synthetic test credential, never production authority
@pytest.mark.parametrize("scheme", ["Basic", "Bearer", "Digest", "Negotiate", "NTLM", "Token", "basic"])
diff --git a/backend/tests/regression/test_trace_export_boundary.py b/backend/tests/regression/test_trace_export_boundary.py
new file mode 100644
index 000000000..a642ffe9b
--- /dev/null
+++ b/backend/tests/regression/test_trace_export_boundary.py
@@ -0,0 +1,264 @@
+"""Every configured trace sink receives sanitized copies, including exception data."""
+from __future__ import annotations
+
+import io
+import json
+
+import pytest
+
+from app.core import tracing
+
+pytest.importorskip("opentelemetry.sdk.trace")
+
+from opentelemetry.exporter.otlp.proto.common.trace_encoder import encode_spans # noqa: E402
+from opentelemetry.sdk.resources import Resource # noqa: E402
+from opentelemetry.sdk.trace import SpanLimits, TracerProvider # noqa: E402
+from opentelemetry.sdk.trace.export import ( # noqa: E402
+ ConsoleSpanExporter,
+ SimpleSpanProcessor,
+ SpanExporter,
+ SpanExportResult,
+)
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter # noqa: E402
+from opentelemetry.trace import Link, SpanContext, SpanKind, TraceFlags, TraceState # noqa: E402
+
+pytestmark = pytest.mark.regression
+
+
+@pytest.fixture
+def sinks():
+ provider = TracerProvider(resource=Resource({"service.name": "testlookup", "server.address": "10.42.0.7"}))
+ safe, original = InMemorySpanExporter(), InMemorySpanExporter()
+ provider.add_span_processor(SimpleSpanProcessor(tracing.redacting_span_exporter(safe)))
+ # This test-only sink proves sanitization did not mutate the original SDK
+ # span or the copies other processors observe. It never sends data anywhere.
+ provider.add_span_processor(SimpleSpanProcessor(original))
+ yield provider, safe, original
+ provider.shutdown()
+
+
+def serialized(spans):
+ return "\n".join(span.to_json() for span in spans).encode() + encode_spans(spans).SerializeToString()
+
+
+@pytest.mark.parametrize(
+ ("text", "secret"),
+ [
+ ("failed https://partner.test/items?unusual=fake-query-secret#fragment", "fake-query-secret"),
+ ("failed https://partner.test/items?x=%66%61%6b%65%2dencoded-secret", "encoded-secret"),
+ ("failed https://hooks.slack.com/services/Tfake/Bfake/fake-hook-path", "fake-hook-path"),
+ ("failed https://fake-user:fake-pass@db.test/items", "fake-pass"),
+ ("Authorization: Basic ZmFrZS11c2VyOmZha2UtcGFzcw==", "ZmFrZS11c2VyOmZha2UtcGFzcw=="),
+ ('decision {"access_token": "tiny"}', "tiny"),
+ ('decision {"private_key": "fake-opaque-private-key"}', "fake-opaque-private-key"),
+ ("Bearer tiny", "tiny"),
+ ("rejected eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ4In0.ZmFrZQ", "eyJhbGciOiJIUzI1NiJ9"),
+ ("rejected tl_fake_key_abcdefghijklmnop", "tl_fake_key_abcdefghijklmnop"),
+ ("failed https://[invalid/fake-malformed-secret?x=y", "fake-malformed-secret"),
+ ("failed //fake-user:fake-relative-pass@partner.test/path", "fake-relative-pass"),
+ ],
+)
+def test_exception_status_events_and_custom_text_are_scrubbed_without_mutation(sinks, text, secret):
+ provider, safe, original = sinks
+ with pytest.raises(RuntimeError):
+ with provider.get_tracer("test.workflow").start_as_current_span("agent.step") as span:
+ span.set_attribute("route.rationale", text)
+ span.set_attribute("decisions.notes", ["legitimate decision", text])
+ span.add_event("decision", {"custom.text": text})
+ raise RuntimeError(text)
+
+ emitted = safe.get_finished_spans()
+ raw = original.get_finished_spans()
+ assert secret.encode() not in serialized(emitted)
+ assert secret in raw[0].to_json(), "the trigger must really reach the original finished span"
+ assert emitted[0] is not raw[0]
+ assert emitted[0].events[-1].attributes["exception.type"] == "RuntimeError"
+ assert emitted[0].status.status_code == raw[0].status.status_code
+ assert emitted[0].context == raw[0].context
+ assert emitted[0].events[-1].timestamp == raw[0].events[-1].timestamp
+
+
+@pytest.mark.parametrize("depth", [0, 1, 2, 3, 4])
+@pytest.mark.parametrize("key", ["access_token", "private-key", "vendor.client_secret"])
+def test_nested_json_credentials_preserve_surrounding_diagnostic_text(sinks, depth, key):
+ provider, safe, original = sinks
+ text = json.dumps({key: 'fake-opaque-secret with "quotes" and a trailing slash\\', "legitimate": "keep-me"})
+ for _ in range(depth):
+ text = json.dumps(text)
+ text = "operation-before " + text + " operation-after"
+ with pytest.raises(ValueError):
+ with provider.get_tracer("test").start_as_current_span("known-operation") as span:
+ span.set_attribute("route.rationale", text)
+ span.add_event("decision", {"custom.text": text})
+ raise ValueError(text)
+ payload = serialized(safe.get_finished_spans())
+ assert b"fake-opaque-secret" not in payload
+ for legitimate in (b"operation-before", b"operation-after", b"keep-me"):
+ assert legitimate in payload
+ assert b"fake-opaque-secret" in serialized(original.get_finished_spans())
+
+
+def test_structured_secrets_and_payloads_are_redacted_but_operational_values_survive(sinks):
+ provider, safe, original = sinks
+ with provider.get_tracer("test.workflow").start_as_current_span("agent.step") as span:
+ span.set_attribute("http.request.header.authorization", "opaque-short-secret")
+ span.set_attribute("testlookup.vendor.api_key", "another-opaque-secret")
+ span.set_attribute("gen_ai.input.messages", "private prompt with no secret marker")
+ span.set_attribute("token_count", 1234567890)
+ span.set_attribute("password_changed", True)
+ span.set_attribute("testlookup.pipeline_run_id", "05982379-5519-4289-a773-123456789012")
+ span.set_attribute("safe.text", "10.42.0.7:6379 processed 1234567890 bytes")
+ snapshot = safe.get_finished_spans()[0]
+ assert snapshot.attributes["http.request.header.authorization"] == tracing.REDACTED
+ assert snapshot.attributes["testlookup.vendor.api_key"] == tracing.REDACTED
+ assert snapshot.attributes["gen_ai.input.messages"] == tracing.REDACTED
+ for key in ("token_count", "password_changed", "testlookup.pipeline_run_id", "safe.text"):
+ assert snapshot.attributes[key] == original.get_finished_spans()[0].attributes[key]
+ assert snapshot.resource.attributes["server.address"] == "10.42.0.7"
+
+
+def test_url_query_and_full_url_sequence_forms_cannot_bypass_sanitization(sinks):
+ provider, safe, _ = sinks
+ with provider.get_tracer("test").start_as_current_span("operation") as span:
+ span.set_attribute("url.query", ["unusual=fake-array-secret", "x=1"])
+ span.set_attribute("url.full", ["//fake-user:fake-password@partner.test/path?x=fake-array-secret"])
+ payload = serialized(safe.get_finished_spans())
+ assert b"fake-array-secret" not in payload and b"fake-password" not in payload
+ assert b"partner.test/path" in payload
+
+
+def test_oversized_text_is_explicitly_omitted_without_exporting_a_partial_secret(sinks):
+ provider, safe, _ = sinks
+ with provider.get_tracer("test").start_as_current_span("operation") as span:
+ span.set_attribute("custom.text", "x" * 100_000 + "fake-trailing-secret")
+ payload = serialized(safe.get_finished_spans())
+ assert b"fake-trailing-secret" not in payload
+ assert b"REDACTED_OVERSIZED_TRACE_TEXT" in payload
+
+
+def test_loss_accounting_is_preserved_for_span_event_and_link():
+ from opentelemetry.attributes import BoundedAttributes
+
+ provider = TracerProvider(span_limits=SpanLimits(max_attributes=1, max_events=1, max_links=1))
+ safe, original = InMemorySpanExporter(), InMemorySpanExporter()
+ provider.add_span_processor(SimpleSpanProcessor(tracing.redacting_span_exporter(safe)))
+ provider.add_span_processor(SimpleSpanProcessor(original))
+ attrs = BoundedAttributes(maxlen=1, attributes={"first": "safe", "second": "safe"})
+ try:
+ with provider.get_tracer("test").start_as_current_span("operation", links=[Link(SpanContext(123, 456, True), attrs)]) as span:
+ span.set_attribute("first", "safe")
+ span.set_attribute("second", "safe")
+ span.add_event("first")
+ span.add_event("second", attrs)
+ snapshot, raw = safe.get_finished_spans()[0], original.get_finished_spans()[0]
+ assert snapshot.dropped_attributes == raw.dropped_attributes == 1
+ assert snapshot.dropped_events == raw.dropped_events == 1
+ assert snapshot.dropped_links == raw.dropped_links
+ assert snapshot.events[0].dropped_attributes == raw.events[0].dropped_attributes
+ assert snapshot.links[0].dropped_attributes == raw.links[0].dropped_attributes
+ finally:
+ provider.shutdown()
+
+
+def test_resource_scope_link_and_span_name_copies_are_sanitized():
+ secret = "fake-metadata-secret"
+ address = f"https://partner.test/path?ticket={secret}"
+ provider = TracerProvider(resource=Resource({"service.name": "testlookup", "custom.reference": address}, address))
+ safe, original = InMemorySpanExporter(), InMemorySpanExporter()
+ provider.add_span_processor(SimpleSpanProcessor(tracing.redacting_span_exporter(safe)))
+ provider.add_span_processor(SimpleSpanProcessor(original))
+ linked_context = SpanContext(
+ 123, 456, is_remote=True, trace_flags=TraceFlags(1),
+ trace_state=TraceState([("vendor", "legitimate"), ("token", secret)]),
+ )
+ try:
+ tracer = provider.get_tracer(address, "1.2.3", schema_url=address, attributes={"custom.text": address})
+ with tracer.start_as_current_span(address, kind=SpanKind.CLIENT, links=[Link(linked_context, {"custom.text": address})]) as span:
+ span.add_event(address, {"custom.text": address})
+ snapshot, raw = safe.get_finished_spans()[0], original.get_finished_spans()[0]
+ assert secret.encode() not in serialized([snapshot])
+ assert secret.encode() in serialized([raw])
+ assert snapshot.kind is SpanKind.CLIENT
+ assert snapshot.context == raw.context
+ assert snapshot.start_time == raw.start_time and snapshot.end_time == raw.end_time
+ assert snapshot.instrumentation_scope.version == "1.2.3"
+ assert snapshot.links[0].context.trace_id == 123
+ assert snapshot.links[0].context.trace_state["vendor"] == "legitimate"
+ assert snapshot.links[0].context.trace_state["token"] == tracing.REDACTED
+ finally:
+ provider.shutdown()
+
+
+@pytest.mark.parametrize("environment", ["development", "production"])
+@pytest.mark.parametrize("encoded_json", [False, True])
+def test_configured_console_and_otlp_paths_serialize_only_sanitized_spans(monkeypatch, environment, encoded_json):
+ from opentelemetry import trace
+ from opentelemetry.exporter.otlp.proto.http import trace_exporter
+ from opentelemetry.sdk.trace import export
+
+ stream = io.StringIO()
+ otlp_payloads = []
+ providers = []
+
+ class RecordingOTLP(SpanExporter):
+ def export(self, spans):
+ otlp_payloads.append(encode_spans(spans).SerializeToString())
+ return SpanExportResult.SUCCESS
+
+ monkeypatch.setattr(trace, "set_tracer_provider", providers.append)
+ monkeypatch.setattr(tracing, "_initialised", False)
+ monkeypatch.setattr(tracing, "_apply_auto_instrumentors", lambda: None)
+ monkeypatch.setattr(export, "BatchSpanProcessor", SimpleSpanProcessor)
+ monkeypatch.setattr(export, "ConsoleSpanExporter", lambda: ConsoleSpanExporter(out=stream))
+ monkeypatch.setattr(trace_exporter, "OTLPSpanExporter", lambda **kwargs: RecordingOTLP())
+ tracing.setup_tracing("testlookup", "test", environment, "http://collector.test:4318" if environment == "production" else None)
+ try:
+ message = "failed https://partner.test/items?token=fake-sink-secret"
+ if encoded_json:
+ message = "operation-before " + json.dumps(json.dumps({"access_token": "fake-sink-secret", "legitimate": "keep-me"})) + " operation-after"
+ with pytest.raises(ValueError):
+ with providers[0].get_tracer("test.export").start_as_current_span("known-operation"):
+ raise ValueError(message)
+ payload = b"".join(otlp_payloads) + stream.getvalue().encode()
+ assert payload and b"fake-sink-secret" not in payload
+ assert b"known-operation" in payload and b"ValueError" in payload
+ if encoded_json:
+ assert b"operation-before" in payload and b"operation-after" in payload and b"keep-me" in payload
+ finally:
+ providers[0].shutdown()
+
+
+def test_sanitization_failure_drops_only_unsafe_span_without_raw_fallback(monkeypatch, caplog, sinks):
+ provider, safe, original = sinks
+ sanitizer = tracing._sanitized_span
+
+ def fail_one(span):
+ if span.name == "unsafe":
+ raise ValueError("fake-failure-secret")
+ return sanitizer(span)
+
+ monkeypatch.setattr(tracing, "_sanitized_span", fail_one)
+ with provider.get_tracer("test").start_as_current_span("unsafe") as span:
+ span.set_attribute("custom.text", "fake-failure-secret")
+ with provider.get_tracer("test").start_as_current_span("ordinary"):
+ pass
+ assert [span.name for span in safe.get_finished_spans()] == ["ordinary"]
+ assert len(original.get_finished_spans()) == 2
+ assert "sanitization failed" in caplog.text and "fake-failure-secret" not in caplog.text
+
+
+def test_exporter_lifecycle_is_forwarded():
+ calls = []
+
+ class Exporter(SpanExporter):
+ def shutdown(self):
+ calls.append("shutdown")
+
+ def force_flush(self, timeout_millis=30000):
+ calls.append(timeout_millis)
+ return True
+
+ wrapped = tracing.redacting_span_exporter(Exporter())
+ assert wrapped.force_flush(timeout_millis=123)
+ wrapped.shutdown()
+ assert calls == [123, "shutdown"]
diff --git a/backend/tests/regression/test_upload_dispatch_boundary.py b/backend/tests/regression/test_upload_dispatch_boundary.py
new file mode 100644
index 000000000..e36ce459a
--- /dev/null
+++ b/backend/tests/regression/test_upload_dispatch_boundary.py
@@ -0,0 +1,322 @@
+"""OBS-23/24: broker uncertainty must not destroy a queued upload or stall HTTP.
+
+The real HTTP handlers, upload status state machine and task signatures run
+against fake auth/storage/Redis. Publication runs on the actual bounded helper;
+thread events simulate a broker that accepts, errors, or answers after timeout.
+"""
+from __future__ import annotations
+
+import asyncio
+import inspect
+import json
+import threading
+import uuid
+from concurrent.futures import ThreadPoolExecutor
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+from fastapi import FastAPI
+from httpx import ASGITransport, AsyncClient
+
+from app.core.deps import get_api_key_context, get_db
+from app.routers import ingest
+from app.services import upload_status
+from app.worker import tasks, upload_dispatch
+from tests.regression.test_upload_status import _fake_redis_with_store
+
+pytestmark = pytest.mark.asyncio
+
+
+class _Storage:
+ def __init__(self):
+ self.objects = {}
+ self.deleted = []
+
+ async def put_object(self, key, content, **_options):
+ self.objects[key] = content
+
+ async def delete_object(self, key, **_options):
+ self.deleted.append(key)
+ self.objects.pop(key, None)
+
+
+@pytest.fixture
+def publisher(monkeypatch):
+ """One real thread/slot per test; no late work escapes its fixture."""
+ executor = ThreadPoolExecutor(max_workers=1)
+ monkeypatch.setattr(upload_dispatch, "_PUBLISH_EXECUTOR", executor)
+ monkeypatch.setattr(upload_dispatch, "_PUBLISH_SLOTS", threading.BoundedSemaphore(1))
+ monkeypatch.setattr(upload_dispatch, "UPLOAD_PUBLISH_TIMEOUT_SECONDS", 0.25)
+ try:
+ yield
+ finally:
+ executor.shutdown(wait=True, cancel_futures=True)
+
+
+@pytest.fixture
+def world(monkeypatch, publisher):
+ app = FastAPI()
+ app.include_router(ingest.router)
+ project_id = uuid.uuid4()
+ user = SimpleNamespace(
+ id=uuid.uuid4(), username="upload-review", full_name="Upload review",
+ role="QA_ENGINEER", is_active=True,
+ )
+
+ async def db():
+ yield AsyncMock()
+
+ async def auth():
+ return user, None
+
+ app.dependency_overrides[get_db] = db
+ app.dependency_overrides[get_api_key_context] = auth
+ redis, records = _fake_redis_with_store()
+ storage = _Storage()
+ monkeypatch.setattr("app.db.redis_client.get_redis", lambda: redis)
+ monkeypatch.setattr("app.db.storage.get_storage_provider", lambda: storage)
+ monkeypatch.setattr(ingest, "resolve_project_scope", AsyncMock())
+ monkeypatch.setattr(ingest, "record_activity", AsyncMock())
+ monkeypatch.setattr(ingest, "_resolve_run_id", AsyncMock(return_value=str(uuid.uuid4())))
+ monkeypatch.setattr(ingest, "run_is_tombstoned", AsyncMock(return_value=False))
+ monkeypatch.setattr(
+ "app.services.ingestion_backpressure.enforce_redis_memory_backpressure", AsyncMock()
+ )
+ monkeypatch.setattr(
+ "app.services.ingestion_rate_limit.enforce_ingest_rate_limit", AsyncMock()
+ )
+ return SimpleNamespace(
+ app=app, project_id=project_id, records=records, storage=storage
+ )
+
+
+async def _post(world, kind):
+ async with AsyncClient(
+ transport=ASGITransport(app=world.app), base_url="http://testserver"
+ ) as client:
+ if kind == "batch":
+ return await client.post("/api/v1/ingest", json={
+ "project_id": str(world.project_id), "build_number": "review-build",
+ "results": [{"test_name": "review_test", "status": "PASSED"}],
+ })
+ return await client.post(
+ "/api/v1/ingest/file",
+ data={"project_id": str(world.project_id), "build_number": "review-build", "format": "junit"},
+ files={"file": ("results.xml", b'', "application/xml")},
+ )
+
+
+async def _poll(world, task_id):
+ async with AsyncClient(
+ transport=ASGITransport(app=world.app), base_url="http://testserver"
+ ) as client:
+ return await client.get(f"/api/v1/ingest/uploads/{task_id}")
+
+
+def _task(kind):
+ return tasks.ingest_uploaded_results if kind == "batch" else tasks.ingest_uploaded_file
+
+
+def _storage_key(message):
+ return message["kwargs"].get("payload_storage_key") or message["kwargs"]["file_storage_key"]
+
+
+@pytest.mark.parametrize("kind", ["batch", "file"])
+async def test_confirmed_publish_keeps_202_and_the_original_task_contract(world, monkeypatch, kind):
+ task = _task(kind)
+ published = []
+
+ def publish(*, kwargs, task_id, **options):
+ task.__header__(**kwargs)
+ inspect.signature(task.run).bind(**kwargs)
+ published.append({"kwargs": kwargs, "task_id": task_id, "options": options})
+
+ monkeypatch.setattr(task, "apply_async", publish)
+ response = await _post(world, kind)
+ assert response.status_code == 202, response.text
+ message, = published
+ assert response.json()["task_id"] == message["task_id"]
+ assert response.json()["run_id"] == message["kwargs"]["run_id"]
+ assert message["options"] == {"ignore_result": True, "retry": False}
+ assert _storage_key(message) in world.storage.objects
+ assert (await _poll(world, message["task_id"])).json()["state"] == "pending"
+
+
+@pytest.mark.parametrize("kind", ["batch", "file"])
+async def test_accepted_then_error_retains_payload_and_pending_poll_identity(world, monkeypatch, kind):
+ accepted = []
+
+ def publish(**message):
+ accepted.append(message)
+ raise ConnectionError("fake confirmation lost after broker acceptance")
+
+ monkeypatch.setattr(_task(kind), "apply_async", publish)
+ response = await _post(world, kind)
+ assert response.status_code == 503, response.text
+ message, = accepted
+ assert _storage_key(message) in world.storage.objects
+ assert world.storage.deleted == []
+ assert response.headers["X-Upload-Task-ID"] == message["task_id"]
+ assert response.headers["X-Upload-Run-ID"] == message["kwargs"]["run_id"]
+ assert response.headers["Location"] == f'/api/v1/ingest/uploads/{message["task_id"]}'
+ assert response.headers["Location"] in response.json()["detail"]
+ poll = await _poll(world, message["task_id"])
+ assert poll.status_code == 200
+ assert poll.json()["state"] == "pending"
+ assert poll.json()["run_id"] == message["kwargs"]["run_id"]
+
+
+@pytest.mark.parametrize("kind", ["batch", "file"])
+async def test_worker_terminal_result_survives_an_unconfirmed_publish(world, monkeypatch, kind):
+ def publish(*, kwargs, task_id, **_options):
+ # Model a worker that completed before the broker client's error.
+ world.records[f"upload:status:{task_id}"] = json.dumps({
+ "task_id": task_id, "run_id": kwargs["run_id"],
+ "project_id": str(world.project_id), "state": "succeeded",
+ "result": {"total": 1},
+ })
+ raise ConnectionError("fake acknowledgement lost")
+
+ monkeypatch.setattr(_task(kind), "apply_async", publish)
+ response = await _post(world, kind)
+ assert response.status_code == 503
+ poll = await _poll(world, response.headers["X-Upload-Task-ID"])
+ assert poll.json()["state"] == "succeeded"
+ assert poll.json()["result"] == {"total": 1}
+
+
+@pytest.mark.parametrize("kind", ["batch", "file"])
+async def test_timeout_keeps_event_loop_responsive_and_late_publication_identity(world, monkeypatch, kind):
+ monkeypatch.setattr(upload_dispatch, "UPLOAD_PUBLISH_TIMEOUT_SECONDS", 0.05)
+ release = threading.Event()
+ finished = threading.Event()
+ accepted = []
+ ticks = []
+ stop = asyncio.Event()
+
+ def publish(**message):
+ try:
+ assert release.wait(2), "test did not release the fake broker"
+ accepted.append(message)
+ finally:
+ finished.set()
+
+ async def heartbeat():
+ while not stop.is_set():
+ ticks.append(1)
+ await asyncio.sleep(0.002)
+
+ monkeypatch.setattr(_task(kind), "apply_async", publish)
+ ticker = asyncio.create_task(heartbeat())
+ try:
+ response = await asyncio.wait_for(_post(world, kind), timeout=1)
+ assert response.status_code == 503
+ assert not finished.is_set(), "HTTP must return while publication is still blocked"
+ assert len(ticks) >= 2, "the synchronous publisher blocked the event loop"
+ task_id = response.headers["X-Upload-Task-ID"]
+ run_id = response.headers["X-Upload-Run-ID"]
+ assert (await _poll(world, task_id)).json()["state"] == "pending"
+ assert len(world.storage.objects) == 1
+ release.set()
+ assert await asyncio.to_thread(finished.wait, 1)
+ message, = accepted
+ assert message["task_id"] == task_id
+ assert message["kwargs"]["run_id"] == run_id
+ assert _storage_key(message) in world.storage.objects
+ # A later worker still advances the SAME monotonic polling record.
+ await upload_status.set_status(
+ task_id, run_id=run_id, project_id=str(world.project_id),
+ state="succeeded", result={"total": 1},
+ )
+ assert (await _poll(world, task_id)).json()["state"] == "succeeded"
+ finally:
+ release.set()
+ stop.set()
+ await ticker
+ await asyncio.to_thread(finished.wait, 1)
+
+
+async def test_timeout_does_not_release_capacity_until_the_real_publish_finishes(publisher, monkeypatch):
+ monkeypatch.setattr(upload_dispatch, "UPLOAD_PUBLISH_TIMEOUT_SECONDS", 0.05)
+ release = threading.Event()
+ finished = threading.Event()
+ calls = []
+
+ def publish(**message):
+ calls.append(message["task_id"])
+ try:
+ assert release.wait(2)
+ finally:
+ finished.set()
+
+ task = SimpleNamespace(apply_async=publish)
+ try:
+ with pytest.raises(TimeoutError):
+ await upload_dispatch.publish_upload(task, kwargs={}, task_id="first")
+ with pytest.raises(upload_dispatch.UploadPublisherBusy):
+ await upload_dispatch.publish_upload(task, kwargs={}, task_id="second")
+ assert calls == ["first"], "a timeout must not admit an unbounded queue of late tasks"
+ finally:
+ release.set()
+ assert await asyncio.to_thread(finished.wait, 1)
+
+
+async def test_request_cancellation_keeps_the_slot_until_publication_ends(publisher):
+ started = threading.Event()
+ release = threading.Event()
+ finished = threading.Event()
+
+ def publish(**_message):
+ started.set()
+ try:
+ assert release.wait(2)
+ finally:
+ finished.set()
+
+ task = SimpleNamespace(apply_async=publish)
+ pending = asyncio.create_task(
+ upload_dispatch.publish_upload(task, kwargs={}, task_id="cancelled-waiter")
+ )
+ try:
+ assert await asyncio.to_thread(started.wait, 1)
+ pending.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await pending
+ with pytest.raises(upload_dispatch.UploadPublisherBusy):
+ await upload_dispatch.publish_upload(task, kwargs={}, task_id="not-submitted")
+ finally:
+ release.set()
+ assert await asyncio.to_thread(finished.wait, 1)
+
+
+@pytest.mark.parametrize("kind", ["batch", "file"])
+async def test_known_capacity_refusal_discards_only_its_unsubmitted_upload(world, monkeypatch, kind):
+ # Unlike a publish error, a full admission semaphore proves no call started.
+ assert upload_dispatch._PUBLISH_SLOTS.acquire(blocking=False)
+ publish = AsyncMock()
+ monkeypatch.setattr(_task(kind), "apply_async", publish)
+ try:
+ response = await _post(world, kind)
+ finally:
+ upload_dispatch._PUBLISH_SLOTS.release()
+ assert response.status_code == 503
+ assert response.headers["Retry-After"] == "1"
+ assert "busy" in response.json()["detail"]
+ assert world.storage.objects == {}
+ assert world.records == {}
+ publish.assert_not_called()
+
+
+@pytest.mark.parametrize("kind", ["batch", "file"])
+async def test_authorization_refusal_still_precedes_storage_and_publication(world, monkeypatch, kind):
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(ingest, "resolve_project_scope", AsyncMock(side_effect=HTTPException(403, "denied")))
+ dispatch = AsyncMock()
+ monkeypatch.setattr(upload_dispatch, "publish_upload", dispatch)
+ response = await _post(world, kind)
+ assert response.status_code == 403
+ assert world.storage.objects == {}
+ assert world.records == {}
+ dispatch.assert_not_awaited()
diff --git a/backend/tests/regression/test_worker_readiness_sentinel.py b/backend/tests/regression/test_worker_readiness_sentinel.py
index 3e47d899e..49e6a1daa 100644
--- a/backend/tests/regression/test_worker_readiness_sentinel.py
+++ b/backend/tests/regression/test_worker_readiness_sentinel.py
@@ -102,6 +102,41 @@ def test_the_signal_handlers_write_and_clear_the_same_path(tmp_path, monkeypatch
assert not sentinel.exists(), "worker_shutdown left the worker reporting Ready"
+@pytest.mark.parametrize("with_metrics", [False, True])
+def test_replacement_clears_preserved_marker_before_becoming_ready(tmp_path, monkeypatch, with_metrics):
+ """A killed container leaves /tmp behind; only its replacement may report Ready."""
+ from celery.signals import celeryd_init, worker_ready, worker_shutdown
+
+ from app.worker import celery_app
+
+ sentinel = tmp_path / "celery-worker-ready"
+ sentinel.write_text("old worker\n", encoding="utf-8")
+ monkeypatch.setattr(celery_app, "READY_SENTINEL", str(sentinel))
+ metric_dir = tmp_path / "metrics"
+ metric_dir.mkdir()
+ stale_metric = metric_dir / "counter_123.db"
+ stale_metric.write_text("old", encoding="utf-8")
+ keep = metric_dir / "README"
+ keep.write_text("keep", encoding="utf-8")
+ if with_metrics:
+ monkeypatch.setenv("PROMETHEUS_MULTIPROC_DIR", str(metric_dir))
+ else:
+ monkeypatch.delenv("PROMETHEUS_MULTIPROC_DIR", raising=False)
+
+ responses = celeryd_init.send(sender=None)
+ assert all(not isinstance(result, Exception) for _, result in responses)
+ assert not sentinel.exists(), "replacement reported Ready before its consumer started"
+ assert stale_metric.exists() is not with_metrics
+ assert keep.read_text(encoding="utf-8") == "keep"
+
+ # No broker connection or metrics listener is needed for this lifecycle proof.
+ monkeypatch.delenv("PROMETHEUS_MULTIPROC_DIR", raising=False)
+ worker_ready.send(sender=None)
+ assert sentinel.read_text(encoding="utf-8") == "ready\n"
+ worker_shutdown.send(sender=None)
+ assert not sentinel.exists()
+
+
def test_readiness_never_blocks_a_worker_from_booting(tmp_path, monkeypatch):
"""An unwritable path must not raise out of the signal handler.
diff --git a/backend/tests/regression/test_worker_task_log_context.py b/backend/tests/regression/test_worker_task_log_context.py
new file mode 100644
index 000000000..7a5b3a6c5
--- /dev/null
+++ b/backend/tests/regression/test_worker_task_log_context.py
@@ -0,0 +1,132 @@
+"""Task execution context follows the current message, including reused children."""
+from types import SimpleNamespace
+
+from celery.exceptions import Retry
+from celery.signals import task_postrun, task_prerun
+import pytest
+from structlog.contextvars import bind_contextvars, clear_contextvars, get_contextvars
+
+from app.worker import celery_app as worker
+from app.worker.tasks import _bind_task_context
+
+pytestmark = pytest.mark.regression
+
+
+@pytest.fixture(autouse=True)
+def _isolated_log_context():
+ clear_contextvars()
+ yield
+ clear_contextvars()
+
+
+def _task(task_id, *, headers=None, retries=0, **request_fields):
+ return SimpleNamespace(
+ name="app.worker.tasks.context_probe",
+ request=SimpleNamespace(
+ id=task_id, headers=headers, retries=retries, is_eager=False, **request_fields,
+ ),
+ )
+
+
+def _send(signal, task, **fields):
+ responses = signal.send(sender=None, task=task, task_id=task.request.id, **fields)
+ assert all(not isinstance(result, Exception) for _, result in responses)
+
+
+@pytest.mark.parametrize("state", ["SUCCESS", "FAILURE", "RETRY"])
+def test_each_execution_binds_current_identity_and_cleans_up_for_reuse(state):
+ first = _task("task-first", headers={"request_id": "request-first", "correlation_id": "flow-first"})
+ bind_contextvars(project_id="stale-project", request_id="stale-request", path="/previous")
+ _send(task_prerun, first, args=("payload",), kwargs={"api_token": "never-copy-payload"})
+ assert get_contextvars() == {
+ "celery_task_id": "task-first",
+ "celery_task_name": first.name,
+ "celery_retry": 0,
+ "request_id": "request-first",
+ "correlation_id": "flow-first",
+ }
+ _bind_task_context(first, project_id="project-first", run_id="run-first")
+ assert get_contextvars()["project_id"] == "project-first"
+ assert get_contextvars()["request_id"] == "request-first"
+ _send(task_postrun, first, state=state)
+ assert get_contextvars() == {}
+
+ second = _task("task-second", retries=1 if state == "RETRY" else 0)
+ _send(task_prerun, second)
+ assert get_contextvars() == {
+ "celery_task_id": "task-second",
+ "celery_task_name": second.name,
+ "celery_retry": second.request.retries,
+ }
+ _send(task_postrun, second, state="SUCCESS")
+ assert get_contextvars() == {}
+
+
+def test_prerun_discards_leftover_context_even_without_a_prior_postrun():
+ bind_contextvars(project_id="previous-project", run_id="previous-run", request_id="previous-request")
+ current = _task("current", headers={"X-Request-ID": "request-current"})
+ _send(task_prerun, current)
+ assert get_contextvars() == {
+ "celery_task_id": "current", "celery_task_name": current.name,
+ "celery_retry": 0, "request_id": "request-current",
+ }
+ _send(task_postrun, current, state="SUCCESS")
+
+
+@pytest.mark.parametrize("invalid", ["bad\nrequest", "bad request", "x" * 129, {"secret": "value"}])
+def test_only_well_formed_allowlisted_correlation_headers_are_bound(invalid):
+ current = _task("current", headers={
+ "request_id": invalid,
+ "correlation_id": invalid,
+ "authorization": "Bearer never-bind-this",
+ "project_id": "untrusted-project",
+ "context": {"project_id": "also-untrusted"},
+ })
+ _send(task_prerun, current)
+ assert get_contextvars() == {
+ "celery_task_id": "current", "celery_task_name": current.name, "celery_retry": 0,
+ }
+ _send(task_postrun, current, state="SUCCESS")
+
+
+def test_task_helper_enriches_canonical_context_without_overwriting_it():
+ current = _task("current", headers={"request_id": "request-current"}, retries=2,
+ correlation_id="message-current")
+ _send(task_prerun, current)
+ _bind_task_context(current, project_id="project-current", run_id="run-current",
+ celery_task_id="incorrect", celery_retry=99)
+ assert get_contextvars() == {
+ "celery_task_id": "current", "celery_task_name": current.name, "celery_retry": 2,
+ "request_id": "request-current", "correlation_id": "message-current",
+ "project_id": "project-current", "run_id": "run-current",
+ }
+ _send(task_postrun, current, state="SUCCESS")
+
+
+@pytest.mark.parametrize("state", ["SUCCESS", "FAILURE", "RETRY"])
+def test_real_eager_execution_runs_signals_and_restores_its_callers_context(state):
+ snapshots = []
+ task_name = f"tests.context_probe_{state.lower()}"
+
+ @worker.celery_app.task(bind=True, name=task_name)
+ def probe(self):
+ _bind_task_context(self, project_id="project-current")
+ snapshots.append(get_contextvars())
+ if state == "FAILURE":
+ raise ValueError("synthetic failure")
+ if state == "RETRY":
+ raise Retry(exc=RuntimeError("synthetic retry"))
+ return "done"
+
+ parent = {"request_id": "request-parent", "path": "/parent"}
+ bind_contextvars(**parent)
+ try:
+ result = probe.apply(task_id="current", headers={"request_id": "request-current"}, throw=False)
+ assert result.state == state
+ assert snapshots == [{
+ "celery_task_id": "current", "celery_task_name": task_name, "celery_retry": 0,
+ "request_id": "request-current", "project_id": "project-current",
+ }]
+ assert get_contextvars() == parent
+ finally:
+ worker.celery_app.tasks.pop(task_name, None)
diff --git a/backend/tests/services/test_agent_operational_metrics.py b/backend/tests/services/test_agent_operational_metrics.py
index 28e4941bc..a247bd84a 100644
--- a/backend/tests/services/test_agent_operational_metrics.py
+++ b/backend/tests/services/test_agent_operational_metrics.py
@@ -136,6 +136,7 @@ async def test_pending_review_age_alert_fires_and_clears(monkeypatch):
async def test_scrape_wrapper_refreshes_agent_metrics(monkeypatch):
from app import bootstrap
from app.services import agent_operational_metrics
+ from app.services import downstream_operational_metrics
queue_refresh = MagicMock()
agent_refresh = MagicMock()
@@ -150,6 +151,10 @@ async def _agent_refresh():
agent_operational_metrics, "refresh_agent_operational_metrics", _agent_refresh
)
monkeypatch.setattr(bootstrap, "_refresh_celery_queue_depths", _queue_refresh)
+ from unittest.mock import AsyncMock
+ monkeypatch.setattr(
+ downstream_operational_metrics, "refresh_downstream_operational_metrics", AsyncMock(return_value=True)
+ )
class _Route:
path = "/metrics"
diff --git a/backend/tests/services/test_shadow_pair_service.py b/backend/tests/services/test_shadow_pair_service.py
index fe3ed74e5..b014e0d86 100644
--- a/backend/tests/services/test_shadow_pair_service.py
+++ b/backend/tests/services/test_shadow_pair_service.py
@@ -153,7 +153,7 @@ async def test_outputs_are_re_sanitized_on_read_and_pending_rows_carry_their_exp
created = datetime(2026, 10, 20, 8, 30, tzinfo=timezone.utc)
stored = _pair(
project_id=project, sample_key="root_cause:not-a-uuid", created_at=created,
- incumbent={"root_cause_summary": "Login used token=Qw3rTy9Uiop1 from the vault", "failure_category": "PRODUCT_BUG"},
+ incumbent={"root_cause_summary": "Login used token=Qw3rTy9Uiop1 from the vault", "failure_category": "PRODUCT_BUG"}, # gitleaks:allow -- synthetic test credential, never production authority
candidate={"failure_category": "FLAKY", "api_key": "Zx81Lm02Pq"},
)
db = _Session(_Result([(stored, 1, None)]), _Result([(1, True)]))
@@ -304,7 +304,7 @@ async def test_expiry_deletes_pending_pairs_older_than_thirty_days_from_now():
async def test_the_labelled_corpus_keeps_verdicts_only_and_re_sanitizes():
project = uuid.uuid4()
human = _pair(project_id=project, status="human_labelled", label={"verdict": "candidate", "source": "human"},
- incumbent={"summary": "token=Ab12Cd34Ef56"})
+ incumbent={"summary": "token=Ab12Cd34Ef56"}) # gitleaks:allow -- synthetic test credential, never production authority
broken = _pair(project_id=project, status="golden_match", label={"source": "feedback"})
db = _Session(_Result([human, broken]))
diff --git a/backend/tests/services/test_tier_comparison_service.py b/backend/tests/services/test_tier_comparison_service.py
index e4a240d8e..7f3ad7365 100644
--- a/backend/tests/services/test_tier_comparison_service.py
+++ b/backend/tests/services/test_tier_comparison_service.py
@@ -443,7 +443,7 @@ async def test_store_shadow_pair_sanitizes_both_outputs_before_the_insert():
sample_key="summary:run-a1",
incumbent_tier="llm",
candidate_tier="slm",
- incumbent_output={"summary": "Retry with token=Zx9Yw8Vu7Ts6", "x": 1},
+ incumbent_output={"summary": "Retry with token=Zx9Yw8Vu7Ts6", "x": 1}, # gitleaks:allow -- synthetic test credential, never production authority
candidate_output={"x": 1},
incumbent_tokens=3,
candidate_tokens=2,
diff --git a/backend/tests/test_agent_invocation_idempotency.py b/backend/tests/test_agent_invocation_idempotency.py
index 924256c0f..97f189f6b 100644
--- a/backend/tests/test_agent_invocation_idempotency.py
+++ b/backend/tests/test_agent_invocation_idempotency.py
@@ -43,7 +43,7 @@ def test_the_fingerprint_ignores_key_order_and_covers_project_and_input():
def test_the_lock_key_is_scoped_by_user_and_project_and_hides_the_client_key():
- key = "018f3c2e-7b1a-7c1d-9e4f-2a6b8c0d1e2f"
+ key = "018f3c2e-7b1a-7c1d-9e4f-2a6b8c0d1e2f" # gitleaks:allow -- synthetic test credential, never production authority
a = idem.lock_key("user-a", "project-1", "agent.summary.v1", key)
assert key not in a
assert a != idem.lock_key("user-b", "project-1", "agent.summary.v1", key)
@@ -117,7 +117,7 @@ async def test_the_lock_degrades_to_unavailable_when_redis_is_down(monkeypatch):
# -- the route -------------------------------------------------------------------------------
-KEY = "018f3c2e-7b1a-7c1d-9e4f-2a6b8c0d1e2f"
+KEY = "018f3c2e-7b1a-7c1d-9e4f-2a6b8c0d1e2f" # gitleaks:allow -- synthetic test credential, never production authority
class _Result:
diff --git a/backend/tests/test_agent_reliability.py b/backend/tests/test_agent_reliability.py
index a39d38687..c1029a0e2 100644
--- a/backend/tests/test_agent_reliability.py
+++ b/backend/tests/test_agent_reliability.py
@@ -189,13 +189,13 @@ def test_flaky_history_classification(self):
class TestPromptRedaction:
def test_bearer_token_redacted(self):
- text = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"
+ text = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U" # gitleaks:allow -- synthetic test credential, never production authority
result = redact_text(text)
assert "eyJ" not in result
assert "[REDACTED" in result
def test_api_key_redacted(self):
- text = "api_key=sk_live_abcdef1234567890abcdef"
+ text = "api_key=sk_live_abcdef1234567890abcdef" # gitleaks:allow -- synthetic test credential, never production authority
result = redact_text(text)
assert "sk_live" not in result
assert "[REDACTED]" in result
@@ -211,7 +211,7 @@ def test_connection_string_redacted(self):
assert "secretpassword" not in result
def test_jwt_redacted(self):
- jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
+ jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" # gitleaks:allow -- synthetic test credential, never production authority
result = redact_text(jwt)
assert "eyJ" not in result
@@ -444,7 +444,7 @@ def test_bearer_in_evidence_excerpt_redacted(self):
assert "eyJ" not in result
def test_api_key_in_config_redacted(self):
- config = "api_key=sk_live_abcdef1234567890abcdef"
+ config = "api_key=sk_live_abcdef1234567890abcdef" # gitleaks:allow -- synthetic test credential, never production authority
result = redact_text(config)
assert "sk_live" not in result
diff --git a/backend/tests/test_api_key_auth.py b/backend/tests/test_api_key_auth.py
index aabf8b821..ee42369f2 100644
--- a/backend/tests/test_api_key_auth.py
+++ b/backend/tests/test_api_key_auth.py
@@ -64,7 +64,7 @@ def test_optional_oauth2_scheme_exists(self):
class TestApiKeyHashLogic:
def test_sha256_hash_matches(self):
"""Verify the hashing logic matches what the API key endpoint stores."""
- raw_key = "qai_test_key_12345678"
+ raw_key = "qai_test_key_12345678" # gitleaks:allow -- synthetic test credential, never production authority
expected_hash = hashlib.sha256(raw_key.encode()).hexdigest()
assert len(expected_hash) == 64 # SHA-256 hex digest
diff --git a/backend/tests/test_bulk_trigger_job.py b/backend/tests/test_bulk_trigger_job.py
index 1731c4e63..9668f7078 100644
--- a/backend/tests/test_bulk_trigger_job.py
+++ b/backend/tests/test_bulk_trigger_job.py
@@ -230,7 +230,7 @@ async def test_a_replayed_client_token_answers_the_first_job_and_queues_nothing(
rows = _rows(2)
redis = FakeRedis()
user = _user()
- payload = agents_router.BulkTriggerRequest(run_ids=[r[0] for r in rows], client_token="tok_12345678")
+ payload = agents_router.BulkTriggerRequest(run_ids=[r[0] for r in rows], client_token="tok_12345678") # gitleaks:allow -- synthetic test credential, never production authority
first, first_calls, _record, _ = await _bulk(payload, _Session(rows), redis=redis, user=user)
assert len(first_calls) == 2 and first.tracking is True
diff --git a/backend/tests/test_cluster_epic_routes.py b/backend/tests/test_cluster_epic_routes.py
index 00e370bd2..8ceda8b0c 100644
--- a/backend/tests/test_cluster_epic_routes.py
+++ b/backend/tests/test_cluster_epic_routes.py
@@ -26,7 +26,7 @@
from app.services import cluster_epic_service as ces # noqa: E402
PROJECT = uuid.UUID("36a00000-0000-4000-8000-0000000000aa")
-KEY = "0123456789abcdef0123456789abcdef"
+KEY = "0123456789abcdef0123456789abcdef" # gitleaks:allow -- synthetic test credential, never production authority
BASE = f"/api/v1/projects/{PROJECT}/systemic-clusters"
@@ -155,7 +155,7 @@ async def test_a_stored_epic_answers_200_created_false(calls):
assert (call["jira_project_key"], call["summary"], call["confirm_not_filed"]) == (None, None, False)
-@pytest.mark.parametrize("bad", ["NOT-A-KEY", "0123456789ABCDEF0123456789ABCDEF", "0123456789abcdef"])
+@pytest.mark.parametrize("bad", ["NOT-A-KEY", "0123456789ABCDEF0123456789ABCDEF", "0123456789abcdef"]) # gitleaks:allow -- synthetic test credential, never production authority
async def test_a_malformed_membership_key_is_refused_before_the_service(calls, bad):
async with _client(_Session(), _user("ADMIN")) as client:
post = await client.post(f"{BASE}/{bad}/epic", json={})
diff --git a/backend/tests/test_cluster_epic_service.py b/backend/tests/test_cluster_epic_service.py
index ec6554257..86172eb01 100644
--- a/backend/tests/test_cluster_epic_service.py
+++ b/backend/tests/test_cluster_epic_service.py
@@ -25,7 +25,7 @@
from tests.fakes.fake_integrations import adf_problems
PID = uuid.UUID("36a00000-0000-4000-8000-000000000003")
-KEY = "0123456789abcdef0123456789abcdef"
+KEY = "0123456789abcdef0123456789abcdef" # gitleaks:allow -- synthetic test credential, never production authority
CFG = {"enabled": True, "domain": "example.atlassian.net", "email": "bot@example.com", "api_token": "t",
"default_project_key": "DEF"}
ACTOR = SimpleNamespace(id=uuid.uuid4(), username="qa.eng", full_name="Qa Eng", role="QA_ENGINEER")
diff --git a/backend/tests/test_compliance_pack_routes_w11.py b/backend/tests/test_compliance_pack_routes_w11.py
index 050498086..f2ff86b19 100644
--- a/backend/tests/test_compliance_pack_routes_w11.py
+++ b/backend/tests/test_compliance_pack_routes_w11.py
@@ -343,7 +343,7 @@ async def test_the_signing_keys_read_writes_nothing_and_creates_no_key(sqlite):
assert not any(s.lstrip().upper().startswith(("INSERT", "UPDATE", "DELETE")) for s in sqlite.statements)
-@pytest.mark.parametrize("bad", ["k-XYZ", "k-0123456789abcde", "key_1", "k-0123456789ABCDEF"])
+@pytest.mark.parametrize("bad", ["k-XYZ", "k-0123456789abcde", "key_1", "k-0123456789ABCDEF"]) # gitleaks:allow -- synthetic test credential, never production authority
async def test_a_pem_id_that_is_not_a_key_id_is_a_404_without_a_statement(sqlite, bad):
async with _client(sqlite, _user(UserRole.VIEWER), []) as client:
response = await client.get(f"/api/v1/compliance-packs/signing-keys/{bad}/pem")
diff --git a/backend/tests/test_embedding_generation_task.py b/backend/tests/test_embedding_generation_task.py
index 405fa7156..861f3f57d 100644
--- a/backend/tests/test_embedding_generation_task.py
+++ b/backend/tests/test_embedding_generation_task.py
@@ -320,7 +320,7 @@ def test_a_stale_fence_is_superseded_and_touches_nothing(world):
def test_a_failure_leaves_the_active_generation_and_records_a_sentence(world):
world.state = building(OLLAMA)
- world.build_result = ConnectionError("http://gpu-box.internal:11434 refused; api_key=sk-live-abc123")
+ world.build_result = ConnectionError("http://gpu-box.internal:11434 refused; api_key=sk-live-abc123") # gitleaks:allow -- synthetic test credential, never production authority
failed = counter(metrics.embedding_generation_builds_total, outcome="failed")
outcome = tasks.rebuild_embedding_generation.run(OLLAMA.tag, 3)
diff --git a/backend/tests/test_evidence_confidence.py b/backend/tests/test_evidence_confidence.py
index 824044db1..19808a1b7 100644
--- a/backend/tests/test_evidence_confidence.py
+++ b/backend/tests/test_evidence_confidence.py
@@ -131,7 +131,7 @@ def test_evidenceref_contribution_coercion_and_clamp():
def test_excerpt_redacts_email_ip_and_bearer_token():
raw_email = "john.doe@example.com"
raw_ip = "192.168.1.100"
- raw_token = "abcdefghij1234567890XYZ"
+ raw_token = "abcdefghij1234567890XYZ" # gitleaks:allow -- synthetic test credential, never production authority
excerpt = (
f"Contact {raw_email} at {raw_ip} with Bearer {raw_token} to authorize"
)
diff --git a/backend/tests/test_global_search.py b/backend/tests/test_global_search.py
index 23d1ffd5a..13175d50b 100644
--- a/backend/tests/test_global_search.py
+++ b/backend/tests/test_global_search.py
@@ -140,7 +140,7 @@ def test_empty_response(self):
def test_single_entity_type_response(self):
resp = GlobalSearchResponse(
items=[
- GlobalSearchResult(entity_type="suite", entity_id="s1", title="api-tests", navigation_url="/cov"),
+ GlobalSearchResult(entity_type="suite", entity_id="s1", title="api-tests", navigation_url="/cov"), # gitleaks:allow -- synthetic test credential, never production authority
GlobalSearchResult(entity_type="suite", entity_id="s2", title="ui-tests", navigation_url="/cov"),
],
total=2,
diff --git a/backend/tests/test_http_exchange_redaction.py b/backend/tests/test_http_exchange_redaction.py
index 155ae9eae..67607c83a 100644
--- a/backend/tests/test_http_exchange_redaction.py
+++ b/backend/tests/test_http_exchange_redaction.py
@@ -26,7 +26,7 @@
#: Fragments of every secret sample in the vector inputs (non-hex: each carries a w / s / k … letter).
RAW_FRAGMENTS = (
"eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9", "c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x", "dzIzZDpzYW1wbGUtcGFzcw",
- "w23dSampleSessionValue", "w23dcsrf", "sid=w23dsid", "tlk_w23d_sample_key_", "cHJveHk6dzIzZFByb3h5UGFzcw",
+ "w23dSampleSessionValue", "w23dcsrf", "sid=w23dsid", "tlk_w23d_sample_key_", "cHJveHk6dzIzZFByb3h5UGFzcw", # gitleaks:allow -- synthetic test credential, never production authority
"w23dSampleSessionToken", "QxZkLmNoPqRsTuVwXy", "W23DSAMPLEKEYQZX", "w23dCustomSecretValue",
"w23dServicePass", "w23dSamplePass", "w23dClientSecretValue", "w23dApiKeyValue", "w23dGithubValue",
"w23d.sample@example.test", "w23dSampleAccessToken123", "w23dsig", "samplepass", "w23dBareUserinfo",
diff --git a/backend/tests/test_http_exchange_store.py b/backend/tests/test_http_exchange_store.py
index d8c663df7..21dcfeac9 100644
--- a/backend/tests/test_http_exchange_store.py
+++ b/backend/tests/test_http_exchange_store.py
@@ -20,7 +20,7 @@
PROJECT = "project-alpha"
RUN = "run-alpha"
-BEARER = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9.c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x"
+BEARER = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9.c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x" # gitleaks:allow -- synthetic test credential, never production authority
class MongoDown(Exception):
diff --git a/backend/tests/test_phase4_safety.py b/backend/tests/test_phase4_safety.py
index 2ea261f40..caab15a94 100644
--- a/backend/tests/test_phase4_safety.py
+++ b/backend/tests/test_phase4_safety.py
@@ -83,7 +83,7 @@ def test_service_name_length_limit(self):
assert len(result) <= 128
def test_error_message_redacts_bearer_token(self):
- msg = "Auth failed: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0.signature123"
+ msg = "Auth failed: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIn0.signature123" # gitleaks:allow -- synthetic test credential, never production authority
result = sanitize_error_message(msg)
assert "eyJhbGciOiJIUzI1NiJ9" not in result
assert "[REDACTED" in result
@@ -95,9 +95,9 @@ def test_error_message_redacts_password(self):
assert "[REDACTED]" in result
def test_error_message_redacts_api_key(self):
- msg = "Request failed, api_key=sk_live_abc123xyz456 was rejected"
+ msg = "Request failed, api_key=sk_live_abc123xyz456 was rejected" # gitleaks:allow -- synthetic test credential, never production authority
result = sanitize_error_message(msg)
- assert "sk_live_abc123xyz456" not in result
+ assert "sk_live_abc123xyz456" not in result # gitleaks:allow -- synthetic test credential, never production authority
assert "[REDACTED]" in result
def test_stack_trace_redacts_connection_string(self):
@@ -149,7 +149,7 @@ def test_query_param_length_limit(self):
def test_jwt_redaction(self):
# JWT embedded without a "token=" prefix — pure JWT pattern match
- msg = "Decoded eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.validSignature in payload"
+ msg = "Decoded eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.validSignature in payload" # gitleaks:allow -- synthetic test credential, never production authority
result = sanitize_error_message(msg)
assert "eyJhbGciOiJSUzI1NiJ9" not in result
assert "[REDACTED" in result
diff --git a/backend/tests/test_privacy_redaction.py b/backend/tests/test_privacy_redaction.py
index 24b1e19dd..48db29bfe 100644
--- a/backend/tests/test_privacy_redaction.py
+++ b/backend/tests/test_privacy_redaction.py
@@ -127,7 +127,7 @@ def test_bearer_token(self):
assert "eyJ" not in result
def test_api_key(self):
- result = redact_text("api_key=sk_live_abcdefghijklmnop")
+ result = redact_text("api_key=sk_live_abcdefghijklmnop") # gitleaks:allow -- synthetic test credential, never production authority
assert "sk_live" not in result
def test_password(self):
diff --git a/backend/tests/test_prometheus_settings.py b/backend/tests/test_prometheus_settings.py
index a9268b344..ce2b75e5b 100644
--- a/backend/tests/test_prometheus_settings.py
+++ b/backend/tests/test_prometheus_settings.py
@@ -244,7 +244,7 @@ def _probe_cfg(**overrides) -> dict:
async def test_the_probe_answers_healthy_auth_error_down_and_skipped(world, monkeypatch):
healthy = await integration_probe_service.probe_prometheus(_probe_cfg())
assert (healthy.status, healthy.message) == ("healthy", "Prometheus API reachable")
- refused = await integration_probe_service.probe_prometheus(_probe_cfg(prometheus_bearer_token="prom_w23dWrongQz"))
+ refused = await integration_probe_service.probe_prometheus(_probe_cfg(prometheus_bearer_token="prom_w23dWrongQz")) # gitleaks:allow -- synthetic test credential, never production authority
assert refused.status == "auth_error"
blocked = await integration_probe_service.probe_prometheus(_probe_cfg(prometheus_base_url="http://127.0.0.1:9090"))
assert (blocked.status, blocked.message) == ("down", "Target host is not allowed (blocked_target:127.0.0.1)")
diff --git a/backend/tests/test_rag_services.py b/backend/tests/test_rag_services.py
index e2c56391f..1f9f93f99 100644
--- a/backend/tests/test_rag_services.py
+++ b/backend/tests/test_rag_services.py
@@ -1134,7 +1134,7 @@ async def test_check_batch_staleness_marks_only_changed_citations(self):
class TestRedactionEdgeCases:
def test_redact_jwt_token(self):
from app.services.rag_redaction_service import redact_prompt
- text = "Token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U"
+ text = "Token: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U" # gitleaks:allow -- synthetic test credential, never production authority
result, was_redacted = redact_prompt(text)
assert was_redacted is True
assert "eyJ" not in result
diff --git a/backend/tests/test_run_context_ingest_paths.py b/backend/tests/test_run_context_ingest_paths.py
index 42b07fe5b..65661be7c 100644
--- a/backend/tests/test_run_context_ingest_paths.py
+++ b/backend/tests/test_run_context_ingest_paths.py
@@ -161,10 +161,10 @@ async def _open(*_a, **_kw):
state["real_file_task"] = tasks.ingest_uploaded_file
state["real_batch_task"] = tasks.ingest_uploaded_results
file_task = MagicMock()
- file_task.apply_async = lambda *, kwargs, task_id: state["file_kwargs"].append(kwargs) or SimpleNamespace(id=task_id)
+ file_task.apply_async = lambda *, kwargs, task_id, **_options: state["file_kwargs"].append(kwargs) or SimpleNamespace(id=task_id)
batch_task = MagicMock()
batch_task.apply_async = (
- lambda *, kwargs, task_id: state["batch_kwargs"].append(kwargs) or SimpleNamespace(id=task_id)
+ lambda *, kwargs, task_id, **_options: state["batch_kwargs"].append(kwargs) or SimpleNamespace(id=task_id)
)
monkeypatch.setattr("app.services.ingestion_backpressure.enforce_redis_memory_backpressure", _open)
monkeypatch.setattr("app.services.ingestion_rate_limit.enforce_ingest_rate_limit", _open)
diff --git a/client/examples/python/http_capture_demo/test_products.py b/client/examples/python/http_capture_demo/test_products.py
index ef1f06b2d..03fc193bf 100644
--- a/client/examples/python/http_capture_demo/test_products.py
+++ b/client/examples/python/http_capture_demo/test_products.py
@@ -29,7 +29,7 @@
API = "https://products.demo.test"
#: A sample bearer value shaped like a JWT -- never a real credential.
-SAMPLE_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkZW1vLXVzZXIifQ.ZGVtby1zaWduYXR1cmUtdmFsdWU"
+SAMPLE_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkZW1vLXVzZXIifQ.ZGVtby1zaWduYXR1cmUtdmFsdWU" # gitleaks:allow -- synthetic test credential, never production authority
CATALOGUE = {7: {"id": 7, "name": "Desk lamp", "price": 24.5, "currency": "EUR", "stock": 12}}
diff --git a/client/java/src/test/java/io/testlookup/restassured/TestLookupRestAssuredFilterTest.java b/client/java/src/test/java/io/testlookup/restassured/TestLookupRestAssuredFilterTest.java
index 3abbc3a5c..855079966 100644
--- a/client/java/src/test/java/io/testlookup/restassured/TestLookupRestAssuredFilterTest.java
+++ b/client/java/src/test/java/io/testlookup/restassured/TestLookupRestAssuredFilterTest.java
@@ -53,7 +53,7 @@
class TestLookupRestAssuredFilterTest {
/** Non-hex, so no uuid or hash in a request can contain it by chance. */
- static final String SECRET = "w32bQzSecretKx";
+ static final String SECRET = "w32bQzSecretKx"; // gitleaks:allow -- synthetic test credential, never production authority
/** The fake's base URL, read by the sample classes. */
static volatile String target;
diff --git a/client/js/tests/auth-and-config.test.mjs b/client/js/tests/auth-and-config.test.mjs
index 305375383..b2ca95527 100644
--- a/client/js/tests/auth-and-config.test.mjs
+++ b/client/js/tests/auth-and-config.test.mjs
@@ -50,12 +50,12 @@ test('a qai_ key passed as token is still sent as X-API-Key', async () => {
})
test('a JWT is sent as Bearer', async () => {
- const [create] = await openAndClose({ token: 'eyJhbGciOiJIUzI1NiJ9.e30.sig' })
+ const [create] = await openAndClose({ token: 'eyJhbGciOiJIUzI1NiJ9.e30.sig' }) // gitleaks:allow -- synthetic test credential, never production authority
assert.deepEqual(authOf(create), { apiKey: undefined, authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.e30.sig' })
})
test('the apiKey wins when both are given', async () => {
- const [create] = await openAndClose({ token: 'eyJhbGciOiJIUzI1NiJ9.e30.sig', apiKey: FAKE_KEY })
+ const [create] = await openAndClose({ token: 'eyJhbGciOiJIUzI1NiJ9.e30.sig', apiKey: FAKE_KEY }) // gitleaks:allow -- synthetic test credential, never production authority
assert.equal(authOf(create).apiKey, FAKE_KEY)
})
@@ -162,7 +162,7 @@ for (const [name, sessionCreate] of [['Jest', jestSessionCreate], ['Mocha', moch
test('a token in the environment beats an API key left in the file', async () => {
const restore = inProjectDir(PROPERTIES.replace(FAKE_KEY, 'qai_REPLACE_ME'))
try {
- process.env.TESTLOOKUP_TOKEN = 'eyJhbGciOiJIUzI1NiJ9.e30.env'
+ process.env.TESTLOOKUP_TOKEN = 'eyJhbGciOiJIUzI1NiJ9.e30.env' // gitleaks:allow -- synthetic test credential, never production authority
const create = await jestSessionCreate()
assert.equal(create.headers.Authorization, 'Bearer eyJhbGciOiJIUzI1NiJ9.e30.env')
assert.equal(create.headers['X-API-Key'], undefined)
@@ -178,7 +178,7 @@ test('an explicit token option beats an API key from the environment', async ()
process.env.TESTLOOKUP_API_KEY = FAKE_KEY
const handlers = {}
const runner = { on(event, fn) { handlers[event] = fn; return this } }
- const reporter = new MochaReporter(runner, { reporterOptions: { testlookupToken: 'eyJhbGciOiJIUzI1NiJ9.e30.opt' } })
+ const reporter = new MochaReporter(runner, { reporterOptions: { testlookupToken: 'eyJhbGciOiJIUzI1NiJ9.e30.opt' } }) // gitleaks:allow -- synthetic test credential, never production authority
handlers.start()
await new Promise((resolve) => reporter.done(0, resolve))
assert.equal(server.sessionCreate().headers.Authorization, 'Bearer eyJhbGciOiJIUzI1NiJ9.e30.opt')
diff --git a/client/tests/test_http_capture.py b/client/tests/test_http_capture.py
index 4a33cba5c..f01502fd2 100644
--- a/client/tests/test_http_capture.py
+++ b/client/tests/test_http_capture.py
@@ -27,7 +27,7 @@
#: The cross-language specification (G-A): every case runs through the SDK port below.
VECTORS_PATH = Path(__file__).resolve().parents[2] / "sdk-vectors" / "http_exchange.json"
-JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9.c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x"
+JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ3MjNkLXNhbXBsZSJ9.c2lnbmF0dXJlLXNhbXBsZS12YWx1ZS0x" # gitleaks:allow -- synthetic test credential, never production authority
PAT = "ghp_" + "w23dSamplePatValueQxZkLmNoPqRsTuVwXy"[:36]
API = "https://api.example.test"
diff --git a/docs/architecture/codebase-map.md b/docs/architecture/codebase-map.md
index 24f004ef0..0e2b10271 100644
--- a/docs/architecture/codebase-map.md
+++ b/docs/architecture/codebase-map.md
@@ -49,7 +49,7 @@ The generated [endpoint index](../reference/api-index.md), [data dictionary](../
| Test management | `test_management_*`, `test_case_lifecycle_service`, `suite_*`, `duplicate_detection_service` | Managed cases, plans, strategies, canonical identity and reviews |
| Flaky/performance | `flaky_*`, `quarantine_*`, `perf_regression_service`, `performance_budgets` | Baselines, quarantine state, signals and coaching |
| Identity/settings | `mfa_service`, `sso_service`, `scim_service`, `refresh_token_service`, `feature_flags`, `secret_service` | Users, tokens, membership, project policies, audit |
-| External integrations | `connectors`, `jira_client`, GitHub/GitLab services, `notification`, `webhook_service` | Remote APIs, attempts/delivery audit and retry |
+| External integrations | `connectors`, `jira_client`, GitHub/GitLab services, `notification`, `webhook_service` | Remote APIs, attempts/delivery audit and retry |
| RAG/search | `knowledge_*`, `rag_*`, `search_*`, `semantic_search` | Source documents/chunks, vector index, generated drafts and provenance |
| Administration | `retention_service`, `run_deletion_service`, `deletion_job_service`, `storage_accounting_service` | Purge policy, tombstones, storage lifecycle and operational reports |
diff --git a/docs/maintainers/README.md b/docs/maintainers/README.md
index 7d50bacfd..316bec580 100644
--- a/docs/maintainers/README.md
+++ b/docs/maintainers/README.md
@@ -4,6 +4,8 @@
This section is for people who maintain TestLookup or take over an area of it: an onboarding order, an acceptance checklist for a new environment, where changes belong, and how the documentation itself is kept correct. Contribution mechanics (branches, tests, DCO sign-off, review) are in [CONTRIBUTING.md](../../CONTRIBUTING.md).
+The [observability delivery program](observability-delivery.md) tracks the epic/story implementation sequence, candidate behavior and remaining production acceptance.
+
Drafts for the public launch (starter issues, the 0.1.0 release notes, the social preview and the organisation profile), with the settings only the owner can change, are in [launch/](launch/README.md).
## Onboarding order
diff --git a/docs/maintainers/observability-delivery.md b/docs/maintainers/observability-delivery.md
new file mode 100644
index 000000000..c78f49fe3
--- /dev/null
+++ b/docs/maintainers/observability-delivery.md
@@ -0,0 +1,127 @@
+# Observability delivery program
+
+[Maintainer guide](README.md)
+
+This program extends the existing Prometheus, Grafana and OpenTelemetry foundation. Its scope is eight epics, 43 stories and 129 implementation/verification tasks. Story identifiers remain stable across iterations. A completed code change does not establish production acceptance.
+
+## Delivery and change tracking
+
+Use the single `feat/production-observability` branch for this program. Keep changes in signed commits by iteration; validate locally and push a reviewed batch when it is ready. Do not create a branch per story, dispatch workflows for status checks, or remove required CI checks to save Actions usage. Each iteration updates this page with affected stories, behavior, checks, remaining acceptance and commit history.
+
+Implementation baseline: `bc71694ca8fc91af2ab1fd72819e14ea3e66d540` on `main`. The earlier assessment baseline was `74fdb6b0c1c003c6d70350e8b4fa22a6686e1ac7`. Upstream authentication/MFA changes are included.
+
+Status meanings: **Open** is planned; **In progress** has partial implementation; **Verification** has a candidate implementation with local checks and outstanding acceptance. **Complete** requires the whole story, its dependencies and evidence in the claimed deployment profiles. No epic is complete.
+
+## Epic and story register
+
+| Epic | Capability | Iteration sequence |
+|---|---|---|
+| OBS-E01 | Safe correlated application telemetry | 1: privacy, errors, worker log context; 3: worker tracing and clients |
+| OBS-E02 | Reliable metric collection | 1: bounded reads, queue coverage and SQL outcomes; 2: producers, exporters and access |
+| OBS-E03 | Alerting and scheduled detection | 1: low-volume webhook and new outcome rules; 2: schedules, discovery and routing |
+| OBS-E04 | Durable log and trace platform | 2: profile contract; 3: collection, storage, offline and BYO profiles |
+| OBS-E05 | Durable operational and audit evidence | 2: event outbox/replay; 3: audit archive and retention |
+| OBS-E06 | Objectives and capacity | 2: SLIs and series budget; 4: measured objectives, burn rates and capacity |
+| OBS-E07 | DevSecOps and operational rollout gates | 1: scan authorization and semantic rule tests; 3-4: full signal, security and rollout |
+| OBS-E08 | Safe ingestion and worker lifecycle | 1: bounded publication, retention and readiness reset; 2: durable reconciliation |
+
+| Story | Outcome | Status |
+|---|---|---|
+| OBS-E01-S01 | Redact every exported span surface | Verification |
+| OBS-E01-S02 | Initialize tracing in every worker and scheduler role | Open |
+| OBS-E01-S03 | Propagate task traces and reset task log context | In progress |
+| OBS-E01-S04 | Transmit bounded browser telemetry using actual UTF-8 bytes | Verification |
+| OBS-E01-S05 | Preserve backend correlation IDs in MCP and CLI errors | Open |
+| OBS-E01-S06 | Instrument MCP operations without corrupting stdio | Open |
+| OBS-E01-S07 | Preserve correlation and sanitized logs for every unexpected API error | Verification |
+| OBS-E02-S01 | Bound dependency collection and expose freshness | Verification |
+| OBS-E02-S02 | Monitor every routed queue including agent children | In progress |
+| OBS-E02-S03 | Emit real SQLAlchemy pool saturation measurements | Open |
+| OBS-E02-S04 | Wire dependency and host exporters by deployment profile | Open |
+| OBS-E02-S05 | Make authenticated scrapes work in reference profiles | Open |
+| OBS-E02-S06 | Detect durable downstream failure independently of Celery success | In progress |
+| OBS-E03-S01 | Make weekly digest alerts reflect actual due work and delivery | Open |
+| OBS-E03-S02 | Detect low-volume terminal webhook failures correctly | Verification |
+| OBS-E03-S03 | Deliver routed firing and resolved notifications | Open |
+| OBS-E03-S04 | Observe durable expected-run and last-success state | Open |
+| OBS-E03-S05 | Detect missing targets and required telemetry | Open |
+| OBS-E03-S06 | Detect monitoring and notification path outages independently | Open |
+| OBS-E04-S01 | Define the production telemetry and ownership contract | Open |
+| OBS-E04-S02 | Deploy bounded and secure log/trace collection | Open |
+| OBS-E04-S03 | Provide central log search and working trace-to-log navigation | Open |
+| OBS-E04-S04 | Persist incident traces with explicit small-install and HA options | Open |
+| OBS-E04-S05 | Adapt and verify Kubernetes, K3s and OpenShift monitoring | Open |
+| OBS-E04-S06 | Package offline telemetry and document cloud/BYO adapters | Open |
+| OBS-E05-S01 | Persist failed pipeline event delivery with stable IDs | Open |
+| OBS-E05-S02 | Replay events idempotently and expose fleet health | Open |
+| OBS-E05-S03 | Protect operational audit history and archive integrity | Open |
+| OBS-E05-S04 | Retain security events without deleting SCIM authority evidence | Open |
+| OBS-E06-S01 | Define and emit durable journey success indicators | Open |
+| OBS-E06-S02 | Add scoped error budgets, burn alerts and runbooks | Open |
+| OBS-E06-S03 | Bound metric cardinality and installation scope | Open |
+| OBS-E06-S04 | Measure storage, sampling and resource limits | Open |
+| OBS-E07-S01 | Run semantic telemetry and mounted-configuration checks in CI | In progress |
+| OBS-E07-S02 | Verify the full signal path against a disposable stack | Open |
+| OBS-E07-S03 | Add useful application source security analysis | Open |
+| OBS-E07-S04 | Validate infrastructure security policy in CI | Open |
+| OBS-E07-S05 | Run authenticated dynamic security checks in isolation | Open |
+| OBS-E07-S06 | Verify every deployed role and rehearse production handoff | Open |
+| OBS-E07-S07 | Require same-SHA secret-scan success before publication and promotion | Verification |
+| OBS-E08-S01 | Keep upload publication off the API event loop | Verification |
+| OBS-E08-S02 | Preserve queued batch payloads after ambiguous publication | In progress |
+| OBS-E08-S03 | Clear stale worker readiness before replacement startup | In progress |
+
+## Iteration 1: critical correctness and signal foundations
+
+Candidate changes on the shared branch:
+
+| Stories | Change | Remaining acceptance |
+|---|---|---|
+| OBS-E01-S01 | Every configured trace exporter receives sanitized copies of attributes, events, exception/status text, names, resources, links and scope. Encoded JSON credentials are scrubbed; oversized text is omitted; unsafe spans fail closed. | Review candidate image sinks and configuration before expanding production tracing. |
+| OBS-E01-S03 | Worker task hooks bind validated request/correlation headers and canonical task identity, clear every task outcome and preserve caller context during eager execution. | Full producer W3C propagation and prefork process lifecycle evidence remain open. |
+| OBS-E01-S04 | Browser error batching uses serialized UTF-8 bytes and bounds messages, stacks, component data, URLs and user agents. | Browser transport acceptance with the candidate build. |
+| OBS-E01-S07 | Unexpected core API errors emit one correlated error log and return X-Request-ID while preserving response bodies; pre-routing shared-link paths are sanitized. | Candidate HTTP smoke, with production log access policy. |
+| OBS-E02-S01 | Concurrent collectors have finite foreground deadlines and one in-flight read per collector; failed/stale reads expose success, error and freshness signals. | Real dependency outage, cancellation and multiprocess fleet checks. |
+| OBS-E02-S02 | Redis queue-depth collection includes agent_children and concurrent reads. | Authoritative routing inventory and queue age/throughput coverage. |
+| OBS-E02-S06 | SQL outbox counts, age and status-specific overdue time expose business failures independently of Redis/Celery status. Unknown operation names use a bounded other bucket. Invalid lease state fails collection. | Real PostgreSQL/fleet evidence, historic-table query cost and authorized investigation/replay. |
+| OBS-E03-S02 | Webhook ratio uses its actual nonzero attempt rate; namespace/cluster grouping preserves low-volume failures. | Receiver delivery and profile routing are separate stories. |
+| OBS-E07-S01 | Semantic Prometheus fixtures cover changed rules; Kubernetes rules are generated from the same source. | Broader configuration, full-signal and CI acceptance remain open. |
+| OBS-E07-S07 | Publication and reusable release authorization require successful trusted same-SHA main-push secret-scan evidence, with bounded waiting and failed/missing evidence denied. Main pushes also scan every tracked candidate blob, independently of added history. | Hosted Actions permission/event validation. |
+| OBS-E08-S01/S02 | Upload publishing leaves the API event loop through a finite thread pool. Timeouts/cancellation retain capacity until the real publisher ends; ambiguous publication retains payload and polling identity, exposed in documented CORS-readable response headers. | Durable initial-upload reconciliation, orphan cleanup and HTTP retry idempotency remain open. Thread timeouts cannot terminate a running broker call. |
+| OBS-E08-S03 | Readiness sentinel is removed at worker startup and shutdown so reused volumes cannot inherit a ready marker after a crash. | Container/prefork crash-and-restart acceptance. |
+
+The new collection and outbox alerts retain target freshness and use maximum values for replicated shared SQL state instead of adding duplicate observations. Future retry deadlines do not alert as overdue. Completed rows are not overdue.
+
+### Verification record
+
+- Focused backend behavioral suites: 371 passed, covering upload admission, accepted-then-error retention, event-loop responsiveness, saturation, cancellation, authorization, worker context/readiness, core errors and metric failure/recovery.
+- Trace serialization was exercised with Console JSON and OTLP encoding on Python 3.14.10 / OpenTelemetry SDK 1.45.2 in an isolated temporary process: 68 passed; one Kubernetes-manifest lookup was skipped because the temporary test tree contains no manifests. No live application code or configuration was replaced.
+- Frontend error-reporting suite: 18 passed; TypeScript, production build and bundle budget checks passed. Full browser journeys and production deployment acceptance remain open.
+- Release authorization uses mocked GitHub evidence tests; no workflow was dispatched or publication performed for this validation.
+- Upload publication failure tests also passed in an isolated Python 3.14.10 / Celery 5.7.0 process: 14 passed against fake broker, storage and authorization boundaries. No live uploads were submitted.
+
+The complete candidate-tree scan reads raw Git blobs in bounded batches and verifies their inventory, type, size and hashes before scanning a temporary snapshot. It scans tracked symlink targets as text and rejects unsupported gitlinks. Export attributes, checkout encodings and filters do not change the scanned bytes. Working-tree secrets and untracked files do not enter the snapshot. Existing synthetic credential fixtures use narrow, explained line annotations or exact path/value/detector exceptions; the former broad SDK-vector directory exemption is removed. Regression fixtures check that other credentials in those files still fail.
+
+### Running semantic alert verification
+
+The existing `backend-test` CI job downloads official Prometheus 3.16.0, verifies the reviewed archive SHA-256 before extraction, and runs the source rules and semantic fixtures. It adds no job or matrix. The version matches the reference Compose monitoring profile; update the version and reviewed official checksum together when that profile changes.
+
+With the matching `promtool` installed, run from the repository root:
+
+```sh
+cd infra/monitoring/tests
+promtool check rules ../prometheus-rules/testlookup-alerts.yml
+promtool test rules operational-alerts.yml
+```
+
+Fixtures live in `infra/monitoring/tests/`, outside the production `rules/*.yml` mount. They exercise collection failure/freshness and recovery, same-target freshness filtering before shared-SQL `max`, replica/installation separation, retry deadlines and nonterminal states, strict thresholds, quiet/absent webhook traffic, low-volume failure, and recovery. They evaluate synthetic samples and send no notifications. This does not replace target discovery, collector integration or receiver-delivery acceptance. See [Prometheus rule testing](https://prometheus.io/docs/prometheus/latest/configuration/unit_testing_rules/) and the [official 3.16.0 release](https://github.com/prometheus/prometheus/releases/tag/v3.16.0).
+
+### Next iteration dependencies
+
+1. Establish deployment-profile collection, selector, receiver, authentication and retention contracts. Reuse an existing monitoring stack where it meets the contract.
+2. Wire missing dependency/pool instruments and scrape authentication; connect all required application targets/rules and exercise an authorized test receiver.
+3. Add durable event/replay evidence and scheduled due-state detection. Reconcile retained initial uploads without duplicate publication.
+4. Implement persistent logs/traces and fork-safe tracing, then measure journey SLIs, label budgets, capacity and burn-rate rules.
+5. Complete all-role signal/security/rollback gates before declaring production readiness.
+
+No production deployment or claim of enterprise readiness is represented by this iteration. Data retention, receivers, SLO targets and platform ownership must be explicit for each supported production profile.
diff --git a/docs/reference/api/ingest.md b/docs/reference/api/ingest.md
index a755fcc5e..85e8eafa2 100644
--- a/docs/reference/api/ingest.md
+++ b/docs/reference/api/ingest.md
@@ -14,7 +14,7 @@ The batch is dispatched to a Celery worker which creates the TestRun,
upserts test cases, runs post-ingestion tagging, and triggers the
AI analysis pipeline.
-Source: [backend/app/routers/ingest.py:91](../../../backend/app/routers/ingest.py#L91).
+Source: [backend/app/routers/ingest.py:141](../../../backend/app/routers/ingest.py#L141).
Dependency chain: `OAuth2PasswordBearer`, `get_api_key_context`, `get_current_user_or_api_key`, `get_db`.
@@ -28,7 +28,7 @@ Direct handler error branches (dependency/service errors can add others):
```python
HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='This API key is restricted to a different project')
-HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail='Upload could not be queued')
+HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail='Upload publisher is busy; try again later.', headers={'Retry-After': '1'})
HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail='Upload storage is temporarily unavailable')
```
@@ -87,6 +87,29 @@ References such as `#/components/schemas/...` resolve in [schemas](../schemas.md
}
},
"description": "Validation Error"
+ },
+ "503": {
+ "description": "Upload admission or queue confirmation unavailable. If Location and X-Upload-Task-ID are present, processing may still start: poll the existing upload before resubmitting.",
+ "headers": {
+ "Location": {
+ "description": "Existing upload status URL, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ },
+ "X-Upload-Run-ID": {
+ "description": "Existing run identifier, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ },
+ "X-Upload-Task-ID": {
+ "description": "Existing upload task identifier, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
},
"security": [
@@ -111,7 +134,7 @@ The Cypress and Playwright parsers are gated behind the ``cypress_ingest``
and ``playwright_ingest`` feature flags respectively — 503 is returned if
a disabled format is requested.
-Source: [backend/app/routers/ingest.py:379](../../../backend/app/routers/ingest.py#L379).
+Source: [backend/app/routers/ingest.py:438](../../../backend/app/routers/ingest.py#L438).
Dependency chain: `OAuth2PasswordBearer`, `get_api_key_context`, `get_current_user_or_api_key`, `get_db`.
@@ -128,7 +151,7 @@ HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"Unsupported form
HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail='This API key is restricted to a different project')
HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail='build_number must not be empty')
HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=exc.detail())
-HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail='Upload could not be queued')
+HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail='Upload publisher is busy; try again later.', headers={'Retry-After': '1'})
HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail='Upload storage is temporarily unavailable')
HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=f"{detected_format.title()} ingestion is disabled. Ask an admin to enable the '{flag_key}' feature flag.")
```
@@ -188,6 +211,29 @@ References such as `#/components/schemas/...` resolve in [schemas](../schemas.md
}
},
"description": "Validation Error"
+ },
+ "503": {
+ "description": "Upload admission or queue confirmation unavailable. If Location and X-Upload-Task-ID are present, processing may still start: poll the existing upload before resubmitting.",
+ "headers": {
+ "Location": {
+ "description": "Existing upload status URL, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ },
+ "X-Upload-Run-ID": {
+ "description": "Existing run identifier, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ },
+ "X-Upload-Task-ID": {
+ "description": "Existing upload task identifier, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
},
"security": [
@@ -208,7 +254,7 @@ Project-scoped: 404 if unknown/expired, 403 if the caller can't access the
run's project (so a leaked/guessed task_id can't reveal another tenant's
run).
-Source: [backend/app/routers/ingest.py:682](../../../backend/app/routers/ingest.py#L682).
+Source: [backend/app/routers/ingest.py:750](../../../backend/app/routers/ingest.py#L750).
Dependency chain: `OAuth2PasswordBearer`, `get_api_key_context`, `get_current_user_or_api_key`, `get_db`.
diff --git a/docs/reference/openapi.json b/docs/reference/openapi.json
index 492bd20f3..3a5a17382 100644
--- a/docs/reference/openapi.json
+++ b/docs/reference/openapi.json
@@ -68759,6 +68759,29 @@
}
},
"description": "Validation Error"
+ },
+ "503": {
+ "description": "Upload admission or queue confirmation unavailable. If Location and X-Upload-Task-ID are present, processing may still start: poll the existing upload before resubmitting.",
+ "headers": {
+ "Location": {
+ "description": "Existing upload status URL, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ },
+ "X-Upload-Run-ID": {
+ "description": "Existing run identifier, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ },
+ "X-Upload-Task-ID": {
+ "description": "Existing upload task identifier, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
},
"security": [
@@ -68824,6 +68847,29 @@
}
},
"description": "Validation Error"
+ },
+ "503": {
+ "description": "Upload admission or queue confirmation unavailable. If Location and X-Upload-Task-ID are present, processing may still start: poll the existing upload before resubmitting.",
+ "headers": {
+ "Location": {
+ "description": "Existing upload status URL, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ },
+ "X-Upload-Run-ID": {
+ "description": "Existing run identifier, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ },
+ "X-Upload-Task-ID": {
+ "description": "Existing upload task identifier, when dispatch is unconfirmed",
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
}
},
"security": [
diff --git a/docs/reference/worker-operations.md b/docs/reference/worker-operations.md
index 453417c69..452eb5a9e 100644
--- a/docs/reference/worker-operations.md
+++ b/docs/reference/worker-operations.md
@@ -50,7 +50,7 @@ True
## queue_delivery_probe
-[backend/app/worker/celery_app.py:52](../../backend/app/worker/celery_app.py#L52)
+[backend/app/worker/celery_app.py:54](../../backend/app/worker/celery_app.py#L54)
Return transport attribution for the release queue-consumption proof.
@@ -61,7 +61,7 @@ queue_delivery_probe(self, correlation_id: str)
## dispatch_run_completed_webhook
-[backend/app/worker/tasks.py:628](../../backend/app/worker/tasks.py#L628)
+[backend/app/worker/tasks.py:627](../../backend/app/worker/tasks.py#L627)
Persist and publish an idempotent run.completed webhook emission.
@@ -72,7 +72,7 @@ dispatch_run_completed_webhook(self, project_id: str, payload: dict)
## repost_pr_comment
-[backend/app/worker/tasks.py:699](../../backend/app/worker/tasks.py#L699)
+[backend/app/worker/tasks.py:698](../../backend/app/worker/tasks.py#L698)
Edit the run's GitHub PR marker comment with the reviewed AI labels.
@@ -83,7 +83,7 @@ repost_pr_comment(self, test_run_id: str, review_id: str)
## repost_mr_note
-[backend/app/worker/tasks.py:712](../../backend/app/worker/tasks.py#L712)
+[backend/app/worker/tasks.py:711](../../backend/app/worker/tasks.py#L711)
Edit the run's GitLab MR marker note with the reviewed AI labels.
@@ -94,7 +94,7 @@ repost_mr_note(self, test_run_id: str, review_id: str)
## persist_live_session
-[backend/app/worker/tasks.py:724](../../backend/app/worker/tasks.py#L724)
+[backend/app/worker/tasks.py:723](../../backend/app/worker/tasks.py#L723)
Persist a completed live execution session to PostgreSQL.
@@ -113,7 +113,7 @@ persist_live_session(self, run_id: str, project_id: str, build_number: str, clie
## ingest_test_run
-[backend/app/worker/tasks.py:1221](../../backend/app/worker/tasks.py#L1221)
+[backend/app/worker/tasks.py:1220](../../backend/app/worker/tasks.py#L1220)
Background task: parse Allure JSON + TestNG XML from MinIO and
upsert structured data into PostgreSQL + MongoDB.
@@ -133,7 +133,7 @@ ingest_test_run(self, sentinel_dict: dict | None=None, minio_prefix: str='', sen
## ingest_uploaded_results
-[backend/app/worker/tasks.py:1328](../../backend/app/worker/tasks.py#L1328)
+[backend/app/worker/tasks.py:1327](../../backend/app/worker/tasks.py#L1327)
Process a JSON batch of test results from POST /api/v1/ingest.
Creates a TestRun, upserts test cases, runs post-ingestion pipeline.
@@ -152,7 +152,7 @@ ingest_uploaded_results(self, run_id: str, payload: dict=None, user_id: str=None
## ingest_uploaded_file
-[backend/app/worker/tasks.py:1545](../../backend/app/worker/tasks.py#L1545)
+[backend/app/worker/tasks.py:1544](../../backend/app/worker/tasks.py#L1544)
Parse an uploaded test result file and ingest.
Supports JUnit XML, TestNG XML, and Allure JSON.
@@ -164,7 +164,7 @@ ingest_uploaded_file(self, run_id: str, file_name: str, file_format: str, projec
## run_live_test_analysis
-[backend/app/worker/tasks.py:2134](../../backend/app/worker/tasks.py#L2134)
+[backend/app/worker/tasks.py:2133](../../backend/app/worker/tasks.py#L2133)
Immediate root-cause analysis for a single test that failed during live execution.
Runs on the critical queue (priority=9) so results appear in the dashboard fast.
@@ -177,7 +177,7 @@ run_live_test_analysis(self, test_case_id: str, test_name: str, run_id: str, pro
## run_ai_analysis
-[backend/app/worker/tasks.py:2227](../../backend/app/worker/tasks.py#L2227)
+[backend/app/worker/tasks.py:2226](../../backend/app/worker/tasks.py#L2226)
Background task: run the LangChain ReAct agent for a single test case.
Used by the offline auto-analyzer. The LLM factory owns endpoint breaker state.
@@ -189,7 +189,7 @@ run_ai_analysis(self, test_case_id: str, test_name: str, **kwargs)
## dispatch_run_notifications
-[backend/app/worker/tasks.py:2274](../../backend/app/worker/tasks.py#L2274)
+[backend/app/worker/tasks.py:2273](../../backend/app/worker/tasks.py#L2273)
Background task: fan-out run-completion notifications to all subscribed users.
@@ -204,7 +204,7 @@ dispatch_run_notifications(self, project_id: str, run_id: str, build_number: str
## dispatch_transition_notifications
-[backend/app/worker/tasks.py:2330](../../backend/app/worker/tasks.py#L2330)
+[backend/app/worker/tasks.py:2329](../../backend/app/worker/tasks.py#L2329)
Background task: evaluate transition events (PMF US-7.1/US-7.2) for a
finalized run and send the batched, cluster-deduped notification.
@@ -226,7 +226,7 @@ dispatch_transition_notifications(self, run_id: str, run_ai: bool=True)
## run_agent_pipeline
-[backend/app/worker/tasks.py:2480](../../backend/app/worker/tasks.py#L2480)
+[backend/app/worker/tasks.py:2479](../../backend/app/worker/tasks.py#L2479)
Background task: run the full multi-agent LangGraph pipeline for a completed test run.
Stages: ingestion → anomaly detection → root-cause analysis → summary → triage
@@ -240,7 +240,7 @@ run_agent_pipeline(self, test_run_id: str, project_id: str, build_number: str, w
## rebuild_run_snapshot
-[backend/app/worker/tasks.py:2825](../../backend/app/worker/tasks.py#L2825)
+[backend/app/worker/tasks.py:2824](../../backend/app/worker/tasks.py#L2824)
Rebuild a run's intelligence snapshot after its pipeline invalidated it (W07 FAIL-04).
@@ -260,7 +260,7 @@ rebuild_run_snapshot(self, run_id: str)
## resume_agent_pipeline
-[backend/app/worker/tasks.py:2998](../../backend/app/worker/tasks.py#L2998)
+[backend/app/worker/tasks.py:2997](../../backend/app/worker/tasks.py#L2997)
Resume a failed / retry_wait / degraded pipeline under its existing id.
@@ -281,7 +281,7 @@ resume_agent_pipeline(self, pipeline_run_id: str, build_number: str='resume', ex
## run_agent_investigation
-[backend/app/worker/tasks.py:3037](../../backend/app/worker/tasks.py#L3037)
+[backend/app/worker/tasks.py:3036](../../backend/app/worker/tasks.py#L3036)
Background task: execute one hypothesis-loop investigation (AI-1).
@@ -299,7 +299,7 @@ run_agent_investigation(self, investigation_id: str)
## run_agent_child_investigation
-[backend/app/worker/tasks.py:3081](../../backend/app/worker/tasks.py#L3081)
+[backend/app/worker/tasks.py:3080](../../backend/app/worker/tasks.py#L3080)
Execute one ID-only, cluster-scoped child on the isolated queue.
@@ -310,7 +310,7 @@ run_agent_child_investigation(self, investigation_id: str)
## resume_agent_child_investigation
-[backend/app/worker/tasks.py:3116](../../backend/app/worker/tasks.py#L3116)
+[backend/app/worker/tasks.py:3115](../../backend/app/worker/tasks.py#L3115)
Resume a failed cluster child under its stable investigation identity.
@@ -321,7 +321,7 @@ resume_agent_child_investigation(self, investigation_id: str)
## relay_agent_child_dispatch_outbox
-[backend/app/worker/tasks.py:3141](../../backend/app/worker/tasks.py#L3141)
+[backend/app/worker/tasks.py:3140](../../backend/app/worker/tasks.py#L3140)
Recover pending/stale cluster-child dispatches from the PG outbox.
@@ -332,7 +332,7 @@ relay_agent_child_dispatch_outbox(self)
## process_decision_report_supersessions
-[backend/app/worker/tasks.py:3164](../../backend/app/worker/tasks.py#L3164)
+[backend/app/worker/tasks.py:3163](../../backend/app/worker/tasks.py#L3163)
Publish terminal child-enriched report versions from durable requests.
@@ -343,7 +343,7 @@ process_decision_report_supersessions(self)
## relay_agent_action_dispatch_outbox
-[backend/app/worker/tasks.py:3190](../../backend/app/worker/tasks.py#L3190)
+[backend/app/worker/tasks.py:3189](../../backend/app/worker/tasks.py#L3189)
Publish approved action IDs to the guarded action executor.
@@ -354,7 +354,7 @@ relay_agent_action_dispatch_outbox(self)
## relay_run_downstream_outbox
-[backend/app/worker/tasks.py:3214](../../backend/app/worker/tasks.py#L3214)
+[backend/app/worker/tasks.py:3213](../../backend/app/worker/tasks.py#L3213)
Publish durable post-ingestion intents whose retry time has arrived.
@@ -365,7 +365,7 @@ relay_run_downstream_outbox(self)
## relay_queued_criteria_deletions
-[backend/app/worker/tasks.py:3238](../../backend/app/worker/tasks.py#L3238)
+[backend/app/worker/tasks.py:3237](../../backend/app/worker/tasks.py#L3237)
Recover criteria deletions committed before broker publication.
@@ -376,7 +376,7 @@ relay_queued_criteria_deletions(self)
## recover_waiting_run_finalizations
-[backend/app/worker/tasks.py:3253](../../backend/app/worker/tasks.py#L3253)
+[backend/app/worker/tasks.py:3252](../../backend/app/worker/tasks.py#L3252)
Resume finalization after a worker died before opening its child gate.
@@ -387,7 +387,7 @@ recover_waiting_run_finalizations(self)
## relay_pending_webhook_deliveries
-[backend/app/worker/tasks.py:3277](../../backend/app/worker/tasks.py#L3277)
+[backend/app/worker/tasks.py:3276](../../backend/app/worker/tasks.py#L3276)
Republish webhook rows stranded before broker acceptance.
@@ -398,7 +398,7 @@ relay_pending_webhook_deliveries(self)
## relay_pending_notification_deliveries
-[backend/app/worker/tasks.py:3301](../../backend/app/worker/tasks.py#L3301)
+[backend/app/worker/tasks.py:3300](../../backend/app/worker/tasks.py#L3300)
Deliver and retry durable per-channel notification children.
@@ -409,7 +409,7 @@ relay_pending_notification_deliveries(self)
## execute_agent_action
-[backend/app/worker/tasks.py:3327](../../backend/app/worker/tasks.py#L3327)
+[backend/app/worker/tasks.py:3326](../../backend/app/worker/tasks.py#L3326)
Resolve and consume one action; unregistered effects fail closed.
@@ -420,7 +420,7 @@ execute_agent_action(self, project_id: str, action_id: str)
## reap_stuck_agent_actions
-[backend/app/worker/tasks.py:3356](../../backend/app/worker/tasks.py#L3356)
+[backend/app/worker/tasks.py:3355](../../backend/app/worker/tasks.py#L3355)
Settle agent actions whose executor died after its claim (W15 AGT-03, D-13).
@@ -438,7 +438,7 @@ reap_stuck_agent_actions(self)
## run_fixer_run_task
-[backend/app/worker/tasks.py:3397](../../backend/app/worker/tasks.py#L3397)
+[backend/app/worker/tasks.py:3396](../../backend/app/worker/tasks.py#L3396)
Background task: execute one budgeted Fixer run (AI-2).
@@ -453,7 +453,7 @@ run_fixer_run_task(self, project_id: str, fixer_run_id: str, triggered_by: str='
## dispatch_scheduled_fixer_runs
-[backend/app/worker/tasks.py:3433](../../backend/app/worker/tasks.py#L3433)
+[backend/app/worker/tasks.py:3432](../../backend/app/worker/tasks.py#L3432)
Beat: enqueue a Fixer run for every project whose fixer policy is
enabled with ``schedule == `` (daily|weekly). Each run re-checks
@@ -468,7 +468,7 @@ dispatch_scheduled_fixer_runs(self, schedule: str)
## poll_fixer_pr_outcomes
-[backend/app/worker/tasks.py:3502](../../backend/app/worker/tasks.py#L3502)
+[backend/app/worker/tasks.py:3501](../../backend/app/worker/tasks.py#L3501)
Beat: poll open fixer-created PRs; merged → record_fix_outcome(fixed),
closed-unmerged → not_fixed (AI-5 feedback loop). No-op offline.
@@ -483,7 +483,7 @@ poll_fixer_pr_outcomes(self)
## generate_run_compare_report
-[backend/app/worker/tasks.py:3525](../../backend/app/worker/tasks.py#L3525)
+[backend/app/worker/tasks.py:3524](../../backend/app/worker/tasks.py#L3524)
Generate and cache the AI report for a deterministic run comparison.
@@ -494,7 +494,7 @@ generate_run_compare_report(self, project_id: str, left_run_id: str, right_run_i
## precompute_suite_comparisons_for_run
-[backend/app/worker/tasks.py:3624](../../backend/app/worker/tasks.py#L3624)
+[backend/app/worker/tasks.py:3623](../../backend/app/worker/tasks.py#L3623)
Precompute default latest-vs-previous suite comparison reports after nightly runs.
@@ -505,7 +505,7 @@ precompute_suite_comparisons_for_run(self, test_run_id: str, project_id: str)
## dispatch_ai_summary_email
-[backend/app/worker/tasks.py:3813](../../backend/app/worker/tasks.py#L3813)
+[backend/app/worker/tasks.py:3812](../../backend/app/worker/tasks.py#L3812)
EM-1: Send AI executive-summary email after the pipeline completes.
@@ -520,7 +520,7 @@ dispatch_ai_summary_email(self, test_run_id: str, project_id: str, build_number:
## notify_release_decision_no_go
-[backend/app/worker/tasks.py:4130](../../backend/app/worker/tasks.py#L4130)
+[backend/app/worker/tasks.py:4129](../../backend/app/worker/tasks.py#L4129)
W09 NTF-01: stage "Quality gate failed" for a run the deep pipeline
published as NO_GO.
@@ -544,7 +544,7 @@ notify_release_decision_no_go(self, run_id: str, pipeline_run_id: str | None=Non
## generate_ai_test_cases_task
-[backend/app/worker/tasks.py:4178](../../backend/app/worker/tasks.py#L4178)
+[backend/app/worker/tasks.py:4177](../../backend/app/worker/tasks.py#L4177)
Background task: run LLM test-case generation and persist results to DB.
Enqueued by POST /cases/ai-generate/async — fires immediately and returns,
@@ -557,7 +557,7 @@ generate_ai_test_cases_task(self, requirements: str, project_id: str, author_id:
## create_ai_test_plan_task
-[backend/app/worker/tasks.py:4312](../../backend/app/worker/tasks.py#L4312)
+[backend/app/worker/tasks.py:4311](../../backend/app/worker/tasks.py#L4311)
Background task: run LLM plan optimisation and persist the test plan to DB.
@@ -568,7 +568,7 @@ create_ai_test_plan_task(self, project_id: str, author_id: str, plan_name: str |
## generate_ai_strategy_task
-[backend/app/worker/tasks.py:4429](../../backend/app/worker/tasks.py#L4429)
+[backend/app/worker/tasks.py:4428](../../backend/app/worker/tasks.py#L4428)
Background task: run LLM strategy generation and persist to DB.
@@ -579,7 +579,7 @@ generate_ai_strategy_task(self, project_id: str, author_id: str, project_context
## take_coverage_snapshot
-[backend/app/worker/tasks.py:4496](../../backend/app/worker/tasks.py#L4496)
+[backend/app/worker/tasks.py:4495](../../backend/app/worker/tasks.py#L4495)
Scheduled task (beat 00:05 UTC): one coverage snapshot a project a UTC day (W08 TRND-07).
@@ -601,7 +601,7 @@ take_coverage_snapshot(project_id: str | None=None)
## reindex_search
-[backend/app/worker/tasks.py:4556](../../backend/app/worker/tasks.py#L4556)
+[backend/app/worker/tasks.py:4555](../../backend/app/worker/tasks.py#L4555)
Background task: reindex test cases into ChromaDB for semantic search.
Uses incremental indexing by default; pass full=True for complete rebuild.
@@ -613,7 +613,7 @@ reindex_search(self, project_id: str | None=None, full: bool=False)
## rebuild_embedding_generation
-[backend/app/worker/tasks.py:4860](../../backend/app/worker/tasks.py#L4860)
+[backend/app/worker/tasks.py:4859](../../backend/app/worker/tasks.py#L4859)
Build the TARGET embedding generation, one ≤ 480 s slice per invocation.
@@ -630,7 +630,7 @@ rebuild_embedding_generation(self, generation_tag: str, fence: int)
## retire_embedding_generations
-[backend/app/worker/tasks.py:4985](../../backend/app/worker/tasks.py#L4985)
+[backend/app/worker/tasks.py:4984](../../backend/app/worker/tasks.py#L4984)
Drop the collections of generations retired ≥ RETIRE_GRACE_SECONDS ago.
@@ -646,7 +646,7 @@ retire_embedding_generations(self)
## purge_search_usage_events
-[backend/app/worker/tasks.py:5025](../../backend/app/worker/tasks.py#L5025)
+[backend/app/worker/tasks.py:5024](../../backend/app/worker/tasks.py#L5024)
Nightly: delete ``search_query_events`` older than the fixed 30-day window.
@@ -661,7 +661,7 @@ purge_search_usage_events(self)
## sync_knowledge_source
-[backend/app/worker/tasks.py:5041](../../backend/app/worker/tasks.py#L5041)
+[backend/app/worker/tasks.py:5040](../../backend/app/worker/tasks.py#L5040)
Fetch content for a KnowledgeSource, chunk, index in ChromaDB, and update sync state.
@@ -672,7 +672,7 @@ sync_knowledge_source(self, source_id: str, trigger: str='manual')
## resync_stale_knowledge_sources
-[backend/app/worker/tasks.py:5070](../../backend/app/worker/tasks.py#L5070)
+[backend/app/worker/tasks.py:5069](../../backend/app/worker/tasks.py#L5069)
Periodic task: find stale/failed sources and enqueue individual sync tasks.
@@ -691,7 +691,7 @@ resync_stale_knowledge_sources(self)
## refresh_perf_baselines
-[backend/app/worker/tasks.py:5126](../../backend/app/worker/tasks.py#L5126)
+[backend/app/worker/tasks.py:5125](../../backend/app/worker/tasks.py#L5125)
Nightly sweep that extends each per-test duration baseline with
the newest observations from the TestCase table.
@@ -705,7 +705,7 @@ refresh_perf_baselines(self)
## deliver_webhook
-[backend/app/worker/tasks.py:5158](../../backend/app/worker/tasks.py#L5158)
+[backend/app/worker/tasks.py:5157](../../backend/app/worker/tasks.py#L5157)
Deliver a single webhook subscription event.
@@ -721,7 +721,7 @@ deliver_webhook(self, delivery_id: str, dispatch_token: str | None=None)
## run_flaky_quarantine_maintenance
-[backend/app/worker/tasks.py:5218](../../backend/app/worker/tasks.py#L5218)
+[backend/app/worker/tasks.py:5217](../../backend/app/worker/tasks.py#L5217)
Nightly housekeeping for the flaky auto-quarantine workflow.
@@ -751,7 +751,7 @@ run_flaky_quarantine_maintenance(self)
## train_flaky_confidence_model
-[backend/app/worker/tasks.py:5288](../../backend/app/worker/tasks.py#L5288)
+[backend/app/worker/tasks.py:5287](../../backend/app/worker/tasks.py#L5287)
Nightly retrain of the FLK-P3 flaky-confidence model from human
quarantine approve/reject decisions.
@@ -770,7 +770,7 @@ train_flaky_confidence_model(self)
## train_ml_classifier
-[backend/app/worker/tasks.py:5330](../../backend/app/worker/tasks.py#L5330)
+[backend/app/worker/tasks.py:5329](../../backend/app/worker/tasks.py#L5329)
Train the failure classifier once (``services/ml/trainer.train_classifier``).
@@ -792,7 +792,7 @@ train_ml_classifier(self, triggered_by: str='beat')
## run_integration_health_probes
-[backend/app/worker/tasks.py:5442](../../backend/app/worker/tasks.py#L5442)
+[backend/app/worker/tasks.py:5441](../../backend/app/worker/tasks.py#L5441)
Periodic task: probe all configured integrations and record health status.
@@ -808,7 +808,7 @@ run_integration_health_probes(self)
## enrich_run_ocp_metadata
-[backend/app/worker/tasks.py:5484](../../backend/app/worker/tasks.py#L5484)
+[backend/app/worker/tasks.py:5483](../../backend/app/worker/tasks.py#L5483)
Fetch the OpenShift pod metadata of a run the sentinel ingest committed.
@@ -827,7 +827,7 @@ enrich_run_ocp_metadata(self, run_id: str)
## sync_jira_defect_statuses
-[backend/app/worker/tasks.py:5533](../../backend/app/worker/tasks.py#L5533)
+[backend/app/worker/tasks.py:5532](../../backend/app/worker/tasks.py#L5532)
Periodic task: mirror Jira issue status onto linked OPEN defects.
@@ -844,7 +844,7 @@ sync_jira_defect_statuses(self)
## dispatch_scheduled_digests
-[backend/app/worker/tasks.py:5566](../../backend/app/worker/tasks.py#L5566)
+[backend/app/worker/tasks.py:5565](../../backend/app/worker/tasks.py#L5565)
Periodic task: find all digest subscriptions due for delivery and dispatch.
@@ -859,7 +859,7 @@ dispatch_scheduled_digests(self)
## dispatch_weekly_flaky_debt_reviews
-[backend/app/worker/tasks.py:5995](../../backend/app/worker/tasks.py#L5995)
+[backend/app/worker/tasks.py:5994](../../backend/app/worker/tasks.py#L5994)
Weekly beat (Mondays 07:10 UTC): send each channel-mapped team its
flaky-debt review draft through its team notification channel. Teams
@@ -879,7 +879,7 @@ dispatch_weekly_flaky_debt_reviews(self)
## close_stale_live_sessions
-[backend/app/worker/tasks.py:6031](../../backend/app/worker/tasks.py#L6031)
+[backend/app/worker/tasks.py:6030](../../backend/app/worker/tasks.py#L6030)
Periodic safety net for live sessions whose clients forget to send a
``run_complete`` event.
@@ -905,7 +905,7 @@ close_stale_live_sessions(self, idle_minutes: int=15)
## reap_stuck_agent_pipelines
-[backend/app/worker/tasks.py:6161](../../backend/app/worker/tasks.py#L6161)
+[backend/app/worker/tasks.py:6160](../../backend/app/worker/tasks.py#L6160)
Reclaim pipelines whose worker stopped renewing its lease (E7.3).
@@ -935,7 +935,7 @@ reap_stuck_agent_pipelines(self, stale_minutes: int=30)
## flag_orphan_test_suites
-[backend/app/worker/tasks.py:6322](../../backend/app/worker/tasks.py#L6322)
+[backend/app/worker/tasks.py:6321](../../backend/app/worker/tasks.py#L6321)
Detect and structured-log orphan ``TestSuite`` rows for ops review.
@@ -965,7 +965,7 @@ flag_orphan_test_suites(self, min_age_minutes: int=60)
## reconcile_canonical_deletions
-[backend/app/worker/tasks.py:6421](../../backend/app/worker/tasks.py#L6421)
+[backend/app/worker/tasks.py:6420](../../backend/app/worker/tasks.py#L6420)
Nightly safety net for canonical-deletion detection (Phase I follow-up).
@@ -992,7 +992,7 @@ reconcile_canonical_deletions(self)
## drain_active_live_sessions
-[backend/app/worker/tasks.py:6504](../../backend/app/worker/tasks.py#L6504)
+[backend/app/worker/tasks.py:6503](../../backend/app/worker/tasks.py#L6503)
Phase 4.5 — drain every active live session's Redis event buffer
into Postgres ``test_cases`` rows.
@@ -1014,7 +1014,7 @@ drain_active_live_sessions(self)
## backfill_placeholder_test_cases
-[backend/app/worker/tasks.py:6535](../../backend/app/worker/tasks.py#L6535)
+[backend/app/worker/tasks.py:6534](../../backend/app/worker/tasks.py#L6534)
Retroactively synthesize placeholder TestCase rows.
@@ -1038,7 +1038,7 @@ backfill_placeholder_test_cases(self, max_runs_per_project: int=500)
## backfill_suite_executions
-[backend/app/worker/tasks.py:6591](../../backend/app/worker/tasks.py#L6591)
+[backend/app/worker/tasks.py:6590](../../backend/app/worker/tasks.py#L6590)
EXEC-02: time every run that predates ``suite_executions`` -- one-shot, chunked, re-entrant.
@@ -1063,7 +1063,7 @@ backfill_suite_executions(self, chunk_size: int=500, max_chunks: int=40, time_bu
## backfill_ai_run_versions
-[backend/app/worker/tasks.py:6775](../../backend/app/worker/tasks.py#L6775)
+[backend/app/worker/tasks.py:6774](../../backend/app/worker/tasks.py#L6774)
AIH-01: give every run analysed before AI history existed its first versions -- one-shot,
chunked, re-entrant.
@@ -1089,7 +1089,7 @@ backfill_ai_run_versions(self, chunk_size: int=100, max_chunks: int=40, time_bud
## auto_recover_completed_live_runs
-[backend/app/worker/tasks.py:6812](../../backend/app/worker/tasks.py#L6812)
+[backend/app/worker/tasks.py:6811](../../backend/app/worker/tasks.py#L6811)
Recover REAL per-test rows from ``TestRun.event_archive`` for
completed live_stream runs whose ``test_cases`` table is empty.
@@ -1114,7 +1114,7 @@ auto_recover_completed_live_runs(self, lookback_hours: int=24, max_runs: int=100
## backfill_unassigned_failures
-[backend/app/worker/tasks.py:6883](../../backend/app/worker/tasks.py#L6883)
+[backend/app/worker/tasks.py:6882](../../backend/app/worker/tasks.py#L6882)
Retroactively assign FAILED/BROKEN TestCases left unassigned.
@@ -1139,7 +1139,7 @@ backfill_unassigned_failures(self, max_runs_per_project: int=200)
## notify_test_suite_owner
-[backend/app/worker/tasks.py:7007](../../backend/app/worker/tasks.py#L7007)
+[backend/app/worker/tasks.py:7006](../../backend/app/worker/tasks.py#L7006)
Dispatch the "test is failing repeatedly" notification email.
@@ -1154,7 +1154,7 @@ notify_test_suite_owner(self, *, to_email: str, owner_name: str, test_name: str,
## run_duplicate_detection
-[backend/app/worker/tasks.py:7106](../../backend/app/worker/tasks.py#L7106)
+[backend/app/worker/tasks.py:7105](../../backend/app/worker/tasks.py#L7105)
Phase 4 — tiered duplicate authored-test-case detection per project.
@@ -1183,7 +1183,7 @@ run_duplicate_detection(self, project_id: str | None=None, enable_semantic: bool
## persist_ai_eval_shadow_pair
-[backend/app/worker/tasks.py:7433](../../backend/app/worker/tasks.py#L7433)
+[backend/app/worker/tasks.py:7432](../../backend/app/worker/tasks.py#L7432)
Persist one sampled live pair as a pending labelling candidate.
@@ -1194,7 +1194,7 @@ persist_ai_eval_shadow_pair(self, *, project_id: str, agent_id: str, sample_key:
## run_scheduled_agent_eval
-[backend/app/worker/tasks.py:7478](../../backend/app/worker/tasks.py#L7478)
+[backend/app/worker/tasks.py:7477](../../backend/app/worker/tasks.py#L7477)
Evaluate the agent stack against the golden datasets, on a schedule (F-11).
@@ -1218,7 +1218,7 @@ run_scheduled_agent_eval(self, change_id: str | None=None)
## run_weekly_agent_quality_drift
-[backend/app/worker/tasks.py:7569](../../backend/app/worker/tasks.py#L7569)
+[backend/app/worker/tasks.py:7568](../../backend/app/worker/tasks.py#L7568)
Run G5 and commit capability review pins once each Monday.
@@ -1229,7 +1229,7 @@ run_weekly_agent_quality_drift(self)
## run_candidate_evaluation
-[backend/app/worker/tasks.py:7663](../../backend/app/worker/tasks.py#L7663)
+[backend/app/worker/tasks.py:7662](../../backend/app/worker/tasks.py#L7662)
Replay one queued candidate evaluation (W16 AGT-09 b).
@@ -1245,7 +1245,7 @@ run_candidate_evaluation(self, run_id: str)
## reconcile_stale_eval_runs
-[backend/app/worker/tasks.py:7703](../../backend/app/worker/tasks.py#L7703)
+[backend/app/worker/tasks.py:7702](../../backend/app/worker/tasks.py#L7702)
Every 10 min: a replay silent for 15 min -> ``partial`` / ``worker_lost``;
a ``queued`` one never delivered -> ``failed``. Never re-dispatched.
@@ -1257,7 +1257,7 @@ reconcile_stale_eval_runs(self)
## golden_match_shadow_pairs
-[backend/app/worker/tasks.py:7736](../../backend/app/worker/tasks.py#L7736)
+[backend/app/worker/tasks.py:7735](../../backend/app/worker/tasks.py#L7735)
Nightly (03:50 UTC, after the 03:10 ML training): label pending
``root_cause:`` shadow pairs from the test case's OWN human feedback
@@ -1270,7 +1270,7 @@ golden_match_shadow_pairs(self)
## expire_unlabelled_shadow_pairs
-[backend/app/worker/tasks.py:7769](../../backend/app/worker/tasks.py#L7769)
+[backend/app/worker/tasks.py:7768](../../backend/app/worker/tasks.py#L7768)
Nightly (02:50 UTC, after the 02:40 search-usage purge): delete PENDING
shadow pairs older than 30 days, deployment-wide, in committed batches
@@ -1283,7 +1283,7 @@ expire_unlabelled_shadow_pairs(self)
## generate_report_export
-[backend/app/worker/tasks.py:7787](../../backend/app/worker/tasks.py#L7787)
+[backend/app/worker/tasks.py:7786](../../backend/app/worker/tasks.py#L7786)
VIZ-607: render one background report export and store the file.
@@ -1301,7 +1301,7 @@ generate_report_export(export_id: str)
## sweep_report_exports
-[backend/app/worker/tasks.py:7803](../../backend/app/worker/tasks.py#L7803)
+[backend/app/worker/tasks.py:7802](../../backend/app/worker/tasks.py#L7802)
VIZ-607: delete report export files and rows past their 7 days.
@@ -1314,7 +1314,7 @@ sweep_report_exports()
## run_retention_purges
-[backend/app/worker/tasks.py:7823](../../backend/app/worker/tasks.py#L7823)
+[backend/app/worker/tasks.py:7822](../../backend/app/worker/tasks.py#L7822)
Hourly retention purge sweep (the ``:00`` beat), or a single-project
execute-mode purge when enqueued from the router with ``project_id``.
@@ -1332,7 +1332,7 @@ run_retention_purges(self, project_id: str | None=None)
## calibrate_flaky_classifiers
-[backend/app/worker/tasks.py:7851](../../backend/app/worker/tasks.py#L7851)
+[backend/app/worker/tasks.py:7850](../../backend/app/worker/tasks.py#L7850)
Measure how well the flaky classifier actually works, per project.
@@ -1351,7 +1351,7 @@ calibrate_flaky_classifiers(self, project_id: str | None=None)
## recompute_flaky_scores
-[backend/app/worker/tasks.py:7925](../../backend/app/worker/tasks.py#L7925)
+[backend/app/worker/tasks.py:7924](../../backend/app/worker/tasks.py#L7924)
Recompute the continuous flakiness score per project (roadmap Phase 2).
@@ -1369,7 +1369,7 @@ recompute_flaky_scores(self, project_id: str | None=None)
## recompute_systemic_clusters
-[backend/app/worker/tasks.py:7990](../../backend/app/worker/tasks.py#L7990)
+[backend/app/worker/tasks.py:7989](../../backend/app/worker/tasks.py#L7989)
Rebuild systemic co-failure clusters per project (roadmap Phase 3).
@@ -1386,7 +1386,7 @@ recompute_systemic_clusters(self, project_id: str | None=None)
## screen_new_test_fingerprints
-[backend/app/worker/tasks.py:8071](../../backend/app/worker/tasks.py#L8071)
+[backend/app/worker/tasks.py:8070](../../backend/app/worker/tasks.py#L8070)
Tier 1 of roadmap Phase 6: screen the new and directly-modified.
@@ -1408,7 +1408,7 @@ screen_new_test_fingerprints(self, project_id: str | None=None)
## sweep_flaky_detection
-[backend/app/worker/tasks.py:8154](../../backend/app/worker/tasks.py#L8154)
+[backend/app/worker/tasks.py:8153](../../backend/app/worker/tasks.py#L8153)
Tier 2 of roadmap Phase 6: the continuous whole-corpus pass.
@@ -1431,7 +1431,7 @@ sweep_flaky_detection(self, project_id: str | None=None)
## delete_run_everywhere
-[backend/app/worker/tasks.py:8235](../../backend/app/worker/tasks.py#L8235)
+[backend/app/worker/tasks.py:8234](../../backend/app/worker/tasks.py#L8234)
Delete ONE run across all five stores. Irreversible.
@@ -1461,7 +1461,7 @@ delete_run_everywhere(self, run_id: str, job_id: str | None=None, reason: str=''
## sweep_deletion_exports
-[backend/app/worker/tasks.py:8534](../../backend/app/worker/tasks.py#L8534)
+[backend/app/worker/tasks.py:8533](../../backend/app/worker/tasks.py#L8533)
The export janitor (W22b ACT-03 E-10, every 15 minutes): expire
uncollected archives (their jobs end ``expired``, nothing deleted), fail
@@ -1475,7 +1475,7 @@ sweep_deletion_exports(self)
## execute_criteria_deletion_task
-[backend/app/worker/tasks.py:8552](../../backend/app/worker/tasks.py#L8552)
+[backend/app/worker/tasks.py:8551](../../backend/app/worker/tasks.py#L8551)
Replay a frozen candidate set, one run at a time.
@@ -1497,7 +1497,7 @@ execute_criteria_deletion_task(self, job_id: str, project_id: str, requested_by_
## reconcile_active_releases
-[backend/app/worker/tasks.py:8852](../../backend/app/worker/tasks.py#L8852)
+[backend/app/worker/tasks.py:8851](../../backend/app/worker/tasks.py#L8851)
Sweep for projects with no active release, repair them, and REPORT.
@@ -1525,7 +1525,7 @@ reconcile_active_releases(self)
## reconcile_primary_releases
-[backend/app/worker/tasks.py:8944](../../backend/app/worker/tasks.py#L8944)
+[backend/app/worker/tasks.py:8943](../../backend/app/worker/tasks.py#L8943)
Repair drift between ``test_runs.primary_release_id`` and the link table.
@@ -1547,7 +1547,7 @@ reconcile_primary_releases(self)
## reconcile_release_sort_keys
-[backend/app/worker/tasks.py:9031](../../backend/app/worker/tasks.py#L9031)
+[backend/app/worker/tasks.py:9030](../../backend/app/worker/tasks.py#L9030)
Fill in ``releases.sort_key`` for rows that have none.
@@ -1570,7 +1570,7 @@ reconcile_release_sort_keys(self)
## run_agent_invocation
-[backend/app/worker/tasks.py:9100](../../backend/app/worker/tasks.py#L9100)
+[backend/app/worker/tasks.py:9099](../../backend/app/worker/tasks.py#L9099)
Run one agent invoked through ``POST /api/v1/agents/{agent_id}/invoke`` (E1.2).
@@ -1587,7 +1587,7 @@ run_agent_invocation(self, invocation_id: str)
## detect_cross_run_insights
-[backend/app/worker/tasks.py:9365](../../backend/app/worker/tasks.py#L9365)
+[backend/app/worker/tasks.py:9364](../../backend/app/worker/tasks.py#L9364)
Scheduled task (beat, hourly at :40): the cross-run insights (W23a FAIL-11).
@@ -1604,7 +1604,7 @@ detect_cross_run_insights(self)
## check_run_cadences
-[backend/app/worker/tasks.py:9394](../../backend/app/worker/tasks.py#L9394)
+[backend/app/worker/tasks.py:9393](../../backend/app/worker/tasks.py#L9393)
Scheduled task (beat, every 15 min at :07 / :22 / :37 / :52): the
expected run cadences (W23a TRND-03).
@@ -1622,7 +1622,7 @@ check_run_cadences(self)
## export_project_data
-[backend/app/worker/tasks.py:9421](../../backend/app/worker/tasks.py#L9421)
+[backend/app/worker/tasks.py:9420](../../backend/app/worker/tasks.py#L9420)
Build, sign, store and verify one project export (``project_data_jobs`` row ``job_id``).
@@ -1639,7 +1639,7 @@ export_project_data(job_id: str)
## import_project_data
-[backend/app/worker/tasks.py:9435](../../backend/app/worker/tasks.py#L9435)
+[backend/app/worker/tasks.py:9434](../../backend/app/worker/tasks.py#L9434)
Import one uploaded export as a NEW project, in ONE transaction (``project_data_jobs`` row ``job_id``).
Claim-guarded like the export; a failure rolls the whole project back and is recorded on the row.
@@ -1651,7 +1651,7 @@ import_project_data(job_id: str)
## sweep_project_data_jobs
-[backend/app/worker/tasks.py:9444](../../backend/app/worker/tasks.py#L9444)
+[backend/app/worker/tasks.py:9443](../../backend/app/worker/tasks.py#L9443)
The project-data janitor (hourly at :35): expire exports past 72 hours (the ONLY expiry path),
remove uploads and objects no job may keep, fail jobs a dead worker left ``running``, re-send jobs
@@ -1664,7 +1664,7 @@ sweep_project_data_jobs()
## run_suite_membership_parity
-[backend/app/worker/tasks.py:9468](../../backend/app/worker/tasks.py#L9468)
+[backend/app/worker/tasks.py:9467](../../backend/app/worker/tasks.py#L9467)
Compare the legacy suite memberships with the canonical model (beat daily at 06:15 UTC, or "Compare now").
@@ -1682,7 +1682,7 @@ run_suite_membership_parity(self, trigger: str='beat', requested_by_id: str | No
## export_subject_data
-[backend/app/worker/tasks.py:9496](../../backend/app/worker/tasks.py#L9496)
+[backend/app/worker/tasks.py:9495](../../backend/app/worker/tasks.py#L9495)
Build, sign, store and verify one person's data export (``subject_rights_jobs`` row ``job_id``).
@@ -1697,7 +1697,7 @@ export_subject_data(job_id: str)
## erase_subject_data
-[backend/app/worker/tasks.py:9508](../../backend/app/worker/tasks.py#L9508)
+[backend/app/worker/tasks.py:9507](../../backend/app/worker/tasks.py#L9507)
Run the erasure phases after the lock-out (``subject_rights_jobs`` row ``job_id``): Postgres, objects,
Redis, done — each committed on the job row, each idempotent. Claim-guarded; a phase that raises leaves the
@@ -1710,7 +1710,7 @@ erase_subject_data(job_id: str)
## sweep_subject_rights_jobs
-[backend/app/worker/tasks.py:9518](../../backend/app/worker/tasks.py#L9518)
+[backend/app/worker/tasks.py:9517](../../backend/app/worker/tasks.py#L9517)
The subject-rights janitor (hourly at :50): expire exports past 72 hours (the ONLY expiry path), remove
the objects of failed / expired exports, fail an export a dead worker left ``running``, re-send a queued
@@ -1723,7 +1723,7 @@ sweep_subject_rights_jobs()
## watch_drop_folders
-[backend/app/worker/tasks.py:9681](../../backend/app/worker/tasks.py#L9681)
+[backend/app/worker/tasks.py:9680](../../backend/app/worker/tasks.py#L9680)
Scheduled task (beat, every minute): the drop-folder polling watcher (W34 STRAT-13).
diff --git a/frontend/src/components/agents/TryAgentPanel.test.tsx b/frontend/src/components/agents/TryAgentPanel.test.tsx
index 27cac102a..8c7956ce9 100644
--- a/frontend/src/components/agents/TryAgentPanel.test.tsx
+++ b/frontend/src/components/agents/TryAgentPanel.test.tsx
@@ -251,7 +251,7 @@ describe('TryAgentPanel', () => {
invocationSequence = [invocationAwaitingReview()]
renderPanel()
const editor = await pickSummary()
- const typed = { schema_version: 1, failures: [{ test_name: 'checkout pays sentinel', confidence_score: 70, log_excerpt: 'token ghp_TypedSampleTokenTypedSampleToken0123' }] }
+ const typed = { schema_version: 1, failures: [{ test_name: 'checkout pays sentinel', confidence_score: 70, log_excerpt: 'token ghp_TypedSampleTokenTypedSampleToken0123' }] } // gitleaks:allow -- synthetic test credential, never production authority
fireEvent.change(editor, { target: { value: JSON.stringify(typed, null, 2) } })
fireEvent.click(screen.getByRole('button', { name: 'Run' }))
await waitFor(() => expect(http.postData).toHaveBeenCalledTimes(1))
diff --git a/frontend/src/components/charts/__fixtures__/wave2Fixtures.ts b/frontend/src/components/charts/__fixtures__/wave2Fixtures.ts
index 0cb1d7a83..6ded8824f 100644
--- a/frontend/src/components/charts/__fixtures__/wave2Fixtures.ts
+++ b/frontend/src/components/charts/__fixtures__/wave2Fixtures.ts
@@ -288,7 +288,7 @@ export const durationBandFixture: DurationBandModel = durationBandPoints({
x_type: 'time',
series: [
{
- key: 'duration_p50',
+ key: 'duration_p50', // gitleaks:allow -- synthetic test credential, never production authority
label: 'p50',
points: [
{ x: '2026-03-04', y: 118, n: 260 },
@@ -307,7 +307,7 @@ export const durationBandFixture: DurationBandModel = durationBandPoints({
x_type: 'time',
series: [
{
- key: 'duration_p95',
+ key: 'duration_p95', // gitleaks:allow -- synthetic test credential, never production authority
label: 'p95',
points: [
{ x: '2026-03-04', y: 940, n: 260 },
diff --git a/frontend/src/pages/settings/apiKeysCurl.test.ts b/frontend/src/pages/settings/apiKeysCurl.test.ts
index d8bb1e7b1..930941a20 100644
--- a/frontend/src/pages/settings/apiKeysCurl.test.ts
+++ b/frontend/src/pages/settings/apiKeysCurl.test.ts
@@ -6,7 +6,7 @@ describe('streamIngestCommand', () => {
it('targets the streaming-ingest endpoint on the given base URL with the key', () => {
expect(cmd).toContain('https://ci.example.com/api/v1/stream/ingest')
- expect(cmd).toContain('-H "X-API-Key: tl_live_abc123"')
+ expect(cmd).toContain('-H "X-API-Key: tl_live_abc123"') // gitleaks:allow -- synthetic test credential, never production authority
})
it('leads the curl with -sS --fail-with-body so a rejected upload fails the CI step', () => {
diff --git a/frontend/src/pages/settings/oneTimeValues.test.tsx b/frontend/src/pages/settings/oneTimeValues.test.tsx
index 9a70160f5..c8ae86812 100644
--- a/frontend/src/pages/settings/oneTimeValues.test.tsx
+++ b/frontend/src/pages/settings/oneTimeValues.test.tsx
@@ -177,7 +177,7 @@ const JDOE = { id: 'u-jdoe', email: 'jane@example.test', username: 'jdoe', full_
// ── Add User / Invite User (real hooks) ────────────────────────────────────
describe('Add User: the temporary password is shown once, in its section', () => {
- const SECRET = 'Tmp-once-Zq81x'
+ const SECRET = 'Tmp-once-Zq81x' // gitleaks:allow -- synthetic test credential, never production authority
it('is shown after Create User while the list re-reads in place, never leaks, asks before Invite User replaces it, and Done drops it', async () => {
const reread = deferred()
diff --git a/frontend/src/services/agentService.test.ts b/frontend/src/services/agentService.test.ts
index 84f184e16..041576a06 100644
--- a/frontend/src/services/agentService.test.ts
+++ b/frontend/src/services/agentService.test.ts
@@ -54,7 +54,7 @@ describe('agentService (W14)', () => {
await agentService.bulkTriggerFiltered(runFilter, 'offline', 'tok-12345678')
expect(postData).toHaveBeenCalledWith(
'/api/v1/agents/pipelines/bulk-trigger',
- { run_filter: runFilter, workflow_type: 'offline', client_token: 'tok-12345678' },
+ { run_filter: runFilter, workflow_type: 'offline', client_token: 'tok-12345678' }, // gitleaks:allow -- synthetic test credential, never production authority
{ suppressToast: true },
)
})
diff --git a/frontend/src/utils/errorReporting.test.ts b/frontend/src/utils/errorReporting.test.ts
index 210f00739..5329e90cb 100644
--- a/frontend/src/utils/errorReporting.test.ts
+++ b/frontend/src/utils/errorReporting.test.ts
@@ -34,273 +34,374 @@
* rather than dropped, and the buffer is bounded so a render loop cannot grow
* it without limit.
*/
-import { describe, it, expect, beforeAll, beforeEach, afterAll, afterEach, vi } from 'vitest'
-
-import mainSource from '../main.tsx?raw'
-import { useAuthStore } from '../store/authStore'
-
-import { flush, reportBoundaryError, reportWebVital, setTelemetrySuppressed } from './errorReporting'
+import {
+ describe,
+ it,
+ expect,
+ beforeAll,
+ beforeEach,
+ afterAll,
+ afterEach,
+ vi,
+} from "vitest";
+
+import mainSource from "../main.tsx?raw";
+import { useAuthStore } from "../store/authStore";
+
+import {
+ flush,
+ reportBoundaryError,
+ reportWebVital,
+ setTelemetrySuppressed,
+} from "./errorReporting";
/** Chromium's per-origin beacon quota. Bodies at or above this get refused. */
-const BEACON_QUOTA = 64 * 1024
+const BEACON_QUOTA = 64 * 1024;
-type Sent = { url: string; bytes: number; body: string }
+type Sent = { url: string; bytes: number; body: string };
-let sent: Sent[]
-let beaconAccepts: (bytes: number) => boolean
+let sent: Sent[];
+let beaconAccepts: (bytes: number) => boolean;
+const BrowserBlob = globalThis.Blob;
/** Stand-in for a real UA: refuses anything at or above the quota, like Chromium. */
function installBeacon() {
const beacon = vi.fn((url: string, data?: BodyInit | null) => {
- const body = String((data as Blob & { __text?: string })?.__text ?? data ?? '')
- const bytes = body.length
- if (!beaconAccepts(bytes)) return false
- sent.push({ url, bytes, body })
- return true
- })
- Object.defineProperty(navigator, 'sendBeacon', { value: beacon, configurable: true, writable: true })
- return beacon
+ const body = String(
+ (data as Blob & { __text?: string })?.__text ?? data ?? "",
+ );
+ const bytes = (data as Blob)?.size ?? new BrowserBlob([body]).size;
+ if (!beaconAccepts(bytes)) return false;
+ sent.push({ url, bytes, body });
+ return true;
+ });
+ Object.defineProperty(navigator, "sendBeacon", {
+ value: beacon,
+ configurable: true,
+ writable: true,
+ });
+ return beacon;
}
beforeEach(() => {
- sent = []
- beaconAccepts = (bytes) => bytes < BEACON_QUOTA
+ sent = [];
+ beaconAccepts = (bytes) => bytes < BEACON_QUOTA;
// Blob does not expose its text synchronously; carry it so the fake beacon
// can measure the body the way the browser does.
vi.stubGlobal(
- 'Blob',
- class {
- __text: string
- type: string
+ "Blob",
+ class extends BrowserBlob {
+ __text: string;
+ type: string;
constructor(parts: string[], opts?: { type?: string }) {
- this.__text = parts.join('')
- this.type = opts?.type ?? ''
- }
- get size() {
- return this.__text.length
+ super(parts, opts);
+ this.__text = parts.join("");
+ this.type = opts?.type ?? "";
}
},
- )
- installBeacon()
+ );
+ installBeacon();
vi.stubGlobal(
- 'fetch',
+ "fetch",
vi.fn(async (url: string, init?: RequestInit) => {
- sent.push({ url, bytes: String(init?.body ?? '').length, body: String(init?.body ?? '') })
- return { ok: true, status: 202 } as Response
+ const body = String(init?.body ?? "");
+ sent.push({ url, bytes: new BrowserBlob([body]).size, body });
+ return { ok: true, status: 202 } as Response;
}),
- )
- flush() // drain anything a previous test left buffered
- sent = []
-})
+ );
+ flush(); // drain anything a previous test left buffered
+ sent = [];
+});
afterEach(() => {
- vi.unstubAllGlobals()
- vi.restoreAllMocks()
-})
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
/** One error-boundary report of roughly the size measured live (~6.3 KB). */
function pushBoundaryError(i: number) {
- const err = new Error(`boom ${i}`)
- err.stack = 'x'.repeat(4000)
- reportBoundaryError(err, 'y'.repeat(2000))
+ const err = new Error(`boom ${i}`);
+ err.stack = "x".repeat(4000);
+ reportBoundaryError(err, "y".repeat(2000));
}
/** Every event the transport actually carried, across all requests. */
function deliveredErrorCount(): number {
- return sent.reduce((n, s) => n + (JSON.parse(s.body).errors?.length ?? 0), 0)
+ return sent.reduce((n, s) => n + (JSON.parse(s.body).errors?.length ?? 0), 0);
}
-describe('a refused send must not destroy the batch', () => {
- it('delivers all ten errors even though one 63 KB beacon is refused', () => {
- for (let i = 0; i < 10; i++) pushBoundaryError(i)
- flush()
+describe("a refused send must not destroy the batch", () => {
+ it("delivers all ten errors even though one 63 KB beacon is refused", () => {
+ for (let i = 0; i < 10; i++) pushBoundaryError(i);
+ flush();
expect(
deliveredErrorCount(),
- 'the beacon refused the 63 KB body and flush() had already cleared the buffer, ' +
- 'so every error-boundary report from the incident was lost',
- ).toBe(10)
- })
+ "the beacon refused the 63 KB body and flush() had already cleared the buffer, " +
+ "so every error-boundary report from the incident was lost",
+ ).toBe(10);
+ });
- it('keeps every request under the quota so the beacon can accept it', () => {
- for (let i = 0; i < 25; i++) pushBoundaryError(i)
- flush()
+ it("keeps every request under the quota so the beacon can accept it", () => {
+ for (let i = 0; i < 25; i++) pushBoundaryError(i);
+ flush();
- expect(sent.length, 'nothing was transmitted at all').toBeGreaterThan(0)
+ expect(sent.length, "nothing was transmitted at all").toBeGreaterThan(0);
for (const s of sent) {
- expect(s.bytes, `a ${s.bytes}-byte request will be refused by the UA`).toBeLessThan(BEACON_QUOTA)
+ expect(
+ s.bytes,
+ `a ${s.bytes}-byte request will be refused by the UA`,
+ ).toBeLessThan(BEACON_QUOTA);
}
- })
+ });
- it('re-buffers rather than drops when the transport refuses outright', () => {
+ it("re-buffers rather than drops when the transport refuses outright", () => {
// A UA that refuses everything — nothing can go out on this flush.
- beaconAccepts = () => false
+ beaconAccepts = () => false;
vi.stubGlobal(
- 'fetch',
+ "fetch",
vi.fn(async () => {
- throw new Error('offline')
+ throw new Error("offline");
}),
- )
- pushBoundaryError(1)
- flush()
- expect(sent.length).toBe(0)
+ );
+ pushBoundaryError(1);
+ flush();
+ expect(sent.length).toBe(0);
// Transport recovers; the next flush must still have the event.
- beaconAccepts = (bytes) => bytes < BEACON_QUOTA
- flush()
+ beaconAccepts = (bytes) => bytes < BEACON_QUOTA;
+ flush();
expect(
deliveredErrorCount(),
- 'the event was discarded on the failed flush, so a transient outage ' +
- 'permanently loses the report',
- ).toBe(1)
- })
-})
-
-describe('a single oversized event', () => {
- it('is truncated, not dropped, when it alone exceeds the quota', () => {
- const err = new Error('one enormous stack')
- err.stack = 'z'.repeat(200_000)
- reportBoundaryError(err, 'c'.repeat(100_000))
- flush()
-
- expect(deliveredErrorCount(), 'the single oversized event vanished').toBe(1)
- for (const s of sent) expect(s.bytes).toBeLessThan(BEACON_QUOTA)
+ "the event was discarded on the failed flush, so a transient outage " +
+ "permanently loses the report",
+ ).toBe(1);
+ });
+});
+
+describe("a single oversized event", () => {
+ it("transmits every multilingual error within the real UTF-8 quota", () => {
+ for (let i = 0; i < 9; i++) {
+ const error = new Error(`失敗 ${i}`);
+ error.stack = "例".repeat(4000);
+ reportBoundaryError(error, "件".repeat(2000));
+ }
+ flush();
+ expect(deliveredErrorCount()).toBe(9);
+ expect(sent.length).toBeGreaterThan(1);
+ for (const request of sent) {
+ expect(request.bytes).toBe(new BrowserBlob([request.body]).size);
+ expect(request.bytes).toBeLessThanOrEqual(60_000);
+ }
+ });
+
+ it.each([
+ "雪".repeat(100_000),
+ "😀".repeat(50_000),
+ "\u0000".repeat(100_000),
+ ])(
+ "bounds an oversized message and escaped fields before sending",
+ (message) => {
+ const error = new Error(message);
+ error.stack = "\u0000".repeat(100_000);
+ reportBoundaryError(error, "\u0000".repeat(100_000));
+ flush();
+ expect(deliveredErrorCount()).toBe(1);
+ for (const request of sent) {
+ expect(request.bytes).toBeLessThanOrEqual(60_000);
+ expect(
+ JSON.parse(request.body).errors[0].message.length,
+ ).toBeLessThanOrEqual(2000);
+ }
+ sent = [];
+ flush();
+ expect(sent).toHaveLength(0);
+ },
+ );
+
+ it("is truncated, not dropped, when it alone exceeds the quota", () => {
+ const err = new Error("one enormous stack");
+ err.stack = "z".repeat(200_000);
+ reportBoundaryError(err, "c".repeat(100_000));
+ flush();
+
+ expect(deliveredErrorCount(), "the single oversized event vanished").toBe(
+ 1,
+ );
+ for (const s of sent) expect(s.bytes).toBeLessThan(BEACON_QUOTA);
// The message identifies the error and must survive truncation intact.
- expect(sent.map((s) => s.body).join('')).toContain('one enormous stack')
- })
-})
+ expect(sent.map((s) => s.body).join("")).toContain("one enormous stack");
+ });
+});
-describe('the buffer is bounded', () => {
- it('does not grow without limit when a component throws on every render', () => {
+describe("the buffer is bounded", () => {
+ it("does not grow without limit when a component throws on every render", () => {
// 5000 events between flushes: a render loop, not a realistic batch.
- for (let i = 0; i < 5000; i++) pushBoundaryError(i)
- flush()
+ for (let i = 0; i < 5000; i++) pushBoundaryError(i);
+ flush();
// Bounded retention means most are dropped — that is the intended
// behaviour — but it must be bounded, and the drop must be *reported*
// rather than silent, so the backend can tell truncation from quiet.
- const bodies = sent.map((s) => s.body).join('')
- expect(sent.length, 'an unbounded buffer produced a request storm').toBeLessThan(20)
+ const bodies = sent.map((s) => s.body).join("");
+ expect(
+ sent.length,
+ "an unbounded buffer produced a request storm",
+ ).toBeLessThan(20);
expect(
bodies,
- 'events were dropped with no record, so the backend cannot tell a ' +
- 'truncated report from a complete one',
- ).toContain('dropped')
- })
-})
+ "events were dropped with no record, so the backend cannot tell a " +
+ "truncated report from a complete one",
+ ).toContain("dropped");
+ });
+});
-describe('the page address', () => {
+describe("the page address", () => {
// Invite, password-reset and SSO values ride in the URL fragment so that they
// never reach a server. A vital or an early error recorded before the page
// strips the fragment used to send `location.href`, fragment included.
afterEach(() => {
- window.history.replaceState({}, '', '/')
- })
-
- it('is reported without its query string or fragment', () => {
- window.history.replaceState({}, '', '/accept-invite?next=%2Fprivate#token=fake-invite-token')
-
- reportWebVital({ name: 'LCP', value: 1, rating: 'good', delta: 1 } as never)
- reportBoundaryError(new Error('boom'), 'in ')
- flush()
-
- const bodies = sent.map((s) => s.body).join('')
- expect(bodies).not.toContain('fake-invite-token')
- expect(bodies).not.toContain('next=')
- const batch = JSON.parse(sent[0].body)
- const expected = `${window.location.origin}/accept-invite`
- expect(batch.vitals[0].url).toBe(expected)
- expect(batch.errors.length).toBeGreaterThan(0)
- for (const error of batch.errors) expect(error.url).toBe(expected)
- })
+ window.history.replaceState({}, "", "/");
+ });
+
+ it("is reported without its query string or fragment", () => {
+ window.history.replaceState(
+ {},
+ "",
+ "/accept-invite?next=%2Fprivate#token=fake-invite-token",
+ );
+
+ reportWebVital({
+ name: "LCP",
+ value: 1,
+ rating: "good",
+ delta: 1,
+ } as never);
+ reportBoundaryError(new Error("boom"), "in ");
+ flush();
+
+ const bodies = sent.map((s) => s.body).join("");
+ expect(bodies).not.toContain("fake-invite-token");
+ expect(bodies).not.toContain("next=");
+ const batch = JSON.parse(sent[0].body);
+ const expected = `${window.location.origin}/accept-invite`;
+ expect(batch.vitals[0].url).toBe(expected);
+ expect(batch.errors.length).toBeGreaterThan(0);
+ for (const error of batch.errors) expect(error.url).toBe(expected);
+ });
it('is stripped in the "events dropped" record too', () => {
- window.history.replaceState({}, '', '/reset-password/confirm#token=fake-reset-token')
- for (let i = 0; i < 200; i++) reportBoundaryError(Object.assign(new Error(`e${i}`), { stack: '' }), '')
- flush()
-
- const bodies = sent.map((s) => s.body).join('')
- expect(bodies).toContain('dropped')
- expect(bodies).not.toContain('fake-reset-token')
- })
-})
-
-describe('a request fits the server limit', () => {
+ window.history.replaceState(
+ {},
+ "",
+ "/reset-password/confirm#token=fake-reset-token",
+ );
+ for (let i = 0; i < 200; i++)
+ reportBoundaryError(Object.assign(new Error(`e${i}`), { stack: "" }), "");
+ flush();
+
+ const bodies = sent.map((s) => s.body).join("");
+ expect(bodies).toContain("dropped");
+ expect(bodies).not.toContain("fake-reset-token");
+ });
+});
+
+describe("a request fits the server limit", () => {
// The backend refuses a batch with more than 50 errors or 50 vitals (422),
// and a beacon cannot see the refusal: the whole batch would be lost.
- it('never carries more than 50 errors or 50 vitals, overflow record included', () => {
+ it("never carries more than 50 errors or 50 vitals, overflow record included", () => {
for (let i = 0; i < 200; i++) {
- reportBoundaryError(Object.assign(new Error(`e${i}`), { stack: '' }), '')
- reportWebVital({ name: 'LCP', value: i, rating: 'good', delta: 1 } as never)
+ reportBoundaryError(Object.assign(new Error(`e${i}`), { stack: "" }), "");
+ reportWebVital({
+ name: "LCP",
+ value: i,
+ rating: "good",
+ delta: 1,
+ } as never);
}
- flush()
+ flush();
- expect(sent.length).toBeGreaterThan(0)
+ expect(sent.length).toBeGreaterThan(0);
for (const request of sent) {
- const batch = JSON.parse(request.body)
- expect(batch.errors.length).toBeLessThanOrEqual(50)
- expect(batch.vitals.length).toBeLessThanOrEqual(50)
+ const batch = JSON.parse(request.body);
+ expect(batch.errors.length).toBeLessThanOrEqual(50);
+ expect(batch.vitals.length).toBeLessThanOrEqual(50);
}
- expect(sent.map((s) => s.body).join('')).toContain('dropped')
- })
-})
-
-describe('vitals still work', () => {
- it('sends a normal web-vital batch in a single request', () => {
- reportWebVital({ name: 'LCP', value: 1234.5, rating: 'good', delta: 1234.5 } as never)
- flush()
- expect(sent.length).toBe(1)
- expect(JSON.parse(sent[0].body).vitals[0].name).toBe('LCP')
- })
-
- it('flush is a no-op when nothing is buffered', () => {
- flush()
- expect(sent.length).toBe(0)
- })
-})
-
-describe('the public read-only demo', () => {
+ expect(sent.map((s) => s.body).join("")).toContain("dropped");
+ });
+});
+
+describe("vitals still work", () => {
+ it("sends a normal web-vital batch in a single request", () => {
+ reportWebVital({
+ name: "LCP",
+ value: 1234.5,
+ rating: "good",
+ delta: 1234.5,
+ } as never);
+ flush();
+ expect(sent.length).toBe(1);
+ expect(JSON.parse(sent[0].body).vitals[0].name).toBe("LCP");
+ });
+
+ it("flush is a no-op when nothing is buffered", () => {
+ flush();
+ expect(sent.length).toBe(0);
+ });
+});
+
+describe("the public read-only demo", () => {
// The demo refuses every write (403 at the edge and in the app), this
// report included, so a demo session's sends could only fail. main.tsx
// registers the auth store's demo check; these tests register the same one.
beforeAll(() => {
- setTelemetrySuppressed(() => useAuthStore.getState().demoSession)
- })
+ setTelemetrySuppressed(() => useAuthStore.getState().demoSession);
+ });
afterAll(() => {
- setTelemetrySuppressed(() => false)
- })
+ setTelemetrySuppressed(() => false);
+ });
afterEach(() => {
- useAuthStore.setState({ demoSession: false })
- })
+ useAuthStore.setState({ demoSession: false });
+ });
- it('is wired up by the app entry point', () => {
+ it("is wired up by the app entry point", () => {
expect(mainSource).toMatch(
/^setTelemetrySuppressed\(\(\) => useAuthStore\.getState\(\)\.demoSession\)$/m,
- )
- })
-
- it('sends nothing from a demo session', () => {
- useAuthStore.setState({ demoSession: true })
- pushBoundaryError(1)
- reportWebVital({ name: 'LCP', value: 1234.5, rating: 'good', delta: 1234.5 } as never)
- flush()
- expect(sent.length, 'a demo session sent telemetry the demo refuses').toBe(0)
- })
-
- it('drops the demo batch instead of holding it for later', () => {
- useAuthStore.setState({ demoSession: true })
- pushBoundaryError(1)
- flush()
- useAuthStore.setState({ demoSession: false })
- flush()
- expect(sent.length, 'events captured during the demo session were sent afterwards').toBe(0)
- })
-
- it('still sends from an ordinary session', () => {
- useAuthStore.setState({ demoSession: false })
- pushBoundaryError(1)
- flush()
- expect(deliveredErrorCount()).toBe(1)
- })
-})
+ );
+ });
+
+ it("sends nothing from a demo session", () => {
+ useAuthStore.setState({ demoSession: true });
+ pushBoundaryError(1);
+ reportWebVital({
+ name: "LCP",
+ value: 1234.5,
+ rating: "good",
+ delta: 1234.5,
+ } as never);
+ flush();
+ expect(sent.length, "a demo session sent telemetry the demo refuses").toBe(
+ 0,
+ );
+ });
+
+ it("drops the demo batch instead of holding it for later", () => {
+ useAuthStore.setState({ demoSession: true });
+ pushBoundaryError(1);
+ flush();
+ useAuthStore.setState({ demoSession: false });
+ flush();
+ expect(
+ sent.length,
+ "events captured during the demo session were sent afterwards",
+ ).toBe(0);
+ });
+
+ it("still sends from an ordinary session", () => {
+ useAuthStore.setState({ demoSession: false });
+ pushBoundaryError(1);
+ flush();
+ expect(deliveredErrorCount()).toBe(1);
+ });
+});
diff --git a/frontend/src/utils/errorReporting.ts b/frontend/src/utils/errorReporting.ts
index 1598e9da9..a204e141b 100644
--- a/frontend/src/utils/errorReporting.ts
+++ b/frontend/src/utils/errorReporting.ts
@@ -11,7 +11,7 @@
* using navigator.sendBeacon on page unload and a periodic flush timer.
*/
-import type { Metric } from 'web-vitals'
+import type { Metric } from "web-vitals";
/**
* Whether this session sends no telemetry. The public read-only demo refuses
@@ -20,16 +20,16 @@ import type { Metric } from 'web-vitals'
* the API client, which reads `window` as it loads, and error boundaries
* import this module lazily, sometimes after a test's environment is gone.
*/
-let _telemetrySuppressed: () => boolean = () => false
+let _telemetrySuppressed: () => boolean = () => false;
export function setTelemetrySuppressed(check: () => boolean): void {
- _telemetrySuppressed = check
+ _telemetrySuppressed = check;
}
// When VITE_API_BASE_URL is unset, use a same-origin relative URL so the
// reporter follows the page through any ingress (k8s, gcp, aws, reference K3s install).
// VITE_API_URL is also accepted as a legacy alias.
-const API_ENDPOINT = `${import.meta.env.VITE_API_URL ?? import.meta.env.VITE_API_BASE_URL ?? ''}/api/v1/observability/frontend`
+const API_ENDPOINT = `${import.meta.env.VITE_API_URL ?? import.meta.env.VITE_API_BASE_URL ?? ""}/api/v1/observability/frontend`;
/**
* The page address without its query string or fragment.
@@ -37,32 +37,32 @@ const API_ENDPOINT = `${import.meta.env.VITE_API_URL ?? import.meta.env.VITE_API
* Invite, password-reset and SSO values ride in the fragment so that they
* never reach a server; `location.href` would send them with every record.
*/
-const _pageUrl = (): string => location.origin + location.pathname
+const _pageUrl = (): string => location.origin + location.pathname;
// ── Types ─────────────────────────────────────────────────────────────────────
interface FrontendError {
- type: 'error' | 'unhandledrejection' | 'boundary'
- message: string
- stack?: string
- component_stack?: string
- url: string
- user_agent: string
- timestamp: string
- context?: Record
+ type: "error" | "unhandledrejection" | "boundary";
+ message: string;
+ stack?: string;
+ component_stack?: string;
+ url: string;
+ user_agent: string;
+ timestamp: string;
+ context?: Record;
}
interface WebVitalReport {
- name: string
- value: number
- rating: string
- url: string
- delta?: number
+ name: string;
+ value: number;
+ rating: string;
+ url: string;
+ delta?: number;
}
interface TelemetryBatch {
- errors: FrontendError[]
- vitals: WebVitalReport[]
+ errors: FrontendError[];
+ vitals: WebVitalReport[];
}
// ── Batch buffer ──────────────────────────────────────────────────────────────
@@ -81,19 +81,49 @@ interface TelemetryBatch {
* every render produces them in a fraction of a second, which is exactly the
* incident the report exists for. Batches are therefore split to fit.
*/
-const BEACON_LIMIT_BYTES = 60_000
+const BEACON_LIMIT_BYTES = 60_000;
/**
* Per-event truncation, applied at capture.
*
- * Bounds a single event to roughly 6 KB so one enormous stack cannot produce a
+ * Bounds every captured string, including its serialized UTF-8 size, so an
+ * enormous message or escaped stack cannot produce a
* chunk that nothing can send. The backend truncates `stack` at 5000 and
* `message` at 2000 anyway, so this discards only what would have been dropped
* server-side — except that here it is discarded before it can cost us the
* whole batch.
*/
-const MAX_STACK_CHARS = 4000
-const MAX_COMPONENT_STACK_CHARS = 2000
+const MAX_STACK_CHARS = 4000;
+const MAX_COMPONENT_STACK_CHARS = 2000;
+const MAX_MESSAGE_CHARS = 2000;
+const MAX_URL_CHARS = 2000;
+const MAX_USER_AGENT_CHARS = 500;
+const utf8 = new TextEncoder();
+
+/** Bound JSON-encoded bytes too: control characters expand to six bytes. */
+function _boundedText(value: string, maxChars: number): string {
+ const prefix = (length: number) => {
+ const text = value.slice(0, length);
+ // Keep a surrogate pair together at a truncation boundary.
+ return /[\uD800-\uDBFF]$/.test(text) ? text.slice(0, -1) : text;
+ };
+ const bounded = prefix(maxChars);
+ const budget = maxChars * 3;
+ if (utf8.encode(JSON.stringify(bounded)).byteLength <= budget) return bounded;
+ let low = 0;
+ let high = bounded.length;
+ while (low < high) {
+ const middle = Math.ceil((low + high) / 2);
+ if (utf8.encode(JSON.stringify(prefix(middle))).byteLength <= budget)
+ low = middle;
+ else high = middle - 1;
+ }
+ return prefix(low);
+}
+
+function _boundedUrl(value: string): string {
+ return _boundedText(value.split(/[?#]/, 1)[0], MAX_URL_CHARS);
+}
/**
* Bound the buffer so a render loop cannot grow it without limit.
@@ -102,28 +132,28 @@ const MAX_COMPONENT_STACK_CHARS = 2000
* error buffer gets one more record on send (the "events dropped" note in
* `flush`), so it holds 49.
*/
-const MAX_BUFFERED_ERRORS = 49
-const MAX_BUFFERED_VITALS = 50
+const MAX_BUFFERED_ERRORS = 49;
+const MAX_BUFFERED_VITALS = 50;
/** Stop rescheduling after this many consecutive failed flushes. */
-const MAX_FLUSH_RETRIES = 3
+const MAX_FLUSH_RETRIES = 3;
-const _batch: TelemetryBatch = { errors: [], vitals: [] }
-let _flushTimer: ReturnType | null = null
-let _droppedEvents = 0
-let _consecutiveFailures = 0
+const _batch: TelemetryBatch = { errors: [], vitals: [] };
+let _flushTimer: ReturnType | null = null;
+let _droppedEvents = 0;
+let _consecutiveFailures = 0;
function _scheduleFlush(): void {
- if (_flushTimer) return
+ if (_flushTimer) return;
_flushTimer = setTimeout(() => {
- _flushTimer = null
- flush()
- }, 5000) // batch window: 5 s
+ _flushTimer = null;
+ flush();
+ }, 5000); // batch window: 5 s
}
/** Serialized size of a batch, measured the way the transport measures it. */
function _sizeOf(batch: TelemetryBatch): number {
- return JSON.stringify(batch).length
+ return utf8.encode(JSON.stringify(batch)).byteLength;
}
/**
@@ -134,28 +164,37 @@ function _sizeOf(batch: TelemetryBatch): number {
* limit on its own, so every event lands in some piece.
*/
function _partition(batch: TelemetryBatch): TelemetryBatch[] {
- if (_sizeOf(batch) <= BEACON_LIMIT_BYTES) return [batch]
-
- const pieces: TelemetryBatch[] = []
- let current: TelemetryBatch = { errors: [], vitals: [] }
- let currentSize = _sizeOf(current)
-
- const add = (item: FrontendError | WebVitalReport, into: 'errors' | 'vitals') => {
- const itemSize = JSON.stringify(item).length + 1 // + comma
- const isEmpty = current.errors.length === 0 && current.vitals.length === 0
- if (!isEmpty && currentSize + itemSize > BEACON_LIMIT_BYTES) {
- pieces.push(current)
- current = { errors: [], vitals: [] }
- currentSize = _sizeOf(current)
+ if (_sizeOf(batch) <= BEACON_LIMIT_BYTES) return [batch];
+
+ const pieces: TelemetryBatch[] = [];
+ let current: TelemetryBatch = { errors: [], vitals: [] };
+
+ const add = (
+ item: FrontendError | WebVitalReport,
+ into: "errors" | "vitals",
+ ) => {
+ const candidate: TelemetryBatch = {
+ errors:
+ into === "errors"
+ ? [...current.errors, item as FrontendError]
+ : current.errors,
+ vitals:
+ into === "vitals"
+ ? [...current.vitals, item as WebVitalReport]
+ : current.vitals,
+ };
+ const isEmpty = current.errors.length === 0 && current.vitals.length === 0;
+ if (!isEmpty && _sizeOf(candidate) > BEACON_LIMIT_BYTES) {
+ pieces.push(current);
+ current = { errors: [], vitals: [] };
}
- ;(current[into] as unknown[]).push(item)
- currentSize += itemSize
- }
+ (current[into] as unknown[]).push(item);
+ };
- for (const err of batch.errors) add(err, 'errors')
- for (const vital of batch.vitals) add(vital, 'vitals')
- if (current.errors.length || current.vitals.length) pieces.push(current)
- return pieces
+ for (const err of batch.errors) add(err, "errors");
+ for (const vital of batch.vitals) add(vital, "vitals");
+ if (current.errors.length || current.vitals.length) pieces.push(current);
+ return pieces;
}
/**
@@ -169,22 +208,22 @@ function _transmit(payload: string): boolean {
try {
if (navigator.sendBeacon) {
// sendBeacon is the only transport that survives page unload.
- const blob = new Blob([payload], { type: 'application/json' })
- return navigator.sendBeacon(API_ENDPOINT, blob)
+ const blob = new Blob([payload], { type: "application/json" });
+ return navigator.sendBeacon(API_ENDPOINT, blob);
}
// No sendBeacon at all (not a real browser we ship to, but keep the path).
fetch(API_ENDPOINT, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
body: payload,
keepalive: true,
}).catch(() => {
/* best-effort — ignore network failures */
- })
- return true
+ });
+ return true;
} catch {
/* never throw from error reporting */
- return false
+ return false;
}
}
@@ -197,72 +236,80 @@ function _transmit(payload: string): boolean {
* refused send destroyed the batch silently.
*/
export function flush(): void {
- if (_batch.errors.length === 0 && _batch.vitals.length === 0 && _droppedEvents === 0) return
+ if (
+ _batch.errors.length === 0 &&
+ _batch.vitals.length === 0 &&
+ _droppedEvents === 0
+ )
+ return;
// The public read-only demo refuses every write, this report included (403
// at the Cloudflare edge and in the app), so a send from a demo session can
// only fail and print a refusal in the console. Drop the batch rather than
// hold it for a retry that is refused the same way.
if (_telemetrySuppressed()) {
- _batch.errors.length = 0
- _batch.vitals.length = 0
- _droppedEvents = 0
- return
+ _batch.errors.length = 0;
+ _batch.vitals.length = 0;
+ _droppedEvents = 0;
+ return;
}
- const errors = [..._batch.errors]
- const vitals = [..._batch.vitals]
- _batch.errors.length = 0
- _batch.vitals.length = 0
+ const errors = [..._batch.errors];
+ const vitals = [..._batch.vitals];
+ _batch.errors.length = 0;
+ _batch.vitals.length = 0;
// Tell the backend the report is incomplete. Silent truncation is
// indistinguishable from silence, and this path only fires during a storm.
if (_droppedEvents > 0) {
errors.push({
- type: 'error',
+ type: "error",
message: `telemetry buffer overflow: ${_droppedEvents} events dropped before send`,
- url: typeof window !== 'undefined' ? _pageUrl() : '',
- user_agent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
+ url: typeof window !== "undefined" ? _boundedUrl(_pageUrl()) : "",
+ user_agent:
+ typeof navigator !== "undefined"
+ ? _boundedText(navigator.userAgent, MAX_USER_AGENT_CHARS)
+ : "",
timestamp: new Date().toISOString(),
context: { dropped: _droppedEvents },
- })
- _droppedEvents = 0
+ });
+ _droppedEvents = 0;
}
- const refused: TelemetryBatch = { errors: [], vitals: [] }
+ const refused: TelemetryBatch = { errors: [], vitals: [] };
for (const piece of _partition({ errors, vitals })) {
- let payload: string
+ let payload: string;
try {
- payload = JSON.stringify(piece)
+ payload = JSON.stringify(piece);
} catch {
- continue // unserializable — dropping it is the only option
+ continue; // unserializable — dropping it is the only option
}
if (!_transmit(payload)) {
- refused.errors.push(...piece.errors)
- refused.vitals.push(...piece.vitals)
+ refused.errors.push(...piece.errors);
+ refused.vitals.push(...piece.vitals);
}
}
if (refused.errors.length || refused.vitals.length) {
// Put them back at the front — oldest events are the ones with context.
- _batch.errors.unshift(...refused.errors)
- _batch.vitals.unshift(...refused.vitals)
- _enforceBufferBounds()
- if (++_consecutiveFailures < MAX_FLUSH_RETRIES) _scheduleFlush()
+ _batch.errors.unshift(...refused.errors);
+ _batch.vitals.unshift(...refused.vitals);
+ _enforceBufferBounds();
+ if (++_consecutiveFailures < MAX_FLUSH_RETRIES) _scheduleFlush();
} else {
- _consecutiveFailures = 0
+ _consecutiveFailures = 0;
}
}
/** Trim the buffer to its bounds, recording how much was discarded. */
function _enforceBufferBounds(): void {
if (_batch.errors.length > MAX_BUFFERED_ERRORS) {
- _droppedEvents += _batch.errors.length - MAX_BUFFERED_ERRORS
- _batch.errors.splice(MAX_BUFFERED_ERRORS)
+ _droppedEvents += _batch.errors.length - MAX_BUFFERED_ERRORS;
+ _batch.errors.splice(MAX_BUFFERED_ERRORS);
}
if (_batch.vitals.length > MAX_BUFFERED_VITALS) {
- _droppedEvents += _batch.vitals.length - MAX_BUFFERED_VITALS
- _batch.vitals.splice(MAX_BUFFERED_VITALS)
+ _droppedEvents += _batch.vitals.length - MAX_BUFFERED_VITALS;
+ _batch.vitals.splice(MAX_BUFFERED_VITALS);
}
}
@@ -270,71 +317,97 @@ function _enforceBufferBounds(): void {
/** Strip full file paths from stack traces, keeping only filename + line number. */
function _sanitizeStack(stack: string | undefined): string | undefined {
- if (!stack) return stack
+ if (!stack) return stack;
// Replace full paths like /home/user/project/src/file.ts:42:10 → file.ts:42:10
- return stack.replace(/(?:\/[\w./-]+\/|[A-Z]:\\[\w.\\-]+\\)([\w.-]+:\d+)/g, '$1')
+ return stack.replace(
+ /(?:\/[\w./-]+\/|[A-Z]:\\[\w.\\-]+\\)([\w.-]+:\d+)/g,
+ "$1",
+ );
}
/** Redact potential PII patterns from error messages. */
function _sanitizeMessage(msg: string): string {
- return msg
- // Email addresses
- .replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, '[REDACTED_EMAIL]')
- // Phone numbers
- .replace(/\b(\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g, '[REDACTED_PHONE]')
- // Bearer tokens — lowered floor from 20 → 8 to catch short opaque tokens
- // (e.g., session IDs) while still avoiding obvious false positives like
- // "Bearer token".
- .replace(/Bearer\s+[A-Za-z0-9\-_.=]{8,}/gi, 'Bearer [REDACTED]')
- // API keys — accept shorter keys (8+) because some integrations ship
- // 10-12 character keys and would otherwise leak.
- .replace(/api[_-]?key\s*[:=]\s*['"]?[A-Za-z0-9\-_]{8,}['"]?/gi, 'api_key=[REDACTED]')
- // Known TestLookup API key prefixes (tl_, qai_, scim_) — catches keys
- // that appear bare in a message without the "api_key=" antecedent.
- .replace(/\b(?:tl|qai|scim)_[A-Za-z0-9\-_]{16,}/g, '[REDACTED_KEY]')
- // JWT tokens (three base64url-ish sections separated by dots)
- .replace(/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, '[REDACTED_JWT]')
- // Connection strings with passwords
- .replace(/(\/\/[^:]+:)[^@]{4,}(@)/g, '$1[REDACTED]$2')
+ return (
+ msg
+ // Email addresses
+ .replace(
+ /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,
+ "[REDACTED_EMAIL]",
+ )
+ // Phone numbers
+ .replace(
+ /\b(\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g,
+ "[REDACTED_PHONE]",
+ )
+ // Bearer tokens — lowered floor from 20 → 8 to catch short opaque tokens
+ // (e.g., session IDs) while still avoiding obvious false positives like
+ // "Bearer token".
+ .replace(/Bearer\s+[A-Za-z0-9\-_.=]{8,}/gi, "Bearer [REDACTED]")
+ // API keys — accept shorter keys (8+) because some integrations ship
+ // 10-12 character keys and would otherwise leak.
+ .replace(
+ /api[_-]?key\s*[:=]\s*['"]?[A-Za-z0-9\-_]{8,}['"]?/gi,
+ "api_key=[REDACTED]",
+ )
+ // Known TestLookup API key prefixes (tl_, qai_, scim_) — catches keys
+ // that appear bare in a message without the "api_key=" antecedent.
+ .replace(/\b(?:tl|qai|scim)_[A-Za-z0-9\-_]{16,}/g, "[REDACTED_KEY]")
+ // JWT tokens (three base64url-ish sections separated by dots)
+ .replace(
+ /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
+ "[REDACTED_JWT]",
+ )
+ // Connection strings with passwords
+ .replace(/(\/\/[^:]+:)[^@]{4,}(@)/g, "$1[REDACTED]$2")
+ );
}
// ── Error capture ─────────────────────────────────────────────────────────────
function _capture(error: FrontendError): void {
// Sanitize before buffering (PR-5: never send raw PII to backend)
- error.message = _sanitizeMessage(error.message)
- error.stack = _sanitizeStack(error.stack)?.slice(0, MAX_STACK_CHARS)
+ error.message = _boundedText(
+ _sanitizeMessage(error.message),
+ MAX_MESSAGE_CHARS,
+ );
+ error.url = _boundedUrl(error.url);
+ error.user_agent = _boundedText(error.user_agent, MAX_USER_AGENT_CHARS);
+ const stack = _sanitizeStack(error.stack);
+ error.stack = stack ? _boundedText(stack, MAX_STACK_CHARS) : stack;
if (error.component_stack) {
- error.component_stack = _sanitizeStack(error.component_stack)?.slice(
- 0,
+ error.component_stack = _boundedText(
+ _sanitizeStack(error.component_stack) ?? "",
MAX_COMPONENT_STACK_CHARS,
- )
+ );
}
- _batch.errors.push(error)
- _enforceBufferBounds()
- _scheduleFlush()
+ _batch.errors.push(error);
+ _enforceBufferBounds();
+ _scheduleFlush();
}
/** Report an error caught by a React Error Boundary. */
-export function reportBoundaryError(error: Error, componentStack: string): void {
+export function reportBoundaryError(
+ error: Error,
+ componentStack: string,
+): void {
_capture({
- type: 'boundary',
+ type: "boundary",
message: error.message,
stack: error.stack,
component_stack: componentStack,
url: _pageUrl(),
user_agent: navigator.userAgent,
timestamp: new Date().toISOString(),
- })
+ });
}
// ── Global error listeners ────────────────────────────────────────────────────
/** Install window-level error and unhandledrejection handlers. Call once from main.tsx. */
export function installGlobalErrorHandlers(): void {
- window.addEventListener('error', (event) => {
+ window.addEventListener("error", (event) => {
_capture({
- type: 'error',
+ type: "error",
message: event.message || String(event.error),
stack: event.error?.stack,
url: event.filename || _pageUrl(),
@@ -344,26 +417,26 @@ export function installGlobalErrorHandlers(): void {
lineno: event.lineno,
colno: event.colno,
},
- })
- })
+ });
+ });
- window.addEventListener('unhandledrejection', (event) => {
- const reason = event.reason
+ window.addEventListener("unhandledrejection", (event) => {
+ const reason = event.reason;
_capture({
- type: 'unhandledrejection',
+ type: "unhandledrejection",
message: reason instanceof Error ? reason.message : String(reason),
stack: reason instanceof Error ? reason.stack : undefined,
url: _pageUrl(),
user_agent: navigator.userAgent,
timestamp: new Date().toISOString(),
- })
- })
+ });
+ });
// Flush on page unload
- window.addEventListener('visibilitychange', () => {
- if (document.visibilityState === 'hidden') flush()
- })
- window.addEventListener('pagehide', flush)
+ window.addEventListener("visibilitychange", () => {
+ if (document.visibilityState === "hidden") flush();
+ });
+ window.addEventListener("pagehide", flush);
}
// ── Web Vitals reporting ──────────────────────────────────────────────────────
@@ -371,12 +444,12 @@ export function installGlobalErrorHandlers(): void {
/** Called by useWebVitals hook with each Core Web Vital measurement. */
export function reportWebVital(metric: Metric): void {
_batch.vitals.push({
- name: metric.name,
+ name: _boundedText(metric.name, 64),
value: metric.value,
- rating: metric.rating,
- url: _pageUrl(),
+ rating: _boundedText(metric.rating, 64),
+ url: _boundedUrl(_pageUrl()),
delta: metric.delta,
- })
- _enforceBufferBounds()
- _scheduleFlush()
+ });
+ _enforceBufferBounds();
+ _scheduleFlush();
}
diff --git a/frontend/tests/visual/production/fixtures-in-page-b.ts b/frontend/tests/visual/production/fixtures-in-page-b.ts
index 0c284c9df..84e133423 100644
--- a/frontend/tests/visual/production/fixtures-in-page-b.ts
+++ b/frontend/tests/visual/production/fixtures-in-page-b.ts
@@ -717,11 +717,11 @@ export const UM_USERS = {
}
/** The one-time values the fixtures answer (fixture strings, not real secrets). */
export const ONE_TIME = {
- tempPassword: 'Tmp-w27b-fixture-Zq81x',
+ tempPassword: 'Tmp-w27b-fixture-Zq81x', // gitleaks:allow -- synthetic test credential, never production authority
invitePath: '/accept-invite#token=w27b-fixture-invite-token',
- streamingKey: 'qai_w27b_fixture_streaming_key_0001',
- personalKey: 'qai_w27b_fixture_personal_key_0002',
- qaLeadPassword: 'QaLead-w27b-fixture-Pw77',
+ streamingKey: 'qai_w27b_fixture_streaming_key_0001', // gitleaks:allow -- synthetic test credential, never production authority
+ personalKey: 'qai_w27b_fixture_personal_key_0002', // gitleaks:allow -- synthetic test credential, never production authority
+ qaLeadPassword: 'QaLead-w27b-fixture-Pw77', // gitleaks:allow -- synthetic test credential, never production authority
}
export const DEFAULT_QA_LEAD_EMAIL = 'qa-lead-checkout@example.test'
/** The id the next created user gets. */
diff --git a/infra/monitoring/prometheus-rules/testlookup-alerts.yml b/infra/monitoring/prometheus-rules/testlookup-alerts.yml
index 9b9645d0c..aa34fa98d 100644
--- a/infra/monitoring/prometheus-rules/testlookup-alerts.yml
+++ b/infra/monitoring/prometheus-rules/testlookup-alerts.yml
@@ -14,6 +14,54 @@ groups:
summary: "TestLookup backend is down"
description: "The FastAPI backend has been unreachable for more than 1 minute."
+ # The scrape can succeed while one operational dependency cannot be read.
+ # Keep per-target labels: another healthy API replica must not hide it.
+ - alert: TestLookupOperationalCollectionStale
+ expr: |
+ testlookup_metric_collection_success == 0
+ or
+ (time() - testlookup_metric_collection_last_success_timestamp_seconds) > 120
+ for: 2m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Operational metric collection failed or is stale"
+ description: "Collector {{ $labels.collector }} cannot provide a fresh snapshot on this target. Scrape availability alone does not prove dependency health; inspect metric_collection_failed logs before trusting the retained gauges."
+
+ # Each API replica reads the SAME SQL outbox. max avoids counting one
+ # failure twice; cluster/namespace preserve independent installations.
+ - alert: TestLookupDownstreamOutboxFailed
+ expr: |
+ max by (cluster, namespace, operation) (
+ testlookup_downstream_outbox_entries{status="failed"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{collector="downstream"} == 1)
+ and on (cluster, namespace, job, instance)
+ ((time() - testlookup_metric_collection_last_success_timestamp_seconds{collector="downstream"}) <= 120)
+ ) > 0
+ for: 1m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Durable downstream work exhausted retries"
+ description: "Operation {{ $labels.operation }} has {{ $value }} terminal failed outbox rows. Empty broker queues and Celery SUCCESS do not imply business completion. Inspect durable outbox outcomes and use the authorized replay process after fixing the cause."
+
+ - alert: TestLookupDownstreamOutboxOverdue
+ expr: |
+ max by (cluster, namespace, operation) (
+ testlookup_downstream_outbox_overdue_seconds{status=~"waiting|pending|sending|published|processing"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{collector="downstream"} == 1)
+ and on (cluster, namespace, job, instance)
+ ((time() - testlookup_metric_collection_last_success_timestamp_seconds{collector="downstream"}) <= 120)
+ ) > 300
+ for: 5m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Durable downstream work missed its retry or lease deadline"
+ description: "Operation {{ $labels.operation }} is {{ $value }} seconds beyond its stored retry or execution lease deadline. The rule includes a five-minute margin and does not treat scheduled future retries as stuck. Inspect relay and worker health."
+
# High HTTP 5xx error rate
- alert: TestLookupHighErrorRate
expr: |
@@ -493,10 +541,12 @@ groups:
- alert: TestLookupWebhookDeliveryFailureRate
expr: |
(
- sum(rate(testlookup_webhook_delivery_attempts_total{result="failure"}[15m]))
+ sum by (cluster, namespace) (rate(testlookup_webhook_delivery_attempts_total{result="failure"}[15m]))
/
- clamp_min(sum(rate(testlookup_webhook_delivery_attempts_total[15m])), 1)
+ sum by (cluster, namespace) (rate(testlookup_webhook_delivery_attempts_total[15m]))
) > 0.05
+ and on (cluster, namespace)
+ sum by (cluster, namespace) (rate(testlookup_webhook_delivery_attempts_total[15m])) > 0
for: 15m
labels:
severity: warning
diff --git a/infra/monitoring/tests/operational-alerts.yml b/infra/monitoring/tests/operational-alerts.yml
new file mode 100644
index 000000000..b01069d1e
--- /dev/null
+++ b/infra/monitoring/tests/operational-alerts.yml
@@ -0,0 +1,348 @@
+# Run from this directory: promtool test rules operational-alerts.yml
+# Loads actual production rules; never put fixture files in prometheus-rules/.
+# Synthetic samples and evaluation only: no notifications or application data.
+# Future retry timestamps are converted to zero overdue by the Python collector;
+# these fixtures check alert semantics, while collector tests check that mapping.
+rule_files:
+- ../prometheus-rules/testlookup-alerts.yml
+evaluation_interval: 30s
+tests:
+- name: stale SQL snapshots cannot override a fresh replica or mask recovery
+ interval: 30s
+ input_series:
+ - series: testlookup_downstream_outbox_entries{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-fresh",operation="agent_pipeline",status="failed"}
+ values: '2x25 0x14'
+ - series: testlookup_downstream_outbox_entries{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-failed-read",operation="agent_pipeline",status="failed"}
+ values: '9x40'
+ - series: testlookup_downstream_outbox_entries{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-stale-time",operation="agent_pipeline",status="failed"}
+ values: '9x40'
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-fresh",operation="agent_pipeline",status="processing"}
+ values: '0x40'
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-failed-read",operation="agent_pipeline",status="processing"}
+ values: '900x40'
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-stale-time",operation="agent_pipeline",status="processing"}
+ values: '900x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-fresh",collector="downstream"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-fresh",collector="downstream"}
+ values: '0+30x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-failed-read",collector="downstream"}
+ values: '0x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-failed-read",collector="downstream"}
+ values: '0+30x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-stale-time",collector="downstream"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-stale-time",collector="downstream"}
+ values: '0x40'
+ alert_rule_test:
+ - eval_time: 10m
+ alertname: TestLookupDownstreamOutboxFailed
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ operation: agent_pipeline
+ severity: warning
+ exp_annotations:
+ summary: Durable downstream work exhausted retries
+ description: Operation agent_pipeline has 2 terminal failed outbox rows. Empty broker queues and Celery SUCCESS do not imply business completion. Inspect durable outbox outcomes and use the authorized replay process after fixing the cause.
+ - eval_time: 13m
+ alertname: TestLookupDownstreamOutboxFailed
+ exp_alerts: []
+ - eval_time: 10m
+ alertname: TestLookupDownstreamOutboxOverdue
+ exp_alerts: []
+ promql_expr_test:
+ - expr: count(ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"})
+ eval_time: 10m
+ exp_samples:
+ - labels: '{}'
+ value: 2
+- name: collector failure is per target, waits two minutes, and resolves
+ interval: 30s
+ input_series:
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",instance="api-a",collector="downstream"}
+ values: 1x1 0x5 1x4
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",instance="api-a",collector="downstream"}
+ values: 0+30x1 30x5 240+30x4
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",instance="api-b",collector="downstream"}
+ values: 1x12
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",instance="api-b",collector="downstream"}
+ values: 0+30x12
+ promql_expr_test:
+ - expr: ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"}
+ eval_time: 2m30s
+ exp_samples: []
+ - expr: count by (cluster,namespace,instance,collector) (ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"})
+ eval_time: 3m
+ exp_samples:
+ - labels: '{cluster="lab",namespace="prod",instance="api-a",collector="downstream"}'
+ value: 1
+ - expr: ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"}
+ eval_time: 4m
+ exp_samples: []
+- name: success flag alone cannot hide a stale timestamp, and fresh collection recovers
+ interval: 30s
+ input_series:
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",instance="api-a",collector="queues"}
+ values: 1x12
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",instance="api-a",collector="queues"}
+ values: 0x9 300+30x2
+ promql_expr_test:
+ - expr: ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"}
+ eval_time: 2m
+ exp_samples: []
+ - expr: ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"}
+ eval_time: 4m
+ exp_samples: []
+ - expr: count by (collector,instance) (ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"})
+ eval_time: 4m30s
+ exp_samples:
+ - labels: '{collector="queues",instance="api-a"}'
+ value: 1
+ - expr: ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"}
+ eval_time: 5m
+ exp_samples: []
+- name: terminal SQL outcomes use MAX across replicas and retain installation scope
+ interval: 30s
+ input_series:
+ - series: testlookup_downstream_outbox_entries{cluster="lab",namespace="prod",instance="api-a",operation="agent_pipeline",status="failed",job="testlookup-backend"}
+ values: 2x5 0x3
+ - series: testlookup_downstream_outbox_entries{cluster="lab",namespace="prod",instance="api-b",operation="agent_pipeline",status="failed",job="testlookup-backend"}
+ values: 2x5 0x3
+ - series: testlookup_downstream_outbox_entries{cluster="lab",namespace="other",instance="api-c",operation="agent_pipeline",status="failed",job="testlookup-backend"}
+ values: '0x9'
+ - series: testlookup_downstream_outbox_entries{cluster="other-cluster",namespace="prod",instance="api-d",operation="agent_pipeline",status="failed",job="testlookup-backend"}
+ values: 1x5 0x3
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 0+30x50
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-b",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-b",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 0+30x50
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-c",job="testlookup-backend",namespace="other",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-c",job="testlookup-backend",namespace="other",collector="downstream"}
+ values: 0+30x50
+ - series: testlookup_metric_collection_success{cluster="other-cluster",instance="api-d",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="other-cluster",instance="api-d",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 0+30x50
+ alert_rule_test:
+ - eval_time: 30s
+ alertname: TestLookupDownstreamOutboxFailed
+ exp_alerts: []
+ - eval_time: 1m
+ alertname: TestLookupDownstreamOutboxFailed
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ operation: agent_pipeline
+ severity: warning
+ exp_annotations:
+ summary: Durable downstream work exhausted retries
+ description: Operation agent_pipeline has 2 terminal failed outbox rows. Empty broker queues and Celery SUCCESS do
+ not imply business completion. Inspect durable outbox outcomes and use the authorized replay process after fixing
+ the cause.
+ - exp_labels:
+ cluster: other-cluster
+ namespace: prod
+ operation: agent_pipeline
+ severity: warning
+ exp_annotations:
+ summary: Durable downstream work exhausted retries
+ description: Operation agent_pipeline has 1 terminal failed outbox rows. Empty broker queues and Celery SUCCESS do
+ not imply business completion. Inspect durable outbox outcomes and use the authorized replay process after fixing
+ the cause.
+ - eval_time: 3m
+ alertname: TestLookupDownstreamOutboxFailed
+ exp_alerts: []
+- name: overdue must exceed 300 seconds and persist five minutes before firing
+ interval: 30s
+ input_series:
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="prod",instance="api-a",operation="agent_pipeline",status="published",job="testlookup-backend"}
+ values: 300x3 301x10 0x2
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="prod",instance="api-b",operation="agent_pipeline",status="published",job="testlookup-backend"}
+ values: '0x16'
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="terminal",operation="agent_pipeline",status="failed",instance="api-a",job="testlookup-backend"}
+ values: 9999x16
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 0+30x50
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="terminal",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="terminal",collector="downstream"}
+ values: 0+30x50
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-b",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-b",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 0+30x50
+ promql_expr_test:
+ - expr: ALERTS{alertname="TestLookupDownstreamOutboxOverdue",alertstate="firing"}
+ eval_time: 1m30s
+ exp_samples: []
+ - expr: ALERTS{alertname="TestLookupDownstreamOutboxOverdue",alertstate="firing"}
+ eval_time: 6m30s
+ exp_samples: []
+ - expr: count by (cluster,namespace,operation) (ALERTS{alertname="TestLookupDownstreamOutboxOverdue",alertstate="firing"})
+ eval_time: 7m
+ exp_samples:
+ - labels: '{cluster="lab",namespace="prod",operation="agent_pipeline"}'
+ value: 1
+ - expr: ALERTS{alertname="TestLookupDownstreamOutboxOverdue",alertstate="firing"}
+ eval_time: 7m30s
+ exp_samples: []
+- name: every nonterminal SQL state is covered without blending namespaces
+ interval: 1m
+ input_series:
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="waiting-ns",operation="agent_pipeline",status="waiting",instance="api-a",job="testlookup-backend"}
+ values: 401x8
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="pending-ns",operation="agent_pipeline",status="pending",instance="api-a",job="testlookup-backend"}
+ values: 401x8
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="sending-ns",operation="agent_pipeline",status="sending",instance="api-a",job="testlookup-backend"}
+ values: 401x8
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="published-ns",operation="agent_pipeline",status="published",instance="api-a",job="testlookup-backend"}
+ values: 401x8
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="processing-ns",operation="agent_pipeline",status="processing",instance="api-a",job="testlookup-backend"}
+ values: 401x8
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="pending-ns",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="pending-ns",collector="downstream"}
+ values: 0+60x50
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="processing-ns",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="processing-ns",collector="downstream"}
+ values: 0+60x50
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="published-ns",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="published-ns",collector="downstream"}
+ values: 0+60x50
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="sending-ns",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="sending-ns",collector="downstream"}
+ values: 0+60x50
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="waiting-ns",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="waiting-ns",collector="downstream"}
+ values: 0+60x50
+ promql_expr_test:
+ - expr: ALERTS{alertname="TestLookupDownstreamOutboxOverdue",alertstate="firing"}
+ eval_time: 4m30s
+ exp_samples: []
+ - expr: count by (cluster,namespace) (ALERTS{alertname="TestLookupDownstreamOutboxOverdue",alertstate="firing"})
+ eval_time: 5m
+ exp_samples:
+ - labels: '{cluster="lab",namespace="waiting-ns"}'
+ value: 1
+ - labels: '{cluster="lab",namespace="pending-ns"}'
+ value: 1
+ - labels: '{cluster="lab",namespace="sending-ns"}'
+ value: 1
+ - labels: '{cluster="lab",namespace="published-ns"}'
+ value: 1
+ - labels: '{cluster="lab",namespace="processing-ns"}'
+ value: 1
+- name: future retries and completed work remain healthy
+ interval: 1m
+ input_series:
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="prod",operation="agent_pipeline",status="pending",instance="api-a",job="testlookup-backend"}
+ values: '0x20'
+ - series: testlookup_downstream_outbox_overdue_seconds{cluster="lab",namespace="prod",operation="agent_pipeline",status="waiting",instance="api-a",job="testlookup-backend"}
+ values: '0x20'
+ - series: testlookup_downstream_outbox_entries{cluster="lab",namespace="prod",operation="agent_pipeline",status="failed",instance="api-a",job="testlookup-backend"}
+ values: '0x20'
+ - series: testlookup_downstream_outbox_entries{cluster="lab",namespace="prod",operation="agent_pipeline",status="completed",instance="api-a",job="testlookup-backend"}
+ values: 1000x20
+ - series: testlookup_metric_collection_success{cluster="lab",instance="api-a",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",instance="api-a",job="testlookup-backend",namespace="prod",collector="downstream"}
+ values: 0+60x50
+ alert_rule_test:
+ - eval_time: 20m
+ alertname: TestLookupDownstreamOutboxOverdue
+ exp_alerts: []
+ - eval_time: 20m
+ alertname: TestLookupDownstreamOutboxFailed
+ exp_alerts: []
+- name: one terminal webhook failure per minute fires without fleet-rate dilution
+ interval: 1m
+ input_series:
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="quiet",result="failure"}
+ values: 0+1x40
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="quiet",result="success"}
+ values: '0x40'
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="busy",result="failure"}
+ values: '0x40'
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="busy",result="success"}
+ values: 0+10000x40
+ promql_expr_test:
+ - expr: ALERTS{alertname="TestLookupWebhookDeliveryFailureRate",alertstate="firing"}
+ eval_time: 15m30s
+ exp_samples: []
+ - expr: count by (cluster,namespace) (ALERTS{alertname="TestLookupWebhookDeliveryFailureRate",alertstate="firing"})
+ eval_time: 16m
+ exp_samples:
+ - labels: '{cluster="lab",namespace="quiet"}'
+ value: 1
+ - expr: count by (cluster,namespace) (ALERTS{alertname="TestLookupWebhookDeliveryFailureRate",alertstate="firing"})
+ eval_time: 30m
+ exp_samples:
+ - labels: '{cluster="lab",namespace="quiet"}'
+ value: 1
+- name: strict webhook threshold and installation scope are preserved
+ interval: 1m
+ input_series:
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="threshold",result="failure"}
+ values: 0+3x40
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="threshold",result="success"}
+ values: 0+57x40
+ - series: testlookup_webhook_delivery_attempts_total{cluster="other-cluster",namespace="threshold",result="failure"}
+ values: 0+4x40
+ - series: testlookup_webhook_delivery_attempts_total{cluster="other-cluster",namespace="threshold",result="success"}
+ values: 0+56x40
+ promql_expr_test:
+ - expr: count by (cluster,namespace) (ALERTS{alertname="TestLookupWebhookDeliveryFailureRate",alertstate="firing"})
+ eval_time: 30m
+ exp_samples:
+ - labels: '{cluster="other-cluster",namespace="threshold"}'
+ value: 1
+- name: zero webhook traffic is quiet and success without a failure series is healthy
+ interval: 1m
+ input_series:
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="zero",result="failure"}
+ values: '0x40'
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="zero",result="success"}
+ values: '0x40'
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="healthy",result="success"}
+ values: 0+1x40
+ alert_rule_test:
+ - eval_time: 40m
+ alertname: TestLookupWebhookDeliveryFailureRate
+ exp_alerts: []
+- name: absent webhook series does not invent failed traffic
+ interval: 1m
+ input_series: []
+ alert_rule_test:
+ - eval_time: 40m
+ alertname: TestLookupWebhookDeliveryFailureRate
+ exp_alerts: []
+- name: webhook failure alert resolves after healthy delivery replaces the bad window
+ interval: 1m
+ input_series:
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="recovering",result="failure"}
+ values: 0+1x20 20x40
+ - series: testlookup_webhook_delivery_attempts_total{cluster="lab",namespace="recovering",result="success"}
+ values: 0x20 0+10x40
+ promql_expr_test:
+ - expr: count by (namespace) (ALERTS{alertname="TestLookupWebhookDeliveryFailureRate",alertstate="firing"})
+ eval_time: 20m
+ exp_samples:
+ - labels: '{namespace="recovering"}'
+ value: 1
+ - expr: ALERTS{alertname="TestLookupWebhookDeliveryFailureRate",alertstate="firing"}
+ eval_time: 40m
+ exp_samples: []
diff --git a/k8s/monitoring/prometheusrule.yaml b/k8s/monitoring/prometheusrule.yaml
index 3b48dd5b2..366012ec1 100644
--- a/k8s/monitoring/prometheusrule.yaml
+++ b/k8s/monitoring/prometheusrule.yaml
@@ -28,6 +28,36 @@ spec:
annotations:
summary: TestLookup backend is down
description: The FastAPI backend has been unreachable for more than 1 minute.
+ - alert: TestLookupOperationalCollectionStale
+ expr: 'testlookup_metric_collection_success == 0
+
+ or
+
+ (time() - testlookup_metric_collection_last_success_timestamp_seconds) > 120
+
+ '
+ for: 2m
+ labels:
+ severity: warning
+ annotations:
+ summary: Operational metric collection failed or is stale
+ description: Collector {{ $labels.collector }} cannot provide a fresh snapshot on this target. Scrape availability alone does not prove dependency health; inspect metric_collection_failed logs before trusting the retained gauges.
+ - alert: TestLookupDownstreamOutboxFailed
+ expr: "max by (cluster, namespace, operation) (\n testlookup_downstream_outbox_entries{status=\"failed\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{collector=\"downstream\"} == 1)\n and on (cluster, namespace, job, instance)\n ((time() - testlookup_metric_collection_last_success_timestamp_seconds{collector=\"downstream\"}) <= 120)\n) > 0\n"
+ for: 1m
+ labels:
+ severity: warning
+ annotations:
+ summary: Durable downstream work exhausted retries
+ description: Operation {{ $labels.operation }} has {{ $value }} terminal failed outbox rows. Empty broker queues and Celery SUCCESS do not imply business completion. Inspect durable outbox outcomes and use the authorized replay process after fixing the cause.
+ - alert: TestLookupDownstreamOutboxOverdue
+ expr: "max by (cluster, namespace, operation) (\n testlookup_downstream_outbox_overdue_seconds{status=~\"waiting|pending|sending|published|processing\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{collector=\"downstream\"} == 1)\n and on (cluster, namespace, job, instance)\n ((time() - testlookup_metric_collection_last_success_timestamp_seconds{collector=\"downstream\"}) <= 120)\n) > 300\n"
+ for: 5m
+ labels:
+ severity: warning
+ annotations:
+ summary: Durable downstream work missed its retry or lease deadline
+ description: Operation {{ $labels.operation }} is {{ $value }} seconds beyond its stored retry or execution lease deadline. The rule includes a five-minute margin and does not treat scheduled future retries as stuck. Inspect relay and worker health.
- alert: TestLookupHighErrorRate
expr: 'sum(rate(http_requests_total{job="testlookup-backend", status=~"5.."}[5m]))
@@ -286,7 +316,7 @@ spec:
interval: 30s
rules:
- alert: TestLookupWebhookDeliveryFailureRate
- expr: "(\n sum(rate(testlookup_webhook_delivery_attempts_total{result=\"failure\"}[15m]))\n /\n clamp_min(sum(rate(testlookup_webhook_delivery_attempts_total[15m])), 1)\n) > 0.05\n"
+ expr: "(\n sum by (cluster, namespace) (rate(testlookup_webhook_delivery_attempts_total{result=\"failure\"}[15m]))\n /\n sum by (cluster, namespace) (rate(testlookup_webhook_delivery_attempts_total[15m]))\n) > 0.05\nand on (cluster, namespace)\nsum by (cluster, namespace) (rate(testlookup_webhook_delivery_attempts_total[15m])) > 0\n"
for: 15m
labels:
severity: warning
diff --git a/samples/README.md b/samples/README.md
index 0e1f706bf..ceabf161e 100644
--- a/samples/README.md
+++ b/samples/README.md
@@ -28,7 +28,7 @@ testlookup upload file samples/allure/allure-results.json --project --build demo-3
-# Via curl, with an API key (or -H "Authorization: Bearer "):
+# Via curl, with an API key (or -H "Authorization: Bearer "):
curl -X POST http://localhost:8000/api/v1/ingest/file \
-H "X-API-Key: qai_your_api_key_here" \
-F "file=@samples/junit/auth-suite.xml" \
diff --git a/scripts/release/scan_secret_snapshot.py b/scripts/release/scan_secret_snapshot.py
new file mode 100644
index 000000000..9d672a167
--- /dev/null
+++ b/scripts/release/scan_secret_snapshot.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python3
+"""Scan every tracked candidate blob, including secrets unchanged by this push.
+
+The added-history scan also runs: a secret added and removed inside one push
+must still fail. This complementary snapshot never reads untracked .env files
+or a developer's working-tree changes. Raw Git blobs bypass export attributes,
+checkout encodings and executable filters; their inventory and hashes are checked.
+"""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import io
+import os
+from pathlib import Path, PurePosixPath
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+
+
+class SnapshotScanError(RuntimeError):
+ """The exact tracked candidate could not be completely checked."""
+
+
+def _git(repository: Path, *arguments: str, input_data: bytes | None = None) -> bytes:
+ try:
+ result = subprocess.run(
+ ["git", "--no-replace-objects", "-C", str(repository), *arguments],
+ input=input_data, capture_output=True, timeout=180, check=False,
+ env={**os.environ, "GIT_NO_LAZY_FETCH": "1"},
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ raise SnapshotScanError("Cannot read the candidate Git tree") from exc
+ if result.returncode:
+ # Do not echo repository diagnostics or candidate-controlled filenames.
+ raise SnapshotScanError("Cannot read the candidate Git tree")
+ return result.stdout
+
+
+def _safe_path(name: str) -> PurePosixPath:
+ path = PurePosixPath(name)
+ if (
+ not name or path.is_absolute() or "\\" in name or ":" in name
+ or any(part in {".", ".."} for part in path.parts)
+ or str(path) != name
+ ):
+ raise SnapshotScanError("Candidate has an unsafe snapshot path")
+ return path
+
+
+def stage_snapshot(repository: Path, source_sha: str, destination: Path) -> int:
+ """Create a verified scan-only snapshot without links or Git metadata."""
+ if not re.fullmatch(r"[0-9a-f]{40}", source_sha):
+ raise SnapshotScanError("source_sha must be a lowercase full Git SHA")
+ repository = repository.resolve()
+ root = _git(repository, "rev-parse", "--show-toplevel").decode().strip()
+ if Path(root).resolve() != repository:
+ raise SnapshotScanError("repository must name its Git root")
+ tree: dict[str, tuple[str, str, int]] = {}
+ for entry in _git(repository, "ls-tree", "-r", "-l", "-z", "--full-tree", source_sha).split(b"\0"):
+ if not entry:
+ continue
+ metadata, raw_path = entry.split(b"\t", 1)
+ mode, kind, oid, size = metadata.decode("ascii").split()
+ name = raw_path.decode("utf-8")
+ _safe_path(name)
+ if kind != "blob" or mode not in {"100644", "100755", "120000"}:
+ raise SnapshotScanError("Candidate has an unsupported snapshot entry")
+ tree[name] = mode, oid, int(size)
+ if not tree:
+ raise SnapshotScanError("Candidate has no tracked blobs to scan")
+ destination.mkdir()
+ batch: list[tuple[str, str, int]] = []
+ batch_size = 0
+
+ def write_batch() -> None:
+ # Bound each response by 1,024 entries / 8 MiB, except a single larger
+ # blob. --batch returns RAW bytes: deliberately no --filters/textconv.
+ request = b"".join(oid.encode("ascii") + b"\n" for _, oid, _ in batch)
+ contents = io.BytesIO(_git(repository, "cat-file", "--batch", input_data=request))
+ for name, expected_oid, size in batch:
+ header = contents.readline().split()
+ if header != [expected_oid.encode("ascii"), b"blob", str(size).encode("ascii")]:
+ raise SnapshotScanError("Git blob response does not match the candidate")
+ data = contents.read(size)
+ if len(data) != size or contents.read(1) != b"\n":
+ raise SnapshotScanError("Git blob response is incomplete")
+ actual_oid = hashlib.sha1(
+ b"blob " + str(len(data)).encode("ascii") + b"\0" + data,
+ usedforsecurity=False, # Git object identity, not a credential hash.
+ ).hexdigest()
+ if actual_oid != expected_oid:
+ raise SnapshotScanError("Git blob bytes do not match the candidate")
+ path = _safe_path(name)
+ target = destination.joinpath(*path.parts)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ # A symlink's raw blob becomes text; never follow its target.
+ # Exclusive creation also rejects case-colliding paths on Windows.
+ with target.open("xb") as output:
+ output.write(data)
+ if contents.read(1):
+ raise SnapshotScanError("Git blob response has unexpected entries")
+
+ for name, (_mode, oid, size) in tree.items():
+ if batch and (len(batch) >= 1024 or batch_size + size > 8 * 1024 * 1024):
+ write_batch()
+ batch, batch_size = [], 0
+ batch.append((name, oid, size))
+ batch_size += size
+ if batch:
+ write_batch()
+ return len(tree)
+
+
+def scan_snapshot(repository: Path, source_sha: str, *, gitleaks: str, timeout_seconds: int = 300) -> int:
+ """Run the pinned scanner against the verified tree and its tracked policy."""
+ if not 0 < timeout_seconds <= 600:
+ raise SnapshotScanError("timeout must be between 1 and 600 seconds")
+ scanner = shutil.which(gitleaks)
+ if not scanner:
+ raise SnapshotScanError("The installed gitleaks executable is unavailable")
+ scanner = str(Path(scanner).resolve())
+ with tempfile.TemporaryDirectory(prefix="secret-snapshot-") as temporary:
+ snapshot = Path(temporary) / "snapshot"
+ count = stage_snapshot(repository, source_sha, snapshot)
+ if not (snapshot / ".gitleaks.toml").is_file():
+ raise SnapshotScanError("Candidate has no tracked secret-scanning policy")
+ try:
+ result = subprocess.run(
+ [scanner, "dir", ".", "--config", ".gitleaks.toml", "--redact",
+ "--no-banner", "--no-color", "--exit-code", "1", "--timeout", str(timeout_seconds)],
+ cwd=snapshot, timeout=timeout_seconds + 10, check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ raise SnapshotScanError("Candidate snapshot scanner did not finish") from exc
+ if result.returncode:
+ raise SnapshotScanError("Candidate snapshot did not pass secret scanning")
+ return count
+
+
+def main(argv=None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--source-sha", required=True)
+ parser.add_argument("--repository", type=Path, default=Path("."))
+ parser.add_argument("--gitleaks", default="gitleaks")
+ parser.add_argument("--timeout-seconds", type=int, default=300)
+ args = parser.parse_args(argv)
+ try:
+ count = scan_snapshot(
+ args.repository, args.source_sha,
+ gitleaks=args.gitleaks, timeout_seconds=args.timeout_seconds,
+ )
+ except (SnapshotScanError, OSError, ValueError) as exc:
+ # Low-level exception text can contain a path or candidate data.
+ message = str(exc) if isinstance(exc, SnapshotScanError) else "Cannot stage the complete candidate snapshot"
+ print(f"Secret snapshot refused: {message}", file=sys.stderr)
+ return 1
+ print(f"Candidate snapshot passed secret scanning ({count} tracked blobs).")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/release/tests/test_scan_secret_snapshot.py b/scripts/release/tests/test_scan_secret_snapshot.py
new file mode 100644
index 000000000..7a6442dcd
--- /dev/null
+++ b/scripts/release/tests/test_scan_secret_snapshot.py
@@ -0,0 +1,211 @@
+"""Snapshot coverage survives an unrelated push after a failed secret scan.
+
+Pure unittest also runs in the secret-scan job without installing packages.
+Set GITLEAKS_TEST_BINARY to the checksum-verified scanner for live CLI proofs.
+All Git writes and synthetic canaries stay in disposable fixture repositories.
+"""
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import scan_secret_snapshot as snapshot # noqa: E402
+
+
+SCANNER = os.environ.get("GITLEAKS_TEST_BINARY")
+ROOT = Path(__file__).resolve().parents[3]
+POLICY = '''[extend]
+useDefault = true
+[[rules]]
+id = "fixture-ingest-key"
+description = "Synthetic snapshot canary"
+regex = "qai_[A-Za-z0-9_]{30,}"
+keywords = ["qai_"]
+'''
+
+
+class SnapshotTests(unittest.TestCase):
+ def setUp(self):
+ self.temporary = tempfile.TemporaryDirectory(prefix="snapshot-fixture-")
+ self.addCleanup(self.temporary.cleanup)
+ self.root = Path(self.temporary.name)
+ self.repo = self.root / "repository"
+ self.repo.mkdir()
+ # Do not inherit a developer's hooks, signing, filters or Git overrides.
+ self.environment = {name: value for name, value in os.environ.items() if not name.startswith("GIT_")}
+ self.environment.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull)
+ self.git("init", "--template=", "--initial-branch=main")
+ self.git("config", "user.name", "Snapshot fixture")
+ self.git("config", "user.email", "snapshot@example.invalid")
+ self.git("config", "core.autocrlf", "false")
+ (self.repo / ".gitleaks.toml").write_text(POLICY, encoding="utf-8")
+
+ def git(self, *arguments, input=None):
+ result = subprocess.run(
+ ["git", "-C", str(self.repo), *arguments],
+ input=input, capture_output=True, env=self.environment, check=True,
+ )
+ return result.stdout
+
+ def commit(self, *, stage=True):
+ if stage:
+ self.git("add", "-A")
+ self.git("commit", "-m", "Synthetic snapshot fixture")
+ return self.git("rev-parse", "HEAD").decode().strip()
+
+ def test_only_the_requested_tracked_tree_is_staged(self):
+ (self.repo / "config.txt").write_text("tracked-safe", encoding="utf-8")
+ sha = self.commit()
+ (self.repo / "config.txt").write_text("uncommitted-different", encoding="utf-8")
+ (self.repo / ".env").write_text("untracked-local", encoding="utf-8")
+ destination = self.root / "snapshot"
+ self.assertEqual(snapshot.stage_snapshot(self.repo, sha, destination), 2)
+ self.assertEqual((destination / "config.txt").read_text(), "tracked-safe")
+ self.assertFalse((destination / ".env").exists())
+ self.assertFalse((destination / ".git").exists())
+
+ def test_export_ignore_does_not_hide_a_tracked_blob(self):
+ (self.repo / ".gitattributes").write_text("hidden.txt export-ignore\n", encoding="utf-8")
+ (self.repo / "hidden.txt").write_text("tracked", encoding="utf-8")
+ sha = self.commit()
+ destination = self.root / "snapshot"
+ self.assertEqual(snapshot.stage_snapshot(self.repo, sha, destination), 3)
+ self.assertEqual((destination / "hidden.txt").read_text(), "tracked")
+
+ def test_export_subst_does_not_replace_candidate_bytes(self):
+ (self.repo / ".gitattributes").write_text("substitute.txt export-subst\n", encoding="utf-8")
+ (self.repo / "substitute.txt").write_text("$Format:%H$", encoding="utf-8")
+ sha = self.commit()
+ destination = self.root / "snapshot"
+ self.assertEqual(snapshot.stage_snapshot(self.repo, sha, destination), 3)
+ self.assertEqual((destination / "substitute.txt").read_text(), "$Format:%H$")
+
+ def test_checkout_eol_and_encoding_attributes_do_not_transform_raw_blobs(self):
+ (self.repo / ".gitattributes").write_text(
+ "*.ps1 text eol=crlf\nencoded.txt working-tree-encoding=UTF-16LE\n", encoding="utf-8"
+ )
+ (self.repo / "script.ps1").write_bytes(b"Write-Output 'fixture'\r\n")
+ (self.repo / "encoded.txt").write_bytes("Encoding fixture\n".encode("utf-16-le"))
+ sha = self.commit()
+ destination = self.root / "snapshot"
+ self.assertEqual(snapshot.stage_snapshot(self.repo, sha, destination), 4)
+ self.assertEqual((destination / "script.ps1").read_bytes(), b"Write-Output 'fixture'\n")
+ self.assertEqual((destination / "encoded.txt").read_bytes(), b"Encoding fixture\n")
+
+ def test_symlink_blob_is_scanned_as_text_without_following_its_target(self):
+ self.commit()
+ blob = self.git("hash-object", "-w", "--stdin", input=b"../../outside-private-file").decode().strip()
+ self.git("update-index", "--add", "--cacheinfo", f"120000,{blob},link")
+ sha = self.commit(stage=False)
+ destination = self.root / "snapshot"
+ snapshot.stage_snapshot(self.repo, sha, destination)
+ self.assertFalse((destination / "link").is_symlink())
+ self.assertEqual((destination / "link").read_text(), "../../outside-private-file")
+
+ def test_unsafe_paths_and_invalid_revision_are_refused(self):
+ for name in ("../outside", "/absolute", "a/../b", "a\\b", "C:/outside", "a//b"):
+ with self.subTest(name=name), self.assertRaises(snapshot.SnapshotScanError):
+ snapshot._safe_path(name)
+ with self.assertRaises(snapshot.SnapshotScanError):
+ snapshot.stage_snapshot(self.repo, "main", self.root / "snapshot")
+
+ def test_submodule_content_is_not_silently_omitted(self):
+ previous = self.commit()
+ self.git("update-index", "--add", "--cacheinfo", f"160000,{previous},submodule")
+ sha = self.commit(stage=False)
+ with self.assertRaisesRegex(snapshot.SnapshotScanError, "unsupported"):
+ snapshot.stage_snapshot(self.repo, sha, self.root / "snapshot")
+
+ def test_scanner_gets_only_verified_snapshot_policy_and_redacted_output(self):
+ (self.repo / "safe.txt").write_text("safe", encoding="utf-8")
+ sha = self.commit()
+ calls = []
+ original = subprocess.run
+
+ def run(command, **options):
+ if command[0] == sys.executable:
+ calls.append((command, options))
+ self.assertEqual((options["cwd"] / "safe.txt").read_text(), "safe")
+ self.assertTrue((options["cwd"] / ".gitleaks.toml").is_file())
+ return subprocess.CompletedProcess(command, 0)
+ return original(command, **options)
+
+ with patch.object(snapshot.subprocess, "run", side_effect=run):
+ self.assertEqual(snapshot.scan_snapshot(self.repo, sha, gitleaks=sys.executable), 2)
+ command, options = calls[0]
+ self.assertEqual(command[1:5], ["dir", ".", "--config", ".gitleaks.toml"])
+ self.assertIn("--redact", command)
+ self.assertEqual(options["timeout"], 310)
+
+ def test_scanner_failure_and_timeout_both_fail_closed(self):
+ sha = self.commit()
+ original = subprocess.run
+ for fail_with_timeout in (False, True):
+ def run(command, **options):
+ if command[0] == sys.executable:
+ if fail_with_timeout:
+ raise subprocess.TimeoutExpired(command, options["timeout"])
+ return subprocess.CompletedProcess(command, 7)
+ return original(command, **options)
+
+ with self.subTest(timeout=fail_with_timeout), patch.object(snapshot.subprocess, "run", side_effect=run):
+ with self.assertRaises(snapshot.SnapshotScanError):
+ snapshot.scan_snapshot(self.repo, sha, gitleaks=sys.executable)
+
+ @unittest.skipUnless(SCANNER, "set GITLEAKS_TEST_BINARY to the pinned scanner")
+ def test_failed_A_then_unrelated_B_still_blocks_the_unchanged_canary(self):
+ # A tracked path must remain covered even when .gitignore matches it.
+ (self.repo / ".gitignore").write_text("credential.txt\n", encoding="utf-8")
+ self.commit()
+ # Constructed synthetic data cannot accidentally be a real credential.
+ canary = "qai_" + "SnapshotCanary7" * 4
+ (self.repo / "credential.txt").write_text("API_KEY=" + canary + "\n", encoding="utf-8")
+ self.git("add", "-f", "credential.txt")
+ failed_a = self.commit()
+ (self.repo / "unrelated.txt").write_text("unrelated change", encoding="utf-8")
+ candidate_b = self.commit()
+ incremental = subprocess.run(
+ [SCANNER, "git", "--config", ".gitleaks.toml", "--redact", "--no-banner",
+ "--log-opts=" + failed_a + ".." + candidate_b, "."],
+ cwd=self.repo, capture_output=True, check=False,
+ )
+ self.assertEqual(incremental.returncode, 0, "the old immediate-push range omits A")
+ with self.assertRaisesRegex(snapshot.SnapshotScanError, "did not pass"):
+ snapshot.scan_snapshot(self.repo, candidate_b, gitleaks=SCANNER)
+ (self.repo / "credential.txt").unlink()
+ repaired = self.commit()
+ self.assertEqual(snapshot.scan_snapshot(self.repo, repaired, gitleaks=SCANNER), 3)
+
+ @unittest.skipUnless(SCANNER, "set GITLEAKS_TEST_BINARY to the pinned scanner")
+ def test_narrow_fixture_exceptions_do_not_allow_another_secret_in_those_files(self):
+ (self.repo / ".gitleaks.toml").write_text((ROOT / ".gitleaks.toml").read_text(), encoding="utf-8")
+ for path in (
+ "backend/tests/integration/golden/analytics_parity_characterisation.json",
+ "sdk-vectors/http_exchange.json",
+ ):
+ with self.subTest(path=path):
+ fixture = self.repo / path
+ fixture.parent.mkdir(parents=True, exist_ok=True)
+ fixture.write_text('{"api_key":"' + "OtherFixtureCanary7" * 4 + '"}', encoding="utf-8") # gitleaks:allow -- generated same-detector negative fixture
+ candidate = self.commit()
+ detected = subprocess.run(
+ [SCANNER, "dir", ".", "--config", ".gitleaks.toml", "--redact",
+ "--no-banner", "--report-format", "json", "--report-path", "-"],
+ cwd=self.repo, capture_output=True, check=False,
+ )
+ self.assertEqual(detected.returncode, 1)
+ self.assertIn("generic-api-key", {finding["RuleID"] for finding in json.loads(detected.stdout)})
+ with self.assertRaisesRegex(snapshot.SnapshotScanError, "did not pass"):
+ snapshot.scan_snapshot(self.repo, candidate, gitleaks=SCANNER)
+ fixture.unlink()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/release/tests/test_verify_secret_scan.py b/scripts/release/tests/test_verify_secret_scan.py
new file mode 100644
index 000000000..bd3dbbe90
--- /dev/null
+++ b/scripts/release/tests/test_verify_secret_scan.py
@@ -0,0 +1,271 @@
+"""Exact-SHA secret scans must authorize publication and release, fail closed."""
+from __future__ import annotations
+
+from copy import deepcopy
+from pathlib import Path
+import subprocess
+import sys
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+import yaml
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import verify_secret_scan as verifier # noqa: E402
+
+ROOT = Path(__file__).resolve().parents[3]
+REPOSITORY = "acme/testlookup"
+SHA = "a" * 40
+WORKFLOW_ID = 42
+
+
+def _run(**changes):
+ run = {
+ "id": 101, "workflow_id": WORKFLOW_ID, "run_number": 9, "run_attempt": 1,
+ "path": verifier.WORKFLOW_PATH, "head_sha": SHA, "head_branch": "main", "event": "push",
+ "repository": {"full_name": REPOSITORY}, "head_repository": {"full_name": REPOSITORY},
+ "status": "completed", "conclusion": "success",
+ }
+ run.update(changes)
+ return run
+
+
+class Clock:
+ def __init__(self):
+ self.now = 0.0
+ self.waits = []
+
+ def __call__(self):
+ return self.now
+
+ def sleep(self, seconds):
+ self.waits.append(seconds)
+ self.now += seconds
+
+
+class FakeAPI:
+ def __init__(self, snapshots, *, workflow=None, detail=None):
+ self.snapshots = snapshots
+ self.workflow = workflow or {"id": WORKFLOW_ID, "path": verifier.WORKFLOW_PATH, "state": "active"}
+ self.detail = detail
+ self.poll = -1
+ self.calls = []
+
+ def __call__(self, path, *, timeout):
+ self.calls.append((path, timeout))
+ if path.endswith("/workflows/secret-scan.yml"):
+ return deepcopy(self.workflow)
+ if "/workflows/42/runs?" in path:
+ query = parse_qs(urlsplit(path).query)
+ assert query["head_sha"] == [SHA]
+ assert query["event"] == ["push"] and query["branch"] == ["main"]
+ page = int(query["page"][0])
+ if page == 1:
+ self.poll += 1
+ current = self.snapshots[min(self.poll, len(self.snapshots) - 1)]
+ return {"total_count": len(current), "workflow_runs": deepcopy(current[(page - 1) * 100:page * 100])}
+ if "/actions/runs/" in path:
+ if self.detail is not None:
+ return deepcopy(self.detail)
+ current = self.snapshots[min(self.poll, len(self.snapshots) - 1)]
+ return deepcopy(next(run for run in current if run["id"] == int(path.rsplit("/", 1)[1])))
+ raise AssertionError(f"Unexpected endpoint: {path}")
+
+
+def _verify(api, clock=None):
+ clock = clock or Clock()
+ return verifier.verify_secret_scan(
+ REPOSITORY, SHA, api_get=api, clock=clock, sleep=clock.sleep,
+ timeout_seconds=3, poll_seconds=1,
+ )
+
+
+def test_exact_main_push_success_authorizes_the_sha_and_records_run_identity():
+ api = FakeAPI([[_run()]])
+ assert _verify(api) == {
+ "repository": REPOSITORY, "source_sha": SHA, "workflow_path": verifier.WORKFLOW_PATH,
+ "workflow_id": WORKFLOW_ID, "run_id": 101, "run_attempt": 1,
+ }
+ assert len(api.calls) == 3
+ assert all(0 < timeout <= 3 for _, timeout in api.calls)
+
+
+@pytest.mark.parametrize("conclusion", ["failure", "cancelled", "timed_out", "skipped", "neutral", None])
+def test_completed_non_success_never_authorizes(conclusion):
+ clock = Clock()
+ with pytest.raises(verifier.SecretScanVerificationError, match="did not succeed"):
+ _verify(FakeAPI([[_run(conclusion=conclusion)]]), clock)
+ assert clock.waits == []
+
+
+@pytest.mark.parametrize("status", ["queued", "in_progress", "waiting", "pending"])
+def test_pending_wait_is_bounded_and_never_authorizes(status):
+ clock = Clock()
+ with pytest.raises(verifier.SecretScanVerificationError, match="Timed out"):
+ _verify(FakeAPI([[_run(status=status, conclusion=None)]]), clock)
+ assert clock.now == 3
+ assert clock.waits == [1, 1, 1]
+
+
+def test_missing_evidence_waits_for_cross_workflow_delivery_then_accepts_success():
+ clock = Clock()
+ api = FakeAPI([[], [_run(status="in_progress", conclusion=None)], [_run()]])
+ assert _verify(api, clock)["run_id"] == 101
+ assert clock.waits == [1, 1]
+
+
+def test_missing_evidence_times_out_without_triggering_a_scan():
+ api, clock = FakeAPI([[]]), Clock()
+ with pytest.raises(verifier.SecretScanVerificationError, match="Timed out"):
+ _verify(api, clock)
+ assert clock.now == 3
+ assert all("dispatch" not in path and "rerun" not in path for path, _ in api.calls)
+
+
+@pytest.mark.parametrize("change", [
+ {"head_sha": "b" * 40}, {"head_branch": "develop"}, {"event": "pull_request"},
+ {"event": "workflow_dispatch"}, {"workflow_id": 999},
+ {"path": ".github/workflows/foreign.yml"},
+ {"repository": {"full_name": "foreign/testlookup"}},
+ {"head_repository": {"full_name": "fork/testlookup"}},
+ {"run_attempt": None}, {"id": None},
+])
+def test_wrong_sha_branch_event_workflow_or_repository_cannot_authorize(change):
+ with pytest.raises(verifier.SecretScanVerificationError, match="Timed out"):
+ _verify(FakeAPI([[_run(**change)]]))
+
+
+@pytest.mark.parametrize("latest", [
+ {"status": "completed", "conclusion": "failure"},
+ {"status": "in_progress", "conclusion": None},
+])
+def test_earlier_success_cannot_bypass_a_newer_failed_or_pending_run(latest):
+ runs = [_run(), _run(id=102, run_number=10, **latest)]
+ with pytest.raises(verifier.SecretScanVerificationError):
+ _verify(FakeAPI([runs]))
+
+
+def test_direct_run_refresh_cannot_reuse_a_stale_successful_attempt():
+ current = _run(run_attempt=2, status="in_progress", conclusion=None)
+ with pytest.raises(verifier.SecretScanVerificationError, match="mismatched scope"):
+ _verify(FakeAPI([[current]], detail=_run(run_attempt=1)))
+
+
+@pytest.mark.parametrize("change", [{"head_sha": "b" * 40}, {"id": 102}, {"path": "other.yml"}])
+def test_refreshed_run_must_still_match_selected_identity_and_scope(change):
+ with pytest.raises(verifier.SecretScanVerificationError, match="mismatched scope"):
+ _verify(FakeAPI([[_run()]], detail=_run(**change)))
+
+
+def test_complete_filtered_run_listing_is_paginated():
+ api = FakeAPI([[_run(id=200 + n, head_sha="b" * 40) for n in range(100)] + [_run()]])
+ assert _verify(api)["run_id"] == 101
+ assert any("page=2" in path for path, _ in api.calls)
+
+
+@pytest.mark.parametrize("workflow", [
+ {"id": WORKFLOW_ID, "path": verifier.WORKFLOW_PATH, "state": "disabled_manually"},
+ {"id": WORKFLOW_ID, "path": "foreign.yml", "state": "active"},
+ {"path": verifier.WORKFLOW_PATH, "state": "active"},
+])
+def test_untrusted_or_disabled_workflow_metadata_is_rejected(workflow):
+ with pytest.raises(verifier.SecretScanVerificationError, match="trusted secret-scan workflow"):
+ _verify(FakeAPI([[_run()]], workflow=workflow))
+
+
+def test_invalid_inputs_fail_before_any_api_call():
+ api = FakeAPI([[_run()]])
+ for repo, sha in [(REPOSITORY, "main"), (REPOSITORY, "A" * 40), ("acme/repo?bad", SHA)]:
+ with pytest.raises(verifier.SecretScanVerificationError):
+ verifier.verify_secret_scan(repo, sha, api_get=api)
+ assert api.calls == []
+
+
+def test_api_uses_get_only_and_suppresses_sensitive_failure_diagnostics(monkeypatch):
+ seen = []
+
+ def reject(command, **kwargs):
+ seen.append((command, kwargs))
+ return subprocess.CompletedProcess(command, 1, "secret stdout", "Bearer sensitive diagnostic")
+
+ monkeypatch.setattr(verifier.subprocess, "run", reject)
+ with pytest.raises(verifier.SecretScanVerificationError) as exc:
+ verifier._github_api("/repos/acme/testlookup/actions/workflows/secret-scan.yml", timeout=5)
+ assert "secret" not in str(exc.value).replace("secret-scan", "scan")
+ assert "Bearer" not in str(exc.value)
+ assert seen[0][0][:4] == ["gh", "api", "--method", "GET"]
+ assert seen[0][1]["timeout"] == 5
+
+
+def test_api_error_or_invalid_response_never_authorizes(monkeypatch):
+ for stdout in ("not JSON", "[]"):
+ monkeypatch.setattr(verifier.subprocess, "run", lambda command, **kw: subprocess.CompletedProcess(command, 0, stdout, ""))
+ with pytest.raises(verifier.SecretScanVerificationError, match="Invalid"):
+ verifier._github_api("/repos/acme/testlookup/actions/workflows/secret-scan.yml", timeout=1)
+
+
+def test_incomplete_or_inconsistent_listing_never_authorizes():
+ for listing in (
+ {"total_count": 1, "workflow_runs": []},
+ {"total_count": 0, "workflow_runs": [_run()]},
+ {"total_count": None, "workflow_runs": [_run()]},
+ ):
+ api = FakeAPI([[_run()]])
+
+ def respond(path, **kwargs):
+ return listing if "/runs?" in path else api(path, **kwargs)
+
+ with pytest.raises(verifier.SecretScanVerificationError, match="run listing"):
+ _verify(respond)
+
+
+def test_cli_refuses_failed_verification_and_prints_only_validated_evidence(monkeypatch, capsys):
+ evidence = {"source_sha": SHA, "run_id": 101}
+ monkeypatch.setattr(verifier, "verify_secret_scan", lambda *args, **kwargs: evidence)
+ arguments = ["--repository", REPOSITORY, "--source-sha", SHA]
+ assert verifier.main(arguments) == 0
+ assert '"run_id": 101' in capsys.readouterr().out
+
+ def refused(*args, **kwargs):
+ raise verifier.SecretScanVerificationError("The latest exact-SHA secret scan did not succeed")
+
+ monkeypatch.setattr(verifier, "verify_secret_scan", refused)
+ assert verifier.main(arguments) == 1
+ output = capsys.readouterr()
+ assert output.out == "" and "authorization refused" in output.err
+
+
+def _workflow(name):
+ return yaml.safe_load((ROOT / ".github" / "workflows" / name).read_text(encoding="utf-8"))
+
+
+def test_first_image_publication_waits_for_read_only_exact_sha_gate():
+ jobs = _workflow("ci.yml")["jobs"]
+ gate, build = jobs["verify-secret-scan"], jobs["build-images"]
+ assert "verify-secret-scan" in build["needs"]
+ assert "security-deps" in build["needs"]
+ assert gate["permissions"] == {"contents": "read", "actions": "read"}
+ assert "actions" not in build["permissions"]
+ assert gate["if"] == build["if"] == "github.ref == 'refs/heads/main' && github.event_name == 'push'"
+ assert not gate.get("continue-on-error")
+ step = next(s for s in gate["steps"] if "verify_secret_scan.py" in s.get("run", ""))
+ assert step["env"]["SOURCE_SHA"] == "${{ github.sha }}"
+ assert '--source-sha "$SOURCE_SHA"' in step["run"]
+ assert not step.get("if") and not step.get("continue-on-error")
+ assert "--timeout-seconds 900" in step["run"] and gate["timeout-minutes"] > 15
+
+
+def test_release_authorization_rechecks_secret_scan_without_weakening_manifest_gate():
+ workflow = _workflow("require-verified-sha.yml")
+ assert workflow["permissions"] == {"actions": "read", "contents": "read"}
+ steps = workflow["jobs"]["require"]["steps"]
+ manifest = next(s for s in steps if s.get("id") == "verify")
+ gate = next(s for s in steps if "verify_secret_scan.py" in s.get("run", ""))
+ checkout = next(s for s in steps if "actions/checkout@" in s.get("uses", ""))
+ assert checkout["with"]["ref"] == "${{ inputs.source_sha }}"
+ assert checkout["with"]["persist-credentials"] is False
+ assert gate["env"]["SOURCE_SHA"] == "${{ inputs.source_sha }}"
+ assert steps.index(manifest) < steps.index(gate)
+ assert "verified-images-$SOURCE_SHA" in manifest["run"]
+ assert "Expected exactly one successful main ci.yml run" in manifest["run"]
+ assert not gate.get("if") and not gate.get("continue-on-error")
diff --git a/scripts/release/verify_secret_scan.py b/scripts/release/verify_secret_scan.py
new file mode 100644
index 000000000..f9cdf9d7b
--- /dev/null
+++ b/scripts/release/verify_secret_scan.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""Authorize one SHA using existing, trusted main-push secret-scan evidence.
+
+Only GET requests are made. Missing or pending evidence is retried for a
+bounded interval; this tool never starts a workflow or substitutes another SHA.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import re
+import subprocess
+import sys
+import time
+from urllib.parse import urlencode
+
+WORKFLOW_PATH = ".github/workflows/secret-scan.yml"
+PENDING_STATUSES = {"queued", "in_progress", "requested", "waiting", "pending"}
+
+
+class SecretScanVerificationError(RuntimeError):
+ """The candidate has no acceptable secret-scan evidence."""
+
+
+def _positive_integer(value: object) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
+
+
+def _github_api(path: str, *, timeout: float) -> dict:
+ try:
+ result = subprocess.run(
+ ["gh", "api", "--method", "GET", path],
+ capture_output=True, text=True, timeout=timeout, check=False,
+ )
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ raise SecretScanVerificationError("Cannot query secret-scan evidence") from exc
+ if result.returncode:
+ # gh's stderr may contain credentials or other sensitive diagnostics.
+ raise SecretScanVerificationError("GitHub rejected the secret-scan evidence query")
+ try:
+ document = json.loads(result.stdout)
+ except (ValueError, TypeError) as exc:
+ raise SecretScanVerificationError("Invalid secret-scan evidence response") from exc
+ if not isinstance(document, dict):
+ raise SecretScanVerificationError("Invalid secret-scan evidence response")
+ return document
+
+
+def _trusted_run(run: object, *, repository: str, source_sha: str, workflow_id: int) -> bool:
+ if not isinstance(run, dict):
+ return False
+ for field in ("repository", "head_repository"):
+ repo = run.get(field)
+ if not isinstance(repo, dict) or str(repo.get("full_name", "")).casefold() != repository.casefold():
+ return False
+ return (
+ run.get("workflow_id") == workflow_id
+ and run.get("path") == WORKFLOW_PATH
+ and run.get("head_sha") == source_sha
+ and run.get("head_branch") == "main"
+ and run.get("event") == "push"
+ and all(_positive_integer(run.get(field)) for field in ("id", "run_number", "run_attempt"))
+ )
+
+
+def verify_secret_scan(
+ repository: str,
+ source_sha: str,
+ *,
+ timeout_seconds: float = 900,
+ poll_seconds: float = 10,
+ api_get=None,
+ clock=None,
+ sleep=None,
+) -> dict:
+ """Return successful newest-run evidence, or fail closed without publication."""
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):
+ raise SecretScanVerificationError("repository must be an owner/repository name")
+ if not re.fullmatch(r"[0-9a-f]{40}", source_sha):
+ raise SecretScanVerificationError("source_sha must be a lowercase full Git SHA")
+ if not math.isfinite(timeout_seconds) or not 0 < timeout_seconds <= 1800:
+ raise SecretScanVerificationError("timeout must be between 0 and 1800 seconds")
+ if not math.isfinite(poll_seconds) or not 0 < poll_seconds <= 60:
+ raise SecretScanVerificationError("poll interval must be between 0 and 60 seconds")
+ api_get = api_get or _github_api
+ clock = clock or time.monotonic
+ sleep = sleep or time.sleep
+ deadline = clock() + timeout_seconds
+
+ def request(path: str) -> dict:
+ remaining = deadline - clock()
+ if remaining <= 0:
+ raise SecretScanVerificationError("Timed out waiting for successful exact-SHA secret-scan evidence")
+ document = api_get(path, timeout=min(20, remaining))
+ if not isinstance(document, dict):
+ raise SecretScanVerificationError("Invalid secret-scan evidence response")
+ return document
+
+ workflow = request(f"/repos/{repository}/actions/workflows/secret-scan.yml")
+ workflow_id = workflow.get("id")
+ if not _positive_integer(workflow_id) or workflow.get("path") != WORKFLOW_PATH or workflow.get("state") != "active":
+ raise SecretScanVerificationError("The trusted secret-scan workflow is missing, disabled or mismatched")
+
+ while True:
+ runs = []
+ for page in range(1, 11):
+ query = urlencode({
+ "head_sha": source_sha, "event": "push", "branch": "main",
+ "per_page": 100, "page": page,
+ })
+ document = request(f"/repos/{repository}/actions/workflows/{workflow_id}/runs?{query}")
+ batch, total = document.get("workflow_runs"), document.get("total_count")
+ if not isinstance(batch, list) or not isinstance(total, int) or isinstance(total, bool) or total < 0:
+ raise SecretScanVerificationError("Invalid secret-scan run listing")
+ runs.extend(batch)
+ if len(batch) > 100 or len(runs) > total:
+ raise SecretScanVerificationError("Invalid secret-scan run listing")
+ if len(runs) >= total:
+ break
+ if not batch or page == 10:
+ raise SecretScanVerificationError("Incomplete secret-scan run listing")
+ candidates = [run for run in runs if _trusted_run(
+ run, repository=repository, source_sha=source_sha, workflow_id=workflow_id,
+ )]
+ if candidates:
+ latest = max(candidates, key=lambda run: (run["run_number"], run["id"], run["run_attempt"]))
+ selected_id, selected_number, selected_attempt = latest["id"], latest["run_number"], latest["run_attempt"]
+ # Re-read the run so a stale list response cannot bless a pending
+ # or failed rerun of an earlier successful attempt.
+ latest = request(f"/repos/{repository}/actions/runs/{latest['id']}")
+ if not _trusted_run(latest, repository=repository, source_sha=source_sha, workflow_id=workflow_id) or (
+ latest["id"] != selected_id or latest["run_number"] != selected_number
+ or latest["run_attempt"] < selected_attempt
+ ):
+ raise SecretScanVerificationError("Selected secret-scan evidence has mismatched scope")
+ if latest.get("status") == "completed":
+ if latest.get("conclusion") != "success":
+ raise SecretScanVerificationError("The latest exact-SHA secret scan did not succeed")
+ if clock() > deadline:
+ raise SecretScanVerificationError("Timed out waiting for successful exact-SHA secret-scan evidence")
+ return {
+ "repository": repository,
+ "source_sha": source_sha,
+ "workflow_path": WORKFLOW_PATH,
+ "workflow_id": workflow_id,
+ "run_id": latest["id"],
+ "run_attempt": latest["run_attempt"],
+ }
+ if latest.get("status") not in PENDING_STATUSES:
+ raise SecretScanVerificationError("The exact-SHA secret scan has an unsupported state")
+ remaining = deadline - clock()
+ if remaining <= 0:
+ raise SecretScanVerificationError("Timed out waiting for successful exact-SHA secret-scan evidence")
+ sleep(min(poll_seconds, remaining))
+
+
+def main(argv=None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repository", required=True)
+ parser.add_argument("--source-sha", required=True)
+ parser.add_argument("--timeout-seconds", type=float, default=900)
+ parser.add_argument("--poll-seconds", type=float, default=10)
+ args = parser.parse_args(argv)
+ try:
+ evidence = verify_secret_scan(
+ args.repository, args.source_sha,
+ timeout_seconds=args.timeout_seconds, poll_seconds=args.poll_seconds,
+ )
+ except SecretScanVerificationError as exc:
+ print(f"Secret-scan authorization refused: {exc}", file=sys.stderr)
+ return 1
+ print(json.dumps(evidence, sort_keys=True))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/test_ci_security.py b/scripts/test_ci_security.py
index 326fdcabe..3eeb40872 100644
--- a/scripts/test_ci_security.py
+++ b/scripts/test_ci_security.py
@@ -440,13 +440,21 @@ def test_the_secret_scan_runs_on_every_change_and_blocks() -> None:
install = next(s for s in steps if "gitleaks" in s.get("name", "").lower() and "curl" in s.get("run", ""))
assert re.fullmatch(r"[0-9a-f]{64}", install["env"]["GITLEAKS_ARCHIVE_SHA256"])
assert install["run"].index("sha256sum --check --strict") < install["run"].index("tar ")
- scan = steps[-1]
+ scan = next(step for step in steps if step.get("name") == "Scan the added commits")
assert "gitleaks git --config .gitleaks.toml" in scan["run"]
assert "--exit-code 1" in scan["run"]
assert "${{" not in scan["run"], "pass event values through env:, never into the script"
version = re.search(r"/download/v([\d.]+)/", install["run"]).group(1)
push_check = (ROOT / "scripts" / "push_check.py").read_text(encoding="utf-8")
assert f"gitleaks/v8@v{version}" in push_check, "push_check.py installs a different gitleaks"
+ snapshot = next(step for step in steps if step.get("name") == "Scan the full tracked candidate snapshot")
+ assert snapshot["if"] == "github.event_name == 'push'"
+ assert 'scan_secret_snapshot.py' in snapshot["run"]
+ assert '--source-sha "$GITHUB_SHA"' in snapshot["run"]
+ assert '--gitleaks /usr/local/bin/gitleaks' in snapshot["run"]
+ assert not snapshot.get("continue-on-error")
+ proof = next(step for step in steps if step.get("name") == "Prove full candidate coverage and raw-blob isolation")
+ assert proof["env"]["GITLEAKS_TEST_BINARY"] == "/usr/local/bin/gitleaks"
def test_the_gitleaks_rules_add_the_tokens_the_defaults_missed() -> None:
From a84edf88e15fbb91d321834a9f999c5e4a3be845 Mon Sep 17 00:00:00 2001
From: Anand Topu
Date: Thu, 26 Nov 2026 23:00:42 -0600
Subject: [PATCH 02/13] feat: improve production metrics and scrape
authentication
Use one queue inventory and read every priority list from the actual
Celery broker. Measure pool saturation and acquisition outcomes per API
and worker process. Clean up dead-child gauges in the worker parent and
retain completed task counters.
Observe fresh Redis and Valkey application/broker memory through the
bounded scrape collector. Scope alerts and dashboards to TestLookup.
Support secret-backed API scrape authentication in optional Compose and
Kubernetes profiles. Validate mounted configs and alert behavior in the
existing CI jobs and track acceptance in the delivery ledger.
More work remains on queue age and consumer signals, dependency and host
exporters, and production PostgreSQL and scraper profile acceptance.
Signed-off-by: Anand Topu
---
.env.example | 5 +
.github/workflows/ci.yml | 12 +-
CHANGELOG.md | 2 +
architecture/OBSERVABILITY.md | 36 ++
backend/app/bootstrap.py | 90 ++---
backend/app/core/config.py | 3 +
backend/app/core/metrics.py | 90 +++++
backend/app/db/pool_metrics.py | 151 ++++++++
backend/app/db/postgres.py | 3 +
backend/app/db/redis_client.py | 32 +-
backend/app/routers/health.py | 20 +-
backend/app/services/celery_queue_metrics.py | 45 +++
backend/app/services/metric_collection.py | 2 +-
.../app/services/redis_resource_metrics.py | 86 +++++
backend/app/worker/celery_app.py | 114 ++++--
backend/app/worker/ingestion_routing.py | 3 +-
backend/app/worker/queue_inventory.py | 44 +++
backend/tests/celery_queue_fakes.py | 35 ++
.../test_db_pool_metrics_postgres.py | 56 +++
.../test_alert_rules_are_deployable.py | 3 +-
.../test_celery_queue_depth_metric.py | 11 +-
.../regression/test_celery_queue_inventory.py | 150 ++++++++
.../tests/regression/test_db_pool_metrics.py | 347 ++++++++++++++++++
.../regression/test_fleet_metrics_topology.py | 47 ++-
..._grafana_dashboard_metrics_are_declared.py | 5 +-
.../test_health_dashboards_need_a_sign_in.py | 51 ++-
.../test_health_ingestion_reports_unknown.py | 5 +-
.../test_operational_metric_collection.py | 8 +-
.../regression/test_redis_resource_metrics.py | 227 ++++++++++++
.../test_worker_metrics_exposure.py | 133 +++++++
docker-compose.monitoring-auth.yml | 20 +
docker-compose.monitoring.yml | 1 +
docs/maintainers/observability-delivery.md | 21 +-
docs/operations/configuration.md | 1 +
docs/operations/db-pool-metrics.md | 41 +++
docs/operations/dependency-metrics.md | 46 +++
docs/operations/deploy-compose.md | 13 +
docs/operations/deploy-kubernetes.md | 10 +-
docs/operations/deployment.md | 2 +-
docs/reference/configuration.md | 1 +
docs/reference/worker-operations.md | 4 +-
.../backend-scrape-authenticated.yml | 10 +
infra/monitoring/backend-scrape.yml | 6 +
.../dashboards/testlookup-overview.json | 105 ++++++
.../prometheus-rules/testlookup-alerts.yml | 47 ++-
infra/monitoring/prometheus.yml | 11 +-
infra/monitoring/tests/pool-alerts.yml | 84 +++++
infra/monitoring/tests/redis-resources.yml | 106 ++++++
.../metrics-auth/backend-token-mount.yaml | 23 ++
.../metrics-auth/kustomization.yaml | 9 +
.../kustomization.yaml | 19 +
k8s/monitoring/prometheusrule.yaml | 22 +-
52 files changed, 2249 insertions(+), 169 deletions(-)
create mode 100644 backend/app/db/pool_metrics.py
create mode 100644 backend/app/services/celery_queue_metrics.py
create mode 100644 backend/app/services/redis_resource_metrics.py
create mode 100644 backend/app/worker/queue_inventory.py
create mode 100644 backend/tests/celery_queue_fakes.py
create mode 100644 backend/tests/integration/test_db_pool_metrics_postgres.py
create mode 100644 backend/tests/regression/test_celery_queue_inventory.py
create mode 100644 backend/tests/regression/test_db_pool_metrics.py
create mode 100644 backend/tests/regression/test_redis_resource_metrics.py
create mode 100644 docker-compose.monitoring-auth.yml
create mode 100644 docs/operations/db-pool-metrics.md
create mode 100644 docs/operations/dependency-metrics.md
create mode 100644 infra/monitoring/backend-scrape-authenticated.yml
create mode 100644 infra/monitoring/backend-scrape.yml
create mode 100644 infra/monitoring/tests/pool-alerts.yml
create mode 100644 infra/monitoring/tests/redis-resources.yml
create mode 100644 k8s/components/metrics-auth/backend-token-mount.yaml
create mode 100644 k8s/components/metrics-auth/kustomization.yaml
create mode 100644 k8s/monitoring-authenticated/kustomization.yaml
diff --git a/.env.example b/.env.example
index c62a49ff6..1b3d86f4f 100644
--- a/.env.example
+++ b/.env.example
@@ -251,6 +251,7 @@ JWT_ACCESS_TOKEN_EXPIRE_MINUTES=30 # clients keep a session going with the re
# LOGIN_ATTEMPTS_PER_USERNAME_PER_MINUTE=20
# Set to require "Authorization: Bearer " on /metrics. Empty = open.
# METRICS_TOKEN=
+# METRICS_TOKEN_FILE=/run/secrets/testlookup-metrics-token
# false turns off /api-docs and the OpenAPI document.
# API_DOCS_ENABLED=true
# Self-service sign-up (the login page's "Register"). SECURE DEFAULT: false --
@@ -296,6 +297,10 @@ E2E_ADMIN_PASSWORD=
KNOWLEDGE_RAG_ENABLED=false
# ── Monitoring (optional overlay) ─────────────────────────────
+# For docker-compose.monitoring-auth.yml, point each service at a protected
+# host file containing the same metrics bearer token. Do not put the token here.
+# METRICS_API_TOKEN_SOURCE=
+# METRICS_PROMETHEUS_TOKEN_SOURCE=
# Required when using docker-compose.monitoring.yml
# Generate with: openssl rand -hex 16
GF_SECURITY_ADMIN_PASSWORD=
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 642c8e165..157303523 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -536,7 +536,16 @@ jobs:
tar -xzf "$archive" -C "$scratch" "prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool"
tool="$scratch/prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool"
"$tool" check rules ../prometheus-rules/testlookup-alerts.yml
- "$tool" test rules operational-alerts.yml
+ "$tool" test rules ./*.yml
+ # Mirror the Compose mounts and validate included scrape jobs and rules.
+ mkdir "$scratch/config"
+ cp ../prometheus.yml "$scratch/config/"
+ cp -R ../prometheus-rules "$scratch/config/rules"
+ for backend_job in ../backend-scrape.yml ../backend-scrape-authenticated.yml; do
+ cp "$backend_job" "$scratch/config/backend-scrape.yml"
+ printf '%s\n' 'synthetic-test-token' > "$scratch/config/metrics-token"
+ "$tool" check config "$scratch/config/prometheus.yml"
+ done
# Blocking, as a ratchet (re-audit M24). mypy reports 391 pre-existing
# errors in 117 files; backend/mypy-baseline.txt holds the per-file
@@ -1075,6 +1084,7 @@ jobs:
tests/integration/test_workflow_definition_races_postgres.py
tests/integration/test_test_case_lifecycle_postgres.py
tests/integration/test_db_connection_budget_postgres.py
+ tests/integration/test_db_pool_metrics_postgres.py
tests/integration/test_engine_hides_parameters_postgres.py
tests/integration/test_decision_report_supersession_postgres_mongo.py
tests/integration/test_http_exchanges_postgres_mongo.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a4e5ea1ad..f32eef78f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,12 +9,14 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).
### Added
+- Operational metrics report SQLAlchemy pool pressure and acquisition timeouts for API and worker processes, plus Redis and Valkey memory for the application and broker. Optional Compose and Kubernetes profiles support file-backed authentication for API scrapes.
- Operational metrics expose collector freshness and durable downstream-outbox failure/overdue state, including alerts that avoid counting the same SQL rows across API replicas.
- Release verification: journey **TL-AUTH-003** (one account per browser profile, P1, disposable stack) checks the D-0019 fix on the live stack. In two tabs of one browser, a sign-in as a viewer moves the admin's tab onto the viewer with the note, a new tab opens as the viewer, and the viewer's sign-out signs the other tab out (`frontend/tests/release/session.spec.ts`, `e2e-runner/catalogue.yaml`).
### Changed
+- Celery queue depth reads all configured broker priority lists, including child work, and reports unknown counts when a list cannot be read.
- Upload publication uses bounded background threads; uncertain queue confirmation retains the payload and returns polling identifiers so callers can check before resubmitting.
- Trace exporters sanitize exception events and custom text as well as URL attributes. Browser error batches use UTF-8 byte limits; unexpected core API errors return a correlated request identifier. Worker task context and startup readiness markers are reset between executions.
- Image publication and release authorization require trusted successful secret-scan evidence for the exact main commit. Main pushes scan the full tracked candidate tree as well as added history, so an unchanged secret from an earlier failed push still blocks publication. Webhook failure alerts detect failures at low traffic volumes.
diff --git a/architecture/OBSERVABILITY.md b/architecture/OBSERVABILITY.md
index ec52ba250..8941a0746 100644
--- a/architecture/OBSERVABILITY.md
+++ b/architecture/OBSERVABILITY.md
@@ -70,6 +70,42 @@ and a pending review older than 24 hours. Operators can inspect both Redis DLQ
stores at `GET /api/v1/admin/dlq`; `POST /api/v1/admin/dlq/{id}/replay` accepts
only the allowlisted Celery task shapes written by the application.
+### 2c. Logical Celery queue depths
+
+`worker/queue_inventory.py` defines the five base queues (`critical`,
+`ingestion`, `ai_analysis`, `agent_children`, `default`) and appends the
+configured ingestion shards. Celery declarations/routes, `/health/ingestion`
+and scrape collection share that inventory. Deployment worker `-Q`
+subscriptions still require profile-specific verification; declaring a queue
+does not establish that an active worker consumes it.
+
+`celery_queue_length{queue_name}` and the health response's existing `queues`
+map count broker-pending messages across **every Redis priority bin**, using
+the configured broker URL, separator, priority steps and global key prefix.
+The standard Redis transport uses four lists per logical queue; reading only
+the unsuffixed list misses nonzero-priority work. Collection uses one
+nontransactional read pipeline. A failed bin makes that logical queue unknown
+(`null` in health), preserves other readable queues, and fails the scrape
+collector's success/freshness contract. Retained metric values must be read
+with `testlookup_metric_collection_success{collector="queues"}` and collection
+freshness; they are not a current measurement after a failed read.
+
+The health endpoint's `status`, `redis_reachable` and memory/admission fields
+retain their existing meaning: **application admission Redis**. Queue counts
+refer to the separately configured broker; an `ok` admission status does not
+make a `null` queue count healthy. No new response fields are introduced.
+Pipeline work is linear in the declared inventory: with default priorities,
+`4 * (5 + LIVE_INGEST_SHARD_COUNT)` length reads. Large shard counts need
+profile sizing; the scrape's collection deadline is not a fixed command-count
+limit or a claim of unlimited throughput.
+
+These counts exclude active, prefetched/reserved and unacknowledged deliveries.
+They do not measure oldest pending age, consumption rate or durable completion.
+Those require producer timestamp and consumer/lifecycle contracts plus a
+disposable stopped-consumer/recovery check; no age is inferred from an arbitrary
+Redis list endpoint. SQL outbox lifecycle signals remain separate. See the
+[Celery Redis priority contract](https://docs.celeryq.dev/en/stable/userguide/routing.html#redis-message-priorities).
+
## 3. Traces (`core/tracing.py`)
`setup_tracing(otlp_endpoint=…)` wires the OTEL SDK with an OTLP HTTP exporter
diff --git a/backend/app/bootstrap.py b/backend/app/bootstrap.py
index 6b8bf9bd7..95f8d5067 100644
--- a/backend/app/bootstrap.py
+++ b/backend/app/bootstrap.py
@@ -4,6 +4,7 @@
import inspect
from collections.abc import Sequence
+from pathlib import Path
from fastapi import APIRouter, Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
@@ -419,8 +420,6 @@ def configure_metrics(app: FastAPI) -> None:
should_ignore_untemplated=True,
excluded_handlers=["/metrics", "/health/live", "/health/ready"],
).instrument(app).expose(app, endpoint="/metrics", include_in_schema=False)
- _require_metrics_token(app)
-
# W17b ADM-06: budgeted routes are also timed in-app (Settings > Performance reads them back
# without a Prometheus server). Cheap: one dict lookup per request, nothing for other routes.
from app.services.observed_performance import ObservedLatencyMiddleware
@@ -457,28 +456,19 @@ def register_routers(app: FastAPI) -> None:
async def _refresh_celery_queue_depths() -> bool:
"""Read pending task counts straight off the Redis broker.
- Celery queues are Redis lists keyed by queue name, so LLEN is the depth.
+ Logical Redis queues may span several priority lists; sum every bin.
Best-effort: metrics collection must never break the scrape or the app —
a failed read leaves the previous sample rather than raising.
"""
try:
from app.core.metrics import celery_queue_length
- from app.db.redis_client import get_redis
- from app.worker.ingestion_routing import LEGACY_INGESTION_QUEUE, all_shard_queues
-
- queues = ["critical", "ai_analysis", "default", "agent_children", LEGACY_INGESTION_QUEUE]
- queues += list(all_shard_queues())
-
- redis = get_redis()
- async def refresh_queue(name: str) -> bool:
- try:
- depth = await redis.llen(name)
- except Exception: # noqa: BLE001 — one bad queue must not hide the rest
- return False
- celery_queue_length.labels(queue_name=name).set(float(depth or 0))
- return True
-
- return all(await asyncio.gather(*(refresh_queue(name) for name in queues)))
+ from app.services.celery_queue_metrics import read_celery_queue_depths
+
+ depths = await read_celery_queue_depths()
+ for name, depth in depths.items():
+ if depth is not None:
+ celery_queue_length.labels(queue_name=name).set(float(depth))
+ return all(depth is not None for depth in depths.values())
except Exception as exc: # noqa: BLE001
import structlog
@@ -488,53 +478,43 @@ async def refresh_queue(name: str) -> bool:
return False
-def _metrics_scrape_refusal(request):
- """A 401 for a scrape without the configured token, else ``None``.
-
- ``METRICS_TOKEN`` is optional: empty leaves ``/metrics`` open, as it always
- was (the shipped proxies do not route it). When it is set, the scrape must
- send ``Authorization: Bearer ``. Read per request, so the setting is
- the only switch.
- """
- expected = settings.METRICS_TOKEN
+def _load_metrics_token() -> bytes:
+ """Load a mounted credential once, including Kubernetes projected files."""
+ if not settings.METRICS_TOKEN_FILE:
+ return settings.METRICS_TOKEN.encode("utf-8")
+ path = Path(settings.METRICS_TOKEN_FILE)
+ try:
+ if not path.is_file():
+ raise OSError
+ with path.open("rb") as handle:
+ data = handle.read(4097)
+ except (OSError, ValueError):
+ raise RuntimeError("The configured metrics credential file cannot be read") from None
+ token = data.strip()
+ if len(data) > 4096 or not token or any(not 33 <= byte <= 126 for byte in token):
+ raise RuntimeError("The configured metrics credential file must contain one nonempty ASCII token")
+ return token
+
+
+def _metrics_scrape_refusal(request, expected: bytes):
+ """Check bearer authentication before running any metrics collectors."""
if not expected:
return None
scheme, _, presented = request.headers.get("authorization", "").partition(" ")
if scheme.lower() == "bearer" and hmac.compare_digest(
- presented.strip().encode("utf-8"), expected.encode("utf-8")
+ presented.strip().encode("utf-8"), expected
):
return None
return PlainTextResponse(
- "The metrics scrape needs the bearer token set in METRICS_TOKEN. "
- "Send it as: Authorization: Bearer \n",
+ "The metrics scrape requires Authorization: Bearer \n",
status_code=401,
headers={"WWW-Authenticate": "Bearer"},
)
-def _require_metrics_token(app) -> None:
- """Put the token check in front of the instrumentator's /metrics route."""
- for route in app.routes:
- if getattr(route, "path", None) != "/metrics":
- continue
- original = route.endpoint
-
- async def _endpoint(request, __orig=original):
- refusal = _metrics_scrape_refusal(request)
- if refusal is not None:
- return refusal
- result = __orig(request)
- if inspect.isawaitable(result):
- result = await result
- return result
-
- route.endpoint = _endpoint
- route.app = request_response(_endpoint)
- return
-
-
def _install_celery_queue_depth_collector(app) -> None:
- """Wrap the instrumentator's /metrics route so depths refresh per scrape."""
+ """Authorize the scrape, then refresh operational metrics."""
+ expected = _load_metrics_token()
for route in app.routes:
if getattr(route, "path", None) != "/metrics":
continue
@@ -544,7 +524,7 @@ async def _endpoint(*args, __orig=original, **kwargs):
# A refused scrape must not cost a Redis round trip: answer it
# before refreshing anything.
request = args[0] if args else kwargs.get("request")
- refusal = _metrics_scrape_refusal(request) if request is not None else None
+ refusal = _metrics_scrape_refusal(request, expected) if request is not None else None
if refusal is not None:
return refusal
from app.services.agent_operational_metrics import (
@@ -554,11 +534,13 @@ async def _endpoint(*args, __orig=original, **kwargs):
refresh_downstream_operational_metrics,
)
from app.services.metric_collection import collect_bounded
+ from app.services.redis_resource_metrics import refresh_redis_resource_metrics
await asyncio.gather(
collect_bounded("queues", _refresh_celery_queue_depths),
collect_bounded("agents", refresh_agent_operational_metrics),
collect_bounded("downstream", refresh_downstream_operational_metrics),
+ collect_bounded("redis", refresh_redis_resource_metrics),
)
result = __orig(*args, **kwargs)
if inspect.isawaitable(result):
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 26a38aa1c..ec808200a 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -976,6 +976,9 @@ def _validate_sso_max_provisioned_role(cls, v):
# scrape open, as before: the shipped proxies do not route /metrics. When
# set, a scrape must send "Authorization: Bearer " or it gets 401.
METRICS_TOKEN: str = ""
+ # Mounted bearer credential, loaded when the API process starts. A
+ # configured file takes precedence and must contain a nonempty token.
+ METRICS_TOKEN_FILE: str = ""
# The API reference (/api-docs, /api-docs/redoc, /api-docs/openapi.json).
# false turns all three routes off.
API_DOCS_ENABLED: bool = True
diff --git a/backend/app/core/metrics.py b/backend/app/core/metrics.py
index 5db16db0a..9c535add7 100644
--- a/backend/app/core/metrics.py
+++ b/backend/app/core/metrics.py
@@ -882,3 +882,93 @@
["operation", "status"],
multiprocess_mode="mostrecent",
)
+
+# Redis/Valkey INFO memory is server-wide, even when logical databases differ.
+# Roles identify configured endpoint authority, never URLs or credentials.
+# Keep each role separate and max (never sum) redundant API observations.
+redis_memory_used_bytes = Gauge(
+ "redis_memory_used_bytes",
+ "Allocator bytes reported by INFO memory for the configured Redis role",
+ ["store_role"], multiprocess_mode="mostrecent",
+)
+redis_memory_max_bytes = Gauge(
+ "redis_memory_max_bytes",
+ "Configured Redis maxmemory bytes; zero explicitly means no dataset limit",
+ ["store_role"], multiprocess_mode="mostrecent",
+)
+redis_memory_rss_bytes = Gauge(
+ "testlookup_redis_memory_rss_bytes",
+ "Process resident memory reported by Redis; not a container capacity limit",
+ ["store_role"], multiprocess_mode="mostrecent",
+)
+redis_memory_not_counted_for_evict_bytes = Gauge(
+ "testlookup_redis_memory_not_counted_for_evict_bytes",
+ "Redis memory excluded from the maxmemory eviction calculation",
+ ["store_role"], multiprocess_mode="mostrecent",
+)
+redis_memory_counted_for_evict_bytes = Gauge(
+ "testlookup_redis_memory_counted_for_evict_bytes",
+ "Allocator memory minus excluded eviction buffers, bounded at zero",
+ ["store_role"], multiprocess_mode="mostrecent",
+)
+redis_memory_limit_configured = Gauge(
+ "testlookup_redis_memory_limit_configured",
+ "Whether the configured Redis role reports a positive maxmemory limit",
+ ["store_role"], multiprocess_mode="mostrecent",
+)
+
+# SQLAlchemy pools are private to each API/prefork process. Sum their current
+# absolute values, but retain the worst live process's utilization: dividing
+# fleet totals would hide an exhausted child behind idle siblings. Only the
+# bounded PG_PROCESS_ROLE (api/worker/operation) is exported as a label.
+sqlalchemy_pool_checked_out = Gauge(
+ "sqlalchemy_pool_checked_out",
+ "Connections checked out from initialized process-local pools",
+ ["role"], multiprocess_mode="livesum",
+)
+sqlalchemy_pool_size = Gauge(
+ "sqlalchemy_pool_size",
+ "Configured persistent size of initialized process-local pools",
+ ["role"], multiprocess_mode="livesum",
+)
+sqlalchemy_pool_max_overflow = Gauge(
+ "sqlalchemy_pool_max_overflow",
+ "Configured finite overflow allowance, zero if unbounded",
+ ["role"], multiprocess_mode="livesum",
+)
+sqlalchemy_pool_capacity = Gauge(
+ "sqlalchemy_pool_capacity",
+ "Configured finite pool size plus overflow, zero if unbounded",
+ ["role"], multiprocess_mode="livesum",
+)
+sqlalchemy_pool_capacity_limited = Gauge(
+ "sqlalchemy_pool_capacity_limited",
+ "Initialized pools with a finite configured capacity",
+ ["role"], multiprocess_mode="livesum",
+)
+sqlalchemy_pool_overflow = Gauge(
+ "sqlalchemy_pool_overflow",
+ "Open connections above persistent pool size, never negative",
+ ["role"], multiprocess_mode="livesum",
+)
+sqlalchemy_pool_utilization_ratio = Gauge(
+ "sqlalchemy_pool_utilization_ratio",
+ "Maximum live process pool checked-out / finite capacity, zero if unbounded",
+ ["role"], multiprocess_mode="livemax",
+)
+sqlalchemy_pool_acquiring = Gauge(
+ "sqlalchemy_pool_acquiring",
+ "Pool acquisition attempts in progress, including queue wait/connect/pre-ping",
+ ["role"], multiprocess_mode="livesum",
+)
+sqlalchemy_pool_acquire_seconds = Histogram(
+ "sqlalchemy_pool_acquire_seconds",
+ "One pool acquisition duration including wait/connect/pre-ping; errors include cancellation",
+ ["role", "outcome"], # success | timeout | error
+ buckets=(0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60),
+)
+sqlalchemy_pool_timeouts_total = Counter(
+ "sqlalchemy_pool_timeouts_total",
+ "Pool queue acquisition timeouts (SQLAlchemy 3o7r), once per public attempt",
+ ["role"],
+)
diff --git a/backend/app/db/pool_metrics.py b/backend/app/db/pool_metrics.py
new file mode 100644
index 000000000..70dbd7060
--- /dev/null
+++ b/backend/app/db/pool_metrics.py
@@ -0,0 +1,151 @@
+"""Process-local SQLAlchemy pool measurements, safe for async and prefork use.
+
+Each application process owns one lazy PostgreSQL engine. Absolute pool values
+sum across live processes, while utilization uses ``livemax``: an exhausted
+child must remain visible even when its siblings have idle pools. Only the
+bounded process role is a label; neither connection strings nor process IDs are
+exported. The existing Gunicorn/Celery child-exit hooks reap these live gauges.
+
+Capacity includes configured overflow, rather than only persistent pool size.
+Negative cold-pool overflow is reported as zero. For an unbounded pool (not a
+supported application configuration), capacity and utilization are zero and
+``capacity_limited`` is zero; zero does not claim that pool is exhausted.
+
+Acquisition duration includes queue wait, connection creation and pre-ping. It
+is not a query timer or a pure queue-wait measurement. A public ``connect`` call
+is one attempt even when SQLAlchemy internally retries checkout. Only its
+documented QueuePool timeout (error code 3o7r) increments the timeout counter.
+"""
+from __future__ import annotations
+
+import logging
+import os
+from time import perf_counter
+from typing import Any
+from weakref import WeakValueDictionary
+
+from sqlalchemy.exc import TimeoutError as SQLAlchemyTimeoutError
+from sqlalchemy.pool import AsyncAdaptedQueuePool
+
+from app.core.config import settings
+from app.core.metrics import (
+ sqlalchemy_pool_acquire_seconds,
+ sqlalchemy_pool_acquiring,
+ sqlalchemy_pool_capacity,
+ sqlalchemy_pool_capacity_limited,
+ sqlalchemy_pool_checked_out,
+ sqlalchemy_pool_max_overflow,
+ sqlalchemy_pool_overflow,
+ sqlalchemy_pool_size,
+ sqlalchemy_pool_timeouts_total,
+ sqlalchemy_pool_utilization_ratio,
+)
+
+logger = logging.getLogger(__name__)
+
+# Internal object identity is never a metric label. Engine.dispose() recreates
+# its pool; late checkins from the detached old pool must not overwrite the new
+# pool's pressure. Weak references do not retain disposed engines/connections.
+_current_pools: WeakValueDictionary[tuple[int, str], InstrumentedAsyncAdaptedQueuePool] = (
+ WeakValueDictionary()
+)
+
+
+class InstrumentedAsyncAdaptedQueuePool(AsyncAdaptedQueuePool):
+ """Keep SQLAlchemy's async queue semantics and add passive measurements.
+
+ ``_do_return_conn`` is the one small internal hook: the public checkin event
+ fires BEFORE the connection has returned to the queue, so sampling there
+ leaves the final checked-out gauge one too high. No queue/lock behavior is
+ replaced. The pinned SQLAlchemy contract is covered by real async tests.
+ """
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self._metric_pid = os.getpid()
+ self._metric_role = settings.PG_PROCESS_ROLE
+ self._metric_warning_logged = False
+ _current_pools[(self._metric_pid, self._metric_role)] = self
+ self._safe_metric_update(self._initialize_series)
+ self._refresh_metrics()
+
+ def _safe_metric_update(self, operation: Any) -> bool:
+ try:
+ operation()
+ return True
+ except Exception:
+ # A failed exporter file/write must not fail a database operation.
+ # No exception text, URL or statement is included in this warning.
+ if not self._metric_warning_logged:
+ self._metric_warning_logged = True
+ logger.warning("db_pool_metric_update_failed")
+ return False
+
+ def _initialize_series(self) -> None:
+ sqlalchemy_pool_acquiring.labels(role=self._metric_role)
+ sqlalchemy_pool_timeouts_total.labels(role=self._metric_role)
+ for outcome in ("success", "timeout", "error"):
+ sqlalchemy_pool_acquire_seconds.labels(role=self._metric_role, outcome=outcome)
+
+ def _refresh_metrics(self) -> None:
+ def update() -> None:
+ key = (self._metric_pid, self._metric_role)
+ if os.getpid() != self._metric_pid or _current_pools.get(key) is not self:
+ return
+ size = self.size()
+ limited = size > 0 and self._max_overflow >= 0
+ capacity = size + self._max_overflow if limited else 0
+ checked_out = max(0, self.checkedout())
+ role = self._metric_role
+ sqlalchemy_pool_checked_out.labels(role=role).set(checked_out)
+ sqlalchemy_pool_size.labels(role=role).set(size)
+ sqlalchemy_pool_max_overflow.labels(role=role).set(max(0, self._max_overflow))
+ sqlalchemy_pool_capacity.labels(role=role).set(capacity)
+ sqlalchemy_pool_capacity_limited.labels(role=role).set(int(limited))
+ sqlalchemy_pool_overflow.labels(role=role).set(max(0, self.overflow()))
+ sqlalchemy_pool_utilization_ratio.labels(role=role).set(
+ checked_out / capacity if capacity else 0
+ )
+
+ self._safe_metric_update(update)
+
+ def connect(self) -> Any:
+ started = perf_counter()
+ outcome = "error"
+ counted = self._safe_metric_update(
+ lambda: sqlalchemy_pool_acquiring.labels(role=self._metric_role).inc()
+ )
+ try:
+ connection = super().connect()
+ outcome = "success"
+ return connection
+ except SQLAlchemyTimeoutError as exc:
+ if exc.code == "3o7r":
+ outcome = "timeout"
+ self._safe_metric_update(
+ lambda: sqlalchemy_pool_timeouts_total.labels(role=self._metric_role).inc()
+ )
+ raise
+ finally:
+ if counted:
+ self._safe_metric_update(
+ lambda: sqlalchemy_pool_acquiring.labels(role=self._metric_role).dec()
+ )
+ self._safe_metric_update(
+ lambda: sqlalchemy_pool_acquire_seconds.labels(
+ role=self._metric_role, outcome=outcome
+ ).observe(perf_counter() - started)
+ )
+ self._refresh_metrics()
+
+ def _do_return_conn(self, record: Any) -> None:
+ try:
+ super()._do_return_conn(record)
+ finally:
+ self._refresh_metrics()
+
+ def dispose(self) -> None:
+ try:
+ super().dispose()
+ finally:
+ self._refresh_metrics()
diff --git a/backend/app/db/postgres.py b/backend/app/db/postgres.py
index 69700a1dd..7097ac904 100644
--- a/backend/app/db/postgres.py
+++ b/backend/app/db/postgres.py
@@ -143,10 +143,13 @@ def get_engine() -> AsyncEngine:
production), pool_recycle capped at 900s to stay within typical PG
idle timeouts.
"""
+ from app.db.pool_metrics import InstrumentedAsyncAdaptedQueuePool
+
pool = get_effective_pool_config()
return create_async_engine(
settings.DATABASE_URL,
echo=settings.is_development,
+ poolclass=InstrumentedAsyncAdaptedQueuePool,
# Re-audit M1: a worker's pooled connections now outlive a task, so a
# Postgres restart or an idle timeout must not strand dead ones in the
# pool. The API keeps the P3-5 saving; its pool was always long-lived.
diff --git a/backend/app/db/redis_client.py b/backend/app/db/redis_client.py
index 7b0258b17..0d76fd847 100644
--- a/backend/app/db/redis_client.py
+++ b/backend/app/db/redis_client.py
@@ -11,6 +11,8 @@
_pool: Optional[aioredis.ConnectionPool] = None
_client: Optional[aioredis.Redis] = None
+_broker_pool: Optional[aioredis.ConnectionPool] = None
+_broker_client: Optional[aioredis.Redis] = None
def _single_attempt_options(retry_class: type) -> dict[str, Any]:
@@ -48,13 +50,41 @@ def get_redis() -> aioredis.Redis:
return _client
+def get_broker_redis() -> aioredis.Redis:
+ """Read the configured Celery broker, which may differ from application Redis.
+
+ Observation shares the application pool only when the complete URLs match;
+ a different database/server must not silently report an empty application
+ list as broker health. This client never publishes or consumes a task.
+ """
+ global _broker_pool, _broker_client
+ if settings.CELERY_BROKER_URL == settings.REDIS_URL:
+ return get_redis()
+ if _broker_pool is None:
+ _broker_pool = aioredis.ConnectionPool.from_url(
+ settings.CELERY_BROKER_URL,
+ max_connections=50,
+ decode_responses=True,
+ **_single_attempt_options(AsyncRetry),
+ )
+ if _broker_client is None:
+ _broker_client = aioredis.Redis(connection_pool=_broker_pool)
+ return _broker_client
+
+
def sync_redis_from_url(url: str) -> redis.Redis:
"""A synchronous client with the same timeouts and single-attempt policy (semantic search's index cursor)."""
return redis.Redis.from_url(url, **_single_attempt_options(SyncRetry))
async def close_redis() -> None:
- global _pool, _client
+ global _pool, _client, _broker_pool, _broker_client
+ if _broker_client is not None:
+ await _broker_client.aclose()
+ _broker_client = None
+ if _broker_pool is not None:
+ await _broker_pool.disconnect()
+ _broker_pool = None
if _client is not None:
await _client.aclose()
_client = None
diff --git a/backend/app/routers/health.py b/backend/app/routers/health.py
index 622922559..6454d6d78 100644
--- a/backend/app/routers/health.py
+++ b/backend/app/routers/health.py
@@ -451,20 +451,12 @@ async def health_ingestion() -> dict:
redis_reachable = False
reject_count = None
- # Celery queue depths. Each queue lives as a Redis List under its
- # routing key — ``LLEN`` is O(1). Falls back to None on error so
- # the rest of the payload still renders. Phase 2.4 adds the
- # ingestion shards; the base queues stay so monitoring tools that
- # alert on the legacy names still work.
- from app.worker.ingestion_routing import all_shard_queues
-
- queue_depths: dict[str, int | None] = {}
- base_queues = ("critical", "ingestion", "ai_analysis", "default")
- for queue in (*base_queues, *all_shard_queues()):
- try:
- queue_depths[queue] = int(await redis.llen(queue))
- except Exception:
- queue_depths[queue] = None
+ # Same logical queue inventory and priority-bin accounting as the scrape.
+ # The broker may use another Redis database/server. A failed queue read is
+ # None, never zero; counts exclude active and worker-reserved deliveries.
+ from app.services.celery_queue_metrics import read_celery_queue_depths
+
+ queue_depths = await read_celery_queue_depths()
# Active live sessions — count of state-key hashes. Same pattern as
# the per-project scan; bounded by live-run count.
diff --git a/backend/app/services/celery_queue_metrics.py b/backend/app/services/celery_queue_metrics.py
new file mode 100644
index 000000000..719f27cb3
--- /dev/null
+++ b/backend/app/services/celery_queue_metrics.py
@@ -0,0 +1,45 @@
+"""Read-only logical queue depths, including Redis transport priority bins."""
+from __future__ import annotations
+
+from typing import Any
+
+import structlog
+
+from app.worker.queue_inventory import all_task_queue_names, redis_queue_keys
+
+logger = structlog.get_logger(__name__)
+
+
+async def read_celery_queue_depths() -> dict[str, int | None]:
+ """One pipeline over the declared inventory; a failed bin makes that queue unknown.
+
+ Counts cover broker-pending messages only, excluding worker-reserved and
+ active deliveries. They do not establish task age, throughput, consumer
+ availability or durable completion. Call within the scrape collector budget.
+ Work is linear in the configured queue/priority count, not an absolute
+ fixed-size bound; large shard configurations require profile sizing.
+ """
+ from app.db.redis_client import get_broker_redis
+
+ queues = all_task_queue_names()
+ unknown: dict[str, int | None] = dict.fromkeys(queues)
+ try:
+ keys = {queue: redis_queue_keys(queue) for queue in queues}
+ redis = get_broker_redis()
+ async with redis.pipeline(transaction=False) as pipeline:
+ for physical_keys in keys.values():
+ for key in physical_keys:
+ pipeline.llen(key)
+ results: list[Any] = await pipeline.execute(raise_on_error=False)
+ if len(results) != sum(len(value) for value in keys.values()):
+ return unknown
+ offset = 0
+ for queue, physical_keys in keys.items():
+ values = results[offset:offset + len(physical_keys)]
+ offset += len(physical_keys)
+ if all(type(value) is int and value >= 0 for value in values):
+ unknown[queue] = sum(values)
+ return unknown
+ except Exception as exc: # noqa: BLE001 -- never turn a failed read into zero
+ logger.debug("celery_queue_depth_read_failed", error_type=type(exc).__name__)
+ return unknown
diff --git a/backend/app/services/metric_collection.py b/backend/app/services/metric_collection.py
index 1497b6e1b..1d40ec3dd 100644
--- a/backend/app/services/metric_collection.py
+++ b/backend/app/services/metric_collection.py
@@ -17,7 +17,7 @@
logger = structlog.get_logger(__name__)
COLLECTION_TIMEOUT_SECONDS = 1.0
-COLLECTORS = ("queues", "agents", "downstream")
+COLLECTORS = ("queues", "agents", "downstream", "redis")
@dataclass
diff --git a/backend/app/services/redis_resource_metrics.py b/backend/app/services/redis_resource_metrics.py
new file mode 100644
index 000000000..6f8896085
--- /dev/null
+++ b/backend/app/services/redis_resource_metrics.py
@@ -0,0 +1,86 @@
+"""Read-only resource observations from the actual application and broker Redis."""
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Mapping
+from dataclasses import dataclass
+import re
+
+from app.core.metrics import (
+ redis_memory_counted_for_evict_bytes,
+ redis_memory_limit_configured,
+ redis_memory_max_bytes,
+ redis_memory_not_counted_for_evict_bytes,
+ redis_memory_rss_bytes,
+ redis_memory_used_bytes,
+)
+
+STORE_ROLES = ("application", "broker")
+
+
+@dataclass(frozen=True)
+class MemoryObservation:
+ used: int
+ maximum: int
+ rss: int
+ excluded_from_eviction: int
+
+
+def _memory_observation(info: object) -> MemoryObservation:
+ if not isinstance(info, Mapping):
+ raise ValueError("Redis INFO memory did not return a mapping")
+
+ def count(field: str) -> int:
+ value = info.get(field)
+ if isinstance(value, bool):
+ raise ValueError("Redis INFO memory has an invalid field")
+ if isinstance(value, int) and value >= 0:
+ return value
+ if isinstance(value, str) and re.fullmatch(r"[0-9]+", value):
+ return int(value)
+ # Missing fields/ACL-restricted views are unknown, never healthy zeros.
+ raise ValueError("Redis INFO memory has a missing or invalid field")
+
+ return MemoryObservation(
+ used=count("used_memory"), maximum=count("maxmemory"),
+ rss=count("used_memory_rss"), excluded_from_eviction=count("mem_not_counted_for_evict"),
+ )
+
+
+async def refresh_redis_resource_metrics() -> bool:
+ """Publish both configured roles only after a complete validated observation.
+
+ This collector uses INFO memory only: no CONFIG, key scans, payload reads,
+ or mutations. collect_bounded("redis", ...) owns timeout/freshness. The
+ existing client policy owns socket timeouts, credentials, TLS and retries.
+ """
+ from app.db.redis_client import get_broker_redis, get_redis
+
+ clients = {"application": get_redis(), "broker": get_broker_redis()}
+ unique = {id(client): client for client in clients.values()}
+
+ async def read_memory(identity: int) -> object:
+ # redis-py's command annotation permits a general Awaitable. Wrap it
+ # in an actual coroutine before scheduling it in a TaskGroup.
+ return await unique[identity].info(section="memory")
+
+ # A shared client is queried once. Different logical databases can still
+ # refer to one physical server: expose each role, never sum their memory.
+ async with asyncio.TaskGroup() as group:
+ reads = {
+ identity: group.create_task(read_memory(identity))
+ for identity in unique
+ }
+ observations = {
+ role: _memory_observation(reads[id(client)].result())
+ for role, client in clients.items()
+ }
+ for role, observation in observations.items():
+ labels = {"store_role": role}
+ redis_memory_used_bytes.labels(**labels).set(observation.used)
+ redis_memory_max_bytes.labels(**labels).set(observation.maximum)
+ redis_memory_rss_bytes.labels(**labels).set(observation.rss)
+ redis_memory_not_counted_for_evict_bytes.labels(**labels).set(observation.excluded_from_eviction)
+ redis_memory_counted_for_evict_bytes.labels(**labels).set(max(0, observation.used - observation.excluded_from_eviction))
+ redis_memory_limit_configured.labels(**labels).set(int(observation.maximum > 0))
+ return True
diff --git a/backend/app/worker/celery_app.py b/backend/app/worker/celery_app.py
index 79a312b9f..1e5a430f7 100644
--- a/backend/app/worker/celery_app.py
+++ b/backend/app/worker/celery_app.py
@@ -19,6 +19,10 @@
from kombu import Exchange, Queue
from app.core.config import settings
+from app.worker.queue_inventory import (
+ AGENT_CHILDREN_QUEUE, AI_ANALYSIS_QUEUE, CRITICAL_QUEUE, DEFAULT_QUEUE,
+ INGESTION_QUEUE, all_task_queue_names,
+)
class TimeLimitedTask(Task):
@@ -76,19 +80,10 @@ def queue_delivery_probe(self, correlation_id: str) -> dict[str, str]:
# tuple imperatively so the shard count is read from settings at startup,
# not frozen at module-import time.
def _build_task_queues() -> tuple[Queue, ...]:
- base = [
- Queue("critical", _default_exchange, routing_key="critical", queue_arguments={"x-max-priority": 10}),
- Queue("ingestion", _default_exchange, routing_key="ingestion", queue_arguments={"x-max-priority": 10}),
- Queue("ai_analysis", _default_exchange, routing_key="ai_analysis", queue_arguments={"x-max-priority": 10}),
- Queue("agent_children", _default_exchange, routing_key="agent_children", queue_arguments={"x-max-priority": 10}),
- Queue("default", _default_exchange, routing_key="default", queue_arguments={"x-max-priority": 10}),
- ]
- # Lazy import to avoid the ``app.core.config`` → ``Celery`` import
- # cycle that bites if we put this at module top.
- from app.worker.ingestion_routing import all_shard_queues
- for q in all_shard_queues():
- base.append(Queue(q, _default_exchange, routing_key=q, queue_arguments={"x-max-priority": 10}))
- return tuple(base)
+ return tuple(
+ Queue(name, _default_exchange, routing_key=name, queue_arguments={"x-max-priority": 10})
+ for name in all_task_queue_names()
+ )
celery_app.conf.task_queues = _build_task_queues()
@@ -99,34 +94,34 @@ def _build_task_queues() -> tuple[Queue, ...]:
result_serializer="json",
timezone="UTC",
enable_utc=True,
- task_default_queue="default",
+ task_default_queue=DEFAULT_QUEUE,
task_default_exchange="default",
- task_default_routing_key="default",
+ task_default_routing_key=DEFAULT_QUEUE,
task_routes={
- "app.worker.tasks.run_live_test_analysis": {"queue": "critical"},
- "app.worker.tasks.ingest_test_run": {"queue": "ingestion"},
- "app.worker.tasks.run_ai_analysis": {"queue": "ai_analysis"},
- "app.worker.tasks.run_agent_pipeline": {"queue": "ai_analysis"},
- "app.worker.tasks.run_agent_child_investigation": {"queue": "agent_children"},
- "app.worker.tasks.generate_run_compare_report": {"queue": "ai_analysis"},
- "app.worker.tasks.precompute_suite_comparisons_for_run": {"queue": "ai_analysis"},
- "app.worker.tasks.generate_ai_test_cases_task": {"queue": "ai_analysis"},
- "app.worker.tasks.create_ai_test_plan_task": {"queue": "ai_analysis"},
- "app.worker.tasks.generate_ai_strategy_task": {"queue": "ai_analysis"},
- "app.worker.tasks.run_fixer_run_task": {"queue": "ai_analysis"},
- "app.worker.training_tasks.export_training_data": {"queue": "default"},
- "app.worker.training_tasks.check_finetune_trigger": {"queue": "default"},
- "app.worker.training_tasks.run_finetune_pipeline": {"queue": "default"},
- "app.worker.tasks.reindex_search": {"queue": "default"},
+ "app.worker.tasks.run_live_test_analysis": {"queue": CRITICAL_QUEUE},
+ "app.worker.tasks.ingest_test_run": {"queue": INGESTION_QUEUE},
+ "app.worker.tasks.run_ai_analysis": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.tasks.run_agent_pipeline": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.tasks.run_agent_child_investigation": {"queue": AGENT_CHILDREN_QUEUE},
+ "app.worker.tasks.generate_run_compare_report": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.tasks.precompute_suite_comparisons_for_run": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.tasks.generate_ai_test_cases_task": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.tasks.create_ai_test_plan_task": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.tasks.generate_ai_strategy_task": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.tasks.run_fixer_run_task": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.training_tasks.export_training_data": {"queue": DEFAULT_QUEUE},
+ "app.worker.training_tasks.check_finetune_trigger": {"queue": DEFAULT_QUEUE},
+ "app.worker.training_tasks.run_finetune_pipeline": {"queue": DEFAULT_QUEUE},
+ "app.worker.tasks.reindex_search": {"queue": DEFAULT_QUEUE},
# W12 SRCH-02: a re-embed into a new generation runs on the AI worker,
# one <= 480 s slice per invocation (never in the API process).
- "app.worker.tasks.rebuild_embedding_generation": {"queue": "ai_analysis"},
- "app.worker.tasks.run_retention_purges": {"queue": "default"},
+ "app.worker.tasks.rebuild_embedding_generation": {"queue": AI_ANALYSIS_QUEUE},
+ "app.worker.tasks.run_retention_purges": {"queue": DEFAULT_QUEUE},
# W07 FAIL-04: may wait minutes for a defect-candidate build; kept off ai_analysis.
- "app.worker.tasks.rebuild_run_snapshot": {"queue": "default"},
+ "app.worker.tasks.rebuild_run_snapshot": {"queue": DEFAULT_QUEUE},
# W34 STRAT-13: the every-minute drop-folder sweep (it queues ingest_test_run on "ingestion").
- "app.worker.tasks.watch_drop_folders": {"queue": "default"},
- "app.worker.tasks.*": {"queue": "default"},
+ "app.worker.tasks.watch_drop_folders": {"queue": DEFAULT_QUEUE},
+ "app.worker.tasks.*": {"queue": DEFAULT_QUEUE},
},
# Redis keeps late-acked deliveries in ``unacked`` until this timeout.
# Keep it above the 31-minute hard task limit so a healthy long-running
@@ -1006,6 +1001,54 @@ def _start_metrics_server(**_kwargs: object) -> None:
)
+def _reap_dead_child_metric_gauges(metric_dir: Path) -> None:
+ """Remove only live gauges whose process is confirmed absent on POSIX.
+
+ A killed/OOM child cannot run ``worker_process_shutdown``. This directory
+ belongs to one worker parent and its children; a successful or denied
+ existence probe must preserve that process's observations. Counters,
+ histograms and non-live gauges retain their existing lifecycle.
+ """
+ import os
+
+ if os.name != "posix":
+ return
+
+ from prometheus_client import multiprocess
+
+ try:
+ files = tuple(metric_dir.glob("gauge_live*_*.db"))
+ except OSError:
+ return
+ pids: set[int] = set()
+ for metric_file in files:
+ match = re.fullmatch(
+ r"gauge_live(?:all|sum|min|max|mostrecent)_([1-9][0-9]*)\.db",
+ metric_file.name,
+ )
+ if match is None:
+ continue
+ try:
+ if metric_file.is_symlink() or not metric_file.is_file():
+ continue
+ pids.add(int(match.group(1)))
+ except (OSError, ValueError):
+ continue
+
+ for pid in pids:
+ try:
+ os.kill(pid, 0)
+ except ProcessLookupError:
+ try:
+ multiprocess.mark_process_dead(pid, path=str(metric_dir))
+ except OSError:
+ # Child shutdown may have removed the same gauge already.
+ pass
+ except (OSError, OverflowError):
+ # Permission denied or an unrepresentable PID is not proof of death.
+ continue
+
+
def _start_metrics_file_guard() -> None:
"""Recycle the worker before dead-child metric files become unbounded.
@@ -1030,6 +1073,7 @@ def guard() -> None:
logger = structlog.get_logger(__name__)
while True:
+ _reap_dead_child_metric_gauges(metric_dir)
if len(list(metric_dir.glob("*.db"))) > max_files:
logger.warning(
"worker_metrics_file_limit_reached",
diff --git a/backend/app/worker/ingestion_routing.py b/backend/app/worker/ingestion_routing.py
index 502a7d0c2..87bab91e6 100644
--- a/backend/app/worker/ingestion_routing.py
+++ b/backend/app/worker/ingestion_routing.py
@@ -31,13 +31,14 @@
import hashlib
from app.core.config import settings
+from app.worker.queue_inventory import INGESTION_QUEUE
# Base queue name — kept stable so existing Celery beat / monitoring
# tooling that watches ``ingestion`` still has something to watch even
# when shard routing is enabled. New shardable tasks use the
# ``ingestion.shard.`` namespace.
-LEGACY_INGESTION_QUEUE = "ingestion"
+LEGACY_INGESTION_QUEUE = INGESTION_QUEUE
SHARD_QUEUE_PREFIX = "ingestion.shard."
diff --git a/backend/app/worker/queue_inventory.py b/backend/app/worker/queue_inventory.py
new file mode 100644
index 000000000..bb88f879d
--- /dev/null
+++ b/backend/app/worker/queue_inventory.py
@@ -0,0 +1,44 @@
+"""Canonical logical task queues shared by routing and operational reads."""
+from __future__ import annotations
+
+CRITICAL_QUEUE = "critical"
+INGESTION_QUEUE = "ingestion"
+AI_ANALYSIS_QUEUE = "ai_analysis"
+AGENT_CHILDREN_QUEUE = "agent_children"
+DEFAULT_QUEUE = "default"
+
+BASE_TASK_QUEUES = (
+ CRITICAL_QUEUE, INGESTION_QUEUE, AI_ANALYSIS_QUEUE, AGENT_CHILDREN_QUEUE, DEFAULT_QUEUE,
+)
+
+
+def all_task_queue_names() -> tuple[str, ...]:
+ """Read effective shard settings at call time, keeping legacy queue names."""
+ from app.worker.ingestion_routing import all_shard_queues
+
+ return (*BASE_TASK_QUEUES, *all_shard_queues())
+
+
+def redis_queue_keys(queue: str) -> tuple[str, ...]:
+ """Physical Redis priority lists for one configured logical queue.
+
+ Use the installed transport's defaults and configured overrides rather
+ than assuming LLEN(queue) includes nonzero-priority work. This reproduces
+ the existing key contract; it does not change message ordering or encoding.
+ """
+ from kombu.transport.redis import Channel
+
+ from app.worker.celery_app import celery_app
+
+ options = celery_app.conf.broker_transport_options or {}
+ steps = options.get("priority_steps", Channel.priority_steps)
+ separator = options.get("sep", Channel.sep)
+ prefix = options.get("global_keyprefix", "")
+ if (
+ not isinstance(steps, (list, tuple)) or not steps
+ or any(type(step) is not int or not 0 <= step <= 9 for step in steps)
+ or list(steps) != sorted(set(steps))
+ or not isinstance(separator, str) or not isinstance(prefix, str)
+ ):
+ raise ValueError("unsupported Redis queue transport configuration")
+ return tuple(prefix + queue + (separator + str(step) if step else "") for step in steps)
diff --git a/backend/tests/celery_queue_fakes.py b/backend/tests/celery_queue_fakes.py
new file mode 100644
index 000000000..320b70acf
--- /dev/null
+++ b/backend/tests/celery_queue_fakes.py
@@ -0,0 +1,35 @@
+"""Small async read-only pipeline fake for queue observation tests."""
+from __future__ import annotations
+
+
+class PipelineRedis:
+ def pipeline(self, *, transaction=False):
+ assert transaction is False
+ return _QueuePipeline(self)
+
+
+class _QueuePipeline:
+ def __init__(self, redis):
+ self.redis = redis
+ self.keys = []
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_):
+ return None
+
+ def llen(self, key):
+ self.keys.append(key)
+ return self
+
+ async def execute(self, *, raise_on_error=True):
+ values = []
+ for key in self.keys:
+ try:
+ values.append(await self.redis.llen(key))
+ except Exception as exc:
+ if raise_on_error:
+ raise
+ values.append(exc)
+ return values
diff --git a/backend/tests/integration/test_db_pool_metrics_postgres.py b/backend/tests/integration/test_db_pool_metrics_postgres.py
new file mode 100644
index 000000000..5f4e674f9
--- /dev/null
+++ b/backend/tests/integration/test_db_pool_metrics_postgres.py
@@ -0,0 +1,56 @@
+"""Optional controlled saturation on an explicitly configured disposable DB.
+
+Only SELECT 1 is executed. The tests never use the application's DATABASE_URL;
+TESTLOOKUP_POSTGRES_TEST_DSN must name the isolated integration database.
+"""
+from __future__ import annotations
+
+import os
+
+from prometheus_client import REGISTRY
+import pytest
+from sqlalchemy import text
+from sqlalchemy.exc import TimeoutError as SQLAlchemyTimeoutError
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from app.core.config import settings
+from app.db.pool_metrics import InstrumentedAsyncAdaptedQueuePool
+
+pytestmark = pytest.mark.integration
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("role", ["api", "worker"])
+async def test_postgres_checkout_pressure_timeout_and_recovery(monkeypatch, role):
+ dsn = os.getenv("TESTLOOKUP_POSTGRES_TEST_DSN", "").strip()
+ if not dsn:
+ pytest.skip("TESTLOOKUP_POSTGRES_TEST_DSN is not configured")
+ monkeypatch.setattr(settings, "PG_PROCESS_ROLE", role)
+ db = create_async_engine(
+ dsn, poolclass=InstrumentedAsyncAdaptedQueuePool,
+ pool_size=1, max_overflow=1, pool_timeout=0.05,
+ )
+
+ def sample(name):
+ return REGISTRY.get_sample_value(f"sqlalchemy_pool_{name}", {"role": role})
+
+ try:
+ before_timeouts = sample("timeouts_total")
+ async with db.connect() as first, db.connect() as second:
+ assert (await first.execute(text("SELECT 1"))).scalar_one() == 1
+ assert (await second.execute(text("SELECT 1"))).scalar_one() == 1
+ assert sample("checked_out") == db.sync_engine.pool.checkedout() == 2
+ assert sample("capacity") == 2
+ assert sample("overflow") == 1
+ assert sample("utilization_ratio") == 1
+ with pytest.raises(SQLAlchemyTimeoutError) as failure:
+ await db.connect()
+ assert failure.value.code == "3o7r"
+ assert sample("timeouts_total") == before_timeouts + 1
+ assert sample("checked_out") == 0
+ assert sample("overflow") == 0
+ assert sample("utilization_ratio") == 0
+ async with db.connect() as recovered:
+ assert (await recovered.execute(text("SELECT 1"))).scalar_one() == 1
+ finally:
+ await db.dispose()
diff --git a/backend/tests/regression/test_alert_rules_are_deployable.py b/backend/tests/regression/test_alert_rules_are_deployable.py
index abae86937..4541146ca 100644
--- a/backend/tests/regression/test_alert_rules_are_deployable.py
+++ b/backend/tests/regression/test_alert_rules_are_deployable.py
@@ -155,7 +155,8 @@ def test_semantic_fixtures_execute_in_the_existing_backend_ci_job() -> None:
commands = step["run"]
assert commands.index("sha256sum --check --strict") < commands.index("tar -xzf")
assert '"$tool" check rules ../prometheus-rules/testlookup-alerts.yml' in commands
- assert '"$tool" test rules operational-alerts.yml' in commands
+ assert '"$tool" test rules ./*.yml' in commands
+ assert '"$tool" check config "$scratch/config/prometheus.yml"' in commands
fixture = REPO_ROOT / step["working-directory"] / "operational-alerts.yml"
assert not fixture.is_relative_to(ALERTS.parent), "fixture would be loaded as a production rule file"
data = yaml.safe_load(fixture.read_text(encoding="utf-8"))
diff --git a/backend/tests/regression/test_celery_queue_depth_metric.py b/backend/tests/regression/test_celery_queue_depth_metric.py
index 4cc096e5a..aeab0dbe3 100644
--- a/backend/tests/regression/test_celery_queue_depth_metric.py
+++ b/backend/tests/regression/test_celery_queue_depth_metric.py
@@ -30,6 +30,7 @@
from pathlib import Path
import pytest
+from tests.celery_queue_fakes import PipelineRedis
pytest.importorskip("app.core.metrics")
@@ -75,10 +76,10 @@ def test_metrics_endpoint_refreshes_depths(self):
def test_refresh_reads_every_queue_including_shards(self, monkeypatch):
seen: list[str] = []
- class FakeRedis:
+ class FakeRedis(PipelineRedis):
async def llen(self, name):
seen.append(name)
- return 7
+ return 0 if "\x06\x16" in name else 7
monkeypatch.setattr("app.db.redis_client.get_redis", lambda: FakeRedis(), raising=False)
asyncio.run(bootstrap._refresh_celery_queue_depths())
@@ -94,7 +95,7 @@ async def llen(self, name):
def test_a_broken_redis_never_breaks_the_scrape(self, monkeypatch):
"""Metrics collection must not take down /metrics — losing the scrape
during an incident is worse than losing one gauge."""
- class Exploding:
+ class Exploding(PipelineRedis):
async def llen(self, name):
raise RuntimeError("redis is down")
@@ -102,11 +103,11 @@ async def llen(self, name):
asyncio.run(bootstrap._refresh_celery_queue_depths()) # must not raise
def test_one_bad_queue_does_not_hide_the_others(self, monkeypatch):
- class Picky:
+ class Picky(PipelineRedis):
async def llen(self, name):
if name == "critical":
raise RuntimeError("nope")
- return 3
+ return 0 if "\x06\x16" in name else 3
monkeypatch.setattr("app.db.redis_client.get_redis", lambda: Picky(), raising=False)
asyncio.run(bootstrap._refresh_celery_queue_depths())
diff --git a/backend/tests/regression/test_celery_queue_inventory.py b/backend/tests/regression/test_celery_queue_inventory.py
new file mode 100644
index 000000000..5e5ed9b2a
--- /dev/null
+++ b/backend/tests/regression/test_celery_queue_inventory.py
@@ -0,0 +1,150 @@
+"""Routing, health and metrics observe the same logical broker queues."""
+from __future__ import annotations
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from tests.celery_queue_fakes import PipelineRedis
+from kombu.transport.redis import Channel
+
+from app import bootstrap
+from app.core.config import settings
+from app.core.metrics import celery_queue_length
+from app.services.celery_queue_metrics import read_celery_queue_depths
+from app.worker.celery_app import _build_task_queues, celery_app
+from app.worker.queue_inventory import BASE_TASK_QUEUES, all_task_queue_names, redis_queue_keys
+
+pytestmark = pytest.mark.regression
+
+
+@pytest.mark.parametrize("shards", [0, 1, 8, 16])
+def test_declared_routed_and_observed_inventory_agrees(monkeypatch, shards):
+ monkeypatch.setattr(settings, "LIVE_INGEST_SHARD_COUNT", shards)
+ expected = (*BASE_TASK_QUEUES, *(f"ingestion.shard.{index}" for index in range(shards)))
+ assert all_task_queue_names() == expected
+ assert len(set(expected)) == len(expected)
+ declared = _build_task_queues()
+ assert tuple(queue.name for queue in declared) == expected
+ assert all(queue.routing_key == queue.name for queue in declared)
+ assert all(queue.queue_arguments == {"x-max-priority": 10} for queue in declared)
+ assert {route["queue"] for route in celery_app.conf.task_routes.values()} <= set(expected)
+ assert celery_app.conf.task_routes["app.worker.tasks.run_agent_child_investigation"]["queue"] == "agent_children"
+ assert celery_app.conf.task_default_queue == "default"
+
+
+@pytest.mark.parametrize("options", [{}, {"priority_steps": [0, 2, 5, 9], "sep": ":", "global_keyprefix": "test:"}])
+def test_physical_keys_match_the_installed_kombu_transport(monkeypatch, options):
+ monkeypatch.setattr(celery_app.conf, "broker_transport_options", options)
+ channel = object.__new__(Channel)
+ channel.priority_steps = options.get("priority_steps", Channel.priority_steps)
+ channel.sep = options.get("sep", Channel.sep)
+ prefix = options.get("global_keyprefix", "")
+ expected = tuple(prefix + channel._q_for_pri("agent_children", priority) for priority in channel.priority_steps)
+ assert redis_queue_keys("agent_children") == expected
+
+
+class _Broker(PipelineRedis):
+ def __init__(self, values=None):
+ self.values = values or {}
+ self.seen = []
+
+ async def llen(self, key):
+ self.seen.append(key)
+ value = self.values.get(key, 0)
+ if isinstance(value, Exception):
+ raise value
+ return value
+
+
+@pytest.mark.asyncio
+async def test_child_work_in_priority_bins_is_visible_and_empty_recovery_resets_it(monkeypatch):
+ from app.db import redis_client
+
+ monkeypatch.setattr(settings, "LIVE_INGEST_SHARD_COUNT", 0)
+ keys = redis_queue_keys("agent_children")
+ broker = _Broker({keys[1]: 4, keys[-1]: 3})
+ monkeypatch.setattr(redis_client, "get_broker_redis", lambda: broker)
+ # Reading the application Redis instead would incorrectly report no work.
+ monkeypatch.setattr(redis_client, "get_redis", lambda: pytest.fail("must inspect actual broker"))
+ depths = await read_celery_queue_depths()
+ assert depths["agent_children"] == 7 and depths["default"] == 0
+ assert set(depths) == set(all_task_queue_names())
+ assert set(keys) <= set(broker.seen)
+ assert await bootstrap._refresh_celery_queue_depths()
+ assert celery_queue_length.labels(queue_name="agent_children")._value.get() == 7
+ broker.values.clear()
+ assert await bootstrap._refresh_celery_queue_depths()
+ assert celery_queue_length.labels(queue_name="agent_children")._value.get() == 0
+
+
+@pytest.mark.asyncio
+async def test_a_failed_priority_bin_is_unknown_without_discarding_other_queues(monkeypatch):
+ from app.db import redis_client
+
+ broker = _Broker({redis_queue_keys("agent_children")[-1]: ConnectionError("fake unavailable"), "default": 2})
+ monkeypatch.setattr(redis_client, "get_broker_redis", lambda: broker)
+ depths = await read_celery_queue_depths()
+ assert depths["agent_children"] is None and depths["default"] == 2
+ assert not await bootstrap._refresh_celery_queue_depths()
+
+
+@pytest.mark.asyncio
+async def test_health_uses_the_same_child_and_shard_priority_accounting(monkeypatch):
+ from app.db import postgres, redis_client
+ from app.routers import health
+ from app.services import ingestion_backpressure, ingestion_dlq, run_downstream_outbox
+
+ monkeypatch.setattr(settings, "LIVE_INGEST_SHARD_COUNT", 2)
+
+ class ApplicationRedis:
+ async def get(self, *_):
+ return 0
+
+ def scan_iter(self, **_):
+ async def empty():
+ if False:
+ yield None
+ return empty()
+
+ broker = _Broker({redis_queue_keys("agent_children")[1]: 5, redis_queue_keys("ingestion.shard.1")[-1]: 2})
+ monkeypatch.setattr(redis_client, "get_redis", lambda: ApplicationRedis())
+ monkeypatch.setattr(redis_client, "get_broker_redis", lambda: broker)
+ monkeypatch.setattr(ingestion_backpressure, "get_redis_memory_snapshot", AsyncMock(return_value=MagicMock(used_bytes=10, max_bytes=1000, used_pct=1.0)))
+ monkeypatch.setattr(ingestion_dlq, "get_dlq_count", AsyncMock(return_value=0))
+ monkeypatch.setattr(ingestion_dlq, "get_stream_dlq_count", AsyncMock(return_value=0))
+ monkeypatch.setattr(run_downstream_outbox, "pending_dispatch_count", AsyncMock(return_value=0))
+ session = AsyncMock()
+ monkeypatch.setattr(postgres, "AsyncSessionLocal", lambda: session)
+ payload = await health.health_ingestion()
+ assert payload["status"] == "ok" and payload["redis_reachable"] is True
+ assert payload["queues"] == await read_celery_queue_depths()
+ assert payload["queues"]["agent_children"] == 5
+ assert payload["queues"]["ingestion.shard.1"] == 2
+
+
+def test_broker_reuses_application_pool_only_for_the_same_url(monkeypatch):
+ from app.db import redis_client
+
+ monkeypatch.setattr(settings, "CELERY_BROKER_URL", settings.REDIS_URL)
+ shared = object()
+ monkeypatch.setattr(redis_client, "get_redis", lambda: shared)
+ assert redis_client.get_broker_redis() is shared
+
+
+@pytest.mark.asyncio
+async def test_distinct_broker_database_uses_bounded_pool_and_closes(monkeypatch):
+ from app.core.config import REDIS_SOCKET_TIMEOUT_SECONDS
+ from app.db import redis_client
+
+ for name in ("_pool", "_client", "_broker_pool", "_broker_client"):
+ monkeypatch.setattr(redis_client, name, None)
+ monkeypatch.setattr(settings, "REDIS_URL", "redis://127.0.0.1:6399/0")
+ monkeypatch.setattr(settings, "CELERY_BROKER_URL", "redis://127.0.0.1:6399/2")
+ broker = redis_client.get_broker_redis()
+ options = broker.connection_pool.connection_kwargs
+ assert options["db"] == 2
+ assert options["socket_timeout"] == options["socket_connect_timeout"] == REDIS_SOCKET_TIMEOUT_SECONDS
+ assert options["retry"].get_retries() == 0
+ assert redis_client.get_broker_redis() is broker
+ await redis_client.close_redis()
+ assert redis_client._broker_client is None and redis_client._broker_pool is None
diff --git a/backend/tests/regression/test_db_pool_metrics.py b/backend/tests/regression/test_db_pool_metrics.py
new file mode 100644
index 000000000..bdb0dc364
--- /dev/null
+++ b/backend/tests/regression/test_db_pool_metrics.py
@@ -0,0 +1,347 @@
+"""Exercise the real async queue, without a network database or live writes."""
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import time
+
+from prometheus_client import REGISTRY
+import pytest
+from sqlalchemy import event, text
+from sqlalchemy.exc import DisconnectionError, TimeoutError as SQLAlchemyTimeoutError
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from app.core.config import settings
+from app.db.pool_metrics import InstrumentedAsyncAdaptedQueuePool
+
+pytestmark = pytest.mark.regression
+
+
+def sample(name: str, *, role: str = "api", **labels: str) -> float:
+ value = REGISTRY.get_sample_value(f"sqlalchemy_pool_{name}", {"role": role, **labels})
+ assert value is not None, (name, labels)
+ return value
+
+
+def engine(*, size: int = 1, overflow: int = 1, timeout: float = 0.04):
+ return create_async_engine(
+ "sqlite+aiosqlite://",
+ poolclass=InstrumentedAsyncAdaptedQueuePool,
+ pool_size=size,
+ max_overflow=overflow,
+ pool_timeout=timeout,
+ )
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("role", ["api", "worker"])
+async def test_real_async_pool_counts_capacity_overflow_timeout_and_recovery(monkeypatch, role):
+ monkeypatch.setattr(settings, "PG_PROCESS_ROLE", role)
+ db = engine()
+ try:
+ assert sample("size", role=role) == 1
+ assert sample("max_overflow", role=role) == 1
+ assert sample("capacity", role=role) == 2
+ assert sample("capacity_limited", role=role) == 1
+ assert sample("checked_out", role=role) == 0
+ assert sample("overflow", role=role) == 0 # cold SQLAlchemy overflow is -1
+ assert sample("utilization_ratio", role=role) == 0
+ before = sample("timeouts_total", role=role)
+ timed = sample("acquire_seconds_count", role=role, outcome="timeout")
+ successful = sample("acquire_seconds_count", role=role, outcome="success")
+ first = await db.connect()
+ second = await db.connect()
+ try:
+ assert sample("checked_out", role=role) == db.sync_engine.pool.checkedout() == 2
+ assert sample("overflow", role=role) == 1
+ assert sample("utilization_ratio", role=role) == 1
+ with pytest.raises(SQLAlchemyTimeoutError) as failure:
+ await db.connect()
+ assert failure.value.code == "3o7r"
+ assert sample("timeouts_total", role=role) - before == 1
+ assert sample("acquire_seconds_count", role=role, outcome="timeout") - timed == 1
+ assert sample("acquire_seconds_count", role=role, outcome="success") - successful == 2
+ assert sample("acquiring", role=role) == 0
+ assert sample("checked_out", role=role) == 2
+ finally:
+ await first.close()
+ assert sample("checked_out", role=role) == db.sync_engine.pool.checkedout() == 1
+ await second.close()
+ assert sample("checked_out", role=role) == 0
+ assert sample("overflow", role=role) == 0
+ assert sample("utilization_ratio", role=role) == 0
+ async with db.connect() as recovered:
+ assert (await recovered.execute(text("SELECT 1"))).scalar_one() == 1
+ finally:
+ await db.dispose()
+
+
+@pytest.mark.asyncio
+async def test_waiting_and_cancelled_acquisition_leave_loop_and_pool_usable(monkeypatch):
+ monkeypatch.setattr(settings, "PG_PROCESS_ROLE", "api")
+ db = engine(overflow=0, timeout=1)
+ held = await db.connect()
+
+ async def acquire():
+ return await db.connect()
+
+ pending = asyncio.create_task(acquire())
+ try:
+ for _ in range(10):
+ if sample("acquiring") == 1:
+ break
+ await asyncio.sleep(0)
+ assert sample("acquiring") == 1
+ before_timeouts = sample("timeouts_total")
+ before_errors = sample("acquire_seconds_count", outcome="error")
+ ticks = 0
+ for _ in range(3):
+ await asyncio.sleep(0.005)
+ ticks += 1
+ assert ticks == 3 and not pending.done()
+ pending.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await pending
+ assert sample("acquiring") == 0
+ assert sample("timeouts_total") == before_timeouts
+ assert sample("acquire_seconds_count", outcome="error") - before_errors == 1
+ assert sample("checked_out") == 1
+ await held.close()
+ async with db.connect() as recovered:
+ assert (await recovered.execute(text("SELECT 1"))).scalar_one() == 1
+ finally:
+ pending.cancel()
+ await held.close()
+ await db.dispose()
+
+
+@pytest.mark.asyncio
+async def test_checkout_retry_is_one_logical_attempt_and_connections_are_reused(monkeypatch):
+ monkeypatch.setattr(settings, "PG_PROCESS_ROLE", "api")
+ db = engine()
+ connects = []
+ retries = []
+
+ @event.listens_for(db.sync_engine, "connect")
+ def connected(*_args):
+ connects.append(1)
+
+ @event.listens_for(db.sync_engine, "checkout")
+ def disconnected_once(*_args):
+ if not retries:
+ retries.append(1)
+ raise DisconnectionError("synthetic disconnect before successful checkout")
+
+ before = sample("acquire_seconds_count", outcome="success")
+ try:
+ for _ in range(3):
+ async with db.connect() as connection:
+ assert (await connection.execute(text("SELECT 1"))).scalar_one() == 1
+ assert len(connects) == 2 # one retry, then reuse the surviving connection
+ assert sample("acquire_seconds_count", outcome="success") - before == 3
+ assert sample("checked_out") == 0
+ finally:
+ await db.dispose()
+
+
+@pytest.mark.asyncio
+async def test_other_sqlalchemy_timeout_is_an_error_not_pool_exhaustion(monkeypatch):
+ monkeypatch.setattr(settings, "PG_PROCESS_ROLE", "api")
+ db = engine()
+
+ @event.listens_for(db.sync_engine, "checkout")
+ def fail_checkout(*_args):
+ raise SQLAlchemyTimeoutError("synthetic unrelated timeout")
+
+ before_timeouts = sample("timeouts_total")
+ before_errors = sample("acquire_seconds_count", outcome="error")
+ try:
+ with pytest.raises(SQLAlchemyTimeoutError, match="unrelated"):
+ await db.connect()
+ assert sample("timeouts_total") == before_timeouts
+ assert sample("acquire_seconds_count", outcome="error") - before_errors == 1
+ assert sample("checked_out") == db.sync_engine.pool.checkedout() == 0
+ assert sample("acquiring") == 0
+ finally:
+ await db.dispose()
+
+
+@pytest.mark.asyncio
+async def test_detached_pool_checkin_cannot_overwrite_replacement_pool(monkeypatch):
+ monkeypatch.setattr(settings, "PG_PROCESS_ROLE", "api")
+ db = engine()
+ old = await db.connect()
+ await db.dispose()
+ assert sample("checked_out") == 0
+ assert sample("capacity") == 2
+ current = await db.connect()
+ try:
+ assert sample("checked_out") == 1
+ await old.close()
+ assert sample("checked_out") == 1
+ await current.invalidate()
+ assert sample("checked_out") == db.sync_engine.pool.checkedout() == 0
+ assert sample("utilization_ratio") == 0
+ finally:
+ await old.close()
+ await current.close()
+ await db.dispose()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(("size", "overflow"), [(0, 1), (1, -1)])
+async def test_unbounded_configuration_has_no_false_finite_pressure(monkeypatch, size, overflow):
+ monkeypatch.setattr(settings, "PG_PROCESS_ROLE", "api")
+ db = engine(size=size, overflow=overflow)
+ try:
+ async with db.connect():
+ assert sample("capacity") == 0
+ assert sample("capacity_limited") == 0
+ assert sample("utilization_ratio") == 0
+ finally:
+ await db.dispose()
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("failed_metric", ["gauge", "acquiring", "duration", "timeouts"])
+async def test_metric_failures_preserve_success_and_original_timeout(monkeypatch, failed_metric, caplog):
+ import app.db.pool_metrics as metrics
+
+ monkeypatch.setattr(settings, "PG_PROCESS_ROLE", "api")
+
+ class BrokenMetric:
+ def labels(self, **_kwargs):
+ raise OSError("synthetic unavailable metrics file")
+
+ if failed_metric == "gauge":
+ monkeypatch.setattr(metrics, "sqlalchemy_pool_checked_out", BrokenMetric())
+ else:
+ name = {"acquiring": "sqlalchemy_pool_acquiring", "duration": "sqlalchemy_pool_acquire_seconds", "timeouts": "sqlalchemy_pool_timeouts_total"}[failed_metric]
+ monkeypatch.setattr(metrics, name, BrokenMetric())
+ db = engine(overflow=0)
+ try:
+ async with db.connect() as held:
+ assert (await held.execute(text("SELECT 1"))).scalar_one() == 1
+ with pytest.raises(SQLAlchemyTimeoutError) as failure:
+ await db.connect()
+ assert failure.value.code == "3o7r"
+ assert sum(record.message == "db_pool_metric_update_failed" for record in caplog.records) == 1
+ finally:
+ await db.dispose()
+
+
+@pytest.mark.parametrize("role", ["api", "worker"])
+def test_real_multiprocess_totals_keep_worst_process_pressure_and_reap_dead_children(tmp_path, role):
+ """One saturated child, one idle child: total utilization is only 50%."""
+ metric_dir = tmp_path / "metrics"
+ metric_dir.mkdir()
+ env = os.environ | {
+ "PROMETHEUS_MULTIPROC_DIR": str(metric_dir),
+ "PG_PROCESS_ROLE": role,
+ "PYTHONPATH": os.pathsep.join(filter(None, (
+ str(Path(__file__).resolve().parents[2]), os.environ.get("PYTHONPATH", "")
+ ))),
+ }
+ emitter = """
+import asyncio, os, sys
+from pathlib import Path
+from sqlalchemy.ext.asyncio import create_async_engine
+from app.db.pool_metrics import InstrumentedAsyncAdaptedQueuePool
+async def main():
+ db = create_async_engine('sqlite+aiosqlite://', poolclass=InstrumentedAsyncAdaptedQueuePool,
+ pool_size=1, max_overflow=1)
+ held = [await db.connect() for _ in range(int(sys.argv[1]))]
+ Path(sys.argv[2]).write_text(str(os.getpid()), encoding='ascii')
+ sys.stdin.readline()
+ for connection in held:
+ await connection.close()
+ await db.dispose()
+asyncio.run(main())
+"""
+ collector = """
+import json
+from prometheus_client import CollectorRegistry, multiprocess
+registry = CollectorRegistry()
+multiprocess.MultiProcessCollector(registry)
+print(json.dumps({s.name + '|' + json.dumps(s.labels, sort_keys=True): s.value
+ for family in registry.collect() for s in family.samples
+ if s.name.startswith('sqlalchemy_pool_')}))
+"""
+
+ def scrape():
+ result = subprocess.run([sys.executable, "-c", collector], env=env, capture_output=True,
+ text=True, check=True, timeout=15)
+ return json.loads(result.stdout)
+
+ def value(samples, name, **labels):
+ return samples[f"sqlalchemy_pool_{name}|" + json.dumps({"role": role, **labels}, sort_keys=True)]
+
+ children = []
+ try:
+ for index, held in enumerate((2, 0)):
+ ready = tmp_path / f"ready-{index}"
+ child = subprocess.Popen([sys.executable, "-c", emitter, str(held), str(ready)],
+ env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, text=True)
+ children.append(child)
+ deadline = time.monotonic() + 15
+ while not ready.exists() and child.poll() is None and time.monotonic() < deadline:
+ time.sleep(0.01)
+ assert ready.exists(), "synthetic async pool child did not initialize"
+ samples = scrape()
+ assert value(samples, "checked_out") == 2
+ assert value(samples, "capacity") == 4
+ assert value(samples, "size") == 2
+ assert value(samples, "max_overflow") == 2
+ assert value(samples, "overflow") == 1
+ assert value(samples, "utilization_ratio") == 1
+ assert value(samples, "acquire_seconds_count", outcome="success") == 2
+ assert all("pid" not in json.loads(key.split("|", 1)[1]) for key in samples)
+ children[0].kill()
+ children[0].wait(timeout=10)
+ from prometheus_client import multiprocess
+
+ multiprocess.mark_process_dead(children[0].pid, path=str(metric_dir))
+ surviving = scrape()
+ assert value(surviving, "checked_out") == 0
+ assert value(surviving, "capacity") == 2
+ assert value(surviving, "utilization_ratio") == 0
+ # Counters/histograms retain completed observations across child recycle.
+ assert value(surviving, "acquire_seconds_count", outcome="success") == 2
+ finally:
+ for child in children:
+ if child.poll() is None:
+ child.kill()
+ child.communicate(timeout=10)
+
+
+def test_application_cached_engine_uses_instrumented_async_pool():
+ from app.db.postgres import get_engine
+
+ db = get_engine()
+ assert isinstance(db.sync_engine.pool, InstrumentedAsyncAdaptedQueuePool)
+ assert get_engine() is db
+
+
+def test_pool_dashboard_preserves_target_pressure_and_scoped_timeout_totals():
+ source = Path(__file__).resolve().parents[3] / "infra/monitoring/grafana/dashboards/testlookup-overview.json"
+ panels = {panel["id"]: panel for panel in json.loads(source.read_text(encoding="utf-8"))["panels"]}
+ assert panels[110]["type"] == "row" and panels[110]["collapsed"] is False
+ assert panels[110]["gridPos"]["y"] < panels[111]["gridPos"]["y"]
+ pressure = panels[111]["targets"][0]["expr"]
+ assert "max by (cluster, namespace, job, instance, role)" in pressure
+ assert "sqlalchemy_pool_utilization_ratio" in pressure
+ assert 'sqlalchemy_pool_capacity_limited{job=~"testlookup-backend|testlookup-worker"} > 0' in pressure
+ assert " / " not in pressure
+ assert panels[111]["fieldConfig"]["defaults"]["unit"] == "percentunit"
+ timeouts = panels[112]["targets"][0]["expr"]
+ assert "sum by (cluster, namespace, role)" in timeouts
+ assert "increase(sqlalchemy_pool_timeouts_total" in timeouts and "[5m]" in timeouts
+ for panel_id in (111, 112):
+ assert 'role=~"api|worker"' in panels[panel_id]["targets"][0]["expr"]
+ assert 'job=~"testlookup-backend|testlookup-worker"' in panels[panel_id]["targets"][0]["expr"]
+ assert '"noValue"' not in json.dumps(panels[panel_id])
diff --git a/backend/tests/regression/test_fleet_metrics_topology.py b/backend/tests/regression/test_fleet_metrics_topology.py
index 0c878fb6c..e6fdbe19b 100644
--- a/backend/tests/regression/test_fleet_metrics_topology.py
+++ b/backend/tests/regression/test_fleet_metrics_topology.py
@@ -5,7 +5,7 @@
scrapes every API pod and both Compose worker services.
"""
import os
-from pathlib import Path
+from pathlib import Path, PurePosixPath
import subprocess
import sys
@@ -23,6 +23,9 @@
MONITORING_COMPOSE = yaml.safe_load(
(REPO_ROOT / "docker-compose.monitoring.yml").read_text(encoding="utf-8")
)
+MONITORING_AUTH = yaml.safe_load(
+ (REPO_ROOT / "docker-compose.monitoring-auth.yml").read_text(encoding="utf-8")
+)
PROMETHEUS = yaml.safe_load(
(REPO_ROOT / "infra" / "monitoring" / "prometheus.yml").read_text(encoding="utf-8")
)
@@ -38,14 +41,27 @@
WORKER_SERVICES = ("worker", "worker-children")
-def _scrape_targets(job_name: str) -> set[str]:
- jobs = {
- job["job_name"]: job
- for job in PROMETHEUS["scrape_configs"]
- }
+def _scrape_jobs(authenticated: bool) -> dict:
+ directory = PurePosixPath("/etc/prometheus")
+ overlays = (MONITORING_COMPOSE, MONITORING_AUTH) if authenticated else (MONITORING_COMPOSE,)
+ mounts = {}
+ for overlay in overlays:
+ for volume in overlay["services"]["prometheus"]["volumes"]:
+ source, target, *_ = volume.split(":")
+ mounts[PurePosixPath(target)] = REPO_ROOT / source
+ configs = list(PROMETHEUS["scrape_configs"])
+ for include in PROMETHEUS["scrape_config_files"]:
+ included = yaml.safe_load(mounts[directory / include].read_text(encoding="utf-8"))
+ configs.extend(included["scrape_configs"])
+ jobs = {job["job_name"]: job for job in configs}
+ assert len(jobs) == len(configs), "multiple mounted jobs use the same name"
+ return jobs
+
+
+def _scrape_targets(job: dict) -> set[str]:
return {
target
- for config in jobs[job_name]["static_configs"]
+ for config in job["static_configs"]
for target in config["targets"]
}
@@ -104,12 +120,23 @@ def test_compose_worker_has_isolated_writable_multiprocess_storage(
), f"{service_name} has no private writable tmpfs at {MULTIPROC_DIR}"
-def test_prometheus_scrapes_every_compose_executor_on_the_bound_port():
- assert _scrape_targets("testlookup-backend") == {"backend:8000"}
- assert _scrape_targets("testlookup-worker") == {
+@pytest.mark.parametrize("authenticated", (False, True))
+def test_prometheus_scrapes_every_compose_executor_on_the_bound_port(authenticated):
+ jobs = _scrape_jobs(authenticated)
+ backend = jobs["testlookup-backend"]
+ worker = jobs["testlookup-worker"]
+ assert _scrape_targets(backend) == {"backend:8000"}
+ assert _scrape_targets(worker) == {
"worker:9100",
"worker-children:9100",
}
+ assert "authorization" not in worker
+ assert ("authorization" in backend) == authenticated
+ if authenticated:
+ secret = MONITORING_AUTH["services"]["prometheus"]["secrets"][0]
+ assert PurePosixPath(secret["target"]) == (
+ PurePosixPath("/etc/prometheus") / backend["authorization"]["credentials_file"]
+ )
def test_monitoring_overlay_does_not_require_a_precreated_network():
diff --git a/backend/tests/regression/test_grafana_dashboard_metrics_are_declared.py b/backend/tests/regression/test_grafana_dashboard_metrics_are_declared.py
index cbc90340f..9093d6e20 100644
--- a/backend/tests/regression/test_grafana_dashboard_metrics_are_declared.py
+++ b/backend/tests/regression/test_grafana_dashboard_metrics_are_declared.py
@@ -9,7 +9,8 @@
Three ratchets:
-1. every ``testlookup_*`` series a panel expression -- or a dashboard
+1. every owned application series (``testlookup_*``, ``sqlalchemy_pool_*`` and
+ native ``redis_memory_*``) a panel expression -- or a dashboard
annotation's expression (W25b: the "Deploys" annotation) -- names is one a
metric declared in ``app.core.metrics`` actually exports -- with
prometheus_client's suffixes: a Counter is declared WITHOUT ``_total`` and
@@ -44,7 +45,7 @@
#: A series name in PromQL. The trailing lookahead keeps a longer identifier
#: from matching as its prefix; label VALUES like ``job="testlookup-backend"``
#: never match (a hyphen is not part of a name).
-_SERIES_RE = re.compile(r"\b(testlookup_[a-z0-9_]+)\b")
+_SERIES_RE = re.compile(r"\b((?:testlookup_|sqlalchemy_pool_|redis_memory_)[a-z0-9_]+)\b")
#: What prometheus_client exports for each metric type, from the name it
#: stores (a Counter's stored name has ``_total`` stripped already).
diff --git a/backend/tests/regression/test_health_dashboards_need_a_sign_in.py b/backend/tests/regression/test_health_dashboards_need_a_sign_in.py
index 0ddceab8e..4e9e2c7d3 100644
--- a/backend/tests/regression/test_health_dashboards_need_a_sign_in.py
+++ b/backend/tests/regression/test_health_dashboards_need_a_sign_in.py
@@ -185,10 +185,10 @@ def test_no_health_response_is_built_from_exception_text():
SCRAPE_TOKEN = "fake-scrape-token-for-tests"
-def _metrics_app() -> FastAPI:
+def _metrics_app(monkeypatch) -> FastAPI:
app = FastAPI()
- with patch.object(bootstrap, "_install_celery_queue_depth_collector", lambda app: None):
- bootstrap.configure_metrics(app)
+ monkeypatch.setattr("app.services.metric_collection.collect_bounded", AsyncMock(return_value=True))
+ bootstrap.configure_metrics(app)
return app
@@ -199,7 +199,7 @@ def _metrics_app() -> FastAPI:
async def test_metrics_refuses_a_scrape_without_the_token(headers, monkeypatch):
monkeypatch.setattr(settings, "METRICS_ENABLED", True)
monkeypatch.setattr(settings, "METRICS_TOKEN", SCRAPE_TOKEN)
- async with _client(_metrics_app()) as client:
+ async with _client(_metrics_app(monkeypatch)) as client:
response = await client.get("/metrics", headers=headers)
assert response.status_code == 401
assert response.headers["WWW-Authenticate"] == "Bearer"
@@ -209,7 +209,7 @@ async def test_metrics_refuses_a_scrape_without_the_token(headers, monkeypatch):
async def test_metrics_answers_a_scrape_with_the_token(monkeypatch):
monkeypatch.setattr(settings, "METRICS_ENABLED", True)
monkeypatch.setattr(settings, "METRICS_TOKEN", SCRAPE_TOKEN)
- async with _client(_metrics_app()) as client:
+ async with _client(_metrics_app(monkeypatch)) as client:
response = await client.get("/metrics", headers={"Authorization": "Bearer " + SCRAPE_TOKEN})
assert response.status_code == 200
assert "# HELP" in response.text
@@ -218,7 +218,7 @@ async def test_metrics_answers_a_scrape_with_the_token(monkeypatch):
async def test_metrics_stays_open_when_no_token_is_set(monkeypatch):
monkeypatch.setattr(settings, "METRICS_ENABLED", True)
monkeypatch.setattr(settings, "METRICS_TOKEN", "")
- async with _client(_metrics_app()) as client:
+ async with _client(_metrics_app(monkeypatch)) as client:
response = await client.get("/metrics")
assert response.status_code == 200
assert "# HELP" in response.text
@@ -244,6 +244,45 @@ async def test_a_refused_scrape_does_not_refresh_the_queue_depths(monkeypatch):
refreshed.assert_awaited_once()
+async def test_mounted_metrics_token_rotates_on_api_restart(tmp_path, monkeypatch):
+ token_file = tmp_path / "metrics-token"
+ token_file.write_text(SCRAPE_TOKEN + "\n", encoding="ascii")
+ monkeypatch.setattr(settings, "METRICS_ENABLED", True)
+ monkeypatch.setattr(settings, "METRICS_TOKEN_FILE", str(token_file))
+ monkeypatch.setattr(settings, "METRICS_TOKEN", "legacy-token")
+
+ async def scrape(client, token):
+ return await client.get("/metrics", headers={"Authorization": "Bearer " + token})
+
+ async with _client(_metrics_app(monkeypatch)) as client:
+ assert (await client.get("/metrics")).status_code == 401
+ assert (await scrape(client, "legacy-token")).status_code == 401
+ allowed = await scrape(client, SCRAPE_TOKEN)
+ assert allowed.status_code == 200
+ assert "# HELP" in allowed.text
+ token_file.write_text("rotated-test-token", encoding="ascii")
+ assert (await scrape(client, SCRAPE_TOKEN)).status_code == 200
+ assert (await scrape(client, "rotated-test-token")).status_code == 401
+
+ async with _client(_metrics_app(monkeypatch)) as client:
+ assert (await scrape(client, SCRAPE_TOKEN)).status_code == 401
+ assert (await scrape(client, "rotated-test-token")).status_code == 200
+
+
+@pytest.mark.parametrize("contents", [None, b"\r\n", b"first\nsecond", b"x" * 4097])
+def test_invalid_metrics_token_file_cannot_fall_back(tmp_path, monkeypatch, contents):
+ token_file = tmp_path / "metrics-token"
+ if contents is not None:
+ token_file.write_bytes(contents)
+ monkeypatch.setattr(settings, "METRICS_ENABLED", True)
+ monkeypatch.setattr(settings, "METRICS_TOKEN_FILE", str(token_file))
+ monkeypatch.setattr(settings, "METRICS_TOKEN", "legacy-token")
+ with pytest.raises(RuntimeError, match="configured metrics credential file") as failure:
+ bootstrap.configure_metrics(FastAPI())
+ assert str(token_file) not in str(failure.value)
+ assert "legacy-token" not in str(failure.value)
+
+
# ── The API reference ────────────────────────────────────────────────────────
DOCS_ROUTES = {"docs_url": "/api-docs", "redoc_url": "/api-docs/redoc", "openapi_url": "/api-docs/openapi.json"}
diff --git a/backend/tests/regression/test_health_ingestion_reports_unknown.py b/backend/tests/regression/test_health_ingestion_reports_unknown.py
index 936310d8e..5e08df681 100644
--- a/backend/tests/regression/test_health_ingestion_reports_unknown.py
+++ b/backend/tests/regression/test_health_ingestion_reports_unknown.py
@@ -30,9 +30,10 @@
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from tests.celery_queue_fakes import PipelineRedis
-class _DeadRedis:
+class _DeadRedis(PipelineRedis):
"""Every access raises, as a refused connection would."""
def _boom(self, *a, **kw):
@@ -159,7 +160,7 @@ async def test_a_healthy_redis_still_reports_ok():
"""The guard must not turn every healthy deployment into "unknown"."""
from app.routers import health
- class _LiveRedis:
+ class _LiveRedis(PipelineRedis):
async def get(self, *a, **kw):
return b"0"
diff --git a/backend/tests/regression/test_operational_metric_collection.py b/backend/tests/regression/test_operational_metric_collection.py
index 3c6a214bd..83f9b405b 100644
--- a/backend/tests/regression/test_operational_metric_collection.py
+++ b/backend/tests/regression/test_operational_metric_collection.py
@@ -1,11 +1,11 @@
"""Freshness and SQL business outcomes remain observable during dependency failure."""
from datetime import datetime, timedelta, timezone
-from types import SimpleNamespace
from unittest.mock import AsyncMock
import asyncio
import pytest
import pytest_asyncio
+from tests.celery_queue_fakes import PipelineRedis
from sqlalchemy import text
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
@@ -298,8 +298,10 @@ async def length(queue):
seen.append(queue)
if queue == "critical":
raise ConnectionError("fake-down")
- return 7
- monkeypatch.setattr(redis_client, "get_redis", lambda: SimpleNamespace(llen=length))
+ return 0 if "\x06\x16" in queue else 7
+ client = PipelineRedis()
+ client.llen = length
+ monkeypatch.setattr(redis_client, "get_broker_redis", lambda: client)
assert await bootstrap._refresh_celery_queue_depths() is False
assert "agent_children" in seen
assert metrics.celery_queue_length.labels(queue_name="agent_children")._value.get() == 7
diff --git a/backend/tests/regression/test_redis_resource_metrics.py b/backend/tests/regression/test_redis_resource_metrics.py
new file mode 100644
index 000000000..0fabea00a
--- /dev/null
+++ b/backend/tests/regression/test_redis_resource_metrics.py
@@ -0,0 +1,227 @@
+"""Native Redis observations use the configured authority and never invent health."""
+from __future__ import annotations
+
+import asyncio
+from contextlib import asynccontextmanager
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+from fastapi import FastAPI, Request
+from fastapi.responses import PlainTextResponse
+import httpx
+from prometheus_client import generate_latest
+import pytest
+import redis
+import redis.asyncio as aioredis
+from redis.exceptions import ResponseError
+
+from app.core import metrics
+from app.db import redis_client
+from app.services import metric_collection, redis_resource_metrics as resources
+
+pytestmark = pytest.mark.regression
+
+
+def _info(used=70, maximum=100, rss=90, excluded=10):
+ return {
+ "used_memory": used, "maxmemory": maximum,
+ "used_memory_rss": rss, "mem_not_counted_for_evict": excluded,
+ }
+
+
+def _clients(monkeypatch, application, broker=None):
+ monkeypatch.setattr(redis_client, "get_redis", lambda: application)
+ monkeypatch.setattr(redis_client, "get_broker_redis", lambda: application if broker is None else broker)
+
+
+def _value(metric, role):
+ return metric.labels(store_role=role)._value.get()
+
+
+@pytest.mark.asyncio
+async def test_shared_client_reads_once_and_preserves_bounded_role_authority(monkeypatch):
+ client = SimpleNamespace(info=AsyncMock(return_value=_info()))
+ _clients(monkeypatch, client)
+ assert await metric_collection.collect_bounded("redis", resources.refresh_redis_resource_metrics)
+ client.info.assert_awaited_once_with(section="memory")
+ for role in resources.STORE_ROLES:
+ assert _value(metrics.redis_memory_used_bytes, role) == 70
+ assert _value(metrics.redis_memory_max_bytes, role) == 100
+ assert _value(metrics.redis_memory_counted_for_evict_bytes, role) == 60
+ assert _value(metrics.redis_memory_rss_bytes, role) == 90
+ assert _value(metrics.redis_memory_limit_configured, role) == 1
+ samples = [sample for family in metrics.redis_memory_used_bytes.collect() for sample in family.samples]
+ assert {tuple(sample.labels) for sample in samples} == {("store_role",)}
+ assert {sample.labels["store_role"] for sample in samples} == set(resources.STORE_ROLES)
+
+
+@pytest.mark.asyncio
+async def test_unlimited_memory_is_explicit_and_excluded_buffers_do_not_go_negative(monkeypatch):
+ client = SimpleNamespace(info=AsyncMock(return_value=_info(used=20, maximum=0, excluded=30)))
+ _clients(monkeypatch, client)
+ assert await metric_collection.collect_bounded("redis", resources.refresh_redis_resource_metrics)
+ assert _value(metrics.redis_memory_max_bytes, "broker") == 0
+ assert _value(metrics.redis_memory_limit_configured, "broker") == 0
+ assert _value(metrics.redis_memory_counted_for_evict_bytes, "broker") == 0
+
+
+@pytest.mark.parametrize("field,value", [
+ ("used_memory", None), ("used_memory", -1), ("used_memory", True),
+ ("maxmemory", "NaN"), ("maxmemory", float("inf")),
+ ("used_memory_rss", None), ("mem_not_counted_for_evict", None),
+])
+def test_missing_or_invalid_info_is_unknown_not_zero(field, value):
+ info = _info()
+ info[field] = value
+ with pytest.raises(ValueError):
+ resources._memory_observation(info)
+
+
+@pytest.mark.asyncio
+async def test_denied_or_incomplete_role_does_not_advance_freshness_or_publish_partial_snapshot(monkeypatch):
+ application = SimpleNamespace(info=AsyncMock(return_value=_info(used=70)))
+ broker = SimpleNamespace(info=AsyncMock(return_value=_info(used=40)))
+ _clients(monkeypatch, application, broker)
+ assert await metric_collection.collect_bounded("redis", resources.refresh_redis_resource_metrics)
+ last = metrics.metric_collection_last_success.labels(collector="redis")._value.get()
+ application.info.return_value = _info(used=99)
+ for invalid in (ResponseError("synthetic ACL denial"), {"used_memory": 99}):
+ broker.info = AsyncMock(side_effect=invalid) if isinstance(invalid, Exception) else AsyncMock(return_value=invalid)
+ assert not await metric_collection.collect_bounded("redis", resources.refresh_redis_resource_metrics)
+ assert _value(metrics.redis_memory_used_bytes, "application") == 70
+ assert _value(metrics.redis_memory_used_bytes, "broker") == 40
+ assert metrics.metric_collection_success.labels(collector="redis")._value.get() == 0
+ assert metrics.metric_collection_last_success.labels(collector="redis")._value.get() == last
+ broker.info = AsyncMock(return_value=_info(used=30))
+ assert await metric_collection.collect_bounded("redis", resources.refresh_redis_resource_metrics)
+ assert _value(metrics.redis_memory_used_bytes, "application") == 99
+ assert _value(metrics.redis_memory_used_bytes, "broker") == 30
+
+
+@pytest.mark.asyncio
+async def test_stalled_info_is_bounded_without_zeroing_previous_observation(monkeypatch):
+ monkeypatch.setattr(metric_collection, "COLLECTION_TIMEOUT_SECONDS", 0.02)
+ client = SimpleNamespace(info=AsyncMock(return_value=_info()))
+ _clients(monkeypatch, client)
+ assert await metric_collection.collect_bounded("redis", resources.refresh_redis_resource_metrics)
+ last = metrics.metric_collection_last_success.labels(collector="redis")._value.get()
+ async def stalled(**kwargs):
+ await asyncio.Event().wait()
+
+ client.info = stalled
+ start = asyncio.get_running_loop().time()
+ assert not await metric_collection.collect_bounded("redis", resources.refresh_redis_resource_metrics)
+ assert asyncio.get_running_loop().time() - start < 0.3
+ assert _value(metrics.redis_memory_used_bytes, "broker") == 70
+ assert metrics.metric_collection_last_success.labels(collector="redis")._value.get() == last
+ await asyncio.sleep(0)
+
+
+_RESP_HANDSHAKE_COMMANDS = {
+ (b"HELLO", b"3"),
+ (b"CLIENT", b"SETINFO", b"LIB-NAME", b"redis-py"),
+ (b"CLIENT", b"SETINFO", b"LIB-VER", redis.__version__.encode()),
+ # redis-py 8 negotiates read-only maintenance notices for this loopback IP.
+ (b"CLIENT", b"MAINT_NOTIFICATIONS", b"ON", b"moving-endpoint-type", b"internal-ip"),
+}
+
+
+@asynccontextmanager
+async def _resp_memory_server(info):
+ """Synthetic local wire endpoint: real redis-py INFO request and parsing."""
+ commands = []
+ handlers = set()
+
+ async def handle(reader, writer):
+ task = asyncio.current_task()
+ handlers.add(task)
+ try:
+ while True:
+ array = await reader.readline()
+ if not array:
+ return
+ assert array.startswith(b"*")
+ parts = []
+ for _ in range(int(array[1:])):
+ length = await reader.readline()
+ assert length.startswith(b"$")
+ parts.append(await reader.readexactly(int(length[1:])))
+ assert await reader.readexactly(2) == b"\r\n"
+ commands.append(tuple(parts))
+ if tuple(parts) == (b"HELLO", b"3"):
+ # redis-py 8 defaults to RESP3; model the negotiation rather
+ # than treating HELLO as a successful arbitrary command.
+ writer.write(
+ b"%7\r\n+server\r\n+redis\r\n+version\r\n+8.1.0\r\n"
+ b"+proto\r\n:3\r\n+id\r\n:1\r\n+mode\r\n+standalone\r\n"
+ b"+role\r\n+master\r\n+modules\r\n*0\r\n"
+ )
+ elif tuple(parts) == (b"INFO", b"memory"):
+ payload = ("# Memory\r\n" + "".join(f"{key}:{value}\r\n" for key, value in info.items())).encode()
+ writer.write(b"$" + str(len(payload)).encode() + b"\r\n" + payload + b"\r\n")
+ elif tuple(parts) in _RESP_HANDSHAKE_COMMANDS:
+ writer.write(b"+OK\r\n") # redis-py's connection metadata handshake
+ else:
+ writer.write(b"-ERR unsupported fixture command\r\n")
+ await writer.drain()
+ except (asyncio.IncompleteReadError, ConnectionResetError):
+ pass
+ finally:
+ writer.close()
+ await writer.wait_closed()
+ handlers.discard(task)
+
+ server = await asyncio.start_server(handle, "127.0.0.1", 0)
+ port = server.sockets[0].getsockname()[1]
+ client = aioredis.Redis(host="127.0.0.1", port=port, decode_responses=True,
+ socket_timeout=0.5, socket_connect_timeout=0.5)
+ try:
+ yield client, commands
+ finally:
+ await client.aclose()
+ server.close()
+ await server.wait_closed()
+ if handlers:
+ await asyncio.wait_for(asyncio.gather(*handlers, return_exceptions=True), timeout=0.5)
+
+
+@pytest.mark.asyncio
+async def test_real_redis_client_reads_distinct_application_and_broker_wire_endpoints(monkeypatch):
+ async with _resp_memory_server(_info(used=80, maximum=100)) as (application, application_commands):
+ async with _resp_memory_server(_info(used=3, maximum=10)) as (broker, broker_commands):
+ _clients(monkeypatch, application, broker)
+ assert await metric_collection.collect_bounded("redis", resources.refresh_redis_resource_metrics)
+ assert _value(metrics.redis_memory_used_bytes, "application") == 80
+ assert _value(metrics.redis_memory_max_bytes, "application") == 100
+ assert _value(metrics.redis_memory_used_bytes, "broker") == 3
+ assert _value(metrics.redis_memory_max_bytes, "broker") == 10
+ for commands in (application_commands, broker_commands):
+ assert commands.count((b"INFO", b"memory")) == 1
+ assert set(commands) <= _RESP_HANDSHAKE_COMMANDS | {(b"INFO", b"memory")}
+
+
+@pytest.mark.asyncio
+async def test_actual_metrics_route_refreshes_and_exports_redis_observations(monkeypatch):
+ from app import bootstrap
+ from app.services import agent_operational_metrics, downstream_operational_metrics
+
+ _clients(monkeypatch, SimpleNamespace(info=AsyncMock(return_value=_info())))
+ monkeypatch.setattr(bootstrap, "_refresh_celery_queue_depths", AsyncMock(return_value=True))
+ monkeypatch.setattr(agent_operational_metrics, "refresh_agent_operational_metrics", AsyncMock(return_value=True))
+ monkeypatch.setattr(downstream_operational_metrics, "refresh_downstream_operational_metrics", AsyncMock(return_value=True))
+ monkeypatch.setattr(bootstrap.settings, "METRICS_TOKEN", "")
+ if hasattr(bootstrap.settings, "METRICS_TOKEN_FILE"):
+ monkeypatch.setattr(bootstrap.settings, "METRICS_TOKEN_FILE", "")
+ app = FastAPI()
+
+ @app.get("/metrics")
+ async def metrics_route(request: Request):
+ return PlainTextResponse(generate_latest().decode())
+
+ bootstrap._install_celery_queue_depth_collector(app)
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
+ response = await client.get("/metrics")
+ assert response.status_code == 200
+ assert 'redis_memory_used_bytes{store_role="broker"} 70.0' in response.text
+ assert 'redis_memory_max_bytes{store_role="application"} 100.0' in response.text
+ assert 'testlookup_metric_collection_success{collector="redis"} 1.0' in response.text
diff --git a/backend/tests/regression/test_worker_metrics_exposure.py b/backend/tests/regression/test_worker_metrics_exposure.py
index d14b8e903..518615b67 100644
--- a/backend/tests/regression/test_worker_metrics_exposure.py
+++ b/backend/tests/regression/test_worker_metrics_exposure.py
@@ -160,3 +160,136 @@ def test_worker_metric_files_have_a_bounded_container_lifecycle():
assert 'WORKER_METRICS_FINAL_SCRAPE_GRACE_SECONDS", "65"' in src
assert "worker_metrics_file_limit_reached" in src
assert "signal.SIGTERM" in src
+
+
+def test_parent_reaps_only_confirmed_dead_live_gauges(tmp_path, monkeypatch):
+ """SIGKILL skips child shutdown; ambiguity must never erase a live gauge."""
+ import errno
+ import os
+
+ from prometheus_client import multiprocess
+
+ from app.worker import celery_app
+
+ dead_files = {
+ f"gauge_{mode}_100.db"
+ for mode in ("liveall", "livesum", "livemin", "livemax", "livemostrecent")
+ }
+ keep_files = {
+ "gauge_livemax_101.db", # process exists
+ "gauge_livemax_102.db", # permission denied
+ "gauge_livemax_103.db", # unrelated OS failure
+ "gauge_livemax_104.db", # PID is not representable on this platform
+ "counter_100.db",
+ "histogram_100.db",
+ "gauge_sum_100.db",
+ "gauge_mostrecent_100.db",
+ "gauge_livemax_0.db",
+ "gauge_livemax_-1.db",
+ "gauge_livemax_notpid.db",
+ "gauge_livemax_1.0.db",
+ "gauge_livemax_001.db",
+ "gauge_liveunknown_999.db",
+ "README",
+ }
+ for name in dead_files | keep_files:
+ (tmp_path / name).write_bytes(b"metric observation")
+ # A matching directory is not a process's gauge file either.
+ (tmp_path / "gauge_livemax_105.db").mkdir()
+ probes = []
+ reaped = []
+ real_mark_process_dead = multiprocess.mark_process_dead
+
+ def probe(pid, sig):
+ assert sig == 0
+ probes.append(pid)
+ if pid == 100:
+ raise ProcessLookupError(errno.ESRCH, "synthetic dead child")
+ if pid == 102:
+ raise PermissionError(errno.EPERM, "synthetic protected process")
+ if pid == 103:
+ raise OSError(errno.EIO, "synthetic unavailable process probe")
+ if pid == 104:
+ raise OverflowError("synthetic unrepresentable PID")
+ assert pid == 101
+
+ def mark_process_dead(pid, path=None):
+ reaped.append((pid, path))
+ real_mark_process_dead(pid, path=path)
+
+ # Scope os.name to this call so Windows can verify the POSIX branch without
+ # changing pathlib's platform selection during fixture/pytest operations.
+ with monkeypatch.context() as patch:
+ patch.setattr(os, "name", "posix")
+ patch.setattr(os, "kill", probe)
+ patch.setattr(multiprocess, "mark_process_dead", mark_process_dead)
+ celery_app._reap_dead_child_metric_gauges(tmp_path)
+
+ assert sorted(probes) == [100, 101, 102, 103, 104]
+ assert reaped == [(100, str(tmp_path))]
+ assert all(not (tmp_path / name).exists() for name in dead_files)
+ assert all((tmp_path / name).read_bytes() == b"metric observation" for name in keep_files)
+ assert (tmp_path / "gauge_livemax_105.db").is_dir()
+
+
+def test_parent_gauge_reaper_is_disabled_off_posix(tmp_path, monkeypatch):
+ import os
+
+ from app.worker import celery_app
+
+ gauge = tmp_path / "gauge_livemax_100.db"
+ gauge.write_bytes(b"keep")
+
+ def unexpected_probe(*_args):
+ pytest.fail("non-POSIX platforms must not probe or signal processes")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(os, "name", "nt")
+ patch.setattr(os, "kill", unexpected_probe)
+ celery_app._reap_dead_child_metric_gauges(tmp_path)
+ assert gauge.read_bytes() == b"keep"
+
+
+def test_periodic_guard_reaps_before_enforcing_the_file_limit(tmp_path, monkeypatch):
+ """A dead live gauge must not trigger a needless container recycle."""
+ import threading
+
+ from app.worker import celery_app
+
+ stale = tmp_path / "gauge_livemax_100.db"
+ stale.write_bytes(b"dead")
+ (tmp_path / "counter_100.db").write_bytes(b"retained")
+ monkeypatch.setenv("PROMETHEUS_MULTIPROC_DIR", str(tmp_path))
+ monkeypatch.setenv("WORKER_METRICS_MAX_FILES", "1")
+ monkeypatch.setenv("WORKER_METRICS_FILE_CHECK_SECONDS", "7")
+ monkeypatch.setenv("WORKER_METRICS_FINAL_SCRAPE_GRACE_SECONDS", "65")
+ calls = []
+
+ class StopGuard(Exception):
+ pass
+
+ def reap(metric_dir):
+ assert metric_dir == tmp_path
+ calls.append("reap")
+ stale.unlink()
+
+ class Event:
+ def wait(self, timeout):
+ calls.append(timeout)
+ raise StopGuard
+
+ class Thread:
+ def __init__(self, *, target, name, daemon):
+ assert name == "prometheus-multiproc-file-guard" and daemon is True
+ self.target = target
+
+ def start(self):
+ with pytest.raises(StopGuard):
+ self.target()
+
+ monkeypatch.setattr(celery_app, "_reap_dead_child_metric_gauges", reap)
+ monkeypatch.setattr(threading, "Event", Event)
+ monkeypatch.setattr(threading, "Thread", Thread)
+ celery_app._start_metrics_file_guard()
+ assert calls == ["reap", 7.0]
+ assert (tmp_path / "counter_100.db").read_bytes() == b"retained"
diff --git a/docker-compose.monitoring-auth.yml b/docker-compose.monitoring-auth.yml
new file mode 100644
index 000000000..fec7fbf6f
--- /dev/null
+++ b/docker-compose.monitoring-auth.yml
@@ -0,0 +1,20 @@
+# Layer after docker-compose.monitoring.yml to authenticate the backend scrape.
+services:
+ backend:
+ environment:
+ METRICS_TOKEN_FILE: /run/secrets/testlookup-metrics-token
+ secrets:
+ - source: metrics-api
+ target: testlookup-metrics-token
+ prometheus:
+ volumes:
+ - ./infra/monitoring/backend-scrape-authenticated.yml:/etc/prometheus/backend-scrape.yml:ro
+ secrets:
+ - source: metrics-prometheus
+ target: /etc/prometheus/metrics-token
+
+secrets:
+ metrics-api:
+ file: ${METRICS_API_TOKEN_SOURCE:?Set the host path to the backend metrics token file}
+ metrics-prometheus:
+ file: ${METRICS_PROMETHEUS_TOKEN_SOURCE:?Set the host path to the Prometheus metrics token file}
diff --git a/docker-compose.monitoring.yml b/docker-compose.monitoring.yml
index 39bb3eccf..cf879cea4 100644
--- a/docker-compose.monitoring.yml
+++ b/docker-compose.monitoring.yml
@@ -50,6 +50,7 @@ services:
# /-/reload without authentication. Restart the container to reload.
volumes:
- ./infra/monitoring/prometheus.yml:/etc/prometheus/prometheus.yml:ro
+ - ./infra/monitoring/backend-scrape.yml:/etc/prometheus/backend-scrape.yml:ro
- ./infra/monitoring/prometheus-rules:/etc/prometheus/rules:ro
- prometheus-data:/prometheus
ports:
diff --git a/docs/maintainers/observability-delivery.md b/docs/maintainers/observability-delivery.md
index c78f49fe3..a3bf57762 100644
--- a/docs/maintainers/observability-delivery.md
+++ b/docs/maintainers/observability-delivery.md
@@ -36,9 +36,9 @@ Status meanings: **Open** is planned; **In progress** has partial implementation
| OBS-E01-S07 | Preserve correlation and sanitized logs for every unexpected API error | Verification |
| OBS-E02-S01 | Bound dependency collection and expose freshness | Verification |
| OBS-E02-S02 | Monitor every routed queue including agent children | In progress |
-| OBS-E02-S03 | Emit real SQLAlchemy pool saturation measurements | Open |
-| OBS-E02-S04 | Wire dependency and host exporters by deployment profile | Open |
-| OBS-E02-S05 | Make authenticated scrapes work in reference profiles | Open |
+| OBS-E02-S03 | Emit real SQLAlchemy pool saturation measurements | Verification |
+| OBS-E02-S04 | Wire dependency and host exporters by deployment profile | In progress |
+| OBS-E02-S05 | Make authenticated scrapes work in reference profiles | Verification |
| OBS-E02-S06 | Detect durable downstream failure independently of Celery success | In progress |
| OBS-E03-S01 | Make weekly digest alerts reflect actual due work and delivery | Open |
| OBS-E03-S02 | Detect low-volume terminal webhook failures correctly | Verification |
@@ -125,3 +125,18 @@ Fixtures live in `infra/monitoring/tests/`, outside the production `rules/*.yml`
5. Complete all-role signal/security/rollback gates before declaring production readiness.
No production deployment or claim of enterprise readiness is represented by this iteration. Data retention, receivers, SLO targets and platform ownership must be explicit for each supported production profile.
+
+## Iteration 2: reliable metric collection
+
+This iteration builds on `30edfba5` and advances four stories in OBS-E02.
+
+| Story | Change | Remaining acceptance |
+|---|---|---|
+| OBS-E02-S02 | The API scrape and ingest health use the Celery routing inventory and the configured broker connection. Counts sum all Redis transport priority lists for each logical queue. A failed list produces an unknown depth. | Measure queue age and processing throughput. Verify the backlog and recovery with a stopped child consumer in a disposable fleet. |
+| OBS-E02-S03 | API and worker engines emit checked-out connections, pool capacity including overflow, in-flight acquisitions and acquisition outcomes. The alert and dashboard surface the most saturated live process. The Celery parent cleans up live gauges left by hard child exits. See [database pool metrics](../operations/db-pool-metrics.md). | Verify exact fleet counts and pressure against PostgreSQL in a deployment using the candidate image. |
+| OBS-E02-S04 | The bounded API collector reads application and broker memory through their actual Redis/Valkey clients. Alerts and dashboards use fresh observations, distinct roles and a separate unlimited-memory signal. | Verify host and datastore exporters for each production profile and provider. See [dependency metrics](../operations/dependency-metrics.md). |
+| OBS-E02-S05 | An optional Compose overlay mounts separate backend and Prometheus credential files. The Kubernetes component and PodMonitor use a namespace-local Secret. Rejected requests bypass dependency collection. | Exercise rotation and recovery in a deployed reference profile with the production selector, secret manager and network policy. See [Compose](../operations/deploy-compose.md#authenticate-the-api-scrape) and [Kubernetes](../operations/deploy-kubernetes.md#authenticate-the-api-scrape). |
+
+Prometheus 3.16 scraped actual samples from an isolated candidate API, received 401 on a token mismatch and resumed scraping after rotation. The source and release Compose configurations and the K3s and OpenShift manifests rendered with the expected targets and mounts. The existing backend CI job checks the two mounted Prometheus configurations and runs all semantic rule fixtures using its checksum-verified binary.
+
+The focused suite passed 354 tests with the repository-pinned metrics dependencies. Two PostgreSQL cases require a disposable database and run in the existing integration job. Promtool validated 39 rules and 19 semantic fixture groups. In a separate Linux process test, removing the gauge from a killed child preserved the live child's gauge and both counters.
diff --git a/docs/operations/configuration.md b/docs/operations/configuration.md
index 88531d169..a4ea274ba 100644
--- a/docs/operations/configuration.md
+++ b/docs/operations/configuration.md
@@ -75,6 +75,7 @@ Two more production-only behaviours:
| `RATE_LIMIT_SHARED_STORAGE` | `auto` / `on` / `off` | `auto` | Where rate-limit counters live. `auto`: Redis (`REDIS_URL`) when `APP_ENV` is production or staging, so a limit holds across workers and pods; process memory in development. While Redis is unreachable the counters fall back to per-process memory. `off` keeps per-process counters everywhere. |
| `LOGIN_ATTEMPTS_PER_USERNAME_PER_MINUTE` | int | `20` | Sign-in attempts accepted per typed account name per minute on `/api/v1/auth/login`, from any address; over it the answer is 429 with `Retry-After`. `0` turns it off. Development uses at least 200. |
| `METRICS_TOKEN` | str | empty | When set, `/metrics` answers only a request with `Authorization: Bearer ` (401 otherwise). Empty leaves `/metrics` open, as before; keep it off the public network either way. |
+| `METRICS_TOKEN_FILE` | str | empty | Path to a mounted file containing one bearer token. Takes precedence over `METRICS_TOKEN`. An absent, unreadable or invalid configured file stops API startup when metrics are enabled. API processes read the file at startup. |
| `API_DOCS_ENABLED` | bool | `true` | `false` turns off `/api-docs`, `/api-docs/redoc` and `/api-docs/openapi.json` (404). |
| `HTTP_VERIFY_TLS` | bool | `true` | Certificate verification for outbound HTTPS from the shared HTTP client (Jira, Slack, Teams, GitHub, GitLab, webhooks, hosted LLM endpoints, knowledge connectors). `false` disables verification and logs a warning; only for isolated labs. Prefer `HTTP_CA_BUNDLE`. |
| `HTTP_CA_BUNDLE` | str (optional) | unset | Path to a PEM bundle of extra trusted roots (corporate CA, TLS-intercepting proxy). Verification stays strict. Takes precedence over `HTTP_VERIFY_TLS`. See [Corporate CA and TLS interception](integrations.md#corporate-ca-and-tls-interception). |
diff --git a/docs/operations/db-pool-metrics.md b/docs/operations/db-pool-metrics.md
new file mode 100644
index 000000000..1b9a22982
--- /dev/null
+++ b/docs/operations/db-pool-metrics.md
@@ -0,0 +1,41 @@
+# PostgreSQL application pool metrics
+
+API processes and Celery prefork children each own an independent SQLAlchemy async connection pool. `app.db.postgres.get_engine()` uses the instrumented `AsyncAdaptedQueuePool` while retaining the existing cached engine, worker event loop, connection settings and connection budget. No extra exporter or database query is required for these measurements.
+
+Series have one bounded application label, `role` (`api`, `worker` or `operation`). Scrape labels still identify the deployment and target. Connection strings, credentials, SQL, tenant IDs and process IDs are never application metric labels.
+
+| Metric | Meaning and aggregation inside one target |
+|---|---|
+| `sqlalchemy_pool_checked_out` | Sum of SQLAlchemy's current checked-out counts. |
+| `sqlalchemy_pool_size` | Sum of configured persistent pool sizes. |
+| `sqlalchemy_pool_max_overflow` | Sum of configured finite overflow allowances. |
+| `sqlalchemy_pool_capacity` | Sum of configured finite `pool_size + max_overflow`. |
+| `sqlalchemy_pool_capacity_limited` | Number of initialized pools with a finite capacity. |
+| `sqlalchemy_pool_overflow` | Sum of currently open connections above persistent size; cold-pool negative overflow is clamped to zero. |
+| `sqlalchemy_pool_utilization_ratio` | Maximum live process's checked-out/capacity ratio. |
+| `sqlalchemy_pool_acquiring` | Sum of acquisition attempts in progress, including queue wait, connection creation and pre-ping. |
+| `sqlalchemy_pool_acquire_seconds{outcome}` | Histogram of one public acquisition attempt, including queue wait, creation and pre-ping. Outcomes are `success`, `timeout` and `error`; cancellation is an error. |
+| `sqlalchemy_pool_timeouts_total` | SQLAlchemy queue-capacity timeouts (code `3o7r`), counted once per public attempt. |
+
+The engine is lazy: only processes that have initialized a pool contribute capacity. A pool's configuration remains visible while it is idle; these gauges are not a count of currently established server connections. Overflow connections count toward finite capacity even though they are discarded when the persistent queue is full on return. [SQLAlchemy documents these async queue and overflow semantics](https://docs.sqlalchemy.org/en/20/core/pooling.html).
+
+Use the maximum process ratio for pressure alerts. Dividing summed checked-out connections by summed capacity answers a different question and can hide a fully occupied child behind idle siblings. `TestLookupDBPoolExhausted` fires when a target's maximum ratio exceeds 90% for two minutes, including worker targets. Acquisition latency is not query latency or pure queue-wait latency. The timeout counter preserves shorter exhaustion events that may not satisfy the alert's two-minute duration.
+
+The Celery parent checks for dead PIDs in its private metrics directory on the existing file-guard interval. It removes confirmed dead-child live gauges and retains counters and histograms. This covers a hard death that skips the child shutdown signal.
+
+The overview dashboard's PostgreSQL application pools row plots the busiest live process per API/worker target and five-minute timeout increases grouped by installation and role. Its pressure panel excludes unbounded pools instead of displaying them as zero percent utilization. Prometheus `increase` estimates the change from scraped samples; it is not an exact event ledger.
+
+The application validates positive persistent size and nonnegative overflow. Defensive support for an unbounded raw SQLAlchemy pool reports capacity, limited-capacity count and utilization as zero; zero capacity is unknown/unbounded, never a denominator for percentage pressure. An absent series also does not prove health: check required target discovery and the initialized workload. Fleet connection-budget validation remains necessary before increasing limits.
+
+Live gauges use the existing per-container multiprocess directory and dead-child cleanup. Counters and histograms retain completed observations across child recycling. Engine disposal creates a replacement pool with the same instrumentation; a late checkin from the detached pool cannot overwrite the replacement's pressure. This contract covers the application's single cached engine per process and role, rather than arbitrary additional independently constructed engines with the same role.
+
+Run the deterministic real async-queue and multiprocess tests without services:
+
+```sh
+cd backend
+PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -p pytest_asyncio.plugin tests/regression/test_db_pool_metrics.py
+cd ../infra/monitoring/tests
+promtool test rules pool-alerts.yml
+```
+
+For release acceptance against an isolated PostgreSQL integration database, set `TESTLOOKUP_POSTGRES_TEST_DSN` and run `tests/integration/test_db_pool_metrics_postgres.py`. It holds two disposable read-only connections, verifies actual checkout/capacity/overflow, induces one bounded third-acquisition timeout, and verifies recovery. A monitored disposable profile must additionally prove API and worker scrape discovery and alert firing/resolution. Local async SQLite, multiprocess and synthetic PromQL tests do not substitute for that deployment evidence.
diff --git a/docs/operations/dependency-metrics.md b/docs/operations/dependency-metrics.md
new file mode 100644
index 000000000..2a5185893
--- /dev/null
+++ b/docs/operations/dependency-metrics.md
@@ -0,0 +1,46 @@
+# Dependency resource metrics
+
+The application exposes Redis/Valkey memory through the existing private API `/metrics` endpoint. The `redis` operational collector reads `INFO memory` from the actual application client (`REDIS_URL`) and broker client (`CELERY_BROKER_URL`). This needs no additional exporter image in Compose, Kubernetes, K3s, OpenShift or disconnected installations. The profile's Prometheus/PodMonitor and scrape authentication must still be configured.
+
+## Redis and Valkey signal contract
+
+Each series carries a bounded `store_role`: `application` or `broker`. A role identifies which configured connection was observed. It does not identify a distinct physical server: URLs differing only in logical database can share server memory. Queries use `max` across redundant API observations and preserve role/installation scope. Do not sum roles or replicas. URLs, credentials, database numbers, key names and project IDs are never metric labels.
+
+| Metric | Unit and meaning |
+|---|---|
+| `redis_memory_used_bytes` | Allocator memory reported by `used_memory`. |
+| `redis_memory_max_bytes` | Reported `maxmemory`; zero explicitly means no dataset eviction limit. |
+| `testlookup_redis_memory_not_counted_for_evict_bytes` | Reported replication/AOF buffers excluded from the eviction calculation. |
+| `testlookup_redis_memory_counted_for_evict_bytes` | `max(used_memory - mem_not_counted_for_evict, 0)`. |
+| `testlookup_redis_memory_rss_bytes` | Process RSS; this is not a container memory limit. |
+| `testlookup_redis_memory_limit_configured` | 1 for positive `maxmemory`, otherwise 0. |
+
+The reader validates every required field before updating either role. ACL denial, malformed/missing fields, connection failures and deadline expiry fail `testlookup_metric_collection_success{collector="redis"}` without advancing its last-success timestamp. The previous resource samples remain diagnostic history; supplied alerts and dashboard panels exclude samples without same-target success and freshness within 120 seconds. An unreadable limit is not interpreted as an unlimited limit or healthy zero.
+
+`TestLookupRedisMemoryHigh` watches fresh eviction-counted utilization above 85% for five minutes. `TestLookupRedisMemoryLimitMissing` watches an explicitly unlimited limit for ten minutes. A legitimate managed-service capacity policy can require an explicitly scoped exception plus its provider's equivalent capacity alert. A missing observation still needs investigation; do not silence collection failure merely because no resource samples were emitted.
+
+The backend performs only `INFO memory` for these signals. It does not call `CONFIG`, inspect application keys or mutate server state. Existing app credentials/TLS and the single-attempt Redis client policy apply; broker and application clients are shared when their configured URLs match and are closed by the existing Redis shutdown lifecycle. If the app ACL currently denies `INFO`, permit that command deliberately or use an approved external monitoring integration. A dedicated external exporter account should have only the read/connection commands its selected exporter requires; it does not need application key or configuration-write access just to read memory. Protect exporter credentials through the platform secret mechanism and keep operational endpoints private.
+
+Redis documents both the [INFO memory fields](https://redis.io/docs/latest/commands/info/) and [maxmemory/eviction semantics](https://redis.io/docs/latest/develop/reference/eviction/). `maxmemory=0` is unlimited; replication/AOF buffers need separate headroom. Do not replace this value with `total_system_memory`: host RAM is not a reliable container capacity. Use platform container/host memory telemetry for RSS-versus-container-limit alerts. Apply least privilege through the [Redis ACL model](https://redis.io/docs/latest/operate/oss_and_stack/management/security/acl/).
+
+## Profile and external-exporter responsibilities
+
+| Profile | Required built-in path | Additional infrastructure responsibility |
+|---|---|---|
+| Source/release Compose | API `/metrics`, actual configured Redis roles, `redis` collector freshness, supplied memory alerts. | Host/container CPU, disk, OOM, restarts and datastore storage need an independently configured platform exporter. Commented example targets in `infra/monitoring/prometheus.yml` do not install one. |
+| Kubernetes/K3s/OpenShift | Selected API PodMonitor, allowed namespace/network path, correct scrape credentials and loaded generated rules. | Reuse node-exporter/kube-state-metrics or approved platform equivalents. Their presence and actual samples must be verified. |
+| Managed/BYO Redis | Built-in `INFO memory` when supported and authorized. | For clustered/managed services, verify all required primaries/shards and provider-specific memory limits. A single app connection is not evidence of whole-cluster capacity. |
+| Disconnected | Same native reader and locally available metrics/routing; no monitoring downloads introduced by this producer. | Any optional external exporter must be pinned, scanned, mirrored and included in the installation inventory. |
+
+An external Redis exporter may coexist in a separate scrape job for node, replication and provider-specific coverage. Its similarly named `redis_memory_*` metrics do not automatically satisfy TestLookup's native `store_role`, freshness and job contract. The supplied memory rules explicitly select `job="testlookup-backend"`; provide a separately tested adapter/rule for the external job. Do not relabel an arbitrary server as the application's broker or merge native and external samples into one total. PostgreSQL exporters likewise do not substitute for Python connection-pool observations.
+
+Acceptance requires actual target discovery, nonempty required series, a controlled threshold crossing/recovery on disposable storage, and denied/unavailable `INFO` yielding failed freshness rather than healthy memory. Run:
+
+```sh
+cd backend
+PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -p pytest_asyncio.plugin tests/regression/test_redis_resource_metrics.py tests/regression/test_grafana_dashboard_metrics_are_declared.py
+cd ../infra/monitoring/tests
+promtool test rules redis-resources.yml
+```
+
+The Python suite includes a local synthetic RESP server to exercise real redis-py parsing and distinct/shared connection authorities. It changes no production Redis configuration. The profile-specific real-server capacity and host-exporter drill remains a separate release acceptance obligation.
diff --git a/docs/operations/deploy-compose.md b/docs/operations/deploy-compose.md
index c9cfea634..a17014f81 100644
--- a/docs/operations/deploy-compose.md
+++ b/docs/operations/deploy-compose.md
@@ -187,6 +187,19 @@ All of these listen on `127.0.0.1` only (`MONITORING_PUBLISH_ADDR`): Jaeger, the
The override sets `OTEL_ENABLED=true`, `OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318` and `METRICS_ENABLED=true` on the backend. The same alert rules are rendered for Kubernetes in [`k8s/monitoring`](deploy-kubernetes.md#monitoring-podmonitor-and-prometheusrule). Metric and alert reference: [observability](../../architecture/OBSERVABILITY.md).
+### Authenticate the API scrape
+
+Use `docker-compose.monitoring-auth.yml` after the monitoring file with either the source or release stack. Set `METRICS_API_TOKEN_SOURCE` and `METRICS_PROMETHEUS_TOKEN_SOURCE` to the absolute host paths of two protected files containing the same bearer token. Grant file read access to the corresponding container users and restrict access to the files on the host. Compose mounts each file only in the service that needs it. File-based Compose secrets use host file ownership and permissions. [Compose secrets](https://docs.docker.com/compose/how-tos/use-secrets/).
+
+```bash
+docker compose -f docker-compose.yml -f docker-compose.monitoring.yml \
+ -f docker-compose.monitoring-auth.yml up -d
+```
+
+Check that the `testlookup-backend` job is up and returns samples in Prometheus. From the private network, an API scrape with missing or mismatched credentials should return 401. Worker scrapes use the private Compose network on port 9100. Keep that port off published host and ingress routes. The bearer token crosses the private service network, so use a TLS scrape endpoint when crossing a trust boundary. [Prometheus scrape authorization](https://prometheus.io/docs/prometheus/latest/configuration/configuration/#http_config).
+
+Rotate by updating the two source files and recreating `backend` and `prometheus` with the same Compose file set. Recreation remounts files even if the secret manager atomically replaced them. Expect transient 401s while the two sides switch. Confirm the backend target is up with the new token and the old token returns 401 before ending the maintenance window.
+
## Backups, restore and upgrades
All commands run through `docker compose exec/run`, so the host needs only Docker and Bash.
diff --git a/docs/operations/deploy-kubernetes.md b/docs/operations/deploy-kubernetes.md
index ab2e8cf9a..b1289e507 100644
--- a/docs/operations/deploy-kubernetes.md
+++ b/docs/operations/deploy-kubernetes.md
@@ -180,7 +180,15 @@ kubectl apply -k k8s/monitoring
| `podmonitors.yaml` | `PodMonitor` `testlookup-backend` (port `http`, `/metrics` on 8000) and `testlookup-worker` (port `metrics`, 9100), each setting the `job` label the rules select on |
| `prometheusrule.yaml` | `PrometheusRule` `testlookup-alerts`, generated from `infra/monitoring/prometheus-rules/testlookup-alerts.yml` by `scripts/render_prometheusrule.py`: application alerts (backend or worker down, error rate, slow requests, AI pipeline failures, LLM circuit breaker, DLQ, stale reviews, live-event archive failures), infrastructure alerts (DB pool, broker memory, queue backlog, task latency, disk, OOM kills), latency SLOs for key API routes, and the two backup alerts |
-The backup alerts read kube-state-metrics, and the disk and OOM alerts read node-exporter; without those exporters the rules stay silent. If your Prometheus selects rules and monitors by label (kube-prometheus-stack uses `release: `), add that label in `k8s/monitoring/kustomization.yaml` as its comment shows.
+The backup alerts read kube-state-metrics, and the disk and OOM alerts read node-exporter. If your Prometheus selects rules and monitors by label (kube-prometheus-stack uses `release: `), add that label in your site monitoring overlay. Confirm that the Prometheus resource selects rules and PodMonitors in the application namespace.
+
+### Authenticate the API scrape
+
+Provision a Secret named `testlookup-metrics-auth` with key `token` in the application namespace through your secret manager. Include the `k8s/components/metrics-auth` component in your application overlay. It mounts the token read-only in the backend container. Select `k8s/monitoring-authenticated` as the monitoring resource in your site overlay. It uses `PodMonitor` bearer authorization with the same Secret key. The Operator needs permission to read that Secret in the PodMonitor namespace. [Prometheus Operator API](https://prometheus-operator.dev/docs/api-reference/api/).
+
+In the selected Prometheus, confirm discovery for each API and worker pod and verify `up{job="testlookup-backend"} == 1`. A direct API scrape from the private network should return 401 with missing or mismatched credentials and return samples with the mounted token. Worker port 9100 relies on the monitoring namespace NetworkPolicy. On platforms with an external scraper, supply a site-specific policy and TLS before crossing a trust boundary.
+
+Rotate the Secret, wait for the Operator to reconcile its scrape configuration, and roll the backend deployment so each API process loads the new token. A rolling transition can produce temporary 401s from pods using different token generations. Verify every API target returns samples after the rollout and the old credential receives 401. Keep token values out of rendered manifests, commands and verification records.
## Backups
diff --git a/docs/operations/deployment.md b/docs/operations/deployment.md
index cbbc8d454..ab68c7701 100644
--- a/docs/operations/deployment.md
+++ b/docs/operations/deployment.md
@@ -132,7 +132,7 @@ Local-model RAM, VRAM and disk depend on the model, quantization, context and co
| Project activity and decision trail | User-visible receipts and agent reasoning/provenance events |
| Upload, outbox, DLQ and pipeline records | Locate the failed asynchronous step, not just HTTP health |
-Prometheus alert rules live in `infra/monitoring/prometheus-rules/`; Compose loads them through the [monitoring add-on](deploy-compose.md#monitoring-add-on) and Kubernetes through [`k8s/monitoring`](deploy-kubernetes.md#monitoring-podmonitor-and-prometheusrule). Alert on stalled pipelines, lease or retry exhaustion, outbox/DLQ backlog, queue imbalance, database connections and broker memory. Installing an OpenTelemetry library does not by itself trace Celery tasks. [Observability deep dive](../../architecture/OBSERVABILITY.md), [troubleshooting](../../user-guide/troubleshooting.md).
+Prometheus alert rules live in `infra/monitoring/prometheus-rules/`; Compose loads them through the [monitoring add-on](deploy-compose.md#monitoring-add-on) and Kubernetes through [`k8s/monitoring`](deploy-kubernetes.md#monitoring-podmonitor-and-prometheusrule). Alert on stalled pipelines, lease or retry exhaustion, outbox/DLQ backlog, queue imbalance, database connections and broker memory. Installing an OpenTelemetry library does not by itself trace Celery tasks. [Dependency metrics](dependency-metrics.md), [observability deep dive](../../architecture/OBSERVABILITY.md), [troubleshooting](../../user-guide/troubleshooting.md).
## Related
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index e5c8128fd..4e29589fe 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -288,6 +288,7 @@ Source declarations only; no `.env` or running secrets are read. Compose/Helm/Ku
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `Optional[str]` | `None` |
| `METRICS_ENABLED` | `bool` | `True` |
| `METRICS_TOKEN` | `str` | `''` |
+| `METRICS_TOKEN_FILE` | `str` | `''` |
| `API_DOCS_ENABLED` | `bool` | `True` |
| `LOG_LEVEL` | `str` | `'INFO'` |
| `LOG_FORMAT` | `Literal['json', 'text']` | `'json'` |
diff --git a/docs/reference/worker-operations.md b/docs/reference/worker-operations.md
index 452eb5a9e..5dc16f9e8 100644
--- a/docs/reference/worker-operations.md
+++ b/docs/reference/worker-operations.md
@@ -9,7 +9,7 @@ Static declarations, not observations of running consumers. Deployment profiles
## task_routes
```python
-{'app.worker.tasks.run_live_test_analysis': {'queue': 'critical'}, 'app.worker.tasks.ingest_test_run': {'queue': 'ingestion'}, 'app.worker.tasks.run_ai_analysis': {'queue': 'ai_analysis'}, 'app.worker.tasks.run_agent_pipeline': {'queue': 'ai_analysis'}, 'app.worker.tasks.run_agent_child_investigation': {'queue': 'agent_children'}, 'app.worker.tasks.generate_run_compare_report': {'queue': 'ai_analysis'}, 'app.worker.tasks.precompute_suite_comparisons_for_run': {'queue': 'ai_analysis'}, 'app.worker.tasks.generate_ai_test_cases_task': {'queue': 'ai_analysis'}, 'app.worker.tasks.create_ai_test_plan_task': {'queue': 'ai_analysis'}, 'app.worker.tasks.generate_ai_strategy_task': {'queue': 'ai_analysis'}, 'app.worker.tasks.run_fixer_run_task': {'queue': 'ai_analysis'}, 'app.worker.training_tasks.export_training_data': {'queue': 'default'}, 'app.worker.training_tasks.check_finetune_trigger': {'queue': 'default'}, 'app.worker.training_tasks.run_finetune_pipeline': {'queue': 'default'}, 'app.worker.tasks.reindex_search': {'queue': 'default'}, 'app.worker.tasks.rebuild_embedding_generation': {'queue': 'ai_analysis'}, 'app.worker.tasks.run_retention_purges': {'queue': 'default'}, 'app.worker.tasks.rebuild_run_snapshot': {'queue': 'default'}, 'app.worker.tasks.watch_drop_folders': {'queue': 'default'}, 'app.worker.tasks.*': {'queue': 'default'}}
+{'app.worker.tasks.run_live_test_analysis': {'queue': CRITICAL_QUEUE}, 'app.worker.tasks.ingest_test_run': {'queue': INGESTION_QUEUE}, 'app.worker.tasks.run_ai_analysis': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.tasks.run_agent_pipeline': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.tasks.run_agent_child_investigation': {'queue': AGENT_CHILDREN_QUEUE}, 'app.worker.tasks.generate_run_compare_report': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.tasks.precompute_suite_comparisons_for_run': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.tasks.generate_ai_test_cases_task': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.tasks.create_ai_test_plan_task': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.tasks.generate_ai_strategy_task': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.tasks.run_fixer_run_task': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.training_tasks.export_training_data': {'queue': DEFAULT_QUEUE}, 'app.worker.training_tasks.check_finetune_trigger': {'queue': DEFAULT_QUEUE}, 'app.worker.training_tasks.run_finetune_pipeline': {'queue': DEFAULT_QUEUE}, 'app.worker.tasks.reindex_search': {'queue': DEFAULT_QUEUE}, 'app.worker.tasks.rebuild_embedding_generation': {'queue': AI_ANALYSIS_QUEUE}, 'app.worker.tasks.run_retention_purges': {'queue': DEFAULT_QUEUE}, 'app.worker.tasks.rebuild_run_snapshot': {'queue': DEFAULT_QUEUE}, 'app.worker.tasks.watch_drop_folders': {'queue': DEFAULT_QUEUE}, 'app.worker.tasks.*': {'queue': DEFAULT_QUEUE}}
```
## broker_transport_options
@@ -50,7 +50,7 @@ True
## queue_delivery_probe
-[backend/app/worker/celery_app.py:54](../../backend/app/worker/celery_app.py#L54)
+[backend/app/worker/celery_app.py:58](../../backend/app/worker/celery_app.py#L58)
Return transport attribution for the release queue-consumption proof.
diff --git a/infra/monitoring/backend-scrape-authenticated.yml b/infra/monitoring/backend-scrape-authenticated.yml
new file mode 100644
index 000000000..ed4120576
--- /dev/null
+++ b/infra/monitoring/backend-scrape-authenticated.yml
@@ -0,0 +1,10 @@
+scrape_configs:
+ - job_name: testlookup-backend
+ static_configs:
+ - targets: ['backend:8000']
+ metrics_path: /metrics
+ scrape_interval: 15s
+ follow_redirects: false
+ authorization:
+ type: Bearer
+ credentials_file: metrics-token
diff --git a/infra/monitoring/backend-scrape.yml b/infra/monitoring/backend-scrape.yml
new file mode 100644
index 000000000..a6c2d5434
--- /dev/null
+++ b/infra/monitoring/backend-scrape.yml
@@ -0,0 +1,6 @@
+scrape_configs:
+ - job_name: testlookup-backend
+ static_configs:
+ - targets: ['backend:8000']
+ metrics_path: /metrics
+ scrape_interval: 15s
diff --git a/infra/monitoring/grafana/dashboards/testlookup-overview.json b/infra/monitoring/grafana/dashboards/testlookup-overview.json
index d41af2884..f70baa596 100644
--- a/infra/monitoring/grafana/dashboards/testlookup-overview.json
+++ b/infra/monitoring/grafana/dashboards/testlookup-overview.json
@@ -990,6 +990,111 @@
],
"title": "Live WebSocket sessions by outcome (5m)",
"type": "timeseries"
+ },
+ {
+ "collapsed": false,
+ "gridPos": { "h": 1, "w": 24, "x": 0, "y": 119 },
+ "id": 100,
+ "title": "Redis / Valkey resources",
+ "type": "row"
+ },
+ {
+ "datasource": "Prometheus",
+ "description": "Native INFO memory: used_memory minus mem_not_counted_for_evict, divided by positive maxmemory. Only fresh successful observations appear. Application and broker roles can name the same physical server; never sum them or API replicas. An unlimited or unreadable limit appears as no data, not zero utilization.",
+ "fieldConfig": {
+ "defaults": { "unit": "percentunit", "min": 0, "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }, { "color": "red", "value": 0.85 }] } },
+ "overrides": []
+ },
+ "gridPos": { "h": 8, "w": 8, "x": 0, "y": 120 },
+ "id": 101,
+ "options": { "legend": { "displayMode": "list" }, "tooltip": { "mode": "multi" } },
+ "targets": [
+ {
+ "expr": "max by (cluster, namespace, store_role) ((testlookup_redis_memory_counted_for_evict_bytes{job=\"testlookup-backend\"} / redis_memory_max_bytes{job=\"testlookup-backend\"}) and on (cluster, namespace, job, instance, store_role) (redis_memory_max_bytes{job=\"testlookup-backend\"} > 0) and on (cluster, namespace, job, instance) (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"redis\"} == 1) and on (cluster, namespace, job, instance) ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"redis\"}) <= 120))",
+ "legendFormat": "{{cluster}} {{namespace}} {{store_role}}",
+ "refId": "A"
+ }
+ ],
+ "title": "Redis eviction memory utilization",
+ "type": "timeseries"
+ },
+ {
+ "datasource": "Prometheus",
+ "description": "Process RSS is separate from the dataset eviction ceiling. Host total RAM is not used as a container limit. Values come from the actual configured Redis role, filtered by collection freshness.",
+ "fieldConfig": { "defaults": { "unit": "bytes", "min": 0 }, "overrides": [] },
+ "gridPos": { "h": 8, "w": 8, "x": 8, "y": 120 },
+ "id": 102,
+ "options": { "legend": { "displayMode": "list" }, "tooltip": { "mode": "multi" } },
+ "targets": [
+ {
+ "expr": "max by (cluster, namespace, store_role) (testlookup_redis_memory_rss_bytes{job=\"testlookup-backend\"} and on (cluster, namespace, job, instance) (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"redis\"} == 1) and on (cluster, namespace, job, instance) ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"redis\"}) <= 120))",
+ "legendFormat": "{{cluster}} {{namespace}} {{store_role}} RSS",
+ "refId": "A"
+ }
+ ],
+ "title": "Redis process resident memory",
+ "type": "timeseries"
+ },
+ {
+ "datasource": "Prometheus",
+ "description": "1 means a positive maxmemory; 0 means the server explicitly reports no dataset limit. Missing or unreadable INFO fields suppress this panel and fail collector health instead of inventing a zero. Managed services may require their native exporter/explicit policy.",
+ "fieldConfig": { "defaults": { "unit": "bool", "min": 0, "max": 1 }, "overrides": [] },
+ "gridPos": { "h": 8, "w": 8, "x": 16, "y": 120 },
+ "id": 103,
+ "options": { "legend": { "displayMode": "list" }, "tooltip": { "mode": "multi" } },
+ "targets": [
+ {
+ "expr": "max by (cluster, namespace, store_role) (testlookup_redis_memory_limit_configured{job=\"testlookup-backend\"} and on (cluster, namespace, job, instance) (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"redis\"} == 1) and on (cluster, namespace, job, instance) ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"redis\"}) <= 120))",
+ "legendFormat": "{{cluster}} {{namespace}} {{store_role}} bounded",
+ "refId": "A"
+ }
+ ],
+ "title": "Redis dataset limit configured",
+ "type": "timeseries"
+ },
+ {
+ "collapsed": false,
+ "gridPos": { "h": 1, "w": 24, "x": 0, "y": 128 },
+ "id": 110,
+ "title": "PostgreSQL application pools",
+ "type": "row"
+ },
+ {
+ "datasource": "Prometheus",
+ "description": "Maximum live process utilization within each API or worker target, including configured overflow in capacity. This preserves a saturated child even if sibling pools are idle; dividing summed checkouts by summed capacity would hide it. Only initialized lazy pools contribute. Missing data does not prove a healthy pool.",
+ "fieldConfig": {
+ "defaults": { "unit": "percentunit", "min": 0, "thresholds": { "mode": "absolute", "steps": [{ "color": "green", "value": null }, { "color": "red", "value": 0.9 }] } },
+ "overrides": []
+ },
+ "gridPos": { "h": 8, "w": 12, "x": 0, "y": 129 },
+ "id": 111,
+ "options": { "legend": { "displayMode": "list" }, "tooltip": { "mode": "multi" } },
+ "targets": [
+ {
+ "expr": "max by (cluster, namespace, job, instance, role) (sqlalchemy_pool_utilization_ratio{job=~\"testlookup-backend|testlookup-worker\",role=~\"api|worker\"} and on (cluster, namespace, job, instance, role) (sqlalchemy_pool_capacity_limited{job=~\"testlookup-backend|testlookup-worker\"} > 0))",
+ "legendFormat": "{{cluster}} {{namespace}} {{job}} {{instance}} {{role}}",
+ "refId": "A"
+ }
+ ],
+ "title": "Busiest live process pool utilization",
+ "type": "timeseries"
+ },
+ {
+ "datasource": "Prometheus",
+ "description": "Estimated five-minute increase of SQLAlchemy queue-capacity timeouts (3o7r), summed across API and worker targets per installation and process role. A public acquisition increments once even if checkout retries internally. Connection/query failures and cancellations do not count as pool-capacity timeouts.",
+ "fieldConfig": { "defaults": { "unit": "short", "min": 0 }, "overrides": [] },
+ "gridPos": { "h": 8, "w": 12, "x": 12, "y": 129 },
+ "id": 112,
+ "options": { "legend": { "displayMode": "list" }, "tooltip": { "mode": "multi" } },
+ "targets": [
+ {
+ "expr": "sum by (cluster, namespace, role) (increase(sqlalchemy_pool_timeouts_total{job=~\"testlookup-backend|testlookup-worker\",role=~\"api|worker\"}[5m]))",
+ "legendFormat": "{{cluster}} {{namespace}} {{role}} timeouts",
+ "refId": "A"
+ }
+ ],
+ "title": "Pool acquisition timeouts (5m)",
+ "type": "timeseries"
}
],
"refresh": "30s",
diff --git a/infra/monitoring/prometheus-rules/testlookup-alerts.yml b/infra/monitoring/prometheus-rules/testlookup-alerts.yml
index aa34fa98d..2b1421629 100644
--- a/infra/monitoring/prometheus-rules/testlookup-alerts.yml
+++ b/infra/monitoring/prometheus-rules/testlookup-alerts.yml
@@ -199,28 +199,57 @@ groups:
interval: 30s
rules:
- # PostgreSQL connection pool exhaustion
+ # livemax preserves one exhausted process even when other pools are idle.
+ # The producer includes configured overflow in each process's capacity.
- alert: TestLookupDBPoolExhausted
expr: |
- sqlalchemy_pool_checked_out{job="testlookup-backend"}
- /
- sqlalchemy_pool_size{job="testlookup-backend"} > 0.9
+ sqlalchemy_pool_utilization_ratio{job=~"testlookup-backend|testlookup-worker"} > 0.9
for: 2m
labels:
severity: critical
annotations:
- summary: "Database connection pool > 90% utilized"
- description: "PostgreSQL pool is nearly exhausted. Increase pool_size or investigate long-running queries."
+ summary: "A database connection pool is > 90% utilized"
+ description: "At least one {{ $labels.role }} process has used over 90% of its PostgreSQL pool capacity, including configured overflow. Investigate held connections and slow transactions; check the fleet connection budget before increasing pool limits."
- # Redis memory at capacity
+ # Native INFO memory observes configured application and broker roles.
+ # Excluded replication/AOF buffers are not part of the eviction budget.
+ # Never sum redundant API replicas or two roles sharing one Redis server.
- alert: TestLookupRedisMemoryHigh
- expr: redis_memory_used_bytes / redis_memory_max_bytes > 0.85
+ expr: |
+ max by (cluster, namespace, store_role) (
+ (
+ testlookup_redis_memory_counted_for_evict_bytes{job="testlookup-backend"}
+ / redis_memory_max_bytes{job="testlookup-backend"}
+ )
+ and on (cluster, namespace, job, instance, store_role)
+ (redis_memory_max_bytes{job="testlookup-backend"} > 0)
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{job="testlookup-backend",collector="redis"} == 1)
+ and on (cluster, namespace, job, instance)
+ ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",collector="redis"}) <= 120)
+ ) > 0.85
for: 5m
labels:
severity: warning
annotations:
summary: "Redis memory usage > 85%"
- description: "Redis is approaching its memory limit. Volatile-LRU eviction may start dropping session tokens."
+ description: "Configured {{ $labels.store_role }} Redis/Valkey memory counted for eviction exceeds 85% of maxmemory. Inspect capacity and key eviction policy; application and broker roles may share one physical server."
+
+ - alert: TestLookupRedisMemoryLimitMissing
+ expr: |
+ max by (cluster, namespace, store_role) (
+ redis_memory_max_bytes{job="testlookup-backend"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{job="testlookup-backend",collector="redis"} == 1)
+ and on (cluster, namespace, job, instance)
+ ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",collector="redis"}) <= 120)
+ ) == 0
+ for: 10m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Redis has no configured dataset memory limit"
+ description: "Configured {{ $labels.store_role }} Redis/Valkey reports maxmemory=0. Percentage saturation is undefined; define a supported capacity policy with headroom for process/container overhead or an explicit managed-service exception."
# Celery queue depth — tasks backing up
- alert: TestLookupCeleryQueueBacklog
diff --git a/infra/monitoring/prometheus.yml b/infra/monitoring/prometheus.yml
index 8bbed6729..bed12d85e 100644
--- a/infra/monitoring/prometheus.yml
+++ b/infra/monitoring/prometheus.yml
@@ -10,15 +10,10 @@ global:
rule_files:
- "rules/*.yml"
-scrape_configs:
-
- # ── FastAPI backend ──────────────────────────────────────────────────────────
- - job_name: 'testlookup-backend'
- static_configs:
- - targets: ['backend:8000']
- metrics_path: /metrics
- scrape_interval: 15s
+scrape_config_files:
+ - backend-scrape.yml
+scrape_configs:
# ── Celery worker (via prometheus-client multiprocess) ───────────────────────
# Each prefork worker container aggregates its children on port 9100.
- job_name: 'testlookup-worker'
diff --git a/infra/monitoring/tests/pool-alerts.yml b/infra/monitoring/tests/pool-alerts.yml
new file mode 100644
index 000000000..cf36366cb
--- /dev/null
+++ b/infra/monitoring/tests/pool-alerts.yml
@@ -0,0 +1,84 @@
+# Actual production expression, using the livemax sample emitted by each target.
+# The runtime multiprocess test proves the sample stays 1 for one saturated
+# child even when a sibling is idle (aggregate checked_out/capacity is 0.5).
+rule_files:
+- ../prometheus-rules/testlookup-alerts.yml
+evaluation_interval: 30s
+tests:
+- name: one exhausted API process fires after two minutes and recovers
+ interval: 30s
+ input_series:
+ - series: sqlalchemy_pool_utilization_ratio{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",role="api"}
+ values: '0.5x1 1x5 0.5x4'
+ - series: sqlalchemy_pool_utilization_ratio{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-b",role="api"}
+ values: '0x12'
+ - series: sqlalchemy_pool_checked_out{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",role="api"}
+ values: '2x12'
+ - series: sqlalchemy_pool_capacity{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",role="api"}
+ values: '4x12'
+ alert_rule_test:
+ - eval_time: 2m30s
+ alertname: TestLookupDBPoolExhausted
+ exp_alerts: []
+ - eval_time: 3m
+ alertname: TestLookupDBPoolExhausted
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ job: testlookup-backend
+ instance: api-a
+ role: api
+ severity: critical
+ exp_annotations:
+ summary: A database connection pool is > 90% utilized
+ description: At least one api process has used over 90% of its PostgreSQL pool capacity, including configured overflow. Investigate held connections and slow transactions; check the fleet connection budget before increasing pool limits.
+ - eval_time: 4m
+ alertname: TestLookupDBPoolExhausted
+ exp_alerts: []
+- name: worker exporter pressure is included alongside API pressure
+ interval: 30s
+ input_series:
+ - series: sqlalchemy_pool_utilization_ratio{cluster="lab",namespace="prod",job="testlookup-worker",instance="worker-children",role="worker"}
+ values: '1x8 0x3'
+ alert_rule_test:
+ - eval_time: 2m
+ alertname: TestLookupDBPoolExhausted
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ job: testlookup-worker
+ instance: worker-children
+ role: worker
+ severity: critical
+ exp_annotations:
+ summary: A database connection pool is > 90% utilized
+ description: At least one worker process has used over 90% of its PostgreSQL pool capacity, including configured overflow. Investigate held connections and slow transactions; check the fleet connection budget before increasing pool limits.
+ - eval_time: 4m30s
+ alertname: TestLookupDBPoolExhausted
+ exp_alerts: []
+- name: strict threshold, unbounded pools and unrelated jobs do not alert
+ interval: 30s
+ input_series:
+ - series: sqlalchemy_pool_utilization_ratio{job="testlookup-backend",instance="threshold",role="api"}
+ values: '0.9x12'
+ - series: sqlalchemy_pool_utilization_ratio{job="testlookup-backend",instance="unbounded",role="api"}
+ values: '0x12'
+ - series: sqlalchemy_pool_capacity{job="testlookup-backend",instance="unbounded",role="api"}
+ values: '0x12'
+ - series: sqlalchemy_pool_checked_out{job="testlookup-backend",instance="unbounded",role="api"}
+ values: '100x12'
+ - series: sqlalchemy_pool_utilization_ratio{job="other-api",instance="other",role="api"}
+ values: '1x12'
+ alert_rule_test:
+ - eval_time: 5m
+ alertname: TestLookupDBPoolExhausted
+ exp_alerts: []
+- name: absent pool data does not falsely claim exhaustion
+ interval: 30s
+ input_series: []
+ alert_rule_test:
+ - eval_time: 5m
+ alertname: TestLookupDBPoolExhausted
+ exp_alerts: []
diff --git a/infra/monitoring/tests/redis-resources.yml b/infra/monitoring/tests/redis-resources.yml
new file mode 100644
index 000000000..11c99ea0d
--- /dev/null
+++ b/infra/monitoring/tests/redis-resources.yml
@@ -0,0 +1,106 @@
+# Native Redis rules: finite limits, low/zero capacity, stale replicas and recovery.
+rule_files:
+- ../prometheus-rules/testlookup-alerts.yml
+evaluation_interval: 30s
+tests:
+- name: fresh native Redis high memory fires once across replicas and recovers
+ interval: 30s
+ input_series:
+ - series: testlookup_redis_memory_counted_for_evict_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",store_role="application"}
+ values: '95x10 50x29'
+ - series: redis_memory_max_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",store_role="application"}
+ values: '100x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",collector="redis"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",collector="redis"}
+ values: '0+30x40'
+ - series: testlookup_redis_memory_counted_for_evict_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-b",store_role="application"}
+ values: '95x10 50x29'
+ - series: redis_memory_max_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-b",store_role="application"}
+ values: '100x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-b",collector="redis"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-b",collector="redis"}
+ values: '0+30x40'
+ promql_expr_test:
+ - expr: count(ALERTS{alertname="TestLookupRedisMemoryHigh",alertstate="firing"}) or vector(0)
+ eval_time: 4m30s
+ exp_samples:
+ - labels: '{}'
+ value: 0
+ - expr: count by (cluster,namespace,store_role) (ALERTS{alertname="TestLookupRedisMemoryHigh",alertstate="firing"})
+ eval_time: 5m
+ exp_samples:
+ - labels: '{cluster="lab",namespace="prod",store_role="application"}'
+ value: 1
+ - expr: count(ALERTS{alertname="TestLookupRedisMemoryHigh",alertstate="firing"}) or vector(0)
+ eval_time: 6m
+ exp_samples:
+ - labels: '{}'
+ value: 0
+- name: unlimited memory is a separate policy alert and never infinite saturation
+ interval: 30s
+ input_series:
+ - series: testlookup_redis_memory_counted_for_evict_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",store_role="broker"}
+ values: '50x40'
+ - series: redis_memory_max_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",store_role="broker"}
+ values: '0x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",collector="redis"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",collector="redis"}
+ values: '0+30x40'
+ promql_expr_test:
+ - expr: count(ALERTS{alertname="TestLookupRedisMemoryHigh",alertstate="firing"}) or vector(0)
+ eval_time: 12m
+ exp_samples:
+ - labels: '{}'
+ value: 0
+ - expr: count(ALERTS{alertname="TestLookupRedisMemoryLimitMissing",alertstate="firing"}) or vector(0)
+ eval_time: 9m30s
+ exp_samples:
+ - labels: '{}'
+ value: 0
+ - expr: count by (cluster,namespace,store_role) (ALERTS{alertname="TestLookupRedisMemoryLimitMissing",alertstate="firing"})
+ eval_time: 10m
+ exp_samples:
+ - labels: '{cluster="lab",namespace="prod",store_role="broker"}'
+ value: 1
+- name: failed and stale replicas cannot override fresh low memory or borrow another namespace health
+ interval: 30s
+ input_series:
+ - series: redis_memory_used_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",store_role="application"}
+ values: '95x40'
+ - series: testlookup_redis_memory_counted_for_evict_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",store_role="application"}
+ values: '80x40'
+ - series: redis_memory_max_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",store_role="application"}
+ values: '100x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",collector="redis"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-a",collector="redis"}
+ values: '0+30x40'
+ - series: testlookup_redis_memory_counted_for_evict_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-failed",store_role="application"}
+ values: '99x40'
+ - series: redis_memory_max_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-failed",store_role="application"}
+ values: '100x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-failed",collector="redis"}
+ values: '0x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-failed",collector="redis"}
+ values: '0+30x40'
+ - series: testlookup_redis_memory_counted_for_evict_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-stale",store_role="application"}
+ values: '99x40'
+ - series: redis_memory_max_bytes{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-stale",store_role="application"}
+ values: '100x40'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-stale",collector="redis"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="api-stale",collector="redis"}
+ values: '0x40'
+ - series: testlookup_redis_memory_counted_for_evict_bytes{cluster="lab",namespace="other",job="testlookup-backend",instance="api-a",store_role="broker"}
+ values: '99x40'
+ - series: redis_memory_max_bytes{cluster="lab",namespace="other",job="testlookup-backend",instance="api-a",store_role="broker"}
+ values: '100x40'
+ promql_expr_test:
+ - expr: count(ALERTS{alertname="TestLookupRedisMemoryHigh",alertstate="firing"}) or vector(0)
+ eval_time: 10m
+ exp_samples:
+ - labels: '{}'
+ value: 0
diff --git a/k8s/components/metrics-auth/backend-token-mount.yaml b/k8s/components/metrics-auth/backend-token-mount.yaml
new file mode 100644
index 000000000..0b0822ed6
--- /dev/null
+++ b/k8s/components/metrics-auth/backend-token-mount.yaml
@@ -0,0 +1,23 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: testlookup-backend
+spec:
+ template:
+ spec:
+ containers:
+ - name: backend
+ env:
+ - name: METRICS_TOKEN_FILE
+ value: /run/secrets/testlookup-metrics/token
+ volumeMounts:
+ - name: metrics-token
+ mountPath: /run/secrets/testlookup-metrics
+ readOnly: true
+ volumes:
+ - name: metrics-token
+ secret:
+ secretName: testlookup-metrics-auth
+ items:
+ - key: token
+ path: token
diff --git a/k8s/components/metrics-auth/kustomization.yaml b/k8s/components/metrics-auth/kustomization.yaml
new file mode 100644
index 000000000..0d4ba2cf9
--- /dev/null
+++ b/k8s/components/metrics-auth/kustomization.yaml
@@ -0,0 +1,9 @@
+apiVersion: kustomize.config.k8s.io/v1alpha1
+kind: Component
+patches:
+ - path: backend-token-mount.yaml
+ target:
+ group: apps
+ version: v1
+ kind: Deployment
+ name: testlookup-backend
diff --git a/k8s/monitoring-authenticated/kustomization.yaml b/k8s/monitoring-authenticated/kustomization.yaml
new file mode 100644
index 000000000..6e00b1c0a
--- /dev/null
+++ b/k8s/monitoring-authenticated/kustomization.yaml
@@ -0,0 +1,19 @@
+apiVersion: kustomize.config.k8s.io/v1beta1
+kind: Kustomization
+resources:
+ - ../monitoring
+patches:
+ - target:
+ kind: PodMonitor
+ name: testlookup-backend
+ patch: |-
+ - op: add
+ path: /spec/podMetricsEndpoints/0/authorization
+ value:
+ type: Bearer
+ credentials:
+ name: testlookup-metrics-auth
+ key: token
+ - op: add
+ path: /spec/podMetricsEndpoints/0/followRedirects
+ value: false
diff --git a/k8s/monitoring/prometheusrule.yaml b/k8s/monitoring/prometheusrule.yaml
index 366012ec1..f34f4e67c 100644
--- a/k8s/monitoring/prometheusrule.yaml
+++ b/k8s/monitoring/prometheusrule.yaml
@@ -162,27 +162,31 @@ spec:
interval: 30s
rules:
- alert: TestLookupDBPoolExhausted
- expr: 'sqlalchemy_pool_checked_out{job="testlookup-backend"}
-
- /
-
- sqlalchemy_pool_size{job="testlookup-backend"} > 0.9
+ expr: 'sqlalchemy_pool_utilization_ratio{job=~"testlookup-backend|testlookup-worker"} > 0.9
'
for: 2m
labels:
severity: critical
annotations:
- summary: Database connection pool > 90% utilized
- description: PostgreSQL pool is nearly exhausted. Increase pool_size or investigate long-running queries.
+ summary: A database connection pool is > 90% utilized
+ description: At least one {{ $labels.role }} process has used over 90% of its PostgreSQL pool capacity, including configured overflow. Investigate held connections and slow transactions; check the fleet connection budget before increasing pool limits.
- alert: TestLookupRedisMemoryHigh
- expr: redis_memory_used_bytes / redis_memory_max_bytes > 0.85
+ expr: "max by (cluster, namespace, store_role) (\n (\n testlookup_redis_memory_counted_for_evict_bytes{job=\"testlookup-backend\"}\n / redis_memory_max_bytes{job=\"testlookup-backend\"}\n )\n and on (cluster, namespace, job, instance, store_role)\n (redis_memory_max_bytes{job=\"testlookup-backend\"} > 0)\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"redis\"} == 1)\n and on (cluster, namespace, job, instance)\n ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"redis\"}) <= 120)\n) > 0.85\n"
for: 5m
labels:
severity: warning
annotations:
summary: Redis memory usage > 85%
- description: Redis is approaching its memory limit. Volatile-LRU eviction may start dropping session tokens.
+ description: Configured {{ $labels.store_role }} Redis/Valkey memory counted for eviction exceeds 85% of maxmemory. Inspect capacity and key eviction policy; application and broker roles may share one physical server.
+ - alert: TestLookupRedisMemoryLimitMissing
+ expr: "max by (cluster, namespace, store_role) (\n redis_memory_max_bytes{job=\"testlookup-backend\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"redis\"} == 1)\n and on (cluster, namespace, job, instance)\n ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"redis\"}) <= 120)\n) == 0\n"
+ for: 10m
+ labels:
+ severity: warning
+ annotations:
+ summary: Redis has no configured dataset memory limit
+ description: Configured {{ $labels.store_role }} Redis/Valkey reports maxmemory=0. Percentage saturation is undefined; define a supported capacity policy with headroom for process/container overhead or an explicit managed-service exception.
- alert: TestLookupCeleryQueueBacklog
expr: 'max by (queue_name) (celery_queue_length) > 100
From be88915c73d3cea921c049964662dabeacb65cd4 Mon Sep 17 00:00:00 2001
From: Anand Topu
Date: Thu, 26 Nov 2026 23:37:32 -0600
Subject: [PATCH 03/13] feat: verify alert routing and detect missed scheduled
work
Add an opt-in Alertmanager profile with authenticated incident and watchdog
receivers. Preserve the scrape configuration and check real delivery against
a disposable TLS sink using the existing backend CI job.
Define the expected targets and metrics independently from discovery. Track
weekly digest delivery and nightly slot completion in durable observations,
so worker replacement, quiet workloads, misses and recovery stay distinct.
Validation: 406 focused backend cases passed and one needs a disposable
PostgreSQL DSN. Forty Prometheus scenarios, ten alert delivery tests, forward
and reverse migration SQL, rendered profiles and generated references passed.
Record remaining site acceptance and the next work in the delivery ledger.
Signed-off-by: Anand Topu
---
.github/workflows/ci.yml | 49 ++-
.github/workflows/third-party-images.yml | 6 +-
CHANGELOG.md | 2 +
architecture/DATABASE_SCHEMA.md | 17 +
backend/app/bootstrap.py | 4 +
backend/app/core/metrics.py | 47 +-
backend/app/models/postgres.py | 22 +
backend/app/routers/digests.py | 6 +
.../services/digest_delivery_observation.py | 81 ++++
.../services/digest_operational_metrics.py | 76 ++++
backend/app/services/feature_flags.py | 12 +
backend/app/services/metric_collection.py | 2 +-
.../app/services/nightly_job_observation.py | 151 +++++++
backend/app/worker/celery_app.py | 11 +-
backend/app/worker/nightly_schedule.py | 50 +++
backend/app/worker/tasks.py | 57 ++-
.../versions/0261_nightly_job_observations.py | 34 ++
.../0262_digest_delivery_observations.py | 36 ++
.../test_nightly_job_observation_postgres.py | 59 +++
.../test_alert_rules_are_deployable.py | 13 +-
.../test_backup_alerts_and_scrape_targets.py | 6 +-
.../test_digest_delivery_observation.py | 408 ++++++++++++++++++
.../test_nightly_job_observation.py | 197 +++++++++
.../regression/test_telemetry_contract.py | 94 ++++
backend/tests/test_digest_scope.py | 7 +
docker-compose.alerting.yml | 70 +++
docs/maintainers/observability-delivery.md | 28 +-
docs/operations/alert-routing.md | 160 +++++++
docs/operations/deploy-compose.md | 2 +
docs/operations/deploy-kubernetes.md | 2 +
docs/operations/deployment.md | 2 +-
docs/operations/scheduled-maintenance.md | 22 +
docs/operations/telemetry-contract.md | 96 +++++
.../operations/weekly-digest-observability.md | 34 ++
docs/reference/api/digests.md | 8 +-
docs/reference/data-dictionary.md | 126 +++---
docs/reference/migrations.md | 2 +
docs/reference/worker-operations.md | 110 ++---
.../monitoring/alertmanager/alertmanager.yml | 57 +++
infra/monitoring/alertmanager/image-lock.json | 20 +
.../alertmanager/telemetry-contract.yml | 12 +
.../backend-scrape-authenticated.yml | 3 +
infra/monitoring/backend-scrape.yml | 3 +
.../dashboards/testlookup-overview.json | 4 +-
.../compose-telemetry-contract.yml | 25 ++
.../prometheus-rules/testlookup-alerts.yml | 214 ++++++---
infra/monitoring/prometheus.yml | 9 +-
.../tests/alerting-telemetry-contract.yml | 32 ++
.../tests/compose-telemetry-contract.yml | 58 +++
infra/monitoring/tests/digest-delivery.yml | 137 ++++++
infra/monitoring/tests/nightly-alerts.yml | 69 +++
infra/monitoring/tests/telemetry-absence.yml | 336 +++++++++++++++
k8s/monitoring/kustomization.yaml | 1 +
k8s/monitoring/podmonitors.yaml | 14 +
k8s/monitoring/prometheusrule.yaml | 109 ++++-
k8s/monitoring/telemetry-contract.yaml | 60 +++
scripts/monitoring/configure_alerting.py | 120 ++++++
.../monitoring/tests/test_alert_routing.py | 300 +++++++++++++
58 files changed, 3480 insertions(+), 212 deletions(-)
create mode 100644 backend/app/services/digest_delivery_observation.py
create mode 100644 backend/app/services/digest_operational_metrics.py
create mode 100644 backend/app/services/nightly_job_observation.py
create mode 100644 backend/app/worker/nightly_schedule.py
create mode 100644 backend/migrations/versions/0261_nightly_job_observations.py
create mode 100644 backend/migrations/versions/0262_digest_delivery_observations.py
create mode 100644 backend/tests/integration/test_nightly_job_observation_postgres.py
create mode 100644 backend/tests/regression/test_digest_delivery_observation.py
create mode 100644 backend/tests/regression/test_nightly_job_observation.py
create mode 100644 backend/tests/regression/test_telemetry_contract.py
create mode 100644 docker-compose.alerting.yml
create mode 100644 docs/operations/alert-routing.md
create mode 100644 docs/operations/scheduled-maintenance.md
create mode 100644 docs/operations/telemetry-contract.md
create mode 100644 docs/operations/weekly-digest-observability.md
create mode 100644 infra/monitoring/alertmanager/alertmanager.yml
create mode 100644 infra/monitoring/alertmanager/image-lock.json
create mode 100644 infra/monitoring/alertmanager/telemetry-contract.yml
create mode 100644 infra/monitoring/prometheus-rules/compose-telemetry-contract.yml
create mode 100644 infra/monitoring/tests/alerting-telemetry-contract.yml
create mode 100644 infra/monitoring/tests/compose-telemetry-contract.yml
create mode 100644 infra/monitoring/tests/digest-delivery.yml
create mode 100644 infra/monitoring/tests/nightly-alerts.yml
create mode 100644 infra/monitoring/tests/telemetry-absence.yml
create mode 100644 k8s/monitoring/telemetry-contract.yaml
create mode 100644 scripts/monitoring/configure_alerting.py
create mode 100644 scripts/monitoring/tests/test_alert_routing.py
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 157303523..f4c8bc332 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -520,7 +520,7 @@ jobs:
# immutable official v3.16.0 sha256sums.txt, checked before extracting or
# executing the tool. Run within this existing job, without a new matrix.
- name: Verify alert semantics with checksum-pinned promtool
- working-directory: infra/monitoring/tests
+ working-directory: .
env:
PROMETHEUS_VERSION: "3.16.0"
PROMETHEUS_ARCHIVE_SHA256: 68727009472a2c02e1ff7f062fd5b3e637285bffc8fc2d340c76fb449d6e0f34
@@ -533,19 +533,51 @@ jobs:
--output "$archive" \
"https://github.com/prometheus/prometheus/releases/download/v${PROMETHEUS_VERSION}/prometheus-${PROMETHEUS_VERSION}.linux-amd64.tar.gz"
printf '%s %s\n' "$PROMETHEUS_ARCHIVE_SHA256" "$archive" | sha256sum --check --strict
- tar -xzf "$archive" -C "$scratch" "prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool"
- tool="$scratch/prometheus-${PROMETHEUS_VERSION}.linux-amd64/promtool"
- "$tool" check rules ../prometheus-rules/testlookup-alerts.yml
- "$tool" test rules ./*.yml
+ prometheus_dir="prometheus-${PROMETHEUS_VERSION}.linux-amd64"
+ tar -xzf "$archive" -C "$scratch" "$prometheus_dir/promtool" "$prometheus_dir/prometheus"
+ tool="$scratch/$prometheus_dir/promtool"
+ monitoring="infra/monitoring"
+ "$tool" check rules "$monitoring/prometheus-rules/testlookup-alerts.yml"
+ "$tool" test rules "$monitoring"/tests/*.yml
# Mirror the Compose mounts and validate included scrape jobs and rules.
mkdir "$scratch/config"
- cp ../prometheus.yml "$scratch/config/"
- cp -R ../prometheus-rules "$scratch/config/rules"
- for backend_job in ../backend-scrape.yml ../backend-scrape-authenticated.yml; do
+ cp "$monitoring/prometheus.yml" "$scratch/config/"
+ cp -R "$monitoring/prometheus-rules" "$scratch/config/rules"
+ for backend_job in "$monitoring/backend-scrape.yml" "$monitoring/backend-scrape-authenticated.yml"; do
cp "$backend_job" "$scratch/config/backend-scrape.yml"
printf '%s\n' 'synthetic-test-token' > "$scratch/config/metrics-token"
"$tool" check config "$scratch/config/prometheus.yml"
done
+ cp "$monitoring/alertmanager/telemetry-contract.yml" "$scratch/config/alertmanager-contract.yml"
+ for input in incident-url watchdog-url; do
+ printf '%s\n' "https://receiver.invalid/$input" > "$scratch/$input"
+ done
+ printf '%s\n' 'synthetic-receiver-token' > "$scratch/receiver-token"
+ ALERTMANAGER_INCIDENT_URL_SOURCE="$scratch/incident-url" \
+ ALERTMANAGER_WATCHDOG_URL_SOURCE="$scratch/watchdog-url" \
+ ALERTMANAGER_INCIDENT_TOKEN_SOURCE="$scratch/receiver-token" \
+ ALERTMANAGER_WATCHDOG_TOKEN_SOURCE="$scratch/receiver-token" \
+ python scripts/monitoring/configure_alerting.py \
+ --output "$scratch/config/alerting.yml" --installation fixture --environment ci --owner platform
+ "$tool" check config "$scratch/config/alerting.yml"
+ # Test firing, resolved and Watchdog delivery to an isolated TLS sink.
+ mapfile -t alertmanager_pin < <(python -c '
+ import json
+ from pathlib import Path
+ pin = json.loads(Path("infra/monitoring/alertmanager/image-lock.json").read_text())["release_binaries"]["linux-amd64"]
+ print(pin["url"], pin["sha256"], sep="\n")
+ ')
+ alertmanager_archive="$scratch/alertmanager.tar.gz"
+ alertmanager_dir="$(basename "${alertmanager_pin[0]}" .tar.gz)"
+ curl --fail --location --silent --show-error --retry 3 --max-time 180 \
+ --output "$alertmanager_archive" "${alertmanager_pin[0]}"
+ printf '%s %s\n' "${alertmanager_pin[1]}" "$alertmanager_archive" | sha256sum --check --strict
+ tar -xzf "$alertmanager_archive" -C "$scratch" "$alertmanager_dir/alertmanager" "$alertmanager_dir/amtool"
+ export PROMETHEUS_TEST_BINARY="$scratch/$prometheus_dir/prometheus"
+ export ALERTMANAGER_TEST_BINARY="$scratch/$alertmanager_dir/alertmanager"
+ export AMTOOL_TEST_BINARY="$scratch/$alertmanager_dir/amtool"
+ export PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ python -m pytest scripts/monitoring/tests -q
# Blocking, as a ratchet (re-audit M24). mypy reports 391 pre-existing
# errors in 117 files; backend/mypy-baseline.txt holds the per-file
@@ -1085,6 +1117,7 @@ jobs:
tests/integration/test_test_case_lifecycle_postgres.py
tests/integration/test_db_connection_budget_postgres.py
tests/integration/test_db_pool_metrics_postgres.py
+ tests/integration/test_nightly_job_observation_postgres.py
tests/integration/test_engine_hides_parameters_postgres.py
tests/integration/test_decision_report_supersession_postgres_mongo.py
tests/integration/test_http_exchanges_postgres_mongo.py
diff --git a/.github/workflows/third-party-images.yml b/.github/workflows/third-party-images.yml
index a257b0649..68e9e28b9 100644
--- a/.github/workflows/third-party-images.yml
+++ b/.github/workflows/third-party-images.yml
@@ -5,7 +5,7 @@ name: Third-party image scan
# Flower and the monitoring add-on's Jaeger, Prometheus and Grafana) were in no
# scan, and Dependabot tracks only their Compose tags (OSS review 2026-11-12,
# H-4). This scans every `infra` row of deploy/images.manifest.txt and every
-# image in docker-compose.monitoring.yml: weekly, when either file changes on
+# image in the monitoring and alerting overlays: weekly, when these files change on
# main, and on demand.
#
# It reports and does not fail on findings: an upstream image's findings are
@@ -22,6 +22,7 @@ on:
paths:
- deploy/images.manifest.txt
- docker-compose.monitoring.yml
+ - docker-compose.alerting.yml
- .github/workflows/third-party-images.yml
# A pull request that changes an image or this workflow sees the report
# before it merges.
@@ -29,6 +30,7 @@ on:
paths:
- deploy/images.manifest.txt
- docker-compose.monitoring.yml
+ - docker-compose.alerting.yml
- .github/workflows/third-party-images.yml
workflow_dispatch:
@@ -77,7 +79,7 @@ jobs:
set -euo pipefail
{
awk '!/^[[:space:]]*#/ && NF >= 2 && $2 == "infra" { print $1 }' deploy/images.manifest.txt
- sed -n 's/^[[:space:]]*image:[[:space:]]*//p' docker-compose.monitoring.yml
+ sed -n 's/^[[:space:]]*image:[[:space:]]*//p' docker-compose.monitoring.yml docker-compose.alerting.yml
} | sort -u > third-party-images.txt
test "$(wc -l < third-party-images.txt)" -ge 8
cat third-party-images.txt
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f32eef78f..462f68d12 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).
### Added
+- The optional Compose alerting overlay adds a private Alertmanager with authenticated HTTPS incident and watchdog receivers. Compose and Kubernetes monitoring inventories detect missing scrape roles and required metric series.
- Operational metrics report SQLAlchemy pool pressure and acquisition timeouts for API and worker processes, plus Redis and Valkey memory for the application and broker. Optional Compose and Kubernetes profiles support file-backed authentication for API scrapes.
- Operational metrics expose collector freshness and durable downstream-outbox failure/overdue state, including alerts that avoid counting the same SQL rows across API replicas.
@@ -16,6 +17,7 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).
### Changed
+- Weekly digest and nightly maintenance alerts follow durable delivery and execution state. They detect overdue work even when a worker never started the task or was replaced.
- Celery queue depth reads all configured broker priority lists, including child work, and reports unknown counts when a list cannot be read.
- Upload publication uses bounded background threads; uncertain queue confirmation retains the payload and returns polling identifiers so callers can check before resubmitting.
- Trace exporters sanitize exception events and custom text as well as URL attributes. Browser error batches use UTF-8 byte limits; unexpected core API errors return a correlated request identifier. Worker task context and startup readiness markers are reset between executions.
diff --git a/architecture/DATABASE_SCHEMA.md b/architecture/DATABASE_SCHEMA.md
index aa80fb556..f2da17e33 100644
--- a/architecture/DATABASE_SCHEMA.md
+++ b/architecture/DATABASE_SCHEMA.md
@@ -3121,11 +3121,28 @@ _Constraints:_ Index(`ix_search_query_events_project_created`, `project_id`, `cr
| `last_delivered_at` | `DateTime` | | | |
| `next_delivery_at` | `DateTime` | | | |
| `delivery_count` | `Integer` | | NN def | |
+| `pending_delivery_since_at` | `DateTime` | | | |
+| `delivery_observation_token` | `UUID` | | | |
+| `last_delivery_attempt_at` | `DateTime` | | | |
+| `last_content_generated_at` | `DateTime` | | | |
+| `last_delivery_outcome` | `String(20)` | | | |
| `created_at` | `DateTime` | | NN def | |
| `updated_at` | `DateTime` | | NN def | |
_Constraints:_ Index(`ix_ds_user`, `user_id`); Index(`ix_ds_next`, `next_delivery_at`); Index(`ix_ds_schedule_active`, `schedule`, `is_active`, `is_paused`)
+#### `nightly_job_observations` (model `NightlyJobObservation`)
+
+| Column | Type | Key | Flags | References |
+|---|---|---|---|---|
+| `schedule_key` | `String(64)` | PK | NN | |
+| `monitoring_since` | `DateTime` | | NN def | |
+| `enabled_since` | `DateTime` | | | |
+| `last_attempt_slot_at` | `DateTime` | | | |
+| `last_attempt_started_at` | `DateTime` | | | |
+| `last_success_slot_at` | `DateTime` | | | |
+| `last_success_finished_at` | `DateTime` | | | |
+
#### `report_share_links` (model `ReportShareLink`)
| Column | Type | Key | Flags | References |
diff --git a/backend/app/bootstrap.py b/backend/app/bootstrap.py
index 95f8d5067..49ce8b788 100644
--- a/backend/app/bootstrap.py
+++ b/backend/app/bootstrap.py
@@ -530,10 +530,12 @@ async def _endpoint(*args, __orig=original, **kwargs):
from app.services.agent_operational_metrics import (
refresh_agent_operational_metrics,
)
+ from app.services.digest_operational_metrics import refresh_digest_operational_metrics
from app.services.downstream_operational_metrics import (
refresh_downstream_operational_metrics,
)
from app.services.metric_collection import collect_bounded
+ from app.services.nightly_job_observation import refresh_nightly_job_metrics
from app.services.redis_resource_metrics import refresh_redis_resource_metrics
await asyncio.gather(
@@ -541,6 +543,8 @@ async def _endpoint(*args, __orig=original, **kwargs):
collect_bounded("agents", refresh_agent_operational_metrics),
collect_bounded("downstream", refresh_downstream_operational_metrics),
collect_bounded("redis", refresh_redis_resource_metrics),
+ collect_bounded("nightly", refresh_nightly_job_metrics),
+ collect_bounded("digests", refresh_digest_operational_metrics),
)
result = __orig(*args, **kwargs)
if inspect.isawaitable(result):
diff --git a/backend/app/core/metrics.py b/backend/app/core/metrics.py
index 9c535add7..8b1ce8de4 100644
--- a/backend/app/core/metrics.py
+++ b/backend/app/core/metrics.py
@@ -618,7 +618,7 @@
retro_digest_dispatch_total = Counter(
"testlookup_retro_digest_dispatch_total",
- "Total weekly retro digest dispatch task runs",
+ "Weekly retro content generation outcomes, not successful provider deliveries",
["status"], # success | skipped | failure
)
@@ -972,3 +972,48 @@
"Pool queue acquisition timeouts (SQLAlchemy 3o7r), once per public attempt",
["role"],
)
+
+# Absolute durable subscription snapshots; scrape replicas must not sum them.
+# Schedule/state/outcome vocabularies are bounded, with no subscriber labels.
+weekly_digest_subscriptions = Gauge(
+ "testlookup_weekly_digest_subscriptions",
+ "Enabled weekly subscriptions by durable due/observation state",
+ ["schedule", "state"], multiprocess_mode="mostrecent",
+)
+weekly_digest_oldest_overdue_seconds = Gauge(
+ "testlookup_weekly_digest_oldest_overdue_seconds",
+ "Oldest unmet weekly delivery slot beyond daily-dispatch plus processing grace",
+ ["schedule"], multiprocess_mode="mostrecent",
+)
+weekly_digest_delivery_outcomes = Gauge(
+ "testlookup_weekly_digest_delivery_outcomes",
+ "Enabled weekly subscriptions by last observed attempt outcome; generation is not delivery",
+ ["schedule", "outcome"], multiprocess_mode="mostrecent",
+)
+
+# Nightly jobs use shared SQL observations. The schedule label comes from the
+# two-job registry, with no task IDs or project data.
+nightly_job_enabled = Gauge(
+ "testlookup_nightly_job_enabled", "Whether the nightly job's feature is enabled", ["schedule"],
+ multiprocess_mode="mostrecent",
+)
+nightly_job_next_due_timestamp = Gauge(
+ "testlookup_nightly_job_next_due_timestamp_seconds", "Next UTC slot, or zero when disabled", ["schedule"],
+ multiprocess_mode="mostrecent",
+)
+nightly_job_last_attempt_timestamp = Gauge(
+ "testlookup_nightly_job_last_attempt_timestamp_seconds", "Start of the most recent observed slot attempt", ["schedule"],
+ multiprocess_mode="mostrecent",
+)
+nightly_job_last_success_timestamp = Gauge(
+ "testlookup_nightly_job_last_success_timestamp_seconds", "Completion of the most recent successful slot", ["schedule"],
+ multiprocess_mode="mostrecent",
+)
+nightly_job_overdue = Gauge(
+ "testlookup_nightly_job_overdue", "Whether an eligible nightly slot missed its success deadline", ["schedule"],
+ multiprocess_mode="mostrecent",
+)
+nightly_job_started_overdue_slot = Gauge(
+ "testlookup_nightly_job_started_overdue_slot", "Whether a worker began the overdue slot or a later one", ["schedule"],
+ multiprocess_mode="mostrecent",
+)
diff --git a/backend/app/models/postgres.py b/backend/app/models/postgres.py
index 0f08c2622..d32df2037 100644
--- a/backend/app/models/postgres.py
+++ b/backend/app/models/postgres.py
@@ -5674,6 +5674,14 @@ class DigestSubscription(Base):
# each scheduled delivery reports changes since the previous send.
last_delivered_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
next_delivery_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ # OBS-E03-S01: an atomic schedule claim must not erase unfinished due
+ # work. This original slot survives retry claims until sent/policy-skipped.
+ # The token fences late writes from an older attempt or schedule edit.
+ pending_delivery_since_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ delivery_observation_token: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True))
+ last_delivery_attempt_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ last_content_generated_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ last_delivery_outcome: Mapped[Optional[str]] = mapped_column(String(20))
delivery_count: Mapped[int] = mapped_column(Integer, default=0)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), onupdate=func.now(), server_default=func.now())
@@ -6653,6 +6661,20 @@ class AgentActionDispatchOutbox(Base):
# history is a first-class audit trail for regulated customers.
+class NightlyJobObservation(Base):
+ """Bounded operational state shared by the scheduled workers and API."""
+
+ __tablename__ = "nightly_job_observations"
+
+ schedule_key: Mapped[str] = mapped_column(String(64), primary_key=True)
+ monitoring_since: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ enabled_since: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ last_attempt_slot_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ last_attempt_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ last_success_slot_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ last_success_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+
+
class FeatureFlag(Base):
"""Named capability toggle gated by project, role, and rollout percent."""
__tablename__ = "feature_flags"
diff --git a/backend/app/routers/digests.py b/backend/app/routers/digests.py
index aa2e17b52..82870965e 100644
--- a/backend/app/routers/digests.py
+++ b/backend/app/routers/digests.py
@@ -237,6 +237,9 @@ async def update_subscription(
if "schedule" in update_data:
delta = timedelta(days=1) if update_data["schedule"] == "DAILY" else timedelta(weeks=1)
sub.next_delivery_at = datetime.now(timezone.utc) + delta
+ from app.services.digest_delivery_observation import reset_digest_observation
+
+ reset_digest_observation(sub)
for field, value in update_data.items():
setattr(sub, field, value)
@@ -309,6 +312,9 @@ async def resume_subscription(
sub.is_paused = False
delta = timedelta(days=1) if sub.schedule == "DAILY" else timedelta(weeks=1)
sub.next_delivery_at = datetime.now(timezone.utc) + delta
+ from app.services.digest_delivery_observation import reset_digest_observation
+
+ reset_digest_observation(sub)
await db.commit()
await db.refresh(sub)
return sub
diff --git a/backend/app/services/digest_delivery_observation.py b/backend/app/services/digest_delivery_observation.py
new file mode 100644
index 000000000..276230176
--- /dev/null
+++ b/backend/app/services/digest_delivery_observation.py
@@ -0,0 +1,81 @@
+"""Durable passive observation of scheduled digest attempts, not a new relay."""
+from __future__ import annotations
+
+import logging
+import uuid
+from datetime import datetime, timezone
+
+from sqlalchemy import func, update
+
+from app.models.postgres import DigestSubscription
+
+logger = logging.getLogger(__name__)
+OUTCOMES = ("not_observed", "generating", "generated", "sent", "failed", "skipped", "unknown")
+
+
+def digest_claim_observation(*, now: datetime, token: uuid.UUID) -> dict:
+ """Stage alongside the successful claim, preserving the first unmet slot."""
+ return {
+ "pending_delivery_since_at": func.coalesce(
+ DigestSubscription.pending_delivery_since_at, DigestSubscription.next_delivery_at
+ ),
+ "delivery_observation_token": token,
+ "last_delivery_attempt_at": now,
+ "last_delivery_outcome": "generating",
+ }
+
+
+def digest_final_observation(status: str) -> dict:
+ if status not in {"sent", "failed", "skipped", "unknown"}:
+ raise ValueError("unsupported digest delivery outcome")
+ values = {"last_delivery_outcome": status, "delivery_observation_token": None}
+ if status in {"sent", "skipped"}:
+ values["pending_delivery_since_at"] = None
+ return values
+
+
+def reset_digest_observation(subscription) -> None:
+ """A deliberate new schedule/resume supersedes old attempt ownership.
+
+ Historical delivery/generation timestamps remain history. Clearing the
+ token prevents an old provider completion from rewriting the new slot.
+ """
+ subscription.pending_delivery_since_at = None
+ subscription.delivery_observation_token = None
+ subscription.last_delivery_outcome = None
+
+
+async def observe_digest_phase(
+ subscription_id: uuid.UUID, token: uuid.UUID, *, phase: str, now: datetime | None = None,
+) -> bool:
+ """Best-effort short transaction; a telemetry failure cannot gate egress.
+
+ The required pending-slot receipt already committed with the claim. This
+ update only improves phase detail and never advances delivery success.
+ """
+ from app.db.postgres import AsyncSessionLocal
+
+ if phase == "generated":
+ values = {
+ "last_content_generated_at": now or datetime.now(timezone.utc),
+ "last_delivery_outcome": "generated",
+ }
+ elif phase in {"unknown", "skipped"}:
+ values = digest_final_observation(phase)
+ else:
+ raise ValueError("unsupported digest observation phase")
+ try:
+ async with AsyncSessionLocal() as db:
+ result = await db.execute(
+ update(DigestSubscription)
+ .where(
+ DigestSubscription.id == subscription_id,
+ DigestSubscription.delivery_observation_token == token,
+ )
+ .values(**values)
+ )
+ await db.commit()
+ return int(getattr(result, "rowcount", 0) or 0) == 1
+ except Exception as exc:
+ logger.warning("digest_observation_update_failed error_type=%s", type(exc).__name__)
+ return False
diff --git a/backend/app/services/digest_operational_metrics.py b/backend/app/services/digest_operational_metrics.py
new file mode 100644
index 000000000..b145132fc
--- /dev/null
+++ b/backend/app/services/digest_operational_metrics.py
@@ -0,0 +1,76 @@
+"""Due-aware weekly delivery snapshots from the persisted subscription state."""
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from sqlalchemy import case, func, select
+
+from app.core.metrics import (
+ weekly_digest_delivery_outcomes,
+ weekly_digest_oldest_overdue_seconds,
+ weekly_digest_subscriptions,
+)
+from app.services.digest_delivery_observation import OUTCOMES
+
+SCHEDULES = ("WEEKLY", "WEEKLY_RETRO")
+STATES = ("enabled", "due", "unresolved", "never_delivered", "missing_schedule")
+# next_delivery_at can fall immediately after the daily 07:00 UTC dispatch.
+# Allow the next daily pass (24h) plus one hour of processing before overdue.
+DELIVERY_GRACE_SECONDS = 25 * 60 * 60
+
+
+def _age(value: datetime | None, now: datetime) -> float:
+ if value is None:
+ return 0.0
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=timezone.utc) # legacy database UTC
+ return max(0.0, (now - value).total_seconds())
+
+
+async def refresh_digest_operational_metrics(*, now: datetime | None = None) -> bool:
+ """Publish only a complete bounded snapshot; collect_bounded owns freshness.
+
+ Generation and provider completion are different persisted facts. Pending
+ claim receipts keep due work visible even after next_delivery_at advances,
+ across retries and worker replacement. No due work means measured zeros.
+ """
+ from app.db.postgres import AsyncSessionLocal
+ from app.models.postgres import DigestSubscription as Subscription
+
+ observed_at = now or datetime.now(timezone.utc)
+ if observed_at.tzinfo is None:
+ raise ValueError("digest observation time must include timezone")
+ observed_at = observed_at.astimezone(timezone.utc)
+ due = func.coalesce(Subscription.pending_delivery_since_at, Subscription.next_delivery_at)
+ outcome = func.coalesce(Subscription.last_delivery_outcome, "not_observed")
+ statement = select(
+ Subscription.schedule, outcome.label("outcome"), func.count(),
+ func.sum(case((due <= observed_at, 1), else_=0)),
+ func.sum(case((Subscription.pending_delivery_since_at.is_not(None), 1), else_=0)),
+ func.sum(case((Subscription.last_delivered_at.is_(None), 1), else_=0)),
+ func.sum(case((due.is_(None), 1), else_=0)),
+ func.min(due),
+ ).where(
+ Subscription.schedule.in_(SCHEDULES), Subscription.is_active.is_(True),
+ Subscription.is_paused.is_(False),
+ ).group_by(Subscription.schedule, outcome)
+ async with AsyncSessionLocal() as db:
+ rows = (await db.execute(statement)).all()
+
+ snapshot = {schedule: {state: 0 for state in STATES} for schedule in SCHEDULES}
+ outcomes = {(schedule, state): 0 for schedule in SCHEDULES for state in OUTCOMES}
+ overdue = dict.fromkeys(SCHEDULES, 0.0)
+ for schedule, state, count, due_count, unresolved, never, missing, oldest in rows:
+ if schedule not in SCHEDULES or state not in OUTCOMES:
+ raise ValueError("unknown digest observation state")
+ outcomes[(schedule, state)] += count
+ for name, value in zip(STATES, (count, due_count, unresolved, never, missing)):
+ snapshot[schedule][name] += int(value)
+ overdue[schedule] = max(overdue[schedule], _age(oldest, observed_at) - DELIVERY_GRACE_SECONDS)
+ for schedule in SCHEDULES:
+ for state in STATES:
+ weekly_digest_subscriptions.labels(schedule=schedule, state=state).set(snapshot[schedule][state])
+ weekly_digest_oldest_overdue_seconds.labels(schedule=schedule).set(overdue[schedule])
+ for state in OUTCOMES:
+ weekly_digest_delivery_outcomes.labels(schedule=schedule, outcome=state).set(outcomes[(schedule, state)])
+ return True
diff --git a/backend/app/services/feature_flags.py b/backend/app/services/feature_flags.py
index e5a51a781..a881197d2 100644
--- a/backend/app/services/feature_flags.py
+++ b/backend/app/services/feature_flags.py
@@ -356,6 +356,12 @@ async def create_flag(
# audit row below can reference them and the response serialization
# below sees the fully-hydrated row. Router owns the commit.
await db.flush()
+ from app.services.nightly_job_observation import stage_nightly_activation
+
+ await stage_nightly_activation(
+ db, key, was_enabled=False,
+ is_enabled=flag.enabled_global and flag.rollout_percent > 0, at=flag.updated_at,
+ )
_write_audit_entry(db, actor, action="create", key=key, after=_serialize_flag(flag), reason=reason)
return flag
@@ -395,6 +401,12 @@ async def update_flag(
flag.updated_by_user_id = actor.id
flag.updated_at = datetime.now(timezone.utc)
await db.flush()
+ from app.services.nightly_job_observation import stage_nightly_activation
+
+ await stage_nightly_activation(
+ db, key, was_enabled=bool(before["enabled_global"] and before["rollout_percent"] > 0),
+ is_enabled=flag.enabled_global and flag.rollout_percent > 0, at=flag.updated_at,
+ )
_write_audit_entry(
db, actor, action="update", key=key, before=before, after=_serialize_flag(flag), reason=reason,
)
diff --git a/backend/app/services/metric_collection.py b/backend/app/services/metric_collection.py
index 1d40ec3dd..ff3805b4d 100644
--- a/backend/app/services/metric_collection.py
+++ b/backend/app/services/metric_collection.py
@@ -17,7 +17,7 @@
logger = structlog.get_logger(__name__)
COLLECTION_TIMEOUT_SECONDS = 1.0
-COLLECTORS = ("queues", "agents", "downstream", "redis")
+COLLECTORS = ("queues", "agents", "downstream", "redis", "nightly", "digests")
@dataclass
diff --git a/backend/app/services/nightly_job_observation.py b/backend/app/services/nightly_job_observation.py
new file mode 100644
index 000000000..a4d0ae653
--- /dev/null
+++ b/backend/app/services/nightly_job_observation.py
@@ -0,0 +1,151 @@
+"""Durable worker observations and read-only API scrape snapshots."""
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from datetime import datetime, timedelta, timezone
+from typing import Any
+
+from sqlalchemy import and_, case, or_, select, update
+from sqlalchemy.ext.asyncio import AsyncSession
+import structlog
+
+from app.worker.nightly_schedule import (
+ NIGHTLY_SCHEDULES, NIGHTLY_SUCCESS_GRACE, NightlySchedule, latest_due, read_nightly_slot,
+)
+
+logger = structlog.get_logger(__name__)
+
+
+async def stage_nightly_activation(
+ db: AsyncSession, flag_key: str, *, was_enabled: bool, is_enabled: bool, at: datetime,
+) -> None:
+ """Stage a true off-to-on transition in the feature flag transaction."""
+ if was_enabled or not is_enabled:
+ return
+ for schedule in NIGHTLY_SCHEDULES:
+ if schedule.flag == flag_key:
+ from app.models.postgres import NightlyJobObservation as Observation
+
+ await db.execute(
+ update(Observation).where(Observation.schedule_key == schedule.key).values(enabled_since=at)
+ )
+ return
+
+
+async def _record_attempt(schedule: NightlySchedule, slot: datetime, started: datetime) -> bool:
+ from app.db.postgres import AsyncSessionLocal
+ from app.models.postgres import NightlyJobObservation as Observation
+ from app.services.feature_flags import is_enabled
+
+ async with AsyncSessionLocal() as db:
+ enabled = await is_enabled(schedule.flag, db=db, any_scope=True)
+ await db.execute(
+ update(Observation).where(
+ Observation.schedule_key == schedule.key,
+ or_(
+ Observation.last_attempt_slot_at.is_(None),
+ Observation.last_attempt_slot_at < slot,
+ and_(Observation.last_attempt_slot_at == slot, Observation.last_attempt_started_at < started),
+ ),
+ ).values(last_attempt_slot_at=slot, last_attempt_started_at=started)
+ )
+ await db.commit()
+ return enabled
+
+
+async def _record_success(schedule: NightlySchedule, slot: datetime, finished: datetime) -> None:
+ from app.db.postgres import AsyncSessionLocal
+ from app.models.postgres import NightlyJobObservation as Observation
+
+ async with AsyncSessionLocal() as db:
+ await db.execute(
+ update(Observation).where(
+ Observation.schedule_key == schedule.key,
+ or_(
+ Observation.last_success_slot_at.is_(None),
+ Observation.last_success_slot_at < slot,
+ and_(Observation.last_success_slot_at == slot, Observation.last_success_finished_at < finished),
+ ),
+ ).values(last_success_slot_at=slot, last_success_finished_at=finished)
+ )
+ await db.commit()
+
+
+async def observe_nightly_job(
+ schedule: NightlySchedule,
+ headers: object,
+ operation: Callable[[], Awaitable[dict[str, Any]]],
+) -> dict[str, Any]:
+ """Preserve the job's outcome even if its observation cannot be persisted."""
+ started = datetime.now(timezone.utc)
+ slot = read_nightly_slot(schedule, headers, started)
+ enabled = False
+ if slot is not None:
+ try:
+ enabled = await _record_attempt(schedule, slot, started)
+ except Exception as exc: # noqa: BLE001 -- a failed observation must not stop maintenance
+ logger.warning("nightly_job_attempt_record_failed", schedule=schedule.key, error_type=type(exc).__name__)
+ result = await operation()
+ if slot is not None and enabled and not result.get("skipped"):
+ try:
+ await _record_success(schedule, slot, datetime.now(timezone.utc))
+ except Exception as exc: # noqa: BLE001 -- preserve a completed job's result
+ logger.warning("nightly_job_success_record_failed", schedule=schedule.key, error_type=type(exc).__name__)
+ return result
+
+
+def _utc(value: datetime) -> datetime:
+ # Some test/embedded database drivers return naive UTC timestamps.
+ return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value.astimezone(timezone.utc)
+
+
+def _metric_timestamp(value: datetime | None) -> float:
+ return _utc(value).timestamp() if value is not None else 0.0
+
+
+async def refresh_nightly_job_metrics(*, now: datetime | None = None) -> bool:
+ """Compute schedule expectations from SQL-backed history and flag state."""
+ from app.core.metrics import (
+ nightly_job_enabled, nightly_job_last_attempt_timestamp, nightly_job_last_success_timestamp,
+ nightly_job_next_due_timestamp, nightly_job_overdue, nightly_job_started_overdue_slot,
+ )
+ from app.db.postgres import AsyncSessionLocal
+ from app.models.postgres import FeatureFlag, NightlyJobObservation as Observation
+
+ observed_at = _utc(now) if now is not None else datetime.now(timezone.utc)
+ flag_by_schedule = case({schedule.key: schedule.flag for schedule in NIGHTLY_SCHEDULES}, value=Observation.schedule_key)
+ async with AsyncSessionLocal() as db:
+ rows = (await db.execute(
+ select(Observation, FeatureFlag.enabled_global, FeatureFlag.rollout_percent)
+ .outerjoin(FeatureFlag, FeatureFlag.key == flag_by_schedule)
+ .where(Observation.schedule_key.in_([schedule.key for schedule in NIGHTLY_SCHEDULES]))
+ )).all()
+
+ observations = {row.schedule_key: (row, bool(on and rollout and rollout > 0)) for row, on, rollout in rows}
+ if any(schedule.key not in observations for schedule in NIGHTLY_SCHEDULES):
+ raise RuntimeError("nightly job observation rows are missing")
+
+ for schedule in NIGHTLY_SCHEDULES:
+ state, enabled = observations[schedule.key]
+ active_since = _utc(state.monitoring_since)
+ if state.enabled_since is not None:
+ active_since = max(active_since, _utc(state.enabled_since))
+ # Keep yesterday's unresolved deadline visible through today's grace
+ # window, and only compare outcomes for the actual broker-stamped slot.
+ deadline_slot = latest_due(schedule, observed_at - NIGHTLY_SUCCESS_GRACE)
+ success_slot = state.last_success_slot_at
+ overdue = enabled and deadline_slot >= active_since and (
+ success_slot is None or _utc(success_slot) < deadline_slot
+ )
+ attempt_slot = state.last_attempt_slot_at
+ started = overdue and attempt_slot is not None and _utc(attempt_slot) >= deadline_slot
+ labels = {"schedule": schedule.key}
+ nightly_job_enabled.labels(**labels).set(int(enabled))
+ nightly_job_next_due_timestamp.labels(**labels).set(
+ (latest_due(schedule, observed_at) + timedelta(days=1)).timestamp() if enabled else 0
+ )
+ nightly_job_last_attempt_timestamp.labels(**labels).set(_metric_timestamp(state.last_attempt_started_at))
+ nightly_job_last_success_timestamp.labels(**labels).set(_metric_timestamp(state.last_success_finished_at))
+ nightly_job_overdue.labels(**labels).set(int(overdue))
+ nightly_job_started_overdue_slot.labels(**labels).set(int(started))
+ return True
diff --git a/backend/app/worker/celery_app.py b/backend/app/worker/celery_app.py
index 1e5a430f7..02e161ab6 100644
--- a/backend/app/worker/celery_app.py
+++ b/backend/app/worker/celery_app.py
@@ -6,6 +6,7 @@
from celery import Celery, Task
from celery.signals import (
+ before_task_publish,
celeryd_init,
setup_logging,
task_postrun,
@@ -19,6 +20,9 @@
from kombu import Exchange, Queue
from app.core.config import settings
+from app.worker.nightly_schedule import (
+ PERF_BASELINE_REFRESH, QUARANTINE_MAINTENANCE, SCHEDULE_HEADER, stamp_nightly_slot,
+)
from app.worker.queue_inventory import (
AGENT_CHILDREN_QUEUE, AI_ANALYSIS_QUEUE, CRITICAL_QUEUE, DEFAULT_QUEUE,
INGESTION_QUEUE, all_task_queue_names,
@@ -52,6 +56,7 @@ def bind(cls, app):
include=["app.worker.tasks", "app.worker.training_tasks"],
task_cls=TimeLimitedTask,
)
+before_task_publish.connect(stamp_nightly_slot)
@celery_app.task(bind=True, name="app.worker.celery_app.queue_delivery_probe")
@@ -387,14 +392,16 @@ def _build_task_queues() -> tuple[Queue, ...]:
# No-op until the ``flaky_auto_quarantine`` feature flag is enabled.
"nightly-flaky-quarantine-maintenance": {
"task": "app.worker.tasks.run_flaky_quarantine_maintenance",
- "schedule": crontab(hour=4, minute=0),
+ "schedule": crontab(hour=QUARANTINE_MAINTENANCE.hour, minute=QUARANTINE_MAINTENANCE.minute),
+ "options": {"headers": {SCHEDULE_HEADER: QUARANTINE_MAINTENANCE.key}},
},
# Tier 2 item 10: per-test duration baseline refresh (nightly at
# 04:30 UTC, after quarantine maintenance so its reclassifications
# land first). No-op until ``perf_regression_detection`` flag is on.
"nightly-perf-baseline-refresh": {
"task": "app.worker.tasks.refresh_perf_baselines",
- "schedule": crontab(hour=4, minute=30),
+ "schedule": crontab(hour=PERF_BASELINE_REFRESH.hour, minute=PERF_BASELINE_REFRESH.minute),
+ "options": {"headers": {SCHEDULE_HEADER: PERF_BASELINE_REFRESH.key}},
},
# Tier 2 item 12: weekly auto-retro digest dispatch (Mondays
# 07:00 UTC, same time as the existing daily digest pass). The
diff --git a/backend/app/worker/nightly_schedule.py b/backend/app/worker/nightly_schedule.py
new file mode 100644
index 000000000..25ef0eb0c
--- /dev/null
+++ b/backend/app/worker/nightly_schedule.py
@@ -0,0 +1,50 @@
+"""UTC contracts shared by Beat, workers and schedule monitoring."""
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+
+
+@dataclass(frozen=True)
+class NightlySchedule:
+ key: str
+ task_name: str
+ flag: str
+ hour: int
+ minute: int
+
+
+QUARANTINE_MAINTENANCE = NightlySchedule(
+ "quarantine_maintenance", "app.worker.tasks.run_flaky_quarantine_maintenance", "flaky_auto_quarantine", 4, 0,
+)
+PERF_BASELINE_REFRESH = NightlySchedule(
+ "perf_baseline_refresh", "app.worker.tasks.refresh_perf_baselines", "perf_regression_detection", 4, 30,
+)
+NIGHTLY_SCHEDULES = (QUARANTINE_MAINTENANCE, PERF_BASELINE_REFRESH)
+NIGHTLY_SUCCESS_GRACE = timedelta(hours=1)
+SCHEDULE_HEADER = "testlookup-nightly-schedule"
+SLOT_HEADER = "testlookup-nightly-slot"
+
+
+def latest_due(schedule: NightlySchedule, now: datetime) -> datetime:
+ now = now.astimezone(timezone.utc)
+ slot = now.replace(hour=schedule.hour, minute=schedule.minute, second=0, microsecond=0)
+ return slot if slot <= now else slot - timedelta(days=1)
+
+
+def stamp_nightly_slot(sender=None, headers=None, **_kwargs) -> None:
+ """Use the scheduled slot when publishing so queue delay cannot change it."""
+ if not isinstance(headers, dict) or SCHEDULE_HEADER not in headers or SLOT_HEADER in headers:
+ return
+ for schedule in NIGHTLY_SCHEDULES:
+ if sender == schedule.task_name and headers[SCHEDULE_HEADER] == schedule.key:
+ headers[SLOT_HEADER] = int(latest_due(schedule, datetime.now(timezone.utc)).timestamp())
+ return
+
+
+def read_nightly_slot(schedule: NightlySchedule, headers: object, now: datetime) -> datetime | None:
+ if not isinstance(headers, dict) or headers.get(SCHEDULE_HEADER) != schedule.key:
+ return None
+ stamp = headers.get(SLOT_HEADER)
+ if type(stamp) is not int or not 0 < stamp <= now.timestamp():
+ return None
+ slot = datetime.fromtimestamp(stamp, timezone.utc)
+ return slot if latest_due(schedule, slot) == slot else None
diff --git a/backend/app/worker/tasks.py b/backend/app/worker/tasks.py
index 6fb158cfa..4c59499c9 100644
--- a/backend/app/worker/tasks.py
+++ b/backend/app/worker/tasks.py
@@ -5141,7 +5141,10 @@ async def _run():
)
return out
- return cast(dict, _run_async(_run()))
+ from app.services.nightly_job_observation import observe_nightly_job
+ from app.worker.nightly_schedule import PERF_BASELINE_REFRESH
+
+ return cast(dict, _run_async(observe_nightly_job(PERF_BASELINE_REFRESH, self.request.headers, _run)))
# ── Outbound webhook delivery (Tier 2 item 6) ──────────────────────────────
@@ -5272,7 +5275,10 @@ async def _run():
**outcomes,
}
- return cast(dict[str, Any], _run_async(_run()))
+ from app.services.nightly_job_observation import observe_nightly_job
+ from app.worker.nightly_schedule import QUARANTINE_MAINTENANCE
+
+ return cast(dict[str, Any], _run_async(observe_nightly_job(QUARANTINE_MAINTENANCE, self.request.headers, _run)))
# ── FLK-P3: flaky-confidence model retraining ───────────────────────────────
@@ -5580,6 +5586,11 @@ async def _dispatch():
from app.db.postgres import AsyncSessionLocal
from app.models.postgres import DigestSubscription, NotificationLog, User
from app.services.digest_content_service import generate_digest, render_digest_html
+ from app.services.digest_delivery_observation import (
+ digest_claim_observation,
+ digest_final_observation,
+ observe_digest_phase,
+ )
from app.services.digest_scope_service import PROJECT_SCOPE, resolve_digest_scope
now = datetime.now(timezone.utc)
@@ -5635,6 +5646,7 @@ async def _dispatch():
saved_view_id,
saved_view_name,
) in due:
+ observation_token = uuid.uuid4()
delta = timedelta(days=1) if schedule == "DAILY" else timedelta(weeks=1)
scheduled_next = now + delta
period = "daily" if schedule == "DAILY" else "weekly"
@@ -5658,9 +5670,11 @@ async def _dispatch():
DigestSubscription.is_active.is_(True),
DigestSubscription.is_paused.is_(False),
DigestSubscription.next_delivery_at <= now,
+ DigestSubscription.schedule == schedule,
)
.values(
next_delivery_at=scheduled_next,
+ **digest_claim_observation(now=now, token=observation_token),
)
.returning(
DigestSubscription.user_id,
@@ -5676,9 +5690,8 @@ async def _dispatch():
continue
user_id, project_id, channel = claimed
- # Step 3: actually deliver. A failure here only affects the log
- # row — the claim is already persisted so we will not retry at
- # the next beat tick.
+ # Step 3: actually deliver. The pending-slot observation already
+ # committed with the claim; generation is not provider success.
status = "sent"
error_detail = None
scope = PROJECT_SCOPE
@@ -5719,6 +5732,16 @@ async def _dispatch():
with_release_verdict=True,
)
+ # Generation performs reads. Return that connection before
+ # the independent short phase-observation transaction so
+ # even a one-connection worker pool cannot deadlock itself.
+ from app.db.postgres import release_read_connection
+
+ if await release_read_connection(db):
+ await observe_digest_phase(
+ sub_id, observation_token, phase="generated",
+ )
+
user_result = await db.execute(
select(User).where(User.id == user_id)
)
@@ -5728,6 +5751,15 @@ async def _dispatch():
"Claimed subscription %s references missing user %s",
sub_id, user_id,
)
+ await db.execute(
+ update(DigestSubscription)
+ .where(
+ DigestSubscription.id == sub_id,
+ DigestSubscription.delivery_observation_token == observation_token,
+ )
+ .values(**digest_final_observation("skipped"))
+ )
+ await db.commit()
continue
# US-7.4: zero-change window + send_when_unchanged=False
@@ -5919,8 +5951,11 @@ async def _dispatch():
error_detail = str(e)
logger.warning(
"Digest %s delivery failed for sub %s: %s",
- channel, sub_id, e,
+ channel, sub_id, type(e).__name__,
)
+ else:
+ status = "failed"
+ error_detail = "Unsupported scheduled digest channel"
db.add(NotificationLog(
user_id=user_id,
@@ -5954,12 +5989,14 @@ async def _dispatch():
now=now,
scheduled_next=scheduled_next,
)
+ outcome.update(digest_final_observation(status))
increment_count = outcome.pop("increment_delivery_count", False)
if increment_count:
outcome["delivery_count"] = DigestSubscription.delivery_count + 1
if outcome:
final_update = update(DigestSubscription).where(
- DigestSubscription.id == sub_id
+ DigestSubscription.id == sub_id,
+ DigestSubscription.delivery_observation_token == observation_token,
)
# A failed delivery may shorten only the slot this
# attempt claimed. A concurrent pause/resume or schedule
@@ -5971,7 +6008,11 @@ async def _dispatch():
await db.execute(final_update.values(**outcome))
await db.commit()
except Exception as exc:
- logger.error("Digest delivery failed for subscription %s: %s", sub_id, exc)
+ # A provider may have accepted before a later transaction
+ # failed. Keep its slot unresolved; never infer success or
+ # automatically replay an ambiguous outcome from telemetry.
+ await observe_digest_phase(sub_id, observation_token, phase="unknown")
+ logger.error("Digest delivery failed for subscription %s: %s", sub_id, type(exc).__name__)
with _beat_span("dispatch_scheduled_digests") as span:
try:
diff --git a/backend/migrations/versions/0261_nightly_job_observations.py b/backend/migrations/versions/0261_nightly_job_observations.py
new file mode 100644
index 000000000..f5f6e2419
--- /dev/null
+++ b/backend/migrations/versions/0261_nightly_job_observations.py
@@ -0,0 +1,34 @@
+"""Persist the latest observed attempt and success of two nightly jobs.
+
+The seeded monitoring boundary prevents pre-upgrade history from being
+reported as missed work. Older worker logs and counters are not backfilled.
+
+Revision ID: 0261
+Revises: 0260
+"""
+
+from alembic import op
+import sqlalchemy as sa
+
+revision = "0261"
+down_revision = "0260"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ table = op.create_table(
+ "nightly_job_observations",
+ sa.Column("schedule_key", sa.String(64), primary_key=True),
+ sa.Column("monitoring_since", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
+ sa.Column("enabled_since", sa.DateTime(timezone=True), nullable=True),
+ sa.Column("last_attempt_slot_at", sa.DateTime(timezone=True), nullable=True),
+ sa.Column("last_attempt_started_at", sa.DateTime(timezone=True), nullable=True),
+ sa.Column("last_success_slot_at", sa.DateTime(timezone=True), nullable=True),
+ sa.Column("last_success_finished_at", sa.DateTime(timezone=True), nullable=True),
+ )
+ op.bulk_insert(table, [{"schedule_key": "quarantine_maintenance"}, {"schedule_key": "perf_baseline_refresh"}])
+
+
+def downgrade() -> None:
+ op.drop_table("nightly_job_observations")
diff --git a/backend/migrations/versions/0262_digest_delivery_observations.py b/backend/migrations/versions/0262_digest_delivery_observations.py
new file mode 100644
index 000000000..324204b4c
--- /dev/null
+++ b/backend/migrations/versions/0262_digest_delivery_observations.py
@@ -0,0 +1,36 @@
+"""Preserve scheduled digest due work independently of its dispatch claim.
+
+Five nullable observation fields; no delivery is replayed or marked successful
+by this migration. Historical claimed-but-unfinished work cannot be inferred
+from a future next_delivery_at, so there is deliberately no invented backfill.
+
+Revision ID: 0262
+Revises: 0261
+"""
+from alembic import op
+import sqlalchemy as sa
+from sqlalchemy.dialects.postgresql import UUID
+
+revision = "0262"
+down_revision = "0261"
+branch_labels = None
+depends_on = None
+
+TABLE = "digest_subscriptions"
+COLUMNS = (
+ ("pending_delivery_since_at", sa.DateTime(timezone=True)),
+ ("delivery_observation_token", UUID(as_uuid=True)),
+ ("last_delivery_attempt_at", sa.DateTime(timezone=True)),
+ ("last_content_generated_at", sa.DateTime(timezone=True)),
+ ("last_delivery_outcome", sa.String(20)),
+)
+
+
+def upgrade() -> None:
+ for name, column_type in COLUMNS:
+ op.add_column(TABLE, sa.Column(name, column_type, nullable=True))
+
+
+def downgrade() -> None:
+ for name, _ in reversed(COLUMNS):
+ op.drop_column(TABLE, name)
diff --git a/backend/tests/integration/test_nightly_job_observation_postgres.py b/backend/tests/integration/test_nightly_job_observation_postgres.py
new file mode 100644
index 000000000..7eb325534
--- /dev/null
+++ b/backend/tests/integration/test_nightly_job_observation_postgres.py
@@ -0,0 +1,59 @@
+"""Concurrent worker observations against an explicitly disposable PostgreSQL."""
+import asyncio
+import os
+import uuid
+from datetime import datetime, timedelta, timezone
+from unittest.mock import AsyncMock
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.db import postgres
+from app.models.postgres import NightlyJobObservation
+from app.services import feature_flags, nightly_job_observation as observations
+from app.worker.nightly_schedule import QUARANTINE_MAINTENANCE
+
+
+@pytest.mark.integration
+@pytest.mark.asyncio
+async def test_concurrent_older_delivery_cannot_overwrite_the_newer_slot(monkeypatch):
+ dsn = os.getenv("TESTLOOKUP_POSTGRES_TEST_DSN")
+ if not dsn:
+ pytest.skip("requires a disposable PostgreSQL DSN")
+ schema = f"nightly_fixture_{uuid.uuid4().hex}"
+ admin = create_async_engine(dsn)
+ engine = create_async_engine(dsn, connect_args={"server_settings": {"search_path": schema}})
+ schedule = QUARANTINE_MAINTENANCE
+ latest = datetime(2026, 10, 8, 4, 0, tzinfo=timezone.utc)
+ older = latest - timedelta(days=1)
+ factory = async_sessionmaker(engine)
+ monkeypatch.setattr(postgres, "AsyncSessionLocal", factory)
+ monkeypatch.setattr(feature_flags, "is_enabled", AsyncMock(return_value=True))
+
+ try:
+ async with admin.begin() as db:
+ await db.execute(text(f"CREATE SCHEMA {schema}"))
+ async with engine.begin() as db:
+ await db.run_sync(NightlyJobObservation.__table__.create)
+ async with factory.begin() as db:
+ db.add(NightlyJobObservation(schedule_key=schedule.key, monitoring_since=older))
+
+ async def worker(slot, observed_at):
+ await observations._record_attempt(schedule, slot, observed_at)
+ await observations._record_success(schedule, slot, observed_at + timedelta(minutes=1))
+
+ await asyncio.gather(
+ worker(latest, latest + timedelta(minutes=5)),
+ worker(older, latest + timedelta(minutes=6)),
+ )
+ async with factory() as db:
+ record = await db.get(NightlyJobObservation, schedule.key)
+ assert record.last_attempt_slot_at == latest
+ assert record.last_success_slot_at == latest
+ assert record.last_success_finished_at == latest + timedelta(minutes=6)
+ finally:
+ await engine.dispose()
+ async with admin.begin() as db:
+ await db.execute(text(f"DROP SCHEMA IF EXISTS {schema} CASCADE"))
+ await admin.dispose()
diff --git a/backend/tests/regression/test_alert_rules_are_deployable.py b/backend/tests/regression/test_alert_rules_are_deployable.py
index 4541146ca..f0a967ead 100644
--- a/backend/tests/regression/test_alert_rules_are_deployable.py
+++ b/backend/tests/regression/test_alert_rules_are_deployable.py
@@ -136,7 +136,9 @@ def test_the_rule_is_opt_in_not_in_base() -> None:
)
# The rule and the PodMonitors that feed it (QA-B45-P5); both need the
# Operator CRDs, so both stay out of base.
- assert kustomization["resources"] == ["prometheusrule.yaml", "podmonitors.yaml"]
+ assert kustomization["resources"] == [
+ "prometheusrule.yaml", "podmonitors.yaml", "telemetry-contract.yaml",
+ ]
base = yaml.safe_load((REPO_ROOT / "k8s" / "base" / "kustomization.yaml").read_text(encoding="utf-8"))
assert not any("monitoring" in str(r) or "prometheusrule" in str(r) for r in base["resources"])
@@ -147,17 +149,18 @@ def test_semantic_fixtures_execute_in_the_existing_backend_ci_job() -> None:
job = workflow["jobs"]["backend-test"]
step = next(s for s in job["steps"] if s.get("name") == "Verify alert semantics with checksum-pinned promtool")
assert not step.get("continue-on-error") and not step.get("if")
- assert step["working-directory"] == "infra/monitoring/tests"
+ assert step["working-directory"] == "."
compose = yaml.safe_load((REPO_ROOT / "docker-compose.monitoring.yml").read_text(encoding="utf-8"))
runtime_version = compose["services"]["prometheus"]["image"].rsplit(":", 1)[1].lstrip("v")
assert step["env"]["PROMETHEUS_VERSION"] == runtime_version
assert re.fullmatch(r"[0-9a-f]{64}", step["env"]["PROMETHEUS_ARCHIVE_SHA256"])
commands = step["run"]
assert commands.index("sha256sum --check --strict") < commands.index("tar -xzf")
- assert '"$tool" check rules ../prometheus-rules/testlookup-alerts.yml' in commands
- assert '"$tool" test rules ./*.yml' in commands
+ assert '"$tool" check rules "$monitoring/prometheus-rules/testlookup-alerts.yml"' in commands
+ assert '"$tool" test rules "$monitoring"/tests/*.yml' in commands
assert '"$tool" check config "$scratch/config/prometheus.yml"' in commands
- fixture = REPO_ROOT / step["working-directory"] / "operational-alerts.yml"
+ assert "python -m pytest scripts/monitoring/tests -q" in commands
+ fixture = REPO_ROOT / "infra/monitoring/tests/operational-alerts.yml"
assert not fixture.is_relative_to(ALERTS.parent), "fixture would be loaded as a production rule file"
data = yaml.safe_load(fixture.read_text(encoding="utf-8"))
assert data["tests"] and len(data["rule_files"]) == 1
diff --git a/backend/tests/regression/test_backup_alerts_and_scrape_targets.py b/backend/tests/regression/test_backup_alerts_and_scrape_targets.py
index 0fe0dfbad..221904d1a 100644
--- a/backend/tests/regression/test_backup_alerts_and_scrape_targets.py
+++ b/backend/tests/regression/test_backup_alerts_and_scrape_targets.py
@@ -452,7 +452,11 @@ def test_every_job_an_alert_selects_is_produced_by_a_monitor() -> None:
job for rule in _rules().values() for job in re.findall(r'(?Synthetic
")
+ monkeypatch.setattr(digest_scope_service, "resolve_digest_scope", AsyncMock(return_value=digest_scope_service.PROJECT_SCOPE))
+ monkeypatch.setattr(email_service, "get_smtp_config", AsyncMock(return_value={"enabled": True}))
+ monkeypatch.setattr(email_service, "send_html_email_with_attachments", send)
+ monkeypatch.setattr(manager, "digest_owner_block_reason", AsyncMock(return_value=None))
+ captured = []
+ monkeypatch.setattr(tasks, "_run_async", captured.append)
+
+ async def dispatch():
+ tasks.dispatch_scheduled_digests.run()
+ assert len(captured) == 1
+ await captured.pop()
+
+ async def create(**kwargs):
+ values = {
+ "id": uuid.uuid4(), "user_id": user_id, "project_id": project_id,
+ "name": "Synthetic subscription", "schedule": "WEEKLY", "channel": "email",
+ "next_delivery_at": datetime.now(timezone.utc) - timedelta(days=3),
+ "created_at": datetime.now(timezone.utc) - timedelta(days=10),
+ }
+ values.update(kwargs)
+ async with sessions() as db:
+ row = DigestSubscription(**values)
+ db.add(row)
+ await db.commit()
+ return row.id
+
+ async def read(identifier):
+ async with sessions() as db:
+ return await db.get(DigestSubscription, identifier)
+
+ yield SimpleNamespace(
+ sessions=sessions, create=create, read=read, dispatch=dispatch,
+ send=send, generate=generate, logs=logs, manager=manager,
+ )
+ for coroutine in captured:
+ coroutine.close()
+ await engine.dispose()
+
+
+@pytest.mark.asyncio
+async def test_generated_content_provider_failure_and_later_success_are_distinct(world):
+ identifier = await world.create()
+ initial = await world.read(identifier)
+
+ async def failed_provider(**_kwargs):
+ persisted = await world.read(identifier)
+ assert persisted.last_delivery_outcome == "generated"
+ assert persisted.last_content_generated_at is not None
+ assert persisted.last_delivered_at is None
+ raise RuntimeError("synthetic provider refused")
+
+ world.send.side_effect = failed_provider
+ await world.dispatch()
+ failed = await world.read(identifier)
+ assert failed.last_delivery_outcome == "failed"
+ assert failed.last_delivered_at is None and failed.delivery_count == 0
+ assert _utc(failed.pending_delivery_since_at) == _utc(initial.next_delivery_at)
+ assert failed.delivery_observation_token is None
+ await refresh_digest_operational_metrics()
+ assert _sample("delivery_outcomes", outcome="failed") == 1
+ assert _sample("oldest_overdue_seconds") > 0
+
+ # Simulate the next legitimate due retry; the oldest unresolved slot stays.
+ async with world.sessions() as db:
+ await db.execute(update(DigestSubscription).where(DigestSubscription.id == identifier).values(
+ next_delivery_at=datetime.now(timezone.utc) - timedelta(seconds=1)
+ ))
+ await db.commit()
+ world.send.side_effect = None
+ await world.dispatch()
+ sent = await world.read(identifier)
+ assert sent.last_delivery_outcome == "sent"
+ assert sent.last_delivered_at is not None and sent.delivery_count == 1
+ assert sent.pending_delivery_since_at is None
+ await refresh_digest_operational_metrics()
+ assert _sample("oldest_overdue_seconds") == 0
+ assert _sample("delivery_outcomes", outcome="sent") == 1
+ assert [row.status for row in world.logs] == ["failed", "sent"]
+
+
+@pytest.mark.asyncio
+async def test_claim_then_worker_loss_survives_future_next_slot_and_new_collection(world):
+ identifier = await world.create()
+ original = await world.read(identifier)
+ world.generate.side_effect = asyncio.CancelledError()
+ with pytest.raises(asyncio.CancelledError):
+ await world.dispatch()
+ receipt = await world.read(identifier)
+ assert _utc(receipt.next_delivery_at) > datetime.now(timezone.utc)
+ assert _utc(receipt.pending_delivery_since_at) == _utc(original.next_delivery_at)
+ assert receipt.last_delivery_outcome == "generating"
+ assert receipt.delivery_observation_token is not None
+ assert receipt.last_delivered_at is None
+ world.send.assert_not_awaited()
+ await refresh_digest_operational_metrics()
+ assert _sample("subscriptions", state="unresolved") == 1
+ assert _sample("subscriptions", state="due") == 1
+ assert _sample("oldest_overdue_seconds") > 0
+
+
+@pytest.mark.asyncio
+async def test_generation_error_is_unknown_unresolved_without_delivery_success(world):
+ identifier = await world.create()
+ world.generate.side_effect = RuntimeError("synthetic generation failure")
+ await world.dispatch()
+ receipt = await world.read(identifier)
+ assert receipt.last_delivery_outcome == "unknown"
+ assert receipt.pending_delivery_since_at is not None
+ assert receipt.last_content_generated_at is None
+ assert receipt.last_delivered_at is None and receipt.delivery_count == 0
+ world.send.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_intentional_no_change_skip_resolves_due_slot_without_claiming_delivery(world):
+ identifier = await world.create(send_when_unchanged=False)
+ world.generate.return_value = {"project_name": "Synthetic", "is_zero_change": True}
+ await world.dispatch()
+ skipped = await world.read(identifier)
+ assert skipped.last_delivery_outcome == "skipped"
+ assert skipped.pending_delivery_since_at is None
+ assert skipped.last_delivered_at is None and skipped.delivery_count == 0
+ world.send.assert_not_awaited()
+ await refresh_digest_operational_metrics()
+ assert _sample("oldest_overdue_seconds") == 0
+ assert _sample("delivery_outcomes", outcome="skipped") == 1
+
+
+@pytest.mark.asyncio
+async def test_owner_authorization_skip_never_counts_a_provider_delivery(world, monkeypatch):
+ identifier = await world.create()
+ monkeypatch.setattr(world.manager, "digest_owner_block_reason", AsyncMock(return_value="synthetic access revoked"))
+ await world.dispatch()
+ row = await world.read(identifier)
+ assert row.last_delivery_outcome == "skipped" and row.pending_delivery_since_at is None
+ assert row.last_delivered_at is None and row.delivery_count == 0
+ world.send.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_unsupported_legacy_channel_cannot_be_recorded_as_sent(world):
+ identifier = await world.create(channel="invalid")
+ await world.dispatch()
+ row = await world.read(identifier)
+ assert row.last_delivery_outcome == "failed" and row.pending_delivery_since_at is not None
+ assert row.last_delivered_at is None and row.delivery_count == 0
+ world.send.assert_not_awaited()
+
+
+@pytest.mark.asyncio
+async def test_stale_provider_completion_cannot_clear_a_new_claim(world):
+ identifier = await world.create()
+ newer_token = uuid.uuid4()
+ newer_due = datetime.now(timezone.utc) - timedelta(hours=1)
+
+ async def completed_after_new_claim(**_kwargs):
+ async with world.sessions() as db:
+ await db.execute(update(DigestSubscription).where(DigestSubscription.id == identifier).values(
+ delivery_observation_token=newer_token, pending_delivery_since_at=newer_due,
+ last_delivery_outcome="generating",
+ ))
+ await db.commit()
+
+ world.send.side_effect = completed_after_new_claim
+ await world.dispatch()
+ row = await world.read(identifier)
+ assert row.delivery_observation_token == newer_token
+ assert _utc(row.pending_delivery_since_at) == newer_due
+ assert row.last_delivery_outcome == "generating"
+ # The old provider acceptance remains an honest sent NotificationLog,
+ # while it cannot settle the new subscription slot or overwrite its state.
+ assert [log.status for log in world.logs] == ["sent"]
+
+
+@pytest.mark.asyncio
+async def test_optional_phase_observation_failure_does_not_gate_provider(world, monkeypatch):
+ identifier = await world.create()
+ monkeypatch.setattr("app.services.digest_delivery_observation.observe_digest_phase", AsyncMock(return_value=False))
+ await world.dispatch()
+ row = await world.read(identifier)
+ world.send.assert_awaited_once()
+ assert row.last_delivery_outcome == "sent" and row.delivery_count == 1
+ assert row.pending_delivery_since_at is None
+
+
+@pytest.mark.asyncio
+async def test_cas_rejects_stale_generation_and_completion_after_new_schedule(world):
+ old_token, new_token = uuid.uuid4(), uuid.uuid4()
+ identifier = await world.create(delivery_observation_token=new_token, last_delivery_outcome="generating")
+ assert await observe_digest_phase(identifier, old_token, phase="generated") is False
+ assert await observe_digest_phase(identifier, old_token, phase="skipped") is False
+ current = await world.read(identifier)
+ assert current.delivery_observation_token == new_token
+ assert current.last_content_generated_at is None
+ assert await observe_digest_phase(identifier, new_token, phase="generated") is True
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("weekday", range(7))
+async def test_due_work_is_weekday_independent_and_timezone_normalized(world, weekday):
+ # The first of November 2026 is Sunday, so this covers every due weekday.
+ due = datetime(2026, 11, 1 + weekday, 11, 0, tzinfo=timezone.utc)
+ await world.create(next_delivery_at=due)
+ now = due + timedelta(seconds=DELIVERY_GRACE_SECONDS + 17)
+ await refresh_digest_operational_metrics(now=now.astimezone(timezone(timedelta(hours=-7))))
+ assert _sample("subscriptions", state="due") == 1
+ assert _sample("subscriptions", state="never_delivered") == 1
+ assert _sample("oldest_overdue_seconds") == 17
+
+
+@pytest.mark.asyncio
+async def test_normal_daily_dispatch_lag_is_not_overdue(world):
+ due = datetime(2026, 11, 4, 7, 1, tzinfo=timezone.utc)
+ await world.create(next_delivery_at=due)
+ await refresh_digest_operational_metrics(now=due + timedelta(hours=24, minutes=59))
+ assert _sample("subscriptions", state="due") == 1
+ assert _sample("oldest_overdue_seconds") == 0
+
+
+@pytest.mark.asyncio
+async def test_no_active_subscriptions_is_measured_zero_and_missing_schedule_is_explicit(world):
+ await world.create(is_active=False)
+ await world.create(is_paused=True)
+ await world.create(schedule="DAILY")
+ await refresh_digest_operational_metrics()
+ for schedule in ("WEEKLY", "WEEKLY_RETRO"):
+ assert _sample("subscriptions", schedule=schedule, state="enabled") == 0
+ assert _sample("oldest_overdue_seconds", schedule=schedule) == 0
+ await world.create(schedule="WEEKLY_RETRO", next_delivery_at=None)
+ await refresh_digest_operational_metrics()
+ assert _sample("subscriptions", schedule="WEEKLY_RETRO", state="enabled") == 1
+ assert _sample("subscriptions", schedule="WEEKLY_RETRO", state="missing_schedule") == 1
+ assert _sample("oldest_overdue_seconds", schedule="WEEKLY_RETRO") == 0
+
+
+@pytest.mark.asyncio
+async def test_unknown_durable_outcome_fails_collection_instead_of_healthy_zero(world):
+ await world.create(last_delivery_outcome="invalid")
+ with pytest.raises(ValueError, match="unknown digest"):
+ await refresh_digest_operational_metrics()
+
+
+def test_schedule_reset_invalidates_attempt_but_preserves_real_success_history():
+ history = datetime(2026, 11, 1, tzinfo=timezone.utc)
+ row = SimpleNamespace(pending_delivery_since_at=history, delivery_observation_token=uuid.uuid4(),
+ last_delivery_outcome="generated", last_delivered_at=history)
+ reset_digest_observation(row)
+ assert row.pending_delivery_since_at is None and row.delivery_observation_token is None
+ assert row.last_delivery_outcome is None and row.last_delivered_at == history
+ assert "pending_delivery_since_at" not in digest_final_observation("failed")
+
+
+def test_migration_is_nullable_additive_with_no_invented_historical_state():
+ path = Path(__file__).resolve().parents[2] / "migrations/versions/0262_digest_delivery_observations.py"
+ spec = importlib.util.spec_from_file_location("digest_migration_0262", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ assert module.revision == "0262" and module.down_revision == "0261"
+ module.op = MagicMock()
+ module.upgrade()
+ added = [call.args[1] for call in module.op.add_column.call_args_list]
+ assert len(added) == 5
+ for column in added:
+ actual = DigestSubscription.__table__.c[column.name]
+ assert actual.nullable is True and column.nullable is True
+ assert column.server_default is None
+ module.op.execute.assert_not_called()
+ module.downgrade()
+ assert [call.args[1] for call in module.op.drop_column.call_args_list] == [c.name for c in reversed(added)]
+
+
+def test_migration_round_trip_preserves_existing_rows_without_inventing_success():
+ import sqlalchemy as sa
+ from alembic.migration import MigrationContext
+ from alembic.operations import Operations
+
+ path = Path(__file__).resolve().parents[2] / "migrations/versions/0262_digest_delivery_observations.py"
+ spec = importlib.util.spec_from_file_location("digest_migration_round_trip", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ engine = sa.create_engine("sqlite://")
+ try:
+ with engine.begin() as connection:
+ connection.exec_driver_sql(
+ "CREATE TABLE digest_subscriptions (id TEXT PRIMARY KEY, "
+ "next_delivery_at DATETIME, last_delivered_at DATETIME, delivery_count INTEGER)"
+ )
+ connection.exec_driver_sql(
+ "INSERT INTO digest_subscriptions VALUES "
+ "('synthetic', '2026-11-04 07:00:00', NULL, 7)"
+ )
+ module.op = Operations(MigrationContext.configure(connection))
+ module.upgrade()
+ row = connection.execute(sa.text("SELECT * FROM digest_subscriptions")).mappings().one()
+ assert row["delivery_count"] == 7 and row["last_delivered_at"] is None
+ assert row["next_delivery_at"] == "2026-11-04 07:00:00"
+ assert all(row[name] is None for name, _ in module.COLUMNS)
+ module.downgrade()
+ remaining = {column["name"] for column in sa.inspect(connection).get_columns("digest_subscriptions")}
+ assert remaining == {"id", "next_delivery_at", "last_delivered_at", "delivery_count"}
+ finally:
+ engine.dispose()
+
+
+@pytest.mark.asyncio
+async def test_retry_claim_preserves_original_slot_in_real_update(world):
+ original = datetime(2026, 10, 1, tzinfo=timezone.utc)
+ identifier = await world.create(pending_delivery_since_at=original)
+ token = uuid.uuid4()
+ async with world.sessions() as db:
+ await db.execute(update(DigestSubscription).where(DigestSubscription.id == identifier).values(
+ next_delivery_at=datetime.now(timezone.utc) + timedelta(days=7),
+ **digest_claim_observation(now=datetime.now(timezone.utc), token=token),
+ ))
+ await db.commit()
+ receipt = await world.read(identifier)
+ assert _utc(receipt.pending_delivery_since_at) == original
+ assert receipt.delivery_observation_token == token
diff --git a/backend/tests/regression/test_nightly_job_observation.py b/backend/tests/regression/test_nightly_job_observation.py
new file mode 100644
index 000000000..265983a9a
--- /dev/null
+++ b/backend/tests/regression/test_nightly_job_observation.py
@@ -0,0 +1,197 @@
+"""Scheduled maintenance evidence survives missing and out-of-order workers."""
+from datetime import datetime, timedelta, timezone
+from unittest.mock import AsyncMock
+
+import pytest
+import pytest_asyncio
+from sqlalchemy import text, update
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.core import metrics
+from app.db import postgres
+from app.models.postgres import NightlyJobObservation
+from app.services import feature_flags, nightly_job_observation as observations
+from app.worker.nightly_schedule import (
+ PERF_BASELINE_REFRESH, QUARANTINE_MAINTENANCE, SCHEDULE_HEADER, SLOT_HEADER, latest_due, read_nightly_slot,
+)
+
+SLOT = datetime(2026, 10, 8, 4, 0, tzinfo=timezone.utc)
+
+
+@pytest_asyncio.fixture
+async def session(monkeypatch):
+ engine = create_async_engine("sqlite+aiosqlite://")
+ factory = async_sessionmaker(engine)
+ monkeypatch.setattr(postgres, "AsyncSessionLocal", factory)
+ async with engine.begin() as db:
+ await db.run_sync(NightlyJobObservation.__table__.create)
+ await db.execute(text(
+ "CREATE TABLE feature_flags (key TEXT PRIMARY KEY, enabled_global BOOL, "
+ "rollout_percent INTEGER, updated_at DATETIME)"
+ ))
+ async with factory.begin() as db:
+ for schedule in (QUARANTINE_MAINTENANCE, PERF_BASELINE_REFRESH):
+ active_since = SLOT - timedelta(days=3)
+ db.add(NightlyJobObservation(schedule_key=schedule.key, monitoring_since=active_since))
+ await db.execute(
+ text("INSERT INTO feature_flags VALUES (:key, 1, 100, :updated)"),
+ {"key": schedule.flag, "updated": active_since},
+ )
+ monkeypatch.setattr(feature_flags, "is_enabled", AsyncMock(return_value=True))
+ try:
+ yield factory
+ finally:
+ await engine.dispose()
+
+
+def _quarantine_sample(metric):
+ return metric.labels(schedule=QUARANTINE_MAINTENANCE.key)._value.get()
+
+
+def test_beat_publishes_the_right_slot_and_manual_jobs_do_not_get_it():
+ from celery.signals import before_task_publish
+ from app.worker.celery_app import celery_app
+
+ schedule = QUARANTINE_MAINTENANCE
+ entry = celery_app.conf.beat_schedule["nightly-flaky-quarantine-maintenance"]
+ assert entry["task"] == schedule.task_name
+ assert entry["schedule"].hour == {4} and entry["schedule"].minute == {0}
+ headers = dict(entry["options"]["headers"])
+ before_task_publish.send(sender=schedule.task_name, headers=headers)
+ now = datetime.now(timezone.utc)
+ slot = read_nightly_slot(schedule, headers, now)
+ assert slot == latest_due(schedule, now)
+ # A queued message that waits until tomorrow still belongs to this slot.
+ assert read_nightly_slot(schedule, headers, now + timedelta(days=1)) == slot
+ manual = {}
+ before_task_publish.send(sender=schedule.task_name, headers=manual)
+ assert SLOT_HEADER not in manual
+ wrong_sender = {SCHEDULE_HEADER: schedule.key}
+ before_task_publish.send(sender=PERF_BASELINE_REFRESH.task_name, headers=wrong_sender)
+ assert SLOT_HEADER not in wrong_sender
+
+
+def test_celery_serializes_a_fresh_slot_per_dispatch(monkeypatch):
+ from kombu import Connection, Exchange, Producer, Queue
+ from app.worker import nightly_schedule
+ from app.worker.celery_app import celery_app
+
+ class Clock(datetime):
+ value = SLOT
+
+ @classmethod
+ def now(cls, tz=None):
+ return cls.value
+
+ monkeypatch.setattr(nightly_schedule, "datetime", Clock)
+ schedule = QUARANTINE_MAINTENANCE
+ entry = celery_app.conf.beat_schedule["nightly-flaky-quarantine-maintenance"]
+ headers = entry["options"]["headers"]
+ fixture = "nightly-slot-fixture"
+ queue = Queue(fixture, Exchange(fixture), routing_key=fixture)
+ with Connection("memory://") as broker:
+ consumer = queue(broker)
+ with Producer(broker) as producer:
+ for day in (0, 1):
+ Clock.value = SLOT + timedelta(days=day)
+ message = celery_app.amqp.create_task_message(f"nightly-fixture-{day}", schedule.task_name)
+ celery_app.amqp.send_task_message(producer, schedule.task_name, message, queue=queue, headers=headers)
+ delivered = consumer.get(no_ack=True)
+ assert delivered.headers[SLOT_HEADER] == int(Clock.value.timestamp())
+ assert SLOT_HEADER not in headers
+ consumer.delete()
+
+
+async def test_never_run_deadline_started_failure_and_recovery_across_sessions(session):
+ schedule = QUARANTINE_MAINTENANCE
+ # The prior slot succeeded. Before today's grace runs out no failure fires.
+ yesterday = SLOT - timedelta(days=1)
+ await observations._record_success(schedule, yesterday, yesterday + timedelta(minutes=10))
+ assert await observations.refresh_nightly_job_metrics(now=SLOT + timedelta(minutes=59))
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 0
+ assert _quarantine_sample(metrics.nightly_job_next_due_timestamp) == (SLOT + timedelta(days=1)).timestamp()
+
+ assert await observations.refresh_nightly_job_metrics(now=SLOT + timedelta(hours=1))
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 1
+ assert _quarantine_sample(metrics.nightly_job_started_overdue_slot) == 0
+ # Separate commit from a worker whose business operation failed. Merely
+ # starting a task must not satisfy the durable completion requirement.
+ await observations._record_attempt(schedule, SLOT, SLOT + timedelta(minutes=15))
+ await observations.refresh_nightly_job_metrics(now=SLOT + timedelta(hours=1, minutes=1))
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 1
+ assert _quarantine_sample(metrics.nightly_job_started_overdue_slot) == 1
+ assert _quarantine_sample(metrics.nightly_job_last_attempt_timestamp) == (SLOT + timedelta(minutes=15)).timestamp()
+
+ await observations._record_success(schedule, SLOT, SLOT + timedelta(hours=1, minutes=2))
+ # A delayed prior-day delivery cannot overwrite the newer success.
+ await observations._record_success(schedule, yesterday, SLOT + timedelta(hours=1, minutes=3))
+ await observations.refresh_nightly_job_metrics(now=SLOT + timedelta(hours=1, minutes=5))
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 0
+ assert _quarantine_sample(metrics.nightly_job_last_success_timestamp) == (SLOT + timedelta(hours=1, minutes=2)).timestamp()
+
+
+async def test_upgrade_boundary_and_disabled_flag_do_not_invent_missed_runs(session):
+ later = SLOT + timedelta(hours=2)
+ await observations.refresh_nightly_job_metrics(now=later)
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 1 # installed and never attempted
+ async with session.begin() as db:
+ await db.execute(
+ update(NightlyJobObservation).where(NightlyJobObservation.schedule_key == QUARANTINE_MAINTENANCE.key)
+ .values(monitoring_since=SLOT + timedelta(minutes=1))
+ )
+ await observations.refresh_nightly_job_metrics(now=later)
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 0
+ async with session.begin() as db:
+ await db.execute(text("UPDATE feature_flags SET rollout_percent = 0"))
+ await observations.refresh_nightly_job_metrics(now=later + timedelta(days=2))
+ assert _quarantine_sample(metrics.nightly_job_enabled) == 0
+ assert _quarantine_sample(metrics.nightly_job_next_due_timestamp) == 0
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 0
+
+
+async def test_metadata_edit_preserves_the_alert_and_reenablement_starts_a_new_window(session):
+ after_slot = SLOT + timedelta(hours=2)
+ async with session.begin() as db:
+ await db.execute(text("UPDATE feature_flags SET updated_at = :at"), {"at": after_slot})
+ await observations.stage_nightly_activation(
+ db, QUARANTINE_MAINTENANCE.flag, was_enabled=True, is_enabled=True, at=after_slot,
+ )
+ await observations.refresh_nightly_job_metrics(now=after_slot)
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 1
+
+ async with session.begin() as db:
+ await observations.stage_nightly_activation(
+ db, QUARANTINE_MAINTENANCE.flag, was_enabled=False, is_enabled=True, at=after_slot,
+ )
+ await observations.refresh_nightly_job_metrics(now=after_slot)
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 0
+ await observations.refresh_nightly_job_metrics(now=after_slot + timedelta(days=1))
+ assert _quarantine_sample(metrics.nightly_job_overdue) == 1
+
+
+async def test_disabled_skipped_and_failed_work_cannot_record_success(monkeypatch):
+ headers = {SCHEDULE_HEADER: QUARANTINE_MAINTENANCE.key, SLOT_HEADER: int(SLOT.timestamp())}
+ record = AsyncMock(return_value=False)
+ success = AsyncMock()
+ monkeypatch.setattr(observations, "_record_attempt", record)
+ monkeypatch.setattr(observations, "_record_success", success)
+
+ enabled_task = AsyncMock(return_value={"expired": 0})
+ await observations.observe_nightly_job(QUARANTINE_MAINTENANCE, headers, enabled_task)
+ enabled_task.assert_awaited_once()
+ record.return_value = True
+ skipped_task = AsyncMock(return_value={"skipped": 1})
+ await observations.observe_nightly_job(QUARANTINE_MAINTENANCE, headers, skipped_task)
+ failed_task = AsyncMock(side_effect=RuntimeError("synthetic maintenance failure"))
+ with pytest.raises(RuntimeError, match="synthetic maintenance failure"):
+ await observations.observe_nightly_job(QUARANTINE_MAINTENANCE, headers, failed_task)
+ success.assert_not_awaited()
+ assert record.await_count == 3
+
+
+async def test_missing_observation_store_does_not_break_the_job(monkeypatch):
+ headers = {SCHEDULE_HEADER: PERF_BASELINE_REFRESH.key, SLOT_HEADER: int((SLOT + timedelta(minutes=30)).timestamp())}
+ monkeypatch.setattr(observations, "_record_attempt", AsyncMock(side_effect=RuntimeError("synthetic disconnected store")))
+ worker = AsyncMock(return_value={"observed": 6})
+ assert await observations.observe_nightly_job(PERF_BASELINE_REFRESH, headers, worker) == {"observed": 6}
+ worker.assert_awaited_once()
diff --git a/backend/tests/regression/test_telemetry_contract.py b/backend/tests/regression/test_telemetry_contract.py
new file mode 100644
index 000000000..204c33e1a
--- /dev/null
+++ b/backend/tests/regression/test_telemetry_contract.py
@@ -0,0 +1,94 @@
+"""Default required telemetry is independent of scrape discovery and traffic."""
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import pytest
+import yaml
+
+ROOT = Path(__file__).resolve().parents[3]
+MONITORING = ROOT / "infra/monitoring"
+pytestmark = pytest.mark.skipif(not MONITORING.exists(), reason="infra absent")
+
+
+def load(path: Path) -> dict:
+ return yaml.safe_load(path.read_text(encoding="utf-8"))
+
+
+def records(document: dict) -> list[dict]:
+ return [rule for group in document["groups"] for rule in group["rules"] if "record" in rule]
+
+
+def test_compose_contract_matches_both_scrape_auth_profiles():
+ contract = records(load(MONITORING / "prometheus-rules/compose-telemetry-contract.yml"))
+ expected = {(r["labels"]["job"], r["labels"]["telemetry_role"]) for r in contract}
+ assert expected == {
+ ("testlookup-backend", "backend"),
+ ("testlookup-worker", "worker"),
+ ("testlookup-worker", "worker-children"),
+ }
+ assert len(contract) == len(expected)
+ assert all(r["expr"] == "vector(1)" for r in contract), "inventory must survive deleted scrape jobs"
+ assert all(r["labels"]["telemetry_profile"] == "compose" for r in contract)
+ main = load(MONITORING / "prometheus.yml")
+ assert "rules/*.yml" in main["rule_files"]
+ for source in ("backend-scrape.yml", "backend-scrape-authenticated.yml"):
+ jobs = main["scrape_configs"] + load(MONITORING / source)["scrape_configs"]
+ actual = {
+ (job["job_name"], config["labels"]["telemetry_role"])
+ for job in jobs for config in job["static_configs"]
+ if config.get("labels", {}).get("telemetry_profile") == "compose"
+ }
+ assert expected == actual
+
+
+def test_operator_contract_matches_rendered_worker_roles_and_target_labels():
+ directory = ROOT / "k8s/monitoring"
+ resource = load(directory / "telemetry-contract.yaml")
+ contract = records(resource["spec"])
+ deployments = []
+ for source in ("backend-deployment.yaml", "worker-deployments.yaml", "worker-children-deployment.yaml"):
+ deployments.extend(
+ d for d in yaml.safe_load_all((ROOT / "k8s/base" / source).read_text(encoding="utf-8"))
+ if d and d.get("kind") == "Deployment"
+ and d["spec"]["template"]["metadata"]["labels"].get("app.kubernetes.io/component") in {"api", "worker"}
+ )
+ expected_roles = {d["spec"]["template"]["metadata"]["labels"]["app"].removeprefix("testlookup-") for d in deployments}
+ assert len(contract) == len(expected_roles) == 6
+ assert {r["labels"]["telemetry_role"] for r in contract} == expected_roles
+ assert all(r["expr"] == "vector(1)" for r in contract)
+ assert all(r["labels"]["namespace"] == resource["metadata"]["namespace"] == "testlookup" for r in contract)
+ assert all(r["labels"]["telemetry_profile"] == "kubernetes" for r in contract)
+ monitors = list(yaml.safe_load_all((directory / "podmonitors.yaml").read_text(encoding="utf-8")))
+ for deployment in deployments:
+ labels = deployment["spec"]["template"]["metadata"]["labels"]
+ monitor, = (m for m in monitors if all(labels.get(k) == v for k, v in m["spec"]["selector"]["matchLabels"].items()))
+ output = {}
+ for relabel in monitor["spec"]["podMetricsEndpoints"][0]["relabelings"]:
+ sources = relabel.get("sourceLabels", [])
+ value = ";".join(labels["app"] if s == "__meta_kubernetes_pod_label_app" else "" for s in sources)
+ match = re.fullmatch(relabel.get("regex", "(.*)"), value)
+ if match:
+ output[relabel["targetLabel"]] = re.sub(r"\$(\d+)", lambda m: match.group(int(m[1])), relabel["replacement"])
+ role = labels["app"].removeprefix("testlookup-")
+ expected, = (r["labels"] for r in contract if r["labels"]["telemetry_role"] == role)
+ assert output == {k: v for k, v in expected.items() if k != "namespace"}
+ # A site's common labels apply to both PrometheusRules and both monitors.
+ resources = load(directory / "kustomization.yaml")["resources"]
+ assert "telemetry-contract.yaml" in resources
+ assert resource["metadata"]["labels"] == load(directory / "prometheusrule.yaml")["metadata"]["labels"]
+ assert monitors[0]["metadata"]["labels"].items() <= resource["metadata"]["labels"].items()
+
+
+def test_required_collectors_are_an_explicit_unconditional_baseline():
+ from app.services.metric_collection import COLLECTORS
+
+ document = load(MONITORING / "prometheus-rules/testlookup-alerts.yml")
+ collector_rule, = (r for r in records(document) if r["record"] == "testlookup:telemetry_required_collector")
+ baseline = set(re.findall(r'"collector", "([a-z_]+)"', collector_rule["expr"]))
+ assert baseline == {"queues", "agents", "downstream", "redis"}
+ assert baseline <= set(COLLECTORS), "a required collector must be initialized by the application"
+ # Later feature/profile-specific collectors require a deliberate contract
+ # decision; they are not automatically mandatory in every installation.
+ assert "up{job=\"testlookup-backend\"} == 1" in collector_rule["expr"]
diff --git a/backend/tests/test_digest_scope.py b/backend/tests/test_digest_scope.py
index 28a341001..ad3030f4d 100644
--- a/backend/tests/test_digest_scope.py
+++ b/backend/tests/test_digest_scope.py
@@ -576,6 +576,13 @@ def _dispatch(monkeypatch, *, schedule, saved_view_id, saved_view_name, view_ans
None, # the finalising UPDATE
]
monkeypatch.setattr(postgres, "AsyncSessionLocal", lambda: _ScriptedSession(world))
+ # These cases isolate saved-view scoping; real transactional phase/CAS
+ # observation is exercised in test_digest_delivery_observation.py.
+ monkeypatch.setattr(postgres, "release_read_connection", AsyncMock(return_value=True))
+ monkeypatch.setattr(
+ "app.services.digest_delivery_observation.observe_digest_phase",
+ AsyncMock(return_value=True),
+ )
async def _generate(db, project_id, period, *args, **kwargs):
world.generated.append(kwargs)
diff --git a/docker-compose.alerting.yml b/docker-compose.alerting.yml
new file mode 100644
index 000000000..f3f4a2b88
--- /dev/null
+++ b/docker-compose.alerting.yml
@@ -0,0 +1,70 @@
+# Explicit opt-in after docker-compose.monitoring.yml. Authentication overlay
+# docker-compose.monitoring-auth.yml can precede or follow this file.
+# Run scripts/monitoring/configure_alerting.py first; see alert-routing.md.
+services:
+ prometheus:
+ volumes:
+ - ${ALERTING_PROMETHEUS_CONFIG_SOURCE:?Set the validated generated Prometheus configuration path}:/etc/prometheus/prometheus.yml:ro
+ - ./infra/monitoring/alertmanager/telemetry-contract.yml:/etc/prometheus/alertmanager-contract.yml:ro
+
+ alertmanager-config-check:
+ image: docker.io/prom/alertmanager:v0.35.1@sha256:4e3d029e69c7f61dd53a2b31a3dc427a2b81736cffca185c0854075e07969e36
+ entrypoint: ["/bin/amtool"]
+ command: ["check-config", "/etc/alertmanager/alertmanager.yml"]
+ volumes:
+ - ./infra/monitoring/alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
+ secrets: &alertmanager-secrets
+ - source: alertmanager-incident-url
+ target: alertmanager-incident-url
+ - source: alertmanager-incident-token
+ target: alertmanager-incident-token
+ - source: alertmanager-watchdog-url
+ target: alertmanager-watchdog-url
+ - source: alertmanager-watchdog-token
+ target: alertmanager-watchdog-token
+ network_mode: none
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: [no-new-privileges:true]
+
+ alertmanager:
+ image: docker.io/prom/alertmanager:v0.35.1@sha256:4e3d029e69c7f61dd53a2b31a3dc427a2b81736cffca185c0854075e07969e36
+ restart: unless-stopped
+ command:
+ - --config.file=/etc/alertmanager/alertmanager.yml
+ - --storage.path=/alertmanager
+ - --data.retention=120h
+ - --cluster.listen-address=
+ - --web.listen-address=:9093
+ - --log.level=warn
+ volumes:
+ - ./infra/monitoring/alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml:ro
+ - alertmanager-data:/alertmanager
+ secrets: *alertmanager-secrets
+ networks: [testlookup_net]
+ # No host port: this API can create alerts and silences and reload config.
+ # Use a temporary authenticated operator tunnel when managing silences.
+ depends_on:
+ alertmanager-config-check:
+ condition: service_completed_successfully
+ healthcheck:
+ test: ["CMD", "wget", "-qO-", "http://localhost:9093/-/ready"]
+ interval: 20s
+ timeout: 5s
+ retries: 3
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: [no-new-privileges:true]
+
+volumes:
+ alertmanager-data:
+
+secrets:
+ alertmanager-incident-url:
+ file: ${ALERTMANAGER_INCIDENT_URL_SOURCE:?Set an HTTPS incident webhook URL file}
+ alertmanager-incident-token:
+ file: ${ALERTMANAGER_INCIDENT_TOKEN_SOURCE:?Set the incident webhook bearer token file}
+ alertmanager-watchdog-url:
+ file: ${ALERTMANAGER_WATCHDOG_URL_SOURCE:?Set an independent HTTPS heartbeat webhook URL file}
+ alertmanager-watchdog-token:
+ file: ${ALERTMANAGER_WATCHDOG_TOKEN_SOURCE:?Set the heartbeat webhook bearer token file}
diff --git a/docs/maintainers/observability-delivery.md b/docs/maintainers/observability-delivery.md
index a3bf57762..cd29720f2 100644
--- a/docs/maintainers/observability-delivery.md
+++ b/docs/maintainers/observability-delivery.md
@@ -18,7 +18,7 @@ Status meanings: **Open** is planned; **In progress** has partial implementation
|---|---|---|
| OBS-E01 | Safe correlated application telemetry | 1: privacy, errors, worker log context; 3: worker tracing and clients |
| OBS-E02 | Reliable metric collection | 1: bounded reads, queue coverage and SQL outcomes; 2: producers, exporters and access |
-| OBS-E03 | Alerting and scheduled detection | 1: low-volume webhook and new outcome rules; 2: schedules, discovery and routing |
+| OBS-E03 | Alerting and scheduled detection | 1: low-volume webhook and new outcome rules; 3: schedules, discovery and routing |
| OBS-E04 | Durable log and trace platform | 2: profile contract; 3: collection, storage, offline and BYO profiles |
| OBS-E05 | Durable operational and audit evidence | 2: event outbox/replay; 3: audit archive and retention |
| OBS-E06 | Objectives and capacity | 2: SLIs and series budget; 4: measured objectives, burn rates and capacity |
@@ -40,12 +40,12 @@ Status meanings: **Open** is planned; **In progress** has partial implementation
| OBS-E02-S04 | Wire dependency and host exporters by deployment profile | In progress |
| OBS-E02-S05 | Make authenticated scrapes work in reference profiles | Verification |
| OBS-E02-S06 | Detect durable downstream failure independently of Celery success | In progress |
-| OBS-E03-S01 | Make weekly digest alerts reflect actual due work and delivery | Open |
+| OBS-E03-S01 | Make weekly digest alerts reflect actual due work and delivery | Verification |
| OBS-E03-S02 | Detect low-volume terminal webhook failures correctly | Verification |
-| OBS-E03-S03 | Deliver routed firing and resolved notifications | Open |
-| OBS-E03-S04 | Observe durable expected-run and last-success state | Open |
-| OBS-E03-S05 | Detect missing targets and required telemetry | Open |
-| OBS-E03-S06 | Detect monitoring and notification path outages independently | Open |
+| OBS-E03-S03 | Deliver routed firing and resolved notifications | Verification |
+| OBS-E03-S04 | Observe durable expected-run and last-success state | Verification |
+| OBS-E03-S05 | Detect missing targets and required telemetry | Verification |
+| OBS-E03-S06 | Detect monitoring and notification path outages independently | In progress |
| OBS-E04-S01 | Define the production telemetry and ownership contract | Open |
| OBS-E04-S02 | Deploy bounded and secure log/trace collection | Open |
| OBS-E04-S03 | Provide central log search and working trace-to-log navigation | Open |
@@ -140,3 +140,19 @@ This iteration builds on `30edfba5` and advances four stories in OBS-E02.
Prometheus 3.16 scraped actual samples from an isolated candidate API, received 401 on a token mismatch and resumed scraping after rotation. The source and release Compose configurations and the K3s and OpenShift manifests rendered with the expected targets and mounts. The existing backend CI job checks the two mounted Prometheus configurations and runs all semantic rule fixtures using its checksum-verified binary.
The focused suite passed 354 tests with the repository-pinned metrics dependencies. Two PostgreSQL cases require a disposable database and run in the existing integration job. Promtool validated 39 rules and 19 semantic fixture groups. In a separate Linux process test, removing the gauge from a killed child preserved the live child's gauge and both counters.
+
+## Iteration 3: alerting and scheduled detection
+
+This iteration builds on `a84edf88`. It extends the existing profile monitoring and alert evaluation without adding a CI job.
+
+| Story | Change | Remaining acceptance |
+|---|---|---|
+| OBS-E03-S01 | The digest claim records its unresolved slot, and the worker tracks generation, skipped work, provider success and ambiguous completion separately. The weekly alerts cover real subscription due dates and ignore inactive or paused subscriptions. | Apply migration 0262 and demonstrate failure, overdue detection and delivery recovery using isolated subscriptions. |
+| OBS-E03-S03 | The optional Compose Alertmanager profile uses pinned images, private mounts, and explicitly configured HTTPS incident and watchdog receivers. An existing Kubernetes Alertmanager can reuse the contract. | Verify deployed mounts and receiver routing, finish rule ownership and runbook links, and perform an on-call handoff. See [alert routing](../operations/alert-routing.md). |
+| OBS-E03-S04 | Beat stamps the UTC slot into nightly messages. Workers persist attempts and successful outcomes in a shared SQL table. Rules alert on missed enabled deadlines across worker replacements. | Apply migration 0261 and exercise missed dispatch and recovery in a deployment. See [scheduled maintenance](../operations/scheduled-maintenance.md). |
+| OBS-E03-S05 | Compose and Kubernetes declare expected scrape roles independently of discovery. Rules detect missing roles and missing required series while accepting a surviving healthy rollout replica. | Confirm the site's Operator selectors, apply its inventory, and demonstrate loss and recovery in a disposable deployment. See [telemetry contract](../operations/telemetry-contract.md). |
+| OBS-E03-S06 | The watchdog has a dedicated receiver route. Optional Alertmanager metrics expose delivery and notification path failures. | Configure an external service to page when the heartbeat stops, and verify it during Prometheus or Alertmanager outages. |
+
+Prometheus 3.16 and Alertmanager 0.35.1 delivered firing and resolved payloads to a disposable TLS receiver. The test exercised grouped replicas, deduplication, silence, inhibition, watchdog cadence and provider retry. The rule fixtures cover missed schedules, receiver availability, disappearing roles and required series. Both migrations were rendered forward and backward for PostgreSQL. The disposable PostgreSQL concurrency case is part of the existing integration job.
+
+The focused backend suite passed 406 tests and skipped the case that requires a disposable PostgreSQL instance. All 40 Prometheus semantic scenarios passed. Compose and Operator manifests were rendered, and no production receivers were contacted.
diff --git a/docs/operations/alert-routing.md b/docs/operations/alert-routing.md
new file mode 100644
index 000000000..63e50deb1
--- /dev/null
+++ b/docs/operations/alert-routing.md
@@ -0,0 +1,160 @@
+# Alert delivery and recovery notifications
+
+The ordinary monitoring overlay evaluates rules without sending notifications.
+Add `docker-compose.alerting.yml` only after choosing an incident receiver and an
+independent heartbeat service. The reference integration speaks the
+[Alertmanager webhook protocol](https://prometheus.io/docs/alerting/latest/configuration/#webhook_config).
+An enterprise gateway can translate that protocol into the site's on-call,
+ticketing or chat service. An arbitrary chat incoming-webhook URL is not
+necessarily compatible with this payload.
+
+## Configure a reference Compose installation
+
+Create four private UTF-8 files using the site's secret manager: an HTTPS
+incident webhook URL, its bearer token, an HTTPS watchdog webhook URL and its
+separate bearer token. Do not put credentials in Compose environment values,
+the checked-in YAML, URL userinfo, shell history or release artifacts. URLs may
+also contain credentials and are mounted as secrets. Both endpoints must
+accept `Authorization: Bearer ...`; redirects are disabled and server
+certificates are verified. The heartbeat service must alert on **absence** of
+the `TestLookupWatchdog` firing message, rather than treating each heartbeat
+as an incident.
+
+Set these environment variables to absolute host **file paths**:
+
+```sh
+export ALERTMANAGER_INCIDENT_URL_SOURCE=/private/monitoring/incident-url
+export ALERTMANAGER_INCIDENT_TOKEN_SOURCE=/private/monitoring/incident-token
+export ALERTMANAGER_WATCHDOG_URL_SOURCE=/private/monitoring/watchdog-url
+export ALERTMANAGER_WATCHDOG_TOKEN_SOURCE=/private/monitoring/watchdog-token
+export ALERTING_PROMETHEUS_CONFIG_SOURCE=/private/monitoring/prometheus-alerting.yml
+python scripts/monitoring/configure_alerting.py \
+ --installation production-site-a --environment production --owner platform-oncall \
+ --output "$ALERTING_PROMETHEUS_CONFIG_SOURCE"
+```
+
+The helper requires PyYAML, validates the four files without printing values
+or contacting their endpoints, and derives the alternate main configuration
+from the current `infra/monitoring/prometheus.yml`. It preserves the current
+rules and scrape includes. Installation/environment are mandatory stable
+identifiers; the owner fills only an absent alert-owner label. Regenerate
+after every base monitoring configuration change and validate the mounted
+result with the pinned `promtool check config`. A previously generated file
+does not automatically incorporate new base scrape settings.
+
+The overlay also mounts its independent Alertmanager expected-role recording
+rule. With the common telemetry rules loaded, deleting the Alertmanager
+scrape job still produces a required-role alert. Disabling alerting must
+remove both the overlay and its generated main configuration.
+
+Then render and review the selected profile before starting it:
+
+```sh
+docker compose -f docker-compose.yml -f docker-compose.monitoring.yml \
+ -f docker-compose.monitoring-auth.yml -f docker-compose.alerting.yml config --quiet
+docker compose -f docker-compose.yml -f docker-compose.monitoring.yml \
+ -f docker-compose.monitoring-auth.yml -f docker-compose.alerting.yml up -d
+```
+
+Supply the metrics-token paths required by the authentication overlay as
+described in [authenticated metrics](deploy-compose.md#authenticate-the-api-scrape). The
+authentication and alerting overlays may be layered in either order: one
+replaces the backend scrape include and the other replaces the main config.
+Use the same base/image overrides as the installation; the commands above
+show the source-build reference profile.
+
+The official image runs as `nobody` (UID/GID 65534). Compose local file secrets
+are bind mounts: UID/GID/mode remapping is not guaranteed. Make the mounted
+files readable by that container identity while restricting the enclosing
+host directory to the operator, and verify that `alertmanager-config-check`
+succeeds. Do not copy private values into a support bundle. For a private
+certificate authority, mount its PEM and add `tls_config.ca_file` to each
+receiver in a reviewed site configuration; keep certificate verification on.
+
+Alertmanager has no host port. Prometheus sends to its private service DNS;
+Alertmanager persists silences and notification deduplication state in
+`alertmanager-data` with 120 hours' retention. The API can inject alerts,
+create silences and reload configuration, so keep untrusted containers off
+the monitoring network. Use an authenticated operator tunnel/proxy for API
+access. This single-node overlay is a reference deployment, not an HA claim.
+For production HA, use an existing managed/clustered Alertmanager with
+authenticated TLS ingress and send Prometheus to **every** replica as
+[upstream recommends](https://prometheus.io/docs/alerting/latest/ha/).
+
+## Routing, context and maintenance
+
+Alerts group by installation, environment, cluster, namespace and alert name.
+Critical alerts wait 10 seconds and repeat every 30 minutes; other incidents
+wait 30 seconds and repeat every four hours. A separate watchdog route sends
+each minute. Both routes send resolved notifications. The external heartbeat
+service must distinguish `status=firing` from `status=resolved` and page if
+firing heartbeats stop for the site's chosen allowance, for example three
+minutes. A receiver on the same host or cluster cannot independently detect
+that host or cluster failing.
+
+Use `severity`, an accountable `owner`, and annotations `summary`,
+`description`, `runbook_url`, `dashboard_url` on production rules. Link to
+the installed dashboard and an accessible operational runbook. The transport
+preserves these fields; it does not invent a runbook for existing rules that
+lack one. Existing rule-by-rule ownership/link coverage still needs review.
+Avoid user identifiers, credentials and payloads in labels or annotations.
+
+Warning inhibition is enabled only when **both** alerts have a nonempty
+`alert_family`, match installation/environment/cluster/namespace and the
+critical source remains active. Use that label only for two severities of the
+same underlying condition. A critical alert without this opt-in cannot mute
+unrelated warnings. For maintenance, create a time-bounded silence matching
+the exact installation and affected alert/component, with accountable author
+and reason. Avoid broad `.*` silences; do not silence the watchdog to hide a
+broken monitoring path. Preserve `alertmanager-data` across replacement to
+retain silences and deduplication state. Back it up with the site's volume
+snapshot procedure; losing the volume can repeat incidents and lose silences.
+
+Check Prometheus `/api/v1/alertmanagers` for the active destination, the
+`alertmanager` scrape for health, and notification-failure/config-reload
+rules for delivery errors. A working Prometheus-to-Alertmanager connection
+alone does not prove receiver delivery. A failed receiver also cannot report
+its own failure over the failed route: independent heartbeat absence is the
+last-mile outage signal.
+
+Rotate URL/token files using the secret manager, revalidate/regenerate and
+recreate the config-check and Alertmanager services. File bind mounts may
+retain an old inode after an atomic host-file replacement. Test a disposable
+receiver before activating the new production credential.
+
+## Kubernetes, K3s and OpenShift reuse
+
+Prefer the site's existing Prometheus Operator Alertmanager. Mount the four
+values from a namespace-local Secret and reuse the checked-in routing config,
+adjusting absolute file paths to those mounts. Put `installation` and
+`environment` in Prometheus external labels and preserve its rule-specific
+owner labels; configure Prometheus alerting endpoints through the Operator's
+`spec.alerting.alertmanagers` with matching namespace, Service and named port.
+Keep TLS, service-account/RBAC and NetworkPolicy consistent with that site's
+operator. The Compose service name `alertmanager:9093` is not a Kubernetes
+endpoint. Kubernetes Secrets are namespaced; an operator-specific
+`AlertmanagerConfig` needs its own selected namespace and Secret selectors.
+Select the site's Alertmanager self-monitor/ServiceMonitor separately: the
+application PodMonitor does not scrape an externally owned Alertmanager.
+Review and render that site's CRD version before deployment. This change
+provides a reusable routing contract, not a new in-cluster Alertmanager.
+
+The monitoring sidecar is intentionally excluded from the application/offline
+image manifest under the existing image-drift policy. Its official version,
+manifest-index digest, source and binary checksums are recorded separately in
+[`image-lock.json`](../../infra/monitoring/alertmanager/image-lock.json).
+Mirror that exact digest and distribute site configuration/secrets separately
+for an air-gapped monitoring installation; there is no new offline-bundle
+coverage claim.
+
+## Disposable delivery verification
+
+`scripts/monitoring/tests/test_alert_routing.py` tests static safety and config
+preservation. Set `ALERTMANAGER_TEST_BINARY`, `AMTOOL_TEST_BINARY` and
+`PROMETHEUS_TEST_BINARY` to checksum-verified official release binaries to run
+its real delivery case. It starts only loopback listeners, generates an
+ephemeral TLS certificate and credentials, evaluates synthetic rules in a
+temporary Prometheus, and observes Alertmanager firing/resolved delivery,
+deduplication, maintenance silence, scoped inhibition, separate watchdog
+delivery and an HTTP 503 followed by retry/recovery. No actual on-call service
+is contacted. Skipping this case is not full signal-path verification.
diff --git a/docs/operations/deploy-compose.md b/docs/operations/deploy-compose.md
index a17014f81..56f051002 100644
--- a/docs/operations/deploy-compose.md
+++ b/docs/operations/deploy-compose.md
@@ -187,6 +187,8 @@ All of these listen on `127.0.0.1` only (`MONITORING_PUBLISH_ADDR`): Jaeger, the
The override sets `OTEL_ENABLED=true`, `OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318` and `METRICS_ENABLED=true` on the backend. The same alert rules are rendered for Kubernetes in [`k8s/monitoring`](deploy-kubernetes.md#monitoring-podmonitor-and-prometheusrule). Metric and alert reference: [observability](../../architecture/OBSERVABILITY.md).
+Use the [alert routing overlay](alert-routing.md) to deliver incident notifications and an independent watchdog over authenticated HTTPS. The [telemetry contract](telemetry-contract.md) lists the required roles and series.
+
### Authenticate the API scrape
Use `docker-compose.monitoring-auth.yml` after the monitoring file with either the source or release stack. Set `METRICS_API_TOKEN_SOURCE` and `METRICS_PROMETHEUS_TOKEN_SOURCE` to the absolute host paths of two protected files containing the same bearer token. Grant file read access to the corresponding container users and restrict access to the files on the host. Compose mounts each file only in the service that needs it. File-based Compose secrets use host file ownership and permissions. [Compose secrets](https://docs.docker.com/compose/how-tos/use-secrets/).
diff --git a/docs/operations/deploy-kubernetes.md b/docs/operations/deploy-kubernetes.md
index b1289e507..4e7c90a52 100644
--- a/docs/operations/deploy-kubernetes.md
+++ b/docs/operations/deploy-kubernetes.md
@@ -182,6 +182,8 @@ kubectl apply -k k8s/monitoring
The backup alerts read kube-state-metrics, and the disk and OOM alerts read node-exporter. If your Prometheus selects rules and monitors by label (kube-prometheus-stack uses `release: `), add that label in your site monitoring overlay. Confirm that the Prometheus resource selects rules and PodMonitors in the application namespace.
+Include the telemetry inventory Rule along with the shared alert Rule. The [telemetry contract](telemetry-contract.md) explains the role labels and namespace scope. Use the cluster's Alertmanager and check [alert delivery and watchdog routing](alert-routing.md) against your site configuration.
+
### Authenticate the API scrape
Provision a Secret named `testlookup-metrics-auth` with key `token` in the application namespace through your secret manager. Include the `k8s/components/metrics-auth` component in your application overlay. It mounts the token read-only in the backend container. Select `k8s/monitoring-authenticated` as the monitoring resource in your site overlay. It uses `PodMonitor` bearer authorization with the same Secret key. The Operator needs permission to read that Secret in the PodMonitor namespace. [Prometheus Operator API](https://prometheus-operator.dev/docs/api-reference/api/).
diff --git a/docs/operations/deployment.md b/docs/operations/deployment.md
index ab68c7701..c8e681850 100644
--- a/docs/operations/deployment.md
+++ b/docs/operations/deployment.md
@@ -132,7 +132,7 @@ Local-model RAM, VRAM and disk depend on the model, quantization, context and co
| Project activity and decision trail | User-visible receipts and agent reasoning/provenance events |
| Upload, outbox, DLQ and pipeline records | Locate the failed asynchronous step, not just HTTP health |
-Prometheus alert rules live in `infra/monitoring/prometheus-rules/`; Compose loads them through the [monitoring add-on](deploy-compose.md#monitoring-add-on) and Kubernetes through [`k8s/monitoring`](deploy-kubernetes.md#monitoring-podmonitor-and-prometheusrule). Alert on stalled pipelines, lease or retry exhaustion, outbox/DLQ backlog, queue imbalance, database connections and broker memory. Installing an OpenTelemetry library does not by itself trace Celery tasks. [Dependency metrics](dependency-metrics.md), [observability deep dive](../../architecture/OBSERVABILITY.md), [troubleshooting](../../user-guide/troubleshooting.md).
+Prometheus alert rules live in `infra/monitoring/prometheus-rules/`; Compose loads them through the [monitoring add-on](deploy-compose.md#monitoring-add-on) and Kubernetes through [`k8s/monitoring`](deploy-kubernetes.md#monitoring-podmonitor-and-prometheusrule). Alert on stalled pipelines, lease or retry exhaustion, outbox/DLQ backlog, queue imbalance, database connections and broker memory. Installing an OpenTelemetry library does not by itself trace Celery tasks. [Dependency metrics](dependency-metrics.md), [scheduled maintenance monitoring](scheduled-maintenance.md), [observability deep dive](../../architecture/OBSERVABILITY.md), [troubleshooting](../../user-guide/troubleshooting.md).
## Related
diff --git a/docs/operations/scheduled-maintenance.md b/docs/operations/scheduled-maintenance.md
new file mode 100644
index 000000000..ae8efba71
--- /dev/null
+++ b/docs/operations/scheduled-maintenance.md
@@ -0,0 +1,22 @@
+# Scheduled maintenance monitoring
+
+Nightly quarantine maintenance runs at 04:00 UTC. Performance baseline refresh runs at 04:30 UTC. The alerts allow an hour for each enabled run to finish and wait another five minutes before firing.
+
+Beat stamps its messages with the planned UTC slot when it publishes. The worker records the slot's attempt before doing the work and records completion after it succeeds. PostgreSQL stores both across worker restarts. A delayed message from an older slot cannot certify a newer one. Disabled features and a skipped baseline refresh do not record success. Interactive task calls without the Beat headers do not count as scheduled work.
+
+The reader considers slots from the later of the schema installation time and the last off-to-on feature transition. This gives a newly monitored or re-enabled job time to reach its next scheduled slot. A description edit or a change between two positive rollout percentages leaves an overdue slot visible. Earlier history remains outside the new observation window.
+
+| API sample | Meaning |
+|---|---|
+| `testlookup_nightly_job_enabled` | 1 when the job's feature is globally enabled with a positive rollout. |
+| `testlookup_nightly_job_next_due_timestamp_seconds` | Unix timestamp of the next dispatch slot, or zero while disabled. |
+| `testlookup_nightly_job_last_attempt_timestamp_seconds` | Start of the latest slot observed by a worker. |
+| `testlookup_nightly_job_last_success_timestamp_seconds` | Completion of the latest successful slot. |
+| `testlookup_nightly_job_overdue` | 1 when the latest eligible slot missed its completion deadline. |
+| `testlookup_nightly_job_started_overdue_slot` | 1 when overdue and a worker began the slot or a later one. |
+
+For `TestLookupFlakyQuarantineMaintenanceFailing` or `TestLookupPerfBaselineRefreshFailing`, inspect the latest attempt and success for the matching `schedule`. An overdue slot without an observed attempt points to Beat dispatch, queue delay or inability to persist the attempt. An observed attempt without success points to an incomplete, failed or skipped job. Check worker logs and database health before rerunning maintenance. The alert keeps its existing name for routing compatibility. It clears when a fresh scrape sees a successful slot that satisfies the deadline.
+
+Verify collector health first with `testlookup_metric_collection_success{collector="nightly"}` and its last-success timestamp. A failed or stale scrape does not provide schedule truth. API replicas observe the same database, and Prometheus takes the maximum across fresh replicas for each schedule and installation.
+
+Apply database migrations before starting the new Beat and workers so their observations can be stored. The threshold and recovery are covered by `infra/monitoring/tests/nightly-alerts.yml`. The worker/SQL regression covers never-run, disabled, failed, late and recovered slots. A deployment check should also exercise missed dispatch with an isolated broker and the intended alert receiver. [Celery periodic task options](https://docs.celeryq.dev/en/stable/userguide/periodic-tasks.html#available-fields).
diff --git a/docs/operations/telemetry-contract.md b/docs/operations/telemetry-contract.md
new file mode 100644
index 000000000..9507a8057
--- /dev/null
+++ b/docs/operations/telemetry-contract.md
@@ -0,0 +1,96 @@
+# Required telemetry and discovery failures
+
+The monitoring profiles keep an explicit inventory separate from scrape
+discovery. The Compose profile loads
+`infra/monitoring/prometheus-rules/compose-telemetry-contract.yml` through the
+existing rules volume. The Operator profile includes the separate
+`k8s/monitoring/telemetry-contract.yaml` PrometheusRule. Both emit
+`testlookup:telemetry_expected_role = 1` for each required role.
+
+The default Compose roles are `backend`, `worker` and `worker-children`.
+The default Kubernetes roles are `backend`, `worker-critical`,
+`worker-ingestion`, `worker-ai`, `worker-default` and `worker-children`.
+Beat does not expose a task metrics target. Optional node/PostgreSQL exporters
+and Alertmanager are not requirements of the base inventory. Scheduled-work
+and independent heartbeat checks cover different questions.
+
+`TestLookupExpectedRoleUnavailable` fires after five minutes without **any
+healthy target** for a declared role. It covers both `up = 0` and the complete
+absence of `up`, including a deleted or mis-selected PodMonitor. An extra
+rolling replica does not change the inventory; one healthy replica prevents a
+role-loss alert. Existing down alerts still report individual scrape failures.
+This is minimum role coverage, not exact replica-count or consumer-capacity
+verification. `TestLookupTelemetryContractMissing` fires after five minutes
+when the entire inventory is absent.
+
+`TestLookupRequiredTelemetryMissing` checks each healthy API target for both
+success and last-success series from the unconditional `queues`, `agents`,
+`downstream` and `redis` collectors. API and worker targets must also expose
+the preinitialized `testlookup_finalize_step_failures_total{step="suite_sync"}`
+series as a registry sentinel. Zero values are healthy presence. Missing
+series hold for five minutes; existing collection-failure/staleness rules
+check values and freshness separately. Lazy task-labelled histograms, pool
+metrics before pool initialization, optional collectors, and outbox/queue
+values before a successful dependency read are excluded. This baseline does
+not prove task execution or completeness of every application metric.
+
+Before applying an Operator site overlay, configure its actual
+`ruleSelector`, `ruleNamespaceSelector`, `podMonitorSelector` and
+`podMonitorNamespaceSelector` and the permitted scrape ingress. Apply the
+site's selection labels to **both** PrometheusRules and both PodMonitors,
+using the monitoring kustomization's common labels. No private release,
+cluster or receiver labels belong in tracked base files. If the application
+namespace changes, patch the inventory rules' `labels.namespace` as well as
+resource namespaces. Kustomize's namespace transformer does not rewrite
+PromQL sample labels. If local scrape relabeling adds `cluster`, add the same
+label to each inventory record. Prometheus external labels are not present
+on ordinary local query results. Central/federated evaluation needs an
+inventory for every selected cluster and namespace. Configure exactly one
+inventory per profile; do not load the Compose inventory into the Operator
+installation.
+
+The reference contract assumes each evaluating Prometheus sees all required
+application roles. A sharded installation needs central rule evaluation over
+all shards, or an explicitly reviewed shard-specific inventory. Loading the
+complete inventory into every shard that sees only a subset of targets would
+create false role-loss alerts. Prometheus HA replicas that each scrape the
+complete target set can evaluate this same contract independently.
+
+If a role is intentionally disabled, remove its inventory entry in the same
+reviewed site overlay. Do not infer applicability from the role's observed
+targets: that would suppress the failure this inventory detects. New
+mandatory collectors require an explicit applicability decision and fixture
+update. Partial inventory edits are configuration changes; the missing
+inventory alert cannot reconstruct a deleted individual requirement.
+
+For triage, inspect `testlookup:telemetry_expected_role`, compare it with
+`up` grouped by `namespace`, `job`, `telemetry_profile` and `telemetry_role`,
+then inspect the target's discovery labels and last scrape error. Check
+monitor selection, metrics port/path, credentials, dropped metric filters
+and network policy before changing an application's workload. Verify the
+required sample and current collection timestamp after recovery.
+
+CI executes the semantic fixtures in `infra/monitoring/tests` with the pinned
+promtool from the existing backend test job. The fixture covers complete
+discovery loss, all targets down, a surviving rollout replica, missing series
+on one healthy replica, zero activity, optional absence and recovery. These
+are synthetic rule tests. They do not prove actual Operator selection,
+network-policy reachability, notification delivery or outage recovery.
+Disposable-profile monitor deletion, selector changes, blocked scrapes and
+required-series removal remain runtime acceptance steps.
+
+`TestLookupWatchdog` always fires and is routed only when the optional
+[alerting profile](alert-routing.md) is configured. Its independently hosted
+authenticated receiver must alert on a missing heartbeat. A rule inside
+Prometheus cannot report the loss of that same Prometheus through its failed
+notification path. The Alertmanager failure rules use actual optional scrape
+series and do not make Alertmanager mandatory in the base profile. Receiver
+delivery and independent synthetic journeys need separate runtime evidence.
+
+The matching and empty-vector behavior follow the official
+[PromQL set operators](https://prometheus.io/docs/prometheus/latest/querying/operators/#logicalset-binary-operators)
+and [absent function](https://prometheus.io/docs/prometheus/latest/querying/functions/#absent).
+The inventory uses ordinary
+[recording rules](https://prometheus.io/docs/prometheus/latest/configuration/recording_rules/).
+Target labels and monitor selection use the
+[Prometheus Operator API](https://prometheus-operator.dev/docs/api-reference/api/).
diff --git a/docs/operations/weekly-digest-observability.md b/docs/operations/weekly-digest-observability.md
new file mode 100644
index 000000000..0ccc17b85
--- /dev/null
+++ b/docs/operations/weekly-digest-observability.md
@@ -0,0 +1,34 @@
+# Weekly digest delivery observations
+
+Weekly and weekly retro subscriptions are due at their persisted `next_delivery_at`, on any weekday. The normal dispatcher runs daily at 07:00 UTC; the additional Monday pass does not define every subscription's due date. Creation, schedule edits and resume calculate UTC timestamps. There is no subscriber-local timezone or calendar-Monday promise.
+
+Migration `0262` adds nullable observation fields to each existing subscription. An atomic dispatch claim preserves the original unmet due slot in `pending_delivery_since_at`, records an attempt time and installs a unique observation token before advancing the scheduler's next date. A retry preserves that original slot. Generation records a separate content timestamp and `generated` phase. Only a provider call returning successfully can finalize `sent` and advance the existing successful-send watermark/count; generating content does not do so.
+
+A known provider refusal remains `failed` with the original slot unresolved. An interrupted/ambiguous attempt stays unresolved as `generating`, `generated` or `unknown`; the observer never automatically replays it. Intentional unchanged-content or authorization skips finalize `skipped` and resolve the due slot without increasing delivered history. An explicit schedule edit or resume supersedes old attempt ownership and due state. Token checks stop an older completion from clearing the newer slot. Notification audit rows and their relay ownership remain unchanged.
+
+The read-only `digests` scrape collector publishes aggregate snapshots, with bounded `schedule` (`WEEKLY`, `WEEKLY_RETRO`) and state/outcome labels:
+
+| Metric | Meaning |
+|---|---|
+| `testlookup_weekly_digest_subscriptions{state}` | Counts of enabled/non-paused subscriptions: `enabled`, `due`, `unresolved`, `never_delivered`, `missing_schedule`. These states overlap; do not sum them into a total. |
+| `testlookup_weekly_digest_oldest_overdue_seconds` | Age of the oldest effective due slot beyond 25 hours: the normal maximum daily dispatch lag plus one hour for processing. |
+| `testlookup_weekly_digest_delivery_outcomes{outcome}` | Current subscriptions by most recent observed phase/outcome: `not_observed`, `generating`, `generated`, `sent`, `failed`, `skipped`, `unknown`. This is a snapshot, not an event counter. |
+
+No subscription, user, project, address, URL or token is a metric label. Snapshots use the freshest successful per-target observation and are deduplicated with `max` across API replicas. A failed/expired collection invalidates its resource samples through the common collection-health contract. No enabled subscriptions yields measured zeros; a future first delivery is quiet even though it has never succeeded. An enabled subscription with no due date is a separate schedule defect.
+
+`TestLookupWeeklyDigestDeliveryOverdue` alerts after a fresh positive overrun persists for 15 minutes. `TestLookupWeeklyDigestScheduleMissing` detects enabled rows without either a next due time or an unresolved claimed slot. Neither alert requires generation traffic or a Monday clock window. The old `testlookup_retro_digest_dispatch_total` remains a content-generation diagnostic for compatibility, with corrected help text.
+
+The 25-hour allowance reflects the existing daily scheduling cadence; it is not a promise that delivery will occur precisely at the stored due timestamp. Provider `sent` means the provider call accepted the notification, not proof of inbox receipt, display or bounce-free email. Alert delivery, provider failures and ambiguous send reconciliation need their own operational evidence.
+
+No historical claim state is backfilled: a future next date written by a pre-upgrade worker cannot prove whether it delivered, skipped or crashed. New claims gain durable observation after the migration and worker rollout. This change detects unresolved work but does not add durable message publication, an automatic unknown-send retry policy, or repair old ambiguous sends.
+
+Validation uses real ephemeral SQLite transactions with synthetic providers to cover generation followed by refusal, successful retry, loss after claim, stale tokens, intentional skips, every weekday, UTC offset normalization, no subscriptions, missing schedules, and nullable migration upgrade/downgrade. Run:
+
+```sh
+cd backend
+PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -p pytest_asyncio.plugin tests/regression/test_digest_delivery_observation.py tests/regression/test_digest_failure_retry.py
+cd ../infra/monitoring/tests
+promtool test rules digest-delivery.yml
+```
+
+A migrated disposable PostgreSQL deployment must additionally verify the same persisted claim/phase/completion states, actual `/metrics` samples, alert firing/resolution and a controlled provider acceptance/refusal. Local tests do not establish those deployment outcomes.
diff --git a/docs/reference/api/digests.md b/docs/reference/api/digests.md
index 0e5f5c569..d6d9395c3 100644
--- a/docs/reference/api/digests.md
+++ b/docs/reference/api/digests.md
@@ -20,7 +20,7 @@ that view would receive. The view is checked for THIS caller in THIS
project with the subscription rule: another project's view, a teammate's
private view and a layout row all answer the same 422.
-Source: [backend/app/routers/digests.py:317](../../../backend/app/routers/digests.py#L317).
+Source: [backend/app/routers/digests.py:323](../../../backend/app/routers/digests.py#L323).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`.
@@ -310,7 +310,7 @@ Delete Subscription
Delete (unsubscribe from) a digest subscription.
-Source: [backend/app/routers/digests.py:250](../../../backend/app/routers/digests.py#L250).
+Source: [backend/app/routers/digests.py:253](../../../backend/app/routers/digests.py#L253).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`.
@@ -574,7 +574,7 @@ Pause Subscription
Pause digest delivery without deleting.
-Source: [backend/app/routers/digests.py:271](../../../backend/app/routers/digests.py#L271).
+Source: [backend/app/routers/digests.py:274](../../../backend/app/routers/digests.py#L274).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`.
@@ -661,7 +661,7 @@ Resume Subscription
Resume a paused subscription.
-Source: [backend/app/routers/digests.py:293](../../../backend/app/routers/digests.py#L293).
+Source: [backend/app/routers/digests.py:296](../../../backend/app/routers/digests.py#L296).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`.
diff --git a/docs/reference/data-dictionary.md b/docs/reference/data-dictionary.md
index d784696dd..7a97f66e2 100644
--- a/docs/reference/data-dictionary.md
+++ b/docs/reference/data-dictionary.md
@@ -45,7 +45,7 @@ Current SQLAlchemy metadata, without a database connection. All columns, server/
| [defect_candidates](#defect_candidates) | DefectCandidate | 19 |
| [defects](#defects) | Defect | 35 |
| [deletion_jobs](#deletion_jobs) | DeletionJob | 28 |
-| [digest_subscriptions](#digest_subscriptions) | DigestSubscription | 20 |
+| [digest_subscriptions](#digest_subscriptions) | DigestSubscription | 25 |
| [dismissed_duplicate_pairs](#dismissed_duplicate_pairs) | DismissedDuplicatePair | 6 |
| [drop_folder_builds](#drop_folder_builds) | DropFolderBuild | 10 |
| [duplicate_test_case_candidates](#duplicate_test_case_candidates) | DuplicateTestCaseCandidate | 11 |
@@ -79,6 +79,7 @@ Current SQLAlchemy metadata, without a database connection. All columns, server/
| [managed_test_cases](#managed_test_cases) | ManagedTestCase | 52 |
| [mfa_recovery_codes](#mfa_recovery_codes) | MfaRecoveryCode | 5 |
| [model_versions](#model_versions) | ModelVersion | 16 |
+| [nightly_job_observations](#nightly_job_observations) | NightlyJobObservation | 7 |
| [notification_logs](#notification_logs) | NotificationLog | 24 |
| [notification_preferences](#notification_preferences) | NotificationPreference | 12 |
| [notification_test_states](#notification_test_states) | NotificationTestState | 10 |
@@ -217,7 +218,7 @@ Constraints and indexes:
## agent_action_dispatch_outbox
-[backend/app/models/postgres.py:6608](../../backend/app/models/postgres.py#L6608)
+[backend/app/models/postgres.py:6616](../../backend/app/models/postgres.py#L6616)
Durable delivery intent for approved actions; never contains prompts.
@@ -249,7 +250,7 @@ Constraints and indexes:
## agent_action_ledger
-[backend/app/models/postgres.py:6149](../../backend/app/models/postgres.py#L6149)
+[backend/app/models/postgres.py:6157](../../backend/app/models/postgres.py#L6157)
Append-only proposal/execution ledger for agent-originated actions.
@@ -336,7 +337,7 @@ Constraints and indexes:
## agent_configs
-[backend/app/models/postgres.py:6395](../../backend/app/models/postgres.py#L6395)
+[backend/app/models/postgres.py:6403](../../backend/app/models/postgres.py#L6403)
A project's configuration of one agent (architecture E4.1, section 4.2).
@@ -437,7 +438,7 @@ Constraints and indexes:
## agent_invocations
-[backend/app/models/postgres.py:6315](../../backend/app/models/postgres.py#L6315)
+[backend/app/models/postgres.py:6323](../../backend/app/models/postgres.py#L6323)
One call of a single agent through the public API (architecture E1.2).
@@ -482,7 +483,7 @@ Constraints and indexes:
## agent_memory_entries
-[backend/app/models/postgres.py:6094](../../backend/app/models/postgres.py#L6094)
+[backend/app/models/postgres.py:6102](../../backend/app/models/postgres.py#L6102)
Unified memory linking a run/snapshot to related entities (clusters, defects,
release decisions, ownership) for project-scoped historical recall.
@@ -788,7 +789,7 @@ Constraints and indexes:
## ai_eval_baselines
-[backend/app/models/postgres.py:5811](../../backend/app/models/postgres.py#L5811)
+[backend/app/models/postgres.py:5819](../../backend/app/models/postgres.py#L5819)
Baseline metrics per agent/task_type for comparison gating.
@@ -826,7 +827,7 @@ Constraints and indexes:
## ai_eval_datasets
-[backend/app/models/postgres.py:5685](../../backend/app/models/postgres.py#L5685)
+[backend/app/models/postgres.py:5693](../../backend/app/models/postgres.py#L5693)
Labeled evaluation dataset for measuring AI quality over time.
@@ -851,7 +852,7 @@ Constraints and indexes:
## ai_eval_gate_runs
-[backend/app/models/postgres.py:5848](../../backend/app/models/postgres.py#L5848)
+[backend/app/models/postgres.py:5856](../../backend/app/models/postgres.py#L5856)
Historical record of an agent-stack release gate decision.
@@ -887,7 +888,7 @@ Constraints and indexes:
## ai_eval_item_outputs
-[backend/app/models/postgres.py:5772](../../backend/app/models/postgres.py#L5772)
+[backend/app/models/postgres.py:5780](../../backend/app/models/postgres.py#L5780)
One replayed item of a candidate evaluation run (W16 AGT-09, 0231).
@@ -922,7 +923,7 @@ Constraints and indexes:
## ai_eval_reviewer_quality
-[backend/app/models/postgres.py:5915](../../backend/app/models/postgres.py#L5915)
+[backend/app/models/postgres.py:5923](../../backend/app/models/postgres.py#L5923)
A G3 reviewer-quality observation batch or scheduled 30-day rollup.
@@ -967,7 +968,7 @@ Constraints and indexes:
## ai_eval_runs
-[backend/app/models/postgres.py:5705](../../backend/app/models/postgres.py#L5705)
+[backend/app/models/postgres.py:5713](../../backend/app/models/postgres.py#L5713)
Record of running an evaluation dataset against a model version.
@@ -1018,7 +1019,7 @@ Constraints and indexes:
## ai_eval_shadow_pairs
-[backend/app/models/postgres.py:5885](../../backend/app/models/postgres.py#L5885)
+[backend/app/models/postgres.py:5893](../../backend/app/models/postgres.py#L5893)
A bounded live tier pair awaiting a human or golden-input label.
@@ -1311,7 +1312,7 @@ Constraints and indexes:
## compliance_packs
-[backend/app/models/postgres.py:7441](../../backend/app/models/postgres.py#L7441)
+[backend/app/models/postgres.py:7463](../../backend/app/models/postgres.py#L7463)
Generated compliance export pack (ZIP) for a release decision.
@@ -1345,7 +1346,7 @@ Constraints and indexes:
## compliance_signing_keys
-[backend/app/models/postgres.py:7518](../../backend/app/models/postgres.py#L7518)
+[backend/app/models/postgres.py:7540](../../backend/app/models/postgres.py#L7540)
The deployment's Ed25519 compliance-pack signing keys (migration 0225, W11 REL-11, D14).
@@ -1411,7 +1412,7 @@ Constraints and indexes:
## decision_report_eval_cycles
-[backend/app/models/postgres.py:5977](../../backend/app/models/postgres.py#L5977)
+[backend/app/models/postgres.py:5985](../../backend/app/models/postgres.py#L5985)
Durable evidence for a report-level evaluation corpus cycle.
@@ -1503,7 +1504,7 @@ Constraints and indexes:
## decision_report_supersession_requests
-[backend/app/models/postgres.py:6039](../../backend/app/models/postgres.py#L6039)
+[backend/app/models/postgres.py:6047](../../backend/app/models/postgres.py#L6047)
Durable, idempotent request to publish a child-enriched report version.
@@ -1681,7 +1682,7 @@ approver: Mapped[Optional['User']] = relationship('User', foreign_keys=[approved
## deletion_jobs
-[backend/app/models/postgres.py:7820](../../backend/app/models/postgres.py#L7820)
+[backend/app/models/postgres.py:7842](../../backend/app/models/postgres.py#L7842)
One record of a deletion actually happening (migration 0147, S2b).
@@ -1783,6 +1784,11 @@ User subscription to a scheduled or event-driven report delivery.
| `report_attachment` | `BOOLEAN` | False | False | `application=False` | |
| `last_delivered_at` | `DATETIME` | True | False | `—` | |
| `next_delivery_at` | `DATETIME` | True | False | `—` | |
+| `pending_delivery_since_at` | `DATETIME` | True | False | `—` | |
+| `delivery_observation_token` | `UUID` | True | False | `—` | |
+| `last_delivery_attempt_at` | `DATETIME` | True | False | `—` | |
+| `last_content_generated_at` | `DATETIME` | True | False | `—` | |
+| `last_delivery_outcome` | `VARCHAR(20)` | True | False | `—` | |
| `delivery_count` | `INTEGER` | False | False | `application=0` | |
| `created_at` | `DATETIME` | False | False | `server=now()` | |
| `updated_at` | `DATETIME` | False | False | `server=now(); onupdate=now()` | |
@@ -1830,7 +1836,7 @@ Constraints and indexes:
## drop_folder_builds
-[backend/app/models/postgres.py:8643](../../backend/app/models/postgres.py#L8643)
+[backend/app/models/postgres.py:8665](../../backend/app/models/postgres.py#L8665)
One build folder ``/runs//`` seen by the drop-folder watcher (W34 STRAT-13; migration 0254).
@@ -1959,7 +1965,7 @@ Constraints and indexes:
## failure_attribution
-[backend/app/models/postgres.py:6848](../../backend/app/models/postgres.py#L6848)
+[backend/app/models/postgres.py:6870](../../backend/app/models/postgres.py#L6870)
@@ -2016,7 +2022,7 @@ Constraints and indexes:
## feature_flags
-[backend/app/models/postgres.py:6656](../../backend/app/models/postgres.py#L6656)
+[backend/app/models/postgres.py:6678](../../backend/app/models/postgres.py#L6678)
Named capability toggle gated by project, role, and rollout percent.
@@ -2124,7 +2130,7 @@ Constraints and indexes:
## flaky_classifier_calibration
-[backend/app/models/postgres.py:7022](../../backend/app/models/postgres.py#L7022)
+[backend/app/models/postgres.py:7044](../../backend/app/models/postgres.py#L7044)
@@ -2185,7 +2191,7 @@ Constraints and indexes:
## flaky_detection_state
-[backend/app/models/postgres.py:7058](../../backend/app/models/postgres.py#L7058)
+[backend/app/models/postgres.py:7080](../../backend/app/models/postgres.py#L7080)
@@ -2215,7 +2221,7 @@ Constraints and indexes:
## flaky_quarantine_requests
-[backend/app/models/postgres.py:7561](../../backend/app/models/postgres.py#L7561)
+[backend/app/models/postgres.py:7583](../../backend/app/models/postgres.py#L7583)
Workflow record for proposing, approving, and enforcing quarantine
of a flaky test.
@@ -2279,7 +2285,7 @@ Constraints and indexes:
## flaky_score
-[backend/app/models/postgres.py:6988](../../backend/app/models/postgres.py#L6988)
+[backend/app/models/postgres.py:7010](../../backend/app/models/postgres.py#L7010)
@@ -2373,7 +2379,7 @@ Constraints and indexes:
## github_integrations
-[backend/app/models/postgres.py:7293](../../backend/app/models/postgres.py#L7293)
+[backend/app/models/postgres.py:7315](../../backend/app/models/postgres.py#L7315)
Per-project GitHub Checks API integration config.
@@ -2406,7 +2412,7 @@ Constraints and indexes:
## gitlab_integrations
-[backend/app/models/postgres.py:7358](../../backend/app/models/postgres.py#L7358)
+[backend/app/models/postgres.py:7380](../../backend/app/models/postgres.py#L7380)
Per-project GitLab integration config (PMF Epic 3 US-3.1).
@@ -2515,7 +2521,7 @@ Constraints and indexes:
## instance_retention_policy
-[backend/app/models/postgres.py:8403](../../backend/app/models/postgres.py#L8403)
+[backend/app/models/postgres.py:8425](../../backend/app/models/postgres.py#L8425)
The instance-wide retention defaults (W22b ACT-06, migration 0242).
@@ -2968,6 +2974,26 @@ Constraints and indexes:
- `PrimaryKeyConstraint` `unnamed`: `id`
- Index `ix_model_versions_track_status` (unique=False): `model_versions.track, model_versions.status`; options `{}`
+## nightly_job_observations
+
+[backend/app/models/postgres.py:6664](../../backend/app/models/postgres.py#L6664)
+
+Bounded operational state shared by the scheduled workers and API.
+
+| Column | SQL type | Nullable | PK | Default | Foreign key / on delete |
+|---|---|---|---|---|---|
+| `schedule_key` | `VARCHAR(64)` | False | True | `—` | |
+| `monitoring_since` | `DATETIME` | False | False | `server=now()` | |
+| `enabled_since` | `DATETIME` | True | False | `—` | |
+| `last_attempt_slot_at` | `DATETIME` | True | False | `—` | |
+| `last_attempt_started_at` | `DATETIME` | True | False | `—` | |
+| `last_success_slot_at` | `DATETIME` | True | False | `—` | |
+| `last_success_finished_at` | `DATETIME` | True | False | `—` | |
+
+Constraints and indexes:
+
+- `PrimaryKeyConstraint` `unnamed`: `schedule_key`
+
## notification_logs
[backend/app/models/postgres.py:3042](../../backend/app/models/postgres.py#L3042)
@@ -3136,7 +3162,7 @@ Constraints and indexes:
## perf_baselines
-[backend/app/models/postgres.py:7108](../../backend/app/models/postgres.py#L7108)
+[backend/app/models/postgres.py:7130](../../backend/app/models/postgres.py#L7130)
Per-test running duration statistics.
@@ -3190,7 +3216,7 @@ Constraints and indexes:
## project_activity_events
-[backend/app/models/postgres.py:8494](../../backend/app/models/postgres.py#L8494)
+[backend/app/models/postgres.py:8516](../../backend/app/models/postgres.py#L8516)
Append-only, project-scoped product feed of everything that happens.
@@ -3268,7 +3294,7 @@ Constraints and indexes:
## project_data_jobs
-[backend/app/models/postgres.py:7945](../../backend/app/models/postgres.py#L7945)
+[backend/app/models/postgres.py:7967](../../backend/app/models/postgres.py#L7967)
One project export or import (W24 ADM-05 phase 1: settings + catalog; migration 0247).
@@ -3379,7 +3405,7 @@ Constraints and indexes:
## project_llm_quota
-[backend/app/models/postgres.py:6725](../../backend/app/models/postgres.py#L6725)
+[backend/app/models/postgres.py:6747](../../backend/app/models/postgres.py#L6747)
Per-project LLM spend config used by the usage-based billing gate.
@@ -3407,7 +3433,7 @@ Constraints and indexes:
## project_llm_usage
-[backend/app/models/postgres.py:8454](../../backend/app/models/postgres.py#L8454)
+[backend/app/models/postgres.py:8476](../../backend/app/models/postgres.py#L8476)
Running per-period LLM cost meter for a project.
@@ -3460,7 +3486,7 @@ Constraints and indexes:
## project_retention_policies
-[backend/app/models/postgres.py:8302](../../backend/app/models/postgres.py#L8302)
+[backend/app/models/postgres.py:8324](../../backend/app/models/postgres.py#L8324)
Per-project data retention policy (PMF US-11.4, migration 0113).
@@ -3539,7 +3565,7 @@ Constraints and indexes:
## project_workflow_defaults
-[backend/app/models/postgres.py:6522](../../backend/app/models/postgres.py#L6522)
+[backend/app/models/postgres.py:6530](../../backend/app/models/postgres.py#L6530)
A project's default workflow for one base (W14 AGT-08, migration 0230).
@@ -3622,7 +3648,7 @@ canonical_test_cases: Mapped[list['CanonicalTestCase']] = relationship('Canonica
## quarantine_lifecycle_policies
-[backend/app/models/postgres.py:7697](../../backend/app/models/postgres.py#L7697)
+[backend/app/models/postgres.py:7719](../../backend/app/models/postgres.py#L7719)
Per-project quarantine lifecycle configuration (PMF US-5.4/5.5/5.6).
@@ -4019,7 +4045,7 @@ test_run_links: Mapped[list['ReleaseTestRunLink']] = relationship('ReleaseTestRu
## report_exports
-[backend/app/models/postgres.py:8251](../../backend/app/models/postgres.py#L8251)
+[backend/app/models/postgres.py:8273](../../backend/app/models/postgres.py#L8273)
VIZ-607: one background export of a report (migration 0194).
@@ -4122,7 +4148,7 @@ Constraints and indexes:
## retention_holds
-[backend/app/models/postgres.py:8165](../../backend/app/models/postgres.py#L8165)
+[backend/app/models/postgres.py:8187](../../backend/app/models/postgres.py#L8187)
A retention hold on a project, a release, a run or a compliance pack (W22a ACT-05, migration 0239).
@@ -4178,7 +4204,7 @@ Constraints and indexes:
## review_requests
-[backend/app/models/postgres.py:6217](../../backend/app/models/postgres.py#L6217)
+[backend/app/models/postgres.py:6225](../../backend/app/models/postgres.py#L6225)
One human review for one AI report-producing run (architecture section 8.1).
@@ -4532,7 +4558,7 @@ Constraints and indexes:
## run_tombstones
-[backend/app/models/postgres.py:7779](../../backend/app/models/postgres.py#L7779)
+[backend/app/models/postgres.py:7801](../../backend/app/models/postgres.py#L7801)
A run that was deliberately deleted, and must not come back (0148, S2c).
@@ -4899,7 +4925,7 @@ Constraints and indexes:
## subject_erasure_requests
-[backend/app/models/postgres.py:8112](../../backend/app/models/postgres.py#L8112)
+[backend/app/models/postgres.py:8134](../../backend/app/models/postgres.py#L8134)
A person's request to have their account erased (W38: W31 F-1; migration 0256).
@@ -4938,7 +4964,7 @@ Constraints and indexes:
## subject_rights_jobs
-[backend/app/models/postgres.py:8036](../../backend/app/models/postgres.py#L8036)
+[backend/app/models/postgres.py:8058](../../backend/app/models/postgres.py#L8058)
One personal-data export or erasure of ONE person (W31 STRAT-12; migration 0253).
@@ -5193,7 +5219,7 @@ Constraints and indexes:
## systemic_cluster_epics
-[backend/app/models/postgres.py:6941](../../backend/app/models/postgres.py#L6941)
+[backend/app/models/postgres.py:6963](../../backend/app/models/postgres.py#L6963)
A Jira epic a person filed for a recurring systemic cluster (W36 STRAT-03; migration 0255).
@@ -5225,7 +5251,7 @@ Constraints and indexes:
## systemic_flake_cluster
-[backend/app/models/postgres.py:6886](../../backend/app/models/postgres.py#L6886)
+[backend/app/models/postgres.py:6908](../../backend/app/models/postgres.py#L6908)
@@ -5252,7 +5278,7 @@ Constraints and indexes:
## systemic_flake_cluster_member
-[backend/app/models/postgres.py:6921](../../backend/app/models/postgres.py#L6921)
+[backend/app/models/postgres.py:6943](../../backend/app/models/postgres.py#L6943)
@@ -6257,7 +6283,7 @@ Constraints and indexes:
## value_metric_assumptions
-[backend/app/models/postgres.py:7738](../../backend/app/models/postgres.py#L7738)
+[backend/app/models/postgres.py:7760](../../backend/app/models/postgres.py#L7760)
Per-project tunable assumptions for the engineer-hours-saved model
(PMF US-12.1, migration 0112).
@@ -6290,7 +6316,7 @@ Constraints and indexes:
## webhook_deliveries
-[backend/app/models/postgres.py:7217](../../backend/app/models/postgres.py#L7217)
+[backend/app/models/postgres.py:7239](../../backend/app/models/postgres.py#L7239)
Audit trail for every webhook delivery attempt.
@@ -6333,7 +6359,7 @@ Constraints and indexes:
## webhook_subscriptions
-[backend/app/models/postgres.py:7158](../../backend/app/models/postgres.py#L7158)
+[backend/app/models/postgres.py:7180](../../backend/app/models/postgres.py#L7180)
Customer-managed outbound webhook subscription.
@@ -6370,7 +6396,7 @@ Constraints and indexes:
## workflow_definitions
-[backend/app/models/postgres.py:6428](../../backend/app/models/postgres.py#L6428)
+[backend/app/models/postgres.py:6436](../../backend/app/models/postgres.py#L6436)
One immutable-on-publish version of a project workflow (E3.1).
@@ -6420,7 +6446,7 @@ Constraints and indexes:
## workflow_replay_corpus
-[backend/app/models/postgres.py:6560](../../backend/app/models/postgres.py#L6560)
+[backend/app/models/postgres.py:6568](../../backend/app/models/postgres.py#L6568)
A project run output cached for deterministic workflow evaluation (E9.5).
diff --git a/docs/reference/migrations.md b/docs/reference/migrations.md
index a74b71d02..27a625f88 100644
--- a/docs/reference/migrations.md
+++ b/docs/reference/migrations.md
@@ -268,3 +268,5 @@ Alembic revisions extracted without executing migrations. An inventory is not ev
| [backend/migrations/versions/0258_test_case_category_source.py](../../backend/migrations/versions/0258_test_case_category_source.py) | `'0258'` | `'0257'` | Who set a test case's failure category: a person or an analysis. |
| [backend/migrations/versions/0259_test_runs_project_run_time_index.py](../../backend/migrations/versions/0259_test_runs_project_run_time_index.py) | `'0259'` | `'0258'` | Index a project's runs by run time (product finding D-19). |
| [backend/migrations/versions/0260_flaky_quarantine_proposed_by.py](../../backend/migrations/versions/0260_flaky_quarantine_proposed_by.py) | `'0260'` | `'0259'` | Who proposed a flaky-test quarantine (product finding D-53). |
+| [backend/migrations/versions/0261_nightly_job_observations.py](../../backend/migrations/versions/0261_nightly_job_observations.py) | `'0261'` | `'0260'` | Persist the latest observed attempt and success of two nightly jobs. |
+| [backend/migrations/versions/0262_digest_delivery_observations.py](../../backend/migrations/versions/0262_digest_delivery_observations.py) | `'0262'` | `'0261'` | Preserve scheduled digest due work independently of its dispatch claim. |
diff --git a/docs/reference/worker-operations.md b/docs/reference/worker-operations.md
index 5dc16f9e8..a636f92d3 100644
--- a/docs/reference/worker-operations.md
+++ b/docs/reference/worker-operations.md
@@ -21,7 +21,7 @@ Static declarations, not observations of running consumers. Deployment profiles
## beat_schedule
```python
-{'daily-coverage-snapshot': {'task': 'app.worker.tasks.take_coverage_snapshot', 'schedule': crontab(hour=0, minute=5)}, 'daily-agent-eval': {'task': 'app.worker.tasks.run_scheduled_agent_eval', 'schedule': crontab(hour=4, minute=0), 'options': {'queue': 'default'}}, 'weekly-agent-quality-drift': {'task': 'app.worker.tasks.run_weekly_agent_quality_drift', 'schedule': crontab(hour=6, minute=0, day_of_week='monday'), 'options': {'queue': 'default'}}, 'hourly-retention-purge': {'task': 'app.worker.tasks.run_retention_purges', 'schedule': crontab(minute=0)}, 'nightly-search-usage-purge': {'task': 'app.worker.tasks.purge_search_usage_events', 'schedule': crontab(hour=2, minute=40), 'options': {'queue': 'default'}}, 'expire-unlabelled-shadow-pairs': {'task': 'app.worker.tasks.expire_unlabelled_shadow_pairs', 'schedule': crontab(hour=2, minute=50), 'options': {'queue': 'default'}}, 'golden-match-shadow-pairs': {'task': 'app.worker.tasks.golden_match_shadow_pairs', 'schedule': crontab(hour=3, minute=50), 'options': {'queue': 'default'}}, 'reconcile-stale-eval-runs': {'task': 'app.worker.tasks.reconcile_stale_eval_runs', 'schedule': crontab(minute='*/10'), 'options': {'queue': 'default'}}, 'nightly-report-export-sweep': {'task': 'app.worker.tasks.sweep_report_exports', 'schedule': crontab(hour=1, minute=15)}, 'weekly-training-export': {'task': 'app.worker.training_tasks.export_training_data', 'schedule': crontab(hour=2, minute=0, day_of_week='sunday')}, 'daily-finetune-trigger-check': {'task': 'app.worker.training_tasks.check_finetune_trigger', 'schedule': crontab(hour=3, minute=0)}, 'nightly-ml-classifier-training': {'task': 'app.worker.tasks.train_ml_classifier', 'schedule': crontab(hour=3, minute=10), 'kwargs': {'triggered_by': 'beat'}}, 'hourly-search-reindex': {'task': 'app.worker.tasks.reindex_search', 'schedule': crontab(minute=30)}, 'daily-digest-dispatch': {'task': 'app.worker.tasks.dispatch_scheduled_digests', 'schedule': crontab(hour=7, minute=0)}, 'integration-health-probes': {'task': 'app.worker.tasks.run_integration_health_probes', 'schedule': crontab(minute='*/15')}, 'jira-defect-status-sync': {'task': 'app.worker.tasks.sync_jira_defect_statuses', 'schedule': crontab(minute='5-59/15')}, 'knowledge-source-resync': {'task': 'app.worker.tasks.resync_stale_knowledge_sources', 'schedule': crontab(minute=0, hour='*/4')}, 'reconcile-active-releases': {'task': 'app.worker.tasks.reconcile_active_releases', 'schedule': crontab(minute=20)}, 'reconcile-primary-releases': {'task': 'app.worker.tasks.reconcile_primary_releases', 'schedule': crontab(minute=50)}, 'reconcile-release-sort-keys': {'task': 'app.worker.tasks.reconcile_release_sort_keys', 'schedule': crontab(minute=35)}, 'nightly-flaky-confidence-training': {'task': 'app.worker.tasks.train_flaky_confidence_model', 'schedule': crontab(hour=3, minute=30)}, 'close-stale-live-sessions': {'task': 'app.worker.tasks.close_stale_live_sessions', 'schedule': crontab(minute='*/2'), 'kwargs': {'idle_minutes': 5}}, 'reap-stuck-agent-pipelines': {'task': 'app.worker.tasks.reap_stuck_agent_pipelines', 'schedule': crontab(minute='*/10')}, 'relay-agent-child-dispatch-outbox': {'task': 'app.worker.tasks.relay_agent_child_dispatch_outbox', 'schedule': crontab(minute='*')}, 'process-decision-report-supersessions': {'task': 'app.worker.tasks.process_decision_report_supersessions', 'schedule': crontab(minute='*')}, 'relay-agent-action-dispatch-outbox': {'task': 'app.worker.tasks.relay_agent_action_dispatch_outbox', 'schedule': crontab(minute='*')}, 'reap-stuck-agent-actions': {'task': 'app.worker.tasks.reap_stuck_agent_actions', 'schedule': crontab(minute='*/5')}, 'relay-run-downstream-outbox': {'task': 'app.worker.tasks.relay_run_downstream_outbox', 'schedule': crontab(minute='*')}, 'relay-queued-criteria-deletions': {'task': 'app.worker.tasks.relay_queued_criteria_deletions', 'schedule': crontab(minute='*')}, 'sweep-deletion-exports': {'task': 'app.worker.tasks.sweep_deletion_exports', 'schedule': crontab(minute='*/15'), 'options': {'queue': 'default'}}, 'sweep-project-data-jobs': {'task': 'app.worker.tasks.sweep_project_data_jobs', 'schedule': crontab(minute=35), 'options': {'queue': 'default'}}, 'sweep-subject-rights-jobs': {'task': 'app.worker.tasks.sweep_subject_rights_jobs', 'schedule': crontab(minute=50), 'options': {'queue': 'default'}}, 'recover-waiting-run-finalizations': {'task': 'app.worker.tasks.recover_waiting_run_finalizations', 'schedule': crontab(minute='*')}, 'relay-pending-webhook-deliveries': {'task': 'app.worker.tasks.relay_pending_webhook_deliveries', 'schedule': crontab(minute='*')}, 'relay-pending-notification-deliveries': {'task': 'app.worker.tasks.relay_pending_notification_deliveries', 'schedule': crontab(minute='*')}, 'nightly-flaky-quarantine-maintenance': {'task': 'app.worker.tasks.run_flaky_quarantine_maintenance', 'schedule': crontab(hour=4, minute=0)}, 'nightly-perf-baseline-refresh': {'task': 'app.worker.tasks.refresh_perf_baselines', 'schedule': crontab(hour=4, minute=30)}, 'monday-weekly-retro-digests': {'task': 'app.worker.tasks.dispatch_scheduled_digests', 'schedule': crontab(hour=7, minute=5, day_of_week='monday')}, 'monday-weekly-flaky-debt-reviews': {'task': 'app.worker.tasks.dispatch_weekly_flaky_debt_reviews', 'schedule': crontab(hour=7, minute=10, day_of_week='monday')}, 'daily-fixer-runs': {'task': 'app.worker.tasks.dispatch_scheduled_fixer_runs', 'schedule': crontab(hour=6, minute=0), 'args': ('daily',)}, 'weekly-fixer-runs': {'task': 'app.worker.tasks.dispatch_scheduled_fixer_runs', 'schedule': crontab(hour=6, minute=15, day_of_week='monday'), 'args': ('weekly',)}, 'poll-fixer-pr-outcomes': {'task': 'app.worker.tasks.poll_fixer_pr_outcomes', 'schedule': crontab(minute='*/30')}, 'nightly-orphan-test-suite-flag': {'task': 'app.worker.tasks.flag_orphan_test_suites', 'schedule': crontab(hour=5, minute=0)}, 'nightly-canonical-deletion-reconcile': {'task': 'app.worker.tasks.reconcile_canonical_deletions', 'schedule': crontab(hour=5, minute=30)}, 'daily-suite-membership-parity': {'task': 'app.worker.tasks.run_suite_membership_parity', 'schedule': crontab(hour=6, minute=15), 'kwargs': {'trigger': 'beat'}, 'options': {'queue': 'default', 'ignore_result': True}}, 'nightly-flaky-classifier-calibration': {'task': 'app.worker.tasks.calibrate_flaky_classifiers', 'schedule': crontab(hour=5, minute=45)}, 'nightly-flaky-score-recompute': {'task': 'app.worker.tasks.recompute_flaky_scores', 'schedule': crontab(hour=6, minute=10)}, 'nightly-systemic-cluster-recompute': {'task': 'app.worker.tasks.recompute_systemic_clusters', 'schedule': crontab(hour=6, minute=40)}, 'screen-new-test-fingerprints': {'task': 'app.worker.tasks.screen_new_test_fingerprints', 'schedule': crontab(minute='*/30')}, 'nightly-flaky-detection-sweep': {'task': 'app.worker.tasks.sweep_flaky_detection', 'schedule': crontab(hour=6, minute=55)}, 'backfill-unassigned-failures': {'task': 'app.worker.tasks.backfill_unassigned_failures', 'schedule': crontab(minute='*/15')}, 'drain-active-live-sessions': {'task': 'app.worker.tasks.drain_active_live_sessions', 'schedule': timedelta(seconds=30)}, 'backfill-placeholder-test-cases': {'task': 'app.worker.tasks.backfill_placeholder_test_cases', 'schedule': crontab(minute=10)}, 'backfill-suite-executions': {'task': 'app.worker.tasks.backfill_suite_executions', 'schedule': crontab(minute='*/10')}, 'backfill-ai-run-versions': {'task': 'app.worker.tasks.backfill_ai_run_versions', 'schedule': crontab(minute='5,15,25,35,45,55')}, 'auto-recover-completed-live-runs': {'task': 'app.worker.tasks.auto_recover_completed_live_runs', 'schedule': timedelta(minutes=2)}, 'nightly-duplicate-detection': {'task': 'app.worker.tasks.run_duplicate_detection', 'schedule': crontab(hour=6, minute=0)}, 'hourly-cross-run-insights': {'task': 'app.worker.tasks.detect_cross_run_insights', 'schedule': crontab(minute=40), 'options': {'queue': 'default'}}, 'quarter-hourly-run-cadence-check': {'task': 'app.worker.tasks.check_run_cadences', 'schedule': crontab(minute='7-59/15'), 'options': {'queue': 'default'}}, 'watch-drop-folders': {'task': 'app.worker.tasks.watch_drop_folders', 'schedule': crontab(minute='*'), 'options': {'queue': 'default'}}}
+{'daily-coverage-snapshot': {'task': 'app.worker.tasks.take_coverage_snapshot', 'schedule': crontab(hour=0, minute=5)}, 'daily-agent-eval': {'task': 'app.worker.tasks.run_scheduled_agent_eval', 'schedule': crontab(hour=4, minute=0), 'options': {'queue': 'default'}}, 'weekly-agent-quality-drift': {'task': 'app.worker.tasks.run_weekly_agent_quality_drift', 'schedule': crontab(hour=6, minute=0, day_of_week='monday'), 'options': {'queue': 'default'}}, 'hourly-retention-purge': {'task': 'app.worker.tasks.run_retention_purges', 'schedule': crontab(minute=0)}, 'nightly-search-usage-purge': {'task': 'app.worker.tasks.purge_search_usage_events', 'schedule': crontab(hour=2, minute=40), 'options': {'queue': 'default'}}, 'expire-unlabelled-shadow-pairs': {'task': 'app.worker.tasks.expire_unlabelled_shadow_pairs', 'schedule': crontab(hour=2, minute=50), 'options': {'queue': 'default'}}, 'golden-match-shadow-pairs': {'task': 'app.worker.tasks.golden_match_shadow_pairs', 'schedule': crontab(hour=3, minute=50), 'options': {'queue': 'default'}}, 'reconcile-stale-eval-runs': {'task': 'app.worker.tasks.reconcile_stale_eval_runs', 'schedule': crontab(minute='*/10'), 'options': {'queue': 'default'}}, 'nightly-report-export-sweep': {'task': 'app.worker.tasks.sweep_report_exports', 'schedule': crontab(hour=1, minute=15)}, 'weekly-training-export': {'task': 'app.worker.training_tasks.export_training_data', 'schedule': crontab(hour=2, minute=0, day_of_week='sunday')}, 'daily-finetune-trigger-check': {'task': 'app.worker.training_tasks.check_finetune_trigger', 'schedule': crontab(hour=3, minute=0)}, 'nightly-ml-classifier-training': {'task': 'app.worker.tasks.train_ml_classifier', 'schedule': crontab(hour=3, minute=10), 'kwargs': {'triggered_by': 'beat'}}, 'hourly-search-reindex': {'task': 'app.worker.tasks.reindex_search', 'schedule': crontab(minute=30)}, 'daily-digest-dispatch': {'task': 'app.worker.tasks.dispatch_scheduled_digests', 'schedule': crontab(hour=7, minute=0)}, 'integration-health-probes': {'task': 'app.worker.tasks.run_integration_health_probes', 'schedule': crontab(minute='*/15')}, 'jira-defect-status-sync': {'task': 'app.worker.tasks.sync_jira_defect_statuses', 'schedule': crontab(minute='5-59/15')}, 'knowledge-source-resync': {'task': 'app.worker.tasks.resync_stale_knowledge_sources', 'schedule': crontab(minute=0, hour='*/4')}, 'reconcile-active-releases': {'task': 'app.worker.tasks.reconcile_active_releases', 'schedule': crontab(minute=20)}, 'reconcile-primary-releases': {'task': 'app.worker.tasks.reconcile_primary_releases', 'schedule': crontab(minute=50)}, 'reconcile-release-sort-keys': {'task': 'app.worker.tasks.reconcile_release_sort_keys', 'schedule': crontab(minute=35)}, 'nightly-flaky-confidence-training': {'task': 'app.worker.tasks.train_flaky_confidence_model', 'schedule': crontab(hour=3, minute=30)}, 'close-stale-live-sessions': {'task': 'app.worker.tasks.close_stale_live_sessions', 'schedule': crontab(minute='*/2'), 'kwargs': {'idle_minutes': 5}}, 'reap-stuck-agent-pipelines': {'task': 'app.worker.tasks.reap_stuck_agent_pipelines', 'schedule': crontab(minute='*/10')}, 'relay-agent-child-dispatch-outbox': {'task': 'app.worker.tasks.relay_agent_child_dispatch_outbox', 'schedule': crontab(minute='*')}, 'process-decision-report-supersessions': {'task': 'app.worker.tasks.process_decision_report_supersessions', 'schedule': crontab(minute='*')}, 'relay-agent-action-dispatch-outbox': {'task': 'app.worker.tasks.relay_agent_action_dispatch_outbox', 'schedule': crontab(minute='*')}, 'reap-stuck-agent-actions': {'task': 'app.worker.tasks.reap_stuck_agent_actions', 'schedule': crontab(minute='*/5')}, 'relay-run-downstream-outbox': {'task': 'app.worker.tasks.relay_run_downstream_outbox', 'schedule': crontab(minute='*')}, 'relay-queued-criteria-deletions': {'task': 'app.worker.tasks.relay_queued_criteria_deletions', 'schedule': crontab(minute='*')}, 'sweep-deletion-exports': {'task': 'app.worker.tasks.sweep_deletion_exports', 'schedule': crontab(minute='*/15'), 'options': {'queue': 'default'}}, 'sweep-project-data-jobs': {'task': 'app.worker.tasks.sweep_project_data_jobs', 'schedule': crontab(minute=35), 'options': {'queue': 'default'}}, 'sweep-subject-rights-jobs': {'task': 'app.worker.tasks.sweep_subject_rights_jobs', 'schedule': crontab(minute=50), 'options': {'queue': 'default'}}, 'recover-waiting-run-finalizations': {'task': 'app.worker.tasks.recover_waiting_run_finalizations', 'schedule': crontab(minute='*')}, 'relay-pending-webhook-deliveries': {'task': 'app.worker.tasks.relay_pending_webhook_deliveries', 'schedule': crontab(minute='*')}, 'relay-pending-notification-deliveries': {'task': 'app.worker.tasks.relay_pending_notification_deliveries', 'schedule': crontab(minute='*')}, 'nightly-flaky-quarantine-maintenance': {'task': 'app.worker.tasks.run_flaky_quarantine_maintenance', 'schedule': crontab(hour=QUARANTINE_MAINTENANCE.hour, minute=QUARANTINE_MAINTENANCE.minute), 'options': {'headers': {SCHEDULE_HEADER: QUARANTINE_MAINTENANCE.key}}}, 'nightly-perf-baseline-refresh': {'task': 'app.worker.tasks.refresh_perf_baselines', 'schedule': crontab(hour=PERF_BASELINE_REFRESH.hour, minute=PERF_BASELINE_REFRESH.minute), 'options': {'headers': {SCHEDULE_HEADER: PERF_BASELINE_REFRESH.key}}}, 'monday-weekly-retro-digests': {'task': 'app.worker.tasks.dispatch_scheduled_digests', 'schedule': crontab(hour=7, minute=5, day_of_week='monday')}, 'monday-weekly-flaky-debt-reviews': {'task': 'app.worker.tasks.dispatch_weekly_flaky_debt_reviews', 'schedule': crontab(hour=7, minute=10, day_of_week='monday')}, 'daily-fixer-runs': {'task': 'app.worker.tasks.dispatch_scheduled_fixer_runs', 'schedule': crontab(hour=6, minute=0), 'args': ('daily',)}, 'weekly-fixer-runs': {'task': 'app.worker.tasks.dispatch_scheduled_fixer_runs', 'schedule': crontab(hour=6, minute=15, day_of_week='monday'), 'args': ('weekly',)}, 'poll-fixer-pr-outcomes': {'task': 'app.worker.tasks.poll_fixer_pr_outcomes', 'schedule': crontab(minute='*/30')}, 'nightly-orphan-test-suite-flag': {'task': 'app.worker.tasks.flag_orphan_test_suites', 'schedule': crontab(hour=5, minute=0)}, 'nightly-canonical-deletion-reconcile': {'task': 'app.worker.tasks.reconcile_canonical_deletions', 'schedule': crontab(hour=5, minute=30)}, 'daily-suite-membership-parity': {'task': 'app.worker.tasks.run_suite_membership_parity', 'schedule': crontab(hour=6, minute=15), 'kwargs': {'trigger': 'beat'}, 'options': {'queue': 'default', 'ignore_result': True}}, 'nightly-flaky-classifier-calibration': {'task': 'app.worker.tasks.calibrate_flaky_classifiers', 'schedule': crontab(hour=5, minute=45)}, 'nightly-flaky-score-recompute': {'task': 'app.worker.tasks.recompute_flaky_scores', 'schedule': crontab(hour=6, minute=10)}, 'nightly-systemic-cluster-recompute': {'task': 'app.worker.tasks.recompute_systemic_clusters', 'schedule': crontab(hour=6, minute=40)}, 'screen-new-test-fingerprints': {'task': 'app.worker.tasks.screen_new_test_fingerprints', 'schedule': crontab(minute='*/30')}, 'nightly-flaky-detection-sweep': {'task': 'app.worker.tasks.sweep_flaky_detection', 'schedule': crontab(hour=6, minute=55)}, 'backfill-unassigned-failures': {'task': 'app.worker.tasks.backfill_unassigned_failures', 'schedule': crontab(minute='*/15')}, 'drain-active-live-sessions': {'task': 'app.worker.tasks.drain_active_live_sessions', 'schedule': timedelta(seconds=30)}, 'backfill-placeholder-test-cases': {'task': 'app.worker.tasks.backfill_placeholder_test_cases', 'schedule': crontab(minute=10)}, 'backfill-suite-executions': {'task': 'app.worker.tasks.backfill_suite_executions', 'schedule': crontab(minute='*/10')}, 'backfill-ai-run-versions': {'task': 'app.worker.tasks.backfill_ai_run_versions', 'schedule': crontab(minute='5,15,25,35,45,55')}, 'auto-recover-completed-live-runs': {'task': 'app.worker.tasks.auto_recover_completed_live_runs', 'schedule': timedelta(minutes=2)}, 'nightly-duplicate-detection': {'task': 'app.worker.tasks.run_duplicate_detection', 'schedule': crontab(hour=6, minute=0)}, 'hourly-cross-run-insights': {'task': 'app.worker.tasks.detect_cross_run_insights', 'schedule': crontab(minute=40), 'options': {'queue': 'default'}}, 'quarter-hourly-run-cadence-check': {'task': 'app.worker.tasks.check_run_cadences', 'schedule': crontab(minute='7-59/15'), 'options': {'queue': 'default'}}, 'watch-drop-folders': {'task': 'app.worker.tasks.watch_drop_folders', 'schedule': crontab(minute='*'), 'options': {'queue': 'default'}}}
```
## worker_prefetch_multiplier
@@ -50,7 +50,7 @@ True
## queue_delivery_probe
-[backend/app/worker/celery_app.py:58](../../backend/app/worker/celery_app.py#L58)
+[backend/app/worker/celery_app.py:63](../../backend/app/worker/celery_app.py#L63)
Return transport attribution for the release queue-consumption proof.
@@ -705,7 +705,7 @@ refresh_perf_baselines(self)
## deliver_webhook
-[backend/app/worker/tasks.py:5157](../../backend/app/worker/tasks.py#L5157)
+[backend/app/worker/tasks.py:5160](../../backend/app/worker/tasks.py#L5160)
Deliver a single webhook subscription event.
@@ -721,7 +721,7 @@ deliver_webhook(self, delivery_id: str, dispatch_token: str | None=None)
## run_flaky_quarantine_maintenance
-[backend/app/worker/tasks.py:5217](../../backend/app/worker/tasks.py#L5217)
+[backend/app/worker/tasks.py:5220](../../backend/app/worker/tasks.py#L5220)
Nightly housekeeping for the flaky auto-quarantine workflow.
@@ -751,7 +751,7 @@ run_flaky_quarantine_maintenance(self)
## train_flaky_confidence_model
-[backend/app/worker/tasks.py:5287](../../backend/app/worker/tasks.py#L5287)
+[backend/app/worker/tasks.py:5293](../../backend/app/worker/tasks.py#L5293)
Nightly retrain of the FLK-P3 flaky-confidence model from human
quarantine approve/reject decisions.
@@ -770,7 +770,7 @@ train_flaky_confidence_model(self)
## train_ml_classifier
-[backend/app/worker/tasks.py:5329](../../backend/app/worker/tasks.py#L5329)
+[backend/app/worker/tasks.py:5335](../../backend/app/worker/tasks.py#L5335)
Train the failure classifier once (``services/ml/trainer.train_classifier``).
@@ -792,7 +792,7 @@ train_ml_classifier(self, triggered_by: str='beat')
## run_integration_health_probes
-[backend/app/worker/tasks.py:5441](../../backend/app/worker/tasks.py#L5441)
+[backend/app/worker/tasks.py:5447](../../backend/app/worker/tasks.py#L5447)
Periodic task: probe all configured integrations and record health status.
@@ -808,7 +808,7 @@ run_integration_health_probes(self)
## enrich_run_ocp_metadata
-[backend/app/worker/tasks.py:5483](../../backend/app/worker/tasks.py#L5483)
+[backend/app/worker/tasks.py:5489](../../backend/app/worker/tasks.py#L5489)
Fetch the OpenShift pod metadata of a run the sentinel ingest committed.
@@ -827,7 +827,7 @@ enrich_run_ocp_metadata(self, run_id: str)
## sync_jira_defect_statuses
-[backend/app/worker/tasks.py:5532](../../backend/app/worker/tasks.py#L5532)
+[backend/app/worker/tasks.py:5538](../../backend/app/worker/tasks.py#L5538)
Periodic task: mirror Jira issue status onto linked OPEN defects.
@@ -844,7 +844,7 @@ sync_jira_defect_statuses(self)
## dispatch_scheduled_digests
-[backend/app/worker/tasks.py:5565](../../backend/app/worker/tasks.py#L5565)
+[backend/app/worker/tasks.py:5571](../../backend/app/worker/tasks.py#L5571)
Periodic task: find all digest subscriptions due for delivery and dispatch.
@@ -859,7 +859,7 @@ dispatch_scheduled_digests(self)
## dispatch_weekly_flaky_debt_reviews
-[backend/app/worker/tasks.py:5994](../../backend/app/worker/tasks.py#L5994)
+[backend/app/worker/tasks.py:6035](../../backend/app/worker/tasks.py#L6035)
Weekly beat (Mondays 07:10 UTC): send each channel-mapped team its
flaky-debt review draft through its team notification channel. Teams
@@ -879,7 +879,7 @@ dispatch_weekly_flaky_debt_reviews(self)
## close_stale_live_sessions
-[backend/app/worker/tasks.py:6030](../../backend/app/worker/tasks.py#L6030)
+[backend/app/worker/tasks.py:6071](../../backend/app/worker/tasks.py#L6071)
Periodic safety net for live sessions whose clients forget to send a
``run_complete`` event.
@@ -905,7 +905,7 @@ close_stale_live_sessions(self, idle_minutes: int=15)
## reap_stuck_agent_pipelines
-[backend/app/worker/tasks.py:6160](../../backend/app/worker/tasks.py#L6160)
+[backend/app/worker/tasks.py:6201](../../backend/app/worker/tasks.py#L6201)
Reclaim pipelines whose worker stopped renewing its lease (E7.3).
@@ -935,7 +935,7 @@ reap_stuck_agent_pipelines(self, stale_minutes: int=30)
## flag_orphan_test_suites
-[backend/app/worker/tasks.py:6321](../../backend/app/worker/tasks.py#L6321)
+[backend/app/worker/tasks.py:6362](../../backend/app/worker/tasks.py#L6362)
Detect and structured-log orphan ``TestSuite`` rows for ops review.
@@ -965,7 +965,7 @@ flag_orphan_test_suites(self, min_age_minutes: int=60)
## reconcile_canonical_deletions
-[backend/app/worker/tasks.py:6420](../../backend/app/worker/tasks.py#L6420)
+[backend/app/worker/tasks.py:6461](../../backend/app/worker/tasks.py#L6461)
Nightly safety net for canonical-deletion detection (Phase I follow-up).
@@ -992,7 +992,7 @@ reconcile_canonical_deletions(self)
## drain_active_live_sessions
-[backend/app/worker/tasks.py:6503](../../backend/app/worker/tasks.py#L6503)
+[backend/app/worker/tasks.py:6544](../../backend/app/worker/tasks.py#L6544)
Phase 4.5 — drain every active live session's Redis event buffer
into Postgres ``test_cases`` rows.
@@ -1014,7 +1014,7 @@ drain_active_live_sessions(self)
## backfill_placeholder_test_cases
-[backend/app/worker/tasks.py:6534](../../backend/app/worker/tasks.py#L6534)
+[backend/app/worker/tasks.py:6575](../../backend/app/worker/tasks.py#L6575)
Retroactively synthesize placeholder TestCase rows.
@@ -1038,7 +1038,7 @@ backfill_placeholder_test_cases(self, max_runs_per_project: int=500)
## backfill_suite_executions
-[backend/app/worker/tasks.py:6590](../../backend/app/worker/tasks.py#L6590)
+[backend/app/worker/tasks.py:6631](../../backend/app/worker/tasks.py#L6631)
EXEC-02: time every run that predates ``suite_executions`` -- one-shot, chunked, re-entrant.
@@ -1063,7 +1063,7 @@ backfill_suite_executions(self, chunk_size: int=500, max_chunks: int=40, time_bu
## backfill_ai_run_versions
-[backend/app/worker/tasks.py:6774](../../backend/app/worker/tasks.py#L6774)
+[backend/app/worker/tasks.py:6815](../../backend/app/worker/tasks.py#L6815)
AIH-01: give every run analysed before AI history existed its first versions -- one-shot,
chunked, re-entrant.
@@ -1089,7 +1089,7 @@ backfill_ai_run_versions(self, chunk_size: int=100, max_chunks: int=40, time_bud
## auto_recover_completed_live_runs
-[backend/app/worker/tasks.py:6811](../../backend/app/worker/tasks.py#L6811)
+[backend/app/worker/tasks.py:6852](../../backend/app/worker/tasks.py#L6852)
Recover REAL per-test rows from ``TestRun.event_archive`` for
completed live_stream runs whose ``test_cases`` table is empty.
@@ -1114,7 +1114,7 @@ auto_recover_completed_live_runs(self, lookback_hours: int=24, max_runs: int=100
## backfill_unassigned_failures
-[backend/app/worker/tasks.py:6882](../../backend/app/worker/tasks.py#L6882)
+[backend/app/worker/tasks.py:6923](../../backend/app/worker/tasks.py#L6923)
Retroactively assign FAILED/BROKEN TestCases left unassigned.
@@ -1139,7 +1139,7 @@ backfill_unassigned_failures(self, max_runs_per_project: int=200)
## notify_test_suite_owner
-[backend/app/worker/tasks.py:7006](../../backend/app/worker/tasks.py#L7006)
+[backend/app/worker/tasks.py:7047](../../backend/app/worker/tasks.py#L7047)
Dispatch the "test is failing repeatedly" notification email.
@@ -1154,7 +1154,7 @@ notify_test_suite_owner(self, *, to_email: str, owner_name: str, test_name: str,
## run_duplicate_detection
-[backend/app/worker/tasks.py:7105](../../backend/app/worker/tasks.py#L7105)
+[backend/app/worker/tasks.py:7146](../../backend/app/worker/tasks.py#L7146)
Phase 4 — tiered duplicate authored-test-case detection per project.
@@ -1183,7 +1183,7 @@ run_duplicate_detection(self, project_id: str | None=None, enable_semantic: bool
## persist_ai_eval_shadow_pair
-[backend/app/worker/tasks.py:7432](../../backend/app/worker/tasks.py#L7432)
+[backend/app/worker/tasks.py:7473](../../backend/app/worker/tasks.py#L7473)
Persist one sampled live pair as a pending labelling candidate.
@@ -1194,7 +1194,7 @@ persist_ai_eval_shadow_pair(self, *, project_id: str, agent_id: str, sample_key:
## run_scheduled_agent_eval
-[backend/app/worker/tasks.py:7477](../../backend/app/worker/tasks.py#L7477)
+[backend/app/worker/tasks.py:7518](../../backend/app/worker/tasks.py#L7518)
Evaluate the agent stack against the golden datasets, on a schedule (F-11).
@@ -1218,7 +1218,7 @@ run_scheduled_agent_eval(self, change_id: str | None=None)
## run_weekly_agent_quality_drift
-[backend/app/worker/tasks.py:7568](../../backend/app/worker/tasks.py#L7568)
+[backend/app/worker/tasks.py:7609](../../backend/app/worker/tasks.py#L7609)
Run G5 and commit capability review pins once each Monday.
@@ -1229,7 +1229,7 @@ run_weekly_agent_quality_drift(self)
## run_candidate_evaluation
-[backend/app/worker/tasks.py:7662](../../backend/app/worker/tasks.py#L7662)
+[backend/app/worker/tasks.py:7703](../../backend/app/worker/tasks.py#L7703)
Replay one queued candidate evaluation (W16 AGT-09 b).
@@ -1245,7 +1245,7 @@ run_candidate_evaluation(self, run_id: str)
## reconcile_stale_eval_runs
-[backend/app/worker/tasks.py:7702](../../backend/app/worker/tasks.py#L7702)
+[backend/app/worker/tasks.py:7743](../../backend/app/worker/tasks.py#L7743)
Every 10 min: a replay silent for 15 min -> ``partial`` / ``worker_lost``;
a ``queued`` one never delivered -> ``failed``. Never re-dispatched.
@@ -1257,7 +1257,7 @@ reconcile_stale_eval_runs(self)
## golden_match_shadow_pairs
-[backend/app/worker/tasks.py:7735](../../backend/app/worker/tasks.py#L7735)
+[backend/app/worker/tasks.py:7776](../../backend/app/worker/tasks.py#L7776)
Nightly (03:50 UTC, after the 03:10 ML training): label pending
``root_cause:`` shadow pairs from the test case's OWN human feedback
@@ -1270,7 +1270,7 @@ golden_match_shadow_pairs(self)
## expire_unlabelled_shadow_pairs
-[backend/app/worker/tasks.py:7768](../../backend/app/worker/tasks.py#L7768)
+[backend/app/worker/tasks.py:7809](../../backend/app/worker/tasks.py#L7809)
Nightly (02:50 UTC, after the 02:40 search-usage purge): delete PENDING
shadow pairs older than 30 days, deployment-wide, in committed batches
@@ -1283,7 +1283,7 @@ expire_unlabelled_shadow_pairs(self)
## generate_report_export
-[backend/app/worker/tasks.py:7786](../../backend/app/worker/tasks.py#L7786)
+[backend/app/worker/tasks.py:7827](../../backend/app/worker/tasks.py#L7827)
VIZ-607: render one background report export and store the file.
@@ -1301,7 +1301,7 @@ generate_report_export(export_id: str)
## sweep_report_exports
-[backend/app/worker/tasks.py:7802](../../backend/app/worker/tasks.py#L7802)
+[backend/app/worker/tasks.py:7843](../../backend/app/worker/tasks.py#L7843)
VIZ-607: delete report export files and rows past their 7 days.
@@ -1314,7 +1314,7 @@ sweep_report_exports()
## run_retention_purges
-[backend/app/worker/tasks.py:7822](../../backend/app/worker/tasks.py#L7822)
+[backend/app/worker/tasks.py:7863](../../backend/app/worker/tasks.py#L7863)
Hourly retention purge sweep (the ``:00`` beat), or a single-project
execute-mode purge when enqueued from the router with ``project_id``.
@@ -1332,7 +1332,7 @@ run_retention_purges(self, project_id: str | None=None)
## calibrate_flaky_classifiers
-[backend/app/worker/tasks.py:7850](../../backend/app/worker/tasks.py#L7850)
+[backend/app/worker/tasks.py:7891](../../backend/app/worker/tasks.py#L7891)
Measure how well the flaky classifier actually works, per project.
@@ -1351,7 +1351,7 @@ calibrate_flaky_classifiers(self, project_id: str | None=None)
## recompute_flaky_scores
-[backend/app/worker/tasks.py:7924](../../backend/app/worker/tasks.py#L7924)
+[backend/app/worker/tasks.py:7965](../../backend/app/worker/tasks.py#L7965)
Recompute the continuous flakiness score per project (roadmap Phase 2).
@@ -1369,7 +1369,7 @@ recompute_flaky_scores(self, project_id: str | None=None)
## recompute_systemic_clusters
-[backend/app/worker/tasks.py:7989](../../backend/app/worker/tasks.py#L7989)
+[backend/app/worker/tasks.py:8030](../../backend/app/worker/tasks.py#L8030)
Rebuild systemic co-failure clusters per project (roadmap Phase 3).
@@ -1386,7 +1386,7 @@ recompute_systemic_clusters(self, project_id: str | None=None)
## screen_new_test_fingerprints
-[backend/app/worker/tasks.py:8070](../../backend/app/worker/tasks.py#L8070)
+[backend/app/worker/tasks.py:8111](../../backend/app/worker/tasks.py#L8111)
Tier 1 of roadmap Phase 6: screen the new and directly-modified.
@@ -1408,7 +1408,7 @@ screen_new_test_fingerprints(self, project_id: str | None=None)
## sweep_flaky_detection
-[backend/app/worker/tasks.py:8153](../../backend/app/worker/tasks.py#L8153)
+[backend/app/worker/tasks.py:8194](../../backend/app/worker/tasks.py#L8194)
Tier 2 of roadmap Phase 6: the continuous whole-corpus pass.
@@ -1431,7 +1431,7 @@ sweep_flaky_detection(self, project_id: str | None=None)
## delete_run_everywhere
-[backend/app/worker/tasks.py:8234](../../backend/app/worker/tasks.py#L8234)
+[backend/app/worker/tasks.py:8275](../../backend/app/worker/tasks.py#L8275)
Delete ONE run across all five stores. Irreversible.
@@ -1461,7 +1461,7 @@ delete_run_everywhere(self, run_id: str, job_id: str | None=None, reason: str=''
## sweep_deletion_exports
-[backend/app/worker/tasks.py:8533](../../backend/app/worker/tasks.py#L8533)
+[backend/app/worker/tasks.py:8574](../../backend/app/worker/tasks.py#L8574)
The export janitor (W22b ACT-03 E-10, every 15 minutes): expire
uncollected archives (their jobs end ``expired``, nothing deleted), fail
@@ -1475,7 +1475,7 @@ sweep_deletion_exports(self)
## execute_criteria_deletion_task
-[backend/app/worker/tasks.py:8551](../../backend/app/worker/tasks.py#L8551)
+[backend/app/worker/tasks.py:8592](../../backend/app/worker/tasks.py#L8592)
Replay a frozen candidate set, one run at a time.
@@ -1497,7 +1497,7 @@ execute_criteria_deletion_task(self, job_id: str, project_id: str, requested_by_
## reconcile_active_releases
-[backend/app/worker/tasks.py:8851](../../backend/app/worker/tasks.py#L8851)
+[backend/app/worker/tasks.py:8892](../../backend/app/worker/tasks.py#L8892)
Sweep for projects with no active release, repair them, and REPORT.
@@ -1525,7 +1525,7 @@ reconcile_active_releases(self)
## reconcile_primary_releases
-[backend/app/worker/tasks.py:8943](../../backend/app/worker/tasks.py#L8943)
+[backend/app/worker/tasks.py:8984](../../backend/app/worker/tasks.py#L8984)
Repair drift between ``test_runs.primary_release_id`` and the link table.
@@ -1547,7 +1547,7 @@ reconcile_primary_releases(self)
## reconcile_release_sort_keys
-[backend/app/worker/tasks.py:9030](../../backend/app/worker/tasks.py#L9030)
+[backend/app/worker/tasks.py:9071](../../backend/app/worker/tasks.py#L9071)
Fill in ``releases.sort_key`` for rows that have none.
@@ -1570,7 +1570,7 @@ reconcile_release_sort_keys(self)
## run_agent_invocation
-[backend/app/worker/tasks.py:9099](../../backend/app/worker/tasks.py#L9099)
+[backend/app/worker/tasks.py:9140](../../backend/app/worker/tasks.py#L9140)
Run one agent invoked through ``POST /api/v1/agents/{agent_id}/invoke`` (E1.2).
@@ -1587,7 +1587,7 @@ run_agent_invocation(self, invocation_id: str)
## detect_cross_run_insights
-[backend/app/worker/tasks.py:9364](../../backend/app/worker/tasks.py#L9364)
+[backend/app/worker/tasks.py:9405](../../backend/app/worker/tasks.py#L9405)
Scheduled task (beat, hourly at :40): the cross-run insights (W23a FAIL-11).
@@ -1604,7 +1604,7 @@ detect_cross_run_insights(self)
## check_run_cadences
-[backend/app/worker/tasks.py:9393](../../backend/app/worker/tasks.py#L9393)
+[backend/app/worker/tasks.py:9434](../../backend/app/worker/tasks.py#L9434)
Scheduled task (beat, every 15 min at :07 / :22 / :37 / :52): the
expected run cadences (W23a TRND-03).
@@ -1622,7 +1622,7 @@ check_run_cadences(self)
## export_project_data
-[backend/app/worker/tasks.py:9420](../../backend/app/worker/tasks.py#L9420)
+[backend/app/worker/tasks.py:9461](../../backend/app/worker/tasks.py#L9461)
Build, sign, store and verify one project export (``project_data_jobs`` row ``job_id``).
@@ -1639,7 +1639,7 @@ export_project_data(job_id: str)
## import_project_data
-[backend/app/worker/tasks.py:9434](../../backend/app/worker/tasks.py#L9434)
+[backend/app/worker/tasks.py:9475](../../backend/app/worker/tasks.py#L9475)
Import one uploaded export as a NEW project, in ONE transaction (``project_data_jobs`` row ``job_id``).
Claim-guarded like the export; a failure rolls the whole project back and is recorded on the row.
@@ -1651,7 +1651,7 @@ import_project_data(job_id: str)
## sweep_project_data_jobs
-[backend/app/worker/tasks.py:9443](../../backend/app/worker/tasks.py#L9443)
+[backend/app/worker/tasks.py:9484](../../backend/app/worker/tasks.py#L9484)
The project-data janitor (hourly at :35): expire exports past 72 hours (the ONLY expiry path),
remove uploads and objects no job may keep, fail jobs a dead worker left ``running``, re-send jobs
@@ -1664,7 +1664,7 @@ sweep_project_data_jobs()
## run_suite_membership_parity
-[backend/app/worker/tasks.py:9467](../../backend/app/worker/tasks.py#L9467)
+[backend/app/worker/tasks.py:9508](../../backend/app/worker/tasks.py#L9508)
Compare the legacy suite memberships with the canonical model (beat daily at 06:15 UTC, or "Compare now").
@@ -1682,7 +1682,7 @@ run_suite_membership_parity(self, trigger: str='beat', requested_by_id: str | No
## export_subject_data
-[backend/app/worker/tasks.py:9495](../../backend/app/worker/tasks.py#L9495)
+[backend/app/worker/tasks.py:9536](../../backend/app/worker/tasks.py#L9536)
Build, sign, store and verify one person's data export (``subject_rights_jobs`` row ``job_id``).
@@ -1697,7 +1697,7 @@ export_subject_data(job_id: str)
## erase_subject_data
-[backend/app/worker/tasks.py:9507](../../backend/app/worker/tasks.py#L9507)
+[backend/app/worker/tasks.py:9548](../../backend/app/worker/tasks.py#L9548)
Run the erasure phases after the lock-out (``subject_rights_jobs`` row ``job_id``): Postgres, objects,
Redis, done — each committed on the job row, each idempotent. Claim-guarded; a phase that raises leaves the
@@ -1710,7 +1710,7 @@ erase_subject_data(job_id: str)
## sweep_subject_rights_jobs
-[backend/app/worker/tasks.py:9517](../../backend/app/worker/tasks.py#L9517)
+[backend/app/worker/tasks.py:9558](../../backend/app/worker/tasks.py#L9558)
The subject-rights janitor (hourly at :50): expire exports past 72 hours (the ONLY expiry path), remove
the objects of failed / expired exports, fail an export a dead worker left ``running``, re-send a queued
@@ -1723,7 +1723,7 @@ sweep_subject_rights_jobs()
## watch_drop_folders
-[backend/app/worker/tasks.py:9680](../../backend/app/worker/tasks.py#L9680)
+[backend/app/worker/tasks.py:9721](../../backend/app/worker/tasks.py#L9721)
Scheduled task (beat, every minute): the drop-folder polling watcher (W34 STRAT-13).
diff --git a/infra/monitoring/alertmanager/alertmanager.yml b/infra/monitoring/alertmanager/alertmanager.yml
new file mode 100644
index 000000000..9d8ba4983
--- /dev/null
+++ b/infra/monitoring/alertmanager/alertmanager.yml
@@ -0,0 +1,57 @@
+# No delivery is enabled by the ordinary monitoring overlay. The opt-in
+# alerting overlay requires the operator's URL and bearer-token secret files.
+global:
+ resolve_timeout: 5m
+
+route:
+ receiver: incidents
+ group_by: [installation, environment, cluster, namespace, alertname]
+ group_wait: 30s
+ group_interval: 5m
+ repeat_interval: 4h
+ routes:
+ # The heartbeat must reach an independent service which pages on absence.
+ - receiver: watchdog
+ matchers: ['alertname="TestLookupWatchdog"']
+ group_wait: 0s
+ group_interval: 1m
+ repeat_interval: 1m
+ - receiver: incidents
+ matchers: ['severity="critical"']
+ group_wait: 10s
+ repeat_interval: 30m
+
+# Inhibition is opt-in through a nonempty alert_family label. Missing labels
+# must never cause an unrelated critical alert to suppress every warning.
+inhibit_rules:
+ - source_matchers: ['severity="critical"', 'alert_family=~".+"']
+ target_matchers: ['severity="warning"', 'alert_family=~".+"']
+ equal: [installation, environment, cluster, namespace, alert_family]
+
+receivers:
+ - name: incidents
+ webhook_configs:
+ - url_file: /run/secrets/alertmanager-incident-url
+ send_resolved: true
+ timeout: 10s
+ http_config:
+ authorization:
+ type: Bearer
+ credentials_file: /run/secrets/alertmanager-incident-token
+ follow_redirects: false
+ proxy_from_environment: false
+ tls_config:
+ min_version: TLS12
+ - name: watchdog
+ webhook_configs:
+ - url_file: /run/secrets/alertmanager-watchdog-url
+ send_resolved: true
+ timeout: 10s
+ http_config:
+ authorization:
+ type: Bearer
+ credentials_file: /run/secrets/alertmanager-watchdog-token
+ follow_redirects: false
+ proxy_from_environment: false
+ tls_config:
+ min_version: TLS12
diff --git a/infra/monitoring/alertmanager/image-lock.json b/infra/monitoring/alertmanager/image-lock.json
new file mode 100644
index 000000000..57674d23b
--- /dev/null
+++ b/infra/monitoring/alertmanager/image-lock.json
@@ -0,0 +1,20 @@
+{
+ "image": "docker.io/prom/alertmanager:v0.35.1@sha256:4e3d029e69c7f61dd53a2b31a3dc427a2b81736cffca185c0854075e07969e36",
+ "upstream_source": "https://github.com/prometheus/alertmanager/tree/v0.35.1",
+ "upstream_release": "https://github.com/prometheus/alertmanager/releases/tag/v0.35.1",
+ "digest_source": "https://registry-1.docker.io/v2/prom/alertmanager/manifests/v0.35.1",
+ "digest_kind": "multi-platform manifest index",
+ "verified_at": "2026-11-26",
+ "bundle": "excluded",
+ "reason": "Opt-in monitoring sidecar; excluded from application image manifest and offline application bundle under existing image-drift policy.",
+ "release_binaries": {
+ "windows-amd64": {
+ "url": "https://github.com/prometheus/alertmanager/releases/download/v0.35.1/alertmanager-0.35.1.windows-amd64.zip",
+ "sha256": "89deab50f465f3d7eb79f392d87493ac1972c6ffdefe617c0699458af933cfcf"
+ },
+ "linux-amd64": {
+ "url": "https://github.com/prometheus/alertmanager/releases/download/v0.35.1/alertmanager-0.35.1.linux-amd64.tar.gz",
+ "sha256": "626bb9ae4486e14044705a6d6a0394f2ad8e3bf40df918f18f15b3d3775aa069"
+ }
+ }
+}
diff --git a/infra/monitoring/alertmanager/telemetry-contract.yml b/infra/monitoring/alertmanager/telemetry-contract.yml
new file mode 100644
index 000000000..35a260310
--- /dev/null
+++ b/infra/monitoring/alertmanager/telemetry-contract.yml
@@ -0,0 +1,12 @@
+# Loaded only by the opt-in alerting profile. Discovery must not define its
+# own expected inventory: deleting the AM scrape must remain detectable.
+groups:
+ - name: testlookup.telemetry_contract.alerting
+ interval: 30s
+ rules:
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ telemetry_profile: compose
+ telemetry_role: alertmanager
+ job: alertmanager
diff --git a/infra/monitoring/backend-scrape-authenticated.yml b/infra/monitoring/backend-scrape-authenticated.yml
index ed4120576..42f3ee1e5 100644
--- a/infra/monitoring/backend-scrape-authenticated.yml
+++ b/infra/monitoring/backend-scrape-authenticated.yml
@@ -2,6 +2,9 @@ scrape_configs:
- job_name: testlookup-backend
static_configs:
- targets: ['backend:8000']
+ labels:
+ telemetry_profile: compose
+ telemetry_role: backend
metrics_path: /metrics
scrape_interval: 15s
follow_redirects: false
diff --git a/infra/monitoring/backend-scrape.yml b/infra/monitoring/backend-scrape.yml
index a6c2d5434..f29f71cfc 100644
--- a/infra/monitoring/backend-scrape.yml
+++ b/infra/monitoring/backend-scrape.yml
@@ -2,5 +2,8 @@ scrape_configs:
- job_name: testlookup-backend
static_configs:
- targets: ['backend:8000']
+ labels:
+ telemetry_profile: compose
+ telemetry_role: backend
metrics_path: /metrics
scrape_interval: 15s
diff --git a/infra/monitoring/grafana/dashboards/testlookup-overview.json b/infra/monitoring/grafana/dashboards/testlookup-overview.json
index f70baa596..702e5d0ea 100644
--- a/infra/monitoring/grafana/dashboards/testlookup-overview.json
+++ b/infra/monitoring/grafana/dashboards/testlookup-overview.json
@@ -873,7 +873,7 @@
},
{
"datasource": "Prometheus",
- "description": "Weekly auto-retro digests by status over 7 days, one per weekly-retro subscription the dispatcher reaches: skipped (the weekly_retro_digest flag is off for its project), success (the retro document was built). The pass rides dispatch_scheduled_digests on Mondays 07:05 UTC. Emitted by backend/app/services/retro_digest_service.py (generate_weekly_retro).",
+ "description": "Weekly retro content generation over 7 days: skipped means the project feature flag is off; success means content was built, not that a provider accepted delivery. The dispatcher processes persisted due dates on arbitrary weekdays in its daily 07:00 UTC pass, with an additional Monday pass. Delivery due/outcome gauges and alerts separately observe provider acceptance and unresolved work.",
"fieldConfig": {
"defaults": { "unit": "short", "color": { "mode": "palette-classic" } },
"overrides": []
@@ -888,7 +888,7 @@
"refId": "A"
}
],
- "title": "Weekly retro digest dispatch (7d)",
+ "title": "Weekly retro content generation (7d)",
"type": "timeseries"
},
{
diff --git a/infra/monitoring/prometheus-rules/compose-telemetry-contract.yml b/infra/monitoring/prometheus-rules/compose-telemetry-contract.yml
new file mode 100644
index 000000000..f5713aef0
--- /dev/null
+++ b/infra/monitoring/prometheus-rules/compose-telemetry-contract.yml
@@ -0,0 +1,25 @@
+# Required roles for the shipped Compose monitoring profile. Keep this
+# independent of discovery: removing a scrape job must not remove its contract.
+# Optional exporters/alerting services are not requirements of the base profile.
+groups:
+ - name: testlookup.telemetry_contract.compose
+ interval: 30s
+ rules:
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ telemetry_profile: compose
+ telemetry_role: backend
+ job: testlookup-backend
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ telemetry_profile: compose
+ telemetry_role: worker
+ job: testlookup-worker
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ telemetry_profile: compose
+ telemetry_role: worker-children
+ job: testlookup-worker
diff --git a/infra/monitoring/prometheus-rules/testlookup-alerts.yml b/infra/monitoring/prometheus-rules/testlookup-alerts.yml
index 2b1421629..fb4accba3 100644
--- a/infra/monitoring/prometheus-rules/testlookup-alerts.yml
+++ b/infra/monitoring/prometheus-rules/testlookup-alerts.yml
@@ -1,5 +1,114 @@
# TestLookup — Prometheus alerting rules
groups:
+ # The expected-role inventory is independent of scrape discovery. Compose
+ # loads compose-telemetry-contract.yml; Operator installs the equivalent
+ # k8s/monitoring/telemetry-contract.yaml. Do not derive it from `up`.
+ - name: testlookup.telemetry
+ interval: 30s
+ rules:
+ - alert: TestLookupTelemetryContractMissing
+ expr: absent(testlookup:telemetry_expected_role)
+ for: 5m
+ labels:
+ severity: critical
+ annotations:
+ summary: "The required telemetry inventory is not loaded"
+ description: "No expected-role recording rules are evaluating. Load the inventory for this monitoring profile and verify its selection independently of the application PodMonitors. Missing inventory makes role-loss detection incomplete. Runbook: docs/operations/telemetry-contract.md."
+
+ # Set matching intentionally tolerates extra rollout replicas and only
+ # requires one healthy target per declared role. It also handles `up`
+ # disappearing entirely, unlike `up == 0` on its own.
+ - alert: TestLookupExpectedRoleUnavailable
+ expr: |
+ (testlookup:telemetry_expected_role == 1)
+ unless on (cluster, namespace, job, telemetry_profile, telemetry_role)
+ (up == 1)
+ for: 5m
+ labels:
+ severity: critical
+ annotations:
+ summary: "A required TestLookup telemetry role has no healthy target"
+ description: "Profile {{ $labels.telemetry_profile }} role {{ $labels.telemetry_role }} has no healthy {{ $labels.job }} scrape target for five minutes. Check discovery, monitor selectors, port, scrape credentials and network policy; an entirely deleted monitor also triggers this alert. Runbook: docs/operations/telemetry-contract.md."
+
+ # These four collectors are an unconditional E02 baseline. New optional
+ # collectors must explicitly join the contract when applicable. Preserve
+ # each target, rather than allowing a healthy replica to hide a broken one.
+ - record: testlookup:telemetry_required_collector
+ expr: |
+ label_replace(up{job="testlookup-backend"} == 1, "collector", "queues", "job", ".*")
+ or label_replace(up{job="testlookup-backend"} == 1, "collector", "agents", "job", ".*")
+ or label_replace(up{job="testlookup-backend"} == 1, "collector", "downstream", "job", ".*")
+ or label_replace(up{job="testlookup-backend"} == 1, "collector", "redis", "job", ".*")
+
+ - alert: TestLookupRequiredTelemetryMissing
+ expr: |
+ label_replace(
+ testlookup:telemetry_required_collector
+ unless on (cluster, namespace, job, instance, telemetry_profile, telemetry_role, collector)
+ testlookup_metric_collection_success,
+ "signal", "collection_success", "job", ".*"
+ )
+ or
+ label_replace(
+ testlookup:telemetry_required_collector
+ unless on (cluster, namespace, job, instance, telemetry_profile, telemetry_role, collector)
+ testlookup_metric_collection_last_success_timestamp_seconds,
+ "signal", "collection_last_success", "job", ".*"
+ )
+ or
+ label_replace(
+ (up{job=~"testlookup-backend|testlookup-worker"} == 1)
+ unless on (cluster, namespace, job, instance, telemetry_profile, telemetry_role)
+ testlookup_finalize_step_failures_total{step="suite_sync"},
+ "signal", "metric_registry", "job", ".*"
+ )
+ for: 5m
+ labels:
+ severity: warning
+ annotations:
+ summary: "A healthy scrape is missing required application telemetry"
+ description: "Target {{ $labels.instance }} is up but required signal {{ $labels.signal }} (collector {{ $labels.collector }}) is absent. Check exporter initialization and metric relabel/drop filters. Zero is valid; lazy task histograms and optional collectors are deliberately excluded. Runbook: docs/operations/telemetry-contract.md."
+
+ # An external dead-man receiver must alert when these notifications stop.
+ # This rule alone cannot detect the failure of its own Prometheus server.
+ - alert: TestLookupWatchdog
+ expr: vector(1)
+ labels:
+ severity: none
+ category: watchdog
+ annotations:
+ summary: "TestLookup notification heartbeat"
+ description: "Always firing. Route to an independently hosted authenticated dead-man receiver that alarms on missing heartbeats; do not page on normal receipt. Runbook: docs/operations/alert-routing.md."
+
+ # Alertmanager is optional. These rules require its actual scrape series;
+ # the opt-in alerting profile supplies its job and external routing.
+ - alert: TestLookupAlertmanagerDown
+ expr: up{job="alertmanager"} == 0
+ for: 2m
+ labels:
+ severity: critical
+ annotations:
+ summary: "The configured Alertmanager scrape is failing"
+ description: "Alert delivery may be unavailable. Check Alertmanager health and its scrape path, then use the independent heartbeat receiver to confirm notification-path recovery."
+
+ - alert: TestLookupAlertmanagerNotificationsFailing
+ expr: increase(alertmanager_notifications_failed_total{job="alertmanager"}[5m]) > 0
+ for: 1m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Alertmanager failed to deliver notifications"
+ description: "A configured receiver has failed notification attempts in the last five minutes. Inspect receiver authorization, connectivity and rate limits; verify delivery through the independent receiver."
+
+ - alert: TestLookupAlertmanagerConfigReloadFailed
+ expr: alertmanager_config_last_reload_successful{job="alertmanager"} == 0
+ for: 1m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Alertmanager rejected its latest configuration reload"
+ description: "The intended routing configuration is not active. Validate the configuration and confirm a successful reload before relying on new receiver routes."
+
- name: testlookup.application
interval: 30s
rules:
@@ -585,78 +694,81 @@ groups:
summary: "Outbound webhook delivery failure rate > 5% for 15 min"
description: "More than 5% of webhook delivery attempts are terminal failures over the last 15 minutes. Check the Webhook Deliveries panel in /settings/webhooks for the DLQ rows and the most recent error text, and consider quarantining the offending subscription until the receiver is fixed."
- # ── 1-3 Flaky quarantine maintenance: back-to-back failures ────────
- # The beat runs once daily at 04:00 UTC. Two failures in a row
- # leaves the quarantine queue unmanaged for 48+ hours, during
- # which PROPOSED rows won't expire and approved rows won't be
- # re-checked. Scoped to the specific Celery task name so other
- # task failures don't page the quarantine on-call.
+ # 04:00 UTC due slot and one-hour completion margin. The SQL snapshot
+ # describes the same installation across worker and API replacement.
- alert: TestLookupFlakyQuarantineMaintenanceFailing
expr: |
- increase(
- testlookup_celery_tasks_total{
- task_name="app.worker.tasks.run_flaky_quarantine_maintenance",
- status="failure"
- }[2d]
- ) >= 2
- for: 0m
+ max by (cluster, namespace, schedule) (
+ testlookup_nightly_job_overdue{job="testlookup-backend",schedule="quarantine_maintenance"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{job="testlookup-backend",collector="nightly"} == 1)
+ and on (cluster, namespace, job, instance)
+ ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",collector="nightly"}) <= 120)
+ ) == 1
+ for: 5m
labels:
severity: warning
tier: "1-3"
feature: flaky_auto_quarantine
annotations:
- summary: "Flaky quarantine maintenance beat failed twice in a row"
- description: "The run_flaky_quarantine_maintenance Celery beat (04:00 UTC) has failed on two consecutive runs. PROPOSED rows aren't being expired and approved rows aren't being rechecked. Check the worker logs for the most recent traceback and the celery.beat.run_flaky_quarantine_maintenance spans in Jaeger."
+ summary: "Flaky quarantine maintenance missed its completion deadline"
+ description: "The enabled nightly quarantine slot has no durable success after its one-hour completion margin. Compare the schedule's last attempt and success to distinguish missing dispatch from incomplete work, then inspect worker and Beat health."
- # ── 2-12 Weekly retro digest: missed Monday dispatch ───────────────
- # The Monday 07:05 UTC beat entry produces a WEEKLY_RETRO digest
- # for each subscribed project. If the success counter hasn't
- # incremented in the last 2 hours of the Monday 08:00-10:00 UTC
- # window, the dispatch almost certainly didn't fire — either the
- # beat scheduler is down, the feature flag got flipped off, or
- # the retro_digest_service crashed inside the dispatcher loop.
- # The day-of-week+hour guard narrows the alert to the window
- # where we'd actually expect traffic.
- - alert: TestLookupWeeklyRetroDigestMissedMonday
+ # Subscription due dates are UTC instants on arbitrary weekdays. The
+ # durable claim receipt survives next_delivery_at advancement/retries.
+ # The producer allows the normal daily dispatch interval plus processing
+ # grace. Generation counters are diagnostics, never delivery evidence.
+ - alert: TestLookupWeeklyDigestDeliveryOverdue
expr: |
- (
- increase(
- testlookup_retro_digest_dispatch_total{status="success"}[2h]
- ) == 0
- )
- and (day_of_week() == 1)
- and (hour() >= 8 and hour() < 10)
+ max by (cluster, namespace, schedule) (
+ testlookup_weekly_digest_oldest_overdue_seconds{job="testlookup-backend"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{job="testlookup-backend",collector="digests"} == 1)
+ and on (cluster, namespace, job, instance)
+ ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",collector="digests"}) <= 120)
+ ) > 0
for: 15m
labels:
severity: warning
- tier: "2-12"
- feature: weekly_retro_digest
annotations:
- summary: "Weekly retro digest didn't dispatch on Monday"
- description: "No retro_digest_dispatch_total{status=\"success\"} increments have been observed during the Monday 08:00-10:00 UTC window. The Monday 07:05 UTC beat either didn't fire, the weekly_retro_digest feature flag got flipped off, or every generate_weekly_retro call raised. Check the celery.beat.dispatch_scheduled_digests span in Jaeger for the most recent Monday and the worker logs."
+ summary: "Weekly digest delivery has overdue work"
+ description: "An enabled {{ $labels.schedule }} subscription has an unresolved due slot beyond the normal daily dispatch interval and processing grace. Content generation is not provider delivery. Inspect durable attempt outcomes and provider logs before replaying any ambiguous send."
- # ── 2-10 Perf baseline refresh: back-to-back failures ──────────────
- # The nightly refresh is best-effort (the release gate falls back
- # to the hardcoded config thresholds if no baseline exists), so a
- # single miss is not a page. Two consecutive failures mean the
- # baselines are frozen on stale data and spike detection at gate
- # time degrades to "no signal".
+ - alert: TestLookupWeeklyDigestScheduleMissing
+ expr: |
+ max by (cluster, namespace, schedule) (
+ testlookup_weekly_digest_subscriptions{job="testlookup-backend",state="missing_schedule"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{job="testlookup-backend",collector="digests"} == 1)
+ and on (cluster, namespace, job, instance)
+ ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",collector="digests"}) <= 120)
+ ) > 0
+ for: 15m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Enabled weekly digest has no due schedule"
+ description: "An enabled {{ $labels.schedule }} subscription has neither a next delivery time nor an unresolved claimed slot. Inspect its durable schedule; absence of a due date is not successful delivery."
+
+ # 04:30 UTC due slot and one-hour completion margin. Disabled features
+ # have no deadline, and a skipped refresh does not advance success.
- alert: TestLookupPerfBaselineRefreshFailing
expr: |
- increase(
- testlookup_celery_tasks_total{
- task_name="app.worker.tasks.refresh_perf_baselines",
- status="failure"
- }[2d]
- ) >= 2
- for: 0m
+ max by (cluster, namespace, schedule) (
+ testlookup_nightly_job_overdue{job="testlookup-backend",schedule="perf_baseline_refresh"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{job="testlookup-backend",collector="nightly"} == 1)
+ and on (cluster, namespace, job, instance)
+ ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",collector="nightly"}) <= 120)
+ ) == 1
+ for: 5m
labels:
severity: warning
tier: "2-10"
feature: perf_regression_detection
annotations:
- summary: "Perf baseline refresh beat failed twice in a row"
- description: "The refresh_perf_baselines Celery beat (04:30 UTC) has failed on two consecutive runs. Release-gate spike detection will degrade to 'no signal' against stale baselines. Check the celery.beat.refresh_perf_baselines spans in Jaeger and the worker logs."
+ summary: "Performance baseline refresh missed its completion deadline"
+ description: "The enabled nightly baseline refresh has no durable success after its one-hour completion margin. Check the schedule's last attempt and success, Beat dispatch and worker logs. Release gating may use stale baselines."
# ── 1-4 Release compliance pack generation errors ──────────────────
# Pack generation is user-triggered (QA Lead clicks "Generate
diff --git a/infra/monitoring/prometheus.yml b/infra/monitoring/prometheus.yml
index bed12d85e..23b904ad7 100644
--- a/infra/monitoring/prometheus.yml
+++ b/infra/monitoring/prometheus.yml
@@ -18,7 +18,14 @@ scrape_configs:
# Each prefork worker container aggregates its children on port 9100.
- job_name: 'testlookup-worker'
static_configs:
- - targets: ['worker:9100', 'worker-children:9100']
+ - targets: ['worker:9100']
+ labels:
+ telemetry_profile: compose
+ telemetry_role: worker
+ - targets: ['worker-children:9100']
+ labels:
+ telemetry_profile: compose
+ telemetry_role: worker-children
metrics_path: /metrics
scrape_interval: 30s
diff --git a/infra/monitoring/tests/alerting-telemetry-contract.yml b/infra/monitoring/tests/alerting-telemetry-contract.yml
new file mode 100644
index 000000000..a2458f541
--- /dev/null
+++ b/infra/monitoring/tests/alerting-telemetry-contract.yml
@@ -0,0 +1,32 @@
+# The optional alerting profile makes Alertmanager required only when enabled.
+rule_files:
+ - ../prometheus-rules/testlookup-alerts.yml
+ - ../alertmanager/telemetry-contract.yml
+evaluation_interval: 30s
+tests:
+ - name: enabled alerting inventory survives deletion of its discovery job
+ interval: 30s
+ input_series:
+ - series: 'up{job="alertmanager",telemetry_profile="compose",telemetry_role="alertmanager",instance="alertmanager:9093"}'
+ values: '1x4 stale _x10 1x20'
+ promql_expr_test:
+ - expr: 'count(testlookup:telemetry_expected_role{telemetry_role="alertmanager"})'
+ eval_time: 1m
+ exp_samples:
+ - labels: '{}'
+ value: 1
+ - expr: 'count(ALERTS{alertname="TestLookupExpectedRoleUnavailable",telemetry_role="alertmanager",alertstate="firing"}) or vector(0)'
+ eval_time: 7m
+ exp_samples:
+ - labels: '{}'
+ value: 0
+ - expr: 'count(ALERTS{alertname="TestLookupExpectedRoleUnavailable",telemetry_role="alertmanager",alertstate="firing"}) or vector(0)'
+ eval_time: 7m30s
+ exp_samples:
+ - labels: '{}'
+ value: 1
+ - expr: 'count(ALERTS{alertname="TestLookupExpectedRoleUnavailable",telemetry_role="alertmanager",alertstate="firing"}) or vector(0)'
+ eval_time: 8m
+ exp_samples:
+ - labels: '{}'
+ value: 0
diff --git a/infra/monitoring/tests/compose-telemetry-contract.yml b/infra/monitoring/tests/compose-telemetry-contract.yml
new file mode 100644
index 000000000..acff92e47
--- /dev/null
+++ b/infra/monitoring/tests/compose-telemetry-contract.yml
@@ -0,0 +1,58 @@
+# Synthetic absence semantics; fixtures are outside the runtime rules glob.
+rule_files:
+- ../prometheus-rules/testlookup-alerts.yml
+- ../prometheus-rules/compose-telemetry-contract.yml
+evaluation_interval: 30s
+tests:
+- name: "actual Compose inventory loads three roles and accepts quiet baseline targets"
+ interval: 30s
+ input_series:
+ - series: "up{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_success{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",collector=\"queues\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",collector=\"queues\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",collector=\"agents\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",collector=\"agents\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",collector=\"downstream\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",collector=\"downstream\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",collector=\"redis\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",collector=\"redis\"}"
+ values: "0+30x50"
+ - series: "testlookup_finalize_step_failures_total{telemetry_profile=\"compose\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"backend:8000\",step=\"suite_sync\"}"
+ values: "0x50"
+ - series: "up{job=\"testlookup-worker\",telemetry_profile=\"compose\",telemetry_role=\"worker\",instance=\"worker:9100\"}"
+ values: "1x50"
+ - series: "up{job=\"testlookup-worker\",telemetry_profile=\"compose\",telemetry_role=\"worker-children\",instance=\"worker-children:9100\"}"
+ values: "1x50"
+ - series: "testlookup_finalize_step_failures_total{job=\"testlookup-worker\",telemetry_profile=\"compose\",telemetry_role=\"worker\",instance=\"worker:9100\",step=\"suite_sync\"}"
+ values: "0x50"
+ - series: "testlookup_finalize_step_failures_total{job=\"testlookup-worker\",telemetry_profile=\"compose\",telemetry_role=\"worker-children\",instance=\"worker-children:9100\",step=\"suite_sync\"}"
+ values: "0x50"
+ promql_expr_test:
+ - expr: "count(testlookup:telemetry_expected_role)"
+ eval_time: 1m
+ exp_samples:
+ - labels: "{}"
+ value: 3
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupRequiredTelemetryMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupTelemetryContractMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
diff --git a/infra/monitoring/tests/digest-delivery.yml b/infra/monitoring/tests/digest-delivery.yml
new file mode 100644
index 000000000..ba6529100
--- /dev/null
+++ b/infra/monitoring/tests/digest-delivery.yml
@@ -0,0 +1,137 @@
+rule_files:
+- ../prometheus-rules/testlookup-alerts.yml
+evaluation_interval: 30s
+tests:
+- name: enabled future work and disabled/no subscriptions are quiet
+ interval: 30s
+ input_series:
+ - series: testlookup_weekly_digest_subscriptions{job="testlookup-backend",instance="api",schedule="WEEKLY",state="enabled"}
+ values: '2x40'
+ - series: testlookup_weekly_digest_oldest_overdue_seconds{job="testlookup-backend",instance="api",schedule="WEEKLY"}
+ values: '0x40'
+ - series: testlookup_weekly_digest_subscriptions{job="testlookup-backend",instance="api",schedule="WEEKLY",state="missing_schedule"}
+ values: '0x40'
+ - series: testlookup_weekly_digest_subscriptions{job="testlookup-backend",instance="api",schedule="WEEKLY_RETRO",state="enabled"}
+ values: '0x40'
+ - series: testlookup_weekly_digest_oldest_overdue_seconds{job="testlookup-backend",instance="api",schedule="WEEKLY_RETRO"}
+ values: '0x40'
+ - series: testlookup_metric_collection_success{job="testlookup-backend",instance="api",collector="digests"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",instance="api",collector="digests"}
+ values: '0+30x40'
+ alert_rule_test:
+ - eval_time: 20m
+ alertname: TestLookupWeeklyDigestDeliveryOverdue
+ exp_alerts: []
+ - eval_time: 20m
+ alertname: TestLookupWeeklyDigestScheduleMissing
+ exp_alerts: []
+- name: generation success cannot hide a failed delivery and fresh recovery beats stale replica
+ interval: 30s
+ input_series:
+ - series: testlookup_retro_digest_dispatch_total{status="success"}
+ values: '0+1x60'
+ - series: testlookup_weekly_digest_oldest_overdue_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="fresh",schedule="WEEKLY_RETRO"}
+ values: '100x40 0x20'
+ - series: testlookup_weekly_digest_delivery_outcomes{cluster="lab",namespace="prod",job="testlookup-backend",instance="fresh",schedule="WEEKLY_RETRO",outcome="failed"}
+ values: '1x40 0x20'
+ - series: testlookup_weekly_digest_oldest_overdue_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="stale",schedule="WEEKLY_RETRO"}
+ values: '900x60'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="fresh",collector="digests"}
+ values: '1x60'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="fresh",collector="digests"}
+ values: '0+30x60'
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="stale",collector="digests"}
+ values: '1x60'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="stale",collector="digests"}
+ values: '0x60'
+ alert_rule_test:
+ - eval_time: 14m30s
+ alertname: TestLookupWeeklyDigestDeliveryOverdue
+ exp_alerts: []
+ - eval_time: 15m
+ alertname: TestLookupWeeklyDigestDeliveryOverdue
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ schedule: WEEKLY_RETRO
+ severity: warning
+ exp_annotations:
+ summary: Weekly digest delivery has overdue work
+ description: An enabled WEEKLY_RETRO subscription has an unresolved due slot beyond the normal daily dispatch interval and processing grace. Content generation is not provider delivery. Inspect durable attempt outcomes and provider logs before replaying any ambiguous send.
+ - eval_time: 22m
+ alertname: TestLookupWeeklyDigestDeliveryOverdue
+ exp_alerts: []
+- name: never-delivered work fires outside Monday without content-generation traffic
+ interval: 30s
+ input_series:
+ - series: testlookup_weekly_digest_oldest_overdue_seconds{job="testlookup-backend",instance="replacement-api",schedule="WEEKLY"}
+ values: '10x40'
+ - series: testlookup_weekly_digest_subscriptions{job="testlookup-backend",instance="replacement-api",schedule="WEEKLY",state="never_delivered"}
+ values: '1x40'
+ - series: testlookup_metric_collection_success{job="testlookup-backend",instance="replacement-api",collector="digests"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",instance="replacement-api",collector="digests"}
+ values: '0+30x40'
+ alert_rule_test:
+ # Promtool starts on Thursday, outside any Monday-only window.
+ - eval_time: 15m
+ alertname: TestLookupWeeklyDigestDeliveryOverdue
+ exp_alerts:
+ - exp_labels:
+ schedule: WEEKLY
+ severity: warning
+ exp_annotations:
+ summary: Weekly digest delivery has overdue work
+ description: An enabled WEEKLY subscription has an unresolved due slot beyond the normal daily dispatch interval and processing grace. Content generation is not provider delivery. Inspect durable attempt outcomes and provider logs before replaying any ambiguous send.
+- name: missing schedule alerts without pretending that zero overdue proves delivery
+ interval: 30s
+ input_series:
+ - series: testlookup_weekly_digest_subscriptions{job="testlookup-backend",instance="api",schedule="WEEKLY",state="missing_schedule"}
+ values: '1x40'
+ - series: testlookup_weekly_digest_oldest_overdue_seconds{job="testlookup-backend",instance="api",schedule="WEEKLY"}
+ values: '0x40'
+ - series: testlookup_metric_collection_success{job="testlookup-backend",instance="api",collector="digests"}
+ values: '1x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",instance="api",collector="digests"}
+ values: '0+30x40'
+ alert_rule_test:
+ - eval_time: 15m
+ alertname: TestLookupWeeklyDigestScheduleMissing
+ exp_alerts:
+ - exp_labels:
+ schedule: WEEKLY
+ severity: warning
+ exp_annotations:
+ summary: Enabled weekly digest has no due schedule
+ description: An enabled WEEKLY subscription has neither a next delivery time nor an unresolved claimed slot. Inspect its durable schedule; absence of a due date is not successful delivery.
+ - eval_time: 15m
+ alertname: TestLookupWeeklyDigestDeliveryOverdue
+ exp_alerts: []
+- name: failed collection does not present old overdue samples as current
+ interval: 30s
+ input_series:
+ - series: testlookup_weekly_digest_oldest_overdue_seconds{job="testlookup-backend",instance="api",schedule="WEEKLY"}
+ values: '100x40'
+ - series: testlookup_metric_collection_success{job="testlookup-backend",instance="api",collector="digests"}
+ values: '0x40'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",instance="api",collector="digests"}
+ values: '0x40'
+ alert_rule_test:
+ - eval_time: 20m
+ alertname: TestLookupWeeklyDigestDeliveryOverdue
+ exp_alerts: []
+ promql_expr_test:
+ - expr: count(ALERTS{alertname="TestLookupOperationalCollectionStale",alertstate="firing"})
+ eval_time: 20m
+ exp_samples:
+ - labels: '{}'
+ value: 1
+- name: absent observations cannot invent overdue deliveries
+ interval: 30s
+ input_series: []
+ alert_rule_test:
+ - eval_time: 20m
+ alertname: TestLookupWeeklyDigestDeliveryOverdue
+ exp_alerts: []
diff --git a/infra/monitoring/tests/nightly-alerts.yml b/infra/monitoring/tests/nightly-alerts.yml
new file mode 100644
index 000000000..6c72569c5
--- /dev/null
+++ b/infra/monitoring/tests/nightly-alerts.yml
@@ -0,0 +1,69 @@
+rule_files:
+- ../prometheus-rules/testlookup-alerts.yml
+evaluation_interval: 30s
+tests:
+- name: fresh overdue maintenance fires and stale replicas cannot block recovery
+ interval: 30s
+ input_series:
+ - series: testlookup_nightly_job_overdue{job="testlookup-backend",namespace="team",instance="api-a",schedule="quarantine_maintenance"}
+ values: '1x25'
+ - series: testlookup_metric_collection_success{job="testlookup-backend",namespace="team",instance="api-a",collector="nightly"}
+ values: '1x25'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",namespace="team",instance="api-a",collector="nightly"}
+ values: '0+30x12 360x12'
+ - series: testlookup_nightly_job_overdue{job="testlookup-backend",namespace="team",instance="api-b",schedule="quarantine_maintenance"}
+ values: '1x16 0x8'
+ - series: testlookup_metric_collection_success{job="testlookup-backend",namespace="team",instance="api-b",collector="nightly"}
+ values: '1x25'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",namespace="team",instance="api-b",collector="nightly"}
+ values: '0+30x25'
+ alert_rule_test:
+ - eval_time: 4m30s
+ alertname: TestLookupFlakyQuarantineMaintenanceFailing
+ exp_alerts: []
+ - eval_time: 5m
+ alertname: TestLookupFlakyQuarantineMaintenanceFailing
+ exp_alerts:
+ - exp_labels:
+ namespace: team
+ schedule: quarantine_maintenance
+ severity: warning
+ tier: '1-3'
+ feature: flaky_auto_quarantine
+ exp_annotations:
+ summary: Flaky quarantine maintenance missed its completion deadline
+ description: The enabled nightly quarantine slot has no durable success after its one-hour completion margin. Compare the schedule's last attempt and success to distinguish missing dispatch from incomplete work, then inspect worker and Beat health.
+ - eval_time: 8m30s
+ alertname: TestLookupFlakyQuarantineMaintenanceFailing
+ exp_alerts: []
+- name: the baseline alert uses its own fresh deadline and recovers
+ interval: 30s
+ input_series:
+ - series: testlookup_nightly_job_overdue{job="testlookup-backend",cluster="local",namespace="team",instance="api-a",schedule="perf_baseline_refresh"}
+ values: '0x1 1x11 0x8'
+ - series: testlookup_nightly_job_overdue{job="testlookup-backend",cluster="local",namespace="team",instance="api-a",schedule="quarantine_maintenance"}
+ values: '0x22'
+ - series: testlookup_metric_collection_success{job="testlookup-backend",cluster="local",namespace="team",instance="api-a",collector="nightly"}
+ values: '1x22'
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{job="testlookup-backend",cluster="local",namespace="team",instance="api-a",collector="nightly"}
+ values: '0+30x22'
+ alert_rule_test:
+ - eval_time: 6m
+ alertname: TestLookupPerfBaselineRefreshFailing
+ exp_alerts:
+ - exp_labels:
+ cluster: local
+ namespace: team
+ schedule: perf_baseline_refresh
+ severity: warning
+ tier: '2-10'
+ feature: perf_regression_detection
+ exp_annotations:
+ summary: Performance baseline refresh missed its completion deadline
+ description: The enabled nightly baseline refresh has no durable success after its one-hour completion margin. Check the schedule's last attempt and success, Beat dispatch and worker logs. Release gating may use stale baselines.
+ - eval_time: 6m
+ alertname: TestLookupFlakyQuarantineMaintenanceFailing
+ exp_alerts: []
+ - eval_time: 7m
+ alertname: TestLookupPerfBaselineRefreshFailing
+ exp_alerts: []
diff --git a/infra/monitoring/tests/telemetry-absence.yml b/infra/monitoring/tests/telemetry-absence.yml
new file mode 100644
index 000000000..c9664c857
--- /dev/null
+++ b/infra/monitoring/tests/telemetry-absence.yml
@@ -0,0 +1,336 @@
+# Synthetic absence semantics; fixtures are outside the runtime rules glob.
+rule_files:
+- ../prometheus-rules/testlookup-alerts.yml
+evaluation_interval: 30s
+tests:
+- name: "missing inventory has a five-minute grace while watchdog is always firing"
+ interval: 30s
+ input_series: []
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupTelemetryContractMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 4m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupTelemetryContractMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 5m
+ exp_samples:
+ - labels: "{}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupWatchdog\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 0m
+ exp_samples:
+ - labels: "{}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupWatchdog\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 12m
+ exp_samples:
+ - labels: "{}"
+ value: 1
+- name: "all replicas of a declared role down cross the grace then recover"
+ interval: 30s
+ input_series:
+ - series: "testlookup:telemetry_expected_role{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\"}"
+ values: "0x10 1x30"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-b\"}"
+ values: "0x10 1x30"
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 4m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 5m
+ exp_samples:
+ - labels: "{}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 5m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+- name: "discovery deletion is detected after stale markers and recovers"
+ interval: 30s
+ input_series:
+ - series: "testlookup:telemetry_expected_role{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\"}"
+ values: "1x4 stale _x10 1x20"
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 7m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 7m30s
+ exp_samples:
+ - labels: "{}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 8m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+- name: "a healthy rolling replica prevents a role-loss alert"
+ interval: 30s
+ input_series:
+ - series: "testlookup:telemetry_expected_role{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\"}"
+ values: "1x4 stale"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-replacement\"}"
+ values: "_x3 1x40"
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 5m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 12m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+- name: "another namespace cluster or worker role cannot satisfy a missing role"
+ interval: 30s
+ input_series:
+ - series: "testlookup:telemetry_expected_role{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-worker\",telemetry_role=\"worker-children\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-b\",telemetry_profile=\"kubernetes\",job=\"testlookup-worker\",telemetry_role=\"worker-children\",instance=\"other-namespace\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-b\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-worker\",telemetry_role=\"worker-children\",instance=\"other-cluster\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-worker\",telemetry_role=\"worker-default\",instance=\"other-role\"}"
+ values: "1x50"
+ promql_expr_test:
+ - expr: "count by (cluster,namespace,telemetry_role) (ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"})"
+ eval_time: 5m
+ exp_samples:
+ - labels: "{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_role=\"worker-children\"}"
+ value: 1
+- name: "quiet healthy zero series and omitted optional roles are valid"
+ interval: 30s
+ input_series:
+ - series: "testlookup:telemetry_expected_role{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"queues\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"queues\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"agents\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"agents\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"downstream\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"downstream\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"redis\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"redis\"}"
+ values: "0+30x50"
+ - series: "testlookup_finalize_step_failures_total{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",step=\"suite_sync\"}"
+ values: "0x50"
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupExpectedRoleUnavailable\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupRequiredTelemetryMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupTelemetryContractMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerDown\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerNotificationsFailing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerConfigReloadFailed\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 10m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+- name: "healthy replica cannot mask another target missing required collector or registry series"
+ interval: 30s
+ input_series:
+ - series: "testlookup:telemetry_expected_role{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"queues\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"queues\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"agents\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"agents\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"downstream\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"downstream\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"redis\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"redis\"}"
+ values: "0+30x50"
+ - series: "testlookup_finalize_step_failures_total{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",step=\"suite_sync\"}"
+ values: "0x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-b\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-b\",collector=\"queues\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-b\",collector=\"agents\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-b\",collector=\"agents\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-b\",collector=\"downstream\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-b\",collector=\"downstream\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-b\",collector=\"redis\"}"
+ values: "0+30x50"
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupRequiredTelemetryMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 4m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count by (instance,collector,signal) (ALERTS{alertname=\"TestLookupRequiredTelemetryMissing\",alertstate=\"firing\"})"
+ eval_time: 5m
+ exp_samples:
+ - labels: "{instance=\"api-b\",collector=\"redis\",signal=\"collection_success\"}"
+ value: 1
+ - labels: "{instance=\"api-b\",collector=\"queues\",signal=\"collection_last_success\"}"
+ value: 1
+ - labels: "{instance=\"api-b\",signal=\"metric_registry\"}"
+ value: 1
+- name: "required series recover independently and a down target is not reported as missing telemetry"
+ interval: 30s
+ input_series:
+ - series: "testlookup:telemetry_expected_role{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"queues\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"queues\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"agents\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"agents\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"downstream\"}"
+ values: "1x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"downstream\"}"
+ values: "0+30x50"
+ - series: "testlookup_metric_collection_last_success_timestamp_seconds{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"redis\"}"
+ values: "0+30x50"
+ - series: "testlookup_finalize_step_failures_total{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",step=\"suite_sync\"}"
+ values: "0x50"
+ - series: "testlookup_metric_collection_success{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-a\",collector=\"redis\"}"
+ values: "_x12 1x30"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-backend\",telemetry_role=\"backend\",instance=\"api-down\"}"
+ values: "0x50"
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupRequiredTelemetryMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 5m
+ exp_samples:
+ - labels: "{}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupRequiredTelemetryMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 6m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+- name: "worker core registry is required without demanding lazy task histograms"
+ interval: 30s
+ input_series:
+ - series: "testlookup:telemetry_expected_role{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-worker\",telemetry_role=\"worker-default\"}"
+ values: "1x50"
+ - series: "up{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-worker\",telemetry_role=\"worker-default\",instance=\"worker-a\"}"
+ values: "1x50"
+ - series: "testlookup_finalize_step_failures_total{cluster=\"fixture-a\",namespace=\"tenant-a\",telemetry_profile=\"kubernetes\",job=\"testlookup-worker\",telemetry_role=\"worker-default\",instance=\"worker-a\",step=\"suite_sync\"}"
+ values: "_x12 0x30"
+ promql_expr_test:
+ - expr: "count by (signal) (ALERTS{alertname=\"TestLookupRequiredTelemetryMissing\",alertstate=\"firing\"})"
+ eval_time: 5m
+ exp_samples:
+ - labels: "{signal=\"metric_registry\"}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupRequiredTelemetryMissing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 6m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+- name: "configured optional Alertmanager scrape failure holds for two minutes"
+ interval: 30s
+ input_series:
+ - series: "up{job=\"alertmanager\",instance=\"alertmanager:9093\",telemetry_profile=\"compose\",telemetry_role=\"alertmanager\"}"
+ values: "0x4 1x30"
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerDown\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 1m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerDown\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 2m
+ exp_samples:
+ - labels: "{}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerDown\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 2m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+- name: "Alertmanager notification and configuration failures fire and recover"
+ interval: 30s
+ input_series:
+ - series: "alertmanager_notifications_failed_total{job=\"alertmanager\",instance=\"alertmanager:9093\",telemetry_profile=\"compose\",telemetry_role=\"alertmanager\",receiver=\"fixture-receiver\",integration=\"webhook\"}"
+ values: "0+1x10 10x30"
+ - series: "alertmanager_config_last_reload_successful{job=\"alertmanager\",instance=\"alertmanager:9093\",telemetry_profile=\"compose\",telemetry_role=\"alertmanager\"}"
+ values: "0x4 1x30"
+ promql_expr_test:
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerNotificationsFailing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 2m
+ exp_samples:
+ - labels: "{}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerNotificationsFailing\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 11m
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerConfigReloadFailed\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerConfigReloadFailed\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 1m
+ exp_samples:
+ - labels: "{}"
+ value: 1
+ - expr: "count(ALERTS{alertname=\"TestLookupAlertmanagerConfigReloadFailed\",alertstate=\"firing\"}) or vector(0)"
+ eval_time: 2m30s
+ exp_samples:
+ - labels: "{}"
+ value: 0
diff --git a/k8s/monitoring/kustomization.yaml b/k8s/monitoring/kustomization.yaml
index 6bf793d71..cd50e672f 100644
--- a/k8s/monitoring/kustomization.yaml
+++ b/k8s/monitoring/kustomization.yaml
@@ -35,3 +35,4 @@ namespace: testlookup
resources:
- prometheusrule.yaml
- podmonitors.yaml
+ - telemetry-contract.yaml
diff --git a/k8s/monitoring/podmonitors.yaml b/k8s/monitoring/podmonitors.yaml
index 50cbdfbfd..5c98372ca 100644
--- a/k8s/monitoring/podmonitors.yaml
+++ b/k8s/monitoring/podmonitors.yaml
@@ -33,6 +33,12 @@ spec:
- action: replace
targetLabel: job
replacement: testlookup-backend
+ - action: replace
+ targetLabel: telemetry_profile
+ replacement: kubernetes
+ - action: replace
+ targetLabel: telemetry_role
+ replacement: backend
---
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
@@ -58,3 +64,11 @@ spec:
- action: replace
targetLabel: job
replacement: testlookup-worker
+ - action: replace
+ targetLabel: telemetry_profile
+ replacement: kubernetes
+ - action: replace
+ sourceLabels: [__meta_kubernetes_pod_label_app]
+ regex: 'testlookup-(worker-(critical|ingestion|ai|default|children))'
+ targetLabel: telemetry_role
+ replacement: '$1'
diff --git a/k8s/monitoring/prometheusrule.yaml b/k8s/monitoring/prometheusrule.yaml
index f34f4e67c..684d6ddbb 100644
--- a/k8s/monitoring/prometheusrule.yaml
+++ b/k8s/monitoring/prometheusrule.yaml
@@ -17,6 +17,81 @@ metadata:
role: alert-rules
spec:
groups:
+ - name: testlookup.telemetry
+ interval: 30s
+ rules:
+ - alert: TestLookupTelemetryContractMissing
+ expr: absent(testlookup:telemetry_expected_role)
+ for: 5m
+ labels:
+ severity: critical
+ annotations:
+ summary: The required telemetry inventory is not loaded
+ description: 'No expected-role recording rules are evaluating. Load the inventory for this monitoring profile and verify its selection independently of the application PodMonitors. Missing inventory makes role-loss detection incomplete. Runbook: docs/operations/telemetry-contract.md.'
+ - alert: TestLookupExpectedRoleUnavailable
+ expr: '(testlookup:telemetry_expected_role == 1)
+
+ unless on (cluster, namespace, job, telemetry_profile, telemetry_role)
+
+ (up == 1)
+
+ '
+ for: 5m
+ labels:
+ severity: critical
+ annotations:
+ summary: A required TestLookup telemetry role has no healthy target
+ description: 'Profile {{ $labels.telemetry_profile }} role {{ $labels.telemetry_role }} has no healthy {{ $labels.job }} scrape target for five minutes. Check discovery, monitor selectors, port, scrape credentials and network policy; an entirely deleted monitor also triggers this alert. Runbook: docs/operations/telemetry-contract.md.'
+ - record: testlookup:telemetry_required_collector
+ expr: 'label_replace(up{job="testlookup-backend"} == 1, "collector", "queues", "job", ".*")
+
+ or label_replace(up{job="testlookup-backend"} == 1, "collector", "agents", "job", ".*")
+
+ or label_replace(up{job="testlookup-backend"} == 1, "collector", "downstream", "job", ".*")
+
+ or label_replace(up{job="testlookup-backend"} == 1, "collector", "redis", "job", ".*")
+
+ '
+ - alert: TestLookupRequiredTelemetryMissing
+ expr: "label_replace(\n testlookup:telemetry_required_collector\n unless on (cluster, namespace, job, instance, telemetry_profile, telemetry_role, collector)\n testlookup_metric_collection_success,\n \"signal\", \"collection_success\", \"job\", \".*\"\n)\nor\nlabel_replace(\n testlookup:telemetry_required_collector\n unless on (cluster, namespace, job, instance, telemetry_profile, telemetry_role, collector)\n testlookup_metric_collection_last_success_timestamp_seconds,\n \"signal\", \"collection_last_success\", \"job\", \".*\"\n)\nor\nlabel_replace(\n (up{job=~\"testlookup-backend|testlookup-worker\"} == 1)\n unless on (cluster, namespace, job, instance, telemetry_profile, telemetry_role)\n testlookup_finalize_step_failures_total{step=\"suite_sync\"},\n \"signal\", \"metric_registry\", \"job\", \".*\"\n)\n"
+ for: 5m
+ labels:
+ severity: warning
+ annotations:
+ summary: A healthy scrape is missing required application telemetry
+ description: 'Target {{ $labels.instance }} is up but required signal {{ $labels.signal }} (collector {{ $labels.collector }}) is absent. Check exporter initialization and metric relabel/drop filters. Zero is valid; lazy task histograms and optional collectors are deliberately excluded. Runbook: docs/operations/telemetry-contract.md.'
+ - alert: TestLookupWatchdog
+ expr: vector(1)
+ labels:
+ severity: none
+ category: watchdog
+ annotations:
+ summary: TestLookup notification heartbeat
+ description: 'Always firing. Route to an independently hosted authenticated dead-man receiver that alarms on missing heartbeats; do not page on normal receipt. Runbook: docs/operations/alert-routing.md.'
+ - alert: TestLookupAlertmanagerDown
+ expr: up{job="alertmanager"} == 0
+ for: 2m
+ labels:
+ severity: critical
+ annotations:
+ summary: The configured Alertmanager scrape is failing
+ description: Alert delivery may be unavailable. Check Alertmanager health and its scrape path, then use the independent heartbeat receiver to confirm notification-path recovery.
+ - alert: TestLookupAlertmanagerNotificationsFailing
+ expr: increase(alertmanager_notifications_failed_total{job="alertmanager"}[5m]) > 0
+ for: 1m
+ labels:
+ severity: warning
+ annotations:
+ summary: Alertmanager failed to deliver notifications
+ description: A configured receiver has failed notification attempts in the last five minutes. Inspect receiver authorization, connectivity and rate limits; verify delivery through the independent receiver.
+ - alert: TestLookupAlertmanagerConfigReloadFailed
+ expr: alertmanager_config_last_reload_successful{job="alertmanager"} == 0
+ for: 1m
+ labels:
+ severity: warning
+ annotations:
+ summary: Alertmanager rejected its latest configuration reload
+ description: The intended routing configuration is not active. Validate the configuration and confirm a successful reload before relying on new receiver routes.
- name: testlookup.application
interval: 30s
rules:
@@ -330,35 +405,41 @@ spec:
summary: Outbound webhook delivery failure rate > 5% for 15 min
description: More than 5% of webhook delivery attempts are terminal failures over the last 15 minutes. Check the Webhook Deliveries panel in /settings/webhooks for the DLQ rows and the most recent error text, and consider quarantining the offending subscription until the receiver is fixed.
- alert: TestLookupFlakyQuarantineMaintenanceFailing
- expr: "increase(\n testlookup_celery_tasks_total{\n task_name=\"app.worker.tasks.run_flaky_quarantine_maintenance\",\n status=\"failure\"\n }[2d]\n) >= 2\n"
- for: 0m
+ expr: "max by (cluster, namespace, schedule) (\n testlookup_nightly_job_overdue{job=\"testlookup-backend\",schedule=\"quarantine_maintenance\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"nightly\"} == 1)\n and on (cluster, namespace, job, instance)\n ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"nightly\"}) <= 120)\n) == 1\n"
+ for: 5m
labels:
severity: warning
tier: 1-3
feature: flaky_auto_quarantine
annotations:
- summary: Flaky quarantine maintenance beat failed twice in a row
- description: The run_flaky_quarantine_maintenance Celery beat (04:00 UTC) has failed on two consecutive runs. PROPOSED rows aren't being expired and approved rows aren't being rechecked. Check the worker logs for the most recent traceback and the celery.beat.run_flaky_quarantine_maintenance spans in Jaeger.
- - alert: TestLookupWeeklyRetroDigestMissedMonday
- expr: "(\n increase(\n testlookup_retro_digest_dispatch_total{status=\"success\"}[2h]\n ) == 0\n)\nand (day_of_week() == 1)\nand (hour() >= 8 and hour() < 10)\n"
+ summary: Flaky quarantine maintenance missed its completion deadline
+ description: The enabled nightly quarantine slot has no durable success after its one-hour completion margin. Compare the schedule's last attempt and success to distinguish missing dispatch from incomplete work, then inspect worker and Beat health.
+ - alert: TestLookupWeeklyDigestDeliveryOverdue
+ expr: "max by (cluster, namespace, schedule) (\n testlookup_weekly_digest_oldest_overdue_seconds{job=\"testlookup-backend\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"digests\"} == 1)\n and on (cluster, namespace, job, instance)\n ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"digests\"}) <= 120)\n) > 0\n"
for: 15m
labels:
severity: warning
- tier: 2-12
- feature: weekly_retro_digest
annotations:
- summary: Weekly retro digest didn't dispatch on Monday
- description: No retro_digest_dispatch_total{status="success"} increments have been observed during the Monday 08:00-10:00 UTC window. The Monday 07:05 UTC beat either didn't fire, the weekly_retro_digest feature flag got flipped off, or every generate_weekly_retro call raised. Check the celery.beat.dispatch_scheduled_digests span in Jaeger for the most recent Monday and the worker logs.
+ summary: Weekly digest delivery has overdue work
+ description: An enabled {{ $labels.schedule }} subscription has an unresolved due slot beyond the normal daily dispatch interval and processing grace. Content generation is not provider delivery. Inspect durable attempt outcomes and provider logs before replaying any ambiguous send.
+ - alert: TestLookupWeeklyDigestScheduleMissing
+ expr: "max by (cluster, namespace, schedule) (\n testlookup_weekly_digest_subscriptions{job=\"testlookup-backend\",state=\"missing_schedule\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"digests\"} == 1)\n and on (cluster, namespace, job, instance)\n ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"digests\"}) <= 120)\n) > 0\n"
+ for: 15m
+ labels:
+ severity: warning
+ annotations:
+ summary: Enabled weekly digest has no due schedule
+ description: An enabled {{ $labels.schedule }} subscription has neither a next delivery time nor an unresolved claimed slot. Inspect its durable schedule; absence of a due date is not successful delivery.
- alert: TestLookupPerfBaselineRefreshFailing
- expr: "increase(\n testlookup_celery_tasks_total{\n task_name=\"app.worker.tasks.refresh_perf_baselines\",\n status=\"failure\"\n }[2d]\n) >= 2\n"
- for: 0m
+ expr: "max by (cluster, namespace, schedule) (\n testlookup_nightly_job_overdue{job=\"testlookup-backend\",schedule=\"perf_baseline_refresh\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{job=\"testlookup-backend\",collector=\"nightly\"} == 1)\n and on (cluster, namespace, job, instance)\n ((time() - testlookup_metric_collection_last_success_timestamp_seconds{job=\"testlookup-backend\",collector=\"nightly\"}) <= 120)\n) == 1\n"
+ for: 5m
labels:
severity: warning
tier: 2-10
feature: perf_regression_detection
annotations:
- summary: Perf baseline refresh beat failed twice in a row
- description: The refresh_perf_baselines Celery beat (04:30 UTC) has failed on two consecutive runs. Release-gate spike detection will degrade to 'no signal' against stale baselines. Check the celery.beat.refresh_perf_baselines spans in Jaeger and the worker logs.
+ summary: Performance baseline refresh missed its completion deadline
+ description: The enabled nightly baseline refresh has no durable success after its one-hour completion margin. Check the schedule's last attempt and success, Beat dispatch and worker logs. Release gating may use stale baselines.
- alert: TestLookupCompliancePackGenerationErrors
expr: "increase(\n testlookup_compliance_pack_generated_total{result=\"error\"}[1h]\n) > 3\n"
for: 0m
diff --git a/k8s/monitoring/telemetry-contract.yaml b/k8s/monitoring/telemetry-contract.yaml
new file mode 100644
index 000000000..e42e64b55
--- /dev/null
+++ b/k8s/monitoring/telemetry-contract.yaml
@@ -0,0 +1,60 @@
+# Opt-in Operator inventory, selected with the same site labels as the shared
+# PrometheusRule. It must remain independent of PodMonitor discovery.
+# If the application namespace or enabled roles change, patch this contract in
+# the site overlay too. Never copy private cluster/release labels into this file.
+apiVersion: monitoring.coreos.com/v1
+kind: PrometheusRule
+metadata:
+ name: testlookup-telemetry-contract
+ namespace: testlookup
+ labels:
+ app.kubernetes.io/name: testlookup
+ app.kubernetes.io/part-of: testlookup
+ role: alert-rules
+spec:
+ groups:
+ - name: testlookup.telemetry_contract.kubernetes
+ interval: 30s
+ rules:
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ namespace: testlookup
+ telemetry_profile: kubernetes
+ telemetry_role: backend
+ job: testlookup-backend
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ namespace: testlookup
+ telemetry_profile: kubernetes
+ telemetry_role: worker-critical
+ job: testlookup-worker
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ namespace: testlookup
+ telemetry_profile: kubernetes
+ telemetry_role: worker-ingestion
+ job: testlookup-worker
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ namespace: testlookup
+ telemetry_profile: kubernetes
+ telemetry_role: worker-ai
+ job: testlookup-worker
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ namespace: testlookup
+ telemetry_profile: kubernetes
+ telemetry_role: worker-default
+ job: testlookup-worker
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ namespace: testlookup
+ telemetry_profile: kubernetes
+ telemetry_role: worker-children
+ job: testlookup-worker
diff --git a/scripts/monitoring/configure_alerting.py b/scripts/monitoring/configure_alerting.py
new file mode 100644
index 000000000..6421df858
--- /dev/null
+++ b/scripts/monitoring/configure_alerting.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python3
+"""Validate private receiver inputs and derive the opt-in Prometheus config.
+
+This command never contacts a receiver and never prints input values. It
+preserves the current base scrape/rule configuration, including authenticated
+scrape include paths; the result is mounted at the original main-config path.
+"""
+from __future__ import annotations
+
+import argparse
+import copy
+import os
+from pathlib import Path
+import re
+from urllib.parse import urlsplit
+
+import yaml
+
+ROOT = Path(__file__).resolve().parents[2]
+IDENTITY = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,62}\Z")
+SECRET_ENVIRONMENTS = {
+ "incident_url": "ALERTMANAGER_INCIDENT_URL_SOURCE",
+ "incident_token": "ALERTMANAGER_INCIDENT_TOKEN_SOURCE",
+ "watchdog_url": "ALERTMANAGER_WATCHDOG_URL_SOURCE",
+ "watchdog_token": "ALERTMANAGER_WATCHDOG_TOKEN_SOURCE",
+}
+
+
+class ConfigurationError(ValueError):
+ """Safe error containing neither endpoint nor credential values."""
+
+
+def validate_receiver_files(files: dict[str, Path]) -> None:
+ for name in SECRET_ENVIRONMENTS:
+ path = files[name]
+ try:
+ if not path.is_file() or path.stat().st_size > 8192:
+ raise ConfigurationError(f"{name}: expected a nonempty private file of at most 8192 bytes")
+ value = path.read_text(encoding="utf-8").strip()
+ except (OSError, UnicodeError) as error:
+ raise ConfigurationError(f"{name}: cannot read UTF-8 secret file") from error
+ if not value or any(character.isspace() or ord(character) < 32 for character in value):
+ raise ConfigurationError(f"{name}: empty value or embedded whitespace is not allowed")
+ if name.endswith("_url"):
+ try:
+ url = urlsplit(value)
+ valid = (
+ url.scheme == "https" and bool(url.hostname)
+ and url.username is None and url.password is None
+ and not url.fragment and (url.port is None or 1 <= url.port <= 65535)
+ )
+ except ValueError:
+ valid = False
+ if not valid:
+ raise ConfigurationError(f"{name}: HTTPS URL without userinfo or fragment is required")
+
+
+def render_prometheus(base: dict, *, installation: str, environment: str, owner: str) -> dict:
+ for name, value in (("installation", installation), ("environment", environment), ("owner", owner)):
+ if not IDENTITY.fullmatch(value):
+ raise ConfigurationError(f"{name}: use 1-63 ASCII letters, digits, dots, underscores or hyphens")
+ result = copy.deepcopy(base)
+ if "alerting" in result or any(job.get("job_name") == "alertmanager" for job in result.get("scrape_configs", [])):
+ raise ConfigurationError("base already contains alerting configuration; merge explicitly before generating")
+ result.setdefault("global", {}).setdefault("external_labels", {}).update(
+ installation=installation, environment=environment,
+ )
+ result["alerting"] = {
+ "alert_relabel_configs": [{
+ "source_labels": ["owner"], "regex": "", "target_label": "owner", "replacement": owner,
+ }],
+ "alertmanagers": [{
+ "scheme": "http", "timeout": "10s", "api_version": "v2",
+ "follow_redirects": False,
+ "static_configs": [{"targets": ["alertmanager:9093"]}],
+ }],
+ }
+ result.setdefault("scrape_configs", []).append({
+ "job_name": "alertmanager", "scrape_interval": "15s",
+ "static_configs": [{
+ "targets": ["alertmanager:9093"],
+ "labels": {"telemetry_profile": "compose", "telemetry_role": "alertmanager"},
+ }],
+ })
+ result.setdefault("rule_files", []).append("alertmanager-contract.yml")
+ return result
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--base", type=Path, default=ROOT / "infra/monitoring/prometheus.yml")
+ parser.add_argument("--output", required=True, type=Path)
+ parser.add_argument("--installation", required=True)
+ parser.add_argument("--environment", required=True)
+ parser.add_argument("--owner", required=True)
+ args = parser.parse_args(argv)
+ try:
+ files = {}
+ for name, variable in SECRET_ENVIRONMENTS.items():
+ if not os.environ.get(variable):
+ raise ConfigurationError(f"{variable}: required private file path is missing")
+ files[name] = Path(os.environ[variable])
+ validate_receiver_files(files)
+ if args.output.resolve() == args.base.resolve():
+ raise ConfigurationError("output must differ from the tracked base configuration")
+ rendered = render_prometheus(
+ yaml.safe_load(args.base.read_text(encoding="utf-8")),
+ installation=args.installation, environment=args.environment, owner=args.owner,
+ )
+ args.output.parent.mkdir(parents=True, exist_ok=True)
+ args.output.write_text(yaml.safe_dump(rendered, sort_keys=False), encoding="utf-8")
+ except (ConfigurationError, OSError, yaml.YAMLError):
+ # Do not include exception text: YAML parsers and paths can echo secrets.
+ parser.exit(2, "Alert routing configuration failed; check private files, HTTPS URLs, identity fields and output path.\n")
+ print("Validated receiver inputs and generated the opt-in Prometheus configuration; no notification sent.")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/monitoring/tests/test_alert_routing.py b/scripts/monitoring/tests/test_alert_routing.py
new file mode 100644
index 000000000..7ee00d061
--- /dev/null
+++ b/scripts/monitoring/tests/test_alert_routing.py
@@ -0,0 +1,300 @@
+"""Opt-in routing contracts and real Prometheus -> Alertmanager -> TLS sink."""
+from __future__ import annotations
+
+from contextlib import contextmanager
+from datetime import datetime, timedelta, timezone
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import importlib.util
+import json
+import os
+from pathlib import Path
+import shutil
+import socket
+import ssl
+import subprocess
+import threading
+import time
+from urllib.error import HTTPError
+from urllib.request import ProxyHandler, Request, build_opener
+import uuid
+
+import pytest
+import yaml
+
+ROOT = Path(__file__).resolve().parents[3]
+SPEC = importlib.util.spec_from_file_location("configure_alerting", ROOT / "scripts/monitoring/configure_alerting.py")
+configure = importlib.util.module_from_spec(SPEC)
+assert SPEC.loader is not None
+SPEC.loader.exec_module(configure)
+
+
+def _private_files(tmp_path):
+ files = {}
+ for name in configure.SECRET_ENVIRONMENTS:
+ path = tmp_path / name
+ path.write_text("https://sink.invalid/" + name if name.endswith("_url") else uuid.uuid4().hex)
+ files[name] = path
+ return files
+
+
+@pytest.mark.parametrize("bad", ["", "http://sink.invalid/a", "https://user:secret@sink.invalid/a", "https://sink.invalid/#fragment", "https://sink.invalid:99999/a", "https://sink.invalid/a\nb"])
+def test_unsafe_receiver_input_is_rejected_without_echoing_it(tmp_path, bad):
+ files = _private_files(tmp_path)
+ files["incident_url"].write_text(bad)
+ with pytest.raises(configure.ConfigurationError) as error:
+ configure.validate_receiver_files(files)
+ assert "secret" not in str(error.value)
+ assert "sink.invalid" not in str(error.value)
+
+
+def test_credentials_must_be_nonempty_and_single_line(tmp_path):
+ files = _private_files(tmp_path)
+ configure.validate_receiver_files(files)
+ files["watchdog_token"].write_text("header\r\ninjection")
+ with pytest.raises(configure.ConfigurationError):
+ configure.validate_receiver_files(files)
+
+
+def test_generated_configuration_preserves_current_base_and_separate_auth_include():
+ base = yaml.safe_load((ROOT / "infra/monitoring/prometheus.yml").read_text())
+ generated = configure.render_prometheus(base, installation="fixture", environment="test", owner="platform")
+ assert generated["scrape_config_files"] == base["scrape_config_files"]
+ assert generated["rule_files"][:-1] == base["rule_files"]
+ assert generated["rule_files"][-1] == "alertmanager-contract.yml"
+ assert generated["scrape_configs"][:-1] == base["scrape_configs"]
+ assert "alerting" not in base
+ assert generated["global"]["external_labels"]["installation"] == "fixture"
+ assert generated["alerting"]["alertmanagers"][0]["static_configs"] == [{"targets": ["alertmanager:9093"]}]
+ assert generated["alerting"]["alert_relabel_configs"][0]["regex"] == ""
+ with pytest.raises(configure.ConfigurationError):
+ configure.render_prometheus(base, installation="", environment="test", owner="platform")
+
+
+def test_overlay_pin_inventory_private_api_and_secret_only_receivers():
+ overlay = yaml.safe_load((ROOT / "docker-compose.alerting.yml").read_text())
+ lock = json.loads((ROOT / "infra/monitoring/alertmanager/image-lock.json").read_text())
+ for service in ("alertmanager", "alertmanager-config-check"):
+ assert overlay["services"][service]["image"] == lock["image"]
+ assert "ports" not in overlay["services"][service]
+ assert "@sha256:" in lock["image"]
+ config = yaml.safe_load((ROOT / "infra/monitoring/alertmanager/alertmanager.yml").read_text())
+ assert {receiver["name"] for receiver in config["receivers"]} == {"incidents", "watchdog"}
+ for receiver in config["receivers"]:
+ webhook = receiver["webhook_configs"][0]
+ assert "url" not in webhook
+ assert webhook["url_file"].startswith("/run/secrets/")
+ assert webhook["send_resolved"] is True
+ http = webhook["http_config"]
+ assert http["authorization"]["credentials_file"].startswith("/run/secrets/")
+ assert http["follow_redirects"] is False
+ assert http["tls_config"]["min_version"] == "TLS12"
+ assert lock["bundle"] == "excluded"
+
+
+def _port():
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ return listener.getsockname()[1]
+
+
+def _eventually(check, timeout=15):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ result = check()
+ if result:
+ return result
+ time.sleep(0.05)
+ raise AssertionError("Local synthetic routing condition did not become true before its deadline")
+
+
+@contextmanager
+def _routing_stack(tmp_path):
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import rsa
+ from cryptography.x509.oid import NameOID
+ import ipaddress
+
+ token = uuid.uuid4().hex
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
+ subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "TestLookup disposable sink")])
+ now = datetime.now(timezone.utc)
+ certificate = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject)
+ .public_key(key.public_key()).serial_number(x509.random_serial_number())
+ .not_valid_before(now - timedelta(minutes=1)).not_valid_after(now + timedelta(hours=1))
+ .add_extension(x509.SubjectAlternativeName([x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), critical=False)
+ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
+ .sign(key, hashes.SHA256()))
+ cert_path, key_path = tmp_path / "sink-ca.pem", tmp_path / "sink-key.pem"
+ cert_path.write_bytes(certificate.public_bytes(serialization.Encoding.PEM))
+ key_path.write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
+ state = {"flags": {}, "events": [], "fail": False}
+ lock = threading.Lock()
+
+ class Sink(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_GET(self):
+ with lock:
+ body = "# TYPE synthetic_alert_active gauge\n" + "".join(
+ f'synthetic_alert_active{{name="{name}",replica="{replica}"}} {active}\n'
+ for name, active in state["flags"].items()
+ for replica in (("a", "b") if name == "Delivery" else ("a",))
+ )
+ self.send_response(200)
+ self.send_header("Content-Type", "text/plain; version=0.0.4")
+ self.end_headers()
+ self.wfile.write(body.encode())
+
+ def do_POST(self):
+ valid = self.headers.get("Authorization") == "Bearer " + token
+ payload = json.loads(self.rfile.read(min(int(self.headers.get("Content-Length", "0")), 1048576)))
+ with lock:
+ status = 503 if state["fail"] and self.path == "/incident" else (200 if valid else 401)
+ state["events"].append((self.path, status, payload))
+ self.send_response(status)
+ self.end_headers()
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Sink)
+ context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ context.load_cert_chain(cert_path, key_path)
+ server.socket = context.wrap_socket(server.socket, server_side=True)
+ server_thread = threading.Thread(target=server.serve_forever, daemon=True)
+ server_thread.start()
+ am_port, prom_port = _port(), _port()
+ am = yaml.safe_load((ROOT / "infra/monitoring/alertmanager/alertmanager.yml").read_text())
+ am["route"].update(group_wait="300ms", group_interval="300ms", repeat_interval="30s")
+ for route in am["route"]["routes"]:
+ route.update(group_wait="300ms", group_interval="300ms", repeat_interval="30s")
+ if route["receiver"] == "watchdog":
+ route["repeat_interval"] = "1s"
+ for receiver in am["receivers"]:
+ webhook = receiver["webhook_configs"][0]
+ route_path = "incident" if receiver["name"] == "incidents" else "watchdog"
+ url_file, token_file = tmp_path / (route_path + "-url"), tmp_path / (route_path + "-token")
+ url_file.write_text(f"https://127.0.0.1:{server.server_port}/{route_path}")
+ token_file.write_text(token)
+ webhook["url_file"] = str(url_file)
+ webhook["http_config"]["authorization"]["credentials_file"] = str(token_file)
+ webhook["http_config"]["tls_config"]["ca_file"] = str(cert_path)
+ am_config = tmp_path / "alertmanager.yml"
+ am_config.write_text(yaml.safe_dump(am))
+ rules = []
+ for name, severity, family in (
+ ("Delivery", "warning", ""), ("Silenced", "warning", ""),
+ ("Critical", "critical", "synthetic-family"), ("Inhibited", "warning", "synthetic-family"),
+ ("Failure", "critical", ""), ("Watchdog", "none", ""),
+ ):
+ alertname = "TestLookupWatchdog" if name == "Watchdog" else "Synthetic" + name
+ labels = {"severity": severity}
+ if family:
+ labels["alert_family"] = family
+ rules.append({"alert": alertname, "expr": f'synthetic_alert_active{{name="{name}"}} == 1',
+ "labels": labels,
+ "annotations": {"summary": "Disposable delivery proof", "runbook_url": "https://docs.invalid/runbook", "dashboard_url": "https://grafana.invalid/dashboard"}})
+ rule_file = tmp_path / "rules.yml"
+ rule_file.write_text(yaml.safe_dump({"groups": [{"name": "synthetic", "rules": rules}]}))
+ base = {"global": {"scrape_interval": "500ms", "scrape_timeout": "400ms", "evaluation_interval": "500ms"}, "rule_files": [str(rule_file)], "scrape_configs": [
+ {"job_name": "synthetic", "scheme": "https", "tls_config": {"ca_file": str(cert_path)}, "static_configs": [{"targets": [f"127.0.0.1:{server.server_port}"]}]}]}
+ prom = configure.render_prometheus(base, installation="fixture", environment="test", owner="platform")
+ prom["alerting"]["alertmanagers"][0]["static_configs"][0]["targets"] = [f"127.0.0.1:{am_port}"]
+ prom["scrape_configs"][-1]["static_configs"][0]["targets"] = [f"127.0.0.1:{am_port}"]
+ prom["scrape_configs"][-1]["scrape_interval"] = "500ms"
+ prom_file = tmp_path / "prometheus.yml"
+ shutil.copyfile(ROOT / "infra/monitoring/alertmanager/telemetry-contract.yml", tmp_path / "alertmanager-contract.yml")
+ prom_file.write_text(yaml.safe_dump(prom))
+ opener = build_opener(ProxyHandler({}))
+
+ def api(path, body=None, method=None):
+ request = Request(f"http://127.0.0.1:{am_port}" + path,
+ data=None if body is None else json.dumps(body).encode(),
+ headers={"Content-Type": "application/json"}, method=method)
+ with opener.open(request, timeout=1) as response:
+ raw = response.read()
+ return json.loads(raw) if raw and path.startswith("/api/") else raw.decode()
+
+ def ready():
+ try:
+ return api("/-/ready")
+ except (OSError, HTTPError):
+ return False
+
+ def events(alertname, status="firing", code=200):
+ with lock:
+ return [body for _, received, body in state["events"] if received == code and body["status"] == status
+ and any(alert["labels"]["alertname"] == alertname for alert in body["alerts"])]
+
+ processes = []
+ try:
+ if os.environ.get("AMTOOL_TEST_BINARY"):
+ subprocess.run([os.environ["AMTOOL_TEST_BINARY"], "check-config", str(am_config)], check=True, capture_output=True, timeout=10)
+ for binary, arguments in (
+ (os.environ["ALERTMANAGER_TEST_BINARY"], [f"--config.file={am_config}", f"--web.listen-address=127.0.0.1:{am_port}", f"--storage.path={tmp_path / 'am-data'}", "--cluster.listen-address=", "--log.level=warn"]),
+ (os.environ["PROMETHEUS_TEST_BINARY"], [f"--config.file={prom_file}", f"--web.listen-address=127.0.0.1:{prom_port}", f"--storage.tsdb.path={tmp_path / 'prom-data'}", "--rules.alert.resend-delay=500ms", "--log.level=warn"]),
+ ):
+ log = (tmp_path / (Path(binary).stem + ".log")).open("wb")
+ processes.append((subprocess.Popen([binary, *arguments], stdout=log, stderr=subprocess.STDOUT), log))
+ _eventually(ready)
+ yield state, lock, api, events
+ finally:
+ for process, log in reversed(processes):
+ process.terminate()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=5)
+ log.close()
+ server.shutdown()
+ server.server_close()
+ server_thread.join(timeout=2)
+
+
+@pytest.mark.skipif(not (os.environ.get("ALERTMANAGER_TEST_BINARY") and os.environ.get("PROMETHEUS_TEST_BINARY")), reason="requires pinned local Alertmanager and Prometheus binaries")
+def test_actual_rule_delivery_recovery_dedup_silence_inhibition_and_receiver_failure(tmp_path):
+ with _routing_stack(tmp_path) as (state, lock, api, events):
+ with lock:
+ state["flags"]["Delivery"] = 1
+ state["flags"]["Watchdog"] = 1
+ delivered = _eventually(lambda: events("SyntheticDelivery"))[0]
+ assert len(delivered["alerts"]) == 2 # Distinct replicas share one notification group.
+ alert = delivered["alerts"][0]
+ assert alert["labels"]["installation"] == "fixture"
+ assert alert["labels"]["environment"] == "test"
+ assert alert["labels"]["severity"] == "warning"
+ assert alert["labels"]["owner"] == "platform"
+ assert alert["annotations"]["runbook_url"] == "https://docs.invalid/runbook"
+ assert alert["annotations"]["dashboard_url"] == "https://grafana.invalid/dashboard"
+ _eventually(lambda: len(events("TestLookupWatchdog")) >= 2)
+ with lock:
+ assert all(path == "/watchdog" for path, _, body in state["events"] if any(a["labels"]["alertname"] == "TestLookupWatchdog" for a in body["alerts"]))
+ assert len(events("SyntheticDelivery")) == 1 # Prometheus resends did not duplicate delivery.
+ with lock:
+ state["flags"]["Delivery"] = 0
+ _eventually(lambda: events("SyntheticDelivery", "resolved"))
+
+ now = datetime.now(timezone.utc)
+ silence = api("/api/v2/silences", {"matchers": [{"name": "alertname", "value": "SyntheticSilenced", "isRegex": False, "isEqual": True}],
+ "startsAt": now.isoformat(), "endsAt": (now + timedelta(minutes=2)).isoformat(), "createdBy": "disposable-test", "comment": "synthetic maintenance proof"})
+ with lock:
+ state["flags"].update(Silenced=1, Critical=1, Inhibited=1)
+ _eventually(lambda: events("SyntheticCritical"))
+ _eventually(lambda: any(a["labels"]["alertname"] == "SyntheticSilenced" and a["status"]["silencedBy"] for a in api("/api/v2/alerts")))
+ _eventually(lambda: any(a["labels"]["alertname"] == "SyntheticInhibited" and a["status"]["inhibitedBy"] for a in api("/api/v2/alerts")))
+ assert not events("SyntheticSilenced")
+ assert not events("SyntheticInhibited")
+ api("/api/v2/silence/" + silence["silenceID"], method="DELETE")
+ _eventually(lambda: events("SyntheticSilenced"))
+
+ with lock:
+ state["fail"] = True
+ state["flags"]["Failure"] = 1
+ _eventually(lambda: events("SyntheticFailure", code=503))
+ _eventually(lambda: any(float(line.rsplit(" ", 1)[1]) > 0 for line in api("/metrics").splitlines() if line.startswith("alertmanager_notifications_failed_total{")))
+ with lock:
+ state["fail"] = False
+ _eventually(lambda: events("SyntheticFailure"), timeout=25)
+ with lock:
+ state["flags"]["Failure"] = 0
+ _eventually(lambda: events("SyntheticFailure", "resolved"))
From 25fcc0c9e25ce2f45ae657583f12435a192e78d6 Mon Sep 17 00:00:00 2001
From: Anand Topu
Date: Fri, 27 Nov 2026 00:23:20 -0600
Subject: [PATCH 04/13] feat: persist and correlate operational telemetry
Add a private Compose reference profile with durable Collector queues, Loki logs and Jaeger traces. Export bounded API, Celery and MCP operational events and verify trace and log correlation against pinned native services.
Provide mTLS client adapters for site-operated Kubernetes gateways, profile queue indicators, immutable image inventory and optional offline packaging with pinned external prerequisites.
Signed-off-by: Anand Topu
---
.github/workflows/ci.yml | 28 ++
.github/workflows/offline-bundle.yml | 28 +-
.github/workflows/third-party-images.yml | 4 +-
CHANGELOG.md | 1 +
THIRD_PARTY_NOTICES.md | 14 +-
backend/app/core/config.py | 5 +
backend/app/core/logging_config.py | 18 +-
backend/app/core/operational_logs.py | 165 +++++++++
backend/app/core/tracing.py | 14 +-
backend/app/worker/celery_app.py | 23 +-
backend/licenses/THIRD_PARTY_NOTICES.md | 14 +-
backend/requirements-lock.txt | 1 +
backend/requirements.txt | 1 +
backend/tests/test_operational_log_export.py | 95 +++++
deploy/images.manifest.txt | 15 +
docker-compose.monitoring.yml | 6 +-
docker-compose.telemetry.yml | 148 ++++++++
docs/maintainers/observability-delivery.md | 15 +
docs/operations/configuration.md | 3 +
docs/operations/deploy-cloud.md | 1 +
docs/operations/deploy-compose.md | 1 +
docs/operations/deploy-kubernetes.md | 2 +
docs/operations/deploy-openshift.md | 1 +
docs/operations/durable-telemetry.md | 71 ++++
docs/operations/log-storage.md | 160 +++++++++
docs/operations/persistent-jaeger.md | 62 ++++
docs/operations/telemetry-collector.md | 163 +++++++++
docs/reference/configuration.md | 2 +
e2e-runner/requirements-lock.txt | 254 +++++++++++++-
frontend/licenses/THIRD_PARTY_NOTICES.md | 14 +-
.../grafana/telemetry-datasources.yml | 45 +++
infra/monitoring/jaeger-image-lock.json | 11 +
infra/monitoring/jaeger.yml | 76 ++++
infra/monitoring/loki/image-lock.json | 27 ++
infra/monitoring/loki/loki.yml | 110 ++++++
infra/monitoring/otel-collector/config.yml | 169 +++++++++
.../monitoring/otel-collector/image-lock.json | 21 ++
infra/monitoring/otel-collector/scrape.yml | 7 +
.../otel-collector/telemetry-rules.yml | 43 +++
infra/monitoring/prometheus.yml | 1 +
infra/monitoring/tests/durable-telemetry.yml | 56 +++
k8s/components/telemetry-client/api.yaml | 32 ++
.../telemetry-client/kustomization.yaml | 11 +
k8s/components/telemetry-client/mcp.yaml | 28 ++
.../telemetry-client/networkpolicy.yaml | 23 ++
k8s/components/telemetry-client/worker.yaml | 29 ++
k8s/overlays/k3s-telemetry/kustomization.yaml | 7 +
.../openshift-telemetry/kustomization.yaml | 7 +
.../prod-telemetry/kustomization.yaml | 7 +
mcp/config.py | 2 +
mcp/licenses/THIRD_PARTY_NOTICES.md | 14 +-
mcp/operational_logs.py | 95 +++++
mcp/requirements-lock.txt | 254 +++++++++++++-
mcp/requirements.txt | 5 +
mcp/server.py | 14 +-
mcp/tests/test_operational_logs.py | 65 ++++
scripts/license-allowlist.json | 1 +
.../monitoring/tests/test_loki_reference.py | 273 +++++++++++++++
.../monitoring/tests/test_otel_collector.py | 326 ++++++++++++++++++
.../tests/test_telemetry_profile.py | 68 ++++
scripts/ops/verify_jaeger_persistence.py | 266 ++++++++++++++
scripts/release/check_image_drift.py | 49 ++-
scripts/release/image-manifest.sh | 18 +-
scripts/release/offline-bundle.sh | 52 ++-
scripts/test_jaeger_persistence.py | 87 +++++
user-guide/air-gapped-install.md | 1 +
66 files changed, 3562 insertions(+), 67 deletions(-)
create mode 100644 backend/app/core/operational_logs.py
create mode 100644 backend/tests/test_operational_log_export.py
create mode 100644 docker-compose.telemetry.yml
create mode 100644 docs/operations/durable-telemetry.md
create mode 100644 docs/operations/log-storage.md
create mode 100644 docs/operations/persistent-jaeger.md
create mode 100644 docs/operations/telemetry-collector.md
create mode 100644 infra/monitoring/grafana/telemetry-datasources.yml
create mode 100644 infra/monitoring/jaeger-image-lock.json
create mode 100644 infra/monitoring/jaeger.yml
create mode 100644 infra/monitoring/loki/image-lock.json
create mode 100644 infra/monitoring/loki/loki.yml
create mode 100644 infra/monitoring/otel-collector/config.yml
create mode 100644 infra/monitoring/otel-collector/image-lock.json
create mode 100644 infra/monitoring/otel-collector/scrape.yml
create mode 100644 infra/monitoring/otel-collector/telemetry-rules.yml
create mode 100644 infra/monitoring/tests/durable-telemetry.yml
create mode 100644 k8s/components/telemetry-client/api.yaml
create mode 100644 k8s/components/telemetry-client/kustomization.yaml
create mode 100644 k8s/components/telemetry-client/mcp.yaml
create mode 100644 k8s/components/telemetry-client/networkpolicy.yaml
create mode 100644 k8s/components/telemetry-client/worker.yaml
create mode 100644 k8s/overlays/k3s-telemetry/kustomization.yaml
create mode 100644 k8s/overlays/openshift-telemetry/kustomization.yaml
create mode 100644 k8s/overlays/prod-telemetry/kustomization.yaml
create mode 100644 mcp/operational_logs.py
create mode 100644 mcp/tests/test_operational_logs.py
create mode 100644 scripts/monitoring/tests/test_loki_reference.py
create mode 100644 scripts/monitoring/tests/test_otel_collector.py
create mode 100644 scripts/monitoring/tests/test_telemetry_profile.py
create mode 100644 scripts/ops/verify_jaeger_persistence.py
create mode 100644 scripts/test_jaeger_persistence.py
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f4c8bc332..863f62ea2 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -560,6 +560,9 @@ jobs:
python scripts/monitoring/configure_alerting.py \
--output "$scratch/config/alerting.yml" --installation fixture --environment ci --owner platform
"$tool" check config "$scratch/config/alerting.yml"
+ cp "$monitoring/otel-collector/scrape.yml" "$scratch/config/telemetry-scrape-collector.yml"
+ cp "$monitoring/otel-collector/telemetry-rules.yml" "$scratch/config/rules/durable-telemetry.yml"
+ "$tool" check config "$scratch/config/alerting.yml"
# Test firing, resolved and Watchdog delivery to an isolated TLS sink.
mapfile -t alertmanager_pin < <(python -c '
import json
@@ -576,8 +579,33 @@ jobs:
export PROMETHEUS_TEST_BINARY="$scratch/$prometheus_dir/prometheus"
export ALERTMANAGER_TEST_BINARY="$scratch/$alertmanager_dir/alertmanager"
export AMTOOL_TEST_BINARY="$scratch/$alertmanager_dir/amtool"
+ # Native processes use loopback and disposable storage in the tests.
+ fetch_monitoring_archive() {
+ local lock="$1" output="$2"
+ local -a pin
+ mapfile -t pin < <(python -c '
+ import json
+ from pathlib import Path
+ import sys
+ pin = json.loads(Path(sys.argv[1]).read_text())["release_binaries"]["linux-amd64"]
+ print(pin["url"], pin["sha256"], sep="\n")
+ ' "$lock")
+ curl --fail --location --silent --show-error --retry 3 --max-time 180 \
+ --output "$output" "${pin[0]}"
+ printf '%s %s\n' "${pin[1]}" "$output" | sha256sum --check --strict
+ }
+ fetch_monitoring_archive "$monitoring/otel-collector/image-lock.json" "$scratch/otelcol.tar.gz"
+ fetch_monitoring_archive "$monitoring/loki/image-lock.json" "$scratch/loki.zip"
+ fetch_monitoring_archive "$monitoring/jaeger-image-lock.json" "$scratch/jaeger.tar.gz"
+ tar -xzf "$scratch/otelcol.tar.gz" -C "$scratch" otelcol-contrib
+ unzip -q "$scratch/loki.zip" loki-linux-amd64 -d "$scratch"
+ tar -xzf "$scratch/jaeger.tar.gz" -C "$scratch" jaeger-2.23.0-linux-amd64/jaeger
+ export OTELCOL_TEST_BINARY="$scratch/otelcol-contrib"
+ export LOKI_TEST_BINARY="$scratch/loki-linux-amd64"
+ export JAEGER_TEST_BINARY="$scratch/jaeger-2.23.0-linux-amd64/jaeger"
export PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
python -m pytest scripts/monitoring/tests -q
+ python -m pytest scripts/test_jaeger_persistence.py -q
# Blocking, as a ratchet (re-audit M24). mypy reports 391 pre-existing
# errors in 117 files; backend/mypy-baseline.txt holds the per-file
diff --git a/.github/workflows/offline-bundle.yml b/.github/workflows/offline-bundle.yml
index fdf399e0a..122d89dca 100644
--- a/.github/workflows/offline-bundle.yml
+++ b/.github/workflows/offline-bundle.yml
@@ -55,6 +55,10 @@ on:
description: "Also bundle Ollama + ChromaDB (adds ~4 GB)"
type: boolean
default: false
+ with_telemetry:
+ description: "Include durable Compose telemetry configuration and redistributable images"
+ type: boolean
+ default: false
version:
description: "Release version without the v (for example 0.1.0): bundle the images that release promoted instead of building them. Leave empty for a CI check build."
type: string
@@ -69,6 +73,8 @@ permissions:
env:
BUNDLE_VERSION: ${{ inputs.version || format('ci-{0}', github.sha) }}
RELEASE_TAG: ${{ inputs.version && format('v{0}', inputs.version) || '' }}
+ WITH_LLM: ${{ inputs.with_llm || false }}
+ WITH_TELEMETRY: ${{ inputs.with_telemetry || false }}
jobs:
# ───────────────────────────────────────────────────────────────
@@ -173,9 +179,11 @@ jobs:
- name: Show the bundle plan
run: |
- bash scripts/release/offline-bundle.sh --dry-run \
- --version "${BUNDLE_VERSION}" \
- --created-at "${{ steps.meta.outputs.created_at }}"
+ set -euo pipefail
+ args=(--dry-run --version "$BUNDLE_VERSION" --created-at "${{ steps.meta.outputs.created_at }}")
+ if [ "$WITH_LLM" = true ]; then args+=(--with-llm); fi
+ if [ "$WITH_TELEMETRY" = true ]; then args+=(--with-telemetry); fi
+ bash scripts/release/offline-bundle.sh "${args[@]}"
# syft is intentionally NOT installed here: the released images carry
# BuildKit SBOM attestations in the registry, which `docker save` cannot
@@ -187,15 +195,11 @@ jobs:
- name: Build the offline bundle
run: |
set -euo pipefail
- ARGS="--version ${BUNDLE_VERSION} --created-at ${{ steps.meta.outputs.created_at }}"
- if [ "${{ github.event.inputs.with_llm }}" = "true" ]; then
- ARGS="$ARGS --with-llm"
- fi
- if [ -n "$RELEASE_TAG" ]; then
- ARGS="$ARGS --skip-build"
- fi
- # shellcheck disable=SC2086
- bash scripts/release/offline-bundle.sh $ARGS
+ args=(--version "$BUNDLE_VERSION" --created-at "${{ steps.meta.outputs.created_at }}")
+ if [ "$WITH_LLM" = true ]; then args+=(--with-llm); fi
+ if [ "$WITH_TELEMETRY" = true ]; then args+=(--with-telemetry); fi
+ if [ -n "$RELEASE_TAG" ]; then args+=(--skip-build); fi
+ bash scripts/release/offline-bundle.sh "${args[@]}"
# The bundle must carry the pulled digests, not a local build:
# MANIFEST.json records each app image's registry digest.
diff --git a/.github/workflows/third-party-images.yml b/.github/workflows/third-party-images.yml
index 68e9e28b9..f1dbf6272 100644
--- a/.github/workflows/third-party-images.yml
+++ b/.github/workflows/third-party-images.yml
@@ -23,6 +23,7 @@ on:
- deploy/images.manifest.txt
- docker-compose.monitoring.yml
- docker-compose.alerting.yml
+ - docker-compose.telemetry.yml
- .github/workflows/third-party-images.yml
# A pull request that changes an image or this workflow sees the report
# before it merges.
@@ -31,6 +32,7 @@ on:
- deploy/images.manifest.txt
- docker-compose.monitoring.yml
- docker-compose.alerting.yml
+ - docker-compose.telemetry.yml
- .github/workflows/third-party-images.yml
workflow_dispatch:
@@ -79,7 +81,7 @@ jobs:
set -euo pipefail
{
awk '!/^[[:space:]]*#/ && NF >= 2 && $2 == "infra" { print $1 }' deploy/images.manifest.txt
- sed -n 's/^[[:space:]]*image:[[:space:]]*//p' docker-compose.monitoring.yml docker-compose.alerting.yml
+ sed -n 's/^[[:space:]]*image:[[:space:]]*//p' docker-compose.monitoring.yml docker-compose.alerting.yml docker-compose.telemetry.yml
} | sort -u > third-party-images.txt
test "$(wc -l < third-party-images.txt)" -ge 8
cat third-party-images.txt
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 462f68d12..f30219b35 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).
### Added
+- The durable telemetry profile adds queued OpenTelemetry export, persistent Loki logs and Jaeger traces, Grafana correlation, and queue loss alerts. Kubernetes client overlays support a site-operated mTLS gateway, and the offline Compose bundle can include the durable stack.
- The optional Compose alerting overlay adds a private Alertmanager with authenticated HTTPS incident and watchdog receivers. Compose and Kubernetes monitoring inventories detect missing scrape roles and required metric series.
- Operational metrics report SQLAlchemy pool pressure and acquisition timeouts for API and worker processes, plus Redis and Valkey memory for the application and broker. Optional Compose and Kubernetes profiles support file-backed authentication for API scrapes.
- Operational metrics expose collector freshness and durable downstream-outbox failure/overdue state, including alerts that avoid counting the same SQL rows across API replicas.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index a447f8785..9b0932830 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -146,12 +146,12 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `numpy` | BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0 | backend |
| `openpyxl` | MIT | backend |
| `opentelemetry-api` | Apache-2.0 | backend |
-| `opentelemetry-exporter-otlp-proto-http` | Apache-2.0 | backend |
+| `opentelemetry-exporter-otlp-proto-http` | Apache-2.0 | backend, mcp |
| `opentelemetry-instrumentation-fastapi` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-httpx` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-redis` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-sqlalchemy` | Apache-2.0 | backend |
-| `opentelemetry-sdk` | Apache-2.0 | backend |
+| `opentelemetry-sdk` | Apache-2.0 | backend, mcp |
| `passlib` | BSD-3-Clause | backend |
| `platformdirs` | MIT | cli |
| `prometheus-client` | Apache-2.0 AND BSD-2-Clause | backend |
@@ -174,6 +174,7 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `pyyaml` | MIT | backend, cli, client |
| `redis` | MIT | backend |
| `reportlab` | BSD-3-Clause | backend |
+| `requests` | Apache-2.0 | backend, mcp |
| `rich` | MIT | cli |
| `ruff` | MIT | backend |
| `scikit-learn` | BSD-3-Clause | backend |
@@ -188,7 +189,7 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `typer` | MIT | cli |
| `types-python-dateutil` | Apache-2.0 | backend |
| `tzdata` | Apache-2.0 | backend |
-| `uvicorn` | BSD-3-Clause | backend |
+| `uvicorn` | BSD-3-Clause | backend, mcp |
## Container base images
@@ -234,6 +235,13 @@ They are listed for your own license review.
| `ollama/ollama:0.40.10` | MIT; the image also contains NVIDIA CUDA runtime libraries under the NVIDIA CUDA EULA | https://github.com/ollama/ollama |
| `chromadb/chroma:1.5.9` | Apache-2.0 | https://github.com/chroma-core/chroma |
| `mher/flower:2.0` | BSD-3-Clause | https://github.com/mher/flower |
+| `busybox:1.36@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662` | see upstream | |
+| `prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06` | see upstream | |
+| `grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf` | see upstream | |
+| `otel/opentelemetry-collector-contrib:0.166.0@sha256:3e18fe04181de50bdd72e23ad4a4d6214b54351e63d496f1c58127cc4541ad7f` | see upstream | |
+| `cr.jaegertracing.io/jaegertracing/jaeger:2.23.0@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e` | see upstream | |
+| `grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7` | see upstream | |
+| `docker.io/prom/alertmanager:v0.35.1@sha256:4e3d029e69c7f61dd53a2b31a3dc427a2b81736cffca185c0854075e07969e36` | see upstream | |
**MongoDB** is licensed under the Server Side Public License (SSPL-1.0), which
is not an OSI-approved license. TestLookup only connects to it with the
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index ec808200a..18b14616d 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -970,6 +970,11 @@ def _validate_sso_max_provisioned_role(cls, v):
# When empty: stdout in development only; elsewhere nothing is exported
# and one warning is logged (core/tracing.py, re-audit N22)
OTEL_EXPORTER_OTLP_ENDPOINT: Optional[str] = None
+ # Signal-specific OTLP/HTTP URL, including /v1/logs. Unset keeps stdout
+ # as the only log destination. The reference profile uses a private
+ # Compose network; remote and platform-managed endpoints use HTTPS.
+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: str = ""
+ OTEL_LOGS_ROLE: Literal["api", "worker", "worker-children", "beat"] = "api"
# Prometheus metrics endpoint
METRICS_ENABLED: bool = True
# Optional bearer token for GET /metrics. Empty (the default) leaves the
diff --git a/backend/app/core/logging_config.py b/backend/app/core/logging_config.py
index 90261caba..a0bcccd71 100644
--- a/backend/app/core/logging_config.py
+++ b/backend/app/core/logging_config.py
@@ -166,8 +166,22 @@ def configure_logging() -> None:
structlog.dev.set_exc_info,
structlog.processors.format_exc_info,
structlog.processors.UnicodeDecoder(),
- _privacy_redaction,
]
+ structured_processors = shared_processors.copy()
+ if settings.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:
+ from app.core.operational_logs import operational_log_export
+
+ structured_processors.append(operational_log_export(
+ endpoint=settings.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT,
+ service=settings.OTEL_SERVICE_NAME,
+ environment=settings.APP_ENV,
+ role=settings.OTEL_LOGS_ROLE,
+ min_level=level,
+ ))
+ # The exporter hashes caller IDs before the stdout scrubber can replace a
+ # numeric ID. Its independent allowlist does not forward any free text.
+ shared_processors.append(_privacy_redaction)
+ structured_processors.append(_privacy_redaction)
renderer: Any = (
structlog.processors.JSONRenderer()
@@ -181,7 +195,7 @@ def configure_logging() -> None:
structlog.configure(
processors=[
- *shared_processors,
+ *structured_processors,
structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
],
logger_factory=structlog.stdlib.LoggerFactory(),
diff --git a/backend/app/core/operational_logs.py b/backend/app/core/operational_logs.py
new file mode 100644
index 000000000..ec03ccf2f
--- /dev/null
+++ b/backend/app/core/operational_logs.py
@@ -0,0 +1,165 @@
+"""Export an allowlisted projection of application logs to a private OTLP sink."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import re
+import threading
+import time
+from functools import lru_cache
+from urllib.parse import urlsplit
+
+import requests
+from opentelemetry import trace
+from opentelemetry._logs import Logger, SeverityNumber
+from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
+from opentelemetry.sdk._logs import LoggerProvider
+from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
+from opentelemetry.sdk.resources import Resource
+from opentelemetry.util.types import AttributeValue
+from structlog.types import EventDict, WrappedLogger
+
+logger = logging.getLogger(__name__)
+
+_HTTP_EVENTS = frozenset({
+ ("http.access", "http_request"),
+ ("app.core.analytics_errors", "analytics_unhandled_error"),
+ ("app.core.analytics_errors", "http_unhandled_error"),
+})
+_WORKER_EVENT = ("app.worker.celery_app", "celery_task_execution")
+_STATE = frozenset({"success", "failure", "retry", "other"})
+_IDENTIFIER = re.compile(r"[A-Za-z0-9._:-]{1,128}")
+_SEVERITY = {"warning": SeverityNumber.WARN, "error": SeverityNumber.ERROR}
+
+
+def _validate_endpoint(url: str) -> None:
+ endpoint = urlsplit(url)
+ private_http = endpoint.scheme == "http" and endpoint.hostname in {
+ "otel-collector", "localhost", "127.0.0.1", "::1",
+ }
+ if (
+ not endpoint.hostname or (endpoint.scheme != "https" and not private_http)
+ or endpoint.path != "/v1/logs" or endpoint.username is not None
+ or endpoint.query or endpoint.fragment
+ ):
+ raise ValueError("expected an HTTPS OTLP/HTTP logs URL")
+
+
+class OperationalLogExport:
+ """Feed a bounded SDK processor without replacing the normal stdout log."""
+
+ def __init__(
+ self, *, endpoint: str, service: str, environment: str, role: str, min_level: int = logging.INFO,
+ ) -> None:
+ self._endpoint = endpoint
+ self._attributes = {
+ "service.name": service,
+ "service.namespace": "testlookup",
+ "deployment.environment.name": environment,
+ "testlookup.service.role": role,
+ }
+ self._role = role
+ self._min_level = min_level
+ self._pid = os.getpid()
+ self._sdk_logger: Logger | None = None
+ self._start_failed = False
+ self._lock = threading.Lock()
+
+ def _get_logger(self) -> Logger | None:
+ if self._start_failed:
+ return None
+ if self._sdk_logger is not None:
+ return self._sdk_logger
+ with self._lock:
+ if self._sdk_logger is not None or self._start_failed:
+ return self._sdk_logger
+ try:
+ _validate_endpoint(self._endpoint)
+ session = requests.Session()
+ session.trust_env = False
+ session.max_redirects = 0
+ exporter = OTLPLogExporter(
+ endpoint=self._endpoint, timeout=2, max_request_size=65_536, session=session,
+ )
+ provider = LoggerProvider(resource=Resource(self._attributes))
+ provider.add_log_record_processor(BatchLogRecordProcessor(
+ exporter, max_queue_size=512, max_export_batch_size=64, schedule_delay_millis=1000,
+ ))
+ self._sdk_logger = provider.get_logger("testlookup.operational")
+ except Exception: # noqa: BLE001 - telemetry must not interrupt logging
+ self._start_failed = True
+ logger.warning("Operational log exporter could not initialize; using stdout")
+ return self._sdk_logger
+
+ def __call__(self, _logger: WrappedLogger, method: str, event: EventDict) -> EventDict:
+ event_name = event.get("event")
+ source = event.get("logger")
+ if not isinstance(event_name, str) or not isinstance(source, str):
+ return event
+ key = (source, event_name)
+ api_event = key in _HTTP_EVENTS and self._role == "api"
+ worker_event = key == _WORKER_EVENT and self._role in {"worker", "worker-children"}
+ if not api_event and not worker_event:
+ return event
+ if getattr(logging, method.upper(), logging.INFO) < self._min_level:
+ return event
+ pid = os.getpid()
+ if pid != self._pid:
+ # The inherited SDK session and lock may belong to a dead thread.
+ self._sdk_logger = None
+ self._lock = threading.Lock()
+ self._start_failed = False
+ self._pid = pid
+ sdk_logger = self._get_logger()
+ if sdk_logger is None:
+ return event
+ try:
+ body: dict[str, str | int | float] = {"event": event_name}
+ attributes: dict[str, AttributeValue] = {}
+ for field in ("request_id", "celery_task_id"):
+ value = event.get(field)
+ if isinstance(value, str) and _IDENTIFIER.fullmatch(value):
+ # IDs come from callers/brokers. Hash even well-formed
+ # values to keep arbitrary opaque input out of the store.
+ digest = hashlib.sha256(value.encode("ascii")).hexdigest()
+ body[field] = digest
+ attributes[field] = digest
+ status = event.get("status_code")
+ if type(status) is int and 100 <= status <= 599:
+ body["status_code"] = status
+ attributes["status_code"] = status
+ duration = event.get("duration_ms")
+ if isinstance(duration, (int, float)) and not isinstance(duration, bool) and 0 <= duration <= 600_000:
+ body["duration_ms"] = duration
+ attributes["duration_ms"] = duration
+ state = event.get("state")
+ if isinstance(state, str) and state in _STATE:
+ body["state"] = state
+ attributes["state"] = state
+ span = trace.get_current_span().get_span_context()
+ if span.is_valid:
+ body.update(trace_id=f"{span.trace_id:032x}", span_id=f"{span.span_id:016x}")
+ severity = _SEVERITY.get(method, SeverityNumber.INFO)
+ sdk_logger.emit(
+ timestamp=time.time_ns(),
+ severity_number=severity,
+ severity_text=severity.name,
+ event_name=event_name,
+ body=json.dumps(body, separators=(",", ":")),
+ attributes=attributes,
+ )
+ except Exception: # noqa: BLE001 - preserve stdout if projection or submission fails
+ logger.warning("Operational log submission failed")
+ return event
+
+
+@lru_cache(maxsize=1)
+def operational_log_export(
+ *, endpoint: str, service: str, environment: str, role: str, min_level: int,
+) -> OperationalLogExport:
+ return OperationalLogExport(
+ endpoint=endpoint, service=service, environment=environment, role=role, min_level=min_level,
+ )
diff --git a/backend/app/core/tracing.py b/backend/app/core/tracing.py
index ffc5435b1..91311d58f 100644
--- a/backend/app/core/tracing.py
+++ b/backend/app/core/tracing.py
@@ -459,9 +459,19 @@ def setup_tracing(
)
trace_endpoint = _otlp_trace_endpoint(otlp_endpoint)
- exporter = OTLPSpanExporter(endpoint=trace_endpoint, timeout=10)
+ if urlsplit(trace_endpoint).hostname in {
+ "otel-collector", "testlookup-otel.testlookup-telemetry.svc",
+ }:
+ import requests
+
+ session = requests.Session()
+ session.trust_env = False
+ session.max_redirects = 0
+ exporter = OTLPSpanExporter(endpoint=trace_endpoint, timeout=10, session=session)
+ else:
+ exporter = OTLPSpanExporter(endpoint=trace_endpoint, timeout=10)
_add_exporter(provider, exporter)
- logger.info("OTEL tracing enabled → %s", trace_endpoint)
+ logger.info("OTEL tracing enabled")
except ImportError:
if environment == "development":
logger.warning(
diff --git a/backend/app/worker/celery_app.py b/backend/app/worker/celery_app.py
index 02e161ab6..c5f2535c0 100644
--- a/backend/app/worker/celery_app.py
+++ b/backend/app/worker/celery_app.py
@@ -920,16 +920,25 @@ def _record_task_outcome(task_id=None, task=None, state=None, **_kwargs: object)
@task_postrun.connect
-def _clear_task_log_context(task=None, **_kwargs: object) -> None:
+def _clear_task_log_context(task=None, state=None, **_kwargs: object) -> None:
"""Postrun runs for success, failure and retry; none may leak into the next task."""
from structlog.contextvars import bind_contextvars, clear_contextvars
- clear_contextvars()
- request = getattr(task, "request", None)
- parent_context = getattr(request, "_testlookup_parent_log_context", None)
- if getattr(request, "is_eager", False) and isinstance(parent_context, dict):
- del request._testlookup_parent_log_context
- bind_contextvars(**parent_context)
+ try:
+ if settings.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT:
+ import structlog
+
+ outcome = {"SUCCESS": "success", "FAILURE": "failure", "RETRY": "retry"}.get(state, "other")
+ task_logger = structlog.get_logger(__name__)
+ log = task_logger.warning if outcome in {"failure", "retry"} else task_logger.info
+ log("celery_task_execution", state=outcome)
+ finally:
+ clear_contextvars()
+ request = getattr(task, "request", None)
+ parent_context = getattr(request, "_testlookup_parent_log_context", None)
+ if getattr(request, "is_eager", False) and isinstance(parent_context, dict):
+ del request._testlookup_parent_log_context
+ bind_contextvars(**parent_context)
#: Readiness sentinel. Written once the worker has booted and connected to the
diff --git a/backend/licenses/THIRD_PARTY_NOTICES.md b/backend/licenses/THIRD_PARTY_NOTICES.md
index a447f8785..9b0932830 100644
--- a/backend/licenses/THIRD_PARTY_NOTICES.md
+++ b/backend/licenses/THIRD_PARTY_NOTICES.md
@@ -146,12 +146,12 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `numpy` | BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0 | backend |
| `openpyxl` | MIT | backend |
| `opentelemetry-api` | Apache-2.0 | backend |
-| `opentelemetry-exporter-otlp-proto-http` | Apache-2.0 | backend |
+| `opentelemetry-exporter-otlp-proto-http` | Apache-2.0 | backend, mcp |
| `opentelemetry-instrumentation-fastapi` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-httpx` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-redis` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-sqlalchemy` | Apache-2.0 | backend |
-| `opentelemetry-sdk` | Apache-2.0 | backend |
+| `opentelemetry-sdk` | Apache-2.0 | backend, mcp |
| `passlib` | BSD-3-Clause | backend |
| `platformdirs` | MIT | cli |
| `prometheus-client` | Apache-2.0 AND BSD-2-Clause | backend |
@@ -174,6 +174,7 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `pyyaml` | MIT | backend, cli, client |
| `redis` | MIT | backend |
| `reportlab` | BSD-3-Clause | backend |
+| `requests` | Apache-2.0 | backend, mcp |
| `rich` | MIT | cli |
| `ruff` | MIT | backend |
| `scikit-learn` | BSD-3-Clause | backend |
@@ -188,7 +189,7 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `typer` | MIT | cli |
| `types-python-dateutil` | Apache-2.0 | backend |
| `tzdata` | Apache-2.0 | backend |
-| `uvicorn` | BSD-3-Clause | backend |
+| `uvicorn` | BSD-3-Clause | backend, mcp |
## Container base images
@@ -234,6 +235,13 @@ They are listed for your own license review.
| `ollama/ollama:0.40.10` | MIT; the image also contains NVIDIA CUDA runtime libraries under the NVIDIA CUDA EULA | https://github.com/ollama/ollama |
| `chromadb/chroma:1.5.9` | Apache-2.0 | https://github.com/chroma-core/chroma |
| `mher/flower:2.0` | BSD-3-Clause | https://github.com/mher/flower |
+| `busybox:1.36@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662` | see upstream | |
+| `prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06` | see upstream | |
+| `grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf` | see upstream | |
+| `otel/opentelemetry-collector-contrib:0.166.0@sha256:3e18fe04181de50bdd72e23ad4a4d6214b54351e63d496f1c58127cc4541ad7f` | see upstream | |
+| `cr.jaegertracing.io/jaegertracing/jaeger:2.23.0@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e` | see upstream | |
+| `grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7` | see upstream | |
+| `docker.io/prom/alertmanager:v0.35.1@sha256:4e3d029e69c7f61dd53a2b31a3dc427a2b81736cffca185c0854075e07969e36` | see upstream | |
**MongoDB** is licensed under the Server Side Public License (SSPL-1.0), which
is not an OSI-approved license. TestLookup only connects to it with the
diff --git a/backend/requirements-lock.txt b/backend/requirements-lock.txt
index 07d9bb447..a37c7b7b6 100644
--- a/backend/requirements-lock.txt
+++ b/backend/requirements-lock.txt
@@ -4092,6 +4092,7 @@ requests==2.34.2 \
--hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \
--hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed
# via
+ # -r requirements.txt
# google-auth
# google-genai
# kubernetes
diff --git a/backend/requirements.txt b/backend/requirements.txt
index 9fa2ea73d..d99130edd 100644
--- a/backend/requirements.txt
+++ b/backend/requirements.txt
@@ -132,6 +132,7 @@ aiohttp==3.14.5 # CVE-2026-69244; CVE-2026-111064, CVE-2026-111066 (3.1
opentelemetry-api==1.45.2
opentelemetry-sdk==1.45.2
opentelemetry-exporter-otlp-proto-http==1.45.2
+requests==2.34.2 # explicit no-proxy sessions for private OTLP endpoints
# Auto-instrumentors — must match sdk 1.45.2 → instrumentor 0.66b2.
# The coupling is hard, not stylistic: sdk 1.45.2 pins
# opentelemetry-semantic-conventions==0.66b2 and every instrumentor 0.66b2
diff --git a/backend/tests/test_operational_log_export.py b/backend/tests/test_operational_log_export.py
new file mode 100644
index 000000000..6cfc8f173
--- /dev/null
+++ b/backend/tests/test_operational_log_export.py
@@ -0,0 +1,95 @@
+"""The private OTLP hop carries only the approved operational projection."""
+
+import hashlib
+import json
+import logging
+import queue
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from threading import Thread
+
+import structlog
+from opentelemetry import trace
+from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
+
+from app.core.operational_logs import OperationalLogExport
+from app.core.config import settings
+from app.core.logging_config import configure_logging
+
+
+def test_operational_events_are_exported_without_free_text() -> None:
+ uploads: queue.Queue[ExportLogsServiceRequest] = queue.Queue()
+
+ class Receiver(BaseHTTPRequestHandler):
+ def do_POST(self) -> None:
+ assert self.path == "/v1/logs"
+ request = ExportLogsServiceRequest.FromString(self.rfile.read(int(self.headers["Content-Length"])))
+ uploads.put(request)
+ self.send_response(200)
+ self.end_headers()
+
+ with ThreadingHTTPServer(("127.0.0.1", 0), Receiver) as receiver:
+ server = Thread(target=receiver.serve_forever)
+ server.start()
+ try:
+ sink = OperationalLogExport(
+ endpoint=f"http://127.0.0.1:{receiver.server_port}/v1/logs",
+ service="testlookup", environment="production", role="api",
+ )
+ secret = "synthetic-opaque-input"
+ approved = {
+ "logger": "http.access", "event": "http_request", "duration_ms": 4.2,
+ "status_code": 201, "request_id": secret, "path": "/" + secret,
+ "trace_id": "a" * 32, "error": secret,
+ }
+ ignored = {"logger": "app.other", "event": "http_request", "request_id": secret}
+ assert sink(None, "info", ignored) is ignored
+ assert uploads.empty()
+
+ span = trace.NonRecordingSpan(trace.SpanContext(
+ trace_id=0x101, span_id=0x102, is_remote=False, trace_flags=trace.TraceFlags.SAMPLED,
+ ))
+ with trace.use_span(span):
+ assert sink(None, "info", approved) is approved
+ serialized = uploads.get(timeout=5)
+ assert secret.encode() not in serialized.SerializeToString()
+ resource = serialized.resource_logs[0]
+ assert len(resource.scope_logs[0].log_records) == 1
+ record = resource.scope_logs[0].log_records[0]
+ assert record.event_name == "http_request"
+ assert record.trace_id.hex() == f"{0x101:032x}"
+ assert record.span_id.hex() == f"{0x102:016x}"
+ digest = hashlib.sha256(secret.encode()).hexdigest()
+ assert json.loads(record.body.string_value) == {
+ "event": "http_request", "duration_ms": 4.2, "status_code": 201,
+ "request_id": digest, "trace_id": f"{0x101:032x}", "span_id": f"{0x102:016x}",
+ }
+ assert {value.key: value.value.string_value for value in record.attributes}["request_id"] == digest
+ finally:
+ receiver.shutdown()
+ server.join()
+
+
+def test_cleartext_remote_endpoint_leaves_normal_logging_available() -> None:
+ sink = OperationalLogExport(
+ endpoint="http://other.example/v1/logs",
+ service="testlookup", environment="production", role="api",
+ )
+ event = {"logger": "http.access", "event": "http_request"}
+ assert sink(None, "info", event) is event
+ assert sink._start_failed
+
+
+def test_configured_operational_export_preserves_stdout_logging(monkeypatch) -> None:
+ root = logging.getLogger()
+ previous_settings = structlog.get_config()
+ previous_handlers, previous_level = root.handlers[:], root.level
+ monkeypatch.setattr(settings, "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "http://otel-collector:4318/v1/logs")
+ try:
+ configure_logging()
+ assert len(root.handlers) == 1
+ assert any(isinstance(processor, OperationalLogExport)
+ for processor in structlog.get_config()["processors"])
+ finally:
+ structlog.configure(**previous_settings)
+ root.handlers[:] = previous_handlers
+ root.setLevel(previous_level)
diff --git a/deploy/images.manifest.txt b/deploy/images.manifest.txt
index 5a50a1d30..b4fcdeb95 100644
--- a/deploy/images.manifest.txt
+++ b/deploy/images.manifest.txt
@@ -24,8 +24,11 @@
# 3. surfaces comma list of the deployment surfaces that reference it:
# compose = docker-compose{,.release,.dev-lite}.yml
# k8s = k8s/base + k8s/overlays/**
+# telemetry = optional durable Compose monitoring overlays
# 4. bundle core = always in the offline bundle
# llm = only with `make offline-bundle ARGS=--with-llm`
+# telemetry = only with `make offline-bundle ARGS=--with-telemetry`
+# telemetry-external = operator-supplied telemetry prereq
# external = a third-party PREREQUISITE the deployment needs
# but the bundle does not redistribute (licence —
# reason in the comment above the row). The
@@ -95,3 +98,15 @@ chromadb/chroma:1.5.9 infra compose,k8s llm
# docker-compose.release.yml + docker-compose.airgap.yml, which has no flower
# service, so shipping it would be dead weight.
mher/flower:2.0 infra compose excluded
+
+# Optional durable Compose telemetry. Source references are immutable. The
+# offline builder saves the selected architecture under a local-only alias.
+busybox:1.36@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662 infra telemetry telemetry
+prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06 infra telemetry telemetry
+# Grafana and Loki upstream OSS images are AGPLv3. They stay external to
+# TestLookup's distributed archives. See https://grafana.com/licensing/
+grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf infra telemetry telemetry-external
+otel/opentelemetry-collector-contrib:0.166.0@sha256:3e18fe04181de50bdd72e23ad4a4d6214b54351e63d496f1c58127cc4541ad7f infra telemetry telemetry
+cr.jaegertracing.io/jaegertracing/jaeger:2.23.0@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e infra telemetry telemetry
+grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7 infra telemetry telemetry-external
+docker.io/prom/alertmanager:v0.35.1@sha256:4e3d029e69c7f61dd53a2b31a3dc427a2b81736cffca185c0854075e07969e36 infra telemetry telemetry
diff --git a/docker-compose.monitoring.yml b/docker-compose.monitoring.yml
index cf879cea4..9691f4790 100644
--- a/docker-compose.monitoring.yml
+++ b/docker-compose.monitoring.yml
@@ -39,7 +39,7 @@ services:
# ── Prometheus ──────────────────────────────────────────────────────────────
prometheus:
- image: prom/prometheus:v3.16.0
+ image: prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06
container_name: testlookup-prometheus
restart: unless-stopped
command:
@@ -98,7 +98,6 @@ services:
- testlookup_net
depends_on:
- prometheus
- - jaeger
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:3000/api/health"]
interval: 20s
@@ -111,9 +110,6 @@ services:
OTEL_ENABLED: "true"
OTEL_EXPORTER_OTLP_ENDPOINT: "http://jaeger:4318"
METRICS_ENABLED: "true"
- depends_on:
- jaeger:
- condition: service_healthy
volumes:
prometheus-data:
diff --git a/docker-compose.telemetry.yml b/docker-compose.telemetry.yml
new file mode 100644
index 000000000..fc21505f5
--- /dev/null
+++ b/docker-compose.telemetry.yml
@@ -0,0 +1,148 @@
+# Opt in after docker-compose.monitoring.yml. See docs/operations/durable-telemetry.md.
+x-telemetry-hardening: &telemetry-hardening
+ read_only: true
+ cap_drop: [ALL]
+ security_opt: [no-new-privileges:true]
+ restart: unless-stopped
+ depends_on:
+ telemetry-volume-init:
+ condition: service_completed_successfully
+
+x-log-rotation: &log-rotation
+ driver: local
+ options:
+ max-size: "10m"
+ max-file: "3"
+
+x-worker-telemetry: &worker-telemetry
+ OTEL_SERVICE_NAME: testlookup
+ OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: http://otel-collector:4318/v1/logs
+
+services:
+ telemetry-volume-init:
+ image: busybox:1.36@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662
+ user: "0:0"
+ network_mode: none
+ read_only: true
+ cap_drop: [ALL]
+ cap_add: [CHOWN]
+ security_opt: [no-new-privileges:true]
+ command:
+ - sh
+ - -ec
+ - |
+ mkdir -p /otel/storage /otel/compaction
+ chown 10001:10001 /otel /otel/storage /otel/compaction /jaeger /loki
+ volumes:
+ - otel-spool:/otel
+ - jaeger-data:/jaeger
+ - loki-data:/loki
+
+ otel-collector:
+ <<: *telemetry-hardening
+ image: otel/opentelemetry-collector-contrib:0.166.0@sha256:3e18fe04181de50bdd72e23ad4a4d6214b54351e63d496f1c58127cc4541ad7f
+ user: "10001:10001"
+ command: [--config=/etc/otelcol-contrib/config.yml]
+ environment:
+ GOMEMLIMIT: 448MiB
+ mem_limit: 512m
+ cpus: 1.0
+ volumes:
+ - ./infra/monitoring/otel-collector/config.yml:/etc/otelcol-contrib/config.yml:ro
+ - otel-spool:/var/lib/otelcol
+ networks: [telemetry_ingress, telemetry_storage, telemetry_metrics]
+ logging: *log-rotation
+
+ jaeger:
+ <<: *telemetry-hardening
+ image: cr.jaegertracing.io/jaegertracing/jaeger:2.23.0@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e
+ user: "10001:10001"
+ command: [--config=/etc/jaeger/config.yaml]
+ environment: !override
+ GOMEMLIMIT: 384MiB
+ mem_limit: 512m
+ cpus: 1.0
+ ports: !reset []
+ networks: !override [telemetry_storage]
+ healthcheck: !override
+ disable: true
+ volumes:
+ - ./infra/monitoring/jaeger.yml:/etc/jaeger/config.yaml:ro
+ - jaeger-data:/var/lib/jaeger
+ logging: *log-rotation
+
+ loki:
+ <<: *telemetry-hardening
+ image: grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7
+ user: "10001:10001"
+ command: [-config.file=/etc/loki/testlookup.yml]
+ environment:
+ GOMEMLIMIT: 768MiB
+ mem_limit: 1g
+ cpus: 1.0
+ volumes:
+ - ./infra/monitoring/loki/loki.yml:/etc/loki/testlookup.yml:ro
+ - loki-data:/loki
+ networks: [telemetry_storage]
+ logging: *log-rotation
+
+ prometheus:
+ networks: [telemetry_metrics]
+ volumes:
+ - ./infra/monitoring/otel-collector/scrape.yml:/etc/prometheus/telemetry-scrape-collector.yml:ro
+ - ./infra/monitoring/otel-collector/telemetry-rules.yml:/etc/prometheus/rules/durable-telemetry.yml:ro
+
+ grafana:
+ networks: [telemetry_storage]
+ environment:
+ GF_FEATURE_TOGGLES_ENABLE: jaegerEnableGrpcEndpoint
+ GF_ANALYTICS_REPORTING_ENABLED: "false"
+ GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
+ GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: "false"
+ volumes:
+ - ./infra/monitoring/grafana/telemetry-datasources.yml:/etc/grafana/provisioning/datasources/prometheus.yml:ro
+
+ backend:
+ environment:
+ <<: *worker-telemetry
+ OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
+ OTEL_LOGS_ROLE: api
+ networks: [telemetry_ingress]
+ logging: *log-rotation
+
+ worker:
+ environment:
+ <<: *worker-telemetry
+ OTEL_LOGS_ROLE: worker
+ networks: [telemetry_ingress]
+ logging: *log-rotation
+
+ worker-children:
+ environment:
+ <<: *worker-telemetry
+ OTEL_LOGS_ROLE: worker-children
+ networks: [telemetry_ingress]
+ logging: *log-rotation
+
+ beat:
+ logging: *log-rotation
+
+ mcp:
+ environment:
+ TESTLOOKUP_OTLP_LOGS_ENDPOINT: http://otel-collector:4318/v1/logs
+ TESTLOOKUP_TELEMETRY_ENVIRONMENT: ${APP_ENV:-production}
+ networks: [telemetry_ingress]
+ logging: *log-rotation
+
+networks:
+ telemetry_ingress:
+ internal: true
+ telemetry_storage:
+ internal: true
+ telemetry_metrics:
+ internal: true
+
+volumes:
+ otel-spool:
+ jaeger-data:
+ loki-data:
diff --git a/docs/maintainers/observability-delivery.md b/docs/maintainers/observability-delivery.md
index cd29720f2..09d49f9da 100644
--- a/docs/maintainers/observability-delivery.md
+++ b/docs/maintainers/observability-delivery.md
@@ -156,3 +156,18 @@ This iteration builds on `a84edf88`. It extends the existing profile monitoring
Prometheus 3.16 and Alertmanager 0.35.1 delivered firing and resolved payloads to a disposable TLS receiver. The test exercised grouped replicas, deduplication, silence, inhibition, watchdog cadence and provider retry. The rule fixtures cover missed schedules, receiver availability, disappearing roles and required series. Both migrations were rendered forward and backward for PostgreSQL. The disposable PostgreSQL concurrency case is part of the existing integration job.
The focused backend suite passed 406 tests and skipped the case that requires a disposable PostgreSQL instance. All 40 Prometheus semantic scenarios passed. Compose and Operator manifests were rendered, and no production receivers were contacted.
+
+## Iteration 4: durable log and trace collection
+
+This iteration builds on `be88915c`. The app keeps its normal stdout logs and Prometheus scrapes. An opt-in profile exports selected operational records and API traces.
+
+| Story | Change | Remaining acceptance |
+|---|---|---|
+| OBS-E04-S01 | The [profile and ownership contract](../operations/durable-telemetry.md) defines installation boundaries, retention, capacity and fault drills across Compose and managed deployments. | Assign site owners and validate retention, storage sizing, residency and receiver routing with the deployment team. |
+| OBS-E04-S02 | Collector ingress accepts the TestLookup service, rebuilds bounded log records and stores two finite, persistent exporter queues. Prometheus observes queue pressure and refusals. | Measure the actual full-stack failure window, pre-collector loss and capacity under site traffic. |
+| OBS-E04-S03 | Persistent Loki indexes three resource labels. API, Celery and MCP use a structured projection with hashed request or task IDs. Grafana queries Loki and can open a known Jaeger trace. | Run an authorized access drill and measure retention expiry, disk use and incident readback in the deployed profile. |
+| OBS-E04-S04 | Jaeger 2.23 uses synchronous Badger storage with a 72-hour TTL. Grafana can read traces by ID through the v3 API, and native Jaeger handles service and operation search. | Validate filesystem sizing, private UI access and the chosen HA storage path at each site. |
+| OBS-E04-S05 | Kubernetes, K3s and OpenShift render optional mTLS client adapters for a site-operated gateway. | Verify workload admission, certificate rotation, monitoring selection and persistent readback in disposable platform-matched clusters. |
+| OBS-E04-S06 | The image manifest and third-party scan track every durable reference image. The optional offline bundle records exact pins and aliases for all components and lists Grafana and Loki as operator-supplied prerequisites. | Exercise image import and the full stack with outbound internet blocked. |
+
+Disposable native runs covered queue overflow, retry exhaustion and recovery after collector restart, plus forced Loki and Jaeger restarts. Grafana returned matching trace and log IDs using the pinned datasource versions. The Kubernetes adapters were rendered locally. The Compose stack's runtime networking, actual site gateways and disconnected operation still need deployment-level evidence.
diff --git a/docs/operations/configuration.md b/docs/operations/configuration.md
index a4ea274ba..4ca7604b9 100644
--- a/docs/operations/configuration.md
+++ b/docs/operations/configuration.md
@@ -437,6 +437,9 @@ Setup steps for each integration are in [Integrations](integrations.md). Values
| `OTEL_ENABLED` | bool | `true` | OpenTelemetry tracing for the API. |
| `OTEL_SERVICE_NAME` | str | `testlookup` | Service name on spans. |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | str (optional) | unset | OTLP/HTTP collector, for example `http://otel-collector:4318`. Unset: spans go to stdout in development only; elsewhere nothing is exported and one warning is logged. |
+| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | str | unset | Full OTLP/HTTP URL ending in `/v1/logs` for selected API or worker events. Use HTTPS outside the private Compose or loopback hop. |
+| `OTEL_LOGS_ROLE` | literal | `api` | Use `worker` or `worker-children` for task outcomes. See the [durable telemetry contract](durable-telemetry.md). |
+| `TESTLOOKUP_OTLP_LOGS_ENDPOINT` | str | unset | Full OTLP/HTTP log URL for MCP's SSE transport. |
| `METRICS_ENABLED` | bool | `true` | Exposes Prometheus metrics at `/metrics` on the API. Worker metrics are separate (see `PROMETHEUS_MULTIPROC_DIR` below). |
| `LOG_LEVEL` | str | `INFO` | `DEBUG`, `INFO`, `WARNING` or `ERROR`. |
| `LOG_FORMAT` | `json` \| `text` | `json` | Structured JSON for log shippers; `text` for reading in a terminal. Logs can name people (proxy query strings; application lines written before the release that added personal-data erasure): see [Scrubbing a person from your log store](../../user-guide/compliance.md#scrubbing-a-person-from-your-log-store). |
diff --git a/docs/operations/deploy-cloud.md b/docs/operations/deploy-cloud.md
index 7b790169e..a89c2985a 100644
--- a/docs/operations/deploy-cloud.md
+++ b/docs/operations/deploy-cloud.md
@@ -110,5 +110,6 @@ The overlay keeps the NGINX annotations from the base (120-second proxy timeouts
## Related
- [Kubernetes guide](deploy-kubernetes.md) for the base, secrets, monitoring and backups
+- [Durable telemetry](durable-telemetry.md#kubernetes-and-managed-gateways) for private or managed OTLP collection
- [Sizing](../../user-guide/sizing.md)
- [Startup and upgrade order](deployment.md#startup-and-upgrade-order)
diff --git a/docs/operations/deploy-compose.md b/docs/operations/deploy-compose.md
index 56f051002..29bcd6aa0 100644
--- a/docs/operations/deploy-compose.md
+++ b/docs/operations/deploy-compose.md
@@ -11,6 +11,7 @@ Docker Compose runs the whole stack on one host. There are four Compose files yo
| `docker-compose.release.yml` | Pulls prebuilt images from `ghcr.io/test-intelligence/testlookup` | A host that runs published images, installed with `install.sh` or by hand |
| `docker-compose.airgap.yml` (override) | Re-points every image at your registry | Air-gapped hosts, layered on the release file |
| `docker-compose.monitoring.yml` (override) | Pulls Prometheus, Grafana, Jaeger | Metrics, dashboards and traces next to the stack |
+| `docker-compose.telemetry.yml` (override) | Adds Collector, persistent Jaeger and Loki | [Durable logs and traces](durable-telemetry.md) |
| `docker-compose.gcp-vm.yml` (override) | Production build targets | A cloud VM; see [single VM](deploy-single-vm.md) |
## Prerequisites
diff --git a/docs/operations/deploy-kubernetes.md b/docs/operations/deploy-kubernetes.md
index 4e7c90a52..25edb766f 100644
--- a/docs/operations/deploy-kubernetes.md
+++ b/docs/operations/deploy-kubernetes.md
@@ -190,6 +190,8 @@ Provision a Secret named `testlookup-metrics-auth` with key `token` in the appli
In the selected Prometheus, confirm discovery for each API and worker pod and verify `up{job="testlookup-backend"} == 1`. A direct API scrape from the private network should return 401 with missing or mismatched credentials and return samples with the mounted token. Worker port 9100 relies on the monitoring namespace NetworkPolicy. On platforms with an external scraper, supply a site-specific policy and TLS before crossing a trust boundary.
+The [durable telemetry adapters](durable-telemetry.md#kubernetes-and-managed-gateways) add client-authenticated OTLP export for API, workers and MCP to a site-operated gateway.
+
Rotate the Secret, wait for the Operator to reconcile its scrape configuration, and roll the backend deployment so each API process loads the new token. A rolling transition can produce temporary 401s from pods using different token generations. Verify every API target returns samples after the rollout and the old credential receives 401. Keep token values out of rendered manifests, commands and verification records.
## Backups
diff --git a/docs/operations/deploy-openshift.md b/docs/operations/deploy-openshift.md
index f1bcd68a8..d0c550ba2 100644
--- a/docs/operations/deploy-openshift.md
+++ b/docs/operations/deploy-openshift.md
@@ -117,3 +117,4 @@ If no host can reach both the internet and the Artifactory, use the [offline bun
- [Kubernetes guide](deploy-kubernetes.md): Secret and ConfigMap keys, migrations, network policies, monitoring
- [Backup component](../../k8s/components/backup/README.md)
- [Air-gapped install](../../user-guide/air-gapped-install.md)
+- [Durable telemetry and site gateway credentials](durable-telemetry.md#kubernetes-and-managed-gateways)
diff --git a/docs/operations/durable-telemetry.md b/docs/operations/durable-telemetry.md
new file mode 100644
index 000000000..e187e2c94
--- /dev/null
+++ b/docs/operations/durable-telemetry.md
@@ -0,0 +1,71 @@
+# Durable logs and traces
+
+The durable profile keeps selected operational logs and API traces searchable across process and container restarts. Prometheus continues to scrape application metrics directly. The platform operator owns collection, storage capacity, Grafana access, and the alerts for telemetry loss.
+
+| Platform | Collection and storage | Trust and availability |
+|---|---|---|
+| Source and release Compose | OpenTelemetry Collector, Loki filesystem storage, and Jaeger with Badger. Grafana reuses its existing Prometheus and Jaeger UIDs and adds `loki`. | One installation on one host. The private network peers share a trust boundary and the named volumes have no replication. |
+| Kubernetes, K3s and OpenShift | The telemetry client overlays send to the site's authenticated OTLP gateway. The site owns the gateway, persistent queue, native Loki ingestion or equivalent, and a supported Jaeger or managed trace backend. | Workloads use client certificates. The gateway owner configures admission, ingress policy, storage, authorized query access and HA. |
+| Managed cloud or existing monitoring | Use the same HTTPS OTLP log and trace export contracts with the site's authenticated endpoint. Keep native Prometheus, managed scraping or an existing compatible metrics stack. | The service owner specifies retention, residency, access, egress and loss monitoring in the incident runbook. |
+| Air-gapped Compose | The optional offline bundle includes the redistributable telemetry images and configuration, with pinned Grafana and Loki prerequisites supplied by the operator. | Build on the target architecture and verify the archive and its matching source release before import. Use locally authorized HTTPS receivers for alerting. |
+
+## Enable Compose
+
+Use Docker Compose 2.24.4 or later. Supply the existing monitoring profile's Grafana credentials and expose Grafana through an authorized operator tunnel or authenticated TLS proxy. The additional components publish no host ports.
+
+```sh
+docker compose -f docker-compose.release.yml -f docker-compose.monitoring.yml \
+ -f docker-compose.telemetry.yml config --quiet
+docker compose -f docker-compose.release.yml -f docker-compose.monitoring.yml \
+ -f docker-compose.telemetry.yml up -d
+```
+
+Use `docker-compose.yml` as the base when building images from source. The [authenticated scrape](deploy-compose.md#authenticate-the-api-scrape) and [alert routing](alert-routing.md) overlays can follow the durable profile. Regenerate an existing alerting configuration from the new Prometheus source so it loads the collector's scrape include. API and workers start independently of all telemetry services. The initialization container prepares the three volume mounts for non-root processes, has no network access, and exits before those processes start.
+
+## Search an incident
+
+In Grafana Explore, select **Loki**. Resource labels are `service_name`, `service_namespace`, and `deployment_environment_name`. Request, task, span and trace IDs stay out of the index. For a request ID the API or MCP service returned, hash its original ASCII spelling with no newline.
+
+```sh
+printf '%s' "$REQUEST_ID" | sha256sum
+```
+
+```logql
+{service_name="testlookup", service_namespace="testlookup"}
+ | request_id=""
+```
+
+Search Celery execution records by the same hash in `celery_task_id`. Cases with an active API span include its native OTLP trace and span IDs, plus fields Grafana can link to Jaeger. The Jaeger datasource uses Grafana's v3 option for lookup by trace ID. Service and operation search uses the private Jaeger v2 UI, available through an authorized path on the storage network. App and operational error logs remain available through each service's stdout. The Compose profile rotates those service logs at three 10 MiB files per container.
+
+## Data and limits
+
+- Central logs include API request and server error events, Celery task outcomes, and MCP SSE response metadata. The collector rebuilds these records from fixed event names, hashed IDs and bounded status and duration fields before enqueueing. It discards the incoming log body. URLs, payloads, raw exception text, credentials, and product data stay out of the central log projection. Keep business audit and retention evidence in the application stores.
+- Current API traces are sanitized before OTLP export. The collector applies a second attribute allowlist and clears trace status messages and event text. Library span context and timing can reveal infrastructure topology. Limit trace access to operators with that responsibility.
+- The app log SDK holds 512 records per process in memory and sends batches of up to 64. The collector has a 32 MiB persistent queue per exporter, a 64 MiB per-database ceiling, and up to 10 minutes of retry per dequeued item. Install a filesystem or volume quota that can accommodate both queues and compaction. A collector acknowledgement means it admitted the batch to its durable queue. The downstream store can still refuse it.
+- Reference log search retains 7 days, with asynchronous compaction and deletion. Reference traces retain 72 hours. Badger may preallocate several GiB even with little trace traffic. Reserve separate quota and headroom for each store, measure real intake, and alert on free space and retained volume. Choose retention and backup for the installation's incident and privacy obligations.
+- A single node's disk loss can remove both queued and stored telemetry. For HA use a separately operated collector deployment and shared or replicated stores supported by the vendors. Preserve a separate heartbeat and alert delivery path.
+
+## Kubernetes and managed gateways
+
+Render `k8s/overlays/prod-telemetry`, `k8s/overlays/k3s-telemetry`, or `k8s/overlays/openshift-telemetry` with the same image and application configuration as the base installation. Each enables the private OTLP/HTTP address `https://testlookup-otel.testlookup-telemetry.svc:4318`. The service's gateway pods carry the label `app.kubernetes.io/name: testlookup-otel` and accept application traffic on port 4318 from the authorized namespaces and pod roles. The gateway certificate must match that service DNS name.
+
+Install separate namespace-local Secrets `testlookup-otel-api-client`, `testlookup-otel-worker-client`, and `testlookup-otel-mcp-client` with `ca.crt`, `tls.crt`, and `tls.key` keys. The app sends through the OpenTelemetry exporter and reads the mounted trust material from files. The mounts are optional so missing material or a gateway outage leaves the application available. Require client authentication at the gateway and rotate credentials with a controlled workload restart. For a managed gateway, change the client endpoints, egress policy and trust material to the approved site values.
+
+The added egress policy names the gateway and port. Existing application policies may allow broader egress because Kubernetes combines allow rules. Enforce source admission and a dedicated client trust policy on the gateway, including denial without the expected client certificate.
+
+## Offline Compose
+
+Add `--with-telemetry` to the standard [offline bundle](../../user-guide/air-gapped-install.md) build. It records upstream digests alongside local image aliases. The OSS Grafana and Loki images are external prerequisites under TestLookup's redistribution policy. The bundle's `compose/telemetry-prerequisites.list` records each pinned source image and required local alias as tab-separated fields. Stage those two images on a connected host, tag each verified image under its listed alias, and transfer and load them using your approved offline image process. [Grafana Labs licensing](https://grafana.com/licensing/).
+
+After verified import and normal registry setup, layer `docker-compose.monitoring.yml` and `docker-compose.telemetry.yml` after the release and air-gap Compose files. Run `docker compose ... up --pull never`. Provide environment files, credentials and optional alert receiver trust from local sources. Perform the first run with outbound network access denied and verify no external image, plugin, catalog or notification dependency is needed.
+
+## Acceptance and response
+
+1. Confirm the expected Collector role is up in Prometheus. Check `otelcol_exporter_queue_size`, `otelcol_exporter_queue_capacity`, enqueue and send failure counters, receiver refusals and available space. The durable overlay alerts on a queue above 80% for two minutes or recent loss. Verify the separate receiver can report a complete monitoring outage.
+2. Generate a synthetic API request, a Celery task, and an MCP request. Read them back by hashed ID. Follow the API trace from Grafana and confirm that payload and credential markers are absent.
+3. Break each storage connection in a disposable deployment. Observe queue growth without an application readiness failure. Verify recovery after a collector restart, queue refusal at capacity, and loss metrics when retries expire.
+4. Restart each store with its volume retained and verify readback. Check retention and authorized and denied query paths. Check cluster admission, monitor selection and credential rotation independently for K3s and OpenShift.
+
+The reference configuration follows the [OpenTelemetry Collector resiliency guide](https://opentelemetry.io/docs/collector/resiliency/), [Loki native OTLP mapping](https://grafana.com/docs/loki/latest/send-data/otel/), and [Jaeger storage documentation](https://www.jaegertracing.io/docs/2.23/storage/).
+
+Component details and verification commands are in [collector operations](telemetry-collector.md), [log storage](log-storage.md), and [persistent Jaeger](persistent-jaeger.md).
diff --git a/docs/operations/log-storage.md b/docs/operations/log-storage.md
new file mode 100644
index 000000000..fdd7457a4
--- /dev/null
+++ b/docs/operations/log-storage.md
@@ -0,0 +1,160 @@
+# Persistent application logs and trace correlation
+
+The opt-in [durable telemetry profile](durable-telemetry.md) sends application
+OTLP logs through the collector to a private, single-process Loki backend.
+It does not mount the Docker socket, container log directories or host files.
+Only explicitly configured application exporters enter this pipeline; logs
+from other containers, host services and early process startup are not claimed
+as collected. The application's bounded local/container log rotation remains
+a separate troubleshooting fallback.
+
+The pinned reference uses Loki 3.7.10, verified against the upstream release
+and multi-platform image manifest in
+[`image-lock.json`](../../infra/monitoring/loki/image-lock.json).
+It is a small-install reference with persistent storage, not an HA service or
+a compliance retention system. Larger deployments can point the same OTLP
+exporter and Grafana datasource at the site's authenticated managed Loki.
+
+## Storage and trust boundary
+
+[`loki.yml`](../../infra/monitoring/loki/loki.yml) stores chunks, the TSDB v13
+index, index cache, WAL and compactor retention markers below `/loki`.
+The profile mounts `loki-data` there and initializes ownership for the pinned
+image's non-root UID `10001`. Keep one writer and one compactor for this
+volume. Do not share it between Loki replicas. WAL recovery preserves
+acknowledged fixture logs across a killed Loki process; this does not prove
+durability across disk corruption, node loss or a failed volume.
+
+Compactor retention is enabled for seven days (`168h`), using a 24-hour TSDB
+index period and a two-hour asynchronous deletion delay. The compactor's
+working directory is persistent so deletion markers survive process restarts.
+Query lookback is also seven days. User-requested deletion APIs are disabled.
+Retention is asynchronous and is not an exact deletion deadline or a disk
+quota. Measure daily volume, leave WAL/index/compaction headroom, set a
+site-specific volume budget and alert before the filesystem fills. Back up
+the volume using a consistent snapshot while the service is stopped if
+incident-log recovery is required; this reference does not configure backups,
+legal holds, immutable audit storage or automatic disk expansion.
+
+Loki's `auth_enabled: false` selects a single tenant; it does **not** add
+authentication. HTTP `3100` is reachable only on the dedicated internal
+storage network, from Grafana and the collector, with no published host port.
+The gRPC listener binds to `127.0.0.1`. Do not add public ingress to this
+reference endpoint. A shared/untrusted network needs a separately reviewed
+TLS/authentication boundary and tenant/query authorization. Grafana access
+controls govern its authenticated query path; everyone with access to this
+single datasource sees this tenant's operational logs.
+
+The configuration bounds ingestion to 1 MiB/s with a 2 MiB burst, 500 active
+streams, 64 KiB log lines and 16 KiB/32 entries of structured metadata per
+record. Lines above the limit are rejected, not partially truncated. Queries
+are limited to 1,000 log entries, 30 seconds and two concurrent queriers.
+These settings bound specific operations; they do not guarantee total memory
+or disk use. Observe collector queue/drop/retry and Loki rejection metrics
+when tuning the profile. The collector's persistent queue and application
+export buffers have their own limits and failure windows.
+
+## Labels, metadata and safe queries
+
+Only these resource attributes become indexed stream labels:
+
+| OTLP resource attribute | Loki label |
+|---|---|
+| `service.name` | `service_name` |
+| `service.namespace` | `service_namespace` |
+| `deployment.environment.name` | `deployment_environment_name` |
+
+The reference application service and namespace are `testlookup`. Environment
+and application role must come from deployment configuration, not a caller.
+Bounded roles such as `api`, `worker`, `worker-children`, `beat` and `mcp` stay
+metadata (`testlookup_service_role`), as do per-instance identity and version.
+Trace IDs, span IDs, request IDs, task IDs and correlation IDs never become
+indexed labels. Loki stores native trace/span IDs and allowlisted OTLP record
+attributes as structured metadata. The sanitized JSON body redundantly
+contains trace and diagnostic IDs when available, supporting text inspection
+and Grafana's derived-field link. Missing trace context is valid for records
+outside a sampled/current span.
+
+The reference Jaeger trace retention is shorter than Loki log retention.
+A valid log link can therefore refer to a trace that was not sampled or has
+already expired; a missing trace is not proof that the stored log is invalid.
+
+The collector restricts source identity and attribute intake; it does not
+make arbitrary message bodies safe. Preserve the application's redaction
+boundary before export. Request/response bodies, prompts, credentials and
+user identifiers must not be introduced as log payloads or labels. Existing
+operational logs are not a durable, tamper-evident audit record.
+
+Use a narrow time range and an indexed service/environment selector, then
+filter IDs as metadata:
+
+```logql
+{service_namespace="testlookup",deployment_environment_name="production"} | request_id="example-request"
+{service_namespace="testlookup"} | trace_id="0123456789abcdef0123456789abcdef"
+{service_namespace="testlookup"} | task_id="example-task"
+{service_namespace="testlookup"} | testlookup_service_role="worker"
+```
+
+Do not put the request or trace ID inside the braces: those are not indexed
+stream labels. Use `| json` only when inspecting a field that exists solely
+inside the body, and avoid an unnecessarily broad body scan.
+
+## Grafana provisioning and links
+
+Mount the complete opt-in
+[`telemetry-datasources.yml`](../../infra/monitoring/grafana/telemetry-datasources.yml)
+over `/etc/grafana/provisioning/datasources/prometheus.yml`. It preserves the
+Prometheus datasource and existing Jaeger UID `jaeger`, then adds Loki UID
+`loki` at `http://loki:3100`. Do not add a second datasource provisioning file
+that repeats the Jaeger UID. The source is deliberately outside the base
+provisioning directory so the basic monitoring profile does not load it.
+
+Jaeger's `tracesToLogsV2` query selects native `trace_id` metadata within the
+`testlookup` namespace, widening the span window by two minutes on each side.
+The Loki derived field extracts a 32-character trace ID from the sanitized
+JSON body and opens the existing Jaeger datasource. The provisioning file
+escapes Grafana macros with `$$`; stored datasource settings must retain
+`${__span.traceId}` and `${__value.raw}` after provisioning.
+
+The pinned Grafana 13.3.1 Jaeger datasource needs
+`GF_FEATURE_TOGGLES_ENABLE=jaegerEnableGrpcEndpoint` for Jaeger 2.23's HTTP v3
+health/service/operation/trace-ID path. The flag's name does not mean the
+query URL should use a gRPC port: it remains `http://jaeger:16686`.
+Full Grafana Jaeger search still uses an unavailable legacy endpoint in this
+combination; use direct trace-ID correlation or the native Jaeger UI for
+search. This reference does not provide a compatibility shim or claim full
+Grafana trace-search support.
+
+## Disposable verification
+
+Static tests run with:
+
+```sh
+python -m pytest scripts/monitoring/tests/test_loki_reference.py -q
+```
+
+Set `LOKI_TEST_BINARY` to a checksum-verified executable from the recorded
+release to execute actual OTLP ingestion, metadata-only ID filtering, exact
+three-label index checks and forced-kill/WAL recovery. Also set
+`GRAFANA_TEST_HOME` to the checksum-verified Grafana release recorded in the
+lock file to execute actual datasource provisioning, macro escaping, health
+and Grafana `/api/ds/query` against Loki. `GRAFANA_TEST_BINARY` can override
+the executable path. Set `JAEGER_TEST_BINARY` as well for the joint case to
+start the pinned Jaeger fixture, emit the same synthetic trace/log ID, and
+verify Grafana health and direct trace-ID readback. Every listener is loopback
+and every data path is temporary; these tests do not contact an incident
+receiver or change a deployment.
+
+Skipping the runtime tests is not ingestion or restart evidence. The
+reference tests do not wait seven days for compactor deletion, prove full
+filesystem/node failure recovery, exercise Grafana UI clicks, or validate
+site authorization and production capacity. Installation acceptance must
+also verify actual application-to-collector export, queue recovery and
+sanitized source-to-query correlation in the selected profile.
+
+Primary references: [Loki OTLP mapping](https://grafana.com/docs/loki/latest/send-data/otel/),
+[TSDB storage](https://grafana.com/docs/loki/latest/operations/storage/tsdb/),
+[compactor retention](https://grafana.com/docs/loki/latest/operations/storage/retention/),
+[Loki datasource](https://grafana.com/docs/grafana/latest/datasources/loki/configure/),
+[Jaeger datasource](https://grafana.com/docs/grafana/latest/datasources/jaeger/configure/),
+and [the pinned Loki release](https://github.com/grafana/loki/releases/tag/v3.7.10).
diff --git a/docs/operations/persistent-jaeger.md b/docs/operations/persistent-jaeger.md
new file mode 100644
index 000000000..1fd2039e2
--- /dev/null
+++ b/docs/operations/persistent-jaeger.md
@@ -0,0 +1,62 @@
+# Persistent Jaeger reference
+
+The opt-in `docker-compose.telemetry.yml` profile replaces the original monitoring add-on's ephemeral all-in-one with Jaeger **2.23.0** and the native [jaeger.yml](../../infra/monitoring/jaeger.yml) configuration. Keep this profile separate from the default monitoring command. It is a small-install reference with one process and one dedicated Badger volume, not a highly available or horizontally scalable trace service.
+
+Jaeger's [Badger documentation](https://www.jaegertracing.io/docs/2.23/storage/badger/) restricts embedded storage to a single node. Do not mount this writable database into multiple Jaeger instances or share it over a network filesystem. The collector and query extension in this process use the same `incident_traces` backend. Larger deployments should use an operator-owned supported distributed backend; Jaeger documents Cassandra, Elasticsearch and OpenSearch, and recommends OpenSearch for large production deployments. See its [storage backend contract](https://www.jaegertracing.io/docs/2.23/storage/).
+
+## Immutable artifacts and process contract
+
+| Artifact | Pin |
+|---|---|
+| Container index | `cr.jaegertracing.io/jaegertracing/jaeger:2.23.0@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e` |
+| Upstream source | `v2.23.0`, commit `d723f91447f29a345c288f37eb8d1ce7807bc0be` |
+| Linux amd64 archive SHA256 | `4b7bd152ed31d2205e4e73b873d289c61cd3fabaecc86443070143448d40b753` |
+| Windows amd64 ZIP SHA256 | `56eccf9d72df52b65fc1bcbe0cb3c9cd566681de99274f1e8ecf07a7f9bf9f4c` |
+
+Both binary archives come from the official [2.23.0 release](https://github.com/jaegertracing/jaeger/releases/tag/v2.23.0), published November 5, 2026. The multi-platform image index was resolved from the official registry; its Linux amd64 manifest is `sha256:1d157a0fa25fb0e1588427522031bce7aad80152800df62772511b8b4916140e`, and arm64 is `sha256:c8c9a90a7cd02710a9ba7406ebab7126017da76a7b77724b2725184eab418455`.
+
+The release image's [Dockerfile](https://github.com/jaegertracing/jaeger/blob/v2.23.0/cmd/jaeger/Dockerfile) specifies UID/GID `10001:10001` and executable `/cmd/jaeger/jaeger-linux`. The command is `--config=/etc/jaeger/config.yaml`. The dedicated volume mounted at `/var/lib/jaeger` must already be writable by that user. The profile's narrowly scoped volume-initialization service handles this; the Jaeger process itself stays non-root with a read-only root filesystem.
+
+| Surface | Reference behavior |
+|---|---|
+| OTLP/HTTP | Private `4318`, traces only; request bodies limited to 4 MiB. The upstream Collector exports to `http://jaeger:4318/v1/traces`. |
+| Query/UI | Private `16686`; Grafana datasource UID remains `jaeger`, URL `http://jaeger:16686`. |
+| Query gRPC | Loopback-only `127.0.0.1:16685`; not needed by the supplied Grafana path. |
+| Health | Private `13133/status`; the old all-in-one `14269` health endpoint and `wget` check do not apply to the new distroless release. |
+| Internal metrics | Private `8888`; inspect storage and receiver/exporter failures along with Collector queue/drop telemetry. |
+
+No AI/MCP sidecar, remote sampling, Zipkin receiver, debug exporter, pprof or zpages is enabled. These endpoints have no built-in public authentication in this reference; keep them on the dedicated internal network. Do not publish the storage ports directly to clients. Native UI access for an authorized operator needs an approved authenticated gateway or temporary loopback tunnel; it is not published on the host by the opt-in profile.
+
+## Acknowledgements, retention and resource limits
+
+Badger is explicitly non-ephemeral. Its `consistency: true` enables synchronous disk writes, with separate `keys` and `values` directories under the dedicated volume. The Jaeger pipeline has no batch processor or exporter queue; the upstream Collector owns batching, durable buffering and retries. The storage exporter has its own queue and retry disabled, so a final-hop acknowledgement follows its storage call instead of a second volatile enqueue. A returned storage error can therefore reach the upstream collector for its bounded retry policy. This does not guarantee exactly-once end-to-end delivery.
+
+Span keys have a finite **72-hour TTL**. Expired spans become unreadable; physical file reclamation depends on Badger maintenance/compaction. TTL is not a disk quota or a deletion guarantee for backups and snapshots. Use a dedicated capacity-limited filesystem or volume quota, monitor free bytes/inodes and write rejection, and budget temporary compaction/backup space. Do not delete database files underneath the running process to make room.
+
+The Compose process ceiling is 512 MiB, with `GOMEMLIMIT=384MiB` and a memory limiter configured for 384 MiB hard/96 MiB spike headroom. The limiter is a pressure control, not a substitute for the container memory ceiling or workload sizing. A one-span Windows native baseline used approximately 43.7 MB RSS. Two tiny retained traces yielded about 2.28 GB of logical database file lengths because Badger preallocates files; that is not a measurement of physical allocation. Provision several GiB of dedicated storage headroom even for a small test, then measure representative ingestion, compaction and restart workloads before choosing production capacity.
+
+Align the Collector's bounded batches and attribute/event limits with the 4 MiB final receiver limit. A request rejected as too large is not repaired by retrying the same body. Collector queue capacity, storage pressure, discarded data and retry exhaustion need explicit operational ownership.
+
+For maintenance, stop the single writer before a filesystem-consistent backup, retain its matching configuration/version, and rehearse restore on an isolated volume. Replication, failover, online backup, disaster recovery, storage access controls and compliance retention are operator responsibilities. A BYO distributed store must verify write/read credentials, TLS, index lifecycle/retention, backup/restore and actual trace readback; selecting a supported backend alone does not prove those controls.
+
+## Grafana compatibility boundary
+
+Jaeger 2.23 serves native service discovery and search through `/api/v3/services` and `/api/v3/trace-summaries`. It retains direct trace-ID readback. Grafana's pinned Jaeger **13.0.8** plugin uses the v3 gateway for health, service/operation discovery and trace-ID queries when `jaegerEnableGrpcEndpoint` is enabled. Despite that flag's name, these calls use HTTP on `16686`, not the gRPC listener.
+
+That plugin still sends its Search query to the removed legacy `/api/traces` endpoint. Full Grafana Jaeger Search is therefore unsupported in this reference. Use direct trace-ID/log links in Grafana and the private native Jaeger UI for discovery/search. The [pinned plugin query implementation](https://github.com/grafana/grafana-jaeger-datasource/blob/v13.0.8/pkg/jaeger/querydata.go) makes that distinction explicit. Do not describe a healthy datasource or working trace-ID lookup as proof that every search mode works.
+
+## Executable verification
+
+After independently verifying the release archive checksum, run:
+
+```sh
+JAEGER_TEST_BINARY=/absolute/path/jaeger-2.23.0-linux-amd64/jaeger \
+ python -m unittest discover -s scripts -p test_jaeger_persistence.py
+
+python scripts/ops/verify_jaeger_persistence.py \
+ --jaeger-binary /absolute/path/jaeger-2.23.0-linux-amd64/jaeger
+```
+
+The seven tests include native schema validation and rejection of an unknown storage key. The real-binary proof derives a private loopback configuration from the reference, writes a synthetic trace, forcibly kills the process after acknowledgement, restarts against the same files, and verifies trace-ID retrieval, native service discovery/search and continued ingestion. A separate disposable three-second TTL store proves read expiry. It reports the known legacy Grafana Search limitation rather than treating it as a successful feature. No application, homelab service or production trace is touched.
+
+The local Windows release proof passed all seven cases. The joint Loki/Grafana proof can reuse `running_jaeger` from the same helper to compare an actual Grafana trace-ID result with the correlated synthetic Loki log. Container admission, Linux volume ownership, filesystem quotas, restart of the complete Compose profile, representative throughput, retention reclamation and site-specific backup/restore still need deployment evidence. Native binary tests do not substitute for those checks.
diff --git a/docs/operations/telemetry-collector.md b/docs/operations/telemetry-collector.md
new file mode 100644
index 000000000..c4118c789
--- /dev/null
+++ b/docs/operations/telemetry-collector.md
@@ -0,0 +1,163 @@
+# Private telemetry collector
+
+The optional reference collector accepts the installation's approved
+application logs and sanitized traces over private OTLP/HTTP. It forwards
+logs to `http://loki:3100/otlp/v1/logs` and traces to
+`http://jaeger:4318/v1/traces`. Prometheus continues to pull application and
+collector metrics directly; the collector has no metrics ingestion pipeline.
+
+[`config.yml`](../../infra/monitoring/otel-collector/config.yml) is validated
+against the official Collector Contrib 0.166.0 distribution. The separate
+[`image-lock.json`](../../infra/monitoring/otel-collector/image-lock.json)
+records its immutable image index, non-root identity and release archive
+checksums. The optional `--with-telemetry` bundle includes this image.
+
+## Transport and process contract
+
+Mount the configuration at `/etc/otelcol-contrib/config.yml` and pass
+`--config=/etc/otelcol-contrib/config.yml` to `/otelcol-contrib`. Run as
+10001:10001, drop capabilities, disable privilege escalation and make the
+root filesystem read-only. Initialize only the dedicated persistent volume
+for that identity; do not grant host-wide ownership or mount a Docker socket.
+The writable directories are `/var/lib/otelcol/storage` and
+`/var/lib/otelcol/compaction`, owned by that identity. Keep both on the same
+persistent volume and permit no second collector process to open its files.
+
+Port 4318 accepts OTLP/HTTP only. Ports 13133 (process health) and 8888
+(Prometheus self-metrics) are operational APIs. None should have a host port,
+public ingress or CORS origin. The Compose trust boundary is dedicated
+internal networks: approved application services to the collector, then the
+collector to its stores, with separately selected monitoring access. Service
+identity filters constrain data; they do not authenticate a hostile client.
+Do not attach unrelated containers or tenants to these networks.
+
+HTTP here is confined to that single trusted installation. Before crossing
+hosts, clusters or another trust boundary, replace ingress and exporter
+transports with authenticated TLS/mTLS, verify the destination CA/name and
+mount certificates/keys from the site's secret manager. Configure the
+corresponding SDK OTLP certificate/client-identity settings; do not turn off
+certificate verification or publish this reference HTTP receiver. Test the
+site configuration with the pinned binary and a disposable authenticated
+destination before using it. Public or multi-tenant OTLP ingestion requires
+a different reviewed authorization/tenant-isolation contract.
+
+## Data allowed into durable storage
+
+Both pipelines require `service.namespace=testlookup` and
+`service.name=testlookup`. The reference log roles are `api`, `worker`,
+`worker-children`, `beat` and `mcp`; an unsupported service/role is filtered.
+Custom service names need an explicit reviewed site filter change.
+
+Logs require the SDK's native event name to be one of `http_request`,
+`http_unhandled_error`, `analytics_unhandled_error`, `celery_task_execution`
+or `mcp_request`. The collector discards the incoming body and rebuilds JSON
+from that approved event name, severity, service, native trace/span IDs,
+64-character lower-case SHA-256 request/task identifiers, HTTP status
+100–599, duration 0–600000 milliseconds and a closed task-state vocabulary.
+Unknown attributes and free text never enter its export queue. Hashes are
+correlation pseudonyms, not anonymized data: restrict access and retention.
+
+The application remains the complete trace privacy boundary, including span
+names, links, scopes, resources and credentials in custom text. The pinned
+SDK export-boundary regression serializes sensitive fake link/tracestate
+values and verifies their removal while preserving causal identifiers. The
+collector additionally retains a small operational attribute set, removes
+status text and free event text, clears top-level tracestate and removes
+unapproved resource/scope attributes before queueing. Already-sanitized span
+links remain intact. This is not a general scrubber for arbitrary third-party
+spans; do not bypass the application's exporter wrapper.
+
+Only the approved event projection is ingested. Ordinary stdout logs remain
+available through the platform's existing logging facilities. There is no
+filelog receiver, host-log discovery, audit-history ingestion or duplicate
+stdout collection in this reference configuration. The SDK event projection
+does not imply full API/worker/beat/MCP trace coverage.
+
+## Bounds, durability and loss
+
+Each receiver request is limited to 1 MiB. The memory limiter starts refusing
+work at a 320 MiB soft threshold with a 384 MiB hard limit and a one-second
+check interval; begin with a 512 MiB container limit and measure the selected
+workload before sizing production. It cannot prevent every allocation spike.
+
+Each exporter persists at most 32 MiB of serialized queued telemetry and has
+two consumers. Batching happens inside the persistent exporter queue, rather
+than in an acknowledged in-memory batch processor: 8 KiB minimum, 64 KiB
+maximum and one-second flush interval. A single indivisible record can exceed
+the batch target; the receiver limit and destination request limit must also
+fit. Rejection is immediate when a queue is full. Export attempts have a
+five-second timeout and retries back off from one to ten seconds, with ten
+minutes allowed per retry sequence. Queue waiting time is additional; this
+is not a ten-minute event retention TTL. Restart may begin a new retry
+sequence, so repeated restarts are not a retention mechanism.
+
+File storage uses fsync and caps **each** bbolt database at 64 MiB. Two
+exporters, their indexes and compaction need additional disk space: reserve
+and enforce an installation-level filesystem/volume budget, initially
+512 MiB, and alert before it fills. Compaction runs at startup and on rebound.
+The database cap is distinct from a volume quota; neither removes unrelated
+files or orphaned databases after changing component IDs. Keep exporter IDs
+and spool paths stable across replacement. Review stored-state migration
+before changing versions; do not delete an active queue to repair a full disk.
+Use host/storage encryption and restrict volume/backups as telemetry data.
+
+Persistent queues survive an abrupt collector restart when their volume
+survives. Delivery is at least once and duplicates remain possible around
+acknowledgement. Disk corruption/loss, full storage, permanent destination
+errors, queue overflow and exhausted retries can still lose telemetry.
+Application SDK buffers are finite and asynchronous; collector health must
+not be a prerequisite for application startup or request processing. Data
+not yet accepted by the collector can be lost during an outage. This local
+queue is not an audit ledger, backup, replicated broker or HA guarantee.
+
+## Observe and verify
+
+The pinned binary exposes these Prometheus series without a `_total` suffix:
+
+| Question | Series |
+|---|---|
+| Queued serialized bytes / capacity | `otelcol_exporter_queue_size`, `otelcol_exporter_queue_capacity` |
+| Queue/storage refused input | `otelcol_exporter_enqueue_failed_spans`, `otelcol_exporter_enqueue_failed_log_records` |
+| Terminal retry/export loss | `otelcol_exporter_send_failed_spans`, `otelcol_exporter_send_failed_log_records` |
+| Accepted/refused/failed ingress | `otelcol_receiver_accepted_*`, `otelcol_receiver_refused_*`, `otelcol_receiver_failed_*` for `spans` / `log_records` |
+| Contract filtering | `otelcol_processor_filter_spans_filtered`, `otelcol_processor_filter_logs_filtered` |
+| Process resident memory bytes | `otelcol_process_memory_rss` |
+
+Some error series are created only after the relevant event. Terminal
+`send_failed` counts do not count every temporary 503 while a batch is still
+retrying. Watch queue utilization and refusals during an outage and terminal
+loss after retry exhaustion. Health port 13133 proves process readiness; it
+does not prove export success, freshness, free disk or an empty queue.
+
+Set `OTELCOL_TEST_BINARY` to the checksum-verified official executable and run
+`python -m pytest scripts/monitoring/tests/test_otel_collector.py -q`.
+The native tests validate the actual config, send OTLP through real filtering
+and persistence, force a 4 KiB test queue to overflow against a disposable
+503 sink, check byte-cap/error metrics and pre-queue canary removal, kill the
+process without shutdown, then verify replay of every accepted synthetic
+trace/log to the recovered sink. A separate short retry sequence verifies
+terminal-loss metrics. The tests use loopback, temporary data and fake
+payloads only. They require PyYAML, pytest and the application's OTLP protobuf
+package. Without the binary the runtime tests are skipped; that is not
+production verification.
+
+Also set `LOKI_TEST_BINARY` and `JAEGER_TEST_BINARY` to their verified releases
+to enable joint store readback. That test sends matching native trace/log IDs
+through the real collector, retrieves the trace from Jaeger and the projected
+log from Loki, repeats after collector replacement and checks Loki's series
+API for its three allowed indexed resource labels. Query-result stream labels
+alone are not index evidence: LogQL can promote filtered structured metadata
+into those returned labels. This test covers disposable native processes,
+not rendered container network/volume permissions or full application traffic.
+
+Production acceptance still requires the rendered container network/UID/
+volume permissions, encrypted cross-boundary settings where applicable,
+application availability under telemetry outage, representative throughput
+and memory/disk budgets, store readback, restart and retention evidence for
+the selected deployment profile.
+
+Configuration and limits follow the official
+[OTLP receiver](https://github.com/open-telemetry/opentelemetry-collector/tree/v0.166.0/receiver/otlpreceiver),
+[exporter queue/retry helper](https://github.com/open-telemetry/opentelemetry-collector/tree/v0.166.0/exporter/exporterhelper),
+[file storage extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/v0.166.0/extension/storage/filestorage)
+and [Collector resiliency guidance](https://opentelemetry.io/docs/collector/resiliency/).
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index 4e29589fe..372105f97 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -286,6 +286,8 @@ Source declarations only; no `.env` or running secrets are read. Compose/Helm/Ku
| `OTEL_ENABLED` | `bool` | `True` |
| `OTEL_SERVICE_NAME` | `str` | `'testlookup'` |
| `OTEL_EXPORTER_OTLP_ENDPOINT` | `Optional[str]` | `None` |
+| `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` | `str` | `''` |
+| `OTEL_LOGS_ROLE` | `Literal['api', 'worker', 'worker-children', 'beat']` | `'api'` |
| `METRICS_ENABLED` | `bool` | `True` |
| `METRICS_TOKEN` | `str` | `''` |
| `METRICS_TOKEN_FILE` | `str` | `''` |
diff --git a/e2e-runner/requirements-lock.txt b/e2e-runner/requirements-lock.txt
index ef46e717b..342e75e22 100644
--- a/e2e-runner/requirements-lock.txt
+++ b/e2e-runner/requirements-lock.txt
@@ -29,6 +29,7 @@ certifi==2026.10.23 \
# via
# httpcore
# httpx
+ # requests
cffi==2.1.1 ; platform_python_implementation != 'PyPy' \
--hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \
--hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \
@@ -131,7 +132,181 @@ cffi==2.1.1 ; platform_python_implementation != 'PyPy' \
--hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \
--hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264
# via cryptography
-click==8.5.1 ; sys_platform != 'emscripten' \
+charset-normalizer==3.5.3 \
+ --hash=sha256:00edb7682962c596f774bfa126e6b6f885b7af2319f448d327591c284a482de8 \
+ --hash=sha256:01b35bec964b92b89bdf94adf931d2e80a15f1c7b93bf850b4430cca23f7a2a2 \
+ --hash=sha256:020cabbb90926b2d8b022a5e057ab349f28844b61f34117323fc08c2971915e3 \
+ --hash=sha256:02b1abf64742b2d0782172cd2542616e462c201c829c23aff833390babe2967f \
+ --hash=sha256:06d07272f70d9880fba32d4876e966ae4dc9961134bc989066a0901509dfd8cf \
+ --hash=sha256:0810592b80dc5a97f8103443460264b588f31c6baa8a20abae7c683435d8117a \
+ --hash=sha256:085a5d1f49eaf96596d79494fcab18d9a32db6e345da15d6debfc90110b20679 \
+ --hash=sha256:09833ba78c91f0d1fd06387c69dae9f079428b77ea05eaaf1553eecead31fb68 \
+ --hash=sha256:0b3fc6f7dd9db4a7782e65dc98eb80b2a91a854cf54a03dd93649be2f7ca638d \
+ --hash=sha256:0c0fe07631dce6dae788a59c20ed927adc6feeb2d9ed440747eb367d89822a45 \
+ --hash=sha256:0ca25f1b1167e9fb94d93d3708df0b631de241bf8440947b0cb9f8c4cb66fed0 \
+ --hash=sha256:0ca2da4a505fae7ef95922f8d48235b2e49ff8f10f4edcc0481e5f6526ba3841 \
+ --hash=sha256:0cf4cb8d75090a8da3bd30c0963b2c6c6114e791c6fc060c3cef8971497b1f04 \
+ --hash=sha256:106b9d0438e2ff0a0e8ebd869273fcb3640af28323bba8651c714c57efb38e51 \
+ --hash=sha256:11ad35a0b856ad8bbd0c9e900c069461a4661694714aa17b6e6e2e8621e1c373 \
+ --hash=sha256:139aeb8ca63946dc79364c37f2c9cfe5c1b7f3882f2c47484d0e54bf14b921b0 \
+ --hash=sha256:1714ff1ba001da5241a585fbd17a7742a61ad34efb4be8404aca5679f51e53ea \
+ --hash=sha256:183aee7e84789391e547ec1609f8269332b9b123d21e97f7ef79eaa474c47e08 \
+ --hash=sha256:1a34385837db59d5de814c9f1e0f4157b571f9ce0eabdaeace410aa93bf5df62 \
+ --hash=sha256:1b2704f4651539eab50ba104a975b96c3cd5246011aa0755d2dd71ac12546644 \
+ --hash=sha256:2246873913d7db43ed5a3d98ace398b989b2ae20b77c8d761a7bef5fdb9bed42 \
+ --hash=sha256:249bf0b6f43985c33c83adbbab0ca71246ec24c82d960fa00c4ddb2cfed25db9 \
+ --hash=sha256:256b434b2860ef9da1cb6a5fd4ebb5d600936668e50e2035858948b96b068ecd \
+ --hash=sha256:26c6ad87bb79628954b52f8f7b9e18ab5cd9667546712ded9689fb7677e630d6 \
+ --hash=sha256:277b72183b96879887f0c3aa0bdac1fee08a6c7e67bad53145c4fd416d99dfd3 \
+ --hash=sha256:28ba8e6361e0f319641707484994096ceb77e05c29eaad2919756218c0c89001 \
+ --hash=sha256:28d954a437bfa5fcdfe7ad8902cf4347a8486f34a86c5f39003bc1288eb67d72 \
+ --hash=sha256:2978c799237eb66619d8951d2ab7efd317414cb6682160e05614ce1c8b5c905f \
+ --hash=sha256:29ac44f5878142128ffe4fa7e041ddc4cc5fafe43983245b9a141908c40b515d \
+ --hash=sha256:2a6f937e0b70133d1f826d0a253331b6fe1a4c874808cc12e16f2fb8177042f4 \
+ --hash=sha256:2b7797a5b0cb197f118fd13b41c14c5a3c38dd625a87c1da58a3066cf53254fd \
+ --hash=sha256:2c4e0050b732ee3dca3676a5f5cf7fbd0c131761c194f1bb1d24c055fad071cf \
+ --hash=sha256:2e7fbd98443f28a5ed8004f0b058edcc4720a3d344adf007c0b7f1adbff2f59f \
+ --hash=sha256:2f2d973d3c79fbd1066d63d1bafb2ade66934c0840ed149f6fac13c3fdf80793 \
+ --hash=sha256:323d5cf6df3ea724afcc3bfb07c73be06d2e8200a8b6b37979a300ae1e7836d0 \
+ --hash=sha256:326a7a0e3715c3ac24c21e7a3b831d6799cc795bff260aa49c23b69025852f99 \
+ --hash=sha256:34054580168b04e90e6c7c0f6c80173fa2d4f72c4db91c9095598454f96d6389 \
+ --hash=sha256:366f5efe95a6149ecbcebf779c2594a6a4ff6fc116402826c72ed0eccd6aabe9 \
+ --hash=sha256:390ef7c7e018c0abb8c0ec2d28ee137567ff50c3706facf6d115cac832ac993b \
+ --hash=sha256:39229c222445415db07a0be4dff8ad1addc3126644d7aa72d73f1575b637d69e \
+ --hash=sha256:396fdf2d4367674531a7c8d54ecabbc8e5131e3a1a06270285eb99f3140143df \
+ --hash=sha256:39e019884c8f857393df954d35f42bf99c5ab85af226fe74d1410188c6fec31f \
+ --hash=sha256:3ce4e4587e451ebc7d9899a7a1f539ea30a3c712d7bc8e0d256923c697fd5dcc \
+ --hash=sha256:3e8da696ef1935a019c10ec16555a062183ddf6d5901e296edeca4b2a8f84e1d \
+ --hash=sha256:40b2ba91f0851aa864994b3c7022e4d96d09026717e6a72e44410d6fb3a74a13 \
+ --hash=sha256:45aa4ccf5a6caba138dd0f8bf36fa3e26654585d534881b62ce5e4fea2487772 \
+ --hash=sha256:4831fb33e98e92140fa17d4d673a9f49f9c0ddd056115b722858793e4b86b0c5 \
+ --hash=sha256:48f7c7f537246bb3af2b3139f44716a30b21e78c2fd1cff0f3e392fbd55d8044 \
+ --hash=sha256:499e4bbeb1e79b14756311a1d12cb88112f244423e152d80981d9bcaff3279fa \
+ --hash=sha256:4a991dbd7aec868fe10802b02bddbf898173a47ba236f2d6afb4ab1f98243534 \
+ --hash=sha256:4ff5e27478681ef1b13b036baaf9beaf9b4c6990e903c752ad3b8764692c6d6c \
+ --hash=sha256:56405211fa124c393eea14b3aeacf5b90de72b1f69b0a60c9bc40b01dfe71a42 \
+ --hash=sha256:581d6e7df9b58d34147e21efde42a480b5087fe54f31e42550c26321566ba1e4 \
+ --hash=sha256:5970d148182b6b7c22b8290a81f02fb521c4e7aee6747743b3e645db58d5001a \
+ --hash=sha256:5f86753952f7de3abc7ce871f8239ce4e0d32a91c84d22f3a667e669907c3897 \
+ --hash=sha256:6118055f4ad0d94e016eadbb86caed9caf2c9033631ed70964ba631c1336984f \
+ --hash=sha256:61e32fdbf56f4cd25a1efa451c8b5fe886fc5e00143ccaacafdf21f301fad059 \
+ --hash=sha256:61f3258f700412c68fde407e7c749ed6930e795ea8f5ead9a40afddefbec12c4 \
+ --hash=sha256:6423accb6ecd1456bf824bbac98ba919398523a69ee5f1680dd1da88769de866 \
+ --hash=sha256:643724071b01cc0369026e259850791212cc187c6031d0e930abcd253f128e0c \
+ --hash=sha256:656b9744bac4493561d28b56d7d646afd7a8471254ef7004d849aa8368020037 \
+ --hash=sha256:6651fecdac146ecfa52700e02a5fa3b3677bddf5fced4983b43e904244de3f6a \
+ --hash=sha256:67bb767a8de7a2b1164c74fdbe5cdc32b9c15d7142efd9a6dc77ff63da94e846 \
+ --hash=sha256:6b702d36c565f6c650f4b479488f475b2982132ab8d0840d42b1442462c21056 \
+ --hash=sha256:6bfbbb9414dd0f5b81c259deb7e50b4b44e65e05879eee482351bdabed49d7f4 \
+ --hash=sha256:6c80b4e83e2fbddd25fe27804cdfc45ef71bb387522caa575af42118d72dc970 \
+ --hash=sha256:6c8abe7d59bbc891e5080b8b142c36db93154f840c4baf7c83ad6273a1a15397 \
+ --hash=sha256:6dde7edd9ba5005389bc7c0ab461411f281dbacb2b06e52bd23592eba42bb503 \
+ --hash=sha256:6eea31136fd924ecbb4e7c4f3df4b18230409629a22b3896f38a6754d5857794 \
+ --hash=sha256:70f65dd0c2ed79ea2d9776096e9c7d25e398c2c03eb31877753598d201d91784 \
+ --hash=sha256:73b4ddf1230df56c9e7017a16e3f5171b6ef0e4ff554a418a370d7ac7245bd84 \
+ --hash=sha256:747e83d415939612284afdc99f15295382639c0d3fc69a73aeb84b380d1f4af3 \
+ --hash=sha256:7a7e5bb8974842ad747d4a2b9fb928f84c3cdbe2c2fd7e405197fc1a1badaeaa \
+ --hash=sha256:7c313b46730b4a68bb31450973467313b2c496fefa42ae316b86c186cba74613 \
+ --hash=sha256:7fd816f466883dcaac196ac77271d0292eee4a81f4db1191b95d15328f335937 \
+ --hash=sha256:7fdd11094a0b07bce306b359fa7311c71d93466d967b3b345f2e9f03d8b2c959 \
+ --hash=sha256:806e72ebaeef54d7faa03414be9e8409eb3dcae49fba089d62063a60c0b5a4e5 \
+ --hash=sha256:81132eaffa984f0a399233df4cd383caad18e8cadc6c24c568cf9324732a9768 \
+ --hash=sha256:8231365b03b702b516aad35c9515694177ac31c9dc6240326f07308a4c45c708 \
+ --hash=sha256:826d82356907350f345cf0aa744d43a69ac7948bd60f460f997cde86928beadf \
+ --hash=sha256:84356c7b7ddf090e3e4692cb99fc820e6189b5f6662ca7e8589f41095cc8efca \
+ --hash=sha256:87d5a237d6531c654e7b9b319be9ba7e368665c466e02a03cfd4d3d77730782e \
+ --hash=sha256:87f7d6c595465a25d33fa3d5215a571a98c4cad00ead3ad18ebfb62adb3d3e6e \
+ --hash=sha256:885f202d6e4e2298bea9802ffc6d8c7dc45394199a8dd9e1492f05fe32dce311 \
+ --hash=sha256:8b969f0309de905101bc3d2471c112e9ccbba711a7590b12d51f372b4163688a \
+ --hash=sha256:8baddc6349faf49edae4d1322f12b681b9e86acacd01874457c997437ef4ccaa \
+ --hash=sha256:8c4dfcd3269f13dff7f29f9c332d54a4a21f17be818b49e769e111befd4d39e6 \
+ --hash=sha256:90b1ff6cb9c7a204a3b79b1b0ed6ac8a1d8fed3b6dc69e50ae5de0f358ee81d4 \
+ --hash=sha256:92bf85ecec3ad6374ae50d870bd1deb34de12bc1158b5fd09036d4c435c6f58c \
+ --hash=sha256:92ddc32b6a1508ea145f4f7995e00666db454b8fd3e2cae6c2ecbde4f4d44616 \
+ --hash=sha256:948fb3649416a70bcdbb267d79c7048e8aa16e989ab9da09f416e67cdd3d6b8c \
+ --hash=sha256:94b595e64bc2927f679774de50df340b7828dc1c07c99149ba7c2d0828dd8bf3 \
+ --hash=sha256:94c9d5d91c16554f6397b823d9e47181ba100d830ab16b5d720adc229e17b2e2 \
+ --hash=sha256:9510da88bdebc903be7844f31523ac8d7b3f63e167db54b6045104a2354afa6a \
+ --hash=sha256:96387278c3b17bc1170f80693398d0babac7b41df128ced8e27588a7155d95b2 \
+ --hash=sha256:96e268b0cbda016ac519513294fcd17032264085b600abaac58b93049477e132 \
+ --hash=sha256:9902e80096a94cf70fb72d12ae40e3b187b40e96fa722873d4d62afcd0333c46 \
+ --hash=sha256:9a6b95b1737f9b5942c35676c52db0c302d60fa806efde3fc2d9f54247ecf4be \
+ --hash=sha256:9b887e8a7103ae2171dccbab00a4bb2bf1560f5c10c28227e5513bc90a608cad \
+ --hash=sha256:9c1bd8321a840729a6b2620774cf4000fafe66c54cac9064972a10c4f607794b \
+ --hash=sha256:9eba4613d45b49196af04a5cbadfc5e9379ba94aac85184b72cb1107ad31af0d \
+ --hash=sha256:a094178c51530c9ebd1775e72d160af0eac4be244fb06ff1b6f182128c71903c \
+ --hash=sha256:a09ca76391f6e17b12d55c1068b4b5f8f6c9b44b432d936075372fa12782292d \
+ --hash=sha256:a250888753faa289e2997962fbb17c4960cbdb58575533ca6fceee68c224bdff \
+ --hash=sha256:a312fedd182357f2c22f066d17dcd7413b6a205ee3d063d36950e94e3019d3de \
+ --hash=sha256:a36bba41dc7fd263417688c4daf95a1091f93e1f6957c0f71ad7798907c5a10c \
+ --hash=sha256:a3f4044dd5d2f7b958be6b9903cb432e6a0fd944d673707ca5cab68137d0592c \
+ --hash=sha256:a43831574e14423103d69fb1357e76e4f2347041c98e8357ab88ef21812e80d9 \
+ --hash=sha256:a491d4afb361aba32d55d7df7ccde766a3aa9a34c002d2c32c2743bf6e77c13c \
+ --hash=sha256:a5a7e0326566759f9a7bc44f4b9a179cc40a297e09e759b0bc7c848c06347527 \
+ --hash=sha256:a6eba94fc00d899f8d268712772c8dcafc40215aa9b51701a397afc9426e012b \
+ --hash=sha256:a8f92cc9080bff47555c79b88e7fb8655438ce3bcf29c5f01ed2ed5efdf174a4 \
+ --hash=sha256:aa2476abf8669be493689634bdb79f468a6fe57b005a5126db7e9f61d1954fe2 \
+ --hash=sha256:aa8be1f24fbc03a07cfe002b70ba0716effc6b3011fd9e5560ca399d3d0605ad \
+ --hash=sha256:aa9390d89822dd06f9920ae3038819cb121643a72f4753b2eee1a79b2f1215f8 \
+ --hash=sha256:acaa0e100f39287dc5d13de96e33ba0786f1cdfb5b4ca28918913ab0eec3af72 \
+ --hash=sha256:ad1becd776f5a41a4d91cb9ee51778f4fd687ef15e4919779e00a33c6cff6948 \
+ --hash=sha256:af217012cfdaf6ea5dc0c538aac29b7bd030eb865056cc60f1d973b982b7917b \
+ --hash=sha256:b013417037c931583578639cab2523d5a2efc35a584c192d07f4c909b133f6b0 \
+ --hash=sha256:b0aa6b81bc632af7cac7b270c933298cb5ee858506dcf344e0da006667e0c351 \
+ --hash=sha256:b30e5496e453ac971bb17f5e096b84fbaae16d09e2613f6148ff528c08a54a0c \
+ --hash=sha256:b66a0e045cf859d7418f26a554509b65f21ebb6d90a95152460781939e8264f4 \
+ --hash=sha256:b6dad86d938104f9d43404029e5fc8392f82762d171933be4f192a6008bffa53 \
+ --hash=sha256:b6ea5bf7e3c39f6e56957d82274ac7cfab469590085883fdbc86e754cde76b11 \
+ --hash=sha256:b8fc4fe56992b089d6177021fe6db641321bb2bc2fc7a1abf815c29a80ca2137 \
+ --hash=sha256:ba26e4d073a4f7f2594676f2ff20ab80a7f03332b81c3f9964e9e53bf2305329 \
+ --hash=sha256:bed05639ae1bc23df7996a4fd13ea5064ddf60dc7dabd754f8badf060daec63f \
+ --hash=sha256:c08e06fc69750827d7ccebba63ebc97a85e479cd5c9dbdb80f5e08a77b774fdb \
+ --hash=sha256:c39a4fe28a16e8fa667c55c154f62c6c3cd9ca2491cca9f16330dd7360d05b76 \
+ --hash=sha256:c437ed8775d201d37206f37d233f547506e3aef60b9711584c65444c686b4905 \
+ --hash=sha256:c43d9737c3b85ccd16b1862b1e7aa5c4bf30a6033068403713c0a2bba5bda979 \
+ --hash=sha256:c9d1f467d121b33b06865c94ed5ed8388a9ef76f5e1acc1c8a854ac653493f5d \
+ --hash=sha256:caefc441edff6070a9f9749ca880a22731a1715d9e74b24304a546eec44bfc16 \
+ --hash=sha256:cb18428af7399e0a6f7e3b45f110d57a1a47cf07fd4b3ce50e2366d99a38959a \
+ --hash=sha256:cb4c25a9d3410262216b5c7447e51bfd2de0efae0a7640772dc6d2a8741590de \
+ --hash=sha256:cbd09b22b340f846671e79e8d832167fac60c1884be4c71fd667211486a3b58e \
+ --hash=sha256:cd5422fd4f8a7859846c9289e310dd95c0d1890c31819667942753e510f88f69 \
+ --hash=sha256:d12571adb9ceeb9ba0640db46433430062f5f1dec89e39713a2a5a8ce3016c37 \
+ --hash=sha256:d1b7a3fe4cf679eb3870b91b86b8ce12cacd5cf4d74bc114864a5cd65319ddac \
+ --hash=sha256:d313494077f849d8199f36166947785da1eeb36335fda15fde2e8f801ef271b6 \
+ --hash=sha256:d3c9d5284d64f4c1015d95b751577b260fd6d14e3f8edf21710f4436e7ac4c49 \
+ --hash=sha256:d4e7ecaa25f0dae672ac783c2e5aa9054a62e011749d64ff47b887af360a3e82 \
+ --hash=sha256:d57f1b6affc3581fbf0bc6d783cc60e7c9957adfd9c7b89f8a9f3573ad1cd49a \
+ --hash=sha256:d8f85e019c9f08ec134648a378ddd3f6f073c1e4b5ce9bdacd9a9e7b60749cd2 \
+ --hash=sha256:d93403a13c8f6f2d027185d90ab695e81d95e3ebd000f0078e201a1c3159d4d1 \
+ --hash=sha256:da606e3015dbd4b9a31c0468898a0c4c998846197ddfda78308821dc8c9e9be3 \
+ --hash=sha256:db2eedef732424346f98d0aba5c6ad688b648bc79847f4cc70dfca830130b1e6 \
+ --hash=sha256:dbdd407104ebf2360464ce02c7933c6ffac58bd5b64cdf6ef7dc0e787e782aaf \
+ --hash=sha256:ddea089587432e3df6771a4a405ef249cc9727f7becb1de3f00ab571b2432002 \
+ --hash=sha256:dfbde696fb427301ec40cd82b8eec0b528e44c6af8239f33ede2b2552d9a085a \
+ --hash=sha256:e1cdbde56f9fa6d426b78941c381e2ba160c1214809baa47e02c1d0d8881d598 \
+ --hash=sha256:e282983b8def5ada758fa1f18bf9060bb8ce6cdd73be32f62a2de59820d3286d \
+ --hash=sha256:e34f591669498a03cd70993b0a79b9f0ef40c4e6f8232466bac33c42f0c15742 \
+ --hash=sha256:e405cce4170de1fe520d9a92de9d7ececc23dfcf6888c62ab608a21be50838eb \
+ --hash=sha256:e4a0f2adf29a69dd8fe58e42bb191f3c87067b05fcc63279983e8c9ce5092abd \
+ --hash=sha256:e4f85c34f9be32ec5568a0668fb8bc029d3e729285fb8fccc38695e185379a9b \
+ --hash=sha256:e5e4785d8a0adeadfbdf75f4efc357911842674651cbafd7e97f69b11ec3cbc6 \
+ --hash=sha256:e86a27ab632d2e888c22b79263864eaff8b7dea9e87328a9bb0ea04eff24786f \
+ --hash=sha256:ea880ae1a692ae694c11bca7be74864614ff1a58bdfff4605f36d1956b4b1588 \
+ --hash=sha256:ee9de080e8d6221bbe4ba2667367b1cee0f47a53f60ffc5e431b698cd2f2b214 \
+ --hash=sha256:ef8b925f2b331a1f17d6fb32625e09fd571cf41844f578379f934dab0067cf0d \
+ --hash=sha256:f06e257ee0cc85a7e4ec44f171ae2595fd901c34212f3c9e7ab8fd8621401e99 \
+ --hash=sha256:f1214052966421a88ed526ba93e4463b39346862fa4721be5306434b33dae795 \
+ --hash=sha256:f160f03e15bd1e3c35db9bfc20c42ff83155d37f9b0c79806cb10051ca725f13 \
+ --hash=sha256:f1b357340e4cd29011683bd81226175611ad835fec22e5b7df83b96701571226 \
+ --hash=sha256:f39290a0c2e3f4196563189bb45e6ef5d5badf50864e1bfaafa9003f0595573f \
+ --hash=sha256:f5a5c311e5de6954c36230a37863b5ca58ce232589bd637ad2881c4056897b12 \
+ --hash=sha256:f7a841170fde40b0e1345884bee09ceca7db49a9291fa340089bec66a366c243 \
+ --hash=sha256:f7fb9a3275f1a1528e542a0f5a3d2c89fcaf68e797fc5c6530434cbd92a852c4 \
+ --hash=sha256:fc540d1618c5638fcf5aea97060cf011467918b010bf682a84ecc0c9474e6cd0 \
+ --hash=sha256:fcb17f1d40c38912a2cdb56ea47aadac3527cd0b06fe24f3a0c4896febbea063 \
+ --hash=sha256:fd0341b9dea133d187d7c5a2cd7e21ae6449a7b68ea8c2454f9cf77def11ec1b
+ # via requests
+click==8.5.1 \
--hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37 \
--hash=sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4
# via uvicorn
@@ -204,6 +379,10 @@ cryptography==50.0.2 \
# via
# testlookup-cli (../cli/pyproject.toml)
# pyjwt
+googleapis-common-protos==1.76.0 \
+ --hash=sha256:59e13344a9f3651aa201a03e2bee815a3bf43a4baf1f9ff8a9b62a840ce25fac \
+ --hash=sha256:71db0e44a1d4c2dd024ebad44ca67129cc1e2892e4861df466764749d5ef8642
+ # via opentelemetry-exporter-otlp-proto-http
h11==0.16.0 \
--hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \
--hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
@@ -240,6 +419,7 @@ idna==3.20 \
# anyio
# httpx
# httpx2
+ # requests
iniconfig==2.3.1 \
--hash=sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960 \
--hash=sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7
@@ -271,7 +451,45 @@ mdurl==0.1.2 \
opentelemetry-api==1.45.2 \
--hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34 \
--hash=sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4
- # via mcp
+ # via
+ # mcp
+ # opentelemetry-exporter-http-transport
+ # opentelemetry-exporter-otlp-proto-http
+ # opentelemetry-sdk
+ # opentelemetry-semantic-conventions
+opentelemetry-exporter-http-transport==0.66b2 \
+ --hash=sha256:66d6ed810a515432c8891da9a834464332fd70badeca45bdeeae81b4280c903b \
+ --hash=sha256:fd5f5b490c099acda1cd7b909d5e8981436bf18cc8c6098d302d114c271720e9
+ # via opentelemetry-exporter-otlp-proto-http
+opentelemetry-exporter-otlp-common==0.66b2 \
+ --hash=sha256:06f5a9b88638e310efa1f1d206cdf6b75393e112aba4e174a963416192bd1028 \
+ --hash=sha256:ace86efb75489f925f1ef809856ae5f0c7db534e4afdc624530222228b1236a5
+ # via opentelemetry-exporter-otlp-proto-http
+opentelemetry-exporter-otlp-proto-common==1.45.2 \
+ --hash=sha256:af483b24217028892f017096731b794b196b785025d2e6808874720fd0b05a80 \
+ --hash=sha256:f1f2806f3f28ce7938033823e50934fcd91595a39de38e69a28a51e19f40fc6d
+ # via opentelemetry-exporter-otlp-proto-http
+opentelemetry-exporter-otlp-proto-http==1.45.2 \
+ --hash=sha256:5984a3fb46bc4628e4e2b85d4a6e72637e03962aae6cf372791137768a4ad939 \
+ --hash=sha256:6e4d025138829d0ee57946930c2ccad6491ad4d92a958e9c7eea69278fe60cfc
+ # via -r ../mcp/requirements.txt
+opentelemetry-proto==1.45.2 \
+ --hash=sha256:03a7ca1b43f89fd5b965d5975902bb2515c0c86e2428b456836e9a6149c6235a \
+ --hash=sha256:bd8d23cf770605b0af9b7be2071d26a464fea289d35429abfd2a66226114ad64
+ # via
+ # opentelemetry-exporter-otlp-proto-common
+ # opentelemetry-exporter-otlp-proto-http
+opentelemetry-sdk==1.45.2 \
+ --hash=sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d \
+ --hash=sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6
+ # via
+ # -r ../mcp/requirements.txt
+ # opentelemetry-exporter-otlp-common
+ # opentelemetry-exporter-otlp-proto-http
+opentelemetry-semantic-conventions==0.66b2 \
+ --hash=sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8 \
+ --hash=sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976
+ # via opentelemetry-sdk
packaging==26.3 \
--hash=sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79 \
--hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c
@@ -284,6 +502,18 @@ pluggy==1.7.0 \
--hash=sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec \
--hash=sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8
# via pytest
+protobuf==7.36.2 \
+ --hash=sha256:497d0463ff3316681da6c0b9e8d06cb465d61abce00b613ab42226175644d1bb \
+ --hash=sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2 \
+ --hash=sha256:912c1221170e16c08d1f086762f563dd61ff83c18b5fa6652952dfaded66f728 \
+ --hash=sha256:a300819d441e078a5608c0d3c709796bb548136058fda017ae51d425b44fd353 \
+ --hash=sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e \
+ --hash=sha256:cbc70b17ee27e28894c7fee8bb04be1abead49e936bc70eb60052531eee2079e \
+ --hash=sha256:e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e \
+ --hash=sha256:f4fee11ec330d238b34a05c9b675f693c20415d1c5bd7d5320cc2f8a798eb9cf
+ # via
+ # googleapis-common-protos
+ # opentelemetry-proto
pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' \
--hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e \
--hash=sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6
@@ -577,6 +807,13 @@ referencing==0.37.0 \
# via
# jsonschema
# jsonschema-specifications
+requests==2.34.2 \
+ --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \
+ --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed
+ # via
+ # -r ../mcp/requirements.txt
+ # opentelemetry-exporter-http-transport
+ # opentelemetry-exporter-otlp-proto-http
rich==15.0.0 \
--hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb \
--hash=sha256:edd07a4824c6b40189fb7ac9bc4c52536e9780fbbfbddf6f1e2502c31b068c36
@@ -752,6 +989,9 @@ typing-extensions==4.16.0 \
# mcp
# mcp-types
# opentelemetry-api
+ # opentelemetry-exporter-otlp-proto-http
+ # opentelemetry-sdk
+ # opentelemetry-semantic-conventions
# pydantic
# pydantic-core
# pydantic-settings
@@ -765,7 +1005,13 @@ typing-inspection==0.4.5 \
# mcp
# pydantic
# pydantic-settings
-uvicorn==0.54.0 ; sys_platform != 'emscripten' \
+urllib3==2.8.0 \
+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
+ --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
+ # via requests
+uvicorn==0.54.0 \
--hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \
--hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620
- # via mcp
+ # via
+ # -r ../mcp/requirements.txt
+ # mcp
diff --git a/frontend/licenses/THIRD_PARTY_NOTICES.md b/frontend/licenses/THIRD_PARTY_NOTICES.md
index a447f8785..9b0932830 100644
--- a/frontend/licenses/THIRD_PARTY_NOTICES.md
+++ b/frontend/licenses/THIRD_PARTY_NOTICES.md
@@ -146,12 +146,12 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `numpy` | BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0 | backend |
| `openpyxl` | MIT | backend |
| `opentelemetry-api` | Apache-2.0 | backend |
-| `opentelemetry-exporter-otlp-proto-http` | Apache-2.0 | backend |
+| `opentelemetry-exporter-otlp-proto-http` | Apache-2.0 | backend, mcp |
| `opentelemetry-instrumentation-fastapi` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-httpx` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-redis` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-sqlalchemy` | Apache-2.0 | backend |
-| `opentelemetry-sdk` | Apache-2.0 | backend |
+| `opentelemetry-sdk` | Apache-2.0 | backend, mcp |
| `passlib` | BSD-3-Clause | backend |
| `platformdirs` | MIT | cli |
| `prometheus-client` | Apache-2.0 AND BSD-2-Clause | backend |
@@ -174,6 +174,7 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `pyyaml` | MIT | backend, cli, client |
| `redis` | MIT | backend |
| `reportlab` | BSD-3-Clause | backend |
+| `requests` | Apache-2.0 | backend, mcp |
| `rich` | MIT | cli |
| `ruff` | MIT | backend |
| `scikit-learn` | BSD-3-Clause | backend |
@@ -188,7 +189,7 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `typer` | MIT | cli |
| `types-python-dateutil` | Apache-2.0 | backend |
| `tzdata` | Apache-2.0 | backend |
-| `uvicorn` | BSD-3-Clause | backend |
+| `uvicorn` | BSD-3-Clause | backend, mcp |
## Container base images
@@ -234,6 +235,13 @@ They are listed for your own license review.
| `ollama/ollama:0.40.10` | MIT; the image also contains NVIDIA CUDA runtime libraries under the NVIDIA CUDA EULA | https://github.com/ollama/ollama |
| `chromadb/chroma:1.5.9` | Apache-2.0 | https://github.com/chroma-core/chroma |
| `mher/flower:2.0` | BSD-3-Clause | https://github.com/mher/flower |
+| `busybox:1.36@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662` | see upstream | |
+| `prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06` | see upstream | |
+| `grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf` | see upstream | |
+| `otel/opentelemetry-collector-contrib:0.166.0@sha256:3e18fe04181de50bdd72e23ad4a4d6214b54351e63d496f1c58127cc4541ad7f` | see upstream | |
+| `cr.jaegertracing.io/jaegertracing/jaeger:2.23.0@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e` | see upstream | |
+| `grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7` | see upstream | |
+| `docker.io/prom/alertmanager:v0.35.1@sha256:4e3d029e69c7f61dd53a2b31a3dc427a2b81736cffca185c0854075e07969e36` | see upstream | |
**MongoDB** is licensed under the Server Side Public License (SSPL-1.0), which
is not an OSI-approved license. TestLookup only connects to it with the
diff --git a/infra/monitoring/grafana/telemetry-datasources.yml b/infra/monitoring/grafana/telemetry-datasources.yml
new file mode 100644
index 000000000..d3032cd1e
--- /dev/null
+++ b/infra/monitoring/grafana/telemetry-datasources.yml
@@ -0,0 +1,45 @@
+# Opt-in replacement for provisioning/datasources/prometheus.yml. Mount over
+# that exact file; adding a second Jaeger UID definition is invalid provisioning.
+apiVersion: 1
+
+datasources:
+ - name: Prometheus
+ type: prometheus
+ access: proxy
+ url: http://prometheus:9090
+ isDefault: true
+ editable: false
+
+ - name: Jaeger
+ uid: jaeger
+ type: jaeger
+ access: proxy
+ url: http://jaeger:16686
+ isDefault: false
+ editable: false
+ jsonData:
+ tracesToLogsV2:
+ datasourceUid: loki
+ spanStartTimeShift: '-2m'
+ spanEndTimeShift: '2m'
+ filterByTraceID: false
+ filterBySpanID: false
+ customQuery: true
+ query: '{service_namespace="testlookup"} | trace_id="$${__span.traceId}"'
+
+ - name: Loki
+ uid: loki
+ type: loki
+ access: proxy
+ url: http://loki:3100
+ isDefault: false
+ editable: false
+ jsonData:
+ maxLines: 1000
+ timeout: 30
+ derivedFields:
+ - name: TraceID
+ datasourceUid: jaeger
+ matcherRegex: '"trace_id"\s*:\s*"([0-9a-fA-F]{32})"'
+ url: '$${__value.raw}'
+ urlDisplayLabel: Open trace
diff --git a/infra/monitoring/jaeger-image-lock.json b/infra/monitoring/jaeger-image-lock.json
new file mode 100644
index 000000000..57df1e9d0
--- /dev/null
+++ b/infra/monitoring/jaeger-image-lock.json
@@ -0,0 +1,11 @@
+{
+ "image": "cr.jaegertracing.io/jaegertracing/jaeger:2.23.0@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e",
+ "upstream_source": "https://github.com/jaegertracing/jaeger/tree/v2.23.0",
+ "bundle": "telemetry",
+ "release_binaries": {
+ "linux-amd64": {
+ "url": "https://github.com/jaegertracing/jaeger/releases/download/v2.23.0/jaeger-2.23.0-linux-amd64.tar.gz",
+ "sha256": "4b7bd152ed31d2205e4e73b873d289c61cd3fabaecc86443070143448d40b753"
+ }
+ }
+}
diff --git a/infra/monitoring/jaeger.yml b/infra/monitoring/jaeger.yml
new file mode 100644
index 000000000..b0bb8341f
--- /dev/null
+++ b/infra/monitoring/jaeger.yml
@@ -0,0 +1,76 @@
+# Jaeger 2.23.0 small-install, single-instance reference. No HA/shared Badger.
+# Mount a dedicated writable volume at /var/lib/jaeger, owned by 10001:10001.
+# Upstream OTEL Collector owns batching and the persistent retry queue. Keep
+# this final hop synchronous, so HTTP acknowledgement follows the disk write.
+extensions:
+ jaeger_storage:
+ backends:
+ incident_traces:
+ badger:
+ directories:
+ keys: /var/lib/jaeger/keys
+ values: /var/lib/jaeger/values
+ ephemeral: false
+ consistency: true
+ ttl:
+ spans: 72h
+ maintenance_interval: 5m
+ metrics_update_interval: 10s
+ jaeger_query:
+ storage:
+ traces: incident_traces
+ http:
+ endpoint: 0.0.0.0:16686
+ read_header_timeout: 5s
+ write_timeout: 30s
+ # Query gRPC is not used by the reference Grafana datasource.
+ grpc:
+ endpoint: 127.0.0.1:16685
+ healthcheckv2:
+ use_v2: true
+ http:
+ endpoint: 0.0.0.0:13133
+
+receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4318
+ max_request_body_size: 4194304
+ read_header_timeout: 5s
+ write_timeout: 30s
+
+processors:
+ memory_limiter:
+ check_interval: 1s
+ limit_mib: 384
+ spike_limit_mib: 96
+
+exporters:
+ jaeger_storage_exporter:
+ trace_storage: incident_traces
+ queue:
+ enabled: false
+ retry_on_failure:
+ enabled: false
+
+service:
+ extensions: [jaeger_storage, jaeger_query, healthcheckv2]
+ pipelines:
+ traces:
+ receivers: [otlp]
+ processors: [memory_limiter]
+ exporters: [jaeger_storage_exporter]
+ telemetry:
+ resource:
+ service.name: testlookup-jaeger
+ logs:
+ level: warn
+ metrics:
+ level: normal
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
diff --git a/infra/monitoring/loki/image-lock.json b/infra/monitoring/loki/image-lock.json
new file mode 100644
index 000000000..383ef9278
--- /dev/null
+++ b/infra/monitoring/loki/image-lock.json
@@ -0,0 +1,27 @@
+{
+ "image": "docker.io/grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
+ "upstream_source": "https://github.com/grafana/loki/tree/v3.7.10",
+ "upstream_release": "https://github.com/grafana/loki/releases/tag/v3.7.10",
+ "digest_source": "https://registry-1.docker.io/v2/grafana/loki/manifests/3.7.10",
+ "digest_kind": "multi-platform manifest index",
+ "verified_at": "2026-11-27",
+ "image_user": "10001",
+ "bundle": "telemetry-external",
+ "release_checksums": "https://github.com/grafana/loki/releases/download/v3.7.10/SHA256SUMS",
+ "verification_grafana": {
+ "version": "13.3.1",
+ "url": "https://dl.grafana.com/grafana/release/13.3.1/grafana_13.3.1_42849527790_linux_amd64.tar.gz",
+ "sha256": "6acf8939dd2f73332cbcafc27a33973fb1115b8867e7ffa3223c6e2ecbed8531",
+ "source": "https://grafana.com/grafana/download/13.3.1?edition=oss"
+ },
+ "release_binaries": {
+ "linux-amd64": {
+ "url": "https://github.com/grafana/loki/releases/download/v3.7.10/loki-linux-amd64.zip",
+ "sha256": "200e74f7e631969bd0f2a066a2e1d33cdea9b3c0801aaaa7d78947c4ac29bddb"
+ },
+ "windows-amd64": {
+ "url": "https://github.com/grafana/loki/releases/download/v3.7.10/loki-windows-amd64.exe.zip",
+ "sha256": "7e3ae97518b290cbcaf9dc359af00e9d0a541333fe131fe7ce3056197306bfaf"
+ }
+ }
+}
diff --git a/infra/monitoring/loki/loki.yml b/infra/monitoring/loki/loki.yml
new file mode 100644
index 000000000..e8a6fc7f7
--- /dev/null
+++ b/infra/monitoring/loki/loki.yml
@@ -0,0 +1,110 @@
+# Private, single-process reference profile. Loki has no authentication layer:
+# expose it only to the collector/Grafana on the dedicated internal network.
+target: all
+auth_enabled: false
+analytics:
+ reporting_enabled: false
+
+server:
+ http_listen_address: 0.0.0.0
+ http_listen_port: 3100
+ grpc_listen_address: 127.0.0.1
+ grpc_listen_port: 9096
+ http_server_read_timeout: 30s
+ http_server_write_timeout: 30s
+
+common:
+ instance_addr: 127.0.0.1
+ path_prefix: /loki
+ replication_factor: 1
+ ring:
+ kvstore:
+ store: inmemory
+ storage:
+ filesystem:
+ chunks_directory: /loki/chunks
+ rules_directory: /loki/rules
+
+schema_config:
+ configs:
+ - from: '2024-01-01'
+ store: tsdb
+ object_store: filesystem
+ schema: v13
+ index:
+ prefix: index_
+ period: 24h
+
+storage_config:
+ tsdb_shipper:
+ active_index_directory: /loki/index
+ cache_location: /loki/index-cache
+
+ingester:
+ lifecycler:
+ min_ready_duration: 1s
+ wal:
+ enabled: true
+ dir: /loki/wal
+ flush_on_shutdown: true
+
+compactor:
+ working_directory: /loki/compactor
+ compaction_interval: 10m
+ retention_enabled: true
+ retention_delete_delay: 2h
+ retention_delete_worker_count: 10
+ delete_request_store: filesystem
+
+limits_config:
+ retention_period: 168h
+ deletion_mode: disabled
+ reject_old_samples: true
+ reject_old_samples_max_age: 168h
+ allow_structured_metadata: true
+ max_structured_metadata_size: 16KB
+ max_structured_metadata_entries_count: 32
+ # Only these OTLP resource attributes become stream/index labels. IDs,
+ # per-instance identity and bounded application role remain metadata.
+ otlp_config:
+ resource_attributes:
+ ignore_defaults: true
+ attributes_config:
+ - action: index_label
+ attributes:
+ - service.name
+ - service.namespace
+ - deployment.environment.name
+ ingestion_rate_strategy: local
+ ingestion_rate_mb: 1
+ ingestion_burst_size_mb: 2
+ per_stream_rate_limit: 512KB
+ per_stream_rate_limit_burst: 1MB
+ max_global_streams_per_user: 500
+ max_line_size: 64KB
+ max_line_size_truncate: false
+ max_label_names_per_series: 3
+ max_query_lookback: 168h
+ max_query_length: 168h
+ max_query_series: 500
+ max_entries_limit_per_query: 1000
+ max_query_parallelism: 4
+ query_timeout: 30s
+ shard_streams:
+ enabled: false
+
+querier:
+ max_concurrent: 2
+frontend:
+ max_outstanding_per_tenant: 64
+query_range:
+ results_cache:
+ cache:
+ embedded_cache:
+ enabled: true
+ max_size_mb: 32
+ruler:
+ enable_api: false
+ rule_path: /loki/rules-temp
+ wal:
+ dir: /loki/ruler-wal
diff --git a/infra/monitoring/otel-collector/config.yml b/infra/monitoring/otel-collector/config.yml
new file mode 100644
index 000000000..e2fd7c957
--- /dev/null
+++ b/infra/monitoring/otel-collector/config.yml
@@ -0,0 +1,169 @@
+# Reference single-installation collector. No host port may publish these
+# endpoints. Cross-host/cross-trust ingress and BYO egress require TLS/mTLS in
+# a reviewed site configuration; this HTTP profile uses isolated networks.
+receivers:
+ otlp:
+ protocols:
+ http:
+ endpoint: 0.0.0.0:4318
+ max_request_body_size: 1048576
+ read_timeout: 5s
+ write_timeout: 10s
+
+extensions:
+ health_check:
+ endpoint: 0.0.0.0:13133
+ file_storage:
+ directory: /var/lib/otelcol/storage
+ create_directory: true
+ fsync: true
+ # Each exporter database is bounded independently. Also reserve a bounded
+ # filesystem/volume: compaction and filesystem overhead need extra space.
+ max_size: 67108864
+ compaction:
+ directory: /var/lib/otelcol/compaction
+ on_start: true
+ on_rebound: true
+ rebound_needed_threshold_mib: 16
+ rebound_trigger_threshold_mib: 8
+
+processors:
+ memory_limiter:
+ check_interval: 1s
+ limit_mib: 384
+ spike_limit_mib: 64
+
+ filter/identity:
+ error_mode: propagate
+ traces:
+ span:
+ - 'resource.attributes["service.namespace"] != "testlookup"'
+ - 'resource.attributes["service.name"] != "testlookup"'
+ logs:
+ log_record:
+ - 'resource.attributes["service.namespace"] != "testlookup"'
+ - 'resource.attributes["service.name"] != "testlookup"'
+ - 'not (log.event_name == "http_request" or log.event_name == "http_unhandled_error" or log.event_name == "analytics_unhandled_error" or log.event_name == "celery_task_execution" or log.event_name == "mcp_request")'
+ - 'not (resource.attributes["testlookup.service.role"] == "api" or resource.attributes["testlookup.service.role"] == "worker" or resource.attributes["testlookup.service.role"] == "worker-children" or resource.attributes["testlookup.service.role"] == "beat" or resource.attributes["testlookup.service.role"] == "mcp")'
+
+ transform/privacy:
+ error_mode: propagate
+ trace_statements:
+ - context: resource
+ statements:
+ - 'set(attributes["deployment.environment.name"], attributes["deployment.environment"]) where attributes["deployment.environment.name"] == nil'
+ - 'keep_keys(attributes, ["service.name", "service.namespace", "service.version", "service.instance.id", "deployment.environment.name", "testlookup.installation", "testlookup.service.role"])'
+ - 'truncate_all(attributes, 128)'
+ - context: scope
+ statements:
+ - 'keep_keys(attributes, [])'
+ - context: span
+ statements:
+ # The application export boundary sanitizes names. No payload, URL,
+ # query, SQL statement, prompt, user or project field passes here.
+ - 'keep_keys(attributes, ["http.request.method", "http.method", "http.response.status_code", "http.status_code", "http.route", "rpc.system", "rpc.service", "rpc.method", "db.system", "db.operation.name", "messaging.system", "messaging.operation.type", "messaging.destination.name", "server.port", "error.type", "celery.task_name", "task.name", "status", "stage", "duration_ms"])'
+ - 'truncate_all(attributes, 256)'
+ - 'set(status.message, "")'
+ - 'set(trace_state, "")'
+ - 'set(name, "operation") where Len(name) > 128'
+ - context: spanevent
+ statements:
+ - 'set(name, "operational-event")'
+ - 'keep_keys(attributes, ["exception.type", "error.type"])'
+ - 'truncate_all(attributes, 128)'
+ log_statements:
+ - context: resource
+ statements:
+ - 'set(attributes["deployment.environment.name"], attributes["deployment.environment"]) where attributes["deployment.environment.name"] == nil'
+ - 'keep_keys(attributes, ["service.name", "service.namespace", "service.version", "service.instance.id", "deployment.environment.name", "testlookup.installation", "testlookup.service.role"])'
+ - 'truncate_all(attributes, 128)'
+ - context: scope
+ statements:
+ - 'keep_keys(attributes, [])'
+ - context: log
+ statements:
+ # Rebuild JSON without reading incoming body text. Only code-selected
+ # event names, hashed IDs and bounded operational values are durable.
+ - 'set(cache["safe"], ParseJSON("{}"))'
+ - 'set(cache["safe"]["event"], event_name)'
+ - 'set(cache["safe"]["service"], resource.attributes["service.name"])'
+ - 'set(cache["safe"]["level"], severity_text) where IsMatch(severity_text, "^(TRACE|DEBUG|INFO|WARN|WARNING|ERROR|FATAL|CRITICAL)$")'
+ - 'set(cache["safe"]["trace_id"], trace_id.string) where trace_id.string != "00000000000000000000000000000000"'
+ - 'set(cache["safe"]["span_id"], span_id.string) where span_id.string != "0000000000000000"'
+ - 'set(cache["safe"]["request_id"], attributes["request_id"]) where IsString(attributes["request_id"]) and IsMatch(attributes["request_id"], "^[0-9a-f]{64}$")'
+ - 'set(cache["safe"]["celery_task_id"], attributes["celery_task_id"]) where IsString(attributes["celery_task_id"]) and IsMatch(attributes["celery_task_id"], "^[0-9a-f]{64}$")'
+ - 'set(cache["safe"]["status_code"], attributes["status_code"]) where IsInt(attributes["status_code"]) and attributes["status_code"] >= 100 and attributes["status_code"] <= 599'
+ - 'set(cache["safe"]["duration_ms"], attributes["duration_ms"]) where (IsInt(attributes["duration_ms"]) or IsDouble(attributes["duration_ms"])) and attributes["duration_ms"] >= 0 and attributes["duration_ms"] <= 600000'
+ - 'set(cache["safe"]["state"], attributes["state"]) where IsString(attributes["state"]) and IsMatch(attributes["state"], "^(success|failure|retry|other)$")'
+ - 'set(body, String(cache["safe"]))'
+ - 'keep_keys(attributes, [])'
+ - 'set(attributes["request_id"], cache["safe"]["request_id"]) where cache["safe"]["request_id"] != nil'
+ - 'set(attributes["celery_task_id"], cache["safe"]["celery_task_id"]) where cache["safe"]["celery_task_id"] != nil'
+
+exporters:
+ otlp_http/traces:
+ endpoint: http://jaeger:4318
+ timeout: 5s
+ retry_on_failure:
+ enabled: true
+ initial_interval: 1s
+ max_interval: 10s
+ max_elapsed_time: 10m
+ sending_queue:
+ enabled: true
+ storage: file_storage
+ sizer: bytes
+ queue_size: 33554432
+ num_consumers: 2
+ block_on_overflow: false
+ wait_for_result: false
+ batch:
+ sizer: bytes
+ min_size: 8192
+ max_size: 65536
+ flush_timeout: 1s
+ otlp_http/logs:
+ endpoint: http://loki:3100/otlp
+ timeout: 5s
+ retry_on_failure:
+ enabled: true
+ initial_interval: 1s
+ max_interval: 10s
+ max_elapsed_time: 10m
+ sending_queue:
+ enabled: true
+ storage: file_storage
+ sizer: bytes
+ queue_size: 33554432
+ num_consumers: 2
+ block_on_overflow: false
+ wait_for_result: false
+ batch:
+ sizer: bytes
+ min_size: 8192
+ max_size: 65536
+ flush_timeout: 1s
+
+service:
+ extensions: [health_check, file_storage]
+ telemetry:
+ logs:
+ level: warn
+ encoding: json
+ metrics:
+ level: normal
+ readers:
+ - pull:
+ exporter:
+ prometheus:
+ host: 0.0.0.0
+ port: 8888
+ pipelines:
+ traces:
+ receivers: [otlp]
+ processors: [memory_limiter, filter/identity, transform/privacy]
+ exporters: [otlp_http/traces]
+ logs:
+ receivers: [otlp]
+ processors: [memory_limiter, filter/identity, transform/privacy]
+ exporters: [otlp_http/logs]
diff --git a/infra/monitoring/otel-collector/image-lock.json b/infra/monitoring/otel-collector/image-lock.json
new file mode 100644
index 000000000..06be96aef
--- /dev/null
+++ b/infra/monitoring/otel-collector/image-lock.json
@@ -0,0 +1,21 @@
+{
+ "image": "docker.io/otel/opentelemetry-collector-contrib:0.166.0@sha256:3e18fe04181de50bdd72e23ad4a4d6214b54351e63d496f1c58127cc4541ad7f",
+ "upstream_source": "https://github.com/open-telemetry/opentelemetry-collector-releases/tree/v0.166.0/distributions/otelcol-contrib",
+ "upstream_release": "https://github.com/open-telemetry/opentelemetry-collector-releases/releases/tag/v0.166.0",
+ "digest_source": "https://registry-1.docker.io/v2/otel/opentelemetry-collector-contrib/manifests/0.166.0",
+ "digest_kind": "multi-platform manifest index",
+ "verified_at": "2026-11-27",
+ "user": "10001:10001",
+ "entrypoint": "/otelcol-contrib",
+ "bundle": "telemetry",
+ "release_binaries": {
+ "windows-amd64": {
+ "url": "https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.166.0/otelcol-contrib_0.166.0_windows_amd64.tar.gz",
+ "sha256": "713e506e766a22deca7a58806b166918649140f1d97bed89a4f8f2997b8e859f"
+ },
+ "linux-amd64": {
+ "url": "https://github.com/open-telemetry/opentelemetry-collector-releases/releases/download/v0.166.0/otelcol-contrib_0.166.0_linux_amd64.tar.gz",
+ "sha256": "928cb39c115d428c53211818b7e33cd8b26810b8896dc74e0bd13b8d1457c391"
+ }
+ }
+}
diff --git a/infra/monitoring/otel-collector/scrape.yml b/infra/monitoring/otel-collector/scrape.yml
new file mode 100644
index 000000000..08ee8e2cd
--- /dev/null
+++ b/infra/monitoring/otel-collector/scrape.yml
@@ -0,0 +1,7 @@
+scrape_configs:
+ - job_name: testlookup-otel-collector
+ static_configs:
+ - targets: [otel-collector:8888]
+ labels:
+ telemetry_profile: compose
+ telemetry_role: otel-collector
diff --git a/infra/monitoring/otel-collector/telemetry-rules.yml b/infra/monitoring/otel-collector/telemetry-rules.yml
new file mode 100644
index 000000000..b20cde0a2
--- /dev/null
+++ b/infra/monitoring/otel-collector/telemetry-rules.yml
@@ -0,0 +1,43 @@
+groups:
+ - name: testlookup.durable_telemetry
+ interval: 30s
+ rules:
+ - record: testlookup:telemetry_expected_role
+ expr: vector(1)
+ labels:
+ job: testlookup-otel-collector
+ telemetry_profile: compose
+ telemetry_role: otel-collector
+
+ - alert: TestLookupTelemetryExporterQueueHigh
+ expr: |
+ (
+ otelcol_exporter_queue_size{job="testlookup-otel-collector"}
+ /
+ otelcol_exporter_queue_capacity{job="testlookup-otel-collector"}
+ ) > 0.8
+ for: 2m
+ labels:
+ severity: warning
+ alert_family: telemetry_export
+ annotations:
+ summary: "A durable telemetry exporter queue is nearing its limit"
+ description: "Check the {{ $labels.exporter }} destination, credentials and storage. The remaining buffer can fill during an outage. Runbook at docs/operations/durable-telemetry.md."
+
+ - alert: TestLookupTelemetryExportLoss
+ expr: |
+ max by (job, telemetry_profile, telemetry_role, instance) (
+ increase(otelcol_exporter_send_failed_log_records{job="testlookup-otel-collector"}[5m]) > 0
+ or increase(otelcol_exporter_send_failed_spans{job="testlookup-otel-collector"}[5m]) > 0
+ or increase(otelcol_exporter_enqueue_failed_log_records{job="testlookup-otel-collector"}[5m]) > 0
+ or increase(otelcol_exporter_enqueue_failed_spans{job="testlookup-otel-collector"}[5m]) > 0
+ or increase(otelcol_receiver_refused_log_records{job="testlookup-otel-collector"}[5m]) > 0
+ or increase(otelcol_receiver_refused_spans{job="testlookup-otel-collector"}[5m]) > 0
+ )
+ for: 1m
+ labels:
+ severity: warning
+ alert_family: telemetry_export
+ annotations:
+ summary: "A durable telemetry hop refused or lost data"
+ description: "Review Collector receiver refusals, enqueue failures, exporter retry exhaustion and available disk. Compare the last known searchable trace or log with the source. Runbook at docs/operations/durable-telemetry.md."
diff --git a/infra/monitoring/prometheus.yml b/infra/monitoring/prometheus.yml
index 23b904ad7..ed13edba8 100644
--- a/infra/monitoring/prometheus.yml
+++ b/infra/monitoring/prometheus.yml
@@ -12,6 +12,7 @@ rule_files:
scrape_config_files:
- backend-scrape.yml
+ - telemetry-scrape-*.yml
scrape_configs:
# ── Celery worker (via prometheus-client multiprocess) ───────────────────────
diff --git a/infra/monitoring/tests/durable-telemetry.yml b/infra/monitoring/tests/durable-telemetry.yml
new file mode 100644
index 000000000..6016f29b5
--- /dev/null
+++ b/infra/monitoring/tests/durable-telemetry.yml
@@ -0,0 +1,56 @@
+rule_files:
+ - ../otel-collector/telemetry-rules.yml
+evaluation_interval: 30s
+tests:
+ - name: one exporter stays above the byte queue threshold then recovers
+ interval: 30s
+ input_series:
+ - series: 'otelcol_exporter_queue_size{job="testlookup-otel-collector",exporter="otlp_http/loki"}'
+ values: '80 90+0x5 40+0x5'
+ - series: 'otelcol_exporter_queue_capacity{job="testlookup-otel-collector",exporter="otlp_http/loki"}'
+ values: '100+0x12'
+ alert_rule_test:
+ - eval_time: 2m
+ alertname: TestLookupTelemetryExporterQueueHigh
+ exp_alerts: []
+ - eval_time: 3m
+ alertname: TestLookupTelemetryExporterQueueHigh
+ exp_alerts:
+ - exp_labels:
+ job: testlookup-otel-collector
+ exporter: otlp_http/loki
+ severity: warning
+ alert_family: telemetry_export
+ exp_annotations:
+ summary: "A durable telemetry exporter queue is nearing its limit"
+ description: "Check the otlp_http/loki destination, credentials and storage. The remaining buffer can fill during an outage. Runbook at docs/operations/durable-telemetry.md."
+ - eval_time: 4m
+ alertname: TestLookupTelemetryExporterQueueHigh
+ exp_alerts: []
+ - name: several signals with identical scrape labels reduce to one affected collector
+ interval: 30s
+ input_series:
+ - series: 'otelcol_exporter_enqueue_failed_log_records{job="testlookup-otel-collector",instance="collector:8888",telemetry_profile="compose",telemetry_role="otel-collector"}'
+ values: '0+0x3 2+0x15'
+ - series: 'otelcol_receiver_refused_spans{job="testlookup-otel-collector",instance="collector:8888",telemetry_profile="compose",telemetry_role="otel-collector"}'
+ values: '0+0x3 1+0x15'
+ alert_rule_test:
+ - eval_time: 1m
+ alertname: TestLookupTelemetryExportLoss
+ exp_alerts: []
+ - eval_time: 4m
+ alertname: TestLookupTelemetryExportLoss
+ exp_alerts:
+ - exp_labels:
+ job: testlookup-otel-collector
+ instance: collector:8888
+ telemetry_profile: compose
+ telemetry_role: otel-collector
+ severity: warning
+ alert_family: telemetry_export
+ exp_annotations:
+ summary: "A durable telemetry hop refused or lost data"
+ description: "Review Collector receiver refusals, enqueue failures, exporter retry exhaustion and available disk. Compare the last known searchable trace or log with the source. Runbook at docs/operations/durable-telemetry.md."
+ - eval_time: 8m
+ alertname: TestLookupTelemetryExportLoss
+ exp_alerts: []
diff --git a/k8s/components/telemetry-client/api.yaml b/k8s/components/telemetry-client/api.yaml
new file mode 100644
index 000000000..f90dcb044
--- /dev/null
+++ b/k8s/components/telemetry-client/api.yaml
@@ -0,0 +1,32 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: testlookup-backend
+ namespace: testlookup
+spec:
+ template:
+ spec:
+ containers:
+ - name: backend
+ env:
+ - name: OTEL_ENABLED
+ value: "true"
+ - name: OTEL_EXPORTER_OTLP_ENDPOINT
+ value: https://testlookup-otel.testlookup-telemetry.svc:4318
+ - name: OTEL_EXPORTER_OTLP_LOGS_ENDPOINT
+ value: https://testlookup-otel.testlookup-telemetry.svc:4318/v1/logs
+ - name: OTEL_EXPORTER_OTLP_CERTIFICATE
+ value: /var/run/testlookup-otel/ca.crt
+ - name: OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE
+ value: /var/run/testlookup-otel/tls.crt
+ - name: OTEL_EXPORTER_OTLP_CLIENT_KEY
+ value: /var/run/testlookup-otel/tls.key
+ volumeMounts:
+ - name: telemetry-client-identity
+ mountPath: /var/run/testlookup-otel
+ readOnly: true
+ volumes:
+ - name: telemetry-client-identity
+ secret:
+ secretName: testlookup-otel-api-client
+ optional: true
diff --git a/k8s/components/telemetry-client/kustomization.yaml b/k8s/components/telemetry-client/kustomization.yaml
new file mode 100644
index 000000000..7571f1778
--- /dev/null
+++ b/k8s/components/telemetry-client/kustomization.yaml
@@ -0,0 +1,11 @@
+apiVersion: kustomize.config.k8s.io/v1alpha1
+kind: Component
+resources:
+ - networkpolicy.yaml
+patches:
+ - path: api.yaml
+ - path: worker.yaml
+ target:
+ kind: Deployment
+ name: testlookup-worker-.+
+ - path: mcp.yaml
diff --git a/k8s/components/telemetry-client/mcp.yaml b/k8s/components/telemetry-client/mcp.yaml
new file mode 100644
index 000000000..b71f138f7
--- /dev/null
+++ b/k8s/components/telemetry-client/mcp.yaml
@@ -0,0 +1,28 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: testlookup-mcp
+ namespace: testlookup
+spec:
+ template:
+ spec:
+ containers:
+ - name: mcp
+ env:
+ - name: TESTLOOKUP_OTLP_LOGS_ENDPOINT
+ value: https://testlookup-otel.testlookup-telemetry.svc:4318/v1/logs
+ - name: OTEL_EXPORTER_OTLP_CERTIFICATE
+ value: /var/run/testlookup-otel/ca.crt
+ - name: OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE
+ value: /var/run/testlookup-otel/tls.crt
+ - name: OTEL_EXPORTER_OTLP_CLIENT_KEY
+ value: /var/run/testlookup-otel/tls.key
+ volumeMounts:
+ - name: telemetry-client-identity
+ mountPath: /var/run/testlookup-otel
+ readOnly: true
+ volumes:
+ - name: telemetry-client-identity
+ secret:
+ secretName: testlookup-otel-mcp-client
+ optional: true
diff --git a/k8s/components/telemetry-client/networkpolicy.yaml b/k8s/components/telemetry-client/networkpolicy.yaml
new file mode 100644
index 000000000..bddeea913
--- /dev/null
+++ b/k8s/components/telemetry-client/networkpolicy.yaml
@@ -0,0 +1,23 @@
+apiVersion: networking.k8s.io/v1
+kind: NetworkPolicy
+metadata:
+ name: allow-telemetry-client
+ namespace: testlookup
+spec:
+ podSelector:
+ matchExpressions:
+ - key: app.kubernetes.io/component
+ operator: In
+ values: [api, worker, mcp-server]
+ policyTypes: [Egress]
+ egress:
+ - to:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: testlookup-telemetry
+ podSelector:
+ matchLabels:
+ app.kubernetes.io/name: testlookup-otel
+ ports:
+ - protocol: TCP
+ port: 4318
diff --git a/k8s/components/telemetry-client/worker.yaml b/k8s/components/telemetry-client/worker.yaml
new file mode 100644
index 000000000..a0808c526
--- /dev/null
+++ b/k8s/components/telemetry-client/worker.yaml
@@ -0,0 +1,29 @@
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: testlookup-worker
+spec:
+ template:
+ spec:
+ containers:
+ - name: worker
+ env:
+ - name: OTEL_LOGS_ROLE
+ value: worker
+ - name: OTEL_EXPORTER_OTLP_LOGS_ENDPOINT
+ value: https://testlookup-otel.testlookup-telemetry.svc:4318/v1/logs
+ - name: OTEL_EXPORTER_OTLP_CERTIFICATE
+ value: /var/run/testlookup-otel/ca.crt
+ - name: OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE
+ value: /var/run/testlookup-otel/tls.crt
+ - name: OTEL_EXPORTER_OTLP_CLIENT_KEY
+ value: /var/run/testlookup-otel/tls.key
+ volumeMounts:
+ - name: telemetry-client-identity
+ mountPath: /var/run/testlookup-otel
+ readOnly: true
+ volumes:
+ - name: telemetry-client-identity
+ secret:
+ secretName: testlookup-otel-worker-client
+ optional: true
diff --git a/k8s/overlays/k3s-telemetry/kustomization.yaml b/k8s/overlays/k3s-telemetry/kustomization.yaml
new file mode 100644
index 000000000..4418e87da
--- /dev/null
+++ b/k8s/overlays/k3s-telemetry/kustomization.yaml
@@ -0,0 +1,7 @@
+apiVersion: kustomize.config.k8s.io/v1beta1
+kind: Kustomization
+namespace: testlookup
+resources:
+ - ../k3s
+components:
+ - ../../components/telemetry-client
diff --git a/k8s/overlays/openshift-telemetry/kustomization.yaml b/k8s/overlays/openshift-telemetry/kustomization.yaml
new file mode 100644
index 000000000..bbd3e7858
--- /dev/null
+++ b/k8s/overlays/openshift-telemetry/kustomization.yaml
@@ -0,0 +1,7 @@
+apiVersion: kustomize.config.k8s.io/v1beta1
+kind: Kustomization
+namespace: testlookup
+resources:
+ - ../openshift
+components:
+ - ../../components/telemetry-client
diff --git a/k8s/overlays/prod-telemetry/kustomization.yaml b/k8s/overlays/prod-telemetry/kustomization.yaml
new file mode 100644
index 000000000..a7f35081b
--- /dev/null
+++ b/k8s/overlays/prod-telemetry/kustomization.yaml
@@ -0,0 +1,7 @@
+apiVersion: kustomize.config.k8s.io/v1beta1
+kind: Kustomization
+namespace: testlookup
+resources:
+ - ../prod
+components:
+ - ../../components/telemetry-client
diff --git a/mcp/config.py b/mcp/config.py
index a0d1eee6f..311fe90a0 100644
--- a/mcp/config.py
+++ b/mcp/config.py
@@ -47,6 +47,8 @@ class Settings(BaseSettings):
# exact hosts/origins; ``:*`` is supported for local ephemeral ports.
mcp_allowed_hosts: str = "127.0.0.1:*,localhost:*,[::1]:*"
mcp_allowed_origins: str = ""
+ otlp_logs_endpoint: str = ""
+ telemetry_environment: str = "production"
model_config = SettingsConfigDict(
env_prefix="TESTLOOKUP_",
diff --git a/mcp/licenses/THIRD_PARTY_NOTICES.md b/mcp/licenses/THIRD_PARTY_NOTICES.md
index a447f8785..9b0932830 100644
--- a/mcp/licenses/THIRD_PARTY_NOTICES.md
+++ b/mcp/licenses/THIRD_PARTY_NOTICES.md
@@ -146,12 +146,12 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `numpy` | BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0 | backend |
| `openpyxl` | MIT | backend |
| `opentelemetry-api` | Apache-2.0 | backend |
-| `opentelemetry-exporter-otlp-proto-http` | Apache-2.0 | backend |
+| `opentelemetry-exporter-otlp-proto-http` | Apache-2.0 | backend, mcp |
| `opentelemetry-instrumentation-fastapi` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-httpx` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-redis` | Apache-2.0 | backend |
| `opentelemetry-instrumentation-sqlalchemy` | Apache-2.0 | backend |
-| `opentelemetry-sdk` | Apache-2.0 | backend |
+| `opentelemetry-sdk` | Apache-2.0 | backend, mcp |
| `passlib` | BSD-3-Clause | backend |
| `platformdirs` | MIT | cli |
| `prometheus-client` | Apache-2.0 AND BSD-2-Clause | backend |
@@ -174,6 +174,7 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `pyyaml` | MIT | backend, cli, client |
| `redis` | MIT | backend |
| `reportlab` | BSD-3-Clause | backend |
+| `requests` | Apache-2.0 | backend, mcp |
| `rich` | MIT | cli |
| `ruff` | MIT | backend |
| `scikit-learn` | BSD-3-Clause | backend |
@@ -188,7 +189,7 @@ Apache-2.0, MIT or MPL-2.0 and is used under Apache-2.0.
| `typer` | MIT | cli |
| `types-python-dateutil` | Apache-2.0 | backend |
| `tzdata` | Apache-2.0 | backend |
-| `uvicorn` | BSD-3-Clause | backend |
+| `uvicorn` | BSD-3-Clause | backend, mcp |
## Container base images
@@ -234,6 +235,13 @@ They are listed for your own license review.
| `ollama/ollama:0.40.10` | MIT; the image also contains NVIDIA CUDA runtime libraries under the NVIDIA CUDA EULA | https://github.com/ollama/ollama |
| `chromadb/chroma:1.5.9` | Apache-2.0 | https://github.com/chroma-core/chroma |
| `mher/flower:2.0` | BSD-3-Clause | https://github.com/mher/flower |
+| `busybox:1.36@sha256:73aaf090f3d85aa34ee199857f03fa3a95c8ede2ffd4cc2cdb5b94e566b11662` | see upstream | |
+| `prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06` | see upstream | |
+| `grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf` | see upstream | |
+| `otel/opentelemetry-collector-contrib:0.166.0@sha256:3e18fe04181de50bdd72e23ad4a4d6214b54351e63d496f1c58127cc4541ad7f` | see upstream | |
+| `cr.jaegertracing.io/jaegertracing/jaeger:2.23.0@sha256:3823829974ccfc2485d2e48b165579091f32295022ae80ca49704e2f4834116e` | see upstream | |
+| `grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7` | see upstream | |
+| `docker.io/prom/alertmanager:v0.35.1@sha256:4e3d029e69c7f61dd53a2b31a3dc427a2b81736cffca185c0854075e07969e36` | see upstream | |
**MongoDB** is licensed under the Server Side Public License (SSPL-1.0), which
is not an OSI-approved license. TestLookup only connects to it with the
diff --git a/mcp/operational_logs.py b/mcp/operational_logs.py
new file mode 100644
index 000000000..db52a678c
--- /dev/null
+++ b/mcp/operational_logs.py
@@ -0,0 +1,95 @@
+"""Bounded, payload-free operational logs for the deployed SSE transport."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import re
+import time
+import uuid
+from urllib.parse import urlsplit
+
+import requests
+from opentelemetry._logs import SeverityNumber
+from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
+from opentelemetry.sdk._logs import LoggerProvider
+from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
+from opentelemetry.sdk.resources import Resource
+from opentelemetry.util.types import AttributeValue
+from starlette.datastructures import Headers, MutableHeaders
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
+
+logger = logging.getLogger(__name__)
+_CORRELATION_ID = re.compile(r"[A-Za-z0-9._:-]{1,128}")
+_QUIET_PATHS = frozenset({"/health/live", "/health/ready"})
+
+
+def add_operational_logs(app: ASGIApp, endpoint: str, environment: str) -> ASGIApp:
+ try:
+ url = urlsplit(endpoint)
+ private_http = url.scheme == "http" and url.hostname in {
+ "otel-collector", "localhost", "127.0.0.1", "::1",
+ }
+ if (
+ not url.hostname or (url.scheme != "https" and not private_http)
+ or url.path != "/v1/logs" or url.username is not None
+ or url.query or url.fragment
+ ):
+ raise ValueError("expected an HTTPS OTLP/HTTP logs URL")
+ resource = Resource({
+ "service.name": "testlookup",
+ "service.namespace": "testlookup",
+ "deployment.environment.name": environment
+ if environment in {"development", "staging", "production"} else "unknown",
+ "testlookup.service.role": "mcp",
+ })
+ session = requests.Session()
+ session.trust_env = False
+ session.max_redirects = 0
+ exporter = OTLPLogExporter(
+ endpoint=endpoint, timeout=2, max_request_size=65_536, session=session,
+ )
+ provider = LoggerProvider(resource=resource)
+ provider.add_log_record_processor(BatchLogRecordProcessor(
+ exporter, max_queue_size=512, max_export_batch_size=64, schedule_delay_millis=1000,
+ ))
+ sink = provider.get_logger("testlookup.operational")
+ except Exception: # noqa: BLE001 - the service runs if telemetry configuration is invalid
+ logger.warning("Operational log exporter could not initialize")
+ return app
+
+ async def observed(scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] != "http" or scope["path"] in _QUIET_PATHS:
+ await app(scope, receive, send)
+ return
+ supplied = Headers(scope=scope).get("X-Request-ID", "")
+ request_id = supplied if _CORRELATION_ID.fullmatch(supplied) else str(uuid.uuid4())
+ started = time.monotonic()
+
+ async def send_observed(message: Message) -> None:
+ if message["type"] == "http.response.start":
+ MutableHeaders(scope=message)["X-Request-ID"] = request_id
+ status = message["status"]
+ severity = SeverityNumber.WARN if status >= 500 else SeverityNumber.INFO
+ attributes: dict[str, AttributeValue] = {
+ "request_id": hashlib.sha256(request_id.encode("ascii")).hexdigest(),
+ "status_code": status,
+ "duration_ms": round((time.monotonic() - started) * 1000, 2),
+ }
+ try:
+ sink.emit(
+ timestamp=time.time_ns(),
+ severity_number=severity,
+ severity_text=severity.name,
+ event_name="mcp_request",
+ body=json.dumps({"event": "mcp_request", **attributes}, separators=(",", ":")),
+ attributes=attributes,
+ )
+ except Exception: # noqa: BLE001 - preserve the response if telemetry fails
+ logger.warning("Operational log submission failed")
+ await send(message)
+
+ await app(scope, receive, send_observed)
+
+ return observed
diff --git a/mcp/requirements-lock.txt b/mcp/requirements-lock.txt
index fad549afa..b9fbfb43c 100644
--- a/mcp/requirements-lock.txt
+++ b/mcp/requirements-lock.txt
@@ -25,6 +25,7 @@ certifi==2026.11.20 \
# via
# httpcore
# httpx
+ # requests
cffi==2.1.1 ; platform_python_implementation != 'PyPy' \
--hash=sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e \
--hash=sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66 \
@@ -127,7 +128,181 @@ cffi==2.1.1 ; platform_python_implementation != 'PyPy' \
--hash=sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4 \
--hash=sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264
# via cryptography
-click==8.5.1 ; sys_platform != 'emscripten' \
+charset-normalizer==3.5.3 \
+ --hash=sha256:00edb7682962c596f774bfa126e6b6f885b7af2319f448d327591c284a482de8 \
+ --hash=sha256:01b35bec964b92b89bdf94adf931d2e80a15f1c7b93bf850b4430cca23f7a2a2 \
+ --hash=sha256:020cabbb90926b2d8b022a5e057ab349f28844b61f34117323fc08c2971915e3 \
+ --hash=sha256:02b1abf64742b2d0782172cd2542616e462c201c829c23aff833390babe2967f \
+ --hash=sha256:06d07272f70d9880fba32d4876e966ae4dc9961134bc989066a0901509dfd8cf \
+ --hash=sha256:0810592b80dc5a97f8103443460264b588f31c6baa8a20abae7c683435d8117a \
+ --hash=sha256:085a5d1f49eaf96596d79494fcab18d9a32db6e345da15d6debfc90110b20679 \
+ --hash=sha256:09833ba78c91f0d1fd06387c69dae9f079428b77ea05eaaf1553eecead31fb68 \
+ --hash=sha256:0b3fc6f7dd9db4a7782e65dc98eb80b2a91a854cf54a03dd93649be2f7ca638d \
+ --hash=sha256:0c0fe07631dce6dae788a59c20ed927adc6feeb2d9ed440747eb367d89822a45 \
+ --hash=sha256:0ca25f1b1167e9fb94d93d3708df0b631de241bf8440947b0cb9f8c4cb66fed0 \
+ --hash=sha256:0ca2da4a505fae7ef95922f8d48235b2e49ff8f10f4edcc0481e5f6526ba3841 \
+ --hash=sha256:0cf4cb8d75090a8da3bd30c0963b2c6c6114e791c6fc060c3cef8971497b1f04 \
+ --hash=sha256:106b9d0438e2ff0a0e8ebd869273fcb3640af28323bba8651c714c57efb38e51 \
+ --hash=sha256:11ad35a0b856ad8bbd0c9e900c069461a4661694714aa17b6e6e2e8621e1c373 \
+ --hash=sha256:139aeb8ca63946dc79364c37f2c9cfe5c1b7f3882f2c47484d0e54bf14b921b0 \
+ --hash=sha256:1714ff1ba001da5241a585fbd17a7742a61ad34efb4be8404aca5679f51e53ea \
+ --hash=sha256:183aee7e84789391e547ec1609f8269332b9b123d21e97f7ef79eaa474c47e08 \
+ --hash=sha256:1a34385837db59d5de814c9f1e0f4157b571f9ce0eabdaeace410aa93bf5df62 \
+ --hash=sha256:1b2704f4651539eab50ba104a975b96c3cd5246011aa0755d2dd71ac12546644 \
+ --hash=sha256:2246873913d7db43ed5a3d98ace398b989b2ae20b77c8d761a7bef5fdb9bed42 \
+ --hash=sha256:249bf0b6f43985c33c83adbbab0ca71246ec24c82d960fa00c4ddb2cfed25db9 \
+ --hash=sha256:256b434b2860ef9da1cb6a5fd4ebb5d600936668e50e2035858948b96b068ecd \
+ --hash=sha256:26c6ad87bb79628954b52f8f7b9e18ab5cd9667546712ded9689fb7677e630d6 \
+ --hash=sha256:277b72183b96879887f0c3aa0bdac1fee08a6c7e67bad53145c4fd416d99dfd3 \
+ --hash=sha256:28ba8e6361e0f319641707484994096ceb77e05c29eaad2919756218c0c89001 \
+ --hash=sha256:28d954a437bfa5fcdfe7ad8902cf4347a8486f34a86c5f39003bc1288eb67d72 \
+ --hash=sha256:2978c799237eb66619d8951d2ab7efd317414cb6682160e05614ce1c8b5c905f \
+ --hash=sha256:29ac44f5878142128ffe4fa7e041ddc4cc5fafe43983245b9a141908c40b515d \
+ --hash=sha256:2a6f937e0b70133d1f826d0a253331b6fe1a4c874808cc12e16f2fb8177042f4 \
+ --hash=sha256:2b7797a5b0cb197f118fd13b41c14c5a3c38dd625a87c1da58a3066cf53254fd \
+ --hash=sha256:2c4e0050b732ee3dca3676a5f5cf7fbd0c131761c194f1bb1d24c055fad071cf \
+ --hash=sha256:2e7fbd98443f28a5ed8004f0b058edcc4720a3d344adf007c0b7f1adbff2f59f \
+ --hash=sha256:2f2d973d3c79fbd1066d63d1bafb2ade66934c0840ed149f6fac13c3fdf80793 \
+ --hash=sha256:323d5cf6df3ea724afcc3bfb07c73be06d2e8200a8b6b37979a300ae1e7836d0 \
+ --hash=sha256:326a7a0e3715c3ac24c21e7a3b831d6799cc795bff260aa49c23b69025852f99 \
+ --hash=sha256:34054580168b04e90e6c7c0f6c80173fa2d4f72c4db91c9095598454f96d6389 \
+ --hash=sha256:366f5efe95a6149ecbcebf779c2594a6a4ff6fc116402826c72ed0eccd6aabe9 \
+ --hash=sha256:390ef7c7e018c0abb8c0ec2d28ee137567ff50c3706facf6d115cac832ac993b \
+ --hash=sha256:39229c222445415db07a0be4dff8ad1addc3126644d7aa72d73f1575b637d69e \
+ --hash=sha256:396fdf2d4367674531a7c8d54ecabbc8e5131e3a1a06270285eb99f3140143df \
+ --hash=sha256:39e019884c8f857393df954d35f42bf99c5ab85af226fe74d1410188c6fec31f \
+ --hash=sha256:3ce4e4587e451ebc7d9899a7a1f539ea30a3c712d7bc8e0d256923c697fd5dcc \
+ --hash=sha256:3e8da696ef1935a019c10ec16555a062183ddf6d5901e296edeca4b2a8f84e1d \
+ --hash=sha256:40b2ba91f0851aa864994b3c7022e4d96d09026717e6a72e44410d6fb3a74a13 \
+ --hash=sha256:45aa4ccf5a6caba138dd0f8bf36fa3e26654585d534881b62ce5e4fea2487772 \
+ --hash=sha256:4831fb33e98e92140fa17d4d673a9f49f9c0ddd056115b722858793e4b86b0c5 \
+ --hash=sha256:48f7c7f537246bb3af2b3139f44716a30b21e78c2fd1cff0f3e392fbd55d8044 \
+ --hash=sha256:499e4bbeb1e79b14756311a1d12cb88112f244423e152d80981d9bcaff3279fa \
+ --hash=sha256:4a991dbd7aec868fe10802b02bddbf898173a47ba236f2d6afb4ab1f98243534 \
+ --hash=sha256:4ff5e27478681ef1b13b036baaf9beaf9b4c6990e903c752ad3b8764692c6d6c \
+ --hash=sha256:56405211fa124c393eea14b3aeacf5b90de72b1f69b0a60c9bc40b01dfe71a42 \
+ --hash=sha256:581d6e7df9b58d34147e21efde42a480b5087fe54f31e42550c26321566ba1e4 \
+ --hash=sha256:5970d148182b6b7c22b8290a81f02fb521c4e7aee6747743b3e645db58d5001a \
+ --hash=sha256:5f86753952f7de3abc7ce871f8239ce4e0d32a91c84d22f3a667e669907c3897 \
+ --hash=sha256:6118055f4ad0d94e016eadbb86caed9caf2c9033631ed70964ba631c1336984f \
+ --hash=sha256:61e32fdbf56f4cd25a1efa451c8b5fe886fc5e00143ccaacafdf21f301fad059 \
+ --hash=sha256:61f3258f700412c68fde407e7c749ed6930e795ea8f5ead9a40afddefbec12c4 \
+ --hash=sha256:6423accb6ecd1456bf824bbac98ba919398523a69ee5f1680dd1da88769de866 \
+ --hash=sha256:643724071b01cc0369026e259850791212cc187c6031d0e930abcd253f128e0c \
+ --hash=sha256:656b9744bac4493561d28b56d7d646afd7a8471254ef7004d849aa8368020037 \
+ --hash=sha256:6651fecdac146ecfa52700e02a5fa3b3677bddf5fced4983b43e904244de3f6a \
+ --hash=sha256:67bb767a8de7a2b1164c74fdbe5cdc32b9c15d7142efd9a6dc77ff63da94e846 \
+ --hash=sha256:6b702d36c565f6c650f4b479488f475b2982132ab8d0840d42b1442462c21056 \
+ --hash=sha256:6bfbbb9414dd0f5b81c259deb7e50b4b44e65e05879eee482351bdabed49d7f4 \
+ --hash=sha256:6c80b4e83e2fbddd25fe27804cdfc45ef71bb387522caa575af42118d72dc970 \
+ --hash=sha256:6c8abe7d59bbc891e5080b8b142c36db93154f840c4baf7c83ad6273a1a15397 \
+ --hash=sha256:6dde7edd9ba5005389bc7c0ab461411f281dbacb2b06e52bd23592eba42bb503 \
+ --hash=sha256:6eea31136fd924ecbb4e7c4f3df4b18230409629a22b3896f38a6754d5857794 \
+ --hash=sha256:70f65dd0c2ed79ea2d9776096e9c7d25e398c2c03eb31877753598d201d91784 \
+ --hash=sha256:73b4ddf1230df56c9e7017a16e3f5171b6ef0e4ff554a418a370d7ac7245bd84 \
+ --hash=sha256:747e83d415939612284afdc99f15295382639c0d3fc69a73aeb84b380d1f4af3 \
+ --hash=sha256:7a7e5bb8974842ad747d4a2b9fb928f84c3cdbe2c2fd7e405197fc1a1badaeaa \
+ --hash=sha256:7c313b46730b4a68bb31450973467313b2c496fefa42ae316b86c186cba74613 \
+ --hash=sha256:7fd816f466883dcaac196ac77271d0292eee4a81f4db1191b95d15328f335937 \
+ --hash=sha256:7fdd11094a0b07bce306b359fa7311c71d93466d967b3b345f2e9f03d8b2c959 \
+ --hash=sha256:806e72ebaeef54d7faa03414be9e8409eb3dcae49fba089d62063a60c0b5a4e5 \
+ --hash=sha256:81132eaffa984f0a399233df4cd383caad18e8cadc6c24c568cf9324732a9768 \
+ --hash=sha256:8231365b03b702b516aad35c9515694177ac31c9dc6240326f07308a4c45c708 \
+ --hash=sha256:826d82356907350f345cf0aa744d43a69ac7948bd60f460f997cde86928beadf \
+ --hash=sha256:84356c7b7ddf090e3e4692cb99fc820e6189b5f6662ca7e8589f41095cc8efca \
+ --hash=sha256:87d5a237d6531c654e7b9b319be9ba7e368665c466e02a03cfd4d3d77730782e \
+ --hash=sha256:87f7d6c595465a25d33fa3d5215a571a98c4cad00ead3ad18ebfb62adb3d3e6e \
+ --hash=sha256:885f202d6e4e2298bea9802ffc6d8c7dc45394199a8dd9e1492f05fe32dce311 \
+ --hash=sha256:8b969f0309de905101bc3d2471c112e9ccbba711a7590b12d51f372b4163688a \
+ --hash=sha256:8baddc6349faf49edae4d1322f12b681b9e86acacd01874457c997437ef4ccaa \
+ --hash=sha256:8c4dfcd3269f13dff7f29f9c332d54a4a21f17be818b49e769e111befd4d39e6 \
+ --hash=sha256:90b1ff6cb9c7a204a3b79b1b0ed6ac8a1d8fed3b6dc69e50ae5de0f358ee81d4 \
+ --hash=sha256:92bf85ecec3ad6374ae50d870bd1deb34de12bc1158b5fd09036d4c435c6f58c \
+ --hash=sha256:92ddc32b6a1508ea145f4f7995e00666db454b8fd3e2cae6c2ecbde4f4d44616 \
+ --hash=sha256:948fb3649416a70bcdbb267d79c7048e8aa16e989ab9da09f416e67cdd3d6b8c \
+ --hash=sha256:94b595e64bc2927f679774de50df340b7828dc1c07c99149ba7c2d0828dd8bf3 \
+ --hash=sha256:94c9d5d91c16554f6397b823d9e47181ba100d830ab16b5d720adc229e17b2e2 \
+ --hash=sha256:9510da88bdebc903be7844f31523ac8d7b3f63e167db54b6045104a2354afa6a \
+ --hash=sha256:96387278c3b17bc1170f80693398d0babac7b41df128ced8e27588a7155d95b2 \
+ --hash=sha256:96e268b0cbda016ac519513294fcd17032264085b600abaac58b93049477e132 \
+ --hash=sha256:9902e80096a94cf70fb72d12ae40e3b187b40e96fa722873d4d62afcd0333c46 \
+ --hash=sha256:9a6b95b1737f9b5942c35676c52db0c302d60fa806efde3fc2d9f54247ecf4be \
+ --hash=sha256:9b887e8a7103ae2171dccbab00a4bb2bf1560f5c10c28227e5513bc90a608cad \
+ --hash=sha256:9c1bd8321a840729a6b2620774cf4000fafe66c54cac9064972a10c4f607794b \
+ --hash=sha256:9eba4613d45b49196af04a5cbadfc5e9379ba94aac85184b72cb1107ad31af0d \
+ --hash=sha256:a094178c51530c9ebd1775e72d160af0eac4be244fb06ff1b6f182128c71903c \
+ --hash=sha256:a09ca76391f6e17b12d55c1068b4b5f8f6c9b44b432d936075372fa12782292d \
+ --hash=sha256:a250888753faa289e2997962fbb17c4960cbdb58575533ca6fceee68c224bdff \
+ --hash=sha256:a312fedd182357f2c22f066d17dcd7413b6a205ee3d063d36950e94e3019d3de \
+ --hash=sha256:a36bba41dc7fd263417688c4daf95a1091f93e1f6957c0f71ad7798907c5a10c \
+ --hash=sha256:a3f4044dd5d2f7b958be6b9903cb432e6a0fd944d673707ca5cab68137d0592c \
+ --hash=sha256:a43831574e14423103d69fb1357e76e4f2347041c98e8357ab88ef21812e80d9 \
+ --hash=sha256:a491d4afb361aba32d55d7df7ccde766a3aa9a34c002d2c32c2743bf6e77c13c \
+ --hash=sha256:a5a7e0326566759f9a7bc44f4b9a179cc40a297e09e759b0bc7c848c06347527 \
+ --hash=sha256:a6eba94fc00d899f8d268712772c8dcafc40215aa9b51701a397afc9426e012b \
+ --hash=sha256:a8f92cc9080bff47555c79b88e7fb8655438ce3bcf29c5f01ed2ed5efdf174a4 \
+ --hash=sha256:aa2476abf8669be493689634bdb79f468a6fe57b005a5126db7e9f61d1954fe2 \
+ --hash=sha256:aa8be1f24fbc03a07cfe002b70ba0716effc6b3011fd9e5560ca399d3d0605ad \
+ --hash=sha256:aa9390d89822dd06f9920ae3038819cb121643a72f4753b2eee1a79b2f1215f8 \
+ --hash=sha256:acaa0e100f39287dc5d13de96e33ba0786f1cdfb5b4ca28918913ab0eec3af72 \
+ --hash=sha256:ad1becd776f5a41a4d91cb9ee51778f4fd687ef15e4919779e00a33c6cff6948 \
+ --hash=sha256:af217012cfdaf6ea5dc0c538aac29b7bd030eb865056cc60f1d973b982b7917b \
+ --hash=sha256:b013417037c931583578639cab2523d5a2efc35a584c192d07f4c909b133f6b0 \
+ --hash=sha256:b0aa6b81bc632af7cac7b270c933298cb5ee858506dcf344e0da006667e0c351 \
+ --hash=sha256:b30e5496e453ac971bb17f5e096b84fbaae16d09e2613f6148ff528c08a54a0c \
+ --hash=sha256:b66a0e045cf859d7418f26a554509b65f21ebb6d90a95152460781939e8264f4 \
+ --hash=sha256:b6dad86d938104f9d43404029e5fc8392f82762d171933be4f192a6008bffa53 \
+ --hash=sha256:b6ea5bf7e3c39f6e56957d82274ac7cfab469590085883fdbc86e754cde76b11 \
+ --hash=sha256:b8fc4fe56992b089d6177021fe6db641321bb2bc2fc7a1abf815c29a80ca2137 \
+ --hash=sha256:ba26e4d073a4f7f2594676f2ff20ab80a7f03332b81c3f9964e9e53bf2305329 \
+ --hash=sha256:bed05639ae1bc23df7996a4fd13ea5064ddf60dc7dabd754f8badf060daec63f \
+ --hash=sha256:c08e06fc69750827d7ccebba63ebc97a85e479cd5c9dbdb80f5e08a77b774fdb \
+ --hash=sha256:c39a4fe28a16e8fa667c55c154f62c6c3cd9ca2491cca9f16330dd7360d05b76 \
+ --hash=sha256:c437ed8775d201d37206f37d233f547506e3aef60b9711584c65444c686b4905 \
+ --hash=sha256:c43d9737c3b85ccd16b1862b1e7aa5c4bf30a6033068403713c0a2bba5bda979 \
+ --hash=sha256:c9d1f467d121b33b06865c94ed5ed8388a9ef76f5e1acc1c8a854ac653493f5d \
+ --hash=sha256:caefc441edff6070a9f9749ca880a22731a1715d9e74b24304a546eec44bfc16 \
+ --hash=sha256:cb18428af7399e0a6f7e3b45f110d57a1a47cf07fd4b3ce50e2366d99a38959a \
+ --hash=sha256:cb4c25a9d3410262216b5c7447e51bfd2de0efae0a7640772dc6d2a8741590de \
+ --hash=sha256:cbd09b22b340f846671e79e8d832167fac60c1884be4c71fd667211486a3b58e \
+ --hash=sha256:cd5422fd4f8a7859846c9289e310dd95c0d1890c31819667942753e510f88f69 \
+ --hash=sha256:d12571adb9ceeb9ba0640db46433430062f5f1dec89e39713a2a5a8ce3016c37 \
+ --hash=sha256:d1b7a3fe4cf679eb3870b91b86b8ce12cacd5cf4d74bc114864a5cd65319ddac \
+ --hash=sha256:d313494077f849d8199f36166947785da1eeb36335fda15fde2e8f801ef271b6 \
+ --hash=sha256:d3c9d5284d64f4c1015d95b751577b260fd6d14e3f8edf21710f4436e7ac4c49 \
+ --hash=sha256:d4e7ecaa25f0dae672ac783c2e5aa9054a62e011749d64ff47b887af360a3e82 \
+ --hash=sha256:d57f1b6affc3581fbf0bc6d783cc60e7c9957adfd9c7b89f8a9f3573ad1cd49a \
+ --hash=sha256:d8f85e019c9f08ec134648a378ddd3f6f073c1e4b5ce9bdacd9a9e7b60749cd2 \
+ --hash=sha256:d93403a13c8f6f2d027185d90ab695e81d95e3ebd000f0078e201a1c3159d4d1 \
+ --hash=sha256:da606e3015dbd4b9a31c0468898a0c4c998846197ddfda78308821dc8c9e9be3 \
+ --hash=sha256:db2eedef732424346f98d0aba5c6ad688b648bc79847f4cc70dfca830130b1e6 \
+ --hash=sha256:dbdd407104ebf2360464ce02c7933c6ffac58bd5b64cdf6ef7dc0e787e782aaf \
+ --hash=sha256:ddea089587432e3df6771a4a405ef249cc9727f7becb1de3f00ab571b2432002 \
+ --hash=sha256:dfbde696fb427301ec40cd82b8eec0b528e44c6af8239f33ede2b2552d9a085a \
+ --hash=sha256:e1cdbde56f9fa6d426b78941c381e2ba160c1214809baa47e02c1d0d8881d598 \
+ --hash=sha256:e282983b8def5ada758fa1f18bf9060bb8ce6cdd73be32f62a2de59820d3286d \
+ --hash=sha256:e34f591669498a03cd70993b0a79b9f0ef40c4e6f8232466bac33c42f0c15742 \
+ --hash=sha256:e405cce4170de1fe520d9a92de9d7ececc23dfcf6888c62ab608a21be50838eb \
+ --hash=sha256:e4a0f2adf29a69dd8fe58e42bb191f3c87067b05fcc63279983e8c9ce5092abd \
+ --hash=sha256:e4f85c34f9be32ec5568a0668fb8bc029d3e729285fb8fccc38695e185379a9b \
+ --hash=sha256:e5e4785d8a0adeadfbdf75f4efc357911842674651cbafd7e97f69b11ec3cbc6 \
+ --hash=sha256:e86a27ab632d2e888c22b79263864eaff8b7dea9e87328a9bb0ea04eff24786f \
+ --hash=sha256:ea880ae1a692ae694c11bca7be74864614ff1a58bdfff4605f36d1956b4b1588 \
+ --hash=sha256:ee9de080e8d6221bbe4ba2667367b1cee0f47a53f60ffc5e431b698cd2f2b214 \
+ --hash=sha256:ef8b925f2b331a1f17d6fb32625e09fd571cf41844f578379f934dab0067cf0d \
+ --hash=sha256:f06e257ee0cc85a7e4ec44f171ae2595fd901c34212f3c9e7ab8fd8621401e99 \
+ --hash=sha256:f1214052966421a88ed526ba93e4463b39346862fa4721be5306434b33dae795 \
+ --hash=sha256:f160f03e15bd1e3c35db9bfc20c42ff83155d37f9b0c79806cb10051ca725f13 \
+ --hash=sha256:f1b357340e4cd29011683bd81226175611ad835fec22e5b7df83b96701571226 \
+ --hash=sha256:f39290a0c2e3f4196563189bb45e6ef5d5badf50864e1bfaafa9003f0595573f \
+ --hash=sha256:f5a5c311e5de6954c36230a37863b5ca58ce232589bd637ad2881c4056897b12 \
+ --hash=sha256:f7a841170fde40b0e1345884bee09ceca7db49a9291fa340089bec66a366c243 \
+ --hash=sha256:f7fb9a3275f1a1528e542a0f5a3d2c89fcaf68e797fc5c6530434cbd92a852c4 \
+ --hash=sha256:fc540d1618c5638fcf5aea97060cf011467918b010bf682a84ecc0c9474e6cd0 \
+ --hash=sha256:fcb17f1d40c38912a2cdb56ea47aadac3527cd0b06fe24f3a0c4896febbea063 \
+ --hash=sha256:fd0341b9dea133d187d7c5a2cd7e21ae6449a7b68ea8c2454f9cf77def11ec1b
+ # via requests
+click==8.5.1 \
--hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37 \
--hash=sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4
# via uvicorn
@@ -192,6 +367,10 @@ cryptography==50.0.2 \
--hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb \
--hash=sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b
# via pyjwt
+googleapis-common-protos==1.76.0 \
+ --hash=sha256:59e13344a9f3651aa201a03e2bee815a3bf43a4baf1f9ff8a9b62a840ce25fac \
+ --hash=sha256:71db0e44a1d4c2dd024ebad44ca67129cc1e2892e4861df466764749d5ef8642
+ # via opentelemetry-exporter-otlp-proto-http
h11==0.16.0 \
--hash=sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1 \
--hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
@@ -226,6 +405,7 @@ idna==3.20 \
# anyio
# httpx
# httpx2
+ # requests
jsonschema==4.26.0 \
--hash=sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326 \
--hash=sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce
@@ -245,7 +425,57 @@ mcp-types==2.3.0 \
opentelemetry-api==1.45.2 \
--hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34 \
--hash=sha256:d7b0008e21e5fd61cbe7a7f34ca3b6905a78ab677d9bc395e299359c75cda6b4
- # via mcp
+ # via
+ # mcp
+ # opentelemetry-exporter-http-transport
+ # opentelemetry-exporter-otlp-proto-http
+ # opentelemetry-sdk
+ # opentelemetry-semantic-conventions
+opentelemetry-exporter-http-transport==0.66b2 \
+ --hash=sha256:66d6ed810a515432c8891da9a834464332fd70badeca45bdeeae81b4280c903b \
+ --hash=sha256:fd5f5b490c099acda1cd7b909d5e8981436bf18cc8c6098d302d114c271720e9
+ # via opentelemetry-exporter-otlp-proto-http
+opentelemetry-exporter-otlp-common==0.66b2 \
+ --hash=sha256:06f5a9b88638e310efa1f1d206cdf6b75393e112aba4e174a963416192bd1028 \
+ --hash=sha256:ace86efb75489f925f1ef809856ae5f0c7db534e4afdc624530222228b1236a5
+ # via opentelemetry-exporter-otlp-proto-http
+opentelemetry-exporter-otlp-proto-common==1.45.2 \
+ --hash=sha256:af483b24217028892f017096731b794b196b785025d2e6808874720fd0b05a80 \
+ --hash=sha256:f1f2806f3f28ce7938033823e50934fcd91595a39de38e69a28a51e19f40fc6d
+ # via opentelemetry-exporter-otlp-proto-http
+opentelemetry-exporter-otlp-proto-http==1.45.2 \
+ --hash=sha256:5984a3fb46bc4628e4e2b85d4a6e72637e03962aae6cf372791137768a4ad939 \
+ --hash=sha256:6e4d025138829d0ee57946930c2ccad6491ad4d92a958e9c7eea69278fe60cfc
+ # via -r requirements.txt
+opentelemetry-proto==1.45.2 \
+ --hash=sha256:03a7ca1b43f89fd5b965d5975902bb2515c0c86e2428b456836e9a6149c6235a \
+ --hash=sha256:bd8d23cf770605b0af9b7be2071d26a464fea289d35429abfd2a66226114ad64
+ # via
+ # opentelemetry-exporter-otlp-proto-common
+ # opentelemetry-exporter-otlp-proto-http
+opentelemetry-sdk==1.45.2 \
+ --hash=sha256:7eec4de13dd21ff3a1670dcb0e02079e692736f94d733dfdce5af461d884248d \
+ --hash=sha256:ff974ea70ee4f1d51e2ec152db37c2b626c7bf82bb3f7d86114fd8704e7199c6
+ # via
+ # -r requirements.txt
+ # opentelemetry-exporter-otlp-common
+ # opentelemetry-exporter-otlp-proto-http
+opentelemetry-semantic-conventions==0.66b2 \
+ --hash=sha256:4cbe61e5f9275d57ab31708446e7938ef4291ebbe6a7fca6f7a629c5acae87d8 \
+ --hash=sha256:7da5f1a5dc4383eb66711d4d3d3e71824d9403ac1559fea021cc103c1a4c4976
+ # via opentelemetry-sdk
+protobuf==7.36.2 \
+ --hash=sha256:497d0463ff3316681da6c0b9e8d06cb465d61abce00b613ab42226175644d1bb \
+ --hash=sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2 \
+ --hash=sha256:912c1221170e16c08d1f086762f563dd61ff83c18b5fa6652952dfaded66f728 \
+ --hash=sha256:a300819d441e078a5608c0d3c709796bb548136058fda017ae51d425b44fd353 \
+ --hash=sha256:bdb3a345d48db958e6ce1f18e508beb0cc981d64f24088427549c866cd039f1e \
+ --hash=sha256:cbc70b17ee27e28894c7fee8bb04be1abead49e936bc70eb60052531eee2079e \
+ --hash=sha256:e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e \
+ --hash=sha256:f4fee11ec330d238b34a05c9b675f693c20415d1c5bd7d5320cc2f8a798eb9cf
+ # via
+ # googleapis-common-protos
+ # opentelemetry-proto
pycparser==3.12 ; implementation_name != 'PyPy' and platform_python_implementation != 'PyPy' \
--hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e \
--hash=sha256:f03387877eab82ce01bbdfd0ba7252ee55a90b1c708d5129e2ce915475cf1db6
@@ -448,6 +678,13 @@ referencing==0.37.0 \
# via
# jsonschema
# jsonschema-specifications
+requests==2.34.2 \
+ --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0 \
+ --hash=sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed
+ # via
+ # -r requirements.txt
+ # opentelemetry-exporter-http-transport
+ # opentelemetry-exporter-otlp-proto-http
rpds-py==2026.9.1 \
--hash=sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25 \
--hash=sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68 \
@@ -604,6 +841,9 @@ typing-extensions==4.16.0 \
# mcp
# mcp-types
# opentelemetry-api
+ # opentelemetry-exporter-otlp-proto-http
+ # opentelemetry-sdk
+ # opentelemetry-semantic-conventions
# pydantic
# pydantic-core
# pydantic-settings
@@ -615,7 +855,13 @@ typing-inspection==0.4.5 \
# mcp
# pydantic
# pydantic-settings
-uvicorn==0.54.0 ; sys_platform != 'emscripten' \
+urllib3==2.8.0 \
+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
+ --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
+ # via requests
+uvicorn==0.54.0 \
--hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67faf \
--hash=sha256:a2e33cbfaa0306f8e6b0c13e0cb89d7d7a2da3e62b90c66e18c33d9807b28620
- # via mcp
+ # via
+ # -r requirements.txt
+ # mcp
diff --git a/mcp/requirements.txt b/mcp/requirements.txt
index 871e2e9f5..2c5d29e36 100644
--- a/mcp/requirements.txt
+++ b/mcp/requirements.txt
@@ -5,3 +5,8 @@ httpx>=0.28.1
PyJWT>=2.14.0,<3.0.0
pydantic-settings>=2.16.3
python-dotenv>=1.2.3
+# Keep the optional SSE log exporter on the backend's OTLP HTTP release.
+opentelemetry-sdk==1.45.2
+opentelemetry-exporter-otlp-proto-http==1.45.2
+requests==2.34.2
+uvicorn==0.54.0
diff --git a/mcp/server.py b/mcp/server.py
index ccc57b86f..0e41c5324 100644
--- a/mcp/server.py
+++ b/mcp/server.py
@@ -240,12 +240,22 @@ async def ready(_request): # noqa: ANN001
def sse_app():
"""The SSE ASGI app WITH this server's transport security (the tests and any embedding use this)."""
- return mcp.sse_app(transport_security=TRANSPORT_SECURITY, host=SSE_HOST)
+ app = mcp.sse_app(transport_security=TRANSPORT_SECURITY, host=SSE_HOST)
+ if settings.otlp_logs_endpoint:
+ from operational_logs import add_operational_logs
+
+ app = add_operational_logs(app, settings.otlp_logs_endpoint, settings.telemetry_environment)
+ return app
def run_sse(port: int) -> None:
"""Serve SSE on ``SSE_HOST:port`` WITH this server's transport security (the image's CMD)."""
- mcp.run(transport="sse", host=SSE_HOST, port=port, transport_security=TRANSPORT_SECURITY)
+ if settings.otlp_logs_endpoint:
+ import uvicorn
+
+ uvicorn.run(sse_app(), host=SSE_HOST, port=port, access_log=False)
+ else:
+ mcp.run(transport="sse", host=SSE_HOST, port=port, transport_security=TRANSPORT_SECURITY)
if __name__ == "__main__":
diff --git a/mcp/tests/test_operational_logs.py b/mcp/tests/test_operational_logs.py
new file mode 100644
index 000000000..fdb05ff39
--- /dev/null
+++ b/mcp/tests/test_operational_logs.py
@@ -0,0 +1,65 @@
+"""Verify SSE correlation without sending request payloads to an exporter."""
+
+import asyncio
+import hashlib
+import json
+import sys
+from pathlib import Path
+
+import httpx
+from starlette.responses import JSONResponse
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from operational_logs import add_operational_logs
+
+
+def test_mcp_operational_log_contains_only_correlation_and_response_metadata(monkeypatch) -> None:
+ import operational_logs
+
+ records = []
+
+ class Provider:
+ def __init__(self, *, resource):
+ assert resource.attributes["testlookup.service.role"] == "mcp"
+
+ def add_log_record_processor(self, processor):
+ pass
+
+ def get_logger(self, _scope):
+ return self
+
+ def emit(self, **record):
+ records.append(record)
+
+ monkeypatch.setattr(operational_logs, "LoggerProvider", Provider)
+ monkeypatch.setattr(operational_logs, "BatchLogRecordProcessor", lambda *_args, **_kwargs: object())
+ monkeypatch.setattr(operational_logs, "OTLPLogExporter", lambda **_kwargs: object())
+
+ async def asgi(scope, receive, send):
+ await JSONResponse({"ok": True})(scope, receive, send)
+
+ async def exercise():
+ app = add_operational_logs(asgi, "http://otel-collector:4318/v1/logs", "production")
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://fixture") as client:
+ request_id = "synthetic-opaque-id"
+ response = await client.post(
+ "/messages?argument=not-central",
+ headers={"X-Request-ID": request_id, "Authorization": "Bearer fixture-only"},
+ json={"prompt": "synthetic-payload"},
+ )
+ assert response.json() == {"ok": True}
+ assert response.headers["X-Request-ID"] == request_id
+ await client.get("/health/live")
+ assert len(records) == 1
+ record = records[0]
+ assert record["event_name"] == "mcp_request"
+ body = json.loads(record["body"])
+ assert set(body) == {"event", "request_id", "status_code", "duration_ms"}
+ assert body["request_id"] == hashlib.sha256(request_id.encode()).hexdigest()
+
+ asyncio.run(exercise())
+
+
+def test_remote_plaintext_mcp_endpoint_preserves_application() -> None:
+ app = object()
+ assert add_operational_logs(app, "http://fixture.example/v1/logs", "production") is app
diff --git a/scripts/license-allowlist.json b/scripts/license-allowlist.json
index b68251c5f..aecdbd95d 100644
--- a/scripts/license-allowlist.json
+++ b/scripts/license-allowlist.json
@@ -106,6 +106,7 @@
"pyyaml": "MIT",
"redis": "MIT",
"reportlab": "BSD-3-Clause",
+ "requests": "Apache-2.0",
"rich": "MIT",
"ruff": "MIT",
"scikit-learn": "BSD-3-Clause",
diff --git a/scripts/monitoring/tests/test_loki_reference.py b/scripts/monitoring/tests/test_loki_reference.py
new file mode 100644
index 000000000..961446123
--- /dev/null
+++ b/scripts/monitoring/tests/test_loki_reference.py
@@ -0,0 +1,273 @@
+"""Private Loki persistence and Grafana's provisioned log-query contract."""
+from __future__ import annotations
+
+from contextlib import ExitStack, contextmanager
+import base64
+import importlib.util
+import json
+import os
+from pathlib import Path
+import re
+import socket
+import subprocess
+import time
+from urllib.parse import urlencode
+from urllib.request import ProxyHandler, Request, build_opener
+import uuid
+
+import pytest
+import yaml
+
+ROOT = Path(__file__).resolve().parents[3]
+LOKI = ROOT / "infra/monitoring/loki"
+DATASOURCES = ROOT / "infra/monitoring/grafana/telemetry-datasources.yml"
+TRACE_ID = "0123456789abcdef0123456789abcdef"
+SPAN_ID = "0123456789abcdef"
+QUERY = '{service_namespace="testlookup"} | trace_id="' + TRACE_ID + '" | request_id="fixture-request"'
+HTTP = build_opener(ProxyHandler({}))
+
+
+def test_reference_limits_persist_all_state_and_do_not_index_ids():
+ config = yaml.safe_load((LOKI / "loki.yml").read_text())
+ limits = config["limits_config"]
+ assert config["auth_enabled"] is False # relies on the private Compose trust boundary
+ assert config["analytics"]["reporting_enabled"] is False
+ assert config["server"]["grpc_listen_address"] == "127.0.0.1"
+ assert config["common"]["replication_factor"] == 1
+ assert config["ingester"]["wal"]["enabled"] is True
+ assert config["ingester"]["wal"]["dir"] == "/loki/wal"
+ assert config["compactor"]["working_directory"] == "/loki/compactor"
+ assert config["compactor"]["retention_enabled"] is True
+ assert config["compactor"]["delete_request_store"] == "filesystem"
+ assert limits["retention_period"] == limits["max_query_lookback"] == "168h"
+ assert limits["deletion_mode"] == "disabled"
+ schema, = config["schema_config"]["configs"]
+ assert (schema["store"], schema["schema"], schema["object_store"], schema["index"]["period"]) == ("tsdb", "v13", "filesystem", "24h")
+ otlp = limits["otlp_config"]["resource_attributes"]
+ assert otlp["ignore_defaults"] is True
+ assert otlp["attributes_config"] == [{"action": "index_label", "attributes": [
+ "service.name", "service.namespace", "deployment.environment.name",
+ ]}]
+ assert limits["max_global_streams_per_user"] == 500
+ assert limits["max_entries_limit_per_query"] == 1000
+ assert limits["query_timeout"] == "30s"
+ assert limits["ingestion_rate_mb"] == 1 and limits["ingestion_burst_size_mb"] == 2
+ assert limits["max_line_size"] == "64KB" and limits["max_line_size_truncate"] is False
+ assert limits["max_structured_metadata_entries_count"] == 32
+
+
+def test_opt_in_datasource_replacement_preserves_uids_and_bidirectional_links():
+ config = yaml.safe_load(DATASOURCES.read_text())
+ sources = {source["name"]: source for source in config["datasources"]}
+ base = yaml.safe_load((ROOT / "infra/monitoring/grafana/provisioning/datasources/prometheus.yml").read_text())
+ assert sources["Prometheus"] == base["datasources"][0]
+ assert sources["Jaeger"]["uid"] == "jaeger" and sources["Loki"]["uid"] == "loki"
+ assert not DATASOURCES.is_relative_to(ROOT / "infra/monitoring/grafana/provisioning")
+ assert sources["Loki"]["url"] == "http://loki:3100"
+ assert sources["Jaeger"]["url"] == "http://jaeger:16686"
+ link = sources["Jaeger"]["jsonData"]["tracesToLogsV2"]
+ assert link["datasourceUid"] == "loki" and link["customQuery"] is True
+ assert link["query"] == '{service_namespace="testlookup"} | trace_id="$${__span.traceId}"'
+ derived, = sources["Loki"]["jsonData"]["derivedFields"]
+ assert derived["datasourceUid"] == "jaeger" and derived["url"] == "$${__value.raw}"
+ body = json.dumps({"event": "fixture_event", "trace_id": TRACE_ID, "span_id": SPAN_ID})
+ assert re.search(derived["matcherRegex"], body)[1] == TRACE_ID
+ assert re.search(derived["matcherRegex"], json.dumps({"trace_id": "malformed"})) is None
+
+
+def test_loki_image_has_an_immutable_upstream_and_verifiable_binary_pin():
+ lock = json.loads((LOKI / "image-lock.json").read_text())
+ assert re.fullmatch(r"docker.io/grafana/loki:3\.7\.10@sha256:[0-9a-f]{64}", lock["image"])
+ assert lock["image_user"] == "10001" and lock["bundle"] == "telemetry-external"
+ assert lock["digest_source"].startswith("https://registry-1.docker.io/v2/grafana/loki/manifests/")
+ for binary in lock["release_binaries"].values():
+ assert binary["url"].startswith("https://github.com/grafana/loki/releases/download/v3.7.10/")
+ assert re.fullmatch(r"[0-9a-f]{64}", binary["sha256"])
+
+
+def _port():
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ return listener.getsockname()[1]
+
+
+def _request(url, payload=None, headers=None):
+ body = json.dumps(payload).encode() if payload is not None else None
+ request = Request(url, data=body, headers={"Content-Type": "application/json", **(headers or {})})
+ with HTTP.open(request, timeout=10) as response:
+ data = response.read()
+ return json.loads(data) if data else None
+
+
+def _eventually(operation, process, timeout=45):
+ deadline = time.monotonic() + timeout
+ last_error = None
+ while time.monotonic() < deadline:
+ assert process.poll() is None, "reference process exited; inspect its scratch log"
+ try:
+ result = operation()
+ if result:
+ return result
+ except Exception as error:
+ last_error = error
+ time.sleep(0.1)
+ raise AssertionError(f"reference endpoint did not become available: {type(last_error).__name__}")
+
+
+def _stop(process, *, hard=False):
+ if process.poll() is None:
+ process.kill() if hard else process.terminate()
+ try:
+ process.wait(timeout=15)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=10)
+
+
+@contextmanager
+def _loki(tmp_path):
+ binary = os.environ["LOKI_TEST_BINARY"]
+ config = yaml.safe_load((LOKI / "loki.yml").read_text())
+ data = tmp_path / "loki-data"
+ data.mkdir()
+
+ def relocate(value):
+ if isinstance(value, dict):
+ return {key: relocate(item) for key, item in value.items()}
+ if isinstance(value, list):
+ return [relocate(item) for item in value]
+ return str(data) + value[len("/loki"):] if isinstance(value, str) and value.startswith("/loki") else value
+
+ config = relocate(config)
+ port = _port()
+ config["server"].update(http_listen_address="127.0.0.1", http_listen_port=port, grpc_listen_port=_port())
+ path = tmp_path / "loki.yml"
+ path.write_text(yaml.safe_dump(config), encoding="utf-8")
+ subprocess.run([binary, "-config.file=" + str(path), "-verify-config=true"], check=True, capture_output=True, timeout=30)
+ url = f"http://127.0.0.1:{port}"
+ with (tmp_path / "loki.log").open("ab") as output:
+ def start():
+ process = subprocess.Popen(
+ [binary, "-config.file=" + str(path)], stdout=output, stderr=output,
+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
+ )
+ # /ready is plain text; use the raw response instead of JSON parsing.
+ def ready():
+ with HTTP.open(url + "/ready", timeout=2) as response:
+ return response.status == 200
+ try:
+ _eventually(ready, process)
+ except BaseException:
+ _stop(process)
+ raise
+ return process
+
+ process = start()
+ try:
+ yield url, process, start
+ finally:
+ _stop(process)
+
+
+def _push(url):
+ body = json.dumps({"event": "fixture_event", "trace_id": TRACE_ID, "span_id": SPAN_ID, "request_id": "fixture-request"})
+ attributes = {"service.name": "testlookup", "service.namespace": "testlookup", "deployment.environment.name": "test", "testlookup.service.role": "worker", "service.instance.id": "fixture-instance"}
+ _request(url + "/otlp/v1/logs", {"resourceLogs": [{
+ "resource": {"attributes": [{"key": key, "value": {"stringValue": value}} for key, value in attributes.items()]},
+ "scopeLogs": [{"scope": {"name": "testlookup.fixture"}, "logRecords": [{
+ "timeUnixNano": str(time.time_ns()), "severityNumber": 9, "severityText": "INFO",
+ "traceId": TRACE_ID, "spanId": SPAN_ID, "body": {"stringValue": body},
+ "attributes": [{"key": "request_id", "value": {"stringValue": "fixture-request"}}],
+ }]}],
+ }]})
+
+
+def _query(url):
+ params = {"query": QUERY, "start": str(time.time_ns() - 120_000_000_000), "end": str(time.time_ns() + 1_000_000_000), "limit": "10"}
+ return _request(url + "/loki/api/v1/query_range?" + urlencode(params))["data"]["result"]
+
+
+@pytest.mark.skipif(not os.getenv("LOKI_TEST_BINARY"), reason="set checksum-verified LOKI_TEST_BINARY for real ingestion/restart")
+def test_actual_otlp_ingestion_metadata_query_and_wal_recovery(tmp_path):
+ with _loki(tmp_path) as (url, process, restart):
+ _push(url)
+ result = _eventually(lambda: _query(url), process)
+ assert json.loads(result[0]["values"][0][1])["trace_id"] == TRACE_ID
+ series = _request(url + "/loki/api/v1/series?" + urlencode({"match[]": '{service_namespace="testlookup"}'}))["data"]
+ assert series == [{"deployment_environment_name": "test", "service_name": "testlookup", "service_namespace": "testlookup"}]
+ assert any((tmp_path / "loki-data/wal").iterdir())
+ # No graceful flush: simulate child/container termination and recover
+ # the acknowledged log from the same volume's WAL after restart.
+ _stop(process, hard=True)
+ replacement = restart()
+ try:
+ recovered = _eventually(lambda: _query(url), replacement)
+ assert json.loads(recovered[0]["values"][0][1])["request_id"] == "fixture-request"
+ finally:
+ _stop(replacement)
+
+
+@pytest.mark.skipif(not (os.getenv("LOKI_TEST_BINARY") and os.getenv("GRAFANA_TEST_HOME")), reason="set pinned Loki binary and Grafana home for real datasource query")
+def test_actual_grafana_provisioning_macro_escaping_and_loki_query(tmp_path):
+ with _loki(tmp_path) as (loki_url, loki_process, _), ExitStack() as dependencies:
+ _push(loki_url)
+ _eventually(lambda: _query(loki_url), loki_process)
+ home = Path(os.environ["GRAFANA_TEST_HOME"])
+ binary = Path(os.getenv("GRAFANA_TEST_BINARY", str(home / "bin/grafana")))
+ provision = tmp_path / "provisioning/datasources"
+ provision.mkdir(parents=True)
+ config = yaml.safe_load(DATASOURCES.read_text())
+ next(d for d in config["datasources"] if d.get("uid") == "loki")["url"] = loki_url
+ if jaeger_binary := os.getenv("JAEGER_TEST_BINARY"):
+ spec = importlib.util.spec_from_file_location("jaeger_reference", ROOT / "scripts/ops/verify_jaeger_persistence.py")
+ assert spec is not None and spec.loader is not None
+ jaeger = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(jaeger)
+ jaeger_config = dependencies.enter_context(jaeger.running_jaeger(Path(jaeger_binary)))
+ jaeger._write(jaeger_config, trace_id=TRACE_ID, span_id=SPAN_ID)
+ next(d for d in config["datasources"] if d.get("uid") == "jaeger")["url"] = jaeger._url(jaeger_config, "query", "")
+ (provision / "prometheus.yml").write_text(yaml.safe_dump(config), encoding="utf-8")
+ port = _port()
+ password = uuid.uuid4().hex
+ env = os.environ | {
+ "GF_PATHS_DATA": str(tmp_path / "grafana-data"), "GF_PATHS_LOGS": str(tmp_path / "grafana-logs"),
+ "GF_PATHS_PLUGINS": str(tmp_path / "grafana-plugins"), "GF_PATHS_PROVISIONING": str(provision.parent),
+ "GF_SERVER_HTTP_ADDR": "127.0.0.1", "GF_SERVER_HTTP_PORT": str(port),
+ "GF_SECURITY_ADMIN_USER": "fixture", "GF_SECURITY_ADMIN_PASSWORD": password,
+ "GF_PLUGINS_PREINSTALL_DISABLED": "true", "GF_PLUGINS_PREINSTALL_AUTO_UPDATE": "false",
+ "GF_ANALYTICS_REPORTING_ENABLED": "false", "GF_ANALYTICS_CHECK_FOR_UPDATES": "false",
+ "GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES": "false", "GF_UNIFIED_ALERTING_ENABLED": "false",
+ "GF_FEATURE_TOGGLES_ENABLE": "jaegerEnableGrpcEndpoint",
+ }
+ headers = {"Authorization": "Basic " + base64.b64encode(("fixture:" + password).encode()).decode()}
+ url = f"http://127.0.0.1:{port}"
+ with (tmp_path / "grafana.log").open("wb") as output:
+ grafana = subprocess.Popen(
+ [str(binary), "server", "--homepath", str(home)], env=env, stdout=output, stderr=output,
+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
+ )
+ try:
+ _eventually(lambda: _request(url + "/api/health"), grafana, timeout=60)
+ jaeger = _request(url + "/api/datasources/uid/jaeger", headers=headers)
+ loki = _request(url + "/api/datasources/uid/loki", headers=headers)
+ assert jaeger["jsonData"]["tracesToLogsV2"]["query"] == '{service_namespace="testlookup"} | trace_id="${__span.traceId}"'
+ assert loki["jsonData"]["derivedFields"][0]["url"] == "${__value.raw}"
+ assert _request(url + "/api/datasources/uid/loki/health", headers=headers)["status"] == "OK"
+ payload = {"from": str(int(time.time() * 1000) - 120000), "to": str(int(time.time() * 1000)), "queries": [{
+ "refId": "A", "datasource": {"type": "loki", "uid": "loki"}, "expr": QUERY,
+ "queryType": "range", "maxLines": 10, "intervalMs": 1000, "maxDataPoints": 100,
+ }]}
+ result = _request(url + "/api/ds/query", payload, headers)
+ assert result["results"]["A"].get("status", 200) == 200
+ assert TRACE_ID in json.dumps(result) and "fixture-request" in json.dumps(result)
+ if jaeger_binary:
+ assert _request(url + "/api/datasources/uid/jaeger/health", headers=headers)["status"] == "OK"
+ trace_query = {**payload, "queries": [{
+ "refId": "T", "datasource": {"type": "jaeger", "uid": "jaeger"},
+ "query": TRACE_ID, "queryType": "",
+ }]}
+ trace = _request(url + "/api/ds/query", trace_query, headers)
+ assert trace["results"]["T"].get("status", 200) == 200
+ assert TRACE_ID in json.dumps(trace)
+ finally:
+ _stop(grafana)
diff --git a/scripts/monitoring/tests/test_otel_collector.py b/scripts/monitoring/tests/test_otel_collector.py
new file mode 100644
index 000000000..55af847ba
--- /dev/null
+++ b/scripts/monitoring/tests/test_otel_collector.py
@@ -0,0 +1,326 @@
+"""Validate the pinned collector and its real local durable export boundary."""
+from __future__ import annotations
+
+from contextlib import ExitStack, contextmanager
+import gzip
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import importlib.util
+import os
+from pathlib import Path
+import socket
+import subprocess
+import threading
+import time
+from urllib.error import HTTPError
+from urllib.parse import urlencode
+from urllib.request import ProxyHandler, Request, build_opener
+
+import pytest
+import yaml
+
+ROOT = Path(__file__).resolve().parents[3]
+CONFIG = ROOT / "infra/monitoring/otel-collector/config.yml"
+BINARY = os.environ.get("OTELCOL_TEST_BINARY")
+
+
+def test_collector_has_only_scoped_otlp_input_and_two_bounded_persistent_exports():
+ config = yaml.safe_load(CONFIG.read_text())
+ assert set(config["receivers"]) == {"otlp"}
+ assert set(config["receivers"]["otlp"]["protocols"]) == {"http"}
+ assert config["receivers"]["otlp"]["protocols"]["http"]["max_request_body_size"] == 1048576
+ assert set(config["service"]["pipelines"]) == {"logs", "traces"}
+ assert "debug" not in config["exporters"]
+ storage = config["extensions"]["file_storage"]
+ assert storage["fsync"] is True and storage["max_size"] == 64 * 1024 * 1024
+ for pipeline in config["service"]["pipelines"].values():
+ assert pipeline["processors"] == ["memory_limiter", "filter/identity", "transform/privacy"]
+ exporter = config["exporters"][pipeline["exporters"][0]]
+ queue = exporter["sending_queue"]
+ assert queue["storage"] == "file_storage"
+ assert queue["sizer"] == "bytes" and queue["queue_size"] == 32 * 1024 * 1024
+ assert queue["block_on_overflow"] is False and queue["wait_for_result"] is False
+ assert queue["batch"]["max_size"] == 65536
+ assert exporter["retry_on_failure"]["max_elapsed_time"] == "10m"
+ image = json.loads((CONFIG.parent / "image-lock.json").read_text())
+ assert "@sha256:" in image["image"] and image["user"] == "10001:10001"
+
+
+@pytest.mark.skipif(not BINARY, reason="requires checksum-verified pinned Collector Contrib binary")
+def test_pinned_collector_validates_checked_in_configuration():
+ result = subprocess.run([BINARY, "validate", "--config", str(CONFIG)], capture_output=True, text=True, timeout=20)
+ assert result.returncode == 0, result.stderr
+
+
+def _port():
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ return listener.getsockname()[1]
+
+
+def _eventually(check, timeout=15):
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ value = check()
+ if value:
+ return value
+ time.sleep(0.05)
+ raise AssertionError("Disposable collector condition did not become true before its deadline")
+
+
+@contextmanager
+def _collector(tmp_path, *, retry_lifetime="30s", destinations=None):
+ logs_pb = pytest.importorskip("opentelemetry.proto.collector.logs.v1.logs_service_pb2")
+ traces_pb = pytest.importorskip("opentelemetry.proto.collector.trace.v1.trace_service_pb2")
+ state = {"failed": True, "failed_attempts": 0, "received": []}
+ lock = threading.Lock()
+
+ class Sink(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ payload = self.rfile.read(int(self.headers["Content-Length"]))
+ if self.headers.get("Content-Encoding") == "gzip":
+ payload = gzip.decompress(payload)
+ message = logs_pb.ExportLogsServiceRequest() if self.path.endswith("/logs") else traces_pb.ExportTraceServiceRequest()
+ message.ParseFromString(payload)
+ with lock:
+ failed = state["failed"]
+ if failed:
+ state["failed_attempts"] += 1
+ if not failed:
+ state["received"].append(message)
+ self.send_response(503 if failed else 200)
+ self.send_header("Content-Type", "application/x-protobuf")
+ self.end_headers()
+
+ sink = ThreadingHTTPServer(("127.0.0.1", 0), Sink)
+ thread = threading.Thread(target=sink.serve_forever, daemon=True)
+ thread.start()
+ config = yaml.safe_load(CONFIG.read_text())
+ otlp_port, health_port, metrics_port = _port(), _port(), _port()
+ config["receivers"]["otlp"]["protocols"]["http"]["endpoint"] = f"127.0.0.1:{otlp_port}"
+ config["extensions"]["health_check"]["endpoint"] = f"127.0.0.1:{health_port}"
+ storage = config["extensions"]["file_storage"]
+ storage["directory"] = str(tmp_path / "spool")
+ storage["compaction"]["directory"] = str(tmp_path / "compaction")
+ metrics = config["service"]["telemetry"]["metrics"]["readers"][0]["pull"]["exporter"]["prometheus"]
+ metrics.update(host="127.0.0.1", port=metrics_port)
+ for name, exporter in config["exporters"].items():
+ exporter["endpoint"] = (destinations or {}).get(name, f"http://127.0.0.1:{sink.server_port}")
+ exporter["timeout"] = "200ms"
+ exporter["retry_on_failure"].update(initial_interval="200ms", max_interval="1s", max_elapsed_time=retry_lifetime)
+ exporter["sending_queue"].update(queue_size=4096, num_consumers=1)
+ exporter["sending_queue"]["batch"].update(min_size=1, max_size=1024, flush_timeout="50ms")
+ output = tmp_path / "config.yml"
+ output.write_text(yaml.safe_dump(config))
+ opener = build_opener(ProxyHandler({}))
+ process = None
+ handle = None
+
+ def get(port, path):
+ with opener.open(f"http://127.0.0.1:{port}" + path, timeout=1) as response:
+ return response.read().decode()
+
+ def start():
+ nonlocal process, handle
+ handle = (tmp_path / "collector.log").open("ab")
+ process = subprocess.Popen([BINARY, "--config", str(output)], stdout=handle, stderr=subprocess.STDOUT)
+
+ def ready():
+ if process.poll() is not None:
+ raise AssertionError((tmp_path / "collector.log").read_text(errors="replace")[-5000:])
+ try:
+ return get(health_port, "/")
+ except OSError:
+ return False
+ _eventually(ready)
+
+ def kill():
+ nonlocal process, handle
+ if process is not None:
+ process.kill() # Deliberately ungraceful, exercising durable replay.
+ process.wait(timeout=5)
+ process = None
+ if handle is not None:
+ handle.close()
+ handle = None
+
+ def post(signal, payload):
+ request = Request(f"http://127.0.0.1:{otlp_port}/v1/{signal}", data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"})
+ try:
+ with opener.open(request, timeout=2) as response:
+ return response.status
+ except HTTPError as error:
+ return error.code
+
+ try:
+ start()
+ yield state, lock, post, lambda: get(metrics_port, "/metrics"), kill, start
+ finally:
+ kill()
+ sink.shutdown()
+ sink.server_close()
+ thread.join(timeout=2)
+
+
+def _attribute(key, value):
+ return {"key": key, "value": {"stringValue": value}}
+
+
+def _resource():
+ return {"attributes": [_attribute("service.name", "testlookup"), _attribute("service.namespace", "testlookup"),
+ _attribute("deployment.environment.name", "test"),
+ _attribute("testlookup.service.role", "api"), _attribute("private.payload", "synthetic-private-canary")]}
+
+
+def _logs(identifier, *, event="http_request"):
+ return {"resourceLogs": [{"resource": _resource(), "scopeLogs": [{"scope": {"name": "synthetic"}, "logRecords": [{
+ "timeUnixNano": str(time.time_ns()), "traceId": f"{identifier:032x}", "spanId": f"{identifier:016x}",
+ "eventName": event, "severityText": "INFO", "severityNumber": 9,
+ "body": {"stringValue": "synthetic-private-canary"},
+ "attributes": [_attribute("request_id", "a" * 64), _attribute("celery_task_id", "raw-private-id"),
+ _attribute("private.payload", "synthetic-private-canary")],
+ }]}]}]}
+
+
+def _traces(identifier):
+ now = time.time_ns()
+ return {"resourceSpans": [{"resource": _resource(), "scopeSpans": [{"scope": {"name": "synthetic"}, "spans": [{
+ "traceId": f"{identifier:032x}", "spanId": f"{identifier:016x}", "name": "synthetic.operation", "kind": 2,
+ "startTimeUnixNano": str(now), "endTimeUnixNano": str(now + 1000),
+ "attributes": [_attribute("http.route", "/health"), _attribute("http.request.body", "synthetic-private-canary")],
+ "status": {"code": 2, "message": "synthetic-private-canary"},
+ "events": [{"timeUnixNano": str(now), "name": "synthetic-private-canary", "attributes": [_attribute("payload", "synthetic-private-canary")]}],
+ # Links rely on the application's full export-boundary sanitization;
+ # the Collector preserves that already-sanitized causal relationship.
+ "links": [{"traceId": "f" * 32, "spanId": "f" * 16}],
+ }]}]}]}
+
+
+def _metric_values(text, prefix):
+ return [float(line.rsplit(" ", 1)[1]) for line in text.splitlines() if line.startswith(prefix) and not line.startswith("#")]
+
+
+@pytest.mark.skipif(not BINARY, reason="requires checksum-verified pinned Collector Contrib binary")
+def test_real_queue_overflow_privacy_and_recovery_after_abrupt_restart(tmp_path):
+ expected_logs, expected_traces = set(), set()
+ with _collector(tmp_path) as (state, lock, post, metrics, kill, start):
+ assert post("logs", _logs(9999, event="unapproved_private_event")) == 200
+ rejected = []
+ began = time.monotonic()
+ for index in range(1, 50):
+ for signal, payload, expected in (("logs", _logs(index), expected_logs), ("traces", _traces(index), expected_traces)):
+ status = post(signal, payload)
+ if status == 200:
+ expected.add(index)
+ else:
+ assert status in (429, 500, 503)
+ rejected.append((signal, index))
+ assert time.monotonic() - began < 15 # Full queues refuse; the producer is not held indefinitely.
+ assert expected_logs and expected_traces and rejected
+ _eventually(lambda: sum(_metric_values(metrics(), "otelcol_exporter_enqueue_failed_")) > 0)
+ observed = metrics()
+ sizes = _metric_values(observed, "otelcol_exporter_queue_size")
+ capacities = _metric_values(observed, "otelcol_exporter_queue_capacity")
+ assert sizes and max(sizes) <= 4096 and capacities and set(capacities) == {4096.0}
+ # Failed attempts still retrying are not terminal send_failed metrics.
+ _eventually(lambda: state["failed_attempts"] > 0)
+ kill()
+ spool_files = [path for path in (tmp_path / "spool").rglob("*") if path.is_file()]
+ assert spool_files and all(b"synthetic-private-canary" not in path.read_bytes() for path in spool_files)
+ with lock:
+ state["failed"] = False
+ start()
+
+ def recovered():
+ seen_logs, seen_traces = set(), set()
+ with lock:
+ messages = list(state["received"])
+ for message in messages:
+ assert "synthetic-private-canary" not in str(message)
+ if hasattr(message, "resource_logs"):
+ for resource in message.resource_logs:
+ for scope in resource.scope_logs:
+ for record in scope.log_records:
+ seen_logs.add(int.from_bytes(record.trace_id, "big"))
+ body = json.loads(record.body.string_value)
+ assert body["event"] == "http_request" and body["request_id"] == "a" * 64
+ assert "celery_task_id" not in body
+ assert body["trace_id"] == record.trace_id.hex()
+ else:
+ for resource in message.resource_spans:
+ for scope in resource.scope_spans:
+ for span in scope.spans:
+ seen_traces.add(int.from_bytes(span.trace_id, "big"))
+ assert len(span.links) == 1 and not span.status.message
+ assert 9999 not in seen_logs
+ return expected_logs <= seen_logs and expected_traces <= seen_traces
+ _eventually(recovered)
+
+
+@pytest.mark.skipif(not BINARY, reason="requires checksum-verified pinned Collector Contrib binary")
+def test_real_retry_exhaustion_exposes_terminal_loss(tmp_path):
+ with _collector(tmp_path, retry_lifetime="2s") as (state, lock, post, metrics, kill, start):
+ assert post("logs", _logs(1)) == 200
+ assert post("traces", _traces(1)) == 200
+ _eventually(lambda: sum(_metric_values(metrics(), "otelcol_exporter_send_failed_log_records")) > 0)
+ _eventually(lambda: sum(_metric_values(metrics(), "otelcol_exporter_send_failed_spans")) > 0)
+ assert state["failed_attempts"] > 0 and not state["received"]
+
+
+def _module(name, path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ assert spec.loader is not None
+ spec.loader.exec_module(module)
+ return module
+
+
+@pytest.mark.skipif(not (BINARY and os.environ.get("LOKI_TEST_BINARY") and os.environ.get("JAEGER_TEST_BINARY")), reason="requires checksum-verified Collector, Loki and Jaeger binaries")
+def test_real_collector_to_both_reference_stores_and_same_id_readback(tmp_path):
+ loki = _module("collector_loki_fixture", ROOT / "scripts/monitoring/tests/test_loki_reference.py")
+ jaeger = _module("collector_jaeger_fixture", ROOT / "scripts/ops/verify_jaeger_persistence.py")
+ (tmp_path / "loki").mkdir()
+ (tmp_path / "collector").mkdir()
+ with ExitStack() as stack:
+ logs_url, loki_process, _ = stack.enter_context(loki._loki(tmp_path / "loki"))
+ trace_config = stack.enter_context(jaeger.running_jaeger(Path(os.environ["JAEGER_TEST_BINARY"])))
+ destinations = {"otlp_http/logs": logs_url + "/otlp", "otlp_http/traces": jaeger._url(trace_config, "ingest", "")}
+ _, _, post, _, kill, start = stack.enter_context(_collector(tmp_path / "collector", destinations=destinations))
+
+ def joint_trace_id(identifier):
+ # Jaeger's legacy JSON renders all-zero high bits as a 64-bit ID.
+ # Use full 128-bit IDs for an exact cross-store string comparison.
+ return "1122334455667788" + f"{identifier:016x}"
+
+ def read_log(identifier):
+ trace_id = joint_trace_id(identifier)
+ query = '{service_namespace="testlookup"} | trace_id="' + trace_id + '" | request_id="' + "a" * 64 + '"'
+ parameters = {"query": query, "start": str(time.time_ns() - 120_000_000_000), "end": str(time.time_ns() + 1_000_000_000), "limit": "10"}
+ response = loki._request(logs_url + "/loki/api/v1/query_range?" + urlencode(parameters))
+ results = response["data"]["result"]
+ if not results:
+ return False
+ # Query results may promote filtered structured metadata into the
+ # returned stream. The series API proves what is actually indexed.
+ series = loki._request(logs_url + "/loki/api/v1/series?" + urlencode({"match[]": '{service_namespace="testlookup"}'}))["data"]
+ assert series == [{"deployment_environment_name": "test", "service_name": "testlookup", "service_namespace": "testlookup"}]
+ body = json.loads(results[0]["values"][0][1])
+ assert body["trace_id"] == trace_id and body["event"] == "http_request"
+ assert "synthetic-private-canary" not in json.dumps(response)
+ return True
+
+ for identifier in (101, 102):
+ traces, logs = _traces(identifier), _logs(identifier)
+ traces["resourceSpans"][0]["scopeSpans"][0]["spans"][0]["traceId"] = joint_trace_id(identifier)
+ logs["resourceLogs"][0]["scopeLogs"][0]["logRecords"][0]["traceId"] = joint_trace_id(identifier)
+ assert post("traces", traces) == 200
+ assert post("logs", logs) == 200
+ _eventually(lambda: jaeger._contains_trace(trace_config, joint_trace_id(identifier)))
+ _eventually(lambda: read_log(identifier))
+ assert loki_process.poll() is None
+ if identifier == 101:
+ kill()
+ start()
diff --git a/scripts/monitoring/tests/test_telemetry_profile.py b/scripts/monitoring/tests/test_telemetry_profile.py
new file mode 100644
index 000000000..0594deac4
--- /dev/null
+++ b/scripts/monitoring/tests/test_telemetry_profile.py
@@ -0,0 +1,68 @@
+"""The optional Compose profile isolates its privileged telemetry endpoints."""
+
+import json
+import os
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[3]
+
+
+@pytest.mark.parametrize("base", ["docker-compose.yml", "docker-compose.release.yml"])
+def test_compose_durable_and_authentication_overlays_are_compatible(base):
+ if shutil.which("docker") is None:
+ pytest.skip("Docker Compose renderer is unavailable")
+ version = subprocess.run(["docker", "compose", "version"], capture_output=True, timeout=30)
+ if version.returncode != 0:
+ pytest.skip("Docker Compose renderer is unavailable")
+ placeholders = {
+ name: "fixture-only"
+ for name in (
+ "GF_SECURITY_ADMIN_PASSWORD", "POSTGRES_PASSWORD", "MONGO_PASSWORD",
+ "MINIO_ACCESS_KEY", "MINIO_SECRET_KEY", "MINIO_ROOT_USER",
+ "MINIO_ROOT_PASSWORD", "FLOWER_PASSWORD", "REDIS_PASSWORD",
+ )
+ }
+ paths = {
+ name: "./fixture-only"
+ for name in (
+ "METRICS_API_TOKEN_SOURCE", "METRICS_PROMETHEUS_TOKEN_SOURCE",
+ "ALERTING_PROMETHEUS_CONFIG_SOURCE", "ALERTMANAGER_INCIDENT_URL_SOURCE",
+ "ALERTMANAGER_INCIDENT_TOKEN_SOURCE", "ALERTMANAGER_WATCHDOG_URL_SOURCE",
+ "ALERTMANAGER_WATCHDOG_TOKEN_SOURCE",
+ )
+ }
+ command = [
+ "docker", "compose", "-f", base, "-f", "docker-compose.monitoring.yml",
+ "-f", "docker-compose.telemetry.yml", "-f", "docker-compose.alerting.yml",
+ "-f", "docker-compose.monitoring-auth.yml", "config", "--no-env-resolution",
+ "--format", "json",
+ ]
+ rendered = subprocess.run(
+ command, cwd=ROOT, env={**os.environ, **placeholders, **paths}, capture_output=True,
+ text=True, timeout=45, check=True,
+ )
+ project = json.loads(rendered.stdout)
+ services = project["services"]
+ for name in ("otel-collector", "jaeger", "loki"):
+ service = services[name]
+ assert not service.get("ports")
+ assert service["user"] == "10001:10001"
+ assert service["read_only"]
+ for name in ("otel-collector", "jaeger", "loki", "telemetry-volume-init"):
+ for app in ("backend", "worker", "worker-children", "mcp"):
+ assert name not in services[app].get("depends_on", {})
+ assert set(services["jaeger"]["networks"]) == {"telemetry_storage"}
+ assert set(services["loki"]["networks"]) == {"telemetry_storage"}
+ assert set(services["otel-collector"]["networks"]) == {
+ "telemetry_storage", "telemetry_ingress", "telemetry_metrics",
+ }
+ assert all(project["networks"][name]["internal"] for name in services["otel-collector"]["networks"])
+ assert services["backend"]["environment"]["OTEL_EXPORTER_OTLP_ENDPOINT"] == "http://otel-collector:4318"
+ assert services["backend"]["environment"]["METRICS_TOKEN_FILE"] == "/run/secrets/testlookup-metrics-token"
+ assert services["grafana"]["environment"]["GF_FEATURE_TOGGLES_ENABLE"] == "jaegerEnableGrpcEndpoint"
+ assert services["telemetry-volume-init"]["network_mode"] == "none"
diff --git a/scripts/ops/verify_jaeger_persistence.py b/scripts/ops/verify_jaeger_persistence.py
new file mode 100644
index 000000000..c9240b100
--- /dev/null
+++ b/scripts/ops/verify_jaeger_persistence.py
@@ -0,0 +1,266 @@
+"""Prove pinned Jaeger persistence/TTL with synthetic spans on loopback only.
+
+Supply a checksum-verified Jaeger 2.23.0 release executable. The verifier
+derives a private test config from the production reference, changes only
+storage paths/listen addresses, and starts no container or live deployment.
+All data and logs live in a temporary directory and contain synthetic data.
+"""
+from __future__ import annotations
+
+import argparse
+from contextlib import contextmanager
+from copy import deepcopy
+from datetime import datetime, timedelta, timezone
+import json
+import os
+from pathlib import Path
+import socket
+import subprocess
+import tempfile
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+import yaml
+
+VERSION = "v2.23.0"
+COMMIT = "d723f91447f29a345c288f37eb8d1ce7807bc0be"
+DEFAULT_CONFIG = Path(__file__).resolve().parents[2] / "infra/monitoring/jaeger.yml"
+_HTTP = urllib.request.build_opener(urllib.request.ProxyHandler({}))
+_TRACE_ID = "1" * 32
+_SPAN_ID = "2" * 16
+_SERVICE = "testlookup-jaeger-persistence-probe"
+
+
+def _port() -> int:
+ with socket.socket() as listener:
+ listener.bind(("127.0.0.1", 0))
+ return listener.getsockname()[1]
+
+
+def local_config(source: dict, directory: Path, *, ttl: str | None = None) -> dict:
+ """Keep the production pipeline/storage contract; isolate local test I/O."""
+ config = deepcopy(source)
+ storage = config["extensions"]["jaeger_storage"]["backends"]["incident_traces"]["badger"]
+ storage["directories"] = {
+ "keys": str(directory / "keys"), "values": str(directory / "values"),
+ }
+ if ttl is not None:
+ storage["ttl"]["spans"] = ttl
+ config["extensions"]["jaeger_query"]["http"]["endpoint"] = f"127.0.0.1:{_port()}"
+ config["extensions"]["jaeger_query"]["grpc"]["endpoint"] = f"127.0.0.1:{_port()}"
+ config["extensions"]["healthcheckv2"]["http"]["endpoint"] = f"127.0.0.1:{_port()}"
+ config["receivers"]["otlp"]["protocols"]["http"]["endpoint"] = f"127.0.0.1:{_port()}"
+ prometheus = config["service"]["telemetry"]["metrics"]["readers"][0]["pull"]["exporter"]["prometheus"]
+ prometheus.update(host="127.0.0.1", port=_port())
+ return config
+
+
+def _url(config: dict, surface: str, path: str) -> str:
+ if surface == "query":
+ address = config["extensions"]["jaeger_query"]["http"]["endpoint"]
+ elif surface == "health":
+ address = config["extensions"]["healthcheckv2"]["http"]["endpoint"]
+ else:
+ address = config["receivers"]["otlp"]["protocols"]["http"]["endpoint"]
+ return f"http://{address}{path}"
+
+
+def _request(url: str, payload: dict | None = None) -> tuple[int, bytes]:
+ request = urllib.request.Request(
+ url, data=None if payload is None else json.dumps(payload).encode(),
+ headers={"Content-Type": "application/json"},
+ )
+ try:
+ response = _HTTP.open(request, timeout=2)
+ except urllib.error.HTTPError as exc:
+ response = exc
+ with response:
+ body = response.read(1_048_577)
+ if len(body) > 1_048_576:
+ raise RuntimeError("synthetic Jaeger response exceeded proof budget")
+ return response.code, body
+
+
+def _span(trace_id: str = _TRACE_ID, span_id: str = _SPAN_ID) -> dict:
+ now = time.time_ns()
+ return {"resourceSpans": [{
+ "resource": {"attributes": [
+ {"key": "service.name", "value": {"stringValue": _SERVICE}},
+ {"key": "service.namespace", "value": {"stringValue": "testlookup"}},
+ ]},
+ "scopeSpans": [{"scope": {"name": "testlookup.persistence.probe"}, "spans": [{
+ "traceId": trace_id, "spanId": span_id, "name": "synthetic-restart-proof",
+ "kind": 1, "startTimeUnixNano": str(now), "endTimeUnixNano": str(now + 1_000_000),
+ }]}],
+ }]}
+
+
+def _contains_trace(config: dict, trace_id: str = _TRACE_ID) -> bool:
+ status, body = _request(_url(config, "query", f"/api/traces/{trace_id}"))
+ if status == 404:
+ return False
+ if status != 200:
+ raise RuntimeError(f"synthetic Jaeger trace query returned HTTP {status}")
+ data = json.loads(body).get("data") or []
+ return any(trace.get("traceID") == trace_id and trace.get("spans") for trace in data)
+
+
+def _wait_for(check, *, seconds: float, description: str) -> None:
+ deadline = time.monotonic() + seconds
+ while True:
+ try:
+ if check():
+ return
+ except (OSError, urllib.error.URLError):
+ pass
+ if time.monotonic() >= deadline:
+ raise RuntimeError(f"timed out waiting for synthetic {description}")
+ time.sleep(0.05)
+
+
+def _start(binary: Path, config: dict, root: Path):
+ config_path = root / "jaeger-test.yml"
+ config_path.write_text(yaml.safe_dump(config), encoding="utf-8")
+ log = (root / "jaeger.log").open("ab")
+ process = subprocess.Popen(
+ [str(binary), f"--config={config_path}"], cwd=root,
+ stdin=subprocess.DEVNULL, stdout=log, stderr=log,
+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
+ )
+
+ def ready():
+ if process.poll() is not None:
+ raise RuntimeError("synthetic Jaeger process exited before readiness")
+ status, _ = _request(_url(config, "health", "/status"))
+ return status == 200
+
+ try:
+ _wait_for(ready, seconds=20, description="Jaeger readiness")
+ except BaseException:
+ _stop(process)
+ log.close()
+ raise
+ return process, log
+
+
+def _stop(process, *, crash: bool = False) -> None:
+ if process.poll() is None:
+ process.kill() if crash else process.terminate()
+ try:
+ process.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=10)
+
+
+def _write(config: dict, trace_id: str = _TRACE_ID, span_id: str = _SPAN_ID) -> None:
+ status, body = _request(_url(config, "ingest", "/v1/traces"), _span(trace_id, span_id))
+ if status != 200:
+ raise RuntimeError(f"synthetic Jaeger OTLP write returned HTTP {status}")
+ result = json.loads(body or b"{}")
+ if int(result.get("partialSuccess", {}).get("rejectedSpans", 0)):
+ raise RuntimeError("synthetic Jaeger OTLP write rejected spans")
+ _wait_for(lambda: _contains_trace(config, trace_id), seconds=5, description="trace readback")
+
+
+@contextmanager
+def running_jaeger(binary: Path, *, config_path: Path = DEFAULT_CONFIG):
+ """Local integration fixture for a separately verified release executable.
+
+ The caller may emit a matching synthetic log/trace ID and point an isolated
+ Grafana at ``_url(config, "query", "")``. No deployment ports are used.
+ """
+ source = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+ with tempfile.TemporaryDirectory(prefix="testlookup-jaeger-integration-") as temporary:
+ root = Path(temporary)
+ config = local_config(source, root / "data")
+ process, log = _start(binary.resolve(strict=True), config, root)
+ try:
+ yield config
+ finally:
+ _stop(process)
+ log.close()
+
+
+def prove(binary: Path, *, config_path: Path = DEFAULT_CONFIG) -> dict:
+ binary = binary.resolve(strict=True)
+ version = subprocess.run([str(binary), "version"], capture_output=True, text=True, check=True, timeout=15)
+ identity = json.loads(version.stdout)
+ if identity.get("gitVersion") != VERSION or identity.get("gitCommit") != COMMIT:
+ raise RuntimeError("Jaeger executable does not match the pinned release identity")
+ subprocess.run([str(binary), "validate", f"--config={config_path.resolve()}"],
+ capture_output=True, check=True, timeout=15)
+ source = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+ with tempfile.TemporaryDirectory(prefix="testlookup-jaeger-proof-") as temporary:
+ root = Path(temporary)
+ config = local_config(source, root / "persistent")
+ process, log = _start(binary, config, root)
+ try:
+ _write(config)
+ # The acknowledgement precedes forced loss; there is no graceful
+ # shutdown flush and no replay by the test producer.
+ _stop(process, crash=True)
+ finally:
+ _stop(process)
+ log.close()
+ process, log = _start(binary, config, root)
+ try:
+ if not _contains_trace(config):
+ raise RuntimeError("acknowledged synthetic trace was lost after forced restart")
+ services_status, services_body = _request(_url(config, "query", "/api/v3/services"))
+ if services_status != 200 or _SERVICE not in json.loads(services_body).get("services", []):
+ raise RuntimeError("Jaeger native service discovery did not retain the synthetic service")
+ status, body = _request(_url(config, "query", f"/api/v3/traces/{_TRACE_ID}"))
+ if status != 200 or not json.loads(body).get("result", {}).get("resourceSpans"):
+ raise RuntimeError("Jaeger v3 trace-ID query failed")
+ now = datetime.now(timezone.utc)
+ query = urllib.parse.urlencode({
+ "query.service_name": _SERVICE,
+ "query.start_time_min": (now - timedelta(minutes=1)).isoformat(),
+ "query.start_time_max": (now + timedelta(minutes=1)).isoformat(),
+ "query.search_depth": 20,
+ })
+ status, body = _request(_url(config, "query", f"/api/v3/trace-summaries?{query}"))
+ if status != 200 or not json.loads(body).get("summaries"):
+ raise RuntimeError("Jaeger native trace search did not find the retained trace")
+ # Grafana Jaeger 13.0.8 still routes Search to the removed legacy
+ # endpoint even with jaegerEnableGrpcEndpoint. Record that boundary
+ # explicitly; native UI discovery/search and trace-ID links work.
+ legacy_search_status, _ = _request(_url(config, "query", f"/api/traces?service={_SERVICE}"))
+ _write(config, "3" * 32, "4" * 16)
+ data_bytes = sum(path.stat().st_size for path in (root / "persistent").rglob("*") if path.is_file())
+ finally:
+ _stop(process)
+ log.close()
+
+ # A short TTL is a separate disposable store. Physical reclamation
+ # remains asynchronous; this proves read expiry, not a disk quota.
+ config = local_config(source, root / "expiry", ttl="3s")
+ process, log = _start(binary, config, root)
+ try:
+ _write(config)
+ _wait_for(lambda: not _contains_trace(config), seconds=10, description="trace TTL expiry")
+ finally:
+ _stop(process)
+ log.close()
+ return {
+ "version": VERSION, "forced_restart_retained_trace": True,
+ "continued_ingestion": True, "native_service_discovery_and_search": True,
+ "legacy_and_v3_trace_id_readback": True,
+ "grafana_legacy_search_supported": legacy_search_status == 200,
+ "short_ttl_read_expiry": True, "logical_store_bytes_before_cleanup": data_bytes,
+ }
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--jaeger-binary", type=Path, required=True)
+ parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
+ args = parser.parse_args()
+ print(json.dumps(prove(args.jaeger_binary, config_path=args.config), sort_keys=True))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/release/check_image_drift.py b/scripts/release/check_image_drift.py
index b89822a0c..da75efbfe 100644
--- a/scripts/release/check_image_drift.py
+++ b/scripts/release/check_image_drift.py
@@ -31,10 +31,7 @@
from pathlib import Path
# Compose files whose literal image: lines are covered by the manifest.
-# docker-compose.monitoring.yml (prometheus/grafana/jaeger) and
-# docker-compose.gcp-vm.yml (a build-only override with no image: lines) are
-# deliberately out of scope: the monitoring sidecar stack is not part of the
-# TestLookup application bundle. They are still scanned for :latest below.
+# The separately bundled durable telemetry overlays have their own inventory.
MANIFEST_COMPOSE_FILES = (
"docker-compose.yml",
"docker-compose.release.yml",
@@ -42,6 +39,11 @@
)
AIRGAP_COMPOSE_FILE = "docker-compose.airgap.yml"
+TELEMETRY_COMPOSE_FILES = (
+ "docker-compose.monitoring.yml",
+ "docker-compose.telemetry.yml",
+ "docker-compose.alerting.yml",
+)
OPENSHIFT_KUSTOMIZATION = "k8s/overlays/openshift-artifactory/kustomization.yaml"
OPENSHIFT_SCRIPTS = (
"openshiftsetup/mirror-images.sh",
@@ -81,18 +83,20 @@ def __init__(self, ref: str, role: str, surfaces: str, bundle: str, lineno: int)
@property
def name(self) -> str:
- return self.ref.rsplit(":", 1)[0]
+ return self.ref.split("@sha256:", 1)[0].rsplit(":", 1)[0]
@property
def tag(self) -> str:
- return self.ref.rsplit(":", 1)[1] if ":" in self.ref else ""
+ tagged = self.ref.split("@sha256:", 1)[0]
+ return tagged.rsplit(":", 1)[1] if ":" in tagged else ""
def load_manifest(path: Path) -> list[Row]:
rows: list[Row] = []
valid_roles = {"app", "infra"}
- valid_bundles = {"core", "llm", "external", "excluded"}
- valid_surfaces = {"compose", "k8s"}
+ telemetry_bundles = {"telemetry", "telemetry-external"}
+ valid_bundles = {"core", "llm", "external", "excluded", *telemetry_bundles}
+ valid_surfaces = {"compose", "k8s", "telemetry"}
for lineno, raw in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
line = raw.split("#", 1)[0].strip()
if not line:
@@ -115,6 +119,14 @@ def load_manifest(path: Path) -> list[Row]:
f"{path}:{lineno}: app images must carry the literal tag {APP_TAG_TOKEN} "
"(the real tag is resolved at build time)"
)
+ if "telemetry" in row.surfaces or row.bundle in telemetry_bundles:
+ if (
+ row.role != "infra" or row.surfaces != ("telemetry",) or row.bundle not in telemetry_bundles
+ or not re.fullmatch(r"[^\s@]+:[^\s@:]+@sha256:[a-f0-9]{64}", row.ref)
+ ):
+ raise SystemExit(f"{path}:{lineno}: telemetry images need an immutable optional infra reference")
+ if row.name in {"grafana/grafana", "grafana/loki"} and row.bundle != "telemetry-external":
+ raise SystemExit(f"{path}:{lineno}: Grafana Labs OSS images must stay external to shipment")
rows.append(row)
if not rows:
raise SystemExit(f"{path}: manifest is empty")
@@ -155,6 +167,27 @@ def check(repo_root: Path) -> list[str]:
app_names = {r.name for r in rows if r.role == "app"}
all_infra_names = {r.name for r in rows if r.role == "infra"}
+ telemetry_refs = {r.ref for r in rows if "telemetry" in r.surfaces}
+ telemetry_files = [repo_root / rel for rel in TELEMETRY_COMPOSE_FILES]
+ if telemetry_refs or (repo_root / "docker-compose.telemetry.yml").exists():
+ missing_files = [file.name for file in telemetry_files if not file.is_file()]
+ if missing_files:
+ errors.append(f"durable telemetry Compose files are missing: {missing_files}")
+ else:
+ telemetry_images = {
+ ref
+ for file in telemetry_files
+ for _, ref in compose_image_refs(file)
+ # The durable overlay replaces the basic, ephemeral service.
+ if not (file.name == "docker-compose.monitoring.yml" and ref.startswith("jaegertracing/all-in-one:"))
+ }
+ if telemetry_images != telemetry_refs:
+ errors.append(
+ f"durable telemetry image inventory differs from Compose; "
+ f"missing from manifest: {sorted(telemetry_images - telemetry_refs)}, "
+ f"missing from Compose: {sorted(telemetry_refs - telemetry_images)}"
+ )
+
# ── 1. Compose <-> manifest, both directions ────────────────────────────
seen_compose: set[str] = set()
for rel in MANIFEST_COMPOSE_FILES:
diff --git a/scripts/release/image-manifest.sh b/scripts/release/image-manifest.sh
index bf319dcdf..0e0c5673e 100755
--- a/scripts/release/image-manifest.sh
+++ b/scripts/release/image-manifest.sh
@@ -13,9 +13,9 @@
# manifest_refs any app any # app refs still carry @APP_TAG
#
# manifest_refs
-# surface compose | k8s | any
+# surface compose | k8s | telemetry | any
# role app | infra | any
-# bundle comma list (core,llm,external,excluded) | any
+# bundle comma list (core,llm,telemetry,telemetry-external,external,excluded) | any
#
# Set APP_TAG before calling to have `@APP_TAG` substituted in app refs.
# Running this file directly prints the whole manifest (a quick sanity check).
@@ -57,7 +57,19 @@ manifest_refs() {
}
# Strip the tag from a ref: valkey/valkey:8.1-alpine -> valkey/valkey
-manifest_ref_name() { printf '%s\n' "${1%:*}"; }
+manifest_ref_name() {
+ local tagged="${1%@sha256:*}"
+ printf '%s\n' "${tagged%:*}"
+}
+
+# docker save/load preserves repository tags but not the registry index digest.
+# A separate namespace prevents the temporary alias overwriting a vendor tag.
+manifest_archive_ref() {
+ case "$1" in
+ *@sha256:*) printf 'localhost/testlookup-telemetry/%s\n' "${1%@sha256:*}" ;;
+ *) printf '%s\n' "$1" ;;
+ esac
+}
# Turn a ref into a filesystem-safe basename for images/.tar
manifest_ref_slug() { printf '%s\n' "$1" | tr '/:' '__' | tr -cd 'A-Za-z0-9._-'; }
diff --git a/scripts/release/offline-bundle.sh b/scripts/release/offline-bundle.sh
index 15dca9588..856352151 100755
--- a/scripts/release/offline-bundle.sh
+++ b/scripts/release/offline-bundle.sh
@@ -27,6 +27,7 @@
# --created-at ISO-8601 UTC timestamp recorded in MANIFEST.json.
# PASS THIS from your release pipeline — see "Determinism".
# --with-llm also bundle the optional Ollama + ChromaDB images
+# --with-telemetry also bundle the optional durable Compose monitoring stack
# --skip-build don't build the app images (must already exist locally)
# --skip-pull don't pull infra images (must already exist locally)
# --skip-k8s-render don't render the k8s manifests (no kustomize on host)
@@ -57,7 +58,7 @@ DOCKER="${DOCKER:-docker}"
# ── Flags ───────────────────────────────────────────────────────────────────
VERSION=""; OUTPUT_DIR="$REPO_ROOT/dist"; CREATED_AT=""
-WITH_LLM=false; SKIP_BUILD=false; SKIP_PULL=false; SKIP_K8S=false
+WITH_LLM=false; WITH_TELEMETRY=false; SKIP_BUILD=false; SKIP_PULL=false; SKIP_K8S=false
KEEP_STAGING=false; DRY_RUN=false
while [ $# -gt 0 ]; do
case "$1" in
@@ -65,6 +66,7 @@ while [ $# -gt 0 ]; do
--output) OUTPUT_DIR="${2:?--output needs a value}"; shift 2 ;;
--created-at) CREATED_AT="${2:?--created-at needs a value}"; shift 2 ;;
--with-llm) WITH_LLM=true; shift ;;
+ --with-telemetry) WITH_TELEMETRY=true; shift ;;
--skip-build) SKIP_BUILD=true; shift ;;
--skip-pull) SKIP_PULL=true; shift ;;
--skip-k8s-render) SKIP_K8S=true; shift ;;
@@ -100,6 +102,7 @@ TARBALL="$OUTPUT_DIR/${BUNDLE_NAME}.tar.gz"
BUNDLE_FILTER="core"
[ "$WITH_LLM" = true ] && BUNDLE_FILTER="core,llm"
+[ "$WITH_TELEMETRY" = true ] && BUNDLE_FILTER="$BUNDLE_FILTER,telemetry"
# ── sha256: hard requirement, never silently degraded ───────────────────────
# A bundle whose checksums are "unavailable" is a bundle nobody can verify on
@@ -118,6 +121,8 @@ ALL_REFS="$(printf '%s\n%s\n' "$APP_REFS" "$INFRA_REFS" | grep -v '^$')"
# (bundle class `external` in the manifest — today MongoDB, SSPL-1.0). They are
# listed in the plan, README.md and MANIFEST.json so the operator mirrors them.
EXTERNAL_REFS="$(manifest_refs any infra external)"
+TELEMETRY_EXTERNAL_REFS=""
+[ "$WITH_TELEMETRY" = true ] && TELEMETRY_EXTERNAL_REFS="$(manifest_refs telemetry infra telemetry-external)"
header "Plan"
echo " version : $VERSION"
@@ -125,6 +130,7 @@ echo " created_at : $CREATED_AT"
echo " git sha : $GIT_SHA"
echo " container CLI: $DOCKER"
echo " llm images : $WITH_LLM"
+echo " telemetry : $WITH_TELEMETRY"
echo " output : $TARBALL"
echo " images :"
printf ' %s\n' $ALL_REFS
@@ -132,6 +138,10 @@ if [ -n "$EXTERNAL_REFS" ]; then
echo " NOT bundled : (external prerequisites — the operator mirrors these)"
printf ' %s\n' $EXTERNAL_REFS
fi
+if [ -n "$TELEMETRY_EXTERNAL_REFS" ]; then
+ echo " operator-provided telemetry images:"
+ printf ' %s\n' $TELEMETRY_EXTERNAL_REFS
+fi
if [ "$DRY_RUN" = true ]; then
warn "--dry-run — nothing built, pulled, saved or written."
@@ -211,15 +221,21 @@ command -v syft >/dev/null 2>&1 && HAVE_SYFT=true
: > "$STAGING/images.list"
IMAGE_JSON=""
for ref in $ALL_REFS; do
+ archive_ref="$(manifest_archive_ref "$ref")"
+ if [ "$archive_ref" != "$ref" ]; then
+ source_id="$("$DOCKER" image inspect --format '{{.Id}}' "$ref")" || error "Pinned image $ref is missing"
+ [ -n "$source_id" ] || error "Pinned image $ref has no local image ID"
+ "$DOCKER" tag "$source_id" "$archive_ref" || error "Could not tag the pinned image $ref for offline use"
+ fi
slug="$(manifest_ref_slug "$ref")"
tar_rel="images/${slug}.tar"
log "save $ref -> $tar_rel"
- "$DOCKER" save -o "$STAGING/$tar_rel" "$ref" || error "docker save failed for $ref"
+ "$DOCKER" save -o "$STAGING/$tar_rel" "$archive_ref" || error "docker save failed for $ref"
[ -s "$STAGING/$tar_rel" ] || error "docker save produced an empty tar for $ref"
# images.list is what import-bundle.sh reads — plain "\t[" so the
# import side needs no JSON parser.
- printf '%s\t%s\n' "$tar_rel" "$ref" >> "$STAGING/images.list"
+ printf '%s\t%s\n' "$tar_rel" "$archive_ref" >> "$STAGING/images.list"
size="$(wc -c < "$STAGING/$tar_rel" | tr -d '[:space:]')"
sha="$(SHA_CMD "$STAGING/$tar_rel")"
@@ -238,7 +254,7 @@ for ref in $ALL_REFS; do
# 2. otherwise -> an explicit "unavailable" record with the reason.
# We never imply an SBOM exists when it does not.
if [ "$HAVE_SYFT" = true ]; then
- if syft "${DOCKER}:${ref}" -o spdx-json > "$STAGING/sbom/${slug}.spdx.json" 2>/dev/null \
+ if syft "${DOCKER}:${archive_ref}" -o spdx-json > "$STAGING/sbom/${slug}.spdx.json" 2>/dev/null \
|| syft "$ref" -o spdx-json > "$STAGING/sbom/${slug}.spdx.json" 2>/dev/null; then
sbom_json="{\"status\":\"present\",\"tool\":\"syft\",\"format\":\"spdx-json\",\"file\":\"sbom/${slug}.spdx.json\"}"
else
@@ -250,7 +266,7 @@ for ref in $ALL_REFS; do
sbom_json="{\"status\":\"unavailable\",\"reason\":\"syft was not installed on the build host; docker save does not carry BuildKit SBOM attestations (they live in the registry manifest, see .github/workflows/release.yml)\"}"
fi
- entry="{\"ref\":\"$ref\",\"role\":\"$role\",\"file\":\"$tar_rel\",\"bytes\":$size,\"sha256\":\"$sha\",\"image_id\":\"$image_id\",\"repo_digest\":\"$repo_digest\",\"sbom\":$sbom_json}"
+ entry="{\"ref\":\"$ref\",\"archive_ref\":\"$archive_ref\",\"role\":\"$role\",\"file\":\"$tar_rel\",\"bytes\":$size,\"sha256\":\"$sha\",\"image_id\":\"$image_id\",\"repo_digest\":\"$repo_digest\",\"sbom\":$sbom_json}"
if [ -z "$IMAGE_JSON" ]; then IMAGE_JSON=" $entry"; else IMAGE_JSON="$IMAGE_JSON,
$entry"; fi
done
@@ -263,6 +279,25 @@ cp "$REPO_ROOT/.env.example" "$STAGING/compose/" 2>/dev/null || wa
cp "$REPO_ROOT/scripts/gen-dev-env.sh" "$STAGING/compose/scripts/" 2>/dev/null || true
cp "$REPO_ROOT/scripts/init-db.sql" "$STAGING/compose/scripts/"
log "compose/: release + airgap override + .env.example + init-db.sql"
+if [ "$WITH_TELEMETRY" = true ]; then
+ mkdir -p "$STAGING/compose/infra" "$STAGING/compose/scripts/monitoring"
+ # Only the committed configuration is eligible for an offline package.
+ # Operator receiver credentials, local overrides and data directories may
+ # live alongside it and must never be copied from the working tree.
+ git -C "$REPO_ROOT" archive "$GIT_SHA" infra/monitoring | tar -xf - -C "$STAGING/compose"
+ cp "$REPO_ROOT/scripts/monitoring/configure_alerting.py" "$STAGING/compose/scripts/monitoring/"
+ cp "$REPO_ROOT/docker-compose.monitoring-auth.yml" "$STAGING/compose/"
+ for overlay in monitoring telemetry alerting; do
+ file="docker-compose.$overlay.yml"
+ sed -E 's|^([[:space:]]*image:[[:space:]]+)([^[:space:]@]+)@sha256:[a-f0-9]{64}$|\1localhost/testlookup-telemetry/\2|' \
+ "$REPO_ROOT/$file" > "$STAGING/compose/$file"
+ done
+ : > "$STAGING/compose/telemetry-prerequisites.list"
+ for ref in $TELEMETRY_EXTERNAL_REFS; do
+ printf '%s\t%s\n' "$ref" "$(manifest_archive_ref "$ref")" >> "$STAGING/compose/telemetry-prerequisites.list"
+ done
+ log "compose/: attached private telemetry overlays, image aliases, and monitoring configuration"
+fi
# ── Step 5 — Kubernetes manifests ───────────────────────────────────────────
# The openshift-artifactory overlay is the air-gap-ready one: its images: block
@@ -324,6 +359,11 @@ for ref in $EXTERNAL_REFS; do EXTERNAL_MD="${EXTERNAL_MD}* \`$ref\`
"; done
[ -n "$EXTERNAL_MD" ] || EXTERNAL_MD="* (none)
"
+TELEMETRY_EXTERNAL_JSON=""
+for ref in $TELEMETRY_EXTERNAL_REFS; do
+ [ -z "$TELEMETRY_EXTERNAL_JSON" ] || TELEMETRY_EXTERNAL_JSON="$TELEMETRY_EXTERNAL_JSON, "
+ TELEMETRY_EXTERNAL_JSON="$TELEMETRY_EXTERNAL_JSON\"$ref\""
+done
SBOM_MODE="unavailable"; [ "$HAVE_SYFT" = true ] && SBOM_MODE="syft"
cat > "$STAGING/MANIFEST.json" < "$STAGING/MANIFEST.json" </:",
@@ -342,6 +383,7 @@ cat > "$STAGING/MANIFEST.json" <
Date: Fri, 27 Nov 2026 01:25:33 -0600
Subject: [PATCH 05/13] feat: preserve operational and identity audit evidence
Stage scoped pipeline event intents with their source changes and replay them through a leased, idempotent Mongo relay. Add shared delivery health, authorized repair, retention fencing and incomplete-export protection.
Add independently signed archive custody and opt-in identity retention. Preserve SCIM authority, respect identity holds and record bounded maintenance receipts.
Signed-off-by: Anand Topu
---
.github/workflows/ci.yml | 3 +
CHANGELOG.md | 1 +
DATA_AND_PRIVACY.md | 9 +-
architecture/DATABASE_SCHEMA.md | 1 +
backend/app/agents/anomaly_agent.py | 7 +-
backend/app/agents/base.py | 51 +-
backend/app/agents/investigator/workflow.py | 21 +-
backend/app/agents/workflow.py | 67 +-
backend/app/bootstrap.py | 2 +
backend/app/core/metrics.py | 25 +
backend/app/db/mongo.py | 3 +
backend/app/models/identity_retention.py | 100 ++
backend/app/models/postgres.py | 46 +-
backend/app/models/schemas.py | 6 +
backend/app/routers/agent_actions.py | 9 +-
backend/app/routers/agents.py | 49 +-
backend/app/routers/identity_events.py | 135 +-
backend/app/routers/reviews.py | 12 +-
backend/app/services/activity/events.py | 1 +
.../services/agent_investigation_service.py | 9 +-
.../services/identity_retention_service.py | 265 +++
backend/app/services/metric_collection.py | 2 +-
.../app/services/pipeline_event_admission.py | 156 ++
.../app/services/pipeline_event_delivery.py | 263 +++
backend/app/services/pipeline_event_log.py | 193 ++-
.../pipeline_event_operational_metrics.py | 107 ++
.../app/services/pipeline_replay_service.py | 2 +-
.../app/services/project_export_documents.py | 8 +-
.../app/services/project_export_history.py | 24 +
backend/app/services/retention_service.py | 114 +-
.../app/services/subject_data_inventory.py | 4 +
backend/app/worker/celery_app.py | 5 +
backend/app/worker/tasks.py | 26 +
.../versions/0263_pipeline_event_outbox.py | 63 +
.../test_identity_retention_postgres.py | 96 ++
.../test_pipeline_event_outbox_postgres.py | 108 ++
.../test_anomaly_decision_pool_boundary.py | 106 ++
.../regression/test_audit_archive_custody.py | 281 +++
.../test_pipeline_event_admission.py | 131 ++
.../test_pipeline_event_delivery.py | 306 ++++
backend/tests/test_agent_actions_router.py | 3 +-
...est_agent_pipeline_hardening_regression.py | 20 +-
backend/tests/test_identity_retention.py | 339 ++++
backend/tests/test_p2_features.py | 43 +-
backend/tests/test_project_export_history.py | 93 +-
backend/tests/test_project_reset_documents.py | 14 +-
backend/tests/test_project_reset_service.py | 8 +-
backend/tests/test_retention_purge_holds.py | 16 +
.../tests/test_retention_retained_archives.py | 25 +-
backend/tests/test_subject_data_inventory.py | 7 +-
cli/requirements-audit-archive.txt | 26 +
cli/testlookup_cli/audit_archive.py | 341 ++++
docs/maintainers/observability-delivery.md | 13 +
docs/operations/audit-archive-custody.md | 233 +++
docs/operations/identity-event-retention.md | 85 +
docs/operations/pipeline-event-delivery.md | 161 ++
docs/reference/api-index.md | 10 +-
docs/reference/api/agent-actions.md | 2 +-
docs/reference/api/agent-operations.md | 144 +-
docs/reference/api/identity-audit.md | 582 ++++++-
docs/reference/api/reviews.md | 8 +-
docs/reference/data-dictionary.md | 299 ++--
docs/reference/migrations.md | 1 +
docs/reference/openapi.json | 1506 ++++++++++++++---
docs/reference/schemas.md | 454 +++++
docs/reference/worker-operations.md | 167 +-
infra/audit-archive/iam-policies.example.json | 310 ++++
.../prometheus-rules/testlookup-alerts.yml | 66 +
.../tests/pipeline-event-delivery.yml | 135 ++
k8s/monitoring/prometheusrule.yaml | 38 +
70 files changed, 7230 insertions(+), 736 deletions(-)
create mode 100644 backend/app/models/identity_retention.py
create mode 100644 backend/app/services/identity_retention_service.py
create mode 100644 backend/app/services/pipeline_event_admission.py
create mode 100644 backend/app/services/pipeline_event_delivery.py
create mode 100644 backend/app/services/pipeline_event_operational_metrics.py
create mode 100644 backend/migrations/versions/0263_pipeline_event_outbox.py
create mode 100644 backend/tests/integration/test_identity_retention_postgres.py
create mode 100644 backend/tests/integration/test_pipeline_event_outbox_postgres.py
create mode 100644 backend/tests/regression/test_anomaly_decision_pool_boundary.py
create mode 100644 backend/tests/regression/test_audit_archive_custody.py
create mode 100644 backend/tests/regression/test_pipeline_event_admission.py
create mode 100644 backend/tests/regression/test_pipeline_event_delivery.py
create mode 100644 backend/tests/test_identity_retention.py
create mode 100644 cli/requirements-audit-archive.txt
create mode 100644 cli/testlookup_cli/audit_archive.py
create mode 100644 docs/operations/audit-archive-custody.md
create mode 100644 docs/operations/identity-event-retention.md
create mode 100644 docs/operations/pipeline-event-delivery.md
create mode 100644 infra/audit-archive/iam-policies.example.json
create mode 100644 infra/monitoring/tests/pipeline-event-delivery.yml
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 863f62ea2..2bdd819ae 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -906,6 +906,7 @@ jobs:
DATABASE_URL: postgresql+asyncpg://testlookup_user:test_password@localhost:5432/testlookup_test
TESTLOOKUP_POSTGRES_TEST_DSN: postgresql+asyncpg://testlookup_user:test_password@localhost:5432/testlookup_test
MONGO_URI: mongodb://localhost:27017
+ TESTLOOKUP_MONGO_EVENT_TEST_URI: mongodb://localhost:27017
REDIS_URL: redis://localhost:6379/0
APP_SECRET_KEY: test-secret-key-for-ci
JWT_SECRET_KEY: test-jwt-key-for-ci
@@ -1146,6 +1147,8 @@ jobs:
tests/integration/test_db_connection_budget_postgres.py
tests/integration/test_db_pool_metrics_postgres.py
tests/integration/test_nightly_job_observation_postgres.py
+ tests/integration/test_pipeline_event_outbox_postgres.py
+ tests/integration/test_identity_retention_postgres.py
tests/integration/test_engine_hides_parameters_postgres.py
tests/integration/test_decision_report_supersession_postgres_mongo.py
tests/integration/test_http_exchanges_postgres_mongo.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f30219b35..ad82e2997 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).
### Added
+- Pipeline events use a PostgreSQL outbox with stable IDs for MongoDB replay, shared delivery health, and project-scoped recovery. Audit archives support independent integrity verification, and an opt-in identity retention policy preserves SCIM authority events.
- The durable telemetry profile adds queued OpenTelemetry export, persistent Loki logs and Jaeger traces, Grafana correlation, and queue loss alerts. Kubernetes client overlays support a site-operated mTLS gateway, and the offline Compose bundle can include the durable stack.
- The optional Compose alerting overlay adds a private Alertmanager with authenticated HTTPS incident and watchdog receivers. Compose and Kubernetes monitoring inventories detect missing scrape roles and required metric series.
- Operational metrics report SQLAlchemy pool pressure and acquisition timeouts for API and worker processes, plus Redis and Valkey memory for the application and broker. Optional Compose and Kubernetes profiles support file-backed authentication for API scrapes.
diff --git a/DATA_AND_PRIVACY.md b/DATA_AND_PRIVACY.md
index 41ed4f4e2..d0169d16e 100644
--- a/DATA_AND_PRIVACY.md
+++ b/DATA_AND_PRIVACY.md
@@ -87,9 +87,12 @@ environment can.
person. Erasure pseudonymises the account everywhere except audit records and
signed compliance packs, which keep the stored name (Article 17(3)).
- **Retention:** policies for raw events, runs, artifacts and some audit
- records, **off until you enable them**. Identity events (which hold sign-in IP
- addresses) and the settings audit log are never purged by TestLookup; prune
- them yourself if your policy requires it. AI analysis history is capped per run
+ records, **off until you enable them**. A separate, default-off instance policy
+ can expire successful routine sign-in, sign-out and MFA verification events
+ after administrator approval. SCIM authority and all other identity records
+ stay retained; independent instance identity holds stop this expiry. See
+ [identity event retention](docs/operations/identity-event-retention.md).
+ The settings audit log is never purged. AI analysis history is capped per run
and per test, and agent memory expires after 365 days
(`AGENT_MEMORY_RETENTION_DAYS`).
- **Audit:** administrators can export up to 365 days of audit records as CSV,
diff --git a/architecture/DATABASE_SCHEMA.md b/architecture/DATABASE_SCHEMA.md
index f2da17e33..a190c5117 100644
--- a/architecture/DATABASE_SCHEMA.md
+++ b/architecture/DATABASE_SCHEMA.md
@@ -3353,6 +3353,7 @@ The older per-domain sections omitted these tables. Their full field definitions
| `live_event_receipts` | `LiveEventReceipt` | [Fields and constraints](../docs/reference/data-dictionary.md#live_event_receipts) |
| `live_projection_checkpoints` | `LiveProjectionCheckpoint` | [Fields and constraints](../docs/reference/data-dictionary.md#live_projection_checkpoints) |
| `run_downstream_outbox` | `RunDownstreamOutbox` | [Fields and constraints](../docs/reference/data-dictionary.md#run_downstream_outbox) |
+| `pipeline_event_outbox` | `PipelineEventOutbox` | [Fields and constraints](../docs/reference/data-dictionary.md#pipeline_event_outbox) |
| `semantic_reindex_jobs` | `SemanticReindexJob` | [Fields and constraints](../docs/reference/data-dictionary.md#semantic_reindex_jobs) |
| `agent_child_dispatch_outbox` | `AgentChildDispatchOutbox` | [Fields and constraints](../docs/reference/data-dictionary.md#agent_child_dispatch_outbox) |
| `decision_report_feedback` | `DecisionReportFeedback` | [Fields and constraints](../docs/reference/data-dictionary.md#decision_report_feedback) |
diff --git a/backend/app/agents/anomaly_agent.py b/backend/app/agents/anomaly_agent.py
index cacdb533e..dbbc0e358 100644
--- a/backend/app/agents/anomaly_agent.py
+++ b/backend/app/agents/anomaly_agent.py
@@ -29,7 +29,7 @@
from app.agents.base import BaseAgent
from app.core.config import settings
-from app.db.postgres import AsyncSessionLocal
+from app.db.postgres import AsyncSessionLocal, release_read_connection
from app.models.agent_contracts import (
AnomalyDetectionAgentOutput,
validate_agent_contract,
@@ -83,6 +83,11 @@ async def run(self, state: dict) -> dict:
baseline_rate, prior_run_ids, baseline_run_id = await self._get_baseline_pass_rate(
db, project_id, test_run_id, branch
)
+ # Baseline facts are scalar values. Return this read connection
+ # before log_decision opens its independent SQL outbox session;
+ # a one-connection worker pool cannot hold both at once. The
+ # same session can start fresh reads for the checks below.
+ await release_read_connection(db)
if baseline_rate is None or not prior_run_ids:
# No baseline means every check below is skipped and the run
diff --git a/backend/app/agents/base.py b/backend/app/agents/base.py
index 0759cc9aa..e3e084d44 100644
--- a/backend/app/agents/base.py
+++ b/backend/app/agents/base.py
@@ -2,6 +2,7 @@
import time
from abc import ABC, abstractmethod
from datetime import datetime, timezone
+from uuid import uuid5
from typing import Any, Optional
from app.core.metrics import (
@@ -333,30 +334,24 @@ async def mark_stage_done(
duration_secs = round(
time.perf_counter() - self._stage_start.get(pipeline_run_id, time.perf_counter()), 3
)
- await emit_event(
- pipeline_run_id, event_type,
- stage_name=runtime_stage_name(type(self).stage_name),
- detail={
- "duration_seconds": duration_secs,
- "input_tokens": input_tokens,
- "output_tokens": output_tokens,
- "total_tokens": total_tokens,
- "llm_calls_count": llm_calls_count,
- "cost_usd": round(cost_usd, 6),
- # How the number was arrived at: "priced" | "self_hosted" |
- # "unpriced" | "caller". A $0.00 from a self-hosted provider
- # and a $0.00 from an unpriced cloud model mean opposite
- # things, and the reader must be able to tell them apart.
- "cost_source": cost_source,
- **({"confidence_score": confidence_score} if confidence_score is not None else {}),
- **({"evidence_count": evidence_count} if evidence_count is not None else {}),
- **({"error": error[:500]} if error else {}),
- **({"error_category": error_category} if error_category else {}),
- **({"fallback_reason": fallback_reason} if fallback_reason else {}),
- **({"route_rationale": route_rationale} if route_rationale else {}),
- **({"result_summary": {k: v for k, v in (result_data or {}).items() if not isinstance(v, (list, dict))}} if result_data else {}),
- },
- )
+ event_detail = {
+ "duration_seconds": duration_secs,
+ "input_tokens": input_tokens,
+ "output_tokens": output_tokens,
+ "total_tokens": total_tokens,
+ "llm_calls_count": llm_calls_count,
+ "cost_usd": round(cost_usd, 6),
+ # A zero cost from a self-hosted provider and an unpriced cloud
+ # model have different meanings.
+ "cost_source": cost_source,
+ **({"confidence_score": confidence_score} if confidence_score is not None else {}),
+ **({"evidence_count": evidence_count} if evidence_count is not None else {}),
+ **({"error": error[:500]} if error else {}),
+ **({"error_category": error_category} if error_category else {}),
+ **({"fallback_reason": fallback_reason} if fallback_reason else {}),
+ **({"route_rationale": route_rationale} if route_rationale else {}),
+ **({"result_summary": {k: v for k, v in (result_data or {}).items() if not isinstance(v, (list, dict))}} if result_data else {}),
+ }
# Record Prometheus metrics
duration = time.perf_counter() - self._stage_start.pop(pipeline_run_id, time.perf_counter())
@@ -549,6 +544,14 @@ async def mark_stage_done(
decisions = self._stage_decisions.pop(pipeline_run_id, None)
if decisions:
stage.decision_log = decisions
+ await db.flush()
+ await emit_event(
+ pipeline_run_id, event_type,
+ stage_name=runtime_stage_name(type(self).stage_name),
+ detail=event_detail,
+ db=db,
+ event_id=uuid5(stage.id, f"{event_type}:{stage_attempt}"),
+ )
await db.commit()
# Settlement is intentionally a second transaction. If its commit
diff --git a/backend/app/agents/investigator/workflow.py b/backend/app/agents/investigator/workflow.py
index fe2548a8c..3362291bb 100644
--- a/backend/app/agents/investigator/workflow.py
+++ b/backend/app/agents/investigator/workflow.py
@@ -953,6 +953,19 @@ async def _finalize(
duration_ms=int(wall_seconds * 1000),
prompt_registry_digest=_registry_digest(),
)
+ if pipeline is not None and error is None and final_state is not None:
+ await emit_event(
+ pipeline_run_id, "pipeline_completed", db=db,
+ event_id=uuid.uuid5(pipeline.id, f"pipeline-completed:{pipeline.attempt}"),
+ detail={
+ "workflow_type": "investigation",
+ "investigation_id": investigation_id,
+ "primary_cause": (final_state.get("verdict") or {}).get("primary_cause"),
+ "cancelled": bool(final_state.get("cancelled")),
+ "spend_llm_calls": final_state.get("spend_llm_calls"),
+ "spend_tokens": final_state.get("spend_tokens"),
+ },
+ )
await db.commit()
@@ -1235,14 +1248,6 @@ async def run_investigation(
error=None,
wall_seconds=wall,
)
- await emit_event(pipeline_run_id, "pipeline_completed", detail={
- "workflow_type": "investigation",
- "investigation_id": investigation_id,
- "primary_cause": (final_state.get("verdict") or {}).get("primary_cause"),
- "cancelled": bool(final_state.get("cancelled")),
- "spend_llm_calls": final_state.get("spend_llm_calls"),
- "spend_tokens": final_state.get("spend_tokens"),
- })
logger.info(
"investigation_finished",
investigation_id=investigation_id,
diff --git a/backend/app/agents/workflow.py b/backend/app/agents/workflow.py
index 3c0e239fd..d016f94df 100644
--- a/backend/app/agents/workflow.py
+++ b/backend/app/agents/workflow.py
@@ -2221,15 +2221,6 @@ async def _complete_cost_budget_block(
final_state=state,
fencing_token=state.get("_fencing_token"),
)
- await emit_event(
- pipeline_run_id,
- "pipeline_completed",
- detail={
- "workflow_type": workflow_type,
- "cost_budget_blocked": True,
- "budget_action": state.get("_cost_budget_action"),
- },
- )
return state
@@ -2909,20 +2900,6 @@ async def run_offline_pipeline(
final_state=final_state,
fencing_token=initial_state.get("_fencing_token"),
)
- await emit_event(
- pipeline_run_id,
- "workflow_verified",
- stage_name="workflow",
- detail=final_state.get("workflow_verification", {}),
- )
- await emit_event(pipeline_run_id, "pipeline_completed", detail={
- "workflow_type": workflow_type,
- "stages_completed": final_state.get("completed_stages", []),
- "stages_skipped": final_state.get("skipped_stages", []),
- "analysis_mode_requested": final_state.get("analysis_mode_requested"),
- "analysis_mode_resolved": final_state.get("analysis_mode_resolved"),
- "error_count": len(final_state.get("errors", [])),
- })
logger.info(
"pipeline_complete",
pipeline_run_id=pipeline_run_id,
@@ -3209,20 +3186,6 @@ async def run_deep_pipeline(
final_state=final_state,
fencing_token=initial_state.get("_fencing_token"),
)
- await emit_event(
- pipeline_run_id,
- "workflow_verified",
- stage_name="workflow",
- detail=final_state.get("workflow_verification", {}),
- )
- await emit_event(pipeline_run_id, "pipeline_completed", detail={
- "workflow_type": "deep",
- "stages_completed": final_state.get("completed_stages", []),
- "stages_skipped": final_state.get("skipped_stages", []),
- "analysis_mode_requested": final_state.get("analysis_mode_requested"),
- "analysis_mode_resolved": final_state.get("analysis_mode_resolved"),
- "error_count": len(final_state.get("errors", [])),
- })
logger.info(
"deep_pipeline_complete",
pipeline_run_id=pipeline_run_id,
@@ -4462,4 +4425,34 @@ async def _mark_pipeline_done(
skipped_reason="Stage not on active pipeline branch",
)
)
+ if run is not None and success and final_state is not None:
+ await db.flush()
+ await _stage_completion_events(db, run, final_state)
await db.commit()
+
+
+async def _stage_completion_events(db, run: AgentPipelineRun, final_state: dict) -> None:
+ """Stage event intent with the terminal state and its current attempt."""
+ detail: dict[str, Any] = {"workflow_type": run.workflow_type}
+ if final_state.get("cost_budget_blocked"):
+ detail.update(
+ cost_budget_blocked=True,
+ budget_action=final_state.get("_cost_budget_action"),
+ )
+ else:
+ await emit_event(
+ str(run.id), "workflow_verified", stage_name="workflow",
+ detail=final_state.get("workflow_verification", {}), db=db,
+ event_id=uuid.uuid5(run.id, f"workflow-verified:{run.attempt}"),
+ )
+ detail.update(
+ stages_completed=final_state.get("completed_stages", []),
+ stages_skipped=final_state.get("skipped_stages", []),
+ analysis_mode_requested=final_state.get("analysis_mode_requested"),
+ analysis_mode_resolved=final_state.get("analysis_mode_resolved"),
+ error_count=len(final_state.get("errors", [])),
+ )
+ await emit_event(
+ str(run.id), "pipeline_completed", detail=detail, db=db,
+ event_id=uuid.uuid5(run.id, f"pipeline-completed:{run.attempt}"),
+ )
diff --git a/backend/app/bootstrap.py b/backend/app/bootstrap.py
index 49ce8b788..66f3e4fc2 100644
--- a/backend/app/bootstrap.py
+++ b/backend/app/bootstrap.py
@@ -536,6 +536,7 @@ async def _endpoint(*args, __orig=original, **kwargs):
)
from app.services.metric_collection import collect_bounded
from app.services.nightly_job_observation import refresh_nightly_job_metrics
+ from app.services.pipeline_event_operational_metrics import refresh_pipeline_event_operational_metrics
from app.services.redis_resource_metrics import refresh_redis_resource_metrics
await asyncio.gather(
@@ -545,6 +546,7 @@ async def _endpoint(*args, __orig=original, **kwargs):
collect_bounded("redis", refresh_redis_resource_metrics),
collect_bounded("nightly", refresh_nightly_job_metrics),
collect_bounded("digests", refresh_digest_operational_metrics),
+ collect_bounded("pipeline_events", refresh_pipeline_event_operational_metrics),
)
result = __orig(*args, **kwargs)
if inspect.isawaitable(result):
diff --git a/backend/app/core/metrics.py b/backend/app/core/metrics.py
index 8b1ce8de4..3a4a726d5 100644
--- a/backend/app/core/metrics.py
+++ b/backend/app/core/metrics.py
@@ -1017,3 +1017,28 @@
"testlookup_nightly_job_started_overdue_slot", "Whether a worker began the overdue slot or a later one", ["schedule"],
multiprocess_mode="mostrecent",
)
+
+# Absolute shared event-delivery snapshots: API replicas observe the same
+# SQL rows, so fleet queries must use max rather than sum across scrapers.
+pipeline_event_outbox_entries = Gauge(
+ "testlookup_pipeline_event_outbox_entries", "Retained shared pipeline event intents by delivery state",
+ ["status"], multiprocess_mode="mostrecent",
+)
+pipeline_event_outbox_oldest_age = Gauge(
+ "testlookup_pipeline_event_outbox_oldest_age_seconds", "Oldest unresolved event intent age by state",
+ ["status"], multiprocess_mode="mostrecent",
+)
+pipeline_event_outbox_overdue = Gauge(
+ "testlookup_pipeline_event_outbox_retry_overdue_seconds", "Oldest due retry or expired delivery lease by state",
+ ["status"], multiprocess_mode="mostrecent",
+)
+pipeline_event_outbox_capacity = Gauge(
+ "testlookup_pipeline_event_outbox_capacity", "Shared SQL admission row capacity including retained receipts",
+ multiprocess_mode="mostrecent",
+)
+pipeline_event_admission_failures = Counter(
+ "testlookup_pipeline_event_admission_failures_total", "Event intents refused before durable SQL acceptance",
+ ["reason"],
+)
+for _reason in ("scope", "capacity", "storage", "contention", "payload", "conflict", "other"):
+ pipeline_event_admission_failures.labels(reason=_reason)
diff --git a/backend/app/db/mongo.py b/backend/app/db/mongo.py
index 811ea136b..fc770ab8c 100644
--- a/backend/app/db/mongo.py
+++ b/backend/app/db/mongo.py
@@ -153,6 +153,8 @@ async def ensure_indexes() -> None:
),
# Retention sweep / project-wide reads.
(Collections.AI_RUN_VERSIONS, [("project_id", 1), ("generated_at", -1)], {}),
+ (Collections.PIPELINE_EVENT_LOG, [("pipeline_run_id", 1), ("timestamp", 1), ("_id", 1)], {}),
+ (Collections.PIPELINE_EVENT_LOG, [("test_run_id", 1)], {}),
]
for coll, keys, kwargs in specs:
try:
@@ -178,3 +180,4 @@ class Collections:
DECISION_REPORT_ATTEMPTS = "decision_report_attempts"
LIVE_EXECUTION_EVENTS = "live_execution_events" # Sanitized events from live runner
AI_RUN_VERSIONS = "ai_run_versions" # AIH-01: immutable run_summary / analysis_digest versions
+ PIPELINE_EVENT_LOG = "pipeline_event_log"
diff --git a/backend/app/models/identity_retention.py b/backend/app/models/identity_retention.py
new file mode 100644
index 000000000..a4c5998e7
--- /dev/null
+++ b/backend/app/models/identity_retention.py
@@ -0,0 +1,100 @@
+"""Explicit instance retention contracts for routine authentication events."""
+from __future__ import annotations
+
+from typing import Literal
+import uuid
+
+from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, StrictBool, StrictInt, model_validator
+
+ROUTINE_EVENT_TYPES = ("MFA_VERIFY_SUCCESS", "SSO_LOGIN", "SSO_LOGOUT")
+AUTHORITY_EVENT_TYPES = ("SCIM_USER_CREATED",)
+RETENTION_MIN_DAYS, RETENTION_MAX_DAYS, RETENTION_DEFAULT_DAYS = 365, 3650, 2555
+MAX_BATCH_SIZE = 500
+MAX_HOLDS = 100
+
+
+class IdentityRetentionHold(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ id: uuid.UUID
+ reason: str = Field(min_length=3, max_length=500)
+ placed_at: AwareDatetime
+ expires_at: AwareDatetime | None = None
+ audit_id: uuid.UUID
+
+
+class IdentityRetentionDocument(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+ schema_version: Literal[1] = 1
+ enabled: StrictBool = False
+ retention_days: StrictInt = Field(default=RETENTION_DEFAULT_DAYS, ge=RETENTION_MIN_DAYS, le=RETENTION_MAX_DAYS)
+ revision: StrictInt = Field(default=0, ge=0)
+ approved_at: AwareDatetime | None = None
+ eligible_event_types: list[str] = Field(default_factory=lambda: list(ROUTINE_EVENT_TYPES))
+ holds: list[IdentityRetentionHold] = Field(default_factory=list, max_length=MAX_HOLDS)
+
+ @model_validator(mode="after")
+ def check_authority(self):
+ if self.eligible_event_types != list(ROUTINE_EVENT_TYPES):
+ raise ValueError("identity record classes need explicit policy migration")
+ if self.enabled and self.approved_at is None:
+ raise ValueError("enabled identity retention has no approval")
+ if len({hold.id for hold in self.holds}) != len(self.holds):
+ raise ValueError("duplicate identity hold")
+ return self
+
+
+class IdentityRetentionRead(IdentityRetentionDocument):
+ scope: Literal["instance"] = "instance"
+ protected_authority_event_types: list[str] = Field(default_factory=lambda: list(AUTHORITY_EVENT_TYPES))
+ protected_identity_events: str = "All other identity event types, including unknown future types, remain retained."
+ active_hold_count: int = 0
+
+
+class IdentityRetentionPreview(BaseModel):
+ observed_at: AwareDatetime
+ cutoff: AwareDatetime
+ retention_days: int
+ enabled: bool
+ active_hold_count: int
+ counts: dict[str, int]
+ max_batch_size: int = MAX_BATCH_SIZE
+ preview_hash: str
+ enable_confirmation: str
+ purge_confirmation: str
+
+
+class IdentityRetentionApproval(BaseModel):
+ retention_days: StrictInt = Field(ge=RETENTION_MIN_DAYS, le=RETENTION_MAX_DAYS)
+ observed_at: AwareDatetime
+ preview_hash: str = Field(pattern=r"^[a-f0-9]{64}$")
+ confirmation: str
+ reason: str = Field(min_length=3, max_length=500)
+
+
+class IdentityRetentionReason(BaseModel):
+ reason: str = Field(min_length=3, max_length=500)
+
+
+class IdentityRetentionHoldCreate(IdentityRetentionReason):
+ expires_at: AwareDatetime | None = None
+
+
+class IdentityRetentionHoldRelease(IdentityRetentionReason):
+ confirmation: str
+
+
+class IdentityRetentionPurge(BaseModel):
+ observed_at: AwareDatetime
+ preview_hash: str = Field(pattern=r"^[a-f0-9]{64}$")
+ confirmation: str
+ reason: str = Field(min_length=3, max_length=500)
+ batch_size: StrictInt = Field(default=MAX_BATCH_SIZE, ge=1, le=MAX_BATCH_SIZE)
+
+
+class IdentityRetentionPurgeResult(BaseModel):
+ status: Literal["completed"]
+ deleted: int
+ batch_size: int
+ batch_full: bool
+ cutoff: AwareDatetime
+ policy_revision: int
diff --git a/backend/app/models/postgres.py b/backend/app/models/postgres.py
index d32df2037..a92fc5614 100644
--- a/backend/app/models/postgres.py
+++ b/backend/app/models/postgres.py
@@ -2659,6 +2659,40 @@ class AgentPipelineRun(Base):
stages: Mapped[list["AgentStageResult"]] = relationship("AgentStageResult", back_populates="pipeline_run", cascade="all, delete-orphan")
+class PipelineEventOutbox(Base):
+ """Project-scoped event intent awaiting idempotent Mongo materialization."""
+
+ __tablename__ = "pipeline_event_outbox"
+ __table_args__ = (
+ CheckConstraint("status IN ('pending', 'sending', 'delivered', 'failed')", name="ck_pipeline_event_outbox_status"),
+ CheckConstraint("attempts >= 0", name="ck_pipeline_event_outbox_attempts"),
+ Index("ix_pipeline_event_outbox_schedule", "status", "next_attempt_at", "created_at"),
+ Index("ix_pipeline_event_outbox_lease", "status", "lease_expires_at"),
+ Index("ix_pipeline_event_outbox_delivered", "status", "delivered_at"),
+ Index("ix_pipeline_event_outbox_project", "project_id", "status"),
+ Index("ix_pipeline_event_outbox_pipeline", "pipeline_id"),
+ Index("ix_pipeline_event_outbox_timeline", "pipeline_run_id", "created_at"),
+ Index("ix_pipeline_event_outbox_run", "test_run_id"),
+ Index("ix_pipeline_event_outbox_test_case", "test_case_id"),
+ )
+
+ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
+ project_id: Mapped[uuid.UUID] = mapped_column(ForeignKey("projects.id", ondelete="CASCADE"), nullable=False)
+ pipeline_id: Mapped[Optional[uuid.UUID]] = mapped_column(ForeignKey("agent_pipeline_runs.id", ondelete="CASCADE"))
+ test_run_id: Mapped[Optional[uuid.UUID]] = mapped_column(ForeignKey("test_runs.id", ondelete="CASCADE"))
+ test_case_id: Mapped[Optional[uuid.UUID]] = mapped_column(ForeignKey("test_cases.id", ondelete="CASCADE"))
+ pipeline_run_id: Mapped[str] = mapped_column(String(128), nullable=False)
+ payload: Mapped[dict] = mapped_column(JSON().with_variant(JSONB(), "postgresql"), nullable=False)
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
+ status: Mapped[str] = mapped_column(String(12), default="pending", server_default="pending")
+ attempts: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
+ next_attempt_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ lease_token: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True))
+ lease_expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+ last_error_code: Mapped[Optional[str]] = mapped_column(String(48))
+ delivered_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True))
+
+
class AgentStageResult(Base):
"""Per-stage result for an AgentPipelineRun."""
__tablename__ = "agent_stage_results"
@@ -4995,7 +5029,7 @@ class IdentityEventType(str, PyEnum):
# if a future addition is not.
#
# Deliberately absent: a per-attempt LOGIN_FAILED event. ``identity_events``
- # has no retention clock (see the model docstring), so anything an
+ # retains failures indefinitely (see the model docstring), so anything an
# unauthenticated attacker can emit at will accumulates forever. The events
# here are either operator-initiated or bounded by the lockout threshold.
MFA_ENROLL_STARTED = "MFA_ENROLL_STARTED"
@@ -5166,9 +5200,13 @@ class IdentityEvent(Base):
UPDATEs an audit table or DELETEs from one outside
``services/retention_service.py``.
- Not currently covered by any retention clock: the US-11.4 purge does not
- touch this table (it has no project scope), so rows accumulate until an
- operator prunes them out-of-band.
+ The project retention clocks do not apply: this table has no project
+ scope. A separate default-off instance policy can expire only successful
+ SSO_LOGIN, SSO_LOGOUT and MFA_VERIFY_SUCCESS records after explicit admin
+ approval, subject to independent instance identity holds. SCIM_USER_CREATED
+ rows remain live authorization evidence; all other types, failed routine
+ records and unknown future types stay retained. Policy/hold/purge receipts
+ remain in the never-purged settings audit trail.
Beyond that, durability is the **operator's** responsibility: direct
Postgres credentials can still rewrite or drop rows. Real immutability
diff --git a/backend/app/models/schemas.py b/backend/app/models/schemas.py
index 3b045808e..cb97b3c47 100644
--- a/backend/app/models/schemas.py
+++ b/backend/app/models/schemas.py
@@ -3483,6 +3483,7 @@ class AgentRunSummaryResponse(BaseModel):
# ── Agent Workflow Timeline Schemas ─────────────────────────────────────────
class PipelineTimelineEventResponse(BaseModel):
+ event_id: Optional[uuid.UUID] = None
event_type: str
stage_name: Optional[str] = None
test_case_id: Optional[str] = None
@@ -3826,6 +3827,11 @@ class PipelineEventLogHealthResponse(BaseModel):
dead_letter_count: int = 0
dead_letter_limit: int = 0
recent_dead_letters: List[Dict[str, Any]] = Field(default_factory=list)
+ backlog_count: int = 0
+ oldest_pending_age_seconds: float = 0
+ outbox_total_count: int = 0
+ capacity: int = 0
+ status_counts: Dict[str, int] = Field(default_factory=dict)
# ── W15 AGT-01: the agent-action queue (enum-like fields are plain str; vocab in services/agent_action_types.py) ──
diff --git a/backend/app/routers/agent_actions.py b/backend/app/routers/agent_actions.py
index 75c56e677..6268e4f4e 100644
--- a/backend/app/routers/agent_actions.py
+++ b/backend/app/routers/agent_actions.py
@@ -210,8 +210,8 @@ async def _undo(
return row
-async def _emit_action_event(row: AgentActionLedger, status: str) -> None:
- """Best-effort pipeline event AFTER the commit (the reviews' order)."""
+async def _stage_action_event(db: AsyncSession, row: AgentActionLedger, status: str) -> None:
+ """Stage the pipeline event alongside the action decision."""
if row.pipeline_run_id is None:
return
try:
@@ -220,9 +220,10 @@ async def _emit_action_event(row: AgentActionLedger, status: str) -> None:
await emit_event(
str(row.pipeline_run_id),
f"agent_action_{status}",
+ db=db,
detail={"action_id": str(row.id), "action_type": row.action_type},
)
- except Exception as exc: # noqa: BLE001 -- the decision is already committed
+ except Exception as exc: # noqa: BLE001 - the action still has its authoritative SQL audit
logger.warning("agent_action_event_not_logged", error_type=type(exc).__name__)
@@ -271,11 +272,11 @@ async def transition_agent_action(
entity_id=row.id, entity_label=entity_label,
context={**facts, "result_kind": _result_kind(row)},
)
+ await _stage_action_event(db, row, body.status)
await db.commit()
if body.status == "rolled_back":
await bump_analytics_epoch(project_id) # the undone effect changed analytics data; after the commit
await db.refresh(row) # updated_at is onupdate: refresh before serialising
- await _emit_action_event(row, body.status)
try:
return await queue.read_action(db, project_id=project_id, action_id=action_id, viewer=current_user)
except LookupError:
diff --git a/backend/app/routers/agents.py b/backend/app/routers/agents.py
index e5bfdb532..9cd6d59ed 100644
--- a/backend/app/routers/agents.py
+++ b/backend/app/routers/agents.py
@@ -1228,7 +1228,7 @@ async def get_pipeline_timeline(
.order_by(AgentStageResult.started_at, AgentStageResult.stage_name)
)
stages = stage_result.scalars().all()
- events = await _resolve_maybe_awaitable(get_pipeline_events(str(pipeline_id)))
+ events = await _resolve_maybe_awaitable(get_pipeline_events(str(pipeline_id), db=db))
from app.services.pipeline_replay_service import build_replay_integrity_summary
replay_integrity = build_replay_integrity_summary(pipeline, list(stages), list(events))
@@ -1295,6 +1295,7 @@ async def get_pipeline_timeline(
],
"events": [
PipelineTimelineEventResponse(
+ event_id=event.get("event_id"),
event_type=event.get("event_type", "unknown"),
stage_name=event.get("stage_name"),
test_case_id=event.get("test_case_id"),
@@ -1426,17 +1427,45 @@ async def get_agentic_runtime(
@router.get("/event-log/health", response_model=PipelineEventLogHealthResponse)
async def get_pipeline_event_log_health(
- _: Any = Depends(require_role(UserRole.QA_LEAD)),
+ project_id: uuid.UUID | None = Query(None),
+ db: AsyncSession = Depends(get_db),
+ current_user: Any = Depends(require_role(UserRole.QA_LEAD)),
):
- """Return write-health details for the pipeline audit event log."""
- from app.services.pipeline_event_log import get_event_log_health
+ """Read shared delivery health within the caller's accessible projects."""
+ from app.services.pipeline_event_operational_metrics import read_event_log_health
- health = get_event_log_health()
- status = "degraded" if health.get("write_failure_count", 0) else "healthy"
- return {
- "status": status,
- **health,
- }
+ selected, accessible = await resolve_project_scope(db, current_user, str(project_id) if project_id else None)
+ projects = {selected} if selected is not None else (None if accessible is None else set(accessible))
+ return await read_event_log_health(db, project_ids=projects)
+
+
+@router.post("/event-log/{event_id}/replay", status_code=202)
+async def replay_pipeline_event_delivery(
+ event_id: uuid.UUID,
+ project_id: uuid.UUID = Query(...),
+ db: AsyncSession = Depends(get_db),
+ current_user: Any = Depends(require_role(UserRole.QA_LEAD)),
+):
+ """Requeue one failed delivery; never re-execute pipeline business work."""
+ from app.services.pipeline_event_delivery import requeue_failed_event
+
+ await resolve_project_scope(db, current_user, str(project_id))
+ try:
+ result = await requeue_failed_event(db, event_id, project_id=project_id)
+ except ValueError:
+ raise HTTPException(409, detail="Only failed event deliveries may be requeued.") from None
+ except RuntimeError:
+ raise HTTPException(409, detail="Event history is busy; retry later.") from None
+ if result is None:
+ raise HTTPException(404, detail="Event delivery not found.")
+ await record_activity(
+ db, project_id=project_id, event_type="analysis.event_delivery_requeued",
+ actor=ActorRef.from_user(current_user), entity_id=project_id,
+ entity_label="Pipeline event delivery",
+ context={"event_id": str(event_id), "previous_attempts": result["previous_attempts"]},
+ )
+ await db.commit()
+ return result
@router.get("/pipelines/{pipeline_id}/replay", response_model=PipelineReplayResponse)
diff --git a/backend/app/routers/identity_events.py b/backend/app/routers/identity_events.py
index 4b10d973f..d196a1c43 100644
--- a/backend/app/routers/identity_events.py
+++ b/backend/app/routers/identity_events.py
@@ -4,7 +4,7 @@
from datetime import datetime, timedelta, timezone
from typing import Optional
-from fastapi import APIRouter, Depends, Query
+from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -23,12 +23,145 @@
IdentitySyncStatus,
)
from app.services.sso_service import get_sync_status
+from app.models.identity_retention import (
+ IdentityRetentionApproval,
+ IdentityRetentionHold,
+ IdentityRetentionHoldCreate,
+ IdentityRetentionHoldRelease,
+ IdentityRetentionPreview,
+ IdentityRetentionPurge,
+ IdentityRetentionPurgeResult,
+ IdentityRetentionRead,
+ IdentityRetentionReason,
+)
+from app.services import identity_retention_service
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/identity", tags=["Identity & Audit"])
+def _retention_error(exc: identity_retention_service.IdentityRetentionError) -> HTTPException:
+ return HTTPException(status_code=exc.status_code, detail={"code": exc.code, "message": str(exc)})
+
+
+@router.get("/retention/policy", response_model=IdentityRetentionRead)
+async def read_identity_retention_policy(
+ current_user: User = Depends(require_role(UserRole.ADMIN)),
+ db: AsyncSession = Depends(get_db),
+):
+ """Read the separate, default-off instance identity policy and its holds."""
+ try:
+ return await identity_retention_service.read_policy(db, now=datetime.now(timezone.utc))
+ except identity_retention_service.IdentityRetentionError as exc:
+ raise _retention_error(exc) from exc
+
+
+@router.get("/retention/preview", response_model=IdentityRetentionPreview)
+async def preview_identity_retention(
+ retention_days: Optional[int] = Query(default=None, ge=365, le=3650),
+ current_user: User = Depends(require_role(UserRole.ADMIN)),
+ db: AsyncSession = Depends(get_db),
+):
+ """Count aged record classes without reading event content or deleting rows."""
+ try:
+ return await identity_retention_service.preview(
+ db, now=datetime.now(timezone.utc), retention_days=retention_days,
+ )
+ except identity_retention_service.IdentityRetentionError as exc:
+ raise _retention_error(exc) from exc
+
+
+@router.post("/retention/policy", response_model=IdentityRetentionRead)
+async def approve_identity_retention_policy(
+ payload: IdentityRetentionApproval,
+ current_user: User = Depends(require_role(UserRole.ADMIN)),
+ db: AsyncSession = Depends(get_db),
+):
+ """Approve routine-event expiry with a fresh preview and typed confirmation.
+
+ Requires an interactive instance administrator. Existing project retention
+ enablement never authorizes this separate policy.
+ """
+ try:
+ await identity_retention_service.approve_policy(
+ db, actor=current_user, **payload.model_dump(), now=datetime.now(timezone.utc),
+ )
+ await db.commit()
+ return await identity_retention_service.read_policy(db, now=datetime.now(timezone.utc))
+ except identity_retention_service.IdentityRetentionError as exc:
+ raise _retention_error(exc) from exc
+
+
+@router.post("/retention/disable", response_model=IdentityRetentionRead)
+async def disable_identity_retention_policy(
+ payload: IdentityRetentionReason,
+ current_user: User = Depends(require_role(UserRole.ADMIN)),
+ db: AsyncSession = Depends(get_db),
+):
+ """Disable future identity expiry without releasing any hold."""
+ try:
+ await identity_retention_service.disable_policy(db, actor=current_user, reason=payload.reason)
+ await db.commit()
+ return await identity_retention_service.read_policy(db, now=datetime.now(timezone.utc))
+ except identity_retention_service.IdentityRetentionError as exc:
+ raise _retention_error(exc) from exc
+
+
+@router.post("/retention/holds", response_model=IdentityRetentionHold, status_code=201)
+async def place_identity_retention_hold(
+ payload: IdentityRetentionHoldCreate,
+ current_user: User = Depends(require_role(UserRole.ADMIN)),
+ db: AsyncSession = Depends(get_db),
+):
+ """Place an independent instance identity hold; all live holds block expiry."""
+ try:
+ hold = await identity_retention_service.place_hold(
+ db, actor=current_user, **payload.model_dump(), now=datetime.now(timezone.utc),
+ )
+ await db.commit()
+ return hold
+ except identity_retention_service.IdentityRetentionError as exc:
+ raise _retention_error(exc) from exc
+
+
+@router.post("/retention/holds/{hold_id}/release", response_model=IdentityRetentionRead)
+async def release_identity_retention_hold(
+ hold_id: uuid.UUID,
+ payload: IdentityRetentionHoldRelease,
+ current_user: User = Depends(require_role(UserRole.ADMIN)),
+ db: AsyncSession = Depends(get_db),
+):
+ """Release only this hold with a reason; overlapping holds remain absolute."""
+ try:
+ await identity_retention_service.release_hold(
+ db, actor=current_user, hold_id=hold_id, **payload.model_dump(), now=datetime.now(timezone.utc),
+ )
+ await db.commit()
+ return await identity_retention_service.read_policy(db, now=datetime.now(timezone.utc))
+ except identity_retention_service.IdentityRetentionError as exc:
+ raise _retention_error(exc) from exc
+
+
+@router.post("/retention/purge", response_model=IdentityRetentionPurgeResult)
+async def purge_identity_retention_batch(
+ payload: IdentityRetentionPurge,
+ current_user: User = Depends(require_role(UserRole.ADMIN)),
+ db: AsyncSession = Depends(get_db),
+):
+ """Execute one approved, unheld batch of at most 500 routine events."""
+ from app.services.retention_service import purge_identity_events_batch
+
+ try:
+ result = await purge_identity_events_batch(
+ db, actor=current_user, **payload.model_dump(), now=datetime.now(timezone.utc),
+ )
+ await db.commit()
+ return result
+ except identity_retention_service.IdentityRetentionError as exc:
+ raise _retention_error(exc) from exc
+
+
@router.get("/events", response_model=IdentityEventListResponse)
async def list_identity_events(
event_type: Optional[IdentityEventType] = None,
diff --git a/backend/app/routers/reviews.py b/backend/app/routers/reviews.py
index fa398b156..aaea1e26d 100644
--- a/backend/app/routers/reviews.py
+++ b/backend/app/routers/reviews.py
@@ -239,8 +239,8 @@ async def _stage_reposts(db: AsyncSession, review: ReviewRequest) -> None:
)
-async def _emit_review_event(review: ReviewRequest, decision: str) -> None:
- """Best-effort pipeline event after the commit (section 8.3)."""
+async def _stage_review_event(db: AsyncSession, review: ReviewRequest, decision: str) -> None:
+ """Stage the pipeline event alongside the review decision."""
if review.pipeline_run_id is None:
return
try:
@@ -249,9 +249,11 @@ async def _emit_review_event(review: ReviewRequest, decision: str) -> None:
await emit_event(
str(review.pipeline_run_id),
f"review_{decision}",
+ db=db,
+ event_id=uuid.uuid5(review.id, f"review-{decision}"),
detail={"review_id": str(review.id), "reason_code": review.reason_code},
)
- except Exception as exc: # noqa: BLE001 -- the decision is already committed
+ except Exception as exc: # noqa: BLE001 - the review still has its authoritative SQL audit
logger.warning("review event not logged (%s)", type(exc).__name__)
@@ -324,8 +326,8 @@ async def accept_review(
context={"review_id": str(review.id), "pipeline_run_id": str(review.pipeline_run_id or "")},
)
await _stage_reposts(db, review)
+ await _stage_review_event(db, review, "accepted")
await db.commit()
- await _emit_review_event(review, "accepted")
return _to_response(review)
@@ -354,6 +356,6 @@ async def reject_review(
"reason_code": review.reason_code,
},
)
+ await _stage_review_event(db, review, "rejected")
await db.commit()
- await _emit_review_event(review, "rejected")
return _to_response(review)
diff --git a/backend/app/services/activity/events.py b/backend/app/services/activity/events.py
index 8d4f1b776..cfefdc638 100644
--- a/backend/app/services/activity/events.py
+++ b/backend/app/services/activity/events.py
@@ -269,6 +269,7 @@ def _spec(
# fails. A cancel in particular must leave a trace precisely when it did
# NOT tidily succeed.
_spec("analysis.retried", "analysis", "run", "Analysis for {entity_label} was retried ({mode})", "attempt"),
+ _spec("analysis.event_delivery_requeued", "analysis", "project", "{entity_label} was requeued", "outcome"),
_spec("analysis.cancelled", "analysis", "run", "Analysis for {entity_label} was cancelled", "attempt"),
# W14 AGT-12: a tracked bulk job was cancelled (one row per project of the
# job). An attempt write, like the bulk trigger it cancels: the cancel
diff --git a/backend/app/services/agent_investigation_service.py b/backend/app/services/agent_investigation_service.py
index de66bd536..e52b49ef7 100644
--- a/backend/app/services/agent_investigation_service.py
+++ b/backend/app/services/agent_investigation_service.py
@@ -437,7 +437,7 @@ async def write_agent_run_row(
Writes one ``agent_runs`` row and mirrors a durable
``agent_run_recorded`` event to the Mongo pipeline event log. Stage-only
- on the PG side (caller commits); the Mongo mirror is best-effort. The
+ on the PG side (caller commits). The mirror intent shares that transaction. The
Investigator (:func:`record_agent_run`) and the Fixer both funnel through
here so the ledger shape + audit mirror stay identical across agents.
"""
@@ -460,7 +460,8 @@ async def write_agent_run_row(
db.add(entry)
await db.flush()
- # Durable Mongo mirror — same append-only stream the pipeline audit uses.
+ # Stage the mirror before the caller commits, so a rolled back ledger
+ # insertion cannot appear later as a successful materialized record.
try:
from app.services.pipeline_event_log import emit_event
@@ -468,6 +469,10 @@ async def write_agent_run_row(
event_source_id,
"agent_run_recorded",
stage_name=stage_name,
+ db=db,
+ project_id=entry.project_id,
+ test_run_id=entry.run_id,
+ event_id=uuid.uuid5(entry.id, "agent-run-recorded"),
detail={
"agent_run_id": str(entry.id),
"agent_id": entry.agent_id,
diff --git a/backend/app/services/identity_retention_service.py b/backend/app/services/identity_retention_service.py
new file mode 100644
index 000000000..73b48e21c
--- /dev/null
+++ b/backend/app/services/identity_retention_service.py
@@ -0,0 +1,265 @@
+"""Default-off, instance-scoped routine identity retention and independent holds.
+
+SCIM creation events remain live authorization evidence, not disposable logs.
+The policy follows the existing MFA/SCIM setting pattern in app_settings.
+Every mutation and purge locks that single row; holds serialize with deletion.
+Released/expired hold history stays in the never-purged settings audit trail.
+This module stages writes only. The caller owns commit/rollback.
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+import uuid
+
+from pydantic import ValidationError
+from sqlalchemy import and_, case, func, select
+from sqlalchemy.dialects.postgresql import insert
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.identity_retention import (
+ AUTHORITY_EVENT_TYPES, MAX_HOLDS, RETENTION_MAX_DAYS, RETENTION_MIN_DAYS,
+ ROUTINE_EVENT_TYPES, IdentityRetentionDocument, IdentityRetentionHold,
+)
+from app.models.postgres import AppSetting, IdentityEvent, SettingsAuditLog
+from app.services.canonical_json import stable_json_sha256
+
+POLICY_KEY = "identity_event_retention_policy"
+PURGE_AUDIT_KEY = "identity_event_retention_purge"
+RELEASE_CONFIRMATION = "release this identity retention hold"
+PREVIEW_TTL = timedelta(minutes=10)
+ERRORS = {
+ "interactive_admin_required": "Identity retention changes require a signed-in instance administrator.",
+ "policy_unreadable": "Identity retention policy is unreadable; nothing can be purged.",
+ "invalid_days": "Choose an identity retention period between 365 and 3650 days.",
+ "invalid_reason": "A reason of 3 to 500 characters is required.",
+ "preview_stale": "Identity retention changed or the preview expired; preview again.",
+ "confirmation_mismatch": "Type the confirmation exactly as shown.",
+ "retention_disabled": "Routine identity retention is disabled.",
+ "retention_held": "An instance identity hold prevents this purge.",
+ "invalid_expiry": "Hold expiry must be in the future and at most 3650 days ahead.",
+ "hold_not_found": "Identity retention hold not found.",
+ "hold_limit": "The active identity hold limit has been reached; retention remains held.",
+ "invalid_batch": "An identity retention batch must contain between 1 and 500 events.",
+}
+
+
+class IdentityRetentionError(Exception):
+ def __init__(self, code: str, status_code: int = 409):
+ self.code, self.status_code = code, status_code
+ super().__init__(ERRORS[code])
+
+
+def aware(now: datetime) -> datetime:
+ if now.tzinfo is None:
+ raise ValueError("identity retention requires an aware UTC timestamp")
+ return now.astimezone(timezone.utc)
+
+
+def require_interactive_admin(actor) -> None:
+ from app.core.deps import CREDENTIAL_KIND_JWT, credential_kind
+
+ role = getattr(actor, "role", None)
+ if getattr(role, "value", role) != "ADMIN" or credential_kind(actor) != CREDENTIAL_KIND_JWT:
+ raise IdentityRetentionError("interactive_admin_required", 403)
+
+
+def clean_reason(reason: str) -> str:
+ value = reason.strip()
+ if not 3 <= len(value) <= 500:
+ raise IdentityRetentionError("invalid_reason", 422)
+ return value
+
+
+def live_holds(policy: IdentityRetentionDocument, now: datetime) -> list[IdentityRetentionHold]:
+ now = aware(now)
+ return [hold for hold in policy.holds if hold.expires_at is None or hold.expires_at > now]
+
+
+def document(row: AppSetting | None) -> IdentityRetentionDocument:
+ if row is None:
+ return IdentityRetentionDocument()
+ if row.is_secret_backed or row.secret_ref_id is not None or not isinstance(row.value, dict):
+ raise IdentityRetentionError("policy_unreadable")
+ try:
+ return IdentityRetentionDocument.model_validate(row.value)
+ except ValidationError as exc:
+ raise IdentityRetentionError("policy_unreadable") from exc
+
+
+async def policy_row(db: AsyncSession, *, lock: bool = False, create: bool = False) -> AppSetting | None:
+ statement = select(AppSetting).where(AppSetting.key == POLICY_KEY)
+ if lock:
+ statement = statement.with_for_update().execution_options(populate_existing=True)
+ row = (await db.execute(statement)).scalar_one_or_none()
+ if row is None and create:
+ await db.execute(insert(AppSetting).values(
+ key=POLICY_KEY, value=IdentityRetentionDocument().model_dump(mode="json"), is_secret_backed=False,
+ ).on_conflict_do_nothing(index_elements=[AppSetting.key]))
+ row = (await db.execute(statement)).scalar_one()
+ return row
+
+
+async def read_policy(db, *, now: datetime) -> dict:
+ policy = document(await policy_row(db))
+ return {**policy.model_dump(mode="json"), "active_hold_count": len(live_holds(policy, now))}
+
+
+def enable_confirmation(days: int) -> str:
+ return f"enable routine identity retention ({days} days)"
+
+
+def purge_confirmation(days: int) -> str:
+ return f"purge routine identity events older than {days} days"
+
+
+def routine_event_clause():
+ # A malformed/legacy failure recorded under a routine event name is still
+ # security evidence. Positive success, not merely its type, is required.
+ return and_(IdentityEvent.event_type.in_(ROUTINE_EVENT_TYPES), IdentityEvent.success.is_(True))
+
+
+async def preview(db, *, now: datetime, retention_days: int | None = None, policy=None) -> dict:
+ observed = aware(now)
+ policy = policy if policy is not None else document(await policy_row(db))
+ days = policy.retention_days if retention_days is None else retention_days
+ if type(days) is not int or not RETENTION_MIN_DAYS <= days <= RETENTION_MAX_DAYS:
+ raise IdentityRetentionError("invalid_days", 422)
+ cutoff = observed - timedelta(days=days)
+ record_class = case(
+ (routine_event_clause(), "routine_authentication"),
+ (IdentityEvent.event_type.in_(AUTHORITY_EVENT_TYPES), "scim_authority"),
+ else_="protected_identity",
+ )
+ rows = (await db.execute(select(record_class, func.count()).where(
+ IdentityEvent.created_at < cutoff,
+ ).group_by(record_class))).all()
+ counts = dict.fromkeys(("routine_authentication", "scim_authority", "protected_identity"), 0)
+ counts.update({name: int(count) for name, count in rows})
+ payload = {
+ "observed_at": observed, "cutoff": cutoff, "retention_days": days,
+ "enabled": policy.enabled, "active_hold_count": len(live_holds(policy, observed)), "counts": counts,
+ "enable_confirmation": enable_confirmation(days), "purge_confirmation": purge_confirmation(days),
+ }
+ payload["preview_hash"] = stable_json_sha256({
+ "observed_at": observed.isoformat(), "days": days, "counts": counts,
+ "policy": policy.model_dump(mode="json"),
+ })
+ return payload
+
+
+async def verify_preview(db, *, policy, observed_at, now, retention_days, preview_hash):
+ observed, current = aware(observed_at), aware(now)
+ if observed > current + timedelta(seconds=5) or current - observed > PREVIEW_TTL:
+ raise IdentityRetentionError("preview_stale")
+ snapshot = await preview(db, now=observed, retention_days=retention_days, policy=policy)
+ if snapshot["preview_hash"] != preview_hash:
+ raise IdentityRetentionError("preview_stale")
+ return snapshot
+
+
+def audit(db, *, actor, action, policy, reason, details=None, audit_id=None, setting_key=POLICY_KEY):
+ row = SettingsAuditLog(
+ id=audit_id or uuid.uuid4(), setting_key=setting_key, action=action,
+ actor_id=getattr(actor, "id", None),
+ actor_name=(getattr(actor, "full_name", None) or getattr(actor, "username", None)) if actor else None,
+ reason=reason,
+ changed_fields={"policy_revision": policy.revision, "record_class": "routine_authentication",
+ "reason": reason, **(details or {})},
+ )
+ db.add(row)
+ return row
+
+
+async def approve_policy(db, *, actor, retention_days, observed_at, preview_hash, confirmation, reason, now):
+ require_interactive_admin(actor)
+ reason, now = clean_reason(reason), aware(now)
+ row = await policy_row(db, lock=True, create=True)
+ policy = document(row)
+ await verify_preview(db, policy=policy, observed_at=observed_at, now=now,
+ retention_days=retention_days, preview_hash=preview_hash)
+ if confirmation != enable_confirmation(retention_days):
+ raise IdentityRetentionError("confirmation_mismatch", 422)
+ updated = policy.model_copy(update={
+ "enabled": True, "retention_days": retention_days,
+ "approved_at": now, "revision": policy.revision + 1,
+ })
+ row.value, row.updated_by = updated.model_dump(mode="json"), actor.id
+ audit(db, actor=actor, action="enabled", policy=updated, reason=reason, details={
+ "before": {"enabled": policy.enabled, "retention_days": policy.retention_days},
+ "after": {"enabled": True, "retention_days": retention_days},
+ })
+ await db.flush()
+ return updated
+
+
+async def disable_policy(db, *, actor, reason):
+ require_interactive_admin(actor)
+ reason = clean_reason(reason)
+ row = await policy_row(db, lock=True, create=True)
+ policy = document(row)
+ updated = policy.model_copy(update={"enabled": False, "revision": policy.revision + 1})
+ row.value, row.updated_by = updated.model_dump(mode="json"), actor.id
+ audit(db, actor=actor, action="disabled", policy=updated, reason=reason)
+ await db.flush()
+ return updated
+
+
+async def place_hold(db, *, actor, reason, expires_at, now):
+ require_interactive_admin(actor)
+ reason, now = clean_reason(reason), aware(now)
+ expires = None if expires_at is None else aware(expires_at)
+ if expires is not None and not now < expires <= now + timedelta(days=3650):
+ raise IdentityRetentionError("invalid_expiry", 422)
+ row = await policy_row(db, lock=True, create=True)
+ policy = document(row)
+ active = live_holds(policy, now)
+ if len(active) >= MAX_HOLDS:
+ raise IdentityRetentionError("hold_limit")
+ hold = IdentityRetentionHold(id=uuid.uuid4(), reason=reason, placed_at=now, expires_at=expires, audit_id=uuid.uuid4())
+ updated = policy.model_copy(update={"holds": [*active, hold], "revision": policy.revision + 1})
+ row.value, row.updated_by = updated.model_dump(mode="json"), actor.id
+ audit(db, actor=actor, action="hold_placed", policy=updated, reason=reason,
+ details={"hold": hold.model_dump(mode="json")}, audit_id=hold.audit_id)
+ await db.flush()
+ return hold
+
+
+async def release_hold(db, *, actor, hold_id, reason, confirmation, now):
+ require_interactive_admin(actor)
+ reason, now = clean_reason(reason), aware(now)
+ if confirmation != RELEASE_CONFIRMATION:
+ raise IdentityRetentionError("confirmation_mismatch", 422)
+ row = await policy_row(db, lock=True)
+ policy = document(row)
+ hold = next((item for item in policy.holds if item.id == hold_id), None)
+ if hold is None:
+ raise IdentityRetentionError("hold_not_found", 404)
+ updated = policy.model_copy(update={
+ "holds": [item for item in live_holds(policy, now) if item.id != hold_id], "revision": policy.revision + 1,
+ })
+ row.value, row.updated_by = updated.model_dump(mode="json"), actor.id
+ audit(db, actor=actor, action="hold_released", policy=updated, reason=reason,
+ details={"hold": hold.model_dump(mode="json")})
+ await db.flush()
+ return updated
+
+
+async def run_scheduled_batch(*, now: datetime | None = None) -> dict:
+ """One approved instance batch, only in the existing instance UTC window.
+
+ Default-off is independent of project retention enablement. Never call
+ this from an explicit project purge: identity events are instance scoped.
+ """
+ from app.db.postgres import AsyncSessionLocal
+ from app.services.retention_instance_service import get_instance_policy
+ from app.services.retention_service import purge_identity_events_batch
+
+ observed = aware(now or datetime.now(timezone.utc))
+ async with AsyncSessionLocal() as db:
+ instance = await get_instance_policy(db)
+ hour = instance.purge_window_start_utc if instance.purge_window_start_utc is not None else 2
+ if observed.hour != hour:
+ return {"status": "outside_window", "deleted": 0}
+ result = await purge_identity_events_batch(db, now=observed, scheduled=True)
+ await db.commit()
+ return result
diff --git a/backend/app/services/metric_collection.py b/backend/app/services/metric_collection.py
index ff3805b4d..efab73167 100644
--- a/backend/app/services/metric_collection.py
+++ b/backend/app/services/metric_collection.py
@@ -17,7 +17,7 @@
logger = structlog.get_logger(__name__)
COLLECTION_TIMEOUT_SECONDS = 1.0
-COLLECTORS = ("queues", "agents", "downstream", "redis", "nightly", "digests")
+COLLECTORS = ("queues", "agents", "downstream", "redis", "nightly", "digests", "pipeline_events")
@dataclass
diff --git a/backend/app/services/pipeline_event_admission.py b/backend/app/services/pipeline_event_admission.py
new file mode 100644
index 000000000..31e2af7df
--- /dev/null
+++ b/backend/app/services/pipeline_event_admission.py
@@ -0,0 +1,156 @@
+"""Project-scoped admission and purge fencing for pipeline event evidence."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from datetime import date, datetime
+from typing import Any, cast
+from uuid import UUID
+
+from sqlalchemy import BigInteger, delete, func, literal, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.postgres import AgentPipelineRun, PipelineEventOutbox, TestCase, TestRun
+from app.services.evidence_sanitizer import sanitize_persistence_payload
+
+PIPELINE_EVENT_CAPACITY = 10_000
+MAX_PIPELINE_EVENT_BYTES = 16_384
+_ADMISSION_LOCK = 0x544C50454F555442
+# The resolved run UUID can replace JSON null after source scope is checked.
+_RUN_ID_GROWTH_BYTES = 34
+
+
+class EventAdmissionError(Exception):
+ """A safe, bounded reason for an event that could not be admitted."""
+
+
+def as_uuid(value: UUID | str | None) -> UUID | None:
+ if isinstance(value, UUID):
+ return value
+ try:
+ return UUID(value) if value else None
+ except ValueError:
+ return None
+
+
+def _json_value(value: object) -> str:
+ if isinstance(value, (datetime, date)):
+ return value.isoformat()
+ if isinstance(value, UUID):
+ return str(value)
+ raise TypeError("Unsupported event value")
+
+
+def bounded_event_payload(event: dict[str, Any]) -> dict[str, Any]:
+ """Retain event identity even when optional detail cannot be stored."""
+ payload = event.copy()
+ try:
+ detail, _ = sanitize_persistence_payload(event["detail"])
+ payload["detail"] = detail
+ serialized = json.dumps(payload, default=_json_value, allow_nan=False, ensure_ascii=False)
+ reserved = _RUN_ID_GROWTH_BYTES if payload.get("test_run_id") is None else 0
+ if len(serialized.encode("utf-8")) + reserved <= MAX_PIPELINE_EVENT_BYTES:
+ return cast(dict[str, Any], json.loads(serialized))
+ except (TypeError, ValueError, UnicodeError, OverflowError):
+ pass
+ payload["detail"] = {"detail_omitted": "size_or_content"}
+ return cast(dict[str, Any], json.loads(json.dumps(payload, default=_json_value, allow_nan=False)))
+
+
+async def lock_project_event_history(db: AsyncSession, project_id: UUID, *, exclusive: bool = False) -> bool:
+ """Serialize Mongo-first policy deletion with SQL admission and delivery."""
+ if db.get_bind().dialect.name != "postgresql":
+ return True
+ key = literal(int.from_bytes(hashlib.blake2b(
+ project_id.bytes, digest_size=8, person=b"tl-event-project",
+ ).digest(), "big", signed=True), type_=BigInteger())
+ if exclusive:
+ await db.execute(select(func.pg_advisory_xact_lock(key)))
+ return True
+ return bool(await db.scalar(select(func.pg_try_advisory_xact_lock_shared(key))))
+
+
+async def _source_scope(
+ db: AsyncSession, event: dict[str, Any], supplied_project_id: UUID | str | None,
+) -> tuple[UUID, UUID | None, UUID | None, UUID | None]:
+ project_id = as_uuid(supplied_project_id)
+ pipeline_id = as_uuid(event["pipeline_run_id"])
+ test_run_id = as_uuid(event.get("test_run_id"))
+ case_id = as_uuid(event["test_case_id"])
+ if pipeline_id:
+ pipeline = (await db.execute(
+ select(TestRun.id, TestRun.project_id).join(AgentPipelineRun, AgentPipelineRun.test_run_id == TestRun.id)
+ .where(AgentPipelineRun.id == pipeline_id)
+ )).one_or_none()
+ if pipeline is None:
+ if project_id is None or event["event_type"] != "agent_run_recorded":
+ raise EventAdmissionError("scope")
+ # These ledger writers use the committed investigation or fixer
+ # identity as their correlation ID, rather than a pipeline UUID.
+ pipeline_id = None
+ else:
+ if (project_id and pipeline.project_id != project_id) or (test_run_id and pipeline.id != test_run_id):
+ raise EventAdmissionError("scope")
+ project_id, test_run_id = pipeline.project_id, pipeline.id
+ if case_id:
+ case = (await db.execute(
+ select(TestRun.id, TestRun.project_id).join(TestCase, TestCase.test_run_id == TestRun.id)
+ .where(TestCase.id == case_id)
+ )).one_or_none()
+ if case is None or (project_id and case.project_id != project_id) or (test_run_id and case.id != test_run_id):
+ raise EventAdmissionError("scope")
+ project_id, test_run_id = case.project_id, case.id
+ if test_run_id and not (pipeline_id or case_id):
+ run_project = await db.scalar(select(TestRun.project_id).where(TestRun.id == test_run_id))
+ if run_project is None or (project_id and run_project != project_id):
+ raise EventAdmissionError("scope")
+ project_id = run_project
+ if project_id is None:
+ raise EventAdmissionError("scope")
+ return project_id, pipeline_id, test_run_id, case_id
+
+
+async def stage_pipeline_event(
+ db: AsyncSession, *, event_id: UUID, event: dict[str, Any], project_id: UUID | str | None,
+) -> None:
+ """Stage the event in the caller's transaction without committing it."""
+ scope, pipeline_id, test_run_id, case_id = await _source_scope(db, event, project_id)
+ event = {**event, "test_run_id": str(test_run_id) if test_run_id else None}
+ if not await lock_project_event_history(db, scope):
+ raise EventAdmissionError("contention")
+ if db.get_bind().dialect.name == "postgresql":
+ quota_key = literal(_ADMISSION_LOCK, type_=BigInteger())
+ if not await db.scalar(select(func.pg_try_advisory_xact_lock(quota_key))):
+ raise EventAdmissionError("contention")
+ previous = await db.get(PipelineEventOutbox, event_id)
+ if previous is not None:
+ prior = {key: value for key, value in previous.payload.items() if key != "timestamp"}
+ current = {key: value for key, value in event.items() if key != "timestamp"}
+ if previous.project_id != scope or prior != current:
+ raise EventAdmissionError("conflict")
+ return
+ existing = await db.scalar(select(func.count()).select_from(PipelineEventOutbox))
+ if existing is None or existing >= PIPELINE_EVENT_CAPACITY:
+ raise EventAdmissionError("capacity")
+ db.add(PipelineEventOutbox(
+ id=event_id, project_id=scope, pipeline_id=pipeline_id, test_run_id=test_run_id, test_case_id=case_id,
+ pipeline_run_id=event["pipeline_run_id"], payload=event, next_attempt_at=datetime.fromisoformat(event["timestamp"]),
+ ))
+ await db.flush()
+
+
+async def purge_pipeline_event_intents(
+ db: AsyncSession, project_id: UUID, *, pipeline_run_ids: set[str], test_run_ids: set[UUID],
+) -> None:
+ """Fence replay before the existing Mongo deletes, within the purge transaction."""
+ if not pipeline_run_ids and not test_run_ids:
+ return
+ await lock_project_event_history(db, project_id, exclusive=True)
+ statement = delete(PipelineEventOutbox).where(PipelineEventOutbox.project_id == project_id)
+ ordered = sorted(pipeline_run_ids)
+ for offset in range(0, len(ordered), 500):
+ await db.execute(statement.where(PipelineEventOutbox.pipeline_run_id.in_(ordered[offset:offset + 500])))
+ runs = sorted(test_run_ids)
+ for offset in range(0, len(runs), 500):
+ await db.execute(statement.where(PipelineEventOutbox.test_run_id.in_(runs[offset:offset + 500])))
diff --git a/backend/app/services/pipeline_event_delivery.py b/backend/app/services/pipeline_event_delivery.py
new file mode 100644
index 000000000..4e69352b2
--- /dev/null
+++ b/backend/app/services/pipeline_event_delivery.py
@@ -0,0 +1,263 @@
+"""Bounded, append-only materialization of shared pipeline-event intents."""
+from __future__ import annotations
+
+import copy
+from datetime import datetime, timedelta, timezone
+import time
+from typing import Any, cast
+import uuid
+
+import pymongo
+from pymongo.errors import DuplicateKeyError, PyMongoError
+from pymongo.read_preferences import ReadPreference
+from pymongo.write_concern import WriteConcern
+from sqlalchemy import delete, func, or_, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.postgres import PipelineEventOutbox
+
+STATUSES = ("pending", "sending", "delivered", "failed")
+MAX_ATTEMPTS = 8
+LEASE_SECONDS = 120
+MONGO_TIMEOUT_SECONDS = 2.0
+DELIVERED_RETENTION_SECONDS = 3600
+PRUNE_BATCH_SIZE = 100
+
+
+class EventIdentityConflict(ValueError):
+ """An existing immutable Mongo document has different content."""
+
+
+class EventPayloadInvalid(ValueError):
+ """The stored intent is not a valid scoped event envelope."""
+
+
+def _utcnow() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _utc(value: datetime) -> datetime:
+ return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value.astimezone(timezone.utc)
+
+
+def _document(row: PipelineEventOutbox) -> dict[str, Any]:
+ document = copy.deepcopy(row.payload)
+ if not isinstance(document, dict) or document.get("pipeline_run_id") != row.pipeline_run_id:
+ raise EventPayloadInvalid()
+ if document.get("event_id", str(row.id)) != str(row.id) or document.get("project_id", str(row.project_id)) != str(row.project_id):
+ raise EventPayloadInvalid()
+ try:
+ timestamp = datetime.fromisoformat(document["timestamp"])
+ except (KeyError, TypeError, ValueError) as error:
+ raise EventPayloadInvalid() from error
+ if timestamp.tzinfo is None or not isinstance(document.get("event_type"), str):
+ raise EventPayloadInvalid()
+ timestamp = _utc(timestamp)
+ # BSON dates have millisecond precision; normalize before insert and
+ # duplicate comparison instead of misclassifying a legitimate retry.
+ document["timestamp"] = timestamp.replace(microsecond=timestamp.microsecond // 1000 * 1000)
+ document.update(_id=str(row.id), event_id=str(row.id), project_id=str(row.project_id))
+ return document
+
+
+def _same_document(existing: dict[str, Any] | None, expected: dict[str, Any]) -> bool:
+ if not isinstance(existing, dict):
+ return False
+ document = copy.deepcopy(existing)
+ if isinstance(document.get("timestamp"), datetime):
+ document["timestamp"] = _utc(document["timestamp"])
+ # An explicitly reused event ID can be staged after its SQL receipt was
+ # pruned. Preserve Mongo's original timestamp; a new intake timestamp is
+ # transport metadata, never permission to modify logical event content.
+ document.pop("timestamp", None)
+ canonical = copy.deepcopy(expected)
+ canonical.pop("timestamp", None)
+ return document == canonical
+
+
+async def _materialize(row: PipelineEventOutbox) -> None:
+ from app.db.mongo import get_mongo_db
+
+ document = _document(row)
+ source = get_mongo_db()["pipeline_event_log"]
+ concern = dict(source.write_concern.document)
+ # Never downgrade a site's majority/custom acknowledgement requirement.
+ # An unacknowledged collection cannot settle durable SQL evidence.
+ if concern.get("w") in (None, 0):
+ concern["w"] = 1
+ concern["j"] = True
+ configured_timeout = concern.get("wtimeout")
+ limit_ms = int(MONGO_TIMEOUT_SECONDS * 1000)
+ concern["wtimeout"] = min(configured_timeout, limit_ms) if isinstance(configured_timeout, int) and configured_timeout > 0 else limit_ms
+ collection = source.with_options(
+ # Motor's annotation names the ReadPreference container, whereas
+ # PyMongo supplies its supported Primary mode instance.
+ write_concern=WriteConcern(**concern), read_preference=cast(Any, ReadPreference.PRIMARY),
+ )
+ # Driver-level CSOT bounds selection, checkout and network operations for
+ # Motor as well. No detached Mongo task may outlive the SQL purge fence.
+ with pymongo.timeout(MONGO_TIMEOUT_SECONDS):
+ try:
+ await collection.insert_one(document)
+ except DuplicateKeyError:
+ existing = await collection.find_one({"_id": str(row.id)})
+ if not _same_document(existing, document):
+ raise EventIdentityConflict() from None
+
+
+async def _claim_one() -> tuple[uuid.UUID, uuid.UUID, uuid.UUID] | None:
+ from app.db.postgres import AsyncSessionLocal
+
+ now = _utcnow()
+ eligible = or_(
+ (PipelineEventOutbox.status == "pending") & (
+ PipelineEventOutbox.next_attempt_at.is_(None) | (PipelineEventOutbox.next_attempt_at <= now)
+ ),
+ (PipelineEventOutbox.status == "sending") & (
+ PipelineEventOutbox.lease_expires_at.is_(None) | (PipelineEventOutbox.lease_expires_at <= now)
+ ),
+ )
+ async with AsyncSessionLocal() as db:
+ row = (await db.execute(
+ select(PipelineEventOutbox).where(eligible)
+ .order_by(PipelineEventOutbox.created_at, PipelineEventOutbox.id)
+ .with_for_update(skip_locked=True).limit(1)
+ )).scalar_one_or_none()
+ if row is None:
+ return None
+ if row.attempts >= MAX_ATTEMPTS:
+ row.status = "failed"
+ row.last_error_code = row.last_error_code or "attempts_exhausted"
+ row.lease_token = None
+ row.lease_expires_at = None
+ row.next_attempt_at = None
+ await db.commit()
+ return row.id, row.project_id, uuid.UUID(int=0)
+ token = uuid.uuid4()
+ row.status = "sending"
+ row.attempts += 1
+ row.lease_token = token
+ row.lease_expires_at = now + timedelta(seconds=LEASE_SECONDS)
+ await db.commit()
+ return row.id, row.project_id, token
+
+
+def _error_code(error: Exception) -> str:
+ if isinstance(error, EventIdentityConflict):
+ return "identity_conflict"
+ if isinstance(error, EventPayloadInvalid):
+ return "payload_invalid"
+ if isinstance(error, PyMongoError):
+ return "mongo_timeout" if error.timeout else "mongo_unavailable"
+ if isinstance(error, TimeoutError):
+ return "mongo_timeout"
+ return "delivery_error"
+
+
+async def _deliver_owned(event_id: uuid.UUID, project_id: uuid.UUID, token: uuid.UUID) -> str:
+ from app.db.postgres import AsyncSessionLocal
+ from app.services.pipeline_event_admission import lock_project_event_history
+
+ if token.int == 0:
+ return "failed"
+ async with AsyncSessionLocal() as db:
+ # Match purge's project -> row lock order. Holding the row lock alone
+ # while waiting for a project lock would introduce a deadlock.
+ if not await lock_project_event_history(db, project_id):
+ return "deferred"
+ row = (await db.execute(
+ select(PipelineEventOutbox).where(
+ PipelineEventOutbox.id == event_id,
+ PipelineEventOutbox.project_id == project_id,
+ PipelineEventOutbox.status == "sending",
+ PipelineEventOutbox.lease_token == token,
+ ).with_for_update()
+ )).scalar_one_or_none()
+ if row is None:
+ return "stale"
+ try:
+ await _materialize(row)
+ except Exception as error:
+ code = _error_code(error)
+ row.last_error_code = code
+ terminal = code in {"identity_conflict", "payload_invalid"} or row.attempts >= MAX_ATTEMPTS
+ row.status = "failed" if terminal else "pending"
+ row.next_attempt_at = None if terminal else _utcnow() + timedelta(seconds=min(300, 2 ** row.attempts))
+ outcome = "failed" if terminal else "retry"
+ else:
+ row.status = "delivered"
+ row.last_error_code = None
+ row.delivered_at = _utcnow()
+ row.next_attempt_at = None
+ outcome = "delivered"
+ row.lease_token = None
+ row.lease_expires_at = None
+ await db.commit()
+ return outcome
+
+
+async def prune_delivered_events(*, limit: int = PRUNE_BATCH_SIZE) -> int:
+ """Release receipt capacity only after durable Mongo acknowledgement."""
+ from app.db.postgres import AsyncSessionLocal
+ from app.services.pipeline_event_admission import PIPELINE_EVENT_CAPACITY
+
+ if not 1 <= limit <= PRUNE_BATCH_SIZE:
+ raise ValueError("invalid pipeline event prune limit")
+ async with AsyncSessionLocal() as db:
+ total = await db.scalar(select(func.count()).select_from(PipelineEventOutbox))
+ pressure = int(total or 0) * 10 >= PIPELINE_EVENT_CAPACITY * 9
+ eligible = (PipelineEventOutbox.status == "delivered") & PipelineEventOutbox.delivered_at.is_not(None)
+ if not pressure:
+ eligible = eligible & (PipelineEventOutbox.delivered_at < _utcnow() - timedelta(seconds=DELIVERED_RETENTION_SECONDS))
+ ids = list((await db.scalars(
+ select(PipelineEventOutbox.id).where(eligible)
+ .order_by(PipelineEventOutbox.delivered_at).with_for_update(skip_locked=True).limit(limit)
+ )).all())
+ if ids:
+ await db.execute(delete(PipelineEventOutbox).where(PipelineEventOutbox.id.in_(ids)))
+ await db.commit()
+ return len(ids)
+
+
+async def relay_pipeline_events(*, batch_size: int = 50, max_seconds: float = 20.0) -> dict[str, int]:
+ """Materialize at most one bounded batch; cancellation preserves its lease."""
+ if not 1 <= batch_size <= 100 or not 0 < max_seconds <= 30:
+ raise ValueError("invalid pipeline event replay bound")
+ results = dict.fromkeys(("delivered", "retry", "failed", "deferred", "stale"), 0)
+ deadline = time.monotonic() + max_seconds
+ for _ in range(batch_size):
+ if time.monotonic() >= deadline:
+ break
+ claim = await _claim_one()
+ if claim is None:
+ break
+ outcome = await _deliver_owned(*claim)
+ results[outcome] += 1
+ results["pruned"] = await prune_delivered_events()
+ return results
+
+
+async def requeue_failed_event(
+ db: AsyncSession, event_id: uuid.UUID, *, project_id: uuid.UUID,
+) -> dict[str, Any] | None:
+ """Stage one explicit retry, with authorization/audit/commit owned by caller."""
+ from app.services.pipeline_event_admission import lock_project_event_history
+
+ if not await lock_project_event_history(db, project_id):
+ raise RuntimeError("pipeline_event_history_busy")
+ row = (await db.execute(select(PipelineEventOutbox).where(
+ PipelineEventOutbox.id == event_id, PipelineEventOutbox.project_id == project_id,
+ ).with_for_update())).scalar_one_or_none()
+ if row is None:
+ return None
+ if row.status != "failed":
+ raise ValueError("pipeline_event_not_failed")
+ previous_attempts = row.attempts
+ row.status = "pending"
+ row.attempts = 0
+ row.next_attempt_at = _utcnow()
+ row.lease_token = None
+ row.lease_expires_at = None
+ # Keep the compact previous error until a successful materialization.
+ await db.flush()
+ return {"event_id": str(row.id), "project_id": str(row.project_id), "status": "pending", "previous_attempts": previous_attempts}
diff --git a/backend/app/services/pipeline_event_log.py b/backend/app/services/pipeline_event_log.py
index b4812cf07..36ca997f0 100644
--- a/backend/app/services/pipeline_event_log.py
+++ b/backend/app/services/pipeline_event_log.py
@@ -13,41 +13,37 @@
3. Audit — immutable timeline of all pipeline actions
4. Cost tracking — count LLM calls and tool invocations per run
-Events are append-only (insert, never update or delete).
+The SQL outbox accepts event intent. Materialization creates one immutable
+Mongo document per event ID. Authorized retention handles deletion.
"""
-import logging
import asyncio
+import logging
+import re
from datetime import datetime, timezone
from typing import Any, Optional
+from uuid import UUID, uuid4
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
-from app.db.mongo import get_mongo_db
+from app.db.mongo import Collections, get_mongo_db
+from app.db.postgres import get_session_factory
+from app.models.postgres import PipelineEventOutbox
+from app.services.pipeline_event_admission import EventAdmissionError, bounded_event_payload, stage_pipeline_event
logger = logging.getLogger("services.pipeline_event_log")
-_COLLECTION = "pipeline_event_log"
-_MAX_WRITE_ATTEMPTS = 2
-_DEAD_LETTER_LIMIT = 200
-_WRITE_FAILURE_COUNT = 0
-_DEAD_LETTER_EVENTS: list[dict[str, Any]] = []
-
-
-def _record_dead_letter(event: dict[str, Any], error: Exception) -> None:
- """Keep bounded accounting for audit writes that could not reach Mongo."""
- global _WRITE_FAILURE_COUNT
- _WRITE_FAILURE_COUNT += 1
- _DEAD_LETTER_EVENTS.append({
- "failed_at": datetime.now(timezone.utc).isoformat(),
- "error": str(error)[:500],
- "event": {
- "pipeline_run_id": event.get("pipeline_run_id"),
- "event_type": event.get("event_type"),
- "stage_name": event.get("stage_name"),
- "test_case_id": event.get("test_case_id"),
- "detail": event.get("detail", {}),
- },
- })
- if len(_DEAD_LETTER_EVENTS) > _DEAD_LETTER_LIMIT:
- del _DEAD_LETTER_EVENTS[: len(_DEAD_LETTER_EVENTS) - _DEAD_LETTER_LIMIT]
+_COLLECTION = Collections.PIPELINE_EVENT_LOG
+_SOURCE_NAME = re.compile(r"[A-Za-z0-9._:-]{0,128}")
+_ADMISSION_SECONDS = 2
+
+
+def _admission_failure(event_id: UUID, reason: str) -> bool:
+ from app.core.metrics import pipeline_event_admission_failures
+
+ pipeline_event_admission_failures.labels(reason=reason).inc()
+ logger.warning("Pipeline event not confirmed, event_id=%s reason=%s", event_id, reason)
+ return False
async def emit_event(
@@ -55,67 +51,102 @@ async def emit_event(
event_type: str,
*,
stage_name: Optional[str] = None,
- test_case_id: Optional[str] = None,
+ test_case_id: str | UUID | None = None,
detail: Optional[dict[str, Any]] = None,
-) -> None:
- """
- Append an immutable event to the pipeline event log.
-
- Args:
- pipeline_run_id: The pipeline run this event belongs to.
- event_type: One of: stage_started, stage_completed, stage_failed,
- stage_skipped, tool_invoked, llm_called, cache_hit,
- checkpoint_restored, error_occurred, pipeline_completed.
- stage_name: The pipeline stage (optional, depends on event type).
- test_case_id: The test case ID (optional, for per-test events).
- detail: Additional event-specific data.
- """
+ db: AsyncSession | None = None,
+ project_id: UUID | str | None = None,
+ test_run_id: UUID | None = None,
+ event_id: UUID | None = None,
+) -> bool:
+ """Admit one event or stage it atomically with an uncommitted source write."""
+ identity = event_id or uuid4()
+ if isinstance(test_case_id, UUID):
+ test_case_id = str(test_case_id)
+ required = (pipeline_run_id, event_type)
+ optional = (stage_name, test_case_id)
+ if not event_type or any(not isinstance(x, str) or not _SOURCE_NAME.fullmatch(x) for x in required):
+ return _admission_failure(identity, "payload")
+ if any(x is not None and (not isinstance(x, str) or not _SOURCE_NAME.fullmatch(x)) for x in optional):
+ return _admission_failure(identity, "payload")
event = {
+ "event_id": str(identity),
"pipeline_run_id": pipeline_run_id,
"event_type": event_type,
- "timestamp": datetime.now(timezone.utc),
+ "timestamp": datetime.now(timezone.utc).isoformat(),
"stage_name": stage_name,
"test_case_id": test_case_id,
+ "test_run_id": str(test_run_id) if test_run_id else None,
"detail": detail or {},
}
- last_error: Exception | None = None
- for attempt in range(1, _MAX_WRITE_ATTEMPTS + 1):
+ try:
+ payload = bounded_event_payload(event)
+ async with asyncio.timeout(_ADMISSION_SECONDS):
+ if db is not None:
+ async with db.begin_nested():
+ await stage_pipeline_event(db, event_id=identity, event=payload, project_id=project_id)
+ else:
+ async with get_session_factory().begin() as session:
+ await stage_pipeline_event(session, event_id=identity, event=payload, project_id=project_id)
+ except EventAdmissionError as exc:
+ return _admission_failure(identity, str(exc))
+ except Exception: # noqa: BLE001 - do not replace business outcomes with optional event errors
+ return _admission_failure(identity, "storage")
+ return True
+
+
+def _event_time(event: dict) -> datetime:
+ timestamp = event.get("timestamp")
+ if isinstance(timestamp, str):
try:
- db = get_mongo_db()
- await db[_COLLECTION].insert_one(event)
- return
- except Exception as exc:
- last_error = exc
- if attempt < _MAX_WRITE_ATTEMPTS:
- await asyncio.sleep(0)
-
- # Event logging is best-effort — never fail the pipeline — but failed
- # writes are now counted and retained so operators can audit gaps.
- if last_error is not None:
- _record_dead_letter(event, last_error)
- logger.warning(
- "Pipeline event log write failed after %s attempts: %s",
- _MAX_WRITE_ATTEMPTS,
- last_error,
- )
-
-
-async def get_pipeline_timeline(pipeline_run_id: str) -> list[dict]:
- """
- Retrieve the full event timeline for a pipeline run.
-
- Returns events sorted by timestamp (oldest first).
- """
+ timestamp = datetime.fromisoformat(timestamp)
+ except ValueError:
+ timestamp = None
+ if not isinstance(timestamp, datetime):
+ return datetime.min.replace(tzinfo=timezone.utc)
+ return timestamp if timestamp.tzinfo else timestamp.replace(tzinfo=timezone.utc)
+
+
+async def _read_retained_events(pipeline_run_id: str, db: AsyncSession | None) -> list[dict]:
+ statement = (
+ select(PipelineEventOutbox.payload)
+ .where(PipelineEventOutbox.pipeline_run_id == pipeline_run_id)
+ .order_by(PipelineEventOutbox.created_at, PipelineEventOutbox.id)
+ .limit(500)
+ )
+ if db is not None:
+ return list((await db.scalars(statement)).all())
+ async with get_session_factory()() as session:
+ return list((await session.scalars(statement)).all())
+
+
+async def get_pipeline_timeline(pipeline_run_id: str, *, db: AsyncSession | None = None) -> list[dict]:
+ """Read both accepted intents and materialized history, oldest first."""
try:
- db = get_mongo_db()
- cursor = db[_COLLECTION].find(
+ if db is None:
+ async with asyncio.timeout(_ADMISSION_SECONDS):
+ accepted = await _read_retained_events(pipeline_run_id, db)
+ else:
+ # Keep an unavailable or pre-migration outbox from aborting this
+ # request's transaction and the already-authorized Mongo read.
+ async with db.begin_nested():
+ accepted = await _read_retained_events(pipeline_run_id, db)
+ except Exception as exc: # noqa: BLE001 - preserve the materialized view
+ logger.warning("Pipeline event outbox timeline unavailable (%s)", type(exc).__name__)
+ accepted = []
+ try:
+ mongo = get_mongo_db()
+ cursor = mongo[_COLLECTION].find(
{"pipeline_run_id": pipeline_run_id},
{"_id": 0},
- ).sort("timestamp", 1)
- return await cursor.to_list(length=500)
+ ).sort([("timestamp", 1), ("_id", 1)])
+ materialized = await cursor.to_list(length=500)
except Exception as exc:
- logger.warning("Pipeline timeline query failed: %s", exc)
- return []
+ logger.warning("Pipeline timeline query failed (%s)", type(exc).__name__)
+ materialized = []
+ seen = {event.get("event_id") for event in materialized}
+ merged = [*materialized, *(event for event in accepted if event["event_id"] not in seen)]
+ merged.sort(key=lambda item: (_event_time(item), item.get("event_id") or ""))
+ return [{**event, "timestamp": _event_time(event)} for event in merged[:500]]
async def get_pipeline_event_stats(pipeline_run_id: str) -> dict:
@@ -135,15 +166,5 @@ async def get_pipeline_event_stats(pipeline_run_id: str) -> dict:
stats[doc["_id"]] = doc["count"]
return stats
except Exception as exc:
- logger.warning("Pipeline event stats query failed: %s", exc)
+ logger.warning("Pipeline event stats query failed (%s)", type(exc).__name__)
return {}
-
-
-def get_event_log_health() -> dict[str, Any]:
- """Expose bounded write-failure accounting for audit observability."""
- return {
- "write_failure_count": _WRITE_FAILURE_COUNT,
- "dead_letter_count": len(_DEAD_LETTER_EVENTS),
- "dead_letter_limit": _DEAD_LETTER_LIMIT,
- "recent_dead_letters": list(_DEAD_LETTER_EVENTS),
- }
diff --git a/backend/app/services/pipeline_event_operational_metrics.py b/backend/app/services/pipeline_event_operational_metrics.py
new file mode 100644
index 000000000..cc7e58267
--- /dev/null
+++ b/backend/app/services/pipeline_event_operational_metrics.py
@@ -0,0 +1,107 @@
+"""Shared project-scoped event health and bounded fleet metric snapshots."""
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from typing import Any
+import uuid
+
+from sqlalchemy import case, func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core import metrics
+from app.models.postgres import PipelineEventOutbox
+from app.services.pipeline_event_admission import PIPELINE_EVENT_CAPACITY
+from app.services.pipeline_event_delivery import STATUSES
+
+
+def _age(value: datetime | None, now: datetime) -> float:
+ if value is None:
+ return 0.0
+ if value.tzinfo is None:
+ value = value.replace(tzinfo=timezone.utc)
+ return max(0.0, (now - value).total_seconds())
+
+
+def _scope(statement, project_ids: set[uuid.UUID] | None):
+ return statement if project_ids is None else statement.where(PipelineEventOutbox.project_id.in_(project_ids))
+
+
+async def read_event_delivery_snapshot(
+ db: AsyncSession, *, project_ids: set[uuid.UUID] | None = None, now: datetime | None = None,
+) -> dict[str, Any]:
+ observed_at = now or datetime.now(timezone.utc)
+ if observed_at.tzinfo is None:
+ raise ValueError("event snapshot time must include timezone")
+ due = case(
+ (PipelineEventOutbox.status == "pending", func.coalesce(PipelineEventOutbox.next_attempt_at, PipelineEventOutbox.created_at)),
+ (PipelineEventOutbox.status == "sending", PipelineEventOutbox.lease_expires_at),
+ else_=None,
+ )
+ statement = select(
+ PipelineEventOutbox.status, func.count(), func.min(PipelineEventOutbox.created_at), func.min(due),
+ func.sum(case((PipelineEventOutbox.last_error_code.is_not(None), 1), else_=0)),
+ func.sum(case(((PipelineEventOutbox.status == "sending") & PipelineEventOutbox.lease_expires_at.is_(None), 1), else_=0)),
+ func.sum(case(((PipelineEventOutbox.status == "delivered") & PipelineEventOutbox.delivered_at.is_(None), 1), else_=0)),
+ ).group_by(PipelineEventOutbox.status)
+ rows = (await db.execute(_scope(statement, project_ids))).all()
+ snapshot = {state: {"count": 0, "oldest_age_seconds": 0.0, "overdue_seconds": 0.0} for state in STATUSES}
+ unresolved_errors = 0
+ for state, count, oldest, deadline, errors, missing_lease, missing_receipt in rows:
+ if state not in STATUSES or missing_lease or missing_receipt:
+ raise ValueError("invalid event delivery lifecycle")
+ snapshot[state] = {
+ "count": int(count),
+ "oldest_age_seconds": 0.0 if state == "delivered" else _age(oldest, observed_at),
+ "overdue_seconds": _age(deadline, observed_at),
+ }
+ if state != "delivered":
+ unresolved_errors += int(errors)
+ counts = {state: int(value["count"]) for state, value in snapshot.items()}
+ backlog = sum(counts[state] for state in ("pending", "sending", "failed"))
+ # Legacy count names remain compatibility aliases for current shared
+ # unresolved failures, not process-lifetime monotonic counters.
+ return {
+ "status": "degraded" if counts["failed"] or unresolved_errors or max(
+ float(value["oldest_age_seconds"]) for value in snapshot.values()
+ ) > 300 else "healthy",
+ "write_failure_count": unresolved_errors,
+ "dead_letter_count": counts["failed"],
+ "dead_letter_limit": PIPELINE_EVENT_CAPACITY,
+ "recent_dead_letters": [],
+ "backlog_count": backlog,
+ "oldest_pending_age_seconds": max(float(value["oldest_age_seconds"]) for value in snapshot.values()),
+ "outbox_total_count": sum(counts.values()),
+ "capacity": PIPELINE_EVENT_CAPACITY,
+ "status_counts": counts,
+ "states": snapshot,
+ }
+
+
+async def read_event_log_health(
+ db: AsyncSession, *, project_ids: set[uuid.UUID] | None,
+) -> dict[str, Any]:
+ snapshot = await read_event_delivery_snapshot(db, project_ids=project_ids)
+ statement = select(
+ PipelineEventOutbox.id, PipelineEventOutbox.pipeline_run_id,
+ PipelineEventOutbox.attempts, PipelineEventOutbox.last_error_code,
+ ).where(PipelineEventOutbox.status == "failed").order_by(PipelineEventOutbox.created_at).limit(20)
+ rows = (await db.execute(_scope(statement, project_ids))).all()
+ snapshot["recent_dead_letters"] = [{
+ "event_id": str(identifier), "pipeline_run_id": pipeline,
+ "attempts": int(attempts), "error_code": error,
+ } for identifier, pipeline, attempts, error in rows]
+ snapshot.pop("states")
+ return snapshot
+
+
+async def refresh_pipeline_event_operational_metrics() -> bool:
+ from app.db.postgres import AsyncSessionLocal
+
+ async with AsyncSessionLocal() as db:
+ snapshot = await read_event_delivery_snapshot(db)
+ for state, values in snapshot["states"].items():
+ metrics.pipeline_event_outbox_entries.labels(status=state).set(values["count"])
+ metrics.pipeline_event_outbox_oldest_age.labels(status=state).set(values["oldest_age_seconds"])
+ metrics.pipeline_event_outbox_overdue.labels(status=state).set(values["overdue_seconds"])
+ metrics.pipeline_event_outbox_capacity.set(snapshot["capacity"])
+ return True
diff --git a/backend/app/services/pipeline_replay_service.py b/backend/app/services/pipeline_replay_service.py
index 98c3f86b2..71713c539 100644
--- a/backend/app/services/pipeline_replay_service.py
+++ b/backend/app/services/pipeline_replay_service.py
@@ -254,7 +254,7 @@ async def build_pipeline_replay(
)
stages = sorted(stage_result.scalars().all(), key=_stage_sort_key)
- events = [_normalize_event(event) for event in await get_pipeline_timeline(str(pipeline_id))]
+ events = [_normalize_event(event) for event in await get_pipeline_timeline(str(pipeline_id), db=db)]
if not any(
event.get("event_type") == "decision_made" and event.get("stage_name") == "workflow"
for event in events
diff --git a/backend/app/services/project_export_documents.py b/backend/app/services/project_export_documents.py
index aa1e91b14..026ab2a38 100644
--- a/backend/app/services/project_export_documents.py
+++ b/backend/app/services/project_export_documents.py
@@ -36,7 +36,7 @@
from app.db.mongo import Collections
from app.services.project_export_vocab import MONGO_DOC_MAX_BYTES, MONGO_MAX_DEPTH
-#: == ``retention_service._PIPELINE_EVENT_LOG`` (asserted) — not a ``Collections`` member; the
+#: == ``retention_service._PIPELINE_EVENT_LOG`` (asserted). The
#: literal is repeated here so this pure module never imports the purge.
PIPELINE_EVENT_LOG = "pipeline_event_log"
@@ -92,8 +92,10 @@ class MongoSpec:
unique_key=("project_id", "test_run_id", "pipeline_run_id")),
# M-7: keyed by case only; the import ADDS test_run_id (the new run) so the copy is removable by run
MongoSpec(Collections.AI_ANALYSIS_PAYLOADS, key="test_case_id", key_map=_CASES, added_fields={"test_run_id": _RUNS}),
- # M-8: the writer (pipeline_event_log.emit_event) sets pipeline_run_id + test_case_id (open point 4)
- MongoSpec(PIPELINE_EVENT_LOG, key="pipeline_run_id", key_map=_PIPELINES, id_fields={"test_case_id": _CASES}),
+ # M-8: remap run and case references while retaining the audit event's own ID.
+ MongoSpec(PIPELINE_EVENT_LOG, key="pipeline_run_id", key_map=_PIPELINES,
+ id_fields={"test_case_id": _CASES, "test_run_id": _RUNS},
+ project_field="project_id", kept_ids=("event_id",)),
MongoSpec(Collections.DECISION_REPORTS, key="test_run_id", key_map=_RUNS, id_fields={"pipeline_run_id": _PIPELINES},
project_field="project_id", unique_key=("test_run_id", "report_version"),
kept_ids=("report_id", "supersedes_report_id", "evidence_snapshot_id"),
diff --git a/backend/app/services/project_export_history.py b/backend/app/services/project_export_history.py
index 7104b9ee4..baf9ea66f 100644
--- a/backend/app/services/project_export_history.py
+++ b/backend/app/services/project_export_history.py
@@ -550,6 +550,7 @@ async def iter_documents(
from app.services.project_export_documents import UnsupportedDocumentType
from app.services.project_export_service import ProjectExportFailed
+ await ensure_pipeline_events_materialized(db, window)
history = stats.setdefault("history", {})
documents: dict[str, dict[str, int]] = history.setdefault("documents", {})
slugs = await live_session_keys(db, window)
@@ -588,6 +589,29 @@ async def iter_documents(
await on_progress("documents", written, total)
+async def ensure_pipeline_events_materialized(db: Any, window: RunWindow) -> None:
+ """Do not publish incomplete event history from this SQL snapshot.
+
+ Match the existing MongoSpec's canonical, terminal pipeline selection.
+ Other projects, runs outside the selected window and correlation-only
+ agent-run aliases do not block this archive. Estimates remain counts-only.
+ """
+ if not window.run_ids:
+ return
+ from app.services.project_export_service import ProjectExportFailed
+
+ outbox = _table("pipeline_event_outbox")
+ outstanding = select(outbox.c.id).where(
+ outbox.c.project_id == window.project_id,
+ outbox.c.status != "delivered",
+ outbox.c.pipeline_id.in_(exported_ids("agent_pipeline_runs", window)),
+ ).limit(1)
+ if (await db.execute(outstanding)).scalar():
+ # Existing safe error surface: no payload, event ID or foreign-project
+ # details. The archive runner fails before storage publication.
+ raise ProjectExportFailed("export_build", error_type="PipelineEventDeliveryPending")
+
+
# ── objects (R-1) ────────────────────────────────────────────────────────────
@dataclass(frozen=True)
diff --git a/backend/app/services/retention_service.py b/backend/app/services/retention_service.py
index bde1810ca..e4ed9cfdd 100644
--- a/backend/app/services/retention_service.py
+++ b/backend/app/services/retention_service.py
@@ -1884,12 +1884,25 @@ async def execute_candidates(
are derived from four independent clocks, and seven of them never
reference a run.
"""
+ # Fence event relay before Mongo deletion while the source mapping is
+ # intact. In-flight relay finishes under the same per-project lock.
+ from app.services.pipeline_event_admission import as_uuid, purge_pipeline_event_intents
+
+ audit_runs = {run for item in cand.audit_run_strs if (run := as_uuid(item)) is not None}
+ await purge_pipeline_event_intents(
+ db, project_id,
+ pipeline_run_ids=set(cand.audit_pipeline_strs),
+ test_run_ids=set(cand.purge_run_ids) | audit_runs,
+ )
# (2) Mongo deletes — while the Postgres mapping still exists.
mongo_deleted: dict[str, int] = {}
for collection, field, attr in _MONGO_PLANS:
mongo_deleted[collection] = await _mongo_delete(
mongo, collection, field, list(getattr(cand, attr))
)
+ mongo_deleted[_PIPELINE_EVENT_LOG] += await _mongo_delete(
+ mongo, _PIPELINE_EVENT_LOG, "test_run_id", cand.audit_run_strs,
+ )
# (3) MinIO deletes.
minio_deleted = 0
@@ -2061,10 +2074,6 @@ async def execute_candidates(
return counts
-#: The ``_Candidates`` attribute of the one case-keyed ``_MONGO_PLANS`` entry.
-_CASE_KEYED_ATTR = "purge_tc_strs"
-
-
async def delete_project_run_documents(
db: AsyncSession,
mongo: Any,
@@ -2080,7 +2089,8 @@ async def delete_project_run_documents(
a document whose run row is gone is never reached again (the nightly purge
resolves its candidates FROM Postgres runs).
- Reads only in Postgres (stages nothing, never commits). Returns
+ Cancels local pipeline-event intents before deleting Mongo history (the
+ caller commits). Returns
``{collection: deleted}`` with a key for EVERY ``_MONGO_PLANS`` collection
(0 included). Driven from ``_MONGO_PLANS`` on purpose, so a collection
added to that table later is reset too, by construction.
@@ -2102,6 +2112,7 @@ async def delete_project_run_documents(
the job).
"""
from app.services.stream_service import canonical_test_run_uuid
+ from app.services.pipeline_event_admission import purge_pipeline_event_intents
counts: dict[str, int] = {collection: 0 for collection, _f, _a in _MONGO_PLANS}
@@ -2158,6 +2169,9 @@ async def delete_project_run_documents(
audit_pipeline_strs=pipeline_strs,
audit_run_strs=run_strs,
)
+ await purge_pipeline_event_intents(
+ db, project_id, pipeline_run_ids=set(pipeline_strs), test_run_ids=run_set,
+ )
case_plans: list[tuple[str, str]] = []
for collection, field, attr in _MONGO_PLANS:
@@ -2167,6 +2181,9 @@ async def delete_project_run_documents(
counts[collection] = await _mongo_delete(
mongo, collection, field, list(getattr(cand, attr))
)
+ counts[_PIPELINE_EVENT_LOG] += await _mongo_delete(
+ mongo, _PIPELINE_EVENT_LOG, "test_run_id", run_strs,
+ )
if case_plans:
stream = await db.stream_scalars(
@@ -2182,4 +2199,89 @@ async def delete_project_run_documents(
mongo, collection, field, page_strs
)
- return counts
\ No newline at end of file
+ return counts
+
+# Instance-scoped identity events have no project owner. This separate,
+# explicitly approved policy never inherits a project's enabled flag or clock.
+async def purge_identity_events_batch(
+ db: AsyncSession, *, now: datetime, batch_size: int = 500,
+ actor: Any = None, scheduled: bool = False, observed_at: Optional[datetime] = None,
+ preview_hash: Optional[str] = None, confirmation: Optional[str] = None,
+ reason: str = "Approved instance identity retention sweep",
+) -> dict[str, Any]:
+ """Stage one finite SQL-only batch plus its permanent audit atomically.
+
+ The policy row lock serializes this batch with enable/disable and EVERY
+ identity hold mutation. SCIM authority, other security/lifecycle events,
+ unknown types and unsuccessful routine events cannot match either the
+ candidate query or the final DELETE. The caller commits only on success.
+ """
+ from sqlalchemy import text
+
+ from app.models.identity_retention import MAX_BATCH_SIZE
+ from app.models.postgres import IdentityEvent
+ from app.services import identity_retention_service as identity
+
+ observed = identity.aware(now)
+ if type(batch_size) is not int or not 1 <= batch_size <= MAX_BATCH_SIZE:
+ raise identity.IdentityRetentionError("invalid_batch", 422)
+ if not scheduled:
+ identity.require_interactive_admin(actor)
+ reason = identity.clean_reason(reason)
+ # Keep a stalled DB/hold lock from becoming an unbounded maintenance job.
+ # These LOCAL settings disappear on the caller's commit or rollback.
+ if db.get_bind().dialect.name == "postgresql":
+ await db.execute(text("SET LOCAL lock_timeout = '2s'"))
+ await db.execute(text("SET LOCAL statement_timeout = '5s'"))
+ row = await identity.policy_row(db, lock=True)
+ policy = identity.document(row)
+ if not policy.enabled:
+ if not scheduled:
+ raise identity.IdentityRetentionError("retention_disabled")
+ return {"status": "disabled", "deleted": 0}
+ if identity.live_holds(policy, observed):
+ if not scheduled:
+ raise identity.IdentityRetentionError("retention_held")
+ return {"status": "held", "deleted": 0}
+ if scheduled:
+ cutoff = observed - timedelta(days=policy.retention_days)
+ else:
+ if observed_at is None or preview_hash is None:
+ raise identity.IdentityRetentionError("preview_stale")
+ snapshot = await identity.verify_preview(
+ db, policy=policy, observed_at=observed_at, now=observed,
+ retention_days=policy.retention_days, preview_hash=preview_hash,
+ )
+ if confirmation != identity.purge_confirmation(policy.retention_days):
+ raise identity.IdentityRetentionError("confirmation_mismatch", 422)
+ cutoff = snapshot["cutoff"]
+ candidates = (await db.execute(
+ select(IdentityEvent.id)
+ .where(identity.routine_event_clause(), IdentityEvent.created_at < cutoff)
+ .order_by(IdentityEvent.created_at, IdentityEvent.id)
+ .limit(batch_size)
+ .with_for_update(skip_locked=True)
+ )).scalars().all()
+ deleted = 0
+ if candidates:
+ deleted = len((await db.execute(
+ delete(IdentityEvent)
+ .where(
+ IdentityEvent.id.in_(candidates), identity.routine_event_clause(),
+ IdentityEvent.created_at < cutoff,
+ )
+ .returning(IdentityEvent.id)
+ )).all())
+ identity.audit(
+ db, actor=actor, action="purged", policy=policy, reason=reason,
+ details={"deleted": deleted, "cutoff": cutoff.isoformat(), "batch_size": batch_size,
+ "scheduled": scheduled}, setting_key=identity.PURGE_AUDIT_KEY,
+ )
+ await db.flush()
+ return {"status": "completed", "deleted": deleted, "batch_size": batch_size,
+ "batch_full": deleted == batch_size, "cutoff": cutoff.isoformat(),
+ "policy_revision": policy.revision}
+
+
+#: The ``_Candidates`` attribute of the one case-keyed ``_MONGO_PLANS`` entry.
+_CASE_KEYED_ATTR = "purge_tc_strs"
diff --git a/backend/app/services/subject_data_inventory.py b/backend/app/services/subject_data_inventory.py
index b6883da3f..67a6bf53a 100644
--- a/backend/app/services/subject_data_inventory.py
+++ b/backend/app/services/subject_data_inventory.py
@@ -386,6 +386,9 @@ def _own(table: str, column: str, category: str, label: str, **more: Any) -> Loc
label="Component owner maps", reason=_NOT_ACCOUNT),
_row("service_ownership_rules", "team_contact", match="value", export_as="none", category=None,
erase="out_of_scope", label="Team contacts on ownership rules", reason=_NOT_ACCOUNT),
+ _row("pipeline_event_outbox", "payload", match="none", export_as="none", category=None,
+ erase="keep_record", label="Pending pipeline timeline evidence",
+ reason="Pending redacted delivery data follows the source project and run retention."),
)
_E_OBJECTS: tuple[Location, ...] = (
_store("objects:subject-exports/", "objects", match="id_key", erase="delete", label="Their data exports",
@@ -620,6 +623,7 @@ def _own(table: str, column: str, category: str, label: str, **more: Any) -> Loc
("app/services/retention_hold_service.py", "SettingsAuditLog.actor_name"): _SET,
("app/services/retention_hold_service.py", "attr:released_by_name"): "retention_holds.released_by_name",
("app/services/retention_instance_service.py", "SettingsAuditLog.actor_name"): _SET,
+ ("app/services/identity_retention_service.py", "SettingsAuditLog.actor_name"): _SET,
("app/services/settings_audit_service.py", "SettingsAuditLog.actor_name"): _SET,
("app/services/share_link_service.py", "ReportShareLink.created_by_name"): "report_share_links.created_by_name",
("app/services/test_management_audit_service.py", "TestCaseAuditLog.actor_name"): "test_case_audit_logs.actor_name",
diff --git a/backend/app/worker/celery_app.py b/backend/app/worker/celery_app.py
index c5f2535c0..748a36e04 100644
--- a/backend/app/worker/celery_app.py
+++ b/backend/app/worker/celery_app.py
@@ -344,6 +344,11 @@ def _build_task_queues() -> tuple[Queue, ...]:
"task": "app.worker.tasks.relay_run_downstream_outbox",
"schedule": crontab(minute="*"),
},
+ "relay-pipeline-event-outbox": {
+ "task": "app.worker.tasks.relay_pipeline_event_outbox",
+ "schedule": crontab(minute="*"),
+ "options": {"expires": 55},
+ },
"relay-queued-criteria-deletions": {
"task": "app.worker.tasks.relay_queued_criteria_deletions",
"schedule": crontab(minute="*"),
diff --git a/backend/app/worker/tasks.py b/backend/app/worker/tasks.py
index 4c59499c9..c9180a50e 100644
--- a/backend/app/worker/tasks.py
+++ b/backend/app/worker/tasks.py
@@ -3227,6 +3227,21 @@ def relay_run_downstream_outbox(self):
) from None
+@celery_app.task(
+ name="app.worker.tasks.relay_pipeline_event_outbox",
+ bind=True,
+ max_retries=0,
+ queue="default",
+ time_limit=40,
+)
+def relay_pipeline_event_outbox(self):
+ """Materialize accepted operational evidence in bounded retry batches."""
+ _bind_task_context(self)
+ from app.services.pipeline_event_delivery import relay_pipeline_events
+
+ return _run_async(relay_pipeline_events())
+
+
@celery_app.task(
name="app.worker.tasks.relay_queued_criteria_deletions",
bind=True,
@@ -7874,7 +7889,18 @@ def run_retention_purges(self, project_id: str | None = None) -> dict:
async def _run():
with _beat_span("run_retention_purges") as span:
+ identity = None
+ if project_id is None:
+ from app.services.identity_retention_service import run_scheduled_batch
+
+ try:
+ identity = await run_scheduled_batch()
+ except Exception as exc: # noqa: BLE001 - preserve the independent project sweep
+ identity = {"status": "failed", "deleted": 0}
+ _slog.warning("identity_retention_sweep_failed", error_type=type(exc).__name__)
out = await _retention_purge_sweep(project_id, owner=owner)
+ if identity is not None:
+ out["identity_security_events"] = identity
span.set_attribute("result.projects", int(out.get("projects", 0)))
span.set_attribute("result.errors", int(out.get("errors", 0)))
span.set_attribute("explicit_project", bool(project_id))
diff --git a/backend/migrations/versions/0263_pipeline_event_outbox.py b/backend/migrations/versions/0263_pipeline_event_outbox.py
new file mode 100644
index 000000000..45e1589de
--- /dev/null
+++ b/backend/migrations/versions/0263_pipeline_event_outbox.py
@@ -0,0 +1,63 @@
+"""Add a project-scoped queue for immutable pipeline event delivery.
+
+Revision ID: 0263
+Revises: 0262
+"""
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy.dialects.postgresql import JSONB, UUID
+
+revision = "0263"
+down_revision = "0262"
+branch_labels = None
+depends_on = None
+
+TABLE = "pipeline_event_outbox"
+INDEXES = {
+ "schedule": ("status", "next_attempt_at", "created_at"),
+ "lease": ("status", "lease_expires_at"),
+ "delivered": ("status", "delivered_at"),
+ "project": ("project_id", "status"),
+ "pipeline": ("pipeline_id",),
+ "timeline": ("pipeline_run_id", "created_at"),
+ "run": ("test_run_id",),
+ "test_case": ("test_case_id",),
+}
+
+
+def upgrade() -> None:
+ op.create_table(
+ TABLE,
+ sa.Column("id", UUID(as_uuid=True), primary_key=True),
+ sa.Column("project_id", UUID(as_uuid=True), sa.ForeignKey("projects.id", ondelete="CASCADE"), nullable=False),
+ sa.Column("pipeline_id", UUID(as_uuid=True), sa.ForeignKey("agent_pipeline_runs.id", ondelete="CASCADE")),
+ sa.Column("test_run_id", UUID(as_uuid=True), sa.ForeignKey("test_runs.id", ondelete="CASCADE")),
+ sa.Column("test_case_id", UUID(as_uuid=True), sa.ForeignKey("test_cases.id", ondelete="CASCADE")),
+ sa.Column("pipeline_run_id", sa.String(128), nullable=False),
+ sa.Column("payload", JSONB, nullable=False),
+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
+ sa.Column("status", sa.String(12), server_default="pending", nullable=False),
+ sa.Column("attempts", sa.Integer, server_default="0", nullable=False),
+ sa.Column("next_attempt_at", sa.DateTime(timezone=True)),
+ sa.Column("lease_token", UUID(as_uuid=True)),
+ sa.Column("lease_expires_at", sa.DateTime(timezone=True)),
+ sa.Column("last_error_code", sa.String(48)),
+ sa.Column("delivered_at", sa.DateTime(timezone=True)),
+ sa.CheckConstraint("status IN ('pending', 'sending', 'delivered', 'failed')", name="ck_pipeline_event_outbox_status"),
+ sa.CheckConstraint("attempts >= 0", name="ck_pipeline_event_outbox_attempts"),
+ )
+ for suffix, columns in INDEXES.items():
+ op.create_index(f"ix_{TABLE}_{suffix}", TABLE, columns)
+
+
+def downgrade() -> None:
+ op.execute("""
+ DO $pipeline_event_outbox$
+ BEGIN
+ IF EXISTS (SELECT 1 FROM pipeline_event_outbox WHERE status <> 'delivered') THEN
+ RAISE EXCEPTION 'Drain unresolved pipeline event intents before removing the outbox';
+ END IF;
+ END;
+ $pipeline_event_outbox$;
+ """)
+ op.drop_table(TABLE)
diff --git a/backend/tests/integration/test_identity_retention_postgres.py b/backend/tests/integration/test_identity_retention_postgres.py
new file mode 100644
index 000000000..591969ad1
--- /dev/null
+++ b/backend/tests/integration/test_identity_retention_postgres.py
@@ -0,0 +1,96 @@
+"""Optional policy/hold serialization proof in an isolated PostgreSQL schema.
+
+Requires an explicit disposable TESTLOOKUP_POSTGRES_TEST_DSN. Only LIKE copies
+of three already migrated tables are used; public rows are never modified.
+"""
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime, timedelta, timezone
+import os
+from types import SimpleNamespace
+import uuid
+
+import pytest
+from sqlalchemy import select, text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.core.deps import _bind_credential_kind
+from app.models.postgres import IdentityEvent, SettingsAuditLog
+from app.services import identity_retention_service as service
+from app.services.retention_service import purge_identity_events_batch
+
+pytestmark = [pytest.mark.integration, pytest.mark.asyncio]
+
+
+async def test_committed_instance_hold_serializes_with_expiry_and_scim_rows_survive():
+ dsn = os.getenv("TESTLOOKUP_POSTGRES_TEST_DSN", "").strip()
+ if not dsn:
+ pytest.skip("TESTLOOKUP_POSTGRES_TEST_DSN is not configured")
+ schema = "identity_retention_proof_" + uuid.uuid4().hex
+ # The identifier is generated here, never supplied in a request or DSN.
+ assert schema.startswith("identity_retention_proof_") and len(schema.rsplit("_", 1)[1]) == 32
+ control = create_async_engine(dsn)
+ engine = None
+ try:
+ async with control.begin() as connection:
+ await connection.execute(text(f'CREATE SCHEMA "{schema}"'))
+ for table in ("app_settings", "identity_events", "settings_audit_log"):
+ # LIKE copies column/default/index/check contracts, not foreign
+ # keys into account tables. This schema has no real accounts.
+ await connection.execute(text(f'CREATE TABLE "{schema}"."{table}" (LIKE public."{table}" INCLUDING ALL)'))
+ engine = create_async_engine(dsn, connect_args={"server_settings": {"search_path": schema + ",public"}})
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ now = datetime.now(timezone.utc)
+ admin = SimpleNamespace(id=uuid.uuid4(), role="ADMIN", username="synthetic-admin", full_name="Synthetic Admin")
+ _bind_credential_kind(admin, "jwt")
+ routine, authority = uuid.uuid4(), uuid.uuid4()
+ async with sessions() as db:
+ db.add_all([
+ IdentityEvent(id=routine, event_type="SSO_LOGIN", success=True, created_at=now - timedelta(days=500)),
+ IdentityEvent(id=authority, event_type="SCIM_USER_CREATED", success=True, created_at=now - timedelta(days=5000)),
+ ])
+ await db.commit()
+ preview = await service.preview(db, now=now, retention_days=365)
+ await service.approve_policy(db, actor=admin, retention_days=365, observed_at=now,
+ preview_hash=preview["preview_hash"], confirmation=preview["enable_confirmation"],
+ reason="Synthetic PostgreSQL proof", now=now)
+ await db.commit()
+ async with sessions() as holder, sessions() as purger:
+ await purger.execute(text("SELECT 1")) # establish its connection before the race
+ hold = await service.place_hold(holder, actor=admin, reason="Synthetic independent hold", expires_at=None, now=now)
+ task = asyncio.create_task(purge_identity_events_batch(purger, now=now, scheduled=True))
+ try:
+ await asyncio.sleep(0.1)
+ assert not task.done(), "purge bypassed the policy/hold transaction lock"
+ await holder.commit()
+ assert (await task)["status"] == "held"
+ await purger.commit()
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ async with sessions() as db:
+ assert set((await db.execute(select(IdentityEvent.id))).scalars()) == {routine, authority}
+ await service.release_hold(db, actor=admin, hold_id=hold.id, reason="Synthetic case resolved",
+ confirmation=service.RELEASE_CONFIRMATION, now=now)
+ await db.commit()
+ assert (await purge_identity_events_batch(db, now=now, scheduled=True))["deleted"] == 1
+ await db.commit()
+ assert set((await db.execute(select(IdentityEvent.id))).scalars()) == {authority}
+ # Read committed receipts through a fresh session, not pending objects.
+ async with sessions() as db:
+ receipts = list((await db.execute(select(SettingsAuditLog))).scalars())
+ assert {row.action for row in receipts} == {"enabled", "hold_placed", "hold_released", "purged"}
+ assert len(receipts) == 4
+ assert all(row.actor_name == "Synthetic Admin" for row in receipts if row.action != "purged")
+ purge = next(row for row in receipts if row.action == "purged")
+ assert purge.setting_key == service.PURGE_AUDIT_KEY
+ assert purge.changed_fields["deleted"] == 1
+ assert purge.changed_fields["scheduled"] is True
+ finally:
+ if engine is not None:
+ await engine.dispose()
+ async with control.begin() as connection:
+ await connection.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))
+ await control.dispose()
diff --git a/backend/tests/integration/test_pipeline_event_outbox_postgres.py b/backend/tests/integration/test_pipeline_event_outbox_postgres.py
new file mode 100644
index 000000000..0c26d2bb5
--- /dev/null
+++ b/backend/tests/integration/test_pipeline_event_outbox_postgres.py
@@ -0,0 +1,108 @@
+"""PostgreSQL locking, admission and lease behavior against an isolated schema."""
+
+import asyncio
+import os
+import uuid
+from datetime import datetime, timezone
+
+import pytest
+import pytest_asyncio
+from motor.motor_asyncio import AsyncIOMotorClient
+from sqlalchemy import select, text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.db import mongo, postgres
+from app.models.postgres import PipelineEventOutbox
+from app.services import pipeline_event_admission, pipeline_event_delivery, pipeline_event_log
+
+
+pytestmark = [pytest.mark.integration, pytest.mark.asyncio]
+
+
+@pytest_asyncio.fixture
+async def postgres_outbox(monkeypatch):
+ dsn = os.environ.get("TESTLOOKUP_POSTGRES_TEST_DSN")
+ if not dsn:
+ pytest.skip("requires a disposable PostgreSQL DSN")
+ schema = f"pipeline_event_fixture_{uuid.uuid4().hex}"
+ admin = create_async_engine(dsn)
+ engine = create_async_engine(dsn, connect_args={"server_settings": {"search_path": schema}})
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ monkeypatch.setattr(pipeline_event_log, "get_session_factory", lambda: factory)
+ monkeypatch.setattr(postgres, "get_session_factory", lambda: factory)
+ project, run, pipeline = (uuid.uuid4() for _ in range(3))
+ try:
+ async with admin.begin() as db:
+ await db.execute(text(f"CREATE SCHEMA {schema}"))
+ async with engine.begin() as db:
+ await db.execute(text("CREATE TABLE projects (id uuid PRIMARY KEY)"))
+ await db.execute(text("CREATE TABLE test_runs (id uuid PRIMARY KEY, project_id uuid)"))
+ await db.execute(text("CREATE TABLE agent_pipeline_runs (id uuid PRIMARY KEY, test_run_id uuid)"))
+ await db.execute(text("CREATE TABLE test_cases (id uuid PRIMARY KEY, test_run_id uuid)"))
+ await db.execute(text("INSERT INTO projects VALUES (:project)"), {"project": project})
+ await db.execute(text("INSERT INTO test_runs VALUES (:run, :project)"), {"run": run, "project": project})
+ await db.execute(text("INSERT INTO agent_pipeline_runs VALUES (:pipeline, :run)"), {
+ "pipeline": pipeline, "run": run,
+ })
+ await db.run_sync(PipelineEventOutbox.__table__.create)
+ yield factory, project, pipeline
+ finally:
+ await engine.dispose()
+ async with admin.begin() as db:
+ await db.execute(text(f"DROP SCHEMA IF EXISTS {schema} CASCADE"))
+ await admin.dispose()
+
+
+async def test_project_purge_fence_global_capacity_and_single_claim(postgres_outbox, monkeypatch):
+ factory, project, pipeline = postgres_outbox
+ monkeypatch.setattr(pipeline_event_admission, "PIPELINE_EVENT_CAPACITY", 1)
+ async with factory.begin() as purge:
+ assert await pipeline_event_admission.lock_project_event_history(purge, project, exclusive=True)
+ assert not await pipeline_event_log.emit_event(str(pipeline), "decision_made")
+
+ # Separate producers cannot both take the last admission slot.
+ results = await asyncio.gather(*[
+ pipeline_event_log.emit_event(str(pipeline), "decision_made") for _ in range(5)
+ ])
+ assert results.count(True) == 1
+ claims = await asyncio.gather(
+ pipeline_event_delivery._claim_one(), pipeline_event_delivery._claim_one(),
+ )
+ assert sum(claim is not None for claim in claims) == 1
+ async with factory() as db:
+ row = (await db.scalars(select(PipelineEventOutbox))).one()
+ assert row.status == "sending" and row.attempts == 1
+
+
+async def test_postgres_and_mongo_recover_after_uncertain_receipt(postgres_outbox, monkeypatch):
+ uri = os.environ.get("TESTLOOKUP_MONGO_EVENT_TEST_URI")
+ if not uri:
+ pytest.skip("requires a disposable MongoDB URI")
+ factory, _, pipeline = postgres_outbox
+ client = AsyncIOMotorClient(uri, serverSelectionTimeoutMS=3000)
+ database = client[f"pipeline_event_fixture_{uuid.uuid4().hex}"]
+ monkeypatch.setattr(mongo, "get_mongo_db", lambda: database)
+ monkeypatch.setattr(pipeline_event_log, "get_mongo_db", lambda: database)
+ identity = uuid.uuid4()
+ try:
+ await client.admin.command("ping")
+ assert await pipeline_event_log.emit_event(str(pipeline), "decision_made", event_id=identity)
+ assert (await pipeline_event_delivery.relay_pipeline_events())["delivered"] == 1
+ original = await database.pipeline_event_log.find_one({"_id": str(identity)})
+ assert original["event_id"] == str(identity)
+
+ # Simulate a lost SQL acknowledgement after Mongo committed the event.
+ async with factory.begin() as db:
+ row = await db.get(PipelineEventOutbox, identity)
+ row.status = "pending"
+ row.delivered_at = None
+ row.next_attempt_at = datetime.now(timezone.utc)
+ assert (await pipeline_event_delivery.relay_pipeline_events())["delivered"] == 1
+ assert await database.pipeline_event_log.find_one({"_id": str(identity)}) == original
+ assert await database.pipeline_event_log.count_documents({}) == 1
+ assert [event["event_id"] for event in await pipeline_event_log.get_pipeline_timeline(str(pipeline))] == [
+ str(identity),
+ ]
+ finally:
+ await client.drop_database(database.name)
+ client.close()
diff --git a/backend/tests/regression/test_anomaly_decision_pool_boundary.py b/backend/tests/regression/test_anomaly_decision_pool_boundary.py
new file mode 100644
index 000000000..185819860
--- /dev/null
+++ b/backend/tests/regression/test_anomaly_decision_pool_boundary.py
@@ -0,0 +1,106 @@
+"""Decision outbox admission must fit in one real pooled SQL connection."""
+import asyncio
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+from sqlalchemy import Column, Integer, MetaData, String, Table, insert, select, text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlalchemy.pool import AsyncAdaptedQueuePool
+
+from app.agents import anomaly_agent, base
+
+
+@pytest.mark.parametrize(
+ "baseline,current,chosen",
+ [(None, 80.0, "no_baseline"), (95.0, 80.0, "regression"), (95.0, 93.0, "within_tolerance")],
+)
+async def test_anomaly_decision_releases_read_connection_and_preserves_baseline_facts(monkeypatch, baseline, current, chosen):
+ engine = create_async_engine(
+ "sqlite+aiosqlite://", poolclass=AsyncAdaptedQueuePool,
+ pool_size=1, max_overflow=0, pool_timeout=0.05,
+ )
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ metadata = MetaData()
+ outbox = Table("decision_admission_fixture", metadata, Column("id", Integer, primary_key=True), Column("detail", String))
+ async with engine.begin() as connection:
+ await connection.run_sync(metadata.create_all)
+
+ agent = anomaly_agent.AnomalyDetectionAgent()
+ for method in ("mark_stage_running", "mark_stage_done", "broadcast_progress"):
+ monkeypatch.setattr(agent, method, AsyncMock())
+ monkeypatch.setattr(anomaly_agent, "AsyncSessionLocal", sessions)
+ monkeypatch.setattr(anomaly_agent.settings, "ANOMALY_REGRESSION_THRESHOLD", 10.0)
+ reads = []
+ prior = ["prior-most-recent", "prior-older", "prior-oldest"] if baseline is not None else []
+
+ async def read(db, label):
+ await db.execute(text("SELECT 1"))
+ assert engine.pool.checkedout() == 1
+ reads.append(label)
+
+ async def baseline_read(db, *_args):
+ await read(db, "baseline")
+ return baseline, prior, prior[0] if prior else None
+
+ async def failure_read(db, _current_id, previous_id):
+ assert previous_id == prior[0]
+ await read(db, "failure_diff")
+ return {"new": [], "reopened": [], "persistent": []}
+
+ async def performance_read(db, *_args):
+ await read(db, "performance")
+ return []
+
+ async def flaky_read(db, *_args):
+ await read(db, "flaky")
+ return []
+
+ # Keep the real BaseAgent.log_decision, including its independent emit
+ # boundary; only substitute the external outbox schema/admission operation.
+ async def admit(_pipeline_run_id, event_type, **kwargs):
+ assert event_type == "decision_made"
+ assert engine.pool.checkedout() == 0, "a read connection is still held before independent decision admission"
+ async with sessions() as writer:
+ await writer.execute(insert(outbox).values(detail=json.dumps(kwargs["detail"])))
+ await writer.commit()
+
+ monkeypatch.setattr(agent, "_get_baseline_pass_rate", baseline_read)
+ monkeypatch.setattr(agent, "_classify_failure_diff", failure_read)
+ monkeypatch.setattr(agent, "_detect_perf_anomalies", performance_read)
+ monkeypatch.setattr(agent, "_find_flaky_tests_in_run", flaky_read)
+ monkeypatch.setattr(base, "emit_event", admit)
+ try:
+ result = await asyncio.wait_for(agent.run({
+ "pipeline_run_id": "11111111-1111-4111-8111-111111111111",
+ "test_run_id": "22222222-2222-4222-8222-222222222222",
+ "project_id": "33333333-3333-4333-8333-333333333333",
+ "pass_rate": current, "total_tests": 20, "branch": "main",
+ "_cost_budget_mode_override": "rules",
+ }), timeout=2)
+ assert result["errors"] == []
+ assert result["is_regression"] is (chosen == "regression")
+ assert engine.pool.checkedout() == 0
+ async with sessions() as reader:
+ rows = (await reader.execute(select(outbox.c.detail))).scalars().all()
+ assert len(rows) == 1
+ decision = json.loads(rows[0])
+ assert decision["chosen"] == chosen
+ if baseline is None:
+ assert decision["decision_point"] == "baseline_availability"
+ assert reads == ["baseline", "performance", "flaky"]
+ else:
+ assert decision["decision_point"] == "pass_rate_regression"
+ assert decision["context"]["baseline_pass_rate"] == 95.0
+ assert decision["context"]["sample_size"] == 3
+ assert decision["context"]["baseline_type"] == "branch=main"
+ assert decision["context"]["drop"] == round(95.0 - current, 2)
+ assert reads == ["baseline", "failure_diff", "performance", "flaky"]
+ if chosen == "regression":
+ anomaly, = result["anomalies"]
+ assert anomaly["baseline_run_id"] == prior[0]
+ assert anomaly["sample_size"] == 3 and anomaly["value"] == 15.0
+ agent.mark_stage_done.assert_awaited_once()
+ assert "error" not in agent.mark_stage_done.await_args.kwargs
+ finally:
+ await engine.dispose()
diff --git a/backend/tests/regression/test_audit_archive_custody.py b/backend/tests/regression/test_audit_archive_custody.py
new file mode 100644
index 000000000..0a3a03823
--- /dev/null
+++ b/backend/tests/regression/test_audit_archive_custody.py
@@ -0,0 +1,281 @@
+"""Independent custody contracts; every S3 operation is stubbed, never live."""
+from datetime import datetime, timedelta, timezone
+import base64
+import hashlib
+import io
+import json
+from pathlib import Path
+import re
+from types import SimpleNamespace
+import zipfile
+import uuid
+
+import boto3
+from botocore.stub import Stubber
+from botocore.exceptions import ClientError
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
+import pytest
+
+from testlookup_cli import audit_archive as custody
+
+NOW = datetime(2026, 11, 27, tzinfo=timezone.utc)
+PROJECT = "11111111-1111-4111-8111-111111111111"
+OWNER = "123456789012"
+BUCKET = "independent-audit-fixture"
+KMS = f"arn:aws:kms:us-east-1:{OWNER}:key/11111111-2222-3333-4444-555555555555"
+PRIVATE = Ed25519PrivateKey.from_private_bytes(b"\x03" * 32)
+PUBLIC = PRIVATE.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
+SCOPE = {"kind": "project", "project_id": PROJECT, "window_start": (NOW - timedelta(days=1)).isoformat(), "window_end": NOW.isoformat()}
+ROW = f"access,role_changed,FAKE_PAYLOAD_MARKER,{PROJECT},{NOW.isoformat()}\n"
+CSV = ("source,action,actor_name,project_id,created_at\n" + ROW).encode()
+
+
+def sealed(**overrides):
+ args = dict(source_kind="audit_csv", scope=SCOPE, retention_until=(NOW + timedelta(days=367)).isoformat(), private_key=PRIVATE, now=NOW)
+ args.update(overrides)
+ return custody.seal(CSV, **args)
+
+
+def rewrite(blob, change):
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = {name: archive.read(name) for name in archive.namelist()}
+ members = change(members)
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive:
+ for name, value in members.items():
+ archive.writestr(name, value)
+ return output.getvalue()
+
+
+def test_capture_and_restored_copy_verify_without_application_credentials(tmp_path):
+ blob = sealed()
+ restored = tmp_path / "restored.zip"
+ restored.write_bytes(blob)
+ doc = custody.verify(restored.read_bytes(), public_key_pem=PUBLIC, expected_sha256=hashlib.sha256(blob).hexdigest())
+ assert doc["scope"] == SCOPE
+ assert doc["source_check"] == {"authenticity": "operator_attested_projection", "rows": 1}
+ assert doc["completeness"] == "captured_projection_only"
+ assert doc["legal_hold"] == "ON"
+ assert "FAKE_PAYLOAD_MARKER" not in json.dumps(doc)
+
+
+@pytest.mark.parametrize("member", ["payload", "manifest.json", "signature.json"])
+def test_payload_scope_and_signature_tampering_are_refused(member):
+ def altered(members):
+ members[member] = members[member] + b"x"
+ return members
+ with pytest.raises(custody.CustodyError):
+ custody.verify(rewrite(sealed(), altered), public_key_pem=PUBLIC)
+
+
+def test_untrusted_key_substitution_and_wrong_object_receipt_are_refused():
+ other = Ed25519PrivateKey.from_private_bytes(b"\x04" * 32).public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
+ with pytest.raises(custody.CustodyError):
+ custody.verify(sealed(), public_key_pem=other)
+ with pytest.raises(custody.CustodyError, match="recorded object checksum"):
+ custody.verify(sealed(), public_key_pem=PUBLIC, expected_sha256="0" * 64)
+
+
+@pytest.mark.parametrize("extra", ["../payload", "foreign-note", "payload/"])
+def test_no_unlisted_or_path_like_member_can_enter_custody(extra):
+ with pytest.raises(custody.CustodyError):
+ custody.verify(rewrite(sealed(), lambda members: {**members, extra: b"foreign"}), public_key_pem=PUBLIC)
+
+
+def test_truncated_source_or_incorrect_scope_is_not_attested_as_complete():
+ for bad in [dict(SCOPE, project_id="22222222-2222-4222-8222-222222222222"), dict(SCOPE, window_start=NOW.isoformat(), window_end=(NOW + timedelta(hours=1)).isoformat())]:
+ with pytest.raises(custody.CustodyError):
+ sealed(scope=bad)
+ capped = CSV.splitlines(keepends=True)[0] + ROW.encode() * 5000
+ with pytest.raises(custody.CustodyError, match="source export cap"):
+ custody.seal(capped, source_kind="audit_csv", scope=SCOPE, retention_until=(NOW + timedelta(days=367)).isoformat(), private_key=PRIVATE, now=NOW)
+
+
+async def test_existing_real_signed_pack_uses_existing_verifier_and_independent_key(monkeypatch):
+ from tests.test_compliance_pack_verify import _generate, install_world
+ world = install_world(monkeypatch)
+ row, source, db = await _generate(world)
+ with zipfile.ZipFile(io.BytesIO(source)) as archive:
+ manifest = json.loads(archive.read("manifest.json"))
+ generated = datetime.fromisoformat(manifest["generated_at"])
+ scope = {"kind": "project", "project_id": manifest["project_id"], "window_start": (generated - timedelta(seconds=1)).isoformat(), "window_end": generated.isoformat()}
+ args = dict(source_kind="compliance_pack", scope=scope, retention_until=(generated + timedelta(days=367)).isoformat(), private_key=PRIVATE, source_public_keys={world.key.key_id: world.key.public_key_pem}, source_manifest_sha256=row.manifest_sha256, now=generated)
+ archived = custody.seal(source, **args)
+ assert custody.verify(archived, public_key_pem=PUBLIC)["source_check"]["authenticity"] == "application_signature_verified"
+ assert db.commits == 0 # no change to the product's stage-only transaction semantics
+ for changed in [{"source_public_keys": {}}, {"source_manifest_sha256": "0" * 64}, {"private_key": world.key.private_key}, {"source_kind": "retention_archive"}, {"scope": dict(scope, project_id=PROJECT)}]:
+ with pytest.raises(custody.CustodyError):
+ custody.seal(source, **(args | changed))
+
+
+def test_signed_runs_archive_uses_existing_manifest_and_signature_format():
+ from app.services import compliance_pack_service as packs, compliance_signing as signing
+ source_private = Ed25519PrivateKey.from_private_bytes(b"\x07" * 32)
+ source_public = source_private.public_key()
+ source_key = signing.SigningKey(signing.key_id_for(source_public), signing.public_key_pem(source_public), source_private)
+ scope = packs.ExportScope.for_runs(project_id=uuid.UUID(PROJECT), run_ids=[uuid.UUID(PROJECT)], tier="summary")
+ manifest = packs._build_manifest(files={"audit_events.json": b"[]"}, generated_at=NOW, scope=scope, run=None, decision=None)
+ digest = hashlib.sha256(manifest).hexdigest()
+ signature = signing.signature_document(source_key, pack_id=uuid.UUID(PROJECT), manifest_sha256=digest, signed_at=NOW)
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:
+ for name, value in {"audit_events.json": b"[]", "manifest.json": manifest, "signature.json": json.dumps(signature).encode()}.items():
+ archive.writestr(name, value)
+ result = custody.seal(buffer.getvalue(), source_kind="retention_archive", scope=SCOPE, retention_until=(NOW + timedelta(days=367)).isoformat(), private_key=PRIVATE, source_public_keys={source_key.key_id: source_key.public_key_pem}, source_manifest_sha256=digest, now=NOW)
+ assert custody.verify(result, public_key_pem=PUBLIC)["source_kind"] == "retention_archive"
+
+
+def test_cli_seal_verify_and_exclusive_output_preserve_local_custody(tmp_path, monkeypatch, capsys):
+ class Clock(datetime):
+ @classmethod
+ def now(cls, tz=None):
+ return NOW
+ monkeypatch.setattr(custody, "datetime", Clock)
+ paths = {name: tmp_path / name for name in ("private.pem", "public.pem", "source.csv", "scope.json", "archive.zip")}
+ paths["private.pem"].write_bytes(PRIVATE.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
+ paths["private.pem"].chmod(0o600)
+ paths["public.pem"].write_bytes(PUBLIC)
+ paths["source.csv"].write_bytes(CSV)
+ paths["scope.json"].write_text(json.dumps(SCOPE))
+ args = ["seal", "--input", str(paths["source.csv"]), "--source-kind", "audit_csv", "--scope", str(paths["scope.json"]), "--retention-until", (NOW + timedelta(days=367)).isoformat(), "--private-key", str(paths["private.pem"]), "--output", str(paths["archive.zip"])]
+ assert custody.main(args) == 0
+ original = paths["archive.zip"].read_bytes()
+ assert custody.main(args) == 2
+ assert paths["archive.zip"].read_bytes() == original
+ assert custody.main(["verify", "--input", str(paths["archive.zip"]), "--public-key", str(paths["public.pem"]), "--expected-sha256", hashlib.sha256(original).hexdigest()]) == 0
+ recovered = tmp_path / "recovered-export"
+ recover_args = ["recover", "--input", str(paths["archive.zip"]), "--public-key", str(paths["public.pem"]), "--expected-sha256", hashlib.sha256(original).hexdigest(), "--output", str(recovered)]
+ assert custody.main(recover_args) == 0
+ assert recovered.read_bytes() == CSV
+ assert custody.main(recover_args) == 2
+ output = capsys.readouterr()
+ assert "FAKE_PAYLOAD_MARKER" not in output.out + output.err
+
+
+def client():
+ # Static test credentials + Stubber: neither credential discovery nor an
+ # externally reachable endpoint is used by any test operation.
+ return boto3.Session(aws_access_key_id="fixture", aws_secret_access_key="fixture").client("s3", region_name="us-east-1")
+
+
+def queue_publish(stub, blob, *, mode="COMPLIANCE", hold="ON", version="version-fixture", kms=KMS, put_error=False):
+ doc = custody.verify(blob, public_key_pem=PUBLIC)
+ until = datetime.fromisoformat(doc["retention_until"])
+ common = {"Bucket": BUCKET, "ExpectedBucketOwner": OWNER}
+ key = "audit-custody/" + doc["archive_id"] + ".zip"
+ checksum = base64.b64encode(hashlib.sha256(blob).digest()).decode()
+ stub.add_response("get_bucket_versioning", {"Status": "Enabled"}, common)
+ stub.add_response("get_object_lock_configuration", {"ObjectLockConfiguration": {"ObjectLockEnabled": "Enabled"}}, common)
+ expected = {
+ **common, "Key": key, "Body": blob, "ContentType": "application/zip", "IfNoneMatch": "*",
+ "ChecksumAlgorithm": "SHA256", "ChecksumSHA256": checksum, "ServerSideEncryption": "aws:kms", "SSEKMSKeyId": KMS,
+ "ObjectLockMode": "COMPLIANCE", "ObjectLockRetainUntilDate": until, "ObjectLockLegalHoldStatus": "ON",
+ }
+ if put_error:
+ stub.add_client_error("put_object", service_error_code="PreconditionFailed", http_status_code=412, expected_params=expected)
+ return
+ stub.add_response("put_object", {"VersionId": version, "ChecksumSHA256": checksum, "ServerSideEncryption": "aws:kms", "SSEKMSKeyId": kms}, expected)
+ if version != "null" and kms == KMS:
+ object_args = {**common, "Key": key, "VersionId": version}
+ stub.add_response("get_object_retention", {"Retention": {"Mode": mode, "RetainUntilDate": until}}, object_args)
+ stub.add_response("get_object_legal_hold", {"LegalHold": {"Status": hold}}, object_args)
+
+
+def test_locked_publish_uses_versioned_create_only_encrypted_checksum_contract():
+ api, blob = client(), sealed()
+ with Stubber(api) as stub:
+ queue_publish(stub, blob)
+ receipt = custody.publish(api, blob, public_key_pem=PUBLIC, bucket=BUCKET, owner=OWNER, kms_key=KMS, now=NOW)
+ stub.assert_no_pending_responses()
+ assert receipt["version_id"] == "version-fixture"
+ assert receipt["sha256"] == hashlib.sha256(blob).hexdigest()
+ assert receipt["key"].endswith(receipt["archive_id"] + ".zip")
+
+
+def test_existing_object_refusal_never_retries_with_an_unprotected_overwrite():
+ api, blob = client(), sealed()
+ with Stubber(api) as stub:
+ queue_publish(stub, blob, put_error=True)
+ with pytest.raises(ClientError):
+ custody.publish(api, blob, public_key_pem=PUBLIC, bucket=BUCKET, owner=OWNER, kms_key=KMS, now=NOW)
+ stub.assert_no_pending_responses()
+
+
+@pytest.mark.parametrize("failure", [{"mode": "GOVERNANCE"}, {"hold": "OFF"}, {"version": "null"}, {"kms": KMS + "-different"}])
+def test_missing_hold_compliance_version_or_encryption_is_not_a_success(failure):
+ api, blob = client(), sealed()
+ with Stubber(api) as stub:
+ queue_publish(stub, blob, **failure)
+ with pytest.raises(custody.CustodyError):
+ custody.publish(api, blob, public_key_pem=PUBLIC, bucket=BUCKET, owner=OWNER, kms_key=KMS, now=NOW)
+ stub.assert_no_pending_responses()
+
+
+def test_expired_retention_and_unversioned_bucket_refuse_before_writing():
+ api, blob = client(), sealed()
+ with Stubber(api):
+ with pytest.raises(custody.CustodyError, match="retention has expired"):
+ custody.publish(api, blob, public_key_pem=PUBLIC, bucket=BUCKET, owner=OWNER, kms_key=KMS, now=NOW + timedelta(days=400))
+ with Stubber(api) as stub:
+ stub.add_response("get_bucket_versioning", {"Status": "Suspended"}, {"Bucket": BUCKET, "ExpectedBucketOwner": OWNER})
+ with pytest.raises(custody.CustodyError, match="versioning"):
+ custody.publish(api, blob, public_key_pem=PUBLIC, bucket=BUCKET, owner=OWNER, kms_key=KMS, now=NOW)
+ stub.assert_no_pending_responses()
+
+
+def test_application_caller_is_refused_before_any_archive_client_write(tmp_path, monkeypatch, capsys):
+ blob = tmp_path / "capture.zip"
+ public = tmp_path / "trusted.pem"
+ blob.write_bytes(sealed())
+ public.write_bytes(PUBLIC)
+
+ class Session:
+ def __init__(self, **kwargs):
+ assert kwargs["profile_name"] == "fixture-app"
+
+ def client(self, name, **_kwargs):
+ assert name == "sts", "wrong role must not construct the S3 client"
+ assert _kwargs["config"].ignore_configured_endpoint_urls is True
+ return SimpleNamespace(get_caller_identity=lambda: {"Account": OWNER, "Arn": f"arn:aws:sts::{OWNER}:assumed-role/Application/fixture"})
+
+ monkeypatch.setattr(boto3, "Session", Session)
+ result = custody.main(["publish", "--input", str(blob), "--public-key", str(public), "--archive-profile", "fixture-app", "--writer-role-arn", f"arn:aws:iam::{OWNER}:role/ArchiveWriter", "--bucket", BUCKET, "--owner-account", OWNER, "--kms-key-arn", KMS, "--region", "us-east-1"])
+ assert result == 2
+ output = capsys.readouterr()
+ assert "configured archive writer role" in output.err
+ assert "FAKE_PAYLOAD_MARKER" not in output.err
+
+
+def test_role_templates_separate_write_read_retention_and_app_capabilities():
+ path = Path(__file__).resolve().parents[3] / "infra/audit-archive/iam-policies.example.json"
+ policies = json.loads(path.read_text())
+
+ def actions(name):
+ return {action for statement in policies[name]["Statement"] for action in ([statement["Action"]] if isinstance(statement["Action"], str) else statement["Action"])}
+
+ assert "s3:PutObject" in actions("archive_writer")
+ assert not actions("archive_writer") & {"s3:GetObject", "s3:GetObjectVersion", "s3:DeleteObject", "s3:DeleteObjectVersion", "kms:Decrypt"}
+ assert not actions("audit_reader") & {"s3:PutObject", "s3:PutObjectRetention", "s3:PutObjectLegalHold", "s3:DeleteObjectVersion"}
+ assert actions("retention_operator") == {"s3:GetObjectRetention", "s3:GetObjectLegalHold", "s3:PutObjectLegalHold", "s3:DeleteObjectVersion"}
+ assert policies["application_explicit_deny"]["Statement"][0]["Effect"] == "Deny"
+ guards = {statement["Sid"]: statement for statement in policies["bucket_guard"]["Statement"]}
+ assert guards["DenyMissingCreateOnlyCondition"]["Condition"] == {"Null": {"s3:if-none-match": "true"}}
+ assert guards["DenyHoldRemovalExceptRetentionRole"]["Condition"]["ArnNotEquals"]["aws:PrincipalArn"] == "__RETENTION_OPERATOR_ROLE_ARN__"
+ assert guards["DenyDeleteMarkers"]["Action"] == "s3:DeleteObject"
+
+
+def test_optional_operator_sdk_pins_and_hashes_match_the_existing_backend_lock():
+ root = Path(__file__).resolve().parents[3]
+
+ def pins(path):
+ blocks = re.split(r"(?m)(?=^[a-zA-Z0-9][a-zA-Z0-9_.-]*==)", path.read_text())
+ return {
+ block.split("==")[0]: (block.splitlines()[0].rstrip(" \\"), set(re.findall(r"--hash=sha256:([0-9a-f]{64})", block)))
+ for block in blocks if re.match(r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*==", block)
+ }
+
+ backend = pins(root / "backend/requirements-lock.txt")
+ operator = pins(root / "cli/requirements-audit-archive.txt")
+ assert set(operator) == {"boto3", "botocore", "jmespath", "s3transfer", "python-dateutil", "six", "urllib3"}
+ assert all(value == backend[name] for name, value in operator.items())
diff --git a/backend/tests/regression/test_pipeline_event_admission.py b/backend/tests/regression/test_pipeline_event_admission.py
new file mode 100644
index 000000000..8ffc78607
--- /dev/null
+++ b/backend/tests/regression/test_pipeline_event_admission.py
@@ -0,0 +1,131 @@
+"""Exercise SQL evidence admission without any network or user data."""
+
+import uuid
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+import pytest_asyncio
+from sqlalchemy import event as sa_event, select, text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.models.postgres import PipelineEventOutbox
+from app.services import pipeline_event_admission, pipeline_event_log
+
+pytestmark = pytest.mark.asyncio
+
+
+@pytest_asyncio.fixture
+async def outbox(monkeypatch):
+ engine = create_async_engine("sqlite+aiosqlite://")
+
+ @sa_event.listens_for(engine.sync_engine, "begin")
+ def explicit_begin(conn):
+ conn.exec_driver_sql("BEGIN")
+
+ project, run, pipeline, other_project, other_run = (uuid.uuid4() for _ in range(5))
+ async with engine.begin() as conn:
+ await conn.execute(text("CREATE TABLE projects (id char(32) PRIMARY KEY)"))
+ await conn.execute(text("CREATE TABLE test_runs (id char(32) PRIMARY KEY, project_id char(32))"))
+ await conn.execute(text("CREATE TABLE agent_pipeline_runs (id char(32) PRIMARY KEY, test_run_id char(32))"))
+ await conn.execute(text("CREATE TABLE test_cases (id char(32) PRIMARY KEY, test_run_id char(32))"))
+ await conn.execute(text("INSERT INTO projects VALUES (:id), (:other)"), {
+ "id": project.hex, "other": other_project.hex,
+ })
+ await conn.execute(text("INSERT INTO test_runs VALUES (:run, :p), (:other, :other_p)"), {
+ "run": run.hex, "p": project.hex, "other": other_run.hex, "other_p": other_project.hex,
+ })
+ await conn.execute(text("INSERT INTO agent_pipeline_runs VALUES (:pipeline, :run)"), {
+ "pipeline": pipeline.hex, "run": run.hex,
+ })
+ await conn.run_sync(PipelineEventOutbox.__table__.create)
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ monkeypatch.setattr(pipeline_event_log, "get_session_factory", lambda: factory)
+ try:
+ yield factory, project, run, pipeline, other_project, other_run
+ finally:
+ await engine.dispose()
+
+
+async def test_intent_persists_across_sessions_and_distinguishes_retries(outbox):
+ from app.core.metrics import pipeline_event_admission_failures
+
+ def conflicts():
+ return next(
+ sample.value
+ for metric in pipeline_event_admission_failures.collect()
+ for sample in metric.samples
+ if sample.name.endswith("_total") and sample.labels == {"reason": "conflict"}
+ )
+
+ before = conflicts()
+ factory, project, run, pipeline, other_project, _ = outbox
+ event_id = uuid.uuid4()
+ detail = {"decision": "inspect", "contact": "fixture@example.invalid"}
+ assert await pipeline_event_log.emit_event(str(pipeline), "decision_made", detail=detail, event_id=event_id)
+ assert await pipeline_event_log.emit_event(str(pipeline), "decision_made", detail=detail, event_id=event_id)
+ assert not await pipeline_event_log.emit_event(str(pipeline), "decision_made", event_id=event_id)
+ assert conflicts() == before + 1
+ assert not await pipeline_event_log.emit_event(str(pipeline), "decision_made", project_id=other_project)
+ assert await pipeline_event_log.emit_event(str(pipeline), "decision_made", detail=detail)
+ async with factory() as db:
+ rows = (await db.scalars(select(PipelineEventOutbox))).all()
+ assert len(rows) == 2
+ assert {row.project_id for row in rows} == {project}
+ assert {row.test_run_id for row in rows} == {run}
+ assert {row.payload["event_id"] for row in rows} == {str(row.id) for row in rows}
+ assert all("fixture@example.invalid" not in str(row.payload) for row in rows)
+
+
+async def test_source_rollback_leaves_no_successful_evidence(outbox):
+ factory, project, run, _, _, _ = outbox
+ correlation = str(uuid.uuid4())
+ async with factory() as db:
+ assert await pipeline_event_log.emit_event(
+ correlation, "agent_run_recorded", db=db, project_id=project, test_run_id=run,
+ )
+ await db.rollback()
+ async with factory() as db:
+ assert (await db.scalars(select(PipelineEventOutbox))).all() == []
+
+
+async def test_quota_rejection_and_oversize_detail_retains_identity(outbox, monkeypatch):
+ factory, _, _, pipeline, _, _ = outbox
+ monkeypatch.setattr(pipeline_event_admission, "PIPELINE_EVENT_CAPACITY", 1)
+ detail = {"oversize": ["a" * 5000 for _ in range(8)]}
+ assert await pipeline_event_log.emit_event(str(pipeline), "decision_made", detail=detail)
+ assert not await pipeline_event_log.emit_event(str(pipeline), "decision_made")
+ async with factory() as db:
+ row = (await db.scalars(select(PipelineEventOutbox))).one()
+ assert row.payload["detail"] == {"detail_omitted": "size_or_content"}
+
+
+async def test_timeline_keeps_accepted_evidence_and_deduplicates_mongo(outbox, monkeypatch):
+ factory, _, _, pipeline, _, _ = outbox
+ assert await pipeline_event_log.emit_event(str(pipeline), "decision_made")
+ assert await pipeline_event_log.emit_event(str(pipeline), "stage_started")
+ async with factory() as db:
+ accepted = (await db.scalars(select(PipelineEventOutbox.payload))).all()
+ history = MagicMock()
+ cursor = history.__getitem__.return_value.find.return_value.sort.return_value
+ cursor.to_list = AsyncMock(return_value=[accepted[0]])
+ monkeypatch.setattr(pipeline_event_log, "get_mongo_db", lambda: history)
+ assert [row["event_type"] for row in await pipeline_event_log.get_pipeline_timeline(str(pipeline))] == [
+ "decision_made", "stage_started",
+ ]
+ cursor.to_list.side_effect = OSError("fixture unavailable")
+ assert len(await pipeline_event_log.get_pipeline_timeline(str(pipeline))) == 2
+
+
+async def test_purge_cancels_only_the_requested_source_intents(outbox):
+ factory, project, run, pipeline, other_project, other_run = outbox
+ assert await pipeline_event_log.emit_event(str(pipeline), "decision_made")
+ assert await pipeline_event_log.emit_event(
+ str(uuid.uuid4()), "agent_run_recorded", project_id=other_project, test_run_id=other_run,
+ )
+ async with factory.begin() as db:
+ await pipeline_event_admission.purge_pipeline_event_intents(
+ db, project, pipeline_run_ids=set(), test_run_ids={run, other_run},
+ )
+ async with factory() as db:
+ kept = (await db.scalars(select(PipelineEventOutbox))).one()
+ assert kept.project_id == other_project
diff --git a/backend/tests/regression/test_pipeline_event_delivery.py b/backend/tests/regression/test_pipeline_event_delivery.py
new file mode 100644
index 000000000..da0e5c050
--- /dev/null
+++ b/backend/tests/regression/test_pipeline_event_delivery.py
@@ -0,0 +1,306 @@
+"""Shared SQL receipts with synthetic Mongo and mounted scoped recovery API."""
+from __future__ import annotations
+
+import asyncio
+import copy
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+import uuid
+
+from fastapi import FastAPI, HTTPException
+import httpx
+from pymongo.errors import DuplicateKeyError, NetworkTimeout
+from pymongo.read_preferences import ReadPreference
+from pymongo.write_concern import WriteConcern
+import pytest
+from sqlalchemy import delete, select, update
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.core import metrics
+from app.models.postgres import PipelineEventOutbox, ProjectActivityEvent, UserRole
+from app.services import pipeline_event_delivery as delivery
+from app.services import pipeline_event_operational_metrics as health
+
+pytestmark = pytest.mark.regression
+
+
+@pytest.fixture
+async def world(monkeypatch, tmp_path):
+ from app.db import mongo, postgres
+
+ engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'events.sqlite'}")
+ async with engine.begin() as connection:
+ await connection.run_sync(lambda sync: PipelineEventOutbox.__table__.create(sync))
+ await connection.run_sync(lambda sync: ProjectActivityEvent.__table__.create(sync))
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ monkeypatch.setattr(postgres, "AsyncSessionLocal", sessions)
+ state = SimpleNamespace(now=datetime.now(timezone.utc), project=uuid.uuid4(), other=uuid.uuid4(), sessions=sessions)
+ monkeypatch.setattr(delivery, "_utcnow", lambda: state.now)
+
+ class Collection:
+ def __init__(self):
+ self.documents = {}
+ self.failure = None
+ self.accept_then_cancel = False
+ self.writes = 0
+ self.write_concern = WriteConcern()
+ self.options = None
+
+ def with_options(self, **kwargs):
+ self.options = kwargs
+ return self
+
+ async def insert_one(self, document):
+ self.writes += 1
+ if self.failure:
+ raise self.failure
+ if document["_id"] in self.documents:
+ raise DuplicateKeyError("synthetic duplicate")
+ stored = copy.deepcopy(document)
+ stored["timestamp"] = stored["timestamp"].replace(tzinfo=None) # BSON's default UTC readback.
+ self.documents[document["_id"]] = stored
+ if self.accept_then_cancel:
+ raise asyncio.CancelledError()
+ return SimpleNamespace(inserted_id=document["_id"])
+
+ async def find_one(self, query):
+ return copy.deepcopy(self.documents.get(query["_id"]))
+
+ collection = Collection()
+ monkeypatch.setattr(mongo, "get_mongo_db", lambda: {"pipeline_event_log": collection})
+
+ async def create(*, project_id=None, **values):
+ identifier = values.pop("id", uuid.uuid4())
+ defaults = dict(
+ id=identifier, project_id=project_id or state.project, pipeline_run_id=str(uuid.uuid4()),
+ status="pending", attempts=0, created_at=state.now - timedelta(minutes=10), next_attempt_at=state.now,
+ )
+ defaults.update(values)
+ defaults.setdefault("payload", {"pipeline_run_id": defaults["pipeline_run_id"], "event_type": "stage_completed",
+ "timestamp": state.now.isoformat(), "detail": {"synthetic": "private-evidence"}})
+ async with sessions() as db:
+ db.add(PipelineEventOutbox(**defaults))
+ await db.commit()
+ return identifier
+
+ async def read(identifier):
+ async with sessions() as db:
+ return await db.get(PipelineEventOutbox, identifier)
+
+ state.create, state.read, state.collection = create, read, collection
+ yield state
+ await engine.dispose()
+
+
+@pytest.mark.asyncio
+async def test_outage_then_recovery_retains_shared_receipt_and_one_logical_event(world):
+ identifier = await world.create()
+ world.collection.failure = NetworkTimeout("synthetic private connection failure")
+ result = await delivery.relay_pipeline_events()
+ assert result["retry"] == 1
+ failed = await world.read(identifier)
+ assert failed.status == "pending" and failed.attempts == 1
+ assert failed.last_error_code == "mongo_timeout"
+ async with world.sessions() as independent_api:
+ snapshot = await health.read_event_delivery_snapshot(independent_api, project_ids={world.project}, now=world.now)
+ assert snapshot["backlog_count"] == 1 and snapshot["write_failure_count"] == 1
+ world.collection.failure = None
+ world.now += timedelta(seconds=10)
+ assert (await delivery.relay_pipeline_events())["delivered"] == 1
+ assert (await world.read(identifier)).status == "delivered"
+ assert len(world.collection.documents) == 1
+ assert (await delivery.relay_pipeline_events())["delivered"] == 0
+ async with world.sessions() as another_api:
+ assert (await health.read_event_delivery_snapshot(another_api))["status"] == "healthy"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("configured,expected", [(WriteConcern(w="majority", j=False, wtimeout=7000), "majority"), (WriteConcern(w=0), 1)])
+async def test_materialization_preserves_stronger_ack_and_uses_primary_duplicate_reads(world, configured, expected):
+ world.collection.write_concern = configured
+ await world.create()
+ assert (await delivery.relay_pipeline_events())["delivered"] == 1
+ applied = world.collection.options
+ assert applied["write_concern"].document == {"w": expected, "j": True, "wtimeout": 2000}
+ assert applied["read_preference"] == ReadPreference.PRIMARY
+
+
+@pytest.mark.asyncio
+async def test_process_loss_after_mongo_acceptance_replays_same_id_without_duplicate(world):
+ identifier = await world.create()
+ world.collection.accept_then_cancel = True
+ with pytest.raises(asyncio.CancelledError):
+ await delivery.relay_pipeline_events()
+ old = await world.read(identifier)
+ assert old.status == "sending" and len(world.collection.documents) == 1
+ world.collection.accept_then_cancel = False
+ world.now += timedelta(seconds=delivery.LEASE_SECONDS + 1)
+ assert (await delivery.relay_pipeline_events())["delivered"] == 1
+ assert len(world.collection.documents) == 1
+ assert (await world.read(identifier)).attempts == 2
+
+
+@pytest.mark.asyncio
+async def test_duplicate_id_with_different_content_fails_without_overwriting_evidence(world):
+ identifier = await world.create()
+ original = {"_id": str(identifier), "detail": {"original": "synthetic"}}
+ world.collection.documents[str(identifier)] = copy.deepcopy(original)
+ assert (await delivery.relay_pipeline_events())["failed"] == 1
+ assert (await world.read(identifier)).last_error_code == "identity_conflict"
+ assert world.collection.documents[str(identifier)] == original
+ assert (await delivery.relay_pipeline_events())["failed"] == 0
+
+
+@pytest.mark.asyncio
+async def test_deleted_or_replaced_claim_cannot_materialize(world):
+ identifier = await world.create()
+ claim = await delivery._claim_one()
+ async with world.sessions() as db:
+ await db.execute(update(PipelineEventOutbox).where(PipelineEventOutbox.id == identifier).values(lease_token=uuid.uuid4()))
+ await db.commit()
+ assert await delivery._deliver_owned(*claim) == "stale"
+ async with world.sessions() as db:
+ await db.execute(delete(PipelineEventOutbox).where(PipelineEventOutbox.id == identifier))
+ await db.commit()
+ assert await delivery._deliver_owned(*claim) == "stale"
+ assert world.collection.writes == 0
+
+
+@pytest.mark.asyncio
+async def test_busy_project_purge_defers_without_mongo_write(world, monkeypatch):
+ from app.services import pipeline_event_admission
+ identifier = await world.create()
+ claim = await delivery._claim_one()
+
+ async def busy(*args, **kwargs):
+ return False
+
+ monkeypatch.setattr(pipeline_event_admission, "lock_project_event_history", busy)
+ assert await delivery._deliver_owned(*claim) == "deferred"
+ assert (await world.read(identifier)).status == "sending"
+ assert world.collection.writes == 0
+
+
+@pytest.mark.asyncio
+async def test_attempt_ceiling_and_explicit_requeue_are_bounded_and_caller_committed(world):
+ identifier = await world.create(attempts=delivery.MAX_ATTEMPTS)
+ assert (await delivery.relay_pipeline_events())["failed"] == 1
+ assert world.collection.writes == 0
+ async with world.sessions() as db:
+ assert await delivery.requeue_failed_event(db, identifier, project_id=world.other) is None
+ result = await delivery.requeue_failed_event(db, identifier, project_id=world.project)
+ assert result["previous_attempts"] == delivery.MAX_ATTEMPTS
+ await db.rollback()
+ assert (await world.read(identifier)).status == "failed"
+ async with world.sessions() as db:
+ await delivery.requeue_failed_event(db, identifier, project_id=world.project)
+ await db.commit()
+ assert (await delivery.relay_pipeline_events())["delivered"] == 1
+ assert (await world.read(identifier)).attempts == 1
+
+
+@pytest.mark.asyncio
+async def test_prune_only_old_delivered_receipts_and_preserve_unresolved_evidence(world):
+ old = await world.create(status="delivered", delivered_at=world.now - timedelta(hours=2))
+ fresh = await world.create(status="delivered", delivered_at=world.now)
+ failed = await world.create(status="failed")
+ pending = await world.create()
+ assert await delivery.prune_delivered_events() == 1
+ assert await world.read(old) is None
+ for identifier in (fresh, failed, pending):
+ assert await world.read(identifier) is not None
+
+
+@pytest.mark.asyncio
+async def test_pressure_prune_restores_capacity_without_removing_unresolved_evidence(world, monkeypatch):
+ from app.services import pipeline_event_admission
+ monkeypatch.setattr(pipeline_event_admission, "PIPELINE_EVENT_CAPACITY", 3)
+ delivered = await world.create(status="delivered", delivered_at=world.now)
+ failed = await world.create(status="failed")
+ pending = await world.create()
+ assert await delivery.prune_delivered_events() == 1
+ assert await world.read(delivered) is None
+ assert await world.read(failed) is not None and await world.read(pending) is not None
+
+
+@pytest.mark.asyncio
+async def test_same_logical_id_after_receipt_expiry_preserves_original_mongo_timestamp(world):
+ identifier = await world.create()
+ receipt = await world.read(identifier)
+ await delivery.relay_pipeline_events()
+ original = copy.deepcopy(world.collection.documents[str(identifier)])
+ world.now += timedelta(hours=2)
+ assert await delivery.prune_delivered_events() == 1
+ payload = copy.deepcopy(receipt.payload)
+ payload["timestamp"] = world.now.isoformat()
+ await world.create(id=identifier, pipeline_run_id=receipt.pipeline_run_id, payload=payload)
+ assert (await delivery.relay_pipeline_events())["delivered"] == 1
+ assert world.collection.documents[str(identifier)] == original
+
+
+@pytest.mark.asyncio
+async def test_health_is_shared_scoped_and_never_returns_event_detail(world):
+ await world.create(status="failed", last_error_code="mongo_timeout", attempts=8)
+ other_id = await world.create(project_id=world.other, status="failed", last_error_code="mongo_unavailable")
+ async with world.sessions() as db:
+ snapshot = await health.read_event_log_health(db, project_ids={world.project})
+ empty = await health.read_event_log_health(db, project_ids=set())
+ assert snapshot["dead_letter_count"] == 1 and snapshot["backlog_count"] == 1
+ assert str(other_id) not in str(snapshot) and "private-evidence" not in str(snapshot)
+ assert empty["status"] == "healthy" and empty["outbox_total_count"] == 0
+ await health.refresh_pipeline_event_operational_metrics()
+ assert metrics.pipeline_event_outbox_entries.labels(status="failed")._value.get() == 2
+ assert metrics.pipeline_event_outbox_capacity._value.get() == 10_000
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("state", ["sending", "delivered"])
+async def test_bad_lease_or_receipt_state_cannot_publish_fresh_healthy_zero(world, state):
+ identifier = await world.create(status=state, lease_expires_at=None, delivered_at=None)
+ with pytest.raises(ValueError, match="lifecycle"):
+ await health.refresh_pipeline_event_operational_metrics()
+ assert await delivery.prune_delivered_events() == 0
+ assert await world.read(identifier) is not None
+
+
+@pytest.mark.asyncio
+async def test_mounted_replay_requires_role_project_scope_and_records_safe_activity(world, monkeypatch):
+ from app.core import deps
+ from app.db.postgres import get_db
+ from app.routers import agents
+
+ identifier = await world.create(status="failed", attempts=8, last_error_code="mongo_timeout")
+ foreign = await world.create(project_id=world.other, status="failed")
+ actor = SimpleNamespace(id=uuid.uuid4(), role=UserRole.QA_LEAD, username="synthetic-lead", is_active=True)
+ app = FastAPI()
+ app.include_router(agents.router)
+ app.dependency_overrides[deps.get_current_active_user] = lambda: actor
+
+ async def session():
+ async with world.sessions() as db:
+ yield db
+
+ async def scope(db, user, requested):
+ if requested and uuid.UUID(requested) != world.project:
+ raise HTTPException(403, "No project access")
+ return (uuid.UUID(requested) if requested else None), {world.project}
+
+ app.dependency_overrides[get_db] = session
+ monkeypatch.setattr(agents, "resolve_project_scope", scope)
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
+ assert (await client.post(f"/api/v1/agents/event-log/{foreign}/replay", params={"project_id": str(world.other)})).status_code == 403
+ assert (await client.post(f"/api/v1/agents/event-log/{foreign}/replay", params={"project_id": str(world.project)})).status_code == 404
+ actor.role = UserRole.VIEWER
+ assert (await client.post(f"/api/v1/agents/event-log/{identifier}/replay", params={"project_id": str(world.project)})).status_code == 403
+ actor.role = UserRole.QA_LEAD
+ response = await client.post(f"/api/v1/agents/event-log/{identifier}/replay", params={"project_id": str(world.project)})
+ assert response.status_code == 202 and response.json()["status"] == "pending"
+ assert "private-evidence" not in response.text
+ assert (await client.post(f"/api/v1/agents/event-log/{identifier}/replay", params={"project_id": str(world.project)})).status_code == 409
+ observed = await client.get("/api/v1/agents/event-log/health")
+ assert observed.status_code == 200 and observed.json()["backlog_count"] == 1
+ assert str(foreign) not in observed.text
+ async with world.sessions() as db:
+ events = (await db.scalars(select(ProjectActivityEvent))).all()
+ assert len(events) == 1 and events[0].event_type == "analysis.event_delivery_requeued"
+ assert (await world.read(foreign)).status == "failed"
diff --git a/backend/tests/test_agent_actions_router.py b/backend/tests/test_agent_actions_router.py
index 8d13529ba..6d1b78649 100644
--- a/backend/tests/test_agent_actions_router.py
+++ b/backend/tests/test_agent_actions_router.py
@@ -317,7 +317,8 @@ async def _spy(db, **kw):
db, ("add", "AccessAuditLog"), ("add", "ProjectActivityEvent"), ("commit",), ("refresh",),
("event", "agent_action_approved"),
)
- assert audit_at < commit_at and activity_at < commit_at < refresh_at < event_at
+ assert audit_at < event_at and activity_at < event_at < commit_at < refresh_at
+ assert live.emitted.await_args.kwargs["db"] is db
assert answer.status == "approved" and answer.approved_by == str(approver.id)
live.bump.assert_not_awaited() # nothing changed analytics data yet: the executor bumps
diff --git a/backend/tests/test_agent_pipeline_hardening_regression.py b/backend/tests/test_agent_pipeline_hardening_regression.py
index 4e67a0c99..47242034b 100644
--- a/backend/tests/test_agent_pipeline_hardening_regression.py
+++ b/backend/tests/test_agent_pipeline_hardening_regression.py
@@ -339,17 +339,14 @@ def test_stage_replay_checksums_and_runtime_versions_are_persisted():
assert '"final_state_checksum_sha256": _canonical_checksum(final_state)' in mark_done
-def test_event_log_has_retry_and_dead_letter_accounting():
- event_log = _read("app/services/pipeline_event_log.py")
+def test_event_log_admits_to_sql_before_relay():
emit_event = _function_source("app/services/pipeline_event_log.py", "emit_event")
+ stage_event = _function_source("app/services/pipeline_event_admission.py", "stage_pipeline_event")
- assert "_MAX_WRITE_ATTEMPTS" in event_log
- assert "_DEAD_LETTER_EVENTS" in event_log
- assert "def _record_dead_letter" in event_log
- assert "def get_event_log_health" in event_log
- assert "for attempt in range(1, _MAX_WRITE_ATTEMPTS + 1)" in emit_event
- assert "await asyncio.sleep(0)" in emit_event
- assert "_record_dead_letter(event, last_error)" in emit_event
+ assert "await stage_pipeline_event" in emit_event
+ assert "db.begin_nested()" in emit_event
+ assert "get_mongo_db" not in emit_event
+ assert "PipelineEventOutbox(" in stage_event
def test_decision_trail_falls_back_to_postgres_route_decisions():
@@ -420,8 +417,9 @@ def test_agents_router_exposes_event_log_health_and_timeline_integrity():
assert "PipelineEventLogHealthResponse" in router
assert '@router.get("/event-log/health", response_model=PipelineEventLogHealthResponse)' in router
assert "require_role(UserRole.QA_LEAD)" in health
- assert "get_event_log_health" in health
- assert '"status": status' in health
+ assert "read_event_log_health" in health
+ assert "resolve_project_scope" in health
+ assert "project_ids=projects" in health
assert "build_replay_integrity_summary" in timeline
assert '"replay_integrity": replay_integrity' in timeline
diff --git a/backend/tests/test_identity_retention.py b/backend/tests/test_identity_retention.py
new file mode 100644
index 000000000..896f5d403
--- /dev/null
+++ b/backend/tests/test_identity_retention.py
@@ -0,0 +1,339 @@
+"""Narrow identity expiry: real disposable SQL, protected authority and guards."""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+import uuid
+
+from fastapi import FastAPI
+from httpx import ASGITransport, AsyncClient
+import pytest
+from sqlalchemy import Column, MetaData, Table, func, insert, select
+from sqlalchemy.dialects import postgresql
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.core.deps import (
+ _bind_api_key_project, _bind_credential_kind, get_current_active_user,
+)
+from app.db.postgres import get_db
+from app.models.identity_retention import ROUTINE_EVENT_TYPES, IdentityRetentionDocument
+from app.models.postgres import (
+ AppSetting, FederatedIdentity, IdentityEvent, InstanceRetentionPolicy, SettingsAuditLog, User,
+)
+from app.routers.identity_events import router
+from app.services import identity_retention_service as service
+from app.services.retention_service import FIELD_BOUNDS, purge_identity_events_batch
+
+
+def actor(*, role="ADMIN", credential="jwt", bound=False):
+ user = SimpleNamespace(id=uuid.uuid4(), role=role, username="synthetic-admin", full_name="Synthetic Admin", is_active=True)
+ _bind_credential_kind(user, credential)
+ if bound:
+ _bind_api_key_project(user, uuid.uuid4())
+ return user
+
+
+@pytest.fixture
+async def world(tmp_path, monkeypatch):
+ engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'identity.sqlite'}")
+ # Only the id column is needed by the real SCIM scope query. This avoids
+ # pretending SQLite tests the unrelated PostgreSQL account schema.
+ users = Table("users", MetaData(), Column("id", User.__table__.c.id.type, primary_key=True))
+ async with engine.begin() as connection:
+ await connection.run_sync(users.create)
+ for table in (AppSetting.__table__, IdentityEvent.__table__, SettingsAuditLog.__table__,
+ FederatedIdentity.__table__, InstanceRetentionPolicy.__table__):
+ await connection.run_sync(table.create)
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ principal, local, admin = uuid.uuid4(), uuid.uuid4(), actor()
+ now = datetime.now(timezone.utc)
+ async with sessions() as db:
+ await db.execute(insert(users).values([{"id": value} for value in (principal, local, admin.id)]))
+ await db.commit()
+ monkeypatch.setattr("app.db.postgres.AsyncSessionLocal", sessions, raising=False)
+
+ async def seed(event_type="SSO_LOGIN", *, days=500, success=True, user_id=None, count=1):
+ async with sessions() as db:
+ events = [IdentityEvent(
+ id=uuid.uuid4(), event_type=event_type, user_id=user_id or principal,
+ created_at=now - timedelta(days=days), success=success,
+ detail={"marker": "synthetic-event-content"}, ip_address="203.0.113.17",
+ ) for _ in range(count)]
+ db.add_all(events)
+ await db.commit()
+ return [event.id for event in events]
+
+ async def approve(days=365):
+ async with sessions() as db:
+ preview = await service.preview(db, now=now, retention_days=days)
+ await service.approve_policy(
+ db, actor=admin, retention_days=days, observed_at=preview["observed_at"],
+ preview_hash=preview["preview_hash"], confirmation=preview["enable_confirmation"],
+ reason="Synthetic approved retention policy", now=now,
+ )
+ await db.commit()
+
+ async def remaining():
+ async with sessions() as db:
+ return set((await db.execute(select(IdentityEvent.id))).scalars())
+
+ async def purge(*, batch_size=500, scheduled=False, commit=True):
+ async with sessions() as db:
+ preview = await service.preview(db, now=now)
+ result = await purge_identity_events_batch(
+ db, now=now, actor=admin, batch_size=batch_size, scheduled=scheduled,
+ observed_at=preview["observed_at"], preview_hash=preview["preview_hash"],
+ confirmation=preview["purge_confirmation"], reason="Synthetic explicit maintenance",
+ )
+ if commit:
+ await db.commit()
+ else:
+ await db.rollback()
+ return result
+
+ yield SimpleNamespace(sessions=sessions, now=now, seed=seed, approve=approve, remaining=remaining,
+ purge=purge, principal=principal, local=local, admin=admin)
+ await engine.dispose()
+
+
+@pytest.mark.asyncio
+async def test_default_does_not_inherit_existing_project_instance_enablement(world):
+ old = await world.seed(days=5000)
+ async with world.sessions() as db:
+ db.add(InstanceRetentionPolicy(id=1, enabled=True, audit_days=365))
+ await db.commit()
+ assert (await world.purge(scheduled=True)) == {"status": "disabled", "deleted": 0}
+ assert await world.remaining() == set(old)
+ async with world.sessions() as db:
+ assert await db.get(AppSetting, service.POLICY_KEY) is None
+ assert (await db.execute(select(func.count()).select_from(SettingsAuditLog))).scalar_one() == 0
+
+
+@pytest.mark.asyncio
+async def test_only_successful_routine_events_expire_and_scim_authority_still_authorizes(world):
+ from app.services.mfa_service import is_sso_managed
+ from app.services.scim_service import scim_visible_user_ids
+
+ disposable = set()
+ for kind in ROUTINE_EVENT_TYPES:
+ disposable.update(await world.seed(kind))
+ kept = set(await world.seed("SCIM_USER_CREATED", days=5000))
+ kept.update(await world.seed("SSO_LOGIN_FAILED", days=5000, success=False))
+ kept.update(await world.seed("ACCOUNT_LOCKED", days=5000))
+ kept.update(await world.seed("MFA_BREAKGLASS_RESET", days=5000))
+ kept.update(await world.seed("UNKNOWN_FUTURE_EVENT", days=5000))
+ kept.update(await world.seed("SSO_LOGIN", success=False))
+ kept.update(await world.seed("SSO_LOGIN", days=20))
+ await world.approve()
+ result = await world.purge()
+ assert result["deleted"] == len(disposable) == 3
+ assert await world.remaining() == kept
+ async with world.sessions() as db:
+ assert await scim_visible_user_ids(db, {world.principal, world.local}, None) == {world.principal}
+ assert await is_sso_managed(db, SimpleNamespace(id=world.principal)) is True
+ assert await is_sso_managed(db, SimpleNamespace(id=world.local)) is False
+ audit = (await db.execute(select(SettingsAuditLog).where(
+ SettingsAuditLog.setting_key == service.PURGE_AUDIT_KEY,
+ ))).scalar_one()
+ assert audit.actor_id == world.admin.id
+ assert audit.changed_fields["deleted"] == 3
+ assert "synthetic-event-content" not in str(audit.changed_fields)
+ assert "203.0.113.17" not in str(audit.changed_fields)
+
+
+@pytest.mark.asyncio
+async def test_finite_batches_boundary_and_atomic_rollback(world):
+ await world.seed(count=5)
+ boundary = await world.seed(days=365)
+ await world.approve()
+ assert (await world.purge(batch_size=2, commit=False))["deleted"] == 2
+ assert len(await world.remaining()) == 6
+ async with world.sessions() as db:
+ assert (await db.execute(select(func.count()).select_from(SettingsAuditLog).where(
+ SettingsAuditLog.setting_key == service.PURGE_AUDIT_KEY,
+ ))).scalar_one() == 0
+ assert (await world.purge(batch_size=2))["batch_full"] is True
+ assert (await world.purge(batch_size=2))["deleted"] == 2
+ assert (await world.purge(batch_size=2))["deleted"] == 1
+ assert await world.remaining() == set(boundary)
+
+
+@pytest.mark.asyncio
+async def test_overlapping_holds_are_independent_and_preserve_audit_history(world):
+ original = set(await world.seed())
+ await world.approve()
+ async with world.sessions() as db:
+ first = await service.place_hold(db, actor=world.admin, reason="Synthetic investigation one", expires_at=None, now=world.now)
+ second = await service.place_hold(db, actor=world.admin, reason="Synthetic investigation two", expires_at=None, now=world.now)
+ await db.commit()
+ assert (await world.purge(scheduled=True))["status"] == "held"
+ async with world.sessions() as db:
+ await service.release_hold(db, actor=world.admin, hold_id=first.id, reason="Synthetic case resolved",
+ confirmation=service.RELEASE_CONFIRMATION, now=world.now)
+ await db.commit()
+ with pytest.raises(service.IdentityRetentionError, match="hold prevents"):
+ await world.purge()
+ assert await world.remaining() == original
+ async with world.sessions() as db:
+ await service.release_hold(db, actor=world.admin, hold_id=second.id, reason="Synthetic second case resolved",
+ confirmation=service.RELEASE_CONFIRMATION, now=world.now)
+ await db.commit()
+ rows = (await db.execute(select(SettingsAuditLog).where(SettingsAuditLog.action.in_(["hold_placed", "hold_released"])))).scalars().all()
+ assert len(rows) == 4
+ assert {row.changed_fields["hold"]["id"] for row in rows} == {str(first.id), str(second.id)}
+ assert (await world.purge())["deleted"] == 1
+
+
+@pytest.mark.asyncio
+async def test_expired_hold_does_not_require_a_job_and_disable_never_releases_live_hold(world):
+ await world.seed()
+ await world.approve()
+ async with world.sessions() as db:
+ await service.place_hold(db, actor=world.admin, reason="Synthetic expired hold",
+ expires_at=world.now - timedelta(days=1), now=world.now - timedelta(days=2))
+ await db.commit()
+ assert (await world.purge())["deleted"] == 1
+ async with world.sessions() as db:
+ await service.place_hold(db, actor=world.admin, reason="Synthetic live hold", expires_at=None, now=world.now)
+ await service.disable_policy(db, actor=world.admin, reason="Synthetic safe disable")
+ await db.commit()
+ read = await service.read_policy(db, now=world.now)
+ assert read["enabled"] is False and read["active_hold_count"] == 1
+
+
+@pytest.mark.asyncio
+async def test_stale_preview_and_policy_corruption_fail_closed(world):
+ original = set(await world.seed())
+ async with world.sessions() as db:
+ preview = await service.preview(db, now=world.now, retention_days=365)
+ await service.place_hold(db, actor=world.admin, reason="Synthetic new hold", expires_at=None, now=world.now)
+ await db.commit()
+ with pytest.raises(service.IdentityRetentionError, match="preview expired"):
+ await service.approve_policy(db, actor=world.admin, retention_days=365,
+ observed_at=world.now, preview_hash=preview["preview_hash"],
+ confirmation=preview["enable_confirmation"], reason="Synthetic approval", now=world.now)
+ await db.rollback()
+ row = await db.get(AppSetting, service.POLICY_KEY)
+ row.value = {"enabled": True, "retention_days": 1}
+ await db.commit()
+ with pytest.raises(service.IdentityRetentionError, match="unreadable"):
+ await world.purge(scheduled=True)
+ assert await world.remaining() == original
+
+
+@pytest.mark.asyncio
+async def test_failed_audit_flush_rolls_back_deleted_rows(world, monkeypatch):
+ original = set(await world.seed())
+ await world.approve()
+ async with world.sessions() as db:
+ monkeypatch.setattr(db, "flush", AsyncMock(side_effect=RuntimeError("synthetic audit failure")))
+ with pytest.raises(RuntimeError, match="synthetic audit"):
+ await purge_identity_events_batch(db, now=world.now, scheduled=True)
+ await db.rollback()
+ assert await world.remaining() == original
+
+
+@pytest.mark.asyncio
+async def test_scheduled_wrapper_honors_instance_utc_window(world):
+ await world.seed()
+ await world.approve()
+ async with world.sessions() as db:
+ db.add(InstanceRetentionPolicy(id=1, enabled=False, purge_window_start_utc=0))
+ await db.commit()
+ assert (await service.run_scheduled_batch(now=world.now.replace(hour=1)))["status"] == "outside_window"
+ assert (await service.run_scheduled_batch(now=world.now.replace(hour=0)))["deleted"] == 1
+
+
+def test_allowlist_bounds_and_lock_contract():
+ assert set(ROUTINE_EVENT_TYPES) == {"SSO_LOGIN", "SSO_LOGOUT", "MFA_VERIFY_SUCCESS"}
+ assert FIELD_BOUNDS["audit_days"] == (365, 3650)
+ assert IdentityRetentionDocument().enabled is False
+ statement = select(AppSetting).where(AppSetting.key == service.POLICY_KEY).with_for_update()
+ assert "FOR UPDATE" in str(statement.compile(dialect=postgresql.dialect()))
+ candidate = select(IdentityEvent.id).where(service.routine_event_clause()).limit(500).with_for_update(skip_locked=True)
+ sql = str(candidate.compile(dialect=postgresql.dialect()))
+ assert "FOR UPDATE SKIP LOCKED" in sql and "success IS true" in sql
+
+
+@pytest.fixture
+def client_factory(world):
+ def create(user):
+ app = FastAPI()
+ app.include_router(router)
+
+ async def db_dependency():
+ async with world.sessions() as db:
+ try:
+ yield db
+ except BaseException:
+ await db.rollback()
+ raise
+
+ app.dependency_overrides[get_db] = db_dependency
+ app.dependency_overrides[get_current_active_user] = lambda: user
+ return AsyncClient(transport=ASGITransport(app=app), base_url="http://testserver")
+ return create
+
+
+_READS = [("GET", "/retention/policy", None), ("GET", "/retention/preview", None)]
+_WRITES = [
+ ("POST", "/retention/policy", {"retention_days": 365, "observed_at": datetime.now(timezone.utc).isoformat(),
+ "preview_hash": "a" * 64, "confirmation": "synthetic", "reason": "Synthetic reason"}),
+ ("POST", "/retention/disable", {"reason": "Synthetic reason"}),
+ ("POST", "/retention/holds", {"reason": "Synthetic reason"}),
+ ("POST", f"/retention/holds/{uuid.UUID(int=1)}/release", {"reason": "Synthetic reason", "confirmation": "synthetic"}),
+ ("POST", "/retention/purge", {"observed_at": datetime.now(timezone.utc).isoformat(), "preview_hash": "a" * 64,
+ "confirmation": "synthetic", "reason": "Synthetic reason"}),
+]
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("role", ["VIEWER", "QA_ENGINEER", "QA_LEAD"])
+@pytest.mark.parametrize(("method", "path", "body"), [*_READS, *_WRITES])
+async def test_every_retention_route_is_instance_admin_only(client_factory, role, method, path, body):
+ async with client_factory(actor(role=role)) as client:
+ response = await client.request(method, "/api/v1/identity" + path, json=body)
+ assert response.status_code == 403
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(("method", "path", "body"), _WRITES)
+async def test_even_unbound_admin_api_keys_cannot_mutate_retention(client_factory, method, path, body):
+ async with client_factory(actor(credential="api_key")) as client:
+ response = await client.request(method, "/api/v1/identity" + path, json=body)
+ assert response.status_code == 403
+ assert response.json()["detail"]["code"] == "interactive_admin_required"
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(("method", "path", "body"), [*_READS, *_WRITES])
+async def test_project_bound_admin_key_cannot_read_or_mutate_instance_policy(client_factory, method, path, body):
+ async with client_factory(actor(credential="api_key", bound=True)) as client:
+ response = await client.request(method, "/api/v1/identity" + path, json=body)
+ assert response.status_code == 403
+
+
+@pytest.mark.asyncio
+async def test_real_guarded_enable_preview_purge_and_permanent_audit(world, client_factory):
+ routine = set(await world.seed(count=2))
+ authority = set(await world.seed("SCIM_USER_CREATED", days=5000))
+ async with client_factory(world.admin) as client:
+ preview = (await client.get("/api/v1/identity/retention/preview?retention_days=365")).json()
+ assert preview["counts"] == {"routine_authentication": 2, "scim_authority": 1, "protected_identity": 0}
+ assert "synthetic-event-content" not in str(preview)
+ response = await client.post("/api/v1/identity/retention/policy", json={
+ "retention_days": 365, "observed_at": preview["observed_at"], "preview_hash": preview["preview_hash"],
+ "confirmation": preview["enable_confirmation"], "reason": "Synthetic approved administration",
+ })
+ assert response.status_code == 200, response.text
+ assert response.json()["enabled"] is True
+ preview = (await client.get("/api/v1/identity/retention/preview")).json()
+ response = await client.post("/api/v1/identity/retention/purge", json={
+ "observed_at": preview["observed_at"], "preview_hash": preview["preview_hash"],
+ "confirmation": preview["purge_confirmation"], "reason": "Synthetic explicit cleanup", "batch_size": 1,
+ })
+ assert response.status_code == 200, response.text
+ assert response.json()["deleted"] == 1
+ assert authority <= await world.remaining()
+ assert len(routine & await world.remaining()) == 1
diff --git a/backend/tests/test_p2_features.py b/backend/tests/test_p2_features.py
index 7ee02e1aa..0f9969421 100644
--- a/backend/tests/test_p2_features.py
+++ b/backend/tests/test_p2_features.py
@@ -283,22 +283,19 @@ class TestPipelineEventLog:
"""Verify immutable event log operations."""
@pytest.mark.asyncio
- async def test_emit_event_inserts_to_mongo(self):
+ async def test_emit_event_stages_an_immutable_intent(self):
from app.services.pipeline_event_log import emit_event
- mock_collection = AsyncMock()
- mock_collection.insert_one = AsyncMock()
- mock_db = MagicMock()
- mock_db.__getitem__ = MagicMock(return_value=mock_collection)
-
- with patch("app.services.pipeline_event_log.get_mongo_db", return_value=mock_db):
- await emit_event(
+ db = MagicMock()
+ with patch("app.services.pipeline_event_log.stage_pipeline_event", new_callable=AsyncMock) as stage:
+ assert await emit_event(
"run-123", "stage_started",
stage_name="ingestion",
detail={"message": "starting"},
+ db=db,
)
- mock_collection.insert_one.assert_called_once()
- event = mock_collection.insert_one.call_args[0][0]
+ stage.assert_awaited_once()
+ event = stage.call_args.kwargs["event"]
assert event["pipeline_run_id"] == "run-123"
assert event["event_type"] == "stage_started"
assert event["stage_name"] == "ingestion"
@@ -308,9 +305,9 @@ async def test_emit_event_inserts_to_mongo(self):
async def test_emit_event_does_not_raise_on_error(self):
from app.services.pipeline_event_log import emit_event
- with patch("app.services.pipeline_event_log.get_mongo_db", side_effect=Exception("mongo down")):
+ with patch("app.services.pipeline_event_log.get_session_factory", side_effect=Exception("database down")):
# Should not raise — event logging is best-effort
- await emit_event("run-123", "stage_started")
+ assert not await emit_event("run-123", "stage_started")
@pytest.mark.asyncio
async def test_get_pipeline_timeline_returns_events(self):
@@ -329,7 +326,10 @@ async def test_get_pipeline_timeline_returns_events(self):
mock_db = MagicMock()
mock_db.__getitem__ = MagicMock(return_value=mock_collection)
- with patch("app.services.pipeline_event_log.get_mongo_db", return_value=mock_db):
+ with (
+ patch("app.services.pipeline_event_log.get_mongo_db", return_value=mock_db),
+ patch("app.services.pipeline_event_log._read_retained_events", new=AsyncMock(return_value=[])),
+ ):
events = await get_pipeline_timeline("run-123")
assert len(events) == 2
assert events[0]["event_type"] == "stage_started"
@@ -338,7 +338,10 @@ async def test_get_pipeline_timeline_returns_events(self):
async def test_get_pipeline_timeline_returns_empty_on_error(self):
from app.services.pipeline_event_log import get_pipeline_timeline
- with patch("app.services.pipeline_event_log.get_mongo_db", side_effect=Exception("mongo down")):
+ with (
+ patch("app.services.pipeline_event_log.get_mongo_db", side_effect=Exception("mongo down")),
+ patch("app.services.pipeline_event_log._read_retained_events", new=AsyncMock(return_value=[])),
+ ):
events = await get_pipeline_timeline("run-123")
assert events == []
@@ -346,17 +349,13 @@ async def test_get_pipeline_timeline_returns_empty_on_error(self):
async def test_emit_event_includes_test_case_id(self):
from app.services.pipeline_event_log import emit_event
- mock_collection = AsyncMock()
- mock_collection.insert_one = AsyncMock()
- mock_db = MagicMock()
- mock_db.__getitem__ = MagicMock(return_value=mock_collection)
-
- with patch("app.services.pipeline_event_log.get_mongo_db", return_value=mock_db):
- await emit_event(
+ with patch("app.services.pipeline_event_log.stage_pipeline_event", new_callable=AsyncMock) as stage:
+ assert await emit_event(
"run-123", "cache_hit",
test_case_id="tc-456",
detail={"type": "redis_exact"},
+ db=MagicMock(),
)
- event = mock_collection.insert_one.call_args[0][0]
+ event = stage.call_args.kwargs["event"]
assert event["test_case_id"] == "tc-456"
assert event["detail"]["type"] == "redis_exact"
diff --git a/backend/tests/test_project_export_history.py b/backend/tests/test_project_export_history.py
index 4484f2486..fe7bdb8a9 100644
--- a/backend/tests/test_project_export_history.py
+++ b/backend/tests/test_project_export_history.py
@@ -494,7 +494,7 @@ def test_a_live_event_keyed_by_a_session_slug_travels_under_its_run(monkeypatch:
assert sorted(line["run_id"] for line in lines) == sorted([str(run_id), str(other_run)])
(call,) = mongo.calls
assert sorted(call["query"]["run_id"]["$in"]) == sorted([str(run_id), str(other_run), slug])
- assert "FROM live_sessions" in _sql(db.statements[0])
+ assert any("FROM live_sessions" in _sql(statement) for statement in db.statements)
def test_the_real_mongo_specs_are_all_selectable() -> None:
@@ -800,6 +800,97 @@ async def no_sleep(_seconds: float) -> None:
assert world["mongo"].calls == [] and world["store"].streamed == []
+def test_accepted_event_guard_uses_only_the_selected_canonical_pipeline_scope() -> None:
+ project_id, run_id = uuid.uuid4(), uuid.uuid4()
+ db = RecordingSession({})
+ window = _window([run_id], project_id)
+ asyncio.run(hx.ensure_pipeline_events_materialized(db, window))
+ statement, = db.statements
+ sql = _sql(statement)
+ assert "pipeline_event_outbox.project_id =" in sql
+ assert "pipeline_event_outbox.status !=" in sql
+ assert "pipeline_event_outbox.pipeline_id IN (SELECT agent_pipeline_runs.id" in sql
+ assert "agent_pipeline_runs.test_run_id = ANY" in sql
+ assert "agent_pipeline_runs.status IN" in sql
+ params = statement.compile(dialect=PG).params
+ assert params["project_id_1"] == project_id
+ assert params["run_window"] == [run_id]
+ assert params["status_1"] == "delivered"
+
+
+def test_accepted_sql_event_without_mongo_materialization_blocks_publication(
+ monkeypatch: pytest.MonkeyPatch, signing: Any,
+) -> None:
+ world = _history_world(monkeypatch)
+ world["rows"]["pipeline_event_outbox"] = [{"id": uuid.uuid4(), "status": "pending"}]
+ db = RecordingSession(world["rows"], users=world["users"], counts=(1, 0))
+ with pytest.raises(svc.ProjectExportFailed) as caught:
+ _export(world, db, sign_db=RecordingSession({}))
+ assert caught.value.code == "export_build"
+ assert caught.value.params == {"error_type": "PipelineEventDeliveryPending"}
+ assert world["store"].archives == {} and world["store"].streamed == []
+ assert world["mongo"].calls == []
+ # Counts-only preview remains available rather than turning a GET into an
+ # archive creation/error path. It does not promise materialization.
+ estimated = _estimate(world, RecordingSession(world["rows"], counts=(1, 0)))
+ assert estimated.measured["documents"] is True and estimated.estimated_bytes is not None
+
+
+def test_real_sql_guard_ignores_other_windows_projects_and_delivered_receipts(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Any,
+) -> None:
+ from sqlalchemy import Uuid, literal, select, update
+ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+ from app.models.postgres import PipelineEventOutbox
+
+ project_id, foreign_project, run_id, pipeline_id, outside_pipeline = (uuid.uuid4() for _ in range(5))
+ # Existing canonical-pipeline selection is compiled above. Substitute its
+ # result for SQLite, which has no PostgreSQL ANY(array) operator, while
+ # exercising the actual new tenant/state/pipeline predicate on real rows.
+ monkeypatch.setattr(hx, "exported_ids", lambda table, window: select(literal(pipeline_id, Uuid())))
+
+ async def scenario() -> None:
+ engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'export-events.sqlite'}")
+ try:
+ async with engine.begin() as connection:
+ await connection.run_sync(lambda sync: PipelineEventOutbox.__table__.create(sync))
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ selected = uuid.uuid4()
+ now = datetime.now(timezone.utc)
+ async with sessions() as db:
+ for identifier, project, pipeline in (
+ (selected, project_id, pipeline_id),
+ (uuid.uuid4(), project_id, outside_pipeline),
+ (uuid.uuid4(), foreign_project, pipeline_id),
+ (uuid.uuid4(), project_id, None),
+ ):
+ db.add(PipelineEventOutbox(
+ id=identifier, project_id=project, pipeline_id=pipeline,
+ pipeline_run_id=str(pipeline or uuid.uuid4()), payload={"detail": "synthetic-private-evidence"},
+ status="pending", attempts=0, created_at=now,
+ ))
+ await db.commit()
+ window = _window([run_id], project_id)
+ mongo = FakeMongo({})
+ async with sessions() as db:
+ with pytest.raises(svc.ProjectExportFailed) as caught:
+ _ = [member async for member in hx.iter_documents(db, mongo, window=window, stats={})]
+ assert caught.value.params == {"error_type": "PipelineEventDeliveryPending"}
+ assert "synthetic-private-evidence" not in str(caught.value)
+ assert mongo.calls == []
+ async with sessions() as db:
+ await db.execute(update(PipelineEventOutbox).where(PipelineEventOutbox.id == selected).values(
+ status="delivered", delivered_at=now,
+ ))
+ await db.commit()
+ async with sessions() as db:
+ await hx.ensure_pipeline_events_materialized(db, window)
+ finally:
+ await engine.dispose()
+
+ asyncio.run(scenario())
+
+
# ── E-H7: the estimate (a GET: counts only) ─────────────────────────────────
def _estimate(world: dict[str, Any], db: Any, *, mongo: Any = None, store: Any = None) -> Any:
diff --git a/backend/tests/test_project_reset_documents.py b/backend/tests/test_project_reset_documents.py
index 6a01bda1e..4e6eda452 100644
--- a/backend/tests/test_project_reset_documents.py
+++ b/backend/tests/test_project_reset_documents.py
@@ -66,6 +66,9 @@ async def execute(self, stmt):
rows = self._runs
return SimpleNamespace(scalars=lambda: SimpleNamespace(all=lambda: list(rows)))
+ def get_bind(self):
+ return SimpleNamespace(dialect=SimpleNamespace(name="sqlite"))
+
async def stream_scalars(self, stmt):
self.streamed.append(stmt)
return self.stream
@@ -95,9 +98,12 @@ async def test_every_run_keyed_collection_is_deleted_in_500_id_chunks():
assert run_keyed, "the table has run-keyed collections"
for collection, attr in run_keyed:
calls = mongo.calls[collection]
- assert [len(c) for c in calls] == [500, 500, 200], collection
- assert sorted(v for c in calls for v in c) == sorted(expected[attr]), collection
- assert counts[collection] == 1200, collection
+ wanted_ids = expected[attr]
+ if collection == retention_service._PIPELINE_EVENT_LOG:
+ wanted_ids = [*wanted_ids, *expected["audit_run_strs"]]
+ assert [len(c) for c in calls] == [500, 500, 200] * (len(wanted_ids) // 1200), collection
+ assert sorted(v for c in calls for v in c) == sorted(wanted_ids), collection
+ assert counts[collection] == len(wanted_ids), collection
@pytest.mark.asyncio
@@ -156,6 +162,8 @@ async def test_the_result_has_a_key_for_every_mongo_plans_collection():
assert set(counts) == {c for c, _f, _a in retention_service._MONGO_PLANS}
for collection, _f, attr in retention_service._MONGO_PLANS:
want = 1 if attr == "purge_tc_strs" else len(expected[attr])
+ if collection == retention_service._PIPELINE_EVENT_LOG:
+ want += len(expected["audit_run_strs"])
assert counts[collection] == want, collection
assert mongo.calls[collection], f"{collection} was never visited"
diff --git a/backend/tests/test_project_reset_service.py b/backend/tests/test_project_reset_service.py
index 9509449fe..4b67cbb8c 100644
--- a/backend/tests/test_project_reset_service.py
+++ b/backend/tests/test_project_reset_service.py
@@ -297,6 +297,9 @@ def _mongo_phase_db(*, project, run_ids, journal):
])
async def execute(stmt):
+ if getattr(stmt, "is_delete", False) and stmt.table.name == "pipeline_event_outbox":
+ journal.append(("outbox", ""))
+ return MagicMock()
journal.append(("delete", "") if getattr(stmt, "is_delete", False) else ("select", ""))
return next(results)
@@ -309,6 +312,7 @@ async def stream_scalars(_stmt):
return SimpleNamespace(
execute=execute,
+ get_bind=lambda: SimpleNamespace(dialect=SimpleNamespace(name="sqlite")),
stream_scalars=stream_scalars,
add=MagicMock(),
commit=AsyncMock(side_effect=lambda: journal.append(("commit", ""))),
@@ -331,11 +335,11 @@ async def test_a_store_deletes_the_documents_first_and_records_them():
documents = result["documents"]
assert set(documents) == {c for c, _f, _a in _MONGO_PLANS}
- assert documents["ai_analysis_payloads"] == 1 and documents["pipeline_event_log"] == 0
+ assert documents["ai_analysis_payloads"] == 1 and documents["pipeline_event_log"] == 3
assert documents["run_summaries"] == 3 and documents["decision_reports"] == 3
assert db.add.call_args.args[0].changed_fields["documents"] == documents
kinds = [k for k, _ in journal]
- assert kinds.index("mongo") < kinds.index("delete") < kinds.index("commit"), (
+ assert kinds.index("outbox") < kinds.index("mongo") < kinds.index("delete") < kinds.index("commit"), (
"the Mongo phase must run while the run → document mapping still exists"
)
diff --git a/backend/tests/test_retention_purge_holds.py b/backend/tests/test_retention_purge_holds.py
index 831607d03..f3b9eb9dc 100644
--- a/backend/tests/test_retention_purge_holds.py
+++ b/backend/tests/test_retention_purge_holds.py
@@ -15,6 +15,7 @@
import uuid
from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
import pytest
from sqlalchemy.dialects import postgresql
@@ -31,6 +32,10 @@ class _CaptureDB(_FakeDB):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.captured: list[tuple[str, str, str]] = []
+ self.outbox_delete_stmts: list = []
+
+ def get_bind(self):
+ return SimpleNamespace(dialect=SimpleNamespace(name="sqlite"))
async def execute(self, stmt):
kind = type(stmt).__name__.lower()
@@ -40,6 +45,12 @@ async def execute(self, stmt):
froms = stmt.get_final_froms()
table = getattr(froms[0], "name", "") if froms else ""
self.captured.append((kind, table, str(stmt.compile(dialect=postgresql.dialect()))))
+ if kind == "delete" and table == "pipeline_event_outbox":
+ # Replay cancellation stages before Mongo, independently of the
+ # later business/source-row DELETE whose ordering we still assert.
+ self.outbox_delete_stmts.append(stmt)
+ self.events.append(("pg_outbox_cancel", table))
+ return SimpleNamespace(rowcount=0)
return await super().execute(stmt)
def where_of(self, kind: str, table: str, *, contains: str = "") -> list[str]:
@@ -128,6 +139,11 @@ async def test_the_executed_deletes_carry_the_same_clauses():
assert run_deletes and all("retention_holds" not in w for w in run_deletes), (
"the run delete is BY ID — the hold already acted on the select that produced the ids"
)
+ cancellation = db.where_of("delete", "pipeline_event_outbox")
+ assert cancellation and all("project_id" in where and "test_run_id" in where for where in cancellation)
+ assert db.events.index(("pg_outbox_cancel", "pipeline_event_outbox")) < next(
+ i for i, event in enumerate(db.events) if event[0] == "mongo_delete"
+ ), "fence queued replay before deleting Mongo evidence"
async def test_execute_locks_the_project_row_first_and_preview_takes_no_lock():
diff --git a/backend/tests/test_retention_retained_archives.py b/backend/tests/test_retention_retained_archives.py
index b241217b5..ea0e01763 100644
--- a/backend/tests/test_retention_retained_archives.py
+++ b/backend/tests/test_retention_retained_archives.py
@@ -12,6 +12,7 @@
import inspect
import uuid
+from types import SimpleNamespace
import pytest
@@ -20,7 +21,24 @@
from sqlalchemy.dialects import postgresql # noqa: E402
from app.services import retention_service as svc # noqa: E402
-from tests.test_retention_purge import NOW, PROJECT_ID, _FakeStorage, _purge_fixture # noqa: E402
+from tests.test_retention_purge import NOW, PROJECT_ID, _FakeStorage, _purge_fixture as _source_purge_fixture # noqa: E402
+
+
+def _purge_fixture(**kwargs):
+ db, mongo, storage, events = _source_purge_fixture(**kwargs)
+ db.get_bind = lambda: SimpleNamespace(dialect=SimpleNamespace(name="sqlite"))
+ db.outbox_delete_stmts = []
+ original = db.execute
+
+ async def execute(stmt):
+ if type(stmt).__name__ == "Delete" and stmt.table.name == "pipeline_event_outbox":
+ db.outbox_delete_stmts.append(stmt)
+ events.append(("pg_outbox_cancel", stmt.table.name))
+ return SimpleNamespace(rowcount=0)
+ return await original(stmt)
+
+ db.execute = execute
+ return db, mongo, storage, events
def _archives():
@@ -80,6 +98,7 @@ async def test_the_preview_counts_the_archives_and_deletes_nothing():
assert out["candidates"]["export_archives_expired"] == 2
assert storage.deleted_objects == []
assert not any(kind == "pg_delete" for kind, _ in events)
+ assert db.outbox_delete_stmts == []
async def test_execute_deletes_each_object_before_the_rows():
@@ -96,6 +115,10 @@ async def test_execute_deletes_each_object_before_the_rows():
assert "archives_deleted" not in out["counts"]["postgres"], "objects, not rows: never summed as records"
job_delete = next(s for s in db.delete_stmts if s.table.name == "deletion_jobs")
assert "NOT IN" not in str(job_delete.compile(dialect=postgresql.dialect()))
+ assert db.outbox_delete_stmts, "source run deletion also stages replay cancellation"
+ assert events.index(("pg_outbox_cancel", "pipeline_event_outbox")) < next(
+ i for i, event in enumerate(events) if event[0] == "mongo_delete"
+ ) < events.index(("pg_delete", "test_runs")), "cancel replay, delete external evidence, then delete source rows"
async def test_a_failed_object_delete_keeps_its_row_and_never_logs_the_key(monkeypatch):
diff --git a/backend/tests/test_subject_data_inventory.py b/backend/tests/test_subject_data_inventory.py
index ca7b1a57f..907186218 100644
--- a/backend/tests/test_subject_data_inventory.py
+++ b/backend/tests/test_subject_data_inventory.py
@@ -453,16 +453,17 @@ def test_7_pinned_counts():
# .decided_by_id (reference), both FKs, neither exported (177 -> 179, FKs 124 -> 126)
# Batch 5 D-53 (deliberate, 2026-11-23): + flaky_quarantine_requests.proposed_by_user_id, a reference,
# exported like approved_by_user_id (179 -> 180, FKs 126 -> 127)
- assert counts == (180, 127, 25, 8, 10, 8, 1, 1), (
+ # OBS-E05 adds one transient pipeline delivery store linked to project and run retention.
+ assert counts == (181, 127, 26, 8, 10, 8, 1, 1), (
f"(locations, postgres_fk, postgres_other, objects, mongo, redis, chroma, logs) = {counts}: a location was "
"added or moved — classify it in subject_data_inventory.py and update this pin deliberately"
)
erase = collections.Counter(location.erase for location in locations)
assert (erase["delete"], erase["pseudonymise"] + erase["reference"], erase["keep_audit"], erase["keep_record"],
- erase["no_personal_data"], erase["out_of_scope"]) == (21, 108, 24, 8, 13, 6), erase # W38: +1 ref, +1 keep_record; D-53 +1 ref
+ erase["no_personal_data"], erase["out_of_scope"]) == (21, 108, 24, 9, 13, 6), erase
assert (erase["pseudonymise"], erase["reference"]) == (11, 97), erase
exported = sum(1 for location in locations if location.export_as != "none")
- assert (exported, len(locations) - exported) == (124, 56) # W38: the two request columns are not exported; D-53 +1
+ assert (exported, len(locations) - exported) == (124, 57)
# ── (8) fail-open, and the module stays pure data ────────────────────────────
diff --git a/cli/requirements-audit-archive.txt b/cli/requirements-audit-archive.txt
new file mode 100644
index 000000000..d1f27dee0
--- /dev/null
+++ b/cli/requirements-audit-archive.txt
@@ -0,0 +1,26 @@
+# Optional operator publisher SDK only; covered by the existing cli/ updates.
+# Install the existing TestLookup CLI
+# separately for its offline verifier and cryptography dependencies.
+# These exact pins/hashes are a subset of backend/requirements-lock.txt;
+# update them together (test_audit_archive_custody.py checks parity).
+boto3==1.40.61 \
+ --hash=sha256:6b9c57b2a922b5d8c17766e29ed792586a818098efe84def27c8f582b33f898c \
+ --hash=sha256:d6c56277251adf6c2bdd25249feae625abe4966831676689ff23b4694dea5b12
+botocore==1.40.61 \
+ --hash=sha256:17ebae412692fd4824f99cde0f08d50126dc97954008e5ba2b522eb049238aa7 \
+ --hash=sha256:a2487ad69b090f9cccd64cf07c7021cd80ee9c0655ad974f87045b02f3ef52cd
+jmespath==1.1.0 \
+ --hash=sha256:472c87d80f36026ae83c6ddd0f1d05d4e510134ed462851fd5f754c8c3cbb88d \
+ --hash=sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64
+python-dateutil==2.9.0.post0 \
+ --hash=sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3 \
+ --hash=sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427
+s3transfer==0.14.0 \
+ --hash=sha256:ea3b790c7077558ed1f02a3072fb3cb992bbbd253392f4b6e9e8976941c7d456 \
+ --hash=sha256:eff12264e7c8b4985074ccce27a3b38a485bb7f7422cc8046fee9be4983e4125
+six==1.17.0 \
+ --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \
+ --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81
+urllib3==2.8.0 \
+ --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3 \
+ --hash=sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63
diff --git a/cli/testlookup_cli/audit_archive.py b/cli/testlookup_cli/audit_archive.py
new file mode 100644
index 000000000..6f78cb160
--- /dev/null
+++ b/cli/testlookup_cli/audit_archive.py
@@ -0,0 +1,341 @@
+"""Independent operator custody of authorized exports; no application config/DB.
+
+The independent signature attests captured bytes and declared scope, not source
+completeness. No network operation occurs except the explicit publish command.
+"""
+from __future__ import annotations
+
+import argparse
+import base64
+import csv
+from datetime import datetime, timezone
+import hashlib
+import io
+import json
+import os
+from pathlib import Path
+import re
+from typing import Any
+import uuid
+import zipfile
+
+from cryptography.exceptions import InvalidSignature
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
+
+from testlookup_cli.pack_verify import MAX_MANIFEST_BYTES, verify_pack_bytes
+
+FORMAT = "testlookup-audit-custody-v1"
+MAX_SOURCE_BYTES = 64 * 1024 * 1024
+MAX_METADATA_BYTES = 16 * 1024
+SOURCE_KINDS = ("audit_csv", "compliance_pack", "retention_archive")
+
+
+class CustodyError(ValueError):
+ """Safe operator error: never include source contents or credential values."""
+
+
+def _json(value: Any) -> bytes:
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False).encode()
+
+
+def _sha(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def _time(value: str) -> datetime:
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ if parsed.tzinfo is None:
+ raise ValueError
+ return parsed.astimezone(timezone.utc)
+ except (ValueError, TypeError, AttributeError):
+ raise CustodyError("timestamps must be explicit UTC/offset ISO8601 values") from None
+
+
+def _key_id(public: Ed25519PublicKey) -> str:
+ return "archive-" + _sha(public.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw))
+
+
+def _public(pem: bytes) -> Ed25519PublicKey:
+ try:
+ key = serialization.load_pem_public_key(pem)
+ except (ValueError, TypeError):
+ raise CustodyError("invalid archive public key") from None
+ if not isinstance(key, Ed25519PublicKey):
+ raise CustodyError("archive public key must be Ed25519")
+ return key
+
+
+def _statement(manifest: bytes, key_id: str) -> bytes:
+ return f"{FORMAT}\n{_sha(manifest)}\n{key_id}\n".encode()
+
+
+def _scope(scope: dict) -> dict:
+ if not isinstance(scope, dict) or set(scope) != {"kind", "project_id", "window_start", "window_end"}:
+ raise CustodyError("scope requires kind, project_id, window_start and window_end only")
+ if scope["kind"] not in {"instance", "project"}:
+ raise CustodyError("scope kind must be instance or project")
+ try:
+ project = str(uuid.UUID(scope["project_id"])) if scope["project_id"] is not None else None
+ except (ValueError, TypeError, AttributeError):
+ raise CustodyError("scope project_id must be a UUID or null") from None
+ if (scope["kind"] == "project") != (project is not None):
+ raise CustodyError("project scope requires an ID; instance scope requires null")
+ start, end = _time(scope["window_start"]), _time(scope["window_end"])
+ if start >= end:
+ raise CustodyError("scope window must be increasing")
+ return {"kind": scope["kind"], "project_id": project, "window_start": start.isoformat(), "window_end": end.isoformat()}
+
+
+def _csv_projection(source: bytes, scope: dict) -> int:
+ try:
+ rows = list(csv.reader(io.StringIO(source.decode("utf-8"), newline=""), strict=True))
+ except (ValueError, UnicodeError, csv.Error):
+ raise CustodyError("source is not an authorized audit CSV projection") from None
+ if not rows or rows[0] != ["source", "action", "actor_name", "project_id", "created_at"]:
+ raise CustodyError("audit CSV headers do not match the supported redacted export")
+ if len(rows) - 1 >= 5000:
+ raise CustodyError("audit CSV reaches the source export cap; narrow scope before archival")
+ start, end = _time(scope["window_start"]), _time(scope["window_end"])
+ for row in rows[1:]:
+ if len(row) != 5 or not row[0] or not row[1]:
+ raise CustodyError("audit CSV contains an invalid row")
+ if not start <= _time(row[4]) <= end:
+ raise CustodyError("audit CSV row falls outside the declared capture window")
+ if scope["kind"] == "project" and row[3] != scope["project_id"]:
+ raise CustodyError("audit CSV row falls outside the declared project scope")
+ return len(rows) - 1
+
+
+def seal(
+ source: bytes, *, source_kind: str, scope: dict, retention_until: str,
+ private_key: Ed25519PrivateKey, source_public_keys: dict[str, str] | None = None,
+ source_manifest_sha256: str | None = None, now: datetime | None = None,
+) -> bytes:
+ """Bounded local capture. Source authorization remains an operator duty."""
+ if not source or len(source) > MAX_SOURCE_BYTES or source_kind not in SOURCE_KINDS:
+ raise CustodyError("unsupported or oversized archive source")
+ if not isinstance(private_key, Ed25519PrivateKey):
+ raise CustodyError("independent signing key must be Ed25519")
+ captured = now or datetime.now(timezone.utc)
+ if captured.tzinfo is None:
+ raise CustodyError("capture timestamp must include its timezone")
+ captured = captured.astimezone(timezone.utc)
+ until = _time(retention_until)
+ if not 1 <= (until - captured).total_seconds() / 86400 <= 3650:
+ raise CustodyError("archive retention must be between one day and ten years")
+ capture_scope = _scope(scope)
+ if _time(capture_scope["window_end"]) > captured:
+ raise CustodyError("capture scope cannot include future events")
+ source_check: dict[str, Any] = {"authenticity": "operator_attested_projection"}
+ if source_kind == "audit_csv":
+ source_check["rows"] = _csv_projection(source, capture_scope)
+ else:
+ if not isinstance(source_manifest_sha256, str) or not re.fullmatch("[0-9a-f]{64}", source_manifest_sha256):
+ raise CustodyError("signed source requires its independently recorded manifest SHA256")
+ try:
+ with zipfile.ZipFile(io.BytesIO(source)) as archive:
+ members = archive.infolist()
+ if len(members) > 1000 or sum(m.file_size for m in members) > 256 * 1024 * 1024:
+ raise CustodyError("signed source exceeds verification bounds")
+ if archive.getinfo("manifest.json").file_size > MAX_MANIFEST_BYTES:
+ raise CustodyError("signed source manifest exceeds verification bounds")
+ source_manifest = json.loads(archive.read("manifest.json"))
+ except (zipfile.BadZipFile, ValueError, KeyError):
+ raise CustodyError("signed source is not a readable evidence archive") from None
+ for pem in (source_public_keys or {}).values():
+ if _key_id(_public(pem.encode())) == _key_id(private_key.public_key()):
+ raise CustodyError("archive custody key must differ from application signing keys")
+ checked = verify_pack_bytes(source, recorded_manifest_sha256=source_manifest_sha256, public_keys=source_public_keys or {})
+ if checked["result"] != "verified" or checked["signature"] != "valid":
+ raise CustodyError("source evidence must have a valid trusted application signature and digest")
+ if not isinstance(source_manifest, dict) or (source_kind == "compliance_pack" and "release_id" not in source_manifest) or (source_kind == "retention_archive" and source_manifest.get("scope") != "runs"):
+ raise CustodyError("signed source kind does not match the supported export class")
+ if capture_scope["kind"] == "project" and source_manifest.get("project_id") != capture_scope["project_id"]:
+ raise CustodyError("signed source project differs from declared custody scope")
+ if not _time(capture_scope["window_start"]) <= _time(source_manifest.get("generated_at")) <= _time(capture_scope["window_end"]):
+ raise CustodyError("signed source generation is outside the capture window")
+ source_check = {"authenticity": "application_signature_verified", "manifest_sha256": source_manifest_sha256, "key_id": checked["signing_key_id"]}
+ manifest = _json({
+ "format": FORMAT, "archive_id": str(uuid.uuid4()), "captured_at": captured.isoformat(),
+ "source_kind": source_kind, "source_sha256": _sha(source), "source_bytes": len(source),
+ "scope": capture_scope, "source_check": source_check, "retention_until": until.isoformat(),
+ "legal_hold": "ON", "completeness": "captured_projection_only",
+ })
+ if len(manifest) > MAX_METADATA_BYTES:
+ raise CustodyError("capture metadata exceeds bounds")
+ key_id = _key_id(private_key.public_key())
+ signature = _json({"algorithm": "ed25519", "key_id": key_id, "signature": base64.b64encode(private_key.sign(_statement(manifest, key_id))).decode()})
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_STORED) as archive:
+ archive.writestr("payload", source)
+ archive.writestr("manifest.json", manifest)
+ archive.writestr("signature.json", signature)
+ return output.getvalue()
+
+
+def verify(blob: bytes, *, public_key_pem: bytes, expected_sha256: str | None = None) -> dict:
+ """Verify captured payload/scope with an independently pinned public key."""
+ if len(blob) > MAX_SOURCE_BYTES + 2 * MAX_METADATA_BYTES + 4096:
+ raise CustodyError("custody archive exceeds bounds")
+ if expected_sha256 is not None and _sha(blob) != expected_sha256:
+ raise CustodyError("archive differs from the independently recorded object checksum")
+ try:
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ members = archive.infolist()
+ if sorted(m.filename for m in members) != ["manifest.json", "payload", "signature.json"] or any(m.compress_type != zipfile.ZIP_STORED for m in members):
+ raise CustodyError("unexpected custody archive members or compression")
+ for member in members:
+ if member.file_size > (MAX_SOURCE_BYTES if member.filename == "payload" else MAX_METADATA_BYTES):
+ raise CustodyError("custody archive member exceeds bounds")
+ source, manifest, signature = (archive.read(name) for name in ("payload", "manifest.json", "signature.json"))
+ document, signed = json.loads(manifest), json.loads(signature)
+ public = _public(public_key_pem)
+ if set(signed) != {"algorithm", "key_id", "signature"} or signed["algorithm"] != "ed25519" or signed["key_id"] != _key_id(public):
+ raise CustodyError("archive signing key is not the independently trusted key")
+ public.verify(base64.b64decode(signed["signature"], validate=True), _statement(manifest, signed["key_id"]))
+ expected = {"format", "archive_id", "captured_at", "source_kind", "source_sha256", "source_bytes", "scope", "source_check", "retention_until", "legal_hold", "completeness"}
+ if set(document) != expected or _json(document) != manifest or document["format"] != FORMAT:
+ raise CustodyError("invalid or noncanonical custody manifest")
+ uuid.UUID(document["archive_id"])
+ _scope(document["scope"])
+ if document["source_sha256"] != _sha(source) or document["source_bytes"] != len(source):
+ raise CustodyError("captured payload differs from its signed digest")
+ if document["source_kind"] not in SOURCE_KINDS or document["legal_hold"] != "ON" or document["completeness"] != "captured_projection_only":
+ raise CustodyError("unsupported custody policy")
+ captured, until = _time(document["captured_at"]), _time(document["retention_until"])
+ if not 1 <= (until - captured).total_seconds() / 86400 <= 3650 or _time(document["scope"]["window_end"]) > captured:
+ raise CustodyError("invalid signed custody retention window")
+ if document["source_kind"] == "audit_csv":
+ if document["source_check"] != {"authenticity": "operator_attested_projection", "rows": _csv_projection(source, document["scope"])}:
+ raise CustodyError("invalid signed audit projection attestation")
+ elif not isinstance(document["source_check"], dict) or set(document["source_check"]) != {"authenticity", "manifest_sha256", "key_id"} or document["source_check"]["authenticity"] != "application_signature_verified" or not re.fullmatch(r"[0-9a-f]{64}", document["source_check"]["manifest_sha256"]):
+ raise CustodyError("invalid signed source verification attestation")
+ return document
+ except CustodyError:
+ raise
+ except (ValueError, TypeError, KeyError, AttributeError, zipfile.BadZipFile, InvalidSignature, RuntimeError):
+ raise CustodyError("archive integrity verification failed") from None
+
+
+def publish(client, blob: bytes, *, public_key_pem: bytes, bucket: str, owner: str, kms_key: str, now: datetime | None = None) -> dict:
+ """Create-only locked write; injected clients enable fake-only tests."""
+ document = verify(blob, public_key_pem=public_key_pem)
+ if not re.fullmatch(r"[0-9]{12}", owner) or not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
+ raise CustodyError("invalid independent archive account/bucket")
+ if not re.fullmatch(r"arn:aws(?:-us-gov|-cn)?:kms:[a-z0-9-]+:" + owner + r":key/[a-zA-Z0-9-]+", kms_key):
+ raise CustodyError("use a full KMS key ARN in the independent archive account")
+ until = _time(document["retention_until"])
+ current = now or datetime.now(timezone.utc)
+ if until <= current:
+ raise CustodyError("archive retention has expired; obtain a reviewed new capture policy")
+ common = {"Bucket": bucket, "ExpectedBucketOwner": owner}
+ if client.get_bucket_versioning(**common).get("Status") != "Enabled":
+ raise CustodyError("archive bucket must have versioning enabled")
+ if client.get_object_lock_configuration(**common).get("ObjectLockConfiguration", {}).get("ObjectLockEnabled") != "Enabled":
+ raise CustodyError("archive bucket must have Object Lock enabled")
+ key = "audit-custody/" + document["archive_id"] + ".zip"
+ checksum = base64.b64encode(hashlib.sha256(blob).digest()).decode()
+ response = client.put_object(
+ **common, Key=key, Body=blob, ContentType="application/zip", IfNoneMatch="*",
+ ChecksumAlgorithm="SHA256", ChecksumSHA256=checksum,
+ ServerSideEncryption="aws:kms", SSEKMSKeyId=kms_key,
+ ObjectLockMode="COMPLIANCE", ObjectLockRetainUntilDate=until, ObjectLockLegalHoldStatus="ON",
+ )
+ version = response.get("VersionId")
+ if not version or version == "null" or response.get("ChecksumSHA256") != checksum or response.get("ServerSideEncryption") != "aws:kms" or response.get("SSEKMSKeyId") != kms_key:
+ raise CustodyError("publish acknowledgement is incomplete; reconcile the object before retrying")
+ object_args = {**common, "Key": key, "VersionId": version}
+ retained = client.get_object_retention(**object_args).get("Retention", {})
+ held = client.get_object_legal_hold(**object_args).get("LegalHold", {}).get("Status")
+ if retained.get("Mode") != "COMPLIANCE" or held != "ON" or retained.get("RetainUntilDate", current) < until:
+ raise CustodyError("publish protection readback failed; reconcile before any retention action")
+ return {"archive_id": document["archive_id"], "key": key, "version_id": version, "sha256": _sha(blob), "key_id": _key_id(_public(public_key_pem))}
+
+
+def _read(path: Path, limit: int) -> bytes:
+ with path.open("rb") as source:
+ data = source.read(limit + 1)
+ if len(data) > limit:
+ raise CustodyError("input file exceeds bounds")
+ return data
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ commands = parser.add_subparsers(dest="command", required=True)
+ seal_parser = commands.add_parser("seal", help="countersign an already-authorized local export")
+ seal_parser.add_argument("--input", type=Path, required=True)
+ seal_parser.add_argument("--source-kind", choices=SOURCE_KINDS, required=True)
+ seal_parser.add_argument("--scope", type=Path, required=True)
+ seal_parser.add_argument("--retention-until", required=True)
+ seal_parser.add_argument("--private-key", type=Path, required=True)
+ seal_parser.add_argument("--output", type=Path, required=True)
+ seal_parser.add_argument("--source-public-key", type=Path)
+ seal_parser.add_argument("--source-manifest-sha256")
+ for name in ("verify", "recover", "publish"):
+ command = commands.add_parser(name)
+ command.add_argument("--input", type=Path, required=True)
+ command.add_argument("--public-key", type=Path, required=True)
+ if name == "verify":
+ command.add_argument("--expected-sha256")
+ elif name == "recover":
+ command.add_argument("--expected-sha256", required=True)
+ command.add_argument("--output", type=Path, required=True)
+ else:
+ command.add_argument("--archive-profile", required=True)
+ command.add_argument("--writer-role-arn", required=True)
+ command.add_argument("--bucket", required=True)
+ command.add_argument("--owner-account", required=True)
+ command.add_argument("--kms-key-arn", required=True)
+ command.add_argument("--region", required=True)
+ args = parser.parse_args(argv)
+ try:
+ if args.command == "seal":
+ if os.name == "posix" and args.private_key.stat().st_mode & 0o077:
+ raise CustodyError("custody private key must be readable only by its operator owner")
+ private = serialization.load_pem_private_key(_read(args.private_key, MAX_METADATA_BYTES), password=None)
+ keys = {}
+ if args.source_public_key:
+ from testlookup_cli.pack_verify import load_public_key
+ key_id, _ = load_public_key(_read(args.source_public_key, MAX_METADATA_BYTES).decode())
+ keys[key_id] = args.source_public_key.read_text()
+ blob = seal(_read(args.input, MAX_SOURCE_BYTES), source_kind=args.source_kind, scope=json.loads(_read(args.scope, MAX_METADATA_BYTES)), retention_until=args.retention_until, private_key=private, source_public_keys=keys, source_manifest_sha256=args.source_manifest_sha256)
+ with os.fdopen(os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as output:
+ output.write(blob)
+ print(json.dumps({"result": "sealed", "sha256": _sha(blob)}))
+ else:
+ blob = _read(args.input, MAX_SOURCE_BYTES + 2 * MAX_METADATA_BYTES + 4096)
+ public = _read(args.public_key, MAX_METADATA_BYTES)
+ document = verify(blob, public_key_pem=public, expected_sha256=getattr(args, "expected_sha256", None))
+ if args.command == "verify":
+ print(json.dumps({"result": "verified", "archive_id": document["archive_id"], "source_kind": document["source_kind"]}))
+ elif args.command == "recover":
+ with zipfile.ZipFile(io.BytesIO(blob)) as archive:
+ source = archive.read("payload")
+ with os.fdopen(os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as output:
+ output.write(source)
+ print(json.dumps({"result": "recovered_local_export", "archive_id": document["archive_id"], "source_sha256": _sha(source)}))
+ else:
+ import boto3
+ from botocore.config import Config
+ if args.archive_profile == "default" or not re.fullmatch(r"[A-Za-z0-9_.-]{1,100}", args.archive_profile):
+ raise CustodyError("use an explicit independently provisioned archive writer profile")
+ session = boto3.Session(profile_name=args.archive_profile, region_name=args.region)
+ identity = session.client("sts", config=Config(connect_timeout=5, read_timeout=10, retries={"total_max_attempts": 1}, ignore_configured_endpoint_urls=True)).get_caller_identity()
+ role = re.fullmatch(r"arn:(aws(?:-us-gov|-cn)?):iam::([0-9]{12}):role/(?:[A-Za-z0-9_+=,.@-]+/)*([A-Za-z0-9_+=,.@-]+)", args.writer_role_arn)
+ expected = f"arn:{role[1]}:sts::{role[2]}:assumed-role/{role[3]}/" if role else ""
+ if not role or identity.get("Account") != args.owner_account or role[2] != args.owner_account or not str(identity.get("Arn", "")).startswith(expected):
+ raise CustodyError("caller is not the independently configured archive writer role")
+ client = session.client("s3", config=Config(connect_timeout=5, read_timeout=30, retries={"total_max_attempts": 1}, ignore_configured_endpoint_urls=True))
+ print(json.dumps(publish(client, blob, public_key_pem=public, bucket=args.bucket, owner=args.owner_account, kms_key=args.kms_key_arn)))
+ return 0
+ except Exception as error:
+ # Provider/key parser messages may contain endpoints or credential data.
+ print("audit custody operation refused: " + (str(error) if isinstance(error, CustodyError) else type(error).__name__), file=__import__("sys").stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/docs/maintainers/observability-delivery.md b/docs/maintainers/observability-delivery.md
index 09d49f9da..7ade8e7d7 100644
--- a/docs/maintainers/observability-delivery.md
+++ b/docs/maintainers/observability-delivery.md
@@ -171,3 +171,16 @@ This iteration builds on `be88915c`. The app keeps its normal stdout logs and Pr
| OBS-E04-S06 | The image manifest and third-party scan track every durable reference image. The optional offline bundle records exact pins and aliases for all components and lists Grafana and Loki as operator-supplied prerequisites. | Exercise image import and the full stack with outbound internet blocked. |
Disposable native runs covered queue overflow, retry exhaustion and recovery after collector restart, plus forced Loki and Jaeger restarts. Grafana returned matching trace and log IDs using the pinned datasource versions. The Kubernetes adapters were rendered locally. The Compose stack's runtime networking, actual site gateways and disconnected operation still need deployment-level evidence.
+
+## Iteration 5: durable operational and audit evidence
+
+This iteration builds on `25fcc0c9`. Pipeline event health comes from shared SQL state, and the timeline includes accepted events while MongoDB delivery is pending.
+
+| Story | Change | Remaining acceptance |
+|---|---|---|
+| OBS-E05-S01 | Migration 0263 adds a bounded project-scoped outbox. Committed stage, review, action and agent ledger changes can stage their audit intent in the source transaction. Rollback removes uncommitted intent, and the schema downgrade protects unresolved events. | Measure admission contention, throughput and full-queue behavior with the site's normal traffic and retention policy. |
+| OBS-E05-S02 | A leased Celery relay materializes each stable ID once in MongoDB. Shared health exposes safe failed references and QA leads can request a project-scoped retry. Alerts cover backlog, capacity, failed delivery and admission refusal. History exports require delivered events in the selected pipelines. | Verify receipt recovery and notification delivery in a deployed fleet under controlled failure. See [pipeline event delivery](../operations/pipeline-event-delivery.md). |
+| OBS-E05-S03 | An operator custody command seals and verifies archives with an independent key. The optional S3 publisher uses a conditional create and checks Object Lock, hold, encryption and checksum receipts. | Provision independent IAM and storage, test denied mutation and hold or deletion actions, and agree which source exports meet site evidence requirements. See [audit archive custody](../operations/audit-archive-custody.md). |
+| OBS-E05-S04 | An admin-approved identity policy expires selected routine, successful events in bounded batches. Instance holds pause cleanup and SCIM authority rows remain available for supported authorization paths. | Confirm site defaults, approvals, window and retention behavior with the identity owner. See [identity event retention](../operations/identity-event-retention.md). |
+
+Disposable PostgreSQL and MongoDB tests exercised competing producers and claims, the purge fence, and a retry following a lost receipt. The same event remained a single MongoDB document. Migration 0263 was applied and rolled back in a disposable schema. A downgrade with pending evidence was refused. A PostgreSQL identity test observed hold and purge transactions from independent sessions and verified the resulting audit receipts. Archive tests used synthetic records and provider fixtures.
diff --git a/docs/operations/audit-archive-custody.md b/docs/operations/audit-archive-custody.md
new file mode 100644
index 000000000..9ed62738b
--- /dev/null
+++ b/docs/operations/audit-archive-custody.md
@@ -0,0 +1,233 @@
+# Independent custody of audit exports
+
+The standalone operator command `python -m testlookup_cli.audit_archive`
+preserves an already-authorized local export under an independent Ed25519
+custody signature. Its optional publisher writes a new, versioned, encrypted
+Object Lock object using a separately provisioned archive-writer role. It
+does not connect to the application database, read application configuration,
+download source data, run on the application scheduler, or delete evidence.
+Provisioning and any real storage write require the site's normal operator
+authorization; none are performed by the repository tests.
+
+This is a protective custody path for **captured projections**. It is not a
+complete operational-history collector or a replacement for source audit
+controls. Keep the application writer, authorized source exporter, independent
+archive signer/writer, audit reader and retention operator distinct. Do not
+mount the custody private key or archive credentials in API/worker containers,
+reuse `APP_SECRET_KEY`, reuse the application's compliance signing key, or
+place the archive under an application-controlled MinIO root credential.
+Use an independent storage account/administrative boundary and retain its
+public-key fingerprint and publication receipts outside the application.
+
+## Existing record and retention contracts
+
+`audit_log_service.record_outcome` stages a settings audit row in the business
+transaction; a rollback removes that outcome. `record_attempt` uses a separate
+session and retains the attempt across a caller rollback. Access-change audit
+writes stage on the caller's session. This custody command changes none of
+these semantics, source table grants, or database ownership.
+
+Operational SQL/Mongo audit records, compliance evidence and custody copies
+have different lifecycles. Source retention currently removes some project
+audit classes and expired exports, respects applicable project/run/release/
+pack holds, and retains settings audit records. Existing compliance packs
+and retention-run archives already use one SHA-256 manifest and Ed25519
+signature format. That application signing key is encrypted beside the
+database under `APP_SECRET_KEY`; compromising both can forge future source
+exports. The independent countersignature anchors what the operator captured
+at a time, rather than proving an honest or complete source database.
+
+The supported inputs are:
+
+| Source kind | Input and trust contract |
+|---|---|
+| `audit_csv` | Existing ADMIN-only `/api/v1/audit-dashboard/export` CSV, with its exact five redacted projection columns. Operator attests authorization and capture scope. It has no source signature or stable event IDs. |
+| `compliance_pack` | Existing signed release pack with trusted application public key and independently recorded manifest digest. Unsigned, altered, wrong-key or out-of-scope packs are refused. |
+| `retention_archive` | Existing signed `scope="runs"` archive using the same manifest/signature verifier. Subject/project portability exports are deliberately unsupported here. |
+
+The CSV endpoint caps its merged result at **5,000 rows**, has a relative-days
+filter, and omits original event IDs and detail fields. A CSV reaching that
+cap is refused, because completeness is ambiguous. A smaller CSV still does
+not prove full history. Review project/category/window coverage before every
+capture; high-volume or stable-ID recovery requires a separate authorized
+export design. Missing source events before archival, sampling/omissions in a
+source pack and deletion of an uncatalogued archive cannot be reconstructed
+by a signature. Every custody manifest explicitly says
+`completeness="captured_projection_only"`.
+
+## Local sealing and offline verification
+
+Use an isolated operator environment with the existing TestLookup CLI. Only
+the optional publisher additionally needs the backend-compatible SDK pins:
+
+```sh
+python -m pip install --require-hashes -r cli/requirements-audit-archive.txt
+```
+
+The SDK file is a small dependency subset, not an installation of the backend.
+Keep it synchronized with the backend lock when upgrading that SDK. No new
+application setting or database migration is required.
+
+Generate or obtain a dedicated Ed25519 key using the site's secret-management
+process. Keep its private PEM readable only by the signer account; POSIX
+group/world-readable key files are refused. Windows deployments must enforce
+equivalent ACLs outside Python's permission-bit checks. Keep the public key
+and fingerprint independently pinned; a public key copied from the same
+untrusted archive is not a trust anchor. The CLI never generates production
+keys, stores them in application tables or prints key material.
+
+Prepare a small scope JSON containing exactly:
+
+```json
+{"kind":"project","project_id":"11111111-1111-4111-8111-111111111111","window_start":"2026-11-26T00:00:00+00:00","window_end":"2026-11-27T00:00:00+00:00"}
+```
+
+Use `kind="instance", project_id=null` only for an authorized instance-wide
+export. Project captures reject CSV rows or signed evidence for another
+project. For a CSV, the window covers row timestamps. For a signed pack/run
+archive, it covers the export's signed generation timestamp; it does not
+claim that all contained historical facts occurred within that window.
+Use opaque scope identifiers, not names, credentials or destination URLs.
+
+```sh
+python -m testlookup_cli.audit_archive seal --input audit.csv --source-kind audit_csv --scope scope.json --retention-until 2028-01-01T00:00:00Z --private-key custody-private.pem --output custody.zip
+python -m testlookup_cli.audit_archive verify --input custody.zip --public-key custody-public.pem --expected-sha256
+python -m testlookup_cli.audit_archive recover --input custody.zip --public-key custody-public.pem --expected-sha256 --output recovered-export
+```
+
+For signed source kinds also provide `--source-public-key` and
+`--source-manifest-sha256`, obtained and pinned through the existing evidence
+process. The application key and independent custody key must differ.
+Retain old public keys after rotation so old captures remain verifiable.
+Rotation of a private key must not replace an old public trust anchor.
+
+Sealing is bounded to 64 MiB source bytes; source evidence verification also
+bounds member count and uncompressed size. Output contains only fixed
+`payload`, `manifest.json`, and `signature.json` members, with no extraction
+or caller-controlled paths. The signature binds the payload digest, scope,
+capture time, archive UUID, provenance check and requested retention window.
+The final ZIP checksum printed at sealing binds the complete transport
+object when saved independently. Output creation is exclusive and mode 0600
+on POSIX; an existing output is never overwritten. A partial local file from
+an interrupted write must fail verification and be handled as an incomplete
+capture. Protect plaintext source/output files with the operator's encrypted
+storage and ACLs; delete temporary copies only under the applicable policy.
+
+## Independent storage and role guard
+
+[`iam-policies.example.json`](../../infra/audit-archive/iam-policies.example.json)
+contains separate example identity policies and a bucket guard. It is not
+one directly deployable policy. Replace every `__PLACEHOLDER__`, choose
+retention bounds and KMS key/region, validate rendered policies against the
+provider, and have the storage owner review them before provisioning. The
+`kms:ViaService` example targets commercial AWS; adjust its DNS suffix for
+other partitions. Use dedicated roles without broader inherited policies,
+bucket-admin rights, object ACL rights or governance-bypass permissions.
+
+| Credential/role | Intended capability |
+|---|---|
+| Application writer | Explicitly denied access to the independent archive bucket. Existing source DB permissions are unchanged. |
+| Archive writer | Conditional, encrypted new-object write; place COMPLIANCE retention and hold ON; read protection metadata; generate KMS data key. No object-body read, decrypt, deletion or hold removal. |
+| Audit reader | Retrieve a known version and its protection metadata, and decrypt with the dedicated KMS key. No write or retention mutation. |
+| Retention operator | Read protection metadata, deliberately release/restore holds, delete an eligible **version**. No source/application mutation, archive write, body read or decrypt. |
+
+Enable bucket versioning, Object Lock and the example public-access block.
+The bucket guard refuses insecure transport, application principals,
+unconditional writes, the wrong encryption key/mode and non-COMPLIANCE
+retention. Hold removal is reserved for the retention role. It denies
+unversioned `DeleteObject` operations, preventing delete markers from hiding
+locked history; maintenance uses explicit version IDs. Choose the legal
+retention period before sealing: COMPLIANCE retention cannot be shortened,
+including by the account root user. Allow at least an additional day beyond
+the configured minimum before upload so elapsed capture/transfer time does
+not cross a remaining-retention-days policy boundary.
+
+The explicit publisher command is intended for an independently provisioned
+AWS role profile, not the application's environment/default credential chain:
+
+```sh
+python -m testlookup_cli.audit_archive publish --input custody.zip --public-key custody-public.pem --archive-profile independent-archive-writer --writer-role-arn --bucket --owner-account <12-digit-archive-account> --kms-key-arn --region
+```
+
+The publisher verifies the capture first, requires the expected assumed role
+and bucket owner, ignores endpoint overrides, checks versioning/Object Lock,
+then uses one conditional `PutObject` with `If-None-Match: *`, SHA-256 checksum,
+SSE-KMS, COMPLIANCE expiry and legal hold **ON**. It verifies the acknowledged
+checksum/encryption/version and reads retention/hold metadata back for that
+specific version. It never retries with an unprotected overwrite and offers
+no hold-release/delete command. S3-compatible providers are not an assumed
+drop-in: this command intentionally uses the AWS SDK's AWS endpoints and
+must not be pointed at the application's shared MinIO.
+
+Save the receipt's key, version ID, complete-object SHA-256 and signing-key
+fingerprint in an independently governed catalog. Regularly reconcile that
+catalog against known object versions. On any interrupted/failed publish,
+treat outcome as **uncertain**: the object may already exist and be locked.
+Reconcile it through the archive owner before retrying. Do not delete it,
+shorten protection, reuse a different key to conceal the attempt or fall
+back to the application storage credentials.
+
+## Holds, authorized retention and recovery
+
+Custody hold ON is a conservative intake hold, independent of source holds.
+Application retention or an administrator retiring a source pack does not
+authorize deleting the custody copy. The custody command does not poll,
+extend, mirror or release source holds. The retention operator must obtain
+current source project/run/release/pack hold state and the applicable legal
+policy from an authorized reviewer, record approval against the exact archive
+UUID/version, and verify the provider's protection metadata before any hold
+release. Retain hold-release/deletion approvals independently from the
+application and archive writer. If that source/approval check is unavailable,
+leave the hold ON. Active legal holds remain indefinite until explicitly
+released; an expired COMPLIANCE date alone is insufficient.
+
+After the COMPLIANCE deadline, after all source/custody holds are released,
+and after the approved retention decision, a retention-only role may delete
+the exact version using the provider's supported maintenance operation.
+Re-read both protection metadata and the deletion outcome and update the
+independent catalog. Do not delete by current key without a version ID.
+This workflow requires a site drill; the repository does not automate or
+execute it.
+
+For recovery, the audit reader retrieves the receipt's exact version to
+protected local scratch, then verifies it against the independently retained
+public key and object SHA-256. The offline `recover` command requires that
+receipt checksum and writes the verified original payload to a fresh local
+file without overwriting an existing path. Preserve those source bytes when
+handing them to the existing offline compliance verifier. This demonstrates
+evidence readback, not database restore: existing retention exports explicitly
+cannot be re-imported into TestLookup. Source business data restoration
+continues to use the existing backup/restore process.
+
+Readback also depends on preserving the KMS key and public trust anchors.
+Object Lock does not supply key backup, KMS deletion controls or recovery
+from storage-account control-plane compromise; those remain independent
+storage-owner responsibilities.
+
+## Validation and acceptance still open
+
+The focused tests in
+[`test_audit_archive_custody.py`](../../backend/tests/regression/test_audit_archive_custody.py)
+exercise independent signatures, payload/scope/signature tampering, strict
+existing source verification, scope/cap refusal, exclusive CLI output,
+application-role refusal, SDK request shapes, encryption/version/hold
+readback failures and local recovered-copy verification. S3 responses are
+Botocore stubs. These tests do **not** prove AWS IAM enforcement or WORM on a
+real provider. Existing product signing/hold/retention tests remain separate
+requirements and their source behavior is unchanged.
+
+S03 acceptance remains open for real independent account/role provisioning,
+application mutation refusal against that provider, provider hold and
+COMPLIANCE expiry/deletion controls, signed receipt/catalog reconciliation,
+an authorized recovery drill, complete operational-source coverage and any
+desired source DB role separation. The source exporter currently requires
+ADMIN; dedicated read-only export authority is a separate product change.
+Do not mark operational audit history globally immutable or claim compliance
+certification from this custody path.
+
+Primary guidance: [existing source signing format](../../backend/app/services/compliance_signing.py),
+[existing offline verifier](../../cli/testlookup_cli/pack_verify.py),
+[AWS conditional-write policies](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes-enforce.html),
+[Object Lock and holds](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html),
+[Object Lock maintenance](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock-managing.html),
+and [S3 action/condition support](https://docs.aws.amazon.com/service-authorization/latest/reference/list_s3.html).
diff --git a/docs/operations/identity-event-retention.md b/docs/operations/identity-event-retention.md
new file mode 100644
index 000000000..18d51cf8a
--- /dev/null
+++ b/docs/operations/identity-event-retention.md
@@ -0,0 +1,85 @@
+# Instance identity event retention
+
+Identity events have no project owner. Their expiry uses a separate instance policy, disabled until a signed-in instance administrator approves it. Enabling the existing instance or project retention policies does not enable identity expiry. No database migration is required: the versioned policy and independent hold registry live in the `identity_event_retention_policy` application setting.
+
+Only the following records can expire:
+
+| Record class | Eligibility |
+|---|---|
+| Routine authentication | `SSO_LOGIN`, `SSO_LOGOUT`, or `MFA_VERIFY_SUCCESS`, **and** `success = true`, strictly older than the approved cutoff. |
+| SCIM authority | Every `SCIM_USER_CREATED` record stays retained. These records participate in SCIM user scope and SSO-managed MFA authorization. |
+| Protected identity | Every other type, unknown future type, and unsuccessful routine record stays retained. This includes security failures, account and federation changes, and break-glass events. |
+
+The permitted clock is 365–3650 days; the initial, disabled policy uses 2555 days, matching the existing audit-retention default. These are product bounds, not a determination of an organization's required retention period. Review security investigation, contractual and other applicable requirements before approving a clock. OWASP's [log disposal guidance](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html#disposal-of-logs) calls for retaining records for the required period and removing them when that period ends. This narrow policy does not expire protected identity records, settings audit receipts, backups, exports or copies in external logging systems; those still require their own lifecycle controls.
+
+## Approval and one manual batch
+
+The base path is `/api/v1/identity/retention`. An instance `ADMIN` may read policy and count previews. Mutations require that administrator's interactive JWT session. API keys cannot approve, disable, hold, release or purge; project-bound keys cannot access these instance endpoints at all. Keep reasons free of credentials and unnecessary personal information: they are permanent audit evidence.
+
+1. `GET /policy` reads the policy, revision and independent holds. Missing policy means disabled; reading never creates an enabled policy.
+2. `GET /preview?retention_days=365` returns aged counts by the three record classes, `observed_at`, a `preview_hash`, and exact confirmation phrases. It returns no event bodies, IP addresses or subject identifiers.
+3. Submit `POST /policy` using the chosen days and the returned observation, hash and enable phrase. For example, the body shape for a 365-day approval is:
+
+ ```json
+ {
+ "retention_days": 365,
+ "observed_at": "",
+ "preview_hash": "",
+ "confirmation": "enable routine identity retention (365 days)",
+ "reason": "Approved routine authentication retention policy"
+ }
+ ```
+
+4. Preview again after approval, because policy approval advances its revision. To execute one manual batch, submit `POST /purge` with that fresh `observed_at` and `preview_hash`, the returned purge phrase, a reason, and `batch_size` between 1 and 500:
+
+ ```json
+ {
+ "observed_at": "",
+ "preview_hash": "",
+ "confirmation": "purge routine identity events older than 365 days",
+ "reason": "Execute approved routine authentication expiry",
+ "batch_size": 500
+ }
+ ```
+
+A preview is valid for ten minutes. Changes to policy, holds or the aged class counts invalidate it. A disabled policy, any live identity hold, unreadable policy, invalid confirmation or insufficient authority refuses deletion. `batch_full = true` means this batch reached its limit; it does not establish that all eligible records have been removed. Preview again to assess a backlog. Use `POST /disable` with `{"reason":"Suspend routine authentication expiry"}` to stop future batches without releasing holds or restoring already deleted records.
+
+## Independent instance identity holds
+
+Project holds do not apply to these unscoped events. Place a separate instance identity hold with `POST /holds` and a reason. `expires_at` is optional; an omitted expiry holds indefinitely. An expiry must be in the future and no more than 3650 days away. The response includes the hold UUID and its permanent placement audit UUID. Every live identity hold blocks all routine identity expiry, including scheduled batches.
+
+Release a particular hold with `POST /holds/{hold_id}/release`:
+
+```json
+{
+ "reason": "Investigation resolved and release approved",
+ "confirmation": "release this identity retention hold"
+}
+```
+
+Releasing one hold does not release any other hold. Expired holds stop blocking at their UTC expiry. Placement, release and policy changes each advance the policy revision and write an attributable settings audit receipt. The bounded current registry supports up to 100 live holds. Expired entries may be compacted on subsequent changes; their placement and release evidence remains in `settings_audit_log`, which TestLookup does not purge. Reaching the hold limit refuses an additional hold and preserves the existing holds.
+
+All policy, hold and purge transactions lock the same policy row. An uncommitted hold serializes with a competing purge; once the hold commits, that competing purge reads the held policy and deletes nothing. A hold takes effect on commit and cannot recover a deletion that committed earlier. Do not treat merely submitting a hold request as proof it committed.
+
+## Scheduled maintenance and storage safety
+
+The existing whole-instance hourly retention task calls `identity_retention_service.run_scheduled_batch()`. It uses the existing instance `purge_window_start_utc` hour, default `02:00` UTC; midnight (`0`) is valid. It is independent of project retention enablement and never runs from an explicit project purge. Each eligible invocation attempts at most 500 routine events. It does not drain an arbitrarily large backlog in a loop. Scheduler or worker failure leaves records retained until another approved batch runs.
+
+On PostgreSQL, the batch sets transaction-local lock and statement limits of two and five seconds. It locks the policy, rechecks all holds, selects a finite candidate set with `FOR UPDATE SKIP LOCKED`, and repeats the positive-success/type/cutoff predicates in the final deletion. Its permanent purge receipt and actual deletion share a SQL transaction. Failure before commit rolls both back. A malformed setting or unsupported record-class definition fails closed rather than widening deletion eligibility. The API commits before returning a successful purge result.
+
+Inspect `settings_audit_log` under the `identity_event_retention_policy` and `identity_event_retention_purge` keys for policy revision, actor, reason, hold metadata and committed deletion counts. Scheduled purge receipts identify the service execution with `scheduled = true` and have no interactive actor; they use the previously approved policy revision. Receipts do not copy deleted event bodies, subject IDs or IP addresses. Existing direct-database permissions and backups remain operator responsibilities; these application controls do not make the database immutable.
+
+Rolling back application code requires no schema downgrade. Earlier code does not run this new expiry path. Retain the setting and audit receipts for later inspection; disabling the policy explicitly before a rollback makes the intended state clear.
+
+## Verification
+
+From `backend`, run:
+
+```powershell
+$env:PYTEST_DISABLE_PLUGIN_AUTOLOAD = '1'
+python -m pytest -q -p pytest_asyncio.plugin tests/test_identity_retention.py tests/test_subject_data_inventory.py tests/regression/test_scim_unbound_token_scope.py
+```
+
+`tests/integration/test_identity_retention_postgres.py` additionally requires an explicitly configured disposable `TESTLOOKUP_POSTGRES_TEST_DSN` with the three existing source tables and permission to create a temporary test schema. It copies table definitions with PostgreSQL `LIKE`, inserts only synthetic rows into that generated schema, proves hold/purge serialization and SCIM preservation, reads committed audit receipts from a fresh session, and removes its schema. It does not modify public rows or verify account foreign keys. Never point this test at an application database containing real data.
+
+The local native proof used PostgreSQL 16.15 with three synthetic source tables compiled from the current ORM definitions, without account foreign keys. It proves PostgreSQL row-lock behavior and bounded deletion/audit atomicity for the fixture, not migration compatibility, full account-schema behavior, backup lifecycle or a deployed scheduler. CI runs the integration test against its disposable migrated PostgreSQL database.
diff --git a/docs/operations/pipeline-event-delivery.md b/docs/operations/pipeline-event-delivery.md
new file mode 100644
index 000000000..d90bd34ac
--- /dev/null
+++ b/docs/operations/pipeline-event-delivery.md
@@ -0,0 +1,161 @@
+# Recover shared pipeline-event delivery
+
+Pipeline event delivery uses a shared SQL intent and an append-only Mongo
+materialization. This is delivery of audit/timeline evidence, not a request
+to run the pipeline's tools, model calls or business mutations again.
+The source's SQL acceptance/transaction contract determines whether an event
+is accepted; an event refused before that boundary is not recoverable from
+this outbox. A source retry needs its original stable event ID to refer to
+the same logical event. A new legitimate decision/attempt uses a new ID.
+
+## Acceptance and rollout
+
+Migration 0263 adds the scoped SQL outbox. Stage and pipeline completion
+events and AgentRun ledger mirrors share the source transaction. A rollback
+removes the still-uncommitted intent. Observations such as a decision or cache
+hit use a separate short transaction after resolving a durable project/run
+scope. The timeline can read accepted evidence immediately and deduplicates it
+with materialized history by event ID.
+
+A history archive requires delivered events for its selected canonical
+pipelines. The export fails before publishing if those events are
+pending, leased or failed. Once delivery is confirmed, request the export
+again.
+
+Admission reserves space in a transaction and caps the installation at 10,000
+retained intents. It sanitizes event detail and replaces oversized or invalid
+detail with a compact omission marker. Each serialized envelope is limited
+to 16 KiB. Refusals from contention, capacity, invalid scope or PostgreSQL
+unavailability produce a bounded metric reason and an operational event ID.
+Business processing can continue when telemetry admission is refused.
+
+Apply the migration before enabling workers with the new relay. For an
+application rollback, leave the table in place while accepted events drain.
+Migration downgrade refuses to remove a table with pending, leased or failed
+intents. Back up the accepted queue before a maintenance operation that
+replaces the database.
+
+## Observe the shared state
+
+`GET /api/v1/agents/event-log/health` requires QA lead privileges and scopes
+results to the caller's accessible projects. Its optional `project_id` limits
+the view further; an inaccessible project is refused. An instance admin may
+read the installation view. The response reads SQL, so independent API
+processes observe worker-written backlog rather than local process globals.
+It returns counts, oldest age, status counts and up to 20 compact failed-event
+references; it never returns event detail or connection/provider error text.
+
+The legacy `write_failure_count` is now the number of currently unresolved
+intents with a recorded delivery error. It is not a monotonic lifetime total.
+`dead_letter_count` means terminal failed receipts, `dead_letter_limit` is the
+installation admission capacity, and `recent_dead_letters` contains safe
+references rather than payloads. Delivered receipt pruning can reduce these
+counts. A new, briefly pending intent is normal; unresolved failures or a
+backlog older than five minutes make health degraded.
+
+The collector `pipeline_events` publishes these absolute shared gauges:
+
+| Signal | Meaning |
+|---|---|
+| `testlookup_pipeline_event_outbox_entries{status}` | Retained pending/sending/delivered/failed rows |
+| `testlookup_pipeline_event_outbox_oldest_age_seconds{status}` | Oldest unresolved intent age; delivered is zero |
+| `testlookup_pipeline_event_outbox_retry_overdue_seconds{status}` | Due retry or expired lease age |
+| `testlookup_pipeline_event_outbox_capacity` | Installation row limit, including retained acknowledgements |
+
+Read them only with successful, fresh collection. SQL failure or malformed
+lease state must not appear as measured healthy zero. API replicas observe
+the same table: fleet queries take a fresh maximum rather than adding those
+copies. There are no project, event, task or payload labels.
+
+`TestLookupPipelineEventDeliveryFailed` identifies terminal unresolved
+receipts; `TestLookupPipelineEventBacklogStale` identifies a relay falling
+behind; `TestLookupPipelineEventCapacityHigh` warns before admission fills.
+`TestLookupPipelineEventAdmissionRefused` uses the separate source counter
+`testlookup_pipeline_event_admission_failures_total{reason}`. Admission
+refusal is a distinct evidence gap and cannot be repaired by replaying
+accepted rows. Counters still depend on their producing process being
+scraped; SQL-backed backlog is the durable shared delivery state.
+
+## Automatic materialization and replacement
+
+The scheduled relay claims one row at a time, with a two-minute lease and at
+most eight automatic attempts. One invocation starts at most 50 deliveries
+within a 20-second loop budget; an in-progress database/driver operation has
+its own timeout and can extend the last iteration. Worker/task hard limits
+remain an independent deployment bound. No lease is taken for an entire
+unprocessed batch.
+
+Before writing Mongo, the worker takes the project's shared history lock,
+then re-reads/locks the still-owned intent. Purge takes the corresponding
+exclusive project lock and removes eligible SQL intents before Mongo
+deletion. This ordering prevents an ordinary concurrent replay from
+restoring deliberately purged history. A stale/deleted/replaced claim does
+not write Mongo. Driver cancellation, process termination and ambiguous
+remote completion still require the selected purge/reconciliation policy;
+this is not a distributed transaction or a claim of atomic cross-store erase.
+
+Mongo uses the stable event ID as `_id`. Inserts require journalled,
+acknowledged writes under a two-second client-side operation deadline. The
+default minimum is `w=1`, `j=true`; a site's stronger majority/custom write
+concern is preserved, and duplicate confirmation reads the primary even if
+the URI otherwise prefers secondaries. A duplicate key is confirmed by comparing the immutable logical
+payload and project/run identity, rather than accepted blindly or overwritten.
+BSON timestamp precision is normalized. If a source explicitly reuses its
+event ID after the SQL receipt expired, only its new intake timestamp is
+excluded from identity comparison; the original Mongo timestamp is preserved.
+A different payload under that ID becomes a terminal identity conflict.
+
+Transient errors back off from two seconds to a five-minute maximum. Failure
+codes are a small fixed vocabulary; exceptions, URLs and payloads are not
+returned in health or used as metric labels. Exhausted attempts and invalid
+identity/payload retain a `failed` intent. A failed SQL receipt can coexist
+with already accepted Mongo evidence after an ambiguous write; it indicates
+unresolved delivery accounting, not proof that the logical event was lost.
+
+Delivered SQL receipts normally remain for one hour. At 90% admission
+pressure, a bounded prune may remove newer **acknowledged** receipts to
+restore room promptly after a Mongo outage. It never removes pending,
+leased or failed evidence. Mongo retention, backup and erasure remain their
+own policy; deleting a receipt does not delete the materialized event.
+
+## Explicit repair
+
+Restore the default-queue consumer, relay schedule, SQL/Mongo access and
+storage first. Inspect the selected project's failed event references. For
+one eligible terminal failure, call:
+
+```http
+POST /api/v1/agents/event-log/{event_id}/replay?project_id={project_id}
+```
+
+The route requires QA lead privileges and project access, resets only that
+failed intent to pending and records a project-activity outcome with the
+actor and stable reference. It sends no notification and performs no tool or
+pipeline action. The caller's transaction commits the requeue and project
+activity through the existing activity writer; that derived ledger is not a
+tamper-proof compliance history. Delivery occurs through the scheduled
+relay. Repeating a request after it is pending/sending/delivered returns 409;
+an event outside the selected project is not returned. Payload replacement,
+arbitrary task names and bulk unscoped replay are unsupported.
+
+After recovery, verify the row is delivered (or aged out after
+acknowledgement), the timeline contains one logical `event_id`, and fresh
+backlog/error gauges recover. For an identity conflict, investigate the
+source contract; repeatedly requeueing does not authorize overwriting an
+immutable event. Never delete unresolved rows to quiet a capacity alert.
+
+## Verification scope
+
+`backend/tests/regression/test_pipeline_event_delivery.py` exercises actual
+isolated SQL transactions and a synthetic Mongo sink: outage/recovery,
+accepted-before-cancellation replacement, duplicate identity validation,
+deleted/stale leases, purge contention, retry ceilings, pressure pruning,
+timestamp-preserving source retry, scoped independent-session health, role/
+project refusals and persisted project activity. Prometheus semantic fixtures
+in `infra/monitoring/tests/pipeline-event-delivery.yml` check alert/recovery,
+stale replicas and replicated capacity counts. SQLite does not prove
+PostgreSQL advisory/row locking or real Mongo journal/write acknowledgement;
+those require the separate disposable-store and independent-process witness.
+
+Driver deadline semantics follow the official
+[Motor/PyMongo client-side operation timeout guidance](https://www.mongodb.com/docs/languages/python/pymongo-driver/current/connect/connection-options/csot/).
diff --git a/docs/reference/api-index.md b/docs/reference/api-index.md
index 6e7188b84..2d9548de1 100644
--- a/docs/reference/api-index.md
+++ b/docs/reference/api-index.md
@@ -30,6 +30,7 @@ This indexes every OpenAPI HTTP operation. Exact parameters, body schemas and de
| GET | `/api/v1/agents/catalog/{agent_id}` | Get Agent Catalog Entry | [Agents](api/agent-operations.md) |
| POST | `/api/v1/agents/defect-command` | Defect Command | [Agents](api/agent-operations.md) |
| GET | `/api/v1/agents/event-log/health` | Get Pipeline Event Log Health | [Agents](api/agent-operations.md) |
+| POST | `/api/v1/agents/event-log/{event_id}/replay` | Replay Pipeline Event Delivery | [Agents](api/agent-operations.md) |
| GET | `/api/v1/agents/invocations/{invocation_id}` | Get Invocation | [Agent Invocations](api/agent-invocations.md) |
| POST | `/api/v1/agents/invocations/{invocation_id}/cancel` | Cancel Invocation | [Agent Invocations](api/agent-invocations.md) |
| GET | `/api/v1/agents/invocations/{invocation_id}/events` | Stream Invocation Events | [Agent Invocations](api/agent-invocations.md) |
@@ -204,6 +205,13 @@ This indexes every OpenAPI HTTP operation. Exact parameters, body schemas and de
| GET | `/api/v1/github/app/install-url` | Github App Install Url | [GitHub App](api/github-app.md) |
| POST | `/api/v1/github/app/setup-callback` | Github App Setup Callback | [GitHub App](api/github-app.md) |
| GET | `/api/v1/identity/events` | List Identity Events | [Identity & Audit](api/identity-audit.md) |
+| POST | `/api/v1/identity/retention/disable` | Disable Identity Retention Policy | [Identity & Audit](api/identity-audit.md) |
+| POST | `/api/v1/identity/retention/holds` | Place Identity Retention Hold | [Identity & Audit](api/identity-audit.md) |
+| POST | `/api/v1/identity/retention/holds/{hold_id}/release` | Release Identity Retention Hold | [Identity & Audit](api/identity-audit.md) |
+| GET | `/api/v1/identity/retention/policy` | Read Identity Retention Policy | [Identity & Audit](api/identity-audit.md) |
+| POST | `/api/v1/identity/retention/policy` | Approve Identity Retention Policy | [Identity & Audit](api/identity-audit.md) |
+| GET | `/api/v1/identity/retention/preview` | Preview Identity Retention | [Identity & Audit](api/identity-audit.md) |
+| POST | `/api/v1/identity/retention/purge` | Purge Identity Retention Batch | [Identity & Audit](api/identity-audit.md) |
| GET | `/api/v1/identity/sync-status` | Get Identity Sync Status | [Identity & Audit](api/identity-audit.md) |
| POST | `/api/v1/ingest` | Ingest test results (JSON batch) | [Ingest](api/ingest.md) |
| POST | `/api/v1/ingest/file` | Upload test result file (JUnit/TestNG XML, Allure/Cypress/Playwright JSON) | [Ingest](api/ingest.md) |
@@ -753,4 +761,4 @@ This indexes every OpenAPI HTTP operation. Exact parameters, body schemas and de
| POST | `/webhooks/minio` | Minio Webhook | [Webhooks](api/webhooks.md) |
| POST | `/ws/events/{run_id}` | Ingest Live Event | [Live Reporting](api/live-reporting.md) |
-Total: **744 HTTP operations**, **630 paths**, **92 domain pages**.
+Total: **752 HTTP operations**, **637 paths**, **92 domain pages**.
diff --git a/docs/reference/api/agent-actions.md b/docs/reference/api/agent-actions.md
index f5ec5ad85..9d7fa3816 100644
--- a/docs/reference/api/agent-actions.md
+++ b/docs/reference/api/agent-actions.md
@@ -190,7 +190,7 @@ Transition Agent Action
Approve, reject or undo one agent action. Nothing is written before every check passes.
-Source: [backend/app/routers/agent_actions.py:229](../../../backend/app/routers/agent_actions.py#L229).
+Source: [backend/app/routers/agent_actions.py:230](../../../backend/app/routers/agent_actions.py#L230).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_project_access.._check`, `require_role.._check`.
diff --git a/docs/reference/api/agent-operations.md b/docs/reference/api/agent-operations.md
index f8bea5604..264928174 100644
--- a/docs/reference/api/agent-operations.md
+++ b/docs/reference/api/agent-operations.md
@@ -24,7 +24,7 @@ the endpoint leaked every tenant's live run (slug, build number, counts,
timing) to any authenticated user — the ``/active-runs/{run_id}`` sibling
already gates on ``require_run_access`` but the list did not.
-Source: [backend/app/routers/agents.py:1460](../../../backend/app/routers/agents.py#L1460).
+Source: [backend/app/routers/agents.py:1489](../../../backend/app/routers/agents.py#L1489).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`.
@@ -101,7 +101,7 @@ Get Live Run State
Get the current state for a single live test run.
-Source: [backend/app/routers/agents.py:1516](../../../backend/app/routers/agents.py#L1516).
+Source: [backend/app/routers/agents.py:1545](../../../backend/app/routers/agents.py#L1545).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_run_access.._check`.
@@ -361,7 +361,7 @@ Run the Defect Commander on a failure cluster.
Scores the cluster on 7 criticality dimensions, generates a Jira-ready
defect description, and optionally creates a Jira ticket.
-Source: [backend/app/routers/agents.py:1719](../../../backend/app/routers/agents.py#L1719).
+Source: [backend/app/routers/agents.py:1748](../../../backend/app/routers/agents.py#L1748).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
@@ -481,16 +481,16 @@ Contract limit: at least one response has an unstructured schema. Read the linke
Get Pipeline Event Log Health
-Return write-health details for the pipeline audit event log.
+Read shared delivery health within the caller's accessible projects.
-Source: [backend/app/routers/agents.py:1427](../../../backend/app/routers/agents.py#L1427).
+Source: [backend/app/routers/agents.py:1428](../../../backend/app/routers/agents.py#L1428).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
Declared Python handler arguments (includes exact role/guard options):
```python
-_: Any=Depends(require_role(UserRole.QA_LEAD))
+project_id: uuid.UUID | None=Query(None), db: AsyncSession=Depends(get_db), current_user: Any=Depends(require_role(UserRole.QA_LEAD))
```
### Declared wire contract
@@ -501,6 +501,23 @@ References such as `#/components/schemas/...` resolve in [schemas](../schemas.md
{
"operationId": "get_pipeline_event_log_health_api_v1_agents_event_log_health_get",
"parameters": [
+ {
+ "in": "query",
+ "name": "project_id",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id"
+ }
+ },
{
"in": "header",
"name": "X-API-Key",
@@ -548,6 +565,111 @@ References such as `#/components/schemas/...` resolve in [schemas](../schemas.md
}
```
+## POST `/api/v1/agents/event-log/{event_id}/replay`
+
+Replay Pipeline Event Delivery
+
+Requeue one failed delivery; never re-execute pipeline business work.
+
+Source: [backend/app/routers/agents.py:1442](../../../backend/app/routers/agents.py#L1442).
+
+Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
+
+Declared Python handler arguments (includes exact role/guard options):
+
+```python
+event_id: uuid.UUID, project_id: uuid.UUID=Query(...), db: AsyncSession=Depends(get_db), current_user: Any=Depends(require_role(UserRole.QA_LEAD))
+```
+
+Direct handler error branches (dependency/service errors can add others):
+
+```python
+HTTPException(404, detail='Event delivery not found.')
+HTTPException(409, detail='Event history is busy; retry later.')
+HTTPException(409, detail='Only failed event deliveries may be requeued.')
+```
+
+### Declared wire contract
+
+References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json).
+
+```json
+{
+ "operationId": "replay_pipeline_event_delivery_api_v1_agents_event_log__event_id__replay_post",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "event_id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "Event Id",
+ "type": "string"
+ }
+ },
+ {
+ "in": "query",
+ "name": "project_id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "Project Id",
+ "type": "string"
+ }
+ },
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "responses": {
+ "202": {
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ]
+}
+```
+
+Handler return expressions (source excerpts, not an inferred wire schema):
+
+```python
+result
+```
+
+Contract limit: at least one response has an unstructured schema. Read the linked handler/serializer for emitted fields; the empty schema is not a promise of an empty JSON object.
+
## GET `/api/v1/agents/pipelines`
List Pipelines
@@ -1266,7 +1388,7 @@ This additive adapter keeps the established timeline API stable while
exposing selected/skipped capabilities, parent-child task identity,
allocated budgets, actual usage and terminal stop reasons in one model.
-Source: [backend/app/routers/agents.py:1319](../../../backend/app/routers/agents.py#L1319).
+Source: [backend/app/routers/agents.py:1320](../../../backend/app/routers/agents.py#L1320).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`.
@@ -1450,7 +1572,7 @@ Get Pipeline Replay
Return a deterministic replay document for audit reconstruction.
-Source: [backend/app/routers/agents.py:1442](../../../backend/app/routers/agents.py#L1442).
+Source: [backend/app/routers/agents.py:1471](../../../backend/app/routers/agents.py#L1471).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`.
@@ -1826,7 +1948,7 @@ Run the Regression Watchman on an existing test run.
Returns classification of each failure cluster as:
- new_regression | known_flaky_recurrence | environmental_anomaly
-Source: [backend/app/routers/agents.py:1771](../../../backend/app/routers/agents.py#L1771).
+Source: [backend/app/routers/agents.py:1800](../../../backend/app/routers/agents.py#L1800).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
@@ -1926,7 +2048,7 @@ WF-1: Return the latest pipeline execution status for a run and workflow type.
Enables the frontend to know when deep/offline analysis ran, whether it
completed fully, partially, or failed, without scanning the full timeline.
-Source: [backend/app/routers/agents.py:1529](../../../backend/app/routers/agents.py#L1529).
+Source: [backend/app/routers/agents.py:1558](../../../backend/app/routers/agents.py#L1558).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_run_access.._check`.
@@ -2034,7 +2156,7 @@ Carries the human-review envelope (E8.3): ``requires_human_review``,
``review`` and the ``X-TestLookup-AI-Generated`` / ``X-TestLookup-Review-State``
headers. A deterministic fallback is ``not_applicable``: no AI wrote it.
-Source: [backend/app/routers/agents.py:1606](../../../backend/app/routers/agents.py#L1606).
+Source: [backend/app/routers/agents.py:1635](../../../backend/app/routers/agents.py#L1635).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_run_access.._check`.
diff --git a/docs/reference/api/identity-audit.md b/docs/reference/api/identity-audit.md
index 4d02e87a7..2e414cfa9 100644
--- a/docs/reference/api/identity-audit.md
+++ b/docs/reference/api/identity-audit.md
@@ -10,7 +10,7 @@ List Identity Events
List identity events with filtering (ADMIN only).
-Source: [backend/app/routers/identity_events.py:32](../../../backend/app/routers/identity_events.py#L32).
+Source: [backend/app/routers/identity_events.py:165](../../../backend/app/routers/identity_events.py#L165).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
@@ -176,13 +176,591 @@ References such as `#/components/schemas/...` resolve in [schemas](../schemas.md
}
```
+## POST `/api/v1/identity/retention/disable`
+
+Disable Identity Retention Policy
+
+Disable future identity expiry without releasing any hold.
+
+Source: [backend/app/routers/identity_events.py:96](../../../backend/app/routers/identity_events.py#L96).
+
+Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
+
+Declared Python handler arguments (includes exact role/guard options):
+
+```python
+payload: IdentityRetentionReason, current_user: User=Depends(require_role(UserRole.ADMIN)), db: AsyncSession=Depends(get_db)
+```
+
+### Declared wire contract
+
+References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json).
+
+```json
+{
+ "operationId": "disable_identity_retention_policy_api_v1_identity_retention_disable_post",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionReason"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ]
+}
+```
+
+## POST `/api/v1/identity/retention/holds`
+
+Place Identity Retention Hold
+
+Place an independent instance identity hold; all live holds block expiry.
+
+Source: [backend/app/routers/identity_events.py:111](../../../backend/app/routers/identity_events.py#L111).
+
+Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
+
+Declared Python handler arguments (includes exact role/guard options):
+
+```python
+payload: IdentityRetentionHoldCreate, current_user: User=Depends(require_role(UserRole.ADMIN)), db: AsyncSession=Depends(get_db)
+```
+
+### Declared wire contract
+
+References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json).
+
+```json
+{
+ "operationId": "place_identity_retention_hold_api_v1_identity_retention_holds_post",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionHoldCreate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionHold"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ]
+}
+```
+
+## POST `/api/v1/identity/retention/holds/{hold_id}/release`
+
+Release Identity Retention Hold
+
+Release only this hold with a reason; overlapping holds remain absolute.
+
+Source: [backend/app/routers/identity_events.py:128](../../../backend/app/routers/identity_events.py#L128).
+
+Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
+
+Declared Python handler arguments (includes exact role/guard options):
+
+```python
+hold_id: uuid.UUID, payload: IdentityRetentionHoldRelease, current_user: User=Depends(require_role(UserRole.ADMIN)), db: AsyncSession=Depends(get_db)
+```
+
+### Declared wire contract
+
+References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json).
+
+```json
+{
+ "operationId": "release_identity_retention_hold_api_v1_identity_retention_holds__hold_id__release_post",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "hold_id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "Hold Id",
+ "type": "string"
+ }
+ },
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionHoldRelease"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ]
+}
+```
+
+## GET `/api/v1/identity/retention/policy`
+
+Read Identity Retention Policy
+
+Read the separate, default-off instance identity policy and its holds.
+
+Source: [backend/app/routers/identity_events.py:48](../../../backend/app/routers/identity_events.py#L48).
+
+Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
+
+Declared Python handler arguments (includes exact role/guard options):
+
+```python
+current_user: User=Depends(require_role(UserRole.ADMIN)), db: AsyncSession=Depends(get_db)
+```
+
+### Declared wire contract
+
+References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json).
+
+```json
+{
+ "operationId": "read_identity_retention_policy_api_v1_identity_retention_policy_get",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ]
+}
+```
+
+## POST `/api/v1/identity/retention/policy`
+
+Approve Identity Retention Policy
+
+Approve routine-event expiry with a fresh preview and typed confirmation.
+
+Requires an interactive instance administrator. Existing project retention
+enablement never authorizes this separate policy.
+
+Source: [backend/app/routers/identity_events.py:75](../../../backend/app/routers/identity_events.py#L75).
+
+Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
+
+Declared Python handler arguments (includes exact role/guard options):
+
+```python
+payload: IdentityRetentionApproval, current_user: User=Depends(require_role(UserRole.ADMIN)), db: AsyncSession=Depends(get_db)
+```
+
+### Declared wire contract
+
+References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json).
+
+```json
+{
+ "operationId": "approve_identity_retention_policy_api_v1_identity_retention_policy_post",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionApproval"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ]
+}
+```
+
+## GET `/api/v1/identity/retention/preview`
+
+Preview Identity Retention
+
+Count aged record classes without reading event content or deleting rows.
+
+Source: [backend/app/routers/identity_events.py:60](../../../backend/app/routers/identity_events.py#L60).
+
+Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
+
+Declared Python handler arguments (includes exact role/guard options):
+
+```python
+retention_days: Optional[int]=Query(default=None, ge=365, le=3650), current_user: User=Depends(require_role(UserRole.ADMIN)), db: AsyncSession=Depends(get_db)
+```
+
+### Declared wire contract
+
+References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json).
+
+```json
+{
+ "operationId": "preview_identity_retention_api_v1_identity_retention_preview_get",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "retention_days",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "maximum": 3650,
+ "minimum": 365,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Retention Days"
+ }
+ },
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionPreview"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ]
+}
+```
+
+## POST `/api/v1/identity/retention/purge`
+
+Purge Identity Retention Batch
+
+Execute one approved, unheld batch of at most 500 routine events.
+
+Source: [backend/app/routers/identity_events.py:146](../../../backend/app/routers/identity_events.py#L146).
+
+Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
+
+Declared Python handler arguments (includes exact role/guard options):
+
+```python
+payload: IdentityRetentionPurge, current_user: User=Depends(require_role(UserRole.ADMIN)), db: AsyncSession=Depends(get_db)
+```
+
+### Declared wire contract
+
+References such as `#/components/schemas/...` resolve in [schemas](../schemas.md) or [OpenAPI JSON](../openapi.json).
+
+```json
+{
+ "operationId": "purge_identity_retention_batch_api_v1_identity_retention_purge_post",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionPurge"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionPurgeResult"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ]
+}
+```
+
## GET `/api/v1/identity/sync-status`
Get Identity Sync Status
Get aggregated identity sync health (ADMIN only).
-Source: [backend/app/routers/identity_events.py:73](../../../backend/app/routers/identity_events.py#L73).
+Source: [backend/app/routers/identity_events.py:206](../../../backend/app/routers/identity_events.py#L206).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_role.._check`.
diff --git a/docs/reference/api/reviews.md b/docs/reference/api/reviews.md
index d769a6835..5d7a84610 100644
--- a/docs/reference/api/reviews.md
+++ b/docs/reference/api/reviews.md
@@ -13,7 +13,7 @@ The project's review queue, newest first. ``?state=pending_review`` for the open
The body stays a bare list cut at ``limit``; the number of reviews
matching the filter is the ``X-Total-Count`` header.
-Source: [backend/app/routers/reviews.py:258](../../../backend/app/routers/reviews.py#L258).
+Source: [backend/app/routers/reviews.py:260](../../../backend/app/routers/reviews.py#L260).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_project_access.._check`.
@@ -132,7 +132,7 @@ Get Review
-Source: [backend/app/routers/reviews.py:291](../../../backend/app/routers/reviews.py#L291).
+Source: [backend/app/routers/reviews.py:293](../../../backend/app/routers/reviews.py#L293).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_review_access.._check`.
@@ -219,7 +219,7 @@ Accept Review
Accept an AI report. Its run becomes ``passed``.
-Source: [backend/app/routers/reviews.py:305](../../../backend/app/routers/reviews.py#L305).
+Source: [backend/app/routers/reviews.py:307](../../../backend/app/routers/reviews.py#L307).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_review_access.._check`, `require_role.._check`.
@@ -317,7 +317,7 @@ Reject Review
Reject an AI report with a reason code. Its run becomes ``failed``.
-Source: [backend/app/routers/reviews.py:332](../../../backend/app/routers/reviews.py#L332).
+Source: [backend/app/routers/reviews.py:334](../../../backend/app/routers/reviews.py#L334).
Dependency chain: `OAuth2PasswordBearer`, `get_current_active_user`, `get_current_user_or_api_key`, `get_db`, `require_review_access.._check`, `require_role.._check`.
diff --git a/docs/reference/data-dictionary.md b/docs/reference/data-dictionary.md
index 7a97f66e2..ee4736e40 100644
--- a/docs/reference/data-dictionary.md
+++ b/docs/reference/data-dictionary.md
@@ -86,6 +86,7 @@ Current SQLAlchemy metadata, without a database connection. All columns, server/
| [notification_transition_policies](#notification_transition_policies) | NotificationTransitionPolicy | 8 |
| [password_reset_tokens](#password_reset_tokens) | PasswordResetToken | 8 |
| [perf_baselines](#perf_baselines) | PerfBaseline | 14 |
+| [pipeline_event_outbox](#pipeline_event_outbox) | PipelineEventOutbox | 15 |
| [product_usage_events](#product_usage_events) | ProductUsageEvent | 6 |
| [project_activity_events](#project_activity_events) | ProjectActivityEvent | 24 |
| [project_data_jobs](#project_data_jobs) | ProjectDataJob | 27 |
@@ -173,7 +174,7 @@ Current SQLAlchemy metadata, without a database connection. All columns, server/
## access_audit_logs
-[backend/app/models/postgres.py:4810](../../backend/app/models/postgres.py#L4810)
+[backend/app/models/postgres.py:4844](../../backend/app/models/postgres.py#L4844)
Append-only audit trail for user role and project membership changes.
@@ -218,7 +219,7 @@ Constraints and indexes:
## agent_action_dispatch_outbox
-[backend/app/models/postgres.py:6616](../../backend/app/models/postgres.py#L6616)
+[backend/app/models/postgres.py:6654](../../backend/app/models/postgres.py#L6654)
Durable delivery intent for approved actions; never contains prompts.
@@ -250,7 +251,7 @@ Constraints and indexes:
## agent_action_ledger
-[backend/app/models/postgres.py:6157](../../backend/app/models/postgres.py#L6157)
+[backend/app/models/postgres.py:6195](../../backend/app/models/postgres.py#L6195)
Append-only proposal/execution ledger for agent-originated actions.
@@ -337,7 +338,7 @@ Constraints and indexes:
## agent_configs
-[backend/app/models/postgres.py:6403](../../backend/app/models/postgres.py#L6403)
+[backend/app/models/postgres.py:6441](../../backend/app/models/postgres.py#L6441)
A project's configuration of one agent (architecture E4.1, section 4.2).
@@ -438,7 +439,7 @@ Constraints and indexes:
## agent_invocations
-[backend/app/models/postgres.py:6323](../../backend/app/models/postgres.py#L6323)
+[backend/app/models/postgres.py:6361](../../backend/app/models/postgres.py#L6361)
One call of a single agent through the public API (architecture E1.2).
@@ -483,7 +484,7 @@ Constraints and indexes:
## agent_memory_entries
-[backend/app/models/postgres.py:6102](../../backend/app/models/postgres.py#L6102)
+[backend/app/models/postgres.py:6140](../../backend/app/models/postgres.py#L6140)
Unified memory linking a run/snapshot to related entities (clusters, defects,
release decisions, ownership) for project-scoped historical recall.
@@ -620,7 +621,7 @@ Constraints and indexes:
## agent_stage_results
-[backend/app/models/postgres.py:2662](../../backend/app/models/postgres.py#L2662)
+[backend/app/models/postgres.py:2696](../../backend/app/models/postgres.py#L2696)
Per-stage result for an AgentPipelineRun.
@@ -789,7 +790,7 @@ Constraints and indexes:
## ai_eval_baselines
-[backend/app/models/postgres.py:5819](../../backend/app/models/postgres.py#L5819)
+[backend/app/models/postgres.py:5857](../../backend/app/models/postgres.py#L5857)
Baseline metrics per agent/task_type for comparison gating.
@@ -827,7 +828,7 @@ Constraints and indexes:
## ai_eval_datasets
-[backend/app/models/postgres.py:5693](../../backend/app/models/postgres.py#L5693)
+[backend/app/models/postgres.py:5731](../../backend/app/models/postgres.py#L5731)
Labeled evaluation dataset for measuring AI quality over time.
@@ -852,7 +853,7 @@ Constraints and indexes:
## ai_eval_gate_runs
-[backend/app/models/postgres.py:5856](../../backend/app/models/postgres.py#L5856)
+[backend/app/models/postgres.py:5894](../../backend/app/models/postgres.py#L5894)
Historical record of an agent-stack release gate decision.
@@ -888,7 +889,7 @@ Constraints and indexes:
## ai_eval_item_outputs
-[backend/app/models/postgres.py:5780](../../backend/app/models/postgres.py#L5780)
+[backend/app/models/postgres.py:5818](../../backend/app/models/postgres.py#L5818)
One replayed item of a candidate evaluation run (W16 AGT-09, 0231).
@@ -923,7 +924,7 @@ Constraints and indexes:
## ai_eval_reviewer_quality
-[backend/app/models/postgres.py:5923](../../backend/app/models/postgres.py#L5923)
+[backend/app/models/postgres.py:5961](../../backend/app/models/postgres.py#L5961)
A G3 reviewer-quality observation batch or scheduled 30-day rollup.
@@ -968,7 +969,7 @@ Constraints and indexes:
## ai_eval_runs
-[backend/app/models/postgres.py:5713](../../backend/app/models/postgres.py#L5713)
+[backend/app/models/postgres.py:5751](../../backend/app/models/postgres.py#L5751)
Record of running an evaluation dataset against a model version.
@@ -1019,7 +1020,7 @@ Constraints and indexes:
## ai_eval_shadow_pairs
-[backend/app/models/postgres.py:5893](../../backend/app/models/postgres.py#L5893)
+[backend/app/models/postgres.py:5931](../../backend/app/models/postgres.py#L5931)
A bounded live tier pair awaiting a human or golden-input label.
@@ -1054,7 +1055,7 @@ Constraints and indexes:
## ai_feedback
-[backend/app/models/postgres.py:2793](../../backend/app/models/postgres.py#L2793)
+[backend/app/models/postgres.py:2827](../../backend/app/models/postgres.py#L2827)
Human feedback on AI triage results — the primary training signal.
@@ -1095,7 +1096,7 @@ Constraints and indexes:
## api_keys
-[backend/app/models/postgres.py:4538](../../backend/app/models/postgres.py#L4538)
+[backend/app/models/postgres.py:4572](../../backend/app/models/postgres.py#L4572)
Scoped personal access token (PAT) for CI/CD and API access.
@@ -1131,7 +1132,7 @@ Constraints and indexes:
## app_settings
-[backend/app/models/postgres.py:4465](../../backend/app/models/postgres.py#L4465)
+[backend/app/models/postgres.py:4499](../../backend/app/models/postgres.py#L4499)
Key-value store for application-level configuration (e.g. SMTP settings).
@@ -1218,7 +1219,7 @@ attachments: Mapped[list['TestAttachment']] = relationship('TestAttachment', bac
## chat_messages
-[backend/app/models/postgres.py:2769](../../backend/app/models/postgres.py#L2769)
+[backend/app/models/postgres.py:2803](../../backend/app/models/postgres.py#L2803)
A single message in a ChatSession.
@@ -1245,7 +1246,7 @@ session: Mapped['ChatSession'] = relationship('ChatSession', back_populates='mes
## chat_sessions
-[backend/app/models/postgres.py:2747](../../backend/app/models/postgres.py#L2747)
+[backend/app/models/postgres.py:2781](../../backend/app/models/postgres.py#L2781)
A conversation session between a user and the Conversation Agent.
@@ -1278,7 +1279,7 @@ messages: Mapped[list['ChatMessage']] = relationship('ChatMessage', back_populat
## classification_hints
-[backend/app/models/postgres.py:5354](../../backend/app/models/postgres.py#L5354)
+[backend/app/models/postgres.py:5392](../../backend/app/models/postgres.py#L5392)
A QA lead's rule: " contains -> " for one project.
@@ -1312,7 +1313,7 @@ Constraints and indexes:
## compliance_packs
-[backend/app/models/postgres.py:7463](../../backend/app/models/postgres.py#L7463)
+[backend/app/models/postgres.py:7501](../../backend/app/models/postgres.py#L7501)
Generated compliance export pack (ZIP) for a release decision.
@@ -1346,7 +1347,7 @@ Constraints and indexes:
## compliance_signing_keys
-[backend/app/models/postgres.py:7540](../../backend/app/models/postgres.py#L7540)
+[backend/app/models/postgres.py:7578](../../backend/app/models/postgres.py#L7578)
The deployment's Ed25519 compliance-pack signing keys (migration 0225, W11 REL-11, D14).
@@ -1412,7 +1413,7 @@ Constraints and indexes:
## decision_report_eval_cycles
-[backend/app/models/postgres.py:5985](../../backend/app/models/postgres.py#L5985)
+[backend/app/models/postgres.py:6023](../../backend/app/models/postgres.py#L6023)
Durable evidence for a report-level evaluation corpus cycle.
@@ -1464,7 +1465,7 @@ Constraints and indexes:
## decision_report_feedback
-[backend/app/models/postgres.py:2833](../../backend/app/models/postgres.py#L2833)
+[backend/app/models/postgres.py:2867](../../backend/app/models/postgres.py#L2867)
Structured human feedback bound to one immutable DecisionReport version.
@@ -1504,7 +1505,7 @@ Constraints and indexes:
## decision_report_supersession_requests
-[backend/app/models/postgres.py:6047](../../backend/app/models/postgres.py#L6047)
+[backend/app/models/postgres.py:6085](../../backend/app/models/postgres.py#L6085)
Durable, idempotent request to publish a child-enriched report version.
@@ -1543,7 +1544,7 @@ Constraints and indexes:
## deep_findings
-[backend/app/models/postgres.py:2975](../../backend/app/models/postgres.py#L2975)
+[backend/app/models/postgres.py:3009](../../backend/app/models/postgres.py#L3009)
Deep investigation result per failure cluster.
@@ -1682,7 +1683,7 @@ approver: Mapped[Optional['User']] = relationship('User', foreign_keys=[approved
## deletion_jobs
-[backend/app/models/postgres.py:7842](../../backend/app/models/postgres.py#L7842)
+[backend/app/models/postgres.py:7880](../../backend/app/models/postgres.py#L7880)
One record of a deletion actually happening (migration 0147, S2b).
@@ -1761,7 +1762,7 @@ Constraints and indexes:
## digest_subscriptions
-[backend/app/models/postgres.py:5640](../../backend/app/models/postgres.py#L5640)
+[backend/app/models/postgres.py:5678](../../backend/app/models/postgres.py#L5678)
User subscription to a scheduled or event-driven report delivery.
@@ -1805,7 +1806,7 @@ Constraints and indexes:
## dismissed_duplicate_pairs
-[backend/app/models/postgres.py:3431](../../backend/app/models/postgres.py#L3431)
+[backend/app/models/postgres.py:3465](../../backend/app/models/postgres.py#L3465)
Suppression record so a dismissed duplicate pair stays dismissed (Phase 4).
@@ -1836,7 +1837,7 @@ Constraints and indexes:
## drop_folder_builds
-[backend/app/models/postgres.py:8665](../../backend/app/models/postgres.py#L8665)
+[backend/app/models/postgres.py:8703](../../backend/app/models/postgres.py#L8703)
One build folder ``/runs//`` seen by the drop-folder watcher (W34 STRAT-13; migration 0254).
@@ -1873,7 +1874,7 @@ Constraints and indexes:
## duplicate_test_case_candidates
-[backend/app/models/postgres.py:3388](../../backend/app/models/postgres.py#L3388)
+[backend/app/models/postgres.py:3422](../../backend/app/models/postgres.py#L3422)
One detected near-duplicate PAIR of authored ManagedTestCases (Phase 4).
@@ -1917,7 +1918,7 @@ Constraints and indexes:
## evidence_artifacts
-[backend/app/models/postgres.py:4591](../../backend/app/models/postgres.py#L4591)
+[backend/app/models/postgres.py:4625](../../backend/app/models/postgres.py#L4625)
Tenant-bound immutable evidence captured from an executed tool.
@@ -1965,7 +1966,7 @@ Constraints and indexes:
## failure_attribution
-[backend/app/models/postgres.py:6870](../../backend/app/models/postgres.py#L6870)
+[backend/app/models/postgres.py:6908](../../backend/app/models/postgres.py#L6908)
@@ -1994,7 +1995,7 @@ Constraints and indexes:
## failure_clusters
-[backend/app/models/postgres.py:2899](../../backend/app/models/postgres.py#L2899)
+[backend/app/models/postgres.py:2933](../../backend/app/models/postgres.py#L2933)
Semantic cluster of failures grouped by root-cause similarity.
@@ -2022,7 +2023,7 @@ Constraints and indexes:
## feature_flags
-[backend/app/models/postgres.py:6678](../../backend/app/models/postgres.py#L6678)
+[backend/app/models/postgres.py:6716](../../backend/app/models/postgres.py#L6716)
Named capability toggle gated by project, role, and rollout percent.
@@ -2047,7 +2048,7 @@ Constraints and indexes:
## federated_identities
-[backend/app/models/postgres.py:5087](../../backend/app/models/postgres.py#L5087)
+[backend/app/models/postgres.py:5121](../../backend/app/models/postgres.py#L5121)
Links an external IdP subject to a local User.
@@ -2130,7 +2131,7 @@ Constraints and indexes:
## flaky_classifier_calibration
-[backend/app/models/postgres.py:7044](../../backend/app/models/postgres.py#L7044)
+[backend/app/models/postgres.py:7082](../../backend/app/models/postgres.py#L7082)
@@ -2155,7 +2156,7 @@ Constraints and indexes:
## flaky_coach_results
-[backend/app/models/postgres.py:4919](../../backend/app/models/postgres.py#L4919)
+[backend/app/models/postgres.py:4953](../../backend/app/models/postgres.py#L4953)
Project-level flaky test coaching results with quarantine recommendations.
@@ -2191,7 +2192,7 @@ Constraints and indexes:
## flaky_detection_state
-[backend/app/models/postgres.py:7080](../../backend/app/models/postgres.py#L7080)
+[backend/app/models/postgres.py:7118](../../backend/app/models/postgres.py#L7118)
@@ -2221,7 +2222,7 @@ Constraints and indexes:
## flaky_quarantine_requests
-[backend/app/models/postgres.py:7583](../../backend/app/models/postgres.py#L7583)
+[backend/app/models/postgres.py:7621](../../backend/app/models/postgres.py#L7621)
Workflow record for proposing, approving, and enforcing quarantine
of a flaky test.
@@ -2285,7 +2286,7 @@ Constraints and indexes:
## flaky_score
-[backend/app/models/postgres.py:7010](../../backend/app/models/postgres.py#L7010)
+[backend/app/models/postgres.py:7048](../../backend/app/models/postgres.py#L7048)
@@ -2312,7 +2313,7 @@ Constraints and indexes:
## generation_batches
-[backend/app/models/postgres.py:3696](../../backend/app/models/postgres.py#L3696)
+[backend/app/models/postgres.py:3730](../../backend/app/models/postgres.py#L3730)
One row per AI test-case generation request (grounded or raw).
@@ -2346,7 +2347,7 @@ Constraints and indexes:
## generation_case_sources
-[backend/app/models/postgres.py:3727](../../backend/app/models/postgres.py#L3727)
+[backend/app/models/postgres.py:3761](../../backend/app/models/postgres.py#L3761)
Maps a generated ManagedTestCase to the KnowledgeChunks cited for it.
@@ -2379,7 +2380,7 @@ Constraints and indexes:
## github_integrations
-[backend/app/models/postgres.py:7315](../../backend/app/models/postgres.py#L7315)
+[backend/app/models/postgres.py:7353](../../backend/app/models/postgres.py#L7353)
Per-project GitHub Checks API integration config.
@@ -2412,7 +2413,7 @@ Constraints and indexes:
## gitlab_integrations
-[backend/app/models/postgres.py:7380](../../backend/app/models/postgres.py#L7380)
+[backend/app/models/postgres.py:7418](../../backend/app/models/postgres.py#L7418)
Per-project GitLab integration config (PMF Epic 3 US-3.1).
@@ -2449,7 +2450,7 @@ Constraints and indexes:
## identity_events
-[backend/app/models/postgres.py:5159](../../backend/app/models/postgres.py#L5159)
+[backend/app/models/postgres.py:5193](../../backend/app/models/postgres.py#L5193)
Append-only audit trail for SSO, SCIM, and identity lifecycle events.
@@ -2460,9 +2461,13 @@ by the ``backend.audit-write-discipline`` quality gate
UPDATEs an audit table or DELETEs from one outside
``services/retention_service.py``.
-Not currently covered by any retention clock: the US-11.4 purge does not
-touch this table (it has no project scope), so rows accumulate until an
-operator prunes them out-of-band.
+The project retention clocks do not apply: this table has no project
+scope. A separate default-off instance policy can expire only successful
+SSO_LOGIN, SSO_LOGOUT and MFA_VERIFY_SUCCESS records after explicit admin
+approval, subject to independent instance identity holds. SCIM_USER_CREATED
+rows remain live authorization evidence; all other types, failed routine
+records and unknown future types stay retained. Policy/hold/purge receipts
+remain in the never-purged settings audit trail.
Beyond that, durability is the **operator's** responsibility: direct
Postgres credentials can still rewrite or drop rows. Real immutability
@@ -2521,7 +2526,7 @@ Constraints and indexes:
## instance_retention_policy
-[backend/app/models/postgres.py:8425](../../backend/app/models/postgres.py#L8425)
+[backend/app/models/postgres.py:8463](../../backend/app/models/postgres.py#L8463)
The instance-wide retention defaults (W22b ACT-06, migration 0242).
@@ -2562,7 +2567,7 @@ Constraints and indexes:
## integration_health_checks
-[backend/app/models/postgres.py:4737](../../backend/app/models/postgres.py#L4737)
+[backend/app/models/postgres.py:4771](../../backend/app/models/postgres.py#L4771)
Integration health status: the latest snapshot per (provider, scope).
@@ -2587,7 +2592,7 @@ Constraints and indexes:
## integration_probe_results
-[backend/app/models/postgres.py:4756](../../backend/app/models/postgres.py#L4756)
+[backend/app/models/postgres.py:4790](../../backend/app/models/postgres.py#L4790)
Historical record of each integration health probe (OPS-01).
@@ -2611,7 +2616,7 @@ Constraints and indexes:
## knowledge_chunks
-[backend/app/models/postgres.py:3666](../../backend/app/models/postgres.py#L3666)
+[backend/app/models/postgres.py:3700](../../backend/app/models/postgres.py#L3700)
PostgreSQL metadata for each chunk stored in ChromaDB knowledge_chunks collection.
@@ -2642,7 +2647,7 @@ Constraints and indexes:
## knowledge_sources
-[backend/app/models/postgres.py:3605](../../backend/app/models/postgres.py#L3605)
+[backend/app/models/postgres.py:3639](../../backend/app/models/postgres.py#L3639)
Registry of external knowledge sources attached to a project for RAG-grounded test generation.
@@ -2677,7 +2682,7 @@ Constraints and indexes:
## knowledge_sync_events
-[backend/app/models/postgres.py:3640](../../backend/app/models/postgres.py#L3640)
+[backend/app/models/postgres.py:3674](../../backend/app/models/postgres.py#L3674)
Audit log for every sync attempt on a KnowledgeSource.
@@ -2781,7 +2786,7 @@ Constraints and indexes:
## live_sessions
-[backend/app/models/postgres.py:3774](../../backend/app/models/postgres.py#L3774)
+[backend/app/models/postgres.py:3808](../../backend/app/models/postgres.py#L3808)
Tracks an active live test execution session from a client machine.
@@ -2828,7 +2833,7 @@ Constraints and indexes:
## managed_test_cases
-[backend/app/models/postgres.py:3106](../../backend/app/models/postgres.py#L3106)
+[backend/app/models/postgres.py:3140](../../backend/app/models/postgres.py#L3140)
Manually authored or AI-generated test case with full lifecycle management.
@@ -2943,7 +2948,7 @@ Constraints and indexes:
## model_versions
-[backend/app/models/postgres.py:2862](../../backend/app/models/postgres.py#L2862)
+[backend/app/models/postgres.py:2896](../../backend/app/models/postgres.py#L2896)
Registry of fine-tuned model versions per training track.
@@ -2976,7 +2981,7 @@ Constraints and indexes:
## nightly_job_observations
-[backend/app/models/postgres.py:6664](../../backend/app/models/postgres.py#L6664)
+[backend/app/models/postgres.py:6702](../../backend/app/models/postgres.py#L6702)
Bounded operational state shared by the scheduled workers and API.
@@ -2996,7 +3001,7 @@ Constraints and indexes:
## notification_logs
-[backend/app/models/postgres.py:3042](../../backend/app/models/postgres.py#L3042)
+[backend/app/models/postgres.py:3076](../../backend/app/models/postgres.py#L3076)
Audit trail for every dispatched notification.
@@ -3134,7 +3139,7 @@ Constraints and indexes:
## password_reset_tokens
-[backend/app/models/postgres.py:4876](../../backend/app/models/postgres.py#L4876)
+[backend/app/models/postgres.py:4910](../../backend/app/models/postgres.py#L4910)
A single-use password-reset link (W17b ADM-02, migration 0233). Hash only.
@@ -3162,7 +3167,7 @@ Constraints and indexes:
## perf_baselines
-[backend/app/models/postgres.py:7130](../../backend/app/models/postgres.py#L7130)
+[backend/app/models/postgres.py:7168](../../backend/app/models/postgres.py#L7168)
Per-test running duration statistics.
@@ -3190,9 +3195,51 @@ Constraints and indexes:
- `UniqueConstraint` `uq_perf_baseline_fingerprint`: `project_id, test_fingerprint`
- Index `ix_perf_baseline_project` (unique=False): `perf_baselines.project_id`; options `{}`
+## pipeline_event_outbox
+
+[backend/app/models/postgres.py:2662](../../backend/app/models/postgres.py#L2662)
+
+Project-scoped event intent awaiting idempotent Mongo materialization.
+
+| Column | SQL type | Nullable | PK | Default | Foreign key / on delete |
+|---|---|---|---|---|---|
+| `id` | `UUID` | False | True | `—` | |
+| `project_id` | `UUID` | False | False | `—` | projects.id / CASCADE |
+| `pipeline_id` | `UUID` | True | False | `—` | agent_pipeline_runs.id / CASCADE |
+| `test_run_id` | `UUID` | True | False | `—` | test_runs.id / CASCADE |
+| `test_case_id` | `UUID` | True | False | `—` | test_cases.id / CASCADE |
+| `pipeline_run_id` | `VARCHAR(128)` | False | False | `—` | |
+| `payload` | `JSON` | False | False | `—` | |
+| `created_at` | `DATETIME` | False | False | `server=now()` | |
+| `status` | `VARCHAR(12)` | False | False | `server=pending; application=pending` | |
+| `attempts` | `INTEGER` | False | False | `server=0; application=0` | |
+| `next_attempt_at` | `DATETIME` | True | False | `—` | |
+| `lease_token` | `UUID` | True | False | `—` | |
+| `lease_expires_at` | `DATETIME` | True | False | `—` | |
+| `last_error_code` | `VARCHAR(48)` | True | False | `—` | |
+| `delivered_at` | `DATETIME` | True | False | `—` | |
+
+Constraints and indexes:
+
+- `CheckConstraint` `ck_pipeline_event_outbox_attempts`: `attempts >= 0`
+- `CheckConstraint` `ck_pipeline_event_outbox_status`: `status IN ('pending', 'sending', 'delivered', 'failed')`
+- `ForeignKeyConstraint` `unnamed`: `pipeline_id`
+- `ForeignKeyConstraint` `unnamed`: `project_id`
+- `ForeignKeyConstraint` `unnamed`: `test_case_id`
+- `ForeignKeyConstraint` `unnamed`: `test_run_id`
+- `PrimaryKeyConstraint` `unnamed`: `id`
+- Index `ix_pipeline_event_outbox_delivered` (unique=False): `pipeline_event_outbox.status, pipeline_event_outbox.delivered_at`; options `{}`
+- Index `ix_pipeline_event_outbox_lease` (unique=False): `pipeline_event_outbox.status, pipeline_event_outbox.lease_expires_at`; options `{}`
+- Index `ix_pipeline_event_outbox_pipeline` (unique=False): `pipeline_event_outbox.pipeline_id`; options `{}`
+- Index `ix_pipeline_event_outbox_project` (unique=False): `pipeline_event_outbox.project_id, pipeline_event_outbox.status`; options `{}`
+- Index `ix_pipeline_event_outbox_run` (unique=False): `pipeline_event_outbox.test_run_id`; options `{}`
+- Index `ix_pipeline_event_outbox_schedule` (unique=False): `pipeline_event_outbox.status, pipeline_event_outbox.next_attempt_at, pipeline_event_outbox.created_at`; options `{}`
+- Index `ix_pipeline_event_outbox_test_case` (unique=False): `pipeline_event_outbox.test_case_id`; options `{}`
+- Index `ix_pipeline_event_outbox_timeline` (unique=False): `pipeline_event_outbox.pipeline_run_id, pipeline_event_outbox.created_at`; options `{}`
+
## product_usage_events
-[backend/app/models/postgres.py:4793](../../backend/app/models/postgres.py#L4793)
+[backend/app/models/postgres.py:4827](../../backend/app/models/postgres.py#L4827)
Tracks product adoption events for analytics.
@@ -3216,7 +3263,7 @@ Constraints and indexes:
## project_activity_events
-[backend/app/models/postgres.py:8516](../../backend/app/models/postgres.py#L8516)
+[backend/app/models/postgres.py:8554](../../backend/app/models/postgres.py#L8554)
Append-only, project-scoped product feed of everything that happens.
@@ -3294,7 +3341,7 @@ Constraints and indexes:
## project_data_jobs
-[backend/app/models/postgres.py:7967](../../backend/app/models/postgres.py#L7967)
+[backend/app/models/postgres.py:8005](../../backend/app/models/postgres.py#L8005)
One project export or import (W24 ADM-05 phase 1: settings + catalog; migration 0247).
@@ -3405,7 +3452,7 @@ Constraints and indexes:
## project_llm_quota
-[backend/app/models/postgres.py:6747](../../backend/app/models/postgres.py#L6747)
+[backend/app/models/postgres.py:6785](../../backend/app/models/postgres.py#L6785)
Per-project LLM spend config used by the usage-based billing gate.
@@ -3433,7 +3480,7 @@ Constraints and indexes:
## project_llm_usage
-[backend/app/models/postgres.py:8476](../../backend/app/models/postgres.py#L8476)
+[backend/app/models/postgres.py:8514](../../backend/app/models/postgres.py#L8514)
Running per-period LLM cost meter for a project.
@@ -3464,7 +3511,7 @@ Constraints and indexes:
## project_members
-[backend/app/models/postgres.py:4522](../../backend/app/models/postgres.py#L4522)
+[backend/app/models/postgres.py:4556](../../backend/app/models/postgres.py#L4556)
Per-project role assignment for a user.
@@ -3486,7 +3533,7 @@ Constraints and indexes:
## project_retention_policies
-[backend/app/models/postgres.py:8324](../../backend/app/models/postgres.py#L8324)
+[backend/app/models/postgres.py:8362](../../backend/app/models/postgres.py#L8362)
Per-project data retention policy (PMF US-11.4, migration 0113).
@@ -3565,7 +3612,7 @@ Constraints and indexes:
## project_workflow_defaults
-[backend/app/models/postgres.py:6530](../../backend/app/models/postgres.py#L6530)
+[backend/app/models/postgres.py:6568](../../backend/app/models/postgres.py#L6568)
A project's default workflow for one base (W14 AGT-08, migration 0230).
@@ -3648,7 +3695,7 @@ canonical_test_cases: Mapped[list['CanonicalTestCase']] = relationship('Canonica
## quarantine_lifecycle_policies
-[backend/app/models/postgres.py:7719](../../backend/app/models/postgres.py#L7719)
+[backend/app/models/postgres.py:7757](../../backend/app/models/postgres.py#L7757)
Per-project quarantine lifecycle configuration (PMF US-5.4/5.5/5.6).
@@ -3680,7 +3727,7 @@ Constraints and indexes:
## refresh_token_records
-[backend/app/models/postgres.py:5280](../../backend/app/models/postgres.py#L5280)
+[backend/app/models/postgres.py:5318](../../backend/app/models/postgres.py#L5318)
Server-side record of issued refresh tokens for rotation and replay detection.
@@ -3710,7 +3757,7 @@ Constraints and indexes:
## release_attribution_rules
-[backend/app/models/postgres.py:4301](../../backend/app/models/postgres.py#L4301)
+[backend/app/models/postgres.py:4335](../../backend/app/models/postgres.py#L4335)
Per-project rule mapping run metadata to a release (migration 0154).
@@ -3742,7 +3789,7 @@ Constraints and indexes:
## release_decisions
-[backend/app/models/postgres.py:3008](../../backend/app/models/postgres.py#L3008)
+[backend/app/models/postgres.py:3042](../../backend/app/models/postgres.py#L3042)
Release gate decision produced by ReleaseRiskAgent.
@@ -3782,7 +3829,7 @@ Constraints and indexes:
## release_gate_decisions
-[backend/app/models/postgres.py:5462](../../backend/app/models/postgres.py#L5462)
+[backend/app/models/postgres.py:5500](../../backend/app/models/postgres.py#L5500)
A go/no-go verdict for a RELEASE, not for a run (migration 0156).
@@ -3855,7 +3902,7 @@ Constraints and indexes:
## release_gate_policies
-[backend/app/models/postgres.py:5201](../../backend/app/models/postgres.py#L5201)
+[backend/app/models/postgres.py:5239](../../backend/app/models/postgres.py#L5239)
Versioned release gate policy — per-project or system-wide default.
@@ -3889,7 +3936,7 @@ Constraints and indexes:
## release_outcomes
-[backend/app/models/postgres.py:4251](../../backend/app/models/postgres.py#L4251)
+[backend/app/models/postgres.py:4285](../../backend/app/models/postgres.py#L4285)
A human-marked production incident or rollback for a release (E9.9).
@@ -3916,7 +3963,7 @@ Constraints and indexes:
## release_phases
-[backend/app/models/postgres.py:4347](../../backend/app/models/postgres.py#L4347)
+[backend/app/models/postgres.py:4381](../../backend/app/models/postgres.py#L4381)
A phase / milestone within a Release lifecycle.
@@ -3952,7 +3999,7 @@ release: Mapped['Release'] = relationship('Release', back_populates='phases')
## release_test_run_links
-[backend/app/models/postgres.py:4382](../../backend/app/models/postgres.py#L4382)
+[backend/app/models/postgres.py:4416](../../backend/app/models/postgres.py#L4416)
Links a test run to a release for metrics aggregation.
@@ -3988,7 +4035,7 @@ release: Mapped['Release'] = relationship('Release', back_populates='test_run_li
## releases
-[backend/app/models/postgres.py:4052](../../backend/app/models/postgres.py#L4052)
+[backend/app/models/postgres.py:4086](../../backend/app/models/postgres.py#L4086)
A software release tracked through the QA lifecycle.
@@ -4045,7 +4092,7 @@ test_run_links: Mapped[list['ReleaseTestRunLink']] = relationship('ReleaseTestRu
## report_exports
-[backend/app/models/postgres.py:8273](../../backend/app/models/postgres.py#L8273)
+[backend/app/models/postgres.py:8311](../../backend/app/models/postgres.py#L8311)
VIZ-607: one background export of a report (migration 0194).
@@ -4086,7 +4133,7 @@ Constraints and indexes:
## report_share_links
-[backend/app/models/postgres.py:5252](../../backend/app/models/postgres.py#L5252)
+[backend/app/models/postgres.py:5290](../../backend/app/models/postgres.py#L5290)
Time-limited share token for run intelligence reports.
@@ -4122,7 +4169,7 @@ Constraints and indexes:
## requirement_coverage
-[backend/app/models/postgres.py:3755](../../backend/app/models/postgres.py#L3755)
+[backend/app/models/postgres.py:3789](../../backend/app/models/postgres.py#L3789)
Tracks which requirements are covered/uncovered by a generation batch.
@@ -4148,7 +4195,7 @@ Constraints and indexes:
## retention_holds
-[backend/app/models/postgres.py:8187](../../backend/app/models/postgres.py#L8187)
+[backend/app/models/postgres.py:8225](../../backend/app/models/postgres.py#L8225)
A retention hold on a project, a release, a run or a compliance pack (W22a ACT-05, migration 0239).
@@ -4204,7 +4251,7 @@ Constraints and indexes:
## review_requests
-[backend/app/models/postgres.py:6225](../../backend/app/models/postgres.py#L6225)
+[backend/app/models/postgres.py:6263](../../backend/app/models/postgres.py#L6263)
One human review for one AI report-producing run (architecture section 8.1).
@@ -4264,7 +4311,7 @@ Constraints and indexes:
## run_baselines
-[backend/app/models/postgres.py:4659](../../backend/app/models/postgres.py#L4659)
+[backend/app/models/postgres.py:4693](../../backend/app/models/postgres.py#L4693)
Records which baseline was selected for a run and why.
@@ -4382,7 +4429,7 @@ Constraints and indexes:
## run_commit_ranges
-[backend/app/models/postgres.py:2924](../../backend/app/models/postgres.py#L2924)
+[backend/app/models/postgres.py:2958](../../backend/app/models/postgres.py#L2958)
Commit range associated with a run — Epic 8 US-8.1 (migration 0110).
@@ -4429,7 +4476,7 @@ Constraints and indexes:
## run_comparison_reports
-[backend/app/models/postgres.py:4703](../../backend/app/models/postgres.py#L4703)
+[backend/app/models/postgres.py:4737](../../backend/app/models/postgres.py#L4737)
Cached AI report for a run or suite comparison.
@@ -4465,7 +4512,7 @@ Constraints and indexes:
## run_diffs
-[backend/app/models/postgres.py:4684](../../backend/app/models/postgres.py#L4684)
+[backend/app/models/postgres.py:4718](../../backend/app/models/postgres.py#L4718)
Persisted diff payload for a run — avoids recomputation.
@@ -4532,7 +4579,7 @@ Constraints and indexes:
## run_intelligence_snapshots
-[backend/app/models/postgres.py:4572](../../backend/app/models/postgres.py#L4572)
+[backend/app/models/postgres.py:4606](../../backend/app/models/postgres.py#L4606)
Cached run intelligence payload for fast page loads.
@@ -4558,7 +4605,7 @@ Constraints and indexes:
## run_tombstones
-[backend/app/models/postgres.py:7801](../../backend/app/models/postgres.py#L7801)
+[backend/app/models/postgres.py:7839](../../backend/app/models/postgres.py#L7839)
A run that was deliberately deleted, and must not come back (0148, S2c).
@@ -4597,7 +4644,7 @@ Constraints and indexes:
## saved_views
-[backend/app/models/postgres.py:5405](../../backend/app/models/postgres.py#L5405)
+[backend/app/models/postgres.py:5443](../../backend/app/models/postgres.py#L5443)
Persisted filter/scope configuration — personal or shared.
@@ -4630,7 +4677,7 @@ Constraints and indexes:
## scim_group_mappings
-[backend/app/models/postgres.py:5128](../../backend/app/models/postgres.py#L5128)
+[backend/app/models/postgres.py:5162](../../backend/app/models/postgres.py#L5162)
W20 ADM-09: an administrator's grant — members of the group get ``project_role`` on the project.
@@ -4650,7 +4697,7 @@ Constraints and indexes:
## scim_group_members
-[backend/app/models/postgres.py:5120](../../backend/app/models/postgres.py#L5120)
+[backend/app/models/postgres.py:5154](../../backend/app/models/postgres.py#L5154)
@@ -4668,7 +4715,7 @@ Constraints and indexes:
## scim_groups
-[backend/app/models/postgres.py:5107](../../backend/app/models/postgres.py#L5107)
+[backend/app/models/postgres.py:5141](../../backend/app/models/postgres.py#L5141)
W20 ADM-09: a group an IdP pushes over SCIM ``/Groups``.
@@ -4688,7 +4735,7 @@ Constraints and indexes:
## scim_tokens
-[backend/app/models/postgres.py:5140](../../backend/app/models/postgres.py#L5140)
+[backend/app/models/postgres.py:5174](../../backend/app/models/postgres.py#L5174)
Bearer token for SCIM 2.0 provisioning endpoints.
@@ -4715,7 +4762,7 @@ Constraints and indexes:
## search_query_events
-[backend/app/models/postgres.py:5432](../../backend/app/models/postgres.py#L5432)
+[backend/app/models/postgres.py:5470](../../backend/app/models/postgres.py#L5470)
One search a person ran on the /search page (migration 0227, W12 SRCH-05). NO query text: q_hash is an
HMAC-SHA256 keyed from APP_SECRET_KEY over the normalised query (search_usage_service.query_hash), so a
@@ -4749,7 +4796,7 @@ Constraints and indexes:
## secret_refs
-[backend/app/models/postgres.py:4445](../../backend/app/models/postgres.py#L4445)
+[backend/app/models/postgres.py:4479](../../backend/app/models/postgres.py#L4479)
Stores sensitive values (API keys, tokens, passwords) separately from settings.
@@ -4813,7 +4860,7 @@ Constraints and indexes:
## service_ownership_rules
-[backend/app/models/postgres.py:5308](../../backend/app/models/postgres.py#L5308)
+[backend/app/models/postgres.py:5346](../../backend/app/models/postgres.py#L5346)
Maps a matcher pattern (suite, component, package, path) to a team/service owner.
@@ -4842,7 +4889,7 @@ Constraints and indexes:
## settings_audit_log
-[backend/app/models/postgres.py:4482](../../backend/app/models/postgres.py#L4482)
+[backend/app/models/postgres.py:4516](../../backend/app/models/postgres.py#L4516)
Append-only audit trail for settings and secret changes.
@@ -4884,7 +4931,7 @@ Constraints and indexes:
## sso_configurations
-[backend/app/models/postgres.py:5024](../../backend/app/models/postgres.py#L5024)
+[backend/app/models/postgres.py:5058](../../backend/app/models/postgres.py#L5058)
Tenant/system-level SSO configuration for a SAML identity provider.
@@ -4925,7 +4972,7 @@ Constraints and indexes:
## subject_erasure_requests
-[backend/app/models/postgres.py:8134](../../backend/app/models/postgres.py#L8134)
+[backend/app/models/postgres.py:8172](../../backend/app/models/postgres.py#L8172)
A person's request to have their account erased (W38: W31 F-1; migration 0256).
@@ -4964,7 +5011,7 @@ Constraints and indexes:
## subject_rights_jobs
-[backend/app/models/postgres.py:8058](../../backend/app/models/postgres.py#L8058)
+[backend/app/models/postgres.py:8096](../../backend/app/models/postgres.py#L8096)
One personal-data export or erasure of ONE person (W31 STRAT-12; migration 0253).
@@ -5077,7 +5124,7 @@ Constraints and indexes:
## suite_membership_events
-[backend/app/models/postgres.py:3927](../../backend/app/models/postgres.py#L3927)
+[backend/app/models/postgres.py:3961](../../backend/app/models/postgres.py#L3961)
Immutable audit log of suite membership changes detected during sync.
@@ -5105,7 +5152,7 @@ Constraints and indexes:
## suite_membership_parity_runs
-[backend/app/models/postgres.py:3948](../../backend/app/models/postgres.py#L3948)
+[backend/app/models/postgres.py:3982](../../backend/app/models/postgres.py#L3982)
One comparison of the legacy suite memberships with the canonical model (W25a HYG-04; migration 0248).
@@ -5146,7 +5193,7 @@ Constraints and indexes:
## suite_memberships
-[backend/app/models/postgres.py:3897](../../backend/app/models/postgres.py#L3897)
+[backend/app/models/postgres.py:3931](../../backend/app/models/postgres.py#L3931)
Tracks which test cases belong to which suite, linked to the run that confirmed membership.
@@ -5219,7 +5266,7 @@ Constraints and indexes:
## systemic_cluster_epics
-[backend/app/models/postgres.py:6963](../../backend/app/models/postgres.py#L6963)
+[backend/app/models/postgres.py:7001](../../backend/app/models/postgres.py#L7001)
A Jira epic a person filed for a recurring systemic cluster (W36 STRAT-03; migration 0255).
@@ -5251,7 +5298,7 @@ Constraints and indexes:
## systemic_flake_cluster
-[backend/app/models/postgres.py:6908](../../backend/app/models/postgres.py#L6908)
+[backend/app/models/postgres.py:6946](../../backend/app/models/postgres.py#L6946)
@@ -5278,7 +5325,7 @@ Constraints and indexes:
## systemic_flake_cluster_member
-[backend/app/models/postgres.py:6943](../../backend/app/models/postgres.py#L6943)
+[backend/app/models/postgres.py:6981](../../backend/app/models/postgres.py#L6981)
@@ -5331,7 +5378,7 @@ Constraints and indexes:
## tenant_onboarding_status
-[backend/app/models/postgres.py:4777](../../backend/app/models/postgres.py#L4777)
+[backend/app/models/postgres.py:4811](../../backend/app/models/postgres.py#L4811)
Tracks onboarding wizard progress per project.
@@ -5392,7 +5439,7 @@ test_step: Mapped[Optional['TestStep']] = relationship('TestStep', back_populate
## test_case_audit_logs
-[backend/app/models/postgres.py:3839](../../backend/app/models/postgres.py#L3839)
+[backend/app/models/postgres.py:3873](../../backend/app/models/postgres.py#L3873)
Append-only compliance audit trail for all test management actions.
@@ -5448,7 +5495,7 @@ Constraints and indexes:
## test_case_comments
-[backend/app/models/postgres.py:3324](../../backend/app/models/postgres.py#L3324)
+[backend/app/models/postgres.py:3358](../../backend/app/models/postgres.py#L3358)
Threaded comment on a ManagedTestCase.
@@ -5508,7 +5555,7 @@ test_case: Mapped['TestCase'] = relationship('TestCase', back_populates='history
## test_case_requirement_links
-[backend/app/models/postgres.py:3345](../../backend/app/models/postgres.py#L3345)
+[backend/app/models/postgres.py:3379](../../backend/app/models/postgres.py#L3379)
A requirement key a person typed on an authored test case (W13 TCL-06, migration 0229).
@@ -5546,7 +5593,7 @@ Constraints and indexes:
## test_case_reviews
-[backend/app/models/postgres.py:3288](../../backend/app/models/postgres.py#L3288)
+[backend/app/models/postgres.py:3322](../../backend/app/models/postgres.py#L3322)
Review cycle for a ManagedTestCase.
@@ -5578,7 +5625,7 @@ Constraints and indexes:
## test_case_versions
-[backend/app/models/postgres.py:3236](../../backend/app/models/postgres.py#L3236)
+[backend/app/models/postgres.py:3270](../../backend/app/models/postgres.py#L3270)
Immutable snapshot of a ManagedTestCase at each save.
@@ -5763,7 +5810,7 @@ Constraints and indexes:
## test_health_recommendations
-[backend/app/models/postgres.py:4898](../../backend/app/models/postgres.py#L4898)
+[backend/app/models/postgres.py:4932](../../backend/app/models/postgres.py#L4932)
Persisted test health findings per run from TestHealthAgent.
@@ -5791,7 +5838,7 @@ Constraints and indexes:
## test_plan_items
-[backend/app/models/postgres.py:3505](../../backend/app/models/postgres.py#L3505)
+[backend/app/models/postgres.py:3539](../../backend/app/models/postgres.py#L3539)
A test case entry within a TestPlan.
@@ -5823,7 +5870,7 @@ Constraints and indexes:
## test_plans
-[backend/app/models/postgres.py:3462](../../backend/app/models/postgres.py#L3462)
+[backend/app/models/postgres.py:3496](../../backend/app/models/postgres.py#L3496)
Named collection of test cases forming an executable test plan.
@@ -6045,7 +6092,7 @@ attachments: Mapped[list['TestAttachment']] = relationship('TestAttachment', bac
## test_strategies
-[backend/app/models/postgres.py:3537](../../backend/app/models/postgres.py#L3537)
+[backend/app/models/postgres.py:3571](../../backend/app/models/postgres.py#L3571)
AI-generated or manually authored test strategy document for a project.
@@ -6183,7 +6230,7 @@ Constraints and indexes:
## user_invitations
-[backend/app/models/postgres.py:4848](../../backend/app/models/postgres.py#L4848)
+[backend/app/models/postgres.py:4882](../../backend/app/models/postgres.py#L4882)
Email invite token for onboarding new users.
@@ -6214,7 +6261,7 @@ Constraints and indexes:
## user_ui_dismissals
-[backend/app/models/postgres.py:5597](../../backend/app/models/postgres.py#L5597)
+[backend/app/models/postgres.py:5635](../../backend/app/models/postgres.py#L5635)
A UI prompt this user has dismissed (migration 0145).
@@ -6283,7 +6330,7 @@ Constraints and indexes:
## value_metric_assumptions
-[backend/app/models/postgres.py:7760](../../backend/app/models/postgres.py#L7760)
+[backend/app/models/postgres.py:7798](../../backend/app/models/postgres.py#L7798)
Per-project tunable assumptions for the engineer-hours-saved model
(PMF US-12.1, migration 0112).
@@ -6316,7 +6363,7 @@ Constraints and indexes:
## webhook_deliveries
-[backend/app/models/postgres.py:7239](../../backend/app/models/postgres.py#L7239)
+[backend/app/models/postgres.py:7277](../../backend/app/models/postgres.py#L7277)
Audit trail for every webhook delivery attempt.
@@ -6359,7 +6406,7 @@ Constraints and indexes:
## webhook_subscriptions
-[backend/app/models/postgres.py:7180](../../backend/app/models/postgres.py#L7180)
+[backend/app/models/postgres.py:7218](../../backend/app/models/postgres.py#L7218)
Customer-managed outbound webhook subscription.
@@ -6396,7 +6443,7 @@ Constraints and indexes:
## workflow_definitions
-[backend/app/models/postgres.py:6436](../../backend/app/models/postgres.py#L6436)
+[backend/app/models/postgres.py:6474](../../backend/app/models/postgres.py#L6474)
One immutable-on-publish version of a project workflow (E3.1).
@@ -6446,7 +6493,7 @@ Constraints and indexes:
## workflow_replay_corpus
-[backend/app/models/postgres.py:6568](../../backend/app/models/postgres.py#L6568)
+[backend/app/models/postgres.py:6606](../../backend/app/models/postgres.py#L6606)
A project run output cached for deterministic workflow evaluation (E9.5).
diff --git a/docs/reference/migrations.md b/docs/reference/migrations.md
index 27a625f88..b3a57e51f 100644
--- a/docs/reference/migrations.md
+++ b/docs/reference/migrations.md
@@ -270,3 +270,4 @@ Alembic revisions extracted without executing migrations. An inventory is not ev
| [backend/migrations/versions/0260_flaky_quarantine_proposed_by.py](../../backend/migrations/versions/0260_flaky_quarantine_proposed_by.py) | `'0260'` | `'0259'` | Who proposed a flaky-test quarantine (product finding D-53). |
| [backend/migrations/versions/0261_nightly_job_observations.py](../../backend/migrations/versions/0261_nightly_job_observations.py) | `'0261'` | `'0260'` | Persist the latest observed attempt and success of two nightly jobs. |
| [backend/migrations/versions/0262_digest_delivery_observations.py](../../backend/migrations/versions/0262_digest_delivery_observations.py) | `'0262'` | `'0261'` | Preserve scheduled digest due work independently of its dispatch claim. |
+| [backend/migrations/versions/0263_pipeline_event_outbox.py](../../backend/migrations/versions/0263_pipeline_event_outbox.py) | `'0263'` | `'0262'` | Add a project-scoped queue for immutable pipeline event delivery. |
diff --git a/docs/reference/openapi.json b/docs/reference/openapi.json
index 3a5a17382..633671d37 100644
--- a/docs/reference/openapi.json
+++ b/docs/reference/openapi.json
@@ -20118,6 +20118,376 @@
"title": "IdentityEventType",
"type": "string"
},
+ "IdentityRetentionApproval": {
+ "properties": {
+ "confirmation": {
+ "title": "Confirmation",
+ "type": "string"
+ },
+ "observed_at": {
+ "format": "date-time",
+ "title": "Observed At",
+ "type": "string"
+ },
+ "preview_hash": {
+ "pattern": "^[a-f0-9]{64}$",
+ "title": "Preview Hash",
+ "type": "string"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ },
+ "retention_days": {
+ "maximum": 3650.0,
+ "minimum": 365.0,
+ "title": "Retention Days",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "retention_days",
+ "observed_at",
+ "preview_hash",
+ "confirmation",
+ "reason"
+ ],
+ "title": "IdentityRetentionApproval",
+ "type": "object"
+ },
+ "IdentityRetentionHold": {
+ "additionalProperties": false,
+ "properties": {
+ "audit_id": {
+ "format": "uuid",
+ "title": "Audit Id",
+ "type": "string"
+ },
+ "expires_at": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Expires At"
+ },
+ "id": {
+ "format": "uuid",
+ "title": "Id",
+ "type": "string"
+ },
+ "placed_at": {
+ "format": "date-time",
+ "title": "Placed At",
+ "type": "string"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "reason",
+ "placed_at",
+ "audit_id"
+ ],
+ "title": "IdentityRetentionHold",
+ "type": "object"
+ },
+ "IdentityRetentionHoldCreate": {
+ "properties": {
+ "expires_at": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Expires At"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "reason"
+ ],
+ "title": "IdentityRetentionHoldCreate",
+ "type": "object"
+ },
+ "IdentityRetentionHoldRelease": {
+ "properties": {
+ "confirmation": {
+ "title": "Confirmation",
+ "type": "string"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "reason",
+ "confirmation"
+ ],
+ "title": "IdentityRetentionHoldRelease",
+ "type": "object"
+ },
+ "IdentityRetentionPreview": {
+ "properties": {
+ "active_hold_count": {
+ "title": "Active Hold Count",
+ "type": "integer"
+ },
+ "counts": {
+ "additionalProperties": {
+ "type": "integer"
+ },
+ "title": "Counts",
+ "type": "object"
+ },
+ "cutoff": {
+ "format": "date-time",
+ "title": "Cutoff",
+ "type": "string"
+ },
+ "enable_confirmation": {
+ "title": "Enable Confirmation",
+ "type": "string"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "max_batch_size": {
+ "default": 500,
+ "title": "Max Batch Size",
+ "type": "integer"
+ },
+ "observed_at": {
+ "format": "date-time",
+ "title": "Observed At",
+ "type": "string"
+ },
+ "preview_hash": {
+ "title": "Preview Hash",
+ "type": "string"
+ },
+ "purge_confirmation": {
+ "title": "Purge Confirmation",
+ "type": "string"
+ },
+ "retention_days": {
+ "title": "Retention Days",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "observed_at",
+ "cutoff",
+ "retention_days",
+ "enabled",
+ "active_hold_count",
+ "counts",
+ "preview_hash",
+ "enable_confirmation",
+ "purge_confirmation"
+ ],
+ "title": "IdentityRetentionPreview",
+ "type": "object"
+ },
+ "IdentityRetentionPurge": {
+ "properties": {
+ "batch_size": {
+ "default": 500,
+ "maximum": 500.0,
+ "minimum": 1.0,
+ "title": "Batch Size",
+ "type": "integer"
+ },
+ "confirmation": {
+ "title": "Confirmation",
+ "type": "string"
+ },
+ "observed_at": {
+ "format": "date-time",
+ "title": "Observed At",
+ "type": "string"
+ },
+ "preview_hash": {
+ "pattern": "^[a-f0-9]{64}$",
+ "title": "Preview Hash",
+ "type": "string"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "observed_at",
+ "preview_hash",
+ "confirmation",
+ "reason"
+ ],
+ "title": "IdentityRetentionPurge",
+ "type": "object"
+ },
+ "IdentityRetentionPurgeResult": {
+ "properties": {
+ "batch_full": {
+ "title": "Batch Full",
+ "type": "boolean"
+ },
+ "batch_size": {
+ "title": "Batch Size",
+ "type": "integer"
+ },
+ "cutoff": {
+ "format": "date-time",
+ "title": "Cutoff",
+ "type": "string"
+ },
+ "deleted": {
+ "title": "Deleted",
+ "type": "integer"
+ },
+ "policy_revision": {
+ "title": "Policy Revision",
+ "type": "integer"
+ },
+ "status": {
+ "const": "completed",
+ "title": "Status",
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "deleted",
+ "batch_size",
+ "batch_full",
+ "cutoff",
+ "policy_revision"
+ ],
+ "title": "IdentityRetentionPurgeResult",
+ "type": "object"
+ },
+ "IdentityRetentionRead": {
+ "additionalProperties": false,
+ "properties": {
+ "active_hold_count": {
+ "default": 0,
+ "title": "Active Hold Count",
+ "type": "integer"
+ },
+ "approved_at": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Approved At"
+ },
+ "eligible_event_types": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Eligible Event Types",
+ "type": "array"
+ },
+ "enabled": {
+ "default": false,
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "holds": {
+ "items": {
+ "$ref": "#/components/schemas/IdentityRetentionHold"
+ },
+ "maxItems": 100,
+ "title": "Holds",
+ "type": "array"
+ },
+ "protected_authority_event_types": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Protected Authority Event Types",
+ "type": "array"
+ },
+ "protected_identity_events": {
+ "default": "All other identity event types, including unknown future types, remain retained.",
+ "title": "Protected Identity Events",
+ "type": "string"
+ },
+ "retention_days": {
+ "default": 2555,
+ "maximum": 3650.0,
+ "minimum": 365.0,
+ "title": "Retention Days",
+ "type": "integer"
+ },
+ "revision": {
+ "default": 0,
+ "minimum": 0.0,
+ "title": "Revision",
+ "type": "integer"
+ },
+ "schema_version": {
+ "const": 1,
+ "default": 1,
+ "title": "Schema Version",
+ "type": "integer"
+ },
+ "scope": {
+ "const": "instance",
+ "default": "instance",
+ "title": "Scope",
+ "type": "string"
+ }
+ },
+ "title": "IdentityRetentionRead",
+ "type": "object"
+ },
+ "IdentityRetentionReason": {
+ "properties": {
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "reason"
+ ],
+ "title": "IdentityRetentionReason",
+ "type": "object"
+ },
"IdentitySyncStatus": {
"description": "Aggregated sync health for the admin dashboard.",
"properties": {
@@ -30237,6 +30607,16 @@
},
"PipelineEventLogHealthResponse": {
"properties": {
+ "backlog_count": {
+ "default": 0,
+ "title": "Backlog Count",
+ "type": "integer"
+ },
+ "capacity": {
+ "default": 0,
+ "title": "Capacity",
+ "type": "integer"
+ },
"dead_letter_count": {
"default": 0,
"title": "Dead Letter Count",
@@ -30247,6 +30627,16 @@
"title": "Dead Letter Limit",
"type": "integer"
},
+ "oldest_pending_age_seconds": {
+ "default": 0,
+ "title": "Oldest Pending Age Seconds",
+ "type": "number"
+ },
+ "outbox_total_count": {
+ "default": 0,
+ "title": "Outbox Total Count",
+ "type": "integer"
+ },
"recent_dead_letters": {
"items": {
"additionalProperties": true,
@@ -30260,6 +30650,13 @@
"title": "Status",
"type": "string"
},
+ "status_counts": {
+ "additionalProperties": {
+ "type": "integer"
+ },
+ "title": "Status Counts",
+ "type": "object"
+ },
"write_failure_count": {
"default": 0,
"title": "Write Failure Count",
@@ -30621,6 +31018,18 @@
"title": "Detail",
"type": "object"
},
+ "event_id": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Event Id"
+ },
"event_type": {
"title": "Event Type",
"type": "string"
@@ -54573,9 +54982,26 @@
},
"/api/v1/agents/event-log/health": {
"get": {
- "description": "Return write-health details for the pipeline audit event log.",
+ "description": "Read shared delivery health within the caller's accessible projects.",
"operationId": "get_pipeline_event_log_health_api_v1_agents_event_log_health_get",
"parameters": [
+ {
+ "in": "query",
+ "name": "project_id",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id"
+ }
+ },
{
"in": "header",
"name": "X-API-Key",
@@ -54626,18 +55052,28 @@
]
}
},
- "/api/v1/agents/invocations/{invocation_id}": {
- "get": {
- "description": "Poll one invocation: status, attempts, output and review state, read from its run.",
- "operationId": "get_invocation_api_v1_agents_invocations__invocation_id__get",
+ "/api/v1/agents/event-log/{event_id}/replay": {
+ "post": {
+ "description": "Requeue one failed delivery; never re-execute pipeline business work.",
+ "operationId": "replay_pipeline_event_delivery_api_v1_agents_event_log__event_id__replay_post",
"parameters": [
{
"in": "path",
- "name": "invocation_id",
+ "name": "event_id",
"required": true,
"schema": {
"format": "uuid",
- "title": "Invocation Id",
+ "title": "Event Id",
+ "type": "string"
+ }
+ },
+ {
+ "in": "query",
+ "name": "project_id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "Project Id",
"type": "string"
}
},
@@ -54659,12 +55095,10 @@
}
],
"responses": {
- "200": {
+ "202": {
"content": {
"application/json": {
- "schema": {
- "$ref": "#/components/schemas/AgentInvocationResponse"
- }
+ "schema": {}
}
},
"description": "Successful Response"
@@ -54685,16 +55119,16 @@
"JWT": []
}
],
- "summary": "Get Invocation",
+ "summary": "Replay Pipeline Event Delivery",
"tags": [
- "Agent Invocations"
+ "Agents"
]
}
},
- "/api/v1/agents/invocations/{invocation_id}/cancel": {
- "post": {
- "description": "Cancel an invocation cooperatively, exactly as its pipeline run is cancelled.\n\nA run with no live worker stops now; a running one is asked to stop and\nterminalises at its next stage boundary. Cancellation is sticky: an\nautomatic retry never brings it back. Cancellation before the worker\ncreates a run is stored on the invocation and rechecked under a row lock.",
- "operationId": "cancel_invocation_api_v1_agents_invocations__invocation_id__cancel_post",
+ "/api/v1/agents/invocations/{invocation_id}": {
+ "get": {
+ "description": "Poll one invocation: status, attempts, output and review state, read from its run.",
+ "operationId": "get_invocation_api_v1_agents_invocations__invocation_id__get",
"parameters": [
{
"in": "path",
@@ -54724,7 +55158,7 @@
}
],
"responses": {
- "202": {
+ "200": {
"content": {
"application/json": {
"schema": {
@@ -54750,69 +55184,16 @@
"JWT": []
}
],
- "summary": "Cancel Invocation",
- "tags": [
- "Agent Invocations"
- ]
- }
- },
- "/api/v1/agents/invocations/{invocation_id}/events": {
- "get": {
- "description": "Progress of one invocation as server-sent events, until its run finishes.",
- "operationId": "stream_invocation_events_api_v1_agents_invocations__invocation_id__events_get",
- "parameters": [
- {
- "in": "path",
- "name": "invocation_id",
- "required": true,
- "schema": {
- "format": "uuid",
- "title": "Invocation Id",
- "type": "string"
- }
- },
- {
- "in": "query",
- "name": "ticket",
- "required": true,
- "schema": {
- "maxLength": 128,
- "minLength": 16,
- "title": "Ticket",
- "type": "string"
- }
- }
- ],
- "responses": {
- "200": {
- "content": {
- "application/json": {
- "schema": {}
- }
- },
- "description": "Successful Response"
- },
- "422": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/HTTPValidationError"
- }
- }
- },
- "description": "Validation Error"
- }
- },
- "summary": "Stream Invocation Events",
+ "summary": "Get Invocation",
"tags": [
"Agent Invocations"
]
}
},
- "/api/v1/agents/invocations/{invocation_id}/events/ticket": {
+ "/api/v1/agents/invocations/{invocation_id}/cancel": {
"post": {
- "description": "A single-use ticket for ``GET .../events`` (EventSource cannot send Authorization).",
- "operationId": "issue_invocation_stream_ticket_api_v1_agents_invocations__invocation_id__events_ticket_post",
+ "description": "Cancel an invocation cooperatively, exactly as its pipeline run is cancelled.\n\nA run with no live worker stops now; a running one is asked to stop and\nterminalises at its next stage boundary. Cancellation is sticky: an\nautomatic retry never brings it back. Cancellation before the worker\ncreates a run is stored on the invocation and rechecked under a row lock.",
+ "operationId": "cancel_invocation_api_v1_agents_invocations__invocation_id__cancel_post",
"parameters": [
{
"in": "path",
@@ -54842,11 +55223,11 @@
}
],
"responses": {
- "200": {
+ "202": {
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/StreamTicketResponse"
+ "$ref": "#/components/schemas/AgentInvocationResponse"
}
}
},
@@ -54868,16 +55249,16 @@
"JWT": []
}
],
- "summary": "Issue Invocation Stream Ticket",
+ "summary": "Cancel Invocation",
"tags": [
"Agent Invocations"
]
}
},
- "/api/v1/agents/invocations/{invocation_id}/retry": {
- "post": {
- "description": "Retry a failed invocation: a new attempt of the same invocation (E1.2).\n\nThe pipeline retry rules apply to the invocation's run. It is refused with\n409 while the run is in progress, after a clean finish or review rejection,\nor at the attempt ceiling; the last three carry ``links.rerun`` to invoke\nthe agent again. Review rejection is terminal even if configuration changed.\n\nA retry resumes the SAME run, so the frozen plan (this agent and its\ndependencies only) is kept. When the agent configuration changed since the\nrun started, resuming would replay work authorised under the old\nconfiguration, and a rerun needs a new run -- which is a new invocation --\nso that is 409 with ``links.rerun`` too. An invocation whose run never\nstarted is dispatched again.",
- "operationId": "retry_invocation_api_v1_agents_invocations__invocation_id__retry_post",
+ "/api/v1/agents/invocations/{invocation_id}/events": {
+ "get": {
+ "description": "Progress of one invocation as server-sent events, until its run finishes.",
+ "operationId": "stream_invocation_events_api_v1_agents_invocations__invocation_id__events_get",
"parameters": [
{
"in": "path",
@@ -54890,29 +55271,22 @@
}
},
{
- "in": "header",
- "name": "X-API-Key",
- "required": false,
+ "in": "query",
+ "name": "ticket",
+ "required": true,
"schema": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "X-Api-Key"
+ "maxLength": 128,
+ "minLength": 16,
+ "title": "Ticket",
+ "type": "string"
}
}
],
"responses": {
- "202": {
+ "200": {
"content": {
"application/json": {
- "schema": {
- "$ref": "#/components/schemas/AgentInvocationResponse"
- }
+ "schema": {}
}
},
"description": "Successful Response"
@@ -54928,82 +55302,25 @@
"description": "Validation Error"
}
},
- "security": [
- {
- "JWT": []
- }
- ],
- "summary": "Retry Invocation",
+ "summary": "Stream Invocation Events",
"tags": [
"Agent Invocations"
]
}
},
- "/api/v1/agents/pipelines": {
- "get": {
- "description": "List agent pipeline runs, optionally filtered by test run, project, or status.",
- "operationId": "list_pipelines_api_v1_agents_pipelines_get",
+ "/api/v1/agents/invocations/{invocation_id}/events/ticket": {
+ "post": {
+ "description": "A single-use ticket for ``GET .../events`` (EventSource cannot send Authorization).",
+ "operationId": "issue_invocation_stream_ticket_api_v1_agents_invocations__invocation_id__events_ticket_post",
"parameters": [
{
- "in": "query",
- "name": "run_id",
- "required": false,
- "schema": {
- "anyOf": [
- {
- "format": "uuid",
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Run Id"
- }
- },
- {
- "in": "query",
- "name": "project_id",
- "required": false,
- "schema": {
- "anyOf": [
- {
- "format": "uuid",
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Project Id"
- }
- },
- {
- "in": "query",
- "name": "status",
- "required": false,
- "schema": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "title": "Status"
- }
- },
- {
- "in": "query",
- "name": "limit",
- "required": false,
+ "in": "path",
+ "name": "invocation_id",
+ "required": true,
"schema": {
- "default": 20,
- "maximum": 100,
- "minimum": 1,
- "title": "Limit",
- "type": "integer"
+ "format": "uuid",
+ "title": "Invocation Id",
+ "type": "string"
}
},
{
@@ -55028,11 +55345,7 @@
"content": {
"application/json": {
"schema": {
- "items": {
- "$ref": "#/components/schemas/AgentPipelineResponse"
- },
- "title": "Response List Pipelines Api V1 Agents Pipelines Get",
- "type": "array"
+ "$ref": "#/components/schemas/StreamTicketResponse"
}
}
},
@@ -55054,24 +55367,24 @@
"JWT": []
}
],
- "summary": "List Pipelines",
+ "summary": "Issue Invocation Stream Ticket",
"tags": [
- "Agents"
+ "Agent Invocations"
]
}
},
- "/api/v1/agents/pipelines/bulk-jobs/{bulk_job_id}": {
- "get": {
- "description": "A bulk job's request facts and its progress, COUNTED from the pipeline\nrows on this read (restricted to the caller's current projects). Without\nthe request record (expired / flushed) only the caller's own rows are\ncounted and ``counters_source`` says ``postgres``. Writes nothing.",
- "operationId": "get_bulk_job_api_v1_agents_pipelines_bulk_jobs__bulk_job_id__get",
+ "/api/v1/agents/invocations/{invocation_id}/retry": {
+ "post": {
+ "description": "Retry a failed invocation: a new attempt of the same invocation (E1.2).\n\nThe pipeline retry rules apply to the invocation's run. It is refused with\n409 while the run is in progress, after a clean finish or review rejection,\nor at the attempt ceiling; the last three carry ``links.rerun`` to invoke\nthe agent again. Review rejection is terminal even if configuration changed.\n\nA retry resumes the SAME run, so the frozen plan (this agent and its\ndependencies only) is kept. When the agent configuration changed since the\nrun started, resuming would replay work authorised under the old\nconfiguration, and a rerun needs a new run -- which is a new invocation --\nso that is 409 with ``links.rerun`` too. An invocation whose run never\nstarted is dispatched again.",
+ "operationId": "retry_invocation_api_v1_agents_invocations__invocation_id__retry_post",
"parameters": [
{
"in": "path",
- "name": "bulk_job_id",
+ "name": "invocation_id",
"required": true,
"schema": {
"format": "uuid",
- "title": "Bulk Job Id",
+ "title": "Invocation Id",
"type": "string"
}
},
@@ -55093,11 +55406,11 @@
}
],
"responses": {
- "200": {
+ "202": {
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/BulkJobRead"
+ "$ref": "#/components/schemas/AgentInvocationResponse"
}
}
},
@@ -55119,25 +55432,77 @@
"JWT": []
}
],
- "summary": "Get Bulk Job",
+ "summary": "Retry Invocation",
"tags": [
- "Agents"
+ "Agent Invocations"
]
}
},
- "/api/v1/agents/pipelines/bulk-jobs/{bulk_job_id}/cancel": {
- "post": {
- "description": "Cancel a bulk job: its tasks that have NOT started return at their first\nline without creating a pipeline; running pipelines keep their own Stop.\nIdempotent (an already-cancelled job answers 200 and records nothing new);\na finished job is a 409. One ``analysis.bulk_cancelled`` per project.",
- "operationId": "cancel_bulk_job_api_v1_agents_pipelines_bulk_jobs__bulk_job_id__cancel_post",
+ "/api/v1/agents/pipelines": {
+ "get": {
+ "description": "List agent pipeline runs, optionally filtered by test run, project, or status.",
+ "operationId": "list_pipelines_api_v1_agents_pipelines_get",
"parameters": [
{
- "in": "path",
- "name": "bulk_job_id",
- "required": true,
+ "in": "query",
+ "name": "run_id",
+ "required": false,
"schema": {
- "format": "uuid",
- "title": "Bulk Job Id",
- "type": "string"
+ "anyOf": [
+ {
+ "format": "uuid",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Run Id"
+ }
+ },
+ {
+ "in": "query",
+ "name": "project_id",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Project Id"
+ }
+ },
+ {
+ "in": "query",
+ "name": "status",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Status"
+ }
+ },
+ {
+ "in": "query",
+ "name": "limit",
+ "required": false,
+ "schema": {
+ "default": 20,
+ "maximum": 100,
+ "minimum": 1,
+ "title": "Limit",
+ "type": "integer"
}
},
{
@@ -55162,7 +55527,11 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/BulkJobRead"
+ "items": {
+ "$ref": "#/components/schemas/AgentPipelineResponse"
+ },
+ "title": "Response List Pipelines Api V1 Agents Pipelines Get",
+ "type": "array"
}
}
},
@@ -55184,17 +55553,27 @@
"JWT": []
}
],
- "summary": "Cancel Bulk Job",
+ "summary": "List Pipelines",
"tags": [
"Agents"
]
}
},
- "/api/v1/agents/pipelines/bulk-trigger": {
- "post": {
- "description": "Queue the agent pipeline for many runs in one HTTP call.\n\nBacks the /runs bulk-action UI (\"Trigger all FAILED\", multi-row select).\nReplaces the previous client-side fan-out — for a 500-run trigger this\nis one round-trip instead of 500. Tasks are queued in batches of 25 with\na tiny inter-batch sleep so the Celery broker isn't slammed in a single\nburst.\n\nW14 AGT-12: the runs are ``run_ids`` OR the Runs list's own filter\n(``run_filter``, resolved by the list's predicates, newest 2,000); a run\nwhose pipeline is still in progress is skipped and counted (the worker's\nadmission keys never held a person's trigger); the answer carries a\n``bulk_job_id`` whose progress ``GET /pipelines/bulk-jobs/{id}`` counts\nfrom the pipeline rows. ``client_token`` makes a retry queue nothing twice.",
- "operationId": "bulk_trigger_pipelines_api_v1_agents_pipelines_bulk_trigger_post",
+ "/api/v1/agents/pipelines/bulk-jobs/{bulk_job_id}": {
+ "get": {
+ "description": "A bulk job's request facts and its progress, COUNTED from the pipeline\nrows on this read (restricted to the caller's current projects). Without\nthe request record (expired / flushed) only the caller's own rows are\ncounted and ``counters_source`` says ``postgres``. Writes nothing.",
+ "operationId": "get_bulk_job_api_v1_agents_pipelines_bulk_jobs__bulk_job_id__get",
"parameters": [
+ {
+ "in": "path",
+ "name": "bulk_job_id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "Bulk Job Id",
+ "type": "string"
+ }
+ },
{
"in": "header",
"name": "X-API-Key",
@@ -55212,22 +55591,12 @@
}
}
],
- "requestBody": {
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/BulkTriggerRequest"
- }
- }
- },
- "required": true
- },
"responses": {
- "202": {
+ "200": {
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/BulkTriggerResponse"
+ "$ref": "#/components/schemas/BulkJobRead"
}
}
},
@@ -55249,34 +55618,24 @@
"JWT": []
}
],
- "summary": "Bulk Trigger Pipelines",
+ "summary": "Get Bulk Job",
"tags": [
"Agents"
]
}
},
- "/api/v1/agents/pipelines/compare": {
- "get": {
- "description": "Compare two pipeline runs of one project stage by stage (W14 AGT-05).\n\nDeclared BEFORE ``get_pipeline``: FastAPI matches in registration order,\nand the UUID route would otherwise read ``compare`` as a pipeline id.\nBOTH query ids pass the same 404 / 403 gate as ``/pipelines/{id}``.\nWrites nothing.",
- "operationId": "compare_pipelines_api_v1_agents_pipelines_compare_get",
+ "/api/v1/agents/pipelines/bulk-jobs/{bulk_job_id}/cancel": {
+ "post": {
+ "description": "Cancel a bulk job: its tasks that have NOT started return at their first\nline without creating a pipeline; running pipelines keep their own Stop.\nIdempotent (an already-cancelled job answers 200 and records nothing new);\na finished job is a 409. One ``analysis.bulk_cancelled`` per project.",
+ "operationId": "cancel_bulk_job_api_v1_agents_pipelines_bulk_jobs__bulk_job_id__cancel_post",
"parameters": [
{
- "in": "query",
- "name": "a",
- "required": true,
- "schema": {
- "format": "uuid",
- "title": "A",
- "type": "string"
- }
- },
- {
- "in": "query",
- "name": "b",
+ "in": "path",
+ "name": "bulk_job_id",
"required": true,
"schema": {
"format": "uuid",
- "title": "B",
+ "title": "Bulk Job Id",
"type": "string"
}
},
@@ -55302,7 +55661,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/PipelineCompareResponse"
+ "$ref": "#/components/schemas/BulkJobRead"
}
}
},
@@ -55324,16 +55683,16 @@
"JWT": []
}
],
- "summary": "Compare Pipelines",
+ "summary": "Cancel Bulk Job",
"tags": [
"Agents"
]
}
},
- "/api/v1/agents/pipelines/trigger": {
+ "/api/v1/agents/pipelines/bulk-trigger": {
"post": {
- "description": "Manually trigger the agent pipeline for an existing test run.\nReturns 202 Accepted — pipeline runs asynchronously via Celery.",
- "operationId": "trigger_pipeline_api_v1_agents_pipelines_trigger_post",
+ "description": "Queue the agent pipeline for many runs in one HTTP call.\n\nBacks the /runs bulk-action UI (\"Trigger all FAILED\", multi-row select).\nReplaces the previous client-side fan-out — for a 500-run trigger this\nis one round-trip instead of 500. Tasks are queued in batches of 25 with\na tiny inter-batch sleep so the Celery broker isn't slammed in a single\nburst.\n\nW14 AGT-12: the runs are ``run_ids`` OR the Runs list's own filter\n(``run_filter``, resolved by the list's predicates, newest 2,000); a run\nwhose pipeline is still in progress is skipped and counted (the worker's\nadmission keys never held a person's trigger); the answer carries a\n``bulk_job_id`` whose progress ``GET /pipelines/bulk-jobs/{id}`` counts\nfrom the pipeline rows. ``client_token`` makes a retry queue nothing twice.",
+ "operationId": "bulk_trigger_pipelines_api_v1_agents_pipelines_bulk_trigger_post",
"parameters": [
{
"in": "header",
@@ -55356,7 +55715,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/TriggerPipelineRequest"
+ "$ref": "#/components/schemas/BulkTriggerRequest"
}
}
},
@@ -55366,7 +55725,9 @@
"202": {
"content": {
"application/json": {
- "schema": {}
+ "schema": {
+ "$ref": "#/components/schemas/BulkTriggerResponse"
+ }
}
},
"description": "Successful Response"
@@ -55387,24 +55748,34 @@
"JWT": []
}
],
- "summary": "Trigger Pipeline",
+ "summary": "Bulk Trigger Pipelines",
"tags": [
"Agents"
]
}
},
- "/api/v1/agents/pipelines/{pipeline_id}": {
+ "/api/v1/agents/pipelines/compare": {
"get": {
- "description": "Get a single pipeline run with all stage results.",
- "operationId": "get_pipeline_api_v1_agents_pipelines__pipeline_id__get",
+ "description": "Compare two pipeline runs of one project stage by stage (W14 AGT-05).\n\nDeclared BEFORE ``get_pipeline``: FastAPI matches in registration order,\nand the UUID route would otherwise read ``compare`` as a pipeline id.\nBOTH query ids pass the same 404 / 403 gate as ``/pipelines/{id}``.\nWrites nothing.",
+ "operationId": "compare_pipelines_api_v1_agents_pipelines_compare_get",
"parameters": [
{
- "in": "path",
- "name": "pipeline_id",
+ "in": "query",
+ "name": "a",
"required": true,
"schema": {
"format": "uuid",
- "title": "Pipeline Id",
+ "title": "A",
+ "type": "string"
+ }
+ },
+ {
+ "in": "query",
+ "name": "b",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "B",
"type": "string"
}
},
@@ -55430,7 +55801,7 @@
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/AgentPipelineResponse"
+ "$ref": "#/components/schemas/PipelineCompareResponse"
}
}
},
@@ -55452,27 +55823,17 @@
"JWT": []
}
],
- "summary": "Get Pipeline",
+ "summary": "Compare Pipelines",
"tags": [
"Agents"
]
}
},
- "/api/v1/agents/pipelines/{pipeline_id}/agentic-runtime": {
- "get": {
- "description": "Return the versioned unified-runtime projection for one pipeline.\n\nThis additive adapter keeps the established timeline API stable while\nexposing selected/skipped capabilities, parent-child task identity,\nallocated budgets, actual usage and terminal stop reasons in one model.",
- "operationId": "get_agentic_runtime_api_v1_agents_pipelines__pipeline_id__agentic_runtime_get",
+ "/api/v1/agents/pipelines/trigger": {
+ "post": {
+ "description": "Manually trigger the agent pipeline for an existing test run.\nReturns 202 Accepted — pipeline runs asynchronously via Celery.",
+ "operationId": "trigger_pipeline_api_v1_agents_pipelines_trigger_post",
"parameters": [
- {
- "in": "path",
- "name": "pipeline_id",
- "required": true,
- "schema": {
- "format": "uuid",
- "title": "Pipeline Id",
- "type": "string"
- }
- },
{
"in": "header",
"name": "X-API-Key",
@@ -55490,13 +55851,21 @@
}
}
],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TriggerPipelineRequest"
+ }
+ }
+ },
+ "required": true
+ },
"responses": {
- "200": {
+ "202": {
"content": {
"application/json": {
- "schema": {
- "$ref": "#/components/schemas/AgenticRunV1"
- }
+ "schema": {}
}
},
"description": "Successful Response"
@@ -55517,16 +55886,16 @@
"JWT": []
}
],
- "summary": "Get Agentic Runtime",
+ "summary": "Trigger Pipeline",
"tags": [
"Agents"
]
}
},
- "/api/v1/agents/pipelines/{pipeline_id}/cancel": {
- "post": {
- "description": "Cancel a pipeline run (E7.4).\n\nA ``pending`` or ``retry_wait`` run has no live worker and stops here and\nnow. A ``running`` run is *asked* to stop: the flag is set and the worker\nterminalises itself at its next stage boundary, so its in-flight writes\nland coherently instead of being orphaned under a row the API already\ndeclared dead.\n\nCancellation is sticky either way — an automatic retry can never bring a\ncancelled run back. See ``app/services/pipeline_cancellation.py`` for why\nboth orderings of the cancel-vs-retry race end ``failed``.",
- "operationId": "cancel_pipeline_api_v1_agents_pipelines__pipeline_id__cancel_post",
+ "/api/v1/agents/pipelines/{pipeline_id}": {
+ "get": {
+ "description": "Get a single pipeline run with all stage results.",
+ "operationId": "get_pipeline_api_v1_agents_pipelines__pipeline_id__get",
"parameters": [
{
"in": "path",
@@ -55559,7 +55928,9 @@
"200": {
"content": {
"application/json": {
- "schema": {}
+ "schema": {
+ "$ref": "#/components/schemas/AgentPipelineResponse"
+ }
}
},
"description": "Successful Response"
@@ -55580,16 +55951,144 @@
"JWT": []
}
],
- "summary": "Cancel Pipeline",
+ "summary": "Get Pipeline",
"tags": [
"Agents"
]
}
},
- "/api/v1/agents/pipelines/{pipeline_id}/replay": {
+ "/api/v1/agents/pipelines/{pipeline_id}/agentic-runtime": {
"get": {
- "description": "Return a deterministic replay document for audit reconstruction.",
- "operationId": "get_pipeline_replay_api_v1_agents_pipelines__pipeline_id__replay_get",
+ "description": "Return the versioned unified-runtime projection for one pipeline.\n\nThis additive adapter keeps the established timeline API stable while\nexposing selected/skipped capabilities, parent-child task identity,\nallocated budgets, actual usage and terminal stop reasons in one model.",
+ "operationId": "get_agentic_runtime_api_v1_agents_pipelines__pipeline_id__agentic_runtime_get",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "pipeline_id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "Pipeline Id",
+ "type": "string"
+ }
+ },
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgenticRunV1"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Get Agentic Runtime",
+ "tags": [
+ "Agents"
+ ]
+ }
+ },
+ "/api/v1/agents/pipelines/{pipeline_id}/cancel": {
+ "post": {
+ "description": "Cancel a pipeline run (E7.4).\n\nA ``pending`` or ``retry_wait`` run has no live worker and stops here and\nnow. A ``running`` run is *asked* to stop: the flag is set and the worker\nterminalises itself at its next stage boundary, so its in-flight writes\nland coherently instead of being orphaned under a row the API already\ndeclared dead.\n\nCancellation is sticky either way — an automatic retry can never bring a\ncancelled run back. See ``app/services/pipeline_cancellation.py`` for why\nboth orderings of the cancel-vs-retry race end ``failed``.",
+ "operationId": "cancel_pipeline_api_v1_agents_pipelines__pipeline_id__cancel_post",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "pipeline_id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "Pipeline Id",
+ "type": "string"
+ }
+ },
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {}
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Cancel Pipeline",
+ "tags": [
+ "Agents"
+ ]
+ }
+ },
+ "/api/v1/agents/pipelines/{pipeline_id}/replay": {
+ "get": {
+ "description": "Return a deterministic replay document for audit reconstruction.",
+ "operationId": "get_pipeline_replay_api_v1_agents_pipelines__pipeline_id__replay_get",
"parameters": [
{
"in": "path",
@@ -68635,6 +69134,467 @@
]
}
},
+ "/api/v1/identity/retention/disable": {
+ "post": {
+ "description": "Disable future identity expiry without releasing any hold.",
+ "operationId": "disable_identity_retention_policy_api_v1_identity_retention_disable_post",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionReason"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Disable Identity Retention Policy",
+ "tags": [
+ "Identity & Audit"
+ ]
+ }
+ },
+ "/api/v1/identity/retention/holds": {
+ "post": {
+ "description": "Place an independent instance identity hold; all live holds block expiry.",
+ "operationId": "place_identity_retention_hold_api_v1_identity_retention_holds_post",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionHoldCreate"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionHold"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Place Identity Retention Hold",
+ "tags": [
+ "Identity & Audit"
+ ]
+ }
+ },
+ "/api/v1/identity/retention/holds/{hold_id}/release": {
+ "post": {
+ "description": "Release only this hold with a reason; overlapping holds remain absolute.",
+ "operationId": "release_identity_retention_hold_api_v1_identity_retention_holds__hold_id__release_post",
+ "parameters": [
+ {
+ "in": "path",
+ "name": "hold_id",
+ "required": true,
+ "schema": {
+ "format": "uuid",
+ "title": "Hold Id",
+ "type": "string"
+ }
+ },
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionHoldRelease"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Release Identity Retention Hold",
+ "tags": [
+ "Identity & Audit"
+ ]
+ }
+ },
+ "/api/v1/identity/retention/policy": {
+ "get": {
+ "description": "Read the separate, default-off instance identity policy and its holds.",
+ "operationId": "read_identity_retention_policy_api_v1_identity_retention_policy_get",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Read Identity Retention Policy",
+ "tags": [
+ "Identity & Audit"
+ ]
+ },
+ "post": {
+ "description": "Approve routine-event expiry with a fresh preview and typed confirmation.\n\nRequires an interactive instance administrator. Existing project retention\nenablement never authorizes this separate policy.",
+ "operationId": "approve_identity_retention_policy_api_v1_identity_retention_policy_post",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionApproval"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionRead"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Approve Identity Retention Policy",
+ "tags": [
+ "Identity & Audit"
+ ]
+ }
+ },
+ "/api/v1/identity/retention/preview": {
+ "get": {
+ "description": "Count aged record classes without reading event content or deleting rows.",
+ "operationId": "preview_identity_retention_api_v1_identity_retention_preview_get",
+ "parameters": [
+ {
+ "in": "query",
+ "name": "retention_days",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "maximum": 3650,
+ "minimum": 365,
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Retention Days"
+ }
+ },
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionPreview"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Preview Identity Retention",
+ "tags": [
+ "Identity & Audit"
+ ]
+ }
+ },
+ "/api/v1/identity/retention/purge": {
+ "post": {
+ "description": "Execute one approved, unheld batch of at most 500 routine events.",
+ "operationId": "purge_identity_retention_batch_api_v1_identity_retention_purge_post",
+ "parameters": [
+ {
+ "in": "header",
+ "name": "X-API-Key",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "X-Api-Key"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionPurge"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/IdentityRetentionPurgeResult"
+ }
+ }
+ },
+ "description": "Successful Response"
+ },
+ "422": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ },
+ "description": "Validation Error"
+ }
+ },
+ "security": [
+ {
+ "JWT": []
+ }
+ ],
+ "summary": "Purge Identity Retention Batch",
+ "tags": [
+ "Identity & Audit"
+ ]
+ }
+ },
"/api/v1/identity/sync-status": {
"get": {
"description": "Get aggregated identity sync health (ADMIN only).",
diff --git a/docs/reference/schemas.md b/docs/reference/schemas.md
index b35b98d8e..efb31b46d 100644
--- a/docs/reference/schemas.md
+++ b/docs/reference/schemas.md
@@ -21598,6 +21598,421 @@ These are the full generated JSON Schema definitions, including required fields,
}
```
+## IdentityRetentionApproval
+
+```json
+{
+ "properties": {
+ "confirmation": {
+ "title": "Confirmation",
+ "type": "string"
+ },
+ "observed_at": {
+ "format": "date-time",
+ "title": "Observed At",
+ "type": "string"
+ },
+ "preview_hash": {
+ "pattern": "^[a-f0-9]{64}$",
+ "title": "Preview Hash",
+ "type": "string"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ },
+ "retention_days": {
+ "maximum": 3650.0,
+ "minimum": 365.0,
+ "title": "Retention Days",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "retention_days",
+ "observed_at",
+ "preview_hash",
+ "confirmation",
+ "reason"
+ ],
+ "title": "IdentityRetentionApproval",
+ "type": "object"
+}
+```
+
+## IdentityRetentionHold
+
+```json
+{
+ "additionalProperties": false,
+ "properties": {
+ "audit_id": {
+ "format": "uuid",
+ "title": "Audit Id",
+ "type": "string"
+ },
+ "expires_at": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Expires At"
+ },
+ "id": {
+ "format": "uuid",
+ "title": "Id",
+ "type": "string"
+ },
+ "placed_at": {
+ "format": "date-time",
+ "title": "Placed At",
+ "type": "string"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "reason",
+ "placed_at",
+ "audit_id"
+ ],
+ "title": "IdentityRetentionHold",
+ "type": "object"
+}
+```
+
+## IdentityRetentionHoldCreate
+
+```json
+{
+ "properties": {
+ "expires_at": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Expires At"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "reason"
+ ],
+ "title": "IdentityRetentionHoldCreate",
+ "type": "object"
+}
+```
+
+## IdentityRetentionHoldRelease
+
+```json
+{
+ "properties": {
+ "confirmation": {
+ "title": "Confirmation",
+ "type": "string"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "reason",
+ "confirmation"
+ ],
+ "title": "IdentityRetentionHoldRelease",
+ "type": "object"
+}
+```
+
+## IdentityRetentionPreview
+
+```json
+{
+ "properties": {
+ "active_hold_count": {
+ "title": "Active Hold Count",
+ "type": "integer"
+ },
+ "counts": {
+ "additionalProperties": {
+ "type": "integer"
+ },
+ "title": "Counts",
+ "type": "object"
+ },
+ "cutoff": {
+ "format": "date-time",
+ "title": "Cutoff",
+ "type": "string"
+ },
+ "enable_confirmation": {
+ "title": "Enable Confirmation",
+ "type": "string"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "max_batch_size": {
+ "default": 500,
+ "title": "Max Batch Size",
+ "type": "integer"
+ },
+ "observed_at": {
+ "format": "date-time",
+ "title": "Observed At",
+ "type": "string"
+ },
+ "preview_hash": {
+ "title": "Preview Hash",
+ "type": "string"
+ },
+ "purge_confirmation": {
+ "title": "Purge Confirmation",
+ "type": "string"
+ },
+ "retention_days": {
+ "title": "Retention Days",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "observed_at",
+ "cutoff",
+ "retention_days",
+ "enabled",
+ "active_hold_count",
+ "counts",
+ "preview_hash",
+ "enable_confirmation",
+ "purge_confirmation"
+ ],
+ "title": "IdentityRetentionPreview",
+ "type": "object"
+}
+```
+
+## IdentityRetentionPurge
+
+```json
+{
+ "properties": {
+ "batch_size": {
+ "default": 500,
+ "maximum": 500.0,
+ "minimum": 1.0,
+ "title": "Batch Size",
+ "type": "integer"
+ },
+ "confirmation": {
+ "title": "Confirmation",
+ "type": "string"
+ },
+ "observed_at": {
+ "format": "date-time",
+ "title": "Observed At",
+ "type": "string"
+ },
+ "preview_hash": {
+ "pattern": "^[a-f0-9]{64}$",
+ "title": "Preview Hash",
+ "type": "string"
+ },
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "observed_at",
+ "preview_hash",
+ "confirmation",
+ "reason"
+ ],
+ "title": "IdentityRetentionPurge",
+ "type": "object"
+}
+```
+
+## IdentityRetentionPurgeResult
+
+```json
+{
+ "properties": {
+ "batch_full": {
+ "title": "Batch Full",
+ "type": "boolean"
+ },
+ "batch_size": {
+ "title": "Batch Size",
+ "type": "integer"
+ },
+ "cutoff": {
+ "format": "date-time",
+ "title": "Cutoff",
+ "type": "string"
+ },
+ "deleted": {
+ "title": "Deleted",
+ "type": "integer"
+ },
+ "policy_revision": {
+ "title": "Policy Revision",
+ "type": "integer"
+ },
+ "status": {
+ "const": "completed",
+ "title": "Status",
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "deleted",
+ "batch_size",
+ "batch_full",
+ "cutoff",
+ "policy_revision"
+ ],
+ "title": "IdentityRetentionPurgeResult",
+ "type": "object"
+}
+```
+
+## IdentityRetentionRead
+
+```json
+{
+ "additionalProperties": false,
+ "properties": {
+ "active_hold_count": {
+ "default": 0,
+ "title": "Active Hold Count",
+ "type": "integer"
+ },
+ "approved_at": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Approved At"
+ },
+ "eligible_event_types": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Eligible Event Types",
+ "type": "array"
+ },
+ "enabled": {
+ "default": false,
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "holds": {
+ "items": {
+ "$ref": "#/components/schemas/IdentityRetentionHold"
+ },
+ "maxItems": 100,
+ "title": "Holds",
+ "type": "array"
+ },
+ "protected_authority_event_types": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Protected Authority Event Types",
+ "type": "array"
+ },
+ "protected_identity_events": {
+ "default": "All other identity event types, including unknown future types, remain retained.",
+ "title": "Protected Identity Events",
+ "type": "string"
+ },
+ "retention_days": {
+ "default": 2555,
+ "maximum": 3650.0,
+ "minimum": 365.0,
+ "title": "Retention Days",
+ "type": "integer"
+ },
+ "revision": {
+ "default": 0,
+ "minimum": 0.0,
+ "title": "Revision",
+ "type": "integer"
+ },
+ "schema_version": {
+ "const": 1,
+ "default": 1,
+ "title": "Schema Version",
+ "type": "integer"
+ },
+ "scope": {
+ "const": "instance",
+ "default": "instance",
+ "title": "Scope",
+ "type": "string"
+ }
+ },
+ "title": "IdentityRetentionRead",
+ "type": "object"
+}
+```
+
+## IdentityRetentionReason
+
+```json
+{
+ "properties": {
+ "reason": {
+ "maxLength": 500,
+ "minLength": 3,
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "reason"
+ ],
+ "title": "IdentityRetentionReason",
+ "type": "object"
+}
+```
+
## IdentitySyncStatus
```json
@@ -32410,6 +32825,16 @@ These are the full generated JSON Schema definitions, including required fields,
```json
{
"properties": {
+ "backlog_count": {
+ "default": 0,
+ "title": "Backlog Count",
+ "type": "integer"
+ },
+ "capacity": {
+ "default": 0,
+ "title": "Capacity",
+ "type": "integer"
+ },
"dead_letter_count": {
"default": 0,
"title": "Dead Letter Count",
@@ -32420,6 +32845,16 @@ These are the full generated JSON Schema definitions, including required fields,
"title": "Dead Letter Limit",
"type": "integer"
},
+ "oldest_pending_age_seconds": {
+ "default": 0,
+ "title": "Oldest Pending Age Seconds",
+ "type": "number"
+ },
+ "outbox_total_count": {
+ "default": 0,
+ "title": "Outbox Total Count",
+ "type": "integer"
+ },
"recent_dead_letters": {
"items": {
"additionalProperties": true,
@@ -32433,6 +32868,13 @@ These are the full generated JSON Schema definitions, including required fields,
"title": "Status",
"type": "string"
},
+ "status_counts": {
+ "additionalProperties": {
+ "type": "integer"
+ },
+ "title": "Status Counts",
+ "type": "object"
+ },
"write_failure_count": {
"default": 0,
"title": "Write Failure Count",
@@ -32824,6 +33266,18 @@ These are the full generated JSON Schema definitions, including required fields,
"title": "Detail",
"type": "object"
},
+ "event_id": {
+ "anyOf": [
+ {
+ "format": "uuid",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Event Id"
+ },
"event_type": {
"title": "Event Type",
"type": "string"
diff --git a/docs/reference/worker-operations.md b/docs/reference/worker-operations.md
index a636f92d3..0874ecfdd 100644
--- a/docs/reference/worker-operations.md
+++ b/docs/reference/worker-operations.md
@@ -21,7 +21,7 @@ Static declarations, not observations of running consumers. Deployment profiles
## beat_schedule
```python
-{'daily-coverage-snapshot': {'task': 'app.worker.tasks.take_coverage_snapshot', 'schedule': crontab(hour=0, minute=5)}, 'daily-agent-eval': {'task': 'app.worker.tasks.run_scheduled_agent_eval', 'schedule': crontab(hour=4, minute=0), 'options': {'queue': 'default'}}, 'weekly-agent-quality-drift': {'task': 'app.worker.tasks.run_weekly_agent_quality_drift', 'schedule': crontab(hour=6, minute=0, day_of_week='monday'), 'options': {'queue': 'default'}}, 'hourly-retention-purge': {'task': 'app.worker.tasks.run_retention_purges', 'schedule': crontab(minute=0)}, 'nightly-search-usage-purge': {'task': 'app.worker.tasks.purge_search_usage_events', 'schedule': crontab(hour=2, minute=40), 'options': {'queue': 'default'}}, 'expire-unlabelled-shadow-pairs': {'task': 'app.worker.tasks.expire_unlabelled_shadow_pairs', 'schedule': crontab(hour=2, minute=50), 'options': {'queue': 'default'}}, 'golden-match-shadow-pairs': {'task': 'app.worker.tasks.golden_match_shadow_pairs', 'schedule': crontab(hour=3, minute=50), 'options': {'queue': 'default'}}, 'reconcile-stale-eval-runs': {'task': 'app.worker.tasks.reconcile_stale_eval_runs', 'schedule': crontab(minute='*/10'), 'options': {'queue': 'default'}}, 'nightly-report-export-sweep': {'task': 'app.worker.tasks.sweep_report_exports', 'schedule': crontab(hour=1, minute=15)}, 'weekly-training-export': {'task': 'app.worker.training_tasks.export_training_data', 'schedule': crontab(hour=2, minute=0, day_of_week='sunday')}, 'daily-finetune-trigger-check': {'task': 'app.worker.training_tasks.check_finetune_trigger', 'schedule': crontab(hour=3, minute=0)}, 'nightly-ml-classifier-training': {'task': 'app.worker.tasks.train_ml_classifier', 'schedule': crontab(hour=3, minute=10), 'kwargs': {'triggered_by': 'beat'}}, 'hourly-search-reindex': {'task': 'app.worker.tasks.reindex_search', 'schedule': crontab(minute=30)}, 'daily-digest-dispatch': {'task': 'app.worker.tasks.dispatch_scheduled_digests', 'schedule': crontab(hour=7, minute=0)}, 'integration-health-probes': {'task': 'app.worker.tasks.run_integration_health_probes', 'schedule': crontab(minute='*/15')}, 'jira-defect-status-sync': {'task': 'app.worker.tasks.sync_jira_defect_statuses', 'schedule': crontab(minute='5-59/15')}, 'knowledge-source-resync': {'task': 'app.worker.tasks.resync_stale_knowledge_sources', 'schedule': crontab(minute=0, hour='*/4')}, 'reconcile-active-releases': {'task': 'app.worker.tasks.reconcile_active_releases', 'schedule': crontab(minute=20)}, 'reconcile-primary-releases': {'task': 'app.worker.tasks.reconcile_primary_releases', 'schedule': crontab(minute=50)}, 'reconcile-release-sort-keys': {'task': 'app.worker.tasks.reconcile_release_sort_keys', 'schedule': crontab(minute=35)}, 'nightly-flaky-confidence-training': {'task': 'app.worker.tasks.train_flaky_confidence_model', 'schedule': crontab(hour=3, minute=30)}, 'close-stale-live-sessions': {'task': 'app.worker.tasks.close_stale_live_sessions', 'schedule': crontab(minute='*/2'), 'kwargs': {'idle_minutes': 5}}, 'reap-stuck-agent-pipelines': {'task': 'app.worker.tasks.reap_stuck_agent_pipelines', 'schedule': crontab(minute='*/10')}, 'relay-agent-child-dispatch-outbox': {'task': 'app.worker.tasks.relay_agent_child_dispatch_outbox', 'schedule': crontab(minute='*')}, 'process-decision-report-supersessions': {'task': 'app.worker.tasks.process_decision_report_supersessions', 'schedule': crontab(minute='*')}, 'relay-agent-action-dispatch-outbox': {'task': 'app.worker.tasks.relay_agent_action_dispatch_outbox', 'schedule': crontab(minute='*')}, 'reap-stuck-agent-actions': {'task': 'app.worker.tasks.reap_stuck_agent_actions', 'schedule': crontab(minute='*/5')}, 'relay-run-downstream-outbox': {'task': 'app.worker.tasks.relay_run_downstream_outbox', 'schedule': crontab(minute='*')}, 'relay-queued-criteria-deletions': {'task': 'app.worker.tasks.relay_queued_criteria_deletions', 'schedule': crontab(minute='*')}, 'sweep-deletion-exports': {'task': 'app.worker.tasks.sweep_deletion_exports', 'schedule': crontab(minute='*/15'), 'options': {'queue': 'default'}}, 'sweep-project-data-jobs': {'task': 'app.worker.tasks.sweep_project_data_jobs', 'schedule': crontab(minute=35), 'options': {'queue': 'default'}}, 'sweep-subject-rights-jobs': {'task': 'app.worker.tasks.sweep_subject_rights_jobs', 'schedule': crontab(minute=50), 'options': {'queue': 'default'}}, 'recover-waiting-run-finalizations': {'task': 'app.worker.tasks.recover_waiting_run_finalizations', 'schedule': crontab(minute='*')}, 'relay-pending-webhook-deliveries': {'task': 'app.worker.tasks.relay_pending_webhook_deliveries', 'schedule': crontab(minute='*')}, 'relay-pending-notification-deliveries': {'task': 'app.worker.tasks.relay_pending_notification_deliveries', 'schedule': crontab(minute='*')}, 'nightly-flaky-quarantine-maintenance': {'task': 'app.worker.tasks.run_flaky_quarantine_maintenance', 'schedule': crontab(hour=QUARANTINE_MAINTENANCE.hour, minute=QUARANTINE_MAINTENANCE.minute), 'options': {'headers': {SCHEDULE_HEADER: QUARANTINE_MAINTENANCE.key}}}, 'nightly-perf-baseline-refresh': {'task': 'app.worker.tasks.refresh_perf_baselines', 'schedule': crontab(hour=PERF_BASELINE_REFRESH.hour, minute=PERF_BASELINE_REFRESH.minute), 'options': {'headers': {SCHEDULE_HEADER: PERF_BASELINE_REFRESH.key}}}, 'monday-weekly-retro-digests': {'task': 'app.worker.tasks.dispatch_scheduled_digests', 'schedule': crontab(hour=7, minute=5, day_of_week='monday')}, 'monday-weekly-flaky-debt-reviews': {'task': 'app.worker.tasks.dispatch_weekly_flaky_debt_reviews', 'schedule': crontab(hour=7, minute=10, day_of_week='monday')}, 'daily-fixer-runs': {'task': 'app.worker.tasks.dispatch_scheduled_fixer_runs', 'schedule': crontab(hour=6, minute=0), 'args': ('daily',)}, 'weekly-fixer-runs': {'task': 'app.worker.tasks.dispatch_scheduled_fixer_runs', 'schedule': crontab(hour=6, minute=15, day_of_week='monday'), 'args': ('weekly',)}, 'poll-fixer-pr-outcomes': {'task': 'app.worker.tasks.poll_fixer_pr_outcomes', 'schedule': crontab(minute='*/30')}, 'nightly-orphan-test-suite-flag': {'task': 'app.worker.tasks.flag_orphan_test_suites', 'schedule': crontab(hour=5, minute=0)}, 'nightly-canonical-deletion-reconcile': {'task': 'app.worker.tasks.reconcile_canonical_deletions', 'schedule': crontab(hour=5, minute=30)}, 'daily-suite-membership-parity': {'task': 'app.worker.tasks.run_suite_membership_parity', 'schedule': crontab(hour=6, minute=15), 'kwargs': {'trigger': 'beat'}, 'options': {'queue': 'default', 'ignore_result': True}}, 'nightly-flaky-classifier-calibration': {'task': 'app.worker.tasks.calibrate_flaky_classifiers', 'schedule': crontab(hour=5, minute=45)}, 'nightly-flaky-score-recompute': {'task': 'app.worker.tasks.recompute_flaky_scores', 'schedule': crontab(hour=6, minute=10)}, 'nightly-systemic-cluster-recompute': {'task': 'app.worker.tasks.recompute_systemic_clusters', 'schedule': crontab(hour=6, minute=40)}, 'screen-new-test-fingerprints': {'task': 'app.worker.tasks.screen_new_test_fingerprints', 'schedule': crontab(minute='*/30')}, 'nightly-flaky-detection-sweep': {'task': 'app.worker.tasks.sweep_flaky_detection', 'schedule': crontab(hour=6, minute=55)}, 'backfill-unassigned-failures': {'task': 'app.worker.tasks.backfill_unassigned_failures', 'schedule': crontab(minute='*/15')}, 'drain-active-live-sessions': {'task': 'app.worker.tasks.drain_active_live_sessions', 'schedule': timedelta(seconds=30)}, 'backfill-placeholder-test-cases': {'task': 'app.worker.tasks.backfill_placeholder_test_cases', 'schedule': crontab(minute=10)}, 'backfill-suite-executions': {'task': 'app.worker.tasks.backfill_suite_executions', 'schedule': crontab(minute='*/10')}, 'backfill-ai-run-versions': {'task': 'app.worker.tasks.backfill_ai_run_versions', 'schedule': crontab(minute='5,15,25,35,45,55')}, 'auto-recover-completed-live-runs': {'task': 'app.worker.tasks.auto_recover_completed_live_runs', 'schedule': timedelta(minutes=2)}, 'nightly-duplicate-detection': {'task': 'app.worker.tasks.run_duplicate_detection', 'schedule': crontab(hour=6, minute=0)}, 'hourly-cross-run-insights': {'task': 'app.worker.tasks.detect_cross_run_insights', 'schedule': crontab(minute=40), 'options': {'queue': 'default'}}, 'quarter-hourly-run-cadence-check': {'task': 'app.worker.tasks.check_run_cadences', 'schedule': crontab(minute='7-59/15'), 'options': {'queue': 'default'}}, 'watch-drop-folders': {'task': 'app.worker.tasks.watch_drop_folders', 'schedule': crontab(minute='*'), 'options': {'queue': 'default'}}}
+{'daily-coverage-snapshot': {'task': 'app.worker.tasks.take_coverage_snapshot', 'schedule': crontab(hour=0, minute=5)}, 'daily-agent-eval': {'task': 'app.worker.tasks.run_scheduled_agent_eval', 'schedule': crontab(hour=4, minute=0), 'options': {'queue': 'default'}}, 'weekly-agent-quality-drift': {'task': 'app.worker.tasks.run_weekly_agent_quality_drift', 'schedule': crontab(hour=6, minute=0, day_of_week='monday'), 'options': {'queue': 'default'}}, 'hourly-retention-purge': {'task': 'app.worker.tasks.run_retention_purges', 'schedule': crontab(minute=0)}, 'nightly-search-usage-purge': {'task': 'app.worker.tasks.purge_search_usage_events', 'schedule': crontab(hour=2, minute=40), 'options': {'queue': 'default'}}, 'expire-unlabelled-shadow-pairs': {'task': 'app.worker.tasks.expire_unlabelled_shadow_pairs', 'schedule': crontab(hour=2, minute=50), 'options': {'queue': 'default'}}, 'golden-match-shadow-pairs': {'task': 'app.worker.tasks.golden_match_shadow_pairs', 'schedule': crontab(hour=3, minute=50), 'options': {'queue': 'default'}}, 'reconcile-stale-eval-runs': {'task': 'app.worker.tasks.reconcile_stale_eval_runs', 'schedule': crontab(minute='*/10'), 'options': {'queue': 'default'}}, 'nightly-report-export-sweep': {'task': 'app.worker.tasks.sweep_report_exports', 'schedule': crontab(hour=1, minute=15)}, 'weekly-training-export': {'task': 'app.worker.training_tasks.export_training_data', 'schedule': crontab(hour=2, minute=0, day_of_week='sunday')}, 'daily-finetune-trigger-check': {'task': 'app.worker.training_tasks.check_finetune_trigger', 'schedule': crontab(hour=3, minute=0)}, 'nightly-ml-classifier-training': {'task': 'app.worker.tasks.train_ml_classifier', 'schedule': crontab(hour=3, minute=10), 'kwargs': {'triggered_by': 'beat'}}, 'hourly-search-reindex': {'task': 'app.worker.tasks.reindex_search', 'schedule': crontab(minute=30)}, 'daily-digest-dispatch': {'task': 'app.worker.tasks.dispatch_scheduled_digests', 'schedule': crontab(hour=7, minute=0)}, 'integration-health-probes': {'task': 'app.worker.tasks.run_integration_health_probes', 'schedule': crontab(minute='*/15')}, 'jira-defect-status-sync': {'task': 'app.worker.tasks.sync_jira_defect_statuses', 'schedule': crontab(minute='5-59/15')}, 'knowledge-source-resync': {'task': 'app.worker.tasks.resync_stale_knowledge_sources', 'schedule': crontab(minute=0, hour='*/4')}, 'reconcile-active-releases': {'task': 'app.worker.tasks.reconcile_active_releases', 'schedule': crontab(minute=20)}, 'reconcile-primary-releases': {'task': 'app.worker.tasks.reconcile_primary_releases', 'schedule': crontab(minute=50)}, 'reconcile-release-sort-keys': {'task': 'app.worker.tasks.reconcile_release_sort_keys', 'schedule': crontab(minute=35)}, 'nightly-flaky-confidence-training': {'task': 'app.worker.tasks.train_flaky_confidence_model', 'schedule': crontab(hour=3, minute=30)}, 'close-stale-live-sessions': {'task': 'app.worker.tasks.close_stale_live_sessions', 'schedule': crontab(minute='*/2'), 'kwargs': {'idle_minutes': 5}}, 'reap-stuck-agent-pipelines': {'task': 'app.worker.tasks.reap_stuck_agent_pipelines', 'schedule': crontab(minute='*/10')}, 'relay-agent-child-dispatch-outbox': {'task': 'app.worker.tasks.relay_agent_child_dispatch_outbox', 'schedule': crontab(minute='*')}, 'process-decision-report-supersessions': {'task': 'app.worker.tasks.process_decision_report_supersessions', 'schedule': crontab(minute='*')}, 'relay-agent-action-dispatch-outbox': {'task': 'app.worker.tasks.relay_agent_action_dispatch_outbox', 'schedule': crontab(minute='*')}, 'reap-stuck-agent-actions': {'task': 'app.worker.tasks.reap_stuck_agent_actions', 'schedule': crontab(minute='*/5')}, 'relay-run-downstream-outbox': {'task': 'app.worker.tasks.relay_run_downstream_outbox', 'schedule': crontab(minute='*')}, 'relay-pipeline-event-outbox': {'task': 'app.worker.tasks.relay_pipeline_event_outbox', 'schedule': crontab(minute='*'), 'options': {'expires': 55}}, 'relay-queued-criteria-deletions': {'task': 'app.worker.tasks.relay_queued_criteria_deletions', 'schedule': crontab(minute='*')}, 'sweep-deletion-exports': {'task': 'app.worker.tasks.sweep_deletion_exports', 'schedule': crontab(minute='*/15'), 'options': {'queue': 'default'}}, 'sweep-project-data-jobs': {'task': 'app.worker.tasks.sweep_project_data_jobs', 'schedule': crontab(minute=35), 'options': {'queue': 'default'}}, 'sweep-subject-rights-jobs': {'task': 'app.worker.tasks.sweep_subject_rights_jobs', 'schedule': crontab(minute=50), 'options': {'queue': 'default'}}, 'recover-waiting-run-finalizations': {'task': 'app.worker.tasks.recover_waiting_run_finalizations', 'schedule': crontab(minute='*')}, 'relay-pending-webhook-deliveries': {'task': 'app.worker.tasks.relay_pending_webhook_deliveries', 'schedule': crontab(minute='*')}, 'relay-pending-notification-deliveries': {'task': 'app.worker.tasks.relay_pending_notification_deliveries', 'schedule': crontab(minute='*')}, 'nightly-flaky-quarantine-maintenance': {'task': 'app.worker.tasks.run_flaky_quarantine_maintenance', 'schedule': crontab(hour=QUARANTINE_MAINTENANCE.hour, minute=QUARANTINE_MAINTENANCE.minute), 'options': {'headers': {SCHEDULE_HEADER: QUARANTINE_MAINTENANCE.key}}}, 'nightly-perf-baseline-refresh': {'task': 'app.worker.tasks.refresh_perf_baselines', 'schedule': crontab(hour=PERF_BASELINE_REFRESH.hour, minute=PERF_BASELINE_REFRESH.minute), 'options': {'headers': {SCHEDULE_HEADER: PERF_BASELINE_REFRESH.key}}}, 'monday-weekly-retro-digests': {'task': 'app.worker.tasks.dispatch_scheduled_digests', 'schedule': crontab(hour=7, minute=5, day_of_week='monday')}, 'monday-weekly-flaky-debt-reviews': {'task': 'app.worker.tasks.dispatch_weekly_flaky_debt_reviews', 'schedule': crontab(hour=7, minute=10, day_of_week='monday')}, 'daily-fixer-runs': {'task': 'app.worker.tasks.dispatch_scheduled_fixer_runs', 'schedule': crontab(hour=6, minute=0), 'args': ('daily',)}, 'weekly-fixer-runs': {'task': 'app.worker.tasks.dispatch_scheduled_fixer_runs', 'schedule': crontab(hour=6, minute=15, day_of_week='monday'), 'args': ('weekly',)}, 'poll-fixer-pr-outcomes': {'task': 'app.worker.tasks.poll_fixer_pr_outcomes', 'schedule': crontab(minute='*/30')}, 'nightly-orphan-test-suite-flag': {'task': 'app.worker.tasks.flag_orphan_test_suites', 'schedule': crontab(hour=5, minute=0)}, 'nightly-canonical-deletion-reconcile': {'task': 'app.worker.tasks.reconcile_canonical_deletions', 'schedule': crontab(hour=5, minute=30)}, 'daily-suite-membership-parity': {'task': 'app.worker.tasks.run_suite_membership_parity', 'schedule': crontab(hour=6, minute=15), 'kwargs': {'trigger': 'beat'}, 'options': {'queue': 'default', 'ignore_result': True}}, 'nightly-flaky-classifier-calibration': {'task': 'app.worker.tasks.calibrate_flaky_classifiers', 'schedule': crontab(hour=5, minute=45)}, 'nightly-flaky-score-recompute': {'task': 'app.worker.tasks.recompute_flaky_scores', 'schedule': crontab(hour=6, minute=10)}, 'nightly-systemic-cluster-recompute': {'task': 'app.worker.tasks.recompute_systemic_clusters', 'schedule': crontab(hour=6, minute=40)}, 'screen-new-test-fingerprints': {'task': 'app.worker.tasks.screen_new_test_fingerprints', 'schedule': crontab(minute='*/30')}, 'nightly-flaky-detection-sweep': {'task': 'app.worker.tasks.sweep_flaky_detection', 'schedule': crontab(hour=6, minute=55)}, 'backfill-unassigned-failures': {'task': 'app.worker.tasks.backfill_unassigned_failures', 'schedule': crontab(minute='*/15')}, 'drain-active-live-sessions': {'task': 'app.worker.tasks.drain_active_live_sessions', 'schedule': timedelta(seconds=30)}, 'backfill-placeholder-test-cases': {'task': 'app.worker.tasks.backfill_placeholder_test_cases', 'schedule': crontab(minute=10)}, 'backfill-suite-executions': {'task': 'app.worker.tasks.backfill_suite_executions', 'schedule': crontab(minute='*/10')}, 'backfill-ai-run-versions': {'task': 'app.worker.tasks.backfill_ai_run_versions', 'schedule': crontab(minute='5,15,25,35,45,55')}, 'auto-recover-completed-live-runs': {'task': 'app.worker.tasks.auto_recover_completed_live_runs', 'schedule': timedelta(minutes=2)}, 'nightly-duplicate-detection': {'task': 'app.worker.tasks.run_duplicate_detection', 'schedule': crontab(hour=6, minute=0)}, 'hourly-cross-run-insights': {'task': 'app.worker.tasks.detect_cross_run_insights', 'schedule': crontab(minute=40), 'options': {'queue': 'default'}}, 'quarter-hourly-run-cadence-check': {'task': 'app.worker.tasks.check_run_cadences', 'schedule': crontab(minute='7-59/15'), 'options': {'queue': 'default'}}, 'watch-drop-folders': {'task': 'app.worker.tasks.watch_drop_folders', 'schedule': crontab(minute='*'), 'options': {'queue': 'default'}}}
```
## worker_prefetch_multiplier
@@ -363,10 +363,21 @@ celery_app.task(name='app.worker.tasks.relay_run_downstream_outbox', bind=True,
relay_run_downstream_outbox(self)
```
-## relay_queued_criteria_deletions
+## relay_pipeline_event_outbox
[backend/app/worker/tasks.py:3237](../../backend/app/worker/tasks.py#L3237)
+Materialize accepted operational evidence in bounded retry batches.
+
+```python
+celery_app.task(name='app.worker.tasks.relay_pipeline_event_outbox', bind=True, max_retries=0, queue='default', time_limit=40)
+relay_pipeline_event_outbox(self)
+```
+
+## relay_queued_criteria_deletions
+
+[backend/app/worker/tasks.py:3252](../../backend/app/worker/tasks.py#L3252)
+
Recover criteria deletions committed before broker publication.
```python
@@ -376,7 +387,7 @@ relay_queued_criteria_deletions(self)
## recover_waiting_run_finalizations
-[backend/app/worker/tasks.py:3252](../../backend/app/worker/tasks.py#L3252)
+[backend/app/worker/tasks.py:3267](../../backend/app/worker/tasks.py#L3267)
Resume finalization after a worker died before opening its child gate.
@@ -387,7 +398,7 @@ recover_waiting_run_finalizations(self)
## relay_pending_webhook_deliveries
-[backend/app/worker/tasks.py:3276](../../backend/app/worker/tasks.py#L3276)
+[backend/app/worker/tasks.py:3291](../../backend/app/worker/tasks.py#L3291)
Republish webhook rows stranded before broker acceptance.
@@ -398,7 +409,7 @@ relay_pending_webhook_deliveries(self)
## relay_pending_notification_deliveries
-[backend/app/worker/tasks.py:3300](../../backend/app/worker/tasks.py#L3300)
+[backend/app/worker/tasks.py:3315](../../backend/app/worker/tasks.py#L3315)
Deliver and retry durable per-channel notification children.
@@ -409,7 +420,7 @@ relay_pending_notification_deliveries(self)
## execute_agent_action
-[backend/app/worker/tasks.py:3326](../../backend/app/worker/tasks.py#L3326)
+[backend/app/worker/tasks.py:3341](../../backend/app/worker/tasks.py#L3341)
Resolve and consume one action; unregistered effects fail closed.
@@ -420,7 +431,7 @@ execute_agent_action(self, project_id: str, action_id: str)
## reap_stuck_agent_actions
-[backend/app/worker/tasks.py:3355](../../backend/app/worker/tasks.py#L3355)
+[backend/app/worker/tasks.py:3370](../../backend/app/worker/tasks.py#L3370)
Settle agent actions whose executor died after its claim (W15 AGT-03, D-13).
@@ -438,7 +449,7 @@ reap_stuck_agent_actions(self)
## run_fixer_run_task
-[backend/app/worker/tasks.py:3396](../../backend/app/worker/tasks.py#L3396)
+[backend/app/worker/tasks.py:3411](../../backend/app/worker/tasks.py#L3411)
Background task: execute one budgeted Fixer run (AI-2).
@@ -453,7 +464,7 @@ run_fixer_run_task(self, project_id: str, fixer_run_id: str, triggered_by: str='
## dispatch_scheduled_fixer_runs
-[backend/app/worker/tasks.py:3432](../../backend/app/worker/tasks.py#L3432)
+[backend/app/worker/tasks.py:3447](../../backend/app/worker/tasks.py#L3447)
Beat: enqueue a Fixer run for every project whose fixer policy is
enabled with ``schedule == `` (daily|weekly). Each run re-checks
@@ -468,7 +479,7 @@ dispatch_scheduled_fixer_runs(self, schedule: str)
## poll_fixer_pr_outcomes
-[backend/app/worker/tasks.py:3501](../../backend/app/worker/tasks.py#L3501)
+[backend/app/worker/tasks.py:3516](../../backend/app/worker/tasks.py#L3516)
Beat: poll open fixer-created PRs; merged → record_fix_outcome(fixed),
closed-unmerged → not_fixed (AI-5 feedback loop). No-op offline.
@@ -483,7 +494,7 @@ poll_fixer_pr_outcomes(self)
## generate_run_compare_report
-[backend/app/worker/tasks.py:3524](../../backend/app/worker/tasks.py#L3524)
+[backend/app/worker/tasks.py:3539](../../backend/app/worker/tasks.py#L3539)
Generate and cache the AI report for a deterministic run comparison.
@@ -494,7 +505,7 @@ generate_run_compare_report(self, project_id: str, left_run_id: str, right_run_i
## precompute_suite_comparisons_for_run
-[backend/app/worker/tasks.py:3623](../../backend/app/worker/tasks.py#L3623)
+[backend/app/worker/tasks.py:3638](../../backend/app/worker/tasks.py#L3638)
Precompute default latest-vs-previous suite comparison reports after nightly runs.
@@ -505,7 +516,7 @@ precompute_suite_comparisons_for_run(self, test_run_id: str, project_id: str)
## dispatch_ai_summary_email
-[backend/app/worker/tasks.py:3812](../../backend/app/worker/tasks.py#L3812)
+[backend/app/worker/tasks.py:3827](../../backend/app/worker/tasks.py#L3827)
EM-1: Send AI executive-summary email after the pipeline completes.
@@ -520,7 +531,7 @@ dispatch_ai_summary_email(self, test_run_id: str, project_id: str, build_number:
## notify_release_decision_no_go
-[backend/app/worker/tasks.py:4129](../../backend/app/worker/tasks.py#L4129)
+[backend/app/worker/tasks.py:4144](../../backend/app/worker/tasks.py#L4144)
W09 NTF-01: stage "Quality gate failed" for a run the deep pipeline
published as NO_GO.
@@ -544,7 +555,7 @@ notify_release_decision_no_go(self, run_id: str, pipeline_run_id: str | None=Non
## generate_ai_test_cases_task
-[backend/app/worker/tasks.py:4177](../../backend/app/worker/tasks.py#L4177)
+[backend/app/worker/tasks.py:4192](../../backend/app/worker/tasks.py#L4192)
Background task: run LLM test-case generation and persist results to DB.
Enqueued by POST /cases/ai-generate/async — fires immediately and returns,
@@ -557,7 +568,7 @@ generate_ai_test_cases_task(self, requirements: str, project_id: str, author_id:
## create_ai_test_plan_task
-[backend/app/worker/tasks.py:4311](../../backend/app/worker/tasks.py#L4311)
+[backend/app/worker/tasks.py:4326](../../backend/app/worker/tasks.py#L4326)
Background task: run LLM plan optimisation and persist the test plan to DB.
@@ -568,7 +579,7 @@ create_ai_test_plan_task(self, project_id: str, author_id: str, plan_name: str |
## generate_ai_strategy_task
-[backend/app/worker/tasks.py:4428](../../backend/app/worker/tasks.py#L4428)
+[backend/app/worker/tasks.py:4443](../../backend/app/worker/tasks.py#L4443)
Background task: run LLM strategy generation and persist to DB.
@@ -579,7 +590,7 @@ generate_ai_strategy_task(self, project_id: str, author_id: str, project_context
## take_coverage_snapshot
-[backend/app/worker/tasks.py:4495](../../backend/app/worker/tasks.py#L4495)
+[backend/app/worker/tasks.py:4510](../../backend/app/worker/tasks.py#L4510)
Scheduled task (beat 00:05 UTC): one coverage snapshot a project a UTC day (W08 TRND-07).
@@ -601,7 +612,7 @@ take_coverage_snapshot(project_id: str | None=None)
## reindex_search
-[backend/app/worker/tasks.py:4555](../../backend/app/worker/tasks.py#L4555)
+[backend/app/worker/tasks.py:4570](../../backend/app/worker/tasks.py#L4570)
Background task: reindex test cases into ChromaDB for semantic search.
Uses incremental indexing by default; pass full=True for complete rebuild.
@@ -613,7 +624,7 @@ reindex_search(self, project_id: str | None=None, full: bool=False)
## rebuild_embedding_generation
-[backend/app/worker/tasks.py:4859](../../backend/app/worker/tasks.py#L4859)
+[backend/app/worker/tasks.py:4874](../../backend/app/worker/tasks.py#L4874)
Build the TARGET embedding generation, one ≤ 480 s slice per invocation.
@@ -630,7 +641,7 @@ rebuild_embedding_generation(self, generation_tag: str, fence: int)
## retire_embedding_generations
-[backend/app/worker/tasks.py:4984](../../backend/app/worker/tasks.py#L4984)
+[backend/app/worker/tasks.py:4999](../../backend/app/worker/tasks.py#L4999)
Drop the collections of generations retired ≥ RETIRE_GRACE_SECONDS ago.
@@ -646,7 +657,7 @@ retire_embedding_generations(self)
## purge_search_usage_events
-[backend/app/worker/tasks.py:5024](../../backend/app/worker/tasks.py#L5024)
+[backend/app/worker/tasks.py:5039](../../backend/app/worker/tasks.py#L5039)
Nightly: delete ``search_query_events`` older than the fixed 30-day window.
@@ -661,7 +672,7 @@ purge_search_usage_events(self)
## sync_knowledge_source
-[backend/app/worker/tasks.py:5040](../../backend/app/worker/tasks.py#L5040)
+[backend/app/worker/tasks.py:5055](../../backend/app/worker/tasks.py#L5055)
Fetch content for a KnowledgeSource, chunk, index in ChromaDB, and update sync state.
@@ -672,7 +683,7 @@ sync_knowledge_source(self, source_id: str, trigger: str='manual')
## resync_stale_knowledge_sources
-[backend/app/worker/tasks.py:5069](../../backend/app/worker/tasks.py#L5069)
+[backend/app/worker/tasks.py:5084](../../backend/app/worker/tasks.py#L5084)
Periodic task: find stale/failed sources and enqueue individual sync tasks.
@@ -691,7 +702,7 @@ resync_stale_knowledge_sources(self)
## refresh_perf_baselines
-[backend/app/worker/tasks.py:5125](../../backend/app/worker/tasks.py#L5125)
+[backend/app/worker/tasks.py:5140](../../backend/app/worker/tasks.py#L5140)
Nightly sweep that extends each per-test duration baseline with
the newest observations from the TestCase table.
@@ -705,7 +716,7 @@ refresh_perf_baselines(self)
## deliver_webhook
-[backend/app/worker/tasks.py:5160](../../backend/app/worker/tasks.py#L5160)
+[backend/app/worker/tasks.py:5175](../../backend/app/worker/tasks.py#L5175)
Deliver a single webhook subscription event.
@@ -721,7 +732,7 @@ deliver_webhook(self, delivery_id: str, dispatch_token: str | None=None)
## run_flaky_quarantine_maintenance
-[backend/app/worker/tasks.py:5220](../../backend/app/worker/tasks.py#L5220)
+[backend/app/worker/tasks.py:5235](../../backend/app/worker/tasks.py#L5235)
Nightly housekeeping for the flaky auto-quarantine workflow.
@@ -751,7 +762,7 @@ run_flaky_quarantine_maintenance(self)
## train_flaky_confidence_model
-[backend/app/worker/tasks.py:5293](../../backend/app/worker/tasks.py#L5293)
+[backend/app/worker/tasks.py:5308](../../backend/app/worker/tasks.py#L5308)
Nightly retrain of the FLK-P3 flaky-confidence model from human
quarantine approve/reject decisions.
@@ -770,7 +781,7 @@ train_flaky_confidence_model(self)
## train_ml_classifier
-[backend/app/worker/tasks.py:5335](../../backend/app/worker/tasks.py#L5335)
+[backend/app/worker/tasks.py:5350](../../backend/app/worker/tasks.py#L5350)
Train the failure classifier once (``services/ml/trainer.train_classifier``).
@@ -792,7 +803,7 @@ train_ml_classifier(self, triggered_by: str='beat')
## run_integration_health_probes
-[backend/app/worker/tasks.py:5447](../../backend/app/worker/tasks.py#L5447)
+[backend/app/worker/tasks.py:5462](../../backend/app/worker/tasks.py#L5462)
Periodic task: probe all configured integrations and record health status.
@@ -808,7 +819,7 @@ run_integration_health_probes(self)
## enrich_run_ocp_metadata
-[backend/app/worker/tasks.py:5489](../../backend/app/worker/tasks.py#L5489)
+[backend/app/worker/tasks.py:5504](../../backend/app/worker/tasks.py#L5504)
Fetch the OpenShift pod metadata of a run the sentinel ingest committed.
@@ -827,7 +838,7 @@ enrich_run_ocp_metadata(self, run_id: str)
## sync_jira_defect_statuses
-[backend/app/worker/tasks.py:5538](../../backend/app/worker/tasks.py#L5538)
+[backend/app/worker/tasks.py:5553](../../backend/app/worker/tasks.py#L5553)
Periodic task: mirror Jira issue status onto linked OPEN defects.
@@ -844,7 +855,7 @@ sync_jira_defect_statuses(self)
## dispatch_scheduled_digests
-[backend/app/worker/tasks.py:5571](../../backend/app/worker/tasks.py#L5571)
+[backend/app/worker/tasks.py:5586](../../backend/app/worker/tasks.py#L5586)
Periodic task: find all digest subscriptions due for delivery and dispatch.
@@ -859,7 +870,7 @@ dispatch_scheduled_digests(self)
## dispatch_weekly_flaky_debt_reviews
-[backend/app/worker/tasks.py:6035](../../backend/app/worker/tasks.py#L6035)
+[backend/app/worker/tasks.py:6050](../../backend/app/worker/tasks.py#L6050)
Weekly beat (Mondays 07:10 UTC): send each channel-mapped team its
flaky-debt review draft through its team notification channel. Teams
@@ -879,7 +890,7 @@ dispatch_weekly_flaky_debt_reviews(self)
## close_stale_live_sessions
-[backend/app/worker/tasks.py:6071](../../backend/app/worker/tasks.py#L6071)
+[backend/app/worker/tasks.py:6086](../../backend/app/worker/tasks.py#L6086)
Periodic safety net for live sessions whose clients forget to send a
``run_complete`` event.
@@ -905,7 +916,7 @@ close_stale_live_sessions(self, idle_minutes: int=15)
## reap_stuck_agent_pipelines
-[backend/app/worker/tasks.py:6201](../../backend/app/worker/tasks.py#L6201)
+[backend/app/worker/tasks.py:6216](../../backend/app/worker/tasks.py#L6216)
Reclaim pipelines whose worker stopped renewing its lease (E7.3).
@@ -935,7 +946,7 @@ reap_stuck_agent_pipelines(self, stale_minutes: int=30)
## flag_orphan_test_suites
-[backend/app/worker/tasks.py:6362](../../backend/app/worker/tasks.py#L6362)
+[backend/app/worker/tasks.py:6377](../../backend/app/worker/tasks.py#L6377)
Detect and structured-log orphan ``TestSuite`` rows for ops review.
@@ -965,7 +976,7 @@ flag_orphan_test_suites(self, min_age_minutes: int=60)
## reconcile_canonical_deletions
-[backend/app/worker/tasks.py:6461](../../backend/app/worker/tasks.py#L6461)
+[backend/app/worker/tasks.py:6476](../../backend/app/worker/tasks.py#L6476)
Nightly safety net for canonical-deletion detection (Phase I follow-up).
@@ -992,7 +1003,7 @@ reconcile_canonical_deletions(self)
## drain_active_live_sessions
-[backend/app/worker/tasks.py:6544](../../backend/app/worker/tasks.py#L6544)
+[backend/app/worker/tasks.py:6559](../../backend/app/worker/tasks.py#L6559)
Phase 4.5 — drain every active live session's Redis event buffer
into Postgres ``test_cases`` rows.
@@ -1014,7 +1025,7 @@ drain_active_live_sessions(self)
## backfill_placeholder_test_cases
-[backend/app/worker/tasks.py:6575](../../backend/app/worker/tasks.py#L6575)
+[backend/app/worker/tasks.py:6590](../../backend/app/worker/tasks.py#L6590)
Retroactively synthesize placeholder TestCase rows.
@@ -1038,7 +1049,7 @@ backfill_placeholder_test_cases(self, max_runs_per_project: int=500)
## backfill_suite_executions
-[backend/app/worker/tasks.py:6631](../../backend/app/worker/tasks.py#L6631)
+[backend/app/worker/tasks.py:6646](../../backend/app/worker/tasks.py#L6646)
EXEC-02: time every run that predates ``suite_executions`` -- one-shot, chunked, re-entrant.
@@ -1063,7 +1074,7 @@ backfill_suite_executions(self, chunk_size: int=500, max_chunks: int=40, time_bu
## backfill_ai_run_versions
-[backend/app/worker/tasks.py:6815](../../backend/app/worker/tasks.py#L6815)
+[backend/app/worker/tasks.py:6830](../../backend/app/worker/tasks.py#L6830)
AIH-01: give every run analysed before AI history existed its first versions -- one-shot,
chunked, re-entrant.
@@ -1089,7 +1100,7 @@ backfill_ai_run_versions(self, chunk_size: int=100, max_chunks: int=40, time_bud
## auto_recover_completed_live_runs
-[backend/app/worker/tasks.py:6852](../../backend/app/worker/tasks.py#L6852)
+[backend/app/worker/tasks.py:6867](../../backend/app/worker/tasks.py#L6867)
Recover REAL per-test rows from ``TestRun.event_archive`` for
completed live_stream runs whose ``test_cases`` table is empty.
@@ -1114,7 +1125,7 @@ auto_recover_completed_live_runs(self, lookback_hours: int=24, max_runs: int=100
## backfill_unassigned_failures
-[backend/app/worker/tasks.py:6923](../../backend/app/worker/tasks.py#L6923)
+[backend/app/worker/tasks.py:6938](../../backend/app/worker/tasks.py#L6938)
Retroactively assign FAILED/BROKEN TestCases left unassigned.
@@ -1139,7 +1150,7 @@ backfill_unassigned_failures(self, max_runs_per_project: int=200)
## notify_test_suite_owner
-[backend/app/worker/tasks.py:7047](../../backend/app/worker/tasks.py#L7047)
+[backend/app/worker/tasks.py:7062](../../backend/app/worker/tasks.py#L7062)
Dispatch the "test is failing repeatedly" notification email.
@@ -1154,7 +1165,7 @@ notify_test_suite_owner(self, *, to_email: str, owner_name: str, test_name: str,
## run_duplicate_detection
-[backend/app/worker/tasks.py:7146](../../backend/app/worker/tasks.py#L7146)
+[backend/app/worker/tasks.py:7161](../../backend/app/worker/tasks.py#L7161)
Phase 4 — tiered duplicate authored-test-case detection per project.
@@ -1183,7 +1194,7 @@ run_duplicate_detection(self, project_id: str | None=None, enable_semantic: bool
## persist_ai_eval_shadow_pair
-[backend/app/worker/tasks.py:7473](../../backend/app/worker/tasks.py#L7473)
+[backend/app/worker/tasks.py:7488](../../backend/app/worker/tasks.py#L7488)
Persist one sampled live pair as a pending labelling candidate.
@@ -1194,7 +1205,7 @@ persist_ai_eval_shadow_pair(self, *, project_id: str, agent_id: str, sample_key:
## run_scheduled_agent_eval
-[backend/app/worker/tasks.py:7518](../../backend/app/worker/tasks.py#L7518)
+[backend/app/worker/tasks.py:7533](../../backend/app/worker/tasks.py#L7533)
Evaluate the agent stack against the golden datasets, on a schedule (F-11).
@@ -1218,7 +1229,7 @@ run_scheduled_agent_eval(self, change_id: str | None=None)
## run_weekly_agent_quality_drift
-[backend/app/worker/tasks.py:7609](../../backend/app/worker/tasks.py#L7609)
+[backend/app/worker/tasks.py:7624](../../backend/app/worker/tasks.py#L7624)
Run G5 and commit capability review pins once each Monday.
@@ -1229,7 +1240,7 @@ run_weekly_agent_quality_drift(self)
## run_candidate_evaluation
-[backend/app/worker/tasks.py:7703](../../backend/app/worker/tasks.py#L7703)
+[backend/app/worker/tasks.py:7718](../../backend/app/worker/tasks.py#L7718)
Replay one queued candidate evaluation (W16 AGT-09 b).
@@ -1245,7 +1256,7 @@ run_candidate_evaluation(self, run_id: str)
## reconcile_stale_eval_runs
-[backend/app/worker/tasks.py:7743](../../backend/app/worker/tasks.py#L7743)
+[backend/app/worker/tasks.py:7758](../../backend/app/worker/tasks.py#L7758)
Every 10 min: a replay silent for 15 min -> ``partial`` / ``worker_lost``;
a ``queued`` one never delivered -> ``failed``. Never re-dispatched.
@@ -1257,7 +1268,7 @@ reconcile_stale_eval_runs(self)
## golden_match_shadow_pairs
-[backend/app/worker/tasks.py:7776](../../backend/app/worker/tasks.py#L7776)
+[backend/app/worker/tasks.py:7791](../../backend/app/worker/tasks.py#L7791)
Nightly (03:50 UTC, after the 03:10 ML training): label pending
``root_cause:`` shadow pairs from the test case's OWN human feedback
@@ -1270,7 +1281,7 @@ golden_match_shadow_pairs(self)
## expire_unlabelled_shadow_pairs
-[backend/app/worker/tasks.py:7809](../../backend/app/worker/tasks.py#L7809)
+[backend/app/worker/tasks.py:7824](../../backend/app/worker/tasks.py#L7824)
Nightly (02:50 UTC, after the 02:40 search-usage purge): delete PENDING
shadow pairs older than 30 days, deployment-wide, in committed batches
@@ -1283,7 +1294,7 @@ expire_unlabelled_shadow_pairs(self)
## generate_report_export
-[backend/app/worker/tasks.py:7827](../../backend/app/worker/tasks.py#L7827)
+[backend/app/worker/tasks.py:7842](../../backend/app/worker/tasks.py#L7842)
VIZ-607: render one background report export and store the file.
@@ -1301,7 +1312,7 @@ generate_report_export(export_id: str)
## sweep_report_exports
-[backend/app/worker/tasks.py:7843](../../backend/app/worker/tasks.py#L7843)
+[backend/app/worker/tasks.py:7858](../../backend/app/worker/tasks.py#L7858)
VIZ-607: delete report export files and rows past their 7 days.
@@ -1314,7 +1325,7 @@ sweep_report_exports()
## run_retention_purges
-[backend/app/worker/tasks.py:7863](../../backend/app/worker/tasks.py#L7863)
+[backend/app/worker/tasks.py:7878](../../backend/app/worker/tasks.py#L7878)
Hourly retention purge sweep (the ``:00`` beat), or a single-project
execute-mode purge when enqueued from the router with ``project_id``.
@@ -1332,7 +1343,7 @@ run_retention_purges(self, project_id: str | None=None)
## calibrate_flaky_classifiers
-[backend/app/worker/tasks.py:7891](../../backend/app/worker/tasks.py#L7891)
+[backend/app/worker/tasks.py:7917](../../backend/app/worker/tasks.py#L7917)
Measure how well the flaky classifier actually works, per project.
@@ -1351,7 +1362,7 @@ calibrate_flaky_classifiers(self, project_id: str | None=None)
## recompute_flaky_scores
-[backend/app/worker/tasks.py:7965](../../backend/app/worker/tasks.py#L7965)
+[backend/app/worker/tasks.py:7991](../../backend/app/worker/tasks.py#L7991)
Recompute the continuous flakiness score per project (roadmap Phase 2).
@@ -1369,7 +1380,7 @@ recompute_flaky_scores(self, project_id: str | None=None)
## recompute_systemic_clusters
-[backend/app/worker/tasks.py:8030](../../backend/app/worker/tasks.py#L8030)
+[backend/app/worker/tasks.py:8056](../../backend/app/worker/tasks.py#L8056)
Rebuild systemic co-failure clusters per project (roadmap Phase 3).
@@ -1386,7 +1397,7 @@ recompute_systemic_clusters(self, project_id: str | None=None)
## screen_new_test_fingerprints
-[backend/app/worker/tasks.py:8111](../../backend/app/worker/tasks.py#L8111)
+[backend/app/worker/tasks.py:8137](../../backend/app/worker/tasks.py#L8137)
Tier 1 of roadmap Phase 6: screen the new and directly-modified.
@@ -1408,7 +1419,7 @@ screen_new_test_fingerprints(self, project_id: str | None=None)
## sweep_flaky_detection
-[backend/app/worker/tasks.py:8194](../../backend/app/worker/tasks.py#L8194)
+[backend/app/worker/tasks.py:8220](../../backend/app/worker/tasks.py#L8220)
Tier 2 of roadmap Phase 6: the continuous whole-corpus pass.
@@ -1431,7 +1442,7 @@ sweep_flaky_detection(self, project_id: str | None=None)
## delete_run_everywhere
-[backend/app/worker/tasks.py:8275](../../backend/app/worker/tasks.py#L8275)
+[backend/app/worker/tasks.py:8301](../../backend/app/worker/tasks.py#L8301)
Delete ONE run across all five stores. Irreversible.
@@ -1461,7 +1472,7 @@ delete_run_everywhere(self, run_id: str, job_id: str | None=None, reason: str=''
## sweep_deletion_exports
-[backend/app/worker/tasks.py:8574](../../backend/app/worker/tasks.py#L8574)
+[backend/app/worker/tasks.py:8600](../../backend/app/worker/tasks.py#L8600)
The export janitor (W22b ACT-03 E-10, every 15 minutes): expire
uncollected archives (their jobs end ``expired``, nothing deleted), fail
@@ -1475,7 +1486,7 @@ sweep_deletion_exports(self)
## execute_criteria_deletion_task
-[backend/app/worker/tasks.py:8592](../../backend/app/worker/tasks.py#L8592)
+[backend/app/worker/tasks.py:8618](../../backend/app/worker/tasks.py#L8618)
Replay a frozen candidate set, one run at a time.
@@ -1497,7 +1508,7 @@ execute_criteria_deletion_task(self, job_id: str, project_id: str, requested_by_
## reconcile_active_releases
-[backend/app/worker/tasks.py:8892](../../backend/app/worker/tasks.py#L8892)
+[backend/app/worker/tasks.py:8918](../../backend/app/worker/tasks.py#L8918)
Sweep for projects with no active release, repair them, and REPORT.
@@ -1525,7 +1536,7 @@ reconcile_active_releases(self)
## reconcile_primary_releases
-[backend/app/worker/tasks.py:8984](../../backend/app/worker/tasks.py#L8984)
+[backend/app/worker/tasks.py:9010](../../backend/app/worker/tasks.py#L9010)
Repair drift between ``test_runs.primary_release_id`` and the link table.
@@ -1547,7 +1558,7 @@ reconcile_primary_releases(self)
## reconcile_release_sort_keys
-[backend/app/worker/tasks.py:9071](../../backend/app/worker/tasks.py#L9071)
+[backend/app/worker/tasks.py:9097](../../backend/app/worker/tasks.py#L9097)
Fill in ``releases.sort_key`` for rows that have none.
@@ -1570,7 +1581,7 @@ reconcile_release_sort_keys(self)
## run_agent_invocation
-[backend/app/worker/tasks.py:9140](../../backend/app/worker/tasks.py#L9140)
+[backend/app/worker/tasks.py:9166](../../backend/app/worker/tasks.py#L9166)
Run one agent invoked through ``POST /api/v1/agents/{agent_id}/invoke`` (E1.2).
@@ -1587,7 +1598,7 @@ run_agent_invocation(self, invocation_id: str)
## detect_cross_run_insights
-[backend/app/worker/tasks.py:9405](../../backend/app/worker/tasks.py#L9405)
+[backend/app/worker/tasks.py:9431](../../backend/app/worker/tasks.py#L9431)
Scheduled task (beat, hourly at :40): the cross-run insights (W23a FAIL-11).
@@ -1604,7 +1615,7 @@ detect_cross_run_insights(self)
## check_run_cadences
-[backend/app/worker/tasks.py:9434](../../backend/app/worker/tasks.py#L9434)
+[backend/app/worker/tasks.py:9460](../../backend/app/worker/tasks.py#L9460)
Scheduled task (beat, every 15 min at :07 / :22 / :37 / :52): the
expected run cadences (W23a TRND-03).
@@ -1622,7 +1633,7 @@ check_run_cadences(self)
## export_project_data
-[backend/app/worker/tasks.py:9461](../../backend/app/worker/tasks.py#L9461)
+[backend/app/worker/tasks.py:9487](../../backend/app/worker/tasks.py#L9487)
Build, sign, store and verify one project export (``project_data_jobs`` row ``job_id``).
@@ -1639,7 +1650,7 @@ export_project_data(job_id: str)
## import_project_data
-[backend/app/worker/tasks.py:9475](../../backend/app/worker/tasks.py#L9475)
+[backend/app/worker/tasks.py:9501](../../backend/app/worker/tasks.py#L9501)
Import one uploaded export as a NEW project, in ONE transaction (``project_data_jobs`` row ``job_id``).
Claim-guarded like the export; a failure rolls the whole project back and is recorded on the row.
@@ -1651,7 +1662,7 @@ import_project_data(job_id: str)
## sweep_project_data_jobs
-[backend/app/worker/tasks.py:9484](../../backend/app/worker/tasks.py#L9484)
+[backend/app/worker/tasks.py:9510](../../backend/app/worker/tasks.py#L9510)
The project-data janitor (hourly at :35): expire exports past 72 hours (the ONLY expiry path),
remove uploads and objects no job may keep, fail jobs a dead worker left ``running``, re-send jobs
@@ -1664,7 +1675,7 @@ sweep_project_data_jobs()
## run_suite_membership_parity
-[backend/app/worker/tasks.py:9508](../../backend/app/worker/tasks.py#L9508)
+[backend/app/worker/tasks.py:9534](../../backend/app/worker/tasks.py#L9534)
Compare the legacy suite memberships with the canonical model (beat daily at 06:15 UTC, or "Compare now").
@@ -1682,7 +1693,7 @@ run_suite_membership_parity(self, trigger: str='beat', requested_by_id: str | No
## export_subject_data
-[backend/app/worker/tasks.py:9536](../../backend/app/worker/tasks.py#L9536)
+[backend/app/worker/tasks.py:9562](../../backend/app/worker/tasks.py#L9562)
Build, sign, store and verify one person's data export (``subject_rights_jobs`` row ``job_id``).
@@ -1697,7 +1708,7 @@ export_subject_data(job_id: str)
## erase_subject_data
-[backend/app/worker/tasks.py:9548](../../backend/app/worker/tasks.py#L9548)
+[backend/app/worker/tasks.py:9574](../../backend/app/worker/tasks.py#L9574)
Run the erasure phases after the lock-out (``subject_rights_jobs`` row ``job_id``): Postgres, objects,
Redis, done — each committed on the job row, each idempotent. Claim-guarded; a phase that raises leaves the
@@ -1710,7 +1721,7 @@ erase_subject_data(job_id: str)
## sweep_subject_rights_jobs
-[backend/app/worker/tasks.py:9558](../../backend/app/worker/tasks.py#L9558)
+[backend/app/worker/tasks.py:9584](../../backend/app/worker/tasks.py#L9584)
The subject-rights janitor (hourly at :50): expire exports past 72 hours (the ONLY expiry path), remove
the objects of failed / expired exports, fail an export a dead worker left ``running``, re-send a queued
@@ -1723,7 +1734,7 @@ sweep_subject_rights_jobs()
## watch_drop_folders
-[backend/app/worker/tasks.py:9721](../../backend/app/worker/tasks.py#L9721)
+[backend/app/worker/tasks.py:9747](../../backend/app/worker/tasks.py#L9747)
Scheduled task (beat, every minute): the drop-folder polling watcher (W34 STRAT-13).
diff --git a/infra/audit-archive/iam-policies.example.json b/infra/audit-archive/iam-policies.example.json
new file mode 100644
index 000000000..e12f3c032
--- /dev/null
+++ b/infra/audit-archive/iam-policies.example.json
@@ -0,0 +1,310 @@
+{
+ "instructions": "EXAMPLE ONLY. Replace every __PLACEHOLDER__, validate with the provider and deploy in an independent storage account. Identity policies attach to separate dedicated roles; bucket_guard is a bucket policy. Do not apply this file as one AWS policy.",
+ "archive_writer": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "InspectArchiveBucket",
+ "Effect": "Allow",
+ "Action": [
+ "s3:GetBucketVersioning",
+ "s3:GetBucketObjectLockConfiguration"
+ ],
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__"
+ },
+ {
+ "Sid": "AppendConditionalEncryptedArchive",
+ "Effect": "Allow",
+ "Action": "s3:PutObject",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "Null": {
+ "s3:if-none-match": "false"
+ },
+ "StringEquals": {
+ "s3:x-amz-server-side-encryption": "aws:kms",
+ "s3:x-amz-server-side-encryption-aws-kms-key-id": "__ARCHIVE_KMS_KEY_ARN__",
+ "s3:object-lock-mode": "COMPLIANCE",
+ "s3:object-lock-legal-hold": "ON"
+ },
+ "NumericGreaterThanEquals": {
+ "s3:object-lock-remaining-retention-days": "__MIN_RETENTION_DAYS__"
+ },
+ "NumericLessThanEquals": {
+ "s3:object-lock-remaining-retention-days": "__MAX_RETENTION_DAYS__"
+ }
+ }
+ },
+ {
+ "Sid": "SetComplianceRetention",
+ "Effect": "Allow",
+ "Action": "s3:PutObjectRetention",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "StringEquals": {
+ "s3:object-lock-mode": "COMPLIANCE"
+ },
+ "NumericGreaterThanEquals": {
+ "s3:object-lock-remaining-retention-days": "__MIN_RETENTION_DAYS__"
+ },
+ "NumericLessThanEquals": {
+ "s3:object-lock-remaining-retention-days": "__MAX_RETENTION_DAYS__"
+ }
+ }
+ },
+ {
+ "Sid": "PlaceHoldOnly",
+ "Effect": "Allow",
+ "Action": "s3:PutObjectLegalHold",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "StringEquals": {
+ "s3:object-lock-legal-hold": "ON"
+ }
+ }
+ },
+ {
+ "Sid": "ReadProtectionMetadata",
+ "Effect": "Allow",
+ "Action": [
+ "s3:GetObjectRetention",
+ "s3:GetObjectLegalHold"
+ ],
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*"
+ },
+ {
+ "Sid": "EncryptArchiveOnly",
+ "Effect": "Allow",
+ "Action": "kms:GenerateDataKey",
+ "Resource": "__ARCHIVE_KMS_KEY_ARN__",
+ "Condition": {
+ "StringEquals": {
+ "kms:ViaService": "s3.__AWS_REGION__.amazonaws.com"
+ }
+ }
+ }
+ ]
+ },
+ "audit_reader": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "ReadKnownArchiveVersion",
+ "Effect": "Allow",
+ "Action": [
+ "s3:GetObjectVersion",
+ "s3:GetObjectRetention",
+ "s3:GetObjectLegalHold"
+ ],
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*"
+ },
+ {
+ "Sid": "DecryptArchiveOnly",
+ "Effect": "Allow",
+ "Action": "kms:Decrypt",
+ "Resource": "__ARCHIVE_KMS_KEY_ARN__",
+ "Condition": {
+ "StringEquals": {
+ "kms:ViaService": "s3.__AWS_REGION__.amazonaws.com"
+ }
+ }
+ }
+ ]
+ },
+ "retention_operator": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "ReadProtectionMetadata",
+ "Effect": "Allow",
+ "Action": [
+ "s3:GetObjectRetention",
+ "s3:GetObjectLegalHold"
+ ],
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*"
+ },
+ {
+ "Sid": "ReviewHoldRelease",
+ "Effect": "Allow",
+ "Action": "s3:PutObjectLegalHold",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*"
+ },
+ {
+ "Sid": "DeleteExpiredUnheldVersion",
+ "Effect": "Allow",
+ "Action": "s3:DeleteObjectVersion",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*"
+ }
+ ]
+ },
+ "application_explicit_deny": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "NoApplicationArchiveAccess",
+ "Effect": "Deny",
+ "Action": "s3:*",
+ "Resource": [
+ "arn:aws:s3:::__ARCHIVE_BUCKET__",
+ "arn:aws:s3:::__ARCHIVE_BUCKET__/*"
+ ]
+ }
+ ]
+ },
+ "bucket_guard": {
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "DenyPlaintextTransport",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": "s3:*",
+ "Resource": [
+ "arn:aws:s3:::__ARCHIVE_BUCKET__",
+ "arn:aws:s3:::__ARCHIVE_BUCKET__/*"
+ ],
+ "Condition": {
+ "Bool": {
+ "aws:SecureTransport": "false"
+ }
+ }
+ },
+ {
+ "Sid": "DenyApplicationPrincipal",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": "s3:*",
+ "Resource": [
+ "arn:aws:s3:::__ARCHIVE_BUCKET__",
+ "arn:aws:s3:::__ARCHIVE_BUCKET__/*"
+ ],
+ "Condition": {
+ "ArnEquals": {
+ "aws:PrincipalArn": "__APPLICATION_ROLE_ARN__"
+ }
+ }
+ },
+ {
+ "Sid": "DenyMissingCreateOnlyCondition",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": "s3:PutObject",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "Null": {
+ "s3:if-none-match": "true"
+ }
+ }
+ },
+ {
+ "Sid": "DenyWrongEncryption",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": "s3:PutObject",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "StringNotEquals": {
+ "s3:x-amz-server-side-encryption": "aws:kms"
+ }
+ }
+ },
+ {
+ "Sid": "DenyWrongKey",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": "s3:PutObject",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "StringNotEquals": {
+ "s3:x-amz-server-side-encryption-aws-kms-key-id": "__ARCHIVE_KMS_KEY_ARN__"
+ }
+ }
+ },
+ {
+ "Sid": "DenyNonComplianceRetention",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": [
+ "s3:PutObject",
+ "s3:PutObjectRetention"
+ ],
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "StringNotEquals": {
+ "s3:object-lock-mode": "COMPLIANCE"
+ }
+ }
+ },
+ {
+ "Sid": "DenyShortRetention",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": [
+ "s3:PutObject",
+ "s3:PutObjectRetention"
+ ],
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "NumericLessThan": {
+ "s3:object-lock-remaining-retention-days": "__MIN_RETENTION_DAYS__"
+ }
+ }
+ },
+ {
+ "Sid": "DenyLongRetention",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": [
+ "s3:PutObject",
+ "s3:PutObjectRetention"
+ ],
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "NumericGreaterThan": {
+ "s3:object-lock-remaining-retention-days": "__MAX_RETENTION_DAYS__"
+ }
+ }
+ },
+ {
+ "Sid": "DenyHoldRemovalExceptRetentionRole",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": [
+ "s3:PutObject",
+ "s3:PutObjectLegalHold"
+ ],
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*",
+ "Condition": {
+ "StringNotEquals": {
+ "s3:object-lock-legal-hold": "ON"
+ },
+ "ArnNotEquals": {
+ "aws:PrincipalArn": "__RETENTION_OPERATOR_ROLE_ARN__"
+ }
+ }
+ },
+ {
+ "Sid": "DenyDeleteMarkers",
+ "Effect": "Deny",
+ "Principal": "*",
+ "Action": "s3:DeleteObject",
+ "Resource": "arn:aws:s3:::__ARCHIVE_BUCKET__/audit-custody/*"
+ }
+ ]
+ },
+ "bucket_controls": {
+ "versioning": {
+ "Status": "Enabled"
+ },
+ "object_lock": {
+ "ObjectLockEnabled": "Enabled"
+ },
+ "public_access_block": {
+ "BlockPublicAcls": true,
+ "IgnorePublicAcls": true,
+ "BlockPublicPolicy": true,
+ "RestrictPublicBuckets": true
+ },
+ "note": "No lifecycle delete or bypass-governance capability. Provider COMPLIANCE retention and live legal holds gate version deletion; source legal-hold review and approval remain operator duties."
+ }
+}
diff --git a/infra/monitoring/prometheus-rules/testlookup-alerts.yml b/infra/monitoring/prometheus-rules/testlookup-alerts.yml
index fb4accba3..90f52ea10 100644
--- a/infra/monitoring/prometheus-rules/testlookup-alerts.yml
+++ b/infra/monitoring/prometheus-rules/testlookup-alerts.yml
@@ -844,3 +844,69 @@ groups:
annotations:
summary: "No successful TestLookup backup in 26 hours"
description: "The testlookup-backup CronJob has not completed successfully for more than 26h (failing, suspended, or never run). The newest restorable archive is older than a day. Runbook: k8s/components/backup/README.md."
+
+ - name: testlookup.pipeline_event_delivery
+ interval: 30s
+ rules:
+ # Every API reads the same SQL rows. Filter each scrape for successful
+ # fresh collection before taking a fleet maximum; never sum replicas.
+ - alert: TestLookupPipelineEventDeliveryFailed
+ expr: |
+ max by (cluster, namespace) (
+ testlookup_pipeline_event_outbox_entries{job="testlookup-backend",status="failed"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{collector="pipeline_events"} == 1)
+ and on (cluster, namespace, job, instance)
+ (time() - testlookup_metric_collection_last_success_timestamp_seconds{collector="pipeline_events"} < 120)
+ ) > 0
+ for: 1m
+ labels:
+ severity: critical
+ annotations:
+ summary: "Pipeline event delivery requires recovery"
+ description: "Automatic event materialization exhausted retries or found an immutable identity conflict. SQL retains the unresolved evidence; inspect scoped event-log health before explicit delivery requeue. This does not re-execute a pipeline or prove Mongo evidence was lost."
+ runbook_url: "https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md"
+
+ - alert: TestLookupPipelineEventBacklogStale
+ expr: |
+ max by (cluster, namespace) (
+ testlookup_pipeline_event_outbox_oldest_age_seconds{job="testlookup-backend",status=~"pending|sending"}
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{collector="pipeline_events"} == 1)
+ and on (cluster, namespace, job, instance)
+ (time() - testlookup_metric_collection_last_success_timestamp_seconds{collector="pipeline_events"} < 120)
+ ) > 300
+ for: 5m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Pipeline event materialization is falling behind"
+ description: "A durable pending or leased event is older than five minutes. Verify the relay schedule, default-queue consumer, Mongo connectivity and expired leases. Retained intent age is not the age of a missing business operation."
+ runbook_url: "https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md"
+
+ - alert: TestLookupPipelineEventCapacityHigh
+ expr: |
+ max by (cluster, namespace) (
+ (sum without (status) (testlookup_pipeline_event_outbox_entries{job="testlookup-backend"})
+ / testlookup_pipeline_event_outbox_capacity{job="testlookup-backend"})
+ and on (cluster, namespace, job, instance)
+ (testlookup_metric_collection_success{collector="pipeline_events"} == 1)
+ and on (cluster, namespace, job, instance)
+ (time() - testlookup_metric_collection_last_success_timestamp_seconds{collector="pipeline_events"} < 120)
+ ) > 0.85
+ for: 5m
+ labels:
+ severity: warning
+ annotations:
+ summary: "Shared pipeline event admission is near its row limit"
+ description: "Retained intents and acknowledged receipts exceed 85% of the installation row limit. Restore relay delivery; only acknowledged receipts may be pressure-pruned. Never delete pending or failed evidence to make room."
+ runbook_url: "https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md"
+
+ - alert: TestLookupPipelineEventAdmissionRefused
+ expr: sum by (cluster, namespace, reason) (increase(testlookup_pipeline_event_admission_failures_total[5m])) > 0
+ labels:
+ severity: critical
+ annotations:
+ summary: "A pipeline event was not durably admitted"
+ description: "At least one source event could not enter the SQL delivery boundary. Accepted backlog recovery cannot reconstruct an event that was never admitted; inspect the bounded reason and source failure handling."
+ runbook_url: "https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md"
diff --git a/infra/monitoring/tests/pipeline-event-delivery.yml b/infra/monitoring/tests/pipeline-event-delivery.yml
new file mode 100644
index 000000000..0d7fa3e5f
--- /dev/null
+++ b/infra/monitoring/tests/pipeline-event-delivery.yml
@@ -0,0 +1,135 @@
+rule_files:
+- ../prometheus-rules/testlookup-alerts.yml
+evaluation_interval: 30s
+tests:
+- name: shared failures fire and a stale replica cannot hide recovery
+ interval: 30s
+ input_series:
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",collector="pipeline_events"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",collector="pipeline_events"}
+ values: 0+30x50
+ - series: testlookup_pipeline_event_outbox_entries{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",status="failed"}
+ values: 1x20 0x30
+ - series: testlookup_pipeline_event_outbox_entries{cluster="lab",namespace="prod",job="testlookup-backend",instance="stale",status="failed"}
+ values: 99x50
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="stale",collector="pipeline_events"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="stale",collector="pipeline_events"}
+ values: '0x50'
+ alert_rule_test:
+ - eval_time: 4m
+ alertname: TestLookupPipelineEventDeliveryFailed
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ severity: critical
+ exp_annotations:
+ summary: Pipeline event delivery requires recovery
+ description: Automatic event materialization exhausted retries or found an
+ immutable identity conflict. SQL retains the unresolved evidence; inspect
+ scoped event-log health before explicit delivery requeue. This does not
+ re-execute a pipeline or prove Mongo evidence was lost.
+ runbook_url: https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md
+ - eval_time: 16m
+ alertname: TestLookupPipelineEventDeliveryFailed
+ exp_alerts: []
+- name: replicated shared counts below capacity must not be summed
+ interval: 30s
+ input_series:
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",collector="pipeline_events"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",collector="pipeline_events"}
+ values: 0+30x50
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="b",collector="pipeline_events"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="b",collector="pipeline_events"}
+ values: 0+30x50
+ - series: testlookup_pipeline_event_outbox_entries{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",status="pending"}
+ values: 6000x50
+ - series: testlookup_pipeline_event_outbox_entries{cluster="lab",namespace="prod",job="testlookup-backend",instance="b",status="pending"}
+ values: 6000x50
+ - series: testlookup_pipeline_event_outbox_capacity{cluster="lab",namespace="prod",job="testlookup-backend",instance="a"}
+ values: 10000x50
+ - series: testlookup_pipeline_event_outbox_capacity{cluster="lab",namespace="prod",job="testlookup-backend",instance="b"}
+ values: 10000x50
+ alert_rule_test:
+ - eval_time: 10m
+ alertname: TestLookupPipelineEventCapacityHigh
+ exp_alerts: []
+- name: backlog and capacity threshold cross then recover
+ interval: 30s
+ input_series:
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",collector="pipeline_events"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",collector="pipeline_events"}
+ values: 0+30x50
+ - series: testlookup_pipeline_event_outbox_entries{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",status="pending"}
+ values: 9000x20 10x30
+ - series: testlookup_pipeline_event_outbox_capacity{cluster="lab",namespace="prod",job="testlookup-backend",instance="a"}
+ values: 10000x50
+ - series: testlookup_pipeline_event_outbox_oldest_age_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",status="pending"}
+ values: 600x20 0x30
+ alert_rule_test:
+ - eval_time: 8m
+ alertname: TestLookupPipelineEventCapacityHigh
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ severity: warning
+ exp_annotations:
+ summary: Shared pipeline event admission is near its row limit
+ description: Retained intents and acknowledged receipts exceed 85% of the
+ installation row limit. Restore relay delivery; only acknowledged receipts
+ may be pressure-pruned. Never delete pending or failed evidence to make
+ room.
+ runbook_url: https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md
+ - eval_time: 8m
+ alertname: TestLookupPipelineEventBacklogStale
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ severity: warning
+ exp_annotations:
+ summary: Pipeline event materialization is falling behind
+ description: A durable pending or leased event is older than five minutes.
+ Verify the relay schedule, default-queue consumer, Mongo connectivity and
+ expired leases. Retained intent age is not the age of a missing business
+ operation.
+ runbook_url: https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md
+ - eval_time: 16m
+ alertname: TestLookupPipelineEventCapacityHigh
+ exp_alerts: []
+ - eval_time: 16m
+ alertname: TestLookupPipelineEventBacklogStale
+ exp_alerts: []
+- name: source admission refusal is distinct from accepted delivery backlog
+ interval: 30s
+ input_series:
+ - series: testlookup_metric_collection_success{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",collector="pipeline_events"}
+ values: 1x50
+ - series: testlookup_metric_collection_last_success_timestamp_seconds{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",collector="pipeline_events"}
+ values: 0+30x50
+ - series: testlookup_pipeline_event_admission_failures_total{cluster="lab",namespace="prod",job="testlookup-backend",instance="a",reason="capacity"}
+ values: 0 0 1x48
+ alert_rule_test:
+ - eval_time: 2m
+ alertname: TestLookupPipelineEventAdmissionRefused
+ exp_alerts:
+ - exp_labels:
+ cluster: lab
+ namespace: prod
+ severity: critical
+ reason: capacity
+ exp_annotations:
+ summary: A pipeline event was not durably admitted
+ description: At least one source event could not enter the SQL delivery boundary.
+ Accepted backlog recovery cannot reconstruct an event that was never admitted;
+ inspect the bounded reason and source failure handling.
+ runbook_url: https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md
+ - eval_time: 12m
+ alertname: TestLookupPipelineEventAdmissionRefused
+ exp_alerts: []
diff --git a/k8s/monitoring/prometheusrule.yaml b/k8s/monitoring/prometheusrule.yaml
index 684d6ddbb..03cec70b9 100644
--- a/k8s/monitoring/prometheusrule.yaml
+++ b/k8s/monitoring/prometheusrule.yaml
@@ -469,3 +469,41 @@ spec:
annotations:
summary: No successful TestLookup backup in 26 hours
description: 'The testlookup-backup CronJob has not completed successfully for more than 26h (failing, suspended, or never run). The newest restorable archive is older than a day. Runbook: k8s/components/backup/README.md.'
+ - name: testlookup.pipeline_event_delivery
+ interval: 30s
+ rules:
+ - alert: TestLookupPipelineEventDeliveryFailed
+ expr: "max by (cluster, namespace) (\n testlookup_pipeline_event_outbox_entries{job=\"testlookup-backend\",status=\"failed\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{collector=\"pipeline_events\"} == 1)\n and on (cluster, namespace, job, instance)\n (time() - testlookup_metric_collection_last_success_timestamp_seconds{collector=\"pipeline_events\"} < 120)\n) > 0\n"
+ for: 1m
+ labels:
+ severity: critical
+ annotations:
+ summary: Pipeline event delivery requires recovery
+ description: Automatic event materialization exhausted retries or found an immutable identity conflict. SQL retains the unresolved evidence; inspect scoped event-log health before explicit delivery requeue. This does not re-execute a pipeline or prove Mongo evidence was lost.
+ runbook_url: https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md
+ - alert: TestLookupPipelineEventBacklogStale
+ expr: "max by (cluster, namespace) (\n testlookup_pipeline_event_outbox_oldest_age_seconds{job=\"testlookup-backend\",status=~\"pending|sending\"}\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{collector=\"pipeline_events\"} == 1)\n and on (cluster, namespace, job, instance)\n (time() - testlookup_metric_collection_last_success_timestamp_seconds{collector=\"pipeline_events\"} < 120)\n) > 300\n"
+ for: 5m
+ labels:
+ severity: warning
+ annotations:
+ summary: Pipeline event materialization is falling behind
+ description: A durable pending or leased event is older than five minutes. Verify the relay schedule, default-queue consumer, Mongo connectivity and expired leases. Retained intent age is not the age of a missing business operation.
+ runbook_url: https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md
+ - alert: TestLookupPipelineEventCapacityHigh
+ expr: "max by (cluster, namespace) (\n (sum without (status) (testlookup_pipeline_event_outbox_entries{job=\"testlookup-backend\"})\n / testlookup_pipeline_event_outbox_capacity{job=\"testlookup-backend\"})\n and on (cluster, namespace, job, instance)\n (testlookup_metric_collection_success{collector=\"pipeline_events\"} == 1)\n and on (cluster, namespace, job, instance)\n (time() - testlookup_metric_collection_last_success_timestamp_seconds{collector=\"pipeline_events\"} < 120)\n) > 0.85\n"
+ for: 5m
+ labels:
+ severity: warning
+ annotations:
+ summary: Shared pipeline event admission is near its row limit
+ description: Retained intents and acknowledged receipts exceed 85% of the installation row limit. Restore relay delivery; only acknowledged receipts may be pressure-pruned. Never delete pending or failed evidence to make room.
+ runbook_url: https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md
+ - alert: TestLookupPipelineEventAdmissionRefused
+ expr: sum by (cluster, namespace, reason) (increase(testlookup_pipeline_event_admission_failures_total[5m])) > 0
+ labels:
+ severity: critical
+ annotations:
+ summary: A pipeline event was not durably admitted
+ description: At least one source event could not enter the SQL delivery boundary. Accepted backlog recovery cannot reconstruct an event that was never admitted; inspect the bounded reason and source failure handling.
+ runbook_url: https://github.com/test-intelligence/testlookup/blob/main/docs/operations/pipeline-event-delivery.md
From 849323c9a06e127ce7ef80cc6dddb26da35a5ab1 Mon Sep 17 00:00:00 2001
From: Anand Topu
Date: Fri, 27 Nov 2026 02:12:39 -0600
Subject: [PATCH 06/13] feat: add scoped service objectives and telemetry
capacity checks
Measure supported core API responses and retained SQL work without mixing installation scopes or concurrent API process snapshots. Offer an opt-in rule profile with explicit objective adoption and bounded query cadence.
Keep project and workflow evidence in their durable sources and enforce finite stage, task and case telemetry dimensions. Measure the pinned reference stack, queue saturation and trace sampling in disposable local processes.
Signed-off-by: Anand Topu
---
.env.example | 9 +
.github/workflows/ci.yml | 5 +
CHANGELOG.md | 2 +
backend/app/agents/base.py | 22 +-
backend/app/bootstrap.py | 33 +-
backend/app/core/config.py | 11 +
backend/app/core/metric_dimensions.py | 54 ++
backend/app/core/metrics.py | 59 +--
backend/app/middleware/journey_sli.py | 91 ++++
backend/app/models/postgres.py | 3 +
backend/app/services/journey_sli_contracts.py | 48 ++
backend/app/services/journey_sli_metrics.py | 222 +++++++++
backend/app/services/metric_collection.py | 3 +-
.../services/test_case_lifecycle_service.py | 2 -
.../test_management_metrics_service.py | 112 +----
backend/app/services/test_suite_service.py | 28 --
.../services/workflow_evaluation_service.py | 4 -
backend/app/worker/celery_app.py | 30 +-
.../versions/0264_journey_cohort_indexes.py | 44 ++
.../integration/test_journey_sli_postgres.py | 143 ++++++
.../test_alert_rules_are_deployable.py | 25 +-
.../test_alerted_metrics_are_emitted.py | 7 +-
..._grafana_dashboard_metrics_are_declared.py | 7 +
.../test_health_dashboards_need_a_sign_in.py | 42 +-
.../test_operational_metric_dimensions.py | 254 ++++++++++
.../test_test_management_metrics_service.py | 139 ++----
.../test_workflow_evaluation_service.py | 40 ++
.../test_ai_generation_worker_governance.py | 2 +-
backend/tests/test_journey_sli.py | 387 +++++++++++++++
backend/tests/test_test_case_governance_sp.py | 33 +-
.../test_test_case_lifecycle_state_machine.py | 6 +-
backend/tests/test_tracing.py | 23 +
docker-compose.objectives.yml | 19 +
docker-compose.telemetry.yml | 2 +
docs/maintainers/observability-delivery.md | 13 +
docs/operations/api-objectives.md | 107 ++++
docs/operations/deploy-compose.md | 2 +
docs/operations/deploy-kubernetes.md | 4 +-
docs/operations/durable-telemetry.md | 4 +-
docs/operations/journey-slis.md | 99 ++++
docs/operations/metric-cardinality.md | 136 +++++
docs/operations/telemetry-capacity.md | 57 +++
docs/reference/configuration.md | 1 +
docs/reference/data-dictionary.md | 312 ++++++------
docs/reference/migrations.md | 1 +
docs/reference/worker-operations.md | 2 +-
.../dashboards/testlookup-api-objectives.json | 468 ++++++++++++++++++
.../dashboards/testlookup-overview.json | 16 +-
.../monitoring/metric-cardinality-budget.json | 172 +++++++
.../objectives/adoption.example.yml | 26 +
infra/monitoring/objectives/api-slos.yml | 271 ++++++++++
infra/monitoring/tests/metric-scope.yml | 161 ++++++
.../monitoring/tests/objective-burn-rates.yml | 442 +++++++++++++++++
.../tests/objective-window-coverage.yml | 26 +
k8s/monitoring-objectives/kustomization.yaml | 7 +
k8s/monitoring-objectives/prometheusrule.yaml | 225 +++++++++
.../monitoring/measure_reference_capacity.py | 328 ++++++++++++
.../monitoring/tests/test_api_objectives.py | 102 ++++
scripts/release/offline-bundle.sh | 2 +-
scripts/render_prometheusrule.py | 26 +-
user-guide/sizing.md | 1 +
61 files changed, 4417 insertions(+), 505 deletions(-)
create mode 100644 backend/app/core/metric_dimensions.py
create mode 100644 backend/app/middleware/journey_sli.py
create mode 100644 backend/app/services/journey_sli_contracts.py
create mode 100644 backend/app/services/journey_sli_metrics.py
create mode 100644 backend/migrations/versions/0264_journey_cohort_indexes.py
create mode 100644 backend/tests/integration/test_journey_sli_postgres.py
create mode 100644 backend/tests/regression/test_operational_metric_dimensions.py
create mode 100644 backend/tests/test_journey_sli.py
create mode 100644 docker-compose.objectives.yml
create mode 100644 docs/operations/api-objectives.md
create mode 100644 docs/operations/journey-slis.md
create mode 100644 docs/operations/metric-cardinality.md
create mode 100644 docs/operations/telemetry-capacity.md
create mode 100644 infra/monitoring/grafana/dashboards/testlookup-api-objectives.json
create mode 100644 infra/monitoring/metric-cardinality-budget.json
create mode 100644 infra/monitoring/objectives/adoption.example.yml
create mode 100644 infra/monitoring/objectives/api-slos.yml
create mode 100644 infra/monitoring/tests/metric-scope.yml
create mode 100644 infra/monitoring/tests/objective-burn-rates.yml
create mode 100644 infra/monitoring/tests/objective-window-coverage.yml
create mode 100644 k8s/monitoring-objectives/kustomization.yaml
create mode 100644 k8s/monitoring-objectives/prometheusrule.yaml
create mode 100644 scripts/monitoring/measure_reference_capacity.py
create mode 100644 scripts/monitoring/tests/test_api_objectives.py
diff --git a/.env.example b/.env.example
index 1b3d86f4f..334107800 100644
--- a/.env.example
+++ b/.env.example
@@ -301,6 +301,15 @@ KNOWLEDGE_RAG_ENABLED=false
# host file containing the same metrics bearer token. Do not put the token here.
# METRICS_API_TOKEN_SOURCE=
# METRICS_PROMETHEUS_TOKEN_SOURCE=
+# For docker-compose.objectives.yml, choose a stable lowercase installation ID
+# and size Prometheus retention from the capacity runbook. Adoption is optional.
+# OBSERVABILITY_INSTALLATION=
+# SLO_PROMETHEUS_RETENTION_SIZE=
+# SLO_ADOPTION_RULES_FILE=
+# Application trace sampling for the optional durable profile. The SDK defaults
+# to parentbased_always_on. A site may set both values after measuring capacity.
+# OTEL_TRACES_SAMPLER=parentbased_traceidratio
+# OTEL_TRACES_SAMPLER_ARG=0.1
# Required when using docker-compose.monitoring.yml
# Generate with: openssl rand -hex 16
GF_SECURITY_ADMIN_PASSWORD=
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2bdd819ae..8a8a0e75d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -538,6 +538,7 @@ jobs:
tool="$scratch/$prometheus_dir/promtool"
monitoring="infra/monitoring"
"$tool" check rules "$monitoring/prometheus-rules/testlookup-alerts.yml"
+ "$tool" check rules "$monitoring/objectives/api-slos.yml" "$monitoring/objectives/adoption.example.yml"
"$tool" test rules "$monitoring"/tests/*.yml
# Mirror the Compose mounts and validate included scrape jobs and rules.
mkdir "$scratch/config"
@@ -548,6 +549,9 @@ jobs:
printf '%s\n' 'synthetic-test-token' > "$scratch/config/metrics-token"
"$tool" check config "$scratch/config/prometheus.yml"
done
+ cp "$monitoring/objectives/api-slos.yml" "$scratch/config/rules/"
+ cp "$monitoring/objectives/adoption.example.yml" "$scratch/config/rules/slo-adoption.yml"
+ "$tool" check config "$scratch/config/prometheus.yml"
cp "$monitoring/alertmanager/telemetry-contract.yml" "$scratch/config/alertmanager-contract.yml"
for input in incident-url watchdog-url; do
printf '%s\n' "https://receiver.invalid/$input" > "$scratch/$input"
@@ -1149,6 +1153,7 @@ jobs:
tests/integration/test_nightly_job_observation_postgres.py
tests/integration/test_pipeline_event_outbox_postgres.py
tests/integration/test_identity_retention_postgres.py
+ tests/integration/test_journey_sli_postgres.py
tests/integration/test_engine_hides_parameters_postgres.py
tests/integration/test_decision_report_supersession_postgres_mongo.py
tests/integration/test_http_exchanges_postgres_mongo.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad82e2997..498f70861 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).
### Added
+- Optional API objectives report scoped availability, latency, error budgets and measurement coverage. Retained SQL cohorts expose downstream and AI completion, including missed deadlines, and a disposable benchmark measures telemetry capacity.
- Pipeline events use a PostgreSQL outbox with stable IDs for MongoDB replay, shared delivery health, and project-scoped recovery. Audit archives support independent integrity verification, and an opt-in identity retention policy preserves SCIM authority events.
- The durable telemetry profile adds queued OpenTelemetry export, persistent Loki logs and Jaeger traces, Grafana correlation, and queue loss alerts. Kubernetes client overlays support a site-operated mTLS gateway, and the offline Compose bundle can include the durable stack.
- The optional Compose alerting overlay adds a private Alertmanager with authenticated HTTPS incident and watchdog receivers. Compose and Kubernetes monitoring inventories detect missing scrape roles and required metric series.
@@ -19,6 +20,7 @@ contain breaking changes; [UPGRADING.md](UPGRADING.md) lists them).
### Changed
+- Operational metrics bound workflow stage, task and queue labels and remove per-project dimensions from case governance events. Detailed case and workflow state remains in the application. The durable Compose profile accepts an explicit API trace sampling ratio.
- Weekly digest and nightly maintenance alerts follow durable delivery and execution state. They detect overdue work even when a worker never started the task or was replaced.
- Celery queue depth reads all configured broker priority lists, including child work, and reports unknown counts when a list cannot be read.
- Upload publication uses bounded background threads; uncertain queue confirmation retains the payload and returns polling identifiers so callers can check before resubmitting.
diff --git a/backend/app/agents/base.py b/backend/app/agents/base.py
index e3e084d44..af984b173 100644
--- a/backend/app/agents/base.py
+++ b/backend/app/agents/base.py
@@ -16,6 +16,9 @@
pipeline_stage_tokens_total,
)
from app.core.config import settings
+from app.core.metric_dimensions import (
+ ERROR_CATEGORIES, FALLBACK_REASONS, STAGE_NAMES, bounded_dimension,
+)
from app.core.tracing import get_tracer
from app.db.postgres import AsyncSessionLocal
from app.models.postgres import AgentPipelineRun, AgentStageResult
@@ -354,34 +357,37 @@ async def mark_stage_done(
}
# Record Prometheus metrics
+ # A workflow may rename every step. Use its static agent capability
+ # for metrics; retain the runtime step ID in SQL, events and traces.
+ metric_stage_name = bounded_dimension(type(self).stage_name, STAGE_NAMES)
duration = time.perf_counter() - self._stage_start.pop(pipeline_run_id, time.perf_counter())
pipeline_stage_duration_seconds.labels(
- stage_name=runtime_stage_name(type(self).stage_name), status=status
+ stage_name=metric_stage_name, status=status
).observe(duration)
pipeline_stage_runs_total.labels(
- stage_name=runtime_stage_name(type(self).stage_name), status=status
+ stage_name=metric_stage_name, status=status
).inc()
# Phase 6: Token, cost, LLM call, fallback, and error metrics
if input_tokens > 0:
pipeline_stage_tokens_total.labels(
- stage_name=runtime_stage_name(type(self).stage_name), direction="input"
+ stage_name=metric_stage_name, direction="input"
).inc(input_tokens)
if output_tokens > 0:
pipeline_stage_tokens_total.labels(
- stage_name=runtime_stage_name(type(self).stage_name), direction="output"
+ stage_name=metric_stage_name, direction="output"
).inc(output_tokens)
if cost_usd > 0:
- pipeline_stage_cost_usd.labels(stage_name=runtime_stage_name(type(self).stage_name)).inc(cost_usd)
+ pipeline_stage_cost_usd.labels(stage_name=metric_stage_name).inc(cost_usd)
if llm_calls_count > 0:
- pipeline_stage_llm_calls_total.labels(stage_name=runtime_stage_name(type(self).stage_name)).inc(llm_calls_count)
+ pipeline_stage_llm_calls_total.labels(stage_name=metric_stage_name).inc(llm_calls_count)
if fallback_reason:
pipeline_fallback_total.labels(
- stage_name=runtime_stage_name(type(self).stage_name), reason=fallback_reason[:50]
+ stage_name=metric_stage_name, reason=bounded_dimension(fallback_reason, FALLBACK_REASONS)
).inc()
if error_category:
pipeline_stage_errors_by_category.labels(
- stage_name=runtime_stage_name(type(self).stage_name), error_category=error_category
+ stage_name=metric_stage_name, error_category=bounded_dimension(error_category, ERROR_CATEGORIES)
).inc()
# Tier 1 item 2 — feed the LLM cost meter. Runs only when the caller
diff --git a/backend/app/bootstrap.py b/backend/app/bootstrap.py
index 66f3e4fc2..02f19be00 100644
--- a/backend/app/bootstrap.py
+++ b/backend/app/bootstrap.py
@@ -415,6 +415,11 @@ def configure_metrics(app: FastAPI) -> None:
from prometheus_fastapi_instrumentator import Instrumentator
+ from app.middleware.journey_sli import JourneySLIMiddleware
+
+ if settings.OBSERVABILITY_INSTALLATION:
+ app.add_middleware(JourneySLIMiddleware)
+
Instrumentator(
should_group_status_codes=True,
should_ignore_untemplated=True,
@@ -534,23 +539,33 @@ async def _endpoint(*args, __orig=original, **kwargs):
from app.services.downstream_operational_metrics import (
refresh_downstream_operational_metrics,
)
+ from app.services.journey_sli_metrics import refresh_journey_cohort_metrics, render_journey_cohort_metrics
from app.services.metric_collection import collect_bounded
from app.services.nightly_job_observation import refresh_nightly_job_metrics
from app.services.pipeline_event_operational_metrics import refresh_pipeline_event_operational_metrics
from app.services.redis_resource_metrics import refresh_redis_resource_metrics
- await asyncio.gather(
- collect_bounded("queues", _refresh_celery_queue_depths),
- collect_bounded("agents", refresh_agent_operational_metrics),
- collect_bounded("downstream", refresh_downstream_operational_metrics),
- collect_bounded("redis", refresh_redis_resource_metrics),
- collect_bounded("nightly", refresh_nightly_job_metrics),
- collect_bounded("digests", refresh_digest_operational_metrics),
- collect_bounded("pipeline_events", refresh_pipeline_event_operational_metrics),
- )
+ collectors = {
+ "queues": _refresh_celery_queue_depths,
+ "agents": refresh_agent_operational_metrics,
+ "downstream": refresh_downstream_operational_metrics,
+ "redis": refresh_redis_resource_metrics,
+ "nightly": refresh_nightly_job_metrics,
+ "digests": refresh_digest_operational_metrics,
+ "pipeline_events": refresh_pipeline_event_operational_metrics,
+ }
+ if settings.OBSERVABILITY_INSTALLATION:
+ collectors["journeys"] = refresh_journey_cohort_metrics
+ collected = await asyncio.gather(*(collect_bounded(name, refresh) for name, refresh in collectors.items()))
result = __orig(*args, **kwargs)
if inspect.isawaitable(result):
result = await result
+ if dict(zip(collectors, collected)).get("journeys"):
+ # Append one immutable snapshot from the process serving this
+ # scrape. Multiprocess gauges could merge outcomes from two
+ # readers of the same changing rows into a false denominator.
+ result.body += render_journey_cohort_metrics()
+ result.headers["Content-Length"] = str(len(result.body))
return result
route.endpoint = _endpoint
diff --git a/backend/app/core/config.py b/backend/app/core/config.py
index 18b14616d..40fc003ba 100644
--- a/backend/app/core/config.py
+++ b/backend/app/core/config.py
@@ -152,6 +152,17 @@ class Settings(BaseSettings):
# ── Application ─────────────────────────────────────────
APP_NAME: str = "TestLookup"
APP_ENV: Literal["development", "staging", "production"] = "development"
+ # Required only for opt-in SLI objective inputs. Never infer an installation
+ # from a hostname, URL, project or mutable process identity.
+ OBSERVABILITY_INSTALLATION: str = ""
+
+ @field_validator("OBSERVABILITY_INSTALLATION")
+ @classmethod
+ def validate_observability_installation(cls, value: str) -> str:
+ if value and _re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,62}", value, flags=_re.ASCII) is None:
+ raise ValueError("OBSERVABILITY_INSTALLATION must be 1 to 63 ASCII letters, digits, dots, underscores or hyphens, starting with a letter or digit")
+ return value
+
APP_SECRET_KEY: str = "change-me-in-production"
# Optional previous key for secret-at-rest rotation. When set, the secret
# service decrypts with a MultiFernet [current, previous] so values
diff --git a/backend/app/core/metric_dimensions.py b/backend/app/core/metric_dimensions.py
new file mode 100644
index 000000000..56618ed2f
--- /dev/null
+++ b/backend/app/core/metric_dimensions.py
@@ -0,0 +1,54 @@
+"""Closed operational dimensions; detailed identities belong in SQL/events.
+
+Changing these inventories changes the series budget. Never admit a value just
+because it has a short length or matches an identifier-shaped regular expression.
+"""
+from __future__ import annotations
+
+STAGE_NAMES = frozenset({
+ "unknown", "other", "change_ownership", "anomaly_detection", "root_cause_analysis",
+ "failure_clustering", "contract_validation", "decision_report", "decision_report_critic",
+ "defect_commander", "log_intelligence", "flaky_sentinel", "regression_watchman",
+ "gap_detection", "release_risk", "ingestion", "report_refinement", "reviewer",
+ "hypothesis_infra", "hypothesis_commit", "hypothesis_environment", "hypothesis_known_flaky",
+ "hypothesis_regression", "investigator_synthesis", "test_health", "summary", "triage",
+})
+FALLBACK_REASONS = frozenset({
+ "llm_timeout", "llm_error", "token_limit", "provider_unavailable",
+ "no_failure_cluster", "no_log_context", "other",
+})
+ERROR_CATEGORIES = frozenset({
+ "transient", "permanent", "provider_error", "token_limit", "timeout",
+ "classification_error", "anomaly_agent_exception", "change_ownership_error", "other",
+})
+LIFECYCLE_STATES = frozenset({
+ "draft", "review_requested", "under_review", "approved", "active", "rejected",
+ "needs_update", "deprecated", "archived", "other",
+})
+ACTOR_ROLES = frozenset({"VIEWER", "TESTER", "QA_ENGINEER", "QA_LEAD", "ADMIN", "other"})
+TASK_STATES = frozenset({
+ "pending", "received", "started", "success", "failure", "retry", "revoked",
+ "rejected", "ignored", "unknown", "other",
+})
+# A hard ceiling on the deployed code registry, frozen by the worker on first
+# observation. Late/dynamic registrations and over-budget names share "other".
+MAX_METRIC_TASK_NAMES = 128
+TASK_QUEUE_FAMILIES = frozenset({
+ "critical", "ingestion", "ai_analysis", "agent_children", "default",
+ "ingestion_shard", "unknown", "other",
+})
+
+
+def bounded_dimension(value: object, allowed: frozenset[str]) -> str:
+ return value if isinstance(value, str) and value in allowed else "other"
+
+
+def task_queue_family(value: object) -> str:
+ """Collapse shard indexes without changing routing or per-queue depth."""
+ if not value:
+ return "unknown"
+ if isinstance(value, str) and value.startswith("ingestion.shard."):
+ suffix = value.removeprefix("ingestion.shard.")
+ if suffix.isascii() and suffix.isdecimal():
+ return "ingestion_shard"
+ return bounded_dimension(value, TASK_QUEUE_FAMILIES)
diff --git a/backend/app/core/metrics.py b/backend/app/core/metrics.py
index 3a4a726d5..7b2a7c60c 100644
--- a/backend/app/core/metrics.py
+++ b/backend/app/core/metrics.py
@@ -8,6 +8,7 @@
from app.core.metrics import ingestion_runs_total, pipeline_stage_duration_seconds
"""
from prometheus_client import Counter, Gauge, Histogram
+from prometheus_client.core import GaugeMetricFamily
# ── Ingestion ─────────────────────────────────────────────────────────────────
@@ -302,13 +303,13 @@
pipeline_fallback_total = Counter(
"testlookup_pipeline_fallback_total",
"Number of fallback invocations per agent stage",
- ["stage_name", "reason"], # reason: llm_timeout | llm_error | token_limit | provider_unavailable
+ ["stage_name", "reason"], # closed capability/reason inventories: metric_dimensions.py
)
pipeline_stage_errors_by_category = Counter(
"testlookup_pipeline_stage_errors_by_category",
"Error counts by category per agent stage",
- ["stage_name", "error_category"], # error_category: transient | permanent | provider_error | token_limit | timeout
+ ["stage_name", "error_category"], # closed inventories: metric_dimensions.py
)
# ── Release Gate ──────────────────────────────────────────────────────────────
@@ -560,33 +561,17 @@
test_case_transitions_total = Counter(
"testlookup_test_case_transitions_total",
"Validated authored test-case lifecycle transitions",
- ["project", "from", "to", "actor_role"],
-)
-
-test_cases_by_state = Gauge(
- "testlookup_test_cases_by_state",
- "Current authored test cases in each governed lifecycle state",
- ["project", "state"],
- multiprocess_mode="mostrecent",
+ ["from", "to", "actor_role"],
)
test_case_promotions_total = Counter(
"testlookup_test_case_promotions_total",
"Automation canonical cases promoted into authored test management",
- ["project"],
)
test_case_deprecations_without_reason_total = Counter(
"testlookup_test_case_deprecations_without_reason_total",
"Legacy DELETE deprecations that used the first-release compatibility reason",
- ["project"],
-)
-
-automation_cases_orphaned = Gauge(
- "testlookup_automation_cases_orphaned",
- "Deleted automation canonical cases awaiting retirement confirmation",
- ["project"],
- multiprocess_mode="mostrecent",
)
# ── Tier 0-2 operations (Phase E-3, 2026-04-15) ─────────────────────────────
@@ -834,15 +819,8 @@
["outcome"],
)
-# E9.5: fraction of candidate workflow steps backed by an exact replay-cache
-# key during the latest dry-run. Project/workflow labels are bounded by stored
-# definitions and let operators distinguish a safe regression result from an
-# insufficient one.
-workflow_eval_coverage = Gauge(
- "testlookup_workflow_eval_coverage",
- "Fraction of candidate workflow steps measured by the replay corpus",
- ["project_id", "workflow_id"],
-)
+# Tenant/workflow current-state analytics stay in SQL and the authorized APIs.
+# Process gauges retained deleted IDs and could not represent a fleet snapshot.
# Operational collection is bounded; a previous gauge value is not proof that
# its dependency was observed during the current scrape. Shared-state gauges
@@ -1042,3 +1020,28 @@
)
for _reason in ("scope", "capacity", "storage", "contention", "payload", "conflict", "other"):
pipeline_event_admission_failures.labels(reason=_reason)
+
+# Journey SLIs are opt-in and explicitly installation scoped. API counters
+# sum real attempts across processes; durable SQL cohorts are replicated
+# absolute snapshots: select one freshest valid API target for the entire
+# cohort bundle. Independent max per outcome can invent a denominator.
+api_journey_events = Counter(
+ "testlookup_api_journey_events_total", "Eligible completed core API attempts by proposed objective outcome",
+ ["installation", "environment", "objective", "outcome"],
+)
+api_sli_configured = Gauge(
+ "testlookup_api_sli_configured", "API target has initialized both outcomes for this scoped measurement; not objective adoption",
+ ["installation", "environment", "objective"], multiprocess_mode="mostrecent",
+)
+journey_cohort_events = GaugeMetricFamily(
+ "testlookup_journey_cohort_events", "Retained SQL intents in a matured acceptance cohort; not a cumulative counter",
+ labels=["installation", "environment", "journey", "window", "outcome"],
+)
+journey_cohort_observed_at = GaugeMetricFamily(
+ "testlookup_journey_cohort_observed_at_seconds", "UTC observation of the last complete shared SQL cohort snapshot",
+ labels=["installation", "environment"],
+)
+journey_source_supported = GaugeMetricFamily(
+ "testlookup_journey_source_supported", "Whether this journey has the documented retained SQL acceptance/completion source; not historical SLO coverage",
+ labels=["installation", "environment", "journey"],
+)
diff --git a/backend/app/middleware/journey_sli.py b/backend/app/middleware/journey_sli.py
new file mode 100644
index 000000000..354ca764d
--- /dev/null
+++ b/backend/app/middleware/journey_sli.py
@@ -0,0 +1,91 @@
+"""Opt-in core API completion measurements, independent of HTTP diagnostics.
+
+No request credential, ID, query, raw path or response content becomes a label.
+These counters censor requests that never reach a terminal response/exception;
+they are not a durable accepted-to-completed journey or an adopted guarantee.
+"""
+from __future__ import annotations
+
+from time import perf_counter
+import re
+
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
+from starlette._utils import get_route_path
+
+from app.core.config import settings
+from app.core.metrics import api_journey_events, api_sli_configured
+from app.services.journey_sli_contracts import API_OBJECTIVES, API_OUTCOMES, API_ROUTES
+
+_TEMPLATES = tuple(
+ (method, re.compile(r"\A" + "/".join("[^/]+" if part.startswith("{") and part.endswith("}") else re.escape(part)
+ for part in template.split("/")) + r"\Z"), threshold)
+ for (method, template), threshold in API_ROUTES.items()
+)
+
+
+def _threshold(scope: Scope) -> float | None:
+ route = scope.get("route")
+ if route is not None:
+ method, path = scope.get("method"), getattr(route, "path", None)
+ return API_ROUTES.get((method, path)) if isinstance(method, str) and isinstance(path, str) else None
+ # An early application guard can return 429/500 before Router sets route.
+ # Match only the same six fixed templates; never derive a metric label
+ # from an arbitrary path, credential-bearing header, Host or query string.
+ for method, pattern, threshold in _TEMPLATES:
+ if scope.get("method") == method and pattern.fullmatch(get_route_path(scope)):
+ return threshold
+ return None
+
+
+class JourneySLIMiddleware:
+ def __init__(self, app: ASGIApp):
+ self.app = app
+ self.labels = {"installation": settings.OBSERVABILITY_INSTALLATION, "environment": settings.APP_ENV}
+ self.enabled = bool(self.labels["installation"])
+ if self.enabled:
+ for objective in API_OBJECTIVES:
+ for outcome in API_OUTCOMES:
+ api_journey_events.labels(**self.labels, objective=objective, outcome=outcome)
+ api_sli_configured.labels(**self.labels, objective=objective).set(1)
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if not self.enabled or scope["type"] != "http":
+ await self.app(scope, receive, send)
+ return
+ started, status, finished, recorded = perf_counter(), None, False, False
+
+ def record(*, raised: bool = False) -> None:
+ nonlocal recorded
+ if recorded:
+ return
+ # The router resolves this after middleware entry, including errors
+ # from matched handlers. Unknown/raw paths are never keys or labels.
+ threshold = _threshold(scope)
+ if threshold is None:
+ return
+ if not raised and (status is None or (400 <= status < 500 and status != 429)):
+ return
+ recorded = True
+ good = not raised and status is not None and 200 <= status < 400
+ api_journey_events.labels(**self.labels, objective="api_availability", outcome="good" if good else "bad").inc()
+ timely = good and perf_counter() - started <= threshold
+ api_journey_events.labels(**self.labels, objective="api_latency", outcome="good" if timely else "bad").inc()
+
+ async def observed_send(message: Message) -> None:
+ nonlocal status, finished
+ if message["type"] == "http.response.start":
+ status = message["status"]
+ await send(message)
+ if message["type"] == "http.response.body" and not message.get("more_body", False):
+ finished = True
+ record()
+
+ try:
+ await self.app(scope, receive, observed_send)
+ except BaseException:
+ # Includes an unhandled server error after response.start or a
+ # cancelled eligible handler. Reraise without changing behavior.
+ record(raised=True)
+ raise
+ else:
+ record(raised=not finished)
diff --git a/backend/app/models/postgres.py b/backend/app/models/postgres.py
index a92fc5614..9b4a595d3 100644
--- a/backend/app/models/postgres.py
+++ b/backend/app/models/postgres.py
@@ -649,6 +649,8 @@ class RunDownstreamOutbox(Base):
__tablename__ = "run_downstream_outbox"
__table_args__ = (
+ # 0264: retained SLI acceptance cohorts filter the timestamp first.
+ Index("ix_run_downstream_outbox_created_at", "created_at"),
UniqueConstraint(
"run_id",
"operation",
@@ -2594,6 +2596,7 @@ class AgentPipelineRun(Base):
"""Tracks a single execution of the multi-agent pipeline for a test run."""
__tablename__ = "agent_pipeline_runs"
__table_args__ = (
+ Index("ix_agent_pipeline_runs_created_at", "created_at"), # 0264 cohort horizon
Index("ix_pipeline_runs_test_run", "test_run_id"),
Index("ix_pipeline_runs_status", "status"),
CheckConstraint(
diff --git a/backend/app/services/journey_sli_contracts.py b/backend/app/services/journey_sli_contracts.py
new file mode 100644
index 000000000..bb3a88aa0
--- /dev/null
+++ b/backend/app/services/journey_sli_contracts.py
@@ -0,0 +1,48 @@
+"""Bounded measurement contracts; proposed thresholds are not adopted SLOs."""
+from dataclasses import dataclass
+
+from app.services.performance_budgets import LATENCY_BUDGETS
+
+API_OBJECTIVES = ("api_availability", "api_latency")
+API_OUTCOMES = ("good", "bad")
+_CORE_OPERATIONS = frozenset({
+ "project_list", "run_list", "run_scoped_guard", "run_intelligence", "keyword_search", "flaky_coach",
+})
+# Route templates are used only for lookup, never emitted as metric labels.
+API_ROUTES = {
+ (budget.http_method, budget.http_handler): budget.p95_ms / 1000
+ for budget in LATENCY_BUDGETS if budget.operation in _CORE_OPERATIONS and budget.http_handler
+}
+WINDOWS = {"1h": 3600, "6h": 21600, "24h": 86400, "30d": 30 * 86400}
+COHORT_OUTCOMES = ("good", "late", "failed", "overdue", "degraded", "unknown")
+
+
+@dataclass(frozen=True)
+class JourneyContract:
+ name: str
+ source: str
+ acceptance: str
+ completion: str
+ owner: str
+ supported: bool
+
+
+JOURNEYS = (
+ JourneyContract("downstream", "run_downstream_outbox", "committed operation/input_version intent",
+ "explicit completed status and completed_at", "backend", True),
+ JourneyContract("live_materialization", "run_downstream_outbox", "committed persist_live_session intent",
+ "explicit completed status and completed_at", "backend", True),
+ JourneyContract("ai_completion", "agent_pipeline_runs", "committed pipeline identity",
+ "completed/passed plus completed_at; degraded allowed", "AI platform", True),
+ JourneyContract("ai_reported_full_quality", "agent_pipeline_runs", "committed pipeline identity",
+ "timely completed/passed with explicit no-fallback and no degraded quality", "AI platform", True),
+ JourneyContract("api_durable", "none", "no durable request acceptance ledger", "process completion counters only", "backend", False),
+ JourneyContract("upload_acceptance", "none", "202 precedes durable TestRun; advisory Redis status expires",
+ "no durable acceptance/completion timestamps", "backend", False),
+ JourneyContract("live_event_acceptance", "none", "Redis accepted stream evidence; SQL receipts begin at projection",
+ "no complete SQL denominator for all accepted events", "backend", False),
+ JourneyContract("scheduled_history", "none", "nightly/digest observations retain latest slot, not every expected slot",
+ "current due/last-success metrics only", "SRE", False),
+ JourneyContract("backup_verified_restore", "none", "CronJob status is not verified restorable archive",
+ "no durable application restore-verification ledger", "SRE", False),
+)
diff --git a/backend/app/services/journey_sli_metrics.py b/backend/app/services/journey_sli_metrics.py
new file mode 100644
index 000000000..0d2705ed5
--- /dev/null
+++ b/backend/app/services/journey_sli_metrics.py
@@ -0,0 +1,222 @@
+"""Read-only matured SQL-intent cohort snapshots, never task-success counts.
+
+Windows apply to acceptance deadlines, not a success-only completion window.
+Every mature retained intent has exactly one outcome, including never-completed
+work. Replicas/restarts rederive the same absolute gauges; never sum replicas
+or use increase/rate on these gauges. These are current retained cohorts, not
+an immutable historical ledger: authorized retention and same-ID AI resumes
+can change prior outcomes. collect_bounded owns scrape timeout/freshness.
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+from dataclasses import dataclass
+from time import monotonic
+from copy import deepcopy
+from collections.abc import Iterator
+
+from prometheus_client import CollectorRegistry, generate_latest
+from prometheus_client.core import Metric
+from prometheus_client.registry import Collector
+
+from sqlalchemy import and_, case, extract, func, literal, or_, select, text
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.core.config import settings
+from app.core.metrics import (
+ journey_cohort_events, journey_cohort_observed_at, journey_source_supported,
+)
+from app.services.journey_sli_contracts import COHORT_OUTCOMES, JOURNEYS, WINDOWS
+
+CACHE_SECONDS = 30.0
+
+
+@dataclass(frozen=True)
+class _CachedSnapshot:
+ key: tuple[str, str, int]
+ expires_at: float
+ observed: datetime
+ exported: bytes
+
+
+_CACHE: _CachedSnapshot | None = None
+_PUBLISHED: _CachedSnapshot | None = None
+
+
+def _render_snapshot(*, installation: str, environment: str, observed: datetime, snapshot: dict) -> bytes:
+ # Unregistered templates never write native multiprocess metric files.
+ # Copies belong to this one completed snapshot; encoding is immutable.
+ events, timestamp, supported = deepcopy((journey_cohort_events, journey_cohort_observed_at, journey_source_supported))
+ scope = [installation, environment]
+ for contract in JOURNEYS:
+ supported.add_metric([*scope, contract.name], int(contract.supported and contract.name in snapshot))
+ for journey, values in snapshot.items():
+ for (window, outcome), count in values.items():
+ events.add_metric([*scope, journey, window, outcome], count)
+ timestamp.add_metric(scope, observed.timestamp())
+
+ class Bundle(Collector):
+ def collect(self) -> Iterator[Metric]:
+ return iter((events, timestamp, supported))
+
+ registry = CollectorRegistry()
+ registry.register(Bundle())
+ return generate_latest(registry)
+
+
+def render_journey_cohort_metrics() -> bytes:
+ """One serving-child bundle; append only after a successful bounded read.
+
+ Native multiprocess per-Gauge aggregation cannot preserve an atomic group
+ of changing outcome counts. This exact byte string keeps counts, support
+ and actual observation time together through concurrent child scrapes.
+ """
+ key = (settings.OBSERVABILITY_INSTALLATION, settings.APP_ENV, settings.AI_PIPELINE_DEADLINE_SECONDS)
+ return _PUBLISHED.exported if _PUBLISHED is not None and _PUBLISHED.key == key and key[0] else b""
+
+
+def _elapsed(db: AsyncSession, finished, accepted):
+ if db.get_bind().dialect.name == "sqlite":
+ # SQLite is supported only by isolated test fixtures. Its date math is
+ # millisecond precision, unlike PostgreSQL's native timestamp epoch.
+ return func.round((func.julianday(finished) - func.julianday(accepted)) * 86400, 3)
+ return extract("epoch", finished) - extract("epoch", accepted)
+
+
+def _classification(*, accepted, completed, status, known, success, seconds, now, elapsed, degraded=None):
+ invalid = or_(
+ ~status.in_(known),
+ and_(status.in_(success), or_(completed.is_(None), completed < accepted, completed > now)),
+ )
+ branches = [
+ (invalid, "unknown"),
+ (status == "failed", "failed"),
+ (and_(status.in_(success), elapsed > seconds), "late"),
+ ]
+ if degraded is not None:
+ branches.append((and_(status.in_(success), degraded), "degraded"))
+ branches.append((status.in_(success), "good"))
+ return case(*branches, else_="overdue")
+
+
+async def _counts_pair(db: AsyncSession, *, accepted, outcome, seconds: int, now: datetime,
+ second_outcome=None, subset=None) -> tuple[dict, dict]:
+ # Bound the database range, result cardinality and time budget. The outer
+ # collector additionally bounds connection/cancellation behavior.
+ latest = now - timedelta(seconds=seconds)
+ earliest = latest - timedelta(seconds=max(WINDOWS.values()))
+ columns = [outcome.label("outcome")]
+ if second_outcome is not None:
+ columns.append(second_outcome.label("second_outcome"))
+ columns.extend(func.sum(case((accepted > latest - timedelta(seconds=span), 1), else_=0)).label(name)
+ for name, span in WINDOWS.items())
+ if subset is not None:
+ columns.extend(func.sum(case((and_(accepted > latest - timedelta(seconds=span), subset), 1), else_=0)).label("subset_" + name)
+ for name, span in WINDOWS.items())
+ statement = select(*columns).where(accepted > earliest, accepted <= latest)
+ groups = (outcome, second_outcome) if second_outcome is not None else (outcome,)
+ rows = (await db.execute(statement.group_by(*groups))).all()
+ snapshot = {(window, name): 0 for window in WINDOWS for name in COHORT_OUTCOMES}
+ second = dict(snapshot)
+ for row in rows:
+ name = row[0]
+ second_name = row[1] if second_outcome is not None else name
+ offset = 2 if second_outcome is not None else 1
+ counts = row[offset:offset + len(WINDOWS)]
+ second_counts = row[offset + len(WINDOWS):] if subset is not None else counts
+ if name not in COHORT_OUTCOMES or second_name not in COHORT_OUTCOMES:
+ raise ValueError("unknown journey cohort outcome")
+ for window, count in zip(WINDOWS, counts):
+ snapshot[(window, name)] += int(count or 0)
+ for window, count in zip(WINDOWS, second_counts):
+ second[(window, second_name)] += int(count or 0)
+ return snapshot, second
+
+
+async def read_journey_cohorts(db: AsyncSession, *, now: datetime) -> dict:
+ """Derive all supported cohorts in one read-only repeatable snapshot."""
+ from app.models.postgres import AgentPipelineRun as Pipeline, RunDownstreamOutbox as Outbox
+ from app.services.run_downstream_outbox import (
+ EXECUTION_LEASE_SECONDS, FINALIZATION_RECOVERY_GRACE_SECONDS, _OPERATIONS,
+ )
+
+ # This conservative diagnostic deadline includes one finalization recovery
+ # grace plus one execution lease. It is proposed, not a product promise.
+ downstream_seconds = FINALIZATION_RECOVERY_GRACE_SECONDS + EXECUTION_LEASE_SECONDS
+ outbox_outcome = _classification(
+ accepted=Outbox.created_at, completed=Outbox.completed_at, status=Outbox.status,
+ known=("waiting", "pending", "sending", "published", "processing", "completed", "failed"),
+ success=("completed",), seconds=downstream_seconds, now=now,
+ elapsed=_elapsed(db, Outbox.completed_at, Outbox.created_at),
+ )
+ # Unknown operations cannot quietly count as successful work.
+ outbox_outcome = case((~Outbox.operation.in_(_OPERATIONS), literal("unknown")), else_=outbox_outcome)
+ downstream, live = await _counts_pair(
+ db, accepted=Outbox.created_at, outcome=outbox_outcome, seconds=downstream_seconds,
+ now=now, subset=Outbox.operation == "persist_live_session",
+ )
+ result = {"downstream": downstream, "live_materialization": live}
+ ai_seconds = settings.AI_PIPELINE_DEADLINE_SECONDS
+ # A zero pipeline deadline disables that execution bound. Do not invent
+ # an AI time objective or suppress otherwise valid outbox measurements.
+ if type(ai_seconds) is not int or ai_seconds <= 0:
+ return result
+ arguments = dict(
+ accepted=Pipeline.created_at, completed=Pipeline.completed_at, status=Pipeline.status,
+ known=("pending", "running", "retry_wait", "completed", "passed", "failed"),
+ success=("completed", "passed"), seconds=ai_seconds, now=now,
+ elapsed=_elapsed(db, Pipeline.completed_at, Pipeline.created_at),
+ )
+ quality = Pipeline.execution_metadata["stage_quality"].as_string()
+ # Preserve JSON type. Casting "false" or numeric 0 to SQL boolean would
+ # turn malformed/legacy metadata into positive full-quality evidence.
+ if db.get_bind().dialect.name == "sqlite":
+ explicit_no_fallback = func.json_type(Pipeline.execution_metadata, "$.fallback_used") == "false"
+ else:
+ explicit_no_fallback = and_(
+ func.json_typeof(Pipeline.execution_metadata["fallback_used"]) == "boolean",
+ Pipeline.execution_metadata["fallback_used"].as_string() == "false",
+ )
+ # No explicit quality evidence is not proof of a full-quality model result.
+ # The writer omits stage_quality for its normal path, but always persists
+ # fallback_used. Unknown quality markers are conservatively degraded too.
+ degraded = or_(explicit_no_fallback.is_distinct_from(True), and_(quality.is_not(None), quality != "normal"))
+ completion, full_quality = await _counts_pair(
+ db, accepted=Pipeline.created_at, outcome=_classification(**arguments),
+ second_outcome=_classification(**arguments, degraded=degraded), seconds=ai_seconds, now=now,
+ )
+ result.update(ai_completion=completion, ai_reported_full_quality=full_quality)
+ return result
+
+
+async def refresh_journey_cohort_metrics(*, now: datetime | None = None) -> bool:
+ """Publish a complete scoped snapshot, or leave prior values explicitly stale."""
+ global _CACHE, _PUBLISHED
+ installation, environment = settings.OBSERVABILITY_INSTALLATION, settings.APP_ENV
+ if not installation:
+ return True # no objective series, no database work, no inferred site
+ observed = now or datetime.now(timezone.utc)
+ if observed.tzinfo is None:
+ raise ValueError("journey observation requires timezone")
+ observed = observed.astimezone(timezone.utc)
+ key = (installation, environment, settings.AI_PIPELINE_DEADLINE_SECONDS)
+ cached = _CACHE if now is None else None # deterministic explicit-now tests bypass cache
+ if cached is not None and cached.key == key and monotonic() < cached.expires_at:
+ completed = cached
+ else:
+ from app.db.postgres import AsyncSessionLocal
+
+ async with AsyncSessionLocal() as db:
+ if db.get_bind().dialect.name == "postgresql":
+ # Both queries must see one committed state despite concurrent
+ # workers. Must precede the first data query in this transaction.
+ await db.execute(text("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"))
+ await db.execute(text("SET LOCAL statement_timeout = '750ms'"))
+ snapshot = await read_journey_cohorts(db, now=observed)
+ completed = _CachedSnapshot(key, monotonic() + CACHE_SECONDS, observed, _render_snapshot(
+ installation=installation, environment=environment, observed=observed, snapshot=snapshot,
+ ))
+ if now is None:
+ _CACHE = completed
+ _PUBLISHED = completed
+ return True
diff --git a/backend/app/services/metric_collection.py b/backend/app/services/metric_collection.py
index efab73167..7d8055b22 100644
--- a/backend/app/services/metric_collection.py
+++ b/backend/app/services/metric_collection.py
@@ -18,6 +18,7 @@
logger = structlog.get_logger(__name__)
COLLECTION_TIMEOUT_SECONDS = 1.0
COLLECTORS = ("queues", "agents", "downstream", "redis", "nightly", "digests", "pipeline_events")
+OPTIONAL_COLLECTORS = ("journeys",)
@dataclass
@@ -40,7 +41,7 @@ async def collect_bounded(
collector: str, refresh: Callable[[], Coroutine[Any, Any, bool]],
) -> bool:
"""Keep exposition available; failed reads never advance freshness."""
- if collector not in COLLECTORS:
+ if collector not in COLLECTORS and collector not in OPTIONAL_COLLECTORS:
raise ValueError("unknown metric collector")
# wait_for waits for cancellation cleanup, which can itself block on a
# failed database connection. Bound the foreground wait instead. Share
diff --git a/backend/app/services/test_case_lifecycle_service.py b/backend/app/services/test_case_lifecycle_service.py
index ad52b16c3..b4a992bbd 100644
--- a/backend/app/services/test_case_lifecycle_service.py
+++ b/backend/app/services/test_case_lifecycle_service.py
@@ -36,7 +36,6 @@
)
from app.services.test_management_audit_service import audit_event
from app.services.test_management_metrics_service import (
- stage_test_case_state_refresh,
stage_test_management_counter,
)
@@ -406,7 +405,6 @@ def stage_test_case_snapshot(
assignee_id=getattr(test_case, "assignee_id", None),
)
db.add(version)
- stage_test_case_state_refresh(db, test_case.project_id)
return version
diff --git a/backend/app/services/test_management_metrics_service.py b/backend/app/services/test_management_metrics_service.py
index 91222e33d..b42cc0e8f 100644
--- a/backend/app/services/test_management_metrics_service.py
+++ b/backend/app/services/test_management_metrics_service.py
@@ -1,20 +1,16 @@
"""Post-commit, best-effort metrics for test-case governance writes."""
from __future__ import annotations
-import uuid
-from typing import Awaitable, Callable, Iterable
+from typing import Iterable
import structlog
-from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.models.postgres import CanonicalTestCase, ManagedTestCase, TestCaseLifecycleState
+from app.core.metric_dimensions import ACTOR_ROLES, LIFECYCLE_STATES, bounded_dimension
logger = structlog.get_logger("services.test_management_metrics")
_QUEUE_KEY = "test_management_post_commit_metrics"
-_STATE_REFRESH_KEY = "test_management_state_metric_projects"
-_ORPHAN_REFRESH_KEY = "test_management_orphan_metric_projects"
def _emit_counter(name: str, label_values: tuple[str, ...]) -> None:
@@ -25,11 +21,18 @@ def _emit_counter(name: str, label_values: tuple[str, ...]) -> None:
)
if name == "transition":
- test_case_transitions_total.labels(*label_values).inc()
+ # Services keep the transaction payload's project identity for their
+ # domain boundary. It is never a Prometheus dimension.
+ _project, previous, current, role = label_values
+ test_case_transitions_total.labels(
+ bounded_dimension(previous, LIFECYCLE_STATES),
+ bounded_dimension(current, LIFECYCLE_STATES),
+ bounded_dimension(role, ACTOR_ROLES),
+ ).inc()
elif name == "promotion":
- test_case_promotions_total.labels(*label_values).inc()
+ test_case_promotions_total.inc()
elif name == "deprecation_without_reason":
- test_case_deprecations_without_reason_total.labels(*label_values).inc()
+ test_case_deprecations_without_reason_total.inc()
else:
raise ValueError(f"Unknown test-management counter: {name}")
@@ -56,110 +59,19 @@ def stage_test_management_counter(
logger.warning("test_management_metric_failed", metric=name)
-def _stage_project_refresh(db: AsyncSession, key: str, project_id: uuid.UUID) -> None:
- info = getattr(db, "info", None)
- if isinstance(info, dict):
- info.setdefault(key, set()).add(project_id)
-
-
-def stage_test_case_state_refresh(db: AsyncSession, project_id: uuid.UUID) -> None:
- _stage_project_refresh(db, _STATE_REFRESH_KEY, project_id)
-
-
-def stage_orphan_gauge_refresh(db: AsyncSession, project_id: uuid.UUID) -> None:
- _stage_project_refresh(db, _ORPHAN_REFRESH_KEY, project_id)
-
-
-async def _refresh_state_gauge(db: AsyncSession, project_id: uuid.UUID) -> None:
- from app.core.metrics import test_cases_by_state
-
- result = await db.execute(
- select(ManagedTestCase.status, func.count(ManagedTestCase.id))
- .where(ManagedTestCase.project_id == project_id)
- .group_by(ManagedTestCase.status)
- )
- counts = {state: int(count) for state, count in result.all()}
- for state in TestCaseLifecycleState:
- test_cases_by_state.labels(str(project_id), state.value).set(
- counts.get(state.value, 0)
- )
-
-
-async def _refresh_orphan_gauge(db: AsyncSession, project_id: uuid.UUID) -> None:
- from app.core.metrics import automation_cases_orphaned
-
- count = int(
- (
- await db.execute(
- select(func.count(CanonicalTestCase.id)).where(
- CanonicalTestCase.project_id == project_id,
- CanonicalTestCase.status == "deleted",
- CanonicalTestCase.retirement_confirmed_at.is_(None),
- )
- )
- ).scalar()
- or 0
- )
- automation_cases_orphaned.labels(str(project_id)).set(count)
-
-
-async def _run_gauge_refresh(
- request_db: AsyncSession,
- refresh: Callable[[AsyncSession, uuid.UUID], Awaitable[None]],
- project_id: uuid.UUID,
-) -> None:
- """Keep best-effort post-commit reads off the request transaction.
-
- PostgreSQL marks a transaction failed after a statement error. Reusing
- the request session for gauge reads could therefore turn an already-
- committed mutation into a response-time 500. Production AsyncSessions
- receive a short-lived read session; lightweight unit doubles keep using
- themselves.
- """
- if not isinstance(request_db, AsyncSession):
- await refresh(request_db, project_id)
- return
-
- from app.db.postgres import get_session_factory
-
- session_factory = get_session_factory()
- async with session_factory() as metrics_db:
- await refresh(metrics_db, project_id)
-
-
async def emit_staged_test_management_metrics(db: AsyncSession) -> None:
info = getattr(db, "info", None)
if not isinstance(info, dict):
return
queued = list(info.pop(_QUEUE_KEY, []))
- state_projects = set(info.pop(_STATE_REFRESH_KEY, set()))
- orphan_projects = set(info.pop(_ORPHAN_REFRESH_KEY, set()))
for name, values in queued:
try:
_emit_counter(name, values)
except Exception:
logger.warning("test_management_metric_failed", metric=name)
- for project_id in state_projects:
- try:
- await _run_gauge_refresh(db, _refresh_state_gauge, project_id)
- except Exception:
- logger.warning(
- "test_management_state_metric_failed",
- project_id=str(project_id),
- )
- for project_id in orphan_projects:
- try:
- await _run_gauge_refresh(db, _refresh_orphan_gauge, project_id)
- except Exception:
- logger.warning(
- "automation_orphan_metric_failed",
- project_id=str(project_id),
- )
def discard_staged_test_management_metrics(db: AsyncSession) -> None:
info = getattr(db, "info", None)
if isinstance(info, dict):
info.pop(_QUEUE_KEY, None)
- info.pop(_STATE_REFRESH_KEY, None)
- info.pop(_ORPHAN_REFRESH_KEY, None)
diff --git a/backend/app/services/test_suite_service.py b/backend/app/services/test_suite_service.py
index d1c8d72c9..ff1b27513 100644
--- a/backend/app/services/test_suite_service.py
+++ b/backend/app/services/test_suite_service.py
@@ -44,10 +44,8 @@
TestSuiteOwner,
User,
)
-from app.core.metrics import automation_cases_orphaned
from app.services.test_management_audit_service import audit_event
from app.services.test_management_metrics_service import (
- stage_orphan_gauge_refresh,
stage_test_management_counter,
)
from app.services.test_case_lifecycle_service import stage_test_case_snapshot
@@ -590,7 +588,6 @@ async def sync_canonical_test_cases(
tc.canonical_test_case_id = canonical.id
counts["linked"] += 1
- stage_orphan_gauge_refresh(db, project_id)
logger.info(
"canonical_sync_complete",
project_id=str(project_id),
@@ -1333,7 +1330,6 @@ async def confirm_canonical_retirement(
old_values={"retirement_confirmed_at": None},
new_values={"retirement_confirmed_at": canonical.retirement_confirmed_at.isoformat()},
)
- stage_orphan_gauge_refresh(db, canonical.project_id)
await db.flush()
return canonical
@@ -1366,29 +1362,6 @@ async def list_orphaned_canonical_cases(
)
).scalars().all()
)
- count_stmt = select(
- CanonicalTestCase.project_id,
- func.count(CanonicalTestCase.id),
- ).where(
- CanonicalTestCase.status == "deleted",
- CanonicalTestCase.retirement_confirmed_at.is_(None),
- )
- if project_ids is not None:
- count_stmt = count_stmt.where(CanonicalTestCase.project_id.in_(project_ids))
- count_rows = await db.execute(count_stmt.group_by(CanonicalTestCase.project_id))
- counts = {project_id: int(count) for project_id, count in count_rows.all()}
- # Explicitly reset scoped projects with no rows; otherwise a previous
- # non-zero gauge remains stale forever after the queue is cleared.
- if project_ids is None:
- all_project_rows = await db.execute(select(Project.id))
- metric_project_ids = list(all_project_rows.scalars().all())
- else:
- metric_project_ids = project_ids
- for project_id in metric_project_ids:
- try:
- automation_cases_orphaned.labels(str(project_id)).set(counts.get(project_id, 0))
- except Exception:
- logger.warning("automation_orphan_metric_failed", project_id=str(project_id))
return rows, total
@@ -1647,7 +1620,6 @@ async def reconcile_canonical_deletions(
"""
from app.core.config import settings
- stage_orphan_gauge_refresh(db, project_id)
effective_window = (
window_runs if window_runs is not None
else settings.CANONICAL_DELETION_WINDOW_RUNS
diff --git a/backend/app/services/workflow_evaluation_service.py b/backend/app/services/workflow_evaluation_service.py
index 8bb1a44e5..c6cfe0227 100644
--- a/backend/app/services/workflow_evaluation_service.py
+++ b/backend/app/services/workflow_evaluation_service.py
@@ -17,7 +17,6 @@
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
-from app.core.metrics import workflow_eval_coverage
from app.models.postgres import (
AIEvalGateRun,
AgentPipelineRun,
@@ -947,9 +946,6 @@ async def evaluate_definition(
row.eval_regression_accepted_by = None
row.eval_regression_accepted_at = None
await db.flush()
- workflow_eval_coverage.labels(
- project_id=str(project_id), workflow_id=row.workflow_id
- ).set(result["coverage"])
result["gate_run_id"] = str(gate.id)
return result
diff --git a/backend/app/worker/celery_app.py b/backend/app/worker/celery_app.py
index 748a36e04..eebe77c47 100644
--- a/backend/app/worker/celery_app.py
+++ b/backend/app/worker/celery_app.py
@@ -1,5 +1,6 @@
"""Celery application configuration."""
from datetime import timedelta
+from functools import lru_cache
from pathlib import Path
import re
from collections.abc import Mapping
@@ -880,19 +881,33 @@ def _record_task_runtime(task_id=None, task=None, **_kwargs: object) -> None:
return
try:
from app.core.metrics import celery_task_runtime_seconds
+ from app.core.metric_dimensions import task_queue_family
queue = ""
request = getattr(task, "request", None)
if request is not None:
queue = getattr(request, "delivery_info", {}).get("routing_key", "") or ""
celery_task_runtime_seconds.labels(
- task_name=getattr(task, "name", "unknown"),
- queue_name=queue or "unknown",
+ task_name=_metric_task_name(task),
+ queue_name=task_queue_family(queue),
).observe(time.perf_counter() - started)
except Exception: # noqa: BLE001 — metrics must never break the task
pass
+@lru_cache(maxsize=1)
+def _metric_task_names() -> frozenset[str]:
+ """Freeze deployed task identities, never growing with received headers."""
+ from app.core.metric_dimensions import MAX_METRIC_TASK_NAMES
+
+ return frozenset(sorted(celery_app.tasks)[:MAX_METRIC_TASK_NAMES])
+
+
+def _metric_task_name(task: object) -> str:
+ name = getattr(task, "name", None)
+ return name if isinstance(name, str) and name in _metric_task_names() else "other"
+
+
@task_postrun.connect
def _record_task_outcome(task_id=None, task=None, state=None, **_kwargs: object) -> None:
"""Count task outcomes so failure and retry are visible to Prometheus.
@@ -908,17 +923,16 @@ def _record_task_outcome(task_id=None, task=None, state=None, **_kwargs: object)
that has failed terminally — queue depth cannot, because a task waiting
on a retry countdown is not on the queue at all.
- ``state`` is Celery's terminal state for this execution: SUCCESS, FAILURE
- or RETRY. Lower-cased verbatim rather than mapped through a table, so an
- unexpected state (REVOKED, REJECTED) reports itself instead of being
- folded into an "other" bucket that means nothing to the reader.
+ Known Celery states retain their names; custom states share ``other``.
+ Task names must belong to the frozen, capped deployed code registry.
"""
try:
from app.core.metrics import celery_tasks_total
+ from app.core.metric_dimensions import TASK_STATES, bounded_dimension
celery_tasks_total.labels(
- task_name=getattr(task, "name", "unknown"),
- status=str(state or "unknown").lower(),
+ task_name=_metric_task_name(task),
+ status=bounded_dimension(str(state or "unknown").lower(), TASK_STATES),
).inc()
except Exception: # noqa: BLE001 — metrics must never break the task
pass
diff --git a/backend/migrations/versions/0264_journey_cohort_indexes.py b/backend/migrations/versions/0264_journey_cohort_indexes.py
new file mode 100644
index 000000000..dbc77b915
--- /dev/null
+++ b/backend/migrations/versions/0264_journey_cohort_indexes.py
@@ -0,0 +1,44 @@
+"""Index retained SQL-intent acceptance cohorts without blocking writers.
+
+Revision ID: 0264
+Revises: 0263
+
+Both indexes have ORM twins. No columns, rows, policy defaults or historical
+outcomes change. Failed concurrent builds can leave invalid indexes; a retry
+drops only such a named index resolved in the current schema before rebuilding.
+"""
+import sqlalchemy as sa
+from alembic import op
+
+revision = "0264"
+down_revision = "0263"
+branch_labels = None
+depends_on = None
+
+INDEXES = (
+ ("ix_run_downstream_outbox_created_at", "run_downstream_outbox"),
+ ("ix_agent_pipeline_runs_created_at", "agent_pipeline_runs"),
+)
+
+
+def _index_is_invalid(bind, name: str) -> bool:
+ return bool(bind.execute(sa.text(
+ "SELECT 1 FROM pg_index WHERE indexrelid = to_regclass(:name) AND NOT indisvalid"
+ ), {"name": name}).first())
+
+
+def upgrade() -> None:
+ invalid = set() if op.get_context().as_sql else {
+ name for name, _table in INDEXES if _index_is_invalid(op.get_bind(), name)
+ }
+ with op.get_context().autocommit_block():
+ for name, table in INDEXES:
+ if name in invalid:
+ op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {name}")
+ op.execute(f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {name} ON {table} (created_at)")
+
+
+def downgrade() -> None:
+ with op.get_context().autocommit_block():
+ for name, _table in reversed(INDEXES):
+ op.execute(f"DROP INDEX CONCURRENTLY IF EXISTS {name}")
diff --git a/backend/tests/integration/test_journey_sli_postgres.py b/backend/tests/integration/test_journey_sli_postgres.py
new file mode 100644
index 000000000..f13de11dd
--- /dev/null
+++ b/backend/tests/integration/test_journey_sli_postgres.py
@@ -0,0 +1,143 @@
+"""Optional retained-intent workload proof against disposable PostgreSQL.
+
+Only isolated LIKE copies receive synthetic rows. No public rows, workers,
+queues, integrations, or live application databases are modified.
+"""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+import os
+from pathlib import Path
+import importlib.util
+import uuid
+
+import pytest
+from sqlalchemy import select, text, update
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+
+from app.core.config import settings
+from app.models.postgres import AgentPipelineRun as Pipeline, RunDownstreamOutbox as Outbox
+from app.services import journey_sli_metrics as service
+from app.services.journey_sli_contracts import COHORT_OUTCOMES
+
+pytestmark = [pytest.mark.integration, pytest.mark.asyncio]
+
+
+async def test_native_cohort_workload_rederives_across_independent_readers(monkeypatch):
+ dsn = os.getenv("TESTLOOKUP_POSTGRES_TEST_DSN", "").strip()
+ if not dsn:
+ pytest.skip("TESTLOOKUP_POSTGRES_TEST_DSN is not configured")
+ schema = "journey_sli_proof_" + uuid.uuid4().hex
+ control = create_async_engine(dsn)
+ engine = None
+ try:
+ async with control.begin() as connection:
+ await connection.execute(text(f'CREATE SCHEMA "{schema}"'))
+ for table in ("run_downstream_outbox", "agent_pipeline_runs"):
+ await connection.execute(text(f'CREATE TABLE "{schema}"."{table}" (LIKE public."{table}" INCLUDING ALL)'))
+ engine = create_async_engine(dsn, connect_args={"server_settings": {"search_path": schema + ",public"}})
+ migration_path = Path(service.__file__).resolve().parents[2] / "migrations/versions/0264_journey_cohort_indexes.py"
+ spec = importlib.util.spec_from_file_location("journey_indexes_native_proof", migration_path)
+ migration = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(migration)
+
+ def migrate(connection, direction):
+ context = MigrationContext.configure(connection)
+ with context.begin_transaction():
+ with Operations.context(context):
+ getattr(migration, direction)()
+
+ async with engine.connect() as connection:
+ await connection.run_sync(lambda sync: migrate(sync, "upgrade"))
+ await connection.run_sync(lambda sync: migrate(sync, "upgrade")) # idempotent retry
+ async with engine.begin() as connection:
+ rows = (await connection.execute(text(
+ "SELECT indexname, indexdef FROM pg_indexes WHERE schemaname=:schema AND indexname IN "
+ "('ix_run_downstream_outbox_created_at','ix_agent_pipeline_runs_created_at')"
+ ), {"schema": schema})).all()
+ assert len(rows) == 2 and all(definition.endswith("(created_at)") for _name, definition in rows)
+ for name, table in migration.INDEXES:
+ model = Outbox if table == "run_downstream_outbox" else Pipeline
+ orm = next(index for index in model.__table__.indexes if index.name == name)
+ assert [column.name for column in orm.columns] == ["created_at"]
+ sessions = async_sessionmaker(engine, expire_on_commit=False)
+ monkeypatch.setattr(settings, "OBSERVABILITY_INSTALLATION", "synthetic-pg-site")
+ monkeypatch.setattr(settings, "AI_PIPELINE_DEADLINE_SECONDS", 1500)
+ from app.db import postgres
+ monkeypatch.setattr(postgres, "AsyncSessionLocal", sessions)
+ now = datetime.now(timezone.utc)
+ accepted = now - timedelta(seconds=7200)
+ async with sessions() as db:
+ for status in ("waiting", "pending", "sending", "published", "processing", "completed", "failed"):
+ db.add(Outbox(
+ id=uuid.uuid4(), run_id=uuid.uuid4(), project_id=uuid.uuid4(),
+ operation="persist_live_session", input_version="a" * 64, status=status,
+ created_at=accepted, completed_at=accepted + timedelta(seconds=10) if status == "completed" else None,
+ ))
+ db.add(Outbox(id=uuid.uuid4(), run_id=uuid.uuid4(), project_id=uuid.uuid4(), operation="run_notifications",
+ input_version="b" * 64, status="completed", created_at=accepted,
+ completed_at=accepted + timedelta(seconds=4201)))
+ for quality in ({"fallback_used": False}, {"fallback_used": True},
+ *({"fallback_used": value} for value in (0, "false", None, [], {}))):
+ db.add(Pipeline(id=uuid.uuid4(), test_run_id=uuid.uuid4(), status="completed",
+ created_at=now - timedelta(seconds=2000), completed_at=now - timedelta(seconds=1900),
+ execution_metadata=quality))
+ await db.commit()
+ assert await service.refresh_journey_cohort_metrics(now=now)
+ # A different API process/session has no local event checkpoint; it
+ # derives exactly the same logical-intent denominator after restart.
+ async with sessions() as db:
+ first = await service.read_journey_cohorts(db, now=now)
+ assert {name: first["downstream"][("1h", name)] for name in COHORT_OUTCOMES} == {
+ "good": 1, "failed": 1, "late": 1, "overdue": 5, "degraded": 0, "unknown": 0,
+ }
+ assert first["ai_reported_full_quality"][("1h", "good")] == 1
+ assert first["ai_reported_full_quality"][("1h", "degraded")] == 6
+ async with sessions() as db:
+ await db.execute(update(Outbox).values(attempts=5, execution_attempts=2))
+ await db.commit()
+ async with sessions() as db:
+ assert await service.read_journey_cohorts(db, now=now) == first
+ pending = (await db.execute(select(Outbox).where(Outbox.status == "pending"))).scalar_one()
+ pending.status, pending.completed_at = "completed", now
+ await db.commit()
+ async with sessions() as db:
+ recovered = await service.read_journey_cohorts(db, now=now)
+ assert recovered["downstream"][("1h", "overdue")] == 4
+ assert recovered["downstream"][("1h", "late")] == 2
+ assert sum(recovered["downstream"][("1h", name)] for name in COHORT_OUTCOMES) == 8
+ # Enough old retained history to verify natural selective horizon
+ # plans. This is index eligibility evidence, not a capacity benchmark.
+ async with engine.begin() as connection:
+ await connection.execute(text(
+ "INSERT INTO run_downstream_outbox (id,run_id,project_id,operation,input_version,payload,queue,priority,"
+ "status,attempts,dispatch_failures,execution_attempts,created_at,completed_at) "
+ "SELECT gen_random_uuid(),gen_random_uuid(),gen_random_uuid(),'run_notifications',repeat('c',64),"
+ "'{}'::jsonb,'default',5,'completed',0,0,0, :old,:old FROM generate_series(1,20000)"
+ ), {"old": now - timedelta(days=365)})
+ await connection.execute(text(
+ "INSERT INTO agent_pipeline_runs (id,test_run_id,workflow_type,status,attempt,max_attempts,spawn_depth,cancel_requested,"
+ "review_policy,created_at,completed_at) SELECT gen_random_uuid(),gen_random_uuid(),'offline','completed',1,5,0,false,"
+ "'not_applicable',:old,:old FROM generate_series(1,20000)"
+ ), {"old": now - timedelta(days=365)})
+ for table in ("run_downstream_outbox", "agent_pipeline_runs"):
+ await connection.execute(text(f"ANALYZE {table}"))
+ plan = " ".join((await connection.execute(text(
+ f"EXPLAIN (COSTS OFF) SELECT count(*) FROM {table} WHERE created_at > :earliest AND created_at <= :latest"
+ ), {"earliest": now - timedelta(days=30), "latest": now - timedelta(seconds=4200)})).scalars())
+ assert "Index" in plan and "created_at" in plan
+ async with engine.connect() as connection:
+ await connection.run_sync(lambda sync: migrate(sync, "downgrade"))
+ async with engine.begin() as connection:
+ assert (await connection.execute(text(
+ "SELECT count(*) FROM pg_indexes WHERE schemaname=:schema AND indexname IN "
+ "('ix_run_downstream_outbox_created_at','ix_agent_pipeline_runs_created_at')"
+ ), {"schema": schema})).scalar_one() == 0
+ finally:
+ if engine is not None:
+ await engine.dispose()
+ async with control.begin() as connection:
+ await connection.execute(text(f'DROP SCHEMA IF EXISTS "{schema}" CASCADE'))
+ await control.dispose()
diff --git a/backend/tests/regression/test_alert_rules_are_deployable.py b/backend/tests/regression/test_alert_rules_are_deployable.py
index f0a967ead..3479a5948 100644
--- a/backend/tests/regression/test_alert_rules_are_deployable.py
+++ b/backend/tests/regression/test_alert_rules_are_deployable.py
@@ -26,6 +26,8 @@
REPO_ROOT = Path(__file__).resolve().parents[3]
ALERTS = REPO_ROOT / "infra" / "monitoring" / "prometheus-rules" / "testlookup-alerts.yml"
PROMETHEUS_RULE = REPO_ROOT / "k8s" / "monitoring" / "prometheusrule.yaml"
+OBJECTIVES = REPO_ROOT / "infra" / "monitoring" / "objectives"
+OBJECTIVE_OVERLAY = REPO_ROOT / "k8s" / "monitoring-objectives"
METRICS = REPO_ROOT / "backend" / "app" / "core" / "metrics.py"
PIPELINE = REPO_ROOT / "backend" / "app" / "services" / "ingestion_pipeline.py"
@@ -96,7 +98,7 @@ def _declared_metrics() -> set[str]:
names = set()
for node in ast.walk(tree):
if (isinstance(node, ast.Call)
- and getattr(node.func, "id", "") in {"Counter", "Gauge", "Histogram", "Summary"}
+ and getattr(node.func, "id", "") in {"Counter", "Gauge", "Histogram", "Summary", "GaugeMetricFamily"}
and node.args and isinstance(node.args[0], ast.Constant)):
names.add(node.args[0].value)
return names
@@ -143,6 +145,23 @@ def test_the_rule_is_opt_in_not_in_base() -> None:
assert not any("monitoring" in str(r) or "prometheusrule" in str(r) for r in base["resources"])
+def test_api_objectives_have_opt_in_deployment_parity() -> None:
+ source = OBJECTIVES / "api-slos.yml"
+ rules = yaml.safe_load(source.read_text(encoding="utf-8"))["groups"]
+ operator = yaml.safe_load((OBJECTIVE_OVERLAY / "prometheusrule.yaml").read_text(encoding="utf-8"))
+ assert operator["kind"] == "PrometheusRule"
+ assert operator["spec"]["groups"] == rules
+ assert not source.is_relative_to(ALERTS.parent)
+ compose = yaml.safe_load((REPO_ROOT / "docker-compose.objectives.yml").read_text(encoding="utf-8"))
+ prometheus = compose["services"]["prometheus"]
+ assert "--storage.tsdb.retention.time=35d" in prometheus["command"]
+ assert any("--storage.tsdb.retention.size=${SLO_PROMETHEUS_RETENTION_SIZE:?" in flag for flag in prometheus["command"])
+ assert "./infra/monitoring/objectives/api-slos.yml:/etc/prometheus/rules/api-slos.yml:ro" in prometheus["volumes"]
+ adoption = next(mount for mount in prometheus["volumes"] if isinstance(mount, dict))
+ assert adoption["target"] == "/etc/prometheus/rules/slo-adoption.yml" and adoption["read_only"]
+ assert adoption["source"].endswith(":-./infra/monitoring/objectives/adoption.example.yml}")
+
+
def test_semantic_fixtures_execute_in_the_existing_backend_ci_job() -> None:
"""A fixture outside the runtime glob must be executed, not merely committed."""
workflow = yaml.safe_load((REPO_ROOT / ".github/workflows/ci.yml").read_text(encoding="utf-8"))
@@ -151,12 +170,14 @@ def test_semantic_fixtures_execute_in_the_existing_backend_ci_job() -> None:
assert not step.get("continue-on-error") and not step.get("if")
assert step["working-directory"] == "."
compose = yaml.safe_load((REPO_ROOT / "docker-compose.monitoring.yml").read_text(encoding="utf-8"))
- runtime_version = compose["services"]["prometheus"]["image"].rsplit(":", 1)[1].lstrip("v")
+ runtime_image = compose["services"]["prometheus"]["image"].split("@", 1)[0]
+ runtime_version = runtime_image.rsplit(":", 1)[1].lstrip("v")
assert step["env"]["PROMETHEUS_VERSION"] == runtime_version
assert re.fullmatch(r"[0-9a-f]{64}", step["env"]["PROMETHEUS_ARCHIVE_SHA256"])
commands = step["run"]
assert commands.index("sha256sum --check --strict") < commands.index("tar -xzf")
assert '"$tool" check rules "$monitoring/prometheus-rules/testlookup-alerts.yml"' in commands
+ assert '"$tool" check rules "$monitoring/objectives/api-slos.yml"' in commands
assert '"$tool" test rules "$monitoring"/tests/*.yml' in commands
assert '"$tool" check config "$scratch/config/prometheus.yml"' in commands
assert "python -m pytest scripts/monitoring/tests -q" in commands
diff --git a/backend/tests/regression/test_alerted_metrics_are_emitted.py b/backend/tests/regression/test_alerted_metrics_are_emitted.py
index 55678b545..360b6db6a 100644
--- a/backend/tests/regression/test_alerted_metrics_are_emitted.py
+++ b/backend/tests/regression/test_alerted_metrics_are_emitted.py
@@ -66,7 +66,7 @@ def test_each_terminal_state_is_counted(self, state, expected):
import app.worker.celery_app # noqa: F401 (registers the receivers)
- task = _Task(f"app.worker.tasks.probe_{expected}")
+ task = _Task("celery.group")
before = _counter(metrics.celery_tasks_total, task_name=task.name, status=expected)
task_postrun.send(sender=None, task_id="t1", task=task, state=state)
after = _counter(metrics.celery_tasks_total, task_name=task.name, status=expected)
@@ -83,12 +83,13 @@ def test_an_unexpected_state_reports_itself(self):
import app.worker.celery_app # noqa: F401
- task = _Task("app.worker.tasks.probe_revoked")
+ task = _Task("celery.group")
+ before = _counter(metrics.celery_tasks_total, task_name=task.name, status="revoked")
task_postrun.send(sender=None, task_id="t2", task=task, state="REVOKED")
assert _counter(
metrics.celery_tasks_total, task_name=task.name, status="revoked"
- ) == 1.0
+ ) == before + 1
def test_instrumentation_never_raises(self):
"""A metrics failure must not fail the task it is measuring."""
diff --git a/backend/tests/regression/test_grafana_dashboard_metrics_are_declared.py b/backend/tests/regression/test_grafana_dashboard_metrics_are_declared.py
index 9093d6e20..888cdea2d 100644
--- a/backend/tests/regression/test_grafana_dashboard_metrics_are_declared.py
+++ b/backend/tests/regression/test_grafana_dashboard_metrics_are_declared.py
@@ -35,6 +35,7 @@
pytest.importorskip("prometheus_client")
from prometheus_client.metrics import MetricWrapperBase # noqa: E402
+from prometheus_client.core import Metric # noqa: E402
from app.core import metrics # noqa: E402
@@ -95,6 +96,12 @@ def exported_series(module: Any = metrics) -> dict[str, str]:
"""Every series name the declared metrics export -> the declared name."""
out: dict[str, str] = {}
for value in vars(module).values():
+ if isinstance(value, Metric):
+ # Unregistered custom-collector templates are emitted as one
+ # coherent per-scrape bundle, never native multiprocess Gauges.
+ for suffix in _EXPORTED_SUFFIXES.get(value.type, ("",)):
+ out[value.name + suffix] = value.name
+ continue
if not isinstance(value, MetricWrapperBase):
continue
stored, kind = value._name, value._type
diff --git a/backend/tests/regression/test_health_dashboards_need_a_sign_in.py b/backend/tests/regression/test_health_dashboards_need_a_sign_in.py
index 4e9e2c7d3..6107b15f4 100644
--- a/backend/tests/regression/test_health_dashboards_need_a_sign_in.py
+++ b/backend/tests/regression/test_health_dashboards_need_a_sign_in.py
@@ -19,7 +19,7 @@
import json
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, Mock, patch
import pytest
from fastapi import FastAPI
@@ -224,6 +224,46 @@ async def test_metrics_stays_open_when_no_token_is_set(monkeypatch):
assert "# HELP" in response.text
+@pytest.mark.parametrize(("installation", "refresh_succeeds"), [
+ ("scope-fixture", True), ("failing-scope-fixture", False), ("", False),
+])
+async def test_api_objective_and_cohort_collection_follow_explicit_configuration(monkeypatch, installation, refresh_succeeds):
+ from prometheus_client.parser import text_string_to_metric_families
+
+ from app.services import metric_collection
+
+ monkeypatch.setattr(settings, "METRICS_ENABLED", True)
+ monkeypatch.setattr(settings, "METRICS_TOKEN", SCRAPE_TOKEN)
+ monkeypatch.setattr(settings, "METRICS_TOKEN_FILE", "")
+ monkeypatch.setattr(settings, "OBSERVABILITY_INSTALLATION", installation)
+ app = _metrics_app(monkeypatch)
+ metric_collection.collect_bounded.return_value = refresh_succeeds
+ render = Mock(return_value=b"testlookup_journey_cohort_fixture 7\n")
+ monkeypatch.setattr("app.services.journey_sli_metrics.render_journey_cohort_metrics", render)
+
+ @app.get("/api/v1/projects")
+ async def projects():
+ return []
+
+ async with _client(app) as client:
+ assert (await client.get("/api/v1/projects")).status_code == 200
+ assert (await client.get("/metrics")).status_code == 401
+ metric_collection.collect_bounded.assert_not_awaited()
+ response = await client.get("/metrics", headers={"Authorization": "Bearer " + SCRAPE_TOKEN})
+
+ assert response.status_code == 200
+ assert int(response.headers["content-length"]) == len(response.content)
+ assert (b"testlookup_journey_cohort_fixture 7\n" in response.content) == refresh_succeeds
+ assert render.call_count == int(refresh_succeeds)
+ collected = {call.args[0] for call in metric_collection.collect_bounded.await_args_list}
+ assert ("journeys" in collected) == bool(installation)
+ matched = [sample for family in text_string_to_metric_families(response.text)
+ for sample in family.samples if sample.name == "testlookup_api_journey_events_total"
+ and sample.labels == {"installation": installation, "environment": settings.APP_ENV,
+ "objective": "api_availability", "outcome": "good"}]
+ assert [sample.value for sample in matched] == ([1] if installation else [])
+
+
async def test_a_refused_scrape_does_not_refresh_the_queue_depths(monkeypatch):
"""The per-scrape collector wraps the route; the refusal must come first."""
monkeypatch.setattr(settings, "METRICS_ENABLED", True)
diff --git a/backend/tests/regression/test_operational_metric_dimensions.py b/backend/tests/regression/test_operational_metric_dimensions.py
new file mode 100644
index 000000000..c67449829
--- /dev/null
+++ b/backend/tests/regression/test_operational_metric_dimensions.py
@@ -0,0 +1,254 @@
+"""Operational series stay bounded while domain identities remain available."""
+from __future__ import annotations
+
+import ast
+import json
+import os
+import subprocess
+import sys
+import uuid
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from app.core import metric_dimensions as dimensions
+from app.models.postgres import TestCaseLifecycleState as LifecycleState, UserRole
+
+
+def test_deployed_static_stages_and_governance_enums_fit_reviewed_inventory():
+ agents = Path(__file__).resolve().parents[2] / "app" / "agents"
+ declared = set()
+ for path in agents.rglob("*.py"):
+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
+ if isinstance(node, ast.ClassDef):
+ for statement in node.body:
+ if isinstance(statement, ast.Assign) and any(
+ isinstance(target, ast.Name) and target.id == "stage_name"
+ for target in statement.targets
+ ) and isinstance(statement.value, ast.Constant):
+ declared.add(statement.value.value)
+ assert declared <= dimensions.STAGE_NAMES
+ assert {state.value for state in LifecycleState} | {"other"} == dimensions.LIFECYCLE_STATES
+ assert {role.value for role in UserRole} | {"other"} == dimensions.ACTOR_ROLES
+
+
+@pytest.mark.asyncio
+async def test_custom_workflow_step_and_free_text_never_become_metric_labels(monkeypatch):
+ from app.agents import base
+ from app.services.workflow_step_context import workflow_step_scope
+
+ class Agent(base.BaseAgent):
+ stage_name = "summary"
+
+ async def run(self, state):
+ return state
+
+ stage = SimpleNamespace(id=uuid.uuid4(), attempt=1)
+ db = SimpleNamespace(
+ execute=AsyncMock(side_effect=[
+ SimpleNamespace(scalar_one_or_none=lambda: None),
+ SimpleNamespace(scalar_one_or_none=lambda: stage),
+ SimpleNamespace(scalar_one_or_none=lambda: stage),
+ ]), flush=AsyncMock(), commit=AsyncMock(),
+ )
+
+ class Session:
+ async def __aenter__(self):
+ return db
+
+ async def __aexit__(self, *_args):
+ return False
+
+ monkeypatch.setattr(base, "AsyncSessionLocal", Session)
+ event = AsyncMock()
+ monkeypatch.setattr(base, "emit_event", event)
+ names = (
+ "pipeline_stage_duration_seconds", "pipeline_stage_runs_total",
+ "pipeline_stage_tokens_total", "pipeline_stage_cost_usd",
+ "pipeline_stage_llm_calls_total", "pipeline_fallback_total",
+ "pipeline_stage_errors_by_category",
+ )
+ instruments = {name: Mock() for name in names}
+ for name, instrument in instruments.items():
+ monkeypatch.setattr(base, name, instrument)
+ custom_id = "customer-workflow-step-" + uuid.uuid4().hex
+ reason = "provider response with arbitrary per-request detail"
+ category = "customer-exception-" + uuid.uuid4().hex
+ agent = Agent()
+ with workflow_step_scope(custom_id):
+ await agent.mark_stage_done(
+ str(uuid.uuid4()), error="failed", input_tokens=2, output_tokens=3,
+ llm_calls_count=1, cost_usd=0.1, fallback_reason=reason, error_category=category,
+ )
+
+ for instrument in instruments.values():
+ assert instrument.labels.call_count >= 1
+ assert {call.kwargs["stage_name"] for call in instrument.labels.call_args_list} == {"summary"}
+ instruments["pipeline_fallback_total"].labels.assert_called_once_with(stage_name="summary", reason="other")
+ instruments["pipeline_stage_errors_by_category"].labels.assert_called_once_with(stage_name="summary", error_category="other")
+ assert stage.fallback_reason == reason
+ assert stage.error_category == category
+ assert event.await_args.kwargs["stage_name"] == custom_id
+ assert event.await_args.kwargs["detail"]["fallback_reason"] == reason
+ assert event.await_args.kwargs["detail"]["error_category"] == category
+ # The SQL predicate still addresses the authored runtime step.
+ assert custom_id in db.execute.await_args_list[2].args[0].compile().params.values()
+
+
+def test_task_registry_is_frozen_and_hard_capped(monkeypatch):
+ from app.worker import celery_app as worker
+
+ registry = {f"registered.{index:04d}": object() for index in range(1000)}
+ monkeypatch.setattr(worker, "celery_app", SimpleNamespace(tasks=registry))
+ worker._metric_task_names.cache_clear()
+ try:
+ names = worker._metric_task_names()
+ assert len(names) == dimensions.MAX_METRIC_TASK_NAMES
+ registry["late-customer-task"] = object()
+ assert worker._metric_task_names() is names
+ assert worker._metric_task_name(SimpleNamespace(name="late-customer-task")) == "other"
+ assert worker._metric_task_name(SimpleNamespace(name="registered.0000")) == "registered.0000"
+ for index in range(1000):
+ assert worker._metric_task_name(SimpleNamespace(name=f"unregistered-{index}")) == "other"
+ finally:
+ worker._metric_task_names.cache_clear()
+
+
+def test_deployed_worker_registry_fits_task_budget():
+ from app.worker import tasks # noqa: F401 -- load the production registry
+ from app.worker.celery_app import celery_app
+
+ assert len(celery_app.tasks) <= dimensions.MAX_METRIC_TASK_NAMES
+ assert "app.worker.tasks.run_flaky_quarantine_maintenance" in celery_app.tasks
+
+
+def test_task_runtime_and_custom_states_use_finite_dimensions(monkeypatch):
+ from app.core import metrics
+ from app.worker import celery_app as worker
+
+ histogram, counter = Mock(), Mock()
+ monkeypatch.setattr(metrics, "celery_task_runtime_seconds", histogram)
+ monkeypatch.setattr(metrics, "celery_tasks_total", counter)
+ monkeypatch.setattr(worker, "_metric_task_names", lambda: frozenset({"registered.task"}))
+ for index in range(1000):
+ task = SimpleNamespace(name=f"unregistered-{index}", request=SimpleNamespace(delivery_info={"routing_key": f"ingestion.shard.{index}"}))
+ worker._TASK_STARTED_AT["synthetic"] = 0
+ worker._record_task_runtime(task_id="synthetic", task=task)
+ worker._record_task_outcome(task=task, state=f"custom-state-{index}")
+ assert {tuple(sorted(call.kwargs.items())) for call in histogram.labels.call_args_list} == {
+ (("queue_name", "ingestion_shard"), ("task_name", "other")),
+ }
+ counter.labels.assert_called_with(task_name="other", status="other")
+ assert "synthetic" not in worker._TASK_STARTED_AT
+ assert {dimensions.task_queue_family(queue) for queue in (
+ "ingestion.shard.0", "ingestion.shard.9000", "critical", "", "custom-route", "ingestion.shard.no",
+ )} == {"ingestion_shard", "critical", "unknown", "other"}
+
+
+def test_tenant_snapshot_series_are_retired():
+ from app.core import metrics
+
+ for name in ("workflow_eval_coverage", "test_cases_by_state", "automation_cases_orphaned"):
+ assert not hasattr(metrics, name)
+
+
+def test_machine_budget_matches_real_instruments_and_closed_dimensions():
+ from app.core import metrics
+
+ root = Path(__file__).resolve().parents[3]
+ budget = json.loads((root / "infra/monitoring/metric-cardinality-budget.json").read_text(encoding="utf-8"))
+ assert budget["task_registry_limit"] == dimensions.MAX_METRIC_TASK_NAMES
+ total = 0
+ for entry in budget["families"]:
+ instrument = getattr(metrics, entry["instrument"])
+ assert set(instrument._labelnames) == set(entry["dimensions"])
+ children = 1
+ for vocabulary in entry["dimensions"].values():
+ if isinstance(vocabulary, list):
+ children *= len(vocabulary)
+ elif vocabulary == "MAX_METRIC_TASK_NAMES+other":
+ children *= dimensions.MAX_METRIC_TASK_NAMES + 1
+ else:
+ children *= len(getattr(dimensions, vocabulary))
+ assert entry["max_children"] == children
+ samples = len(instrument._upper_bounds) + 3 if instrument._type == "histogram" else 2
+ assert entry["max_samples_per_child"] == samples
+ assert entry["max_series_per_process"] == children * samples
+ assert entry["exported_name"] == instrument._name + ("_total" if instrument._type == "counter" else "")
+ total += children * samples
+ assert budget["conservative_series_per_process"] == total
+
+
+def test_changed_dashboard_queries_are_the_executed_semantic_fixture():
+ import yaml
+
+ root = Path(__file__).resolve().parents[3]
+ dashboard = json.loads((root / "infra/monitoring/grafana/dashboards/testlookup-overview.json").read_text(encoding="utf-8"))
+ fixture = yaml.safe_load((root / "infra/monitoring/tests/metric-scope.yml").read_text(encoding="utf-8"))
+ queries = {
+ " ".join(target["expr"].split())
+ for panel in dashboard["panels"] if panel.get("id") in {12, 31, 88}
+ for target in panel["targets"]
+ }
+ tested = {
+ " ".join(test["expr"].split())
+ for group in fixture["tests"] for test in group["promql_expr_test"]
+ }
+ assert queries == tested
+ assert fixture["rule_files"] == [] # A semantic fixture, never a loaded rule file.
+
+
+def test_native_multiprocess_turnover_preserves_counts_without_identity_growth(tmp_path):
+ root = Path(__file__).resolve().parents[3]
+ directory = tmp_path / "private-metrics"
+ directory.mkdir()
+ env = dict(os.environ, PROMETHEUS_MULTIPROC_DIR=str(directory), PYTHONDONTWRITEBYTECODE="1")
+ env.pop("prometheus_multiproc_dir", None)
+ writer = r'''
+import os, time
+from types import SimpleNamespace
+from app.services.test_management_metrics_service import _emit_counter
+from app.worker.celery_app import _TASK_STARTED_AT, _record_task_runtime, _record_task_outcome
+for index in range(1000):
+ _emit_counter("transition", (f"project-{os.getpid()}-{index}", "draft", "active", "QA_ENGINEER"))
+ _emit_counter("promotion", (f"project-{os.getpid()}-{index}",))
+ task = SimpleNamespace(name="celery.group", request=SimpleNamespace(delivery_info={"routing_key": f"ingestion.shard.{index}"}))
+ _TASK_STARTED_AT["synthetic"] = time.perf_counter() - 1
+ _record_task_runtime(task_id="synthetic", task=task)
+ _record_task_outcome(task=task, state="SUCCESS")
+print(os.getpid())
+'''
+ reader = r'''
+import json, sys
+from prometheus_client import CollectorRegistry, generate_latest, multiprocess
+from prometheus_client.parser import text_string_to_metric_families
+if len(sys.argv) > 1:
+ multiprocess.mark_process_dead(int(sys.argv[1]))
+registry = CollectorRegistry()
+multiprocess.MultiProcessCollector(registry)
+prefixes = ("testlookup_test_case_transitions", "testlookup_test_case_promotions", "testlookup_celery_tasks", "celery_task_runtime_seconds")
+samples = [dict(name=s.name, labels=s.labels, value=s.value) for f in text_string_to_metric_families(generate_latest(registry).decode()) for s in f.samples if s.name.startswith(prefixes)]
+print(json.dumps(samples))
+'''
+
+ def run(script, *args):
+ return subprocess.run(
+ [sys.executable, "-c", script, *args], cwd=root / "backend", env=env,
+ capture_output=True, text=True, check=True, timeout=30,
+ ).stdout.strip()
+
+ dead_pid = run(writer)
+ before = json.loads(run(reader, dead_pid))
+ run(writer) # A replacement process uses a new PID and project identities.
+ after = json.loads(run(reader))
+ assert len(before) == len(after)
+ assert "project-" not in json.dumps(after)
+ for samples, count in ((before, 1000), (after, 2000)):
+ values = {sample["name"]: sample["value"] for sample in samples if not sample["name"].endswith("_bucket")}
+ assert values["testlookup_test_case_transitions_total"] == count
+ assert values["testlookup_test_case_promotions_total"] == count
+ assert values["testlookup_celery_tasks_total"] == count
+ assert values["celery_task_runtime_seconds_count"] == count
+ assert {sample["labels"]["queue_name"] for sample in samples if "queue_name" in sample["labels"]} == {"ingestion_shard"}
diff --git a/backend/tests/services/test_test_management_metrics_service.py b/backend/tests/services/test_test_management_metrics_service.py
index b683a4e9d..862ce0c93 100644
--- a/backend/tests/services/test_test_management_metrics_service.py
+++ b/backend/tests/services/test_test_management_metrics_service.py
@@ -10,11 +10,9 @@
from unittest.mock import AsyncMock, Mock
import pytest
-from sqlalchemy.ext.asyncio import AsyncSession
from app.core import metrics as core_metrics
from app.db import postgres
-from app.models.postgres import TestCaseLifecycleState as LifecycleState
from app.services import test_management_metrics_service as metrics
@@ -72,85 +70,42 @@ async def test_post_commit_metric_failure_is_best_effort_and_queue_is_drained(mo
@pytest.mark.asyncio
-async def test_state_gauge_sets_every_bounded_state_including_zero(monkeypatch):
- project_id = __import__("uuid").uuid4()
- db = SimpleNamespace(
- execute=AsyncMock(
- return_value=SimpleNamespace(all=lambda: [("active", 2), ("draft", 1)])
- )
- )
- values = {}
- gauge = Mock()
-
- def _labels(project, state):
- child = Mock()
- child.set.side_effect = lambda value: values.__setitem__((project, state), value)
- return child
-
- gauge.labels.side_effect = _labels
- monkeypatch.setattr(core_metrics, "test_cases_by_state", gauge)
-
- await metrics._refresh_state_gauge(db, project_id)
-
- assert len(values) == len(LifecycleState)
- assert values[(str(project_id), "active")] == 2
- assert values[(str(project_id), "draft")] == 1
- assert values[(str(project_id), "archived")] == 0
-
-
-@pytest.mark.asyncio
-async def test_post_commit_refreshes_state_and_orphan_gauges_once(monkeypatch):
- project_id = __import__("uuid").uuid4()
- db = _session()
- state_refresh = AsyncMock()
- orphan_refresh = AsyncMock()
- monkeypatch.setattr(metrics, "_refresh_state_gauge", state_refresh)
- monkeypatch.setattr(metrics, "_refresh_orphan_gauge", orphan_refresh)
-
- metrics.stage_test_case_state_refresh(db, project_id)
- metrics.stage_test_case_state_refresh(db, project_id)
- metrics.stage_orphan_gauge_refresh(db, project_id)
- await metrics.emit_staged_test_management_metrics(db)
-
- state_refresh.assert_awaited_once_with(db, project_id)
- orphan_refresh.assert_awaited_once_with(db, project_id)
+async def test_many_project_lifecycles_share_bounded_counters_without_sql_refresh(monkeypatch):
+ from prometheus_client import CollectorRegistry, Counter, generate_latest
+
+ registry = CollectorRegistry()
+ transitions = Counter("testlookup_test_case_transitions_total", "test", ["from", "to", "actor_role"], registry=registry)
+ promotions = Counter("testlookup_test_case_promotions_total", "test", registry=registry)
+ deprecations = Counter("testlookup_test_case_deprecations_without_reason_total", "test", registry=registry)
+ monkeypatch.setattr(core_metrics, "test_case_transitions_total", transitions)
+ monkeypatch.setattr(core_metrics, "test_case_promotions_total", promotions)
+ monkeypatch.setattr(core_metrics, "test_case_deprecations_without_reason_total", deprecations)
+ db = SimpleNamespace(info={}, execute=AsyncMock(side_effect=AssertionError("metrics must not read SQL")))
+ # Project create/delete/recreate cycles must change volume, never series.
+ for generation in range(2):
+ for project in range(1000):
+ project_id = f"project-{generation}-{project}"
+ metrics.stage_test_management_counter(db, "transition", (project_id, "draft", "active", "QA_ENGINEER"))
+ metrics.stage_test_management_counter(db, "promotion", (project_id,))
+ metrics.stage_test_management_counter(db, "deprecation_without_reason", (project_id,))
+ await metrics.emit_staged_test_management_metrics(db)
+
+ assert transitions.labels("draft", "active", "QA_ENGINEER")._value.get() == 2000
+ assert promotions._value.get() == deprecations._value.get() == 2000
+ samples = [sample for family in registry.collect() for sample in family.samples]
+ assert len(samples) == 6 # total + created for three counter children
+ assert b"project-" not in generate_latest(registry)
assert db.info == {}
+ db.execute.assert_not_awaited()
-@pytest.mark.asyncio
-async def test_rollback_discards_staged_gauge_refreshes(monkeypatch):
- project_id = __import__("uuid").uuid4()
- db = _session()
- state_refresh = AsyncMock()
- orphan_refresh = AsyncMock()
- monkeypatch.setattr(metrics, "_refresh_state_gauge", state_refresh)
- monkeypatch.setattr(metrics, "_refresh_orphan_gauge", orphan_refresh)
- metrics.stage_test_case_state_refresh(db, project_id)
- metrics.stage_orphan_gauge_refresh(db, project_id)
-
- metrics.discard_staged_test_management_metrics(db)
- await metrics.emit_staged_test_management_metrics(db)
-
- state_refresh.assert_not_awaited()
- orphan_refresh.assert_not_awaited()
- assert db.info == {}
-
-
-@pytest.mark.asyncio
-async def test_orphan_gauge_refresh_explicitly_resets_zero(monkeypatch):
- project_id = __import__("uuid").uuid4()
- db = SimpleNamespace(
- execute=AsyncMock(
- return_value=SimpleNamespace(scalar=lambda: 0)
- )
- )
- gauge = Mock()
- monkeypatch.setattr(core_metrics, "automation_cases_orphaned", gauge)
-
- await metrics._refresh_orphan_gauge(db, project_id)
-
- gauge.labels.assert_called_once_with(str(project_id))
- gauge.labels.return_value.set.assert_called_once_with(0)
+def test_unexpected_transition_dimensions_collapse_without_losing_event_count(monkeypatch):
+ counter = Mock()
+ monkeypatch.setattr(core_metrics, "test_case_transitions_total", counter)
+ for index in range(1000):
+ metrics._emit_counter("transition", (f"project-{index}", f"old-{index}", f"new-{index}", f"role-{index}"))
+ assert counter.labels.call_count == 1000
+ assert {call.args for call in counter.labels.call_args_list} == {("other", "other", "other")}
def test_test_double_without_session_info_uses_documented_immediate_fallback(
@@ -180,34 +135,6 @@ async def __aexit__(self, *_args):
return False
-@pytest.mark.asyncio
-async def test_failed_gauge_read_is_isolated_from_committed_request_session(
- monkeypatch,
-):
- project_id = __import__("uuid").uuid4()
- request_db = AsyncSession()
- isolated_db = SimpleNamespace()
- state_refresh = AsyncMock(side_effect=RuntimeError("read transaction failed"))
- monkeypatch.setattr(metrics, "_refresh_state_gauge", state_refresh)
- monkeypatch.setattr(
- postgres,
- "get_session_factory",
- lambda: lambda: _SessionContext(isolated_db),
- )
- metrics.stage_test_case_state_refresh(request_db, project_id)
-
- try:
- # A telemetry failure after commit must be swallowed and must never
- # open or abort a transaction on the response-producing session.
- await metrics.emit_staged_test_management_metrics(request_db)
-
- state_refresh.assert_awaited_once_with(isolated_db, project_id)
- assert request_db.info == {}
- assert request_db.in_transaction() is False
- finally:
- await request_db.close()
-
-
@pytest.mark.asyncio
async def test_request_session_emits_only_after_successful_commit(monkeypatch):
calls: list[str] = []
diff --git a/backend/tests/services/test_workflow_evaluation_service.py b/backend/tests/services/test_workflow_evaluation_service.py
index 8cfdf9f81..2f15793e8 100644
--- a/backend/tests/services/test_workflow_evaluation_service.py
+++ b/backend/tests/services/test_workflow_evaluation_service.py
@@ -5,6 +5,7 @@
from types import SimpleNamespace
from datetime import datetime, timezone
from typing import Any
+from unittest.mock import AsyncMock
import pytest
@@ -467,3 +468,42 @@ async def test_inline_invocation_pipelines_are_never_replay_evidence() -> None:
assert "NOT (EXISTS (SELECT 1" in sql
assert "agent_invocations.pipeline_run_id = agent_pipeline_runs.id" in sql
assert "agent_invocations.input_sha256 IS NOT NULL" in sql
+
+
+@pytest.mark.asyncio
+async def test_many_workflow_identities_keep_coverage_in_sql_and_api_without_series(monkeypatch):
+ from prometheus_client import REGISTRY
+ from app.services import agent_authority_lock, workflow_definition_service
+
+ monkeypatch.setattr(agent_authority_lock, "lock_agent_authority_snapshot", AsyncMock())
+ monkeypatch.setattr(svc, "_candidate_step_authority", AsyncMock(return_value={}))
+ monkeypatch.setattr(svc, "_load_replay_cases", AsyncMock(return_value=[]))
+ baseline = _evaluate([_case(index) for index in range(20)])
+ monkeypatch.setattr(svc, "evaluate_replay", lambda **_kwargs: dict(baseline))
+ admitted = []
+
+ def add(gate):
+ gate.id = uuid.uuid4()
+ admitted.append(gate)
+
+ db = SimpleNamespace(execute=AsyncMock(), add=add, flush=AsyncMock())
+ for generation in range(2):
+ # Distinct projects and definitions, including delete/recreate-shaped
+ # identity churn. This unit boundary does not simulate real DB deletes.
+ for index in range(100):
+ row = _row("insufficient_samples")
+ row.project_id = uuid.uuid4()
+ row.workflow_id = f"wf.custom.{generation}.{index}"
+ result = await svc.evaluate_definition(
+ db, project_id=row.project_id, row=row, sample_limit=20, evaluated_by=None,
+ )
+ serialized = workflow_definition_service.serialize(row)
+ assert serialized["workflow_id"] == row.workflow_id
+ assert serialized["project_id"] == str(row.project_id)
+ assert serialized["eval_coverage"] == result["coverage"] == baseline["coverage"]
+ assert serialized["eval_verdict"] == baseline["verdict"]
+ assert serialized["eval_gate_run_id"] == result["gate_run_id"]
+ assert row.evaluated_at is not None
+
+ assert len(admitted) == 200
+ assert "testlookup_workflow_eval_coverage" not in {family.name for family in REGISTRY.collect()}
diff --git a/backend/tests/test_ai_generation_worker_governance.py b/backend/tests/test_ai_generation_worker_governance.py
index 750165f28..57f2af598 100644
--- a/backend/tests/test_ai_generation_worker_governance.py
+++ b/backend/tests/test_ai_generation_worker_governance.py
@@ -92,4 +92,4 @@ async def flush():
assert audits[0].action == "ai_generated"
assert audits[0].actor_id == author_id
assert calls == ["commit", "emit"]
- assert session.info["test_management_state_metric_projects"] == {project_id}
+ assert "test_management_state_metric_projects" not in session.info
diff --git a/backend/tests/test_journey_sli.py b/backend/tests/test_journey_sli.py
new file mode 100644
index 000000000..7be31bc77
--- /dev/null
+++ b/backend/tests/test_journey_sli.py
@@ -0,0 +1,387 @@
+"""Known-workload API and retained-intent accounting, independent of Celery."""
+from __future__ import annotations
+
+from datetime import datetime, timedelta, timezone
+import json
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+import pytest_asyncio
+from prometheus_client import CollectorRegistry, Counter, Gauge
+from prometheus_client.parser import text_string_to_metric_families
+from pydantic import ValidationError
+from sqlalchemy import event, text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+from app.core.config import Settings, settings
+from app.middleware import journey_sli as middleware
+from app.services import journey_sli_metrics as service
+from app.services.journey_sli_contracts import API_ROUTES, COHORT_OUTCOMES, JOURNEYS, WINDOWS
+
+NOW = datetime(2026, 11, 27, 12, tzinfo=timezone.utc)
+SCOPE = {"installation": "synthetic-site", "environment": "development"}
+
+
+def _value(template, **labels):
+ samples = [sample for family in text_string_to_metric_families(service.render_journey_cohort_metrics().decode())
+ for sample in family.samples if sample.name == template.name and sample.labels == labels]
+ assert len(samples) == 1
+ return samples[0].value
+
+
+@pytest.fixture
+def api_values(monkeypatch):
+ monkeypatch.setattr(settings, "OBSERVABILITY_INSTALLATION", SCOPE["installation"])
+ monkeypatch.setattr(settings, "APP_ENV", SCOPE["environment"])
+ registry = CollectorRegistry()
+ counter = Counter("fixture_journey_events", "fixture", ["installation", "environment", "objective", "outcome"], registry=registry)
+ configured = Gauge("fixture_sli_configured", "fixture", ["installation", "environment", "objective"], registry=registry)
+ monkeypatch.setattr(middleware, "api_journey_events", counter)
+ monkeypatch.setattr(middleware, "api_sli_configured", configured)
+ return counter, configured
+
+
+async def _invoke(app, *, route="/api/v1/projects", path=None, method="GET", resolved=True):
+ scope = {"type": "http", "method": method, "path": path or route, "query_string": b"token=synthetic-sensitive-query"}
+ if resolved:
+ scope["route"] = SimpleNamespace(path=route)
+ messages = []
+ async def send(message):
+ messages.append(message)
+ async def receive():
+ return {"type": "http.request", "body": b"", "more_body": False}
+ await middleware.JourneySLIMiddleware(app)(scope, receive, send)
+ return messages
+
+
+def _response(status=200, *, more=False):
+ async def app(scope, receive, send):
+ await send({"type": "http.response.start", "status": status, "headers": []})
+ await send({"type": "http.response.body", "body": b"synthetic", "more_body": more})
+ return app
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize(("status", "availability", "latency"), [(200, "good", "good"), (302, "good", "good"), (429, "bad", "bad"), (500, "bad", "bad"), (503, "bad", "bad")])
+async def test_actual_completed_attempt_has_one_outcome_per_objective(api_values, monkeypatch, status, availability, latency):
+ monkeypatch.setattr(middleware, "perf_counter", lambda: 1.0)
+ messages = await _invoke(_response(status))
+ assert messages[-1]["body"] == b"synthetic"
+ counter, configured = api_values
+ for objective, good in (("api_availability", availability), ("api_latency", latency)):
+ assert configured.labels(**SCOPE, objective=objective)._value.get() == 1
+ for outcome in ("good", "bad"):
+ assert counter.labels(**SCOPE, objective=objective, outcome=outcome)._value.get() == int(outcome == good)
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("status", [400, 401, 403, 404, 409, 422])
+async def test_client_refusals_are_not_a_success_only_denominator(api_values, status):
+ await _invoke(_response(status))
+ for objective in ("api_availability", "api_latency"):
+ assert sum(api_values[0].labels(**SCOPE, objective=objective, outcome=outcome)._value.get() for outcome in ("good", "bad")) == 0
+
+
+@pytest.mark.asyncio
+async def test_latency_uses_final_body_before_background_work(api_values, monkeypatch):
+ clock = [0.0]
+ monkeypatch.setattr(middleware, "perf_counter", lambda: clock[0])
+ async def app(scope, receive, send):
+ await send({"type": "http.response.start", "status": 200, "headers": []})
+ clock[0] = .201 # existing project-list p95 budget is .2s
+ await send({"type": "http.response.body", "body": b""})
+ clock[0] = 500
+ raise RuntimeError("synthetic post-response background failure")
+ with pytest.raises(RuntimeError):
+ await _invoke(app)
+ values = api_values[0]
+ assert values.labels(**SCOPE, objective="api_availability", outcome="good")._value.get() == 1
+ assert values.labels(**SCOPE, objective="api_latency", outcome="bad")._value.get() == 1
+ assert values.labels(**SCOPE, objective="api_availability", outcome="bad")._value.get() == 0
+
+
+@pytest.mark.asyncio
+async def test_unhandled_and_incomplete_response_count_bad_then_propagate(api_values):
+ async def broken(scope, receive, send):
+ raise RuntimeError("synthetic handler failure")
+ with pytest.raises(RuntimeError):
+ await _invoke(broken)
+ await _invoke(_response(more=True))
+ for objective in ("api_availability", "api_latency"):
+ assert api_values[0].labels(**SCOPE, objective=objective, outcome="bad")._value.get() == 2
+
+
+@pytest.mark.asyncio
+async def test_early_guard_matches_only_fixed_core_templates_without_labels(api_values):
+ await _invoke(_response(429), path="/api/v1/runs/synthetic-private-id", resolved=False)
+ await _invoke(_response(500), route="/health/details", resolved=False)
+ await _invoke(_response(500), path="/api/v1/shared/reports/synthetic-bearer", resolved=False)
+ await _invoke(_response(500), method="POST")
+ for objective in ("api_availability", "api_latency"):
+ assert api_values[0].labels(**SCOPE, objective=objective, outcome="bad")._value.get() == 1
+ labels = [sample.labels for family in api_values[0].collect() for sample in family.samples]
+ assert all(set(value) == {"installation", "environment", "objective", "outcome"} for value in labels)
+ assert "synthetic-private-id" not in str(labels) and "synthetic-sensitive-query" not in str(labels)
+
+
+@pytest.mark.parametrize(("path", "root", "matches"), [
+ ("/proxy/api/v1/runs/synthetic-id", "/proxy", True),
+ ("/api/v1/runs/synthetic-id", "/proxy", True), # stripped by upstream already
+ ("/proxy2/api/v1/runs/synthetic-id", "/proxy", False),
+ ("/proxy", "/proxy", False),
+])
+def test_early_guard_match_respects_asgi_root_path_boundary(path, root, matches):
+ assert (middleware._threshold({"method": "GET", "path": path, "root_path": root}) is not None) is matches
+
+
+@pytest.mark.asyncio
+async def test_unset_installation_disables_inputs_and_does_not_infer_identity(api_values, monkeypatch):
+ monkeypatch.setattr(settings, "OBSERVABILITY_INSTALLATION", "")
+ await _invoke(_response(500))
+ assert list(api_values[0].collect())[0].samples == []
+ assert await service.refresh_journey_cohort_metrics(now=NOW) is True
+
+
+@pytest.mark.parametrize("value", ["a", "EU_site.3-prod", "a" * 63, ""])
+def test_valid_installation_scope(value):
+ assert Settings(_env_file=None, OBSERVABILITY_INSTALLATION=value).OBSERVABILITY_INSTALLATION == value
+
+
+@pytest.mark.parametrize("value", ["a" * 64, " site", "site ", "../site", "https://site", "équipe", "site\n", "-site"])
+def test_invalid_installation_scope_fails_configuration(value):
+ with pytest.raises(ValidationError):
+ Settings(_env_file=None, OBSERVABILITY_INSTALLATION=value)
+
+
+@pytest_asyncio.fixture
+async def sql_world(monkeypatch):
+ monkeypatch.setattr(service, "_CACHE", None)
+ monkeypatch.setattr(service, "_PUBLISHED", None)
+ engine = create_async_engine("sqlite+aiosqlite://")
+ async with engine.begin() as connection:
+ await connection.execute(text("CREATE TABLE run_downstream_outbox (id INTEGER PRIMARY KEY, operation TEXT, status TEXT, created_at DATETIME, completed_at DATETIME, attempts INTEGER DEFAULT 0)"))
+ await connection.execute(text("CREATE TABLE agent_pipeline_runs (id INTEGER PRIMARY KEY, status TEXT, created_at DATETIME, completed_at DATETIME, execution_metadata JSON)"))
+ sessions = async_sessionmaker(engine)
+ from app.db import postgres
+ monkeypatch.setattr(postgres, "AsyncSessionLocal", sessions)
+ monkeypatch.setattr(settings, "OBSERVABILITY_INSTALLATION", SCOPE["installation"])
+ monkeypatch.setattr(settings, "APP_ENV", SCOPE["environment"])
+ monkeypatch.setattr(settings, "AI_PIPELINE_DEADLINE_SECONDS", 1500)
+ yield engine, sessions
+ await engine.dispose()
+
+
+async def _row(engine, *, table="run_downstream_outbox", status="completed", age=7200, elapsed=10, operation="run_notifications", metadata=None):
+ accepted = NOW - timedelta(seconds=age)
+ completed = None if elapsed is None else accepted + timedelta(seconds=elapsed)
+ async with engine.begin() as connection:
+ if table == "run_downstream_outbox":
+ await connection.execute(text("INSERT INTO run_downstream_outbox(operation,status,created_at,completed_at) VALUES (:operation,:status,:accepted,:completed)"),
+ {"operation": operation, "status": status, "accepted": accepted, "completed": completed})
+ else:
+ await connection.execute(text("INSERT INTO agent_pipeline_runs(status,created_at,completed_at,execution_metadata) VALUES (:status,:accepted,:completed,:metadata)"),
+ {"status": status, "accepted": accepted, "completed": completed, "metadata": json.dumps(metadata or {})})
+
+
+@pytest.mark.asyncio
+async def test_matured_intent_denominator_includes_every_nonterminal_state_and_retries(sql_world):
+ engine, sessions = sql_world
+ await _row(engine)
+ await _row(engine, elapsed=4201)
+ await _row(engine, status="failed", elapsed=None)
+ for status in ("waiting", "pending", "sending", "published", "processing"):
+ await _row(engine, status=status, elapsed=None)
+ await _row(engine, elapsed=None) # malformed completed without timestamp
+ await _row(engine, operation="synthetic-unknown-operation")
+ await _row(engine, status="pending", age=1, elapsed=None) # not yet mature
+ async with sessions() as db:
+ snapshot = await service.read_journey_cohorts(db, now=NOW)
+ measured = {outcome: snapshot["downstream"][("1h", outcome)] for outcome in COHORT_OUTCOMES}
+ assert measured == {"good": 1, "late": 1, "failed": 1, "overdue": 5, "degraded": 0, "unknown": 2}
+ assert sum(measured.values()) == 10 # not merely the two completed rows
+ async with engine.begin() as connection:
+ await connection.execute(text("UPDATE run_downstream_outbox SET attempts=attempts+5"))
+ async with sessions() as db:
+ assert await service.read_journey_cohorts(db, now=NOW) == snapshot
+
+
+@pytest.mark.asyncio
+async def test_quality_is_explicit_and_degraded_not_full_quality(sql_world):
+ engine, sessions = sql_world
+ for metadata in ({"fallback_used": False}, {"fallback_used": True}, {"fallback_used": False, "stage_quality": "degraded"}, {}):
+ await _row(engine, table="agent_pipeline_runs", age=2000, metadata=metadata)
+ await _row(engine, table="agent_pipeline_runs", age=2000, status="retry_wait", elapsed=None)
+ await _row(engine, table="agent_pipeline_runs", age=2000, status="failed", elapsed=30)
+ await _row(engine, table="agent_pipeline_runs", age=2000, elapsed=1501, metadata={"fallback_used": False})
+ async with sessions() as db:
+ snapshot = await service.read_journey_cohorts(db, now=NOW)
+ assert snapshot["ai_completion"][("1h", "good")] == 4
+ full = snapshot["ai_reported_full_quality"]
+ assert {key: full[("1h", key)] for key in COHORT_OUTCOMES} == {"good": 1, "degraded": 3, "overdue": 1, "failed": 1, "late": 1, "unknown": 0}
+
+
+@pytest.mark.asyncio
+async def test_full_quality_requires_json_boolean_false_not_coercible_values(sql_world):
+ engine, sessions = sql_world
+ for value in (0, "false", None, [], {}):
+ await _row(engine, table="agent_pipeline_runs", age=2000, metadata={"fallback_used": value})
+ async with sessions() as db:
+ result = await service.read_journey_cohorts(db, now=NOW)
+ assert result["ai_reported_full_quality"][("1h", "good")] == 0
+ assert result["ai_reported_full_quality"][("1h", "degraded")] == 5
+
+
+@pytest.mark.asyncio
+async def test_window_boundaries_late_recovery_and_live_subset(sql_world):
+ engine, sessions = sql_world
+ await _row(engine, status="pending", age=4200, elapsed=None, operation="persist_live_session")
+ await _row(engine, age=4200 + 3600, operation="persist_live_session") # exclusive left boundary
+ await _row(engine, age=4200 + 3600 - 1)
+ async with sessions() as db:
+ before = await service.read_journey_cohorts(db, now=NOW)
+ assert before["live_materialization"][("1h", "overdue")] == 1
+ assert before["live_materialization"][("1h", "good")] == 0
+ assert before["live_materialization"][("6h", "good")] == 1
+ async with engine.begin() as connection:
+ await connection.execute(text("UPDATE run_downstream_outbox SET status='completed', completed_at=:now WHERE status='pending'"), {"now": NOW})
+ async with sessions() as db:
+ after = await service.read_journey_cohorts(db, now=NOW + timedelta(seconds=1))
+ assert after["live_materialization"][("1h", "good")] == 1
+
+
+@pytest.mark.asyncio
+async def test_never_completed_then_late_completion_stays_in_bad_denominator(sql_world):
+ engine, sessions = sql_world
+ await _row(engine, status="processing", age=7200, elapsed=None)
+ async with sessions() as db:
+ before = await service.read_journey_cohorts(db, now=NOW)
+ assert before["downstream"][("1h", "overdue")] == 1
+ async with engine.begin() as connection:
+ await connection.execute(text("UPDATE run_downstream_outbox SET status='completed', completed_at=:now"), {"now": NOW})
+ async with sessions() as db:
+ after = await service.read_journey_cohorts(db, now=NOW)
+ assert after["downstream"][("1h", "overdue")] == 0
+ assert after["downstream"][("1h", "late")] == 1
+ assert after["downstream"][("1h", "good")] == 0
+
+
+@pytest.mark.asyncio
+async def test_impossible_completion_timestamps_are_unknown_not_good(sql_world):
+ engine, sessions = sql_world
+ await _row(engine, age=7200, elapsed=-1)
+ await _row(engine, age=7200, elapsed=7201)
+ async with sessions() as db:
+ result = await service.read_journey_cohorts(db, now=NOW)
+ assert result["downstream"][("1h", "unknown")] == 2
+
+
+@pytest.mark.asyncio
+async def test_disabled_ai_deadline_is_unsupported_without_erasing_outbox(sql_world, monkeypatch):
+ engine, _sessions = sql_world
+ await _row(engine)
+ monkeypatch.setattr(settings, "AI_PIPELINE_DEADLINE_SECONDS", 0)
+ assert await service.refresh_journey_cohort_metrics(now=NOW)
+ assert _value(service.journey_cohort_events, **SCOPE, journey="downstream", window="1h", outcome="good") == 1
+ assert _value(service.journey_source_supported, **SCOPE, journey="ai_completion") == 0
+
+
+@pytest.mark.asyncio
+async def test_replicas_restart_and_empty_source_rederive_absolute_snapshot(sql_world):
+ engine, sessions = sql_world
+ await _row(engine, status="pending", elapsed=None)
+ await _row(engine, table="agent_pipeline_runs", age=2000, metadata={"fallback_used": False})
+ assert await service.refresh_journey_cohort_metrics(now=NOW)
+ expected = _value(service.journey_cohort_events, **SCOPE, journey="downstream", window="1h", outcome="overdue")
+ assert expected == 1
+ # Another API replica or restarted collector sees durable state, not a
+ # local increment/checkpoint. A repeated observation must not double it.
+ assert await service.refresh_journey_cohort_metrics(now=NOW)
+ assert _value(service.journey_cohort_events, **SCOPE, journey="downstream", window="1h", outcome="overdue") == expected
+ for contract in JOURNEYS:
+ assert _value(service.journey_source_supported, **SCOPE, journey=contract.name) == int(contract.supported)
+ async with engine.begin() as connection:
+ await connection.execute(text("DELETE FROM run_downstream_outbox"))
+ await connection.execute(text("DELETE FROM agent_pipeline_runs"))
+ assert await service.refresh_journey_cohort_metrics(now=NOW)
+ for journey in (item.name for item in JOURNEYS if item.supported):
+ assert all(_value(service.journey_cohort_events, **SCOPE, journey=journey, window=window, outcome=outcome) == 0
+ for window in WINDOWS for outcome in COHORT_OUTCOMES)
+
+
+@pytest.mark.asyncio
+async def test_paired_journeys_scan_each_source_once(sql_world):
+ engine, sessions = sql_world
+ queries = []
+ def record(_conn, _cursor, statement, _parameters, _context, _many):
+ if statement.lstrip().upper().startswith("SELECT"):
+ queries.append(statement)
+ event.listen(engine.sync_engine, "before_cursor_execute", record)
+ try:
+ async with sessions() as db:
+ await service.read_journey_cohorts(db, now=NOW)
+ finally:
+ event.remove(engine.sync_engine, "before_cursor_execute", record)
+ assert len(queries) == 2
+
+
+@pytest.mark.asyncio
+async def test_cache_preserves_actual_read_time_failed_query_does_not_refresh(sql_world, monkeypatch):
+ clock = [0.0]
+ monkeypatch.setattr(service, "monotonic", lambda: clock[0])
+ reader = AsyncMock(wraps=service.read_journey_cohorts)
+ monkeypatch.setattr(service, "read_journey_cohorts", reader)
+ await service.refresh_journey_cohort_metrics()
+ cached = service._CACHE
+ observed = _value(service.journey_cohort_observed_at, **SCOPE)
+ assert reader.await_count == 1 and cached is not None
+ clock[0] = 20
+ await service.refresh_journey_cohort_metrics()
+ assert reader.await_count == 1
+ assert _value(service.journey_cohort_observed_at, **SCOPE) == observed
+ clock[0] = 31
+ reader.side_effect = RuntimeError("synthetic unavailable source")
+ with pytest.raises(RuntimeError):
+ await service.refresh_journey_cohort_metrics()
+ assert service._CACHE is cached
+ assert _value(service.journey_cohort_observed_at, **SCOPE) == observed
+
+
+@pytest.mark.asyncio
+async def test_cache_never_mixes_site_environment_deadline_or_explicit_now(sql_world, monkeypatch):
+ monkeypatch.setattr(service, "monotonic", lambda: 0.0)
+ reader = AsyncMock(wraps=service.read_journey_cohorts)
+ monkeypatch.setattr(service, "read_journey_cohorts", reader)
+ await service.refresh_journey_cohort_metrics()
+ assert reader.await_count == 1
+ await service.refresh_journey_cohort_metrics(now=NOW)
+ assert reader.await_count == 2 # deterministic reads never borrow cache
+ for field, value in (("OBSERVABILITY_INSTALLATION", "second-site"), ("APP_ENV", "staging"), ("AI_PIPELINE_DEADLINE_SECONDS", 1499)):
+ monkeypatch.setattr(settings, field, value)
+ await service.refresh_journey_cohort_metrics()
+ assert reader.await_count == 5
+
+
+@pytest.mark.asyncio
+async def test_export_keeps_changing_cohort_as_one_immutable_bundle(sql_world):
+ engine, _sessions = sql_world
+ await _row(engine, status="processing", age=7200, elapsed=None)
+ await service.refresh_journey_cohort_metrics(now=NOW)
+ first = service.render_journey_cohort_metrics()
+ async with engine.begin() as connection:
+ await connection.execute(text("UPDATE run_downstream_outbox SET status='completed', completed_at=:now"), {"now": NOW})
+ await service.refresh_journey_cohort_metrics(now=NOW)
+ second = service.render_journey_cohort_metrics()
+ assert first != second
+ for payload, expected in ((first, "overdue"), (second, "late")):
+ samples = [sample for family in text_string_to_metric_families(payload.decode()) for sample in family.samples
+ if sample.name == service.journey_cohort_events.name
+ and sample.labels.get("journey") == "downstream" and sample.labels.get("window") == "1h"]
+ assert sum(sample.value for sample in samples) == 1
+ assert next(sample.value for sample in samples if sample.labels["outcome"] == expected) == 1
+ assert service.journey_cohort_events.samples == [] # global unregistered template stays untouched
+
+
+def test_finite_route_contract_reuses_existing_latency_budgets():
+ assert len(API_ROUTES) == 6
+ assert all(method == "GET" and path.startswith("/api/v1/") for method, path in API_ROUTES)
diff --git a/backend/tests/test_test_case_governance_sp.py b/backend/tests/test_test_case_governance_sp.py
index 523e5cd2d..12c99f7b8 100644
--- a/backend/tests/test_test_case_governance_sp.py
+++ b/backend/tests/test_test_case_governance_sp.py
@@ -352,7 +352,7 @@ async def test_retirement_confirmation_captures_actor_reason_and_timestamp():
@pytest.mark.asyncio
-async def test_orphan_query_is_project_scoped_unconfirmed_and_updates_gauge(monkeypatch):
+async def test_orphan_query_preserves_scoped_paginated_analytics_without_metric_reads():
project_id = uuid.uuid4()
orphan = _canonical(
project_id=project_id,
@@ -362,14 +362,11 @@ async def test_orphan_query_is_project_scoped_unconfirmed_and_updates_gauge(monk
total_result = FakeExecuteResult(scalar_value=1)
rows_result = FakeExecuteResult()
rows_result.scalars = lambda: SimpleNamespace(all=lambda: [orphan])
- count_result = FakeExecuteResult(all_value=[(project_id, 1)])
db = SimpleNamespace(
execute=AsyncMock(
- side_effect=[total_result, rows_result, count_result]
+ side_effect=[total_result, rows_result]
)
)
- metric = Mock()
- monkeypatch.setattr(svc, "automation_cases_orphaned", metric)
rows, total = await svc.list_orphaned_canonical_cases(
db, [project_id], page=2, size=7
@@ -383,48 +380,38 @@ async def test_orphan_query_is_project_scoped_unconfirmed_and_updates_gauge(monk
assert "canonical_test_cases.project_id IN" in compiled
assert "deleted_observed_at ASC NULLS FIRST" in compiled
assert "LIMIT" in compiled and "OFFSET" in compiled
- metric.labels.assert_called_once_with(str(project_id))
- metric.labels.return_value.set.assert_called_once_with(1)
+ assert db.execute.await_count == 2
@pytest.mark.asyncio
-async def test_orphan_gauge_is_reset_when_scoped_project_has_no_orphans(monkeypatch):
+async def test_orphan_query_empty_project_retains_zero_without_global_metric_query():
project_id = uuid.uuid4()
total_result = FakeExecuteResult(scalar_value=0)
rows_result = FakeExecuteResult()
rows_result.scalars = lambda: SimpleNamespace(all=lambda: [])
- count_result = FakeExecuteResult(all_value=[])
db = SimpleNamespace(
execute=AsyncMock(
- side_effect=[total_result, rows_result, count_result]
+ side_effect=[total_result, rows_result]
)
)
- metric = Mock()
- monkeypatch.setattr(svc, "automation_cases_orphaned", metric)
assert await svc.list_orphaned_canonical_cases(db, [project_id]) == ([], 0)
- metric.labels.assert_called_once_with(str(project_id))
- metric.labels.return_value.set.assert_called_once_with(0)
+ assert db.execute.await_count == 2
@pytest.mark.asyncio
-async def test_orphan_gauge_failure_is_best_effort(monkeypatch):
- project_id = uuid.uuid4()
+async def test_orphan_query_all_projects_uses_only_authoritative_total_and_page():
total_result = FakeExecuteResult(scalar_value=0)
rows_result = FakeExecuteResult()
rows_result.scalars = lambda: SimpleNamespace(all=lambda: [])
- count_result = FakeExecuteResult(all_value=[])
db = SimpleNamespace(
execute=AsyncMock(
- side_effect=[total_result, rows_result, count_result]
+ side_effect=[total_result, rows_result]
)
)
- metric = Mock()
- metric.labels.return_value.set.side_effect = RuntimeError("registry down")
- monkeypatch.setattr(svc, "automation_cases_orphaned", metric)
- assert await svc.list_orphaned_canonical_cases(db, [project_id]) == ([], 0)
- metric.labels.return_value.set.assert_called_once_with(0)
+ assert await svc.list_orphaned_canonical_cases(db, None) == ([], 0)
+ assert db.execute.await_count == 2
@pytest.mark.asyncio
diff --git a/backend/tests/test_test_case_lifecycle_state_machine.py b/backend/tests/test_test_case_lifecycle_state_machine.py
index cf8635d41..3fce6fe5f 100644
--- a/backend/tests/test_test_case_lifecycle_state_machine.py
+++ b/backend/tests/test_test_case_lifecycle_state_machine.py
@@ -218,9 +218,7 @@ def test_stage_snapshot_captures_every_authored_field():
assert snapshot.test_case_id == case.id
assert snapshot.changed_by_id == actor_id
assert snapshot.changed_fields == ["priority"]
- assert db.info["test_management_state_metric_projects"] == {
- values["project_id"]
- }
+ assert db.info == {} # SQL snapshot remains; tenant gauges are retired.
@pytest.mark.asyncio
@@ -406,7 +404,7 @@ async def test_transition_stages_snapshot_audit_flush_and_metric(monkeypatch):
monkeypatch.setattr(lifecycle, "stage_test_case_snapshot", snapshot)
monkeypatch.setattr(lifecycle, "audit_event", audit)
metric = test_case_transitions_total.labels(
- str(case.project_id), "approved", "active", UserRole.QA_LEAD.value
+ "approved", "active", UserRole.QA_LEAD.value
)
before = metric._value.get()
diff --git a/backend/tests/test_tracing.py b/backend/tests/test_tracing.py
index 9fffaaafd..58886662b 100644
--- a/backend/tests/test_tracing.py
+++ b/backend/tests/test_tracing.py
@@ -143,6 +143,29 @@ def test_an_endpoint_gets_the_otlp_exporter_and_no_console(monkeypatch):
assert len(_exporters(providers[0])) == 1
+def test_trace_sampling_respects_site_ratio_and_sampled_parent(monkeypatch):
+ from opentelemetry import trace
+
+ _, providers = _spy(monkeypatch)
+ monkeypatch.setenv("OTEL_TRACES_SAMPLER", "parentbased_traceidratio")
+ monkeypatch.setenv("OTEL_TRACES_SAMPLER_ARG", "0")
+ tracing.setup_tracing("testlookup", "test", "production", otlp_endpoint=None)
+ provider = providers[0]
+ tracer = provider.get_tracer("synthetic.sampling")
+ parent = trace.SpanContext(
+ trace_id=1, span_id=1, is_remote=True,
+ trace_flags=trace.TraceFlags(trace.TraceFlags.SAMPLED),
+ )
+ context = trace.set_span_in_context(trace.NonRecordingSpan(parent))
+ try:
+ with tracer.start_as_current_span("synthetic.root") as span:
+ assert span.get_span_context().is_valid and not span.is_recording()
+ with tracer.start_as_current_span("synthetic.child", context=context) as span:
+ assert span.is_recording() and span.get_span_context().trace_id == parent.trace_id
+ finally:
+ provider.shutdown()
+
+
class _NullProcessor:
def on_start(self, span, parent_context=None):
pass
diff --git a/docker-compose.objectives.yml b/docker-compose.objectives.yml
new file mode 100644
index 000000000..8ea92fbfa
--- /dev/null
+++ b/docker-compose.objectives.yml
@@ -0,0 +1,19 @@
+# Optional after docker-compose.monitoring.yml. See docs/operations/api-objectives.md.
+services:
+ backend:
+ environment:
+ OBSERVABILITY_INSTALLATION: ${OBSERVABILITY_INSTALLATION:?Set a stable installation identifier}
+ prometheus:
+ command:
+ - --config.file=/etc/prometheus/prometheus.yml
+ - --storage.tsdb.path=/prometheus
+ - --storage.tsdb.retention.time=35d
+ - --storage.tsdb.retention.size=${SLO_PROMETHEUS_RETENTION_SIZE:?Set a Prometheus retention size within the volume budget}
+ volumes:
+ - ./infra/monitoring/objectives/api-slos.yml:/etc/prometheus/rules/api-slos.yml:ro
+ - type: bind
+ source: ${SLO_ADOPTION_RULES_FILE:-./infra/monitoring/objectives/adoption.example.yml}
+ target: /etc/prometheus/rules/slo-adoption.yml
+ read_only: true
+ bind:
+ create_host_path: false
diff --git a/docker-compose.telemetry.yml b/docker-compose.telemetry.yml
index fc21505f5..e635f6376 100644
--- a/docker-compose.telemetry.yml
+++ b/docker-compose.telemetry.yml
@@ -106,6 +106,8 @@ services:
environment:
<<: *worker-telemetry
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
+ OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_always_on}
+ OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-1.0}
OTEL_LOGS_ROLE: api
networks: [telemetry_ingress]
logging: *log-rotation
diff --git a/docs/maintainers/observability-delivery.md b/docs/maintainers/observability-delivery.md
index 7ade8e7d7..12353771f 100644
--- a/docs/maintainers/observability-delivery.md
+++ b/docs/maintainers/observability-delivery.md
@@ -184,3 +184,16 @@ This iteration builds on `25fcc0c9`. Pipeline event health comes from shared SQL
| OBS-E05-S04 | An admin-approved identity policy expires selected routine, successful events in bounded batches. Instance holds pause cleanup and SCIM authority rows remain available for supported authorization paths. | Confirm site defaults, approvals, window and retention behavior with the identity owner. See [identity event retention](../operations/identity-event-retention.md). |
Disposable PostgreSQL and MongoDB tests exercised competing producers and claims, the purge fence, and a retry following a lost receipt. The same event remained a single MongoDB document. Migration 0263 was applied and rolled back in a disposable schema. A downgrade with pending evidence was refused. A PostgreSQL identity test observed hold and purge transactions from independent sessions and verified the resulting audit receipts. Archive tests used synthetic records and provider fixtures.
+
+## Iteration 6 — service objectives and telemetry capacity
+
+This iteration builds on `58fe721e`. It introduces measurements and proposed objectives that installation owners can review before enabling alerts.
+
+| Story | Change | Remaining acceptance |
+|---|---|---|
+| OBS-E06-S01 | Six core GET operations emit opt-in completion and latency counters. A bounded SQL collector includes late, failed, degraded and never-completed work in retained downstream, live materialization and AI cohorts. Migration 0264 indexes the acceptance timestamp on each source table. [Journey measurement contracts](../operations/journey-slis.md). | Run authenticated synthetic journeys through the ingress and measure database cost at retention scale. Complete durable denominators for upload acceptance, raw live events, scheduled history and verified restores require source evidence. |
+| OBS-E06-S02 | An optional Compose and Operator profile records scoped error budgets, evaluates multiwindow burn and distinguishes quiet traffic from incomplete data. Adoption requires a declared owner and scope. [API objectives](../operations/api-objectives.md). | Approve site targets and routing, verify rule cost and full-window coverage, and exercise operational firing and resolution. |
+| OBS-E06-S03 | Project and workflow detail remains in the application stores. Operational metrics use bounded case lifecycle, workflow stage, task and queue labels. Scoped queries preserve installation and deployment identity. [Metric cardinality](../operations/metric-cardinality.md). | Attach stable scrape identity before combining installations, update site dashboards that read retired families and measure rollout series churn. |
+| OBS-E06-S04 | A disposable workload measures Collector admission and delivery, store readback, Prometheus head series, CPU, RSS and logical bytes. Compose supports an explicit parent-based trace sampling ratio. [Telemetry capacity](../operations/telemetry-capacity.md). | Run a sustained application workload with platform quotas, realistic report sizes and retention compaction. Verify disk, query and alert behavior at site traffic. |
+
+The native reference stack delivered 4,096 logs with each sample policy. The 10% trace profile used 56% fewer OTLP bytes. Full destination outages filled both 32 MiB queues, returned bounded refusals and incremented per-signal failure counters. The disposable PostgreSQL workload verified a stable retry denominator, late recovery, and indexed plans against 20,000 older rows per source. Migration 0264 upgraded, repeated and downgraded in the disposable schema. Prometheus fixtures exercised role turnover, installation isolation, quiet and missing data, burn recovery and the 30-day coverage boundary. Source and release Compose configurations rendered with objectives, authenticated scrapes, alerting and durable telemetry together.
diff --git a/docs/operations/api-objectives.md b/docs/operations/api-objectives.md
new file mode 100644
index 000000000..99cd49700
--- /dev/null
+++ b/docs/operations/api-objectives.md
@@ -0,0 +1,107 @@
+# Proposed API objectives and response policy
+
+These objectives are an **unadopted proposal**. The ordinary monitoring profile does not load the objective rules. The optional profile loads an inert adoption example that keeps objective paging disabled. An installation owner must review the eligible population, targets, data coverage, alert receiver and response policy before adopting either objective.
+
+| Proposed objective | Good eligible attempt | Target | Rolling period |
+| --- | --- | --- | --- |
+| api_availability | A terminal 2xx or 3xx response | 99.9% | 30 days |
+| api_latency | A terminal 2xx or 3xx response whose final response body completes within its existing route budget | 95% | 30 days |
+
+The latency proposal aligns with the existing p95 route budgets and awaits site acceptance. Google recommends baselining indicators and agreeing the objective and response policy with stakeholders before adoption. See [Implementing SLOs](https://sre.google/workbook/implementing-slos/) and the [example SLO document](https://sre.google/workbook/slo-document/).
+
+## Measured boundary
+
+`JourneySLIMiddleware` produces reset-aware process counters:
+
+- `testlookup_api_journey_events_total{installation,environment,objective,outcome}`, with the two closed objectives above and outcomes `good`/`bad`.
+- `testlookup_api_sli_configured{installation,environment,objective}=1` on an enabled API target. Both counter outcomes are initialized even before traffic.
+- `OBSERVABILITY_INSTALLATION` enables measurement and must be a stable, non-secret installation identifier. `APP_ENV` supplies the environment. Neither field may identify a tenant or user.
+
+The eligible population is the six core GET templates in `app/services/journey_sli_contracts.py`: project list (200 ms), run list (250 ms), scoped run read (250 ms), run intelligence (800 ms), search (300 ms), and flaky coach (600 ms). Ordinary 4xx responses are excluded. A 429, 5xx, observed exception/cancellation or incomplete terminal handler is bad for both objectives. Health, metrics, administrative, export and unrelated routes are excluded. Route names, raw URLs, users and project IDs are not metric labels.
+
+These are **observed completed-attempt indicators**. A process that dies before recording its outcome, a request still hung in flight, an unreachable installation and client-side/network failures before the API are censored. Use independent probes, target-discovery alerts and customer-facing measurements alongside these indicators. The durable accepted-to-completed boundary requires separate evidence. Use SQL retained-state cohort gauges for the diagnostics described in [journey-slis.md](journey-slis.md), and source these rate windows from the API counters.
+
+Each recording groups by `installation,environment,cluster,namespace,objective`. The first two labels originate in the application. Cluster/namespace must reflect actual local scrape labels when present. Application and local scrape labels define rule-evaluation scope. Assign distinct installation identifiers to separate deployments with otherwise identical labels. The dashboard selects one exact scope and never sums across installations.
+
+## Unknown, quiet traffic and history
+
+A current scope is valid only if every observed configured API target has both outcome series and its `up` sample equals one. A missing outcome pair or down configured target invalidates assessment. Independent target/series-absence rules cover targets that have vanished entirely from service discovery.
+
+Rules sum each replica's `increase` before dividing. This handles independent counter resets and weights the fleet by eligible attempts. Counter increases are estimates between scrapes. The denominator retains its measured value. Zero eligible attempts yield **no ratio/burn/budget** and remain unknown. Quiet but fully configured targets do not trigger the measurement-unavailable alert. Prometheus documents the counter reset and extrapolation behavior of [increase/rate](https://prometheus.io/docs/prometheus/latest/querying/functions/).
+
+The fast group evaluates every minute. A five-minute window requires all six minute observations including its baseline, and other fast windows require the equivalent complete history. Every five-minute checkpoint requires that complete minute history. Thirty-day coverage requires all 8,640 consecutive checkpoints. A missing checkpoint makes the full window unknown until it rolls out. This coverage measure conservatively requires complete observations.
+
+Heavy three-day and thirty-day raw-counter calculations evaluate every five minutes. Current complete-window gates suppress cached assessments during gaps. The dashboard displays the thirty-day evaluation age. No-data values stay unknown. Allow at least thirty days plus initial scheduling alignment for a complete budget. Rebuilding Prometheus storage restarts this history. The ordinary 15-day retention cannot establish a thirty-day budget.
+
+The optional Compose profile requests 35-day retention and requires a site-selected size cap. A size cap that evicts history early still makes the window unknown. Before adoption, measure rule-group evaluation duration, missed/failed iterations, query sample counts, disk growth and CPU under the actual replica/scrape count. Provision enough storage and headroom. A five-minute group must finish comfortably within its interval. Capacity acceptance belongs to the installation and its measured fleet.
+
+## Proposed response policy
+
+The policy follows Google's multiwindow pattern, which requires simultaneous long and short burns so a recovered burst stops paging promptly. The longer window controls budget significance. The shorter window confirms an ongoing problem. See [Alerting on SLOs](https://sre.google/workbook/alerting-on-slos/).
+
+| Candidate action | Long window and burn | Short window and burn | Additional guard |
+| --- | --- | --- | --- |
+| Page, critical | 1 hour above 14.4x | 5 minutes above 14.4x | At least 3 estimated short-window bad attempts, 2-minute hold |
+| Page, critical | 6 hours above 6x | 30 minutes above 6x | At least 3 estimated short-window bad attempts, 2-minute hold |
+| Ticket candidate, warning | 3 days above 1x | 6 hours above 1x | At least 3 estimated short-window bad attempts, 15-minute hold |
+
+The reference policy proposes the three-bad-attempt guard as a low-traffic safeguard. Revisit it with the owner's actual traffic and independent probe coverage: it deliberately suppresses pages for a very small number of failed attempts.
+
+`TestLookupAPIObjectiveBudgetBurnPage` carries `severity=critical`. `TestLookupAPIObjectiveBudgetBurnTicket` carries `severity=warning`. It creates a ticket **only if the site's receiver implements ticket routing**. The reference Alertmanager sends both severities to its incident webhook with different timing. The site receiver owns ticket creation. Configure and verify the adopted receiver separately using [alert-routing.md](alert-routing.md), including resolved delivery.
+
+`TestLookupAPIObjectiveDataUnavailable` warns after five minutes only for an adopted scope with incomplete current measurement. `TestLookupAPIObjectivePolicyAmbiguous` warns if multiple active owners match one scope. That ambiguity disables objective paging. Initial window warmup remains a measurement state.
+
+## Compose adoption
+
+The source files are `infra/monitoring/objectives/api-slos.yml` and `adoption.example.yml`. Keep paging inert while collecting a baseline:
+
+```sh
+export OBSERVABILITY_INSTALLATION=your-stable-installation
+export SLO_PROMETHEUS_RETENTION_SIZE=20GB # example only: choose within the volume budget
+docker compose -f docker-compose.yml -f docker-compose.monitoring.yml \
+ -f docker-compose.objectives.yml config --quiet
+```
+
+Layer the existing authenticated-scrape, telemetry and alerting overlays used by the installation into that same command and preserve the reviewed overlay order. This command renders configuration only. For prebuilt release images, replace the first file with `docker-compose.release.yml`:
+
+```sh
+docker compose -f docker-compose.release.yml -f docker-compose.monitoring.yml \
+ -f docker-compose.objectives.yml config --quiet
+```
+
+Offline release bundles include the config-only `docker-compose.objectives.yml` overlay and the `infra/monitoring` tree. Preserve their relative paths and append the objective overlay to the bundle's reviewed Compose file list. It reuses the existing Prometheus image and adds no image download. Validate the complete offline render against the bundle manifest and the installation's registry overrides before rollout.
+
+Copy `adoption.example.yml` to a site-owned file. Replace installation/environment/cluster/namespace with the **actual local series labels**, set one accountable owner per objective, and leave each `vector(0)` unchanged until the objective and response policy are accepted. Record owner acceptance, date, rationale, baseline, traffic exclusions, independent monitoring, retention capacity, receiver test and rollback location in the site's change record. Then change only the accepted objective's expression to `vector(1)` and set `SLO_ADOPTION_RULES_FILE` to that file. Do not load both the example and its replacement.
+
+Validate the source and the chosen site file before the separately authorized rollout:
+
+```sh
+promtool check rules infra/monitoring/objectives/api-slos.yml /path/to/site-adoption.yml
+promtool test rules infra/monitoring/tests/objective-burn-rates.yml \
+ infra/monitoring/tests/objective-window-coverage.yml
+```
+
+To disable objective paging, return the site policy to `vector(0)`, validate it and follow the installation's reload/rollout procedure. Keep measurement and diagnostic alerts enabled while investigating.
+
+## Prometheus Operator adoption
+
+Generate the release artifact after editing the source, then inspect the optional overlay:
+
+```sh
+python scripts/render_prometheusrule.py
+kubectl kustomize k8s/monitoring-objectives
+```
+
+The base application, its authenticated metrics PodMonitors and the ordinary monitoring rules must already be selected and scraped. Set `OBSERVABILITY_INSTALLATION` on the API workload through the site's application patch. Configure at least 35-day Prometheus retention with an adequate volume/size limit in the site's Prometheus resource. Storage configuration belongs to that resource.
+
+`k8s/monitoring-objectives/prometheusrule.yaml` contains the objective calculations and alerts. The site supplies the adoption policy separately. Create a separate site-owned `PrometheusRule` whose `spec.groups` contains the reviewed adoption file's groups. Give it the installation namespace and labels selected by that Prometheus resource. Its `ruleNamespaceSelector` must include the namespace, and `ruleSelector` must select both the calculation rule and adoption rule. For kube-prometheus-stack this often requires the matching release label. Wrap the source groups in a Kubernetes manifest. Render/validate the site manifest and apply only through the normal authorized deployment process. Scope adoption labels to the actual scraped cluster/namespace.
+
+## Respond and verify
+
+1. Confirm the exact scope, active owner, current validity, window coverage and budget as-of age in **TestLookup — API Objectives (Proposed)**. Unknown data is not evidence of compliance. Check discovery and scrape failures first.
+2. For a burn, compare the long/short windows and bad-attempt counts. Use the overview route diagnostics, safe logs and sanitized traces to identify the affected route or dependency. For availability, verify independent reachability to cover fully censored outages.
+3. Restore the failing service/dependency or roll back the triggering change through the incident process. Do not change the target or exclude errors merely to silence a burn.
+4. Confirm the short window recovers, the alert resolves at the receiver, and the longer-window debt remains visible. A page clearing does not replenish the rolling budget immediately.
+5. For unavailable measurement, restore both outcome series and successful scrapes, then allow complete windows to warm up. For ambiguous ownership, retain exactly one accepted scoped policy. Record incident and policy decisions.
+
+Native Prometheus fixtures cover weighted replica totals, independent resets, installation/environment/cluster/namespace isolation, quiet/missing data, incomplete replicas, minimum-event suppression, adoption isolation, owner ambiguity, 1h/6h/3d burns and recovery. The thirty-day fixture tests the exact checkpoint boundary and insufficient fifteen-day history with native PromQL. It does not simulate thirty days of wall-clock traffic or certify a production fleet's query/storage capacity.
diff --git a/docs/operations/deploy-compose.md b/docs/operations/deploy-compose.md
index 29bcd6aa0..524395acf 100644
--- a/docs/operations/deploy-compose.md
+++ b/docs/operations/deploy-compose.md
@@ -186,6 +186,8 @@ docker compose -f docker-compose.yml -f docker-compose.monitoring.yml up -d
All of these listen on `127.0.0.1` only (`MONITORING_PUBLISH_ADDR`): Jaeger, the OTLP receivers and Prometheus have no authentication. Prometheus runs without `--web.enable-lifecycle`, so restart its container to reload the configuration.
+The optional objectives overlay records core API availability and latency for a named installation, with separate adoption and routing for burn alerts. [API objectives](api-objectives.md).
+
The override sets `OTEL_ENABLED=true`, `OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318` and `METRICS_ENABLED=true` on the backend. The same alert rules are rendered for Kubernetes in [`k8s/monitoring`](deploy-kubernetes.md#monitoring-podmonitor-and-prometheusrule). Metric and alert reference: [observability](../../architecture/OBSERVABILITY.md).
Use the [alert routing overlay](alert-routing.md) to deliver incident notifications and an independent watchdog over authenticated HTTPS. The [telemetry contract](telemetry-contract.md) lists the required roles and series.
diff --git a/docs/operations/deploy-kubernetes.md b/docs/operations/deploy-kubernetes.md
index 25edb766f..e19fbabab 100644
--- a/docs/operations/deploy-kubernetes.md
+++ b/docs/operations/deploy-kubernetes.md
@@ -178,12 +178,14 @@ kubectl apply -k k8s/monitoring
| File | Contents |
|---|---|
| `podmonitors.yaml` | `PodMonitor` `testlookup-backend` (port `http`, `/metrics` on 8000) and `testlookup-worker` (port `metrics`, 9100), each setting the `job` label the rules select on |
-| `prometheusrule.yaml` | `PrometheusRule` `testlookup-alerts`, generated from `infra/monitoring/prometheus-rules/testlookup-alerts.yml` by `scripts/render_prometheusrule.py`: application alerts (backend or worker down, error rate, slow requests, AI pipeline failures, LLM circuit breaker, DLQ, stale reviews, live-event archive failures), infrastructure alerts (DB pool, broker memory, queue backlog, task latency, disk, OOM kills), latency SLOs for key API routes, and the two backup alerts |
+| `prometheusrule.yaml` | `PrometheusRule` `testlookup-alerts`, generated from `infra/monitoring/prometheus-rules/testlookup-alerts.yml` by `scripts/render_prometheusrule.py`. It covers application errors and availability, infrastructure pressure, key API route latency and backups. |
The backup alerts read kube-state-metrics, and the disk and OOM alerts read node-exporter. If your Prometheus selects rules and monitors by label (kube-prometheus-stack uses `release: `), add that label in your site monitoring overlay. Confirm that the Prometheus resource selects rules and PodMonitors in the application namespace.
Include the telemetry inventory Rule along with the shared alert Rule. The [telemetry contract](telemetry-contract.md) explains the role labels and namespace scope. Use the cluster's Alertmanager and check [alert delivery and watchdog routing](alert-routing.md) against your site configuration.
+The optional `k8s/monitoring-objectives` overlay records availability, latency and coverage for a named installation. [API objectives](api-objectives.md).
+
### Authenticate the API scrape
Provision a Secret named `testlookup-metrics-auth` with key `token` in the application namespace through your secret manager. Include the `k8s/components/metrics-auth` component in your application overlay. It mounts the token read-only in the backend container. Select `k8s/monitoring-authenticated` as the monitoring resource in your site overlay. It uses `PodMonitor` bearer authorization with the same Secret key. The Operator needs permission to read that Secret in the PodMonitor namespace. [Prometheus Operator API](https://prometheus-operator.dev/docs/api-reference/api/).
diff --git a/docs/operations/durable-telemetry.md b/docs/operations/durable-telemetry.md
index e187e2c94..0daf7991a 100644
--- a/docs/operations/durable-telemetry.md
+++ b/docs/operations/durable-telemetry.md
@@ -57,7 +57,7 @@ The added egress policy names the gateway and port. Existing application policie
Add `--with-telemetry` to the standard [offline bundle](../../user-guide/air-gapped-install.md) build. It records upstream digests alongside local image aliases. The OSS Grafana and Loki images are external prerequisites under TestLookup's redistribution policy. The bundle's `compose/telemetry-prerequisites.list` records each pinned source image and required local alias as tab-separated fields. Stage those two images on a connected host, tag each verified image under its listed alias, and transfer and load them using your approved offline image process. [Grafana Labs licensing](https://grafana.com/licensing/).
-After verified import and normal registry setup, layer `docker-compose.monitoring.yml` and `docker-compose.telemetry.yml` after the release and air-gap Compose files. Run `docker compose ... up --pull never`. Provide environment files, credentials and optional alert receiver trust from local sources. Perform the first run with outbound network access denied and verify no external image, plugin, catalog or notification dependency is needed.
+After verified import and normal registry setup, layer `docker-compose.monitoring.yml` and `docker-compose.telemetry.yml` after the release and air-gap Compose files. The bundle also includes the optional objectives overlay and its inert adoption example. Run `docker compose ... up --pull never`. Provide environment files, credentials and optional alert receiver trust from local sources. Perform the first run with outbound network access denied and verify no external image, plugin, catalog or notification dependency is needed. [API objectives](api-objectives.md).
## Acceptance and response
@@ -68,4 +68,4 @@ After verified import and normal registry setup, layer `docker-compose.monitorin
The reference configuration follows the [OpenTelemetry Collector resiliency guide](https://opentelemetry.io/docs/collector/resiliency/), [Loki native OTLP mapping](https://grafana.com/docs/loki/latest/send-data/otel/), and [Jaeger storage documentation](https://www.jaegertracing.io/docs/2.23/storage/).
-Component details and verification commands are in [collector operations](telemetry-collector.md), [log storage](log-storage.md), and [persistent Jaeger](persistent-jaeger.md).
+Component details and verification commands are in [collector operations](telemetry-collector.md), [log storage](log-storage.md), [persistent Jaeger](persistent-jaeger.md), and [telemetry capacity and sampling](telemetry-capacity.md).
diff --git a/docs/operations/journey-slis.md b/docs/operations/journey-slis.md
new file mode 100644
index 000000000..e41fdf032
--- /dev/null
+++ b/docs/operations/journey-slis.md
@@ -0,0 +1,99 @@
+# Journey measurement contracts
+
+These measurements describe observed response and durable business state. Their thresholds are **proposed**, pending owner adoption after workload and deployment review. Enterprise availability commitments require that review. Existing Instrumentator HTTP histograms, performance diagnostics, outbox state/lease alerts, nightly observations and digest delivery alerts remain independently useful.
+
+Set an explicit `OBSERVABILITY_INSTALLATION` on the API before enabling objective inputs. It accepts 1–63 ASCII letters, digits, dots, underscores or hyphens and must start with a letter or digit. An empty value disables all new journey inputs and avoids a database read for this collector. The process never infers a site from a hostname, URL, project or task. Every new series carries that installation and the validated `APP_ENV` as `environment`. Configure one stable value per independently operated installation. Changing it starts a new measurement scope and budget history.
+
+Scrape target labels must also distinguish the actual cluster/namespace. Keep installations, environments and worker/API target populations separate. Preserve application scope labels and reject conflicts. Treat absent/unconfigured inputs as unknown. A measured zero denominator means no eligible activity. The [Google SRE SLO workbook](https://sre.google/workbook/implementing-slos/) recommends defining eligible events and good events around the service users receive. The contracts below identify the available evidence and each remaining complete-journey gap.
+
+## Core API response completion
+
+Owner: backend/SRE. Applicable scope: API processes with metrics enabled and explicit installation identity. `JourneySLIMiddleware` is installed around application middleware and handlers, beneath Starlette's outer server-error machinery. It neither changes responses nor replaces standard HTTP diagnostics.
+
+`testlookup_api_journey_events_total{installation,environment,objective,outcome}` has exactly two objective names, `api_availability` and `api_latency`, and two outcomes, `good` and `bad`. Both outcomes start at zero for each configured target. `testlookup_api_sli_configured{installation,environment,objective} = 1` establishes that initialization. Owner adoption is a separate operator decision.
+
+Only these existing GET operation templates are eligible:
+
+| Operation | Template | Proposed latency threshold |
+|---|---|---:|
+| Project list | `/api/v1/projects` | 200 ms |
+| Run list | `/api/v1/runs` | 250 ms |
+| Run detail | `/api/v1/runs/{run_id}` | 250 ms |
+| Run intelligence | `/api/v1/runs/{run_id}/intelligence` | 800 ms |
+| Keyword search | `/api/v1/search` | 300 ms |
+| Flaky coach | `/api/v1/projects/{project_id}/flaky-coach` | 600 ms |
+
+The thresholds come directly from `LATENCY_BUDGETS`. They are existing p95 diagnostic budgets. A proposed latency objective of 95% within these thresholds is consistent with that basis. A different adopted fraction needs a measured baseline and owner decision. The aggregate is weighted by the traffic mix of these six operations and can hide an individual operation's poor latency. Keep per-operation HTTP diagnostics alongside it. Freeze or deliberately version threshold policy when adopting an objective so a mixed-version rollout remains distinguishable.
+
+Eligibility includes completed 2xx/3xx responses, server quota/backpressure 429, server errors and unhandled/cancelled eligible handlers. Ordinary 4xx client/auth/scope/validation refusals are excluded. A resolved route supplies the template. Before the router runs, an internal matcher recognizes only the same six fixed method/path patterns so an early guard's 429/500 can be observed. It follows Starlette's `root_path` boundary handling for mounted applications and reverse proxies. Metric labels contain only the bounded objective/outcome and configured scope. Guards outside this middleware remain outside its coverage. These are supported core-route **attempts**. An early server error can precede successful authentication.
+
+Availability is good for a fully sent 2xx/3xx response and bad otherwise. Latency is good only when availability is good and the final response body is sent within the operation's threshold. A failed response is bad for both objectives. Each eligible attempt contributes once per objective. Post-response background work preserves the already measured response outcome. Asynchronous uploads, external notifications and AI results require their own completion evidence.
+
+These process counters reset with a fresh process metric epoch. Sum counter rates across actual API processes before computing a ratio. Requests that never finish or raise remain censored until they terminate. A process killed before recording its outcome, scrape loss around a restart, a proxy rejecting a request before the app, and client-to-proxy network failures are outside this denominator. Independent synthetic journeys, availability checks and a durable accepted-request ledger remain required for complete accepted-to-completed availability.
+
+## Matured SQL-intent cohorts
+
+Owner: backend/AI platform. Applicable scope: retained SQL intents observed by an authorized API scrape. The `journeys` bounded collector reads each of its two tables once in a read-only PostgreSQL repeatable-read snapshot. A 750 ms per-statement limit and the existing one-second foreground collection deadline bound the attempt. It publishes only after both aggregate queries succeed. Query failure preserves the previous observation time.
+
+Each serving API child encodes the entire cohort, source-support indicators and observation timestamp into one immutable Prometheus bundle. The authorized scrape appends this bundle only after successful collection. This keeps one child's changing outcomes together when Gunicorn uses multiple workers. The three cohort metric families remain outside native multiprocess Gauge aggregation.
+
+A 30-second local cache reuses a complete bundle for the same installation, environment and AI deadline. Explicit `now` arguments bypass this cache for deterministic tests. A cache hit preserves the database observation timestamp. The collector's successful cached response measures scrape availability. Consumers must also check the actual cohort timestamp against the 120-second freshness contract. The reference 15-second scrape interval fits this contract. Review scrape cadences above 60 seconds, missed-scrape tolerance and the freshness threshold together.
+
+Migration `0264` creates concurrent `created_at` indexes for both source tables with matching ORM definitions. It safely retries an invalid concurrent build and drops only these indexes on downgrade. There is no row backfill. The indexes, two aggregate reads and cache reduce repeated scan work. Production acceptance still requires measuring retained 30-day row counts, query CPU/latency and replica count under the chosen scrape cadence. Statement timeouts provide a bound rather than a capacity result.
+
+`testlookup_journey_cohort_events{installation,environment,journey,window,outcome}` is an **absolute gauge**, not a counter. The bounded windows are `1h`, `6h`, `24h` and `30d`. For observation time `t`, deadline `d` and window `w`, the acceptance interval is `(t-d-w, t-d]`. Work younger than its deadline is not yet eligible. Every retained intent in this matured cohort contributes once, including an intent that never started or completed. A terminal failure enters the cohort when its deadline matures, rather than artificially advancing the failure's acceptance time.
+
+| Journey | Durable acceptance grain | Good completion evidence | Proposed deadline |
+|---|---|---|---|
+| `downstream` | One committed `run_downstream_outbox` row, uniquely keyed by run/operation/input_version | Supported operation with explicit `completed` status and valid `completed_at` | 4200 s: existing finalization recovery grace plus one execution lease |
+| `live_materialization` | The subset whose operation is `persist_live_session` | Explicit completion of that persisted intent | Same 4200 s reference bound |
+| `ai_completion` | One committed `agent_pipeline_runs` identity | `completed` or `passed` with valid `completed_at`; reported degradation is allowed | Current positive `AI_PIPELINE_DEADLINE_SECONDS`, default 1500 s |
+| `ai_reported_full_quality` | The same pipeline identity, with a stricter numerator | Timely completion with explicit `fallback_used = false` and no degraded/unknown stage-quality marker | Same configured reference bound |
+
+The downstream bound provides a conservative diagnostic reference. Workflow-specific product deadlines require separate adoption. The AI bound uses the current configured reference criterion. Historical workflows can have different frozen execution deadlines. A zero/nonpositive AI bound makes both AI source-support indicators zero and omits their cohort samples. The independently valid downstream cohorts remain available.
+
+The six disjoint outcomes are:
+
+| Outcome | Meaning |
+|---|---|
+| `good` | Positive durable completion within the reference deadline; full-quality journey additionally requires its explicit quality evidence. |
+| `late` | Valid durable completion after that deadline. Recovery changes overdue to late, preserving a bad timely-completion denominator. |
+| `failed` | Explicit durable terminal failure. |
+| `overdue` | Mature work still waiting/pending/sending/published/processing, or AI pending/running/retry_wait. |
+| `degraded` | Timely completed AI work lacks explicit full-quality evidence or reports fallback/degradation; used only by the stricter quality journey. |
+| `unknown` | Unknown operation/status, missing successful completion timestamp, or completion timestamp before acceptance or after observation. |
+
+Outbox states retain their actual meanings. `waiting` awaits finalization/recovery. `pending` awaits dispatch. `sending` holds a publication lease. `published` has been sent to the broker. `processing` holds an execution lease. `completed` is explicit tracked-operation completion. `failed` exhausted or explicitly failed its durable lifecycle. A Celery `SUCCESS`, deferred publication, empty broker queue or incremented retry counter provides task/dispatch diagnostics only. Dispatch/execution retries retain the same intent denominator. An operation can validly finish with no configured receiver. Actual notification delivery needs its own delivery receipt.
+
+Select one freshest valid API target for each installation/environment/cluster/namespace tuple. Join that same target identity to **all** outcomes and support indicators before optionally removing replica labels. Equal observation timestamps may choose either single target. Independently taking the maximum of each outcome can combine an old overdue count with a new late count and invent a denominator. Summing replicas has the same duplication risk. These absolute gauges support current-state ratios, with counter operations reserved for actual counters.
+
+A reader or API restart rederives the same SQL state without a local counting checkpoint. Require fresh `testlookup_journey_cohort_observed_at_seconds` **and** successful/fresh `testlookup_metric_collection_*{collector="journeys"}` before displaying any ratio. `testlookup_journey_source_supported` states source capability. A current successful read is established separately by observation freshness.
+
+These are current retained cohorts. Authorized retention and run cascades remove rows. Same-ID AI resumes can clear/rewrite completion and quality. The current deadline criterion can change. An older never-completed intent eventually leaves the rolling horizon while remaining unresolved. Existing all-retained-state outbox failure/overdue alerts continue to expose that old work. An immutable acceptance/outcome ledger and declared retention/measurement epoch remain required for historical business burn rates and a complete long-term SLO.
+
+## Explicit unsupported boundaries
+
+`testlookup_journey_source_supported{installation,environment,journey}` is zero for the following complete journeys. Their contracts and corrective boundaries are explicit. Missing sources remain visible as unsupported measurements.
+
+| Journey | Available evidence and gap | Required completion contract / owner |
+|---|---|---|
+| `api_durable` | Process response counters lack durable accepted requests and never-returning outcomes. | Durable/independent attempted-request accounting, declared request timeout, and customer-facing response deadline; backend/SRE. |
+| `upload_acceptance` | JSON/file 202 precedes durable normalized TestRun. Advisory Redis status expires after 24 h and has no acceptance/completion timestamps; task SUCCESS cannot repair that denominator. | One durable accepted upload identity/receipt and terminal persisted usable result, with measured size/workflow deadlines; backend. |
+| `live_event_acceptance` | Redis stream acceptance/checkpoints and replay protocols exist. SQL attempt/event receipts begin at projection, so counting them alone is success-biased. | Complete accepted event/batch denominator plus durable projection and visibility time, replay deduplication and explicit freshness/recovery bounds; backend. |
+| `scheduled_history` | Nightly slot observations and digest delivery state detect current due/never-delivered work, but retain latest observations rather than every expected slot. | Immutable enabled expected-slot history, deduplicated generation versus confirmed delivery, existing nightly 1 h / weekly-dispatch 25 h grace respected, and owner-adopted schedule objectives; backend/SRE. |
+| `backup_verified_restore` | CronJob success is process completion, not proof of a restorable archive or a successful restore. | Durable expected backup/archive verification receipts, declared RPO/RTO and periodic successful isolated restore of all required stores/artifacts; SRE. |
+
+This stage adds indexes and derives existing records. Complete accepted-upload/live-event, schedule-history and verified-restore objectives remain open until their durable boundaries and safe lifecycle changes have been implemented and tested.
+
+## Known-workload verification
+
+From `backend`:
+
+```powershell
+$env:PYTEST_DISABLE_PLUGIN_AUTOLOAD = '1'
+python -m pytest -q -p pytest_asyncio.plugin tests/test_journey_sli.py
+```
+
+The fixture verifies actual ASGI completion/error behavior, early fixed-template guards, final-body timing, excluded refusals, disabled/invalid installation scope, all seven outbox states, retry deduplication, good/failed/degraded/late/never-completed work, exclusive cohort boundaries, late recovery, repeated independent reads and empty-source zeros. No worker, provider or live application is exercised by this unit fixture.
+
+`tests/integration/test_journey_sli_postgres.py` requires an explicitly configured disposable `TESTLOOKUP_POSTGRES_TEST_DSN` and is wired into the existing CI PostgreSQL command. It creates isolated `LIKE` copies, inserts only synthetic intents/pipelines, executes the actual read-only collector, compares fresh readers and retry/recovery outcomes, and drops its schema. It also verifies migration upgrade/retry/downgrade, ORM index parity and selective query plans with 20,000 older rows in each table. Run it only against a disposable fixture database. Native PostgreSQL 16.15 verification uses synthetic ORM-DDL source tables without account foreign keys. That proof covers SQL derivation, transactions and index eligibility. Full migrated account-schema behavior and production load capacity need separate acceptance evidence.
diff --git a/docs/operations/metric-cardinality.md b/docs/operations/metric-cardinality.md
new file mode 100644
index 000000000..249decb5f
--- /dev/null
+++ b/docs/operations/metric-cardinality.md
@@ -0,0 +1,136 @@
+# Operational metric dimensions and migration
+
+The E06 cardinality boundary keeps project/workflow identities in the authorized
+SQL-backed APIs and pipeline evidence, and uses finite operational dimensions in
+Prometheus. It covers the twelve families in
+[the machine-readable budget](../../infra/monitoring/metric-cardinality-budget.json).
+Measure the remaining registry and production capacity separately.
+
+## Producer contracts
+
+| Signal | Operator question and boundary |
+| --- | --- |
+| `testlookup_test_case_transitions_total` | Committed governance event volume, by stored `from`/`to` states and actor role. Ten state values and six role values include `other`. Project identity stays in SQL. |
+| `testlookup_test_case_promotions_total`, `testlookup_test_case_deprecations_without_reason_total` | Committed governance event volume, with no application labels. The request owner emits only after commit. Rollback discards staged events. Telemetry failures remain best effort. |
+| `testlookup_pipeline_stage_*`, `testlookup_pipeline_fallback_total` | Stage execution, time, tokens, cost, calls and failure/fallback categories by the static agent capability. Stage duration is seconds, cost is USD, and tokens and calls are counts. Authored step identities stay in SQL and events. |
+| `testlookup_celery_tasks_total` | Execution outcomes by a frozen deployed task registry, capped at 128 names plus `other`, and eleven known states including `unknown`/`other`. SUCCESS, FAILURE, RETRY, REVOKED and REJECTED retain their meanings. |
+| `celery_task_runtime_seconds` | Execution duration in seconds by the same task registry and eight queue families. All numeric `ingestion.shard.N` routing keys map to `ingestion_shard`. |
+
+[The shared inventories](../../backend/app/core/metric_dimensions.py) contain 27
+stage values, seven fallback reasons and nine error categories, each including
+an overflow value. Unrecognized free text maps to `other`. Truncating or hashing
+free text still permits unbounded series. Full runtime step identity and
+original fallback/error detail remain in SQL and pipeline events, subject to
+their existing privacy and retention boundaries. Queue routing, exact per-shard
+queue-depth gauges and the ingestion health response are unchanged.
+
+The task inventory freezes at first observation in each process. Production
+workers load their task modules before execution. Late/dynamic registrations
+and names beyond the sorted 128-name budget use `other`. Restart after an
+intentional task-registry change. The source regression test loads the production
+registry and rejects growth above the budget so that increasing it requires an
+explicit capacity review. A received routing key or task name cannot extend
+the vocabulary. This follows [Prometheus instrumentation guidance](https://prometheus.io/docs/practices/instrumentation/)
+to keep dimensions bounded and move detailed high-cardinality analysis to an
+appropriate data system.
+
+## Authoritative tenant analytics
+
+Three process-local snapshots are retired:
+`testlookup_test_cases_by_state`, `testlookup_automation_cases_orphaned` and
+`testlookup_workflow_eval_coverage`. Stored definitions are a growing set, and
+deleted IDs remained in these gauges indefinitely. Neither a request-local
+snapshot nor an unlabeled last-workflow gauge represents shared current state.
+
+Authored cases and immutable lifecycle snapshots remain in SQL. The existing
+orphan endpoint still returns authorized, project-filtered rows and the total,
+including zero and pagination, using its two authoritative queries. Workflow
+evaluation still
+writes coverage/verdict/gate evidence to `WorkflowDefinition` and `AIEvalGateRun`.
+[The workflow serializer](../../backend/app/services/workflow_definition_service.py)
+continues returning `project_id`, `workflow_id`, `eval_coverage` and
+`eval_gate_run_id`. There is no data migration or loss of stored analytics.
+
+## Scope and replica changes
+
+The changed stage and Celery panels in
+[the overview dashboard](../../infra/monitoring/grafana/dashboards/testlookup-overview.json)
+preserve `installation`, `environment`, `cluster` and `namespace` when present.
+Counter increases sum across distinct producer replicas within that scope.
+Histogram buckets aggregate before `histogram_quantile`. Replica count changes
+alter event volume while the application's dimensions stay bounded. Never sum
+replica quantiles or duplicate-scrape one multiprocess producer directory.
+
+The default Compose profile deliberately uses a dedicated local Prometheus and
+has no cluster/namespace labels. These queries continue to work for that
+single-installation boundary. Missing scope labels remain a separate unlabelled
+group. The default legend may show unavailable scope placeholders. The numerical
+query remains usable.
+
+Before federation, remote read or scraping multiple installations, operators
+must attach a unique stable installation/environment identity to each source,
+and cluster/namespace where applicable. Configure scrape relabeling or the site's
+Operator selectors/target labels and prove the resulting **sample labels**.
+Prometheus `external_labels` alone do not label locally evaluated raw samples.
+Align target and application label ownership to avoid conflicts that cause
+Prometheus to rename application labels to `exported_*`. The optional
+objective profile has a separate application-owned identity contract. Coordinate
+with [API objectives](api-objectives.md). Two entirely unlabelled installations
+in the same query source cannot be separated retrospectively. Their multi-site
+acceptance remains open until source identities are verified.
+
+## Budget and rollout
+
+The conservative sum for the twelve selected families is **21,358 series per
+process** if every permitted combination is observed. It includes Counter
+`_created` samples and Histogram `+Inf`, count, sum and created samples. Some
+multiprocess modes omit created samples. For example, stage duration allows
+`27 × 2 × 12 = 648` series, and task runtime allows
+`129 × 8 × 15 = 15,480`. These ceilings assume all combinations are observed.
+Series appear on actual observations. Applicable roles emit subsets of this
+combined budget. Scale by active exporter targets and the union of vocabularies actually
+present in a multiprocess directory. One exporter merges identical child labels.
+
+Account separately for scrape labels, concurrent build versions, process/replica
+churn, the remainder of the registry and historical TSDB retention. A newly
+deployed task inventory may have different names, so its retained union can
+exceed one version's 128 names. Feature flag keys, configured model names and
+endpoint digests are explicit residual dimensions listed in the budget. Budget
+those remaining dimensions separately. Inspect measured
+`scrape_samples_post_metric_relabeling`, head series and TSDB growth before
+setting capacity or changing retention.
+
+Roll out API and worker producers together. Existing governance metric names
+now have fewer labels. Update external queries that filter by `project` and
+replace retired snapshot queries with the existing APIs. During overlap, old
+processes can still export tenant/custom-step series. Do not use an unfiltered
+mixed-version sum as proof of the new schema. To inspect new transition samples
+during overlap, `project=""` excludes old nonempty-project labels. Drain old
+processes and apply the existing private multiprocess-directory startup reset
+before evaluating the current-export budget. The
+[Python client's multiprocess contract](https://prometheus.github.io/client_python/multiprocess/)
+requires this startup directory lifecycle and a separate collector registry.
+Keep historical Prometheus data until its normal retention expiry.
+
+## Verification and remaining deployment acceptance
+
+Source tests exercise 2,000 project identity changes without growing counter
+series, 200 workflow/project evaluation identities while retaining API evidence,
+unknown stage/category/state/task input, the deployed task cap, custom-step SQL
+identity, native multiprocess replacement with cumulative counts, and configured
+shard-family normalization. The synthetic PromQL fixture
+checks default single-installation data, labelled installation/environment and
+namespace isolation, and replica addition/removal:
+
+```powershell
+python -m pytest backend/tests/regression/test_operational_metric_dimensions.py backend/tests/services/test_test_management_metrics_service.py backend/tests/services/test_workflow_evaluation_service.py -q
+promtool test rules infra/monitoring/tests/metric-scope.yml
+```
+
+The fixture is outside the rule-loading directory and runs in the existing
+backend CI job. These tests use local/fake storage boundaries and synthetic
+time series. Deployment acceptance still requires actual target identity,
+exporter deduplication, production series counts, private-directory lifecycle
+and API/worker load capacity. Verify those with a known workload in the intended
+disposable profile, including create/delete/recreate and a rolling replica change, before
+closing the corresponding rollout and capacity acceptance.
diff --git a/docs/operations/telemetry-capacity.md b/docs/operations/telemetry-capacity.md
new file mode 100644
index 000000000..0a8314209
--- /dev/null
+++ b/docs/operations/telemetry-capacity.md
@@ -0,0 +1,57 @@
+# Telemetry capacity and sampling
+
+Use the [durable telemetry profile](durable-telemetry.md) for a single installation. Its Collector, Loki and Jaeger limits bound the footprint of those services. Size Prometheus separately for the application's scrape targets, rules and alert history.
+
+## Reference measurements
+
+The benchmark used Collector Contrib 0.166.0, Loki 3.7.10, Jaeger 2.23.0 and Prometheus 3.16.0 from the pinned releases. They ran as native loopback processes on an Intel Core Ultra 9 285K Windows host with 32 GiB of RAM. The store and queue settings matched the reference files. Native processes did not have the Compose cgroup limits. Each profile began on fresh storage and warmed up with 16 logs and 64 spans. The measured burst used 4,096 synthetic logs, four concurrent producers, 64 records per batch, roughly 5% server errors and four spans per retained trace. Logs represented API, two worker roles and MCP. Prometheus scraped the Collector, stores and itself every 2 seconds for this test.
+
+| Measurement | Every root sampled | 10% of roots sampled |
+|---|---:|---:|
+| Logs and spans delivered | 4,096 and 16,384 | 4,096 and 1,640 |
+| Uncompressed OTLP payload | 5.49 MiB | 2.43 MiB |
+| Collector ingress and complete delivery | 0.267 s and 3.218 s | 0.300 s and 2.812 s |
+| Collector ingestion HTTP p95 | 25.94 ms | 24.90 ms |
+| Largest combined queue sample during ingress | 619.5 KiB | 359.8 KiB |
+| Loki hashed request lookup p95, 12 reads | 31.88 ms | 31.10 ms |
+| Jaeger four-span trace lookup p95, 12 reads | 25.56 ms | 20.02 ms |
+| Prometheus head series observed | 2,259 | 2,259 |
+| CPU seconds added, Collector / Loki / Jaeger / Prometheus | 0.63 / 0.36 / 0.64 / 0.03 | 0.42 / 0.33 / 0.13 / 0.03 |
+| End RSS, Collector / Loki / Jaeger / Prometheus | 167 / 141 / 164 / 76 MiB | 162 / 151 / 65 / 73 MiB |
+| End logical disk, Collector / Loki / Jaeger / Prometheus | 3.00 MiB / 2.24 MiB / 2.13 GiB / 94 KiB | 2.13 MiB / 2.24 MiB / 2.13 GiB / 90 KiB |
+
+The 10% profile used 56% fewer ingress bytes and retained every log. The short run measures burst delivery and readback. Jaeger preallocated about 2.13 GiB even after warmup, and Loki and Prometheus still held recent data in their active write paths. Use measured disk allocation after several compaction cycles under site traffic to calculate storage growth. The burst result includes neither the application scrape series nor application load. The query samples use exact IDs in a recent two-minute range.
+
+With both destinations unavailable, the unchanged Collector queue settings admitted about 31.6 MiB of logs and 32.0 MiB of traces. The next three batches per signal returned HTTP 503 in 1.9–20.6 ms. The Collector reported enqueue failures for 4,500 log records and 768 spans and used 128 MiB of logical queue files. The native recovery tests also exercise persistent replay after abrupt restart, retry exhaustion at a shortened deadline and Jaeger read expiry with a shortened TTL. Loki kept recent data across a forced restart and rejected a synthetic record timestamped eight days earlier under the configured seven-day age limit. Verify asynchronous disk reclamation at the site's configured retention intervals.
+
+## Reproduce in disposable storage
+
+Start the pinned binaries with the reference configuration, unique writable data directories and loopback-only ports. Point the Collector's HTTP exporters at the disposable stores. Use the same scrape and query intervals across comparisons. Keep the storage directories until you have recorded compaction growth, then discard the synthetic profile. The workload command accepts only explicit HTTP loopback origins.
+
+```sh
+python scripts/monitoring/measure_reference_capacity.py \
+ --collector "$COLLECTOR_OTLP" --collector-metrics "$COLLECTOR_METRICS" \
+ --loki "$LOKI" --jaeger "$JAEGER_QUERY" --jaeger-metrics "$JAEGER_METRICS" \
+ --prometheus "$PROMETHEUS" --collector-data "$COLLECTOR_DATA" \
+ --loki-data "$LOKI_DATA" --jaeger-data "$JAEGER_DATA" \
+ --prometheus-data "$PROMETHEUS_DATA" --trace-fraction 1.0
+```
+
+Repeat on a fresh copy with `--trace-fraction 0.1`. The driver checks exact delivery counter deltas, queries up to 24 log and trace IDs, and reports observed queue pressure, process metrics, logical bytes and query times. It generates whole sampled traces. Separately load a candidate application with representative authenticated traffic and large reports, including successful jobs, failed jobs, retries, and concurrent live events. Measure application latency and accepted-to-completed progress alongside telemetry growth so a report's size and its telemetry fan-out can be compared separately.
+
+## Size and operate the stores
+
+| Signal | Reference limit | Site sizing input |
+|---|---|---|
+| Collector queues | 32 MiB per signal, 64 MiB ceiling per database, 10-minute retry per dequeued work item. Compose gives the Collector 1 CPU and 512 MiB of memory. | Reserve space for both databases and compaction, starting with 256 MiB plus filesystem overhead. Divide 32 MiB by each signal's observed enqueue bytes/s to estimate its queue-only outage coverage. Retry age, disk pressure and process availability can shorten it. |
+| Loki | 7-day search/retention window with asynchronous compaction and deletion. The reference limit is 1 MiB/s per tenant and 512 KiB/s per stream before bursts. Compose gives Loki 1 CPU and 1 GiB of memory. | Measure compacted bytes/day, WAL, index and free space at peak traffic. Budget daily growth × retention plus write and compaction headroom. Measure hashed-ID queries at the full search horizon as well as recent lookups. |
+| Jaeger | 72-hour span TTL. Compose gives Jaeger 1 CPU and 512 MiB of memory. | Start with the measured preallocation, add post-compaction daily growth × retention and reserve space for storage maintenance. Compare query latency and RSS under concurrency. |
+| Prometheus | Baseline time retention is 15 days. The optional API objectives profile uses 35 days plus a site-selected size cap. | Measure samples/s, head series, and compacted bytes/day. Prometheus estimates 1–2 bytes per compacted sample. Allow extra room for the WAL and head blocks, and set the size cap to at most 80–85% of a dedicated volume. Whichever retention limit is hit first applies. [Prometheus storage](https://prometheus.io/docs/prometheus/latest/storage/). |
+
+Set explicit disk quotas or volumes on the host with sustained free-space alerts. The shipped telemetry alerts surface high queue occupancy, refused ingress and failed exports. A short burst can fill the queue before an occupancy alert's hold time, so check refusal counters as well. If a store is down, restore write capacity and confirm drain before increasing ingest or retry limits. Separate metric and incident sinks from the application failure domain where required. Single-node storage and a single local filesystem share a loss boundary.
+
+## Select a trace sample rate
+
+The durable Compose profile defaults to `parentbased_always_on`. To reduce transport and storage for a larger site, set `OTEL_TRACES_SAMPLER=parentbased_traceidratio` and an explicit `OTEL_TRACES_SAMPLER_ARG` such as `0.1` on the API. Apply the same policy across its replicas. Child spans respect their parent's sampling decision. A head sampler makes its decision before the request outcome, so a failed request can have a log and trace identifier without a stored trace. Logs, Prometheus counters and authoritative audit evidence remain independent of the trace selection. [OpenTelemetry sampling](https://opentelemetry.io/docs/concepts/sampling/), [SDK environment variables](https://opentelemetry.io/docs/specs/otel/configuration/sdk-environment-variables/).
+
+For a site that needs policy-driven tail sampling, the gateway operator owns routing all spans in a trace to the same sampler, bounded in-memory state, decision delay and sampling failure metrics. Decide how to persist accepted work through gateway failure before moving that stage in front of a durable queue. Verify error and slow-trace visibility with injected failures, peak concurrency, and trace-ID reads. Apply log and trace retention policies independently of [audit evidence custody](audit-archive-custody.md).
diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md
index 372105f97..00f40ac02 100644
--- a/docs/reference/configuration.md
+++ b/docs/reference/configuration.md
@@ -10,6 +10,7 @@ Source declarations only; no `.env` or running secrets are read. Compose/Helm/Ku
|---|---|---|
| `APP_NAME` | `str` | `'TestLookup'` |
| `APP_ENV` | `Literal['development', 'staging', 'production']` | `'development'` |
+| `OBSERVABILITY_INSTALLATION` | `str` | `''` |
| `APP_SECRET_KEY` | `str` | `'change-me-in-production'` |
| `APP_SECRET_KEY_PREVIOUS` | `Optional[str]` | `None` |
| `APP_DEBUG` | `bool` | `False` |
diff --git a/docs/reference/data-dictionary.md b/docs/reference/data-dictionary.md
index ee4736e40..502449c61 100644
--- a/docs/reference/data-dictionary.md
+++ b/docs/reference/data-dictionary.md
@@ -174,7 +174,7 @@ Current SQLAlchemy metadata, without a database connection. All columns, server/
## access_audit_logs
-[backend/app/models/postgres.py:4844](../../backend/app/models/postgres.py#L4844)
+[backend/app/models/postgres.py:4847](../../backend/app/models/postgres.py#L4847)
Append-only audit trail for user role and project membership changes.
@@ -219,7 +219,7 @@ Constraints and indexes:
## agent_action_dispatch_outbox
-[backend/app/models/postgres.py:6654](../../backend/app/models/postgres.py#L6654)
+[backend/app/models/postgres.py:6657](../../backend/app/models/postgres.py#L6657)
Durable delivery intent for approved actions; never contains prompts.
@@ -251,7 +251,7 @@ Constraints and indexes:
## agent_action_ledger
-[backend/app/models/postgres.py:6195](../../backend/app/models/postgres.py#L6195)
+[backend/app/models/postgres.py:6198](../../backend/app/models/postgres.py#L6198)
Append-only proposal/execution ledger for agent-originated actions.
@@ -302,7 +302,7 @@ Constraints and indexes:
## agent_child_dispatch_outbox
-[backend/app/models/postgres.py:2423](../../backend/app/models/postgres.py#L2423)
+[backend/app/models/postgres.py:2425](../../backend/app/models/postgres.py#L2425)
Durable dispatch record for a planner-spawned Investigator child.
@@ -338,7 +338,7 @@ Constraints and indexes:
## agent_configs
-[backend/app/models/postgres.py:6441](../../backend/app/models/postgres.py#L6441)
+[backend/app/models/postgres.py:6444](../../backend/app/models/postgres.py#L6444)
A project's configuration of one agent (architecture E4.1, section 4.2).
@@ -370,7 +370,7 @@ Constraints and indexes:
## agent_investigations
-[backend/app/models/postgres.py:2279](../../backend/app/models/postgres.py#L2279)
+[backend/app/models/postgres.py:2281](../../backend/app/models/postgres.py#L2281)
One Investigator run against a test run (shadow mode).
@@ -439,7 +439,7 @@ Constraints and indexes:
## agent_invocations
-[backend/app/models/postgres.py:6361](../../backend/app/models/postgres.py#L6361)
+[backend/app/models/postgres.py:6364](../../backend/app/models/postgres.py#L6364)
One call of a single agent through the public API (architecture E1.2).
@@ -484,7 +484,7 @@ Constraints and indexes:
## agent_memory_entries
-[backend/app/models/postgres.py:6140](../../backend/app/models/postgres.py#L6140)
+[backend/app/models/postgres.py:6143](../../backend/app/models/postgres.py#L6143)
Unified memory linking a run/snapshot to related entities (clusters, defects,
release decisions, ownership) for project-scoped historical recall.
@@ -532,7 +532,7 @@ Constraints and indexes:
## agent_pipeline_runs
-[backend/app/models/postgres.py:2593](../../backend/app/models/postgres.py#L2593)
+[backend/app/models/postgres.py:2595](../../backend/app/models/postgres.py#L2595)
Tracks a single execution of the multi-agent pipeline for a test run.
@@ -572,6 +572,7 @@ Constraints and indexes:
- `ForeignKeyConstraint` `unnamed`: `rerun_of`
- `ForeignKeyConstraint` `unnamed`: `test_run_id`
- `PrimaryKeyConstraint` `unnamed`: `id`
+- Index `ix_agent_pipeline_runs_created_at` (unique=False): `agent_pipeline_runs.created_at`; options `{}`
- Index `ix_pipeline_runs_status` (unique=False): `agent_pipeline_runs.status`; options `{}`
- Index `ix_pipeline_runs_test_run` (unique=False): `agent_pipeline_runs.test_run_id`; options `{}`
@@ -583,7 +584,7 @@ stages: Mapped[list['AgentStageResult']] = relationship('AgentStageResult', back
## agent_runs
-[backend/app/models/postgres.py:2489](../../backend/app/models/postgres.py#L2489)
+[backend/app/models/postgres.py:2491](../../backend/app/models/postgres.py#L2491)
Agent activity ledger: one row per agent
execution — what ran, why, what it proposed, what it actually did
@@ -621,7 +622,7 @@ Constraints and indexes:
## agent_stage_results
-[backend/app/models/postgres.py:2696](../../backend/app/models/postgres.py#L2696)
+[backend/app/models/postgres.py:2699](../../backend/app/models/postgres.py#L2699)
Per-stage result for an AgentPipelineRun.
@@ -684,7 +685,7 @@ pipeline_run: Mapped['AgentPipelineRun'] = relationship('AgentPipelineRun', back
## ai_analysis
-[backend/app/models/postgres.py:1532](../../backend/app/models/postgres.py#L1532)
+[backend/app/models/postgres.py:1534](../../backend/app/models/postgres.py#L1534)
Stored AI triage results per test case: the LATEST answer (fast read).
@@ -727,7 +728,7 @@ test_case: Mapped['TestCase'] = relationship('TestCase', back_populates='ai_anal
## ai_analysis_versions
-[backend/app/models/postgres.py:1574](../../backend/app/models/postgres.py#L1574)
+[backend/app/models/postgres.py:1576](../../backend/app/models/postgres.py#L1576)
One immutable version of a test result's AI analysis (AIH-01, migration 0205).
@@ -790,7 +791,7 @@ Constraints and indexes:
## ai_eval_baselines
-[backend/app/models/postgres.py:5857](../../backend/app/models/postgres.py#L5857)
+[backend/app/models/postgres.py:5860](../../backend/app/models/postgres.py#L5860)
Baseline metrics per agent/task_type for comparison gating.
@@ -828,7 +829,7 @@ Constraints and indexes:
## ai_eval_datasets
-[backend/app/models/postgres.py:5731](../../backend/app/models/postgres.py#L5731)
+[backend/app/models/postgres.py:5734](../../backend/app/models/postgres.py#L5734)
Labeled evaluation dataset for measuring AI quality over time.
@@ -853,7 +854,7 @@ Constraints and indexes:
## ai_eval_gate_runs
-[backend/app/models/postgres.py:5894](../../backend/app/models/postgres.py#L5894)
+[backend/app/models/postgres.py:5897](../../backend/app/models/postgres.py#L5897)
Historical record of an agent-stack release gate decision.
@@ -889,7 +890,7 @@ Constraints and indexes:
## ai_eval_item_outputs
-[backend/app/models/postgres.py:5818](../../backend/app/models/postgres.py#L5818)
+[backend/app/models/postgres.py:5821](../../backend/app/models/postgres.py#L5821)
One replayed item of a candidate evaluation run (W16 AGT-09, 0231).
@@ -924,7 +925,7 @@ Constraints and indexes:
## ai_eval_reviewer_quality
-[backend/app/models/postgres.py:5961](../../backend/app/models/postgres.py#L5961)
+[backend/app/models/postgres.py:5964](../../backend/app/models/postgres.py#L5964)
A G3 reviewer-quality observation batch or scheduled 30-day rollup.
@@ -969,7 +970,7 @@ Constraints and indexes:
## ai_eval_runs
-[backend/app/models/postgres.py:5751](../../backend/app/models/postgres.py#L5751)
+[backend/app/models/postgres.py:5754](../../backend/app/models/postgres.py#L5754)
Record of running an evaluation dataset against a model version.
@@ -1020,7 +1021,7 @@ Constraints and indexes:
## ai_eval_shadow_pairs
-[backend/app/models/postgres.py:5931](../../backend/app/models/postgres.py#L5931)
+[backend/app/models/postgres.py:5934](../../backend/app/models/postgres.py#L5934)
A bounded live tier pair awaiting a human or golden-input label.
@@ -1055,7 +1056,7 @@ Constraints and indexes:
## ai_feedback
-[backend/app/models/postgres.py:2827](../../backend/app/models/postgres.py#L2827)
+[backend/app/models/postgres.py:2830](../../backend/app/models/postgres.py#L2830)
Human feedback on AI triage results — the primary training signal.
@@ -1096,7 +1097,7 @@ Constraints and indexes:
## api_keys
-[backend/app/models/postgres.py:4572](../../backend/app/models/postgres.py#L4572)
+[backend/app/models/postgres.py:4575](../../backend/app/models/postgres.py#L4575)
Scoped personal access token (PAT) for CI/CD and API access.
@@ -1132,7 +1133,7 @@ Constraints and indexes:
## app_settings
-[backend/app/models/postgres.py:4499](../../backend/app/models/postgres.py#L4499)
+[backend/app/models/postgres.py:4502](../../backend/app/models/postgres.py#L4502)
Key-value store for application-level configuration (e.g. SMTP settings).
@@ -1153,7 +1154,7 @@ Constraints and indexes:
## canonical_test_cases
-[backend/app/models/postgres.py:1240](../../backend/app/models/postgres.py#L1240)
+[backend/app/models/postgres.py:1242](../../backend/app/models/postgres.py#L1242)
Project-scoped test case identity.
@@ -1219,7 +1220,7 @@ attachments: Mapped[list['TestAttachment']] = relationship('TestAttachment', bac
## chat_messages
-[backend/app/models/postgres.py:2803](../../backend/app/models/postgres.py#L2803)
+[backend/app/models/postgres.py:2806](../../backend/app/models/postgres.py#L2806)
A single message in a ChatSession.
@@ -1246,7 +1247,7 @@ session: Mapped['ChatSession'] = relationship('ChatSession', back_populates='mes
## chat_sessions
-[backend/app/models/postgres.py:2781](../../backend/app/models/postgres.py#L2781)
+[backend/app/models/postgres.py:2784](../../backend/app/models/postgres.py#L2784)
A conversation session between a user and the Conversation Agent.
@@ -1279,7 +1280,7 @@ messages: Mapped[list['ChatMessage']] = relationship('ChatMessage', back_populat
## classification_hints
-[backend/app/models/postgres.py:5392](../../backend/app/models/postgres.py#L5392)
+[backend/app/models/postgres.py:5395](../../backend/app/models/postgres.py#L5395)
A QA lead's rule: " contains -> " for one project.
@@ -1313,7 +1314,7 @@ Constraints and indexes:
## compliance_packs
-[backend/app/models/postgres.py:7501](../../backend/app/models/postgres.py#L7501)
+[backend/app/models/postgres.py:7504](../../backend/app/models/postgres.py#L7504)
Generated compliance export pack (ZIP) for a release decision.
@@ -1347,7 +1348,7 @@ Constraints and indexes:
## compliance_signing_keys
-[backend/app/models/postgres.py:7578](../../backend/app/models/postgres.py#L7578)
+[backend/app/models/postgres.py:7581](../../backend/app/models/postgres.py#L7581)
The deployment's Ed25519 compliance-pack signing keys (migration 0225, W11 REL-11, D14).
@@ -1377,7 +1378,7 @@ Constraints and indexes:
## coverage_snapshots
-[backend/app/models/postgres.py:1832](../../backend/app/models/postgres.py#L1832)
+[backend/app/models/postgres.py:1834](../../backend/app/models/postgres.py#L1834)
One coverage snapshot a project a UTC day (W08 TRND-07, migration 0217).
@@ -1413,7 +1414,7 @@ Constraints and indexes:
## decision_report_eval_cycles
-[backend/app/models/postgres.py:6023](../../backend/app/models/postgres.py#L6023)
+[backend/app/models/postgres.py:6026](../../backend/app/models/postgres.py#L6026)
Durable evidence for a report-level evaluation corpus cycle.
@@ -1465,7 +1466,7 @@ Constraints and indexes:
## decision_report_feedback
-[backend/app/models/postgres.py:2867](../../backend/app/models/postgres.py#L2867)
+[backend/app/models/postgres.py:2870](../../backend/app/models/postgres.py#L2870)
Structured human feedback bound to one immutable DecisionReport version.
@@ -1505,7 +1506,7 @@ Constraints and indexes:
## decision_report_supersession_requests
-[backend/app/models/postgres.py:6085](../../backend/app/models/postgres.py#L6085)
+[backend/app/models/postgres.py:6088](../../backend/app/models/postgres.py#L6088)
Durable, idempotent request to publish a child-enriched report version.
@@ -1544,7 +1545,7 @@ Constraints and indexes:
## deep_findings
-[backend/app/models/postgres.py:3009](../../backend/app/models/postgres.py#L3009)
+[backend/app/models/postgres.py:3012](../../backend/app/models/postgres.py#L3012)
Deep investigation result per failure cluster.
@@ -1582,7 +1583,7 @@ Constraints and indexes:
## defect_candidates
-[backend/app/models/postgres.py:1803](../../backend/app/models/postgres.py#L1803)
+[backend/app/models/postgres.py:1805](../../backend/app/models/postgres.py#L1805)
Staging area for defect candidates before promotion to full defects.
@@ -1618,7 +1619,7 @@ Constraints and indexes:
## defects
-[backend/app/models/postgres.py:1672](../../backend/app/models/postgres.py#L1672)
+[backend/app/models/postgres.py:1674](../../backend/app/models/postgres.py#L1674)
Defect records linked to test cases or failure clusters.
@@ -1683,7 +1684,7 @@ approver: Mapped[Optional['User']] = relationship('User', foreign_keys=[approved
## deletion_jobs
-[backend/app/models/postgres.py:7880](../../backend/app/models/postgres.py#L7880)
+[backend/app/models/postgres.py:7883](../../backend/app/models/postgres.py#L7883)
One record of a deletion actually happening (migration 0147, S2b).
@@ -1762,7 +1763,7 @@ Constraints and indexes:
## digest_subscriptions
-[backend/app/models/postgres.py:5678](../../backend/app/models/postgres.py#L5678)
+[backend/app/models/postgres.py:5681](../../backend/app/models/postgres.py#L5681)
User subscription to a scheduled or event-driven report delivery.
@@ -1806,7 +1807,7 @@ Constraints and indexes:
## dismissed_duplicate_pairs
-[backend/app/models/postgres.py:3465](../../backend/app/models/postgres.py#L3465)
+[backend/app/models/postgres.py:3468](../../backend/app/models/postgres.py#L3468)
Suppression record so a dismissed duplicate pair stays dismissed (Phase 4).
@@ -1837,7 +1838,7 @@ Constraints and indexes:
## drop_folder_builds
-[backend/app/models/postgres.py:8703](../../backend/app/models/postgres.py#L8703)
+[backend/app/models/postgres.py:8706](../../backend/app/models/postgres.py#L8706)
One build folder ``/runs//`` seen by the drop-folder watcher (W34 STRAT-13; migration 0254).
@@ -1874,7 +1875,7 @@ Constraints and indexes:
## duplicate_test_case_candidates
-[backend/app/models/postgres.py:3422](../../backend/app/models/postgres.py#L3422)
+[backend/app/models/postgres.py:3425](../../backend/app/models/postgres.py#L3425)
One detected near-duplicate PAIR of authored ManagedTestCases (Phase 4).
@@ -1918,7 +1919,7 @@ Constraints and indexes:
## evidence_artifacts
-[backend/app/models/postgres.py:4625](../../backend/app/models/postgres.py#L4625)
+[backend/app/models/postgres.py:4628](../../backend/app/models/postgres.py#L4628)
Tenant-bound immutable evidence captured from an executed tool.
@@ -1966,7 +1967,7 @@ Constraints and indexes:
## failure_attribution
-[backend/app/models/postgres.py:6908](../../backend/app/models/postgres.py#L6908)
+[backend/app/models/postgres.py:6911](../../backend/app/models/postgres.py#L6911)
@@ -1995,7 +1996,7 @@ Constraints and indexes:
## failure_clusters
-[backend/app/models/postgres.py:2933](../../backend/app/models/postgres.py#L2933)
+[backend/app/models/postgres.py:2936](../../backend/app/models/postgres.py#L2936)
Semantic cluster of failures grouped by root-cause similarity.
@@ -2023,7 +2024,7 @@ Constraints and indexes:
## feature_flags
-[backend/app/models/postgres.py:6716](../../backend/app/models/postgres.py#L6716)
+[backend/app/models/postgres.py:6719](../../backend/app/models/postgres.py#L6719)
Named capability toggle gated by project, role, and rollout percent.
@@ -2048,7 +2049,7 @@ Constraints and indexes:
## federated_identities
-[backend/app/models/postgres.py:5121](../../backend/app/models/postgres.py#L5121)
+[backend/app/models/postgres.py:5124](../../backend/app/models/postgres.py#L5124)
Links an external IdP subject to a local User.
@@ -2075,7 +2076,7 @@ Constraints and indexes:
## fix_attempts
-[backend/app/models/postgres.py:2527](../../backend/app/models/postgres.py#L2527)
+[backend/app/models/postgres.py:2529](../../backend/app/models/postgres.py#L2529)
One (fixer run, candidate test, attempt) of the Fixer.
@@ -2131,7 +2132,7 @@ Constraints and indexes:
## flaky_classifier_calibration
-[backend/app/models/postgres.py:7082](../../backend/app/models/postgres.py#L7082)
+[backend/app/models/postgres.py:7085](../../backend/app/models/postgres.py#L7085)
@@ -2156,7 +2157,7 @@ Constraints and indexes:
## flaky_coach_results
-[backend/app/models/postgres.py:4953](../../backend/app/models/postgres.py#L4953)
+[backend/app/models/postgres.py:4956](../../backend/app/models/postgres.py#L4956)
Project-level flaky test coaching results with quarantine recommendations.
@@ -2192,7 +2193,7 @@ Constraints and indexes:
## flaky_detection_state
-[backend/app/models/postgres.py:7118](../../backend/app/models/postgres.py#L7118)
+[backend/app/models/postgres.py:7121](../../backend/app/models/postgres.py#L7121)
@@ -2222,7 +2223,7 @@ Constraints and indexes:
## flaky_quarantine_requests
-[backend/app/models/postgres.py:7621](../../backend/app/models/postgres.py#L7621)
+[backend/app/models/postgres.py:7624](../../backend/app/models/postgres.py#L7624)
Workflow record for proposing, approving, and enforcing quarantine
of a flaky test.
@@ -2286,7 +2287,7 @@ Constraints and indexes:
## flaky_score
-[backend/app/models/postgres.py:7048](../../backend/app/models/postgres.py#L7048)
+[backend/app/models/postgres.py:7051](../../backend/app/models/postgres.py#L7051)
@@ -2313,7 +2314,7 @@ Constraints and indexes:
## generation_batches
-[backend/app/models/postgres.py:3730](../../backend/app/models/postgres.py#L3730)
+[backend/app/models/postgres.py:3733](../../backend/app/models/postgres.py#L3733)
One row per AI test-case generation request (grounded or raw).
@@ -2347,7 +2348,7 @@ Constraints and indexes:
## generation_case_sources
-[backend/app/models/postgres.py:3761](../../backend/app/models/postgres.py#L3761)
+[backend/app/models/postgres.py:3764](../../backend/app/models/postgres.py#L3764)
Maps a generated ManagedTestCase to the KnowledgeChunks cited for it.
@@ -2380,7 +2381,7 @@ Constraints and indexes:
## github_integrations
-[backend/app/models/postgres.py:7353](../../backend/app/models/postgres.py#L7353)
+[backend/app/models/postgres.py:7356](../../backend/app/models/postgres.py#L7356)
Per-project GitHub Checks API integration config.
@@ -2413,7 +2414,7 @@ Constraints and indexes:
## gitlab_integrations
-[backend/app/models/postgres.py:7418](../../backend/app/models/postgres.py#L7418)
+[backend/app/models/postgres.py:7421](../../backend/app/models/postgres.py#L7421)
Per-project GitLab integration config (PMF Epic 3 US-3.1).
@@ -2450,7 +2451,7 @@ Constraints and indexes:
## identity_events
-[backend/app/models/postgres.py:5193](../../backend/app/models/postgres.py#L5193)
+[backend/app/models/postgres.py:5196](../../backend/app/models/postgres.py#L5196)
Append-only audit trail for SSO, SCIM, and identity lifecycle events.
@@ -2500,7 +2501,7 @@ Constraints and indexes:
## insight_detector_states
-[backend/app/models/postgres.py:1985](../../backend/app/models/postgres.py#L1985)
+[backend/app/models/postgres.py:1987](../../backend/app/models/postgres.py#L1987)
The last evaluation of each detector for each project (W23a FAIL-11, migration 0243).
@@ -2526,7 +2527,7 @@ Constraints and indexes:
## instance_retention_policy
-[backend/app/models/postgres.py:8463](../../backend/app/models/postgres.py#L8463)
+[backend/app/models/postgres.py:8466](../../backend/app/models/postgres.py#L8466)
The instance-wide retention defaults (W22b ACT-06, migration 0242).
@@ -2567,7 +2568,7 @@ Constraints and indexes:
## integration_health_checks
-[backend/app/models/postgres.py:4771](../../backend/app/models/postgres.py#L4771)
+[backend/app/models/postgres.py:4774](../../backend/app/models/postgres.py#L4774)
Integration health status: the latest snapshot per (provider, scope).
@@ -2592,7 +2593,7 @@ Constraints and indexes:
## integration_probe_results
-[backend/app/models/postgres.py:4790](../../backend/app/models/postgres.py#L4790)
+[backend/app/models/postgres.py:4793](../../backend/app/models/postgres.py#L4793)
Historical record of each integration health probe (OPS-01).
@@ -2616,7 +2617,7 @@ Constraints and indexes:
## knowledge_chunks
-[backend/app/models/postgres.py:3700](../../backend/app/models/postgres.py#L3700)
+[backend/app/models/postgres.py:3703](../../backend/app/models/postgres.py#L3703)
PostgreSQL metadata for each chunk stored in ChromaDB knowledge_chunks collection.
@@ -2647,7 +2648,7 @@ Constraints and indexes:
## knowledge_sources
-[backend/app/models/postgres.py:3639](../../backend/app/models/postgres.py#L3639)
+[backend/app/models/postgres.py:3642](../../backend/app/models/postgres.py#L3642)
Registry of external knowledge sources attached to a project for RAG-grounded test generation.
@@ -2682,7 +2683,7 @@ Constraints and indexes:
## knowledge_sync_events
-[backend/app/models/postgres.py:3674](../../backend/app/models/postgres.py#L3674)
+[backend/app/models/postgres.py:3677](../../backend/app/models/postgres.py#L3677)
Audit log for every sync attempt on a KnowledgeSource.
@@ -2786,7 +2787,7 @@ Constraints and indexes:
## live_sessions
-[backend/app/models/postgres.py:3808](../../backend/app/models/postgres.py#L3808)
+[backend/app/models/postgres.py:3811](../../backend/app/models/postgres.py#L3811)
Tracks an active live test execution session from a client machine.
@@ -2833,7 +2834,7 @@ Constraints and indexes:
## managed_test_cases
-[backend/app/models/postgres.py:3140](../../backend/app/models/postgres.py#L3140)
+[backend/app/models/postgres.py:3143](../../backend/app/models/postgres.py#L3143)
Manually authored or AI-generated test case with full lifecycle management.
@@ -2948,7 +2949,7 @@ Constraints and indexes:
## model_versions
-[backend/app/models/postgres.py:2896](../../backend/app/models/postgres.py#L2896)
+[backend/app/models/postgres.py:2899](../../backend/app/models/postgres.py#L2899)
Registry of fine-tuned model versions per training track.
@@ -2981,7 +2982,7 @@ Constraints and indexes:
## nightly_job_observations
-[backend/app/models/postgres.py:6702](../../backend/app/models/postgres.py#L6702)
+[backend/app/models/postgres.py:6705](../../backend/app/models/postgres.py#L6705)
Bounded operational state shared by the scheduled workers and API.
@@ -3001,7 +3002,7 @@ Constraints and indexes:
## notification_logs
-[backend/app/models/postgres.py:3076](../../backend/app/models/postgres.py#L3076)
+[backend/app/models/postgres.py:3079](../../backend/app/models/postgres.py#L3079)
Audit trail for every dispatched notification.
@@ -3046,7 +3047,7 @@ Constraints and indexes:
## notification_preferences
-[backend/app/models/postgres.py:2139](../../backend/app/models/postgres.py#L2139)
+[backend/app/models/postgres.py:2141](../../backend/app/models/postgres.py#L2141)
Per-user, per-channel notification configuration.
@@ -3074,7 +3075,7 @@ Constraints and indexes:
## notification_test_states
-[backend/app/models/postgres.py:2167](../../backend/app/models/postgres.py#L2167)
+[backend/app/models/postgres.py:2169](../../backend/app/models/postgres.py#L2169)
Per-(project, test_fingerprint) rolling state for transition-based
notifications (PMF US-7.1).
@@ -3110,7 +3111,7 @@ Constraints and indexes:
## notification_transition_policies
-[backend/app/models/postgres.py:2213](../../backend/app/models/postgres.py#L2213)
+[backend/app/models/postgres.py:2215](../../backend/app/models/postgres.py#L2215)
Per-project policy for transition-based notifications (PMF US-7.1).
@@ -3139,7 +3140,7 @@ Constraints and indexes:
## password_reset_tokens
-[backend/app/models/postgres.py:4910](../../backend/app/models/postgres.py#L4910)
+[backend/app/models/postgres.py:4913](../../backend/app/models/postgres.py#L4913)
A single-use password-reset link (W17b ADM-02, migration 0233). Hash only.
@@ -3167,7 +3168,7 @@ Constraints and indexes:
## perf_baselines
-[backend/app/models/postgres.py:7168](../../backend/app/models/postgres.py#L7168)
+[backend/app/models/postgres.py:7171](../../backend/app/models/postgres.py#L7171)
Per-test running duration statistics.
@@ -3197,7 +3198,7 @@ Constraints and indexes:
## pipeline_event_outbox
-[backend/app/models/postgres.py:2662](../../backend/app/models/postgres.py#L2662)
+[backend/app/models/postgres.py:2665](../../backend/app/models/postgres.py#L2665)
Project-scoped event intent awaiting idempotent Mongo materialization.
@@ -3239,7 +3240,7 @@ Constraints and indexes:
## product_usage_events
-[backend/app/models/postgres.py:4827](../../backend/app/models/postgres.py#L4827)
+[backend/app/models/postgres.py:4830](../../backend/app/models/postgres.py#L4830)
Tracks product adoption events for analytics.
@@ -3263,7 +3264,7 @@ Constraints and indexes:
## project_activity_events
-[backend/app/models/postgres.py:8554](../../backend/app/models/postgres.py#L8554)
+[backend/app/models/postgres.py:8557](../../backend/app/models/postgres.py#L8557)
Append-only, project-scoped product feed of everything that happens.
@@ -3341,7 +3342,7 @@ Constraints and indexes:
## project_data_jobs
-[backend/app/models/postgres.py:8005](../../backend/app/models/postgres.py#L8005)
+[backend/app/models/postgres.py:8008](../../backend/app/models/postgres.py#L8008)
One project export or import (W24 ADM-05 phase 1: settings + catalog; migration 0247).
@@ -3400,7 +3401,7 @@ Constraints and indexes:
## project_insights
-[backend/app/models/postgres.py:1910](../../backend/app/models/postgres.py#L1910)
+[backend/app/models/postgres.py:1912](../../backend/app/models/postgres.py#L1912)
One EPISODE of one detector firing on one subject (W23a FAIL-11, migration 0243).
@@ -3452,7 +3453,7 @@ Constraints and indexes:
## project_llm_quota
-[backend/app/models/postgres.py:6785](../../backend/app/models/postgres.py#L6785)
+[backend/app/models/postgres.py:6788](../../backend/app/models/postgres.py#L6788)
Per-project LLM spend config used by the usage-based billing gate.
@@ -3480,7 +3481,7 @@ Constraints and indexes:
## project_llm_usage
-[backend/app/models/postgres.py:8514](../../backend/app/models/postgres.py#L8514)
+[backend/app/models/postgres.py:8517](../../backend/app/models/postgres.py#L8517)
Running per-period LLM cost meter for a project.
@@ -3511,7 +3512,7 @@ Constraints and indexes:
## project_members
-[backend/app/models/postgres.py:4556](../../backend/app/models/postgres.py#L4556)
+[backend/app/models/postgres.py:4559](../../backend/app/models/postgres.py#L4559)
Per-project role assignment for a user.
@@ -3533,7 +3534,7 @@ Constraints and indexes:
## project_retention_policies
-[backend/app/models/postgres.py:8362](../../backend/app/models/postgres.py#L8362)
+[backend/app/models/postgres.py:8365](../../backend/app/models/postgres.py#L8365)
Per-project data retention policy (PMF US-11.4, migration 0113).
@@ -3612,7 +3613,7 @@ Constraints and indexes:
## project_workflow_defaults
-[backend/app/models/postgres.py:6568](../../backend/app/models/postgres.py#L6568)
+[backend/app/models/postgres.py:6571](../../backend/app/models/postgres.py#L6571)
A project's default workflow for one base (W14 AGT-08, migration 0230).
@@ -3695,7 +3696,7 @@ canonical_test_cases: Mapped[list['CanonicalTestCase']] = relationship('Canonica
## quarantine_lifecycle_policies
-[backend/app/models/postgres.py:7757](../../backend/app/models/postgres.py#L7757)
+[backend/app/models/postgres.py:7760](../../backend/app/models/postgres.py#L7760)
Per-project quarantine lifecycle configuration (PMF US-5.4/5.5/5.6).
@@ -3727,7 +3728,7 @@ Constraints and indexes:
## refresh_token_records
-[backend/app/models/postgres.py:5318](../../backend/app/models/postgres.py#L5318)
+[backend/app/models/postgres.py:5321](../../backend/app/models/postgres.py#L5321)
Server-side record of issued refresh tokens for rotation and replay detection.
@@ -3757,7 +3758,7 @@ Constraints and indexes:
## release_attribution_rules
-[backend/app/models/postgres.py:4335](../../backend/app/models/postgres.py#L4335)
+[backend/app/models/postgres.py:4338](../../backend/app/models/postgres.py#L4338)
Per-project rule mapping run metadata to a release (migration 0154).
@@ -3789,7 +3790,7 @@ Constraints and indexes:
## release_decisions
-[backend/app/models/postgres.py:3042](../../backend/app/models/postgres.py#L3042)
+[backend/app/models/postgres.py:3045](../../backend/app/models/postgres.py#L3045)
Release gate decision produced by ReleaseRiskAgent.
@@ -3829,7 +3830,7 @@ Constraints and indexes:
## release_gate_decisions
-[backend/app/models/postgres.py:5500](../../backend/app/models/postgres.py#L5500)
+[backend/app/models/postgres.py:5503](../../backend/app/models/postgres.py#L5503)
A go/no-go verdict for a RELEASE, not for a run (migration 0156).
@@ -3902,7 +3903,7 @@ Constraints and indexes:
## release_gate_policies
-[backend/app/models/postgres.py:5239](../../backend/app/models/postgres.py#L5239)
+[backend/app/models/postgres.py:5242](../../backend/app/models/postgres.py#L5242)
Versioned release gate policy — per-project or system-wide default.
@@ -3936,7 +3937,7 @@ Constraints and indexes:
## release_outcomes
-[backend/app/models/postgres.py:4285](../../backend/app/models/postgres.py#L4285)
+[backend/app/models/postgres.py:4288](../../backend/app/models/postgres.py#L4288)
A human-marked production incident or rollback for a release (E9.9).
@@ -3963,7 +3964,7 @@ Constraints and indexes:
## release_phases
-[backend/app/models/postgres.py:4381](../../backend/app/models/postgres.py#L4381)
+[backend/app/models/postgres.py:4384](../../backend/app/models/postgres.py#L4384)
A phase / milestone within a Release lifecycle.
@@ -3999,7 +4000,7 @@ release: Mapped['Release'] = relationship('Release', back_populates='phases')
## release_test_run_links
-[backend/app/models/postgres.py:4416](../../backend/app/models/postgres.py#L4416)
+[backend/app/models/postgres.py:4419](../../backend/app/models/postgres.py#L4419)
Links a test run to a release for metrics aggregation.
@@ -4035,7 +4036,7 @@ release: Mapped['Release'] = relationship('Release', back_populates='test_run_li
## releases
-[backend/app/models/postgres.py:4086](../../backend/app/models/postgres.py#L4086)
+[backend/app/models/postgres.py:4089](../../backend/app/models/postgres.py#L4089)
A software release tracked through the QA lifecycle.
@@ -4092,7 +4093,7 @@ test_run_links: Mapped[list['ReleaseTestRunLink']] = relationship('ReleaseTestRu
## report_exports
-[backend/app/models/postgres.py:8311](../../backend/app/models/postgres.py#L8311)
+[backend/app/models/postgres.py:8314](../../backend/app/models/postgres.py#L8314)
VIZ-607: one background export of a report (migration 0194).
@@ -4133,7 +4134,7 @@ Constraints and indexes:
## report_share_links
-[backend/app/models/postgres.py:5290](../../backend/app/models/postgres.py#L5290)
+[backend/app/models/postgres.py:5293](../../backend/app/models/postgres.py#L5293)
Time-limited share token for run intelligence reports.
@@ -4169,7 +4170,7 @@ Constraints and indexes:
## requirement_coverage
-[backend/app/models/postgres.py:3789](../../backend/app/models/postgres.py#L3789)
+[backend/app/models/postgres.py:3792](../../backend/app/models/postgres.py#L3792)
Tracks which requirements are covered/uncovered by a generation batch.
@@ -4195,7 +4196,7 @@ Constraints and indexes:
## retention_holds
-[backend/app/models/postgres.py:8225](../../backend/app/models/postgres.py#L8225)
+[backend/app/models/postgres.py:8228](../../backend/app/models/postgres.py#L8228)
A retention hold on a project, a release, a run or a compliance pack (W22a ACT-05, migration 0239).
@@ -4251,7 +4252,7 @@ Constraints and indexes:
## review_requests
-[backend/app/models/postgres.py:6263](../../backend/app/models/postgres.py#L6263)
+[backend/app/models/postgres.py:6266](../../backend/app/models/postgres.py#L6266)
One human review for one AI report-producing run (architecture section 8.1).
@@ -4311,7 +4312,7 @@ Constraints and indexes:
## run_baselines
-[backend/app/models/postgres.py:4693](../../backend/app/models/postgres.py#L4693)
+[backend/app/models/postgres.py:4696](../../backend/app/models/postgres.py#L4696)
Records which baseline was selected for a run and why.
@@ -4340,7 +4341,7 @@ Constraints and indexes:
## run_cadence_windows
-[backend/app/models/postgres.py:2097](../../backend/app/models/postgres.py#L2097)
+[backend/app/models/postgres.py:2099](../../backend/app/models/postgres.py#L2099)
What the cadence beat DECIDED for one expected window (W23a TRND-03, migration 0244).
@@ -4376,7 +4377,7 @@ Constraints and indexes:
## run_cadences
-[backend/app/models/postgres.py:2015](../../backend/app/models/postgres.py#L2015)
+[backend/app/models/postgres.py:2017](../../backend/app/models/postgres.py#L2017)
One expected run cadence: "a run of arrives by ]