From 8d8719b5adb62917adf1d1469f3e2d3a26962c0e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Wed, 2 Dec 2026 23:33:47 +0530 Subject: [PATCH 01/47] Every response served from a fallback says so in degraded, and ops.incidents lists current incidents The transports attach the request's degradation notes to every op response over HTTP and MCP, merged after the op's own list and absent when empty; the MCP lean pass keeps them at the top and loom_search adds a Degraded: line to its text. The code-read fallbacks that served a smaller answer silently (review brief, symbol, coverage, search, grep, ask, pr_check legs) now record a note, outside provider health. ops.incidents (viewer, experimental, reached with loom_op) lists the failing readiness checks, providers failing within the window, workers failing 3 or more passes in a row, and the caller's org's SLO classes whose server-side failure share crosses a threshold. Each ClickHouse read is bounded and an unread source is named in degraded. Three settings: ops_incidents_window_minutes, ops_incidents_error_share, ops_incidents_min_requests. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/development/code-generation.md | 2 +- docs/operations/monitoring.md | 21 + docs/reference/configuration.md | 3 + docs/reference/http-api.md | 18 + docs/reference/mcp.md | 4 +- docs/reference/operations.md | 3 +- docs/reference/operations/admin.md | 2 +- docs/reference/operations/agents.md | 2 +- docs/reference/operations/assistant.md | 2 +- docs/reference/operations/audit.md | 2 +- docs/reference/operations/blacklist.md | 2 +- docs/reference/operations/calibration.md | 2 +- docs/reference/operations/code.md | 2 +- docs/reference/operations/collection.md | 2 +- docs/reference/operations/conflicts.md | 2 +- docs/reference/operations/connection.md | 2 +- docs/reference/operations/consolidations.md | 2 +- docs/reference/operations/context.md | 2 +- docs/reference/operations/conversation.md | 2 +- docs/reference/operations/cost.md | 2 +- docs/reference/operations/decision.md | 2 +- docs/reference/operations/erasure.md | 2 +- .../reference/operations/extraction_policy.md | 2 +- docs/reference/operations/facts.md | 2 +- docs/reference/operations/grants.md | 2 +- docs/reference/operations/help.md | 2 +- docs/reference/operations/inbox.md | 2 +- docs/reference/operations/insights.md | 2 +- docs/reference/operations/knowledge.md | 2 +- docs/reference/operations/learnings.md | 2 +- docs/reference/operations/memory.md | 2 +- docs/reference/operations/memory_schema.md | 2 +- docs/reference/operations/mentor.md | 2 +- docs/reference/operations/namespace.md | 2 +- docs/reference/operations/observe.md | 2 +- docs/reference/operations/ops.md | 18 +- docs/reference/operations/org.md | 2 +- docs/reference/operations/policy.md | 2 +- docs/reference/operations/procedure.md | 2 +- docs/reference/operations/profile.md | 2 +- docs/reference/operations/profile_schema.md | 2 +- docs/reference/operations/run.md | 2 +- docs/reference/operations/search.md | 2 +- docs/reference/operations/session.md | 2 +- docs/reference/operations/task.md | 2 +- docs/reference/operations/tracker.md | 2 +- docs/reference/operations/ui.md | 2 +- docs/reference/operations/webhook.md | 2 +- docs/reference/operations/working_memory.md | 2 +- docs/reference/status.md | 4 +- loom.example.yaml | 12 + schemas/loom-settings.schema.json | 20 + scripts/codegen/docs_reference.py | 4 +- scripts/codegen/sdk_go_gen.py | 1 + sdk/go/client.gen.go | 19 + sdk/go/wire/models.gen.go | 380 +++- sdk/python/loom/client.py | 8 + sdk/python/loom/ops.py | 42 + sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 9 +- sdk/rust/src/blocking_operations.rs | 17 + sdk/rust/src/operations.rs | 18 + sdk/rust/src/wire_models.rs | 1554 +++++++++-------- sdk/rust/tests/registry_contracts.rs | 15 + sdk/typescript/src/generated/ops.ts | 23 +- server/code/app/answers.py | 6 + server/code/app/coverage.py | 6 +- server/code/app/enrich.py | 2 + server/code/app/grep.py | 6 +- server/code/app/pr_check.py | 3 + server/code/app/result_lessons.py | 2 + server/code/app/review_brief.py | 5 + server/code/app/search/handler.py | 7 +- server/code/app/search/lexical.py | 2 + server/code/app/search/vector.py | 3 + server/code/app/symbol/coverage.py | 9 +- server/code/app/symbol/dispatch.py | 7 +- server/code/app/symbol/hierarchy.py | 2 + server/code/app/symbol/neighbours.py | 2 + server/code/app/symbol/symbol.py | 7 +- server/identity/domain/read_scope.py | 1 + server/insights/api/models_ops.py | 44 + server/insights/api/ops_ops.py | 20 + server/insights/app/incidents.py | 151 ++ server/insights/store/ops.py | 24 + server/observability/degradations.py | 34 +- server/operations/dashboard.py | 2 + server/operations/reach_manifest.py | 1 + server/settings/catalog.py | 9 + server/transport/arg_check.py | 6 +- server/transport/lean_results.py | 7 +- server/transport/mcp_outcome.py | 13 +- server/workers/status_store.py | 34 + tests/unit/snapshots/settings_defaults.json | 3 + tests/unit/test_code_read_degradations.py | 62 + tests/unit/test_degradations.py | 60 + tests/unit/test_ops_incidents.py | 148 ++ tests/unit/test_sdk_go_codegen.py | 2 +- 97 files changed, 2156 insertions(+), 813 deletions(-) create mode 100644 server/insights/app/incidents.py create mode 100644 tests/unit/test_code_read_degradations.py create mode 100644 tests/unit/test_ops_incidents.py diff --git a/docs/development/code-generation.md b/docs/development/code-generation.md index 41d93b48bea..f44137e4655 100644 --- a/docs/development/code-generation.md +++ b/docs/development/code-generation.md @@ -92,7 +92,7 @@ preserves all three states. `Get` reads a concrete value and `IsNull` tests for explicit null. Open values and unions with different JSON types use `json.RawMessage`. The server validates enum values and applies request defaults. Top-level responses include the HTTP fields `ignored_args`, -`did_you_mean` and `mirrored` when the server sends them. Go skips other +`did_you_mean`, `degraded` and `mirrored` when the server sends them. Go skips other unknown keys when decoding into a struct. The schema hash tracks literal defaults and static factory defaults. Factories diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index d89e6b6fea4..b63c19fcf4b 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -137,6 +137,27 @@ and flags only. | `op_mix` | the recent operation mix in `loom.agent_events` | | `procedure_plane` | `loom.procedure_runs` and the procedure keys recorded on the ledger | +### ops.incidents + +`POST /v1/ops.incidents` (any `viewer`; over MCP through `loom_op`) answers whether Loom +is degraded now, for a client that polls it rather than reading one answer's +[`degraded`](../reference/http-api.md#degraded-answers). `status` is `degraded` when it +lists an incident. Each incident is `{kind, subject, severity, detail, age_s}`, errors +first, at most 20: + +| `kind` | Listed when | Severity | +| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | +| `readiness` | a readiness check of this process fails | error when required, else warn | +| `provider` | a provider's last call failed within `LOOM_OPS_INCIDENTS_WINDOW_MINUTES` (15); a later success clears it | warn | +| `worker` | a worker's last 3 or more passes in `loom.worker_status` failed in a row | warn | +| `requests` | at least `LOOM_OPS_INCIDENTS_ERROR_SHARE` (0.1) of the caller's org's calls of one SLO class failed on the server over the window, counted once the class has `LOOM_OPS_INCIDENTS_MIN_REQUESTS` (20) | error | + +Request counts come from `loom_telemetry.sli_minute`, which trails the calls by about two +minutes, and only for the token's own org: a token for every org reads none. The other +kinds name a check, provider or worker and an error's kind, as `/v1/health` does. Each +ClickHouse read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`; one that fails is named in the +response's `degraded` and the other sources still answer. + ### Smoke test After a deploy, write and read one memory end to end: diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 5b074021843..bb4714415e2 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1713,6 +1713,9 @@ Telemetry, audit, tracing and the ops surface. | `LOOM_OPS_PROCEDURE_PLANE_MIN_PACKS` | `int` | `50` | | Context packs in the `procedure_plane` check's window before "no pack showed a procedure" can warn. | | `LOOM_OPS_PROCEDURE_PLANE_RETENTION_WARN` | `float` | `0.5` | | Success retention (fraction) below which the `procedure_plane` check warns. | | `LOOM_OPS_PROCEDURE_PLANE_MIN_PAIRS` | `int` | `20` | | Pairs the `procedure_plane` check measures success retention over before its warning can fire. | +| `LOOM_OPS_INCIDENTS_WINDOW_MINUTES` | `int` | `15` | | Minutes of history ops.incidents reads: a provider failure seen within them, and the caller's org's request failures over them. | +| `LOOM_OPS_INCIDENTS_ERROR_SHARE` | `float` | `0.1` | | Share (0-1) of the org's requests of one SLO class that failed on the server's side, over the window, at which ops.incidents lists a `requests` incident. | +| `LOOM_OPS_INCIDENTS_MIN_REQUESTS` | `int` | `20` | | Requests of one SLO class in the window before ops.incidents judges its share. | | `LOOM_AUDIT_VERIFIER_ENABLED` | `bool` | `True` | | Periodic re-hash of audit rows; a mismatch writes `audit.tamper_detected`. Per-row detection, not a hash chain (see server/observability/audit.py). | | `LOOM_AUDIT_VERIFIER_INTERVAL_SECONDS` | `int` | `3600` | | Seconds between audit verifier passes (row re-hash and checkpoint sealing). | | `LOOM_AUDIT_CHECKPOINT_WINDOW_SECONDS` | `int` | `3600` | | Length, seconds, of one audit window. Each closed window is sealed as a chained checkpoint once `audit_checkpoint_grace_seconds` old, and the last `audit_checkpoint_verify_windows` are recounted every pass: a short recount is a deletion, which per-row hashes cannot see. | diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 12393c51015..a46e581c83e 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -297,6 +297,24 @@ Operations and fields can change between releases. Nothing keeps a registry of r fields: `ignored_args` is how a client finds out that the server no longer reads something it sends, and the catalogue below is how it checks what the server serves before relying on it. +## Degraded answers + +A response served from a fallback or a partial read names it in `degraded`, a list of +`provider: effect (kind)` entries such as `rerank: input_order_kept (ReadTimeout)` or +`code_index: calls_tests_dropped (DatabaseError)` (`server/observability/degradations.py`). +The transport adds the request's entries to every op's response, over HTTP and MCP, and +leaves the key out when nothing degraded: an answer without `degraded` was served in full. +The HTTP status stays 200. An entry names the error's kind; its text is in the server log. + +- An op whose output declares `degraded` (`memory.set`, `memory.search`, + `memory.set_from_messages`) lists its own entries first; the request's other entries + follow, each once. A request records at most 8. +- Over MCP the trimmed result keeps `degraded` at the top and drops the copies inside its + sections; `loom_search` also ends its text with a `Degraded:` line. +- Whether Loom is degraded now, rather than one answer, is + [`ops.incidents`](./operations/ops.md#opsincidents) + ([incidents](../operations/monitoring.md#opsincidents)). + ## Discovering what a deployment serves Read the catalogue once at start-up rather than probing routes and reading diff --git a/docs/reference/mcp.md b/docs/reference/mcp.md index aabe447cb4d..9e1390f06aa 100644 --- a/docs/reference/mcp.md +++ b/docs/reference/mcp.md @@ -461,7 +461,9 @@ paging and abstain fields. Score components, explanations, retrieval plans and costs, hashes and empty fields are dropped. **Why:** some clients hand `structuredContent` to the model as well as the text block, and the full diagnostic shape costs several thousand tokens for a short answer. -`explain: true` on the call returns the full shape. HTTP, the SDKs and the +`explain: true` on the call returns the full shape. A result served from a fallback or +a partial read keeps `degraded` at the top ([degraded answers](./http-api.md#degraded-answers)). +HTTP, the SDKs and the `assistant` toolset always get the full result (on `assistant`, a `memory.search` without its per-hit score breakdown). diff --git a/docs/reference/operations.md b/docs/reference/operations.md index 3d724eb59e9..22957cd9e8f 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -123,7 +123,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal -379 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). +380 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`, unless it is hidden from MCP; **Audit** marks ops that leave an `audit_log` row. @@ -629,6 +629,7 @@ Fields for every `ops` op: [operations/ops.md](operations/ops.md). | --- | --- | --- | --- | --- | --- | | [`ops.capabilities`](operations/ops.md#opscapabilities) | Identity is optional: a client discovers the surface with whatever token it holds (role check only; no namespace is addressed). | viewer | read | yes | | | [`ops.health`](operations/ops.md#opshealth) | Run the deployment's self-checks (schema contracts, embedding stubs, ClickHouse parts, op mix, procedure plane, workers) and report each as ok, warn or fail. | org_admin | idempotent | no | | +| [`ops.incidents`](operations/ops.md#opsincidents) | Whether Loom is degraded now: failing readiness checks, providers and workers, and the org's calls failing on the server. | viewer | read | no | | | [`ops.projection_failures.list`](operations/ops.md#opsprojection_failureslist) | List recorded projection failures: derived rows (embeddings, graph edges, summaries) a write could not produce. | org_admin | idempotent | no | | | [`ops.projection_failures.resolve`](operations/ops.md#opsprojection_failuresresolve) | Mark projection failures resolved by id without retrying them. | org_admin | idempotent | no | yes | | [`ops.projection_failures.retry`](operations/ops.md#opsprojection_failuresretry) | Retry open projection failures for a namespace, optionally one projection kind. | org_admin | idempotent | no | yes | diff --git a/docs/reference/operations/admin.md b/docs/reference/operations/admin.md index f39b9129b91..0b082b6d998 100644 --- a/docs/reference/operations/admin.md +++ b/docs/reference/operations/admin.md @@ -4,7 +4,7 @@ The exact fields each `admin.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/agents.md b/docs/reference/operations/agents.md index 11cf9820829..7e66b15de1b 100644 --- a/docs/reference/operations/agents.md +++ b/docs/reference/operations/agents.md @@ -4,7 +4,7 @@ The exact fields each `agents.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/assistant.md b/docs/reference/operations/assistant.md index 8776e14406e..3deb2decd9e 100644 --- a/docs/reference/operations/assistant.md +++ b/docs/reference/operations/assistant.md @@ -4,7 +4,7 @@ The exact fields each `assistant.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/audit.md b/docs/reference/operations/audit.md index 3784ae0eead..842480f6a7d 100644 --- a/docs/reference/operations/audit.md +++ b/docs/reference/operations/audit.md @@ -4,7 +4,7 @@ The exact fields each `audit.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/blacklist.md b/docs/reference/operations/blacklist.md index c28103e7bdb..05d589a0c0d 100644 --- a/docs/reference/operations/blacklist.md +++ b/docs/reference/operations/blacklist.md @@ -4,7 +4,7 @@ The exact fields each `blacklist.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/calibration.md b/docs/reference/operations/calibration.md index 12669cd407e..28fbc9737c4 100644 --- a/docs/reference/operations/calibration.md +++ b/docs/reference/operations/calibration.md @@ -4,7 +4,7 @@ The exact fields each `calibration.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index 2bac18f44a3..62a68bf5abf 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -4,7 +4,7 @@ The exact fields each `code.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/collection.md b/docs/reference/operations/collection.md index 78798c8c4fe..0f67ba2daa1 100644 --- a/docs/reference/operations/collection.md +++ b/docs/reference/operations/collection.md @@ -4,7 +4,7 @@ The exact fields each `collection.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/conflicts.md b/docs/reference/operations/conflicts.md index 90a5610443b..bcea6140369 100644 --- a/docs/reference/operations/conflicts.md +++ b/docs/reference/operations/conflicts.md @@ -4,7 +4,7 @@ The exact fields each `conflicts.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/connection.md b/docs/reference/operations/connection.md index d962ba93174..5544c091e74 100644 --- a/docs/reference/operations/connection.md +++ b/docs/reference/operations/connection.md @@ -4,7 +4,7 @@ The exact fields each `connection.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/consolidations.md b/docs/reference/operations/consolidations.md index 027661a2cb6..6f0daf36986 100644 --- a/docs/reference/operations/consolidations.md +++ b/docs/reference/operations/consolidations.md @@ -4,7 +4,7 @@ The exact fields each `consolidations.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/context.md b/docs/reference/operations/context.md index 860b7f8d5ec..a0894765bed 100644 --- a/docs/reference/operations/context.md +++ b/docs/reference/operations/context.md @@ -4,7 +4,7 @@ The exact fields each `context.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/conversation.md b/docs/reference/operations/conversation.md index 11f53adffc4..20525162642 100644 --- a/docs/reference/operations/conversation.md +++ b/docs/reference/operations/conversation.md @@ -4,7 +4,7 @@ The exact fields each `conversation.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/cost.md b/docs/reference/operations/cost.md index f8bcf1fd1ae..53d609b693d 100644 --- a/docs/reference/operations/cost.md +++ b/docs/reference/operations/cost.md @@ -4,7 +4,7 @@ The exact fields each `cost.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/decision.md b/docs/reference/operations/decision.md index 9fbe60affa0..ec7aa90913e 100644 --- a/docs/reference/operations/decision.md +++ b/docs/reference/operations/decision.md @@ -4,7 +4,7 @@ The exact fields each `decision.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/erasure.md b/docs/reference/operations/erasure.md index d7f501212c6..e82baed5fb6 100644 --- a/docs/reference/operations/erasure.md +++ b/docs/reference/operations/erasure.md @@ -4,7 +4,7 @@ The exact fields each `erasure.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/extraction_policy.md b/docs/reference/operations/extraction_policy.md index 28a735779eb..f08a87b50fd 100644 --- a/docs/reference/operations/extraction_policy.md +++ b/docs/reference/operations/extraction_policy.md @@ -4,7 +4,7 @@ The exact fields each `extraction_policy.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/facts.md b/docs/reference/operations/facts.md index eab81778314..f1104f4df83 100644 --- a/docs/reference/operations/facts.md +++ b/docs/reference/operations/facts.md @@ -4,7 +4,7 @@ The exact fields each `facts.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/grants.md b/docs/reference/operations/grants.md index 2f19ca501aa..52365d7121b 100644 --- a/docs/reference/operations/grants.md +++ b/docs/reference/operations/grants.md @@ -4,7 +4,7 @@ The exact fields each `grants.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/help.md b/docs/reference/operations/help.md index 8942b4393f0..82d3ad8904b 100644 --- a/docs/reference/operations/help.md +++ b/docs/reference/operations/help.md @@ -4,7 +4,7 @@ The exact fields each `help.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/inbox.md b/docs/reference/operations/inbox.md index 7a22f85ac9d..9f853b6025f 100644 --- a/docs/reference/operations/inbox.md +++ b/docs/reference/operations/inbox.md @@ -4,7 +4,7 @@ The exact fields each `inbox.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/insights.md b/docs/reference/operations/insights.md index e9bec66357b..f3a0f2c31f0 100644 --- a/docs/reference/operations/insights.md +++ b/docs/reference/operations/insights.md @@ -4,7 +4,7 @@ The exact fields each `insights.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index cd8519353c9..ed625348b32 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -4,7 +4,7 @@ The exact fields each `knowledge.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/learnings.md b/docs/reference/operations/learnings.md index d10b2718ef2..ac43e0a6b24 100644 --- a/docs/reference/operations/learnings.md +++ b/docs/reference/operations/learnings.md @@ -4,7 +4,7 @@ The exact fields each `learnings.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/memory.md b/docs/reference/operations/memory.md index f8ca0cfe6a8..81d89489151 100644 --- a/docs/reference/operations/memory.md +++ b/docs/reference/operations/memory.md @@ -4,7 +4,7 @@ The exact fields each `memory.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/memory_schema.md b/docs/reference/operations/memory_schema.md index 43c50558b9d..79c18525128 100644 --- a/docs/reference/operations/memory_schema.md +++ b/docs/reference/operations/memory_schema.md @@ -4,7 +4,7 @@ The exact fields each `memory_schema.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/mentor.md b/docs/reference/operations/mentor.md index 7893c77086a..09a9522089c 100644 --- a/docs/reference/operations/mentor.md +++ b/docs/reference/operations/mentor.md @@ -4,7 +4,7 @@ The exact fields each `mentor.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/namespace.md b/docs/reference/operations/namespace.md index 76f5813b933..83a2ee29ec4 100644 --- a/docs/reference/operations/namespace.md +++ b/docs/reference/operations/namespace.md @@ -4,7 +4,7 @@ The exact fields each `namespace.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/observe.md b/docs/reference/operations/observe.md index 66dcf380ad6..8b52899de1b 100644 --- a/docs/reference/operations/observe.md +++ b/docs/reference/operations/observe.md @@ -4,7 +4,7 @@ The exact fields each `observe.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/ops.md b/docs/reference/operations/ops.md index db4c14ca1f5..af8b24cc62e 100644 --- a/docs/reference/operations/ops.md +++ b/docs/reference/operations/ops.md @@ -4,7 +4,7 @@ The exact fields each `ops.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). @@ -43,6 +43,22 @@ Run the deployment's self-checks (schema contracts, embedding stubs, ClickHouse | `worker_status` | `dict[str, dict[str, Any]]` | Per background worker in this process: last run time, duration, outcome, the last error's kind (`last_error_kind`), consecutive failures and total runs; empty before any worker has run. | | `overall` | `Literal['ok', 'warn', 'fail']` | `fail` when any check failed, else `warn` when any warned, else `ok`. | +## `ops.incidents` + +Whether Loom is degraded now: failing readiness checks, providers and workers, and the org's calls failing on the server. + +`POST /v1/ops.incidents` · MCP `loom_ops_incidents` · role `viewer` · read · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | `''` | The tenant (first element of the identity tuple). | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `status` | `Literal['ok', 'degraded']` | `degraded` when an incident is listed, else `ok`. | +| `incidents` | `list[OpsIncident]` | Errors first, at most 20. | +| `window_minutes` | `int` | Minutes of history a `provider` or `requests` incident reads. | + ## `ops.projection_failures.list` List recorded projection failures: derived rows (embeddings, graph edges, summaries) a write could not produce. diff --git a/docs/reference/operations/org.md b/docs/reference/operations/org.md index 843f6943137..2b8fa390aa9 100644 --- a/docs/reference/operations/org.md +++ b/docs/reference/operations/org.md @@ -4,7 +4,7 @@ The exact fields each `org.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/policy.md b/docs/reference/operations/policy.md index edfc5df84d9..b73829d2631 100644 --- a/docs/reference/operations/policy.md +++ b/docs/reference/operations/policy.md @@ -4,7 +4,7 @@ The exact fields each `policy.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/procedure.md b/docs/reference/operations/procedure.md index 3e8a2f47627..8897781fc97 100644 --- a/docs/reference/operations/procedure.md +++ b/docs/reference/operations/procedure.md @@ -4,7 +4,7 @@ The exact fields each `procedure.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/profile.md b/docs/reference/operations/profile.md index 899a041e7ec..18a1aecef87 100644 --- a/docs/reference/operations/profile.md +++ b/docs/reference/operations/profile.md @@ -4,7 +4,7 @@ The exact fields each `profile.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/profile_schema.md b/docs/reference/operations/profile_schema.md index 8733b163e29..04e2f38586f 100644 --- a/docs/reference/operations/profile_schema.md +++ b/docs/reference/operations/profile_schema.md @@ -4,7 +4,7 @@ The exact fields each `profile_schema.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/run.md b/docs/reference/operations/run.md index 4f9606262a4..e88a3d18212 100644 --- a/docs/reference/operations/run.md +++ b/docs/reference/operations/run.md @@ -4,7 +4,7 @@ The exact fields each `run.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/search.md b/docs/reference/operations/search.md index 01c039e5d2c..7aecb4f94bf 100644 --- a/docs/reference/operations/search.md +++ b/docs/reference/operations/search.md @@ -4,7 +4,7 @@ The exact fields each `search.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/session.md b/docs/reference/operations/session.md index 4aa5bbd5b6d..0db59aea0fc 100644 --- a/docs/reference/operations/session.md +++ b/docs/reference/operations/session.md @@ -4,7 +4,7 @@ The exact fields each `session.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/task.md b/docs/reference/operations/task.md index 19d75b169aa..e2b6710965e 100644 --- a/docs/reference/operations/task.md +++ b/docs/reference/operations/task.md @@ -4,7 +4,7 @@ The exact fields each `task.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/tracker.md b/docs/reference/operations/tracker.md index ec919ad44e2..bd7daaf14a1 100644 --- a/docs/reference/operations/tracker.md +++ b/docs/reference/operations/tracker.md @@ -4,7 +4,7 @@ The exact fields each `tracker.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/ui.md b/docs/reference/operations/ui.md index ffd7cacce58..a0e0825da34 100644 --- a/docs/reference/operations/ui.md +++ b/docs/reference/operations/ui.md @@ -4,7 +4,7 @@ The exact fields each `ui.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/webhook.md b/docs/reference/operations/webhook.md index 8fe85868279..e1878a79f36 100644 --- a/docs/reference/operations/webhook.md +++ b/docs/reference/operations/webhook.md @@ -4,7 +4,7 @@ The exact fields each `webhook.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/operations/working_memory.md b/docs/reference/operations/working_memory.md index 1c42739885e..c4c9b76c146 100644 --- a/docs/reference/operations/working_memory.md +++ b/docs/reference/operations/working_memory.md @@ -4,7 +4,7 @@ The exact fields each `working_memory.*` operation takes and returns. -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. +Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`, and a response served from a fallback or a partial read names it in `degraded` ([degraded answers](../http-api.md#degraded-answers)). diff --git a/docs/reference/status.md b/docs/reference/status.md index b2167b58d5b..b4782bc31e7 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -379 operations, 265 of them experimental. +380 operations, 266 of them experimental. | Group | Stable | Experimental | | --- | --- | --- | @@ -58,7 +58,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). | `mentor` | 1 | [`mentor.guide`](operations/mentor.md#mentorguide) | | `namespace` | 9 | [`namespace.cancel_request`](operations/namespace.md#namespacecancel_request), [`namespace.delete`](operations/namespace.md#namespacedelete), [`namespace.guide_get`](operations/namespace.md#namespaceguide_get), [`namespace.guide_history`](operations/namespace.md#namespaceguide_history), [`namespace.guide_set`](operations/namespace.md#namespaceguide_set), [`namespace.inventory`](operations/namespace.md#namespaceinventory), [`namespace.join`](operations/namespace.md#namespacejoin), [`namespace.leave`](operations/namespace.md#namespaceleave), [`namespace.list`](operations/namespace.md#namespacelist), [`namespace.list_categories`](operations/namespace.md#namespacelist_categories), [`namespace.list_ontology`](operations/namespace.md#namespacelist_ontology), [`namespace.mark_seen`](operations/namespace.md#namespacemark_seen), [`namespace.register_category`](operations/namespace.md#namespaceregister_category), [`namespace.restore`](operations/namespace.md#namespacerestore), [`namespace.rollback`](operations/namespace.md#namespacerollback), [`namespace.search_categories`](operations/namespace.md#namespacesearch_categories), [`namespace.snapshot`](operations/namespace.md#namespacesnapshot), [`namespace.tune`](operations/namespace.md#namespacetune) | | `observe` | 2 | | -| `ops` | 2 | [`ops.projection_failures.list`](operations/ops.md#opsprojection_failureslist), [`ops.projection_failures.resolve`](operations/ops.md#opsprojection_failuresresolve), [`ops.projection_failures.retry`](operations/ops.md#opsprojection_failuresretry) | +| `ops` | 2 | [`ops.incidents`](operations/ops.md#opsincidents), [`ops.projection_failures.list`](operations/ops.md#opsprojection_failureslist), [`ops.projection_failures.resolve`](operations/ops.md#opsprojection_failuresresolve), [`ops.projection_failures.retry`](operations/ops.md#opsprojection_failuresretry) | | `org` | 0 | [`org.model_calls`](operations/org.md#orgmodel_calls), [`org.set_model_calls`](operations/org.md#orgset_model_calls) | | `policy` | 2 | [`policy.decisions`](operations/policy.md#policydecisions), [`policy.delete`](operations/policy.md#policydelete), [`policy.set`](operations/policy.md#policyset) | | `procedure` | 2 | [`procedure.evolve`](operations/procedure.md#procedureevolve), [`procedure.fork`](operations/procedure.md#procedurefork), [`procedure.list`](operations/procedure.md#procedurelist), [`procedure.locate`](operations/procedure.md#procedurelocate), [`procedure.record_run`](operations/procedure.md#procedurerecord_run), [`procedure.revise`](operations/procedure.md#procedurerevise) | diff --git a/loom.example.yaml b/loom.example.yaml index 05c46a64a51..9d46ecabd47 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -5045,6 +5045,18 @@ settings: # can fire. [restart] # ops_procedure_plane_min_pairs: 20 + # Minutes of history ops.incidents reads: a provider failure seen within them, and the + # caller's org's request failures over them. [restart] + # ops_incidents_window_minutes: 15 + + # Share (0-1) of the org's requests of one SLO class that failed on the server's side, + # over the window, at which ops.incidents lists a `requests` incident. [restart] + # ops_incidents_error_share: 0.1 + + # Requests of one SLO class in the window before ops.incidents judges its share. + # [restart] + # ops_incidents_min_requests: 20 + # Periodic re-hash of audit rows; a mismatch writes `audit.tamper_detected`. Per-row # detection, not a hash chain (see server/observability/audit.py). [restart] # audit_verifier_enabled: true diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 594fd54f137..3cab34bdb7c 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6042,6 +6042,26 @@ "type": "string", "description": "OpenAI's API root, for the Responses API (/responses) and embeddings: point it at an OpenAI-compatible inference gateway in front of OpenAI (its /v1 root)." }, + "ops_incidents_error_share": { + "default": 0.1, + "exclusiveMinimum": 0, + "maximum": 1, + "type": "number", + "description": "Share (0-1) of the org's requests of one SLO class that failed on the server's side, over the window, at which ops.incidents lists a `requests` incident." + }, + "ops_incidents_min_requests": { + "default": 20, + "minimum": 1, + "type": "integer", + "description": "Requests of one SLO class in the window before ops.incidents judges its share." + }, + "ops_incidents_window_minutes": { + "default": 15, + "maximum": 1440, + "minimum": 1, + "type": "integer", + "description": "Minutes of history ops.incidents reads: a provider failure seen within them, and the caller's org's request failures over them." + }, "ops_op_mix_min_writes": { "default": 500, "type": "integer", diff --git a/scripts/codegen/docs_reference.py b/scripts/codegen/docs_reference.py index 4039abe2e7d..ba3af91045b 100644 --- a/scripts/codegen/docs_reference.py +++ b/scripts/codegen/docs_reference.py @@ -358,7 +358,9 @@ def render_group(group: str, ops: list[Operation]) -> str: "its namespace and agent; see " "[identities and namespaces](../../concepts/identities-and-namespaces.md). The " "[operations index](../operations.md) explains role, kind and the MCP `all` " - "listing. Unknown input fields are served and named in `ignored_args`.\n", + "listing. Unknown input fields are served and named in `ignored_args`, and a " + "response served from a fallback or a partial read names it in `degraded` " + "([degraded answers](../http-api.md#degraded-answers)).\n", "\n", ] for op in ops: diff --git a/scripts/codegen/sdk_go_gen.py b/scripts/codegen/sdk_go_gen.py index d430b6b22fd..46544b14ba9 100644 --- a/scripts/codegen/sdk_go_gen.py +++ b/scripts/codegen/sdk_go_gen.py @@ -59,6 +59,7 @@ "ignored_args": {"type": "array", "items": {"type": "string"}}, "did_you_mean": {"type": "object", "additionalProperties": {"type": "string"}}, "mirrored": {"type": "boolean"}, + "degraded": {"type": "array", "items": {"type": "string"}}, } _IDENTITY_FIELDS = {"org", "namespace", "agent"} # These namespaces name the object being managed, not the caller's scope. diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index bd3ffc90bf9..567f3bb125f 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -2399,6 +2399,15 @@ type OpsHealthInput = wire.OpsHealthInput // OpsHealthOutput is the response from ops.health. type OpsHealthOutput = wire.OpsHealthOutput +// OpsIncident is a model used by Loom operations. +type OpsIncident = wire.OpsIncident + +// OpsIncidentsInput is the request to ops.incidents. +type OpsIncidentsInput = wire.OpsIncidentsInput + +// OpsIncidentsOutput is the response from ops.incidents. +type OpsIncidentsOutput = wire.OpsIncidentsOutput + // OpsProjectionFailuresListInput is the request to ops.projection_failures.list. type OpsProjectionFailuresListInput = wire.OpsProjectionFailuresListInput @@ -7534,6 +7543,16 @@ func (s OpsService) Health(ctx context.Context, opts ...Option[OpsHealthInput]) return callOperation[OpsHealthOutput](s.client, ctx, "ops.health", in) } +// Incidents calls ops.incidents. +// Use WithInput to supply additional request fields. +func (s OpsService) Incidents(ctx context.Context, opts ...Option[OpsIncidentsInput]) (*OpsIncidentsOutput, error) { + in := applyOptions(opts) + if in.Org == nil && s.client.identity.Org != "" { + in.Org = Ptr(s.client.identity.Org) + } + return callOperation[OpsIncidentsOutput](s.client, ctx, "ops.incidents", in) +} + // ProjectionFailuresList calls ops.projection_failures.list. // Use WithInput to supply additional request fields. func (s OpsService) ProjectionFailuresList(ctx context.Context, opts ...Option[OpsProjectionFailuresListInput]) (*OpsProjectionFailuresListOutput, error) { diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index e6d53211753..01ad00b90da 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: 3eb21f99aa661c271c54339556b012d4b6add7bb8c11ab3178a84662db3b3f7b +// Registry model schema SHA-256: 8233c32bd31d30d3cb64d76f7f02647fddfd0785c00c2448bf18e50e52d3c7ac // Package wire contains the Go requests and responses for Loom operations. package wire @@ -19,6 +19,7 @@ type AdminUsersOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Users []UserSummary `json:"users"` Total int64 `json:"total"` TotalPendingElevations *int64 `json:"total_pending_elevations,omitempty"` @@ -39,6 +40,7 @@ type AgentsConnectedOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []ConnectedAgent `json:"rows"` WindowHours int64 `json:"window_hours"` NewCount Optional[int64] `json:"new_count,omitempty"` @@ -150,6 +152,7 @@ type AssistantAskOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Answer *string `json:"answer,omitempty"` RunID *string `json:"run_id,omitempty"` Model *string `json:"model,omitempty"` @@ -190,6 +193,7 @@ type AuditListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []AuditListRow `json:"rows"` NextCursor Optional[string] `json:"next_cursor,omitempty"` } @@ -249,6 +253,7 @@ type BlacklistAddOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` PatternID string `json:"pattern_id"` CreatedAt string `json:"created_at"` Swept *int64 `json:"swept,omitempty"` @@ -269,6 +274,7 @@ type BlacklistListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []BlacklistRow `json:"rows"` } @@ -285,6 +291,7 @@ type BlacklistRemoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Removed bool `json:"removed"` RemovedAt Optional[string] `json:"removed_at,omitempty"` } @@ -316,6 +323,7 @@ type BlacklistSweepOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` PatternID string `json:"pattern_id"` Matched int64 `json:"matched"` Tombstoned int64 `json:"tombstoned"` @@ -421,6 +429,7 @@ type BudgetStatusOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` UserID Optional[string] `json:"user_id,omitempty"` Spent24HUsd *float64 `json:"spent_24h_usd"` @@ -482,6 +491,7 @@ type CalibrationGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Source string `json:"source"` EmbedderModel *string `json:"embedder_model,omitempty"` NoiseFloor float64 `json:"noise_floor"` @@ -627,6 +637,7 @@ type CodeAskOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Answer *string `json:"answer,omitempty"` Partial *bool `json:"partial,omitempty"` PartialReason *string `json:"partial_reason,omitempty"` @@ -667,6 +678,7 @@ type CodeBackportGapOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` SkippedBranches *[]map[string]string `json:"skipped_branches,omitempty"` Verdict *string `json:"verdict,omitempty"` Causes *[]string `json:"causes,omitempty"` @@ -703,6 +715,7 @@ type CodeBackportGapsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` SkippedBranches *[]map[string]string `json:"skipped_branches,omitempty"` Branch *string `json:"branch,omitempty"` BranchNamespace *string `json:"branch_namespace,omitempty"` @@ -750,6 +763,7 @@ type CodeBisectCandidatesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict *string `json:"verdict,omitempty"` CandidatesFrom *string `json:"candidates_from,omitempty"` Causes *[]string `json:"causes,omitempty"` @@ -812,6 +826,7 @@ type CodeBlameRangeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict *string `json:"verdict,omitempty"` Causes *[]string `json:"causes,omitempty"` Epistemic *string `json:"epistemic,omitempty"` @@ -847,6 +862,7 @@ type CodeCalibrateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` NoiseFloor float64 `json:"noise_floor"` AbstainThreshold float64 `json:"abstain_threshold"` RerankSkipAbove float64 `json:"rerank_skip_above"` @@ -890,6 +906,7 @@ type CodeCallersOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Lessons *[]map[string]json.RawMessage `json:"lessons,omitempty"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` Edges []CodeEdgeWire `json:"edges"` @@ -1006,6 +1023,7 @@ type CodeContextPackOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Lessons *[]map[string]json.RawMessage `json:"lessons,omitempty"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` Context string `json:"context"` @@ -1044,6 +1062,7 @@ type CodeContextPacksOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []CodeContextPackRow `json:"rows"` Total *int64 `json:"total,omitempty"` } @@ -1067,6 +1086,7 @@ type CodeConventionsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` PrNumber *int64 `json:"pr_number,omitempty"` Source *string `json:"source,omitempty"` Title *string `json:"title,omitempty"` @@ -1105,6 +1125,7 @@ type CodeCoverageClaimOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Subject *string `json:"subject,omitempty"` SubjectKind *string `json:"subject_kind,omitempty"` Verdict *string `json:"verdict,omitempty"` @@ -1147,6 +1168,7 @@ type CodeCoverageOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` AsOfCommit *string `json:"as_of_commit,omitempty"` @@ -1178,6 +1200,7 @@ type CodeCoverageUnwatchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Commit string `json:"commit"` Inbox string `json:"inbox"` Removed bool `json:"removed"` @@ -1199,6 +1222,7 @@ type CodeCoverageWatchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` Commit string `json:"commit"` @@ -1296,6 +1320,7 @@ type CodeEnclosingOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Lessons *[]map[string]json.RawMessage `json:"lessons,omitempty"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` Results []map[string]json.RawMessage `json:"results"` @@ -1330,6 +1355,7 @@ type CodeExamplesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Examples []map[string]json.RawMessage `json:"examples"` TraceRunID *string `json:"trace_run_id,omitempty"` } @@ -1352,6 +1378,7 @@ type CodeFilesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Files *[]map[string]json.RawMessage `json:"files,omitempty"` Total *int64 `json:"total,omitempty"` Truncated *bool `json:"truncated,omitempty"` @@ -1377,6 +1404,7 @@ type CodeFirstBuildOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict *string `json:"verdict,omitempty"` Causes *[]string `json:"causes,omitempty"` Epistemic *string `json:"epistemic,omitempty"` @@ -1440,6 +1468,7 @@ type CodeGrepOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Lessons *[]map[string]json.RawMessage `json:"lessons,omitempty"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` Matches []map[string]json.RawMessage `json:"matches"` @@ -1496,6 +1525,7 @@ type CodeHistoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Prs []map[string]json.RawMessage `json:"prs"` Paths []string `json:"paths"` Items *[]map[string]json.RawMessage `json:"items,omitempty"` @@ -1532,6 +1562,7 @@ type CodeImpactOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Lessons *[]map[string]json.RawMessage `json:"lessons,omitempty"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` ImpactedSymbols []map[string]json.RawMessage `json:"impacted_symbols"` @@ -1583,6 +1614,7 @@ type CodeIndexErrorsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []CodeIndexErrorRow `json:"rows"` Total *int64 `json:"total,omitempty"` } @@ -1604,6 +1636,7 @@ type CodeIndexStatusOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Repo string `json:"repo"` Branch string `json:"branch"` Org *string `json:"org,omitempty"` @@ -1695,6 +1728,7 @@ type CodeMapOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Map string `json:"map"` TokensUsed int64 `json:"tokens_used"` CommitSHA *string `json:"commit_sha,omitempty"` @@ -1722,6 +1756,7 @@ type CodeOutcomeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Recorded bool `json:"recorded"` } @@ -1744,6 +1779,7 @@ type CodeOutlineOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Lessons *[]map[string]json.RawMessage `json:"lessons,omitempty"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` Path string `json:"path"` @@ -1780,6 +1816,7 @@ type CodePathGuardsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict string `json:"verdict"` Causes *[]string `json:"causes,omitempty"` Epistemic *string `json:"epistemic,omitempty"` @@ -1811,6 +1848,7 @@ type CodePrCheckOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict *string `json:"verdict,omitempty"` Items *[]map[string]json.RawMessage `json:"items,omitempty"` Undecided *bool `json:"undecided,omitempty"` @@ -1841,6 +1879,7 @@ type CodeReadOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Lessons *[]map[string]json.RawMessage `json:"lessons,omitempty"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` Results []CodeReadRange `json:"results"` @@ -1897,6 +1936,7 @@ type CodeRecentCommitsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []CodeRecentCommitRow `json:"rows"` } @@ -1917,6 +1957,7 @@ type CodeRefreshOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Triggered bool `json:"triggered"` AlreadyRunning *bool `json:"already_running,omitempty"` HeadBefore *string `json:"head_before,omitempty"` @@ -1938,6 +1979,7 @@ type CodeReindexOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` PreviousHead string `json:"previous_head"` NewHead string `json:"new_head"` } @@ -1973,6 +2015,7 @@ type CodeRepoAddOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` Repo string `json:"repo"` @@ -2003,6 +2046,7 @@ type CodeRepoRemoteBranchesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Repo string `json:"repo"` Remote *string `json:"remote,omitempty"` @@ -2031,6 +2075,7 @@ type CodeRepoRemoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` Repo string `json:"repo"` @@ -2057,6 +2102,7 @@ type CodeRepoSetAccessOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` Repo string `json:"repo"` @@ -2080,6 +2126,7 @@ type CodeRepoSetSourceOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` TrackerNamespaces *[]string `json:"tracker_namespaces,omitempty"` @@ -2146,6 +2193,7 @@ type CodeReposOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Repos []CodeRepoSummary `json:"repos"` } @@ -2174,6 +2222,7 @@ type CodeReviewBriefOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` PrNumber *int64 `json:"pr_number,omitempty"` MergeSHA *string `json:"merge_sha,omitempty"` Source *string `json:"source,omitempty"` @@ -2217,6 +2266,7 @@ type CodeScipIngestOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` BatchID string `json:"batch_id"` PartsReceived int64 `json:"parts_received"` TotalParts int64 `json:"total_parts"` @@ -2238,6 +2288,7 @@ type CodeScipStatusOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` BatchID string `json:"batch_id"` Status string `json:"status"` PartsReceived int64 `json:"parts_received"` @@ -2293,6 +2344,7 @@ type CodeSearchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Lessons *[]map[string]json.RawMessage `json:"lessons,omitempty"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` Results []CodeUnit `json:"results"` @@ -2341,6 +2393,7 @@ type CodeSettingFactsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Verdict *string `json:"verdict,omitempty"` Causes *[]string `json:"causes,omitempty"` @@ -2370,6 +2423,7 @@ type CodeSymbolHistoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict *string `json:"verdict,omitempty"` Causes *[]string `json:"causes,omitempty"` Epistemic *string `json:"epistemic,omitempty"` @@ -2420,6 +2474,7 @@ type CodeSymbolOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Definitions []CodeUnit `json:"definitions"` LessonsLeftOut *int64 `json:"lessons_left_out,omitempty"` Ambiguous *bool `json:"ambiguous,omitempty"` @@ -2461,6 +2516,7 @@ type CodeTestGateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tests *[]map[string]json.RawMessage `json:"tests,omitempty"` Untested *[]map[string]json.RawMessage `json:"untested,omitempty"` Unlinked *[]map[string]json.RawMessage `json:"unlinked,omitempty"` @@ -2500,6 +2556,7 @@ type CodeTestHomeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict *string `json:"verdict,omitempty"` Home *string `json:"home,omitempty"` Candidates *[]map[string]json.RawMessage `json:"candidates,omitempty"` @@ -2527,6 +2584,7 @@ type CodeTestsForOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tests *[]map[string]json.RawMessage `json:"tests,omitempty"` Total *int64 `json:"total,omitempty"` Truncated *bool `json:"truncated,omitempty"` @@ -2578,6 +2636,7 @@ type CodeTraceOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Frames []map[string]json.RawMessage `json:"frames"` Definitions []CodeUnit `json:"definitions"` TokensReturned *int64 `json:"tokens_returned,omitempty"` @@ -2642,6 +2701,7 @@ type CodeVerifyCitationsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict string `json:"verdict"` Counts *map[string]int64 `json:"counts,omitempty"` Citations *[]map[string]json.RawMessage `json:"citations,omitempty"` @@ -2675,6 +2735,7 @@ type CodeVerifyOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict string `json:"verdict"` Reason *string `json:"reason,omitempty"` Explanation string `json:"explanation"` @@ -2709,6 +2770,7 @@ type CollectionBudgetSetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` Changed bool `json:"changed"` DailyCostCapUsd float64 `json:"daily_cost_cap_usd"` @@ -2731,6 +2793,7 @@ type CollectionCreateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` Parent string `json:"parent"` Created bool `json:"created"` @@ -2748,6 +2811,7 @@ type CollectionDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` Deleted bool `json:"deleted"` ErasureID *string `json:"erasure_id,omitempty"` @@ -2778,6 +2842,7 @@ type CollectionListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Collections []CollectionEntry `json:"collections"` NextCursor Optional[string] `json:"next_cursor,omitempty"` } @@ -2794,6 +2859,7 @@ type CollectionMoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` Parent string `json:"parent"` Moved bool `json:"moved"` @@ -2844,6 +2910,7 @@ type ConflictsAllowlistListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []AllowlistRow `json:"rows"` } @@ -2862,6 +2929,7 @@ type ConflictsAllowlistRemoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Removed bool `json:"removed"` } @@ -2882,6 +2950,7 @@ type ConflictsListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []ConflictRow `json:"rows"` NextBeforeVersion Optional[uint64] `json:"next_before_version,omitempty"` Total Optional[int64] `json:"total,omitempty"` @@ -2902,6 +2971,7 @@ type ConflictsProposeRevisionOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Memories *[]ConflictCandidateMemory `json:"memories,omitempty"` Suggestions *[]ConflictRevisionSuggestion `json:"suggestions,omitempty"` @@ -2924,6 +2994,7 @@ type ConflictsResolveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Resolved bool `json:"resolved"` Decision string `json:"decision"` AffectedMemoryIds []string `json:"affected_memory_ids"` @@ -2953,6 +3024,7 @@ type ConnectionDisconnectOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Disconnected bool `json:"disconnected"` } @@ -2977,6 +3049,7 @@ type ConnectionListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Connections []ConnectionEntry `json:"connections"` } @@ -3016,6 +3089,7 @@ type ConsolidationsListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []ConsolidationRunRow `json:"rows"` } @@ -3051,6 +3125,7 @@ type ContextFetchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` BlobKey string `json:"blob_key"` Content *string `json:"content,omitempty"` @@ -3084,6 +3159,7 @@ type ContextOffloadOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` BlobKey string `json:"blob_key"` ContentBytes int64 `json:"content_bytes"` ContentChars int64 `json:"content_chars"` @@ -3126,6 +3202,7 @@ type ContextPackOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rendered string `json:"rendered"` Sections map[string]string `json:"sections"` Blocks *[]ContextBlock `json:"blocks,omitempty"` @@ -3166,6 +3243,7 @@ type ConversationAppendOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MsgID string `json:"msg_id"` Ts string `json:"ts"` Stored *bool `json:"stored,omitempty"` @@ -3187,6 +3265,7 @@ type ConversationCompactOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Compacted bool `json:"compacted"` MessagesSummarized int64 `json:"messages_summarized"` SummaryMsgID *string `json:"summary_msg_id,omitempty"` @@ -3212,6 +3291,7 @@ type ConversationCreateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` ThreadID string `json:"thread_id"` CreatedAt string `json:"created_at"` } @@ -3230,6 +3310,7 @@ type ConversationDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` TombstonedAt string `json:"tombstoned_at"` ThreadID string `json:"thread_id"` RowsAffected map[string]int64 `json:"rows_affected"` @@ -3267,6 +3348,7 @@ type ConversationGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` ThreadID string `json:"thread_id"` Title *string `json:"title,omitempty"` @@ -3307,6 +3389,7 @@ type ConversationListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []ConversationEntry `json:"rows"` NextCursor Optional[string] `json:"next_cursor,omitempty"` } @@ -3328,6 +3411,7 @@ type ConversationListSavedMessagesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []SavedMessageHit `json:"rows"` NextCursor Optional[string] `json:"next_cursor,omitempty"` } @@ -3349,6 +3433,7 @@ type ConversationSaveMessageOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` ConversationID string `json:"conversation_id"` MessageID string `json:"message_id"` Indexed bool `json:"indexed"` @@ -3371,6 +3456,7 @@ type ConversationSavedStatusOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Saved []string `json:"saved"` } @@ -3393,6 +3479,7 @@ type ConversationSearchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Hits []ConversationHit `json:"hits"` NamespacesSkipped *[]string `json:"namespaces_skipped,omitempty"` } @@ -3416,6 +3503,7 @@ type ConversationSearchSavedMessagesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Hits []SavedMessageHit `json:"hits"` } @@ -3431,6 +3519,7 @@ type ConversationSetLoggingOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` Enabled bool `json:"enabled"` } @@ -3463,6 +3552,7 @@ type ConversationThreadsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Threads []ConversationThreadSummary `json:"threads"` } @@ -3481,6 +3571,7 @@ type ConversationUnsaveMessageOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` ConversationID string `json:"conversation_id"` MessageID string `json:"message_id"` Found bool `json:"found"` @@ -3504,6 +3595,7 @@ type ConversationUpdateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Updated bool `json:"updated"` ThreadID string `json:"thread_id"` UpdatedAt Optional[string] `json:"updated_at,omitempty"` @@ -3525,6 +3617,7 @@ type CostAgentSummaryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []CostAgentSummaryRow `json:"rows"` TotalTurns int64 `json:"total_turns"` TotalSessions int64 `json:"total_sessions"` @@ -3572,6 +3665,7 @@ type CostRecordTurnsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Recorded int64 `json:"recorded"` Priced int64 `json:"priced"` UnpricedModels *[]string `json:"unpriced_models,omitempty"` @@ -3599,6 +3693,7 @@ type CostSummaryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []CostSummaryRow `json:"rows"` TotalOps int64 `json:"total_ops"` TotalErrors int64 `json:"total_errors"` @@ -3690,6 +3785,7 @@ type DecisionChainOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Seed string `json:"seed"` SeedDecision Optional[DecisionRow] `json:"seed_decision,omitempty"` Nodes []ChainNodeRow `json:"nodes"` @@ -3710,6 +3806,7 @@ type DecisionOutcomeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` Updated bool `json:"updated"` MemoriesCredited *int64 `json:"memories_credited,omitempty"` @@ -3731,6 +3828,7 @@ type DecisionPrecedentsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Precedents []DecisionRow `json:"precedents"` EmbeddingModel *string `json:"embedding_model,omitempty"` } @@ -3765,6 +3863,7 @@ type DecisionRecordOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` RecordID string `json:"record_id"` SupersededPrior *bool `json:"superseded_prior,omitempty"` @@ -3937,6 +4036,7 @@ type ErasureExportOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` ExportedAt string `json:"exported_at"` Org string `json:"org"` ScopeType string `json:"scope_type"` @@ -3970,6 +4070,7 @@ type ErasureListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []ErasureListRow `json:"rows"` } @@ -4005,6 +4106,7 @@ type ErasureRequestOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` ErasureID string `json:"erasure_id"` Status string `json:"status"` Steps []ErasureStepResult `json:"steps"` @@ -4029,6 +4131,7 @@ type ErasureStatusOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` ErasureID string `json:"erasure_id"` Org Optional[string] `json:"org,omitempty"` @@ -4105,6 +4208,7 @@ type ExposureSummaryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` NamespaceRows int64 `json:"namespace_rows"` Rows []ExposureSummaryRow `json:"rows"` } @@ -4155,6 +4259,7 @@ type ExtractionPolicyOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Scope string `json:"scope"` Namespace *string `json:"namespace,omitempty"` @@ -4225,6 +4330,7 @@ type FactsExpireByAdapterOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` ExpiredTriples int64 `json:"expired_triples"` ExpiredTripleMemories int64 `json:"expired_triple_memories"` } @@ -4251,6 +4357,7 @@ type FactsListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []FactRow `json:"rows"` Truncated *bool `json:"truncated,omitempty"` } @@ -4274,6 +4381,7 @@ type FactsPathOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` EntityA string `json:"entity_a"` EntityB string `json:"entity_b"` Found bool `json:"found"` @@ -4297,6 +4405,7 @@ type FactsRelatedOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Entity string `json:"entity"` Related []RelatedEntity `json:"related"` } @@ -4323,6 +4432,7 @@ type FactsTraverseOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Seed string `json:"seed"` SeedCommunityID Optional[int64] `json:"seed_community_id,omitempty"` Nodes []TraversalNode `json:"nodes"` @@ -4370,6 +4480,7 @@ type GrantsApproveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Subject string `json:"subject"` Namespace string `json:"namespace"` Decision string `json:"decision"` @@ -4392,6 +4503,7 @@ type GrantsCreateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` Subject string `json:"subject"` @@ -4413,6 +4525,7 @@ type GrantsListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []GrantEntry `json:"rows"` NextCursor Optional[string] `json:"next_cursor,omitempty"` Truncated *bool `json:"truncated,omitempty"` @@ -4429,6 +4542,7 @@ type GrantsPendingForMeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []PendingForMeEntry `json:"rows"` } @@ -4444,6 +4558,7 @@ type GrantsRevokeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Revoked bool `json:"revoked"` RevokedAt Optional[string] `json:"revoked_at,omitempty"` } @@ -4461,6 +4576,7 @@ type GrantsShareAgentOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` Subject string `json:"subject"` Role string `json:"role"` @@ -4479,6 +4595,7 @@ type GrantsUnshareAgentOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Revoked bool `json:"revoked"` RevokedAt Optional[string] `json:"revoked_at,omitempty"` } @@ -4516,6 +4633,7 @@ type HelpGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Available bool `json:"available"` Found bool `json:"found"` Path string `json:"path"` @@ -4559,6 +4677,7 @@ type HelpSearchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Available bool `json:"available"` Hits []HelpHit `json:"hits"` } @@ -4586,6 +4705,7 @@ type InboxListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Inboxes []InboxPayload `json:"inboxes"` } @@ -4623,6 +4743,7 @@ type InboxPolicyListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Policies []PolicyPayload `json:"policies"` } @@ -4644,6 +4765,7 @@ type InboxPolicySetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Policy *PolicyPayload `json:"policy"` Removed *bool `json:"removed,omitempty"` } @@ -4663,6 +4785,7 @@ type InboxPrincipalsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Principals []Principal `json:"principals"` Truncated bool `json:"truncated"` } @@ -4691,6 +4814,7 @@ type InboxRegisterOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Inbox InboxPayload `json:"inbox"` Created bool `json:"created"` } @@ -4763,6 +4887,7 @@ type InsightsCatalogOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tables []CatalogTable `json:"tables"` MaxResultRows int64 `json:"max_result_rows"` MaxExecutionS float64 `json:"max_execution_s"` @@ -4782,6 +4907,7 @@ type InsightsQueryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Columns *[]AnalysisColumn `json:"columns,omitempty"` Rows *[][]json.RawMessage `json:"rows,omitempty"` RowCount *int64 `json:"row_count,omitempty"` @@ -4936,6 +5062,7 @@ type KnowledgeAddOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` DocID string `json:"doc_id"` ChunksCreated int64 `json:"chunks_created"` EmbeddingModel string `json:"embedding_model"` @@ -4959,6 +5086,7 @@ type KnowledgeBulkAddOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Written []KnowledgeBulkEntryResult `json:"written"` EmbeddingModel string `json:"embedding_model"` EmbeddingDim int64 `json:"embedding_dim"` @@ -4976,6 +5104,7 @@ type KnowledgeBulkDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Deleted []KnowledgeBulkDeleteResult `json:"deleted"` TotalChunksTombstoned int64 `json:"total_chunks_tombstoned"` } @@ -5026,6 +5155,7 @@ type KnowledgeDatasetApproveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Dataset Optional[DatasetOut] `json:"dataset,omitempty"` Retyped *bool `json:"retyped,omitempty"` @@ -5045,6 +5175,7 @@ type KnowledgeDatasetGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Revision *int64 `json:"revision,omitempty"` Datasets *[]DatasetOut `json:"datasets,omitempty"` @@ -5063,6 +5194,7 @@ type KnowledgeDedupListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` DocClusters *[]KnowledgeDocCluster `json:"doc_clusters,omitempty"` ChunkClusters *[]KnowledgeChunkCluster `json:"chunk_clusters,omitempty"` } @@ -5082,6 +5214,7 @@ type KnowledgeDedupResolveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` CanonicalURI string `json:"canonical_uri"` DuplicateURI string `json:"duplicate_uri"` Decision string `json:"decision"` @@ -5100,6 +5233,7 @@ type KnowledgeDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Deleted bool `json:"deleted"` ChunksTombstoned int64 `json:"chunks_tombstoned"` } @@ -5130,6 +5264,7 @@ type KnowledgeFormatsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Formats *[]KnowledgeFormat `json:"formats,omitempty"` MaxUploadBytes *int64 `json:"max_upload_bytes,omitempty"` RefusedExtensions *[]string `json:"refused_extensions,omitempty"` @@ -5158,6 +5293,7 @@ type KnowledgeGapsDraftOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` CandidateID string `json:"candidate_id"` } @@ -5173,6 +5309,7 @@ type KnowledgeGapsListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Gaps *[]KnowledgeGap `json:"gaps,omitempty"` BuiltAt Optional[string] `json:"built_at,omitempty"` Capturing Optional[bool] `json:"capturing,omitempty"` @@ -5192,6 +5329,7 @@ type KnowledgeGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` SourceURI string `json:"source_uri"` Title Optional[string] `json:"title,omitempty"` @@ -5219,6 +5357,7 @@ type KnowledgeIngestCancelOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` State *string `json:"state,omitempty"` Cancelled *bool `json:"cancelled,omitempty"` @@ -5254,6 +5393,7 @@ type KnowledgeIngestOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` IngestionID string `json:"ingestion_id"` State string `json:"state"` SourceURI string `json:"source_uri"` @@ -5272,6 +5412,7 @@ type KnowledgeIngestStatusOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` IngestionID string `json:"ingestion_id"` SourceURI *string `json:"source_uri,omitempty"` @@ -5305,6 +5446,7 @@ type KnowledgeInspectOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` ComputedAt string `json:"computed_at"` @@ -5358,6 +5500,7 @@ type KnowledgeListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []KnowledgeListEntry `json:"rows"` NextCursor Optional[string] `json:"next_cursor,omitempty"` } @@ -5375,6 +5518,7 @@ type KnowledgeMoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` ToNamespace *string `json:"to_namespace,omitempty"` Results *[]KnowledgeMoveResult `json:"results,omitempty"` @@ -5401,6 +5545,7 @@ type KnowledgeOutlineOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` SourceURI string `json:"source_uri"` Title *string `json:"title,omitempty"` @@ -5448,6 +5593,7 @@ type KnowledgeQueryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Columns []QueryResultColumn `json:"columns"` Rows [][]json.RawMessage `json:"rows"` RowIds *[][]int64 `json:"row_ids,omitempty"` @@ -5470,6 +5616,7 @@ type KnowledgeReadsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` WindowDays int64 `json:"window_days"` Reads *[]map[string]json.RawMessage `json:"reads,omitempty"` } @@ -5487,6 +5634,7 @@ type KnowledgeRestoreOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Restored bool `json:"restored"` Reason *string `json:"reason,omitempty"` DocID *string `json:"doc_id,omitempty"` @@ -5522,6 +5670,7 @@ type KnowledgeSearchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Results []SearchHit `json:"results"` RerankedBy *string `json:"reranked_by,omitempty"` EmbeddingModel string `json:"embedding_model"` @@ -5550,6 +5699,7 @@ type KnowledgeSourceAddOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` CrawlProof Optional[KnowledgeSourceCrawlProof] `json:"crawl_proof,omitempty"` Name string `json:"name"` Kind string `json:"kind"` @@ -5573,6 +5723,7 @@ type KnowledgeSourceCheckOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Reachable *bool `json:"reachable,omitempty"` Documents *int64 `json:"documents,omitempty"` @@ -5641,6 +5792,7 @@ type KnowledgeSourceInspectOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Kind string `json:"kind"` CredentialMode *string `json:"credential_mode,omitempty"` @@ -5668,6 +5820,7 @@ type KnowledgeSourceListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Sources *[]KnowledgeSourceEntry `json:"sources,omitempty"` Enabled *bool `json:"enabled,omitempty"` AcceptsSources *bool `json:"accepts_sources,omitempty"` @@ -5686,6 +5839,7 @@ type KnowledgeSourceParseLinksOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Links *[]KnowledgeSourceParsedLink `json:"links,omitempty"` } @@ -5738,6 +5892,7 @@ type KnowledgeSourceRemoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` DocumentsPending *int64 `json:"documents_pending,omitempty"` } @@ -5755,6 +5910,7 @@ type KnowledgeSourceRotateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` CrawlProof Optional[KnowledgeSourceCrawlProof] `json:"crawl_proof,omitempty"` Name string `json:"name"` Probe *KnowledgeSourceProbe `json:"probe,omitempty"` @@ -5794,6 +5950,7 @@ type KnowledgeSourceSyncNowOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Enabled *bool `json:"enabled,omitempty"` } @@ -5816,6 +5973,7 @@ type KnowledgeSourceUpdateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` CrawlProof Optional[KnowledgeSourceCrawlProof] `json:"crawl_proof,omitempty"` Name string `json:"name"` Items *[]map[string]json.RawMessage `json:"items,omitempty"` @@ -5844,6 +6002,7 @@ type KnowledgeSynthesizeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Answer string `json:"answer"` Windows int64 `json:"windows"` ChunksRead int64 `json:"chunks_read"` @@ -5876,6 +6035,7 @@ type KnowledgeUpdateMetadataOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Updated bool `json:"updated"` Title *string `json:"title,omitempty"` Description *string `json:"description,omitempty"` @@ -5906,6 +6066,7 @@ type KnowledgeUpsertOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` DocID string `json:"doc_id"` ChunksCreated int64 `json:"chunks_created"` ChunksSuperseded int64 `json:"chunks_superseded"` @@ -5953,6 +6114,7 @@ type LearningsListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []LearningEntry `json:"rows"` } @@ -5968,6 +6130,7 @@ type LearningsQualityOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []LearningsQualityRow `json:"rows"` } @@ -5996,6 +6159,7 @@ type LearningsReviewOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` CandidateID string `json:"candidate_id"` NewStatus string `json:"new_status"` PromotedToShared *bool `json:"promoted_to_shared,omitempty"` @@ -6072,6 +6236,7 @@ type MemoryAgentsListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Agents []string `json:"agents"` } @@ -6095,6 +6260,7 @@ type MemoryAggregateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows *[]AggregateRow `json:"rows,omitempty"` SQLExecuted *string `json:"sql_executed,omitempty"` } @@ -6137,6 +6303,7 @@ type MemoryApplyOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Action string `json:"action"` DryRun bool `json:"dry_run"` Target string `json:"target"` @@ -6212,6 +6379,7 @@ type MemoryAskOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Answer *string `json:"answer,omitempty"` Source *string `json:"source,omitempty"` Abstain *bool `json:"abstain,omitempty"` @@ -6294,6 +6462,7 @@ type MemoryAssignCategoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Assigned bool `json:"assigned"` CategoryID string `json:"category_id"` } @@ -6331,6 +6500,7 @@ type MemoryAutoRetirementsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows *[]MemoryAutoRetirement `json:"rows,omitempty"` NextCursor Optional[string] `json:"next_cursor,omitempty"` } @@ -6352,6 +6522,7 @@ type MemoryBacklinksOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` Found *bool `json:"found,omitempty"` Versions *[]BacklinkVersion `json:"versions,omitempty"` @@ -6380,6 +6551,7 @@ type MemoryBriefOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Query *string `json:"query,omitempty"` Answer *string `json:"answer,omitempty"` Abstained *bool `json:"abstained,omitempty"` @@ -6406,6 +6578,7 @@ type MemoryBulkGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Results *map[string]ModelMemoryGetOutput `json:"results,omitempty"` Missing *[]string `json:"missing,omitempty"` } @@ -6428,6 +6601,7 @@ type MemoryBulkSetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Written []BulkSetResult `json:"written"` SkippedPinned *[]string `json:"skipped_pinned,omitempty"` SkippedLocked *[]string `json:"skipped_locked,omitempty"` @@ -6457,6 +6631,7 @@ type MemoryClearOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` ClearedAt string `json:"cleared_at"` RowsAffected map[string]int64 `json:"rows_affected"` Total int64 `json:"total"` @@ -6482,6 +6657,7 @@ type MemoryConsolidateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Consolidated *[]MemoryConsolidateResult `json:"consolidated,omitempty"` Examined *int64 `json:"examined,omitempty"` ClustersFound *int64 `json:"clusters_found,omitempty"` @@ -6519,6 +6695,7 @@ type MemoryCopyToOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Copied bool `json:"copied"` TargetMemoryID *string `json:"target_memory_id,omitempty"` TargetNamespace string `json:"target_namespace"` @@ -6541,6 +6718,7 @@ type MemoryCrossPromoteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Promoted bool `json:"promoted"` TargetMemoryID *string `json:"target_memory_id,omitempty"` TargetNamespace string `json:"target_namespace"` @@ -6563,6 +6741,7 @@ type MemoryDedupCollapseOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` Prefix *string `json:"prefix,omitempty"` DryRun *bool `json:"dry_run,omitempty"` @@ -6587,6 +6766,7 @@ type MemoryDedupListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Clusters []DedupCluster `json:"clusters"` } @@ -6607,6 +6787,7 @@ type MemoryDedupResolveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` CanonicalKey string `json:"canonical_key"` DuplicateKey string `json:"duplicate_key"` Decision string `json:"decision"` @@ -6625,6 +6806,7 @@ type MemoryDefinitionsListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Count int64 `json:"count"` Ceiling int64 `json:"ceiling"` Definitions []DefinitionEntry `json:"definitions"` @@ -6646,6 +6828,7 @@ type MemoryDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tombstoned bool `json:"tombstoned"` Version int64 `json:"version"` Found *bool `json:"found,omitempty"` @@ -6670,6 +6853,7 @@ type MemoryDeleteVersionOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tombstoned bool `json:"tombstoned"` Version *int64 `json:"version,omitempty"` Found *bool `json:"found,omitempty"` @@ -6697,6 +6881,7 @@ type MemoryDemonstrateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Query string `json:"query"` Demonstrations []DemonstrationRow `json:"demonstrations"` Votes *map[string]float64 `json:"votes,omitempty"` @@ -6722,6 +6907,7 @@ type MemoryDemoteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Demoted bool `json:"demoted"` WasReversible bool `json:"was_reversible"` TombstonedAt Optional[string] `json:"tombstoned_at,omitempty"` @@ -6743,6 +6929,7 @@ type MemoryDigestsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []DigestRow `json:"rows"` Truncated *bool `json:"truncated,omitempty"` } @@ -6777,6 +6964,7 @@ type MemoryEvidenceOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` MemoryKey *string `json:"memory_key,omitempty"` MemoryID *string `json:"memory_id,omitempty"` @@ -6805,6 +6993,7 @@ type MemoryExportEvidenceOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Chunks *[]EvidenceChunk `json:"chunks,omitempty"` Digests *[]EvidenceDigest `json:"digests,omitempty"` Edges *[]EvidenceEdge `json:"edges,omitempty"` @@ -6831,6 +7020,7 @@ type MemoryExtractionRetryMineOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Requeued *[]string `json:"requeued,omitempty"` NotFailed *[]string `json:"not_failed,omitempty"` ModelCallsOff *[]string `json:"model_calls_off,omitempty"` @@ -6863,6 +7053,7 @@ type MemoryExtractionStatusMineOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Batches *[]ExtractionQueueRow `json:"batches,omitempty"` Unknown *[]string `json:"unknown,omitempty"` Pending *int64 `json:"pending,omitempty"` @@ -6874,6 +7065,7 @@ type MemoryExtractionStatusOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Batches *[]ExtractionQueueRow `json:"batches,omitempty"` Pending *int64 `json:"pending,omitempty"` Failed *int64 `json:"failed,omitempty"` @@ -6933,6 +7125,7 @@ type MemoryForFileOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Path string `json:"path"` Total int64 `json:"total"` Hits []MemoryForFileHit `json:"hits"` @@ -6963,6 +7156,7 @@ type MemoryGetByIDOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` MemoryID *string `json:"memory_id,omitempty"` Namespace *string `json:"namespace,omitempty"` @@ -7015,6 +7209,7 @@ type MemoryGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found *bool `json:"found,omitempty"` Unchanged *bool `json:"unchanged,omitempty"` MemoryID *string `json:"memory_id,omitempty"` @@ -7090,6 +7285,7 @@ type MemoryHealthOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Live int64 `json:"live"` RecalledEver int64 `json:"recalled_ever"` UsedEver int64 `json:"used_ever"` @@ -7150,6 +7346,7 @@ type MemoryHistoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []MemoryHistoryRow `json:"rows"` } @@ -7198,6 +7395,7 @@ type MemoryImportCuratedOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []MemoryImportCuratedRow `json:"rows"` Written int64 `json:"written"` Merged int64 `json:"merged"` @@ -7241,6 +7439,7 @@ type MemoryImportEvidenceOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` ChunksWritten *int64 `json:"chunks_written,omitempty"` LinksWritten *int64 `json:"links_written,omitempty"` DigestsWritten *int64 `json:"digests_written,omitempty"` @@ -7268,6 +7467,7 @@ type MemoryImportOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Totals MemoryImportTotals `json:"totals"` Results []MemoryImportResult `json:"results"` DryRun *bool `json:"dry_run,omitempty"` @@ -7306,6 +7506,7 @@ type MemoryInspectOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` Subject string `json:"subject"` @@ -7338,6 +7539,7 @@ type MemoryKeysOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Keys []MemoryKeyRef `json:"keys"` Truncated *bool `json:"truncated,omitempty"` } @@ -7360,6 +7562,7 @@ type MemoryLineageOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` MemoryKey string `json:"memory_key"` PromotionEvent *string `json:"promotion_event,omitempty"` @@ -7395,6 +7598,7 @@ type MemoryLinkOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Linked bool `json:"linked"` FromKey string `json:"from_key"` ToKey string `json:"to_key"` @@ -7472,6 +7676,7 @@ type MemoryListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Entries []MemoryListEntry `json:"entries"` Truncated bool `json:"truncated"` Total *int64 `json:"total,omitempty"` @@ -7503,6 +7708,7 @@ type MemoryLockOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Locked bool `json:"locked"` Reason *string `json:"reason,omitempty"` MemoryID *string `json:"memory_id,omitempty"` @@ -7539,6 +7745,7 @@ type MemoryMoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` FromKey string `json:"from_key"` ToKey string `json:"to_key"` Redirected bool `json:"redirected"` @@ -7570,6 +7777,7 @@ type MemoryOutcomeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Recorded bool `json:"recorded"` EvidenceCountAfter int64 `json:"evidence_count_after"` Quarantined *bool `json:"quarantined,omitempty"` @@ -7592,6 +7800,7 @@ type MemoryOutcomeRunOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Applied int64 `json:"applied"` KeysMatched int64 `json:"keys_matched"` RunID string `json:"run_id"` @@ -7615,6 +7824,7 @@ type MemoryOutlineOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` RowsByType *map[string]int64 `json:"rows_by_type,omitempty"` Sessions *[]OutlineSession `json:"sessions,omitempty"` SessionsTotal *int64 `json:"sessions_total,omitempty"` @@ -7637,6 +7847,7 @@ type MemoryOwnerReportOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` UserID string `json:"user_id"` SinceHours int64 `json:"since_hours"` LiveRows int64 `json:"live_rows"` @@ -7672,6 +7883,7 @@ type MemoryPromoteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` SharedMemoryKey string `json:"shared_memory_key"` PromotionEvent string `json:"promotion_event"` ReversibleUntil string `json:"reversible_until"` @@ -7712,6 +7924,7 @@ type MemoryProposalDecideOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Decided *int64 `json:"decided,omitempty"` Results *[]MemoryProposalDecision `json:"results,omitempty"` } @@ -7740,6 +7953,7 @@ type MemoryProposalsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Proposals *[]MemoryProposal `json:"proposals,omitempty"` Total *int64 `json:"total,omitempty"` Policy *ProposalPolicy `json:"policy,omitempty"` @@ -7774,6 +7988,7 @@ type MemoryProvenanceOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` SourceTrace *string `json:"source_trace,omitempty"` SourceKind *string `json:"source_kind,omitempty"` @@ -7818,6 +8033,7 @@ type MemoryRecallOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Turns []RecallTurn `json:"turns"` TotalMatched *int64 `json:"total_matched,omitempty"` Returned *int64 `json:"returned,omitempty"` @@ -7859,6 +8075,7 @@ type MemoryRecordConflictsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []MemoryRecordConflictRow `json:"rows"` Truncated *bool `json:"truncated,omitempty"` } @@ -7876,6 +8093,7 @@ type MemoryRecordHistoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []MemoryRecordRow `json:"rows"` } @@ -7895,6 +8113,7 @@ type MemoryRecordQueryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []MemoryRecordRow `json:"rows"` Truncated *bool `json:"truncated,omitempty"` } @@ -7931,6 +8150,7 @@ type MemoryRecordWriteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` RecordID string `json:"record_id"` FieldCount int64 `json:"field_count"` MemoryKey *string `json:"memory_key,omitempty"` @@ -7954,6 +8174,7 @@ type MemoryRedactOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Redacted bool `json:"redacted"` RefusedHead *bool `json:"refused_head,omitempty"` RedactedAt Optional[string] `json:"redacted_at,omitempty"` @@ -7974,6 +8195,7 @@ type MemoryReindexOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Processed int64 `json:"processed"` SkippedAlreadyCurrent int64 `json:"skipped_already_current"` TargetModel string `json:"target_model"` @@ -7997,6 +8219,7 @@ type MemoryRejectOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rejected bool `json:"rejected"` RejectedAt Optional[string] `json:"rejected_at,omitempty"` } @@ -8028,6 +8251,7 @@ type MemoryRelatedOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Results []MemoryRelatedHit `json:"results"` SourceEntities []string `json:"source_entities"` Reason *string `json:"reason,omitempty"` @@ -8046,6 +8270,7 @@ type MemoryResolveOrphanDuplicatesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Candidates *int64 `json:"candidates,omitempty"` Reactivated *int64 `json:"reactivated,omitempty"` DryRun *bool `json:"dry_run,omitempty"` @@ -8070,6 +8295,7 @@ type MemoryRestoreOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Restored bool `json:"restored"` MemoryID Optional[string] `json:"memory_id,omitempty"` Version Optional[int64] `json:"version,omitempty"` @@ -8098,6 +8324,7 @@ type MemorySchemaDecisionOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Status string `json:"status"` Updated bool `json:"updated"` @@ -8116,6 +8343,7 @@ type MemorySchemaListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Schemas []MemorySchemaSummary `json:"schemas"` } @@ -8141,6 +8369,7 @@ type MemorySchemaRegisterOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` SchemaID string `json:"schema_id"` Name string `json:"name"` FieldCount int64 `json:"field_count"` @@ -8291,6 +8520,7 @@ type MemorySearchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Results []MemorySearchHit `json:"results"` CodeNote *string `json:"code_note,omitempty"` ReaderBlock *string `json:"reader_block,omitempty"` @@ -8319,7 +8549,6 @@ type MemorySearchOutput struct { Abstain *bool `json:"abstain,omitempty"` AbstainReason *string `json:"abstain_reason,omitempty"` AbstainCode *string `json:"abstain_code,omitempty"` - Degraded *[]string `json:"degraded,omitempty"` Recipe *string `json:"recipe,omitempty"` ScoreExplanation *string `json:"score_explanation,omitempty"` RetrievalConfidence *float64 `json:"retrieval_confidence,omitempty"` @@ -8427,6 +8656,7 @@ type MemorySearchTraceOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Results []SearchTraceHit `json:"results"` EmbeddingModel string `json:"embedding_model"` EntityFilter []string `json:"entity_filter"` @@ -8469,6 +8699,7 @@ type MemorySetFromMessagesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Written *[]BulkSetResult `json:"written,omitempty"` Refused *[]RefusedFact `json:"refused,omitempty"` TokensIn *int64 `json:"tokens_in,omitempty"` @@ -8491,7 +8722,6 @@ type MemorySetFromMessagesOutput struct { PipelineErrors *[]string `json:"pipeline_errors,omitempty"` ValueUpdatesLinked *int64 `json:"value_updates_linked,omitempty"` StubbedFields *[]string `json:"stubbed_fields,omitempty"` - Degraded *[]string `json:"degraded,omitempty"` Deferred *bool `json:"deferred,omitempty"` QueueID *string `json:"queue_id,omitempty"` DeferredBy *string `json:"deferred_by,omitempty"` @@ -8542,6 +8772,7 @@ type MemorySetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Version int64 `json:"version"` Pinned *bool `json:"pinned,omitempty"` MemoryID *string `json:"memory_id,omitempty"` @@ -8551,7 +8782,6 @@ type MemorySetOutput struct { Namespace *string `json:"namespace,omitempty"` MemoryKey *string `json:"memory_key,omitempty"` MergedIntoKey *string `json:"merged_into_key,omitempty"` - Degraded *[]string `json:"degraded,omitempty"` RetypedFrom *string `json:"retyped_from,omitempty"` ConflictVerdict *string `json:"conflict_verdict,omitempty"` Peers *[]MemorySetPeer `json:"peers,omitempty"` @@ -8593,6 +8823,7 @@ type MemoryStackOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Entries []StackEntry `json:"entries"` TokensUsed int64 `json:"tokens_used"` TokensBudget int64 `json:"tokens_budget"` @@ -8619,6 +8850,7 @@ type MemoryStatusesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows *[]MemoryStatus `json:"rows,omitempty"` } @@ -8635,6 +8867,7 @@ type MemorySweepExpiredOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Scanned *int64 `json:"scanned,omitempty"` Tombstoned *int64 `json:"tombstoned,omitempty"` Demoted *int64 `json:"demoted,omitempty"` @@ -8678,6 +8911,7 @@ type MemoryTimelineOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Events []MemoryTimelineEntry `json:"events"` TotalMatching *int64 `json:"total_matching,omitempty"` } @@ -8703,6 +8937,7 @@ type MemoryTouchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Touched bool `json:"touched"` Version Optional[int64] `json:"version,omitempty"` ExpiresAt Optional[string] `json:"expires_at,omitempty"` @@ -8735,6 +8970,7 @@ type MemoryUnlockOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Unlocked bool `json:"unlocked"` Reason *string `json:"reason,omitempty"` MemoryID *string `json:"memory_id,omitempty"` @@ -8759,6 +8995,7 @@ type MemoryUnpinOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Unpinned bool `json:"unpinned"` Reason *string `json:"reason,omitempty"` MemoryID *string `json:"memory_id,omitempty"` @@ -8783,6 +9020,7 @@ type MemoryUpdateByIDOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Updated bool `json:"updated"` NewVersion *int64 `json:"new_version,omitempty"` ContentSHA256 *string `json:"content_sha256,omitempty"` @@ -8826,6 +9064,7 @@ type MemoryUpdateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Updated bool `json:"updated"` MemoryID *string `json:"memory_id,omitempty"` MemoryKey *string `json:"memory_key,omitempty"` @@ -8856,6 +9095,7 @@ type MemoryVerifyOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Changed *bool `json:"changed,omitempty"` MemoryID *string `json:"memory_id,omitempty"` @@ -8888,6 +9128,7 @@ type MentorBriefOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` Agent string `json:"agent"` @@ -8918,6 +9159,7 @@ type MentorGuideOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Version string `json:"version"` Part string `json:"part"` Text string `json:"text"` @@ -9066,6 +9308,7 @@ type NamespaceAuditOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` ComputedAt string `json:"computed_at"` @@ -9112,6 +9355,7 @@ type NamespaceBrowseOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []BrowseEntry `json:"rows"` } @@ -9127,6 +9371,7 @@ type NamespaceCancelRequestOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Cancelled bool `json:"cancelled"` Namespace string `json:"namespace"` ClearedRole Optional[string] `json:"cleared_role,omitempty"` @@ -9144,6 +9389,7 @@ type NamespaceDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Deleted bool `json:"deleted"` Namespace string `json:"namespace"` UpdatedAt string `json:"updated_at"` @@ -9181,6 +9427,7 @@ type NamespaceGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Namespace string `json:"namespace"` Kind Optional[string] `json:"kind,omitempty"` @@ -9228,6 +9475,7 @@ type NamespaceGuideGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Revision *int64 `json:"revision,omitempty"` Content *string `json:"content,omitempty"` @@ -9249,6 +9497,7 @@ type NamespaceGuideHistoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Revisions []GuideRevision `json:"revisions"` } @@ -9267,6 +9516,7 @@ type NamespaceGuideSetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Written bool `json:"written"` Conflict *bool `json:"conflict,omitempty"` Revision int64 `json:"revision"` @@ -9288,6 +9538,7 @@ type NamespaceInventoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Scope InventoryScope `json:"scope"` Sections []InventorySection `json:"sections"` Populations []InventoryPopulation `json:"populations"` @@ -9308,6 +9559,7 @@ type NamespaceJoinOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Joined bool `json:"joined"` Namespace string `json:"namespace"` Role string `json:"role"` @@ -9329,6 +9581,7 @@ type NamespaceLeaveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Left bool `json:"left"` Namespace string `json:"namespace"` LeftAt Optional[string] `json:"left_at,omitempty"` @@ -9345,6 +9598,7 @@ type NamespaceListCategoriesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Categories []CategoryEntry `json:"categories"` } @@ -9367,6 +9621,7 @@ type NamespaceListMineOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []MineEntry `json:"rows"` } @@ -9383,6 +9638,7 @@ type NamespaceListOntologyOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Entries []OntologyEntry `json:"entries"` Org string `json:"org"` Namespace string `json:"namespace"` @@ -9393,6 +9649,7 @@ type NamespaceListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []NamespaceEntry `json:"rows"` } @@ -9408,6 +9665,7 @@ type NamespaceMarkSeenOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Namespace string `json:"namespace"` SeenAt string `json:"seen_at"` } @@ -9433,6 +9691,7 @@ type NamespaceRegisterCategoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` CategoryID string `json:"category_id"` Embedded bool `json:"embedded"` } @@ -9487,6 +9746,7 @@ type NamespaceRegisterOntologyOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Registered bool `json:"registered"` Org string `json:"org"` Namespace string `json:"namespace"` @@ -9500,6 +9760,7 @@ type NamespaceRegisterOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Registered bool `json:"registered"` Namespace string `json:"namespace"` UpdatedAt string `json:"updated_at"` @@ -9519,6 +9780,7 @@ type NamespaceRestoreOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Restored bool `json:"restored"` PublicationPending *bool `json:"publication_pending,omitempty"` TargetNamespace string `json:"target_namespace"` @@ -9555,6 +9817,7 @@ type NamespaceRollbackOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` DryRun bool `json:"dry_run"` AsOf string `json:"as_of"` VersionAt int64 `json:"version_at"` @@ -9580,6 +9843,7 @@ type NamespaceSearchCategoriesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Results []CategoryHit `json:"results"` } @@ -9597,6 +9861,7 @@ type NamespaceSnapshotOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` } // NamespaceSnapshotPayload is a model used by Loom operations. @@ -9629,6 +9894,7 @@ type NamespaceSummaryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` TotalMemories int64 `json:"total_memories"` @@ -9654,6 +9920,7 @@ type NamespaceTaxonomyOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tags []TaxonomyEntry `json:"tags"` Entities []TaxonomyEntry `json:"entities"` MemoryCount int64 `json:"memory_count"` @@ -9683,6 +9950,7 @@ type NamespaceTuneOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` ComputedAt string `json:"computed_at"` @@ -9748,6 +10016,7 @@ type NamespaceValidateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Namespace string `json:"namespace"` Healthy bool `json:"healthy"` @@ -9776,6 +10045,7 @@ type ObserveCrystallizeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Enqueued *int64 `json:"enqueued,omitempty"` SessionID *string `json:"session_id,omitempty"` } @@ -9805,6 +10075,7 @@ type ObserveRecordOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` MemoryID *string `json:"memory_id,omitempty"` Kind *string `json:"kind,omitempty"` @@ -9854,6 +10125,7 @@ type OpsCapabilitiesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` BuildCommit *string `json:"build_commit,omitempty"` SchemaVersion *string `json:"schema_version,omitempty"` Ops *[]OpCapability `json:"ops,omitempty"` @@ -9880,11 +10152,37 @@ type OpsHealthOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Checks []OpsHealthCheck `json:"checks"` WorkerStatus *map[string]map[string]json.RawMessage `json:"worker_status,omitempty"` Overall string `json:"overall"` } +// OpsIncident is a model used by Loom operations. +type OpsIncident struct { + Kind string `json:"kind"` + Subject string `json:"subject"` + Severity string `json:"severity"` + Detail string `json:"detail"` + AgeS Optional[float64] `json:"age_s,omitempty"` +} + +// OpsIncidentsInput is the request to ops.incidents. +type OpsIncidentsInput struct { + Org *string `json:"org,omitempty"` +} + +// OpsIncidentsOutput is the response from ops.incidents. +type OpsIncidentsOutput struct { + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` + Status string `json:"status"` + Incidents *[]OpsIncident `json:"incidents,omitempty"` + WindowMinutes int64 `json:"window_minutes"` +} + // OpsProjectionFailuresListInput is the request to ops.projection_failures.list. type OpsProjectionFailuresListInput = ProjectionFailureListInput @@ -9913,6 +10211,7 @@ type OrgModelCallsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Org string `json:"org"` Enabled bool `json:"enabled"` Reason *string `json:"reason,omitempty"` @@ -10030,6 +10329,7 @@ type PolicyCheckOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Decision string `json:"decision"` WouldEnforce bool `json:"would_enforce"` Mode string `json:"mode"` @@ -10069,6 +10369,7 @@ type PolicyDecisionsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []PolicyDecisionRow `json:"rows"` } @@ -10085,6 +10386,7 @@ type PolicyDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Removed bool `json:"removed"` Widening *bool `json:"widening,omitempty"` } @@ -10101,6 +10403,7 @@ type PolicyListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rules []PolicyRuleOut `json:"rules"` Mode string `json:"mode"` } @@ -10151,6 +10454,7 @@ type PolicySetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rule PolicyRuleOut `json:"rule"` LeafCount int64 `json:"leaf_count"` Widening *bool `json:"widening,omitempty"` @@ -10189,6 +10493,7 @@ type ProcedureAddOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` MemoryID string `json:"memory_id"` Version int64 `json:"version"` @@ -10220,6 +10525,7 @@ type ProcedureEvolveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` Version int64 `json:"version"` Revision int64 `json:"revision"` @@ -10262,6 +10568,7 @@ type ProcedureForkOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` Version int64 `json:"version"` Name string `json:"name"` @@ -10286,6 +10593,7 @@ type ProcedureListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Procedures []ProcedureSummary `json:"procedures"` } @@ -10309,6 +10617,7 @@ type ProcedureLocateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` Name *string `json:"name,omitempty"` Status *string `json:"status,omitempty"` @@ -10378,6 +10687,7 @@ type ProcedureMatchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Matches []ProcedureMatch `json:"matches"` Matched *int64 `json:"matched,omitempty"` ProcedureKey *string `json:"procedure_key,omitempty"` @@ -10406,6 +10716,7 @@ type ProcedureRecordRunOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` Version int64 `json:"version"` RunStats map[string]int64 `json:"run_stats"` @@ -10429,6 +10740,7 @@ type ProcedureReviseOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` MemoryKey string `json:"memory_key"` Version int64 `json:"version"` Revision int64 `json:"revision"` @@ -10471,6 +10783,7 @@ type ProfileActivityOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Entries *[]ProfileActivityEntry `json:"entries,omitempty"` } @@ -10495,6 +10808,7 @@ type ProfileMutationOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Version int64 `json:"version"` MemoryID *string `json:"memory_id,omitempty"` ContentSHA256 *string `json:"content_sha256,omitempty"` @@ -10523,6 +10837,7 @@ type ProfileRenderOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rendered string `json:"rendered"` SectionCount int64 `json:"section_count"` TotalChars int64 `json:"total_chars"` @@ -10568,6 +10883,7 @@ type ProfileSchemaOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` JSONSchema *map[string]json.RawMessage `json:"json_schema,omitempty"` SchemaSHA256 *string `json:"schema_sha256,omitempty"` @@ -10619,6 +10935,7 @@ type ProfileStructuredOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Status string `json:"status"` Profile *map[string]json.RawMessage `json:"profile,omitempty"` BuiltAt Optional[string] `json:"built_at,omitempty"` @@ -10642,6 +10959,7 @@ type ProjectionFailureListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []ProjectionFailureRow `json:"rows"` Total int64 `json:"total"` } @@ -10657,6 +10975,7 @@ type ProjectionFailureResolveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Resolved int64 `json:"resolved"` } @@ -10673,6 +10992,7 @@ type ProjectionFailureRetryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Results *[]ProjectionFailureRetryRow `json:"results,omitempty"` Retried int64 `json:"retried"` Resolved int64 `json:"resolved"` @@ -10750,6 +11070,7 @@ type PushStatusOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Enabled *bool `json:"enabled,omitempty"` Status *string `json:"status,omitempty"` Provider *string `json:"provider,omitempty"` @@ -10824,6 +11145,7 @@ type QueryHistoryListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Enabled *bool `json:"enabled,omitempty"` Sources *[]QueryHistorySource `json:"sources,omitempty"` } @@ -10840,6 +11162,7 @@ type QueryHistoryRemoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Removed bool `json:"removed"` } @@ -10862,6 +11185,7 @@ type QueryHistorySourceHTTPResponse struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name *string `json:"name,omitempty"` SourceID *string `json:"source_id,omitempty"` Kind *string `json:"kind,omitempty"` @@ -11015,6 +11339,7 @@ type RunBeginOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` RunID string `json:"run_id"` Status *string `json:"status,omitempty"` StartedAt string `json:"started_at"` @@ -11046,6 +11371,7 @@ type RunCompleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` RunID string `json:"run_id"` Status string `json:"status"` DurationMs int64 `json:"duration_ms"` @@ -11075,6 +11401,7 @@ type RunGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Run Optional[RunRow] `json:"run,omitempty"` Recalled *int64 `json:"recalled,omitempty"` @@ -11105,6 +11432,7 @@ type RunGradeOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Graded *int64 `json:"graded,omitempty"` RunIds *[]string `json:"run_ids,omitempty"` SkippedActive *int64 `json:"skipped_active,omitempty"` @@ -11142,6 +11470,7 @@ type RunListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Runs []RunRow `json:"runs"` Total Optional[int64] `json:"total,omitempty"` } @@ -11275,6 +11604,7 @@ type SearchOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tracker Optional[map[string]json.RawMessage] `json:"tracker,omitempty"` Live Optional[LiveSearchResults] `json:"live,omitempty"` Memory *map[string]json.RawMessage `json:"memory,omitempty"` @@ -11320,6 +11650,7 @@ type SearchTraceLogOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rows []SearchTraceLogRow `json:"rows"` } @@ -11356,6 +11687,7 @@ type SessionBriefDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Deleted bool `json:"deleted"` BriefKey string `json:"brief_key"` Revision *int64 `json:"revision,omitempty"` @@ -11383,6 +11715,7 @@ type SessionBriefGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` BriefKey *string `json:"brief_key,omitempty"` Revision *int64 `json:"revision,omitempty"` @@ -11425,6 +11758,7 @@ type SessionBriefListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Briefs *[]SessionBriefSummary `json:"briefs,omitempty"` Rendered *string `json:"rendered,omitempty"` } @@ -11456,6 +11790,7 @@ type SessionBriefSaveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` BriefKey string `json:"brief_key"` Revision int64 `json:"revision"` Changed bool `json:"changed"` @@ -11698,6 +12033,7 @@ type TaskCountsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Counts []InboxCount `json:"counts"` } @@ -11725,6 +12061,7 @@ type TaskCreateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Task TaskPayload `json:"task"` Created bool `json:"created"` Seq int64 `json:"seq"` @@ -11790,6 +12127,7 @@ type TaskGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Task Optional[TaskPayload] `json:"task,omitempty"` } @@ -11821,6 +12159,7 @@ type TaskHistoryOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` Events []TaskEventPayload `json:"events"` } @@ -11846,6 +12185,7 @@ type TaskListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tasks []map[string]json.RawMessage `json:"tasks"` Truncated bool `json:"truncated"` } @@ -11855,6 +12195,7 @@ type TaskOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Task TaskPayload `json:"task"` Seq *int64 `json:"seq,omitempty"` } @@ -11923,6 +12264,7 @@ type TaskPullOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Tasks []TaskPayload `json:"tasks"` WaitedMs int64 `json:"waited_ms"` Backend string `json:"backend"` @@ -11954,6 +12296,7 @@ type TaskReassignOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Task TaskPayload `json:"task"` Replacement TaskPayload `json:"replacement"` } @@ -12010,6 +12353,7 @@ type TaskUpdateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Task TaskPayload `json:"task"` Seq int64 `json:"seq"` Conflict *bool `json:"conflict,omitempty"` @@ -12032,6 +12376,7 @@ type TaskUpdatesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Events []TaskEventPayload `json:"events"` NextSeq int64 `json:"next_seq"` WaitedMs int64 `json:"waited_ms"` @@ -12072,6 +12417,7 @@ type TrackerAnswerOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Intent *string `json:"intent,omitempty"` Anchors *map[string]json.RawMessage `json:"anchors,omitempty"` Sections *[]map[string]json.RawMessage `json:"sections,omitempty"` @@ -12092,6 +12438,7 @@ type TrackerBindingOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` TrackerNamespace *string `json:"tracker_namespace,omitempty"` TrackerNamespaces *[]string `json:"tracker_namespaces,omitempty"` Restricted *bool `json:"restricted,omitempty"` @@ -12113,6 +12460,7 @@ type TrackerComponentOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Component string `json:"component"` Risk *map[string]json.RawMessage `json:"risk,omitempty"` OpenIssues *[]map[string]json.RawMessage `json:"open_issues,omitempty"` @@ -12131,6 +12479,7 @@ type TrackerContractOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Database string `json:"database"` Tables *[]map[string]json.RawMessage `json:"tables,omitempty"` Templates *map[string]string `json:"templates,omitempty"` @@ -12161,6 +12510,7 @@ type TrackerDuplicateCheckOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Verdict *string `json:"verdict,omitempty"` Items *[]map[string]json.RawMessage `json:"items,omitempty"` Undecided *bool `json:"undecided,omitempty"` @@ -12199,6 +12549,7 @@ type TrackerFlakyOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` TestName string `json:"test_name"` KnownFlaky *bool `json:"known_flaky,omitempty"` OpenIssues *int64 `json:"open_issues,omitempty"` @@ -12220,6 +12571,7 @@ type TrackerItemOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Items []map[string]json.RawMessage `json:"items"` Unknown *[]int64 `json:"unknown,omitempty"` TrackerUnavailable *bool `json:"tracker_unavailable,omitempty"` @@ -12252,6 +12604,7 @@ type TrackerLinksOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Subject *map[string]json.RawMessage `json:"subject,omitempty"` Verdict *string `json:"verdict,omitempty"` Items *[]map[string]json.RawMessage `json:"items,omitempty"` @@ -12273,6 +12626,7 @@ type TrackerReleaseOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Version string `json:"version"` Blockers []map[string]json.RawMessage `json:"blockers"` ActiveBlockers *int64 `json:"active_blockers,omitempty"` @@ -12297,6 +12651,7 @@ type TrackerSimilarOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Items *[]map[string]json.RawMessage `json:"items,omitempty"` Query *map[string]json.RawMessage `json:"query,omitempty"` Legs *map[string]string `json:"legs,omitempty"` @@ -12325,6 +12680,7 @@ type TrackerSourceAddOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Host string `json:"host"` Database string `json:"database"` @@ -12348,6 +12704,7 @@ type TrackerSourceCheckOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Database *string `json:"database,omitempty"` Reachable *bool `json:"reachable,omitempty"` @@ -12373,6 +12730,7 @@ type TrackerSourceInspectOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Host string `json:"host"` Database string `json:"database"` Tables *[]map[string]json.RawMessage `json:"tables,omitempty"` @@ -12391,6 +12749,7 @@ type TrackerSourceListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Sources *[]map[string]json.RawMessage `json:"sources,omitempty"` SelfService *bool `json:"self_service,omitempty"` } @@ -12415,6 +12774,7 @@ type TrackerSourceRemoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Deactivated *bool `json:"deactivated,omitempty"` NamespacesRetired *[]string `json:"namespaces_retired,omitempty"` @@ -12433,6 +12793,7 @@ type TrackerSourceRotateOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Contract *map[string]json.RawMessage `json:"contract,omitempty"` RotatedAt *string `json:"rotated_at,omitempty"` @@ -12451,6 +12812,7 @@ type TrackerSourceSetMappingOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Name string `json:"name"` Contract *map[string]json.RawMessage `json:"contract,omitempty"` DryRun *bool `json:"dry_run,omitempty"` @@ -12474,6 +12836,7 @@ type TrackerTestSignalOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` TestName string `json:"test_name"` Verdict *string `json:"verdict,omitempty"` Why *[]string `json:"why,omitempty"` @@ -12588,6 +12951,7 @@ type UIVitalsOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Recorded *bool `json:"recorded,omitempty"` Route *string `json:"route,omitempty"` } @@ -12633,6 +12997,7 @@ type WebhookDeliveriesOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Deliveries *[]WebhookDelivery `json:"deliveries,omitempty"` } @@ -12673,6 +13038,7 @@ type WebhookListOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Webhooks *[]WebhookInfo `json:"webhooks,omitempty"` } @@ -12690,6 +13056,7 @@ type WebhookRegisterOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Webhook WebhookInfo `json:"webhook"` } @@ -12705,6 +13072,7 @@ type WebhookRemoveOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Removed bool `json:"removed"` } @@ -12749,6 +13117,7 @@ type WorkingMemoryDeleteOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Deleted bool `json:"deleted"` BlockKey string `json:"block_key"` } @@ -12769,6 +13138,7 @@ type WorkingMemoryGetOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Found bool `json:"found"` BlockKey string `json:"block_key"` Content *string `json:"content,omitempty"` @@ -12783,6 +13153,7 @@ type WorkingMemoryMutationOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` BlockKey string `json:"block_key"` Version int64 `json:"version"` CharLimit int64 `json:"char_limit"` @@ -12808,6 +13179,7 @@ type WorkingMemoryRenderOutput struct { IgnoredArgs *[]string `json:"ignored_args,omitempty"` DidYouMean *map[string]string `json:"did_you_mean,omitempty"` Mirrored *bool `json:"mirrored,omitempty"` + Degraded *[]string `json:"degraded,omitempty"` Rendered string `json:"rendered"` Blocks *[]WorkingMemoryBlock `json:"blocks,omitempty"` BlockCount int64 `json:"block_count"` diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py index ce08b6daa61..4b66a7fd87a 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -2753,6 +2753,14 @@ async def health( """`ops.health`.""" return cast("_ops.OpsHealthOutput", await self._agent.call("ops.health", body, **options)) + async def incidents( + self, body: _ops.OpsIncidentsBody | None = None, /, **options: Any + ) -> _ops.OpsIncidentsOutput: + """`ops.incidents`.""" + return cast( + "_ops.OpsIncidentsOutput", await self._agent.call("ops.incidents", body, **options) + ) + async def projection_failures_list( self, body: _ops.OpsProjectionFailuresListBody | None = None, /, **options: Any ) -> _ops.OpsProjectionFailuresListOutput: diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 7cb0243efb1..4cfdaf82837 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -330,6 +330,7 @@ class OpSpec: "observe.record", "ops.capabilities", "ops.health", + "ops.incidents", "ops.projection_failures.list", "ops.projection_failures.resolve", "ops.projection_failures.retry", @@ -712,6 +713,7 @@ class OpSpec: "observe.record", "ops.capabilities", "ops.health", + "ops.incidents", "ops.projection_failures.list", "ops.projection_failures.resolve", "ops.projection_failures.retry", @@ -4295,6 +4297,18 @@ class OpSpec: False, False, ), + "ops.incidents": OpSpec( + "ops.incidents", + "OpsIncidentsInput", + "OpsIncidentsBody", + "OpsIncidentsOutput", + True, + "viewer", + "experimental", + 250, + False, + True, + ), "ops.projection_failures.list": OpSpec( "ops.projection_failures.list", "OpsProjectionFailuresListInput", @@ -18452,6 +18466,34 @@ class OpsHealthCheck(TypedDict, total=False): repair: NotRequired[str] +class OpsIncidentsInput(TypedDict, total=False): + "Whether Loom is degraded now: failing readiness checks, providers and workers, and" + + org: NotRequired[str] + + +class OpsIncidentsBody(TypedDict, total=False): + "Whether Loom is degraded now: failing readiness checks, providers and workers, and" + + org: NotRequired[str] + + +class OpsIncidentsOutput(TypedDict, total=False): + "The deployment's current incidents, as the server that answers sees them. A" + + status: Required[Literal["ok", "degraded"]] + incidents: NotRequired[list["OpsIncident"]] + window_minutes: Required[int] + + +class OpsIncident(TypedDict, total=False): + kind: Required[Literal["readiness", "provider", "worker", "requests"]] + subject: Required[str] + severity: Required[Literal["warn", "error"]] + detail: Required[str] + age_s: NotRequired[Optional[float]] + + class OpsProjectionFailuresListInput(TypedDict, total=False): org: Required[str] namespace: NotRequired[Optional[str]] diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 0dbb0532617..891d10df735 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -8,7 +8,7 @@ module Loom # Every served operation: its spec in OPS, and one method per op on the class # of its group (`client.memory.set(...)` is `memory.set`). module Generated - OP_COUNT = 379 + OP_COUNT = 380 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -303,6 +303,7 @@ module Generated "observe.record" => OpSpec.new("observe.record", "observe", "record", true, false, "writer", "stable", %w[org namespace agent user_id session_id run_id tool_name tool_input tool_output file_paths error tags observation_date action_type metadata observed_at].freeze, %w[org namespace agent tool_name].freeze), "ops.capabilities" => OpSpec.new("ops.capabilities", "ops", "capabilities", true, true, "viewer", "stable", %w[org consumer].freeze, [].freeze), "ops.health" => OpSpec.new("ops.health", "ops", "health", true, false, "org_admin", "stable", %w[org namespace].freeze, %w[org].freeze), + "ops.incidents" => OpSpec.new("ops.incidents", "ops", "incidents", true, true, "viewer", "experimental", %w[org].freeze, [].freeze), "ops.projection_failures.list" => OpSpec.new("ops.projection_failures.list", "ops", "projection_failures_list", true, false, "org_admin", "experimental", %w[org namespace projection status limit].freeze, %w[org].freeze), "ops.projection_failures.resolve" => OpSpec.new("ops.projection_failures.resolve", "ops", "projection_failures_resolve", true, false, "org_admin", "experimental", %w[org failure_ids].freeze, %w[org failure_ids].freeze), "ops.projection_failures.retry" => OpSpec.new("ops.projection_failures.retry", "ops", "projection_failures_retry", true, false, "org_admin", "experimental", %w[org namespace projection limit].freeze, %w[org].freeze), @@ -2374,6 +2375,12 @@ def health(body = nil, request_options: nil, **fields) call_op("ops.health", body, fields, request_options) end + # `ops.incidents` (viewer, read-only, experimental). + # Whether Loom is degraded now: failing readiness checks, providers and workers, and + def incidents(body = nil, request_options: nil, **fields) + call_op("ops.incidents", body, fields, request_options) + end + # `ops.projection_failures.list` (org_admin, writes, Idempotency-Key, experimental). # Required: org. def projection_failures_list(body = nil, request_options: nil, **fields) diff --git a/sdk/rust/src/blocking_operations.rs b/sdk/rust/src/blocking_operations.rs index 6b07db86efc..ae29f73a60e 100644 --- a/sdk/rust/src/blocking_operations.rs +++ b/sdk/rust/src/blocking_operations.rs @@ -3642,6 +3642,23 @@ impl crate::blocking::Client { ) -> Result, crate::CallFailure> { self.call("ops.health", &request, options) } + /// Call `ops.incidents`. + pub fn ops_incidents( + &self, + request: crate::OpsIncidentsInput, + ) -> Result { + self.ops_incidents_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `ops.incidents` with per-request options and metadata. + pub fn ops_incidents_with_options( + &self, + request: crate::OpsIncidentsInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("ops.incidents", &request, options) + } /// Call `ops.projection_failures.list`. pub fn ops_projection_failures_list( &self, diff --git a/sdk/rust/src/operations.rs b/sdk/rust/src/operations.rs index 721893a77ab..72eb178bc93 100644 --- a/sdk/rust/src/operations.rs +++ b/sdk/rust/src/operations.rs @@ -3900,6 +3900,24 @@ impl crate::Client { ) -> Result, crate::CallFailure> { self.call("ops.health", &request, options).await } + /// Call `ops.incidents`. + pub async fn ops_incidents( + &self, + request: crate::OpsIncidentsInput, + ) -> Result { + self.ops_incidents_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `ops.incidents` with per-request options and metadata. + pub async fn ops_incidents_with_options( + &self, + request: crate::OpsIncidentsInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("ops.incidents", &request, options).await + } /// Call `ops.projection_failures.list`. pub async fn ops_projection_failures_list( &self, diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 4aa86138fd5..6251bb19691 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -1126,6 +1126,7 @@ pub(crate) const OP_POLICIES: &[OperationPolicy] = &[ ("mentor.guide", true, true, &["org"], &[]), ("ops.capabilities", true, true, &["org"], &[]), ("ops.health", true, false, &["org"], &[]), + ("ops.incidents", true, true, &["org"], &[]), ("ops.projection_failures.list", true, false, &["org"], &[]), ( "ops.projection_failures.resolve", @@ -49726,32 +49727,115 @@ impl ObserveRecordInput { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum OpsIncidentsOutputStatus { + #[serde(rename = "ok")] + Ok, + #[serde(rename = "degraded")] + Degraded, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum OpsIncidentKind { + #[serde(rename = "readiness")] + Readiness, + #[serde(rename = "provider")] + Provider, + #[serde(rename = "worker")] + Worker, + #[serde(rename = "requests")] + Requests, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum OpsIncidentSeverity { + #[serde(rename = "warn")] + Warn, + #[serde(rename = "error")] + Error, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct OpsIncident { + pub kind: OpsIncidentKind, + pub subject: String, + pub severity: OpsIncidentSeverity, + pub detail: String, + #[serde(default = "default_2208")] + pub age_s: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct OpsIncidentsOutput { + pub status: OpsIncidentsOutputStatus, + #[serde(default = "default_2209")] + pub incidents: Vec, + pub window_minutes: Integer, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct OpsIncidentsInput { + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub org: Option, +} +impl Default for OpsIncidentsInput { + fn default() -> Self { + Self::new() + } +} +impl OpsIncidentsInput { + pub fn new() -> Self { + Self { org: None } + } + pub fn org(mut self, org: impl Into) -> Self { + self.org = Some(org.into()); + self + } + pub async fn send( + self, + client: &crate::Client, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + client.call("ops.incidents", &self, options).await + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProjectionFailureRow { pub failure_id: String, pub org: String, pub namespace: String, - #[serde(default = "default_2208")] + #[serde(default = "default_2210")] pub agent: String, pub projection: String, - #[serde(default = "default_2209")] + #[serde(default = "default_2211")] pub source_operation: String, - #[serde(default = "default_2210")] + #[serde(default = "default_2212")] pub source_resource_id: String, - #[serde(default = "default_2211")] + #[serde(default = "default_2213")] pub memory_keys: Vec, - #[serde(default = "default_2212")] + #[serde(default = "default_2214")] pub error_type: String, - #[serde(default = "default_2213")] + #[serde(default = "default_2215")] pub error_message: String, - #[serde(default = "default_2214")] + #[serde(default = "default_2216")] pub payload: std::collections::HashMap, - #[serde(default = "default_2215")] + #[serde(default = "default_2217")] pub status: String, - #[serde(default = "default_2216")] + #[serde(default = "default_2218")] pub created_at: Option, - #[serde(default = "default_2217")] + #[serde(default = "default_2219")] pub resolved_at: Option, } @@ -49905,22 +49989,22 @@ pub struct ProjectionFailureRetryRow { pub projection: String, pub retried: bool, pub resolved: bool, - #[serde(default = "default_2218")] + #[serde(default = "default_2220")] pub abandoned: bool, - #[serde(default = "default_2219")] + #[serde(default = "default_2221")] pub reason: String, - #[serde(default = "default_2220")] + #[serde(default = "default_2222")] pub error: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProjectionFailureRetryOutput { - #[serde(default = "default_2221")] + #[serde(default = "default_2223")] pub results: Vec, pub retried: Integer, pub resolved: Integer, - #[serde(default = "default_2222")] + #[serde(default = "default_2224")] pub abandoned: Integer, } @@ -50002,15 +50086,15 @@ impl ProjectionFailureRetryInput { pub struct OrgModelCallsOutput { pub org: String, pub enabled: bool, - #[serde(default = "default_2223")] + #[serde(default = "default_2225")] pub reason: String, - #[serde(default = "default_2224")] + #[serde(default = "default_2226")] pub updated_by: String, - #[serde(default = "default_2225")] + #[serde(default = "default_2227")] pub updated_at: Option, - #[serde(default = "default_2226")] + #[serde(default = "default_2228")] pub locked: bool, - #[serde(default = "default_2227")] + #[serde(default = "default_2229")] pub locked_by: String, } @@ -50349,7 +50433,7 @@ impl PolicyDecisionsInput { #[non_exhaustive] pub struct PolicyDeleteOutput { pub removed: bool, - #[serde(default = "default_2228")] + #[serde(default = "default_2230")] pub widening: bool, } @@ -50415,12 +50499,12 @@ pub struct PolicyRuleOut { pub condition: std::collections::HashMap, pub description: String, pub enabled: bool, - #[serde(default = "default_2229")] + #[serde(default = "default_2231")] pub mode: String, pub created_by: String, - #[serde(default = "default_2230")] + #[serde(default = "default_2232")] pub created_at: Option, - #[serde(default = "default_2231")] + #[serde(default = "default_2233")] pub updated_at: Option, } @@ -50492,9 +50576,9 @@ impl PolicyListInput { pub struct PolicySetOutput { pub rule: PolicyRuleOut, pub leaf_count: Integer, - #[serde(default = "default_2232")] + #[serde(default = "default_2234")] pub widening: bool, - #[serde(default = "default_2233")] + #[serde(default = "default_2235")] pub change: Vec, } @@ -50764,37 +50848,37 @@ pub struct ProcedureEvolveOutput { pub revision: Integer, pub changed: bool, pub template: bool, - #[serde(default = "default_2234")] + #[serde(default = "default_2236")] pub folded_runs: Integer, - #[serde(default = "default_2235")] + #[serde(default = "default_2237")] pub gate: ProcedureEvolveOutputGate, - #[serde(default = "default_2236")] + #[serde(default = "default_2238")] pub gate_mode: String, - #[serde(default = "default_2237")] + #[serde(default = "default_2239")] pub gate_llr: f64, - #[serde(default = "default_2238")] + #[serde(default = "default_2240")] pub gate_before: std::collections::HashMap, - #[serde(default = "default_2239")] + #[serde(default = "default_2241")] pub gate_after: std::collections::HashMap, - #[serde(default = "default_2240")] + #[serde(default = "default_2242")] pub gate_cost_before: std::collections::HashMap, - #[serde(default = "default_2241")] + #[serde(default = "default_2243")] pub gate_cost_after: std::collections::HashMap, - #[serde(default = "default_2242")] + #[serde(default = "default_2244")] pub gate_reason: String, - #[serde(default = "default_2243")] + #[serde(default = "default_2245")] pub dead_end_steps: Vec, - #[serde(default = "default_2244")] + #[serde(default = "default_2246")] pub fail_prone_steps: Vec, - #[serde(default = "default_2245")] + #[serde(default = "default_2247")] pub fail_prone_transitions: Vec, - #[serde(default = "default_2246")] + #[serde(default = "default_2248")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2247")] + #[serde(default = "default_2249")] pub strikes: Integer, - #[serde(default = "default_2248")] + #[serde(default = "default_2250")] pub quarantined: bool, - #[serde(default = "default_2249")] + #[serde(default = "default_2251")] pub retention: std::collections::HashMap, } @@ -51017,9 +51101,9 @@ pub struct ProcedureForkOutput { pub memory_key: String, pub version: Integer, pub name: String, - #[serde(default = "default_2250")] + #[serde(default = "default_2252")] pub steps: Vec, - #[serde(default = "default_2251")] + #[serde(default = "default_2253")] pub forked_from: std::collections::HashMap, } @@ -51279,32 +51363,32 @@ pub enum ProcedureLocateOutputStatus { #[non_exhaustive] pub struct ProcedureLocateOutput { pub memory_key: String, - #[serde(default = "default_2252")] + #[serde(default = "default_2254")] pub name: String, - #[serde(default = "default_2253")] + #[serde(default = "default_2255")] pub status: ProcedureLocateOutputStatus, pub matched: bool, - #[serde(default = "default_2254")] + #[serde(default = "default_2256")] pub active: Option>, - #[serde(default = "default_2255")] + #[serde(default = "default_2257")] pub hops: Vec>>, - #[serde(default = "default_2256")] + #[serde(default = "default_2258")] pub entry_nodes: Vec, - #[serde(default = "default_2257")] + #[serde(default = "default_2259")] pub dominant_next: Vec, - #[serde(default = "default_2258")] + #[serde(default = "default_2260")] pub revisits: std::collections::HashMap, - #[serde(default = "default_2259")] + #[serde(default = "default_2261")] pub looping: bool, - #[serde(default = "default_2260")] + #[serde(default = "default_2262")] pub exits: Vec, - #[serde(default = "default_2261")] + #[serde(default = "default_2263")] pub failure_notes: Vec>, - #[serde(default = "default_2262")] + #[serde(default = "default_2264")] pub rendered: String, - #[serde(default = "default_2263")] + #[serde(default = "default_2265")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2264")] + #[serde(default = "default_2266")] pub for_agent: std::collections::HashMap, } @@ -51459,43 +51543,43 @@ pub struct ProcedureMatch { pub name: String, pub situation: String, pub steps: Vec, - #[serde(default = "default_2265")] + #[serde(default = "default_2267")] pub tags: Vec, - #[serde(default = "default_2266")] + #[serde(default = "default_2268")] pub metadata: std::collections::HashMap, pub similarity: f64, pub memory_key: String, pub namespace: String, - #[serde(default = "default_2267")] + #[serde(default = "default_2269")] pub graph: Option>, - #[serde(default = "default_2268")] + #[serde(default = "default_2270")] pub template: bool, - #[serde(default = "default_2269")] + #[serde(default = "default_2271")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2270")] + #[serde(default = "default_2272")] pub status: ProcedureMatchStatus, - #[serde(default = "default_2271")] + #[serde(default = "default_2273")] pub quarantined: Option>, - #[serde(default = "default_2272")] + #[serde(default = "default_2274")] pub fail_prone_steps: Vec, - #[serde(default = "default_2273")] + #[serde(default = "default_2275")] pub revision: Integer, - #[serde(default = "default_2274")] + #[serde(default = "default_2276")] pub rejected_revisions: Vec>, - #[serde(default = "default_2275")] + #[serde(default = "default_2277")] pub tool_overlap: f64, - #[serde(default = "default_2276")] + #[serde(default = "default_2278")] pub score: f64, - #[serde(default = "default_2277")] + #[serde(default = "default_2279")] pub utility: f64, - #[serde(default = "default_2278")] + #[serde(default = "default_2280")] pub goal_similarity: Option, - #[serde(default = "default_2279")] + #[serde(default = "default_2281")] pub for_agent: std::collections::HashMap, - #[serde(default = "default_2280")] + #[serde(default = "default_2282")] pub run_stats_by_agent: std::collections::HashMap>, - #[serde(default = "default_2281")] + #[serde(default = "default_2283")] pub actor: String, } @@ -51503,11 +51587,11 @@ pub struct ProcedureMatch { #[non_exhaustive] pub struct ProcedureMatchOutput { pub matches: Vec, - #[serde(default = "default_2282")] + #[serde(default = "default_2284")] pub matched: Integer, - #[serde(default = "default_2283")] + #[serde(default = "default_2285")] pub procedure_key: String, - #[serde(default = "default_2284")] + #[serde(default = "default_2286")] pub score: f64, } @@ -51899,9 +51983,9 @@ pub struct ProcedureReviseOutput { pub revision: Integer, pub prior_revision: Integer, pub digest: String, - #[serde(default = "default_2285")] + #[serde(default = "default_2287")] pub steps: Vec, - #[serde(default = "default_2286")] + #[serde(default = "default_2288")] pub outcome: ProcedureReviseOutputOutcome, } @@ -52013,14 +52097,14 @@ pub struct ProfileActivityEntry { pub agent: String, pub last_activated_at: String, pub event_count: Integer, - #[serde(default = "default_2287")] + #[serde(default = "default_2289")] pub operations: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProfileActivityOutput { - #[serde(default = "default_2288")] + #[serde(default = "default_2290")] pub entries: Vec, } @@ -52128,17 +52212,17 @@ impl ProfileActivityInput { #[non_exhaustive] pub struct ProfileMutationOutput { pub version: Integer, - #[serde(default = "default_2289")] + #[serde(default = "default_2291")] pub memory_id: String, - #[serde(default = "default_2290")] + #[serde(default = "default_2292")] pub content_sha256: String, - #[serde(default = "default_2291")] + #[serde(default = "default_2293")] pub namespace: String, - #[serde(default = "default_2292")] + #[serde(default = "default_2294")] pub label: String, - #[serde(default = "default_2293")] + #[serde(default = "default_2295")] pub char_limit: Option, - #[serde(default = "default_2294")] + #[serde(default = "default_2296")] pub value_length: Integer, } @@ -52247,7 +52331,7 @@ pub struct ProfileRenderOutput { pub rendered: String, pub section_count: Integer, pub total_chars: Integer, - #[serde(default = "default_2295")] + #[serde(default = "default_2297")] pub labels: Vec, } @@ -52632,17 +52716,17 @@ pub enum ProfileStructuredOutputStatus { #[non_exhaustive] pub struct ProfileStructuredOutput { pub status: ProfileStructuredOutputStatus, - #[serde(default = "default_2296")] + #[serde(default = "default_2298")] pub profile: std::collections::HashMap, - #[serde(default = "default_2297")] + #[serde(default = "default_2299")] pub built_at: Option, - #[serde(default = "default_2298")] + #[serde(default = "default_2300")] pub memory_id: String, - #[serde(default = "default_2299")] + #[serde(default = "default_2301")] pub version: Integer, - #[serde(default = "default_2300")] + #[serde(default = "default_2302")] pub version_text: String, - #[serde(default = "default_2301")] + #[serde(default = "default_2303")] pub schema_sha256: String, } @@ -52759,13 +52843,13 @@ impl ProfileStructuredInput { #[non_exhaustive] pub struct ProfileSchemaOutput { pub found: bool, - #[serde(default = "default_2302")] + #[serde(default = "default_2304")] pub json_schema: std::collections::HashMap, - #[serde(default = "default_2303")] + #[serde(default = "default_2305")] pub schema_sha256: String, - #[serde(default = "default_2304")] + #[serde(default = "default_2306")] pub updated_by: String, - #[serde(default = "default_2305")] + #[serde(default = "default_2307")] pub updated_at: Option, } @@ -52918,10 +53002,10 @@ pub enum RunBeginOutputStatus { #[non_exhaustive] pub struct RunBeginOutput { pub run_id: String, - #[serde(default = "default_2306")] + #[serde(default = "default_2308")] pub status: RunBeginOutputStatus, pub started_at: String, - #[serde(default = "default_2307")] + #[serde(default = "default_2309")] pub next: String, } @@ -53129,29 +53213,29 @@ pub struct RunCompleteOutput { pub run_id: String, pub status: RunCompleteOutputStatus, pub duration_ms: Integer, - #[serde(default = "default_2308")] + #[serde(default = "default_2310")] pub used_applied: Integer, - #[serde(default = "default_2309")] + #[serde(default = "default_2311")] pub evidence_applied: Integer, - #[serde(default = "default_2310")] + #[serde(default = "default_2312")] pub harm_applied: Integer, - #[serde(default = "default_2311")] + #[serde(default = "default_2313")] pub memories_written: Vec, - #[serde(default = "default_2312")] + #[serde(default = "default_2314")] pub recalled: Integer, - #[serde(default = "default_2313")] + #[serde(default = "default_2315")] pub observations: Integer, - #[serde(default = "default_2314")] + #[serde(default = "default_2316")] pub procedure_runs_recorded: Integer, - #[serde(default = "default_2315")] + #[serde(default = "default_2317")] pub reflection_key: String, - #[serde(default = "default_2316")] + #[serde(default = "default_2318")] pub retain: String, - #[serde(default = "default_2317")] + #[serde(default = "default_2319")] pub retained: Integer, - #[serde(default = "default_2318")] + #[serde(default = "default_2320")] pub demoted: Integer, - #[serde(default = "default_2319")] + #[serde(default = "default_2321")] pub expiring: Integer, } @@ -53672,25 +53756,25 @@ pub enum RunGetOutputOverBudgetItem { #[non_exhaustive] pub struct RunGetOutput { pub found: bool, - #[serde(default = "default_2320")] + #[serde(default = "default_2322")] pub run: Option, - #[serde(default = "default_2321")] + #[serde(default = "default_2323")] pub recalled: Integer, - #[serde(default = "default_2322")] + #[serde(default = "default_2324")] pub recalled_keys: Vec, - #[serde(default = "default_2323")] + #[serde(default = "default_2325")] pub memories_written: Vec, - #[serde(default = "default_2324")] + #[serde(default = "default_2326")] pub observations: Integer, - #[serde(default = "default_2325")] + #[serde(default = "default_2327")] pub turns: Integer, - #[serde(default = "default_2326")] + #[serde(default = "default_2328")] pub unpriced_turns: Integer, - #[serde(default = "default_2327")] + #[serde(default = "default_2329")] pub cost_usd: f64, - #[serde(default = "default_2328")] + #[serde(default = "default_2330")] pub elapsed_seconds: Integer, - #[serde(default = "default_2329")] + #[serde(default = "default_2331")] pub over_budget: Vec, } @@ -53757,17 +53841,17 @@ pub struct RunGradeProposal { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct RunGradeOutput { - #[serde(default = "default_2330")] + #[serde(default = "default_2332")] pub graded: Integer, - #[serde(default = "default_2331")] + #[serde(default = "default_2333")] pub run_ids: Vec, - #[serde(default = "default_2332")] + #[serde(default = "default_2334")] pub skipped_active: Integer, - #[serde(default = "default_2333")] + #[serde(default = "default_2335")] pub unchanged: Integer, - #[serde(default = "default_2334")] + #[serde(default = "default_2336")] pub memories_counted: Integer, - #[serde(default = "default_2335")] + #[serde(default = "default_2337")] pub proposals_decided: Vec, } @@ -53882,7 +53966,7 @@ impl RunGradeInput { #[non_exhaustive] pub struct RunListOutput { pub runs: Vec, - #[serde(default = "default_2336")] + #[serde(default = "default_2338")] pub total: Option, } @@ -54159,39 +54243,39 @@ pub struct LiveSearchHit { pub title: String, pub url: String, pub provider: LiveSearchHitProvider, - #[serde(default = "default_2339")] + #[serde(default = "default_2341")] pub content: String, - #[serde(default = "default_2340")] + #[serde(default = "default_2342")] pub live: LiveSearchHitLive, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct LiveSearchResults { - #[serde(default = "default_2338")] + #[serde(default = "default_2340")] pub live: LiveSearchResultsLive, - #[serde(default = "default_2341")] + #[serde(default = "default_2343")] pub results: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SearchOutput { - #[serde(default = "default_2337")] + #[serde(default = "default_2339")] pub tracker: Option>, - #[serde(default = "default_2342")] + #[serde(default = "default_2344")] pub live: Option, - #[serde(default = "default_2343")] + #[serde(default = "default_2345")] pub memory: std::collections::HashMap, - #[serde(default = "default_2344")] + #[serde(default = "default_2346")] pub knowledge: std::collections::HashMap, - #[serde(default = "default_2345")] + #[serde(default = "default_2347")] pub profile: std::collections::HashMap, - #[serde(default = "default_2346")] + #[serde(default = "default_2348")] pub conversations: std::collections::HashMap, - #[serde(default = "default_2347")] + #[serde(default = "default_2349")] pub withheld: Option>, - #[serde(default = "default_2348")] + #[serde(default = "default_2350")] pub namespaces_skipped: Vec, } @@ -54384,7 +54468,7 @@ impl SearchInput { pub struct SessionBriefDeleteOutput { pub deleted: bool, pub brief_key: String, - #[serde(default = "default_2349")] + #[serde(default = "default_2351")] pub revision: Integer, } @@ -54477,67 +54561,67 @@ impl SessionBriefDeleteInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDecision { - #[serde(default = "default_2358")] + #[serde(default = "default_2360")] pub what: String, - #[serde(default = "default_2359")] + #[serde(default = "default_2361")] pub why: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDeadEnd { - #[serde(default = "default_2361")] + #[serde(default = "default_2363")] pub tried: String, - #[serde(default = "default_2362")] + #[serde(default = "default_2364")] pub why_not: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDone { - #[serde(default = "default_2364")] + #[serde(default = "default_2366")] pub what: String, - #[serde(rename = "ref", default = "default_2365")] + #[serde(rename = "ref", default = "default_2367")] pub r#ref: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefFile { - #[serde(default = "default_2369")] + #[serde(default = "default_2371")] pub path: String, - #[serde(default = "default_2370")] + #[serde(default = "default_2372")] pub role: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefSections { - #[serde(default = "default_2355")] + #[serde(default = "default_2357")] pub goal: String, - #[serde(default = "default_2356")] + #[serde(default = "default_2358")] pub status: String, - #[serde(default = "default_2357")] + #[serde(default = "default_2359")] pub verification: String, - #[serde(default = "default_2360")] + #[serde(default = "default_2362")] pub decisions: Vec, - #[serde(default = "default_2363")] + #[serde(default = "default_2365")] pub dead_ends: Vec, - #[serde(default = "default_2366")] + #[serde(default = "default_2368")] pub done: Vec, - #[serde(default = "default_2367")] + #[serde(default = "default_2369")] pub open_questions: Vec, - #[serde(default = "default_2368")] + #[serde(default = "default_2370")] pub next_steps: Vec, - #[serde(default = "default_2371")] + #[serde(default = "default_2373")] pub files: Vec, - #[serde(default = "default_2372")] + #[serde(default = "default_2374")] pub constraints: Vec, - #[serde(default = "default_2373")] + #[serde(default = "default_2375")] pub pointers: Vec, - #[serde(default = "default_2374")] + #[serde(default = "default_2376")] pub client_summary: String, - #[serde(default = "default_2375")] + #[serde(default = "default_2377")] pub client_summary_at: String, } @@ -54545,45 +54629,45 @@ pub struct BriefSections { #[non_exhaustive] pub struct SessionBriefGetOutput { pub found: bool, - #[serde(default = "default_2350")] + #[serde(default = "default_2352")] pub brief_key: String, - #[serde(default = "default_2351")] + #[serde(default = "default_2353")] pub revision: Integer, - #[serde(default = "default_2352")] + #[serde(default = "default_2354")] pub snapshot_id: String, - #[serde(default = "default_2353")] + #[serde(default = "default_2355")] pub snapshot_key: String, - #[serde(default = "default_2354")] + #[serde(default = "default_2356")] pub rendered: String, - #[serde(default = "default_2376")] + #[serde(default = "default_2378")] pub sections: Option, - #[serde(default = "default_2377")] + #[serde(default = "default_2379")] pub project: String, - #[serde(default = "default_2378")] + #[serde(default = "default_2380")] pub branch: String, - #[serde(default = "default_2379")] + #[serde(default = "default_2381")] pub head_sha: String, - #[serde(default = "default_2380")] + #[serde(default = "default_2382")] pub author: String, - #[serde(default = "default_2381")] + #[serde(default = "default_2383")] pub trigger: String, - #[serde(default = "default_2382")] + #[serde(default = "default_2384")] pub actor: String, - #[serde(default = "default_2383")] + #[serde(default = "default_2385")] pub source_sessions: Vec, - #[serde(default = "default_2384")] + #[serde(default = "default_2386")] pub updated_at: Option, - #[serde(default = "default_2385")] + #[serde(default = "default_2387")] pub age_seconds: Integer, - #[serde(default = "default_2386")] + #[serde(default = "default_2388")] pub revisions: Integer, - #[serde(default = "default_2387")] + #[serde(default = "default_2389")] pub events_total: Integer, - #[serde(default = "default_2388")] + #[serde(default = "default_2390")] pub source_chars: Integer, - #[serde(default = "default_2389")] + #[serde(default = "default_2391")] pub brief_chars: Integer, - #[serde(default = "default_2390")] + #[serde(default = "default_2392")] pub deleted: bool, } @@ -54758,34 +54842,34 @@ impl SessionBriefGetInput { pub struct SessionBriefSummary { pub brief_key: String, pub revision: Integer, - #[serde(default = "default_2391")] + #[serde(default = "default_2393")] pub project: String, - #[serde(default = "default_2392")] + #[serde(default = "default_2394")] pub branch: String, - #[serde(default = "default_2393")] + #[serde(default = "default_2395")] pub agent: String, - #[serde(default = "default_2394")] + #[serde(default = "default_2396")] pub goal: String, - #[serde(default = "default_2395")] + #[serde(default = "default_2397")] pub status: String, - #[serde(default = "default_2396")] + #[serde(default = "default_2398")] pub author: String, - #[serde(default = "default_2397")] + #[serde(default = "default_2399")] pub actor: String, - #[serde(default = "default_2398")] + #[serde(default = "default_2400")] pub updated_at: Option, - #[serde(default = "default_2399")] + #[serde(default = "default_2401")] pub age_seconds: Integer, - #[serde(default = "default_2400")] + #[serde(default = "default_2402")] pub brief_chars: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefListOutput { - #[serde(default = "default_2401")] + #[serde(default = "default_2403")] pub briefs: Vec, - #[serde(default = "default_2402")] + #[serde(default = "default_2404")] pub rendered: String, } @@ -54925,25 +55009,25 @@ impl SessionBriefListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefStats { - #[serde(default = "default_2406")] + #[serde(default = "default_2408")] pub events_in: Integer, - #[serde(default = "default_2407")] + #[serde(default = "default_2409")] pub windows: Integer, - #[serde(default = "default_2408")] + #[serde(default = "default_2410")] pub events_total: Integer, - #[serde(default = "default_2409")] + #[serde(default = "default_2411")] pub source_chars: Integer, - #[serde(default = "default_2410")] + #[serde(default = "default_2412")] pub brief_chars: Integer, - #[serde(default = "default_2411")] + #[serde(default = "default_2413")] pub compression_ratio: f64, - #[serde(default = "default_2412")] + #[serde(default = "default_2414")] pub dropped_ungrounded: Integer, - #[serde(default = "default_2413")] + #[serde(default = "default_2415")] pub tokens_in: Integer, - #[serde(default = "default_2414")] + #[serde(default = "default_2416")] pub tokens_out: Integer, - #[serde(default = "default_2415")] + #[serde(default = "default_2417")] pub llm_model: String, } @@ -54953,13 +55037,13 @@ pub struct SessionBriefSaveOutput { pub brief_key: String, pub revision: Integer, pub changed: bool, - #[serde(default = "default_2403")] + #[serde(default = "default_2405")] pub author: String, - #[serde(default = "default_2404")] + #[serde(default = "default_2406")] pub reason: String, - #[serde(default = "default_2405")] + #[serde(default = "default_2407")] pub rendered: String, - #[serde(default = "default_2416")] + #[serde(default = "default_2418")] pub stats: SessionBriefStats, } @@ -55704,39 +55788,39 @@ pub struct TaskPayload { pub priority: Integer, pub disclosure: TaskPayloadDisclosure, pub status: TaskPayloadStatus, - #[serde(default = "default_2417")] + #[serde(default = "default_2419")] pub reason: String, - #[serde(default = "default_2418")] + #[serde(default = "default_2420")] pub blocked_on: String, - #[serde(default = "default_2419")] + #[serde(default = "default_2421")] pub not_before: Option, - #[serde(default = "default_2420")] + #[serde(default = "default_2422")] pub resume_at: Option, - #[serde(default = "default_2421")] + #[serde(default = "default_2423")] pub deadline: Option, - #[serde(default = "default_2422")] + #[serde(default = "default_2424")] pub defer_count: Integer, pub title: String, - #[serde(default = "default_2423")] + #[serde(default = "default_2425")] pub brief: std::collections::HashMap, pub from_agent: String, - #[serde(default = "default_2424")] + #[serde(default = "default_2426")] pub from_subject: String, - #[serde(default = "default_2425")] + #[serde(default = "default_2427")] pub origin: String, - #[serde(default = "default_2426")] + #[serde(default = "default_2428")] pub parent_task_id: Option, - #[serde(default = "default_2427")] + #[serde(default = "default_2429")] pub owner: String, - #[serde(default = "default_2428")] + #[serde(default = "default_2430")] pub attempt: Integer, - #[serde(default = "default_2429")] + #[serde(default = "default_2431")] pub fence: Integer, - #[serde(default = "default_2430")] + #[serde(default = "default_2432")] pub lease_until: Option, - #[serde(default = "default_2431")] + #[serde(default = "default_2433")] pub outcome: std::collections::HashMap, - #[serde(default = "default_2432")] + #[serde(default = "default_2434")] pub last_actor: String, pub created_at: String, pub updated_at: String, @@ -55747,7 +55831,7 @@ pub struct TaskPayload { #[non_exhaustive] pub struct TaskOutput { pub task: TaskPayload, - #[serde(default = "default_2433")] + #[serde(default = "default_2435")] pub seq: Integer, } @@ -56148,10 +56232,10 @@ impl TaskCompleteInput { pub struct InboxCount { pub inbox: String, pub status: String, - #[serde(default = "default_2434")] + #[serde(default = "default_2436")] pub blocked_on: String, pub n: Integer, - #[serde(default = "default_2435")] + #[serde(default = "default_2437")] pub oldest: Option, } @@ -56238,7 +56322,7 @@ pub struct TaskCreateOutput { pub task: TaskPayload, pub created: bool, pub seq: Integer, - #[serde(default = "default_2436")] + #[serde(default = "default_2438")] pub next: String, } @@ -56577,7 +56661,7 @@ impl TaskFailInput { #[non_exhaustive] pub struct TaskGetOutput { pub found: bool, - #[serde(default = "default_2437")] + #[serde(default = "default_2439")] pub task: Option, } @@ -56711,23 +56795,23 @@ pub struct TaskEventPayload { pub task_id: String, pub inbox: String, pub event: String, - #[serde(default = "default_2438")] + #[serde(default = "default_2440")] pub from_status: String, - #[serde(default = "default_2439")] + #[serde(default = "default_2441")] pub to_status: String, - #[serde(default = "default_2440")] + #[serde(default = "default_2442")] pub actor: String, - #[serde(default = "default_2441")] + #[serde(default = "default_2443")] pub agent: String, - #[serde(default = "default_2442")] + #[serde(default = "default_2444")] pub fence: Integer, - #[serde(default = "default_2443")] + #[serde(default = "default_2445")] pub version: Integer, - #[serde(default = "default_2444")] + #[serde(default = "default_2446")] pub reason: String, - #[serde(default = "default_2445")] + #[serde(default = "default_2447")] pub patch: std::collections::HashMap, - #[serde(default = "default_2446")] + #[serde(default = "default_2448")] pub note: String, pub ts: String, } @@ -57067,7 +57151,7 @@ pub struct TaskPullOutput { pub tasks: Vec, pub waited_ms: Integer, pub backend: String, - #[serde(default = "default_2447")] + #[serde(default = "default_2449")] pub note: String, } @@ -57463,7 +57547,7 @@ impl TaskUnblockInput { pub struct TaskUpdateOutput { pub task: TaskPayload, pub seq: Integer, - #[serde(default = "default_2448")] + #[serde(default = "default_2450")] pub conflict: bool, } @@ -57826,19 +57910,19 @@ impl TaskReasonInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerAnswerOutput { - #[serde(default = "default_2449")] + #[serde(default = "default_2451")] pub intent: String, - #[serde(default = "default_2450")] + #[serde(default = "default_2452")] pub anchors: std::collections::HashMap, - #[serde(default = "default_2451")] + #[serde(default = "default_2453")] pub sections: Vec>, - #[serde(default = "default_2452")] + #[serde(default = "default_2454")] pub searched: Vec, - #[serde(default = "default_2453")] + #[serde(default = "default_2455")] pub lines: Vec, - #[serde(default = "default_2454")] + #[serde(default = "default_2456")] pub restricted: bool, - #[serde(default = "default_2455")] + #[serde(default = "default_2457")] pub verdict: String, } @@ -57934,17 +58018,17 @@ impl TrackerAnswerInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerBindingOutput { - #[serde(default = "default_2456")] + #[serde(default = "default_2458")] pub tracker_namespace: String, - #[serde(default = "default_2457")] + #[serde(default = "default_2459")] pub tracker_namespaces: Vec, - #[serde(default = "default_2458")] + #[serde(default = "default_2460")] pub restricted: bool, - #[serde(default = "default_2459")] + #[serde(default = "default_2461")] pub kind: String, - #[serde(default = "default_2460")] + #[serde(default = "default_2462")] pub authorized: bool, - #[serde(default = "default_2461")] + #[serde(default = "default_2463")] pub templates: Vec, } @@ -57997,13 +58081,13 @@ impl TrackerBindingInput { #[non_exhaustive] pub struct TrackerComponentOutput { pub component: String, - #[serde(default = "default_2462")] + #[serde(default = "default_2464")] pub risk: std::collections::HashMap, - #[serde(default = "default_2463")] + #[serde(default = "default_2465")] pub open_issues: Vec>, - #[serde(default = "default_2464")] + #[serde(default = "default_2466")] pub known: bool, - #[serde(default = "default_2465")] + #[serde(default = "default_2467")] pub tracker_unavailable: bool, } @@ -58064,9 +58148,9 @@ impl TrackerComponentInput { #[non_exhaustive] pub struct TrackerContractOutput { pub database: String, - #[serde(default = "default_2466")] + #[serde(default = "default_2468")] pub tables: Vec>, - #[serde(default = "default_2467")] + #[serde(default = "default_2469")] pub templates: std::collections::HashMap, } @@ -58119,66 +58203,66 @@ impl TrackerContractInput { #[non_exhaustive] pub struct TrackerLegStatus { pub name: String, - #[serde(default = "default_2478")] + #[serde(default = "default_2480")] pub status: String, - #[serde(default = "default_2479")] + #[serde(default = "default_2481")] pub reason: String, - #[serde(default = "default_2480")] + #[serde(default = "default_2482")] pub message: String, - #[serde(default = "default_2481")] + #[serde(default = "default_2483")] pub retried: bool, - #[serde(default = "default_2482")] + #[serde(default = "default_2484")] pub ms: Integer, - #[serde(default = "default_2483")] + #[serde(default = "default_2485")] pub cause: String, - #[serde(default = "default_2484")] + #[serde(default = "default_2486")] pub namespace: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerDuplicateCheckOutput { - #[serde(default = "default_2468")] + #[serde(default = "default_2470")] pub verdict: String, - #[serde(default = "default_2469")] + #[serde(default = "default_2471")] pub items: Vec>, - #[serde(default = "default_2470")] + #[serde(default = "default_2472")] pub undecided: bool, - #[serde(default = "default_2471")] + #[serde(default = "default_2473")] pub epistemic: String, - #[serde(default = "default_2472")] + #[serde(default = "default_2474")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2473")] + #[serde(default = "default_2475")] pub judge: std::collections::HashMap, - #[serde(default = "default_2474")] + #[serde(default = "default_2476")] pub fit_at: String, - #[serde(default = "default_2475")] + #[serde(default = "default_2477")] pub fit: std::collections::HashMap, - #[serde(default = "default_2476")] + #[serde(default = "default_2478")] pub query: std::collections::HashMap, - #[serde(default = "default_2477")] + #[serde(default = "default_2479")] pub legs: std::collections::HashMap, - #[serde(default = "default_2485")] + #[serde(default = "default_2487")] pub leg_status: Vec, - #[serde(default = "default_2486")] + #[serde(default = "default_2488")] pub tracker_unavailable: bool, - #[serde(default = "default_2487")] + #[serde(default = "default_2489")] pub namespaces: Vec, - #[serde(default = "default_2488")] + #[serde(default = "default_2490")] pub by_namespace: std::collections::HashMap>, - #[serde(default = "default_2489")] + #[serde(default = "default_2491")] pub closest: Vec>, - #[serde(default = "default_2490")] + #[serde(default = "default_2492")] pub needs: Vec>, - #[serde(default = "default_2491")] + #[serde(default = "default_2493")] pub closest_note: String, - #[serde(default = "default_2492")] + #[serde(default = "default_2494")] pub nearest: Vec>, - #[serde(default = "default_2493")] + #[serde(default = "default_2495")] pub rerank: std::collections::HashMap, - #[serde(default = "default_2494")] + #[serde(default = "default_2496")] pub answer: String, - #[serde(default = "default_2495")] + #[serde(default = "default_2497")] pub related_prs: Vec>, } @@ -58385,17 +58469,17 @@ impl TrackerDuplicateCheckInput { #[non_exhaustive] pub struct TrackerFlakyOutput { pub test_name: String, - #[serde(default = "default_2496")] + #[serde(default = "default_2498")] pub known_flaky: bool, - #[serde(default = "default_2497")] + #[serde(default = "default_2499")] pub open_issues: Integer, - #[serde(default = "default_2498")] + #[serde(default = "default_2500")] pub issues: Vec>, - #[serde(default = "default_2499")] + #[serde(default = "default_2501")] pub verdict: String, - #[serde(default = "default_2500")] + #[serde(default = "default_2502")] pub tracker_unavailable: bool, - #[serde(default = "default_2501")] + #[serde(default = "default_2503")] pub signal: Option>, } @@ -58478,9 +58562,9 @@ impl TrackerFlakyInput { #[non_exhaustive] pub struct TrackerItemOutput { pub items: Vec>, - #[serde(default = "default_2502")] + #[serde(default = "default_2504")] pub unknown: Vec, - #[serde(default = "default_2503")] + #[serde(default = "default_2505")] pub tracker_unavailable: bool, } @@ -58529,19 +58613,19 @@ impl TrackerItemInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerLinksOutput { - #[serde(default = "default_2504")] + #[serde(default = "default_2506")] pub subject: std::collections::HashMap, - #[serde(default = "default_2505")] + #[serde(default = "default_2507")] pub verdict: String, - #[serde(default = "default_2506")] + #[serde(default = "default_2508")] pub items: Vec>, - #[serde(default = "default_2507")] + #[serde(default = "default_2509")] pub epistemic: String, - #[serde(default = "default_2508")] + #[serde(default = "default_2510")] pub record: std::collections::HashMap, - #[serde(default = "default_2509")] + #[serde(default = "default_2511")] pub computed_at: String, - #[serde(default = "default_2510")] + #[serde(default = "default_2512")] pub tracker_unavailable: bool, } @@ -58639,11 +58723,11 @@ impl TrackerLinksInput { pub struct TrackerReleaseOutput { pub version: String, pub blockers: Vec>, - #[serde(default = "default_2511")] + #[serde(default = "default_2513")] pub active_blockers: Integer, - #[serde(default = "default_2512")] + #[serde(default = "default_2514")] pub health: std::collections::HashMap, - #[serde(default = "default_2513")] + #[serde(default = "default_2515")] pub tracker_unavailable: bool, } @@ -58692,17 +58776,17 @@ impl TrackerReleaseInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSimilarOutput { - #[serde(default = "default_2514")] + #[serde(default = "default_2516")] pub items: Vec>, - #[serde(default = "default_2515")] + #[serde(default = "default_2517")] pub query: std::collections::HashMap, - #[serde(default = "default_2516")] + #[serde(default = "default_2518")] pub legs: std::collections::HashMap, - #[serde(default = "default_2517")] + #[serde(default = "default_2519")] pub epistemic: String, - #[serde(default = "default_2518")] + #[serde(default = "default_2520")] pub tracker_unavailable: bool, - #[serde(default = "default_2519")] + #[serde(default = "default_2521")] pub namespaces: Vec, } @@ -58823,19 +58907,19 @@ pub struct TrackerSourceAddOutput { pub name: String, pub host: String, pub database: String, - #[serde(default = "default_2520")] + #[serde(default = "default_2522")] pub namespaces: Vec>, - #[serde(default = "default_2521")] + #[serde(default = "default_2523")] pub contract: std::collections::HashMap, - #[serde(default = "default_2522")] + #[serde(default = "default_2524")] pub roles: Vec, - #[serde(default = "default_2523")] + #[serde(default = "default_2525")] pub my_role: String, - #[serde(default = "default_2524")] + #[serde(default = "default_2526")] pub dry_run: bool, - #[serde(default = "default_2525")] + #[serde(default = "default_2527")] pub written: bool, - #[serde(default = "default_2526")] + #[serde(default = "default_2528")] pub view_templates: std::collections::HashMap, } @@ -58998,13 +59082,13 @@ impl TrackerSourceAddInput { #[non_exhaustive] pub struct TrackerSourceCheckOutput { pub name: String, - #[serde(default = "default_2527")] + #[serde(default = "default_2529")] pub database: String, - #[serde(default = "default_2528")] + #[serde(default = "default_2530")] pub reachable: bool, - #[serde(default = "default_2529")] + #[serde(default = "default_2531")] pub contract: std::collections::HashMap, - #[serde(default = "default_2530")] + #[serde(default = "default_2532")] pub view_templates: std::collections::HashMap, } @@ -59044,11 +59128,11 @@ impl TrackerSourceCheckInput { pub struct TrackerSourceInspectOutput { pub host: String, pub database: String, - #[serde(default = "default_2531")] + #[serde(default = "default_2533")] pub tables: Vec>, - #[serde(default = "default_2532")] + #[serde(default = "default_2534")] pub roles: Vec, - #[serde(default = "default_2533")] + #[serde(default = "default_2535")] pub proposal: std::collections::HashMap, } @@ -59177,9 +59261,9 @@ impl TrackerSourceInspectInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSourceListOutput { - #[serde(default = "default_2534")] + #[serde(default = "default_2536")] pub sources: Vec>, - #[serde(default = "default_2535")] + #[serde(default = "default_2537")] pub self_service: bool, } @@ -59232,9 +59316,9 @@ impl TrackerSourceListInput { #[non_exhaustive] pub struct TrackerSourceRemoveOutput { pub name: String, - #[serde(default = "default_2536")] + #[serde(default = "default_2538")] pub deactivated: bool, - #[serde(default = "default_2537")] + #[serde(default = "default_2539")] pub namespaces_retired: Vec, } @@ -59275,9 +59359,9 @@ impl TrackerSourceRemoveInput { #[non_exhaustive] pub struct TrackerSourceRotateOutput { pub name: String, - #[serde(default = "default_2538")] + #[serde(default = "default_2540")] pub contract: std::collections::HashMap, - #[serde(default = "default_2539")] + #[serde(default = "default_2541")] pub rotated_at: String, } @@ -59324,11 +59408,11 @@ impl TrackerSourceRotateInput { #[non_exhaustive] pub struct TrackerSourceSetMappingOutput { pub name: String, - #[serde(default = "default_2540")] + #[serde(default = "default_2542")] pub contract: std::collections::HashMap, - #[serde(default = "default_2541")] + #[serde(default = "default_2543")] pub dry_run: bool, - #[serde(default = "default_2542")] + #[serde(default = "default_2544")] pub written: bool, } @@ -59395,45 +59479,45 @@ impl TrackerSourceSetMappingInput { #[non_exhaustive] pub struct TrackerTestSignalOutput { pub test_name: String, - #[serde(default = "default_2543")] + #[serde(default = "default_2545")] pub verdict: String, - #[serde(default = "default_2544")] + #[serde(default = "default_2546")] pub why: Vec, - #[serde(default = "default_2545")] + #[serde(default = "default_2547")] pub lower_bound: f64, - #[serde(default = "default_2546")] + #[serde(default = "default_2548")] pub window_days: Integer, - #[serde(default = "default_2547")] + #[serde(default = "default_2549")] pub since: String, - #[serde(default = "default_2548")] + #[serde(default = "default_2550")] pub features: std::collections::HashMap, - #[serde(default = "default_2549")] + #[serde(default = "default_2551")] pub infra: std::collections::HashMap, - #[serde(default = "default_2550")] + #[serde(default = "default_2552")] pub churn: std::collections::HashMap, - #[serde(default = "default_2551")] + #[serde(default = "default_2553")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2552")] + #[serde(default = "default_2554")] pub source: String, - #[serde(default = "default_2553")] + #[serde(default = "default_2555")] pub timings_ms: std::collections::HashMap, - #[serde(default = "default_2554")] + #[serde(default = "default_2556")] pub tracker_unavailable: bool, - #[serde(default = "default_2555")] + #[serde(default = "default_2557")] pub rollup: std::collections::HashMap, - #[serde(default = "default_2556")] + #[serde(default = "default_2558")] pub streak: std::collections::HashMap, - #[serde(default = "default_2557")] + #[serde(default = "default_2559")] pub smells: std::collections::HashMap, - #[serde(default = "default_2558")] + #[serde(default = "default_2560")] pub prior: std::collections::HashMap, - #[serde(default = "default_2559")] + #[serde(default = "default_2561")] pub unavailable_reason: String, - #[serde(default = "default_2560")] + #[serde(default = "default_2562")] pub candidates: Vec>, - #[serde(default = "default_2561")] + #[serde(default = "default_2563")] pub candidate_matches: Integer, - #[serde(default = "default_2562")] + #[serde(default = "default_2564")] pub resolved_from: String, } @@ -59537,9 +59621,9 @@ impl TrackerTestSignalInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct UiVitalsOutput { - #[serde(default = "default_2563")] + #[serde(default = "default_2565")] pub recorded: bool, - #[serde(default = "default_2564")] + #[serde(default = "default_2566")] pub route: String, } @@ -59723,7 +59807,7 @@ pub struct WebhookDelivery { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookDeliveriesOutput { - #[serde(default = "default_2565")] + #[serde(default = "default_2567")] pub deliveries: Vec, } @@ -59845,14 +59929,14 @@ pub struct WebhookInfo { pub secret_ref: String, pub events: Vec, pub created_at: String, - #[serde(default = "default_2566")] + #[serde(default = "default_2568")] pub secret_present: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookListOutput { - #[serde(default = "default_2567")] + #[serde(default = "default_2569")] pub webhooks: Vec, } @@ -60034,7 +60118,7 @@ pub struct WorkingMemoryMutationOutput { pub version: Integer, pub char_limit: Integer, pub value_length: Integer, - #[serde(default = "default_2568")] + #[serde(default = "default_2570")] pub fill_ratio: f64, } @@ -60258,15 +60342,15 @@ impl WorkingMemoryDeleteInput { pub struct WorkingMemoryGetOutput { pub found: bool, pub block_key: String, - #[serde(default = "default_2569")] + #[serde(default = "default_2571")] pub content: String, - #[serde(default = "default_2570")] + #[serde(default = "default_2572")] pub char_limit: Integer, - #[serde(default = "default_2571")] + #[serde(default = "default_2573")] pub version: Integer, - #[serde(default = "default_2572")] + #[serde(default = "default_2574")] pub updated_at: Option, - #[serde(default = "default_2573")] + #[serde(default = "default_2575")] pub fill_ratio: f64, } @@ -60377,7 +60461,7 @@ pub struct WorkingMemoryBlock { pub content: String, pub char_limit: Integer, pub version: Integer, - #[serde(default = "default_2574")] + #[serde(default = "default_2576")] pub updated_at: Option, } @@ -60385,7 +60469,7 @@ pub struct WorkingMemoryBlock { #[non_exhaustive] pub struct WorkingMemoryRenderOutput { pub rendered: String, - #[serde(default = "default_2575")] + #[serde(default = "default_2577")] pub blocks: Vec, pub block_count: Integer, pub total_chars: Integer, @@ -67392,443 +67476,443 @@ fn default_2206() -> Integer { fn default_2207() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2208() -> String { +fn default_2208() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_2209() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2210() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2209() -> String { +fn default_2211() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2210() -> String { +fn default_2212() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2211() -> Vec { +fn default_2213() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2212() -> String { +fn default_2214() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2213() -> String { +fn default_2215() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2214() -> std::collections::HashMap { +fn default_2216() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2215() -> String { +fn default_2217() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2216() -> Option { +fn default_2218() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2217() -> Option { +fn default_2219() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2218() -> bool { +fn default_2220() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2219() -> String { +fn default_2221() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2220() -> String { +fn default_2222() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2221() -> Vec { +fn default_2223() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2222() -> Integer { +fn default_2224() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2223() -> String { +fn default_2225() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2224() -> String { +fn default_2226() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2225() -> Option { +fn default_2227() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2226() -> bool { +fn default_2228() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2227() -> String { +fn default_2229() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2228() -> bool { +fn default_2230() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2229() -> String { +fn default_2231() -> String { serde_json::from_str("\"inherit\"").expect("schema default") } -fn default_2230() -> Option { +fn default_2232() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2231() -> Option { +fn default_2233() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2232() -> bool { +fn default_2234() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2233() -> Vec { +fn default_2235() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2234() -> Integer { +fn default_2236() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2235() -> ProcedureEvolveOutputGate { +fn default_2237() -> ProcedureEvolveOutputGate { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2236() -> String { +fn default_2238() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2237() -> f64 { +fn default_2239() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2238() -> std::collections::HashMap { +fn default_2240() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2239() -> std::collections::HashMap { +fn default_2241() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2240() -> std::collections::HashMap { +fn default_2242() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2241() -> std::collections::HashMap { +fn default_2243() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2242() -> String { +fn default_2244() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2243() -> Vec { +fn default_2245() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2244() -> Vec { +fn default_2246() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2245() -> Vec { +fn default_2247() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2246() -> std::collections::HashMap { +fn default_2248() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2247() -> Integer { +fn default_2249() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2248() -> bool { +fn default_2250() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2249() -> std::collections::HashMap { +fn default_2251() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2250() -> Vec { +fn default_2252() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2251() -> std::collections::HashMap { +fn default_2253() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2252() -> String { +fn default_2254() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2253() -> ProcedureLocateOutputStatus { +fn default_2255() -> ProcedureLocateOutputStatus { serde_json::from_str("\"authored\"").expect("schema default") } -fn default_2254() -> Option> { +fn default_2256() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2255() -> Vec>> { +fn default_2257() -> Vec>> { serde_json::from_str("[]").expect("schema default") } -fn default_2256() -> Vec { +fn default_2258() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2257() -> Vec { +fn default_2259() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2258() -> std::collections::HashMap { +fn default_2260() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2259() -> bool { +fn default_2261() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2260() -> Vec { +fn default_2262() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2261() -> Vec> { +fn default_2263() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2262() -> String { +fn default_2264() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2263() -> std::collections::HashMap { +fn default_2265() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2264() -> std::collections::HashMap { +fn default_2266() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2265() -> Vec { +fn default_2267() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2266() -> std::collections::HashMap { +fn default_2268() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2267() -> Option> { +fn default_2269() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2268() -> bool { +fn default_2270() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2269() -> std::collections::HashMap { +fn default_2271() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2270() -> ProcedureMatchStatus { +fn default_2272() -> ProcedureMatchStatus { serde_json::from_str("\"authored\"").expect("schema default") } -fn default_2271() -> Option> { +fn default_2273() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2272() -> Vec { +fn default_2274() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2273() -> Integer { +fn default_2275() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_2274() -> Vec> { +fn default_2276() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2275() -> f64 { +fn default_2277() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2276() -> f64 { +fn default_2278() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2277() -> f64 { +fn default_2279() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2278() -> Option { +fn default_2280() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2279() -> std::collections::HashMap { +fn default_2281() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2280() -> std::collections::HashMap> { +fn default_2282() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2281() -> String { +fn default_2283() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2282() -> Integer { +fn default_2284() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2283() -> String { +fn default_2285() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2284() -> f64 { +fn default_2286() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2285() -> Vec { +fn default_2287() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2286() -> ProcedureReviseOutputOutcome { +fn default_2288() -> ProcedureReviseOutputOutcome { serde_json::from_str("\"opened\"").expect("schema default") } -fn default_2287() -> Vec { +fn default_2289() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2288() -> Vec { +fn default_2290() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2289() -> String { +fn default_2291() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2290() -> String { +fn default_2292() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2291() -> String { +fn default_2293() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2292() -> String { +fn default_2294() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2293() -> Option { +fn default_2295() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2294() -> Integer { +fn default_2296() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2295() -> Vec { +fn default_2297() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2296() -> std::collections::HashMap { +fn default_2298() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2297() -> Option { +fn default_2299() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2298() -> String { +fn default_2300() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2299() -> Integer { +fn default_2301() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2300() -> String { +fn default_2302() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2301() -> String { +fn default_2303() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2302() -> std::collections::HashMap { +fn default_2304() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2303() -> String { +fn default_2305() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2304() -> String { +fn default_2306() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2305() -> Option { +fn default_2307() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2306() -> RunBeginOutputStatus { +fn default_2308() -> RunBeginOutputStatus { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2307() -> String { +fn default_2309() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2308() -> Integer { +fn default_2310() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2309() -> Integer { +fn default_2311() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2310() -> Integer { +fn default_2312() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2311() -> Vec { +fn default_2313() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2312() -> Integer { +fn default_2314() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_2313() -> Integer { +fn default_2315() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2314() -> Integer { +fn default_2316() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2315() -> String { +fn default_2317() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2316() -> String { +fn default_2318() -> String { serde_json::from_str("\"keep\"").expect("schema default") } -fn default_2317() -> Integer { +fn default_2319() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2318() -> Integer { +fn default_2320() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2319() -> Integer { +fn default_2321() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2320() -> Option { +fn default_2322() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2321() -> Integer { +fn default_2323() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_2322() -> Vec { +fn default_2324() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2323() -> Vec { +fn default_2325() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2324() -> Integer { +fn default_2326() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2325() -> Integer { +fn default_2327() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2326() -> Integer { +fn default_2328() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2327() -> f64 { +fn default_2329() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2328() -> Integer { +fn default_2330() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2329() -> Vec { +fn default_2331() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2330() -> Integer { +fn default_2332() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2331() -> Vec { +fn default_2333() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2332() -> Integer { +fn default_2334() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2333() -> Integer { +fn default_2335() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2334() -> Integer { +fn default_2336() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2335() -> Vec { +fn default_2337() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2336() -> Option { +fn default_2338() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2337() -> Option> { +fn default_2339() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2338() -> LiveSearchResultsLive { +fn default_2340() -> LiveSearchResultsLive { serde_json::from_str("true").expect("schema default") } -fn default_2339() -> String { +fn default_2341() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2340() -> LiveSearchHitLive { +fn default_2342() -> LiveSearchHitLive { serde_json::from_str("true").expect("schema default") } -fn default_2341() -> Vec { +fn default_2343() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2342() -> Option { +fn default_2344() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2343() -> std::collections::HashMap { +fn default_2345() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2344() -> std::collections::HashMap { +fn default_2346() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2345() -> std::collections::HashMap { +fn default_2347() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2346() -> std::collections::HashMap { +fn default_2348() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2347() -> Option> { +fn default_2349() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2348() -> Vec { +fn default_2350() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2349() -> Integer { - serde_json::from_str("0").expect("schema default") -} -fn default_2350() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2351() -> Integer { serde_json::from_str("0").expect("schema default") } fn default_2352() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2353() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2353() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_2354() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -67848,62 +67932,62 @@ fn default_2358() -> String { fn default_2359() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2360() -> Vec { - serde_json::from_str("[]").expect("schema default") +fn default_2360() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_2361() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2362() -> String { +fn default_2362() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2363() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2364() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2363() -> Vec { +fn default_2365() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2364() -> String { +fn default_2366() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2365() -> String { +fn default_2367() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2366() -> Vec { +fn default_2368() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2367() -> Vec { +fn default_2369() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2368() -> Vec { +fn default_2370() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2369() -> String { +fn default_2371() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2370() -> String { +fn default_2372() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2371() -> Vec { +fn default_2373() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2372() -> Vec { +fn default_2374() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2373() -> Vec { +fn default_2375() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2374() -> String { - serde_json::from_str("\"\"").expect("schema default") -} -fn default_2375() -> String { +fn default_2376() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2376() -> Option { - serde_json::from_str("null").expect("schema default") -} fn default_2377() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2378() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2378() -> Option { + serde_json::from_str("null").expect("schema default") } fn default_2379() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -67917,17 +68001,17 @@ fn default_2381() -> String { fn default_2382() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2383() -> Vec { - serde_json::from_str("[]").expect("schema default") +fn default_2383() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_2384() -> Option { - serde_json::from_str("null").expect("schema default") +fn default_2384() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_2385() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_2385() -> Vec { + serde_json::from_str("[]").expect("schema default") } -fn default_2386() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_2386() -> Option { + serde_json::from_str("null").expect("schema default") } fn default_2387() -> Integer { serde_json::from_str("0").expect("schema default") @@ -67938,14 +68022,14 @@ fn default_2388() -> Integer { fn default_2389() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2390() -> bool { - serde_json::from_str("false").expect("schema default") +fn default_2390() -> Integer { + serde_json::from_str("0").expect("schema default") } -fn default_2391() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2391() -> Integer { + serde_json::from_str("0").expect("schema default") } -fn default_2392() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2392() -> bool { + serde_json::from_str("false").expect("schema default") } fn default_2393() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -67962,537 +68046,543 @@ fn default_2396() -> String { fn default_2397() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2398() -> Option { +fn default_2398() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2399() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2400() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2399() -> Integer { +fn default_2401() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2400() -> Integer { +fn default_2402() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2401() -> Vec { +fn default_2403() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2402() -> String { +fn default_2404() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2403() -> String { +fn default_2405() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2404() -> String { +fn default_2406() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2405() -> String { +fn default_2407() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2406() -> Integer { +fn default_2408() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2407() -> Integer { +fn default_2409() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2408() -> Integer { +fn default_2410() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2409() -> Integer { +fn default_2411() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2410() -> Integer { +fn default_2412() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2411() -> f64 { +fn default_2413() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2412() -> Integer { +fn default_2414() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2413() -> Integer { +fn default_2415() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2414() -> Integer { +fn default_2416() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2415() -> String { +fn default_2417() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2416() -> SessionBriefStats { +fn default_2418() -> SessionBriefStats { serde_json::from_str("{\"events_in\":0,\"windows\":0,\"events_total\":0,\"source_chars\":0,\"brief_chars\":0,\"compression_ratio\":0.0,\"dropped_ungrounded\":0,\"tokens_in\":0,\"tokens_out\":0,\"llm_model\":\"\"}").expect("schema default") } -fn default_2417() -> String { +fn default_2419() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2418() -> String { +fn default_2420() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2419() -> Option { +fn default_2421() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2420() -> Option { +fn default_2422() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2421() -> Option { +fn default_2423() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2422() -> Integer { +fn default_2424() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2423() -> std::collections::HashMap { +fn default_2425() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2424() -> String { +fn default_2426() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2425() -> String { +fn default_2427() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2426() -> Option { +fn default_2428() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2427() -> String { +fn default_2429() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2428() -> Integer { +fn default_2430() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2429() -> Integer { +fn default_2431() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2430() -> Option { +fn default_2432() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2431() -> std::collections::HashMap { +fn default_2433() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2432() -> String { +fn default_2434() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2433() -> Integer { +fn default_2435() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2434() -> String { +fn default_2436() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2435() -> Option { +fn default_2437() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2436() -> String { +fn default_2438() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2437() -> Option { +fn default_2439() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2438() -> String { +fn default_2440() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2439() -> String { +fn default_2441() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2440() -> String { +fn default_2442() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2441() -> String { +fn default_2443() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2442() -> Integer { +fn default_2444() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2443() -> Integer { +fn default_2445() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2444() -> String { +fn default_2446() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2445() -> std::collections::HashMap { +fn default_2447() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2446() -> String { +fn default_2448() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2447() -> String { +fn default_2449() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2448() -> bool { +fn default_2450() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2449() -> String { +fn default_2451() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2450() -> std::collections::HashMap { +fn default_2452() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2451() -> Vec> { +fn default_2453() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2452() -> Vec { +fn default_2454() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2453() -> Vec { +fn default_2455() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2454() -> bool { +fn default_2456() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2455() -> String { +fn default_2457() -> String { serde_json::from_str("\"unknown\"").expect("schema default") } -fn default_2456() -> String { +fn default_2458() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2457() -> Vec { +fn default_2459() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2458() -> bool { +fn default_2460() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2459() -> String { +fn default_2461() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2460() -> bool { +fn default_2462() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2461() -> Vec { +fn default_2463() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2462() -> std::collections::HashMap { +fn default_2464() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2463() -> Vec> { +fn default_2465() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2464() -> bool { +fn default_2466() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2465() -> bool { +fn default_2467() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2466() -> Vec> { +fn default_2468() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2467() -> std::collections::HashMap { +fn default_2469() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2468() -> String { +fn default_2470() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2469() -> Vec> { +fn default_2471() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2470() -> bool { +fn default_2472() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2471() -> String { +fn default_2473() -> String { serde_json::from_str("\"calibrated\"").expect("schema default") } -fn default_2472() -> std::collections::HashMap { +fn default_2474() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2473() -> std::collections::HashMap { +fn default_2475() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2474() -> String { +fn default_2476() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2475() -> std::collections::HashMap { +fn default_2477() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2476() -> std::collections::HashMap { +fn default_2478() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2477() -> std::collections::HashMap { +fn default_2479() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2478() -> String { +fn default_2480() -> String { serde_json::from_str("\"ok\"").expect("schema default") } -fn default_2479() -> String { +fn default_2481() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2480() -> String { +fn default_2482() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2481() -> bool { +fn default_2483() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2482() -> Integer { +fn default_2484() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2483() -> String { +fn default_2485() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2484() -> String { +fn default_2486() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2485() -> Vec { +fn default_2487() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2486() -> bool { +fn default_2488() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2487() -> Vec { +fn default_2489() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2488() -> std::collections::HashMap> { +fn default_2490() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2489() -> Vec> { +fn default_2491() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2490() -> Vec> { +fn default_2492() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2491() -> String { +fn default_2493() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2492() -> Vec> { +fn default_2494() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2493() -> std::collections::HashMap { +fn default_2495() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2494() -> String { +fn default_2496() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2495() -> Vec> { +fn default_2497() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2496() -> bool { +fn default_2498() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2497() -> Integer { +fn default_2499() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2498() -> Vec> { +fn default_2500() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2499() -> String { +fn default_2501() -> String { serde_json::from_str("\"no_flaky_signal\"").expect("schema default") } -fn default_2500() -> bool { +fn default_2502() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2501() -> Option> { +fn default_2503() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2502() -> Vec { +fn default_2504() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2503() -> bool { +fn default_2505() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2504() -> std::collections::HashMap { +fn default_2506() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2505() -> String { +fn default_2507() -> String { serde_json::from_str("\"not_computed\"").expect("schema default") } -fn default_2506() -> Vec> { +fn default_2508() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2507() -> String { +fn default_2509() -> String { serde_json::from_str("\"candidate\"").expect("schema default") } -fn default_2508() -> std::collections::HashMap { +fn default_2510() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2509() -> String { +fn default_2511() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2510() -> bool { +fn default_2512() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2511() -> Integer { +fn default_2513() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2512() -> std::collections::HashMap { +fn default_2514() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2513() -> bool { +fn default_2515() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2514() -> Vec> { +fn default_2516() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2515() -> std::collections::HashMap { +fn default_2517() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2516() -> std::collections::HashMap { +fn default_2518() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2517() -> String { +fn default_2519() -> String { serde_json::from_str("\"lower_bound\"").expect("schema default") } -fn default_2518() -> bool { +fn default_2520() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2519() -> Vec { +fn default_2521() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2520() -> Vec> { +fn default_2522() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2521() -> std::collections::HashMap { +fn default_2523() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2522() -> Vec { +fn default_2524() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2523() -> String { +fn default_2525() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2524() -> bool { +fn default_2526() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2525() -> bool { +fn default_2527() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2526() -> std::collections::HashMap { +fn default_2528() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2527() -> String { +fn default_2529() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2528() -> bool { +fn default_2530() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2529() -> std::collections::HashMap { +fn default_2531() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2530() -> std::collections::HashMap { +fn default_2532() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2531() -> Vec> { +fn default_2533() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2532() -> Vec { +fn default_2534() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2533() -> std::collections::HashMap { +fn default_2535() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2534() -> Vec> { +fn default_2536() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2535() -> bool { +fn default_2537() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2536() -> bool { +fn default_2538() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2537() -> Vec { +fn default_2539() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2538() -> std::collections::HashMap { +fn default_2540() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2539() -> String { +fn default_2541() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2540() -> std::collections::HashMap { +fn default_2542() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2541() -> bool { +fn default_2543() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2542() -> bool { +fn default_2544() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2543() -> String { +fn default_2545() -> String { serde_json::from_str("\"no_signal\"").expect("schema default") } -fn default_2544() -> Vec { +fn default_2546() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2545() -> f64 { +fn default_2547() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2546() -> Integer { +fn default_2548() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2547() -> String { +fn default_2549() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2548() -> std::collections::HashMap { +fn default_2550() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2549() -> std::collections::HashMap { +fn default_2551() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2550() -> std::collections::HashMap { +fn default_2552() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2551() -> std::collections::HashMap { +fn default_2553() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2552() -> String { +fn default_2554() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2553() -> std::collections::HashMap { +fn default_2555() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2554() -> bool { +fn default_2556() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2555() -> std::collections::HashMap { +fn default_2557() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2556() -> std::collections::HashMap { +fn default_2558() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2557() -> std::collections::HashMap { +fn default_2559() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2558() -> std::collections::HashMap { +fn default_2560() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2559() -> String { +fn default_2561() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2560() -> Vec> { +fn default_2562() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2561() -> Integer { +fn default_2563() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2562() -> String { +fn default_2564() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2563() -> bool { +fn default_2565() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2564() -> String { +fn default_2566() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2565() -> Vec { +fn default_2567() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2566() -> bool { +fn default_2568() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2567() -> Vec { +fn default_2569() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2568() -> f64 { +fn default_2570() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2569() -> String { +fn default_2571() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2570() -> Integer { +fn default_2572() -> Integer { serde_json::from_str("4096").expect("schema default") } -fn default_2571() -> Integer { +fn default_2573() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2572() -> Option { +fn default_2574() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2573() -> f64 { +fn default_2575() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2574() -> Option { +fn default_2576() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2575() -> Vec { +fn default_2577() -> Vec { serde_json::from_str("[]").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index fea0abf1bf0..804da0163d7 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -6780,6 +6780,21 @@ fn ops_health() { ); } #[test] +fn ops_incidents() { + let value: clickhouse_loom::OpsIncidentsInput = serde_json::from_str("{}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::OpsIncidentsOutput = + serde_json::from_str("{\"status\":\"ok\",\"window_minutes\":1}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + assert_eq!( + encoded["incidents"], + serde_json::from_str::("[]").unwrap(), + "ops.incidents:incidents" + ); +} +#[test] fn ops_projection_failures_list() { let value: clickhouse_loom::ProjectionFailureListInput = serde_json::from_str("{\"org\":\"sample\"}").unwrap(); diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index af2789778bc..f5272f69483 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -8909,6 +8909,24 @@ export interface OpsHealthOutput { overall: "ok" | "warn" | "fail"; } +export interface OpsIncidentsInput { + org?: string; +} + +export interface OpsIncident { + kind: "readiness" | "provider" | "worker" | "requests"; + subject: string; + severity: "warn" | "error"; + detail: string; + age_s?: number | null; +} + +export interface OpsIncidentsOutput { + status: "ok" | "degraded"; + incidents?: OpsIncident[]; + window_minutes: number; +} + export interface OpsProjectionFailuresListInput { org: string; namespace?: string | null; @@ -11060,6 +11078,7 @@ export type OpName = | "observe.record" | "ops.capabilities" | "ops.health" + | "ops.incidents" | "ops.projection_failures.list" | "ops.projection_failures.resolve" | "ops.projection_failures.retry" @@ -11442,6 +11461,7 @@ export interface OpMap { "observe.record": { input: ObserveRecordInput; output: ObserveRecordOutput }; "ops.capabilities": { input: OpsCapabilitiesInput; output: OpsCapabilitiesOutput }; "ops.health": { input: OpsHealthInput; output: OpsHealthOutput }; + "ops.incidents": { input: OpsIncidentsInput; output: OpsIncidentsOutput }; "ops.projection_failures.list": { input: OpsProjectionFailuresListInput; output: OpsProjectionFailuresListOutput }; "ops.projection_failures.resolve": { input: OpsProjectionFailuresResolveInput; output: OpsProjectionFailuresResolveOutput }; "ops.projection_failures.retry": { input: OpsProjectionFailuresRetryInput; output: OpsProjectionFailuresRetryOutput }; @@ -11824,6 +11844,7 @@ export const OPS: readonly OpSpec[] = [ { name: "observe.record", group: "observe", method: "record", idempotent: true, role: "writer", maturity: "stable", budgetP99Ms: 150, audit: false, readOnly: false }, { name: "ops.capabilities", group: "ops", method: "capabilities", idempotent: true, role: "viewer", maturity: "stable", budgetP99Ms: 100, audit: false, readOnly: true }, { name: "ops.health", group: "ops", method: "health", idempotent: true, role: "org_admin", maturity: "stable", budgetP99Ms: 500, audit: false, readOnly: false }, + { name: "ops.incidents", group: "ops", method: "incidents", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 250, audit: false, readOnly: true }, { name: "ops.projection_failures.list", group: "ops", method: "projectionFailuresList", idempotent: true, role: "org_admin", maturity: "experimental", budgetP99Ms: 300, audit: false, readOnly: false }, { name: "ops.projection_failures.resolve", group: "ops", method: "projectionFailuresResolve", idempotent: true, role: "org_admin", maturity: "experimental", budgetP99Ms: 500, audit: true, readOnly: false }, { name: "ops.projection_failures.retry", group: "ops", method: "projectionFailuresRetry", idempotent: true, role: "org_admin", maturity: "experimental", budgetP99Ms: 3000, audit: true, readOnly: false }, @@ -11918,4 +11939,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 379; +export const GENERATED_OP_COUNT = 380; diff --git a/server/code/app/answers.py b/server/code/app/answers.py index faec4212120..29b0c7756bd 100644 --- a/server/code/app/answers.py +++ b/server/code/app/answers.py @@ -53,6 +53,7 @@ from server.embedding.embedder import served_model_label from server.llm import customer from server.llm.traits import is_complete_stop +from server.observability import degradations from server.observability.genai import staged from server.settings import settings from server.settings.budgets import llm_max_tokens @@ -386,6 +387,7 @@ async def _expand_mechanism( return out except Exception as e: # noqa: BLE001 — expansion must never sink an answer logger.debug("mechanism expansion skipped: %s", e) + degradations.note("code_index", "mechanism_expansion_skipped", e, health=False) return [] @@ -404,6 +406,8 @@ async def _propose_identifiers(llm: Any, question: str) -> list[str]: return [t for t in terms if t.replace("_", "").replace("::", "").isalnum()][:6] except Exception as e: # noqa: BLE001 — expansion is best-effort logger.debug("identifier proposal skipped: %s", e) + # The model client counted its own failure in provider health. + degradations.note("llm", "identifier_expansion_skipped", e, health=False) return [] @@ -544,6 +548,7 @@ async def _inject_memory_context(question: str) -> MemoryContext: return MemoryContext() except Exception as e: # noqa: BLE001 — fail closed logger.debug("code.ask memory enrichment authorization failed: %s", e) + degradations.note("memory", "ask_context_dropped", e, health=False) return MemoryContext() shown = 3 # memory lines, one per key try: @@ -565,6 +570,7 @@ async def _inject_memory_context(question: str) -> MemoryContext: ) except Exception as e: # noqa: BLE001 — additive, never fatal logger.debug("code.ask memory enrichment failed: %s", e) + degradations.note("memory", "ask_context_dropped", e, health=False) return MemoryContext() if getattr(out, "abstain", False): return MemoryContext() diff --git a/server/code/app/coverage.py b/server/code/app/coverage.py index 0f95af5b0ed..30253fd23f7 100644 --- a/server/code/app/coverage.py +++ b/server/code/app/coverage.py @@ -50,6 +50,7 @@ from server.code.domain.index.test_gate import static_test_files from server.code.store.index import CodeRepo from server.core.errors import ValidationError +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -167,7 +168,8 @@ async def positive_control(repo: CodeRepo, org: str, ns: str) -> tuple[bool, str return cached[0], probe try: files, _total = await _grep_tests(repo, org, ns, cc.grep_pattern("symbol", probe), limit=3) - except Exception: # noqa: BLE001 — a failed control is a failed control + except Exception as e: # noqa: BLE001 — a failed control is a failed control + degradations.note("code_index", "coverage_control_unread", e, health=False) return False, probe _control_cache[(org, ns)] = (bool(files), probe, now) return bool(files), probe @@ -548,6 +550,7 @@ async def search_terms( ) except Exception as e: # noqa: BLE001 — the SQL names are an extra term, never the claim logger.info("coverage_claim: sql names read failed: %s", e) + degradations.note("code_index", "sql_name_terms_dropped", e, health=False) return terms for n in names: terms[n] = cc.EXACT_SCOPED @@ -718,6 +721,7 @@ async def _leg(coro: Any, what: str) -> list[dict[str, Any]]: return list(await coro) except Exception as e: # noqa: BLE001 — extra evidence, never the claim's failure logger.info("coverage_claim: %s leg failed: %s", what, e) + degradations.note("code_index", f"{what}_tests_dropped", e, health=False) return [] diff --git a/server/code/app/enrich.py b/server/code/app/enrich.py index 9a93240b47d..3c877ea6b0d 100644 --- a/server/code/app/enrich.py +++ b/server/code/app/enrich.py @@ -33,6 +33,7 @@ from server.code.domain.symbol_body import retained_source_window from server.code.store.index import CodeRepo from server.embedding.embedder import served_model_label +from server.observability import degradations from server.settings import settings if TYPE_CHECKING: @@ -111,6 +112,7 @@ async def bounded[T](coro: Awaitable[T], fallback: T, seconds: float | None = No ) except Exception as e: # noqa: BLE001 — enrichment degrades, never fails logger.debug("code enrich degraded: %s", e) + degradations.note("code_index", "enrichment_skipped", e, health=False) return fallback diff --git a/server/code/app/grep.py b/server/code/app/grep.py index 76f4cd3237c..8a03bba754a 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -63,6 +63,7 @@ from server.core.caller_regex import compile_caller_regex from server.core.ch import caller_shaped, class_timeout_s from server.core.errors import ValidationError +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -982,6 +983,7 @@ async def _extra_related_source( return None, {"partial": True, "partial_reason": f"{stage} timed out"} except Exception as error: # noqa: BLE001 — preserve exact evidence on optional read failure logger.debug("%s failed: %s", stage, type(error).__name__) + degradations.note("code_index", "related_source_dropped", error, health=False) return None, {"partial": True, "partial_reason": f"{stage} failed"} if batch and evidence is not None: bodies = await definitions_for( @@ -1141,9 +1143,9 @@ async def _grep_neighbours( entries, capped, tokens = await _attach_enclosing_neighbours( repo, org, ns, anchors, rows, input.neighbour_k ) - except Exception: - # A failed graph read leaves the grep hits intact. + except Exception as e: logger.warning("code.grep: neighbours block failed for %r", input.pattern, exc_info=True) + degradations.note("code_index", "neighbours_dropped", e, health=False) return [], False, 0, route return entries, capped, tokens, route + "+neighbours" diff --git a/server/code/app/pr_check.py b/server/code/app/pr_check.py index b1f59f99fbb..becb601acb1 100644 --- a/server/code/app/pr_check.py +++ b/server/code/app/pr_check.py @@ -22,6 +22,7 @@ from server.code.store.index import CodeRepo from server.core.datetimes import naive_utc_now from server.core.errors import ValidationError +from server.observability import degradations from server.settings import settings _GH_POOL = 400 @@ -83,6 +84,7 @@ async def _leg(status: dict[str, Any], name: str, coro: Any) -> list[dict[str, A rows = await coro except Exception as e: # noqa: BLE001 — a slow replica, a refused read status[name] = f"unavailable: {type(e).__name__}" + degradations.note("code_index", f"{name}_leg_dropped", e, health=False) return [] status[name] = len(rows) return list(rows) @@ -122,6 +124,7 @@ async def _merged_candidates( legs.setdefault(int(r["pr_number"]), set()).add("text") except Exception as e: # noqa: BLE001 — the leg reports unavailable status["merged_text"] = f"unavailable: {type(e).__name__}" + degradations.note("code_index", "merged_text_leg_dropped", e, health=False) if draft.issues: for r in await _leg( status, diff --git a/server/code/app/result_lessons.py b/server/code/app/result_lessons.py index 655679d0854..94b1aa3efd3 100644 --- a/server/code/app/result_lessons.py +++ b/server/code/app/result_lessons.py @@ -32,6 +32,7 @@ from server.core.ch import caller_shaped from server.identity.app import request_scope from server.memory.app import code_plane_reads, path_lessons +from server.observability import degradations from server.settings import settings Handler = Callable[[Any], Awaitable[Any]] @@ -154,6 +155,7 @@ async def scope() -> tuple[str, list[str], str, bool]: ) except Exception as e: # noqa: BLE001 — lesson enrichment must not fail the code answer logger.debug("code lessons skipped: %s", e) + degradations.note("code_lessons", "lessons_dropped", e, health=False) return path_lessons.Lessons([]) diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 7ebfd293a7b..9bebde78cd1 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -36,6 +36,7 @@ from server.code.store.index import CodeRepo from server.core.errors import ValidationError from server.memory.app.recall_credit import is_measurement_label +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -406,6 +407,7 @@ async def _open_head(repo: CodeRepo, org: str, ns: str, pr_number: int) -> tuple head = await history_bound.pull_head(repo, org, ns, git_dir, cfg.git_branch, pr_number) except Exception as e: # noqa: BLE001 — a head the mirror or the store cannot place is missing logger.warning("code.review_brief: head of open PR %s not placed: %s", pr_number, e) + degradations.note("git_mirror", "open_head_unread", e, health=False) head = "" return head, ("" if head else po.HEAD_NOT_IN_MIRROR) @@ -466,6 +468,7 @@ async def _build_open( ) except Exception as e: # noqa: BLE001 — a miss that cannot build is a miss logger.warning("code.review_brief: open build failed for PR %s: %s", pr_number, e) + degradations.note("code.review_brief", "brief_missing", e, health=False) return None @@ -518,6 +521,7 @@ async def _build_on_miss( ) except Exception as e: # noqa: BLE001 — a miss that cannot build is a miss logger.warning("code.review_brief: on-demand build failed for PR %s: %s", pr_number, e) + degradations.note("code.review_brief", "brief_missing", e, health=False) return None, "missing" return payload, source @@ -550,4 +554,5 @@ async def _mirror_facts( merge_sha[:12], e, ) + degradations.note("git_mirror", "brief_missing", e, health=False) return None diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index b664bcc00c4..f7aad834a1e 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -43,6 +43,7 @@ from server.identity.domain.read_scope import ReadFilters from server.llm import customer from server.memory.domain.rerank_names import BUILTIN_PICK +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -420,8 +421,9 @@ async def _annotate_served(res: Any, prefetch: Any, *, reserve: int) -> int: res.retrieval_work["risk_source"] = prefetch.source res.retrieval_work["risk_stale_units"] = prefetch.stale return spent - except Exception: + except Exception as e: logger.warning("code.search: risk annotation failed", exc_info=True) + degradations.note("code_index", "risk_unannotated", e, health=False) return 0 @@ -632,8 +634,9 @@ async def _serve_search_page( tokens += await code_risk.annotate_units( repo, org, ns, units, reserve_tokens=plan.reserve ) - except Exception: + except Exception as e: logger.warning("code.search page: risk annotation failed", exc_info=True) + degradations.note("code_index", "risk_unannotated", e, health=False) calib = dict(payload.get("calib") or {}) route = f"{payload.get('route') or 'hybrid'}+page" diff --git a/server/code/app/search/lexical.py b/server/code/app/search/lexical.py index 081baa636b8..e2e4ad44d7d 100644 --- a/server/code/app/search/lexical.py +++ b/server/code/app/search/lexical.py @@ -12,6 +12,7 @@ from server.code.domain.search_scope import SearchScope from server.code.store.index import CodeRepo from server.core import bm25 +from server.observability import degradations logger = logging.getLogger(__name__) @@ -66,6 +67,7 @@ async def _lexical_leg( span_attrs(sp, results=len(rows)) except Exception as e: # noqa: BLE001 — vector-only degrade logger.warning("code.search lexical leg failed: %s", e) + degradations.note("code_index", "lexical_leg_dropped", e, health=False) work["lexical_leg_failed"] = 1 return [], tokens, [] return rows, lex_tokens, idfs diff --git a/server/code/app/search/vector.py b/server/code/app/search/vector.py index 5a804bab442..92a4172cfef 100644 --- a/server/code/app/search/vector.py +++ b/server/code/app/search/vector.py @@ -13,6 +13,7 @@ from server.code.domain.search_scope import SearchScope from server.code.store.index import CodeRepo from server.llm import customer +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -163,6 +164,8 @@ async def _vector_leg_rows( raise except Exception as e: # noqa: BLE001 — lexical-only degrade logger.warning("code.search vector leg failed: %s", e) + # An embedder failure is already counted by the embedder's client. + degradations.note("code_index", "vector_leg_dropped", e, health=False) work["vector_leg_failed"] = 1 span_attrs(sp, results=len(rows)) return rows, qvec diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index 2fc24b9a6a7..fb92db9854d 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -16,6 +16,7 @@ from server.code.domain.index.epistemic import Envelope, scip_coverage_from_rows from server.code.domain.index.verdicts import GRAPHED_LANGS as _GRAPHED_LANGS from server.code.store.index import CodeRepo +from server.observability import degradations logger = logging.getLogger(__name__) @@ -28,6 +29,7 @@ async def _declined_safe( return await _declined_calls_for(repo, org, ns, seeds) except Exception as e: # noqa: BLE001 logger.debug("declined-call lookup skipped: %s", e) + degradations.note("code_index", "declined_calls_uncounted", e, health=False) return 0, 0 @@ -46,6 +48,7 @@ async def _declined_outgoing_safe( by_path = await repo.live_call_misses_for_paths(org, ns, paths) except Exception as e: # noqa: BLE001 — a disclosure read; the walk stands logger.debug("outgoing declined-call lookup skipped: %s", e) + degradations.note("code_index", "declined_calls_uncounted", e, health=False) return 0, 0 unresolved = ambiguous = 0 for path, rows in by_path.items(): @@ -73,6 +76,7 @@ async def _scip_coverage( covered |= await repo.scip_covered_paths(org, ns, remaining) except Exception as e: # noqa: BLE001 logger.debug("scip coverage read skipped: %s", e) + degradations.note("code_index", "compiler_coverage_unread", e, health=False) return covered @@ -87,6 +91,7 @@ async def _scip_stale(repo: CodeRepo, org: str, ns: str, edges: list[Any]) -> se return await repo.scip_stale_paths(org, ns, paths) except Exception as e: # noqa: BLE001 — a freshness read must not fail the walk logger.debug("scip staleness read skipped: %s", e) + degradations.note("code_index", "compiler_freshness_unread", e, health=False) return set(paths) @@ -121,6 +126,7 @@ async def _unindexed_paths(repo: CodeRepo, org: str, ns: str, bare: list[str]) - return set(bare) - await repo.live_paths_present(org, ns, bare) except Exception as e: # noqa: BLE001 logger.debug("indexed-paths read skipped: %s", e) + degradations.note("code_index", "indexed_paths_unread", e, health=False) return set(bare) @@ -166,7 +172,8 @@ async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, edge_stamp = state_value(state, "extractor_stamp_edge") ts_ok = bool(edge_stamp) and edge_stamp == stage_stamps()["edge"] cov = (scip_ok, ts_ok) - except Exception: # noqa: BLE001 — fail closed: an error can only lower an answer + except Exception as e: # noqa: BLE001 — fail closed: an error can only lower an answer + degradations.note("code_index", "constructor_coverage_unread", e, health=False) cov, ttl = (False, False), PROBE_ERROR_TTL_S _CTOR_CACHE.put((org, ns), cov, ttl_s=ttl) return cov diff --git a/server/code/app/symbol/dispatch.py b/server/code/app/symbol/dispatch.py index e986d466e9b..6b1db7fadf5 100644 --- a/server/code/app/symbol/dispatch.py +++ b/server/code/app/symbol/dispatch.py @@ -10,6 +10,7 @@ from server.code.app.candidates import overrides_of from server.code.app.ttl_cache import TtlCache from server.code.store.index import CodeRepo +from server.observability import degradations async def _widen_dispatch( @@ -186,7 +187,8 @@ async def _dispatch_seeds( edge_kinds=["overrides"], limit=10, ) - except Exception: # noqa: BLE001 + except Exception as err: # noqa: BLE001 — the walk goes on without the exact edges + degradations.note("code_index", "override_edges_unread", err, health=False) ov = [] exact = False for e in ov: @@ -239,7 +241,8 @@ async def _dispatch_seeds( if b and b not in bases: bases.append(b) frontier.append(str(e["to_symbol_id"])) - except Exception: # noqa: BLE001 — hierarchy is best-effort + except Exception as err: # noqa: BLE001 — hierarchy is best-effort + degradations.note("code_index", "inherited_dispatch_dropped", err, health=False) bases = [] for b in bases: for r in await repo.symbols_by_name(org, ns, f"{b}::{method}", limit=3): diff --git a/server/code/app/symbol/hierarchy.py b/server/code/app/symbol/hierarchy.py index 8eb9cf92256..96ab1d1f007 100644 --- a/server/code/app/symbol/hierarchy.py +++ b/server/code/app/symbol/hierarchy.py @@ -9,6 +9,7 @@ from server.code.app.symbol.resolve import _seed_ids_of from server.code.store.index import CodeRepo from server.code.store.index import prefer_scip_edges as _prefer_scip_edges +from server.observability import degradations logger = logging.getLogger(__name__) @@ -77,6 +78,7 @@ async def _symbol_hierarchy( return await _hierarchy_of(repo, org, ns, seeds) except Exception as e: # noqa: BLE001 — a failed side read never fails the definition logger.warning("code.symbol hierarchy read failed: %s", e) + degradations.note("code_index", "hierarchy_dropped", e, health=False) return {} diff --git a/server/code/app/symbol/neighbours.py b/server/code/app/symbol/neighbours.py index 942f1a970f1..118407e854a 100644 --- a/server/code/app/symbol/neighbours.py +++ b/server/code/app/symbol/neighbours.py @@ -17,6 +17,7 @@ from server.code.domain.index.epistemic import classify from server.code.store.index import CodeRepo from server.code.store.index import prefer_scip_edges as _prefer_scip_edges +from server.observability import degradations logger = logging.getLogger(__name__) @@ -129,6 +130,7 @@ async def _soft(coro: Any, default: Any) -> Any: return await coro except Exception as e: # noqa: BLE001 — additive block, the definitions still ship logger.debug("code neighbour/enrichment read skipped: %s", e) + degradations.note("code_index", "neighbour_block_dropped", e, health=False) return default diff --git a/server/code/app/symbol/symbol.py b/server/code/app/symbol/symbol.py index 811992fab0a..b604c6da7bc 100644 --- a/server/code/app/symbol/symbol.py +++ b/server/code/app/symbol/symbol.py @@ -59,6 +59,7 @@ from server.code.store.index import CodeRepo from server.core.errors import ValidationError from server.identity.app.request_scope import request_narrowed +from server.observability import degradations from server.observability.budget_shape import note_budget_shape if TYPE_CHECKING: @@ -101,8 +102,9 @@ async def _symbol_neighbours( entries, _capped, tokens = await _attach_enclosing_neighbours( repo, org, ns, anchors, rows, input.neighbour_k ) - except Exception: + except Exception as e: logger.warning("code.symbol: neighbours block failed for %r", input.name, exc_info=True) + degradations.note("code_index", "neighbours_dropped", e, health=False) return [], 0 return entries, tokens @@ -149,8 +151,9 @@ def sub_for(dep: str) -> CodeSymbolInput: row_of=code_presence._symbol_row, op="code.symbol", ) - except Exception: + except Exception as e: logger.info("code.symbol: dependency presence declined for %s/%s", org, ns, exc_info=True) + degradations.note("code_index", "dependency_presence_unread", e, health=False) return [], {} return rows, code_presence.summarize(rows) diff --git a/server/identity/domain/read_scope.py b/server/identity/domain/read_scope.py index 36db3b4d644..59c810c0fa6 100644 --- a/server/identity/domain/read_scope.py +++ b/server/identity/domain/read_scope.py @@ -409,6 +409,7 @@ def pin_read_filters[M: BaseModel](input: M, auth: Any) -> tuple[M, bool]: # other users' memory keys and payloads. "ops.capabilities": "the deployment's capabilities", "ops.health": "deployment health", + "ops.incidents": "the deployment's incidents and the org's request failure counts, no memory", "mentor.guide": "the deployment's static agent guide, no memory", "help.search": "the deployment's shipped documentation, no memory", "help.get": "the deployment's shipped documentation, no memory", diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 2fa56a5b2fd..094b1631d77 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -157,3 +157,47 @@ class OpsCapabilitiesOutput(BaseModel): # Every field of every request model that names the consumer — the # tag stored on every ledger row. consumer_field: str = "consumer" + + +# ============================================================ +# ops.incidents — what is failing now, for any caller +# ============================================================ + + +class OpsIncidentsInput(BaseModel): + """Whether Loom is degraded now: failing readiness checks, providers and workers, and + the org's calls failing on the server. Identity is optional: the org is the token's + (role check only; no namespace is addressed).""" + + org: str = "" + + +class OpsIncident(BaseModel): + # `readiness` (a check this server must pass to take traffic, such as `clickhouse`), + # `provider` (an embedder, model, reranker or other dependency whose last call this + # server made failed), `worker` (a background loop with failed passes in a row) or + # `requests` (the org's calls of one SLO class failing on the server's side). + kind: Literal["readiness", "provider", "worker", "requests"] + # Which one: the readiness check, the provider, the worker or the SLO class + # (`code`, `search`, `read`, `write`, `admin`). + subject: str + # `error` when calls fail or answer without the part that failed; `warn` when + # answers are thinner or staler than normal. + severity: Literal["warn", "error"] + # What is failing, in one line: an error's kind, never its text. + detail: str + # Seconds since the failure was last seen; null when its source keeps no time. + age_s: float | None = None + + +class OpsIncidentsOutput(BaseModel): + """The deployment's current incidents, as the server that answers sees them. A + client polls it, through `loom_op` over MCP, to tell a Loom outage from an empty + answer. Nothing here names another org.""" + + # `degraded` when an incident is listed, else `ok`. + status: Literal["ok", "degraded"] + # Errors first, at most 20. + incidents: list[OpsIncident] = Field(default_factory=list) + # Minutes of history a `provider` or `requests` incident reads. + window_minutes: int diff --git a/server/insights/api/ops_ops.py b/server/insights/api/ops_ops.py index dc3055e22d2..c537f8efef1 100644 --- a/server/insights/api/ops_ops.py +++ b/server/insights/api/ops_ops.py @@ -7,6 +7,8 @@ OpsCapabilitiesOutput, OpsHealthInput, OpsHealthOutput, + OpsIncidentsInput, + OpsIncidentsOutput, ProjectionFailureListInput, ProjectionFailureListOutput, ProjectionFailureResolveInput, @@ -14,6 +16,7 @@ ProjectionFailureRetryInput, ProjectionFailureRetryOutput, ) +from server.insights.app.incidents import handle_ops_incidents from server.insights.app.ops import ( handle_ops_capabilities, handle_ops_health, @@ -48,6 +51,22 @@ ) +# Any caller polls it to tell a Loom incident from an empty answer: a viewer anywhere in +# the org, a scoped token on its best namespace role. +ops_incidents = Operation( + name="ops.incidents", + maturity="experimental", + input_model=OpsIncidentsInput, + output_model=OpsIncidentsOutput, + handler=handle_ops_incidents, + idempotent=True, + required_role=Role.VIEWER, + audit=False, + skip_namespace_authz=True, + deployment_scoped=True, +) + + projection_failures_list = Operation( name="ops.projection_failures.list", maturity="experimental", @@ -88,6 +107,7 @@ OPERATIONS = [ ops_capabilities, ops_health, + ops_incidents, projection_failures_list, projection_failures_resolve, projection_failures_retry, diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py new file mode 100644 index 00000000000..c1eaaa904a7 --- /dev/null +++ b/server/insights/app/incidents.py @@ -0,0 +1,151 @@ +"""ops.incidents: what is failing now, for any caller to poll. + +A client that gets errors, or answers it cannot trust, asks here whether Loom is in an +incident. The answer comes from what the server already keeps: its readiness checks, +the outcome of the provider calls it made (`provider_health`), the workers' failure +streaks (`loom.worker_status`) and the caller's org's request failures +(`loom_telemetry.sli_minute`). Nothing names another org: a provider or worker incident +carries an error's kind, never its text, and the request counts are the caller's org's. +A source that cannot be read within a readiness check's bound +(`readiness_check_timeout_s`) is named in the answer's `degraded`; the others still +answer, so the op answers during a ClickHouse outage too. +""" + +from __future__ import annotations + +import asyncio +from datetime import UTC, datetime +from typing import Any + +from server.insights.api.models_ops import OpsIncident, OpsIncidentsInput, OpsIncidentsOutput +from server.insights.store import ops as ops_store +from server.observability import degradations, provider_health +from server.settings import settings + +# not a setting: the bound the output model documents +MAX_INCIDENTS = 20 +# not a setting: a day holds the last pass of every worker that runs at least daily +_WORKER_SCAN_HOURS = 24 + + +def _line(text: object) -> str: + return " ".join(str(text).split())[:200] + + +async def _readiness() -> list[OpsIncident]: + """A failing readiness check: required ones stop this server taking traffic.""" + from server.core import readiness + + try: + state = await readiness.evaluate() + except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer + degradations.note("ops.incidents", "readiness_unread", e, health=False) + return [] + return [ + OpsIncident( + kind="readiness", + subject=name, + severity="error" if name in state.required else "warn", + detail=_line(check.reason or "failing"), + ) + for name, check in state.checks.items() + if not check.ok + ] + + +def _providers(window_s: float) -> list[OpsIncident]: + """A provider whose last call this server made failed within the window. `/v1/health` + shows the same entries without a token, so the detail is what it shows.""" + out: list[OpsIncident] = [] + for name, entry in provider_health.status()["providers"].items(): + age = entry.get("last_error_age_s") + if not entry.get("failing") or age is None or age > window_s: + continue + out.append( + OpsIncident( + kind="provider", + subject=str(name), + severity="warn", + detail=_line(entry.get("last_error") or "failing"), + age_s=age, + ) + ) + return out + + +def _age_s(value: Any) -> float | None: + if not isinstance(value, datetime) or value.year < 2000: + return None + at = value if value.tzinfo else value.replace(tzinfo=UTC) + return round(max(0.0, (datetime.now(UTC) - at).total_seconds()), 1) + + +async def _workers() -> list[OpsIncident]: + """A worker whose freshest pass left a failure streak at the supervisor's alert + threshold, from whichever process ran it.""" + from server.workers import status_store + from server.workers.supervisor import _ALERT_THRESHOLD + + try: + async with asyncio.timeout(settings.readiness_check_timeout_s): + rows = await status_store.failing_streaks(_ALERT_THRESHOLD, _WORKER_SCAN_HOURS) + except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer + degradations.note("ops.incidents", "workers_unread", e, health=False) + return [] + out: list[OpsIncident] = [] + for r in rows: + streak = int(r.get("consecutive_failures") or 0) + kind = str(r.get("error_class") or "") + out.append( + OpsIncident( + kind="worker", + subject=str(r.get("worker") or ""), + severity="warn", + detail=_line(f"{streak} failed passes in a row" + (f" ({kind})" if kind else "")), + age_s=_age_s(r.get("last_finished")), + ) + ) + return out + + +async def _requests(org: str, minutes: int) -> list[OpsIncident]: + """An SLO class of the org's calls whose server-side failures reach the share.""" + if not org or org == "*": + return [] # no single org to read: an org-wide token that named none + try: + async with asyncio.timeout(settings.readiness_check_timeout_s): + rows = await ops_store.request_errors_by_class(org, minutes) + except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer + degradations.note("ops.incidents", "requests_unread", e, health=False) + return [] + out: list[OpsIncident] = [] + for r in rows: + total, failed = int(r.get("requests") or 0), int(r.get("server_errors") or 0) + if total < settings.ops_incidents_min_requests: + continue + if failed / total < settings.ops_incidents_error_share: + continue + out.append( + OpsIncident( + kind="requests", + subject=str(r.get("slo_class") or ""), + severity="error", + detail=f"{failed} of {total} calls failed on the server in {minutes} min", + ) + ) + return out + + +async def handle_ops_incidents(input: OpsIncidentsInput) -> OpsIncidentsOutput: + """The current incidents, errors first.""" + minutes = settings.ops_incidents_window_minutes + ready, workers, requests = await asyncio.gather( + _readiness(), _workers(), _requests(input.org, minutes) + ) + incidents = [*ready, *_providers(minutes * 60.0), *workers, *requests] + incidents.sort(key=lambda i: (i.severity != "error", i.kind, i.subject)) + return OpsIncidentsOutput( + status="degraded" if incidents else "ok", + incidents=incidents[:MAX_INCIDENTS], + window_minutes=minutes, + ) diff --git a/server/insights/store/ops.py b/server/insights/store/ops.py index e810827e5d0..26e4ef3a80a 100644 --- a/server/insights/store/ops.py +++ b/server/insights/store/ops.py @@ -101,3 +101,27 @@ async def memory_op_counts( params=params, ) ) + + +async def request_errors_by_class( + org: str, minutes: int, *, ch: _CHClient | None = None +) -> list[dict[str, Any]]: + """The org's requests and server-side failures per SLO class over the last + `minutes`, from the SLI rollup (`slo_class != ''` leaves out its resume marks). The + rollup trails the ledger by one to two minutes.""" + ch = ch or _default_client() + return list( + await ch.query_all( + """ + SELECT slo_class, sum(requests) AS requests, sum(server_errors) AS server_errors + FROM loom_telemetry.sli_minute + WHERE slo_class != '' + AND minute >= toStartOfMinute(now() - toIntervalMinute({minutes:UInt32})) + AND org = {org:String} + GROUP BY slo_class + ORDER BY slo_class + LIMIT 16 + """, + params={"org": org, "minutes": int(minutes)}, + ) + ) diff --git a/server/observability/degradations.py b/server/observability/degradations.py index 751a949694c..38b366394e2 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -7,12 +7,14 @@ is indistinguishable from the normal one. This module makes the fallback visible on the response. A provider that -falls back calls `note(provider, effect, reason)`; the handler reads -`current()` into the output's `degraded` list. The transport binds a fresh -list per op next to the cost accumulator, so notes never leak across -requests. Bounded, never raises, and a note also feeds `provider_health` -(unless it passes `health=False`: a fallback that is no provider's) so the -/v1/health flag agrees with the responses. +falls back, or a handler that serves a partial read, calls +`note(provider, effect, reason)`; both transports put the request's notes on +every op response as `degraded` (`on_response`), so a handler only notes. The +transport binds a fresh list per op next to the cost accumulator, so notes +never leak across requests. Bounded, never raises, and a note also feeds +`provider_health` (unless it passes `health=False`: a fallback that is no +provider's, or a store read whose failure the provider's own client already +counted) so the /v1/health flag agrees with the responses. degraded: ["classify: caller_type_kept (HTTPStatusError)", "rerank: input_order_kept (ReadTimeout)"] @@ -22,6 +24,7 @@ import contextvars import logging +from typing import Any from server.core.errors import caller_text @@ -85,4 +88,21 @@ def current() -> list[str]: return list(lst) if lst else [] -__all__ = ["begin", "current", "note"] +def on_response(body: Any) -> Any: + """`body` (a dumped op result) with `degraded`: the op's own notes first (an output + that declares the field), then this request's, each once. A response nothing + degraded carries no `degraded` key, so a client tests for the key. A non-dict + result, or one whose `degraded` is not a list, is returned as it is.""" + if not isinstance(body, dict): + return body + own = body.get("degraded", []) + if not isinstance(own, list): + return body + notes = [str(n) for n in own] + notes += [n for n in current() if n not in notes] + if notes: + return {**body, "degraded": notes} + return {k: v for k, v in body.items() if k != "degraded"} if "degraded" in body else body + + +__all__ = ["begin", "current", "note", "on_response"] diff --git a/server/operations/dashboard.py b/server/operations/dashboard.py index b842ff826a9..45742b9d3d0 100644 --- a/server/operations/dashboard.py +++ b/server/operations/dashboard.py @@ -177,6 +177,8 @@ def _named_once(*groups: dict[str, str]) -> dict[str, str]: "observe.crystallize", "observe.record", "ops.capabilities", + # The dashboard's Health view reads /v1/health, which carries the same signals. + "ops.incidents", ), CLIENT_CALL, ), diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index df5e640e8f2..0bcac3bac4a 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -974,6 +974,7 @@ "sdk_method", "dashboard", ), + "ops.incidents": ("sdk_method",), "ops.projection_failures.list": ( "sdk_method", "dashboard", diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 545d66d279d..689e3c622ca 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -4462,6 +4462,14 @@ class ObservabilitySettings(BaseModel): # Pairs the `procedure_plane` check measures success retention over before its # warning can fire. ops_procedure_plane_min_pairs: int = 20 + # Minutes of history ops.incidents reads: a provider failure seen within them, and + # the caller's org's request failures over them. + ops_incidents_window_minutes: int = Field(default=15, ge=1, le=1440) + # Share (0-1) of the org's requests of one SLO class that failed on the server's + # side, over the window, at which ops.incidents lists a `requests` incident. + ops_incidents_error_share: float = Field(default=0.1, gt=0, le=1) + # Requests of one SLO class in the window before ops.incidents judges its share. + ops_incidents_min_requests: int = Field(default=20, ge=1) # Periodic re-hash of audit rows; a mismatch writes `audit.tamper_detected`. # Per-row detection, not a hash chain (see server/observability/audit.py). audit_verifier_enabled: bool = True @@ -6798,6 +6806,7 @@ class TrackerSettings(BaseModel): "observe.record": 150, "ops.capabilities": 100, "ops.health": 500, + "ops.incidents": 250, "ops.projection_failures.list": 300, "ops.projection_failures.resolve": 500, "ops.projection_failures.retry": 3000, diff --git a/server/transport/arg_check.py b/server/transport/arg_check.py index edb8c8a2d0f..6a8cb0b6fbd 100644 --- a/server/transport/arg_check.py +++ b/server/transport/arg_check.py @@ -230,8 +230,10 @@ def _note(op_name: str, keys: list[str]) -> None: def response_body(op: Any, args: Any, result: Any) -> Any: """The dumped result a transport returns, with `ignored_args` / - `did_you_mean` when the call carried keys the op does not read.""" + `did_you_mean` when the call carried keys the op does not read, and `degraded` + when the request served a fallback or a partial read.""" from server.core.request_work import flag_response + from server.observability.degradations import on_response from server.transport.epoch_nulls import scrub body = result.model_dump(mode="json") if hasattr(result, "model_dump") else result @@ -239,7 +241,7 @@ def response_body(op: Any, args: Any, result: Any) -> Any: block = ignored_block(op, args) if block: _note(op.name, block["ignored_args"]) - body = attach(body, block) + body = on_response(attach(body, block)) return flag_response(body) if isinstance(body, dict) else body diff --git a/server/transport/lean_results.py b/server/transport/lean_results.py index 9d08582c697..8279c8064df 100644 --- a/server/transport/lean_results.py +++ b/server/transport/lean_results.py @@ -19,6 +19,7 @@ from collections.abc import Callable from typing import Any +from server.observability.degradations import on_response from server.transport.assistant_call import assistant_call # Ranking and accounting detail the model never acts on. `explanation` is @@ -56,6 +57,8 @@ "triples_matched", "set_expansion_phrases", "top_k_ceiling", + # An output's or a section's own copy: the transport puts the request's + # notes back at the top (`mcp_op_result`). "degraded", "pending_extraction", "derived_aggregate", @@ -271,7 +274,9 @@ def mcp_op_result( candidates = {"loom_code_read", "loom_code_edit_context"} followups = frozenset(candidates.intersection(listed_tool_names(toolset))) out = lean_code(op_name, out, arguments, followups=followups) - out = _with_ignored_args(op_name, out, arguments) + # The request's fallbacks at the top, after the lean pass dropped the copies an + # output or its sections carry (`DIAGNOSTIC_KEYS`). + out = on_response(_with_ignored_args(op_name, out, arguments)) if hint is not None and isinstance(out, dict): if hint[1] not in str(out.get("rendered") or ""): # A key, never a prose prefix: content[0].text stays parseable JSON. diff --git a/server/transport/mcp_outcome.py b/server/transport/mcp_outcome.py index aa07bf36deb..7922d586035 100644 --- a/server/transport/mcp_outcome.py +++ b/server/transport/mcp_outcome.py @@ -12,7 +12,7 @@ from server.core import llm_free, request_work from server.core.naming import present -from server.observability import genai +from server.observability import degradations, genai from server.transport._common import ledger_identity from server.transport.lean_results import mcp_op_result from server.transport.mcp_config import TOOL_EXEC_FAILED, _err, _ok @@ -97,9 +97,11 @@ def _search_answer(call: _AdmittedCall, result: Any) -> dict[str, Any]: from server.transport.mcp_tools import search_answer answer = search_answer(result.model_dump(), call.arguments, call.rl_ns, call.mcp_session_id) - answer["structuredContent"] = request_work.flag_response( - _coerce_bigints(answer["structuredContent"]) - ) + structured = degradations.on_response(_coerce_bigints(answer["structuredContent"])) + answer["structuredContent"] = request_work.flag_response(structured) + if notes := structured.get("degraded"): + # The text summary a client reads first says so too. + answer["content"][0]["text"] += "\nDegraded: " + "; ".join(notes) + "." if request_work.mirror_marked(): answer["content"] = [ {"type": "text", "text": json.dumps({"mirrored": True})}, @@ -123,7 +125,8 @@ async def _success_response( req_id, op, input_obj, arguments = call.req_id, call.op, call.input_obj, call.arguments auth, request_id, rl_ns, rl_org = call.auth, call.request_id, call.rl_ns, call.rl_org result_dict = result.model_dump(mode="json") if hasattr(result, "model_dump") else result - result_dict = _coerce_bigints(result_dict) + # `degraded` rides the stored replay and the `explain` shape as HTTP's body carries it. + result_dict = degradations.on_response(_coerce_bigints(result_dict)) if isinstance(result_dict, dict): result_dict = request_work.flag_response(result_dict) diff --git a/server/workers/status_store.py b/server/workers/status_store.py index 3f171729dfd..97e5b866453 100644 --- a/server/workers/status_store.py +++ b/server/workers/status_store.py @@ -594,6 +594,40 @@ async def pass_summaries(prefix: str, days: int, *, ch: Any = None) -> list[dict return list(await client.query_all(PASS_SUMMARY_SQL, {"prefix": prefix, "days": int(days)})) +# The workers whose freshest pass within the window, from whichever process ran it, +# left a failure streak of at least {min_failures}: the class of its last error, never +# its text or namespace, which can name an org. +FAILING_STREAKS_SQL = f""" +SELECT worker, + argMax(failures, finished) AS consecutive_failures, + argMax(error_class, finished) AS error_class, + max(finished) AS last_finished +FROM ( + SELECT worker, instance_label, + argMax(consecutive_failures, version) AS failures, + argMax(error_class, version) AS error_class, + argMax(pass_finished, version) AS finished + FROM {TABLE} + WHERE pass_started > now() - toIntervalHour({{hours:UInt32}}) + GROUP BY worker, instance_label +) +GROUP BY worker +HAVING consecutive_failures >= {{min_failures:UInt32}} +ORDER BY worker +LIMIT 50 +""" + + +async def failing_streaks(min_failures: int, hours: int, *, ch: Any = None) -> list[dict[str, Any]]: + """`FAILING_STREAKS_SQL` rows. Raises what the read raises.""" + client = ch if ch is not None else _client() + return list( + await client.query_all( + FAILING_STREAKS_SQL, {"min_failures": int(min_failures), "hours": int(hours)} + ) + ) + + # --------------------------------------------------------------------------- merge diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 20e3b348e5f..60344ad1512 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -1058,6 +1058,9 @@ "oidc_jit_org": "", "oidc_jit_provision": false, "openai_base_url": "https://api.openai.com/v1", + "ops_incidents_error_share": 0.1, + "ops_incidents_min_requests": 20, + "ops_incidents_window_minutes": 15, "ops_op_mix_min_writes": 500, "ops_op_mix_reads_per_write_warn": 20.0, "ops_op_mix_update_share_warn": 0.01, diff --git a/tests/unit/test_code_read_degradations.py b/tests/unit/test_code_read_degradations.py new file mode 100644 index 00000000000..f3c15ea81ad --- /dev/null +++ b/tests/unit/test_code_read_degradations.py @@ -0,0 +1,62 @@ +"""A code read that serves a partial answer because a read failed says so in `degraded`, +and leaves provider health alone: the store's failure is no provider's.""" + +from __future__ import annotations + +import asyncio +from typing import Any + +import pytest + +from server.observability import degradations, provider_health + + +@pytest.fixture(autouse=True) +def _clean(): + degradations.begin() + provider_health.reset() + yield + provider_health.reset() + + +class _FailingRepo: + """Every read the index would answer raises, as an unreachable replica does.""" + + def __getattr__(self, name: str) -> Any: + async def _fail(*_a: Any, **_k: Any) -> Any: + raise ConnectionError("replica gone") + + return _fail + + +@pytest.mark.asyncio +async def test_an_uncounted_declined_call_is_noted_not_read_as_zero() -> None: + from server.code.app.symbol.coverage import _declined_outgoing_safe + + seeds = [{"path": "src/a.cpp", "qualified_name": "A::f"}] + assert await _declined_outgoing_safe(_FailingRepo(), "o", "n", seeds) == (0, 0) # type: ignore[arg-type] + assert degradations.current() == ["code_index: declined_calls_uncounted (ConnectionError)"] + assert provider_health.status()["providers"] == {} + + +@pytest.mark.asyncio +async def test_an_enrichment_cut_by_its_bound_is_noted() -> None: + from server.code.app.enrich import bounded + + async def _slow() -> list[int]: + await asyncio.sleep(1) + return [1] + + assert await bounded(_slow(), [], seconds=0.001) == [] + assert degradations.current() == ["code_index: enrichment_skipped (TimeoutError)"] + + +@pytest.mark.asyncio +async def test_a_dropped_coverage_leg_names_the_leg() -> None: + from server.code.app.coverage import _leg + + async def _boom() -> list[dict[str, Any]]: + raise ConnectionError("replica gone") + + assert await _leg(_boom(), "calls") == [] + assert degradations.current() == ["code_index: calls_tests_dropped (ConnectionError)"] diff --git a/tests/unit/test_degradations.py b/tests/unit/test_degradations.py index 7d7ff15a6e4..3cb8f61e8a1 100644 --- a/tests/unit/test_degradations.py +++ b/tests/unit/test_degradations.py @@ -181,3 +181,63 @@ def test_output_models_carry_degraded(): .degraded[0] .startswith("classify") ) + + +def test_on_response_puts_the_requests_notes_after_the_ops_own_each_once(): + D.begin() + assert D.on_response({"found": True}) == {"found": True} # nothing degraded: no key + assert D.on_response({"found": True, "degraded": []}) == {"found": True} + D.note("rerank", "input_order_kept", "x", health=False) + D.note("code_index", "risk_unannotated", "y", health=False) + body = {"version": 1, "degraded": ["rerank: input_order_kept (x)"]} + assert D.on_response(body)["degraded"] == [ + "rerank: input_order_kept (x)", + "code_index: risk_unannotated (y)", + ] + assert D.on_response(["a list"]) == ["a list"] # a non-dict result passes as it is + + +def test_every_op_response_carries_the_requests_notes_on_both_transports(): + """An op whose output declares no `degraded` (memory.get) answers it on HTTP's body and + on MCP's lean result; the lean pass drops a section's own copy, not the top one.""" + from server.memory.api.models_crud import MemoryGetOutput + from server.operations.registry import OPERATIONS_BY_NAME + from server.transport.arg_check import response_body + from server.transport.lean_results import mcp_op_result + + op = OPERATIONS_BY_NAME["memory.get"] + D.begin() + assert "degraded" not in response_body(op, {}, MemoryGetOutput(found=False)) + assert "degraded" not in mcp_op_result("memory.get", {"found": False}, {}, None) + + D.note("memory.webhook", "not_announced", "z", health=False) + assert response_body(op, {}, MemoryGetOutput(found=False))["degraded"] == [ + "memory.webhook: not_announced (z)" + ] + nested = {"found": False, "section": {"degraded": ["inner"], "n": 1}} + lean = mcp_op_result("memory.get", nested, {}, None) + assert lean["degraded"] == ["memory.webhook: not_announced (z)"] + assert lean["section"] == {"n": 1} + + +def test_loom_search_says_degraded_in_its_text_and_its_structured_result(): + from types import SimpleNamespace + + from server.memory.api.models_search import MemorySearchOutput + from server.transport.mcp_outcome import _search_answer + + memory = MemorySearchOutput(results=[], embedding_model="m").model_dump() + payload = {"memory": memory, "knowledge": {}, "profile": {}, "conversations": {}} + result = SimpleNamespace(model_dump=lambda: payload) + call = SimpleNamespace(arguments={"query": "q"}, rl_ns="team", mcp_session_id="") + D.begin() + clean = _search_answer(call, result) # type: ignore[arg-type] + assert "degraded" not in clean["structuredContent"] + assert "Degraded" not in clean["content"][0]["text"] + + D.note("rerank", "input_order_kept", "ReadTimeout", health=False) + answer = _search_answer(call, result) # type: ignore[arg-type] + assert answer["structuredContent"]["degraded"] == ["rerank: input_order_kept (ReadTimeout)"] + assert answer["content"][0]["text"].endswith( + "\nDegraded: rerank: input_order_kept (ReadTimeout)." + ) diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py new file mode 100644 index 00000000000..0d1859a0ce0 --- /dev/null +++ b/tests/unit/test_ops_incidents.py @@ -0,0 +1,148 @@ +"""ops.incidents: the current incidents from readiness, provider health, worker streaks +and the org's request failures; an unread source is named in `degraded`, never a 500.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +import pytest + +from server.core import readiness +from server.insights.api.models_ops import OpsIncidentsInput +from server.insights.app.incidents import handle_ops_incidents +from server.observability import degradations, provider_health +from server.operations.base import Role +from server.operations.registry import OPERATIONS_BY_NAME +from server.settings import settings +from tests.unit.ch_fake import RecordingCH, server_error + + +@pytest.fixture(autouse=True) +def _clean(monkeypatch: pytest.MonkeyPatch): + monkeypatch.setattr(readiness, "_CHECKS", {}) + monkeypatch.setattr(readiness, "_draining", False) + provider_health.reset() + degradations.begin() + yield + provider_health.reset() + + +def _ch(monkeypatch: pytest.MonkeyPatch, *, workers=(), sli=()) -> RecordingCH: + ch = RecordingCH().on("loom.worker_status", list(workers)).on("sli_minute", list(sli)) + return ch.install(monkeypatch) + + +@pytest.mark.asyncio +async def test_a_healthy_deployment_answers_ok_with_no_incident(monkeypatch) -> None: + ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 500, "server_errors": 3}]) + + out = await handle_ops_incidents(OpsIncidentsInput(org="acme")) + + assert (out.status, out.incidents) == ("ok", []) + assert out.window_minutes == settings.ops_incidents_window_minutes + assert degradations.current() == [] + (sli,) = ch.statements("sli_minute") + assert sli.params["org"] == "acme" # the caller's org only + + +@pytest.mark.asyncio +async def test_each_source_lists_its_incident_errors_first(monkeypatch) -> None: + readiness.register("clickhouse", lambda: readiness.result(False, "no answer within 2 s")) + readiness.register( + "code_registry", lambda: readiness.result(False, "registry unread"), required=False + ) + provider_health.record_failure("embedding:openai", "ReadTimeout") + provider_health.record_failure("rerank", "input_order_kept") + provider_health.record_success("rerank") # recovered: not an incident + finished = datetime.now(UTC).replace(tzinfo=None) - timedelta(minutes=4) + _ch( + monkeypatch, + workers=[ + { + "worker": "embedding_worker", + "consecutive_failures": 5, + "error_class": "DatabaseError", + "last_finished": finished, + } + ], + sli=[ + {"slo_class": "code", "requests": 1618, "server_errors": 1618}, + {"slo_class": "read", "requests": 200, "server_errors": 2}, # under the share + {"slo_class": "write", "requests": 5, "server_errors": 5}, # under the floor + ], + ) + + out = await handle_ops_incidents(OpsIncidentsInput(org="acme")) + + assert out.status == "degraded" + got = [(i.kind, i.subject, i.severity) for i in out.incidents] + assert got == [ + ("readiness", "clickhouse", "error"), + ("requests", "code", "error"), + ("provider", "embedding:openai", "warn"), + ("readiness", "code_registry", "warn"), + ("worker", "embedding_worker", "warn"), + ] + by = {i.subject: i for i in out.incidents} + assert by["clickhouse"].detail == "no answer within 2 s" + assert ( + by["code"].detail == f"1618 of 1618 calls failed on the server in {out.window_minutes} min" + ) + assert by["embedding:openai"].detail == "ReadTimeout" + assert by["embedding_worker"].detail == "5 failed passes in a row (DatabaseError)" + assert 230 <= (by["embedding_worker"].age_s or 0) <= 300 + + +@pytest.mark.asyncio +async def test_a_provider_failure_older_than_the_window_is_not_current(monkeypatch) -> None: + provider_health.record_failure("classify", "caller_type_kept") + _ch(monkeypatch) + window_s = settings.ops_incidents_window_minutes * 60 + monkeypatch.setattr( + provider_health, + "status", + lambda: { + "degraded": True, + "providers": {"classify": {"failing": True, "last_error_age_s": window_s + 1}}, + }, + ) + + out = await handle_ops_incidents(OpsIncidentsInput(org="acme")) + + assert out.incidents == [] + + +@pytest.mark.asyncio +async def test_an_unread_source_is_named_in_degraded_and_the_others_answer(monkeypatch) -> None: + def _down(sql, params): + raise server_error("Connection refused", code=210) + + readiness.register("migrations", lambda: readiness.result(False, "pending: 200_x.sql")) + RecordingCH().on("loom.worker_status", _down).on("sli_minute", _down).install(monkeypatch) + + out = await handle_ops_incidents(OpsIncidentsInput(org="acme")) + + assert [(i.kind, i.subject) for i in out.incidents] == [("readiness", "migrations")] + notes = degradations.current() + assert [n.split(" (")[0] for n in notes] == [ + "ops.incidents: workers_unread", + "ops.incidents: requests_unread", + ] + assert "Connection refused" not in " ".join(notes) # the kind, never the driver's text + assert provider_health.status()["providers"] == {} # Loom's own reads, not a provider + + +@pytest.mark.asyncio +async def test_an_org_wide_token_that_names_no_org_reads_no_request_counts(monkeypatch) -> None: + ch = _ch(monkeypatch) + + await handle_ops_incidents(OpsIncidentsInput(org="*")) + await handle_ops_incidents(OpsIncidentsInput()) + + assert ch.statements("sli_minute") == [] + + +def test_any_viewer_polls_it_and_it_reads_no_namespace() -> None: + op = OPERATIONS_BY_NAME["ops.incidents"] + assert op.required_role == Role.VIEWER and op.read_only + assert op.deployment_scoped and op.skip_namespace_authz diff --git a/tests/unit/test_sdk_go_codegen.py b/tests/unit/test_sdk_go_codegen.py index 6524b0725d9..86362da618b 100644 --- a/tests/unit/test_sdk_go_codegen.py +++ b/tests/unit/test_sdk_go_codegen.py @@ -70,7 +70,7 @@ def test_generated_response_retains_http_argument_feedback() -> None: generated = build_source() output = generated.split("type MemoryGetOutput struct {", 1)[1].split("\n}", 1)[0] - for key in ("ignored_args", "did_you_mean"): + for key in ("ignored_args", "did_you_mean", "degraded"): assert f'json:"{key},omitempty"' in output row = generated.split("type MemoryBulkGetOutput struct {", 1)[1].split("\n}", 1)[0] nested = re.search(r'map\[string\](\w+) `json:"results', row) From 855605cb5507b48b5b96b26c27131ca5fe39154d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 00:27:55 +0530 Subject: [PATCH 02/47] A replay keeps degraded, each note is listed once, and ops.incidents reads cheaply - The MCP lean pass keeps a non-empty top-level degraded, so an idempotent replay serves the list its first answer stored. - note() skips an entry the request already holds; the cap of 8 counts distinct notes. - A unit-test fixture starts every test with no note list. - ops.incidents reads each ClickHouse source at most once every 5 s per process, a failed read included and still named in degraded. The worker read keys on the enabled worker names, a 6 h window and this deployment's labels, so isolated and bench servers sharing loom.worker_status are not listed. supervisor.ALERT_THRESHOLD is public. Both statements are in the analyzer corpus. - Request counts are read only by a token over every namespace of the org that reads whole namespaces: sli_minute keeps no namespace or user. - The constructor-coverage probe caches a failed read with its kind and notes it on every answer it serves; code.search does not memoize, and code.ask does not store, an answer whose request noted anything. - enrich.bounded() notes a failed read, not a cut by its bound: the callers pass what is left of their budget. - The ops.incidents input docstring opens with one whole sentence; the docs name what an entry carries and who reads request counts. - The SDK public-surface snapshot carries ops.incidents. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 24 ++- docs/reference/http-api.md | 11 +- docs/reference/operations.md | 2 +- docs/reference/operations/ops.md | 2 +- sdk/go/wire/models.gen.go | 2 +- sdk/python/loom/ops.py | 4 +- sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 2 +- server/code/app/answers_cache.py | 6 +- server/code/app/enrich.py | 7 +- server/code/app/search/handler.py | 5 +- server/code/app/symbol/coverage.py | 41 ++-- server/insights/api/models_ops.py | 9 +- server/insights/app/incidents.py | 114 ++++++++--- server/observability/degradations.py | 17 +- server/transport/lean_results.py | 12 +- server/workers/registry.py | 5 + server/workers/status_store.py | 42 ++-- server/workers/supervisor.py | 10 +- tests/analyzer/cases/workers.py | 5 + tests/analyzer/shapes.txt | 2 + tests/unit/conftest.py | 12 ++ tests/unit/snapshots/sdk_public_api.json | 4 + tests/unit/test_code_read_degradations.py | 30 ++- tests/unit/test_degradations.py | 28 ++- .../test_idempotency_across_transports.py | 16 ++ tests/unit/test_ops_incidents.py | 186 +++++++++++++++++- tests/unit/tunable_constants.txt | 2 +- 27 files changed, 482 insertions(+), 118 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index b63c19fcf4b..006159cce1d 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -145,18 +145,22 @@ is degraded now, for a client that polls it rather than reading one answer's lists an incident. Each incident is `{kind, subject, severity, detail, age_s}`, errors first, at most 20: -| `kind` | Listed when | Severity | -| ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | -| `readiness` | a readiness check of this process fails | error when required, else warn | -| `provider` | a provider's last call failed within `LOOM_OPS_INCIDENTS_WINDOW_MINUTES` (15); a later success clears it | warn | -| `worker` | a worker's last 3 or more passes in `loom.worker_status` failed in a row | warn | -| `requests` | at least `LOOM_OPS_INCIDENTS_ERROR_SHARE` (0.1) of the caller's org's calls of one SLO class failed on the server over the window, counted once the class has `LOOM_OPS_INCIDENTS_MIN_REQUESTS` (20) | error | +| `kind` | Listed when | Severity | +| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | +| `readiness` | a readiness check of this process fails | error when required, else warn | +| `provider` | a provider's last call failed within `LOOM_OPS_INCIDENTS_WINDOW_MINUTES` (15); a later success clears it | warn | +| `worker` | an enabled worker's last 3 or more passes failed in a row, the last within 6 hours, in this deployment's processes (`loom.worker_status` rows labelled `deploy…` or unlabelled; an isolated or a bench server reads only its own label's) | warn | +| `requests` | at least `LOOM_OPS_INCIDENTS_ERROR_SHARE` (0.1) of one SLO class's calls in the org the call acts in failed on the server over the window, counted once the class has `LOOM_OPS_INCIDENTS_MIN_REQUESTS` (20) | error | Request counts come from `loom_telemetry.sli_minute`, which trails the calls by about two -minutes, and only for the token's own org: a token for every org reads none. The other -kinds name a check, provider or worker and an error's kind, as `/v1/health` does. Each -ClickHouse read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`; one that fails is named in the -response's `degraded` and the other sources still answer. +minutes and keeps no namespace or user. They are read for the org the call acts in, and +only by a token over every namespace of that org that reads whole namespaces: a token +narrowed to some namespaces or pinned to one user, and a `*` token that names no org, +read none. The other kinds name a check, provider or worker and an error's kind, as +`/v1/health` does. Each ClickHouse source is read at most once every 5 seconds per process, +however many clients poll during an outage, and each read is cut at +`LOOM_READINESS_CHECK_TIMEOUT_S`. A source that failed is named in the response's +`degraded` while its failure is cached, and the other sources still answer. ### Smoke test diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index a46e581c83e..760327f025a 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -304,13 +304,18 @@ A response served from a fallback or a partial read names it in `degraded`, a li `code_index: calls_tests_dropped (DatabaseError)` (`server/observability/degradations.py`). The transport adds the request's entries to every op's response, over HTTP and MCP, and leaves the key out when nothing degraded: an answer without `degraded` was served in full. -The HTTP status stays 200. An entry names the error's kind; its text is in the server log. +The HTTP status stays 200. An entry names a Loom error's code and message, or another +error's kind only; the full text is in the server log. - An op whose output declares `degraded` (`memory.set`, `memory.search`, `memory.set_from_messages`) lists its own entries first; the request's other entries - follow, each once. A request records at most 8. + follow. An entry is listed once, and a request records at most 8. +- A code enrichment cut by its time budget (`LOOM_CODE_ENRICH_TIMEOUT_S`, or what is left + of the request's) is the budget working, not a fallback, and is not listed. - Over MCP the trimmed result keeps `degraded` at the top and drops the copies inside its - sections; `loom_search` also ends its text with a `Degraded:` line. + sections; `loom_search` also ends its text with a `Degraded:` line. An idempotent + replay answers the `degraded` its first answer carried, on either transport. +- `code.search` and `code.ask` do not cache an answer served from a fallback for a later call. - Whether Loom is degraded now, rather than one answer, is [`ops.incidents`](./operations/ops.md#opsincidents) ([incidents](../operations/monitoring.md#opsincidents)). diff --git a/docs/reference/operations.md b/docs/reference/operations.md index 22957cd9e8f..caa6d7f40a5 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -629,7 +629,7 @@ Fields for every `ops` op: [operations/ops.md](operations/ops.md). | --- | --- | --- | --- | --- | --- | | [`ops.capabilities`](operations/ops.md#opscapabilities) | Identity is optional: a client discovers the surface with whatever token it holds (role check only; no namespace is addressed). | viewer | read | yes | | | [`ops.health`](operations/ops.md#opshealth) | Run the deployment's self-checks (schema contracts, embedding stubs, ClickHouse parts, op mix, procedure plane, workers) and report each as ok, warn or fail. | org_admin | idempotent | no | | -| [`ops.incidents`](operations/ops.md#opsincidents) | Whether Loom is degraded now: failing readiness checks, providers and workers, and the org's calls failing on the server. | viewer | read | no | | +| [`ops.incidents`](operations/ops.md#opsincidents) | Whether Loom is degraded now, from its checks, providers, workers and calls. | viewer | read | no | | | [`ops.projection_failures.list`](operations/ops.md#opsprojection_failureslist) | List recorded projection failures: derived rows (embeddings, graph edges, summaries) a write could not produce. | org_admin | idempotent | no | | | [`ops.projection_failures.resolve`](operations/ops.md#opsprojection_failuresresolve) | Mark projection failures resolved by id without retrying them. | org_admin | idempotent | no | yes | | [`ops.projection_failures.retry`](operations/ops.md#opsprojection_failuresretry) | Retry open projection failures for a namespace, optionally one projection kind. | org_admin | idempotent | no | yes | diff --git a/docs/reference/operations/ops.md b/docs/reference/operations/ops.md index af8b24cc62e..cc7e96b34f6 100644 --- a/docs/reference/operations/ops.md +++ b/docs/reference/operations/ops.md @@ -45,7 +45,7 @@ Run the deployment's self-checks (schema contracts, embedding stubs, ClickHouse ## `ops.incidents` -Whether Loom is degraded now: failing readiness checks, providers and workers, and the org's calls failing on the server. +Whether Loom is degraded now, from its checks, providers, workers and calls. `POST /v1/ops.incidents` · MCP `loom_ops_incidents` · role `viewer` · read · not listed under the MCP `all` toolset diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 01ad00b90da..cfab9d18f00 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: 8233c32bd31d30d3cb64d76f7f02647fddfd0785c00c2448bf18e50e52d3c7ac +// Registry model schema SHA-256: c75d4418b0911952ece98e92510550dbb8e27e35f1c10022c01d5de519ea2e64 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 4cfdaf82837..2a0da0fdecc 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -18467,13 +18467,13 @@ class OpsHealthCheck(TypedDict, total=False): class OpsIncidentsInput(TypedDict, total=False): - "Whether Loom is degraded now: failing readiness checks, providers and workers, and" + "Whether Loom is degraded now, from its checks, providers, workers and calls." org: NotRequired[str] class OpsIncidentsBody(TypedDict, total=False): - "Whether Loom is degraded now: failing readiness checks, providers and workers, and" + "Whether Loom is degraded now, from its checks, providers, workers and calls." org: NotRequired[str] diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 891d10df735..e43147d86c4 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -2376,7 +2376,7 @@ def health(body = nil, request_options: nil, **fields) end # `ops.incidents` (viewer, read-only, experimental). - # Whether Loom is degraded now: failing readiness checks, providers and workers, and + # Whether Loom is degraded now, from its checks, providers, workers and calls. def incidents(body = nil, request_options: nil, **fields) call_op("ops.incidents", body, fields, request_options) end diff --git a/server/code/app/answers_cache.py b/server/code/app/answers_cache.py index 16dda7a251d..9b6e23c4786 100644 --- a/server/code/app/answers_cache.py +++ b/server/code/app/answers_cache.py @@ -23,6 +23,7 @@ ) from server.code.store.index import CodeRepo, build_row from server.core.shielded import shielded +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -329,8 +330,9 @@ def _exact_cached(llm: Any, org: str, ns: str) -> Any: async def _remember(ctx: _AskCtx, res: AskResult, llm: Any) -> None: - """Store a memoizable answer, or a negative entry for an abstain.""" - if res.partial: + """Store a memoizable answer, or a negative entry for an abstain. A partial answer, + or one served from a fallback (`degraded`), is not stored.""" + if res.partial or degradations.current(): return try: if res.abstain: diff --git a/server/code/app/enrich.py b/server/code/app/enrich.py index 3c877ea6b0d..fcbdb488985 100644 --- a/server/code/app/enrich.py +++ b/server/code/app/enrich.py @@ -105,11 +105,16 @@ async def share_edit_example_reads() -> AsyncIterator[None]: async def bounded[T](coro: Awaitable[T], fallback: T, seconds: float | None = None) -> T: """`coro`'s answer within `seconds` (`code_enrich_timeout_s` when None), else - `fallback`.""" + `fallback`. A read that fails is named in `degraded`; one cut by the bound is not, + since callers pass what is left of their budget (often nothing) and a cut is the + budget working, like a token cut.""" try: return await asyncio.wait_for( coro, timeout=settings.code_enrich_timeout_s if seconds is None else seconds ) + except TimeoutError: + logger.debug("code enrich cut by its bound") + return fallback except Exception as e: # noqa: BLE001 — enrichment degrades, never fails logger.debug("code enrich degraded: %s", e) degradations.note("code_index", "enrichment_skipped", e, health=False) diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index f7aad834a1e..ca05bdc0b63 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -389,14 +389,15 @@ async def _finish_search( partial=res.partial, partial_reason=res.partial_reason, ) - # a failed history read, a failed leg, a failed pick and a deadline-cut answer are - # transient: never replay + # a failed history read, a failed leg, a failed pick, a deadline-cut answer and one + # served from a fallback (`degraded`) are transient: never replay if ( memo_key is not None and not (res.history or {}).get("failed") and not res.retrieval_work.get("pick_failed") and not out.partial and not res.epistemic + and not degradations.current() ): from server.code.app import search_memo as memo diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index fb92db9854d..b6cc7306b72 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -16,6 +16,7 @@ from server.code.domain.index.epistemic import Envelope, scip_coverage_from_rows from server.code.domain.index.verdicts import GRAPHED_LANGS as _GRAPHED_LANGS from server.code.store.index import CodeRepo +from server.core.errors import caller_text from server.observability import degradations logger = logging.getLogger(__name__) @@ -149,7 +150,8 @@ async def _declined_calls_for( return unresolved, ambiguous -_CTOR_CACHE: TtlCache[tuple[str, str], tuple[bool, bool]] = TtlCache(3600.0) +# (compiler tier, parser tier, the failed read's kind or "") +_CTOR_CACHE: TtlCache[tuple[str, str], tuple[bool, bool, str]] = TtlCache(3600.0) async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, bool]: @@ -158,25 +160,26 @@ async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, compiler tier says so when a full index converted with its source was applied (`scip_ctor_calls`); the parser tier when the namespace's edge stage has converged on the running extractor stamp (or was indexed by it). Fail closed to (False, False): an - error can only lower an answer, and that answer is kept only PROBE_ERROR_TTL_S.""" + error can only lower an answer, and that answer is kept only PROBE_ERROR_TTL_S, named + in `degraded` on every answer that serves it.""" hit = _CTOR_CACHE.get((org, ns)) - if hit is not None: - return hit - ttl: float | None = None - try: - from server.code.app.index.scip_delta import STATE_SCIP_CTOR_CALLS - from server.code.domain.extract.extractor_stamp import stage_stamps - - state = await repo.all_state(org, ns) - scip_ok = state_value(state, STATE_SCIP_CTOR_CALLS) == "1" - edge_stamp = state_value(state, "extractor_stamp_edge") - ts_ok = bool(edge_stamp) and edge_stamp == stage_stamps()["edge"] - cov = (scip_ok, ts_ok) - except Exception as e: # noqa: BLE001 — fail closed: an error can only lower an answer - degradations.note("code_index", "constructor_coverage_unread", e, health=False) - cov, ttl = (False, False), PROBE_ERROR_TTL_S - _CTOR_CACHE.put((org, ns), cov, ttl_s=ttl) - return cov + if hit is None: + ttl: float | None = None + try: + from server.code.app.index.scip_delta import STATE_SCIP_CTOR_CALLS + from server.code.domain.extract.extractor_stamp import stage_stamps + + state = await repo.all_state(org, ns) + scip_ok = state_value(state, STATE_SCIP_CTOR_CALLS) == "1" + edge_stamp = state_value(state, "extractor_stamp_edge") + ts_ok = bool(edge_stamp) and edge_stamp == stage_stamps()["edge"] + hit = (scip_ok, ts_ok, "") + except Exception as e: # noqa: BLE001 — fail closed: an error can only lower an answer + hit, ttl = (False, False, caller_text(e)), PROBE_ERROR_TTL_S + _CTOR_CACHE.put((org, ns), hit, ttl_s=ttl) + if hit[2]: + degradations.note("code_index", "constructor_coverage_unread", hit[2], health=False) + return hit[0], hit[1] def _has_ctor_seed(rows: list[dict[str, Any]]) -> bool: diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 094b1631d77..ba34de491ef 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -165,9 +165,12 @@ class OpsCapabilitiesOutput(BaseModel): class OpsIncidentsInput(BaseModel): - """Whether Loom is degraded now: failing readiness checks, providers and workers, and - the org's calls failing on the server. Identity is optional: the org is the token's - (role check only; no namespace is addressed).""" + """Whether Loom is degraded now, from its checks, providers, workers and calls. + + It lists failing readiness checks, providers and workers, and the share of the org's + calls that failed on the server; a token narrowed to some namespaces or pinned to one + user reads no call counts. Identity is optional: the org is the token's (role check + only; no namespace is addressed).""" org: str = "" diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index c1eaaa904a7..f413b604be8 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -2,21 +2,27 @@ A client that gets errors, or answers it cannot trust, asks here whether Loom is in an incident. The answer comes from what the server already keeps: its readiness checks, -the outcome of the provider calls it made (`provider_health`), the workers' failure -streaks (`loom.worker_status`) and the caller's org's request failures +the outcome of the provider calls it made (`provider_health`), the failure streaks of +the workers this deployment runs (`loom.worker_status`) and the org's request failures (`loom_telemetry.sli_minute`). Nothing names another org: a provider or worker incident -carries an error's kind, never its text, and the request counts are the caller's org's. -A source that cannot be read within a readiness check's bound -(`readiness_check_timeout_s`) is named in the answer's `degraded`; the others still -answer, so the op answers during a ClickHouse outage too. +carries an error's kind, never its text, and the request counts are those of the org the +call acts in, read only by a token over every namespace of it (the rollup keeps no +namespace or user). Each ClickHouse source is read at most once per `_SOURCE_TTL_S` per +process, so clients polling during an outage do not add load. A source that cannot be +read within a readiness check's bound (`readiness_check_timeout_s`) is named in the +answer's `degraded`, as long as that failure is cached; the others still answer, so the +op answers during a ClickHouse outage too. """ from __future__ import annotations import asyncio +import time +from collections.abc import Awaitable, Callable from datetime import UTC, datetime from typing import Any +from server.core.errors import caller_text from server.insights.api.models_ops import OpsIncident, OpsIncidentsInput, OpsIncidentsOutput from server.insights.store import ops as ops_store from server.observability import degradations, provider_health @@ -24,16 +30,48 @@ # not a setting: the bound the output model documents MAX_INCIDENTS = 20 -# not a setting: a day holds the last pass of every worker that runs at least daily -_WORKER_SCAN_HOURS = 24 +# A failure streak whose last pass is older is no current incident (the worker stopped, +# or runs less often than this). +# not a setting: what "current" means for a worker, documented with the op +_WORKER_WINDOW_HOURS = 6 +# not a setting: polls within it share one read of each ClickHouse source +_SOURCE_TTL_S = 5.0 +# The request-count entries are one per org polling; past this the cache starts over. +# not a setting: a memory bound, not a behaviour +_CACHE_MAX = 1024 + +# (source, org) -> (read at, incidents, the read's failure or "") +_cache: dict[tuple[str, str], tuple[float, list[OpsIncident], str]] = {} def _line(text: object) -> str: return " ".join(str(text).split())[:200] +async def _cached( + source: str, org: str, read: Callable[[], Awaitable[list[OpsIncident]]] +) -> list[OpsIncident]: + """`read()`'s incidents, or the ones it gave within `_SOURCE_TTL_S`. A failed read is + cached too, and named in `degraded` on every answer that serves it.""" + now = time.monotonic() + hit = _cache.get((source, org)) + if hit is None or now - hit[0] >= _SOURCE_TTL_S: + try: + async with asyncio.timeout(settings.readiness_check_timeout_s): + incidents, failure = await read(), "" + except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer + incidents, failure = [], caller_text(e) + if len(_cache) >= _CACHE_MAX: + _cache.clear() + hit = _cache[(source, org)] = (now, incidents, failure) + if hit[2]: + degradations.note("ops.incidents", f"{source}_unread", hit[2], health=False) + return hit[1] + + async def _readiness() -> list[OpsIncident]: - """A failing readiness check: required ones stop this server taking traffic.""" + """A failing readiness check: required ones stop this server taking traffic. The + checks cache their own answers.""" from server.core import readiness try: @@ -81,17 +119,16 @@ def _age_s(value: Any) -> float | None: async def _workers() -> list[OpsIncident]: - """A worker whose freshest pass left a failure streak at the supervisor's alert - threshold, from whichever process ran it.""" + """A worker this deployment runs whose freshest pass left a failure streak at the + supervisor's alert threshold.""" + from server.observability.instance import instance_label from server.workers import status_store - from server.workers.supervisor import _ALERT_THRESHOLD + from server.workers.registry import enabled_worker_names + from server.workers.supervisor import ALERT_THRESHOLD - try: - async with asyncio.timeout(settings.readiness_check_timeout_s): - rows = await status_store.failing_streaks(_ALERT_THRESHOLD, _WORKER_SCAN_HOURS) - except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer - degradations.note("ops.incidents", "workers_unread", e, health=False) - return [] + rows = await status_store.failing_streaks( + enabled_worker_names(), instance_label(), ALERT_THRESHOLD, _WORKER_WINDOW_HOURS + ) out: list[OpsIncident] = [] for r in rows: streak = int(r.get("consecutive_failures") or 0) @@ -108,16 +145,23 @@ async def _workers() -> list[OpsIncident]: return out +def _reads_org_calls() -> bool: + """Whether the caller may read the org's call counts: a token over every namespace + of its org that reads whole namespaces, since the rollup keeps no namespace or user; + with auth off, the install's caller. Fails closed: a token narrowed to some + namespaces or pinned to one user, or no token where one is required, reads none.""" + from server.auth.context import current_auth + from server.identity.app.request_scope import request_narrowed + + auth = current_auth() + if auth is None: + return not settings.auth_actually_required() + return "*" in auth.namespaces and not request_narrowed() + + async def _requests(org: str, minutes: int) -> list[OpsIncident]: """An SLO class of the org's calls whose server-side failures reach the share.""" - if not org or org == "*": - return [] # no single org to read: an org-wide token that named none - try: - async with asyncio.timeout(settings.readiness_check_timeout_s): - rows = await ops_store.request_errors_by_class(org, minutes) - except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer - degradations.note("ops.incidents", "requests_unread", e, health=False) - return [] + rows = await ops_store.request_errors_by_class(org, minutes) out: list[OpsIncident] = [] for r in rows: total, failed = int(r.get("requests") or 0), int(r.get("server_errors") or 0) @@ -136,13 +180,25 @@ async def _requests(org: str, minutes: int) -> list[OpsIncident]: return out +async def _no_incidents() -> list[OpsIncident]: + return [] + + async def handle_ops_incidents(input: OpsIncidentsInput) -> OpsIncidentsOutput: """The current incidents, errors first.""" minutes = settings.ops_incidents_window_minutes - ready, workers, requests = await asyncio.gather( - _readiness(), _workers(), _requests(input.org, minutes) + org = input.org + # No single org to read (an org-wide token that named none), or a token that may not + # read the whole org's counts: no request incidents. + requests = ( + _cached("requests", org, lambda: _requests(org, minutes)) + if org and org != "*" and _reads_org_calls() + else _no_incidents() + ) + ready, workers, calls = await asyncio.gather( + _readiness(), _cached("workers", "", _workers), requests ) - incidents = [*ready, *_providers(minutes * 60.0), *workers, *requests] + incidents = [*ready, *_providers(minutes * 60.0), *workers, *calls] incidents.sort(key=lambda i: (i.severity != "error", i.kind, i.subject)) return OpsIncidentsOutput( status="degraded" if incidents else "ok", diff --git a/server/observability/degradations.py b/server/observability/degradations.py index 38b366394e2..2d47c6d19ec 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -11,10 +11,12 @@ `note(provider, effect, reason)`; both transports put the request's notes on every op response as `degraded` (`on_response`), so a handler only notes. The transport binds a fresh list per op next to the cost accumulator, so notes -never leak across requests. Bounded, never raises, and a note also feeds -`provider_health` (unless it passes `health=False`: a fallback that is no -provider's, or a store read whose failure the provider's own client already -counted) so the /v1/health flag agrees with the responses. +never leak across requests. Bounded (each entry once, at most `_MAX_NOTES`), never +raises, and a note also feeds `provider_health` so the /v1/health flag agrees with +the responses. A note passes `health=False` in two cases: + +- the fallback belongs to no provider (a store read or a handler's own step); +- a provider failed, and its own client already recorded the failure. degraded: ["classify: caller_type_kept (HTTPStatusError)", "rerank: input_order_kept (ReadTimeout)"] @@ -47,8 +49,9 @@ def note(provider: str, effect: str, reason: object = "", *, health: bool = True """Record that `provider` fell back to `effect` because of `reason`. `effect` is the short bounded label of what the response did instead - (`caller_type_kept`, `input_order_kept`, `unannotated`). `health=False` keeps - a fallback that is no provider's out of `provider_health`. Never raises. + (`caller_type_kept`, `input_order_kept`, `unannotated`). An entry already listed + is not listed again. `health=False` keeps the note out of `provider_health`. + Never raises. """ try: text = str(reason) if reason is not None else "" @@ -65,7 +68,7 @@ def note(provider: str, effect: str, reason: object = "", *, health: bool = True # for health, and start a list so a later reader sees it. lst = [] _notes.set(lst) - if len(lst) < _MAX_NOTES: + if entry not in lst and len(lst) < _MAX_NOTES: lst.append(entry) if not health: return diff --git a/server/transport/lean_results.py b/server/transport/lean_results.py index 8279c8064df..54429b744be 100644 --- a/server/transport/lean_results.py +++ b/server/transport/lean_results.py @@ -57,9 +57,6 @@ "triples_matched", "set_expansion_phrases", "top_k_ceiling", - # An output's or a section's own copy: the transport puts the request's - # notes back at the top (`mcp_op_result`). - "degraded", "pending_extraction", "derived_aggregate", # Per-hit bookkeeping the reader never acts on (otherwise a memory @@ -105,11 +102,12 @@ def lean(payload: Any, *, top: bool = False) -> Any: empty values dropped (except the KEEP_EMPTY collections), order kept. At the `top` level an empty list survives whatever its key: `inbox.list` with no inboxes must not answer `{}`, or the model cannot tell "none" from - "broken".""" + "broken". A non-empty `degraded` is kept at the top only: a section's copy + repeats the request's notes, which the top one carries (`on_response`).""" if isinstance(payload, dict): out: dict[str, Any] = {} for k, v in payload.items(): - if k in DIAGNOSTIC_KEYS: + if k in DIAGNOSTIC_KEYS or (k == "degraded" and not (top and v)): continue lv = lean(v) if _empty(lv) and k not in KEEP_EMPTY and not (top and isinstance(v, list)): @@ -274,8 +272,8 @@ def mcp_op_result( candidates = {"loom_code_read", "loom_code_edit_context"} followups = frozenset(candidates.intersection(listed_tool_names(toolset))) out = lean_code(op_name, out, arguments, followups=followups) - # The request's fallbacks at the top, after the lean pass dropped the copies an - # output or its sections carry (`DIAGNOSTIC_KEYS`). + # The request's fallbacks at the top, after the lean pass dropped the sections' + # copies (`lean`). out = on_response(_with_ignored_args(op_name, out, arguments)) if hint is not None and isinstance(out, dict): if hint[1] not in str(out.get("rendered") or ""): diff --git a/server/workers/registry.py b/server/workers/registry.py index 69feb29a196..96740111920 100644 --- a/server/workers/registry.py +++ b/server/workers/registry.py @@ -617,6 +617,11 @@ def enabled_workers() -> list[WorkerSpec]: return [_spec_for(row) for row in _WORKERS if _is_enabled(row)] +def enabled_worker_names() -> list[str]: + """The names of the enabled rows, in table order, without importing a worker.""" + return [row.name for row in _WORKERS if _is_enabled(row)] + + def pass_deadline_seconds(name: str) -> float: """The deadline the supervisor enforces on a pass of worker `name`.""" row = next(row for row in _WORKERS if row.name == name) diff --git a/server/workers/status_store.py b/server/workers/status_store.py index 97e5b866453..8e56d60da8c 100644 --- a/server/workers/status_store.py +++ b/server/workers/status_store.py @@ -594,9 +594,11 @@ async def pass_summaries(prefix: str, days: int, *, ch: Any = None) -> list[dict return list(await client.query_all(PASS_SUMMARY_SQL, {"prefix": prefix, "days": int(days)})) -# The workers whose freshest pass within the window, from whichever process ran it, -# left a failure streak of at least {min_failures}: the class of its last error, never -# its text or namespace, which can name an org. +# The {workers} (a prefix of the key) whose freshest pass within the window, in this +# process's deployment, left a failure streak of at least {min_failures}: the class of +# its last error, never its text or namespace, which can name an org. The deployment's +# processes are labelled `deploy…` (or carry no label); any other process (an isolated +# or a bench server sharing the table) reads only its own label's rows. FAILING_STREAKS_SQL = f""" SELECT worker, argMax(failures, finished) AS consecutive_failures, @@ -608,7 +610,11 @@ async def pass_summaries(prefix: str, days: int, *, ch: Any = None) -> list[dict argMax(error_class, version) AS error_class, argMax(pass_finished, version) AS finished FROM {TABLE} - WHERE pass_started > now() - toIntervalHour({{hours:UInt32}}) + WHERE worker IN {{workers:Array(String)}} + AND pass_started > now() - toIntervalHour({{hours:UInt32}}) + AND if({{deployment:Bool}}, + instance_label = '' OR startsWith(instance_label, 'deploy'), + instance_label = {{label:String}}) GROUP BY worker, instance_label ) GROUP BY worker @@ -618,14 +624,28 @@ async def pass_summaries(prefix: str, days: int, *, ch: Any = None) -> list[dict """ -async def failing_streaks(min_failures: int, hours: int, *, ch: Any = None) -> list[dict[str, Any]]: - """`FAILING_STREAKS_SQL` rows. Raises what the read raises.""" +def is_deployment_label(label: str) -> bool: + """Whether a process labelled `label` is the deployment's (`deploy:[:]`, + or no label), not an isolated or a bench server sharing its tables.""" + return not label or label.startswith("deploy") + + +async def failing_streaks( + workers: list[str], label: str, min_failures: int, hours: int, *, ch: Any = None +) -> list[dict[str, Any]]: + """`FAILING_STREAKS_SQL` rows for `workers` in the deployment of a process labelled + `label`. Raises what the read raises.""" + if not workers: + return [] client = ch if ch is not None else _client() - return list( - await client.query_all( - FAILING_STREAKS_SQL, {"min_failures": int(min_failures), "hours": int(hours)} - ) - ) + params = { + "workers": list(workers), + "deployment": is_deployment_label(label), + "label": label, + "min_failures": int(min_failures), + "hours": int(hours), + } + return list(await client.query_all(FAILING_STREAKS_SQL, params)) # --------------------------------------------------------------------------- merge diff --git a/server/workers/supervisor.py b/server/workers/supervisor.py index d873424fcd8..8ea5beb4aac 100644 --- a/server/workers/supervisor.py +++ b/server/workers/supervisor.py @@ -44,7 +44,9 @@ log = logging.getLogger(__name__) -_ALERT_THRESHOLD = 3 +# Failed passes in a row at which a worker is alerting (logged at ERROR, listed by +# ops.incidents). +ALERT_THRESHOLD = 3 @dataclass @@ -109,7 +111,7 @@ def _report_failure( streak, duration_ms, ) - if streak >= _ALERT_THRESHOLD: + if streak >= ALERT_THRESHOLD: log.error( "%s: DEGRADED — %d consecutive failures. Check upstream " "(ClickHouse, Langfuse, external API) and operator dashboard.", @@ -589,7 +591,7 @@ def _after_pass( new_streak, (f"{first[0]} {first[1]}: {first[2]}" if first else ""), ) - if new_streak >= _ALERT_THRESHOLD: + if new_streak >= ALERT_THRESHOLD: log.error( "%s: DEGRADED — %d consecutive passes with a failed leg. " "Check the leg named above.", @@ -692,7 +694,7 @@ def _record_status_row( if status == "timeout" else "" ) - degraded = streak if streak >= _ALERT_THRESHOLD else 0 + degraded = streak if streak >= ALERT_THRESHOLD else 0 error_class, error_text = status_store.error_fields( error, reason=reason, diff --git a/tests/analyzer/cases/workers.py b/tests/analyzer/cases/workers.py index a0120f2d591..10fb2d0e726 100644 --- a/tests/analyzer/cases/workers.py +++ b/tests/analyzer/cases/workers.py @@ -127,6 +127,11 @@ async def _worker_passes(ch: RecordingCH, c: dict[str, Any]) -> None: await status_store.latest_rows(ch=ch) await status_store.resume_cursor("embedding_worker", ch=ch) + # ops.incidents: the deployment's failing workers and the org's request failures. + from server.insights.store import ops as ops_store + + await status_store.failing_streaks(["embedding_worker"], "deploy:web:blue", 3, 6, ch=ch) + await ops_store.request_errors_by_class(ORG, 15, ch=ch) # The cost-cap verdict for a pass's namespaces in one statement. from server.observability import budget diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 5696a8f2f50..24f87f244e1 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -133,6 +133,7 @@ 0f510c19553c SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, memory_key, version, ? AS value_json, toJSONString(content_exc 0f5951ba0297 SELECT DISTINCT kind, start_line, end_line FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path = {path:String} AND tombstoned_at IS NULL 0f5fb44818c9 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a +0f93c7c30394 SELECT worker, argMax(failures, finished) AS consecutive_failures, argMax(error_class, finished) AS error_class, max(finished) AS last_finished FROM ( SELECT worker, instance_label, argMax(consecutive 0fc1bdd2c6d3 SELECT pr_number, title, author, files, merged_at, linked_issues, arraySum( arrayMap( (tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {tokens:Array(String)}, {idfs:Array 0fd1cbc1eecb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 0fdc18bb9750 SELECT memory_key, argMax(tombstoned_at IS NOT NULL, version) AS deleted, argMax(status, version) AS head_status, argMax(content_sha256, version) AS head_sha256, argMax(sensitivity, version) AS head_s @@ -647,6 +648,7 @@ 49041bd47683 SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 492df45ef39b INSERT INTO loom.conversation_embeddings SELECT e.* EXCEPT (embedded, known) REPLACE (if(p.matched = ? AND e.known = ?, p.holder.?, e.agent) AS agent, if(p.matched = ? AND e.known = ?, p.holder.?, e.r 4967ddddb4bf ALTER TABLE loom.learnings_supporters DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync +4994bed5d69d SELECT slo_class, sum(requests) AS requests, sum(server_errors) AS server_errors FROM loom_telemetry.sli_minute WHERE slo_class != ? AND minute >= toStartOfMinute(now() - toIntervalMinute({minutes:UIn 49b4574ab213 SELECT concat(?, c.session_id, ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, c.content AS content_excerpt, toString(ss.session_date) AS created_at, toString(ss.session_date) AS valid_at 49bd450f5650 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id != {id:String}) GROUP 49c788209c09 SELECT count() AS n FROM loom.documents FINAL WHERE org = {org:String} AND user_id = {uid:String} AND (superseded_at IS NULL OR (blob_path != ? AND blob_erased_at IS NULL)) diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 111b6e2ea8c..3847685eeb0 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -930,6 +930,18 @@ def _cost_accumulator_left_as_found() -> Iterator[None]: _current.reset(token) +@pytest.fixture(autouse=True) +def _degradation_notes_left_as_found() -> Iterator[None]: + """Start every test with no degradation note list, and put back what was there: + a sync test that calls `degradations.begin()` or `note()` binds the main thread's + list, and every later test's responses would then carry its notes.""" + from server.observability.degradations import _notes + + token = _notes.set(None) + yield + _notes.reset(token) + + @pytest.fixture(autouse=True) def _trace_tasks_left_as_found() -> Iterator[None]: """Drain `code_common._TRACE_TASKS` after every test. diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json index dbdfea6e89a..a209810f85f 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -1546,6 +1546,10 @@ "body", "options" ], + "incidents": [ + "body", + "options" + ], "projection_failures_list": [ "body", "options" diff --git a/tests/unit/test_code_read_degradations.py b/tests/unit/test_code_read_degradations.py index f3c15ea81ad..d67260d8e2e 100644 --- a/tests/unit/test_code_read_degradations.py +++ b/tests/unit/test_code_read_degradations.py @@ -40,15 +40,41 @@ async def test_an_uncounted_declined_call_is_noted_not_read_as_zero() -> None: @pytest.mark.asyncio -async def test_an_enrichment_cut_by_its_bound_is_noted() -> None: +async def test_a_failed_enrichment_is_noted_and_one_cut_by_its_bound_is_not() -> None: + """Callers pass what is left of their budget, often nothing: a cut is the budget + working, a failed read is a fallback.""" from server.code.app.enrich import bounded async def _slow() -> list[int]: await asyncio.sleep(1) return [1] + async def _boom() -> list[int]: + raise ConnectionError("replica gone") + assert await bounded(_slow(), [], seconds=0.001) == [] - assert degradations.current() == ["code_index: enrichment_skipped (TimeoutError)"] + assert degradations.current() == [] + assert await bounded(_boom(), []) == [] + assert degradations.current() == ["code_index: enrichment_skipped (ConnectionError)"] + + +@pytest.mark.asyncio +async def test_a_cached_failed_probe_is_noted_on_every_answer_that_serves_it() -> None: + """The constructor-coverage probe keeps its lowered answer for PROBE_ERROR_TTL_S; + each answer served from it says so, not only the first.""" + from server.code.app.symbol import coverage + from server.code.app.ttl_cache import clear_all + + clear_all() + try: + assert await coverage._ctor_edge_coverage(_FailingRepo(), "o", "n") == (False, False) # type: ignore[arg-type] + degradations.begin() # the next request, served from the cache: no read + assert await coverage._ctor_edge_coverage(None, "o", "n") == (False, False) # type: ignore[arg-type] + assert degradations.current() == [ + "code_index: constructor_coverage_unread (ConnectionError)" + ] + finally: + clear_all() @pytest.mark.asyncio diff --git a/tests/unit/test_degradations.py b/tests/unit/test_degradations.py index 3cb8f61e8a1..46cdcbbf049 100644 --- a/tests/unit/test_degradations.py +++ b/tests/unit/test_degradations.py @@ -31,8 +31,8 @@ def test_begin_note_current_round_trip_and_bounds(): "x: y", ] # bounded: at most 8 notes, reasons clipped, newlines flattened - for _i in range(20): - D.note("p", "e", "line1\nline2" + "z" * 400) + for i in range(20): + D.note("p", f"e{i}", "line1\nline2" + "z" * 400) cur = D.current() assert len(cur) == 8 and "\n" not in "".join(cur) and len(cur[-1]) < 220 # current() is a copy @@ -40,6 +40,19 @@ def test_begin_note_current_round_trip_and_bounds(): assert len(D.current()) == 8 +def test_a_repeated_note_is_listed_once_and_the_cap_counts_distinct_notes(): + """Two bounded reads of one request that both time out, or the two declined-call + reads, record the same entry: it is listed once and takes one place of the eight.""" + D.begin() + for _ in range(10): + D.note("code_index", "declined_calls_uncounted", ConnectionError("x"), health=False) + for i in range(7): + D.note("p", f"e{i}", health=False) + assert D.current()[0] == "code_index: declined_calls_uncounted (ConnectionError)" + assert len(D.current()) == 8 and len(set(D.current())) == 8 + assert D.current()[-1] == "p: e6" + + def test_notes_feed_provider_health(): D.note("classify", "caller_type_kept", "HTTP 502") st = provider_health.status() @@ -218,6 +231,17 @@ def test_every_op_response_carries_the_requests_notes_on_both_transports(): lean = mcp_op_result("memory.get", nested, {}, None) assert lean["degraded"] == ["memory.webhook: not_announced (z)"] assert lean["section"] == {"n": 1} + # A stored answer (an idempotent replay) keeps its own top-level list; an empty one + # is dropped. + from server.transport.lean_results import lean_result + + stored = {"found": False, "degraded": ["rerank: input_order_kept (x)"], "section": nested} + assert lean_result(stored, {}) == { + "found": False, + "degraded": ["rerank: input_order_kept (x)"], + "section": {"found": False, "section": {"n": 1}}, + } + assert "degraded" not in lean_result({"found": True, "degraded": []}, {}) def test_loom_search_says_degraded_in_its_text_and_its_structured_result(): diff --git a/tests/unit/test_idempotency_across_transports.py b/tests/unit/test_idempotency_across_transports.py index 93605977d4a..623f86a976d 100644 --- a/tests/unit/test_idempotency_across_transports.py +++ b/tests/unit/test_idempotency_across_transports.py @@ -22,6 +22,7 @@ import server.transport.mcp_call as mcp_call import server.transport.mcp_outcome as mcp_outcome from server.auth.jwt import AuthInfo, TokenError +from server.observability import degradations from server.operations.base import Operation, Role from server.settings import settings from server.settings.catalog import OP_BUDGETS_P99_MS @@ -50,6 +51,8 @@ def env(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: rows: dict[str, tuple[str, Any]] = {} async def _handler(inp: Any) -> _Out: + if inp.text == "degraded": + degradations.note("rerank", "input_order_kept", "ReadTimeout", health=False) ran.append(inp.text) return _Out(calls=len(ran)) @@ -143,6 +146,19 @@ def _mcp(env: dict[str, Any], body: dict[str, Any], key: str) -> dict[str, Any]: return asyncio.run(mcp_call._call_tool(1, params, auth=env["alice"]))["result"] +def test_a_replay_carries_the_degraded_its_first_answer_named(env: dict[str, Any]) -> None: + """The stored answer names its fallbacks; a retry serves them on both transports, + though nothing degraded on the retry itself.""" + body = {**BODY, "text": "degraded"} + first = _mcp(env, body, "k-degraded")["structuredContent"] + again = _mcp(env, body, "k-degraded") + over_http = _http(env, body, "k-degraded").json() + assert again["_meta"]["idempotentReplay"] is True + for out in (first, again["structuredContent"], over_http): + assert out["degraded"] == ["rerank: input_order_kept (ReadTimeout)"] + assert env["ran"] == ["degraded"] + + def test_an_http_key_replays_over_mcp(env: dict[str, Any]) -> None: assert _http(env, BODY, "k1").status_code == 200 out = _mcp(env, BODY, "k1") diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 0d1859a0ce0..71fbeb5ddda 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -3,12 +3,18 @@ from __future__ import annotations +from dataclasses import replace from datetime import UTC, datetime, timedelta +from typing import Any +from unittest.mock import AsyncMock import pytest +from server.auth.context import set_current_auth +from server.auth.jwt import AuthInfo, TokenError from server.core import readiness -from server.insights.api.models_ops import OpsIncidentsInput +from server.insights.api.models_ops import OpsIncidentsInput, OpsIncidentsOutput +from server.insights.app import incidents from server.insights.app.incidents import handle_ops_incidents from server.observability import degradations, provider_health from server.operations.base import Role @@ -17,10 +23,26 @@ from tests.unit.ch_fake import RecordingCH, server_error +def _token(org: str = "acme", namespaces: tuple[str, ...] = ("*",), **kw: Any) -> AuthInfo: + return AuthInfo( + subject="viewer", + org=org, + namespaces=namespaces, + roles=(Role.VIEWER,), + is_service_account=True, + **kw, + ) + + +ORG_WIDE = _token() + + @pytest.fixture(autouse=True) def _clean(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(readiness, "_CHECKS", {}) monkeypatch.setattr(readiness, "_draining", False) + monkeypatch.setattr(incidents, "_cache", {}) + monkeypatch.setenv("LOOM_INSTANCE_LABEL", "deploy:web:blue") provider_health.reset() degradations.begin() yield @@ -32,11 +54,19 @@ def _ch(monkeypatch: pytest.MonkeyPatch, *, workers=(), sli=()) -> RecordingCH: return ch.install(monkeypatch) +async def _incidents(org: str = "acme", auth: AuthInfo | None = ORG_WIDE) -> OpsIncidentsOutput: + set_current_auth(auth) + try: + return await handle_ops_incidents(OpsIncidentsInput(org=org)) + finally: + set_current_auth(None) + + @pytest.mark.asyncio async def test_a_healthy_deployment_answers_ok_with_no_incident(monkeypatch) -> None: ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 500, "server_errors": 3}]) - out = await handle_ops_incidents(OpsIncidentsInput(org="acme")) + out = await _incidents() assert (out.status, out.incidents) == ("ok", []) assert out.window_minutes == settings.ops_incidents_window_minutes @@ -72,7 +102,7 @@ async def test_each_source_lists_its_incident_errors_first(monkeypatch) -> None: ], ) - out = await handle_ops_incidents(OpsIncidentsInput(org="acme")) + out = await _incidents() assert out.status == "degraded" got = [(i.kind, i.subject, i.severity) for i in out.incidents] @@ -93,6 +123,28 @@ async def test_each_source_lists_its_incident_errors_first(monkeypatch) -> None: assert 230 <= (by["embedding_worker"].age_s or 0) <= 300 +@pytest.mark.asyncio +async def test_the_worker_read_names_the_enabled_workers_and_this_deployments_labels( + monkeypatch, +) -> None: + from server.workers.registry import enabled_worker_names + from server.workers.supervisor import ALERT_THRESHOLD + + ch = _ch(monkeypatch) + + await _incidents() + monkeypatch.setattr(incidents, "_cache", {}) + monkeypatch.setenv("LOOM_INSTANCE_LABEL", "iso:wt:7864") + await _incidents() + + deployment, isolated = (s.params for s in ch.statements("loom.worker_status")) + assert deployment["workers"] == enabled_worker_names() and deployment["workers"] + assert deployment["deployment"] is True # every deploy… label, never an iso one + assert (isolated["deployment"], isolated["label"]) == (False, "iso:wt:7864") + assert deployment["min_failures"] == ALERT_THRESHOLD + assert deployment["hours"] == incidents._WORKER_WINDOW_HOURS + + @pytest.mark.asyncio async def test_a_provider_failure_older_than_the_window_is_not_current(monkeypatch) -> None: provider_health.record_failure("classify", "caller_type_kept") @@ -107,7 +159,7 @@ async def test_a_provider_failure_older_than_the_window_is_not_current(monkeypat }, ) - out = await handle_ops_incidents(OpsIncidentsInput(org="acme")) + out = await _incidents() assert out.incidents == [] @@ -120,7 +172,7 @@ def _down(sql, params): readiness.register("migrations", lambda: readiness.result(False, "pending: 200_x.sql")) RecordingCH().on("loom.worker_status", _down).on("sli_minute", _down).install(monkeypatch) - out = await handle_ops_incidents(OpsIncidentsInput(org="acme")) + out = await _incidents() assert [(i.kind, i.subject) for i in out.incidents] == [("readiness", "migrations")] notes = degradations.current() @@ -133,16 +185,132 @@ def _down(sql, params): @pytest.mark.asyncio -async def test_an_org_wide_token_that_names_no_org_reads_no_request_counts(monkeypatch) -> None: - ch = _ch(monkeypatch) +async def test_polls_within_the_ttl_share_one_read_and_a_cached_failure_is_still_named( + monkeypatch, +) -> None: + def _down(sql, params): + raise server_error("Connection refused", code=210) + + ch = RecordingCH().on("loom.worker_status", _down).on("sli_minute", []).install(monkeypatch) + + await _incidents() + degradations.begin() # the next poll is another request + await _incidents() + await _incidents(org="other", auth=_token(org="other")) + + assert len(ch.statements("loom.worker_status")) == 1 + assert [s.params["org"] for s in ch.statements("sli_minute")] == ["acme", "other"] + assert [n.split(" (")[0] for n in degradations.current()] == ["ops.incidents: workers_unread"] - await handle_ops_incidents(OpsIncidentsInput(org="*")) - await handle_ops_incidents(OpsIncidentsInput()) + +@pytest.mark.asyncio +async def test_only_a_token_over_the_whole_org_reads_its_request_counts(monkeypatch) -> None: + """The rollup keeps no namespace or user: a narrowed or a pinned token, an org-wide + token that names no org, and no token where one is required read no counts.""" + ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 1618, "server_errors": 1618}]) + + narrowed = await _incidents(auth=_token(namespaces=("team",))) + pinned = await _incidents(auth=_token(read_scope="own_user", read_user_id="ada")) + await _incidents(org="*", auth=_token(org="*")) + await _incidents(org="", auth=_token(org="*")) + await _incidents(auth=None) assert ch.statements("sli_minute") == [] + assert narrowed.incidents == pinned.incidents == [] + whole = await _incidents() + assert [i.subject for i in whole.incidents] == ["code"] def test_any_viewer_polls_it_and_it_reads_no_namespace() -> None: op = OPERATIONS_BY_NAME["ops.incidents"] assert op.required_role == Role.VIEWER and op.read_only assert op.deployment_scoped and op.skip_namespace_authz + + +@pytest.fixture +def transports(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + """The real op's flags and role gate on both transports, with a handler that only + records the org it ran for.""" + from fastapi import FastAPI + from fastapi.testclient import TestClient + + import server.auth.bearer as bearer_mod + import server.transport.mcp as mcp + import server.transport.mcp_call as mcp_call + import server.transport.mcp_outcome as mcp_outcome + from server.transport import http as http_mod + from server.transport import mcp_tools + + tokens = {"acme": _token(), "acme-team": _token(namespaces=("team",))} + ran: list[str] = [] + + async def _handler(inp: OpsIncidentsInput) -> OpsIncidentsOutput: + ran.append(inp.org) + return OpsIncidentsOutput(status="ok", window_minutes=15) + + def _verify(token: str, *, secret: str | None = None) -> AuthInfo: + if token not in tokens: + raise TokenError("bad token") + return tokens[token] + + async def _noop(*_a: Any, **_k: Any) -> None: + return None + + op = replace(OPERATIONS_BY_NAME["ops.incidents"], handler=_handler) + monkeypatch.setattr("server.transport.gates._admitted", _noop) + monkeypatch.setattr("server.auth.personal_namespace.ensure_personal_namespace_cached", _noop) + monkeypatch.setattr(settings, "auth_required", True) + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(settings, "mcp_auth_mode", "required") + monkeypatch.setattr(settings, "oauth_enabled", False) + monkeypatch.setattr(settings, "identity_provider", "", raising=False) + monkeypatch.setattr(bearer_mod, "authenticate_token", AsyncMock(side_effect=_verify)) + monkeypatch.setattr("server.auth.jwt.verify_token", _verify) + monkeypatch.setattr(http_mod, "ALL_OPERATIONS", [op]) + monkeypatch.setattr(http_mod, "_emit_event", lambda *a, **k: None) + monkeypatch.setitem(mcp_call.TOOLS_BY_NAME, "loom_ops_incidents", op) + monkeypatch.setattr(mcp_call, "_caller_defaults", _noop) + monkeypatch.setattr(mcp_call, "_emit_mcp_event", lambda *a, **k: None) + monkeypatch.setattr(mcp_outcome, "_emit_mcp_event", lambda *a, **k: None) + monkeypatch.setattr(mcp_tools, "_emit_mcp_event", lambda *a, **k: None) + http_app = FastAPI() + http_app.include_router(http_mod.build_router()) + mcp_app = FastAPI() + mcp.attach(mcp_app) + return {"http": TestClient(http_app), "mcp": TestClient(mcp_app), "ran": ran} + + +def _http(c: dict[str, Any], who: str, org: str) -> Any: + return c["http"].post( + "/v1/ops.incidents", json={"org": org}, headers={"Authorization": f"Bearer {who}"} + ) + + +def _mcp(c: dict[str, Any], who: str, org: str) -> dict[str, Any]: + body = { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": {"name": "loom_ops_incidents", "arguments": {"org": org}}, + } + r = c["mcp"].post("/mcp", json=body, headers={"Authorization": f"Bearer {who}"}) + assert r.status_code == 200, r.text + return dict(r.json()["result"]) + + +def test_a_token_of_one_org_naming_another_is_refused_on_both_transports( + transports: dict[str, Any], +) -> None: + r = _http(transports, "acme", "other") + assert r.status_code == 403 and r.json()["detail"]["code"] == "AUTH_INSUFFICIENT" + out = _mcp(transports, "acme", "other") + assert out["isError"] is True and out["structuredContent"]["code"] == "ORG_MISMATCH" + assert transports["ran"] == [] + + +def test_a_viewer_of_the_org_polls_it_on_both_transports_narrowed_or_not( + transports: dict[str, Any], +) -> None: + assert _http(transports, "acme", "acme").status_code == 200 + assert _mcp(transports, "acme-team", "acme")["isError"] is False + assert transports["ran"] == ["acme", "acme"] diff --git a/tests/unit/tunable_constants.txt b/tests/unit/tunable_constants.txt index 030db0b73b9..756675f8592 100644 --- a/tests/unit/tunable_constants.txt +++ b/tests/unit/tunable_constants.txt @@ -609,6 +609,6 @@ server/workers/status_store.py::_DETAIL_LIMIT server/workers/status_store.py::_ERROR_LIMIT server/workers/status_store.py::_NAMESPACE_LIMIT server/workers/supervisor.py::OVERDUE_SPREAD_SECONDS -server/workers/supervisor.py::_ALERT_THRESHOLD +server/workers/supervisor.py::ALERT_THRESHOLD server/workers/supervisor.py::_OUTCOME_ARGS_MAX server/workers/supervisor.py::_STALE_LEASE_RECHECK_SECONDS From fc3ab6c8d7dc2d6926d83195920507fde6e3ce2a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 01:17:01 +0530 Subject: [PATCH 03/47] Concurrent ops.incidents polls share one read, and a brief whose read fell back is not stored - ops.incidents: a lock per (source, org) makes polls that arrive while a read runs wait for it and share its answer, so a burst of polls runs one statement per source. - Review briefs: build_for_merge and build_for_open serve a brief unstored when a read it ran fell back, since the stored copy would be served later without its degraded. The ingest worker builds each brief in degradations.scoped(), so one brief's fallback does not keep the next from being stored, and a code.refresh that waits keeps its own notes. - enrich.bounded() notes a read cut by the fixed code_enrich_timeout_s (the store answered slowly) and stays silent for a cut by the caller's remaining budget. - The broad excepts rewritten in code.grep, code.symbol and code.search say what they keep serving. - monitoring.md and the dashboard's reason for leaving out ops.incidents say what each surface shows: worker incidents name workers of every deployment process, which /v1/health?include=workers does not. - memory-architecture.md: memory.search_trace carries the note in the transport's degraded. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/memory-architecture.md | 3 +- docs/operations/monitoring.md | 7 +- server/code/app/enrich.py | 11 ++- server/code/app/grep.py | 2 +- server/code/app/index/pass_stream.py | 9 +- server/code/app/index/review_brief_build.py | 9 ++ server/code/app/search/handler.py | 4 +- server/code/app/symbol/symbol.py | 4 +- server/insights/app/incidents.py | 32 ++++--- server/observability/degradations.py | 16 +++- server/operations/dashboard.py | 5 +- tests/unit/test_code_read_degradations.py | 17 +++- tests/unit/test_ops_incidents.py | 29 ++++++ .../test_review_brief_store_needs_diff.py | 95 ++++++++++++++++++- 14 files changed, 207 insertions(+), 36 deletions(-) diff --git a/docs/architecture/memory-architecture.md b/docs/architecture/memory-architecture.md index d92c8d51199..2fd186337e3 100644 --- a/docs/architecture/memory-architecture.md +++ b/docs/architecture/memory-architecture.md @@ -1147,7 +1147,8 @@ and shared duplicate selection by phrase completion. the side legs, which the assembler folds in later, find no shared row. A pool with no shared definition reads nothing more; one whose source cannot be read loses every shared definition, noted on `memory.search`'s `degraded`. A parked next page applies the same - check, and so does `memory.search_trace`, whose response has no `degraded`. + check, and so does `memory.search_trace`, whose response carries the note in the + `degraded` the transport adds to every response. 6. **Fuse and rank** (`fusion.py`, `ranking.py`). The per-mode rank expression (`fact_rank.py`, `_fact_mode_rank_score`) adds the capped prior group (confidence, diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 006159cce1d..1e392583e29 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -156,8 +156,11 @@ Request counts come from `loom_telemetry.sli_minute`, which trails the calls by minutes and keeps no namespace or user. They are read for the org the call acts in, and only by a token over every namespace of that org that reads whole namespaces: a token narrowed to some namespaces or pinned to one user, and a `*` token that names no org, -read none. The other kinds name a check, provider or worker and an error's kind, as -`/v1/health` does. Each ClickHouse source is read at most once every 5 seconds per process, +read none. The other kinds are deployment state, the same for every org: a readiness or +provider incident names the check or provider and an error's kind, as `/v1/health` does, +and a worker incident names a worker of any of the deployment's processes with its streak +and error kind, where `/v1/health?include=workers` shows only the answering process's +workers. Each ClickHouse source is read at most once every 5 seconds per process, however many clients poll during an outage, and each read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A source that failed is named in the response's `degraded` while its failure is cached, and the other sources still answer. diff --git a/server/code/app/enrich.py b/server/code/app/enrich.py index fcbdb488985..096d1406aba 100644 --- a/server/code/app/enrich.py +++ b/server/code/app/enrich.py @@ -105,15 +105,18 @@ async def share_edit_example_reads() -> AsyncIterator[None]: async def bounded[T](coro: Awaitable[T], fallback: T, seconds: float | None = None) -> T: """`coro`'s answer within `seconds` (`code_enrich_timeout_s` when None), else - `fallback`. A read that fails is named in `degraded`; one cut by the bound is not, - since callers pass what is left of their budget (often nothing) and a cut is the - budget working, like a token cut.""" + `fallback`. A read that fails is named in `degraded`, and so is one cut by the fixed + `code_enrich_timeout_s`: the store answered slowly. One cut by the `seconds` a caller + passes is not, since that is what is left of the caller's budget (often nothing) and + the cut is the budget working, like a token cut.""" try: return await asyncio.wait_for( coro, timeout=settings.code_enrich_timeout_s if seconds is None else seconds ) - except TimeoutError: + except TimeoutError as e: logger.debug("code enrich cut by its bound") + if seconds is None: + degradations.note("code_index", "enrichment_skipped", e, health=False) return fallback except Exception as e: # noqa: BLE001 — enrichment degrades, never fails logger.debug("code enrich degraded: %s", e) diff --git a/server/code/app/grep.py b/server/code/app/grep.py index 8a03bba754a..309f2da38a2 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -1143,7 +1143,7 @@ async def _grep_neighbours( entries, capped, tokens = await _attach_enclosing_neighbours( repo, org, ns, anchors, rows, input.neighbour_k ) - except Exception as e: + except Exception as e: # a failed graph read leaves the grep hits intact logger.warning("code.grep: neighbours block failed for %r", input.pattern, exc_info=True) degradations.note("code_index", "neighbours_dropped", e, health=False) return [], False, 0, route diff --git a/server/code/app/index/pass_stream.py b/server/code/app/index/pass_stream.py index c0ba5d8f3a5..6e5b465d460 100644 --- a/server/code/app/index/pass_stream.py +++ b/server/code/app/index/pass_stream.py @@ -383,10 +383,13 @@ def _brief_builder(cfg: Any) -> Any: code.impact.""" from server.code.app.index.review_brief_build import build_for_merge from server.code.app.review_brief import call_code_op + from server.observability import degradations async def _build(repo: Any, org: str, ns: str, **kw: Any) -> None: - await build_for_merge( - repo, org, ns, path_prefixes=tuple(cfg.path_prefixes), call=call_code_op, **kw - ) + # Each brief's own notes decide whether it is stored (`build_for_merge`). + with degradations.scoped(): + await build_for_merge( + repo, org, ns, path_prefixes=tuple(cfg.path_prefixes), call=call_code_op, **kw + ) return _build diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 52d5d6a42d8..8aa9bffc291 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -38,6 +38,7 @@ source_stems, tests_verdict, ) +from server.observability import degradations logger = logging.getLogger(__name__) @@ -675,6 +676,11 @@ async def build_for_merge( # reads the diff, or every later read would serve the degraded copy. if store and changed_paths and not diff: logger.info("review_brief: PR %s served unstored, its diff was not read", pr_number) + elif store and degradations.current(): + # A read it ran fell back: the stored copy would be served later without its + # `degraded`. + logger.info("review_brief: PR %s served unstored, a read fell back", pr_number) + payload["stored"] = False elif store: try: await repo.insert_rows("code_review_briefs", [brief_row(org, ns, payload)]) @@ -769,6 +775,9 @@ async def build_for_open( # a later request completes logger.info("review_brief: open PR %s served unstored, its overlay is partial", pr_number) payload["stored"] = False + elif store and degradations.current(): + logger.info("review_brief: open PR %s served unstored, a read fell back", pr_number) + payload["stored"] = False elif store: try: await repo.insert_rows( diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index ca05bdc0b63..e57881e8395 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -422,7 +422,7 @@ async def _annotate_served(res: Any, prefetch: Any, *, reserve: int) -> int: res.retrieval_work["risk_source"] = prefetch.source res.retrieval_work["risk_stale_units"] = prefetch.stale return spent - except Exception as e: + except Exception as e: # the units are served without their risk block logger.warning("code.search: risk annotation failed", exc_info=True) degradations.note("code_index", "risk_unannotated", e, health=False) return 0 @@ -635,7 +635,7 @@ async def _serve_search_page( tokens += await code_risk.annotate_units( repo, org, ns, units, reserve_tokens=plan.reserve ) - except Exception as e: + except Exception as e: # the page is served without its risk block logger.warning("code.search page: risk annotation failed", exc_info=True) degradations.note("code_index", "risk_unannotated", e, health=False) diff --git a/server/code/app/symbol/symbol.py b/server/code/app/symbol/symbol.py index b604c6da7bc..59876c64611 100644 --- a/server/code/app/symbol/symbol.py +++ b/server/code/app/symbol/symbol.py @@ -102,7 +102,7 @@ async def _symbol_neighbours( entries, _capped, tokens = await _attach_enclosing_neighbours( repo, org, ns, anchors, rows, input.neighbour_k ) - except Exception as e: + except Exception as e: # the definitions are served without the block logger.warning("code.symbol: neighbours block failed for %r", input.name, exc_info=True) degradations.note("code_index", "neighbours_dropped", e, health=False) return [], 0 @@ -151,7 +151,7 @@ def sub_for(dep: str) -> CodeSymbolInput: row_of=code_presence._symbol_row, op="code.symbol", ) - except Exception as e: + except Exception as e: # the miss is served without its dependency rows logger.info("code.symbol: dependency presence declined for %s/%s", org, ns, exc_info=True) degradations.note("code_index", "dependency_presence_unread", e, health=False) return [], {} diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index f413b604be8..3b897cda2fd 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -40,8 +40,10 @@ # not a setting: a memory bound, not a behaviour _CACHE_MAX = 1024 -# (source, org) -> (read at, incidents, the read's failure or "") +# (source, org) -> (read at, incidents, the read's failure or ""), and the lock its polls +# share while one reads _cache: dict[tuple[str, str], tuple[float, list[OpsIncident], str]] = {} +_locks: dict[tuple[str, str], asyncio.Lock] = {} def _line(text: object) -> str: @@ -51,19 +53,25 @@ def _line(text: object) -> str: async def _cached( source: str, org: str, read: Callable[[], Awaitable[list[OpsIncident]]] ) -> list[OpsIncident]: - """`read()`'s incidents, or the ones it gave within `_SOURCE_TTL_S`. A failed read is + """`read()`'s incidents, or the ones it gave within `_SOURCE_TTL_S`. Polls that arrive + while it reads wait for that read rather than start their own. A failed read is cached too, and named in `degraded` on every answer that serves it.""" - now = time.monotonic() - hit = _cache.get((source, org)) - if hit is None or now - hit[0] >= _SOURCE_TTL_S: - try: - async with asyncio.timeout(settings.readiness_check_timeout_s): - incidents, failure = await read(), "" - except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer - incidents, failure = [], caller_text(e) - if len(_cache) >= _CACHE_MAX: + key = (source, org) + lock = _locks.get(key) + if lock is None: + if len(_locks) >= _CACHE_MAX: + _locks.clear() _cache.clear() - hit = _cache[(source, org)] = (now, incidents, failure) + lock = _locks[key] = asyncio.Lock() + async with lock: + hit = _cache.get(key) + if hit is None or time.monotonic() - hit[0] >= _SOURCE_TTL_S: + try: + async with asyncio.timeout(settings.readiness_check_timeout_s): + incidents, failure = await read(), "" + except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer + incidents, failure = [], caller_text(e) + hit = _cache[key] = (time.monotonic(), incidents, failure) if hit[2]: degradations.note("ops.incidents", f"{source}_unread", hit[2], health=False) return hit[1] diff --git a/server/observability/degradations.py b/server/observability/degradations.py index 2d47c6d19ec..38d4f4b6487 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -26,6 +26,8 @@ import contextvars import logging +from collections.abc import Iterator +from contextlib import contextmanager from typing import Any from server.core.errors import caller_text @@ -45,6 +47,18 @@ def begin() -> None: _notes.set([]) +@contextmanager +def scoped() -> Iterator[None]: + """A fresh note list inside the block, and the caller's back after it: a unit of a + worker's pass (one review brief) reads only its own notes, and a request that runs + the pass inline keeps its own.""" + token = _notes.set([]) + try: + yield + finally: + _notes.reset(token) + + def note(provider: str, effect: str, reason: object = "", *, health: bool = True) -> None: """Record that `provider` fell back to `effect` because of `reason`. @@ -108,4 +122,4 @@ def on_response(body: Any) -> Any: return {k: v for k, v in body.items() if k != "degraded"} if "degraded" in body else body -__all__ = ["begin", "current", "note", "on_response"] +__all__ = ["begin", "current", "note", "on_response", "scoped"] diff --git a/server/operations/dashboard.py b/server/operations/dashboard.py index 45742b9d3d0..c958f61c5ce 100644 --- a/server/operations/dashboard.py +++ b/server/operations/dashboard.py @@ -177,7 +177,10 @@ def _named_once(*groups: dict[str, str]) -> dict[str, str]: "observe.crystallize", "observe.record", "ops.capabilities", - # The dashboard's Health view reads /v1/health, which carries the same signals. + # A client polls it to tell an outage from an empty answer. The dashboard reads + # deployment state elsewhere (its problems banner /v1/health, the Health view + # /v1/admin/workers.status and ops.health); none of them carries the org's + # request failure share, which only this op answers. "ops.incidents", ), CLIENT_CALL, diff --git a/tests/unit/test_code_read_degradations.py b/tests/unit/test_code_read_degradations.py index d67260d8e2e..02c0d8c285b 100644 --- a/tests/unit/test_code_read_degradations.py +++ b/tests/unit/test_code_read_degradations.py @@ -40,9 +40,13 @@ async def test_an_uncounted_declined_call_is_noted_not_read_as_zero() -> None: @pytest.mark.asyncio -async def test_a_failed_enrichment_is_noted_and_one_cut_by_its_bound_is_not() -> None: - """Callers pass what is left of their budget, often nothing: a cut is the budget - working, a failed read is a fallback.""" +async def test_a_failed_or_slow_enrichment_is_noted_and_a_budget_cut_is_not( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A read cut by the fixed `code_enrich_timeout_s` means the store answered slowly, + and a failed read is a fallback; a cut by the `seconds` a caller passes is what is + left of its budget, often nothing: the budget working.""" + from server.code.app import enrich from server.code.app.enrich import bounded async def _slow() -> list[int]: @@ -54,8 +58,13 @@ async def _boom() -> list[int]: assert await bounded(_slow(), [], seconds=0.001) == [] assert degradations.current() == [] + monkeypatch.setattr(enrich.settings, "code_enrich_timeout_s", 0.001) + assert await bounded(_slow(), []) == [] assert await bounded(_boom(), []) == [] - assert degradations.current() == ["code_index: enrichment_skipped (ConnectionError)"] + assert degradations.current() == [ + "code_index: enrichment_skipped (TimeoutError)", + "code_index: enrichment_skipped (ConnectionError)", + ] @pytest.mark.asyncio diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 71fbeb5ddda..e4c29d924c0 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -3,6 +3,7 @@ from __future__ import annotations +import asyncio from dataclasses import replace from datetime import UTC, datetime, timedelta from typing import Any @@ -42,6 +43,7 @@ def _clean(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(readiness, "_CHECKS", {}) monkeypatch.setattr(readiness, "_draining", False) monkeypatch.setattr(incidents, "_cache", {}) + monkeypatch.setattr(incidents, "_locks", {}) monkeypatch.setenv("LOOM_INSTANCE_LABEL", "deploy:web:blue") provider_health.reset() degradations.begin() @@ -203,6 +205,33 @@ def _down(sql, params): assert [n.split(" (")[0] for n in degradations.current()] == ["ops.incidents: workers_unread"] +@pytest.mark.asyncio +async def test_polls_that_arrive_while_a_read_is_in_flight_wait_for_it(monkeypatch) -> None: + """A stalled store: concurrent polls share the one read in flight per source, so they + do not multiply the reads while ClickHouse is slow.""" + from server.insights.store import ops as ops_store + from server.workers import status_store + + calls: list[str] = [] + + async def _slow(source: str) -> list[dict[str, Any]]: + calls.append(source) + await asyncio.sleep(0.05) + return [] + + monkeypatch.setattr(status_store, "failing_streaks", lambda *a, **k: _slow("workers")) + monkeypatch.setattr(ops_store, "request_errors_by_class", lambda *a, **k: _slow("requests")) + set_current_auth(ORG_WIDE) + try: + polls = [handle_ops_incidents(OpsIncidentsInput(org="acme")) for _ in range(8)] + outs = await asyncio.gather(*polls) + finally: + set_current_auth(None) + + assert sorted(calls) == ["requests", "workers"] + assert [o.status for o in outs] == ["ok"] * 8 + + @pytest.mark.asyncio async def test_only_a_token_over_the_whole_org_reads_its_request_counts(monkeypatch) -> None: """The rollup keeps no namespace or user: a narrowed or a pinned token, an org-wide diff --git a/tests/unit/test_review_brief_store_needs_diff.py b/tests/unit/test_review_brief_store_needs_diff.py index 5d8a81c7646..536fd30cdad 100644 --- a/tests/unit/test_review_brief_store_needs_diff.py +++ b/tests/unit/test_review_brief_store_needs_diff.py @@ -1,6 +1,7 @@ -"""A merged PR's brief is stored only when its diff was read: one built where -the mirror is missing (a host still cloning it) or git failed would otherwise be served -from the shared table as `precomputed` by every later read.""" +"""A PR's brief is stored only when its diff was read and no read it ran fell back: one +built where the mirror is missing (a host still cloning it), git failed or a read named +in `degraded` failed would otherwise be served from the shared table as `precomputed` +by every later read.""" from __future__ import annotations @@ -11,6 +12,7 @@ from server.code.app.index import gitrepo from server.code.app.index import review_brief_build as rbb +from server.observability import degradations class _Repo: @@ -74,3 +76,90 @@ def test_a_pr_that_changed_no_file_is_stored_without_a_diff( monkeypatch: pytest.MonkeyPatch, ) -> None: assert len(_build(monkeypatch, git_ok=False, changed=[]).inserted) == 1 + + +def _noting_build(monkeypatch: pytest.MonkeyPatch, *, noting: set[int]) -> None: + """`build_brief` that notes a fallback for each PR in `noting`, as an in-process + code.impact or code.coverage_claim does when its read fails.""" + + async def build_brief(inp: Any, **kw: Any) -> dict[str, Any]: + if inp.pr_number in noting: + degradations.note("code_index", "calls_tests_dropped", "DatabaseError", health=False) + return {"pr_number": inp.pr_number, "merge_sha": inp.merge_sha, "sections": {}} + + async def author(*a: Any) -> str: + return "" + + async def run(git_dir: str, *args: str) -> str: + return "parent\n" if args[0] == "rev-parse" else "diff --git a/x b/x\n" + + monkeypatch.setattr(gitrepo, "run", run) + monkeypatch.setattr(rbb, "build_brief", build_brief) + monkeypatch.setattr(rbb, "_ledger_author", author) + monkeypatch.setattr(rbb, "brief_row", lambda org, ns, payload: payload) + + +async def _none(*a: Any, **kw: Any) -> Any: + return None + + +def test_a_brief_whose_read_fell_back_is_served_unstored(monkeypatch: pytest.MonkeyPatch) -> None: + """Merged and open: stored, it would be served later as `precomputed` without the + `degraded` its build named.""" + repo = _Repo() + _noting_build(monkeypatch, noting={7, 8}) + common: dict[str, Any] = {"git_dir": "/x", "title": "t", "changed_paths": ["a.cpp"]} + + async def both() -> list[dict[str, Any]]: + degradations.begin() + merged = await rbb.build_for_merge( + repo, "acme", "code-widgets", pr_number=7, merge_sha="m" * 40, call=_none, **common + ) + opened = await rbb.build_for_open( + repo, + "acme", + "code-widgets", + pr_number=8, + head_sha="h" * 40, + base_sha="b" * 40, + call=_none, + diff="diff --git a/x b/x\n", + **common, + ) + return [merged, opened] + + merged, opened = asyncio.run(both()) + assert repo.inserted == [] + assert merged["stored"] is False and opened["stored"] is False + + +def test_the_ingest_stores_each_brief_by_its_own_notes(monkeypatch: pytest.MonkeyPatch) -> None: + """The commit step builds briefs one after another in one pass, inline in a + code.refresh that waits: each brief reads only its own notes, and the request keeps + its own.""" + from types import SimpleNamespace + + from server.code.app.index.pass_stream import _brief_builder + + repo = _Repo() + _noting_build(monkeypatch, noting={7}) + build = _brief_builder(SimpleNamespace(path_prefixes=())) + + async def pass_() -> list[str]: + degradations.begin() + degradations.note("rerank", "input_order_kept", "x", health=False) # the request's + for pr in (7, 9): + await build( + repo, + "acme", + "code-widgets", + git_dir="/x", + pr_number=pr, + title="t", + merge_sha=str(pr) * 40, + changed_paths=["a.cpp"], + ) + return degradations.current() + + assert asyncio.run(pass_()) == ["rerank: input_order_kept (x)"] + assert [rows[0]["pr_number"] for _, rows in repo.inserted] == [9] From e5275366686d7a820959cc81388528cd0fffdfb1 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 01:56:23 +0530 Subject: [PATCH 04/47] A brief with an unread diff and a failed overrides probe say so in degraded - build_for_merge and build_for_open note git_mirror: diff_unread when git could not read the diff of a PR that changed files, and the merged brief answers stored: false; it answered stored: true for a brief nothing stored. - The overrides probe caches the failed read's kind with its fail-closed answer and notes it on every answer that serves it, as the constructor probe does. - result_lessons passes what is left of the call's deadline only when that is less than code_enrich_timeout_s, so a lessons read no deadline narrows takes the fixed bound and is noted when cut by it. - http-api.md says a cut by LOOM_CODE_ENRICH_TIMEOUT_S is listed and a cut by the request's remaining deadline is not. - The readiness leg of ops.incidents drops its except: each check already answers as failing when it raises or times out. - The narrow-token reason and the dashboard's reason for ops.incidents say what a narrowed token reads and what only this op carries. - Tests: code.search does not memoize and code.ask does not store an answer whose request noted a fallback, and both do with no note; an HTTP body without org polls the token's org. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/http-api.md | 5 +- server/code/app/index/review_brief_build.py | 7 ++ server/code/app/result_lessons.py | 23 +++---- server/code/app/symbol/dispatch.py | 26 ++++---- server/identity/domain/read_scope.py | 4 +- server/insights/app/incidents.py | 9 +-- server/operations/dashboard.py | 5 +- tests/unit/test_code_answer_completeness.py | 33 ++++++++++ tests/unit/test_code_read_degradations.py | 17 +++++ tests/unit/test_code_result_lessons.py | 32 +++++++++- tests/unit/test_code_search_pick.py | 17 ++++- tests/unit/test_ops_incidents.py | 9 +++ .../test_review_brief_store_needs_diff.py | 64 ++++++++++++++++--- 13 files changed, 204 insertions(+), 47 deletions(-) diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 760327f025a..2ae8d67233e 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -310,8 +310,9 @@ error's kind only; the full text is in the server log. - An op whose output declares `degraded` (`memory.set`, `memory.search`, `memory.set_from_messages`) lists its own entries first; the request's other entries follow. An entry is listed once, and a request records at most 8. -- A code enrichment cut by its time budget (`LOOM_CODE_ENRICH_TIMEOUT_S`, or what is left - of the request's) is the budget working, not a fallback, and is not listed. +- A code enrichment cut by `LOOM_CODE_ENRICH_TIMEOUT_S` is listed: the store answered + slowly. One cut by what is left of the request's own deadline is the budget working, + not a fallback, and is not listed. - Over MCP the trimmed result keeps `degraded` at the top and drops the copies inside its sections; `loom_search` also ends its text with a `Degraded:` line. An idempotent replay answers the `degraded` its first answer carried, on either transport. diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 8aa9bffc291..73ea0e91936 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -642,6 +642,8 @@ async def build_for_merge( parent = (await gitrepo.run(git_dir, "rev-parse", f"{merge_sha}^1")).strip() except Exception as e: # noqa: BLE001 — blame section degrades without it logger.info("review_brief: parent of %s unknown: %s", merge_sha[:12], e) + if changed_paths: + degradations.note("git_mirror", "diff_unread", e, health=False) parent = "" diff = "" if parent: @@ -649,6 +651,8 @@ async def build_for_merge( diff = await gitrepo.run(git_dir, "diff", "--no-renames", parent, merge_sha) except Exception as e: # noqa: BLE001 — the brief still has the file list logger.info("review_brief: diff of %s failed: %s", merge_sha[:12], e) + if changed_paths: + degradations.note("git_mirror", "diff_unread", e, health=False) head = "" try: head = str(await repo.get_state(org, ns, "git_head") or "") @@ -676,6 +680,7 @@ async def build_for_merge( # reads the diff, or every later read would serve the degraded copy. if store and changed_paths and not diff: logger.info("review_brief: PR %s served unstored, its diff was not read", pr_number) + payload["stored"] = False elif store and degradations.current(): # A read it ran fell back: the stored copy would be served later without its # `degraded`. @@ -748,6 +753,8 @@ async def build_for_open( diff = await gitrepo.run(git_dir, "diff", "--no-renames", base_sha, head_sha) except Exception as e: # noqa: BLE001 — the brief still has the file list logger.info("review_brief: open diff of PR %s failed: %s", pr_number, e) + if changed_paths: + degradations.note("git_mirror", "diff_unread", e, health=False) head = "" try: head = str(await repo.get_state(org, ns, "git_head") or "") diff --git a/server/code/app/result_lessons.py b/server/code/app/result_lessons.py index 94b1aa3efd3..cb1463115de 100644 --- a/server/code/app/result_lessons.py +++ b/server/code/app/result_lessons.py @@ -78,19 +78,19 @@ def _searched_namespace(input: Any) -> str: return str(names[0] if len(names) == 1 else input.namespace) -def _bound_s(input: Any, started: float) -> float: - """Seconds the read may take: `code_enrich_timeout_s`, and no more than what is left - of the operation's own `deadline_ms`.""" - bound = settings.code_enrich_timeout_s +def _bound_s(input: Any, started: float) -> float | None: + """What is left of the operation's own `deadline_ms`, when that is less than + `code_enrich_timeout_s`; None when no deadline narrows the read, which then takes the + fixed bound and is named in `degraded` when cut by it (`enrich.bounded`).""" + budget = None if isinstance(input, CodeSearchInput): budget = code_deadline.start(resolve_deadline_ms(input.deadline_ms), started=started) - if budget is not None: - bound = min(bound, budget.left_ms() / 1000) elif isinstance(input, CodeGrepInput): budget = code_deadline.start(input.deadline_ms, started=started) - if budget is not None: - bound = min(bound, budget.left_ms() / 1000) - return bound + if budget is None: + return None + left = budget.left_ms() / 1000 + return left if left < settings.code_enrich_timeout_s else None async def lessons_for( @@ -119,12 +119,13 @@ async def scope() -> tuple[str, list[str], str, bool]: nss = [n for n in nss if memory_links.trunk_namespace(org, n) in ("", trunk)] return org, nss, trunk if trunk in nss else "", ns == trunk - bound = _bound_s(input, started) + narrowed = _bound_s(input, started) + bound = settings.code_enrich_timeout_s if narrowed is None else narrowed if bound <= 0: return path_lessons.Lessons([]) with code_span("enrich.lessons"): read_started = time.monotonic() - resolved = await enrich.bounded(scope(), None, seconds=bound) + resolved = await enrich.bounded(scope(), None, seconds=narrowed) remaining = bound - (time.monotonic() - read_started) if resolved is None or remaining <= 0: return path_lessons.Lessons([]) diff --git a/server/code/app/symbol/dispatch.py b/server/code/app/symbol/dispatch.py index 6b1db7fadf5..60213d7b9e0 100644 --- a/server/code/app/symbol/dispatch.py +++ b/server/code/app/symbol/dispatch.py @@ -10,6 +10,7 @@ from server.code.app.candidates import overrides_of from server.code.app.ttl_cache import TtlCache from server.code.store.index import CodeRepo +from server.core.errors import caller_text from server.observability import degradations @@ -73,7 +74,8 @@ async def _dispatch_missing( return not await _namespace_has_override_edges(repo, org, ns) -_OVR_CACHE: TtlCache[tuple[str, str], bool] = TtlCache(3600.0) +# (has live `overrides` edges, the failed read's kind or "") +_OVR_CACHE: TtlCache[tuple[str, str], tuple[bool, str]] = TtlCache(3600.0) # How long a namespace probe's fail-closed answer after a read error is kept. PROBE_ERROR_TTL_S = 30.0 @@ -92,17 +94,19 @@ async def _namespace_has_override_edges(repo: CodeRepo, org: str, ns: str) -> bo """Cached (1h) per namespace: does the compiler tier carry live `overrides` edges at all? Fail-closed to False so a query error keeps the heuristics; that answer is kept only `PROBE_ERROR_TTL_S`, so one transient error does not hold the - namespace on the slow heuristics for the hour.""" + namespace on the slow heuristics for the hour, and is named in `degraded` on every + answer that serves it.""" hit = _OVR_CACHE.get((org, ns)) - if hit is not None: - return hit - ttl: float | None = None - try: - has = await repo.has_live_scip_override_edges(org, ns) - except Exception: # noqa: BLE001 — fail closed to False: the heuristics stay on - has, ttl = False, PROBE_ERROR_TTL_S - _OVR_CACHE.put((org, ns), has, ttl_s=ttl) - return has + if hit is None: + ttl: float | None = None + try: + hit = (await repo.has_live_scip_override_edges(org, ns), "") + except Exception as e: # noqa: BLE001 — fail closed to False: the heuristics stay on + hit, ttl = (False, caller_text(e)), PROBE_ERROR_TTL_S + _OVR_CACHE.put((org, ns), hit, ttl_s=ttl) + if hit[1]: + degradations.note("code_index", "override_coverage_unread", hit[1], health=False) + return hit[0] # Seed kinds whose direct members' callers count as the seed's callers (a class is used diff --git a/server/identity/domain/read_scope.py b/server/identity/domain/read_scope.py index 59c810c0fa6..1ba46d5b163 100644 --- a/server/identity/domain/read_scope.py +++ b/server/identity/domain/read_scope.py @@ -409,7 +409,9 @@ def pin_read_filters[M: BaseModel](input: M, auth: Any) -> tuple[M, bool]: # other users' memory keys and payloads. "ops.capabilities": "the deployment's capabilities", "ops.health": "deployment health", - "ops.incidents": "the deployment's incidents and the org's request failure counts, no memory", + "ops.incidents": ( + "the deployment's incidents; a narrowed token reads no request counts, no memory" + ), "mentor.guide": "the deployment's static agent guide, no memory", "help.search": "the deployment's shipped documentation, no memory", "help.get": "the deployment's shipped documentation, no memory", diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 3b897cda2fd..2097a3445c4 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -79,14 +79,11 @@ async def _cached( async def _readiness() -> list[OpsIncident]: """A failing readiness check: required ones stop this server taking traffic. The - checks cache their own answers.""" + checks cache their own answers, and a check that raises or times out answers as + failing.""" from server.core import readiness - try: - state = await readiness.evaluate() - except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer - degradations.note("ops.incidents", "readiness_unread", e, health=False) - return [] + state = await readiness.evaluate() return [ OpsIncident( kind="readiness", diff --git a/server/operations/dashboard.py b/server/operations/dashboard.py index c958f61c5ce..4b72f1c49ef 100644 --- a/server/operations/dashboard.py +++ b/server/operations/dashboard.py @@ -177,10 +177,7 @@ def _named_once(*groups: dict[str, str]) -> dict[str, str]: "observe.crystallize", "observe.record", "ops.capabilities", - # A client polls it to tell an outage from an empty answer. The dashboard reads - # deployment state elsewhere (its problems banner /v1/health, the Health view - # /v1/admin/workers.status and ops.health); none of them carries the org's - # request failure share, which only this op answers. + # polled by clients; only it carries the org's request failure share "ops.incidents", ), CLIENT_CALL, diff --git a/tests/unit/test_code_answer_completeness.py b/tests/unit/test_code_answer_completeness.py index 77e37a0b74f..b7301cd3664 100644 --- a/tests/unit/test_code_answer_completeness.py +++ b/tests/unit/test_code_answer_completeness.py @@ -181,6 +181,39 @@ async def forbidden(*args: Any, **kwargs: Any) -> None: await answers_cache._remember(SimpleNamespace(), result, None) +@pytest.mark.asyncio +async def test_an_answer_served_from_a_fallback_is_not_stored( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A later ask would get it from the cache without its `degraded`.""" + from server.code.app import answers_cache + from server.observability import degradations + from server.settings import settings + + stored: list[Any] = [] + + async def store(ctx: Any, row: Any) -> None: + stored.append(row) + + async def not_gone(*args: Any, **kwargs: Any) -> bool: + return False + + monkeypatch.setattr(answers_cache, "_store_then_check", store) + monkeypatch.setattr(answers_cache, "_answer_may_be_gone", not_gone) + monkeypatch.setattr(answers_cache, "_entry_row", lambda ctx, **kw: kw) + monkeypatch.setattr(settings, "code_ask_negative_cache_ttl_s", 600) + result = answers_entry.AskResult(source="abstained", abstain=True, abstain_reason="no_evidence") + ctx = SimpleNamespace(index_head="h" * 40) + + degradations.begin() + degradations.note("code_lessons", "lessons_dropped", "DatabaseError", health=False) + await answers_cache._remember(ctx, result, None) + assert stored == [] + degradations.begin() + await answers_cache._remember(ctx, result, None) + assert stored == [{"kind": "negative", "abstain_reason": "no_evidence"}] + + def test_ranking_changes_invalidate_cached_answers(monkeypatch: pytest.MonkeyPatch) -> None: from server.settings import settings diff --git a/tests/unit/test_code_read_degradations.py b/tests/unit/test_code_read_degradations.py index 02c0d8c285b..16ae29e4759 100644 --- a/tests/unit/test_code_read_degradations.py +++ b/tests/unit/test_code_read_degradations.py @@ -86,6 +86,23 @@ async def test_a_cached_failed_probe_is_noted_on_every_answer_that_serves_it() - clear_all() +@pytest.mark.asyncio +async def test_a_cached_failed_override_probe_is_noted_on_every_answer_that_serves_it() -> None: + """The `overrides` probe fails closed to the heuristic walk for PROBE_ERROR_TTL_S; + each answer that walks so says why.""" + from server.code.app.symbol import dispatch + from server.code.app.ttl_cache import clear_all + + clear_all() + try: + assert await dispatch._namespace_has_override_edges(_FailingRepo(), "o", "n") is False # type: ignore[arg-type] + degradations.begin() # the next request, served from the cache: no read + assert await dispatch._namespace_has_override_edges(None, "o", "n") is False # type: ignore[arg-type] + assert degradations.current() == ["code_index: override_coverage_unread (ConnectionError)"] + finally: + clear_all() + + @pytest.mark.asyncio async def test_a_dropped_coverage_leg_names_the_leg() -> None: from server.code.app.coverage import _leg diff --git a/tests/unit/test_code_result_lessons.py b/tests/unit/test_code_result_lessons.py index 28d8c206a76..3942047a356 100644 --- a/tests/unit/test_code_result_lessons.py +++ b/tests/unit/test_code_result_lessons.py @@ -772,11 +772,41 @@ async def test_a_call_past_its_deadline_reads_no_lessons(monkeypatch: pytest.Mon assert 0 < result_lessons._bound_s(_input(deadline_ms=1000), time.monotonic() - 0.5) < 0.6 # a deadline under 200 ms reads as 200, as the search reads it assert 0.1 < result_lessons._bound_s(_input(deadline_ms=100), time.monotonic() - 0.05) <= 0.2 - # no deadline: the enrichment bound alone + # no deadline, or one with more left than the bound: the enrichment bound alone + assert result_lessons._bound_s(_input(deadline_ms=0), time.monotonic()) is None + assert result_lessons._bound_s(_input(deadline_ms=60_000), time.monotonic()) is None assert (await result_lessons.lessons_for(_input(deadline_ms=0), ["a.py"], late)).rows assert len(calls) == 1 +@pytest.mark.asyncio +async def test_a_scope_read_cut_by_the_bound_is_noted_and_one_cut_by_the_deadline_is_not( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The fixed bound cutting the read means the store answered slowly; what is left of + the call's deadline cutting it is the budget working.""" + from server.observability import degradations + + _stub_reads(monkeypatch, ["code-repo"], []) + + async def _slow(org: str, code_ns: str, extra: list[str]) -> list[str]: + await asyncio.sleep(5) + return ["code-repo"] + + monkeypatch.setattr(code_plane_reads, "lesson_namespaces", _slow) + monkeypatch.setattr(settings, "code_enrich_timeout_s", 0.05) + degradations.begin() + found = await result_lessons.lessons_for(_input(deadline_ms=0), ["a.py"], time.monotonic()) + assert found.rows == [] + assert degradations.current() == ["code_index: enrichment_skipped (TimeoutError)"] + + monkeypatch.setattr(settings, "code_enrich_timeout_s", 5.0) + degradations.begin() + late = time.monotonic() - 0.9 # a 1 s deadline with about 0.1 s left + assert (await result_lessons.lessons_for(_input(deadline_ms=1000), ["a.py"], late)).rows == [] + assert degradations.current() == [] + + @pytest.mark.asyncio async def test_the_op_handler_attaches_lessons_after_its_answer( monkeypatch: pytest.MonkeyPatch, diff --git a/tests/unit/test_code_search_pick.py b/tests/unit/test_code_search_pick.py index 1f16492460d..4c52606da2d 100644 --- a/tests/unit/test_code_search_pick.py +++ b/tests/unit/test_code_search_pick.py @@ -337,9 +337,10 @@ def line(body: str, symbol: str = "pkg.mod::Uploader::send") -> str: def _handle( - monkeypatch: Any, model: Any, *, over_cap: bool = False, **kw: Any + monkeypatch: Any, model: Any, *, over_cap: bool = False, noted: bool = False, **kw: Any ) -> tuple[dict[str, Any], list[Any]]: - """The registered op's reply over `_Repo`, and what it wrote to the memo.""" + """The registered op's reply over `_Repo`, and what it wrote to the memo. `noted`: a + read inside the search falls back and says so in `degraded`.""" import server.operations # noqa: F401 — handlers import wire models lazily from server.code.app import search_memo as memo from server.code.app.search import handler @@ -366,6 +367,10 @@ async def as_of(repo: Any, org: str, ns: str) -> dict[str, Any]: return {"commit": "c" * 40} async def thresholds(org: str, ns: str) -> tuple[float, float, float]: + if noted: + from server.observability import degradations + + degradations.note("code_index", "lexical_leg_dropped", "DatabaseError", health=False) return 0.30, 0.22, 0.62 async def cap(org: str, ns: str, **k: Any) -> bool: @@ -403,6 +408,14 @@ def test_the_reply_carries_the_confidence_and_a_failed_pick_is_not_replayed( assert failed["retrieval_work"]["pick_failed"] == 1 and puts == [] +def test_a_search_served_from_a_fallback_is_not_memoized(monkeypatch: pytest.MonkeyPatch) -> None: + """A replay would serve it later without its `degraded`.""" + plain, puts = _handle(monkeypatch, _picks(2, 1)) + assert len(puts) == 1 + noted, puts = _handle(monkeypatch, _picks(2, 1), noted=True) + assert noted["results"] == plain["results"] and puts == [] + + def test_a_namespace_over_its_llm_cap_makes_no_pick_call( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index e4c29d924c0..1c97428cb03 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -343,3 +343,12 @@ def test_a_viewer_of_the_org_polls_it_on_both_transports_narrowed_or_not( assert _http(transports, "acme", "acme").status_code == 200 assert _mcp(transports, "acme-team", "acme")["isError"] is False assert transports["ran"] == ["acme", "acme"] + + +def test_a_body_without_org_polls_the_tokens_org(transports: dict[str, Any]) -> None: + for who in ("acme", "acme-team"): + r = transports["http"].post( + "/v1/ops.incidents", json={}, headers={"Authorization": f"Bearer {who}"} + ) + assert r.status_code == 200, r.text + assert transports["ran"] == ["acme", "acme"] diff --git a/tests/unit/test_review_brief_store_needs_diff.py b/tests/unit/test_review_brief_store_needs_diff.py index 536fd30cdad..f7c816f4acc 100644 --- a/tests/unit/test_review_brief_store_needs_diff.py +++ b/tests/unit/test_review_brief_store_needs_diff.py @@ -26,7 +26,11 @@ async def insert_rows(self, table: str, rows: list[Any]) -> None: self.inserted.append((table, rows)) -def _build(monkeypatch: pytest.MonkeyPatch, *, git_ok: bool, changed: list[str]) -> _Repo: +def _build( + monkeypatch: pytest.MonkeyPatch, *, git_ok: bool, changed: list[str] +) -> tuple[_Repo, dict[str, Any], list[str]]: + """The repo it stored into, the payload served and the request's notes.""" + async def run(git_dir: str, *args: str) -> str: if not git_ok: raise gitrepo.GitError("fatal: not a git repository") @@ -47,8 +51,9 @@ async def author(*a: Any) -> str: async def call(*a: Any, **kw: Any) -> Any: return None - asyncio.run( - rbb.build_for_merge( + async def build() -> tuple[dict[str, Any], list[str]]: + degradations.begin() + payload = await rbb.build_for_merge( repo, "acme", "code-widgets", @@ -59,23 +64,64 @@ async def call(*a: Any, **kw: Any) -> Any: changed_paths=changed, call=call, ) - ) - return repo + return payload, degradations.current() + + payload, notes = asyncio.run(build()) + return repo, payload, notes def test_a_brief_without_its_diff_is_served_unstored(monkeypatch: pytest.MonkeyPatch) -> None: - assert _build(monkeypatch, git_ok=False, changed=["src/a.cpp"]).inserted == [] + """It says so: `stored: false`, and `degraded` names the unread diff.""" + repo, payload, notes = _build(monkeypatch, git_ok=False, changed=["src/a.cpp"]) + assert repo.inserted == [] and payload["stored"] is False + assert notes == ["git_mirror: diff_unread (GitError)"] def test_a_brief_with_its_diff_is_stored(monkeypatch: pytest.MonkeyPatch) -> None: - [(table, _)] = _build(monkeypatch, git_ok=True, changed=["src/a.cpp"]).inserted - assert table == "code_review_briefs" + repo, payload, notes = _build(monkeypatch, git_ok=True, changed=["src/a.cpp"]) + [(table, _)] = repo.inserted + assert table == "code_review_briefs" and "stored" not in payload and notes == [] def test_a_pr_that_changed_no_file_is_stored_without_a_diff( monkeypatch: pytest.MonkeyPatch, ) -> None: - assert len(_build(monkeypatch, git_ok=False, changed=[]).inserted) == 1 + repo, _, notes = _build(monkeypatch, git_ok=False, changed=[]) + assert len(repo.inserted) == 1 and notes == [] + + +def test_an_open_brief_whose_diff_failed_names_it_and_is_served_unstored( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def run(git_dir: str, *args: str) -> str: + raise gitrepo.GitError("fatal: bad revision") + + async def build_brief(inp: Any, **kw: Any) -> dict[str, Any]: + return {"pr_number": inp.pr_number, "merge_sha": "", "sections": {}} + + monkeypatch.setattr(gitrepo, "run", run) + monkeypatch.setattr(rbb, "build_brief", build_brief) + repo = _Repo() + + async def build() -> tuple[dict[str, Any], list[str]]: + degradations.begin() + payload = await rbb.build_for_open( + repo, + "acme", + "code-widgets", + git_dir="/x", + pr_number=8, + title="t", + head_sha="h" * 40, + base_sha="b" * 40, + changed_paths=["a.cpp"], + call=_none, + ) + return payload, degradations.current() + + payload, notes = asyncio.run(build()) + assert repo.inserted == [] and payload["stored"] is False + assert notes == ["git_mirror: diff_unread (GitError)"] def _noting_build(monkeypatch: pytest.MonkeyPatch, *, noting: set[int]) -> None: From 44c05c86b5ceadc1d9226f11d8dc35d600247fe3 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 04:05:15 +0530 Subject: [PATCH 05/47] Code and memory read fallbacks note what they served, and ops.incidents leaves draining out The read handlers of both planes note each fallback that serves a smaller answer: about 150 broad excepts after a sweep of server/code/app and server/memory/app. An answer a fallback served is not kept where a later call would read it without its notes: code.map's map, a published code status, a memory.ask precedent, a facts.traverse walk and the nightly backport rows. Caches that keep a failed read (the code status, the pending-extraction count, namespace health) name it on each answer they serve, and a later code.search page names its first page's notes. ops.incidents leaves the draining readiness check out, since every deploy drains a process. The worker streak read keeps rows whose label's first segment is exactly `deploy`, one rule for the SQL and label_family, and both incident statements run on clickhouse-local in a new test. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 12 +- docs/reference/http-api.md | 5 +- server/code/app/backport.py | 4 + server/code/app/bisect.py | 4 + server/code/app/bisect_fix.py | 4 + server/code/app/bisect_fusion.py | 3 + server/code/app/bisect_scan.py | 2 + server/code/app/blame.py | 3 + server/code/app/candidates.py | 2 + server/code/app/citations.py | 2 + server/code/app/common.py | 4 +- server/code/app/context.py | 10 +- server/code/app/conventions.py | 3 + server/code/app/fan_in.py | 2 + server/code/app/files.py | 2 + server/code/app/history.py | 2 + server/code/app/index_status.py | 29 ++-- server/code/app/repo_scope.py | 2 + server/code/app/repos.py | 4 +- server/code/app/search/cards.py | 2 + server/code/app/search/definitions.py | 2 + server/code/app/search/handler.py | 3 + server/code/app/search/history.py | 2 + server/code/app/search/symbol.py | 2 + server/code/app/search_cursor.py | 4 + server/code/app/symbol/enclosing.py | 4 +- .../code/app/symbol/enclosing_decorators.py | 5 +- server/code/app/symbol/outline.py | 2 + server/code/app/symbol/resolve.py | 2 + server/code/app/symbol/symbol.py | 3 +- server/code/app/symbol/verify.py | 4 +- server/code/app/symbol_context.py | 2 + server/code/app/symbol_uses.py | 2 + server/code/workers/backport_gaps.py | 39 ++--- server/insights/api/models_ops.py | 4 +- server/insights/app/incidents.py | 5 +- server/memory/app/ask/cascade.py | 3 + server/memory/app/ask/completion.py | 2 + server/memory/app/ask/context_blocks.py | 4 +- server/memory/app/ask/identifiers.py | 8 +- server/memory/app/ask/reader.py | 2 + server/memory/app/ask/records.py | 3 + server/memory/app/ask/supersession.py | 2 + server/memory/app/ask_when_evidence.py | 2 + server/memory/app/code_grounding.py | 10 +- server/memory/app/code_link_reads.py | 3 + server/memory/app/context_pack.py | 7 +- server/memory/app/deep_evidence.py | 2 + server/memory/app/entity_resolution.py | 4 +- server/memory/app/facts.py | 5 +- server/memory/app/for_file.py | 3 + .../memory/app/loom_search/repo_decisions.py | 2 + server/memory/app/loom_search/tracker_leg.py | 4 + server/memory/app/namespace_health.py | 41 +++--- server/memory/app/namespace_types.py | 3 + server/memory/app/pending_disclosure.py | 37 +++-- server/memory/app/pending_evidence.py | 2 + server/memory/app/procedure.py | 4 +- server/memory/app/profile_search.py | 3 + server/memory/app/proposals_ops.py | 2 + server/memory/app/query.py | 2 + server/memory/app/retrieval/chunks.py | 7 +- server/memory/app/retrieval/derived.py | 5 + server/memory/app/retrieval/pool.py | 3 + server/memory/app/retrieval/side_legs.py | 4 + server/memory/app/retrieval/summaries.py | 3 + server/memory/app/runs_manifest.py | 2 + server/memory/app/search/anchor_pool.py | 2 + server/memory/app/search/computed.py | 2 + server/memory/app/search/digest_descent.py | 2 + server/memory/app/search/key_match.py | 2 + server/memory/app/search/output.py | 2 + server/memory/app/search/payload.py | 3 + server/memory/app/search/supplemental.py | 5 +- server/memory/app/search/tiers.py | 1 + server/memory/app/search_llm.py | 10 +- server/memory/app/served_superseded.py | 2 + server/memory/app/stack_knowledge.py | 4 +- server/memory/app/working_memory.py | 2 + server/observability/degradations.py | 17 ++- server/operations/base.py | 10 +- server/workers/status_store.py | 16 ++- tests/analyzer/shapes.txt | 2 +- tests/unit/clickhouse_local.py | 8 +- tests/unit/test_code_backport_gaps.py | 29 ++++ tests/unit/test_code_missing_vector_routes.py | 1 + tests/unit/test_code_read_degradations.py | 133 ++++++++++++++++++ tests/unit/test_code_search_pick.py | 3 + tests/unit/test_extraction_queue.py | 14 +- tests/unit/test_facts_handlers.py | 6 + tests/unit/test_identity_incomplete.py | 3 + tests/unit/test_memory_ask_precedents.py | 30 ++++ tests/unit/test_namespace_health.py | 6 + tests/unit/test_ops_incidents.py | 39 ++++- tests/unit/test_ops_incidents_sql.py | 108 ++++++++++++++ tests/unit/test_ui_read_caches.py | 41 +++++- 96 files changed, 761 insertions(+), 112 deletions(-) create mode 100644 tests/unit/test_ops_incidents_sql.py diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 1e392583e29..00c66a75555 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -145,12 +145,12 @@ is degraded now, for a client that polls it rather than reading one answer's lists an incident. Each incident is `{kind, subject, severity, detail, age_s}`, errors first, at most 20: -| `kind` | Listed when | Severity | -| ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | -| `readiness` | a readiness check of this process fails | error when required, else warn | -| `provider` | a provider's last call failed within `LOOM_OPS_INCIDENTS_WINDOW_MINUTES` (15); a later success clears it | warn | -| `worker` | an enabled worker's last 3 or more passes failed in a row, the last within 6 hours, in this deployment's processes (`loom.worker_status` rows labelled `deploy…` or unlabelled; an isolated or a bench server reads only its own label's) | warn | -| `requests` | at least `LOOM_OPS_INCIDENTS_ERROR_SHARE` (0.1) of one SLO class's calls in the org the call acts in failed on the server over the window, counted once the class has `LOOM_OPS_INCIDENTS_MIN_REQUESTS` (20) | error | +| `kind` | Listed when | Severity | +| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ | +| `readiness` | a readiness check of this process fails, except `draining`: a process shutting down still answers what it started, and every deploy drains one | error when required, else warn | +| `provider` | a provider's last call failed within `LOOM_OPS_INCIDENTS_WINDOW_MINUTES` (15); a later success clears it | warn | +| `worker` | an enabled worker's last 3 or more passes failed in a row, the last within 6 hours, in this deployment's processes (`loom.worker_status` rows unlabelled or whose label's first `:` segment is `deploy`; an isolated or a bench server reads only its own label's) | warn | +| `requests` | at least `LOOM_OPS_INCIDENTS_ERROR_SHARE` (0.1) of one SLO class's calls in the org the call acts in failed on the server over the window, counted once the class has `LOOM_OPS_INCIDENTS_MIN_REQUESTS` (20) | error | Request counts come from `loom_telemetry.sli_minute`, which trails the calls by about two minutes and keeps no namespace or user. They are read for the org the call acts in, and diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 2ae8d67233e..4e96afbcb5e 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -316,7 +316,10 @@ error's kind only; the full text is in the server log. - Over MCP the trimmed result keeps `degraded` at the top and drops the copies inside its sections; `loom_search` also ends its text with a `Degraded:` line. An idempotent replay answers the `degraded` its first answer carried, on either transport. -- `code.search` and `code.ask` do not cache an answer served from a fallback for a later call. +- An answer served from a fallback is not kept for a later call: `code.search` and + `code.ask` do not cache it, `code.map` does not keep its map, and `code.review_brief` + serves the brief unstored (`stored: false`). A later page of a `code.search` names the + entries its first page named. - Whether Loom is degraded now, rather than one answer, is [`ops.incidents`](./operations/ops.md#opsincidents) ([incidents](../operations/monitoring.md#opsincidents)). diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 2f081b383d5..50f15a4ed48 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -61,6 +61,7 @@ from server.code.store.index import CodeRepo from server.code.store.index.pr_history import PrFacts from server.core.errors import ValidationError +from server.observability import degradations from server.settings import settings from server.tracker.app import links as lk from server.tracker.app import patch_history as ph @@ -306,6 +307,7 @@ async def _file_presence( index_as_of(repo, org, ns), ) except Exception as e: # noqa: BLE001 — one branch's read, disclosed as unknown + degradations.note("code_index", "branch_presence_unread", e, health=False) logger.debug("backport_gap: file presence failed on %s: %s", ns, e) return [], [], False return ( @@ -319,6 +321,7 @@ async def _ledger_backports(repo: CodeRepo, org: str, ns: str, number: int) -> l try: rows = await repo.backport_prs_titled(org, ns, number) except Exception as e: # noqa: BLE001 — the ledger leg is a second opinion + degradations.note("code_index", "backport_ledger_dropped", e, health=False) logger.debug("backport_gap: ledger read failed on %s: %s", ns, e) return [] return [ @@ -508,6 +511,7 @@ async def _ledger_fix() -> PrFacts | None: try: return await repo.pr_facts(req.org, req.namespace, number) except Exception as e: # noqa: BLE001 — the ledger miss is disclosed on the fix block + degradations.note("code_index", "fix_ledger_unread", e, health=False) logger.debug("backport_gap: ledger fix read failed: %s", e) return None diff --git a/server/code/app/bisect.py b/server/code/app/bisect.py index 73ab3b3cf24..89f572567d9 100644 --- a/server/code/app/bisect.py +++ b/server/code/app/bisect.py @@ -90,6 +90,7 @@ from server.code.domain.time_window import _iso, _parse_when from server.code.store.index import CodeRepo from server.core.errors import ValidationError +from server.observability import degradations from server.settings import settings from server.tracker.app import links as lk from server.tracker.domain import bisect as bi @@ -117,6 +118,7 @@ async def lookup(name: str) -> list[str]: try: rows = await repo.symbols_by_name(org, ns, name, limit=12) except Exception as e: # noqa: BLE001 — one frame's miss is not the answer + degradations.note("code_index", "frame_paths_dropped", e, health=False) logger.debug("bisect: symbol lookup failed for %s: %s", name, e) rows = [] paths = [ @@ -209,6 +211,7 @@ async def _issue_edges(source: Any, org: str, tracker_ns: str, number: int) -> l ) ) except Exception as e: # noqa: BLE001 — the graph is a bonus, not the range + degradations.note("tracker", "issue_edges_dropped", e, health=False) logger.info("bisect: issue edges unavailable (%s)", e) return [] @@ -325,6 +328,7 @@ async def _attach_merge_shas(repo: CodeRepo, org: str, ns: str, ranked: list[bi. try: ref = await cb.indexed_head(repo, org, ns) or (f"refs/heads/{branch}" if branch else "") except Exception as e: # noqa: BLE001 — the head is unknown: no search past it + degradations.note("code_index", "mirror_search_skipped", e, health=False) logger.info("bisect: indexed head unread, mirror search skipped (%s)", e) ref = "" since = min((br.unix_of(c.merged_at) for c in ranked), default=0) diff --git a/server/code/app/bisect_fix.py b/server/code/app/bisect_fix.py index 04e2a8b17db..39595069902 100644 --- a/server/code/app/bisect_fix.py +++ b/server/code/app/bisect_fix.py @@ -21,6 +21,7 @@ from server.code.app.spans import code_span from server.code.domain.index import blame_introduced as intro from server.code.store.index import CodeRepo +from server.observability import degradations from server.settings import settings from server.tracker.domain import bisect as bi from server.tracker.domain import bisect_fusion as fu @@ -57,6 +58,7 @@ async def _cause_stage( org, tracker_ns, [c.pr_number for c in head], since=since[:19].replace("T", " ") ) except Exception as e: # noqa: BLE001 — a ranking prior, never the answer + degradations.note("tracker", "cause_statements_dropped", e, health=False) logger.info("bisect: cause statements unavailable (%s)", e) return pool if not stmts: @@ -160,6 +162,7 @@ async def _dupcheck_fix(task: Any, started: float | None = None) -> dict[str, An return {"status": "deadline", "budget_s": budget} return {"status": "timeout", "budget_s": budget} except Exception as e: # noqa: BLE001 — fail open + degradations.note("tracker", "dupcheck_fix_skipped", e, health=False) logger.info("bisect: duplicate-check fix skipped: %s", e) return {} @@ -257,6 +260,7 @@ async def _fix_named_stage( try: named = await read(org, tracker_ns, int(fix_pr)) except Exception as e: # noqa: BLE001 — fails open to the scan's order + degradations.note("tracker", "fix_cause_dropped", e, health=False) logger.info("bisect: fix #%s cause statement unavailable (%s)", fix_pr, e) return pool if not named: diff --git a/server/code/app/bisect_fusion.py b/server/code/app/bisect_fusion.py index e051cbc4ac1..56489fa4791 100644 --- a/server/code/app/bisect_fusion.py +++ b/server/code/app/bisect_fusion.py @@ -18,6 +18,7 @@ from server.core.background import create_deferred_task from server.core.llm_free import reads_llm_free from server.llm import customer +from server.observability import degradations from server.settings import settings from server.settings.budgets import llm_max_tokens from server.tracker.domain import bisect as bi @@ -37,6 +38,7 @@ async def _embed(text: str) -> list[float]: except customer.HOLDS: raise # the org's model calls are held: the request answers that except Exception as e: # noqa: BLE001 — no vector leg, the others still rank + degradations.note("embedder", "fusion_vector_leg_dropped", e, health=False) logger.info("bisect fusion: embed failed: %s", e) return [] @@ -59,6 +61,7 @@ async def _vector_order( numbers=numbers, ) except Exception as e: # noqa: BLE001 — the vector leg is optional + degradations.note("tracker", "fusion_vector_leg_dropped", e, health=False) logger.info("bisect fusion: vector read failed: %s", e) return [] return [int(h["number"]) for h in hits] diff --git a/server/code/app/bisect_scan.py b/server/code/app/bisect_scan.py index 3c78b0a2c02..13cd730ad62 100644 --- a/server/code/app/bisect_scan.py +++ b/server/code/app/bisect_scan.py @@ -13,6 +13,7 @@ from server.code.app.spans import code_span from server.code.domain.index.remote import pr_web_url from server.core.datetimes import naive_utc_now_seconds +from server.observability import degradations from server.settings import settings from server.tracker.domain import bisect as bi @@ -264,6 +265,7 @@ async def _code_history_rows( org, ns, paths=paths, dirs=dirs, before=before, after=after, limit=limit ) except Exception as e: # noqa: BLE001 — a failed history read is no candidates + degradations.note("code_index", "history_candidates_dropped", e, health=False) logger.info("bisect: code history of %s/%s unavailable: %s", org, ns, e) return [] cfg = repo_for_namespace(org, ns) diff --git a/server/code/app/blame.py b/server/code/app/blame.py index ebcc7f6c10e..404c948363c 100644 --- a/server/code/app/blame.py +++ b/server/code/app/blame.py @@ -55,6 +55,7 @@ from server.code.domain.index.compiler_tiers import state_value from server.code.domain.index.repos import default_git_dir from server.code.store.index import CodeRepo +from server.observability import degradations from server.settings import settings from server.tracker.domain import bisect as bi @@ -650,6 +651,7 @@ async def _issue_titles( items = await repo.items_by_number(org, ns, nums) except Exception as e: # noqa: BLE001 — a promotion source, not a leg logger.info("blame_range: issue titles unread: %s", e) + degradations.note("tracker", "issue_titles_unread", e, health=False) return {} return {n: str(r.get("title") or "") for n, r in items.items()} @@ -926,6 +928,7 @@ async def _indexed(repo: CodeRepo, org: str, ns: str, path: str) -> bool: try: return path in await repo.live_paths_present(org, ns, [path]) except Exception as e: # noqa: BLE001 — a fact for the verdict, not a leg + degradations.note("code_index", "path_presence_unread", e, health=False) logger.debug("blame_range: live_paths_present failed: %s", e) return False diff --git a/server/code/app/candidates.py b/server/code/app/candidates.py index 72e1366b656..0f3a63464b2 100644 --- a/server/code/app/candidates.py +++ b/server/code/app/candidates.py @@ -28,6 +28,7 @@ CodeCandidateSiteWire, ) from server.code.domain.extract.treesitter import lang_for_path +from server.observability import degradations if TYPE_CHECKING: from server.code.store.index import CodeRepo @@ -334,6 +335,7 @@ async def overrides_of( limit=OVERRIDE_FANOUT_CAP + 1, ) except Exception as e: # noqa: BLE001 + degradations.note("code_index", "override_callers_dropped", e, health=False) logger.debug("overrides read skipped: %s", e) return [], False out: list[dict[str, Any]] = [] diff --git a/server/code/app/citations.py b/server/code/app/citations.py index 606c2d35e97..70db5dee876 100644 --- a/server/code/app/citations.py +++ b/server/code/app/citations.py @@ -51,6 +51,7 @@ from server.code.domain.index.blame_range import sha_text from server.code.domain.index.repos import default_git_dir from server.code.store.index import CodeRepo +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -194,6 +195,7 @@ async def lookup(name: str) -> list[dict[str, Any]]: try: return await repo.symbols_by_name(org, ns, name, limit=20) except Exception as e: # noqa: BLE001 — one name's failure is one unresolved + degradations.note("code_index", "name_unresolved", e, health=False) logger.info("verify_citations: name lookup failed for %s: %s", name, e) return [] diff --git a/server/code/app/common.py b/server/code/app/common.py index eddf444de30..335970e040a 100644 --- a/server/code/app/common.py +++ b/server/code/app/common.py @@ -20,6 +20,7 @@ from server.core.background import create_deferred_task from server.core.errors import PreconditionFailedError from server.core.relative_paths import without_dot_slashes +from server.observability import degradations from server.observability.consumer import current_consumer from server.settings import settings @@ -290,7 +291,8 @@ async def index_as_of(repo: CodeRepo, org: str, ns: str) -> dict[str, Any]: block["failing_tiers"] = failing _AS_OF_CACHE.put((org, ns), block) return dict(block) - except Exception: # noqa: BLE001 — unknown freshness, not an error + except Exception as err: # noqa: BLE001 — unknown freshness, not an error + degradations.note("code_index", "as_of_unread", err, health=False) return {} diff --git a/server/code/app/context.py b/server/code/app/context.py index e066c6bfb02..5959dbcee36 100644 --- a/server/code/app/context.py +++ b/server/code/app/context.py @@ -29,6 +29,7 @@ from server.code.store.index import CodeRepo from server.core.ch import current_query_tag, set_query_tag from server.core.errors import OverloadedError +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -272,7 +273,8 @@ async def _render_map( if await repo.get_state(org, ns, "git_head") != head: continue artifact = _MapArtifact(text=text, commit_sha=head) - _MAP_CACHE.put(key, artifact) + if not degradations.current(): # a map a read left smaller is served, not kept + _MAP_CACHE.put(key, artifact) return artifact raise OverloadedError("Repository index changed while rendering the map; retry shortly.") @@ -303,7 +305,8 @@ async def _build_map_text( # excluded. try: hubs = await code_fan_in.top_under(repo, org, ns, module_prefix, limit=10) - except Exception: # noqa: BLE001 — the file cards stand alone + except Exception as e: # noqa: BLE001 — the file cards stand alone + degradations.note("code_index", "most_called_dropped", e, health=False) hubs = [] if hubs: head = "## Most-called symbols" + (f" under {module_prefix}" if module_prefix else "") @@ -329,8 +332,9 @@ async def _call_graph_hubs( callers = await repo.top_files_by_callers(org, ns, path_prefix=module_prefix, limit=20) paths = [str(r["path"]) for r in callers] cards = await repo.cards_for_paths(org, ns, model, paths) if paths else {} - except Exception: + except Exception as e: # the include-graph map is served without the call-graph hubs logger.info("code map: call-graph hubs unavailable for %s/%s", org, ns, exc_info=True) + degradations.note("code_index", "call_graph_hubs_dropped", e, health=False) return [], {} return callers, cards diff --git a/server/code/app/conventions.py b/server/code/app/conventions.py index bb1fa4b0c59..005736fda66 100644 --- a/server/code/app/conventions.py +++ b/server/code/app/conventions.py @@ -45,6 +45,7 @@ from server.code.domain.index.repos import repo_for_namespace from server.code.store.index import CodeRepo from server.core.errors import ValidationError +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -397,6 +398,7 @@ async def _wide_callers( # parser tier's extents say which function an added line falls in symbols = await repo.functions_for_paths(org, ns, paths) except Exception as e: # noqa: BLE001 — the check reports unknown + degradations.note("code_index", "wide_callers_unread", e, health=False) logger.info("conventions: functions read failed: %s", e) return [], {}, False, True funcs = conventions_rules.touched_functions(src.diff, symbols)[:_MAX_TOUCHED] @@ -413,6 +415,7 @@ async def _wide_callers( per_match=400, ) except Exception as e: # noqa: BLE001 — the check reports unknown + degradations.note("code_index", "wide_callers_unread", e, health=False) logger.info("conventions: callers read failed: %s", e) return funcs, {}, False, True conventions_rules.attach_callers(funcs, edges) diff --git a/server/code/app/fan_in.py b/server/code/app/fan_in.py index 6f1736b865a..845d783c0e5 100644 --- a/server/code/app/fan_in.py +++ b/server/code/app/fan_in.py @@ -25,6 +25,7 @@ from typing import Any from server.code.domain.units import CodeUnit, unit_from_symbol +from server.observability import degradations logger = logging.getLogger("loom.code_fan_in") @@ -78,6 +79,7 @@ async def annotate_units( try: stats = await stats_for(repo, org, ns, wanted[:1000]) except Exception as e: # noqa: BLE001 — the field is additive + degradations.note("code_index", "fan_in_dropped", e, health=False) logger.debug("fan-in annotation skipped: %s", e) return 0 n = 0 diff --git a/server/code/app/files.py b/server/code/app/files.py index 68a92a221f3..96d0c1f3da9 100644 --- a/server/code/app/files.py +++ b/server/code/app/files.py @@ -18,6 +18,7 @@ from server.code.app.search.shared import _not_covered_output from server.code.app.spans import code_span, set_code_span_attributes, span_attrs from server.code.store.index import CodeRepo +from server.observability import degradations logger = logging.getLogger(__name__) @@ -43,6 +44,7 @@ async def attach_reference_siblings( try: present = await repo.live_paths_present(org, ns, [p for c in cands.values() for p in c]) except Exception as e: # noqa: BLE001 — the sibling is decoration, never the answer + degradations.note("code_index", "reference_siblings_unread", e, health=False) logger.debug("code.files: reference sibling read skipped: %s", e) present = set() for i in cands: diff --git a/server/code/app/history.py b/server/code/app/history.py index 0b0d31b9b60..c8ca2bc23b3 100644 --- a/server/code/app/history.py +++ b/server/code/app/history.py @@ -39,6 +39,7 @@ from server.code.domain.units import CodeUnit, unit_from_chunk from server.embedding.normalize import normalize_whitespace +from server.observability import degradations logger = logging.getLogger(__name__) @@ -215,6 +216,7 @@ async def _tracker_facts(org: str, ns: str, nums: list[int]) -> dict[int, dict[s return {} return await tracker_facts_for_numbers(org, tracker_ns, nums) except Exception as e: # noqa: BLE001 — additive + degradations.note("tracker", "history_facts_dropped", e, health=False) logger.debug("qa history enrichment skipped: %s", e) return {} diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index e08b5b74b2c..f5bdab1d31e 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -39,6 +39,7 @@ from server.code.domain.index.state import IndexState, shown_detail from server.code.store.index import CodeRepo from server.core.background import create_deferred_task +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -47,8 +48,9 @@ # The status is caller-independent and costly per repository (a state read plus four git # subprocesses; a serial listing of ~20 repositories took over a second), so one answer per # (org, namespace) serves every caller for `code_status_ttl_s`, and a cold listing computes -# the misses concurrently under a small semaphore instead of in series. -_status_cache: dict[tuple[str, str], tuple[float, CodeIndexStatusOutput]] = {} +# the misses concurrently under a small semaphore instead of in series. The entry keeps the +# notes of the reads its status fell back on, and each answer it serves names them again. +_status_cache: dict[tuple[str, str], tuple[float, CodeIndexStatusOutput, list[str]]] = {} _status_sem = asyncio.Semaphore(8) @@ -69,6 +71,7 @@ async def _repo_status_cached( hit = _status_cache.get(key) now = time.monotonic() if hit is not None: + degradations.restore(hit[2]) if now - hit[0] < max_age_s: return hit[1] if key not in _status_refreshing: @@ -170,12 +173,18 @@ async def _compute_repo_status( async with _status_sem: hit = _status_cache.get(key) if hit is not None and time.monotonic() - hit[0] < settings.code_status_ttl_s: + degradations.restore(hit[2]) return hit[1] - # a caller without a prefetched state (code.index_status, tests' fakes) - # keeps the one-argument call - st = await (_repo_status(cfg, state=state) if state is not None else _repo_status(cfg)) - _status_cache[key] = (time.monotonic(), st) - create_deferred_task(_publish_status_snapshot(cfg, st)) + # its own notes: a listing computes the other repositories' statuses alongside + with degradations.scoped(): + # a caller without a prefetched state (code.index_status, tests' fakes) + # keeps the one-argument call + st = await (_repo_status(cfg, state=state) if state is not None else _repo_status(cfg)) + noted = degradations.current() + degradations.restore(noted) + _status_cache[key] = (time.monotonic(), st, noted) + if not noted: # another process's listing would serve the row without them + create_deferred_task(_publish_status_snapshot(cfg, st)) return st @@ -460,6 +469,7 @@ async def _index_quality( try: candidates = await tree_producers(repo, cfg.org, cfg.namespace) except Exception as e: # noqa: BLE001 — diagnostics must not break status + degradations.note("code_index", "compiler_inference_unread", e, health=False) logger.debug("code status: compiler inference unavailable for %s: %s", cfg.namespace, e) candidates = [] @@ -579,6 +589,7 @@ async def _read_worker_passes(client: Any, days: int) -> dict[str, dict[str, Any try: rows = await status_store.pass_summaries("code_", days, ch=client) except Exception as e: # noqa: BLE001 — the ledger is best-effort here + degradations.note("code_index", "worker_ledger_unread", e, health=False) logger.debug("code status: worker ledger unavailable: %s", e) return {} out: dict[str, dict[str, Any]] = {} @@ -775,9 +786,9 @@ async def _table_summary_cached( n, stamp = await read(CodeRepo()) rows, at = int(n), summary_stamp(stamp) except Exception as e: # noqa: BLE001 — status stays whole when the read fails + degradations.note("code_index", f"{what.replace(' ', '_')}_summary_unread", e, health=False) logger.debug("code status: %s summary unavailable for %s: %s", what, ns, e) - cache[cache_key] = (now, rows, at) - return rows, at + return rows, at # not kept: the status entry names the failure, the next one reads if key and published is None: try: await CodeRepo().publish_summary(org, ns, key, rows, at) diff --git a/server/code/app/repo_scope.py b/server/code/app/repo_scope.py index b4d31cfca42..8a5b8aafd75 100644 --- a/server/code/app/repo_scope.py +++ b/server/code/app/repo_scope.py @@ -19,6 +19,7 @@ repo_for_namespace, ) from server.code.domain.scope import current_code_scope +from server.observability import degradations from server.operations.base import Role log = logging.getLogger("loom.repo_scope") @@ -44,6 +45,7 @@ async def readable_repo_namespace(org: str, code_namespace: str) -> str: except RegistryUnread: return "" # unread: closed, and no gate failure worth a warning per request except Exception as e: # noqa: BLE001 — a gate that cannot check refuses + degradations.note("identity", "repo_legs_dropped", e, health=False) # One line per scoped request while the grants read is down. log.warning("repository namespace gate failed (closed): %s", e) return "" diff --git a/server/code/app/repos.py b/server/code/app/repos.py index e529f2d2835..b1618c58bd4 100644 --- a/server/code/app/repos.py +++ b/server/code/app/repos.py @@ -17,6 +17,7 @@ from server.code.domain.index.state import STAGE_KEY, shown_detail from server.code.store.index import CodeRepo from server.core.grant_sql import LIVE_GRANT +from server.observability import degradations from server.operations.read_projection import project_rows logger = logging.getLogger(__name__) @@ -417,7 +418,8 @@ async def _aliases() -> list[str]: # gate the listing read them, so a failed read must leave it None and # the gate reads each grant for itself. maintained = maintained_now - except Exception: # noqa: BLE001 — directory state is an affordance, not a gate + except Exception as err: # noqa: BLE001 — directory state is an affordance, not a gate + degradations.note("identity", "directory_state_unread", err, health=False) return policies, standing, roles, maintained return policies, standing, roles, maintained diff --git a/server/code/app/search/cards.py b/server/code/app/search/cards.py index 18e46200e57..b5f1087c3f8 100644 --- a/server/code/app/search/cards.py +++ b/server/code/app/search/cards.py @@ -17,6 +17,7 @@ from server.code.domain.index import query_trim from server.code.domain.search_scope import SearchScope from server.code.store.index import CodeRepo +from server.observability import degradations from server.settings import settings from server.settings.budgets import llm_max_tokens @@ -227,6 +228,7 @@ async def _source_cards() -> list[dict[str, Any]]: skip_tests=True, ) except Exception as e: # noqa: BLE001 — a vote, never a gate + degradations.note("code_index", "card_leg_dropped", e, health=False) logger.warning("code.search card term read failed: %s", e) return [] diff --git a/server/code/app/search/definitions.py b/server/code/app/search/definitions.py index 3de86e56805..f2d0658c8cd 100644 --- a/server/code/app/search/definitions.py +++ b/server/code/app/search/definitions.py @@ -33,6 +33,7 @@ from server.code.domain.units import CodeUnit, unit_from_chunk from server.code.store.index import CodeRepo, is_noise_path from server.core.ch import statement_timeout +from server.observability import degradations logger = logging.getLogger(__name__) @@ -403,6 +404,7 @@ async def _or_nothing(lookup: str, read: Awaitable[list[dict[str, Any]]]) -> lis try: return await read except Exception as e: # noqa: BLE001 — the definitions add to an answer, never gate it + degradations.note("code_index", "definition_leg_dropped", e, health=False) logger.warning("code.search definition leg failed (%s lookup): %s", lookup, e) return [] diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index e57881e8395..4b3477c7792 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -563,6 +563,7 @@ def _issue_search_cursor( "top_similarity": res.top_similarity, "score_explanation": res.score_explanation, }, + degraded=degradations.current(), ) paging.put_pool( org, @@ -609,6 +610,8 @@ async def _serve_search_page( if row is None: return None, "pool_not_found", offset payload = row["payload"] + # The pool holds what the first page's fallbacks left: each page says so again. + degradations.restore(payload.get("degraded")) pool = list(payload.get("pool") or []) entries, next_offset, has_more = paging.take_page( pool, offset=offset, size=input.top_k, exclude=set(input.exclude_unit_ids) diff --git a/server/code/app/search/history.py b/server/code/app/search/history.py index f534b7d3bd4..60dd2930f21 100644 --- a/server/code/app/search/history.py +++ b/server/code/app/search/history.py @@ -14,6 +14,7 @@ from server.code.domain.units import CodeUnit, budget_units, remaining_token_budget from server.code.store.index import CodeRepo from server.core import bm25 +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -85,6 +86,7 @@ async def _history_leg( ) ) except Exception as e: # noqa: BLE001 — history is a vote, never a gate + degradations.note("code_index", "history_leg_dropped", e, health=False) logger.warning("code.search history leg failed: %s", e) rows = [] span_attrs(sp, results=len(rows), prs=history_stats["prs"], files=history_stats["files"]) diff --git a/server/code/app/search/symbol.py b/server/code/app/search/symbol.py index fdc0e211c4e..0be23dbae84 100644 --- a/server/code/app/search/symbol.py +++ b/server/code/app/search/symbol.py @@ -16,6 +16,7 @@ from server.code.domain.search_scope import SearchScope from server.code.domain.units import CodeUnit, _card_of, budget_units from server.code.store.index import CodeRepo +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -280,6 +281,7 @@ async def _fuzzy_symbol_vote( try: hit = bool(await repo.symbols_fuzzy(org, ns, bare, limit=1)) except Exception as e: # noqa: BLE001 — a vote, never a gate + degradations.note("code_index", "symbol_vote_dropped", e, health=False) logger.warning("code.search fuzzy-symbol vote failed: %s", e) hit = False span_attrs(sp, results=int(hit)) diff --git a/server/code/app/search_cursor.py b/server/code/app/search_cursor.py index f3f15facff2..1f9fce7f2f9 100644 --- a/server/code/app/search_cursor.py +++ b/server/code/app/search_cursor.py @@ -338,7 +338,10 @@ def search_pool_payload( served: int, pool: list[CodeUnit], calibration: dict[str, Any], + degraded: list[str], ) -> dict[str, Any]: + """The pool row's payload. `degraded`: the first page's notes, which every later page + serves again, since the pool holds what that page's fallbacks left.""" return { "v": CURSOR_VERSION, "kind": "s", @@ -349,4 +352,5 @@ def search_pool_payload( "served": int(served), "pool": [pool_entry(u) for u in pool[: pool_cap()]], "calib": calibration, + "degraded": list(degraded), } diff --git a/server/code/app/symbol/enclosing.py b/server/code/app/symbol/enclosing.py index c2044926320..248fe34ce03 100644 --- a/server/code/app/symbol/enclosing.py +++ b/server/code/app/symbol/enclosing.py @@ -24,6 +24,7 @@ from server.code.app.symbol.resolve import _innermost, symbol_body from server.code.domain.units import symbol_signature from server.code.store.index import CodeRepo +from server.observability import degradations logger = logging.getLogger(__name__) @@ -328,7 +329,8 @@ async def _doc_sections( with code_span("enclosing.sections", paths=len(paths)) as sp: chunks = await repo.chunk_spans_for_paths(org, ns, paths) span_attrs(sp, rows=sum(len(v) for v in chunks.values())) - except Exception: # A section lookup failure leaves other locations usable. + except Exception as err: # A section lookup failure leaves other locations usable. + degradations.note("code_index", "sections_dropped", err, health=False) logger.warning("code.enclosing section read failed", exc_info=True) return {} return section_rows(chunks) diff --git a/server/code/app/symbol/enclosing_decorators.py b/server/code/app/symbol/enclosing_decorators.py index 096a8329521..67ac56aa58c 100644 --- a/server/code/app/symbol/enclosing_decorators.py +++ b/server/code/app/symbol/enclosing_decorators.py @@ -9,6 +9,7 @@ from server.code.app.symbol.resolve import _innermost from server.code.store.index import CodeRepo from server.embedding.embedder import served_model_label +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -63,7 +64,9 @@ async def extend_decorated_spans( org, ns, served_model_label(settings.embedding_model), keys, revisions=revisions ) span_attrs(span, rows=len(starts)) - except Exception: # Optional ownership evidence can be absent while exact matches still work. + except Exception as err: + # Optional ownership evidence can be absent while exact matches still work. + degradations.note("code_index", "decorator_extents_unread", err, health=False) logger.warning("code.enclosing could not read declaration extents", exc_info=True) return set() widened: set[tuple[str, str]] = set() diff --git a/server/code/app/symbol/outline.py b/server/code/app/symbol/outline.py index d744fdab2f4..2f056bded98 100644 --- a/server/code/app/symbol/outline.py +++ b/server/code/app/symbol/outline.py @@ -25,6 +25,7 @@ from server.code.domain.index.verdicts import is_abstain, outline_verdict from server.code.store.index import CodeRepo from server.core.errors import ValidationError +from server.observability import degradations logger = logging.getLogger(__name__) @@ -231,6 +232,7 @@ async def _reference_head(repo: CodeRepo, org: str, ns: str, path: str) -> tuple try: rows = await repo.chunks_of_path(org, ns, path, limit=1) except Exception as e: # noqa: BLE001 + degradations.note("code_index", "reference_head_unread", e, health=False) logger.debug("reference head read skipped: %s", e) return "", False if not rows: diff --git a/server/code/app/symbol/resolve.py b/server/code/app/symbol/resolve.py index 0cd54bd2118..94992bb4bfb 100644 --- a/server/code/app/symbol/resolve.py +++ b/server/code/app/symbol/resolve.py @@ -16,6 +16,7 @@ from server.code.domain.symbol_body import complete_source_span from server.code.store.index import CodeRepo from server.embedding.embedder import served_model_label +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -269,6 +270,7 @@ async def _file_row(repo: CodeRepo, org: str, ns: str, path: str) -> dict[str, A try: rows = await repo.live_files_for_path(org, ns, path) except Exception as e: # noqa: BLE001 + degradations.note("code_index", "file_row_unread", e, health=False) logger.debug("file-row read skipped: %s", e) return None return rows[0] if rows else None diff --git a/server/code/app/symbol/symbol.py b/server/code/app/symbol/symbol.py index 59876c64611..44b2aa02f7c 100644 --- a/server/code/app/symbol/symbol.py +++ b/server/code/app/symbol/symbol.py @@ -258,7 +258,8 @@ async def _chunk_hashes( return await repo.chunk_hashes_for_symbols( org, ns, [str(r.get("symbol_id") or "") for r in head], rows=head ) - except Exception: # noqa: BLE001 — additive, never fatal + except Exception as err: # noqa: BLE001 — additive, never fatal + degradations.note("code_index", "body_hash_unread", err, health=False) return {} diff --git a/server/code/app/symbol/verify.py b/server/code/app/symbol/verify.py index 93678073c39..d5769278319 100644 --- a/server/code/app/symbol/verify.py +++ b/server/code/app/symbol/verify.py @@ -35,6 +35,7 @@ from server.code.store.index import CodeRepo from server.code.store.index import prefer_scip_edges as _prefer_scip_edges from server.core.errors import NotFoundError +from server.observability import degradations _TEMPLATE_ARGS = re.compile(r"<[^<>]*>") @@ -75,7 +76,8 @@ async def _body_complete(repo: CodeRepo, org: str, ns: str, seeds: list[dict[str path, start, end = max(spans, key=lambda t: t[2] - t[1]) try: span = await repo.chunk_line_span(org, ns, path, start, end) - except Exception: # noqa: BLE001 — an unreadable span proves nothing + except Exception as err: # noqa: BLE001 — an unreadable span proves nothing + degradations.note("code_index", "body_span_unread", err, health=False) return False return span is not None and span[0] <= start and span[1] >= end diff --git a/server/code/app/symbol_context.py b/server/code/app/symbol_context.py index 77973a66a96..7872eb57b42 100644 --- a/server/code/app/symbol_context.py +++ b/server/code/app/symbol_context.py @@ -34,6 +34,7 @@ from server.code.store.index import is_generated_path, is_noise_path from server.core.relative_paths import without_dot_slashes +from server.observability import degradations logger = logging.getLogger("loom.code_symbol_context") @@ -147,6 +148,7 @@ async def context_paths( try: facts = await repo.prs_by_number(org, ns, [int(pr_number)]) except Exception as e: # noqa: BLE001 — context is a ranking aid, never fatal + degradations.note("code_index", "pr_context_unread", e, health=False) logger.debug("code.symbol pr_number context read failed: %s", e) return [] row = facts.get(int(pr_number)) or {} diff --git a/server/code/app/symbol_uses.py b/server/code/app/symbol_uses.py index 5776f01e4a0..34ffed7a80c 100644 --- a/server/code/app/symbol_uses.py +++ b/server/code/app/symbol_uses.py @@ -38,6 +38,7 @@ from server.code.domain.extract.treesitter import lang_for_path from server.code.domain.index.epistemic import scip_coverage_from_rows from server.code.store.index import SYMBOL_NOISE_PATH_RE, prefer_scip_edges +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -290,6 +291,7 @@ async def uses_brief( try: stats = await code_fan_in.stats_for(repo, org, ns, ids) except Exception as e: # noqa: BLE001 — the gate falls back to the read cap + degradations.note("code_index", "fan_in_dropped", e, health=False) logger.debug("code.symbol uses fan-in gate skipped: %s", e) threshold = int(settings.code_symbol_uses_hub_fan_in) fan_in = hub_fan_in(stats, ids) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index 0ef75fa00dd..2809858f35f 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -10,8 +10,9 @@ `prs_per_pass` fixes a night, never computed first and then the stalest, and a fix whose every branch row is settled (covered / not_affected exact) is skipped until its window closes. The leg stops cleanly at `budget_s` -and says where; a QA miss on one fix writes nothing for it (a night of -`unknown` rows would overwrite a day of verdicts) and the next fix runs. +and says where; a QA miss on one fix, or a read its answer fell back on, +writes nothing for it (a night of `unknown` rows would overwrite a day of +verdicts) and the next fix runs. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ @@ -28,6 +29,7 @@ from server.code.store.backport_gaps import FixStamp, GapRow, build_gap_row from server.core.datetimes import naive_utc_now_seconds as _now +from server.observability import degradations from server.settings import settings from server.workers.pass_context import note_failure from server.workers.status import log_pass_errors, record_pass @@ -251,29 +253,34 @@ async def compute_fix( version: int, ) -> list[GapRow]: """One fix's composed read → its table rows; [] when the fix could not be - read or its tracker record did not answer (a night of unknowns must not - overwrite verdicts), counted on the result either way.""" + read, its tracker record did not answer, or a read it fell back on left a + smaller answer (a night of unknowns must not overwrite verdicts), counted on + the result either way.""" from server.code.app.backport import BackportGapRequest try: - out = await runner( - BackportGapRequest( - org=cfg.org, - namespace=cfg.namespace, - pr_number=pr, - exact=True, - history=True, - consumer=CONSUMER, - trace=False, + with degradations.scoped(): + out = await runner( + BackportGapRequest( + org=cfg.org, + namespace=cfg.namespace, + pr_number=pr, + exact=True, + history=True, + consumer=CONSUMER, + trace=False, + ) ) - ) + noted = degradations.current() except Exception as e: # noqa: BLE001 — one fix must not end the pass result.fixes_unavailable += 1 note_failure(e, f"code_backport_gaps:#{pr}") logger.info("code_backport_gaps: #%s failed: %s", pr, e) return [] - if bool(getattr(out, "tracker_unavailable", False)) or "tracker_unbound" in list( - out.causes or [] + if ( + noted + or bool(getattr(out, "tracker_unavailable", False)) + or "tracker_unbound" in list(out.causes or []) ): result.fixes_unavailable += 1 return [] diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index ba34de491ef..d434e8bdd2b 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -187,7 +187,9 @@ class OpsIncident(BaseModel): # `error` when calls fail or answer without the part that failed; `warn` when # answers are thinner or staler than normal. severity: Literal["warn", "error"] - # What is failing, in one line: an error's kind, never its text. + # What is failing, in one line: the readiness check's reason, the provider's error + # kind, the worker's streak and its last error's kind, or the class's failed and total + # calls; never a provider's or a worker's error text. detail: str # Seconds since the failure was last seen; null when its source keeps no time. age_s: float | None = None diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 2097a3445c4..2d0d23f0fca 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -80,7 +80,8 @@ async def _cached( async def _readiness() -> list[OpsIncident]: """A failing readiness check: required ones stop this server taking traffic. The checks cache their own answers, and a check that raises or times out answers as - failing.""" + failing. `draining` is left out: a process shutting down still answers what it + started, and every deploy drains one.""" from server.core import readiness state = await readiness.evaluate() @@ -92,7 +93,7 @@ async def _readiness() -> list[OpsIncident]: detail=_line(check.reason or "failing"), ) for name, check in state.checks.items() - if not check.ok + if not check.ok and name != "draining" ] diff --git a/server/memory/app/ask/cascade.py b/server/memory/app/ask/cascade.py index ebc038bfeff..edeb7b5f648 100644 --- a/server/memory/app/ask/cascade.py +++ b/server/memory/app/ask/cascade.py @@ -20,6 +20,7 @@ from server.memory.app.ask.source_context import cancel_and_drain from server.memory.app.ask.state import _LAST_SYNTH_MODEL, _retain_task_result from server.memory.app.ask.synthesis import _not_recorded_second, _synthesize +from server.observability import degradations @dataclass(slots=True) @@ -608,11 +609,13 @@ async def _deferred_judge() -> Any: # window. The write hashes the window off the request path. if codes_only(): return verdict, note, premise_text, None + # An answer a fallback served is no precedent: its reuse would drop the `degraded`. _precedent_eligible = bool( precedent_key and marked_cited and not ans.deep_fired and not _policy.cheap_answer_failed(ans.answer, ans.cited) + and not degradations.current() ) _prec_synth_model = _LAST_SYNTH_MODEL.get() or str(getattr(ans.client, "model", "") or "") _prec_cited, _prec_answer = list(ans.cited), ans.answer diff --git a/server/memory/app/ask/completion.py b/server/memory/app/ask/completion.py index 2f4f7d423f7..ac0751a7ae0 100644 --- a/server/memory/app/ask/completion.py +++ b/server/memory/app/ask/completion.py @@ -13,6 +13,7 @@ from server.memory.app.ask.identity import memory_identity_where from server.memory.app.search_tag_filter import request_hard_tags, stamp_row_tags from server.memory.domain.search_types import row_identity +from server.observability import degradations logger = logging.getLogger(__name__) @@ -385,6 +386,7 @@ async def _once() -> list[dict[str, Any]]: try: return await _call_retrying_empty_block(_once, leg=leg) except Exception as e: # noqa: BLE001 — additive, never fatal: fail open to no rows + degradations.note("memory.ask", f"{leg.replace(' ', '_')}_dropped", e, health=False) logger.debug("%s failed: %s", leg, e) return None diff --git a/server/memory/app/ask/context_blocks.py b/server/memory/app/ask/context_blocks.py index 8ac4189a377..809dd5b347a 100644 --- a/server/memory/app/ask/context_blocks.py +++ b/server/memory/app/ask/context_blocks.py @@ -10,6 +10,7 @@ from server.knowledge.app.source_corpus import LostCorpus from server.knowledge.app.source_passages import CheckedPassages, collect from server.memory.app.ask.source_context import PreparedKnowledge, prepare_knowledge +from server.observability import degradations from server.observability.genai import current_stage, llm_stage from server.settings import settings @@ -116,7 +117,8 @@ async def knowledge_passages( return AskKnowledge(passages) except LostCorpus: raise - except Exception: # noqa: BLE001 — an unavailable additive plane contributes no passages + except Exception as err: # noqa: BLE001 — an unavailable additive plane contributes no passages + degradations.note("memory.ask", "knowledge_dropped", err, health=False) logger.warning("knowledge plane on ask unavailable") return AskKnowledge() diff --git a/server/memory/app/ask/identifiers.py b/server/memory/app/ask/identifiers.py index 6a6892f5f66..50d53dc4be7 100644 --- a/server/memory/app/ask/identifiers.py +++ b/server/memory/app/ask/identifiers.py @@ -18,6 +18,7 @@ from server.memory.app.ask.result import _is_chunk_hit from server.memory.domain.search_types import row_identity from server.memory.domain.sensitivity import HELD_MARGIN, without_high +from server.observability import degradations logger = logging.getLogger(__name__) @@ -150,6 +151,7 @@ async def _mention_window_chunks(search_input: Any, question: str, ranked: list[ user_id=getattr(search_input, "user_id", None), ) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.note("memory.ask", "mention_window_dropped", e, health=False) logger.debug("mention-window chunks skipped: %s", e) return [] @@ -472,6 +474,7 @@ async def _read_decisive_chunks( markers=list(_DECISIVE_MARKERS), ) except Exception as e: # noqa: BLE001 — additive + degradations.note("memory.ask", "decisive_chunks_dropped", e, health=False) logger.debug("decisive chunk injection failed: %s", e) return [] @@ -519,6 +522,7 @@ async def _read_latest_word( order="recency", ) except Exception as e: # noqa: BLE001 — additive + degradations.note("memory.ask", "latest_word_dropped", e, health=False) logger.debug("recent identifier injection failed: %s", e) return rows @@ -550,7 +554,8 @@ async def _inject_identifier_memories( q = getattr(search_input, "query", "") or "" if q: qvec = list(await get_embedder().embed(q)) - except Exception: # noqa: BLE001 — relevance ranking is best-effort + except Exception as err: # noqa: BLE001 — relevance ranking is best-effort + degradations.note("embedder", "identifier_ranking_dropped", err, health=False) qvec = [] # A fresh namespace's rows may sit on a replica this query has not seen # yet (SharedMergeTree): the main leg read with sequential @@ -623,6 +628,7 @@ async def _inject_identifier_memories( search_input, idents, case_insensitive, _lim_settings ) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.note("memory.ask", "identifier_rows_dropped", e, health=False) logger.debug("identifier injection failed: %s", e) return [] diff --git a/server/memory/app/ask/reader.py b/server/memory/app/ask/reader.py index 427f8f07147..8674ab0bf24 100644 --- a/server/memory/app/ask/reader.py +++ b/server/memory/app/ask/reader.py @@ -11,6 +11,7 @@ from server.memory.app.ask.pool import _AskRun from server.memory.app.ask.question_shapes import is_count_intent from server.memory.app.ask.result import _by_keys, _keys_of +from server.observability import degradations logger = logging.getLogger(__name__) @@ -161,6 +162,7 @@ async def _trusted_in_pool(search_input: Any, memories: list[Any]) -> list[Any]: params={**params, "keys": keys}, ) except Exception as e: # noqa: BLE001 — a trust read never blocks an answer + degradations.note("memory.ask", "trust_unread", e, health=False) logger.warning("memory.ask trusted-row read failed (open): %s", e) return [] return trusted_rows([dict(r) for r in rows], keys) diff --git a/server/memory/app/ask/records.py b/server/memory/app/ask/records.py index d94c99c0a2d..0cde10c48f4 100644 --- a/server/memory/app/ask/records.py +++ b/server/memory/app/ask/records.py @@ -7,6 +7,7 @@ from typing import Any, cast from server.memory.app.ask.result import MemoryAskResult +from server.observability import degradations logger = logging.getLogger(__name__) @@ -87,9 +88,11 @@ async def _gh_items_fallback_answer( try: prs = await repo.prs_by_number(code_org, code_ns, numbers) except Exception as e: # noqa: BLE001 — items alone still answer + degradations.note("memory.ask", "pr_history_dropped", e, health=False) logger.warning("memory.ask pr-history fallback failed (open): %s", e) prs = {} except Exception as e: # noqa: BLE001 — the fallback never blocks an abstention + degradations.note("memory.ask", "items_fallback_dropped", e, health=False) logger.warning("memory.ask gh-items fallback failed (open): %s", e) return None as_of = getattr(search_input, "as_of", None) diff --git a/server/memory/app/ask/supersession.py b/server/memory/app/ask/supersession.py index 277876e08c0..9397d86d227 100644 --- a/server/memory/app/ask/supersession.py +++ b/server/memory/app/ask/supersession.py @@ -10,6 +10,7 @@ from typing import Any from server.memory.app.ask.identity import memory_identity_where +from server.observability import degradations logger = logging.getLogger(__name__) @@ -117,6 +118,7 @@ async def superseded_rows_for_pool( params={**params, "keys": keys, "lim": int(limit)}, ) except Exception as e: # noqa: BLE001 — a mask read never blocks an answer + degradations.note("memory.ask", "supersession_unchecked", e, health=False) logger.warning("memory.ask superseded-row read failed (open): %s", e) return [] from types import SimpleNamespace diff --git a/server/memory/app/ask_when_evidence.py b/server/memory/app/ask_when_evidence.py index 8de9fca48a0..10051d72db8 100644 --- a/server/memory/app/ask_when_evidence.py +++ b/server/memory/app/ask_when_evidence.py @@ -26,6 +26,7 @@ class last Friday" into an attribute ("Deborah does yoga") or into nothing, from typing import Any from server.memory.domain.sensitivity import without_high +from server.observability import degradations log = logging.getLogger(__name__) @@ -215,6 +216,7 @@ async def _recall_turns(kwargs: dict[str, Any]) -> list[DatedTurn]: out = await handle_memory_recall(MemoryRecallInput(**kwargs)) except Exception as e: # noqa: BLE001 — the first answer stands when recall fails + degradations.note("memory.ask", "dated_turns_dropped", e, health=False) log.warning("ask when-evidence recall failed (open): %s", e) return [] turns: list[DatedTurn] = [] diff --git a/server/memory/app/code_grounding.py b/server/memory/app/code_grounding.py index 586c2c317b9..1b835921b91 100644 --- a/server/memory/app/code_grounding.py +++ b/server/memory/app/code_grounding.py @@ -24,6 +24,7 @@ from server.memory.domain import code_change from server.memory.store.code_links import LinkRow +from server.observability import degradations logger = logging.getLogger(__name__) @@ -83,6 +84,7 @@ async def _authorized_code_target(search_input: Any, settings: Any) -> tuple[str ) return ("", "") except Exception as e: # noqa: BLE001 — fail closed: no target + degradations.note("memory.ask", "code_grounding_dropped", e, health=False) logger.debug("code grounding authorization failed: %s", e) return ("", "") try: @@ -234,7 +236,8 @@ async def _symbol(sym: str) -> Any | None: consumer=GROUNDING_CONSUMER, ) ) - except Exception: # noqa: BLE001 — additive + except Exception as err: # noqa: BLE001 — additive + degradations.note("memory.ask", "code_symbol_dropped", err, health=False) return None async def _search() -> Any | None: @@ -251,6 +254,7 @@ async def _search() -> Any | None: ) ) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.note("memory.ask", "code_search_dropped", e, health=False) _warn_once("code-context search fallback failed: %s", e) return None @@ -415,6 +419,7 @@ async def _inject_pr_facts( repo = code_index() facts = await repo.prs_by_number(code_org, code_ns, numbers) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.note("memory.ask", "pr_facts_dropped", e, health=False) _warn_once("pr-fact grounding failed: %s", e) return [] as_of = getattr(search_input, "as_of", None) @@ -527,6 +532,7 @@ async def _gate_future_prs( repo = code_index() facts = await repo.prs_by_number(code_org, code_ns, numbers) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.note("memory.ask", "pr_temporal_gate_skipped", e, health=False) logger.debug("pr-temporal gate lookup failed: %s", e) return memories # PRs whose open date is known AND strictly after the anchor = didn't exist. @@ -548,6 +554,7 @@ async def _gate_future_prs( try: items = await repo.items_by_number(code_org, code_ns, rest, within_head=False) except Exception as e: # noqa: BLE001 — absent table or row: never gated + degradations.note("memory.ask", "pr_temporal_gate_skipped", e, health=False) logger.debug("gh-items temporal lookup failed: %s", e) items = {} for num, row in items.items(): @@ -591,6 +598,7 @@ async def _annotate_stale_code_memories(memories: list[Any], search_input: Any) cns = {a["code_namespace"] for v in read for a in v} seen = await readable_namespaces(str(search_input.org), cns) except Exception as e: # noqa: BLE001 — grounding is advisory + degradations.note("memory.ask", "code_staleness_unchecked", e, health=False) _warn_once("code staleness: links unreadable: %s", e) return None for i, v in zip(unread, read, strict=True): diff --git a/server/memory/app/code_link_reads.py b/server/memory/app/code_link_reads.py index a4efcd6fab1..e01ee8b8d63 100644 --- a/server/memory/app/code_link_reads.py +++ b/server/memory/app/code_link_reads.py @@ -20,6 +20,7 @@ from server.memory.domain.files import names_file from server.memory.store import code_links as store from server.memory.store.code_links import LinkRow +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -174,6 +175,7 @@ async def links_of(org: str, memory: dict[str, Any]) -> list[CodeLink]: rows = current(org, memory, await store.for_memories(org, [str(memory["mid"])])) seen = await readable_namespaces(org, {a["code_namespace"] for a in rows}) except Exception as e: # noqa: BLE001 — the links are additive to the read + degradations.note("memory.get", "code_links_dropped", e, health=False) log.debug("code links unavailable: %s", e) return [] return [ @@ -318,6 +320,7 @@ async def annotate_hits(input: Any, hits: list[Any]) -> None: try: memories, seen, policies = await _annotation_reads(input, hits) except Exception as e: # noqa: BLE001 — the links are additive to the read + degradations.note("memory.search", "code_links_unread", e, health=False) log.debug("code links unavailable: %s", e) for h in hits: if unlinked(h): diff --git a/server/memory/app/context_pack.py b/server/memory/app/context_pack.py index 09fe9e50426..a7a7644b358 100644 --- a/server/memory/app/context_pack.py +++ b/server/memory/app/context_pack.py @@ -57,6 +57,7 @@ from server.memory.domain.evidence_pack import EvidenceItem, pack_evidence from server.memory.domain.memory_types import excluded_from_unfiltered_search from server.memory.domain.search_types import SHARED_AGENT, hit_row, hit_row_key, names_row +from server.observability import degradations if TYPE_CHECKING: from server.knowledge.api.models_knowledge import _SearchHit @@ -421,6 +422,7 @@ def _vtext(v: Any) -> str: pinned = await memory_repo.list_by_namespace(ident, pinned_only=True, limit=k, **shape) recent = await memory_repo.list_by_namespace(ident, limit=k * 2, **shape) except Exception as e: # noqa: BLE001 — recall is best-effort + degradations.note("context.pack", "startup_recall_dropped", e, health=False) log.warning("context.pack startup recall failed: %s", e) return @@ -553,6 +555,7 @@ async def _hit_actors(input: ContextPackInput, hits: list[Any]) -> _KeyWriters: scope=request_scope(), ) except Exception as e: # noqa: BLE001 — authorship labels are best-effort; lines say by=unknown + degradations.note("context.pack", "authors_unknown", e, health=False) log.warning("context.pack: memory authors unavailable: %s", e) return {} @@ -1049,6 +1052,7 @@ async def _optional_section(name: str, work: Awaitable[Any]) -> Any: try: return await work except Exception as error: # noqa: BLE001 — a failed optional section leaves other sections available + degradations.note("context.pack", f"{name}_dropped", error, health=False) log.warning("context.pack: section %s failed: %s", name, error) return None @@ -1368,7 +1372,8 @@ async def run_checked_pack(input: ContextPackInput) -> CheckedPack: ) ) scopes.update(request.namespaces) - except Exception: # noqa: BLE001 — scope failure omits only the optional direct knowledge section + except Exception as err: # noqa: BLE001 — scope failure omits only the optional direct knowledge section + degradations.note("context.pack", "knowledge_scope_dropped", err, health=False) log.warning("context.pack: knowledge scope unavailable") if input.include_knowledge and st.wanted("memory_stack"): scopes.add(input.namespace) diff --git a/server/memory/app/deep_evidence.py b/server/memory/app/deep_evidence.py index 04a16110690..6cd57210160 100644 --- a/server/memory/app/deep_evidence.py +++ b/server/memory/app/deep_evidence.py @@ -40,6 +40,7 @@ from server.identity.domain.read_scope import scope_and from server.knowledge.app.source_corpus import LostCorpus from server.memory.domain.sensitivity import without_high +from server.observability import degradations from server.settings.budgets import llm_max_tokens log = logging.getLogger(__name__) @@ -300,6 +301,7 @@ async def fetch_raw_evidence( else [] ) except Exception as e: # noqa: BLE001 — fail-open, keep the excerpt answer + degradations.note("memory.ask", "raw_evidence_dropped", e, health=False) log.warning("deep-evidence fetch failed (fail-open): %s", e) return [] rows = join_links_to_evidence(links, evidence) diff --git a/server/memory/app/entity_resolution.py b/server/memory/app/entity_resolution.py index 7dde1d7df7a..9173ddc2c26 100644 --- a/server/memory/app/entity_resolution.py +++ b/server/memory/app/entity_resolution.py @@ -19,6 +19,7 @@ from server.core.errors import VectorInputTooLargeError from server.memory.api.models_search import SEARCH_ENTITY_FILTER_MAX from server.memory.domain.graph_quality import canonical_entity_text +from server.observability import degradations _MIN_FUZZY_SCORE = 0.95 _MAX_NORMALIZED_ENTROPY = 0.55 @@ -567,7 +568,8 @@ async def lookup_canonical_entities( ) except VectorInputTooLargeError: raise - except Exception: # noqa: BLE001 — a failed alias read keeps the given entities + except Exception as err: # noqa: BLE001 — a failed alias read keeps the given entities + degradations.note("memory.search", "entity_aliases_dropped", err, health=False) return ordered # A full sentinel page cannot prove that omitted aliases fit the bound. if len(rows) > _MAX_EFFECTIVE_ENTITY_FILTER: diff --git a/server/memory/app/facts.py b/server/memory/app/facts.py index 6bf21ac9ea1..b6a976d9e6c 100644 --- a/server/memory/app/facts.py +++ b/server/memory/app/facts.py @@ -31,6 +31,7 @@ _edge_set_sql, _traverse_hop_sql, ) +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -383,7 +384,7 @@ async def walk(self, input: FactsTraverseInput) -> FactsTraverseOutput: out = await _handle_facts_traverse_uncached(input) else: out = await _handle_facts_traverse_uncached(input) - if settling: + if settling or degradations.current(): # a walk a read left smaller is not kept return out if len(self.cache) > 512: self.cache.clear() @@ -582,6 +583,7 @@ async def _hubs( _HUB_DEGREE_SQL, params={"org": org, "ns": namespace, "ents": missing} ) except Exception as e: # noqa: BLE001 — the policy is additive + degradations.note("facts.traverse", "hub_policy_off", e, health=False) log.warning("facts.traverse: hub degree lookup failed (open): %s", e) rows = [] degree_of.update({str(r["entity"]): int(r["d"] or 0) for r in rows}) @@ -735,6 +737,7 @@ async def _colour_by_community( n.community_id = assignment.get(n.entity) return assignment.get(seed) except Exception as e: # noqa: BLE001 — communities are additive + degradations.note("facts.traverse", "communities_dropped", e, health=False) log.debug("facts.traverse: community lookup skipped: %s", e) return None diff --git a/server/memory/app/for_file.py b/server/memory/app/for_file.py index bd9ba44a5ba..e953f8d8466 100644 --- a/server/memory/app/for_file.py +++ b/server/memory/app/for_file.py @@ -36,6 +36,7 @@ from server.memory.domain.memory_types import KEY_IDENTIFIED_TYPES from server.memory.domain.trust import row_verification from server.memory.store.sql import FILE_LISTING_VISIBLE +from server.observability import degradations from server.observability.budget_shape import note_budget_shape from server.settings import settings @@ -783,6 +784,7 @@ async def _linked( links = await current_links(input.org, links) seen = await readable_namespaces(input.org, {a["code_namespace"] for a in links}) except Exception as e: # noqa: BLE001 — the links are additive; the files match stands + degradations.note("memory.for_file", "code_links_dropped", e, health=False) log.debug("memory.for_file: code links skipped: %s", e) return None out: dict[str, list[LinkRow]] = defaultdict(list) @@ -905,6 +907,7 @@ async def _own_rows(input: MemoryForFileInput, path: str) -> list[dict[str, Any] except TimeoutError: log.debug("memory.for_file: the caller's other namespaces ran past their bound") except Exception as e: # noqa: BLE001 — additive; the request's own namespaces stand + degradations.note("memory.for_file", "other_namespaces_dropped", e, health=False) log.warning("memory.for_file: the caller's other namespaces skipped: %r", e) return [] diff --git a/server/memory/app/loom_search/repo_decisions.py b/server/memory/app/loom_search/repo_decisions.py index bf42827e0cd..41434f9cbb5 100644 --- a/server/memory/app/loom_search/repo_decisions.py +++ b/server/memory/app/loom_search/repo_decisions.py @@ -19,6 +19,7 @@ from server.core.shielded import to_its_end from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput, _MemorySearchHit from server.memory.domain import code_change +from server.observability import degradations from server.settings import settings log = logging.getLogger("loom.loom_search") @@ -78,6 +79,7 @@ async def search_repo_decisions( except VectorInputTooLargeError: raise except Exception as e: # noqa: BLE001 — an additive leg never fails the caller + degradations.note("loom_search", "repo_decisions_dropped", e, health=False) log.info( "repo decisions search on %s/%s did not answer: %s", mem_input.org, repo_namespace, e ) diff --git a/server/memory/app/loom_search/tracker_leg.py b/server/memory/app/loom_search/tracker_leg.py index 914c4d7a05c..47a0e636260 100644 --- a/server/memory/app/loom_search/tracker_leg.py +++ b/server/memory/app/loom_search/tracker_leg.py @@ -13,6 +13,8 @@ from dataclasses import dataclass from typing import TYPE_CHECKING, Any +from server.observability import degradations + if TYPE_CHECKING: from server.tracker.app.dupcheck import DuplicateCheckPlan @@ -202,6 +204,7 @@ async def prepare_tracker_search( namespaces = await readable_tracker_namespaces(org, "", [], cap) return TrackerSearchPlan(org, tuple(namespaces), deadline, cap) if namespaces else None except Exception as e: # noqa: BLE001 — fail open: the memory legs answer + degradations.note("loom_search", "tracker_dropped", e, health=False) logger.info("loom_search tracker discovery skipped on %s: %s", org, type(e).__name__) return None @@ -223,6 +226,7 @@ async def tracker_leg( return None return lean_tracker_section(out, defect_report_shape(query) or {}) except Exception as e: # noqa: BLE001 — fail open: the memory legs answer + degradations.note("loom_search", "tracker_dropped", e, health=False) logger.info("loom_search tracker leg skipped on %s: %s", plan.org, type(e).__name__) return None diff --git a/server/memory/app/namespace_health.py b/server/memory/app/namespace_health.py index 1ac99d9f115..6abe1971088 100644 --- a/server/memory/app/namespace_health.py +++ b/server/memory/app/namespace_health.py @@ -25,6 +25,8 @@ from datetime import datetime from server.core.datetimes import naive_utc_now +from server.core.errors import caller_text +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -76,20 +78,22 @@ def unhealthy(self) -> bool: return self.criticals >= 1 or self.warnings >= 2 -# (org, namespace) -> (expires_at on the monotonic clock, health or None for a failure) -_cache: dict[tuple[str, str], tuple[float, NamespaceHealth | None]] = {} +# (org, namespace) -> (expires at on the monotonic clock, health or None, why it is None or "") +_cache: dict[tuple[str, str], tuple[float, NamespaceHealth | None, str]] = {} def reset_cache() -> None: _cache.clear() -def _cache_put(key: tuple[str, str], expires_at: float, value: NamespaceHealth | None) -> None: +def _cache_put( + key: tuple[str, str], expires_at: float, value: NamespaceHealth | None, failure: str = "" +) -> None: if key not in _cache and len(_cache) >= CACHE_MAX_ENTRIES: # Drop the entry closest to expiry; a bounded dict, not an LRU. oldest = min(_cache, key=lambda k: _cache[k][0]) _cache.pop(oldest, None) - _cache[key] = (expires_at, value) + _cache[key] = (expires_at, value, failure) async def _compute(org: str, namespace: str, window_seconds: int) -> NamespaceHealth | None: @@ -140,20 +144,21 @@ async def namespace_health( key = (str(org), str(namespace)) now = clock() hit = _cache.get(key) - if hit is not None and hit[0] > now: - return hit[1] - try: - health = await _compute(org, namespace, window_seconds) - except Exception as exc: # noqa: BLE001 — advisory; the pack must not fail on it - log.warning("namespace_health %s/%s failed: %s", org, namespace, exc) - health = None - _cache_put( - key, - now - + (ttl if health is not None else min(ttl, settings.memory_namespace_health_failure_ttl_s)), - health, - ) - return health + if hit is None or hit[0] <= now: + failure = "" + try: + health = await _compute(org, namespace, window_seconds) + failure = "" if health is not None else "a check could not run" + except Exception as exc: # noqa: BLE001 — advisory; the pack must not fail on it + log.warning("namespace_health %s/%s failed: %s", org, namespace, exc) + health, failure = None, caller_text(exc) + failure_ttl = min(ttl, settings.memory_namespace_health_failure_ttl_s) + _cache_put(key, now + (ttl if health is not None else failure_ttl), health, failure) + hit = _cache[key] + if hit[2]: + # every pack served from the remembered failure says so + degradations.note("context.pack", "namespace_health_dropped", hit[2], health=False) + return hit[1] def _first_clause(remedy: str) -> str: diff --git a/server/memory/app/namespace_types.py b/server/memory/app/namespace_types.py index 2ea0af19e97..cfacebdd663 100644 --- a/server/memory/app/namespace_types.py +++ b/server/memory/app/namespace_types.py @@ -10,6 +10,8 @@ from dataclasses import dataclass from typing import Any +from server.observability import degradations + log = logging.getLogger(__name__) @@ -90,6 +92,7 @@ async def list_type_configs( params={"org": org, "ns": namespace}, ) except Exception as e: # noqa: BLE001 — a failed type list reads as no types + degradations.note("namespace", "type_registry_unread", e, health=False) log.warning("namespace_types list failed: %s", e) return [] return [ diff --git a/server/memory/app/pending_disclosure.py b/server/memory/app/pending_disclosure.py index 68dbfafed3b..63ebba2b8c4 100644 --- a/server/memory/app/pending_disclosure.py +++ b/server/memory/app/pending_disclosure.py @@ -14,11 +14,14 @@ import time from typing import Any +from server.core.errors import caller_text +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) -_cache: dict[tuple[str, str, str, str], tuple[float, int]] = {} +# scope -> (expires at, count, the failed read's kind or "") +_cache: dict[tuple[str, str, str, str], tuple[float, int, str]] = {} _MAX_KEYS = 4096 @@ -34,22 +37,28 @@ async def pending_extraction( user_id: str | None, ch: Any | None = None, ) -> int: + """The scope's pending batches; 0 when the count cannot be read, which every answer + served from that cached 0 names in `degraded`.""" key = (org, namespace, agent or "*", user_id or "-") now = time.monotonic() hit = _cache.get(key) - if hit is not None and hit[0] > now: - return hit[1] - try: - from server.memory.app.extraction_queue import pending_count - - n = await pending_count(org=org, namespace=namespace, agent=agent, user_id=user_id, ch=ch) - except Exception as e: # noqa: BLE001 — a disclosure hint: fails quiet to 0 - log.debug("pending_extraction count failed (fail-quiet): %s", e) - n = 0 - if len(_cache) >= _MAX_KEYS: - _cache.clear() - _cache[key] = (now + settings.memory_pending_disclosure_ttl_s, n) - return n + if hit is None or hit[0] <= now: + failure = "" + try: + from server.memory.app.extraction_queue import pending_count + + n = await pending_count( + org=org, namespace=namespace, agent=agent, user_id=user_id, ch=ch + ) + except Exception as e: # noqa: BLE001 — a disclosure hint: fails quiet to 0 + log.debug("pending_extraction count failed (fail-quiet): %s", e) + n, failure = 0, caller_text(e) + if len(_cache) >= _MAX_KEYS: + _cache.clear() + hit = _cache[key] = (now + settings.memory_pending_disclosure_ttl_s, n, failure) + if hit[2]: + degradations.note("memory", "pending_count_unread", hit[2], health=False) + return hit[1] __all__ = ["pending_extraction", "reset_cache"] diff --git a/server/memory/app/pending_evidence.py b/server/memory/app/pending_evidence.py index ae9a19af533..187d97ae936 100644 --- a/server/memory/app/pending_evidence.py +++ b/server/memory/app/pending_evidence.py @@ -22,6 +22,7 @@ from typing import Any from server.memory.api.models_search import _MemorySearchHit +from server.observability import degradations log = logging.getLogger(__name__) @@ -195,6 +196,7 @@ async def pending_evidence_for( turns = rank_pending_turns(question, batches, max_turns=max_turns) return pending_hits(turns, namespace=namespace) except Exception as e: # noqa: BLE001 — pending evidence never fails an answer + degradations.note("memory.ask", "pending_evidence_dropped", e, health=False) log.debug("pending evidence read failed (fail-open): %s", e) return [] diff --git a/server/memory/app/procedure.py b/server/memory/app/procedure.py index 2636acb6a23..d509a61c830 100644 --- a/server/memory/app/procedure.py +++ b/server/memory/app/procedure.py @@ -35,6 +35,7 @@ from server.memory.domain.procedure_evidence import two_axis_score from server.memory.domain.procedure_graph import utility_from_stats from server.memory.domain.sensitivity import ATTRIBUTE_TAG_PREFIX, SENSITIVITY_TAG_PREFIX +from server.observability import degradations log = logging.getLogger(__name__) _REJECTED_PUBLIC_KEYS = ("revision", "digest", "reason", "before", "after", "steps") @@ -176,7 +177,8 @@ async def _goal_similarities( try: goal_vec = await get_embedder().embed(goal) key_vecs = await _load_key_embeddings(org, keys_by_ns) - except Exception: + except Exception as err: + degradations.note("procedure.match", "goal_axis_dropped", err, health=False) log.warning( "procedure.match: goal axis unavailable, matching on situation only", exc_info=True ) diff --git a/server/memory/app/profile_search.py b/server/memory/app/profile_search.py index 89f3664da6f..99885a40df7 100644 --- a/server/memory/app/profile_search.py +++ b/server/memory/app/profile_search.py @@ -35,6 +35,7 @@ from typing import Any from server.identity.domain.read_scope import ReadFilters, scope_and +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -227,6 +228,7 @@ async def _similarities( try: qv = await embedder.embed(query) except Exception as e: # noqa: BLE001 — the leg degrades to lexical, never fails the search + degradations.note("embedder", "profile_vector_dropped", e, health=False) log.debug("profile leg: query embed failed: %s", e) return {} by_ident = {_ident(r): r for r in rows} @@ -289,6 +291,7 @@ async def _score_unvectored( try: vecs = await embedder.embed_many(texts) except Exception as e: # noqa: BLE001 — the word rule still answers + degradations.note("embedder", "profile_vector_dropped", e, health=False) log.debug("profile leg: on-the-fly embed failed: %s", e) return {} out: dict[Ident, float] = {} diff --git a/server/memory/app/proposals_ops.py b/server/memory/app/proposals_ops.py index 304c32324a5..ed84c83d950 100644 --- a/server/memory/app/proposals_ops.py +++ b/server/memory/app/proposals_ops.py @@ -19,6 +19,7 @@ MemoryProposalsOutput, ) from server.memory.app.conflicts_ops import forget_review_counts +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -143,6 +144,7 @@ async def _usage_counts( params={"org": org, "ns": namespace, "ids": memory_ids}, ) except Exception as e: # noqa: BLE001 — proposals list without usage + degradations.note("memory.proposals", "usage_unread", e, health=False) log.warning("memory.proposals: usage counts unreadable for %s: %s", namespace, e) return {} return {str(r["mid"]): (int(r.get("used") or 0), int(r.get("harm") or 0)) for r in rows} diff --git a/server/memory/app/query.py b/server/memory/app/query.py index fe4d407b8eb..1e4c7c5c107 100644 --- a/server/memory/app/query.py +++ b/server/memory/app/query.py @@ -43,6 +43,7 @@ from server.memory.domain.identity_columns import IdentityColumn from server.memory.store.rows import MemoryRow from server.observability import audit as _audit +from server.observability import degradations from server.observability.budget_shape import note_budget_shape log = logging.getLogger(__name__) @@ -787,6 +788,7 @@ async def _canonical_keys_for_rows(org: str, namespace: str, rows: list[Any]) -> try: by_id = await canonical_keys_for(org, namespace, list(dups.values())) except Exception as e: # noqa: BLE001 — rows return without canonicals + degradations.note("memory.get", "canonical_unread", e, health=False) log.warning("memory.get: canonical lookup failed: %s", e) by_id = {} return {k: by_id.get(cid, "") for k, cid in dups.items()} diff --git a/server/memory/app/retrieval/chunks.py b/server/memory/app/retrieval/chunks.py index 45a99c1df00..3e7f5e13eeb 100644 --- a/server/memory/app/retrieval/chunks.py +++ b/server/memory/app/retrieval/chunks.py @@ -21,6 +21,7 @@ row_identity, ) from server.memory.domain.sensitivity import reads_high +from server.observability import degradations log = logging.getLogger("server.memory.app.retrieval") @@ -717,7 +718,8 @@ async def _search_memory_chunks( try: stage1_sql = _chunk_candidates_sql(chunk_agent_pred) candidates = await _chunk_query(ch, stage1_sql, stage1_params) - except Exception: + except Exception as err: + degradations.note("memory.search", "chunk_leg_dropped", err, health=False) log.exception( "chunk plane query failed; degrading to fact-only retrieval " "(namespace=%s entity_filter=%s stage=candidates)", @@ -785,7 +787,8 @@ async def _search_memory_chunks( ) try: rows = await _chunk_query(ch, sql, chunk_params) - except Exception: + except Exception as err: + degradations.note("memory.search", "chunk_leg_dropped", err, health=False) # Degrade to fact-only retrieval rather than 500'ing the query, but # log it — a silently-disabled chunk plane must leave a trace. log.exception( diff --git a/server/memory/app/retrieval/derived.py b/server/memory/app/retrieval/derived.py index 15dcc492fd8..32dead646ef 100644 --- a/server/memory/app/retrieval/derived.py +++ b/server/memory/app/retrieval/derived.py @@ -15,6 +15,7 @@ from server.memory.app.search_llm import expand_verb_synonyms from server.memory.domain.search_parsing import _iso_date, expand_predicate_class from server.memory.domain.search_types import SearchHit +from server.observability import degradations log = logging.getLogger("server.memory.app.retrieval") @@ -187,6 +188,7 @@ async def fetch_derived_aggregate( agg = agg_rows[0] item_rows = await ch.query_all(items_sql, params=params) except Exception as e: # noqa: BLE001 — the aggregate leg is additive; fail open + degradations.note("memory.search", "aggregate_dropped", e, health=False) log.warning("fetch_derived_aggregate failed (fail-open): %s", e) return None @@ -289,6 +291,7 @@ async def _resolve_operand_event_date( }, ) except Exception as e: # noqa: BLE001 — a failed operand read means no date answer + degradations.note("memory.search", "temporal_diff_dropped", e, health=False) log.warning("_resolve_operand_event_date failed (fail-open): %s", e) return None if not rows: @@ -413,6 +416,7 @@ async def fetch_current_state_observation( try: rows = await ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — the current-state leg is additive; fail open + degradations.note("memory.search", "current_state_leg_dropped", e, health=False) log.warning("fetch_current_state_observation failed (fail-open): %s", e) return [] if not rows: @@ -541,6 +545,7 @@ async def fetch_temporal_diff( params={"a": earlier, "b": later}, ) except Exception as e: # noqa: BLE001 — a failed date diff means no temporal answer + degradations.note("memory.search", "temporal_diff_dropped", e, health=False) log.warning("fetch_temporal_diff failed (fail-open): %s", e) return None if not rows: diff --git a/server/memory/app/retrieval/pool.py b/server/memory/app/retrieval/pool.py index f1799fd8172..36a88385fb9 100644 --- a/server/memory/app/retrieval/pool.py +++ b/server/memory/app/retrieval/pool.py @@ -29,6 +29,7 @@ row_key_of, ) from server.memory.store.rows import parse_memory_value +from server.observability import degradations from server.settings import settings log = logging.getLogger("server.memory.app.retrieval") @@ -85,6 +86,7 @@ async def _recency_backfill( try: rows = await ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — an additive leg fails open + degradations.note("memory.search", "recency_backfill_dropped", e, health=False) log.warning("recency backfill failed (fail-open): %s", e) return hits floor = min((float(h.rank_score or 0.0) for h in hits), default=0.0) @@ -295,6 +297,7 @@ async def _set_chunk_rows( ) values = await _row_values(ch, q, served) except Exception as e: # noqa: BLE001 — naming a chunk's row never fails a search + degradations.note("memory.search", "set_chunks_dropped", e, health=False) log.warning("set chunk rows read failed; this pool's set chunks are dropped: %s", e) return {} by_writer: dict[tuple[str, str, str], list[ChunkId]] = {} diff --git a/server/memory/app/retrieval/side_legs.py b/server/memory/app/retrieval/side_legs.py index 9fa05ce57eb..eb12a11fb42 100644 --- a/server/memory/app/retrieval/side_legs.py +++ b/server/memory/app/retrieval/side_legs.py @@ -22,6 +22,7 @@ names_row, row_identity, ) +from server.observability import degradations log = logging.getLogger("server.memory.app.retrieval") @@ -138,6 +139,7 @@ async def _lexical_recall_fallback( lambda: ch.query_all(sql, params=params), leg="lexical" ) except Exception as e: # noqa: BLE001 — the lexical fallback leg is additive; fail open + degradations.note("memory.search", "lexical_leg_dropped", e, health=False) log.warning("_lexical_recall_fallback failed (fail-open): %s", e) return [] @@ -368,6 +370,7 @@ async def _search_memory_records( lambda: ch.query_all(sql, params=params), leg="records" ) except Exception as e: # noqa: BLE001 — the records leg is additive; fail open + degradations.note("memory.search", "records_leg_dropped", e, health=False) log.warning("_search_memory_records failed (fail-open): %s", e) return [] @@ -467,6 +470,7 @@ async def _fetch_unmatched_candidates( try: rows = await ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — the unmatched-candidate leg is additive; fail open + degradations.note("memory.search", "unmatched_leg_dropped", e, health=False) log.warning("_fetch_unmatched_candidates failed (fail-open): %s", e) return [] diff --git a/server/memory/app/retrieval/summaries.py b/server/memory/app/retrieval/summaries.py index 5abdf216db0..e1484059aee 100644 --- a/server/memory/app/retrieval/summaries.py +++ b/server/memory/app/retrieval/summaries.py @@ -12,6 +12,7 @@ from server.memory.domain.search_parsing import _iso_date from server.memory.domain.search_types import SearchHit from server.memory.domain.sensitivity import without_high +from server.observability import degradations from server.settings import settings log = logging.getLogger("server.memory.app.retrieval") @@ -194,6 +195,7 @@ async def fetch_session_summaries( ch, rows, org=org, namespace=namespace, as_of=as_of, as_of_basis=as_of_basis ) except Exception as e: # noqa: BLE001 — the session-summary leg is additive; fail open + degradations.note("memory.search", "session_summary_leg_dropped", e, health=False) log.warning("fetch_session_summaries failed (fail-open): %s", e) return [] # A stored vector does not establish that the digest passes the sensitivity check. @@ -348,6 +350,7 @@ async def fetch_entity_summaries( try: rows = await ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — the entity-summary leg is additive; fail open + degradations.note("memory.search", "entity_summary_leg_dropped", e, health=False) log.warning("fetch_entity_summaries failed (fail-open): %s", e) return [] out: list[SearchHit] = [] diff --git a/server/memory/app/runs_manifest.py b/server/memory/app/runs_manifest.py index 3e6afb1fc7e..c25916f2d67 100644 --- a/server/memory/app/runs_manifest.py +++ b/server/memory/app/runs_manifest.py @@ -24,6 +24,7 @@ from typing import Any from server.memory.domain.context_layout import label_part, one_item +from server.observability import degradations log = logging.getLogger(__name__) @@ -234,6 +235,7 @@ async def runs_manifest( ch, org=org, namespace=namespace, agent=agent, user_id=user_id, limit=limit ) except Exception as e: # noqa: BLE001 — additive section, never fails the pack + degradations.note("context.pack", "runs_manifest_dropped", e, health=False) log.warning("context.pack runs manifest skipped: %s", e) return "", 0 if not rows: diff --git a/server/memory/app/search/anchor_pool.py b/server/memory/app/search/anchor_pool.py index 6bf20316cf2..5dd936dbe3c 100644 --- a/server/memory/app/search/anchor_pool.py +++ b/server/memory/app/search/anchor_pool.py @@ -14,6 +14,7 @@ from server.memory.app.search_tag_filter import stamp_row_tags as _stamp_row_tags from server.memory.domain.search_sql import agent_filter from server.memory.domain.search_types import hit_row_key, row_identity, row_key_of +from server.observability import degradations log = logging.getLogger(__package__) @@ -120,6 +121,7 @@ async def _anchor_rows_for_ns(ns: str) -> tuple[str, list[dict[str, Any]]]: try: return ns, await _ch_a.query_all(anchor_sql, params=params) except Exception as e: # noqa: BLE001 — one namespace's anchor pool failure must not fail search + degradations.note("memory.search", "anchor_pool_dropped", e, health=False) log.warning("anchor pool fetch failed for ns=%s (non-fatal): %s", ns, e) return ns, [] diff --git a/server/memory/app/search/computed.py b/server/memory/app/search/computed.py index ae888cc8b28..6c84e64d2a1 100644 --- a/server/memory/app/search/computed.py +++ b/server/memory/app/search/computed.py @@ -22,6 +22,7 @@ from server.memory.app.search.evidence_support import _evidence_support_count from server.memory.app.search.knobs import _floor_mode, _noise_floor from server.memory.app.search.scope import _SearchRun +from server.observability import degradations if TYPE_CHECKING: from server.memory.domain.query_intent import QueryIntent @@ -91,6 +92,7 @@ async def _exp(v: str | None) -> list[str] | None: except VectorInputTooLargeError: raise except Exception as e: # noqa: BLE001 + degradations.note("memory.search", "aggregate_unexpanded", e, health=False) log.warning("derived canonical expand failed (non-fatal): %s", e) return None diff --git a/server/memory/app/search/digest_descent.py b/server/memory/app/search/digest_descent.py index f5b1dd11dac..f9fefe96ccb 100644 --- a/server/memory/app/search/digest_descent.py +++ b/server/memory/app/search/digest_descent.py @@ -13,6 +13,7 @@ from server.memory.app.search.sql import _digest_descent_where, digest_descent_sql from server.memory.app.search_tag_filter import stamp_row_tags as _stamp_row_tags from server.memory.domain.search_types import hit_row_key, row_identity, row_key_of +from server.observability import degradations log = logging.getLogger(__package__) @@ -97,6 +98,7 @@ async def _rows(ns: str, sid: str) -> tuple[str, str, list[dict[str, Any]]]: try: return ns, sid, await _ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — additive arm + degradations.note("memory.search", "digest_descent_dropped", e, health=False) log.warning("digest descent failed for %s/%s (non-fatal): %s", ns, sid, e) return ns, sid, [] diff --git a/server/memory/app/search/key_match.py b/server/memory/app/search/key_match.py index 837c1578027..d5542b76bce 100644 --- a/server/memory/app/search/key_match.py +++ b/server/memory/app/search/key_match.py @@ -20,6 +20,7 @@ ) from server.memory.app.search_tag_filter import stamp_row_tags as _stamp_row_tags from server.memory.domain.search_types import hit_row_key, row_identity, row_key_of +from server.observability import degradations log = logging.getLogger(__package__) @@ -337,6 +338,7 @@ async def _rows_for_ns(ns: str) -> tuple[str, list[dict[str, Any]], bool]: try: return ns, await _ch.query_all(sql, params=params), False except Exception as e: # noqa: BLE001 — additive arm + degradations.note("memory.search", "key_match_dropped", e, health=False) log.warning("key-match arm failed for ns=%s (non-fatal): %s", ns, e) return ns, [], False diff --git a/server/memory/app/search/output.py b/server/memory/app/search/output.py index 1bde824a2d7..31a81ea0b03 100644 --- a/server/memory/app/search/output.py +++ b/server/memory/app/search/output.py @@ -248,6 +248,7 @@ async def _readable_namespaces(org: str, namespace: str, payload: dict[str, Any] try: mine = (await resolve_fanout(org)).namespaces except Exception as e: # noqa: BLE001 — unresolved, the page narrows to the addressed namespace + _degradations.note("memory.search", "page_narrowed", e, health=False) log.warning("parked page: fan-out unresolved for %s/%s: %s", org, namespace, e) return authorized return (named & set(mine)) | authorized @@ -556,6 +557,7 @@ async def _attach_scratchpad(input: Any, output: Any) -> None: max_chars=int(_s.memory_scratchpad_max_chars), ) except Exception as e: # noqa: BLE001 — a missing note must not fail a search + _degradations.note("memory.search", "scratchpad_unread", e, health=False) log.debug("scratchpad load skipped: %s", e) return if blocks is None: diff --git a/server/memory/app/search/payload.py b/server/memory/app/search/payload.py index 1b790b6f438..2f60d520a5a 100644 --- a/server/memory/app/search/payload.py +++ b/server/memory/app/search/payload.py @@ -17,6 +17,7 @@ from server.memory.domain.excerpt import build_excerpt from server.memory.domain.search_types import SHARED_AGENT from server.memory.domain.sensitivity import reads_high +from server.observability import degradations log = logging.getLogger(__package__) @@ -169,6 +170,7 @@ async def _fill_hit_usage(hits: list[Any], input: Any, namespaces: list[str] | N prev = folded_by_key.get((ns, key), 0) folded_by_key[(ns, key)] = max(prev, int(count)) except Exception as e: # noqa: BLE001 — counters are additive, never a failure + degradations.note("memory.search", "usage_unread", e, health=False) log.warning("memory.search: include_usage read failed: %s", e) return 0 filled = 0 @@ -502,6 +504,7 @@ async def _expand_source_bodies( by_key[k], spans[k] = linked_eid, span break except Exception as e: # noqa: BLE001 — a body read never fails a search + degradations.note("memory.search", "source_bodies_unread", e, health=False) log.debug("source bodies read failed: %s", e) return (0, 0) budget = int(getattr(input, "body_budget_tokens", 4000) or 4000) diff --git a/server/memory/app/search/supplemental.py b/server/memory/app/search/supplemental.py index 8f0c99c6216..f8ecba78291 100644 --- a/server/memory/app/search/supplemental.py +++ b/server/memory/app/search/supplemental.py @@ -12,6 +12,7 @@ from server.memory.app.search.context import SearchContext from server.memory.app.search.vector_legs import _search_query_for, _wire_hit from server.memory.domain import set_expansion as _set_expansion +from server.observability import degradations log = logging.getLogger(__package__) @@ -32,7 +33,8 @@ async def _supplemental_leg( try: ctx.actual_work["embedding_calls"] = int(ctx.actual_work["embedding_calls"]) + 1 sub_vec = await ctx.embedder.embed(sub_q) - except Exception: # noqa: BLE001 — a failed sub-query embed drops only that sub-query + except Exception as err: # noqa: BLE001 — a failed sub-query embed drops only that sub-query + degradations.note("embedder", "sub_query_dropped", err, health=False) return [] ctx.actual_work["vector_queries"] = int(ctx.actual_work["vector_queries"]) + len(ctx.namespaces) sub_per_ns = await asyncio.gather( @@ -96,6 +98,7 @@ async def _run_set_expansion(ctx: SearchContext) -> None: *[_supplemental_leg(ctx, ph, leg_top_k, seen_keys) for ph in phrases] ) except Exception as e: # noqa: BLE001 — additive legs + degradations.note("memory.search", "set_expansion_dropped", e, health=False) log.warning("set expansion legs failed (non-fatal): %s", e) return # A phrase names the question's entity; a row that answers it does too. diff --git a/server/memory/app/search/tiers.py b/server/memory/app/search/tiers.py index 682dba04a64..016c652d38a 100644 --- a/server/memory/app/search/tiers.py +++ b/server/memory/app/search/tiers.py @@ -89,6 +89,7 @@ async def _prepend_tier( exclude_high_sensitivity=True, ) except Exception as e: # noqa: BLE001 — a tier never fails a search + degradations.note("memory.search", f"{tier}_dropped", e, health=False) log.debug("%s tier read failed: %s", tier, e) return hits, 0 if run_id: diff --git a/server/memory/app/search_llm.py b/server/memory/app/search_llm.py index 39ac8c949da..b34fb100317 100644 --- a/server/memory/app/search_llm.py +++ b/server/memory/app/search_llm.py @@ -19,6 +19,7 @@ _VERB_SYNONYM_PROMPT, ) from server.memory.domain.search_text import canonicalize_verb +from server.observability import degradations from server.observability.genai import staged from server.settings import settings from server.settings.budgets import llm_max_tokens @@ -56,7 +57,8 @@ async def judge_results_iteratively( ) except TimeoutError: return True, "" - except Exception: # noqa: BLE001 — a failed judge call counts as answered + except Exception as err: # noqa: BLE001 — a failed judge call counts as answered + degradations.note("llm", "judge_skipped", err, health=False) return True, "" raw = strip_code_fence(result.text) try: @@ -202,7 +204,8 @@ async def extract_query_triples_llm( _QUERY_ENTITY_CACHE.pop(next(iter(_QUERY_ENTITY_CACHE))) _QUERY_ENTITY_CACHE[key] = [list(t) for t in out] return out - except Exception: # noqa: BLE001 — a failed entity extraction means no query entities + except Exception as err: # noqa: BLE001 — a failed entity extraction means no query entities + degradations.note("llm", "query_entities_dropped", err, health=False) return [] @@ -272,5 +275,6 @@ async def expand_verb_synonyms( _VERB_SYNONYM_CACHE.pop(next(iter(_VERB_SYNONYM_CACHE))) _VERB_SYNONYM_CACHE[key] = out return out - except Exception: # noqa: BLE001 — a failed synonym call keeps the verb alone + except Exception as err: # noqa: BLE001 — a failed synonym call keeps the verb alone + degradations.note("llm", "verb_synonyms_dropped", err, health=False) return [canon] diff --git a/server/memory/app/served_superseded.py b/server/memory/app/served_superseded.py index ac374b308eb..b608a425b85 100644 --- a/server/memory/app/served_superseded.py +++ b/server/memory/app/served_superseded.py @@ -26,6 +26,7 @@ from server.identity.app.request_scope import request_scope from server.memory.domain.search_types import hit_row_key, names_row, record_row_key +from server.observability import degradations log = logging.getLogger(__name__) @@ -102,6 +103,7 @@ async def annotate_pool_superseded(ctx: Any) -> None: input.org, [hit_row_key(h, ns_default) for h in old], scope=scope ) except Exception as e: # noqa: BLE001 — naming the successor never fails a search + degradations.note("memory.search", "successor_unread", e, health=False) log.warning("memory.search: superseded successor read failed: %s", e) return by_row = {record_row_key(r): r for r in rows} diff --git a/server/memory/app/stack_knowledge.py b/server/memory/app/stack_knowledge.py index d5b15317d96..7faad06a3b0 100644 --- a/server/memory/app/stack_knowledge.py +++ b/server/memory/app/stack_knowledge.py @@ -15,6 +15,7 @@ from server.knowledge.app.source_search_proofs import SearchProofs from server.memory.app.agent_rules import request_rule_agent, served_hits from server.memory.domain.assistant_rules import hits_to_ask +from server.observability import degradations @dataclass @@ -106,7 +107,8 @@ async def collect_pass(width: int, fallback: list[ChunkHit]) -> None: try: wider = await ordinary(width) await collect_pass(width, wider) - except Exception: # noqa: BLE001 — a wider ordinary failure must preserve the usable first pass + except Exception as err: # noqa: BLE001 — a wider ordinary failure must preserve the usable first pass + degradations.note("memory.stack", "knowledge_short", err, health=False) wider = None pools = await passes.finish() mixed = [[ranked.chunk for ranked in pool] for pool in pools] diff --git a/server/memory/app/working_memory.py b/server/memory/app/working_memory.py index f845c2c4679..95f1a5026e7 100644 --- a/server/memory/app/working_memory.py +++ b/server/memory/app/working_memory.py @@ -33,6 +33,7 @@ ) from server.memory.app.scratchpad import run_rows from server.memory.store.rows import next_version +from server.observability import degradations log = logging.getLogger(__name__) @@ -337,6 +338,7 @@ async def render_run_blocks( try: rows = await run_rows(ch, org, namespace, run_id, limit=limit) except Exception as e: # noqa: BLE001 — a scratchpad read never blocks an answer + degradations.note("memory.ask", "run_scratchpad_unread", e, health=False) log.warning("working_memory: run block read failed (open): %s", e) return "" parts = [ diff --git a/server/observability/degradations.py b/server/observability/degradations.py index 38d4f4b6487..024b0674669 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -105,6 +105,21 @@ def current() -> list[str]: return list(lst) if lst else [] +def restore(entries: Any) -> None: + """List `entries`, the notes of the request whose stored answer this one serves (a + later page), as they were. Provider health counted them when they happened. Bounded + like `note`; anything but a list is ignored.""" + if not isinstance(entries, list): + return + lst = _notes.get() + if lst is None: + lst = [] + _notes.set(lst) + for entry in map(str, entries): + if entry not in lst and len(lst) < _MAX_NOTES: + lst.append(entry) + + def on_response(body: Any) -> Any: """`body` (a dumped op result) with `degraded`: the op's own notes first (an output that declares the field), then this request's, each once. A response nothing @@ -122,4 +137,4 @@ def on_response(body: Any) -> Any: return {k: v for k, v in body.items() if k != "degraded"} if "degraded" in body else body -__all__ = ["begin", "current", "note", "on_response", "scoped"] +__all__ = ["begin", "current", "note", "on_response", "restore", "scoped"] diff --git a/server/operations/base.py b/server/operations/base.py index 2958568acba..63a8af92591 100644 --- a/server/operations/base.py +++ b/server/operations/base.py @@ -99,10 +99,12 @@ class Operation: # can resolve (memory.verify by id, erasure.request by scope, erasure.list # by caller role); the handler enforces its own rules. Role check still runs. skip_namespace_authz: bool = False - # The op reads facts about the DEPLOYMENT (its build, its op registry), not any - # org's or namespace's data. A scoped token — whose authority is per-namespace and - # which the transport would otherwise refuse with IDENTITY_INCOMPLETE for want of a - # namespace — passes the role gate with its best per-namespace role. + # The op reads facts about the DEPLOYMENT (its build, its op registry, its + # incidents) and no namespace's data; an org-wide aggregate it also answers is + # authorized by its handler (ops.incidents' request counts). A scoped token — whose + # authority is per-namespace and which the transport would otherwise refuse with + # IDENTITY_INCOMPLETE for want of a namespace — passes the role gate with its best + # per-namespace role, in its own org only. deployment_scoped: bool = False # The op is addressed only by an org-wide id (memory_id, erasure_id, # pattern_id) and its handler authorizes the row's scope, before the read diff --git a/server/workers/status_store.py b/server/workers/status_store.py index 8e56d60da8c..ca6ba88c175 100644 --- a/server/workers/status_store.py +++ b/server/workers/status_store.py @@ -529,11 +529,16 @@ async def latest_rows( """ +# The first `:` segment of a deployment process's label (`deploy:[:]`); an +# isolated or a bench server sharing the tables carries another. +DEPLOY_SEGMENT = "deploy" + + def label_family(label: str) -> str: """`deploy:workers:green` → `deploy:workers:` (every colour of the deployment); any other label is its own family, exactly.""" parts = str(label or "").split(":") - if len(parts) >= 3 and parts[0] == "deploy": + if len(parts) >= 3 and parts[0] == DEPLOY_SEGMENT: return ":".join(parts[:-1]) + ":" return str(label or "") @@ -597,8 +602,9 @@ async def pass_summaries(prefix: str, days: int, *, ch: Any = None) -> list[dict # The {workers} (a prefix of the key) whose freshest pass within the window, in this # process's deployment, left a failure streak of at least {min_failures}: the class of # its last error, never its text or namespace, which can name an org. The deployment's -# processes are labelled `deploy…` (or carry no label); any other process (an isolated -# or a bench server sharing the table) reads only its own label's rows. +# processes carry no label or one whose first segment is DEPLOY_SEGMENT; any other +# process (an isolated or a bench server sharing the table) reads only its own label's +# rows. FAILING_STREAKS_SQL = f""" SELECT worker, argMax(failures, finished) AS consecutive_failures, @@ -613,7 +619,7 @@ async def pass_summaries(prefix: str, days: int, *, ch: Any = None) -> list[dict WHERE worker IN {{workers:Array(String)}} AND pass_started > now() - toIntervalHour({{hours:UInt32}}) AND if({{deployment:Bool}}, - instance_label = '' OR startsWith(instance_label, 'deploy'), + instance_label = '' OR splitByChar(':', instance_label)[1] = '{DEPLOY_SEGMENT}', instance_label = {{label:String}}) GROUP BY worker, instance_label ) @@ -627,7 +633,7 @@ async def pass_summaries(prefix: str, days: int, *, ch: Any = None) -> list[dict def is_deployment_label(label: str) -> bool: """Whether a process labelled `label` is the deployment's (`deploy:[:]`, or no label), not an isolated or a bench server sharing its tables.""" - return not label or label.startswith("deploy") + return not label or label.split(":", 1)[0] == DEPLOY_SEGMENT async def failing_streaks( diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 24f87f244e1..70b3c2719b4 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -133,7 +133,6 @@ 0f510c19553c SELECT *, hex(SHA256(toJSONString((value_json, value)))) AS body_sha FROM (SELECT org, namespace, agent, user_id, session_id, ? AS actor, memory_key, version, ? AS value_json, toJSONString(content_exc 0f5951ba0297 SELECT DISTINCT kind, start_line, end_line FROM loom.code_chunks FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path = {path:String} AND tombstoned_at IS NULL 0f5fb44818c9 SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, value, ? AS value_truncated, confidence, version, pinned, char_limit, created_at, updated_at, expires_at, valid_a -0f93c7c30394 SELECT worker, argMax(failures, finished) AS consecutive_failures, argMax(error_class, finished) AS error_class, max(finished) AS last_finished FROM ( SELECT worker, instance_label, argMax(consecutive 0fc1bdd2c6d3 SELECT pr_number, title, author, files, merged_at, linked_issues, arraySum( arrayMap( (tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {tokens:Array(String)}, {idfs:Array 0fd1cbc1eecb SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 0fdc18bb9750 SELECT memory_key, argMax(tombstoned_at IS NOT NULL, version) AS deleted, argMax(status, version) AS head_status, argMax(content_sha256, version) AS head_sha256, argMax(sensitivity, version) AS head_s @@ -1737,6 +1736,7 @@ c14310076fa0 SELECT org, namespace, agent, thread_id, msg_id, role, content, rea c1434f6b0ebe SELECT count() AS n FROM loom.knowledge_uploads WHERE org = {org:String} AND namespace = {ns:String} AND ? c15f8b68d7f7 SELECT agent AS key, sum(upstream_cost_usd) AS total_cost_usd, count() AS total_calls, uniqExact(operation) AS ops_distinct , uniqExact(namespace) AS namespaces_distinct FROM (SELECT raw.ts AS ts, raw c16434c88b3c SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id = {scope_uid:String}) +c165eb8bf32a SELECT worker, argMax(failures, finished) AS consecutive_failures, argMax(error_class, finished) AS error_class, max(finished) AS last_finished FROM ( SELECT worker, instance_label, argMax(consecutive c169a496882f SELECT count() AS n FROM loom.llm_response_cache WHERE org = {org:String} AND namespace = {ns:String} c16e06ab36a7 SELECT chunk_id, path, scope, kind, start_line, end_line, embedding_dim, arraySum( arrayMap( (tok, idf) -> idf * countSubstrings( concat(?, lexemes, ?), concat(?, tok, ?) ), {tokens:Array(String)}, {i c1aa2dbb7a43 SELECT count() AS n FROM loom.llm_response_cache WHERE org = {org:String} AND hasAny(window_keys, {keys:Array(String)}) diff --git a/tests/unit/clickhouse_local.py b/tests/unit/clickhouse_local.py index 96477c35d3f..2f6ca3da69d 100644 --- a/tests/unit/clickhouse_local.py +++ b/tests/unit/clickhouse_local.py @@ -22,11 +22,11 @@ CLICKHOUSE = shutil.which("clickhouse") -def ddl(table: str) -> str: - """The `CREATE TABLE` for `loom.` as schema.sql has it.""" +def ddl(table: str, database: str = "loom") -> str: + """The `CREATE TABLE` for `.
` as schema.sql has it.""" schema = (ROOT / "schemas" / "schema.sql").read_text() - body = schema.split(f"CREATE TABLE IF NOT EXISTS loom.{table}\n", 1)[1] - return f"CREATE TABLE loom.{table}\n" + body.split(";", 1)[0] + body = schema.split(f"CREATE TABLE IF NOT EXISTS {database}.{table}\n", 1)[1] + return f"CREATE TABLE {database}.{table}\n" + body.split(";", 1)[0] def view(name: str) -> str: diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index 81713bc4bbb..5342a2d7979 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -1376,3 +1376,32 @@ async def _ls_fails(gd, *args, timeout_s): monkeypatch.setattr(ph, "_git_rc", _ls_fails) hp = await ph.branch_history(git_dir, branch, _mirror_groups([" return x;"], [])) assert hp.verdict == "" and hp.reason == "error:MirrorReadError" and hp.paths_absent == 0 + + +@pytest.mark.asyncio +async def test_a_fix_whose_read_fell_back_writes_nothing() -> None: + """A branch's ledger read that failed can flip its verdict: the fix keeps last + night's rows, as for a tracker miss, and the pass's own notes hold none of it.""" + from types import SimpleNamespace + + from server.observability import degradations + + async def _runner(req): + degradations.note( + "code_index", "backport_ledger_dropped", ConnectionError("x"), health=False + ) + return _out(req.pr_number) + + degradations.begin() + result = wk.BackportGapsResult() + rows = await wk.compute_fix( + SimpleNamespace(org="acme", namespace=NS), + 7, + {}, + runner=_runner, + result=result, + stamp=NOW, + version=1, + ) + assert rows == [] and result.fixes_unavailable == 1 and result.fixes_computed == 0 + assert degradations.current() == [] diff --git a/tests/unit/test_code_missing_vector_routes.py b/tests/unit/test_code_missing_vector_routes.py index 23c6ec501e8..4870d009b72 100644 --- a/tests/unit/test_code_missing_vector_routes.py +++ b/tests/unit/test_code_missing_vector_routes.py @@ -260,6 +260,7 @@ def test_continuations_keep_the_configured_model_when_initialization_fails( served=1, pool=pool, calibration={}, + degraded=[], ) # A continuation carries its original scope even when the search has no filters. cursor = search_cursor.encode( diff --git a/tests/unit/test_code_read_degradations.py b/tests/unit/test_code_read_degradations.py index 16ae29e4759..e6d236c95db 100644 --- a/tests/unit/test_code_read_degradations.py +++ b/tests/unit/test_code_read_degradations.py @@ -103,6 +103,126 @@ async def test_a_cached_failed_override_probe_is_noted_on_every_answer_that_serv clear_all() +def test_a_later_page_of_a_degraded_search_names_the_first_pages_notes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The pool is what the first page's fallbacks left (lexical only after a dropped + vector leg): page 2, served from it in another request, says so too.""" + from types import SimpleNamespace + + from server.code.api.models_search import CodeSearchInput + from server.code.app import search, search_cursor + from server.code.app.search import handler + from server.code.domain.search_scope import build_scope + from server.code.domain.units import CodeUnit + from server.settings import settings + from tests.unit.test_code_missing_vector_routes import _ModelFilteringRepo + + for name, value in { + "code_intel_enabled": True, + "code_org": "o", + "code_namespace": "n", + "code_trace_log_enabled": False, + "code_risk_annotations": False, + }.items(): + monkeypatch.setattr(settings, name, value) + model = handler._embedding_model_name() + repo = _ModelFilteringRepo(model) + stored: dict[str, Any] = {} + + def put_pool(org: str, ns: str, key: str, payload: dict[str, Any], **_: Any) -> None: + stored["payload"] = payload + + async def get_pool(*_: Any) -> dict[str, Any]: + return {"payload": stored["payload"], "indexed_commit": "c" * 40} + + async def as_of(*_: Any) -> dict[str, Any]: + return {"commit": "c" * 40} + + async def no_retrieval(*_: Any, **__: Any) -> Any: + raise AssertionError("a later page is served from the pool") + + monkeypatch.setattr(search_cursor, "enabled", lambda: True) + monkeypatch.setattr(search_cursor, "put_pool", put_pool) + monkeypatch.setattr(search_cursor, "get_pool", get_pool) + monkeypatch.setattr(handler, "CodeRepo", lambda: repo) + monkeypatch.setattr(handler, "index_as_of", as_of) + monkeypatch.setattr(search, "search", no_retrieval) + request = CodeSearchInput(query="q", top_k=1) + pool = [CodeUnit(unit_id="L1", path="src/a.cpp"), CodeUnit(unit_id="L2", path="src/b.cpp")] + first = SimpleNamespace( + pool=pool, + units=pool[:1], + abstain=False, + failure_reason="", + route="hybrid", + retrieval_risk="low", + retrieval_confidence=0.9, + route_agreement=1.0, + calibration_explanation="", + top_similarity=0.5, + score_explanation="", + ) + degradations.note("code_index", "vector_leg_dropped", "DatabaseError", health=False) + cursor = handler._issue_search_cursor( + request, + "o", + "n", + first, # type: ignore[arg-type] + run_id="run", + embedding_model=model, + indexed_commit="c" * 40, + scope=build_scope(), + ) + + async def page_two() -> tuple[Any, list[str]]: + degradations.begin() # another request + out = await handler.handle_code_search(request.model_copy(update={"cursor": cursor})) + return out, degradations.current() + + out, notes = asyncio.run(page_two()) + assert [u.unit_id for u in out.results] == ["L2"] + assert notes == ["code_index: vector_leg_dropped (DatabaseError)"] + + +@pytest.mark.asyncio +async def test_a_map_without_its_hubs_says_so_and_is_not_kept( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.code.app import context, fan_in + + class _Repo: + async def get_state(self, *_: Any) -> str: + return "head" + + async def top_summaries(self, *_: Any, **__: Any) -> list[Any]: + return [] + + async def top_files_by_callers(self, *_: Any, **__: Any) -> list[Any]: + raise ConnectionError("replica gone") + + async def _boom(*_: Any, **__: Any) -> list[Any]: + raise ConnectionError("replica gone") + + monkeypatch.setattr(fan_in, "top_under", _boom) + monkeypatch.setattr(context, "_MAP_CACHE", context.TtlCache(900.0)) + artifact = await context._render_map(_Repo(), "o", "n", "", 2000) # type: ignore[arg-type] + assert artifact.text.startswith("# Repo map") + assert degradations.current() == [ + "code_index: call_graph_hubs_dropped (ConnectionError)", + "code_index: most_called_dropped (ConnectionError)", + ] + assert context._MAP_CACHE.get(("o", "n", "", 2000, "head")) is None + + +@pytest.mark.asyncio +async def test_unread_issue_titles_are_noted() -> None: + from server.code.app.blame import _issue_titles + + assert await _issue_titles(_FailingRepo(), "o", "n", {1: [42]}, ["fix"]) == {} # type: ignore[arg-type] + assert degradations.current() == ["tracker: issue_titles_unread (ConnectionError)"] + + @pytest.mark.asyncio async def test_a_dropped_coverage_leg_names_the_leg() -> None: from server.code.app.coverage import _leg @@ -112,3 +232,16 @@ async def _boom() -> list[dict[str, Any]]: assert await _leg(_boom(), "calls") == [] assert degradations.current() == ["code_index: calls_tests_dropped (ConnectionError)"] + + +@pytest.mark.asyncio +async def test_a_dropped_fan_in_read_is_noted() -> None: + """A search ranked without fan-in, which `min_fan_in` would then empty, says so.""" + from types import SimpleNamespace + + from server.code.app import fan_in + + units = [SimpleNamespace(unit_id="u1")] + assert await fan_in.annotate_units(_FailingRepo(), "o", "n", units) == 0 # type: ignore[arg-type] + assert degradations.current() == ["code_index: fan_in_dropped (ConnectionError)"] + assert provider_health.status()["providers"] == {} diff --git a/tests/unit/test_code_search_pick.py b/tests/unit/test_code_search_pick.py index 4c52606da2d..62bed2f93f0 100644 --- a/tests/unit/test_code_search_pick.py +++ b/tests/unit/test_code_search_pick.py @@ -69,6 +69,9 @@ async def symbols_fuzzy(self, *a: Any, **k: Any) -> list[Any]: async def unit_signals(self, *a: Any, **k: Any) -> dict[str, Any]: return {} + async def symbol_stats(self, *a: Any, **k: Any) -> dict[str, Any]: + return {} # the fan-in read answers; a missing read would make the search a fallback's + class _Embedder: model_name, dim = "fake-embed", 3 diff --git a/tests/unit/test_extraction_queue.py b/tests/unit/test_extraction_queue.py index 0d4e0145ebd..ed25e268220 100644 --- a/tests/unit/test_extraction_queue.py +++ b/tests/unit/test_extraction_queue.py @@ -35,7 +35,7 @@ from server.memory.app import extraction_queue as queue from server.memory.app import pending_disclosure from server.memory.workers import extraction_queue as worker -from server.observability import cost_accumulator +from server.observability import cost_accumulator, degradations from server.observability.budget import budget_snapshot from server.workers.status import get_registry from tests.unit.clickhouse_local import CLICKHOUSE, KeptCH, ddl @@ -547,12 +547,24 @@ async def query_one(self, *a, **k): raise RuntimeError("no table") pending_disclosure.reset_cache() + unread = ["memory: pending_count_unread (RuntimeError)"] + degradations.begin() assert ( await pending_disclosure.pending_extraction( org="o", namespace="n", agent="*", user_id=None, ch=_Broken() ) == 0 ) + assert degradations.current() == unread + # The remembered failure answers the next search, which names it too. + degradations.begin() + assert ( + await pending_disclosure.pending_extraction( + org="o", namespace="n", agent="*", user_id=None, ch=ch + ) + == 0 + ) + assert degradations.current() == unread # ---------------------------------------------------------------- status op diff --git a/tests/unit/test_facts_handlers.py b/tests/unit/test_facts_handlers.py index 3b2c0ec7735..c9e62a86b9d 100644 --- a/tests/unit/test_facts_handlers.py +++ b/tests/unit/test_facts_handlers.py @@ -782,6 +782,9 @@ async def test_traverse_hub_lookup_fails_open(monkeypatch: pytest.MonkeyPatch) - were off; the graph step never blocks an answer.""" from server.memory.api.models_facts import FactsTraverseInput from server.memory.app import facts as facts_handlers + from server.observability import degradations + + degradations.begin() class _Broken(_HopCH): async def query_all(self, sql: str, params: dict[str, Any] | None = None): @@ -802,6 +805,9 @@ async def query_all(self, sql: str, params: dict[str, Any] | None = None): ) ) assert "weather" in {n.entity for n in out.nodes} and out.hubs == [] + # The walk says the policy was off, and the memo does not keep it for the next caller. + assert degradations.current() == ["facts.traverse: hub_policy_off (RuntimeError)"] + assert facts_handlers._memo.cache == {} def test_is_hub_rules_compose_and_ignore_unknown_degrees() -> None: diff --git a/tests/unit/test_identity_incomplete.py b/tests/unit/test_identity_incomplete.py index bf43097873f..fb6bf1ff1ff 100644 --- a/tests/unit/test_identity_incomplete.py +++ b/tests/unit/test_identity_incomplete.py @@ -80,6 +80,8 @@ def test_only_the_org_level_listings_are_deployment_scoped() -> None: # namespace. # Collections are listed and made by grant, not by a namespace the call # names; a scoped token reaches them no further than its claim. + # The deployment's incidents name no namespace; the handler reads the org's + # request counts only for a token over every namespace of its org. assert scoped == [ "code.repos", "collection.create", @@ -91,6 +93,7 @@ def test_only_the_org_level_listings_are_deployment_scoped() -> None: "namespace.browse", "namespace.list_mine", "ops.capabilities", + "ops.incidents", "tracker.contract", "tracker.source.check", "tracker.source.list", diff --git a/tests/unit/test_memory_ask_precedents.py b/tests/unit/test_memory_ask_precedents.py index eb5e4f705e9..0774c79809f 100644 --- a/tests/unit/test_memory_ask_precedents.py +++ b/tests/unit/test_memory_ask_precedents.py @@ -235,6 +235,17 @@ async def insert( monkeypatch.setattr(repo, "_default_client", lambda: _CH()) monkeypatch.setattr(settings, "memory_ask_precedents", True) monkeypatch.setattr("server.memory.app.ask.handler._schedule_cited_used", lambda *a, **k: None) + # A store that answers: a read that fails here would make every answer a fallback's. + from server.memory.app.ask.context_blocks import AskKnowledge + + async def no_pending(**_k: Any) -> int: + return 0 + + async def no_knowledge(*_a: Any, **_k: Any) -> AskKnowledge: + return AskKnowledge() + + monkeypatch.setattr("server.memory.app.pending_disclosure.pending_extraction", no_pending) + monkeypatch.setattr("server.memory.app.ask.pipeline.knowledge_passages", no_knowledge) return env @@ -333,6 +344,25 @@ async def test_flag_off_and_per_request_false_are_strict_noops( assert len(prec_env.inserts) == 1 +@pytest.mark.asyncio +async def test_an_answer_a_fallback_served_is_no_precedent( + prec_env, monkeypatch: pytest.MonkeyPatch +) -> None: + """Its reuse would serve the smaller answer without the `degraded` that named it.""" + import server.memory.app.search as hsearch + from server.observability import degradations + from tests.unit.test_memory_ask import _search_output + + async def degraded_search(search_input: Any): + degradations.note("memory.search", "lexical_leg_dropped", ConnectionError(), health=False) + return _search_output(list(prec_env.hits)) + + monkeypatch.setattr(hsearch, "handle_memory_search", degraded_search) + degradations.begin() + out = await _ask() + assert out.source == "synthesized" and prec_env.inserts == [] + + @pytest.mark.asyncio async def test_uncited_or_hedged_answers_are_not_stored(prec_env) -> None: prec_env.llm._text = "I have no memory of your favorite color." diff --git a/tests/unit/test_namespace_health.py b/tests/unit/test_namespace_health.py index ac5e18d9a67..18ae5727454 100644 --- a/tests/unit/test_namespace_health.py +++ b/tests/unit/test_namespace_health.py @@ -17,6 +17,7 @@ from server.identity.app import namespace_audit as na from server.memory.app import namespace_health as nh +from server.observability import degradations from server.settings import settings @@ -180,8 +181,13 @@ def test_lookup_failure_returns_none_never_raises_and_is_held_briefly( assert asyncio.run(nh.namespace_health("o", "ns", clock=clock)) is None n = len(ch.sqls) t[0] += settings.memory_namespace_health_failure_ttl_s - 1 + degradations.begin() assert asyncio.run(nh.namespace_health("o", "ns", clock=clock)) is None assert len(ch.sqls) == n # the failure is remembered, not retried on every pack + # and every pack it answers says so + assert [d.split(" (")[0] for d in degradations.current()] == [ + "context.pack: namespace_health_dropped" + ] t[0] += 2 asyncio.run(nh.namespace_health("o", "ns", clock=clock)) assert len(ch.sqls) > n diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 1c97428cb03..ffb272d68d7 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -77,6 +77,18 @@ async def test_a_healthy_deployment_answers_ok_with_no_incident(monkeypatch) -> assert sli.params["org"] == "acme" # the caller's org only +@pytest.mark.asyncio +async def test_a_draining_process_is_no_incident(monkeypatch) -> None: + """Every deploy drains a process, which still answers what it started.""" + _ch(monkeypatch) + readiness.begin_drain() + + out = await _incidents() + + assert (await readiness.evaluate()).failing == ["draining"] + assert (out.status, out.incidents) == ("ok", []) + + @pytest.mark.asyncio async def test_each_source_lists_its_incident_errors_first(monkeypatch) -> None: readiness.register("clickhouse", lambda: readiness.result(False, "no answer within 2 s")) @@ -147,6 +159,24 @@ async def test_the_worker_read_names_the_enabled_workers_and_this_deployments_la assert deployment["hours"] == incidents._WORKER_WINDOW_HOURS +@pytest.mark.asyncio +async def test_a_class_is_an_incident_from_the_failure_share_and_the_call_floor( + monkeypatch, +) -> None: + rows = [ + {"slo_class": "read", "requests": 200, "server_errors": 2}, + {"slo_class": "write", "requests": 5, "server_errors": 5}, + ] + _ch(monkeypatch, sli=rows) + monkeypatch.setattr(settings, "ops_incidents_error_share", 0.1) + monkeypatch.setattr(settings, "ops_incidents_min_requests", 20) + assert (await _incidents()).incidents == [] # 1% is under the share, 5 calls under the floor + monkeypatch.setattr(settings, "ops_incidents_error_share", 0.01) + monkeypatch.setattr(settings, "ops_incidents_min_requests", 5) + monkeypatch.setattr(incidents, "_cache", {}) + assert [i.subject for i in (await _incidents()).incidents] == ["read", "write"] + + @pytest.mark.asyncio async def test_a_provider_failure_older_than_the_window_is_not_current(monkeypatch) -> None: provider_health.record_failure("classify", "caller_type_kept") @@ -330,10 +360,11 @@ def _mcp(c: dict[str, Any], who: str, org: str) -> dict[str, Any]: def test_a_token_of_one_org_naming_another_is_refused_on_both_transports( transports: dict[str, Any], ) -> None: - r = _http(transports, "acme", "other") - assert r.status_code == 403 and r.json()["detail"]["code"] == "AUTH_INSUFFICIENT" - out = _mcp(transports, "acme", "other") - assert out["isError"] is True and out["structuredContent"]["code"] == "ORG_MISMATCH" + for who in ("acme", "acme-team"): # org-wide, and narrowed to one namespace + r = _http(transports, who, "other") + assert r.status_code == 403 and r.json()["detail"]["code"] == "AUTH_INSUFFICIENT", who + out = _mcp(transports, who, "other") + assert out["isError"] is True and out["structuredContent"]["code"] == "ORG_MISMATCH" assert transports["ran"] == [] diff --git a/tests/unit/test_ops_incidents_sql.py b/tests/unit/test_ops_incidents_sql.py new file mode 100644 index 00000000000..28cef07c7ec --- /dev/null +++ b/tests/unit/test_ops_incidents_sql.py @@ -0,0 +1,108 @@ +"""The two statements ops.incidents reads, on clickhouse-local over the production tables: +the failure streaks of this deployment's enabled workers, and the org's calls per SLO +class that failed on the server.""" + +from __future__ import annotations + +import pytest + +from server.insights.store import ops as ops_store +from server.workers import status_store +from tests.unit.clickhouse_local import CLICKHOUSE, LocalCH, ddl + +pytestmark = pytest.mark.skipif(CLICKHOUSE is None, reason="clickhouse binary not installed") + +_ENABLED = ["a", "b", "d", "e", "f", "g", "h"] + +# (worker, label, minutes ago, consecutive failures, error class, version) +_PASSES = [ + ("a", "deploy:api", 60, 3, "ConnectionError", 1), + ("a", "iso:x", 50, 5, "TimeoutError", 1), # an isolated server's row + ("b", "", 420, 4, "ConnectionError", 1), # older than the 6 h window + ("c", "deploy:api", 60, 9, "ConnectionError", 1), # not an enabled worker + ("d", "deploy:api", 61, 3, "ConnectionError", 1), + ("d", "deploy:api", 61, 0, "", 2), # a later version cleared the streak + ("e", "deploy:api", 120, 4, "ConnectionError", 1), + ("e", "deploy:workers:green", 30, 0, "", 1), # its freshest pass succeeded + ("f", "", 90, 3, "OSError", 1), # an unlabelled deployment process + ("g", "deployer:x", 40, 6, "ConnectionError", 1), # `deploy` is not its first segment + ("h", "deploy:api", 20, 2, "ConnectionError", 1), # under the threshold +] + + +def _worker_rows() -> str: + values = ", ".join( + f"('{w}', '{label}', {ago}, {streak}, '{kind}', {version})" + for w, label, ago, streak, kind, version in _PASSES + ) + return ( + "INSERT INTO loom.worker_status (pass_id, worker, instance_label, pass_started, " + "pass_finished, status, error_class, consecutive_failures, version) " + "SELECT generateUUIDv4(), w, l, now64(3) - toIntervalMinute(m), " + "now64(3) - toIntervalMinute(m) + toIntervalSecond(1), if(f > 0, 'error', 'ok'), k, f, v " + "FROM values('w String, l String, m UInt32, f UInt16, k String, v UInt64', " + f"{values})" + ) + + +async def _streaks(label: str) -> list[tuple[str, int, str]]: + ch = LocalCH(ddl("worker_status"), _worker_rows()) + rows = await status_store.failing_streaks(_ENABLED, label, 3, 6, ch=ch) + return [(r["worker"], int(r["consecutive_failures"]), r["error_class"]) for r in rows] + + +async def test_the_deployment_reads_its_enabled_workers_current_streaks() -> None: + assert await _streaks("deploy:api") == [("a", 3, "ConnectionError"), ("f", 3, "OSError")] + assert await _streaks("") == [("a", 3, "ConnectionError"), ("f", 3, "OSError")] + + +async def test_another_server_reads_only_its_own_label() -> None: + assert await _streaks("iso:x") == [("a", 5, "TimeoutError")] + assert await _streaks("deployer:x") == [("g", 6, "ConnectionError")] + + +def test_a_deployment_label_has_deploy_as_its_first_segment() -> None: + assert status_store.is_deployment_label("") + assert status_store.is_deployment_label("deploy:workers:green") + assert not status_store.is_deployment_label("deployer:x") + assert not status_store.is_deployment_label("iso:x") + + +# (minutes ago, SLO class, org, operation, requests, server errors) +_CALLS = [ + (3, "interactive", "o1", "code.search", 1600, 1600), + (2, "interactive", "o1", "code.grep", 18, 18), + (3, "interactive", "o2", "code.search", 50, 0), # another org's + (3, "", "o1", "code.search", 7, 7), # a resume mark of the rollup + (40, "batch", "o1", "code.search", 30, 30), # outside the window +] + + +def _sli_rows() -> str: + values = ", ".join( + f"({ago}, '{cls}', '{org}', '{op}', {n}, {failed})" + for ago, cls, org, op, n, failed in _CALLS + ) + return ( + "INSERT INTO loom_telemetry.sli_minute (minute, slo_class, operation, transport, " + "traffic_class, org, requests, server_errors) " + "SELECT toStartOfMinute(now() - toIntervalMinute(m)), c, op, 'mcp', 'agent', o, r, e " + "FROM values('m UInt32, c String, o String, op String, r UInt64, e UInt64', " + f"{values})" + ) + + +async def test_the_request_read_sums_the_orgs_classes_in_the_window() -> None: + ch = LocalCH( + "CREATE DATABASE IF NOT EXISTS loom_telemetry", + ddl("sli_minute", "loom_telemetry"), + _sli_rows(), + ) + + async def read(org: str) -> list[tuple[str, int, int]]: + rows = await ops_store.request_errors_by_class(org, 15, ch=ch) # type: ignore[arg-type] + return [(r["slo_class"], int(r["requests"]), int(r["server_errors"])) for r in rows] + + assert await read("o1") == [("interactive", 1618, 1618)] + assert await read("o2") == [("interactive", 50, 0)] + assert await read("o3") == [] diff --git a/tests/unit/test_ui_read_caches.py b/tests/unit/test_ui_read_caches.py index 614fc9497ac..4f694cda7e2 100644 --- a/tests/unit/test_ui_read_caches.py +++ b/tests/unit/test_ui_read_caches.py @@ -91,8 +91,8 @@ async def _status(cfg: Any): assert first.v == 1 # age the entry past the TTL key = (cfg.org, cfg.namespace) - at, st = index_status._status_cache[key] - index_status._status_cache[key] = (at - settings.code_status_ttl_s - 1, st) + at, st, noted = index_status._status_cache[key] + index_status._status_cache[key] = (at - settings.code_status_ttl_s - 1, st, noted) stale = await index_status._repo_status_cached(cfg) assert stale is first # served at once, no wait await asyncio.sleep(0) # let the background refresh run @@ -100,3 +100,40 @@ async def _status(cfg: Any): fresh = await index_status._repo_status_cached(cfg) assert fresh.v == 2 and n["calls"] == 2 index_status.reset_repo_status_cache() + + +@pytest.mark.asyncio +async def test_a_status_a_read_left_smaller_names_it_on_every_answer_and_is_not_published( + monkeypatch, +) -> None: + import asyncio + + from server.observability import degradations + + index_status.reset_repo_status_cache() + published: list[str] = [] + + async def _status(cfg: Any): + if cfg.namespace == "code-x": + degradations.note( + "code_index", "worker_ledger_unread", ConnectionError("x"), health=False + ) + return SimpleNamespace(org=cfg.org, namespace=cfg.namespace) + + async def _publish(cfg: Any, st: Any) -> None: + published.append(cfg.namespace) + + monkeypatch.setattr(index_status, "_repo_status", _status) + monkeypatch.setattr(index_status, "_publish_status_snapshot", _publish) + noted = SimpleNamespace(org="acme", namespace="code-x") + whole = SimpleNamespace(org="acme", namespace="code-y") + for _ in range(2): # computed, then served from the cache + degradations.begin() + await index_status._repo_status_cached(noted) + assert degradations.current() == ["code_index: worker_ledger_unread (ConnectionError)"] + degradations.begin() + await index_status._repo_status_cached(whole) + assert degradations.current() == [] + await asyncio.sleep(0) + assert published == ["code-y"] + index_status.reset_repo_status_cache() From e2fdd35d38d163ae78ba84550859bc8c955096c0 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 05:38:27 +0530 Subject: [PATCH 06/47] Caches judge an answer by its own notes, and ops.incidents counts follow the org-wide rule degradations.unit() isolates a block's notes and then lists them in the caller's: code.search, code.ask's fresh answer, code.map, facts.traverse, memory.ask, the review-brief builds and each repository status keep an answer only when their own unit noted nothing. Every read fallback calls degradations.partial(), note with health=False fixed. code.symbol asks only the dependency namespaces the caller may read, so degraded never names one it cannot. ops.incidents reads request counts only for a caller that reads the org whole (reads_every_namespace, now shared with resolve_org_scope) with no restricted namespace hidden. Statuses sharing a failed ledger read each carry its note. A merge sha the mirror does not hold is a miss, not a failed read. The backport-gaps worker logs a fallback and reads the fix once more within the pass budget. Each worker pass and status refresh starts with no notes, and fixed-bound timeouts in memory.search and memory.for_file are noted. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 8 +- sdk/go/wire/models.gen.go | 2 +- server/auth/context.py | 29 ++- server/code/app/answers.py | 54 +++-- server/code/app/answers_cache.py | 2 +- server/code/app/backport.py | 6 +- server/code/app/bisect.py | 6 +- server/code/app/bisect_fix.py | 6 +- server/code/app/bisect_fusion.py | 4 +- server/code/app/bisect_scan.py | 2 +- server/code/app/blame.py | 4 +- server/code/app/candidates.py | 2 +- server/code/app/citations.py | 2 +- server/code/app/common.py | 2 +- server/code/app/context.py | 10 +- server/code/app/conventions.py | 4 +- server/code/app/coverage.py | 6 +- server/code/app/enrich.py | 4 +- server/code/app/fan_in.py | 2 +- server/code/app/files.py | 2 +- server/code/app/grep.py | 4 +- server/code/app/history.py | 2 +- server/code/app/index/gitrepo.py | 9 +- server/code/app/index/review_brief_build.py | 224 +++++++++--------- server/code/app/index/review_brief_sources.py | 12 +- server/code/app/index_status.py | 27 ++- server/code/app/pr_check.py | 4 +- server/code/app/repo_scope.py | 2 +- server/code/app/repos.py | 2 +- server/code/app/result_lessons.py | 2 +- server/code/app/review_brief.py | 8 +- server/code/app/search/cards.py | 2 +- server/code/app/search/definitions.py | 2 +- server/code/app/search/handler.py | 17 +- server/code/app/search/history.py | 2 +- server/code/app/search/lexical.py | 2 +- server/code/app/search/symbol.py | 2 +- server/code/app/search/vector.py | 2 +- server/code/app/symbol/coverage.py | 12 +- server/code/app/symbol/dispatch.py | 6 +- server/code/app/symbol/enclosing.py | 2 +- .../code/app/symbol/enclosing_decorators.py | 5 +- server/code/app/symbol/hierarchy.py | 2 +- server/code/app/symbol/neighbours.py | 2 +- server/code/app/symbol/outline.py | 2 +- server/code/app/symbol/resolve.py | 2 +- server/code/app/symbol/symbol.py | 22 +- server/code/app/symbol/verify.py | 2 +- server/code/app/symbol_context.py | 2 +- server/code/app/symbol_uses.py | 2 +- server/code/workers/backport_gaps.py | 45 ++-- server/insights/api/models_ops.py | 6 +- server/insights/app/incidents.py | 29 ++- server/memory/app/ask/completion.py | 2 +- server/memory/app/ask/context_blocks.py | 2 +- server/memory/app/ask/handler.py | 31 ++- server/memory/app/ask/identifiers.py | 10 +- server/memory/app/ask/reader.py | 2 +- server/memory/app/ask/records.py | 4 +- server/memory/app/ask/supersession.py | 2 +- server/memory/app/ask_when_evidence.py | 2 +- server/memory/app/code_grounding.py | 14 +- server/memory/app/code_link_reads.py | 4 +- server/memory/app/context_pack.py | 8 +- server/memory/app/deep_evidence.py | 2 +- server/memory/app/entity_resolution.py | 2 +- server/memory/app/facts.py | 16 +- server/memory/app/for_file.py | 7 +- .../memory/app/loom_search/repo_decisions.py | 2 +- server/memory/app/loom_search/tracker_leg.py | 4 +- server/memory/app/namespace_health.py | 2 +- server/memory/app/namespace_types.py | 2 +- server/memory/app/pending_disclosure.py | 2 +- server/memory/app/pending_evidence.py | 2 +- server/memory/app/procedure.py | 4 +- server/memory/app/profile_search.py | 4 +- server/memory/app/proposals_ops.py | 2 +- server/memory/app/query.py | 2 +- server/memory/app/retrieval/chunks.py | 8 +- server/memory/app/retrieval/derived.py | 8 +- server/memory/app/retrieval/pool.py | 4 +- server/memory/app/retrieval/side_legs.py | 6 +- server/memory/app/retrieval/summaries.py | 4 +- server/memory/app/runs_manifest.py | 2 +- server/memory/app/search/anchor_pool.py | 2 +- server/memory/app/search/computed.py | 2 +- server/memory/app/search/digest_descent.py | 2 +- server/memory/app/search/key_match.py | 2 +- server/memory/app/search/output.py | 4 +- server/memory/app/search/payload.py | 4 +- .../memory/app/search/shared_definitions.py | 2 +- server/memory/app/search/supplemental.py | 4 +- server/memory/app/search/tiers.py | 4 +- server/memory/app/search_llm.py | 13 +- server/memory/app/served_superseded.py | 2 +- server/memory/app/stack_knowledge.py | 2 +- server/memory/app/working_memory.py | 2 +- server/memory/store/lifecycle.py | 6 +- server/observability/degradations.py | 29 ++- server/workers/supervisor.py | 8 +- tests/unit/test_code_answer_completeness.py | 2 +- tests/unit/test_code_backport_gaps.py | 73 ++++-- tests/unit/test_code_read_degradations.py | 2 +- tests/unit/test_code_review_brief_mirror.py | 8 + tests/unit/test_code_search_pick.py | 27 ++- tests/unit/test_code_symbol_dependency.py | 30 ++- tests/unit/test_degradations.py | 29 ++- .../test_idempotency_across_transports.py | 2 +- tests/unit/test_memory_ask_precedents.py | 2 +- tests/unit/test_ops_incidents.py | 57 ++++- tests/unit/test_pg_authority.py | 2 +- .../test_review_brief_store_needs_diff.py | 4 +- tests/unit/test_ui_read_caches.py | 52 +++- tests/unit/test_worker_ledger_rows.py | 10 + 114 files changed, 745 insertions(+), 432 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 00c66a75555..83bc48ff021 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -154,9 +154,11 @@ first, at most 20: Request counts come from `loom_telemetry.sli_minute`, which trails the calls by about two minutes and keeps no namespace or user. They are read for the org the call acts in, and -only by a token over every namespace of that org that reads whole namespaces: a token -narrowed to some namespaces or pinned to one user, and a `*` token that names no org, -read none. The other kinds are deployment state, the same for every org: a readiness or +only by a caller that reads that org whole, as the org-wide rollups have it: a platform +admin, or an org admin of the org whose claim is `*`, reading whole namespaces, with no +restricted namespace of the org hidden from it. A member's token, an admin narrowed to +some namespaces or pinned to one user, and a `*` token that names no org read none. The +other kinds are deployment state, the same for every org: a readiness or provider incident names the check or provider and an error's kind, as `/v1/health` does, and a worker incident names a worker of any of the deployment's processes with its streak and error kind, where `/v1/health?include=workers` shows only the answering process's diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index cfab9d18f00..a5d46647f74 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: c75d4418b0911952ece98e92510550dbb8e27e35f1c10022c01d5de519ea2e64 +// Registry model schema SHA-256: e9d5400400fc9ed5ffcddfead9a1760771c8dda2049199908fc00227763e24df // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/auth/context.py b/server/auth/context.py index 3dcc764bb01..4623ecd7724 100644 --- a/server/auth/context.py +++ b/server/auth/context.py @@ -325,6 +325,23 @@ async def every_namespace_scope(org: str, *, column: str = "namespace") -> OrgSc return OrgScopeFilter(accessible=True, where=where, params=params) +def reads_every_namespace(auth: AuthInfo, org: str) -> bool: + """Whether `auth` reads `org` whole, but for the restricted namespaces it holds no + grant for (`every_namespace_scope`): a platform admin, or an org admin of `org` + whose claim is `*`. + + An org admin administers its own org; only a platform admin spans orgs. An org + admin whose token lists namespaces reads as a member does: the gate admits it to + no other namespace by name. A platform admin reads the org whole whatever its + claim: its dashboard session lists only the person's own namespaces + (`login._identity_from_rows`).""" + from server.operations.base import Role + + return auth.has_role(Role.PLATFORM_ADMIN) or ( + auth.has_role(Role.ORG_ADMIN) and auth.org in ("*", org) and "*" in auth.namespaces + ) + + async def resolve_org_scope(org: str, *, column: str = "namespace") -> OrgScopeFilter: """WHERE fragment scoping an org-wide read to the namespaces the caller may see. Platform admins and org admins whose claim is `*` get @@ -338,19 +355,10 @@ async def resolve_org_scope(org: str, *, column: str = "namespace") -> OrgScopeF exclusion (``ns_hidden``) and the inclusion (``ns_list``) bind different param names, so equal lists never read as the same scope. """ - from server.operations.base import Role - auth = current_auth() if auth is None or not auth.subject: return OrgScopeFilter(accessible=True, where=f" AND {not_reserved_sql(column)}", params={}) - # An org admin administers its own org; only a platform admin spans orgs. - # An org admin whose token lists namespaces reads as a member does: the - # gate admits it to no other namespace by name. A platform admin reads - # the org whole whatever its claim: its dashboard session lists only the - # person's own namespaces (`login._identity_from_rows`). - if auth.has_role(Role.PLATFORM_ADMIN) or ( - auth.has_role(Role.ORG_ADMIN) and auth.org in ("*", org) and "*" in auth.namespaces - ): + if reads_every_namespace(auth, org): return await every_namespace_scope(org, column=column) ns_list = await rollup_member_namespaces(org) if not ns_list: @@ -370,6 +378,7 @@ async def resolve_org_scope(org: str, *, column: str = "namespace") -> OrgScopeF "every_namespace_scope", "named_claims", "readable_named_claims", + "reads_every_namespace", "resolve_my_namespaces", "resolve_org_scope", "restricted_namespaces_hidden_from", diff --git a/server/code/app/answers.py b/server/code/app/answers.py index 29b0c7756bd..e8b498e42ab 100644 --- a/server/code/app/answers.py +++ b/server/code/app/answers.py @@ -130,28 +130,30 @@ async def ask( outcome = looked.outcome llm_cache_on = cacheable and not no_cache and _pre_synthesis_cache_on() scope = exact_cache_scope(org, ns) if llm_cache_on else contextlib.nullcontext() - with scope: - res = await _answer_fresh( - ctx, - embedder=embedder if qvec else None, - llm=llm, - search_kwargs=search_kwargs - if qvec - else {**search_kwargs, "embedding_model": ctx.model}, - allow_synthesis=allow_synthesis, - cache_llm=llm_cache_on, - ) - res.cache = outcome - _disclose_retrieval(res) - if not qvec: - _mark_incomplete( - res, - "question embedding unavailable", - "Semantic retrieval and answer-cache lookup were unavailable; " - "available repository evidence was used.", - ) - if cacheable: - await _remember(ctx, res, llm) + # the answer's own notes decide whether it is stored, not the request's before it + with degradations.unit(): + with scope: + res = await _answer_fresh( + ctx, + embedder=embedder if qvec else None, + llm=llm, + search_kwargs=search_kwargs + if qvec + else {**search_kwargs, "embedding_model": ctx.model}, + allow_synthesis=allow_synthesis, + cache_llm=llm_cache_on, + ) + res.cache = outcome + _disclose_retrieval(res) + if not qvec: + _mark_incomplete( + res, + "question embedding unavailable", + "Semantic retrieval and answer-cache lookup were unavailable; " + "available repository evidence was used.", + ) + if cacheable: + await _remember(ctx, res, llm) return res @@ -387,7 +389,7 @@ async def _expand_mechanism( return out except Exception as e: # noqa: BLE001 — expansion must never sink an answer logger.debug("mechanism expansion skipped: %s", e) - degradations.note("code_index", "mechanism_expansion_skipped", e, health=False) + degradations.partial("code_index", "mechanism_expansion_skipped", e) return [] @@ -407,7 +409,7 @@ async def _propose_identifiers(llm: Any, question: str) -> list[str]: except Exception as e: # noqa: BLE001 — expansion is best-effort logger.debug("identifier proposal skipped: %s", e) # The model client counted its own failure in provider health. - degradations.note("llm", "identifier_expansion_skipped", e, health=False) + degradations.partial("llm", "identifier_expansion_skipped", e) return [] @@ -548,7 +550,7 @@ async def _inject_memory_context(question: str) -> MemoryContext: return MemoryContext() except Exception as e: # noqa: BLE001 — fail closed logger.debug("code.ask memory enrichment authorization failed: %s", e) - degradations.note("memory", "ask_context_dropped", e, health=False) + degradations.partial("memory", "ask_context_dropped", e) return MemoryContext() shown = 3 # memory lines, one per key try: @@ -570,7 +572,7 @@ async def _inject_memory_context(question: str) -> MemoryContext: ) except Exception as e: # noqa: BLE001 — additive, never fatal logger.debug("code.ask memory enrichment failed: %s", e) - degradations.note("memory", "ask_context_dropped", e, health=False) + degradations.partial("memory", "ask_context_dropped", e) return MemoryContext() if getattr(out, "abstain", False): return MemoryContext() diff --git a/server/code/app/answers_cache.py b/server/code/app/answers_cache.py index 9b6e23c4786..ed7fa25f290 100644 --- a/server/code/app/answers_cache.py +++ b/server/code/app/answers_cache.py @@ -331,7 +331,7 @@ def _exact_cached(llm: Any, org: str, ns: str) -> Any: async def _remember(ctx: _AskCtx, res: AskResult, llm: Any) -> None: """Store a memoizable answer, or a negative entry for an abstain. A partial answer, - or one served from a fallback (`degraded`), is not stored.""" + or one served from a fallback (a note of the unit `ask` builds it in), is not stored.""" if res.partial or degradations.current(): return try: diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 50f15a4ed48..2654a39c09a 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -307,7 +307,7 @@ async def _file_presence( index_as_of(repo, org, ns), ) except Exception as e: # noqa: BLE001 — one branch's read, disclosed as unknown - degradations.note("code_index", "branch_presence_unread", e, health=False) + degradations.partial("code_index", "branch_presence_unread", e) logger.debug("backport_gap: file presence failed on %s: %s", ns, e) return [], [], False return ( @@ -321,7 +321,7 @@ async def _ledger_backports(repo: CodeRepo, org: str, ns: str, number: int) -> l try: rows = await repo.backport_prs_titled(org, ns, number) except Exception as e: # noqa: BLE001 — the ledger leg is a second opinion - degradations.note("code_index", "backport_ledger_dropped", e, health=False) + degradations.partial("code_index", "backport_ledger_dropped", e) logger.debug("backport_gap: ledger read failed on %s: %s", ns, e) return [] return [ @@ -511,7 +511,7 @@ async def _ledger_fix() -> PrFacts | None: try: return await repo.pr_facts(req.org, req.namespace, number) except Exception as e: # noqa: BLE001 — the ledger miss is disclosed on the fix block - degradations.note("code_index", "fix_ledger_unread", e, health=False) + degradations.partial("code_index", "fix_ledger_unread", e) logger.debug("backport_gap: ledger fix read failed: %s", e) return None diff --git a/server/code/app/bisect.py b/server/code/app/bisect.py index 89f572567d9..220041c3147 100644 --- a/server/code/app/bisect.py +++ b/server/code/app/bisect.py @@ -118,7 +118,7 @@ async def lookup(name: str) -> list[str]: try: rows = await repo.symbols_by_name(org, ns, name, limit=12) except Exception as e: # noqa: BLE001 — one frame's miss is not the answer - degradations.note("code_index", "frame_paths_dropped", e, health=False) + degradations.partial("code_index", "frame_paths_dropped", e) logger.debug("bisect: symbol lookup failed for %s: %s", name, e) rows = [] paths = [ @@ -211,7 +211,7 @@ async def _issue_edges(source: Any, org: str, tracker_ns: str, number: int) -> l ) ) except Exception as e: # noqa: BLE001 — the graph is a bonus, not the range - degradations.note("tracker", "issue_edges_dropped", e, health=False) + degradations.partial("tracker", "issue_edges_dropped", e) logger.info("bisect: issue edges unavailable (%s)", e) return [] @@ -328,7 +328,7 @@ async def _attach_merge_shas(repo: CodeRepo, org: str, ns: str, ranked: list[bi. try: ref = await cb.indexed_head(repo, org, ns) or (f"refs/heads/{branch}" if branch else "") except Exception as e: # noqa: BLE001 — the head is unknown: no search past it - degradations.note("code_index", "mirror_search_skipped", e, health=False) + degradations.partial("code_index", "mirror_search_skipped", e) logger.info("bisect: indexed head unread, mirror search skipped (%s)", e) ref = "" since = min((br.unix_of(c.merged_at) for c in ranked), default=0) diff --git a/server/code/app/bisect_fix.py b/server/code/app/bisect_fix.py index 39595069902..c4d395f06fc 100644 --- a/server/code/app/bisect_fix.py +++ b/server/code/app/bisect_fix.py @@ -58,7 +58,7 @@ async def _cause_stage( org, tracker_ns, [c.pr_number for c in head], since=since[:19].replace("T", " ") ) except Exception as e: # noqa: BLE001 — a ranking prior, never the answer - degradations.note("tracker", "cause_statements_dropped", e, health=False) + degradations.partial("tracker", "cause_statements_dropped", e) logger.info("bisect: cause statements unavailable (%s)", e) return pool if not stmts: @@ -162,7 +162,7 @@ async def _dupcheck_fix(task: Any, started: float | None = None) -> dict[str, An return {"status": "deadline", "budget_s": budget} return {"status": "timeout", "budget_s": budget} except Exception as e: # noqa: BLE001 — fail open - degradations.note("tracker", "dupcheck_fix_skipped", e, health=False) + degradations.partial("tracker", "dupcheck_fix_skipped", e) logger.info("bisect: duplicate-check fix skipped: %s", e) return {} @@ -260,7 +260,7 @@ async def _fix_named_stage( try: named = await read(org, tracker_ns, int(fix_pr)) except Exception as e: # noqa: BLE001 — fails open to the scan's order - degradations.note("tracker", "fix_cause_dropped", e, health=False) + degradations.partial("tracker", "fix_cause_dropped", e) logger.info("bisect: fix #%s cause statement unavailable (%s)", fix_pr, e) return pool if not named: diff --git a/server/code/app/bisect_fusion.py b/server/code/app/bisect_fusion.py index 56489fa4791..8c4a9dc7336 100644 --- a/server/code/app/bisect_fusion.py +++ b/server/code/app/bisect_fusion.py @@ -38,7 +38,7 @@ async def _embed(text: str) -> list[float]: except customer.HOLDS: raise # the org's model calls are held: the request answers that except Exception as e: # noqa: BLE001 — no vector leg, the others still rank - degradations.note("embedder", "fusion_vector_leg_dropped", e, health=False) + degradations.partial("embedder", "fusion_vector_leg_dropped", e) logger.info("bisect fusion: embed failed: %s", e) return [] @@ -61,7 +61,7 @@ async def _vector_order( numbers=numbers, ) except Exception as e: # noqa: BLE001 — the vector leg is optional - degradations.note("tracker", "fusion_vector_leg_dropped", e, health=False) + degradations.partial("tracker", "fusion_vector_leg_dropped", e) logger.info("bisect fusion: vector read failed: %s", e) return [] return [int(h["number"]) for h in hits] diff --git a/server/code/app/bisect_scan.py b/server/code/app/bisect_scan.py index 13cd730ad62..a0683406861 100644 --- a/server/code/app/bisect_scan.py +++ b/server/code/app/bisect_scan.py @@ -265,7 +265,7 @@ async def _code_history_rows( org, ns, paths=paths, dirs=dirs, before=before, after=after, limit=limit ) except Exception as e: # noqa: BLE001 — a failed history read is no candidates - degradations.note("code_index", "history_candidates_dropped", e, health=False) + degradations.partial("code_index", "history_candidates_dropped", e) logger.info("bisect: code history of %s/%s unavailable: %s", org, ns, e) return [] cfg = repo_for_namespace(org, ns) diff --git a/server/code/app/blame.py b/server/code/app/blame.py index 404c948363c..58283ed2501 100644 --- a/server/code/app/blame.py +++ b/server/code/app/blame.py @@ -651,7 +651,7 @@ async def _issue_titles( items = await repo.items_by_number(org, ns, nums) except Exception as e: # noqa: BLE001 — a promotion source, not a leg logger.info("blame_range: issue titles unread: %s", e) - degradations.note("tracker", "issue_titles_unread", e, health=False) + degradations.partial("tracker", "issue_titles_unread", e) return {} return {n: str(r.get("title") or "") for n, r in items.items()} @@ -928,7 +928,7 @@ async def _indexed(repo: CodeRepo, org: str, ns: str, path: str) -> bool: try: return path in await repo.live_paths_present(org, ns, [path]) except Exception as e: # noqa: BLE001 — a fact for the verdict, not a leg - degradations.note("code_index", "path_presence_unread", e, health=False) + degradations.partial("code_index", "path_presence_unread", e) logger.debug("blame_range: live_paths_present failed: %s", e) return False diff --git a/server/code/app/candidates.py b/server/code/app/candidates.py index 0f3a63464b2..9c9b56a5a3a 100644 --- a/server/code/app/candidates.py +++ b/server/code/app/candidates.py @@ -335,7 +335,7 @@ async def overrides_of( limit=OVERRIDE_FANOUT_CAP + 1, ) except Exception as e: # noqa: BLE001 - degradations.note("code_index", "override_callers_dropped", e, health=False) + degradations.partial("code_index", "override_callers_dropped", e) logger.debug("overrides read skipped: %s", e) return [], False out: list[dict[str, Any]] = [] diff --git a/server/code/app/citations.py b/server/code/app/citations.py index 70db5dee876..b9761828937 100644 --- a/server/code/app/citations.py +++ b/server/code/app/citations.py @@ -195,7 +195,7 @@ async def lookup(name: str) -> list[dict[str, Any]]: try: return await repo.symbols_by_name(org, ns, name, limit=20) except Exception as e: # noqa: BLE001 — one name's failure is one unresolved - degradations.note("code_index", "name_unresolved", e, health=False) + degradations.partial("code_index", "name_unresolved", e) logger.info("verify_citations: name lookup failed for %s: %s", name, e) return [] diff --git a/server/code/app/common.py b/server/code/app/common.py index 335970e040a..f06d35d3356 100644 --- a/server/code/app/common.py +++ b/server/code/app/common.py @@ -292,7 +292,7 @@ async def index_as_of(repo: CodeRepo, org: str, ns: str) -> dict[str, Any]: _AS_OF_CACHE.put((org, ns), block) return dict(block) except Exception as err: # noqa: BLE001 — unknown freshness, not an error - degradations.note("code_index", "as_of_unread", err, health=False) + degradations.partial("code_index", "as_of_unread", err) return {} diff --git a/server/code/app/context.py b/server/code/app/context.py index 5959dbcee36..0f926f6dc3a 100644 --- a/server/code/app/context.py +++ b/server/code/app/context.py @@ -268,12 +268,14 @@ async def _render_map( cached = _MAP_CACHE.get(key) if cached is not None: return cached - text = await _build_map_text(repo, org, ns, module_prefix, token_budget) + with degradations.unit(): + text = await _build_map_text(repo, org, ns, module_prefix, token_budget) + whole = not degradations.current() # a map a read left smaller is served, not kept # Detect a completed index advance, not a snapshot of its progressive writes. if await repo.get_state(org, ns, "git_head") != head: continue artifact = _MapArtifact(text=text, commit_sha=head) - if not degradations.current(): # a map a read left smaller is served, not kept + if whole: _MAP_CACHE.put(key, artifact) return artifact raise OverloadedError("Repository index changed while rendering the map; retry shortly.") @@ -306,7 +308,7 @@ async def _build_map_text( try: hubs = await code_fan_in.top_under(repo, org, ns, module_prefix, limit=10) except Exception as e: # noqa: BLE001 — the file cards stand alone - degradations.note("code_index", "most_called_dropped", e, health=False) + degradations.partial("code_index", "most_called_dropped", e) hubs = [] if hubs: head = "## Most-called symbols" + (f" under {module_prefix}" if module_prefix else "") @@ -334,7 +336,7 @@ async def _call_graph_hubs( cards = await repo.cards_for_paths(org, ns, model, paths) if paths else {} except Exception as e: # the include-graph map is served without the call-graph hubs logger.info("code map: call-graph hubs unavailable for %s/%s", org, ns, exc_info=True) - degradations.note("code_index", "call_graph_hubs_dropped", e, health=False) + degradations.partial("code_index", "call_graph_hubs_dropped", e) return [], {} return callers, cards diff --git a/server/code/app/conventions.py b/server/code/app/conventions.py index 005736fda66..d33b31254d9 100644 --- a/server/code/app/conventions.py +++ b/server/code/app/conventions.py @@ -398,7 +398,7 @@ async def _wide_callers( # parser tier's extents say which function an added line falls in symbols = await repo.functions_for_paths(org, ns, paths) except Exception as e: # noqa: BLE001 — the check reports unknown - degradations.note("code_index", "wide_callers_unread", e, health=False) + degradations.partial("code_index", "wide_callers_unread", e) logger.info("conventions: functions read failed: %s", e) return [], {}, False, True funcs = conventions_rules.touched_functions(src.diff, symbols)[:_MAX_TOUCHED] @@ -415,7 +415,7 @@ async def _wide_callers( per_match=400, ) except Exception as e: # noqa: BLE001 — the check reports unknown - degradations.note("code_index", "wide_callers_unread", e, health=False) + degradations.partial("code_index", "wide_callers_unread", e) logger.info("conventions: callers read failed: %s", e) return funcs, {}, False, True conventions_rules.attach_callers(funcs, edges) diff --git a/server/code/app/coverage.py b/server/code/app/coverage.py index 30253fd23f7..550e9afcf16 100644 --- a/server/code/app/coverage.py +++ b/server/code/app/coverage.py @@ -169,7 +169,7 @@ async def positive_control(repo: CodeRepo, org: str, ns: str) -> tuple[bool, str try: files, _total = await _grep_tests(repo, org, ns, cc.grep_pattern("symbol", probe), limit=3) except Exception as e: # noqa: BLE001 — a failed control is a failed control - degradations.note("code_index", "coverage_control_unread", e, health=False) + degradations.partial("code_index", "coverage_control_unread", e) return False, probe _control_cache[(org, ns)] = (bool(files), probe, now) return bool(files), probe @@ -550,7 +550,7 @@ async def search_terms( ) except Exception as e: # noqa: BLE001 — the SQL names are an extra term, never the claim logger.info("coverage_claim: sql names read failed: %s", e) - degradations.note("code_index", "sql_name_terms_dropped", e, health=False) + degradations.partial("code_index", "sql_name_terms_dropped", e) return terms for n in names: terms[n] = cc.EXACT_SCOPED @@ -721,7 +721,7 @@ async def _leg(coro: Any, what: str) -> list[dict[str, Any]]: return list(await coro) except Exception as e: # noqa: BLE001 — extra evidence, never the claim's failure logger.info("coverage_claim: %s leg failed: %s", what, e) - degradations.note("code_index", f"{what}_tests_dropped", e, health=False) + degradations.partial("code_index", f"{what}_tests_dropped", e) return [] diff --git a/server/code/app/enrich.py b/server/code/app/enrich.py index 096d1406aba..1dc3b9a7ff8 100644 --- a/server/code/app/enrich.py +++ b/server/code/app/enrich.py @@ -116,11 +116,11 @@ async def bounded[T](coro: Awaitable[T], fallback: T, seconds: float | None = No except TimeoutError as e: logger.debug("code enrich cut by its bound") if seconds is None: - degradations.note("code_index", "enrichment_skipped", e, health=False) + degradations.partial("code_index", "enrichment_skipped", e) return fallback except Exception as e: # noqa: BLE001 — enrichment degrades, never fails logger.debug("code enrich degraded: %s", e) - degradations.note("code_index", "enrichment_skipped", e, health=False) + degradations.partial("code_index", "enrichment_skipped", e) return fallback diff --git a/server/code/app/fan_in.py b/server/code/app/fan_in.py index 845d783c0e5..95e162fa3ee 100644 --- a/server/code/app/fan_in.py +++ b/server/code/app/fan_in.py @@ -79,7 +79,7 @@ async def annotate_units( try: stats = await stats_for(repo, org, ns, wanted[:1000]) except Exception as e: # noqa: BLE001 — the field is additive - degradations.note("code_index", "fan_in_dropped", e, health=False) + degradations.partial("code_index", "fan_in_dropped", e) logger.debug("fan-in annotation skipped: %s", e) return 0 n = 0 diff --git a/server/code/app/files.py b/server/code/app/files.py index 96d0c1f3da9..d60ca860067 100644 --- a/server/code/app/files.py +++ b/server/code/app/files.py @@ -44,7 +44,7 @@ async def attach_reference_siblings( try: present = await repo.live_paths_present(org, ns, [p for c in cands.values() for p in c]) except Exception as e: # noqa: BLE001 — the sibling is decoration, never the answer - degradations.note("code_index", "reference_siblings_unread", e, health=False) + degradations.partial("code_index", "reference_siblings_unread", e) logger.debug("code.files: reference sibling read skipped: %s", e) present = set() for i in cands: diff --git a/server/code/app/grep.py b/server/code/app/grep.py index 309f2da38a2..99eaa78d467 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -983,7 +983,7 @@ async def _extra_related_source( return None, {"partial": True, "partial_reason": f"{stage} timed out"} except Exception as error: # noqa: BLE001 — preserve exact evidence on optional read failure logger.debug("%s failed: %s", stage, type(error).__name__) - degradations.note("code_index", "related_source_dropped", error, health=False) + degradations.partial("code_index", "related_source_dropped", error) return None, {"partial": True, "partial_reason": f"{stage} failed"} if batch and evidence is not None: bodies = await definitions_for( @@ -1145,7 +1145,7 @@ async def _grep_neighbours( ) except Exception as e: # a failed graph read leaves the grep hits intact logger.warning("code.grep: neighbours block failed for %r", input.pattern, exc_info=True) - degradations.note("code_index", "neighbours_dropped", e, health=False) + degradations.partial("code_index", "neighbours_dropped", e) return [], False, 0, route return entries, capped, tokens, route + "+neighbours" diff --git a/server/code/app/history.py b/server/code/app/history.py index c8ca2bc23b3..e4bd46ea5df 100644 --- a/server/code/app/history.py +++ b/server/code/app/history.py @@ -216,7 +216,7 @@ async def _tracker_facts(org: str, ns: str, nums: list[int]) -> dict[int, dict[s return {} return await tracker_facts_for_numbers(org, tracker_ns, nums) except Exception as e: # noqa: BLE001 — additive - degradations.note("tracker", "history_facts_dropped", e, health=False) + degradations.partial("tracker", "history_facts_dropped", e) logger.debug("qa history enrichment skipped: %s", e) return {} diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index 99ba4b65cde..41beaf5a2d8 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -33,7 +33,11 @@ class GitError(RuntimeError): - pass + """A git call that failed; `returncode` is git's exit status when git exited.""" + + def __init__(self, message: str, returncode: int | None = None) -> None: + super().__init__(message) + self.returncode = returncode class ArgumentsTooLong(GitError): @@ -292,7 +296,8 @@ async def _git( if returncode != 0: raise GitError( f"git {' '.join(args[:3])} rc={returncode}: " - f"{_redact(err.decode('utf-8', 'replace'), token)[:500]}" + f"{_redact(err.decode('utf-8', 'replace'), token)[:500]}", + returncode, ) return out.decode("utf-8", "replace") diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 73ea0e91936..b84efc5ba76 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -631,70 +631,72 @@ async def build_for_merge( carries no such key. The author comes from the caller or the ledger's row, when the PR backfill has written it (one point read); blank otherwise.""" - from server.code.app.index import gitrepo - - if not author: - author = await _ledger_author(repo, org, ns, pr_number) - - parent = parent_sha - if not parent: - try: - parent = (await gitrepo.run(git_dir, "rev-parse", f"{merge_sha}^1")).strip() - except Exception as e: # noqa: BLE001 — blame section degrades without it - logger.info("review_brief: parent of %s unknown: %s", merge_sha[:12], e) - if changed_paths: - degradations.note("git_mirror", "diff_unread", e, health=False) - parent = "" - diff = "" - if parent: - try: - diff = await gitrepo.run(git_dir, "diff", "--no-renames", parent, merge_sha) - except Exception as e: # noqa: BLE001 — the brief still has the file list - logger.info("review_brief: diff of %s failed: %s", merge_sha[:12], e) - if changed_paths: - degradations.note("git_mirror", "diff_unread", e, health=False) - head = "" - try: - head = str(await repo.get_state(org, ns, "git_head") or "") - except Exception: # noqa: BLE001 — an unread head is blank; the brief still serves + # the brief is stored only when the reads that built it noted nothing + with degradations.unit(): + from server.code.app.index import gitrepo + + if not author: + author = await _ledger_author(repo, org, ns, pr_number) + + parent = parent_sha + if not parent: + try: + parent = (await gitrepo.run(git_dir, "rev-parse", f"{merge_sha}^1")).strip() + except Exception as e: # noqa: BLE001 — blame section degrades without it + logger.info("review_brief: parent of %s unknown: %s", merge_sha[:12], e) + if changed_paths: + degradations.partial("git_mirror", "diff_unread", e) + parent = "" + diff = "" + if parent: + try: + diff = await gitrepo.run(git_dir, "diff", "--no-renames", parent, merge_sha) + except Exception as e: # noqa: BLE001 — the brief still has the file list + logger.info("review_brief: diff of %s failed: %s", merge_sha[:12], e) + if changed_paths: + degradations.partial("git_mirror", "diff_unread", e) head = "" - inp = BriefInputs( - org=org, - ns=ns, - pr_number=int(pr_number), - merge_sha=merge_sha, - title=title, - changed_paths=list(changed_paths or []), - diff=diff, - parent_sha=parent, - indexed_commit=head, - path_prefixes=path_prefixes, - author=author, - ) - payload = await build_brief(inp, call=call, repo=repo) - if provenance: - payload["provenance"] = dict(provenance) - # A PR that changed files but whose diff could not be read (no mirror here - # yet, or a failed git call) gets a brief without its - # blame and diff sections: serve it, but leave the store to a process that - # reads the diff, or every later read would serve the degraded copy. - if store and changed_paths and not diff: - logger.info("review_brief: PR %s served unstored, its diff was not read", pr_number) - payload["stored"] = False - elif store and degradations.current(): - # A read it ran fell back: the stored copy would be served later without its - # `degraded`. - logger.info("review_brief: PR %s served unstored, a read fell back", pr_number) - payload["stored"] = False - elif store: try: - await repo.insert_rows("code_review_briefs", [brief_row(org, ns, payload)]) - except Exception as e: # noqa: BLE001 — served now, stored on a later call - logger.warning( - "review_brief: store of PR %s failed (served unstored): %s", pr_number, e - ) + head = str(await repo.get_state(org, ns, "git_head") or "") + except Exception: # noqa: BLE001 — an unread head is blank; the brief still serves + head = "" + inp = BriefInputs( + org=org, + ns=ns, + pr_number=int(pr_number), + merge_sha=merge_sha, + title=title, + changed_paths=list(changed_paths or []), + diff=diff, + parent_sha=parent, + indexed_commit=head, + path_prefixes=path_prefixes, + author=author, + ) + payload = await build_brief(inp, call=call, repo=repo) + if provenance: + payload["provenance"] = dict(provenance) + # A PR that changed files but whose diff could not be read (no mirror here + # yet, or a failed git call) gets a brief without its + # blame and diff sections: serve it, but leave the store to a process that + # reads the diff, or every later read would serve the degraded copy. + if store and changed_paths and not diff: + logger.info("review_brief: PR %s served unstored, its diff was not read", pr_number) payload["stored"] = False - return payload + elif store and degradations.current(): + # A read it ran fell back: the stored copy would be served later without its + # `degraded`. + logger.info("review_brief: PR %s served unstored, a read fell back", pr_number) + payload["stored"] = False + elif store: + try: + await repo.insert_rows("code_review_briefs", [brief_row(org, ns, payload)]) + except Exception as e: # noqa: BLE001 — served now, stored on a later call + logger.warning( + "review_brief: store of PR %s failed (served unstored): %s", pr_number, e + ) + payload["stored"] = False + return payload async def _ledger_author(repo: Any, org: str, ns: str, pr_number: int) -> str: @@ -744,55 +746,59 @@ async def build_for_open( pushed head is a miss and a rebuild; the payload says `overlay: true`, `head_sha`, `base_sha`, and its `merge_sha` is ''. A `diff` the caller sent replaces the mirror's, and git is not read.""" - from server.code.app.index import gitrepo - from server.code.app.index import pr_overlay as po - - if diff is None: - diff = "" - try: - diff = await gitrepo.run(git_dir, "diff", "--no-renames", base_sha, head_sha) - except Exception as e: # noqa: BLE001 — the brief still has the file list - logger.info("review_brief: open diff of PR %s failed: %s", pr_number, e) - if changed_paths: - degradations.note("git_mirror", "diff_unread", e, health=False) - head = "" - try: - head = str(await repo.get_state(org, ns, "git_head") or "") - except Exception: # noqa: BLE001 — an unread head is blank; the brief still serves + # the brief is stored only when the reads that built it noted nothing + with degradations.unit(): + from server.code.app.index import gitrepo + from server.code.app.index import pr_overlay as po + + if diff is None: + diff = "" + try: + diff = await gitrepo.run(git_dir, "diff", "--no-renames", base_sha, head_sha) + except Exception as e: # noqa: BLE001 — the brief still has the file list + logger.info("review_brief: open diff of PR %s failed: %s", pr_number, e) + if changed_paths: + degradations.partial("git_mirror", "diff_unread", e) head = "" - inp = BriefInputs( - org=org, - ns=ns, - pr_number=int(pr_number), - merge_sha="", - title=title, - changed_paths=list(changed_paths or []), - diff=diff, - parent_sha=base_sha, - indexed_commit=head, - path_prefixes=path_prefixes, - author=author, - ) - payload = await build_brief(inp, call=overlay_call(pr_number, call), repo=repo) - payload["overlay"] = True - payload["head_sha"] = head_sha - payload["base_sha"] = base_sha - if store and po.NOT_REACHED in str(payload.get("overlay_note") or ""): - # served, not stored: a stored partial brief would be served instead of the one - # a later request completes - logger.info("review_brief: open PR %s served unstored, its overlay is partial", pr_number) - payload["stored"] = False - elif store and degradations.current(): - logger.info("review_brief: open PR %s served unstored, a read fell back", pr_number) - payload["stored"] = False - elif store: try: - await repo.insert_rows( - "code_review_briefs", [brief_row(org, ns, {**payload, "merge_sha": head_sha})] - ) - except Exception as e: # noqa: BLE001 — served now, stored on a later call - logger.warning( - "review_brief: store of open PR %s failed (served unstored): %s", pr_number, e + head = str(await repo.get_state(org, ns, "git_head") or "") + except Exception: # noqa: BLE001 — an unread head is blank; the brief still serves + head = "" + inp = BriefInputs( + org=org, + ns=ns, + pr_number=int(pr_number), + merge_sha="", + title=title, + changed_paths=list(changed_paths or []), + diff=diff, + parent_sha=base_sha, + indexed_commit=head, + path_prefixes=path_prefixes, + author=author, + ) + payload = await build_brief(inp, call=overlay_call(pr_number, call), repo=repo) + payload["overlay"] = True + payload["head_sha"] = head_sha + payload["base_sha"] = base_sha + if store and po.NOT_REACHED in str(payload.get("overlay_note") or ""): + # served, not stored: a stored partial brief would be served instead of the one + # a later request completes + logger.info( + "review_brief: open PR %s served unstored, its overlay is partial", pr_number ) payload["stored"] = False - return payload + elif store and degradations.current(): + logger.info("review_brief: open PR %s served unstored, a read fell back", pr_number) + payload["stored"] = False + elif store: + try: + await repo.insert_rows( + "code_review_briefs", [brief_row(org, ns, {**payload, "merge_sha": head_sha})] + ) + except Exception as e: # noqa: BLE001 — served now, stored on a later call + logger.warning( + "review_brief: store of open PR %s failed (served unstored): %s", pr_number, e + ) + payload["stored"] = False + return payload diff --git a/server/code/app/index/review_brief_sources.py b/server/code/app/index/review_brief_sources.py index 68d229df0e9..817a817baf8 100644 --- a/server/code/app/index/review_brief_sources.py +++ b/server/code/app/index/review_brief_sources.py @@ -117,10 +117,18 @@ async def mirror_commit_facts( timeout_s: float = 20.0, ) -> dict[str, Any] | None: """The same facts for a merge commit named by sha (a `merge_sha`-only - read with no ledger row): None when the sha is not a commit or its - subject names no PR.""" + read with no ledger row): None when the mirror holds no such commit or its + subject names no PR. A mirror git cannot read raises.""" from server.code.app.index import gitrepo + try: + await gitrepo.run( + git_dir, "rev-parse", "--verify", "--quiet", f"{sha}^{{commit}}", timeout_s=timeout_s + ) + except gitrepo.GitError as e: + if e.returncode == 1: # read, and no such commit: a miss, not a failed mirror + return None + raise text = await gitrepo.run( git_dir, "log", diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index f5bdab1d31e..355e36c1388 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -176,12 +176,11 @@ async def _compute_repo_status( degradations.restore(hit[2]) return hit[1] # its own notes: a listing computes the other repositories' statuses alongside - with degradations.scoped(): + with degradations.unit(): # a caller without a prefetched state (code.index_status, tests' fakes) # keeps the one-argument call st = await (_repo_status(cfg, state=state) if state is not None else _repo_status(cfg)) noted = degradations.current() - degradations.restore(noted) _status_cache[key] = (time.monotonic(), st, noted) if not noted: # another process's listing would serve the row without them create_deferred_task(_publish_status_snapshot(cfg, st)) @@ -189,6 +188,8 @@ async def _compute_repo_status( async def _refresh_repo_status(cfg: Any, *, state: IndexState | None = None) -> None: + # a task of the request that served the stale entry: its notes are no part of that answer + degradations.begin() key = (cfg.org, cfg.namespace) try: await _compute_repo_status(cfg, state=state) @@ -469,7 +470,7 @@ async def _index_quality( try: candidates = await tree_producers(repo, cfg.org, cfg.namespace) except Exception as e: # noqa: BLE001 — diagnostics must not break status - degradations.note("code_index", "compiler_inference_unread", e, health=False) + degradations.partial("code_index", "compiler_inference_unread", e) logger.debug("code status: compiler inference unavailable for %s: %s", cfg.namespace, e) candidates = [] @@ -561,14 +562,18 @@ async def _worker_passes_from_ledger(days: int = 14) -> dict[str, dict[str, Any] return hit # Single-flight. A cold listing starts every repository's status together, and each would # ask this question before the first answer had landed (several identical 1.6 MB reads). + # Each waiter lists the read's notes, so no status a failed read left smaller is kept. inflight = _ledger_passes_inflight.get(cache_key) if inflight is not None: - return await asyncio.shield(inflight) - fut: asyncio.Future[dict[str, dict[str, Any]]] = asyncio.get_running_loop().create_future() + out, noted = await asyncio.shield(inflight) + degradations.restore(noted) + return out + fut: asyncio.Future[_LedgerRead] = asyncio.get_running_loop().create_future() _ledger_passes_inflight[cache_key] = fut try: - out = await _read_worker_passes(get_client(), days) - fut.set_result(out) + with degradations.unit(): + out = await _read_worker_passes(get_client(), days) + fut.set_result((out, degradations.current())) return out except BaseException as e: fut.set_exception(e) @@ -577,7 +582,9 @@ async def _worker_passes_from_ledger(days: int = 14) -> dict[str, dict[str, Any] _ledger_passes_inflight.pop(cache_key, None) -_ledger_passes_inflight: dict[str, asyncio.Future[dict[str, dict[str, Any]]]] = {} +# the passes, and the notes the read made +_LedgerRead = tuple[dict[str, dict[str, Any]], list[str]] +_ledger_passes_inflight: dict[str, asyncio.Future[_LedgerRead]] = {} async def _read_worker_passes(client: Any, days: int) -> dict[str, dict[str, Any]]: @@ -589,7 +596,7 @@ async def _read_worker_passes(client: Any, days: int) -> dict[str, dict[str, Any try: rows = await status_store.pass_summaries("code_", days, ch=client) except Exception as e: # noqa: BLE001 — the ledger is best-effort here - degradations.note("code_index", "worker_ledger_unread", e, health=False) + degradations.partial("code_index", "worker_ledger_unread", e) logger.debug("code status: worker ledger unavailable: %s", e) return {} out: dict[str, dict[str, Any]] = {} @@ -786,7 +793,7 @@ async def _table_summary_cached( n, stamp = await read(CodeRepo()) rows, at = int(n), summary_stamp(stamp) except Exception as e: # noqa: BLE001 — status stays whole when the read fails - degradations.note("code_index", f"{what.replace(' ', '_')}_summary_unread", e, health=False) + degradations.partial("code_index", f"{what.replace(' ', '_')}_summary_unread", e) logger.debug("code status: %s summary unavailable for %s: %s", what, ns, e) return rows, at # not kept: the status entry names the failure, the next one reads if key and published is None: diff --git a/server/code/app/pr_check.py b/server/code/app/pr_check.py index becb601acb1..d3b54f5363f 100644 --- a/server/code/app/pr_check.py +++ b/server/code/app/pr_check.py @@ -84,7 +84,7 @@ async def _leg(status: dict[str, Any], name: str, coro: Any) -> list[dict[str, A rows = await coro except Exception as e: # noqa: BLE001 — a slow replica, a refused read status[name] = f"unavailable: {type(e).__name__}" - degradations.note("code_index", f"{name}_leg_dropped", e, health=False) + degradations.partial("code_index", f"{name}_leg_dropped", e) return [] status[name] = len(rows) return list(rows) @@ -124,7 +124,7 @@ async def _merged_candidates( legs.setdefault(int(r["pr_number"]), set()).add("text") except Exception as e: # noqa: BLE001 — the leg reports unavailable status["merged_text"] = f"unavailable: {type(e).__name__}" - degradations.note("code_index", "merged_text_leg_dropped", e, health=False) + degradations.partial("code_index", "merged_text_leg_dropped", e) if draft.issues: for r in await _leg( status, diff --git a/server/code/app/repo_scope.py b/server/code/app/repo_scope.py index 8a5b8aafd75..fe32455d8c5 100644 --- a/server/code/app/repo_scope.py +++ b/server/code/app/repo_scope.py @@ -45,7 +45,7 @@ async def readable_repo_namespace(org: str, code_namespace: str) -> str: except RegistryUnread: return "" # unread: closed, and no gate failure worth a warning per request except Exception as e: # noqa: BLE001 — a gate that cannot check refuses - degradations.note("identity", "repo_legs_dropped", e, health=False) + degradations.partial("identity", "repo_gate_unchecked", e) # One line per scoped request while the grants read is down. log.warning("repository namespace gate failed (closed): %s", e) return "" diff --git a/server/code/app/repos.py b/server/code/app/repos.py index b1618c58bd4..434a01dca35 100644 --- a/server/code/app/repos.py +++ b/server/code/app/repos.py @@ -419,7 +419,7 @@ async def _aliases() -> list[str]: # the gate reads each grant for itself. maintained = maintained_now except Exception as err: # noqa: BLE001 — directory state is an affordance, not a gate - degradations.note("identity", "directory_state_unread", err, health=False) + degradations.partial("identity", "directory_state_unread", err) return policies, standing, roles, maintained return policies, standing, roles, maintained diff --git a/server/code/app/result_lessons.py b/server/code/app/result_lessons.py index cb1463115de..f0cfbfcfbca 100644 --- a/server/code/app/result_lessons.py +++ b/server/code/app/result_lessons.py @@ -156,7 +156,7 @@ async def scope() -> tuple[str, list[str], str, bool]: ) except Exception as e: # noqa: BLE001 — lesson enrichment must not fail the code answer logger.debug("code lessons skipped: %s", e) - degradations.note("code_lessons", "lessons_dropped", e, health=False) + degradations.partial("code_lessons", "lessons_dropped", e) return path_lessons.Lessons([]) diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 9bebde78cd1..0fed7b4aff8 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -407,7 +407,7 @@ async def _open_head(repo: CodeRepo, org: str, ns: str, pr_number: int) -> tuple head = await history_bound.pull_head(repo, org, ns, git_dir, cfg.git_branch, pr_number) except Exception as e: # noqa: BLE001 — a head the mirror or the store cannot place is missing logger.warning("code.review_brief: head of open PR %s not placed: %s", pr_number, e) - degradations.note("git_mirror", "open_head_unread", e, health=False) + degradations.partial("git_mirror", "open_head_unread", e) head = "" return head, ("" if head else po.HEAD_NOT_IN_MIRROR) @@ -468,7 +468,7 @@ async def _build_open( ) except Exception as e: # noqa: BLE001 — a miss that cannot build is a miss logger.warning("code.review_brief: open build failed for PR %s: %s", pr_number, e) - degradations.note("code.review_brief", "brief_missing", e, health=False) + degradations.partial("code.review_brief", "brief_missing", e) return None @@ -521,7 +521,7 @@ async def _build_on_miss( ) except Exception as e: # noqa: BLE001 — a miss that cannot build is a miss logger.warning("code.review_brief: on-demand build failed for PR %s: %s", pr_number, e) - degradations.note("code.review_brief", "brief_missing", e, health=False) + degradations.partial("code.review_brief", "brief_missing", e) return None, "missing" return payload, source @@ -554,5 +554,5 @@ async def _mirror_facts( merge_sha[:12], e, ) - degradations.note("git_mirror", "brief_missing", e, health=False) + degradations.partial("git_mirror", "brief_missing", e) return None diff --git a/server/code/app/search/cards.py b/server/code/app/search/cards.py index b5f1087c3f8..3d92ac848c4 100644 --- a/server/code/app/search/cards.py +++ b/server/code/app/search/cards.py @@ -228,7 +228,7 @@ async def _source_cards() -> list[dict[str, Any]]: skip_tests=True, ) except Exception as e: # noqa: BLE001 — a vote, never a gate - degradations.note("code_index", "card_leg_dropped", e, health=False) + degradations.partial("code_index", "card_leg_dropped", e) logger.warning("code.search card term read failed: %s", e) return [] diff --git a/server/code/app/search/definitions.py b/server/code/app/search/definitions.py index f2d0658c8cd..53036cf59ce 100644 --- a/server/code/app/search/definitions.py +++ b/server/code/app/search/definitions.py @@ -404,7 +404,7 @@ async def _or_nothing(lookup: str, read: Awaitable[list[dict[str, Any]]]) -> lis try: return await read except Exception as e: # noqa: BLE001 — the definitions add to an answer, never gate it - degradations.note("code_index", "definition_leg_dropped", e, health=False) + degradations.partial("code_index", "definition_leg_dropped", e) logger.warning("code.search definition leg failed (%s lookup): %s", lookup, e) return [] diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index 4b3477c7792..22391bcc190 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -51,11 +51,14 @@ async def handle_code_search(input: CodeSearchInput) -> CodeSearchOutput: """code.search. A pattern or path globs put the caller's own expression into the - scans, so such a search runs under the caller-shaped ClickHouse ceilings.""" - if not (input.pattern or input.path_globs or input.exclude_globs): - return await _code_search(input) - with caller_shaped(): - return await _code_search(input) + scans, so such a search runs under the caller-shaped ClickHouse ceilings. One run is + one unit of notes: its memo and its pool row are kept by its own notes, not by those + of the request that called it (a code.ask step, a fan-out's other namespace).""" + with degradations.unit(): + if not (input.pattern or input.path_globs or input.exclude_globs): + return await _code_search(input) + with caller_shaped(): + return await _code_search(input) async def _code_search(input: CodeSearchInput) -> CodeSearchOutput: @@ -424,7 +427,7 @@ async def _annotate_served(res: Any, prefetch: Any, *, reserve: int) -> int: return spent except Exception as e: # the units are served without their risk block logger.warning("code.search: risk annotation failed", exc_info=True) - degradations.note("code_index", "risk_unannotated", e, health=False) + degradations.partial("code_index", "risk_unannotated", e) return 0 @@ -640,7 +643,7 @@ async def _serve_search_page( ) except Exception as e: # the page is served without its risk block logger.warning("code.search page: risk annotation failed", exc_info=True) - degradations.note("code_index", "risk_unannotated", e, health=False) + degradations.partial("code_index", "risk_unannotated", e) calib = dict(payload.get("calib") or {}) route = f"{payload.get('route') or 'hybrid'}+page" diff --git a/server/code/app/search/history.py b/server/code/app/search/history.py index 60dd2930f21..a12da0e2e84 100644 --- a/server/code/app/search/history.py +++ b/server/code/app/search/history.py @@ -86,7 +86,7 @@ async def _history_leg( ) ) except Exception as e: # noqa: BLE001 — history is a vote, never a gate - degradations.note("code_index", "history_leg_dropped", e, health=False) + degradations.partial("code_index", "history_leg_dropped", e) logger.warning("code.search history leg failed: %s", e) rows = [] span_attrs(sp, results=len(rows), prs=history_stats["prs"], files=history_stats["files"]) diff --git a/server/code/app/search/lexical.py b/server/code/app/search/lexical.py index e2e4ad44d7d..702271cafdb 100644 --- a/server/code/app/search/lexical.py +++ b/server/code/app/search/lexical.py @@ -67,7 +67,7 @@ async def _lexical_leg( span_attrs(sp, results=len(rows)) except Exception as e: # noqa: BLE001 — vector-only degrade logger.warning("code.search lexical leg failed: %s", e) - degradations.note("code_index", "lexical_leg_dropped", e, health=False) + degradations.partial("code_index", "lexical_leg_dropped", e) work["lexical_leg_failed"] = 1 return [], tokens, [] return rows, lex_tokens, idfs diff --git a/server/code/app/search/symbol.py b/server/code/app/search/symbol.py index 0be23dbae84..3c3eba801f2 100644 --- a/server/code/app/search/symbol.py +++ b/server/code/app/search/symbol.py @@ -281,7 +281,7 @@ async def _fuzzy_symbol_vote( try: hit = bool(await repo.symbols_fuzzy(org, ns, bare, limit=1)) except Exception as e: # noqa: BLE001 — a vote, never a gate - degradations.note("code_index", "symbol_vote_dropped", e, health=False) + degradations.partial("code_index", "symbol_vote_dropped", e) logger.warning("code.search fuzzy-symbol vote failed: %s", e) hit = False span_attrs(sp, results=int(hit)) diff --git a/server/code/app/search/vector.py b/server/code/app/search/vector.py index 92a4172cfef..abbcd5281a3 100644 --- a/server/code/app/search/vector.py +++ b/server/code/app/search/vector.py @@ -165,7 +165,7 @@ async def _vector_leg_rows( except Exception as e: # noqa: BLE001 — lexical-only degrade logger.warning("code.search vector leg failed: %s", e) # An embedder failure is already counted by the embedder's client. - degradations.note("code_index", "vector_leg_dropped", e, health=False) + degradations.partial("code_index", "vector_leg_dropped", e) work["vector_leg_failed"] = 1 span_attrs(sp, results=len(rows)) return rows, qvec diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index b6cc7306b72..cfe508279d9 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -30,7 +30,7 @@ async def _declined_safe( return await _declined_calls_for(repo, org, ns, seeds) except Exception as e: # noqa: BLE001 logger.debug("declined-call lookup skipped: %s", e) - degradations.note("code_index", "declined_calls_uncounted", e, health=False) + degradations.partial("code_index", "declined_calls_uncounted", e) return 0, 0 @@ -49,7 +49,7 @@ async def _declined_outgoing_safe( by_path = await repo.live_call_misses_for_paths(org, ns, paths) except Exception as e: # noqa: BLE001 — a disclosure read; the walk stands logger.debug("outgoing declined-call lookup skipped: %s", e) - degradations.note("code_index", "declined_calls_uncounted", e, health=False) + degradations.partial("code_index", "declined_calls_uncounted", e) return 0, 0 unresolved = ambiguous = 0 for path, rows in by_path.items(): @@ -77,7 +77,7 @@ async def _scip_coverage( covered |= await repo.scip_covered_paths(org, ns, remaining) except Exception as e: # noqa: BLE001 logger.debug("scip coverage read skipped: %s", e) - degradations.note("code_index", "compiler_coverage_unread", e, health=False) + degradations.partial("code_index", "compiler_coverage_unread", e) return covered @@ -92,7 +92,7 @@ async def _scip_stale(repo: CodeRepo, org: str, ns: str, edges: list[Any]) -> se return await repo.scip_stale_paths(org, ns, paths) except Exception as e: # noqa: BLE001 — a freshness read must not fail the walk logger.debug("scip staleness read skipped: %s", e) - degradations.note("code_index", "compiler_freshness_unread", e, health=False) + degradations.partial("code_index", "compiler_freshness_unread", e) return set(paths) @@ -127,7 +127,7 @@ async def _unindexed_paths(repo: CodeRepo, org: str, ns: str, bare: list[str]) - return set(bare) - await repo.live_paths_present(org, ns, bare) except Exception as e: # noqa: BLE001 logger.debug("indexed-paths read skipped: %s", e) - degradations.note("code_index", "indexed_paths_unread", e, health=False) + degradations.partial("code_index", "indexed_paths_unread", e) return set(bare) @@ -178,7 +178,7 @@ async def _ctor_edge_coverage(repo: CodeRepo, org: str, ns: str) -> tuple[bool, hit, ttl = (False, False, caller_text(e)), PROBE_ERROR_TTL_S _CTOR_CACHE.put((org, ns), hit, ttl_s=ttl) if hit[2]: - degradations.note("code_index", "constructor_coverage_unread", hit[2], health=False) + degradations.partial("code_index", "constructor_coverage_unread", hit[2]) return hit[0], hit[1] diff --git a/server/code/app/symbol/dispatch.py b/server/code/app/symbol/dispatch.py index 60213d7b9e0..0584453e0fd 100644 --- a/server/code/app/symbol/dispatch.py +++ b/server/code/app/symbol/dispatch.py @@ -105,7 +105,7 @@ async def _namespace_has_override_edges(repo: CodeRepo, org: str, ns: str) -> bo hit, ttl = (False, caller_text(e)), PROBE_ERROR_TTL_S _OVR_CACHE.put((org, ns), hit, ttl_s=ttl) if hit[1]: - degradations.note("code_index", "override_coverage_unread", hit[1], health=False) + degradations.partial("code_index", "override_coverage_unread", hit[1]) return hit[0] @@ -192,7 +192,7 @@ async def _dispatch_seeds( limit=10, ) except Exception as err: # noqa: BLE001 — the walk goes on without the exact edges - degradations.note("code_index", "override_edges_unread", err, health=False) + degradations.partial("code_index", "override_edges_unread", err) ov = [] exact = False for e in ov: @@ -246,7 +246,7 @@ async def _dispatch_seeds( bases.append(b) frontier.append(str(e["to_symbol_id"])) except Exception as err: # noqa: BLE001 — hierarchy is best-effort - degradations.note("code_index", "inherited_dispatch_dropped", err, health=False) + degradations.partial("code_index", "inherited_dispatch_dropped", err) bases = [] for b in bases: for r in await repo.symbols_by_name(org, ns, f"{b}::{method}", limit=3): diff --git a/server/code/app/symbol/enclosing.py b/server/code/app/symbol/enclosing.py index 248fe34ce03..c9ec9051dad 100644 --- a/server/code/app/symbol/enclosing.py +++ b/server/code/app/symbol/enclosing.py @@ -330,7 +330,7 @@ async def _doc_sections( chunks = await repo.chunk_spans_for_paths(org, ns, paths) span_attrs(sp, rows=sum(len(v) for v in chunks.values())) except Exception as err: # A section lookup failure leaves other locations usable. - degradations.note("code_index", "sections_dropped", err, health=False) + degradations.partial("code_index", "sections_dropped", err) logger.warning("code.enclosing section read failed", exc_info=True) return {} return section_rows(chunks) diff --git a/server/code/app/symbol/enclosing_decorators.py b/server/code/app/symbol/enclosing_decorators.py index 67ac56aa58c..47b930a8465 100644 --- a/server/code/app/symbol/enclosing_decorators.py +++ b/server/code/app/symbol/enclosing_decorators.py @@ -64,9 +64,8 @@ async def extend_decorated_spans( org, ns, served_model_label(settings.embedding_model), keys, revisions=revisions ) span_attrs(span, rows=len(starts)) - except Exception as err: - # Optional ownership evidence can be absent while exact matches still work. - degradations.note("code_index", "decorator_extents_unread", err, health=False) + except Exception as err: # exact matches answer without the extents + degradations.partial("code_index", "decorator_extents_unread", err) logger.warning("code.enclosing could not read declaration extents", exc_info=True) return set() widened: set[tuple[str, str]] = set() diff --git a/server/code/app/symbol/hierarchy.py b/server/code/app/symbol/hierarchy.py index 96ab1d1f007..5c689268715 100644 --- a/server/code/app/symbol/hierarchy.py +++ b/server/code/app/symbol/hierarchy.py @@ -78,7 +78,7 @@ async def _symbol_hierarchy( return await _hierarchy_of(repo, org, ns, seeds) except Exception as e: # noqa: BLE001 — a failed side read never fails the definition logger.warning("code.symbol hierarchy read failed: %s", e) - degradations.note("code_index", "hierarchy_dropped", e, health=False) + degradations.partial("code_index", "hierarchy_dropped", e) return {} diff --git a/server/code/app/symbol/neighbours.py b/server/code/app/symbol/neighbours.py index 118407e854a..7bbe79d693e 100644 --- a/server/code/app/symbol/neighbours.py +++ b/server/code/app/symbol/neighbours.py @@ -130,7 +130,7 @@ async def _soft(coro: Any, default: Any) -> Any: return await coro except Exception as e: # noqa: BLE001 — additive block, the definitions still ship logger.debug("code neighbour/enrichment read skipped: %s", e) - degradations.note("code_index", "neighbour_block_dropped", e, health=False) + degradations.partial("code_index", "neighbour_block_dropped", e) return default diff --git a/server/code/app/symbol/outline.py b/server/code/app/symbol/outline.py index 2f056bded98..1e3a5d90428 100644 --- a/server/code/app/symbol/outline.py +++ b/server/code/app/symbol/outline.py @@ -232,7 +232,7 @@ async def _reference_head(repo: CodeRepo, org: str, ns: str, path: str) -> tuple try: rows = await repo.chunks_of_path(org, ns, path, limit=1) except Exception as e: # noqa: BLE001 - degradations.note("code_index", "reference_head_unread", e, health=False) + degradations.partial("code_index", "reference_head_unread", e) logger.debug("reference head read skipped: %s", e) return "", False if not rows: diff --git a/server/code/app/symbol/resolve.py b/server/code/app/symbol/resolve.py index 94992bb4bfb..e36a1677bbb 100644 --- a/server/code/app/symbol/resolve.py +++ b/server/code/app/symbol/resolve.py @@ -270,7 +270,7 @@ async def _file_row(repo: CodeRepo, org: str, ns: str, path: str) -> dict[str, A try: rows = await repo.live_files_for_path(org, ns, path) except Exception as e: # noqa: BLE001 - degradations.note("code_index", "file_row_unread", e, health=False) + degradations.partial("code_index", "file_row_unread", e) logger.debug("file-row read skipped: %s", e) return None return rows[0] if rows else None diff --git a/server/code/app/symbol/symbol.py b/server/code/app/symbol/symbol.py index 44b2aa02f7c..66c92fbd3c5 100644 --- a/server/code/app/symbol/symbol.py +++ b/server/code/app/symbol/symbol.py @@ -104,7 +104,7 @@ async def _symbol_neighbours( ) except Exception as e: # the definitions are served without the block logger.warning("code.symbol: neighbours block failed for %r", input.name, exc_info=True) - degradations.note("code_index", "neighbours_dropped", e, health=False) + degradations.partial("code_index", "neighbours_dropped", e) return [], 0 return entries, tokens @@ -113,10 +113,10 @@ async def _dependency_presence( input: CodeSymbolInput, org: str, ns: str ) -> tuple[list[dict[str, Any]], dict[str, list[str]]]: """When the namespace defines no such symbol and its entry names `depends_on` - namespaces, the definition's presence per dependency (the shared presence run: every - namespace authorized at VIEWER first, fail closed, one deadline). A location, a - symbol_id or an entry without dependencies asks nothing; an authorization failure - answers nothing rather than failing the miss.""" + namespaces, the definition's presence per dependency the caller may read (the shared + presence run, one deadline). Loom added those namespaces, so one the caller cannot + read is left out unnamed, as `search_fanout.readable_subset` does. A location, a + symbol_id or an entry without dependencies asks nothing.""" if input.symbol_id or not input.name or _parse_location(input.name): return [], {} from server.code.domain.index.repos import repo_for_namespace @@ -126,6 +126,7 @@ async def _dependency_presence( if not deps: return [], {} from server.code.app import presence as code_presence + from server.code.app import search_fanout as fanout def sub_for(dep: str) -> CodeSymbolInput: return input.model_copy( @@ -142,10 +143,13 @@ def sub_for(dep: str) -> CodeSymbolInput: ) try: - with code_span("symbol.dependency", seeds=len(deps)): + readable, _ = await fanout.readable_subset(org, list(deps)) + if not readable: + return [], {} + with code_span("symbol.dependency", seeds=len(readable)): rows = await code_presence.run( input, - list(deps), + readable, sub_for, handle_code_symbol, row_of=code_presence._symbol_row, @@ -153,7 +157,7 @@ def sub_for(dep: str) -> CodeSymbolInput: ) except Exception as e: # the miss is served without its dependency rows logger.info("code.symbol: dependency presence declined for %s/%s", org, ns, exc_info=True) - degradations.note("code_index", "dependency_presence_unread", e, health=False) + degradations.partial("code_index", "dependency_presence_unread", e) return [], {} return rows, code_presence.summarize(rows) @@ -259,7 +263,7 @@ async def _chunk_hashes( org, ns, [str(r.get("symbol_id") or "") for r in head], rows=head ) except Exception as err: # noqa: BLE001 — additive, never fatal - degradations.note("code_index", "body_hash_unread", err, health=False) + degradations.partial("code_index", "body_hash_unread", err) return {} diff --git a/server/code/app/symbol/verify.py b/server/code/app/symbol/verify.py index d5769278319..c42a318773a 100644 --- a/server/code/app/symbol/verify.py +++ b/server/code/app/symbol/verify.py @@ -77,7 +77,7 @@ async def _body_complete(repo: CodeRepo, org: str, ns: str, seeds: list[dict[str try: span = await repo.chunk_line_span(org, ns, path, start, end) except Exception as err: # noqa: BLE001 — an unreadable span proves nothing - degradations.note("code_index", "body_span_unread", err, health=False) + degradations.partial("code_index", "body_span_unread", err) return False return span is not None and span[0] <= start and span[1] >= end diff --git a/server/code/app/symbol_context.py b/server/code/app/symbol_context.py index 7872eb57b42..6dab3862915 100644 --- a/server/code/app/symbol_context.py +++ b/server/code/app/symbol_context.py @@ -148,7 +148,7 @@ async def context_paths( try: facts = await repo.prs_by_number(org, ns, [int(pr_number)]) except Exception as e: # noqa: BLE001 — context is a ranking aid, never fatal - degradations.note("code_index", "pr_context_unread", e, health=False) + degradations.partial("code_index", "pr_context_unread", e) logger.debug("code.symbol pr_number context read failed: %s", e) return [] row = facts.get(int(pr_number)) or {} diff --git a/server/code/app/symbol_uses.py b/server/code/app/symbol_uses.py index 34ffed7a80c..95adcec3de3 100644 --- a/server/code/app/symbol_uses.py +++ b/server/code/app/symbol_uses.py @@ -291,7 +291,7 @@ async def uses_brief( try: stats = await code_fan_in.stats_for(repo, org, ns, ids) except Exception as e: # noqa: BLE001 — the gate falls back to the read cap - degradations.note("code_index", "fan_in_dropped", e, health=False) + degradations.partial("code_index", "fan_in_dropped", e) logger.debug("code.symbol uses fan-in gate skipped: %s", e) threshold = int(settings.code_symbol_uses_hub_fan_in) fan_in = hub_fan_in(stats, ids) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index 2809858f35f..c20a856815f 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -242,6 +242,25 @@ async def collect_fixes( return fixes +async def _read_fix(cfg: Any, pr: int, runner: Any) -> tuple[Any, list[str]]: + """The fix's composed read, and the notes it made apart from the pass's.""" + from server.code.app.backport import BackportGapRequest + + with degradations.scoped(): + out = await runner( + BackportGapRequest( + org=cfg.org, + namespace=cfg.namespace, + pr_number=pr, + exact=True, + history=True, + consumer=CONSUMER, + trace=False, + ) + ) + return out, degradations.current() + + async def compute_fix( cfg: Any, pr: int, @@ -251,32 +270,25 @@ async def compute_fix( result: BackportGapsResult, stamp: datetime, version: int, + deadline: float | None = None, ) -> list[GapRow]: """One fix's composed read → its table rows; [] when the fix could not be read, its tracker record did not answer, or a read it fell back on left a smaller answer (a night of unknowns must not overwrite verdicts), counted on - the result either way.""" - from server.code.app.backport import BackportGapRequest - + the result either way. A read that fell back is retried once while the pass is + before `deadline` (on the monotonic clock; None: no bound).""" try: - with degradations.scoped(): - out = await runner( - BackportGapRequest( - org=cfg.org, - namespace=cfg.namespace, - pr_number=pr, - exact=True, - history=True, - consumer=CONSUMER, - trace=False, - ) - ) - noted = degradations.current() + out, noted = await _read_fix(cfg, pr, runner) + if noted and (deadline is None or time.monotonic() < deadline): + logger.info("code_backport_gaps: #%s fell back (%s), read again", pr, "; ".join(noted)) + out, noted = await _read_fix(cfg, pr, runner) except Exception as e: # noqa: BLE001 — one fix must not end the pass result.fixes_unavailable += 1 note_failure(e, f"code_backport_gaps:#{pr}") logger.info("code_backport_gaps: #%s failed: %s", pr, e) return [] + if noted: + logger.info("code_backport_gaps: #%s not written, it fell back: %s", pr, "; ".join(noted)) if ( noted or bool(getattr(out, "tracker_unavailable", False)) @@ -341,6 +353,7 @@ async def refresh_namespace( result=result, stamp=stamp, version=version, + deadline=started + budget, ) ) if len(batch) >= INSERT_EVERY * max(1, len(sibs)): diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index d434e8bdd2b..1fc249a97d9 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -168,9 +168,9 @@ class OpsIncidentsInput(BaseModel): """Whether Loom is degraded now, from its checks, providers, workers and calls. It lists failing readiness checks, providers and workers, and the share of the org's - calls that failed on the server; a token narrowed to some namespaces or pinned to one - user reads no call counts. Identity is optional: the org is the token's (role check - only; no namespace is addressed).""" + calls that failed on the server, which only a caller that reads the org whole (an + org admin over `*`, a platform admin) reads. Identity is optional: the org is the + token's (role check only; no namespace is addressed).""" org: str = "" diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 2d0d23f0fca..8aaf22f058e 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -73,7 +73,7 @@ async def _cached( incidents, failure = [], caller_text(e) hit = _cache[key] = (time.monotonic(), incidents, failure) if hit[2]: - degradations.note("ops.incidents", f"{source}_unread", hit[2], health=False) + degradations.partial("ops.incidents", f"{source}_unread", hit[2]) return hit[1] @@ -151,18 +151,29 @@ async def _workers() -> list[OpsIncident]: return out -def _reads_org_calls() -> bool: - """Whether the caller may read the org's call counts: a token over every namespace - of its org that reads whole namespaces, since the rollup keeps no namespace or user; - with auth off, the install's caller. Fails closed: a token narrowed to some - namespaces or pinned to one user, or no token where one is required, reads none.""" - from server.auth.context import current_auth +async def _reads_org_calls(org: str) -> bool: + """Whether the caller may read `org`'s call counts. The rollup keeps no namespace or + user, so only a caller that reads the org whole does (`reads_every_namespace`, the + org-wide rollups' rule), reading whole namespaces, with no restricted namespace + hidden from it; with auth off, the install's caller. Fails closed: a member, a + narrowed or pinned token, an unknown restricted set, or no token where one is + required, reads none.""" + from server.auth.context import ( + current_auth, + reads_every_namespace, + restricted_namespaces_hidden_from, + ) from server.identity.app.request_scope import request_narrowed auth = current_auth() if auth is None: return not settings.auth_actually_required() - return "*" in auth.namespaces and not request_narrowed() + if not reads_every_namespace(auth, org) or request_narrowed(): + return False + hidden = await restricted_namespaces_hidden_from(org) + if hidden == ["*"]: # the restricted set is unread + degradations.partial("ops.incidents", "requests_unread", "ClassificationUnavailable") + return not hidden async def _requests(org: str, minutes: int) -> list[OpsIncident]: @@ -198,7 +209,7 @@ async def handle_ops_incidents(input: OpsIncidentsInput) -> OpsIncidentsOutput: # read the whole org's counts: no request incidents. requests = ( _cached("requests", org, lambda: _requests(org, minutes)) - if org and org != "*" and _reads_org_calls() + if org and org != "*" and await _reads_org_calls(org) else _no_incidents() ) ready, workers, calls = await asyncio.gather( diff --git a/server/memory/app/ask/completion.py b/server/memory/app/ask/completion.py index ac0751a7ae0..10f66b0a731 100644 --- a/server/memory/app/ask/completion.py +++ b/server/memory/app/ask/completion.py @@ -386,7 +386,7 @@ async def _once() -> list[dict[str, Any]]: try: return await _call_retrying_empty_block(_once, leg=leg) except Exception as e: # noqa: BLE001 — additive, never fatal: fail open to no rows - degradations.note("memory.ask", f"{leg.replace(' ', '_')}_dropped", e, health=False) + degradations.partial("memory.ask", f"{leg.replace(' ', '_')}_dropped", e) logger.debug("%s failed: %s", leg, e) return None diff --git a/server/memory/app/ask/context_blocks.py b/server/memory/app/ask/context_blocks.py index 809dd5b347a..2b52b442e73 100644 --- a/server/memory/app/ask/context_blocks.py +++ b/server/memory/app/ask/context_blocks.py @@ -118,7 +118,7 @@ async def knowledge_passages( except LostCorpus: raise except Exception as err: # noqa: BLE001 — an unavailable additive plane contributes no passages - degradations.note("memory.ask", "knowledge_dropped", err, health=False) + degradations.partial("memory.ask", "knowledge_dropped", err) logger.warning("knowledge plane on ask unavailable") return AskKnowledge() diff --git a/server/memory/app/ask/handler.py b/server/memory/app/ask/handler.py index a8df0cab19a..7364f470f80 100644 --- a/server/memory/app/ask/handler.py +++ b/server/memory/app/ask/handler.py @@ -20,6 +20,7 @@ from server.memory.api.models_common import run_next_hint from server.memory.api.models_search import MemorySearchInput from server.memory.app import after_write +from server.observability import degradations if TYPE_CHECKING: from server.memory.app.ask.result import MemoryAskResult @@ -230,14 +231,17 @@ async def handle_memory_ask(input: MemoryAskInput) -> MemoryAskOutput: input = input.model_copy(deep=True) if input.allow_synthesis: refuse_synthesis("memory.ask", "allow_synthesis=false") - prepared = await prepare_knowledge( - input, - input.query, - enabled=input.knowledge, - corpus=(input.allow_synthesis and input.as_of is None and is_corpus_task(input.query)), - ) - with prepared.scope(): - return await _handle_prepared_ask(input, prepared) + # One unit of notes: whether the answer becomes a precedent is judged by the notes + # of the reads that built it, not by those the request made before the handler. + with degradations.unit(): + prepared = await prepare_knowledge( + input, + input.query, + enabled=input.knowledge, + corpus=(input.allow_synthesis and input.as_of is None and is_corpus_task(input.query)), + ) + with prepared.scope(): + return await _handle_prepared_ask(input, prepared) async def _handle_prepared_ask( @@ -286,7 +290,7 @@ async def _handle_prepared_ask( scratchpad = await render_run_blocks(input.org, input.namespace, rid) - pending = await _pending_extraction(input) if prepared.plan.marked else None + pending, pending_noted = await _pending_beside(input) if prepared.plan.marked else (None, []) res = await ask( search_input, question=input.query, @@ -320,6 +324,7 @@ async def _handle_prepared_ask( default_answer_chars=input.default_answer_chars, prepared_knowledge=prepared, ) + degradations.restore(pending_noted) if not prepared.plan.marked: _schedule_cited_used(input, res) @@ -500,6 +505,14 @@ async def search(top_k: int) -> list[Any]: return None +async def _pending_beside(input: MemoryAskInput) -> tuple[int, list[str]]: + """The pending count and its notes, kept apart: the count is no part of the answer + `ask` judges as a precedent, so the caller lists its notes after `ask`.""" + with degradations.scoped(): + pending = await _pending_extraction(input) + return pending, degradations.current() + + async def _pending_extraction(input: MemoryAskInput) -> int: """Deferred batches in flight for the asked scope; 0 on any failure — disclosure must never fail an answer.""" diff --git a/server/memory/app/ask/identifiers.py b/server/memory/app/ask/identifiers.py index 50d53dc4be7..ebde9e042db 100644 --- a/server/memory/app/ask/identifiers.py +++ b/server/memory/app/ask/identifiers.py @@ -151,7 +151,7 @@ async def _mention_window_chunks(search_input: Any, question: str, ranked: list[ user_id=getattr(search_input, "user_id", None), ) except Exception as e: # noqa: BLE001 — additive, never fatal - degradations.note("memory.ask", "mention_window_dropped", e, health=False) + degradations.partial("memory.ask", "mention_window_dropped", e) logger.debug("mention-window chunks skipped: %s", e) return [] @@ -474,7 +474,7 @@ async def _read_decisive_chunks( markers=list(_DECISIVE_MARKERS), ) except Exception as e: # noqa: BLE001 — additive - degradations.note("memory.ask", "decisive_chunks_dropped", e, health=False) + degradations.partial("memory.ask", "decisive_chunks_dropped", e) logger.debug("decisive chunk injection failed: %s", e) return [] @@ -522,7 +522,7 @@ async def _read_latest_word( order="recency", ) except Exception as e: # noqa: BLE001 — additive - degradations.note("memory.ask", "latest_word_dropped", e, health=False) + degradations.partial("memory.ask", "latest_word_dropped", e) logger.debug("recent identifier injection failed: %s", e) return rows @@ -555,7 +555,7 @@ async def _inject_identifier_memories( if q: qvec = list(await get_embedder().embed(q)) except Exception as err: # noqa: BLE001 — relevance ranking is best-effort - degradations.note("embedder", "identifier_ranking_dropped", err, health=False) + degradations.partial("embedder", "identifier_ranking_dropped", err) qvec = [] # A fresh namespace's rows may sit on a replica this query has not seen # yet (SharedMergeTree): the main leg read with sequential @@ -628,7 +628,7 @@ async def _inject_identifier_memories( search_input, idents, case_insensitive, _lim_settings ) except Exception as e: # noqa: BLE001 — additive, never fatal - degradations.note("memory.ask", "identifier_rows_dropped", e, health=False) + degradations.partial("memory.ask", "identifier_rows_dropped", e) logger.debug("identifier injection failed: %s", e) return [] diff --git a/server/memory/app/ask/reader.py b/server/memory/app/ask/reader.py index 8674ab0bf24..85ba3494c1c 100644 --- a/server/memory/app/ask/reader.py +++ b/server/memory/app/ask/reader.py @@ -162,7 +162,7 @@ async def _trusted_in_pool(search_input: Any, memories: list[Any]) -> list[Any]: params={**params, "keys": keys}, ) except Exception as e: # noqa: BLE001 — a trust read never blocks an answer - degradations.note("memory.ask", "trust_unread", e, health=False) + degradations.partial("memory.ask", "trust_unread", e) logger.warning("memory.ask trusted-row read failed (open): %s", e) return [] return trusted_rows([dict(r) for r in rows], keys) diff --git a/server/memory/app/ask/records.py b/server/memory/app/ask/records.py index 0cde10c48f4..c84edddc6d7 100644 --- a/server/memory/app/ask/records.py +++ b/server/memory/app/ask/records.py @@ -88,11 +88,11 @@ async def _gh_items_fallback_answer( try: prs = await repo.prs_by_number(code_org, code_ns, numbers) except Exception as e: # noqa: BLE001 — items alone still answer - degradations.note("memory.ask", "pr_history_dropped", e, health=False) + degradations.partial("memory.ask", "pr_history_dropped", e) logger.warning("memory.ask pr-history fallback failed (open): %s", e) prs = {} except Exception as e: # noqa: BLE001 — the fallback never blocks an abstention - degradations.note("memory.ask", "items_fallback_dropped", e, health=False) + degradations.partial("memory.ask", "items_fallback_dropped", e) logger.warning("memory.ask gh-items fallback failed (open): %s", e) return None as_of = getattr(search_input, "as_of", None) diff --git a/server/memory/app/ask/supersession.py b/server/memory/app/ask/supersession.py index 9397d86d227..bdc31ba55a2 100644 --- a/server/memory/app/ask/supersession.py +++ b/server/memory/app/ask/supersession.py @@ -118,7 +118,7 @@ async def superseded_rows_for_pool( params={**params, "keys": keys, "lim": int(limit)}, ) except Exception as e: # noqa: BLE001 — a mask read never blocks an answer - degradations.note("memory.ask", "supersession_unchecked", e, health=False) + degradations.partial("memory.ask", "supersession_unchecked", e) logger.warning("memory.ask superseded-row read failed (open): %s", e) return [] from types import SimpleNamespace diff --git a/server/memory/app/ask_when_evidence.py b/server/memory/app/ask_when_evidence.py index 10051d72db8..b648415d952 100644 --- a/server/memory/app/ask_when_evidence.py +++ b/server/memory/app/ask_when_evidence.py @@ -216,7 +216,7 @@ async def _recall_turns(kwargs: dict[str, Any]) -> list[DatedTurn]: out = await handle_memory_recall(MemoryRecallInput(**kwargs)) except Exception as e: # noqa: BLE001 — the first answer stands when recall fails - degradations.note("memory.ask", "dated_turns_dropped", e, health=False) + degradations.partial("memory.ask", "dated_turns_dropped", e) log.warning("ask when-evidence recall failed (open): %s", e) return [] turns: list[DatedTurn] = [] diff --git a/server/memory/app/code_grounding.py b/server/memory/app/code_grounding.py index 1b835921b91..bab4825a78d 100644 --- a/server/memory/app/code_grounding.py +++ b/server/memory/app/code_grounding.py @@ -84,7 +84,7 @@ async def _authorized_code_target(search_input: Any, settings: Any) -> tuple[str ) return ("", "") except Exception as e: # noqa: BLE001 — fail closed: no target - degradations.note("memory.ask", "code_grounding_dropped", e, health=False) + degradations.partial("memory.ask", "code_grounding_dropped", e) logger.debug("code grounding authorization failed: %s", e) return ("", "") try: @@ -237,7 +237,7 @@ async def _symbol(sym: str) -> Any | None: ) ) except Exception as err: # noqa: BLE001 — additive - degradations.note("memory.ask", "code_symbol_dropped", err, health=False) + degradations.partial("memory.ask", "code_symbol_dropped", err) return None async def _search() -> Any | None: @@ -254,7 +254,7 @@ async def _search() -> Any | None: ) ) except Exception as e: # noqa: BLE001 — additive, never fatal - degradations.note("memory.ask", "code_search_dropped", e, health=False) + degradations.partial("memory.ask", "code_search_dropped", e) _warn_once("code-context search fallback failed: %s", e) return None @@ -419,7 +419,7 @@ async def _inject_pr_facts( repo = code_index() facts = await repo.prs_by_number(code_org, code_ns, numbers) except Exception as e: # noqa: BLE001 — additive, never fatal - degradations.note("memory.ask", "pr_facts_dropped", e, health=False) + degradations.partial("memory.ask", "pr_facts_dropped", e) _warn_once("pr-fact grounding failed: %s", e) return [] as_of = getattr(search_input, "as_of", None) @@ -532,7 +532,7 @@ async def _gate_future_prs( repo = code_index() facts = await repo.prs_by_number(code_org, code_ns, numbers) except Exception as e: # noqa: BLE001 — additive, never fatal - degradations.note("memory.ask", "pr_temporal_gate_skipped", e, health=False) + degradations.partial("memory.ask", "pr_temporal_gate_skipped", e) logger.debug("pr-temporal gate lookup failed: %s", e) return memories # PRs whose open date is known AND strictly after the anchor = didn't exist. @@ -554,7 +554,7 @@ async def _gate_future_prs( try: items = await repo.items_by_number(code_org, code_ns, rest, within_head=False) except Exception as e: # noqa: BLE001 — absent table or row: never gated - degradations.note("memory.ask", "pr_temporal_gate_skipped", e, health=False) + degradations.partial("memory.ask", "pr_temporal_gate_skipped", e) logger.debug("gh-items temporal lookup failed: %s", e) items = {} for num, row in items.items(): @@ -598,7 +598,7 @@ async def _annotate_stale_code_memories(memories: list[Any], search_input: Any) cns = {a["code_namespace"] for v in read for a in v} seen = await readable_namespaces(str(search_input.org), cns) except Exception as e: # noqa: BLE001 — grounding is advisory - degradations.note("memory.ask", "code_staleness_unchecked", e, health=False) + degradations.partial("memory.ask", "code_staleness_unchecked", e) _warn_once("code staleness: links unreadable: %s", e) return None for i, v in zip(unread, read, strict=True): diff --git a/server/memory/app/code_link_reads.py b/server/memory/app/code_link_reads.py index e01ee8b8d63..7411cf4b738 100644 --- a/server/memory/app/code_link_reads.py +++ b/server/memory/app/code_link_reads.py @@ -175,7 +175,7 @@ async def links_of(org: str, memory: dict[str, Any]) -> list[CodeLink]: rows = current(org, memory, await store.for_memories(org, [str(memory["mid"])])) seen = await readable_namespaces(org, {a["code_namespace"] for a in rows}) except Exception as e: # noqa: BLE001 — the links are additive to the read - degradations.note("memory.get", "code_links_dropped", e, health=False) + degradations.partial("memory.get", "code_links_dropped", e) log.debug("code links unavailable: %s", e) return [] return [ @@ -320,7 +320,7 @@ async def annotate_hits(input: Any, hits: list[Any]) -> None: try: memories, seen, policies = await _annotation_reads(input, hits) except Exception as e: # noqa: BLE001 — the links are additive to the read - degradations.note("memory.search", "code_links_unread", e, health=False) + degradations.partial("memory.search", "code_links_unread", e) log.debug("code links unavailable: %s", e) for h in hits: if unlinked(h): diff --git a/server/memory/app/context_pack.py b/server/memory/app/context_pack.py index a7a7644b358..c8259126330 100644 --- a/server/memory/app/context_pack.py +++ b/server/memory/app/context_pack.py @@ -422,7 +422,7 @@ def _vtext(v: Any) -> str: pinned = await memory_repo.list_by_namespace(ident, pinned_only=True, limit=k, **shape) recent = await memory_repo.list_by_namespace(ident, limit=k * 2, **shape) except Exception as e: # noqa: BLE001 — recall is best-effort - degradations.note("context.pack", "startup_recall_dropped", e, health=False) + degradations.partial("context.pack", "startup_recall_dropped", e) log.warning("context.pack startup recall failed: %s", e) return @@ -555,7 +555,7 @@ async def _hit_actors(input: ContextPackInput, hits: list[Any]) -> _KeyWriters: scope=request_scope(), ) except Exception as e: # noqa: BLE001 — authorship labels are best-effort; lines say by=unknown - degradations.note("context.pack", "authors_unknown", e, health=False) + degradations.partial("context.pack", "authors_unknown", e) log.warning("context.pack: memory authors unavailable: %s", e) return {} @@ -1052,7 +1052,7 @@ async def _optional_section(name: str, work: Awaitable[Any]) -> Any: try: return await work except Exception as error: # noqa: BLE001 — a failed optional section leaves other sections available - degradations.note("context.pack", f"{name}_dropped", error, health=False) + degradations.partial("context.pack", f"{name}_dropped", error) log.warning("context.pack: section %s failed: %s", name, error) return None @@ -1373,7 +1373,7 @@ async def run_checked_pack(input: ContextPackInput) -> CheckedPack: ) scopes.update(request.namespaces) except Exception as err: # noqa: BLE001 — scope failure omits only the optional direct knowledge section - degradations.note("context.pack", "knowledge_scope_dropped", err, health=False) + degradations.partial("context.pack", "knowledge_scope_dropped", err) log.warning("context.pack: knowledge scope unavailable") if input.include_knowledge and st.wanted("memory_stack"): scopes.add(input.namespace) diff --git a/server/memory/app/deep_evidence.py b/server/memory/app/deep_evidence.py index 6cd57210160..06fccc3041e 100644 --- a/server/memory/app/deep_evidence.py +++ b/server/memory/app/deep_evidence.py @@ -301,7 +301,7 @@ async def fetch_raw_evidence( else [] ) except Exception as e: # noqa: BLE001 — fail-open, keep the excerpt answer - degradations.note("memory.ask", "raw_evidence_dropped", e, health=False) + degradations.partial("memory.ask", "raw_evidence_dropped", e) log.warning("deep-evidence fetch failed (fail-open): %s", e) return [] rows = join_links_to_evidence(links, evidence) diff --git a/server/memory/app/entity_resolution.py b/server/memory/app/entity_resolution.py index 9173ddc2c26..e2eb73aeaed 100644 --- a/server/memory/app/entity_resolution.py +++ b/server/memory/app/entity_resolution.py @@ -569,7 +569,7 @@ async def lookup_canonical_entities( except VectorInputTooLargeError: raise except Exception as err: # noqa: BLE001 — a failed alias read keeps the given entities - degradations.note("memory.search", "entity_aliases_dropped", err, health=False) + degradations.partial("memory.search", "entity_aliases_dropped", err) return ordered # A full sentinel page cannot prove that omitted aliases fit the bound. if len(rows) > _MAX_EFFECTIVE_ENTITY_FILTER: diff --git a/server/memory/app/facts.py b/server/memory/app/facts.py index b6a976d9e6c..5582bc75875 100644 --- a/server/memory/app/facts.py +++ b/server/memory/app/facts.py @@ -379,12 +379,14 @@ async def walk(self, input: FactsTraverseInput) -> FactsTraverseOutput: return hit[2].model_copy(deep=True) window = timedelta(seconds=float(settings.ch_read_your_writes_window_s)) settling = wrote is not None and started - wrote < window - if settling and read_your_writes_enabled() and not sequential_reads_active(): - with sequential_reads(): + with degradations.unit(): + if settling and read_your_writes_enabled() and not sequential_reads_active(): + with sequential_reads(): + out = await _handle_facts_traverse_uncached(input) + else: out = await _handle_facts_traverse_uncached(input) - else: - out = await _handle_facts_traverse_uncached(input) - if settling or degradations.current(): # a walk a read left smaller is not kept + whole = not degradations.current() # a walk a read left smaller is not kept + if settling or not whole: return out if len(self.cache) > 512: self.cache.clear() @@ -583,7 +585,7 @@ async def _hubs( _HUB_DEGREE_SQL, params={"org": org, "ns": namespace, "ents": missing} ) except Exception as e: # noqa: BLE001 — the policy is additive - degradations.note("facts.traverse", "hub_policy_off", e, health=False) + degradations.partial("facts.traverse", "hub_policy_off", e) log.warning("facts.traverse: hub degree lookup failed (open): %s", e) rows = [] degree_of.update({str(r["entity"]): int(r["d"] or 0) for r in rows}) @@ -737,7 +739,7 @@ async def _colour_by_community( n.community_id = assignment.get(n.entity) return assignment.get(seed) except Exception as e: # noqa: BLE001 — communities are additive - degradations.note("facts.traverse", "communities_dropped", e, health=False) + degradations.partial("facts.traverse", "communities_dropped", e) log.debug("facts.traverse: community lookup skipped: %s", e) return None diff --git a/server/memory/app/for_file.py b/server/memory/app/for_file.py index e953f8d8466..889583ce1d8 100644 --- a/server/memory/app/for_file.py +++ b/server/memory/app/for_file.py @@ -784,7 +784,7 @@ async def _linked( links = await current_links(input.org, links) seen = await readable_namespaces(input.org, {a["code_namespace"] for a in links}) except Exception as e: # noqa: BLE001 — the links are additive; the files match stands - degradations.note("memory.for_file", "code_links_dropped", e, health=False) + degradations.partial("memory.for_file", "code_links_dropped", e) log.debug("memory.for_file: code links skipped: %s", e) return None out: dict[str, list[LinkRow]] = defaultdict(list) @@ -904,10 +904,11 @@ async def _own_rows(input: MemoryForFileInput, path: str) -> list[dict[str, Any] return None try: return await asyncio.wait_for(_read_own(input, path, tags), _OWN_ROWS_SECONDS) - except TimeoutError: + except TimeoutError as e: + degradations.partial("memory.for_file", "other_namespaces_dropped", e) log.debug("memory.for_file: the caller's other namespaces ran past their bound") except Exception as e: # noqa: BLE001 — additive; the request's own namespaces stand - degradations.note("memory.for_file", "other_namespaces_dropped", e, health=False) + degradations.partial("memory.for_file", "other_namespaces_dropped", e) log.warning("memory.for_file: the caller's other namespaces skipped: %r", e) return [] diff --git a/server/memory/app/loom_search/repo_decisions.py b/server/memory/app/loom_search/repo_decisions.py index 41434f9cbb5..b784c15d816 100644 --- a/server/memory/app/loom_search/repo_decisions.py +++ b/server/memory/app/loom_search/repo_decisions.py @@ -79,7 +79,7 @@ async def search_repo_decisions( except VectorInputTooLargeError: raise except Exception as e: # noqa: BLE001 — an additive leg never fails the caller - degradations.note("loom_search", "repo_decisions_dropped", e, health=False) + degradations.partial("loom_search", "repo_decisions_dropped", e) log.info( "repo decisions search on %s/%s did not answer: %s", mem_input.org, repo_namespace, e ) diff --git a/server/memory/app/loom_search/tracker_leg.py b/server/memory/app/loom_search/tracker_leg.py index 47a0e636260..811148c7a7c 100644 --- a/server/memory/app/loom_search/tracker_leg.py +++ b/server/memory/app/loom_search/tracker_leg.py @@ -204,7 +204,7 @@ async def prepare_tracker_search( namespaces = await readable_tracker_namespaces(org, "", [], cap) return TrackerSearchPlan(org, tuple(namespaces), deadline, cap) if namespaces else None except Exception as e: # noqa: BLE001 — fail open: the memory legs answer - degradations.note("loom_search", "tracker_dropped", e, health=False) + degradations.partial("loom_search", "tracker_dropped", e) logger.info("loom_search tracker discovery skipped on %s: %s", org, type(e).__name__) return None @@ -226,7 +226,7 @@ async def tracker_leg( return None return lean_tracker_section(out, defect_report_shape(query) or {}) except Exception as e: # noqa: BLE001 — fail open: the memory legs answer - degradations.note("loom_search", "tracker_dropped", e, health=False) + degradations.partial("loom_search", "tracker_dropped", e) logger.info("loom_search tracker leg skipped on %s: %s", plan.org, type(e).__name__) return None diff --git a/server/memory/app/namespace_health.py b/server/memory/app/namespace_health.py index 6abe1971088..397ad25016b 100644 --- a/server/memory/app/namespace_health.py +++ b/server/memory/app/namespace_health.py @@ -157,7 +157,7 @@ async def namespace_health( hit = _cache[key] if hit[2]: # every pack served from the remembered failure says so - degradations.note("context.pack", "namespace_health_dropped", hit[2], health=False) + degradations.partial("context.pack", "namespace_health_dropped", hit[2]) return hit[1] diff --git a/server/memory/app/namespace_types.py b/server/memory/app/namespace_types.py index cfacebdd663..88c1ba7edeb 100644 --- a/server/memory/app/namespace_types.py +++ b/server/memory/app/namespace_types.py @@ -92,7 +92,7 @@ async def list_type_configs( params={"org": org, "ns": namespace}, ) except Exception as e: # noqa: BLE001 — a failed type list reads as no types - degradations.note("namespace", "type_registry_unread", e, health=False) + degradations.partial("namespace", "type_registry_unread", e) log.warning("namespace_types list failed: %s", e) return [] return [ diff --git a/server/memory/app/pending_disclosure.py b/server/memory/app/pending_disclosure.py index 63ebba2b8c4..3a0191481c2 100644 --- a/server/memory/app/pending_disclosure.py +++ b/server/memory/app/pending_disclosure.py @@ -57,7 +57,7 @@ async def pending_extraction( _cache.clear() hit = _cache[key] = (now + settings.memory_pending_disclosure_ttl_s, n, failure) if hit[2]: - degradations.note("memory", "pending_count_unread", hit[2], health=False) + degradations.partial("memory", "pending_count_unread", hit[2]) return hit[1] diff --git a/server/memory/app/pending_evidence.py b/server/memory/app/pending_evidence.py index 187d97ae936..4026ad8d602 100644 --- a/server/memory/app/pending_evidence.py +++ b/server/memory/app/pending_evidence.py @@ -196,7 +196,7 @@ async def pending_evidence_for( turns = rank_pending_turns(question, batches, max_turns=max_turns) return pending_hits(turns, namespace=namespace) except Exception as e: # noqa: BLE001 — pending evidence never fails an answer - degradations.note("memory.ask", "pending_evidence_dropped", e, health=False) + degradations.partial("memory.ask", "pending_evidence_dropped", e) log.debug("pending evidence read failed (fail-open): %s", e) return [] diff --git a/server/memory/app/procedure.py b/server/memory/app/procedure.py index d509a61c830..3d19e8ee4bb 100644 --- a/server/memory/app/procedure.py +++ b/server/memory/app/procedure.py @@ -177,8 +177,8 @@ async def _goal_similarities( try: goal_vec = await get_embedder().embed(goal) key_vecs = await _load_key_embeddings(org, keys_by_ns) - except Exception as err: - degradations.note("procedure.match", "goal_axis_dropped", err, health=False) + except Exception as err: # the match runs on the situation axis alone + degradations.partial("procedure.match", "goal_axis_dropped", err) log.warning( "procedure.match: goal axis unavailable, matching on situation only", exc_info=True ) diff --git a/server/memory/app/profile_search.py b/server/memory/app/profile_search.py index 99885a40df7..de35eedf1fe 100644 --- a/server/memory/app/profile_search.py +++ b/server/memory/app/profile_search.py @@ -228,7 +228,7 @@ async def _similarities( try: qv = await embedder.embed(query) except Exception as e: # noqa: BLE001 — the leg degrades to lexical, never fails the search - degradations.note("embedder", "profile_vector_dropped", e, health=False) + degradations.partial("embedder", "profile_vector_dropped", e) log.debug("profile leg: query embed failed: %s", e) return {} by_ident = {_ident(r): r for r in rows} @@ -291,7 +291,7 @@ async def _score_unvectored( try: vecs = await embedder.embed_many(texts) except Exception as e: # noqa: BLE001 — the word rule still answers - degradations.note("embedder", "profile_vector_dropped", e, health=False) + degradations.partial("embedder", "profile_vector_dropped", e) log.debug("profile leg: on-the-fly embed failed: %s", e) return {} out: dict[Ident, float] = {} diff --git a/server/memory/app/proposals_ops.py b/server/memory/app/proposals_ops.py index ed84c83d950..1a1e92e90d7 100644 --- a/server/memory/app/proposals_ops.py +++ b/server/memory/app/proposals_ops.py @@ -144,7 +144,7 @@ async def _usage_counts( params={"org": org, "ns": namespace, "ids": memory_ids}, ) except Exception as e: # noqa: BLE001 — proposals list without usage - degradations.note("memory.proposals", "usage_unread", e, health=False) + degradations.partial("memory.proposals", "usage_unread", e) log.warning("memory.proposals: usage counts unreadable for %s: %s", namespace, e) return {} return {str(r["mid"]): (int(r.get("used") or 0), int(r.get("harm") or 0)) for r in rows} diff --git a/server/memory/app/query.py b/server/memory/app/query.py index 1e4c7c5c107..7ddd9fe5fd3 100644 --- a/server/memory/app/query.py +++ b/server/memory/app/query.py @@ -788,7 +788,7 @@ async def _canonical_keys_for_rows(org: str, namespace: str, rows: list[Any]) -> try: by_id = await canonical_keys_for(org, namespace, list(dups.values())) except Exception as e: # noqa: BLE001 — rows return without canonicals - degradations.note("memory.get", "canonical_unread", e, health=False) + degradations.partial("memory.get", "canonical_unread", e) log.warning("memory.get: canonical lookup failed: %s", e) by_id = {} return {k: by_id.get(cid, "") for k, cid in dups.items()} diff --git a/server/memory/app/retrieval/chunks.py b/server/memory/app/retrieval/chunks.py index 3e7f5e13eeb..58bb27abab2 100644 --- a/server/memory/app/retrieval/chunks.py +++ b/server/memory/app/retrieval/chunks.py @@ -718,8 +718,8 @@ async def _search_memory_chunks( try: stage1_sql = _chunk_candidates_sql(chunk_agent_pred) candidates = await _chunk_query(ch, stage1_sql, stage1_params) - except Exception as err: - degradations.note("memory.search", "chunk_leg_dropped", err, health=False) + except Exception as err: # the fact leg answers without the chunk plane + degradations.partial("memory.search", "chunk_leg_dropped", err) log.exception( "chunk plane query failed; degrading to fact-only retrieval " "(namespace=%s entity_filter=%s stage=candidates)", @@ -787,8 +787,8 @@ async def _search_memory_chunks( ) try: rows = await _chunk_query(ch, sql, chunk_params) - except Exception as err: - degradations.note("memory.search", "chunk_leg_dropped", err, health=False) + except Exception as err: # the fact leg answers without the chunk plane + degradations.partial("memory.search", "chunk_leg_dropped", err) # Degrade to fact-only retrieval rather than 500'ing the query, but # log it — a silently-disabled chunk plane must leave a trace. log.exception( diff --git a/server/memory/app/retrieval/derived.py b/server/memory/app/retrieval/derived.py index 32dead646ef..c0d5fc7c076 100644 --- a/server/memory/app/retrieval/derived.py +++ b/server/memory/app/retrieval/derived.py @@ -188,7 +188,7 @@ async def fetch_derived_aggregate( agg = agg_rows[0] item_rows = await ch.query_all(items_sql, params=params) except Exception as e: # noqa: BLE001 — the aggregate leg is additive; fail open - degradations.note("memory.search", "aggregate_dropped", e, health=False) + degradations.partial("memory.search", "aggregate_dropped", e) log.warning("fetch_derived_aggregate failed (fail-open): %s", e) return None @@ -291,7 +291,7 @@ async def _resolve_operand_event_date( }, ) except Exception as e: # noqa: BLE001 — a failed operand read means no date answer - degradations.note("memory.search", "temporal_diff_dropped", e, health=False) + degradations.partial("memory.search", "temporal_diff_dropped", e) log.warning("_resolve_operand_event_date failed (fail-open): %s", e) return None if not rows: @@ -416,7 +416,7 @@ async def fetch_current_state_observation( try: rows = await ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — the current-state leg is additive; fail open - degradations.note("memory.search", "current_state_leg_dropped", e, health=False) + degradations.partial("memory.search", "current_state_leg_dropped", e) log.warning("fetch_current_state_observation failed (fail-open): %s", e) return [] if not rows: @@ -545,7 +545,7 @@ async def fetch_temporal_diff( params={"a": earlier, "b": later}, ) except Exception as e: # noqa: BLE001 — a failed date diff means no temporal answer - degradations.note("memory.search", "temporal_diff_dropped", e, health=False) + degradations.partial("memory.search", "temporal_diff_dropped", e) log.warning("fetch_temporal_diff failed (fail-open): %s", e) return None if not rows: diff --git a/server/memory/app/retrieval/pool.py b/server/memory/app/retrieval/pool.py index 36a88385fb9..0abb2490e9f 100644 --- a/server/memory/app/retrieval/pool.py +++ b/server/memory/app/retrieval/pool.py @@ -86,7 +86,7 @@ async def _recency_backfill( try: rows = await ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — an additive leg fails open - degradations.note("memory.search", "recency_backfill_dropped", e, health=False) + degradations.partial("memory.search", "recency_backfill_dropped", e) log.warning("recency backfill failed (fail-open): %s", e) return hits floor = min((float(h.rank_score or 0.0) for h in hits), default=0.0) @@ -297,7 +297,7 @@ async def _set_chunk_rows( ) values = await _row_values(ch, q, served) except Exception as e: # noqa: BLE001 — naming a chunk's row never fails a search - degradations.note("memory.search", "set_chunks_dropped", e, health=False) + degradations.partial("memory.search", "set_chunks_dropped", e) log.warning("set chunk rows read failed; this pool's set chunks are dropped: %s", e) return {} by_writer: dict[tuple[str, str, str], list[ChunkId]] = {} diff --git a/server/memory/app/retrieval/side_legs.py b/server/memory/app/retrieval/side_legs.py index eb12a11fb42..74151f3281b 100644 --- a/server/memory/app/retrieval/side_legs.py +++ b/server/memory/app/retrieval/side_legs.py @@ -139,7 +139,7 @@ async def _lexical_recall_fallback( lambda: ch.query_all(sql, params=params), leg="lexical" ) except Exception as e: # noqa: BLE001 — the lexical fallback leg is additive; fail open - degradations.note("memory.search", "lexical_leg_dropped", e, health=False) + degradations.partial("memory.search", "lexical_leg_dropped", e) log.warning("_lexical_recall_fallback failed (fail-open): %s", e) return [] @@ -370,7 +370,7 @@ async def _search_memory_records( lambda: ch.query_all(sql, params=params), leg="records" ) except Exception as e: # noqa: BLE001 — the records leg is additive; fail open - degradations.note("memory.search", "records_leg_dropped", e, health=False) + degradations.partial("memory.search", "records_leg_dropped", e) log.warning("_search_memory_records failed (fail-open): %s", e) return [] @@ -470,7 +470,7 @@ async def _fetch_unmatched_candidates( try: rows = await ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — the unmatched-candidate leg is additive; fail open - degradations.note("memory.search", "unmatched_leg_dropped", e, health=False) + degradations.partial("memory.search", "unmatched_leg_dropped", e) log.warning("_fetch_unmatched_candidates failed (fail-open): %s", e) return [] diff --git a/server/memory/app/retrieval/summaries.py b/server/memory/app/retrieval/summaries.py index e1484059aee..c550ca1987b 100644 --- a/server/memory/app/retrieval/summaries.py +++ b/server/memory/app/retrieval/summaries.py @@ -195,7 +195,7 @@ async def fetch_session_summaries( ch, rows, org=org, namespace=namespace, as_of=as_of, as_of_basis=as_of_basis ) except Exception as e: # noqa: BLE001 — the session-summary leg is additive; fail open - degradations.note("memory.search", "session_summary_leg_dropped", e, health=False) + degradations.partial("memory.search", "session_summary_leg_dropped", e) log.warning("fetch_session_summaries failed (fail-open): %s", e) return [] # A stored vector does not establish that the digest passes the sensitivity check. @@ -350,7 +350,7 @@ async def fetch_entity_summaries( try: rows = await ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — the entity-summary leg is additive; fail open - degradations.note("memory.search", "entity_summary_leg_dropped", e, health=False) + degradations.partial("memory.search", "entity_summary_leg_dropped", e) log.warning("fetch_entity_summaries failed (fail-open): %s", e) return [] out: list[SearchHit] = [] diff --git a/server/memory/app/runs_manifest.py b/server/memory/app/runs_manifest.py index c25916f2d67..7a3183791ab 100644 --- a/server/memory/app/runs_manifest.py +++ b/server/memory/app/runs_manifest.py @@ -235,7 +235,7 @@ async def runs_manifest( ch, org=org, namespace=namespace, agent=agent, user_id=user_id, limit=limit ) except Exception as e: # noqa: BLE001 — additive section, never fails the pack - degradations.note("context.pack", "runs_manifest_dropped", e, health=False) + degradations.partial("context.pack", "runs_manifest_dropped", e) log.warning("context.pack runs manifest skipped: %s", e) return "", 0 if not rows: diff --git a/server/memory/app/search/anchor_pool.py b/server/memory/app/search/anchor_pool.py index 5dd936dbe3c..b38b6a8a76f 100644 --- a/server/memory/app/search/anchor_pool.py +++ b/server/memory/app/search/anchor_pool.py @@ -121,7 +121,7 @@ async def _anchor_rows_for_ns(ns: str) -> tuple[str, list[dict[str, Any]]]: try: return ns, await _ch_a.query_all(anchor_sql, params=params) except Exception as e: # noqa: BLE001 — one namespace's anchor pool failure must not fail search - degradations.note("memory.search", "anchor_pool_dropped", e, health=False) + degradations.partial("memory.search", "anchor_pool_dropped", e) log.warning("anchor pool fetch failed for ns=%s (non-fatal): %s", ns, e) return ns, [] diff --git a/server/memory/app/search/computed.py b/server/memory/app/search/computed.py index 6c84e64d2a1..cae2b1d8508 100644 --- a/server/memory/app/search/computed.py +++ b/server/memory/app/search/computed.py @@ -92,7 +92,7 @@ async def _exp(v: str | None) -> list[str] | None: except VectorInputTooLargeError: raise except Exception as e: # noqa: BLE001 - degradations.note("memory.search", "aggregate_unexpanded", e, health=False) + degradations.partial("memory.search", "aggregate_unexpanded", e) log.warning("derived canonical expand failed (non-fatal): %s", e) return None diff --git a/server/memory/app/search/digest_descent.py b/server/memory/app/search/digest_descent.py index f9fefe96ccb..4803e36541e 100644 --- a/server/memory/app/search/digest_descent.py +++ b/server/memory/app/search/digest_descent.py @@ -98,7 +98,7 @@ async def _rows(ns: str, sid: str) -> tuple[str, str, list[dict[str, Any]]]: try: return ns, sid, await _ch.query_all(sql, params=params) except Exception as e: # noqa: BLE001 — additive arm - degradations.note("memory.search", "digest_descent_dropped", e, health=False) + degradations.partial("memory.search", "digest_descent_dropped", e) log.warning("digest descent failed for %s/%s (non-fatal): %s", ns, sid, e) return ns, sid, [] diff --git a/server/memory/app/search/key_match.py b/server/memory/app/search/key_match.py index d5542b76bce..20cc2e602d8 100644 --- a/server/memory/app/search/key_match.py +++ b/server/memory/app/search/key_match.py @@ -338,7 +338,7 @@ async def _rows_for_ns(ns: str) -> tuple[str, list[dict[str, Any]], bool]: try: return ns, await _ch.query_all(sql, params=params), False except Exception as e: # noqa: BLE001 — additive arm - degradations.note("memory.search", "key_match_dropped", e, health=False) + degradations.partial("memory.search", "key_match_dropped", e) log.warning("key-match arm failed for ns=%s (non-fatal): %s", ns, e) return ns, [], False diff --git a/server/memory/app/search/output.py b/server/memory/app/search/output.py index 31a81ea0b03..602bbd5da62 100644 --- a/server/memory/app/search/output.py +++ b/server/memory/app/search/output.py @@ -248,7 +248,7 @@ async def _readable_namespaces(org: str, namespace: str, payload: dict[str, Any] try: mine = (await resolve_fanout(org)).namespaces except Exception as e: # noqa: BLE001 — unresolved, the page narrows to the addressed namespace - _degradations.note("memory.search", "page_narrowed", e, health=False) + _degradations.partial("memory.search", "page_narrowed", e) log.warning("parked page: fan-out unresolved for %s/%s: %s", org, namespace, e) return authorized return (named & set(mine)) | authorized @@ -557,7 +557,7 @@ async def _attach_scratchpad(input: Any, output: Any) -> None: max_chars=int(_s.memory_scratchpad_max_chars), ) except Exception as e: # noqa: BLE001 — a missing note must not fail a search - _degradations.note("memory.search", "scratchpad_unread", e, health=False) + _degradations.partial("memory.search", "scratchpad_unread", e) log.debug("scratchpad load skipped: %s", e) return if blocks is None: diff --git a/server/memory/app/search/payload.py b/server/memory/app/search/payload.py index 2f60d520a5a..aadd51c4e54 100644 --- a/server/memory/app/search/payload.py +++ b/server/memory/app/search/payload.py @@ -170,7 +170,7 @@ async def _fill_hit_usage(hits: list[Any], input: Any, namespaces: list[str] | N prev = folded_by_key.get((ns, key), 0) folded_by_key[(ns, key)] = max(prev, int(count)) except Exception as e: # noqa: BLE001 — counters are additive, never a failure - degradations.note("memory.search", "usage_unread", e, health=False) + degradations.partial("memory.search", "usage_unread", e) log.warning("memory.search: include_usage read failed: %s", e) return 0 filled = 0 @@ -504,7 +504,7 @@ async def _expand_source_bodies( by_key[k], spans[k] = linked_eid, span break except Exception as e: # noqa: BLE001 — a body read never fails a search - degradations.note("memory.search", "source_bodies_unread", e, health=False) + degradations.partial("memory.search", "source_bodies_unread", e) log.debug("source bodies read failed: %s", e) return (0, 0) budget = int(getattr(input, "body_budget_tokens", 4000) or 4000) diff --git a/server/memory/app/search/shared_definitions.py b/server/memory/app/search/shared_definitions.py index e243b50e5fb..90f6d4c4ab7 100644 --- a/server/memory/app/search/shared_definitions.py +++ b/server/memory/app/search/shared_definitions.py @@ -63,7 +63,7 @@ async def withheld_definition_flags(org: str, namespace: str, hits: list[Any]) - ) # Once per request: a parked page's refill window reads its sources again. if not any(d.startswith(_WITHHELD) for d in degradations.current()): - degradations.note(_PROVIDER, _EFFECT, e, health=False) + degradations.partial(_PROVIDER, _EFFECT, e) return [w is not None for w in wanted] served = { (ns, head.memory_key) diff --git a/server/memory/app/search/supplemental.py b/server/memory/app/search/supplemental.py index f8ecba78291..40104ef58f4 100644 --- a/server/memory/app/search/supplemental.py +++ b/server/memory/app/search/supplemental.py @@ -34,7 +34,7 @@ async def _supplemental_leg( ctx.actual_work["embedding_calls"] = int(ctx.actual_work["embedding_calls"]) + 1 sub_vec = await ctx.embedder.embed(sub_q) except Exception as err: # noqa: BLE001 — a failed sub-query embed drops only that sub-query - degradations.note("embedder", "sub_query_dropped", err, health=False) + degradations.partial("embedder", "sub_query_dropped", err) return [] ctx.actual_work["vector_queries"] = int(ctx.actual_work["vector_queries"]) + len(ctx.namespaces) sub_per_ns = await asyncio.gather( @@ -98,7 +98,7 @@ async def _run_set_expansion(ctx: SearchContext) -> None: *[_supplemental_leg(ctx, ph, leg_top_k, seen_keys) for ph in phrases] ) except Exception as e: # noqa: BLE001 — additive legs - degradations.note("memory.search", "set_expansion_dropped", e, health=False) + degradations.partial("memory.search", "set_expansion_dropped", e) log.warning("set expansion legs failed (non-fatal): %s", e) return # A phrase names the question's entity; a row that answers it does too. diff --git a/server/memory/app/search/tiers.py b/server/memory/app/search/tiers.py index 016c652d38a..38e1a553ea7 100644 --- a/server/memory/app/search/tiers.py +++ b/server/memory/app/search/tiers.py @@ -89,7 +89,7 @@ async def _prepend_tier( exclude_high_sensitivity=True, ) except Exception as e: # noqa: BLE001 — a tier never fails a search - degradations.note("memory.search", f"{tier}_dropped", e, health=False) + degradations.partial("memory.search", f"{tier}_dropped", e) log.debug("%s tier read failed: %s", tier, e) return hits, 0 if run_id: @@ -127,7 +127,7 @@ async def _prepend_tier( except Exception as e: # noqa: BLE001 — a tier never fails a search # Its rows are left out, none of them checked; the response says so. log.warning("%s tier check failed: %s", tier, error_summary(e)) - degradations.note("memory.search", f"{tier}_unchecked", error_summary(e), health=False) + degradations.partial("memory.search", f"{tier}_unchecked", error_summary(e)) return hits, 0 # the tiers join after the pool's code annotation: theirs is read here from server.memory.app.code_link_reads import annotate_hits diff --git a/server/memory/app/search_llm.py b/server/memory/app/search_llm.py index b34fb100317..a294201fa5a 100644 --- a/server/memory/app/search_llm.py +++ b/server/memory/app/search_llm.py @@ -55,10 +55,8 @@ async def judge_results_iteratively( ), timeout=timeout_s, ) - except TimeoutError: - return True, "" - except Exception as err: # noqa: BLE001 — a failed judge call counts as answered - degradations.note("llm", "judge_skipped", err, health=False) + except Exception as err: # noqa: BLE001 — a failed or timed-out judge counts as answered + degradations.partial("llm", "judge_skipped", err) return True, "" raw = strip_code_fence(result.text) try: @@ -102,7 +100,8 @@ async def extract_derived_intent_llm( ), timeout=timeout_s, ) - except (TimeoutError, Exception): # noqa: BLE001 — a failed intent call means no derived intent + except Exception as err: # noqa: BLE001 — a failed or timed-out intent call: no derived intent + degradations.partial("llm", "derived_intent_dropped", err) return None raw = strip_code_fence(result.text) @@ -205,7 +204,7 @@ async def extract_query_triples_llm( _QUERY_ENTITY_CACHE[key] = [list(t) for t in out] return out except Exception as err: # noqa: BLE001 — a failed entity extraction means no query entities - degradations.note("llm", "query_entities_dropped", err, health=False) + degradations.partial("llm", "query_entities_dropped", err) return [] @@ -276,5 +275,5 @@ async def expand_verb_synonyms( _VERB_SYNONYM_CACHE[key] = out return out except Exception as err: # noqa: BLE001 — a failed synonym call keeps the verb alone - degradations.note("llm", "verb_synonyms_dropped", err, health=False) + degradations.partial("llm", "verb_synonyms_dropped", err) return [canon] diff --git a/server/memory/app/served_superseded.py b/server/memory/app/served_superseded.py index b608a425b85..6603ac3fb7d 100644 --- a/server/memory/app/served_superseded.py +++ b/server/memory/app/served_superseded.py @@ -103,7 +103,7 @@ async def annotate_pool_superseded(ctx: Any) -> None: input.org, [hit_row_key(h, ns_default) for h in old], scope=scope ) except Exception as e: # noqa: BLE001 — naming the successor never fails a search - degradations.note("memory.search", "successor_unread", e, health=False) + degradations.partial("memory.search", "successor_unread", e) log.warning("memory.search: superseded successor read failed: %s", e) return by_row = {record_row_key(r): r for r in rows} diff --git a/server/memory/app/stack_knowledge.py b/server/memory/app/stack_knowledge.py index 7faad06a3b0..fe8dc118e99 100644 --- a/server/memory/app/stack_knowledge.py +++ b/server/memory/app/stack_knowledge.py @@ -108,7 +108,7 @@ async def collect_pass(width: int, fallback: list[ChunkHit]) -> None: wider = await ordinary(width) await collect_pass(width, wider) except Exception as err: # noqa: BLE001 — a wider ordinary failure must preserve the usable first pass - degradations.note("memory.stack", "knowledge_short", err, health=False) + degradations.partial("memory.stack", "knowledge_short", err) wider = None pools = await passes.finish() mixed = [[ranked.chunk for ranked in pool] for pool in pools] diff --git a/server/memory/app/working_memory.py b/server/memory/app/working_memory.py index 95f1a5026e7..0d357f2212c 100644 --- a/server/memory/app/working_memory.py +++ b/server/memory/app/working_memory.py @@ -338,7 +338,7 @@ async def render_run_blocks( try: rows = await run_rows(ch, org, namespace, run_id, limit=limit) except Exception as e: # noqa: BLE001 — a scratchpad read never blocks an answer - degradations.note("memory.ask", "run_scratchpad_unread", e, health=False) + degradations.partial("memory.ask", "run_scratchpad_unread", e) log.warning("working_memory: run block read failed (open): %s", e) return "" parts = [ diff --git a/server/memory/store/lifecycle.py b/server/memory/store/lifecycle.py index 108219f4058..0ec2355b051 100644 --- a/server/memory/store/lifecycle.py +++ b/server/memory/store/lifecycle.py @@ -1086,9 +1086,7 @@ async def _tombstone_ch_heads( try: await on_page([{c: r[c] for c in _ANNOUNCED} for r in won]) except Exception as e: # noqa: BLE001 — committed tombstones survive a webhook failure - degradations.note( - "memory.webhook", "not_announced", error_summary(e), health=False - ) + degradations.partial("memory.webhook", "not_announced", error_summary(e)) vectors += await reemit_embedding_rows_for_keys( [ (identity_key(r), {"tombstoned_at": params["at"], "version": int(r["version"])}) @@ -1219,7 +1217,7 @@ async def _tombstone_heads( try: await on_tombstoned([{c: r[c] for c in _ANNOUNCED} for r in committed.rows]) except Exception as e: # noqa: BLE001 — the rows are tombstoned; the clear must not fail - degradations.note("memory.webhook", "not_announced", error_summary(e), health=False) + degradations.partial("memory.webhook", "not_announced", error_summary(e)) vectors += await retire_vectors_for_keys( [(identity_key(r), int(r["version"])) for r in committed.rows], ch=ch ) diff --git a/server/observability/degradations.py b/server/observability/degradations.py index 024b0674669..8904f3b58fa 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -13,11 +13,16 @@ transport binds a fresh list per op next to the cost accumulator, so notes never leak across requests. Bounded (each entry once, at most `_MAX_NOTES`), never raises, and a note also feeds `provider_health` so the /v1/health flag agrees with -the responses. A note passes `health=False` in two cases: +the responses. `partial(provider, effect, reason)` notes without feeding it, in two +cases: - the fallback belongs to no provider (a store read or a handler's own step); - a provider failed, and its own client already recorded the failure. +An answer kept for a later call (a memo, a stored brief) is built inside `unit()`, and +kept only when the unit's own notes are empty: an earlier note of the request is not +the answer's. + degraded: ["classify: caller_type_kept (HTTPStatusError)", "rerank: input_order_kept (ReadTimeout)"] """ @@ -59,6 +64,20 @@ def scoped() -> Iterator[None]: _notes.reset(token) +@contextmanager +def unit() -> Iterator[None]: + """As `scoped`, and the block's notes are then listed in the caller's too: inside + it `current()` reads only the answer the block builds, which a cache keeps only + when that is empty, and the response still names every note.""" + token = _notes.set([]) + try: + yield + finally: + own = _notes.get() or [] + _notes.reset(token) + restore(own) + + def note(provider: str, effect: str, reason: object = "", *, health: bool = True) -> None: """Record that `provider` fell back to `effect` because of `reason`. @@ -99,6 +118,12 @@ def note(provider: str, effect: str, reason: object = "", *, health: bool = True log.debug("degradations.note failed", exc_info=True) +def partial(provider: str, effect: str, reason: object = "") -> None: + """`note` for a fallback that is no provider's failure to count, or one its own + client already counted: a store read, a handler's step, a failed provider call.""" + note(provider, effect, reason, health=False) + + def current() -> list[str]: """The notes recorded so far in this request (a copy).""" lst = _notes.get() @@ -137,4 +162,4 @@ def on_response(body: Any) -> Any: return {k: v for k, v in body.items() if k != "degraded"} if "degraded" in body else body -__all__ = ["begin", "current", "note", "on_response", "restore", "scoped"] +__all__ = ["begin", "current", "note", "on_response", "partial", "restore", "scoped", "unit"] diff --git a/server/workers/supervisor.py b/server/workers/supervisor.py index 8ea5beb4aac..925c09ca2fb 100644 --- a/server/workers/supervisor.py +++ b/server/workers/supervisor.py @@ -526,13 +526,15 @@ def first_pass_delay(spec: WorkerSpec) -> float: def _begin_pass_accounting() -> Any: - """Bind a fresh cost accumulator to this worker task (fail-quiet), and - the ClickHouse work bag (statements, read bytes, elapsed) - the pass's store row reads.""" + """Bind a fresh cost accumulator to this worker task (fail-quiet), the + ClickHouse work bag (statements, read bytes, elapsed) the pass's store row + reads, and an empty list of degradation notes: no pass reads the last one's.""" try: from server.core import request_work + from server.observability import degradations request_work.begin() + degradations.begin() except Exception: # noqa: BLE001 — accounting never breaks the loop pass try: diff --git a/tests/unit/test_code_answer_completeness.py b/tests/unit/test_code_answer_completeness.py index b7301cd3664..d1aed0caff8 100644 --- a/tests/unit/test_code_answer_completeness.py +++ b/tests/unit/test_code_answer_completeness.py @@ -206,7 +206,7 @@ async def not_gone(*args: Any, **kwargs: Any) -> bool: ctx = SimpleNamespace(index_head="h" * 40) degradations.begin() - degradations.note("code_lessons", "lessons_dropped", "DatabaseError", health=False) + degradations.partial("code_index", "lexical_leg_dropped", "DatabaseError") await answers_cache._remember(ctx, result, None) assert stored == [] degradations.begin() diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index 5342a2d7979..820a4e13a0a 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -1379,29 +1379,72 @@ async def _ls_fails(gd, *args, timeout_s): @pytest.mark.asyncio -async def test_a_fix_whose_read_fell_back_writes_nothing() -> None: - """A branch's ledger read that failed can flip its verdict: the fix keeps last - night's rows, as for a tracker miss, and the pass's own notes hold none of it.""" +async def test_a_fix_whose_read_fell_back_writes_nothing(caplog) -> None: + """A branch's ledger read that failed can flip its verdict: the fix is read once + more, and when that falls back too it keeps last night's rows, as for a tracker + miss, the log names the notes and the pass's own notes hold none of them.""" + import logging from types import SimpleNamespace from server.observability import degradations + calls: list[int] = [] + async def _runner(req): - degradations.note( - "code_index", "backport_ledger_dropped", ConnectionError("x"), health=False - ) + calls.append(req.pr_number) + degradations.partial("code_index", "backport_ledger_dropped", ConnectionError("x")) return _out(req.pr_number) degradations.begin() result = wk.BackportGapsResult() - rows = await wk.compute_fix( - SimpleNamespace(org="acme", namespace=NS), - 7, - {}, - runner=_runner, - result=result, - stamp=NOW, - version=1, - ) + with caplog.at_level(logging.INFO, logger=wk.logger.name): + rows = await wk.compute_fix( + SimpleNamespace(org="acme", namespace=NS), + 7, + {}, + runner=_runner, + result=result, + stamp=NOW, + version=1, + ) assert rows == [] and result.fixes_unavailable == 1 and result.fixes_computed == 0 + assert calls == [7, 7] + assert "backport_ledger_dropped (ConnectionError)" in caplog.text assert degradations.current() == [] + + +async def test_a_fix_that_fell_back_is_read_again_only_within_the_pass_budget() -> None: + """A fallback is often a timed-out leg: the second read that answers whole writes + the fix's rows; a pass already past its budget does not read it again.""" + import time + from types import SimpleNamespace + + from server.observability import degradations + + calls: list[int] = [] + + async def _once(req): + calls.append(req.pr_number) + if len(calls) == 1: + degradations.partial("code_index", "backport_ledger_dropped", ConnectionError("x")) + return _out(req.pr_number) + + async def _fix(deadline): + result = wk.BackportGapsResult() + rows = await wk.compute_fix( + SimpleNamespace(org="acme", namespace=NS), + 7, + {}, + runner=_once, + result=result, + stamp=NOW, + version=1, + deadline=deadline, + ) + return rows, result + + rows, result = await _fix(time.monotonic() + 60) + assert calls == [7, 7] and rows and result.fixes_computed == 1 + calls.clear() + rows, result = await _fix(time.monotonic() - 1) + assert calls == [7] and rows == [] and result.fixes_unavailable == 1 diff --git a/tests/unit/test_code_read_degradations.py b/tests/unit/test_code_read_degradations.py index e6d236c95db..e8f80ce0a4a 100644 --- a/tests/unit/test_code_read_degradations.py +++ b/tests/unit/test_code_read_degradations.py @@ -163,7 +163,7 @@ async def no_retrieval(*_: Any, **__: Any) -> Any: top_similarity=0.5, score_explanation="", ) - degradations.note("code_index", "vector_leg_dropped", "DatabaseError", health=False) + degradations.partial("code_index", "vector_leg_dropped", "DatabaseError") cursor = handler._issue_search_cursor( request, "o", diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 6ca57eaa1c7..955f4c780ce 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -202,6 +202,14 @@ async def counting_run(gd: str, *args: str, **kw: Any) -> str: # the root has no ^1; the error propagates to the handler's catch with pytest.raises(gitrepo.GitError): await review_brief_sources.mirror_commit_facts(git_dir, root) + # a sha the mirror does not hold, full or short, is a miss and no failure to note + for absent in ("0123456789abcdef0123456789abcdef01234567", "abc1234"): + assert await review_brief_sources.mirror_commit_facts(git_dir, absent) is None + # a directory git cannot read is a failed mirror, which raises + not_a_repo = Path(git_dir).parent / "not-a-repo" + not_a_repo.mkdir() + with pytest.raises(gitrepo.GitError): + await review_brief_sources.mirror_commit_facts(str(not_a_repo), sha7) @pytest.mark.asyncio diff --git a/tests/unit/test_code_search_pick.py b/tests/unit/test_code_search_pick.py index 62bed2f93f0..13a2a4c1101 100644 --- a/tests/unit/test_code_search_pick.py +++ b/tests/unit/test_code_search_pick.py @@ -373,7 +373,7 @@ async def thresholds(org: str, ns: str) -> tuple[float, float, float]: if noted: from server.observability import degradations - degradations.note("code_index", "lexical_leg_dropped", "DatabaseError", health=False) + degradations.partial("code_index", "lexical_leg_dropped", "DatabaseError") return 0.30, 0.22, 0.62 async def cap(org: str, ns: str, **k: Any) -> bool: @@ -484,3 +484,28 @@ def test_only_code_search_takes_the_pick_and_an_empty_confidence_is_off_the_wire assert "pick_confidence" not in CodeSearchOutput(results=[], route="hybrid").model_dump() served = CodeSearchOutput(results=[], route="hybrid", pick_confidence="medium") assert served.model_dump()["pick_confidence"] == "medium" + + +def test_a_search_is_kept_by_its_own_notes_not_by_its_requests_earlier_ones( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A note the request made before the search ran (a code.ask step, a fan-out's other + namespace) leaves the search's own answer whole: it is memoized, its pool row lists + none of it, and the response still names it. A note of its own keeps it out.""" + from server.code.app import search_cursor as paging + from server.observability import degradations + + pools: list[Any] = [] + monkeypatch.setattr(paging, "enabled", lambda: True) + monkeypatch.setattr(paging, "encode", lambda **k: "cursor") + monkeypatch.setattr(paging, "put_pool", lambda o, n, k, payload, **kw: pools.append(payload)) + earlier = "rerank: input_order_kept (x)" + for own in (False, True): + degradations.begin() + degradations.partial("rerank", "input_order_kept", "x") + out, puts = _handle(monkeypatch, _picks(2, 1), noted=own) + mine = ["code_index: lexical_leg_dropped (DatabaseError)"] if own else [] + assert len(puts) == (0 if own else 1) + assert [p["degraded"] for p in pools] == [mine] and out["next_cursor"] == "cursor" + assert degradations.current() == [earlier, *mine] + pools.clear() diff --git a/tests/unit/test_code_symbol_dependency.py b/tests/unit/test_code_symbol_dependency.py index 04de4766911..718cd8cebd5 100644 --- a/tests/unit/test_code_symbol_dependency.py +++ b/tests/unit/test_code_symbol_dependency.py @@ -1,7 +1,7 @@ """A name the repository does not define is looked for in the -namespaces its entry depends on — presence rows under the caller's own -authorization; nothing asked for a location, a symbol_id or an entry without -dependencies; an authorization failure answers nothing, not an error.""" +namespaces its entry depends on — presence rows for the ones the caller may read; +nothing asked for a location, a symbol_id or an entry without dependencies; one the +caller cannot read is left out unnamed; a failed run answers nothing, not an error.""" from __future__ import annotations @@ -12,6 +12,7 @@ from server.code.api.models_symbol import CodeSymbolInput from server.code.app.symbol import symbol as h +from server.observability import degradations def _cfgs(deps: tuple[str, ...]) -> list[Any]: @@ -21,9 +22,14 @@ def _cfgs(deps: tuple[str, ...]) -> list[Any]: ] -def _run(name: str, *, deps=("code-weave",), rows=None, fail=False, symbol_id=""): +def _run(name: str, *, deps=("code-weave",), rows=None, fail=False, symbol_id="", refused=()): calls: list[Any] = [] + async def fake_readable(org, namespaces): + return [n for n in namespaces if n not in refused], [ + {"namespace": n, "reason": "not_readable"} for n in namespaces if n in refused + ] + async def fake_run(inp, namespaces, sub_for, single, *, row_of, op): calls.append((list(namespaces), op, sub_for(namespaces[0]).namespace)) if fail: @@ -53,7 +59,9 @@ def fake_summarize(rs): patch("server.code.domain.index.repos.configured_repos", return_value=_cfgs(deps)), patch("server.code.app.presence.run", new=fake_run), patch("server.code.app.presence.summarize", new=fake_summarize), + patch("server.code.app.search_fanout.readable_subset", new=fake_readable), ): + degradations.begin() out = asyncio.run(h._dependency_presence(inp, "clickhouse", "code-lumen")) return out, calls @@ -73,8 +81,20 @@ def test_nothing_is_asked_without_dependencies_a_location_or_an_id() -> None: assert _run("weave::x", symbol_id="abc") == (([], {}), []) -def test_the_entry_itself_is_never_a_dependency_and_authz_failure_answers_nothing() -> None: +def test_the_entry_itself_is_never_a_dependency_and_a_failed_run_answers_nothing() -> None: (rows, summary), calls = _run("weave::x", deps=("code-lumen", "code-weave")) assert calls[0][0] == ["code-weave"], "the namespace does not depend on itself" (rows, summary), calls = _run("weave::x", fail=True) assert (rows, summary) == ([], {}) and len(calls) == 1 + assert degradations.current() == ["code_index: dependency_presence_unread (PermissionError)"] + + +def test_a_dependency_the_caller_cannot_read_is_a_miss_that_names_nothing() -> None: + """Loom added the dependency, so a refusal is no degradation of the caller's answer, + and `degraded` must not name a namespace the caller cannot read.""" + out, calls = _run("weave::x", refused=("code-weave",)) + assert out == ([], {}) and calls == [] + assert degradations.current() == [] + out, calls = _run("weave::x", deps=("code-weave", "code-secret"), refused=("code-secret",)) + assert calls[0][0] == ["code-weave"] + assert not any("code-secret" in n for n in degradations.current()) diff --git a/tests/unit/test_degradations.py b/tests/unit/test_degradations.py index 46cdcbbf049..0e39ef3ab43 100644 --- a/tests/unit/test_degradations.py +++ b/tests/unit/test_degradations.py @@ -45,9 +45,9 @@ def test_a_repeated_note_is_listed_once_and_the_cap_counts_distinct_notes(): reads, record the same entry: it is listed once and takes one place of the eight.""" D.begin() for _ in range(10): - D.note("code_index", "declined_calls_uncounted", ConnectionError("x"), health=False) + D.partial("code_index", "declined_calls_uncounted", ConnectionError("x")) for i in range(7): - D.note("p", f"e{i}", health=False) + D.partial("p", f"e{i}") assert D.current()[0] == "code_index: declined_calls_uncounted (ConnectionError)" assert len(D.current()) == 8 and len(set(D.current())) == 8 assert D.current()[-1] == "p: e6" @@ -61,6 +61,23 @@ def test_notes_feed_provider_health(): ), st +def test_a_partial_note_leaves_provider_health_alone(): + D.partial("code_index", "lexical_leg_dropped", ConnectionError("x")) + assert D.current() == ["code_index: lexical_leg_dropped (ConnectionError)"] + assert "code_index" not in (provider_health.status().get("providers") or {}) + + +def test_a_unit_reads_only_its_own_notes_and_the_request_still_names_them(): + """A cache inside a unit keeps an answer only when the unit noted nothing; a note + the request made before it does not stop that, and the response lists both.""" + D.partial("rerank", "input_order_kept", "x") + with D.unit(): + assert D.current() == [] + D.partial("code_index", "fan_in_dropped", "y") + assert D.current() == ["code_index: fan_in_dropped (y)"] + assert D.current() == ["rerank: input_order_kept (x)", "code_index: fan_in_dropped (y)"] + + @pytest.mark.asyncio async def test_requests_are_isolated_by_contextvar(): D.begin() @@ -200,8 +217,8 @@ def test_on_response_puts_the_requests_notes_after_the_ops_own_each_once(): D.begin() assert D.on_response({"found": True}) == {"found": True} # nothing degraded: no key assert D.on_response({"found": True, "degraded": []}) == {"found": True} - D.note("rerank", "input_order_kept", "x", health=False) - D.note("code_index", "risk_unannotated", "y", health=False) + D.partial("rerank", "input_order_kept", "x") + D.partial("code_index", "risk_unannotated", "y") body = {"version": 1, "degraded": ["rerank: input_order_kept (x)"]} assert D.on_response(body)["degraded"] == [ "rerank: input_order_kept (x)", @@ -223,7 +240,7 @@ def test_every_op_response_carries_the_requests_notes_on_both_transports(): assert "degraded" not in response_body(op, {}, MemoryGetOutput(found=False)) assert "degraded" not in mcp_op_result("memory.get", {"found": False}, {}, None) - D.note("memory.webhook", "not_announced", "z", health=False) + D.partial("memory.webhook", "not_announced", "z") assert response_body(op, {}, MemoryGetOutput(found=False))["degraded"] == [ "memory.webhook: not_announced (z)" ] @@ -259,7 +276,7 @@ def test_loom_search_says_degraded_in_its_text_and_its_structured_result(): assert "degraded" not in clean["structuredContent"] assert "Degraded" not in clean["content"][0]["text"] - D.note("rerank", "input_order_kept", "ReadTimeout", health=False) + D.partial("rerank", "input_order_kept", "ReadTimeout") answer = _search_answer(call, result) # type: ignore[arg-type] assert answer["structuredContent"]["degraded"] == ["rerank: input_order_kept (ReadTimeout)"] assert answer["content"][0]["text"].endswith( diff --git a/tests/unit/test_idempotency_across_transports.py b/tests/unit/test_idempotency_across_transports.py index 623f86a976d..c21f124ba02 100644 --- a/tests/unit/test_idempotency_across_transports.py +++ b/tests/unit/test_idempotency_across_transports.py @@ -52,7 +52,7 @@ def env(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: async def _handler(inp: Any) -> _Out: if inp.text == "degraded": - degradations.note("rerank", "input_order_kept", "ReadTimeout", health=False) + degradations.partial("rerank", "input_order_kept", "ReadTimeout") ran.append(inp.text) return _Out(calls=len(ran)) diff --git a/tests/unit/test_memory_ask_precedents.py b/tests/unit/test_memory_ask_precedents.py index 0774c79809f..a3106ac2f85 100644 --- a/tests/unit/test_memory_ask_precedents.py +++ b/tests/unit/test_memory_ask_precedents.py @@ -354,7 +354,7 @@ async def test_an_answer_a_fallback_served_is_no_precedent( from tests.unit.test_memory_ask import _search_output async def degraded_search(search_input: Any): - degradations.note("memory.search", "lexical_leg_dropped", ConnectionError(), health=False) + degradations.partial("memory.search", "lexical_leg_dropped", ConnectionError()) return _search_output(list(prec_env.hits)) monkeypatch.setattr(hsearch, "handle_memory_search", degraded_search) diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index ffb272d68d7..e5a88d09624 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -24,18 +24,24 @@ from tests.unit.ch_fake import RecordingCH, server_error -def _token(org: str = "acme", namespaces: tuple[str, ...] = ("*",), **kw: Any) -> AuthInfo: +def _token( + org: str = "acme", + namespaces: tuple[str, ...] = ("*",), + roles: tuple[Role, ...] = (Role.VIEWER,), + **kw: Any, +) -> AuthInfo: return AuthInfo( subject="viewer", org=org, namespaces=namespaces, - roles=(Role.VIEWER,), + roles=roles, is_service_account=True, **kw, ) -ORG_WIDE = _token() +# reads the org whole, as the org-wide rollups' rule has it (`reads_every_namespace`) +ORG_WIDE = _token(roles=(Role.ORG_ADMIN,)) @pytest.fixture(autouse=True) @@ -45,6 +51,9 @@ def _clean(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(incidents, "_cache", {}) monkeypatch.setattr(incidents, "_locks", {}) monkeypatch.setenv("LOOM_INSTANCE_LABEL", "deploy:web:blue") + monkeypatch.setattr( + "server.auth.context.restricted_namespaces_hidden_from", AsyncMock(return_value=[]) + ) provider_health.reset() degradations.begin() yield @@ -228,7 +237,7 @@ def _down(sql, params): await _incidents() degradations.begin() # the next poll is another request await _incidents() - await _incidents(org="other", auth=_token(org="other")) + await _incidents(org="other", auth=_token(org="other", roles=(Role.ORG_ADMIN,))) assert len(ch.statements("loom.worker_status")) == 1 assert [s.params["org"] for s in ch.statements("sli_minute")] == ["acme", "other"] @@ -263,23 +272,47 @@ async def _slow(source: str) -> list[dict[str, Any]]: @pytest.mark.asyncio -async def test_only_a_token_over_the_whole_org_reads_its_request_counts(monkeypatch) -> None: - """The rollup keeps no namespace or user: a narrowed or a pinned token, an org-wide +async def test_only_a_caller_that_reads_the_org_whole_reads_its_request_counts( + monkeypatch, +) -> None: + """The rollup keeps no namespace or user: a member's `*` token, a delegated `*` + token, an org admin narrowed to some namespaces or pinned to one user, an org-wide token that names no org, and no token where one is required read no counts.""" ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 1618, "server_errors": 1618}]) - - narrowed = await _incidents(auth=_token(namespaces=("team",))) - pinned = await _incidents(auth=_token(read_scope="own_user", read_user_id="ada")) - await _incidents(org="*", auth=_token(org="*")) - await _incidents(org="", auth=_token(org="*")) + admin = (Role.ORG_ADMIN,) + + member = await _incidents(auth=_token()) + delegated = await _incidents(auth=_token(creator="ada", parents=("tok-1",))) + narrowed = await _incidents(auth=_token(namespaces=("team",), roles=admin)) + pinned = await _incidents(auth=_token(roles=admin, read_scope="own_user", read_user_id="ada")) + await _incidents(org="*", auth=_token(org="*", roles=admin)) + await _incidents(org="", auth=_token(org="*", roles=admin)) await _incidents(auth=None) assert ch.statements("sli_minute") == [] - assert narrowed.incidents == pinned.incidents == [] + assert member.incidents == delegated.incidents == narrowed.incidents == pinned.incidents == [] whole = await _incidents() assert [i.subject for i in whole.incidents] == ["code"] +@pytest.mark.asyncio +async def test_an_org_admin_with_a_restricted_namespace_hidden_reads_no_counts( + monkeypatch, +) -> None: + """The counts would include a restricted namespace the admin holds no grant for; when + the restricted set cannot be read, none are read and the answer says so.""" + ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 1618, "server_errors": 1618}]) + hidden = AsyncMock(return_value=["code-secret"]) + monkeypatch.setattr("server.auth.context.restricted_namespaces_hidden_from", hidden) + + assert (await _incidents()).incidents == [] + assert degradations.current() == [] + hidden.return_value = ["*"] + assert (await _incidents()).incidents == [] + assert ch.statements("sli_minute") == [] + assert degradations.current() == ["ops.incidents: requests_unread (ClassificationUnavailable)"] + + def test_any_viewer_polls_it_and_it_reads_no_namespace() -> None: op = OPERATIONS_BY_NAME["ops.incidents"] assert op.required_role == Role.VIEWER and op.read_only diff --git a/tests/unit/test_pg_authority.py b/tests/unit/test_pg_authority.py index 8613091ceed..c7a9d82b18b 100644 --- a/tests/unit/test_pg_authority.py +++ b/tests/unit/test_pg_authority.py @@ -5709,7 +5709,7 @@ def test_a_fallback_that_is_no_providers_stays_out_of_health() -> None: provider_health.reset() degradations.begin() - degradations.note("memory.search", "anchor_first_unchecked", "down", health=False) + degradations.partial("memory.search", "anchor_first_unchecked", "down") assert degradations.current() == ["memory.search: anchor_first_unchecked (down)"] assert "memory.search" not in provider_health.status()["providers"] diff --git a/tests/unit/test_review_brief_store_needs_diff.py b/tests/unit/test_review_brief_store_needs_diff.py index f7c816f4acc..5096c6de7a8 100644 --- a/tests/unit/test_review_brief_store_needs_diff.py +++ b/tests/unit/test_review_brief_store_needs_diff.py @@ -130,7 +130,7 @@ def _noting_build(monkeypatch: pytest.MonkeyPatch, *, noting: set[int]) -> None: async def build_brief(inp: Any, **kw: Any) -> dict[str, Any]: if inp.pr_number in noting: - degradations.note("code_index", "calls_tests_dropped", "DatabaseError", health=False) + degradations.partial("code_index", "calls_tests_dropped", "DatabaseError") return {"pr_number": inp.pr_number, "merge_sha": inp.merge_sha, "sections": {}} async def author(*a: Any) -> str: @@ -193,7 +193,7 @@ def test_the_ingest_stores_each_brief_by_its_own_notes(monkeypatch: pytest.Monke async def pass_() -> list[str]: degradations.begin() - degradations.note("rerank", "input_order_kept", "x", health=False) # the request's + degradations.partial("rerank", "input_order_kept", "x") # the request's for pr in (7, 9): await build( repo, diff --git a/tests/unit/test_ui_read_caches.py b/tests/unit/test_ui_read_caches.py index 4f694cda7e2..8689390a6dc 100644 --- a/tests/unit/test_ui_read_caches.py +++ b/tests/unit/test_ui_read_caches.py @@ -115,9 +115,7 @@ async def test_a_status_a_read_left_smaller_names_it_on_every_answer_and_is_not_ async def _status(cfg: Any): if cfg.namespace == "code-x": - degradations.note( - "code_index", "worker_ledger_unread", ConnectionError("x"), health=False - ) + degradations.partial("code_index", "worker_ledger_unread", ConnectionError("x")) return SimpleNamespace(org=cfg.org, namespace=cfg.namespace) async def _publish(cfg: Any, st: Any) -> None: @@ -137,3 +135,51 @@ async def _publish(cfg: Any, st: Any) -> None: await asyncio.sleep(0) assert published == ["code-y"] index_status.reset_repo_status_cache() + + +@pytest.mark.asyncio +async def test_statuses_that_share_a_failed_ledger_read_each_name_it_and_none_is_published( + monkeypatch, +) -> None: + """A cold listing computes every repository's status together, and they share the one + worker-ledger read in flight: when it fails, each status names it, so none is kept + as whole or published.""" + import asyncio + + from server.observability import degradations + from server.workers import status_store + + index_status.reset_repo_status_cache() + reads: list[int] = [] + published: list[str] = [] + + async def _down(*a: Any, **k: Any) -> list[dict[str, Any]]: + reads.append(1) + await asyncio.sleep(0.01) + raise ConnectionError("x") + + async def _status(cfg: Any): + await index_status._worker_passes_from_ledger() + return SimpleNamespace(org=cfg.org, namespace=cfg.namespace) + + async def _publish(cfg: Any, st: Any) -> None: + published.append(cfg.namespace) + + monkeypatch.setattr(status_store, "pass_summaries", _down) + monkeypatch.setattr("server.core.ch.get_client", lambda: None) + monkeypatch.setattr(index_status, "_repo_status", _status) + monkeypatch.setattr(index_status, "_publish_status_snapshot", _publish) + degradations.begin() + names = ("code-x", "code-y") + await asyncio.gather( + *( + index_status._compute_repo_status(SimpleNamespace(org="acme", namespace=ns)) + for ns in names + ) + ) + await asyncio.sleep(0) + note = "code_index: worker_ledger_unread (ConnectionError)" + assert len(reads) == 1 and published == [] + assert [index_status._status_cache[("acme", ns)][2] for ns in names] == [[note], [note]] + assert degradations.current() == [note] + index_status.reset_repo_status_cache() diff --git a/tests/unit/test_worker_ledger_rows.py b/tests/unit/test_worker_ledger_rows.py index 999de46e978..e4b7595f93f 100644 --- a/tests/unit/test_worker_ledger_rows.py +++ b/tests/unit/test_worker_ledger_rows.py @@ -172,3 +172,13 @@ def test_spend_a_worker_drained_itself_is_not_counted_again( assert [e.operation for e in emitter.events] == ["worker.titler"] assert ticks == ["worker.titler"] assert emitter.events[0].embedding_tokens == 50 and emitter.events[0].namespace == "n" + + +def test_a_pass_starts_with_no_degradation_note() -> None: + """A worker task keeps its context from pass to pass: a note the last pass made must + not hold the next one's rows back (backport gaps, review briefs).""" + from server.observability import degradations + + degradations.partial("code_index", "lexical_leg_dropped", "x") + sup._begin_pass_accounting() + assert degradations.current() == [] From 8a88bfb514afc196666f1abc83319aa98e74ed1c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 05:56:00 +0530 Subject: [PATCH 07/47] A fallback an op's own field reports is in degraded too degraded is the one field a client checks without knowing each op's own disclosure fields. The fallbacks that only showed in an abstain reason, skipped, a partial_reason, a *_failed count, a section's failed or an unknown verdict now note in degraded as well, and the op's own field is unchanged: 34 code-plane sites (code.ask, code.search's legs and pick, code.grep, code.conventions, code.setting_facts, code.bisect_candidates, code.callers, code.symbol's uses legs, code.enclosing, code.review_brief's rationale, the index status lag and calibration) and the memory plane's memory.inspect sections, loom_search's failed legs, memory.search's term leg, tags, unit bodies, page blob and tag belt, and a failed projection retry. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/http-api.md | 8 ++++++-- server/code/app/answers.py | 2 ++ server/code/app/ask.py | 2 ++ server/code/app/bisect_fix.py | 1 + server/code/app/bisect_fusion.py | 1 + server/code/app/candidates.py | 4 +++- server/code/app/conventions.py | 7 +++++++ server/code/app/grep.py | 1 + server/code/app/grep_dependencies.py | 3 +++ server/code/app/index_status.py | 4 +++- server/code/app/review_brief.py | 2 ++ server/code/app/search/cards.py | 3 +++ server/code/app/search/history.py | 1 + server/code/app/search/hyde.py | 2 ++ server/code/app/search/rerank.py | 2 ++ server/code/app/search/track.py | 2 ++ server/code/app/settings.py | 2 ++ server/code/app/symbol/edges.py | 2 ++ server/code/app/symbol/enclosing.py | 3 ++- server/code/app/symbol/uses.py | 2 ++ server/code/app/symbol_uses.py | 2 ++ server/memory/app/inspect.py | 4 ++++ server/memory/app/loom_search/fanout.py | 4 +++- server/memory/app/projection_failures.py | 2 ++ server/memory/app/search/payload.py | 2 ++ server/memory/app/search/term_leg.py | 2 ++ server/memory/app/search_pages.py | 4 +++- server/memory/app/search_tag_filter.py | 2 ++ tests/unit/test_code_read_degradations.py | 20 ++++++++++++++++++++ tests/unit/test_memory_inspect.py | 20 ++++++++++++++++++++ 30 files changed, 109 insertions(+), 7 deletions(-) diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 4e96afbcb5e..9d1fd6c8229 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -307,6 +307,9 @@ leaves the key out when nothing degraded: an answer without `degraded` was serve The HTTP status stays 200. An entry names a Loom error's code and message, or another error's kind only; the full text is in the server log. +- `degraded` is the one field to check. A fallback the op also reports in its own + fields (an abstain reason, `skipped`, a `partial_reason`, a `*_failed` count, a + section's `failed`, an `unknown` verdict) is listed there too. - An op whose output declares `degraded` (`memory.set`, `memory.search`, `memory.set_from_messages`) lists its own entries first; the request's other entries follow. An entry is listed once, and a request records at most 8. @@ -318,8 +321,9 @@ error's kind only; the full text is in the server log. replay answers the `degraded` its first answer carried, on either transport. - An answer served from a fallback is not kept for a later call: `code.search` and `code.ask` do not cache it, `code.map` does not keep its map, and `code.review_brief` - serves the brief unstored (`stored: false`). A later page of a `code.search` names the - entries its first page named. + serves the brief unstored (`stored: false`). Each judges the entries its own reads + recorded, so one the request recorded before it does not stop the cache. A later page + of a `code.search` names the entries its first page named. - Whether Loom is degraded now, rather than one answer, is [`ops.incidents`](./operations/ops.md#opsincidents) ([incidents](../operations/monitoring.md#opsincidents)). diff --git a/server/code/app/answers.py b/server/code/app/answers.py index e8b498e42ab..a350b5c066f 100644 --- a/server/code/app/answers.py +++ b/server/code/app/answers.py @@ -105,6 +105,7 @@ async def ask( except customer.HOLDS: raise except Exception as exc: # noqa: BLE001 — lexical evidence remains useful without embeddings + degradations.partial("embedder", "question_vector_dropped", exc) logger.warning("code.ask question embedding unavailable: %s", error_kind(exc)) qvec = [] ctx = _AskCtx( @@ -246,6 +247,7 @@ async def _grounded_answer( except customer.HOLDS: raise except Exception as exc: # noqa: BLE001 — return cited evidence when synthesis is unavailable + degradations.partial("llm", "synthesis_skipped", exc) logger.warning("code.ask synthesis unavailable: %s", error_kind(exc)) result = AskResult( source="abstained", diff --git a/server/code/app/ask.py b/server/code/app/ask.py index a3ca42318fb..659794336b5 100644 --- a/server/code/app/ask.py +++ b/server/code/app/ask.py @@ -23,6 +23,7 @@ from server.core.llm_free import refuse_synthesis from server.embedding.embedder import served_model_label from server.llm import customer +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -63,6 +64,7 @@ async def handle_code_ask(input: CodeAskInput) -> CodeAskOutput: except customer.HOLDS: raise except Exception as exc: # noqa: BLE001 — lexical evidence remains useful without a provider + degradations.partial("embedder", "question_vector_dropped", exc) logger.warning("code.ask embedding provider unavailable: %s", error_kind(exc)) embedder = None diff --git a/server/code/app/bisect_fix.py b/server/code/app/bisect_fix.py index c4d395f06fc..ea2aad57289 100644 --- a/server/code/app/bisect_fix.py +++ b/server/code/app/bisect_fix.py @@ -362,6 +362,7 @@ async def one(r: Any) -> tuple[Any, list[dict[str, Any]]]: summary["skipped"] = "deadline" if _expired("fix_blame") else "timeout" return pool, summary except Exception as e: # noqa: BLE001 — a lever beside the scan, never the answer + degradations.partial("git_mirror", "fix_blame_skipped", e) logger.info("bisect: fix blame of #%s unavailable (%s)", fix_pr, e) summary["skipped"] = "unavailable" return pool, summary diff --git a/server/code/app/bisect_fusion.py b/server/code/app/bisect_fusion.py index 8c4a9dc7336..10df0d08320 100644 --- a/server/code/app/bisect_fusion.py +++ b/server/code/app/bisect_fusion.py @@ -339,6 +339,7 @@ async def rerank_stage( except customer.HOLDS: raise except Exception as e: # noqa: BLE001 — the fused order stands + degradations.partial("llm", "bisect_rerank_skipped", e) logger.info("bisect rerank failed: %s", e) trigger = "weak" if weak else "asked" return [*pool, *(extras or [])], {"status": "failed", "trigger": trigger} diff --git a/server/code/app/candidates.py b/server/code/app/candidates.py index 9c9b56a5a3a..a29591a24f2 100644 --- a/server/code/app/candidates.py +++ b/server/code/app/candidates.py @@ -187,6 +187,7 @@ async def caller_candidates( try: rows = await repo.live_call_misses_for_names(org, ns, names, limit=CANDIDATE_READ_CAP) except Exception as e: # noqa: BLE001 — a disclosure never fails the answer + degradations.partial("code_index", "candidate_sites_unread", e) logger.debug("candidate-site read skipped: %s", e) return _block( [], @@ -264,7 +265,8 @@ async def callee_candidates( for path in paths: try: rows = await repo.live_call_misses_for_path(org, ns, path) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — a disclosure never fails the answer + degradations.partial("code_index", "candidate_sites_unread", e) logger.debug("candidate-site read skipped: %s", e) failed = True continue diff --git a/server/code/app/conventions.py b/server/code/app/conventions.py index d33b31254d9..eebaf914740 100644 --- a/server/code/app/conventions.py +++ b/server/code/app/conventions.py @@ -157,6 +157,7 @@ async def _placed( try: return await history_bound.placed(repo, org, ns, git_dir, tip, src.head_sha, src.pr_number) except Exception as e: # noqa: BLE001 — a head the store cannot place is unknown, not a failed call + degradations.partial("code_index", "head_unplaced", e) logger.warning("conventions: head %s not placed: %s", src.head_sha[:12], e) return None @@ -297,6 +298,7 @@ async def from_index(path: str, name: str) -> bool | None: try: rows = await repo.chunk_contains(org, ns, path, cv.extern_pattern(name), limit=1) except Exception as e: # noqa: BLE001 — a failed read is an unknown, not a verdict + degradations.partial("code_index", "extern_unread", e) logger.info("conventions: extern read failed: %s", e) return None return bool(rows) @@ -356,6 +358,7 @@ async def one(prefix: str) -> dict[str, int] | None: try: labels = await repo.pr_category_census(org, ns, prefix, days=365, branch=branch) except Exception as e: # noqa: BLE001 — a lead's prior; unknown is fine + degradations.partial("code_index", "category_census_unread", e) logger.info("conventions: census read failed for %s: %s", prefix, e) return None dist: dict[str, int] = {} @@ -431,6 +434,7 @@ async def one(f: conventions_rules.TouchedFunction) -> tuple[str, int]: repo, org, ns, "symbol", f.name, [f.path], limit=5 ) except Exception as e: # noqa: BLE001 — the check reports unknown + degradations.partial("code_index", "wide_callers_coverage_unread", e) logger.info("conventions: coverage read failed: %s", e) return cv.UNKNOWN, 0 return cc.coverage_verdict(ordered, control_ok=True), max(len(ordered), total) @@ -516,6 +520,7 @@ async def _hist() -> list[dict[str, Any]] | None: try: return await history_chunks(repo, org, ns) except Exception as e: # noqa: BLE001 — the check reports unknown + degradations.partial("code_index", "setting_history_unread", e) logger.info("conventions: history read failed: %s", e) return None @@ -530,6 +535,7 @@ async def _numbers() -> tuple[ repo.max_stateless_test_number(org, ns), ) except Exception as e: # noqa: BLE001 — the check reports unknown + degradations.partial("code_index", "stateless_numbers_unread", e) logger.info("conventions: stateless read failed: %s", e) return None, {}, None, 0 own = {t.stem for t in rd.new_tests} @@ -543,6 +549,7 @@ async def _numbers() -> tuple[ _preexisting(git_dir, src.post_sha, same), ) except Exception as e: # noqa: BLE001 — the check reports unknown + degradations.partial("code_index", "test_owners_unread", e) logger.info("conventions: owner read failed: %s", e) return paths, owners, pre, int(max_number or 0) diff --git a/server/code/app/grep.py b/server/code/app/grep.py index 99eaa78d467..3d0e71409c0 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -374,6 +374,7 @@ async def _cover_batch_chunks( except TimeoutError: return chunks, "batch pattern scan timed out" except Exception as error: # noqa: BLE001 — preserve exact hits on optional read failure + degradations.partial("code_index", "pattern_scan_dropped", error) logger.debug("batch pattern scan failed: %s", type(error).__name__) return chunks, "batch pattern scan failed" return sorted(chunks + witnesses, key=lambda row: (row["path"], row["start_line"])), "" diff --git a/server/code/app/grep_dependencies.py b/server/code/app/grep_dependencies.py index 5bad3014b73..f3c33f5d357 100644 --- a/server/code/app/grep_dependencies.py +++ b/server/code/app/grep_dependencies.py @@ -20,6 +20,7 @@ from server.code.domain.search_scope import SearchScope from server.code.store.index import CodeRepo from server.core.caller_regex import compile_caller_regex +from server.observability import degradations logger = logging.getLogger(__name__) @@ -63,6 +64,7 @@ async def add_dependencies( return budget.reason() return "related definition lookup timed out" except Exception as error: # noqa: BLE001 — exact and related source survive optional failures + degradations.partial("code_index", "related_source_dropped", error) logger.debug("code.grep dependency lookup ended: %s", type(error).__name__) return "related definition lookup failed" return "" @@ -107,6 +109,7 @@ async def forwarded_dependency( budget.drop("forwarded definition lookup timed out") return None, "forwarded definition lookup timed out" except Exception as error: # noqa: BLE001 — a failed optional read leaves the exact result intact + degradations.partial("code_index", "forwarded_definition_dropped", error) logger.debug("code.grep forwarded definition lookup ended: %s", type(error).__name__) return None, "forwarded definition lookup failed" return found, "" diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index 355e36c1388..2cd624fa6af 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -229,7 +229,8 @@ async def _lag_between(gitrepo: Any, git_dir: str, since: str, until: str) -> in return hit try: n = int(await gitrepo.commit_count_between(git_dir, since, until)) - except Exception: # noqa: BLE001 — non-ancestor / unknown sha + except Exception as e: # noqa: BLE001 — non-ancestor / unknown sha + degradations.partial("git_mirror", "lag_unknown", e) return -1 if len(_lag_cache) >= _LAG_CACHE_MAX: _lag_cache.clear() @@ -446,6 +447,7 @@ async def _calibration_warnings(org: str, namespace: str) -> list[str]: try: calibration = await get_namespace_calibration(org, namespace) except Exception as e: # noqa: BLE001 — diagnostics must not break status + degradations.partial("code_index", "calibration_unread", e) logger.debug("code status: calibration lookup unavailable: %s", e) return ["Code retrieval calibration could not be checked."] if calibration is not None: diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 0fed7b4aff8..79438b85a51 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -332,6 +332,7 @@ async def _rationale_section( if any(rb.row_names(d) for d in found): diff, cut = await _pr_diff(org, ns, payload, pr_number=pr_number, is_open=is_open) except Exception as e: # noqa: BLE001 — the stored sections serve without this one + degradations.partial("memory", "rationale_unread", e) logger.warning("code.review_brief: rationale read failed: %s", e) return rb.failed_section("decisions_for_paths", e) return rb.rationale_section( @@ -380,6 +381,7 @@ async def _pr_diff( git_dir, "diff", "--no-renames", base, head, max_bytes=rb.MAX_DIFF_CHARS, check=True ) except Exception as e: # noqa: BLE001 — a diff that cannot be read leaves the check unknown + degradations.partial("git_mirror", "diff_unread", e) logger.info("code.review_brief: diff for the rationale check of PR %s: %s", pr_number, e) return None, False diff --git a/server/code/app/search/cards.py b/server/code/app/search/cards.py index 3d92ac848c4..f962e03f8ff 100644 --- a/server/code/app/search/cards.py +++ b/server/code/app/search/cards.py @@ -96,6 +96,7 @@ async def _card_leg_rows( ) ) except Exception as e: # noqa: BLE001 — a vote, never a gate + degradations.partial("code_index", "card_leg_dropped", e) logger.warning("code.search card leg failed: %s", e) work["card_leg_failed"] = 1 rows = [] @@ -180,6 +181,7 @@ async def _concept_leg_rows( scope=scope, ) except Exception as e: # noqa: BLE001 — a vote, never a gate + degradations.partial("code_index", "concept_leg_dropped", e) logger.warning("code.search concept leg failed: %s", e) work["concept_leg_failed"] = 1 rows = [] @@ -246,6 +248,7 @@ async def _concepts() -> list[dict[str, Any]]: try: names = await repo.symbol_names_for_paths(org, ns, paths) except Exception as e: # noqa: BLE001 — a vote, never a gate: no terms + degradations.partial("code_index", "concept_leg_dropped", e) logger.warning("code.search concept term read failed: %s", e) work["concept_leg_failed"] = 1 names = [] diff --git a/server/code/app/search/history.py b/server/code/app/search/history.py index a12da0e2e84..82b966f19c3 100644 --- a/server/code/app/search/history.py +++ b/server/code/app/search/history.py @@ -155,6 +155,7 @@ async def _history_route_units( paths, ) except Exception as e: # noqa: BLE001 — the section is additive, never a gate + degradations.partial("code_index", "history_route_dropped", e) logger.warning("code.search history route failed: %s", e) st.history_section = history_section = { "intent": intent.kind, diff --git a/server/code/app/search/hyde.py b/server/code/app/search/hyde.py index af7ea06b365..786ba6ecaf0 100644 --- a/server/code/app/search/hyde.py +++ b/server/code/app/search/hyde.py @@ -11,6 +11,7 @@ from server.code.app.spans import code_span, span_attrs from server.code.domain.search_scope import SearchScope from server.code.store.index import CodeRepo +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -97,6 +98,7 @@ async def _hyde_leg_rows( span_attrs(sp, results=len(rows)) return rows except Exception as e: # noqa: BLE001 — a vote, never a gate + degradations.partial("code_index", "hyde_leg_dropped", e) logger.warning("code.search hyde leg failed: %s", e) work["hyde_leg_failed"] = 1 return [] diff --git a/server/code/app/search/rerank.py b/server/code/app/search/rerank.py index 2aa34452e02..892bf38444f 100644 --- a/server/code/app/search/rerank.py +++ b/server/code/app/search/rerank.py @@ -15,6 +15,7 @@ from server.core.llm_free import reads_llm_free from server.llm import customer from server.memory.domain.rerank_names import BUILTIN_PICK +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -316,6 +317,7 @@ async def _pick_units( except customer.HOLDS: raise # a refusal or an unread switch, not a provider fault except Exception as e: # noqa: BLE001 — fail-open keeps the ranking + degradations.partial("llm", "pick_skipped", e) logger.warning("code.search pick failed (%s); ranking kept", e) return units, 0, "" picked = [candidates[i] for i in picks] diff --git a/server/code/app/search/track.py b/server/code/app/search/track.py index 64810edccda..f54c0b142ff 100644 --- a/server/code/app/search/track.py +++ b/server/code/app/search/track.py @@ -10,6 +10,7 @@ from server.code.app.search.state import _POOL, _model_name from server.code.app.spans import code_span, span_attrs from server.code.store.index import CodeRepo +from server.observability import degradations logger = logging.getLogger(__name__) @@ -80,6 +81,7 @@ async def _track( else [] ) except Exception as e: # noqa: BLE001 — a diagnostic never sinks a search + degradations.partial("code_index", "track_path_unread", e) logger.warning("code.search track_path read failed: %s", e) return {"path": path, "verdict": f"track read failed: {type(e).__name__}"} out = track_verdict( diff --git a/server/code/app/settings.py b/server/code/app/settings.py index 32ed3edb1d8..d540eee87d3 100644 --- a/server/code/app/settings.py +++ b/server/code/app/settings.py @@ -28,6 +28,7 @@ from server.code.app.ttl_cache import TtlCache from server.code.domain.index import setting_facts as sf from server.code.store.index import CodeRepo +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -103,6 +104,7 @@ async def _control(repo: CodeRepo, org: str, ns: str) -> tuple[bool, str]: try: return (await _declaration(repo, org, ns, probe)) is not None, probe except Exception as e: # noqa: BLE001 — a failed control is a failed control + degradations.partial("code_index", "setting_control_unread", e) logger.info("setting_facts control failed: %s", e) return False, probe diff --git a/server/code/app/symbol/edges.py b/server/code/app/symbol/edges.py index 9ef5d1095b8..a9bb8284c3d 100644 --- a/server/code/app/symbol/edges.py +++ b/server/code/app/symbol/edges.py @@ -12,6 +12,7 @@ from server.code.store.index import CodeRepo from server.code.store.index import prefer_scip_edges as _prefer_scip_edges from server.core.errors import ValidationError +from server.observability import degradations if TYPE_CHECKING: from server.code.app.index.pr_overlay import PrOverlay @@ -231,5 +232,6 @@ async def _pr_overlay(repo: CodeRepo, org: str, ns: str, pr_number: int) -> Any: try: return await po.overlay_for_namespace(repo, org, ns, pr_number) except Exception as e: # noqa: BLE001 — the overlay is additive; the index answers + degradations.partial("code_index", "pr_overlay_unread", e) logger.warning("code overlay for PR %s failed: %s", pr_number, e) return po.PrOverlay(pr_number=int(pr_number), reason="error") diff --git a/server/code/app/symbol/enclosing.py b/server/code/app/symbol/enclosing.py index c9ec9051dad..64110ac0f9b 100644 --- a/server/code/app/symbol/enclosing.py +++ b/server/code/app/symbol/enclosing.py @@ -387,7 +387,8 @@ async def one(r: dict[str, Any]) -> str: if expected := body_revisions.get(r["path"]): return await symbol_body(repo, org, ns, r, expected_commit=expected) return "" - except Exception: # noqa: BLE001 — fail-soft: the name still ships + except Exception as e: # noqa: BLE001 — fail-soft: the name still ships + degradations.partial("code_index", "body_unread", e) logger.warning("code.enclosing body fetch failed for %s", r.get("symbol_id")) return "" diff --git a/server/code/app/symbol/uses.py b/server/code/app/symbol/uses.py index 22017606e8d..383f8c02852 100644 --- a/server/code/app/symbol/uses.py +++ b/server/code/app/symbol/uses.py @@ -14,6 +14,7 @@ from server.code.domain.search_scope import LANG_EXTENSIONS, build_scope from server.code.domain.symbol_body import retained_source_lines from server.code.store.index import CodeRepo +from server.observability import degradations logger = logging.getLogger(__name__) @@ -131,6 +132,7 @@ async def _symbol_uses( spans = await _unit_spans(repo, org, ns, chunks) span_attrs(sp, chunks_matched=len(chunks)) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.partial("code_index", "uses_leg_dropped", e) logger.debug("code.symbol uses leg failed: %s", e) return None, False, "read_failed" definition_spans = [ diff --git a/server/code/app/symbol_uses.py b/server/code/app/symbol_uses.py index 95adcec3de3..689a9a684cb 100644 --- a/server/code/app/symbol_uses.py +++ b/server/code/app/symbol_uses.py @@ -301,6 +301,7 @@ async def uses_brief( try: lines, truncated, skipped = await mention_leg(repo, org, ns, rows) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.partial("code_index", "mention_leg_dropped", e) logger.debug("code.symbol uses mention leg failed: %s", e) lines, truncated, skipped = None, False, "read_failed" if lines is None: @@ -313,6 +314,7 @@ async def uses_brief( repo.live_call_misses_for_names(org, ns, names, limit=READ_CAP) if names else _none(), ) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.partial("code_index", "uses_leg_dropped", e) logger.debug("code.symbol uses leg failed: %s", e) return unread_block(), stats if len(edges) >= READ_CAP or len(misses) >= READ_CAP: diff --git a/server/memory/app/inspect.py b/server/memory/app/inspect.py index 952abfd0d66..f5978d49d0e 100644 --- a/server/memory/app/inspect.py +++ b/server/memory/app/inspect.py @@ -49,6 +49,7 @@ from server.memory.app.finding_evidence import IDENTITY, revisions_for from server.memory.app.search import pg_validation from server.memory.store import inspect as store +from server.observability import degradations from server.observability.consumer import INSPECTOR_CONSUMERS from server.settings import settings @@ -130,6 +131,9 @@ async def guarded[T](self, section: str, read: Callable[[], Awaitable[T]], defau return await read() except Exception as exc: # noqa: BLE001 — a read-only report; one section must not sink the rest log.warning("memory.inspect %s skipped: %s", section, exc) + degradations.partial( + "memory.inspect", "section_skipped", f"{section}: {type(exc).__name__}" + ) self.skipped.append(f"{section}: {type(exc).__name__}") return default diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index 2f5d50255b0..505b7181162 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -35,6 +35,7 @@ from server.memory.app.loom_search.tracker_leg import TrackerSearchPlan, tracker_leg from server.memory.app.profile_search import search_profile from server.memory.domain import code_change +from server.observability import degradations if TYPE_CHECKING: from server.knowledge.api.models_knowledge import KnowledgeSearchInput, KnowledgeSearchOutput @@ -489,7 +490,8 @@ def _leg_error(leg: str, e: Exception) -> str: """A failed leg's error as the payload shows it: a Loom error leads with its code (`EMBED_TIMEOUT: ...`), so an agent can tell what to do. Any other error names its kind: its text can carry a statement or a server address, - so it goes to the server log.""" + so it goes to the server log. The leg is noted in `degraded` too.""" + degradations.partial("loom_search", f"{leg}_leg_dropped", e) if not isinstance(e, LoomServerError): log.warning("loom_search: the %s leg failed: %s: %s", leg, type(e).__name__, e) return caller_text(e) diff --git a/server/memory/app/projection_failures.py b/server/memory/app/projection_failures.py index 6149ab067ff..73bd45eb5d3 100644 --- a/server/memory/app/projection_failures.py +++ b/server/memory/app/projection_failures.py @@ -49,6 +49,7 @@ from server.memory.domain.temporal_sql import HOLDS_VALUE_SQL from server.memory.domain.trust import subject_of from server.memory.store.rows import IdentityKey +from server.observability import degradations log = logging.getLogger(__name__) @@ -539,6 +540,7 @@ async def _retry(failure: ProjectionFailureRow, *, ch: Any) -> ProjectionFailure return _held(failure) except Exception as e: # noqa: BLE001 — reported on the result; the row stays open # `ops.projection_failures.retry` returns the error: its kind; the text is logged. + degradations.partial("ops.projection_failures", "retry_failed", e) log.warning( "projection failure %s: the retry failed: %s: %s", failure.failure_id, diff --git a/server/memory/app/search/payload.py b/server/memory/app/search/payload.py index aadd51c4e54..2c2e07b1161 100644 --- a/server/memory/app/search/payload.py +++ b/server/memory/app/search/payload.py @@ -245,6 +245,7 @@ async def _fill_hit_tags( try: by_key = await _read_row_tags(input.org, nss, [str(h.memory_key) for h in gaps]) except Exception as e: # noqa: BLE001 — tags are additive, never a failure + degradations.partial("memory.search", "tags_unread", e) log.warning("memory.search: include_tags read failed: %s", e) by_key = {} if work is not None: @@ -323,6 +324,7 @@ async def _read(writer: tuple[str, str, str, str], group: list[Any]) -> list[Any exclude_high_sensitivity=True, ) except Exception as e: # noqa: BLE001 — a body read never fails a search + degradations.partial("memory.search", "unit_bodies_unread", e) log.debug("unit bodies read failed for %s/%s: %s", ns, sid, e) return [] diff --git a/server/memory/app/search/term_leg.py b/server/memory/app/search/term_leg.py index 9e2e472dd07..571e84b01c5 100644 --- a/server/memory/app/search/term_leg.py +++ b/server/memory/app/search/term_leg.py @@ -36,6 +36,7 @@ from server.memory.domain.search_types import SHARED_AGENT, hit_row, is_computed_row from server.memory.store import shared as shared_repo from server.memory.store.embeddings import live_vectors +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -134,6 +135,7 @@ async def outcome(task: asyncio.Task[TermLeg] | None, wait_s: float) -> TermLeg: except TimeoutError: return TermLeg("timed_out") except Exception as e: # noqa: BLE001 — a failed read withholds the definitions only + degradations.partial("memory.search", "term_definitions_withheld", e) log.warning("term leg failed, its definitions withheld: %s", error_summary(e)) return TermLeg("failed") diff --git a/server/memory/app/search_pages.py b/server/memory/app/search_pages.py index b5717a02ca7..bc9e3e8d198 100644 --- a/server/memory/app/search_pages.py +++ b/server/memory/app/search_pages.py @@ -35,6 +35,7 @@ from server.core.datetimes import naive_utc_now from server.memory.domain.code_change import UNLINKED from server.memory.domain.search_types import RowKey, hit_row_key +from server.observability import degradations from server.settings import settings if TYPE_CHECKING: @@ -235,7 +236,8 @@ async def load_page(ch: Any, *, org: str, namespace: str, blob_key: str) -> dict return None try: payload = json.loads(str(row.get("content") or "")) - except Exception: # noqa: BLE001 — an unreadable page blob is a miss + except Exception as e: # noqa: BLE001 — an unreadable page blob is a miss + degradations.partial("memory.search", "page_unread", e) return None if not isinstance(payload, dict) or int(payload.get("v") or 0) != PAGE_VERSION: return None diff --git a/server/memory/app/search_tag_filter.py b/server/memory/app/search_tag_filter.py index 765d9784fdd..8b2dc4d8db7 100644 --- a/server/memory/app/search_tag_filter.py +++ b/server/memory/app/search_tag_filter.py @@ -13,6 +13,7 @@ from server.core.ch import get_client from server.memory.domain.search_sql import hard_tag_filter +from server.observability import degradations log = logging.getLogger(__name__) @@ -92,6 +93,7 @@ async def enforce_hard_tag_filter( try: by_key = await read_row_tags(input.org, nss, [str(h.memory_key) for h in unknown]) except Exception as e: # noqa: BLE001 — a belt never fails a search + degradations.partial("memory.search", "tag_belt_unverified", e) log.warning( "memory.search: hard tag belt read failed (kept %d rows): %s", len(unknown), e ) diff --git a/tests/unit/test_code_read_degradations.py b/tests/unit/test_code_read_degradations.py index e8f80ce0a4a..2d64414f1db 100644 --- a/tests/unit/test_code_read_degradations.py +++ b/tests/unit/test_code_read_degradations.py @@ -245,3 +245,23 @@ async def test_a_dropped_fan_in_read_is_noted() -> None: assert await fan_in.annotate_units(_FailingRepo(), "o", "n", units) == 0 # type: ignore[arg-type] assert degradations.current() == ["code_index: fan_in_dropped (ConnectionError)"] assert provider_health.status()["providers"] == {} + + +@pytest.mark.asyncio +async def test_a_fallback_the_ops_own_field_reports_is_in_degraded_too() -> None: + """`degraded` is the one field a client checks: a failed candidate-site read already + says so in the block's note, and is listed there as well.""" + from server.code.app import candidates + + block = await candidates.caller_candidates( + _FailingRepo(), # type: ignore[arg-type] + "o", + "n", + [{"symbol": "pkg.mod::send", "path": "a.py"}], + [], + max_nodes=5, + virtual=False, + ) + assert block.note == "candidate read failed; none listed" + assert degradations.current() == ["code_index: candidate_sites_unread (ConnectionError)"] + assert provider_health.status()["providers"] == {} diff --git a/tests/unit/test_memory_inspect.py b/tests/unit/test_memory_inspect.py index 4dd0d3582e3..dc49b79dd65 100644 --- a/tests/unit/test_memory_inspect.py +++ b/tests/unit/test_memory_inspect.py @@ -259,6 +259,26 @@ async def test_an_unread_retention_claims_no_gap(monkeypatch: pytest.MonkeyPatch assert out.activity.gap == "" and "activity.retention: RuntimeError" in out.skipped +@pytest.mark.asyncio +async def test_a_section_skipped_is_in_degraded_too(monkeypatch: pytest.MonkeyPatch) -> None: + """`degraded` is the one field a client checks: the section `skipped` already names + is listed there as well.""" + from server.observability import degradations + from server.settings import settings + + fake = _ch(retention=_boom) + fake.strict = False + fake.install(monkeypatch, "server.identity.app.namespace_catalog") + monkeypatch.setattr(settings, "retention_agent_events_days", 3) + degradations.begin() + out = await mi.handle_memory_inspect(_inp(window_seconds=7 * 86400)) + assert "activity.retention: RuntimeError" in out.skipped + assert ( + "memory.inspect: section_skipped (activity.retention: RuntimeError)" + in degradations.current() + ) + + @pytest.mark.asyncio async def test_the_extraction_policy_is_read_only_for_an_org_admin( ch: RecordingCH, monkeypatch: pytest.MonkeyPatch From 584b3ab5a5a07143028f8e83cbfc646d734f9133 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 06:47:09 +0530 Subject: [PATCH 08/47] Later pages name only their pool's notes, and grep and memory pages carry them too A code.search pool row keeps the notes taken when the ranking returns, so a later page no longer repeats page 1's risk block, whole-file expansion or index head. A code.grep pool row keeps its scan's notes and a memory.search parked page keeps its ranking's, and each later page names them again; a payload without the key serves as before. A search whose embedder would not build notes embedder: query_vector_dropped, so the memo does not keep it. code.ask with no embedder adds no second note. A code.map render the index head moved past is discarded with its notes. code.symbol reads each dependency's grant with row_reach and notes identity: dependency_unverified, naming no namespace, when one cannot be read. A delegated org admin's * token reads ops.incidents request counts, under the org-wide rollup rule; the docs and tests say so. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 5 +- server/code/app/answers.py | 17 +- server/code/app/candidates.py | 2 +- server/code/app/context.py | 9 +- server/code/app/grep.py | 73 ++++--- server/code/app/index_status.py | 10 +- server/code/app/search/handler.py | 17 +- server/code/app/symbol/coverage.py | 6 +- server/code/app/symbol/outline.py | 2 +- server/code/app/symbol/resolve.py | 2 +- server/code/app/symbol/symbol.py | 11 +- server/memory/app/search/computed.py | 2 +- server/memory/app/search/context.py | 2 + server/memory/app/search/handler.py | 10 + server/memory/app/search/output.py | 2 + server/memory/app/search_pages.py | 6 +- tests/unit/test_code_read_degradations.py | 221 ++++++++++++++++++++- tests/unit/test_code_symbol_dependency.py | 29 ++- tests/unit/test_decision_code_discovery.py | 1 + tests/unit/test_ops_incidents.py | 12 +- tests/unit/test_search_pages.py | 28 +++ 21 files changed, 396 insertions(+), 71 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 83bc48ff021..cdf492cda6f 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -156,8 +156,9 @@ Request counts come from `loom_telemetry.sli_minute`, which trails the calls by minutes and keeps no namespace or user. They are read for the org the call acts in, and only by a caller that reads that org whole, as the org-wide rollups have it: a platform admin, or an org admin of the org whose claim is `*`, reading whole namespaces, with no -restricted namespace of the org hidden from it. A member's token, an admin narrowed to -some namespaces or pinned to one user, and a `*` token that names no org read none. The +restricted namespace of the org hidden from it. A token delegated with those roles and +claims reads them too. A member's token, an admin narrowed to some namespaces or pinned to one user, +and a `*` token that names no org read none. The other kinds are deployment state, the same for every org: a readiness or provider incident names the check or provider and an error's kind, as `/v1/health` does, and a worker incident names a worker of any of the deployment's processes with its streak diff --git a/server/code/app/answers.py b/server/code/app/answers.py index a350b5c066f..c3b51aa450b 100644 --- a/server/code/app/answers.py +++ b/server/code/app/answers.py @@ -100,14 +100,15 @@ async def ask( writes.""" from server.llm.cache import exact_cache_scope - try: - qvec = await embedder.embed(question) - except customer.HOLDS: - raise - except Exception as exc: # noqa: BLE001 — lexical evidence remains useful without embeddings - degradations.partial("embedder", "question_vector_dropped", exc) - logger.warning("code.ask question embedding unavailable: %s", error_kind(exc)) - qvec = [] + qvec: list[float] = [] + if embedder is not None: # None: the caller noted why it has no embedder + try: + qvec = await embedder.embed(question) + except customer.HOLDS: + raise + except Exception as exc: # noqa: BLE001 — lexical evidence remains useful without embeddings + degradations.partial("embedder", "question_vector_dropped", exc) + logger.warning("code.ask question embedding unavailable: %s", error_kind(exc)) ctx = _AskCtx( repo=repo, org=org, diff --git a/server/code/app/candidates.py b/server/code/app/candidates.py index a29591a24f2..3dcf447512c 100644 --- a/server/code/app/candidates.py +++ b/server/code/app/candidates.py @@ -336,7 +336,7 @@ async def overrides_of( edge_kinds=["overrides"], limit=OVERRIDE_FANOUT_CAP + 1, ) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the direct callers are served without them degradations.partial("code_index", "override_callers_dropped", e) logger.debug("overrides read skipped: %s", e) return [], False diff --git a/server/code/app/context.py b/server/code/app/context.py index 0f926f6dc3a..c01857a81c3 100644 --- a/server/code/app/context.py +++ b/server/code/app/context.py @@ -268,14 +268,17 @@ async def _render_map( cached = _MAP_CACHE.get(key) if cached is not None: return cached - with degradations.unit(): + # Each attempt's notes are its own: only the served attempt's reach the response. + with degradations.scoped(): text = await _build_map_text(repo, org, ns, module_prefix, token_budget) - whole = not degradations.current() # a map a read left smaller is served, not kept + noted = degradations.current() # Detect a completed index advance, not a snapshot of its progressive writes. if await repo.get_state(org, ns, "git_head") != head: continue artifact = _MapArtifact(text=text, commit_sha=head) - if whole: + if noted: # a map a read left smaller is served, not kept + degradations.restore(noted) + else: _MAP_CACHE.put(key, artifact) return artifact raise OverloadedError("Repository index changed while rendering the map; retry shortly.") diff --git a/server/code/app/grep.py b/server/code/app/grep.py index 3d0e71409c0..8b2b615c250 100644 --- a/server/code/app/grep.py +++ b/server/code/app/grep.py @@ -10,7 +10,7 @@ import re import time from collections import defaultdict -from collections.abc import Callable, Iterator +from collections.abc import Callable, Iterator, Sequence from dataclasses import dataclass, replace from typing import Any @@ -543,19 +543,23 @@ async def _grep_lines( limit = input.effective_limit served_limit = page_limit or limit as_of = _as_of_early(repo, org, ns) # Beside the reads - scan = await _scan_grep_lines( - repo, - org, - ns, - input, - route=route, - scope=scope, - line_re=line_re, - budget=budget, - first_page=not offset, - limit=limit, - page_limit=served_limit, - ) + # The scan's notes are the pool's, which later pages name again; this page's own + # reads (context, definitions, neighbours) note only on this page. + with degradations.unit(): + scan = await _scan_grep_lines( + repo, + org, + ns, + input, + route=route, + scope=scope, + line_re=line_re, + budget=budget, + first_page=not offset, + limit=limit, + page_limit=served_limit, + ) + scan_noted = degradations.current() route, related_pattern, note = scan.route, scan.related_pattern, scan.note trace_run_id = new_trace_run_id() matches = scan.matches[offset : offset + served_limit] @@ -636,6 +640,7 @@ async def _grep_lines( complete_contexts=complete_contexts, match_commits=scan.match_commits, scope=scope, + degraded=scan_noted, ) # one entry per matched FILE (ids and paths alike — grep has no unit ids, # so the outcome fold skips this op; the paths still feed opened_file) @@ -1383,10 +1388,12 @@ def _issue_grep_cursor( complete_contexts: CompleteContexts = frozenset(), match_commits: dict[tuple[str, int], str], scope: SearchScope, + degraded: Sequence[str] = (), ) -> str: """Store every extracted line (served ones included, so offsets are pool positions) and return the cursor for the page after `served`; - "" when nothing was extracted past it or the tier is off.""" + "" when nothing was extracted past it or the tier is off. `degraded`: the + scan's notes, which each later page names again.""" from server.code.app import search_cursor as paging if not paging.enabled() or len(matches) <= served: @@ -1409,6 +1416,7 @@ def _issue_grep_cursor( "line_mapping": _GREP_LINE_MAPPING_VERSION, "partial": partial, "partial_reason": partial_reason, + "degraded": list(degraded), **({"context_source": context_source} if context_source else {}), **({"complete_contexts": sorted(complete_contexts)} if complete_contexts else {}), }, @@ -1418,6 +1426,25 @@ def _issue_grep_cursor( return paging.encode(kind="g", run_id=pool_id, offset=served, params=ph, indexed_commit="") +def _pool_page( + pool: list[dict[str, Any]], commits: list[Any], offset: int, limit: int, excluded: set[str] +) -> tuple[list[dict[str, Any]], dict[tuple[str, int], str], int]: + """The page from `offset`: up to `limit` matches outside the `excluded` paths, their + commits, and the pool position after the last match read.""" + page: list[dict[str, Any]] = [] + match_commits: dict[tuple[str, int], str] = {} + i = offset + while i < len(pool) and len(page) < limit: + m = pool[i] + commit = commits[i] if i < len(commits) else "" + i += 1 + if str(m.get("path") or "") in excluded: + continue + match_commits[(m["path"], m["line"])] = str(commit or "") + page.append(m) + return page, match_commits, i + + async def _serve_grep_page( input: CodeGrepInput, org: str, @@ -1451,21 +1478,13 @@ async def _serve_grep_page( payload = row["payload"] if payload.get("line_mapping") != _GREP_LINE_MAPPING_VERSION: return None, "source_line_mapping_changed", offset + degradations.restore(payload.get("degraded")) # what the scan's fallbacks left pool = [dict(m) for m in (payload.get("matches") or [])] pool_commits = payload.get("match_commits") or [] limit = input.effective_limit - excluded = set(input.exclude_unit_ids) - page: list[dict[str, Any]] = [] - match_commits: dict[tuple[str, int], str] = {} - i = offset - while i < len(pool) and len(page) < limit: - m = pool[i] - commit = pool_commits[i] if i < len(pool_commits) else "" - i += 1 - if str(m.get("path") or "") in excluded: - continue - match_commits[(m["path"], m["line"])] = str(commit or "") - page.append(m) + page, match_commits, i = _pool_page( + pool, pool_commits, offset, limit, set(input.exclude_unit_ids) + ) has_more = i < len(pool) next_cursor = ( paging.encode( diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index 2cd624fa6af..aae41aae315 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -550,6 +550,11 @@ def _adhoc_repo(org: str, ns: str) -> Any: ) +# the passes, and the notes the read made +_LedgerRead = tuple[dict[str, dict[str, Any]], list[str]] +_ledger_passes_inflight: dict[str, asyncio.Future[_LedgerRead]] = {} + + async def _worker_passes_from_ledger(days: int = 14) -> dict[str, dict[str, Any]]: """The newest recorded pass per `code_*` worker from `loom.worker_status`, in the registry snapshot's shape, so `code.index_status` reads the same facts whichever container answers. @@ -584,11 +589,6 @@ async def _worker_passes_from_ledger(days: int = 14) -> dict[str, dict[str, Any] _ledger_passes_inflight.pop(cache_key, None) -# the passes, and the notes the read made -_LedgerRead = tuple[dict[str, dict[str, Any]], list[str]] -_ledger_passes_inflight: dict[str, asyncio.Future[_LedgerRead]] = {} - - async def _read_worker_passes(client: Any, days: int) -> dict[str, dict[str, Any]]: """The ledger read itself; `_worker_passes_from_ledger` remembers and single-flights it.""" diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index 22391bcc190..6082f2fac53 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -5,6 +5,7 @@ import logging import time +from collections.abc import Sequence from typing import Any from server.code.api.models_search import CodeSearchInput, CodeSearchOutput @@ -212,6 +213,9 @@ async def _code_search(input: CodeSearchInput) -> CodeSearchOutput: budget=budget, ) + # The pool's notes: what ranked it. The risk block, the whole-file expansion and the + # index head are each page's own, so a later page reads them again and notes its own. + pool_noted = degradations.current() if expand_calls: # counted as an assist ("query_expand") by the retrieval metrics res.retrieval_work["llm_query_expand_calls"] = expand_calls @@ -240,6 +244,7 @@ async def _code_search(input: CodeSearchInput) -> CodeSearchOutput: embedding_model=embedding_model, memo_key=memo_key if memo_on else None, scope=scope, + pool_noted=pool_noted, ) @@ -282,6 +287,7 @@ def _search_embedder(input: CodeSearchInput) -> tuple[Any, str]: except customer.HOLDS: raise except Exception as e: # noqa: BLE001 — lexical-only degrade + degradations.partial("embedder", "query_vector_dropped", e) logger.warning("code.search: embedder unavailable (%s)", e) embedding_model = input.embedding_model or _served_model_name(embedder) @@ -309,9 +315,11 @@ async def _finish_search( embedding_model: str, memo_key: str | None, scope: SearchScope, + pool_noted: list[str], ) -> CodeSearchOutput: """The trace row, the span, the cursor and the output of a searched answer; memoized - under `memo_key` unless it is transient.""" + under `memo_key` unless it is transient. `pool_noted`: the notes the ranked pool + carries to its later pages.""" trace_run_id = new_trace_run_id() schedule_code_trace( org=org, @@ -360,6 +368,7 @@ async def _finish_search( embedding_model=embedding_model, indexed_commit=str(as_of.get("commit") or ""), scope=scope, + degraded=pool_noted, ) out = CodeSearchOutput( results=res.units, @@ -537,6 +546,7 @@ def _issue_search_cursor( embedding_model: str, indexed_commit: str, scope: SearchScope, + degraded: Sequence[str] = (), ) -> str: """Store the ranked pool (fire-and-forget) and return the cursor for the page after the served one; "" when nothing remains, the search @@ -566,7 +576,7 @@ def _issue_search_cursor( "top_similarity": res.top_similarity, "score_explanation": res.score_explanation, }, - degraded=degradations.current(), + degraded=list(degraded), ) paging.put_pool( org, @@ -808,7 +818,8 @@ async def _escalate_top_to_file( res.tokens_returned += await _expand_top_to_file( repo, org, ns, res.units, leftover, embedder, model=model ) - except Exception: + except Exception as e: # the top hit keeps its chunk body + degradations.partial("code_index", "file_expansion_skipped", e) logger.debug("code.search: whole-file expansion skipped", exc_info=True) diff --git a/server/code/app/symbol/coverage.py b/server/code/app/symbol/coverage.py index cfe508279d9..63a6a592847 100644 --- a/server/code/app/symbol/coverage.py +++ b/server/code/app/symbol/coverage.py @@ -28,7 +28,7 @@ async def _declined_safe( """_declined_calls_for, fail-open: a disclosure lookup never fails the answer.""" try: return await _declined_calls_for(repo, org, ns, seeds) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — a disclosure lookup never fails the answer logger.debug("declined-call lookup skipped: %s", e) degradations.partial("code_index", "declined_calls_uncounted", e) return 0, 0 @@ -75,7 +75,7 @@ async def _scip_coverage( if remaining: try: covered |= await repo.scip_covered_paths(org, ns, remaining) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the answer stays a lower bound logger.debug("scip coverage read skipped: %s", e) degradations.partial("code_index", "compiler_coverage_unread", e) return covered @@ -125,7 +125,7 @@ async def _unindexed_paths(repo: CodeRepo, org: str, ns: str, bare: list[str]) - return set() try: return set(bare) - await repo.live_paths_present(org, ns, bare) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — a failed read only lowers the verdict logger.debug("indexed-paths read skipped: %s", e) degradations.partial("code_index", "indexed_paths_unread", e) return set(bare) diff --git a/server/code/app/symbol/outline.py b/server/code/app/symbol/outline.py index 1e3a5d90428..27a08622fe9 100644 --- a/server/code/app/symbol/outline.py +++ b/server/code/app/symbol/outline.py @@ -231,7 +231,7 @@ async def _reference_head(repo: CodeRepo, org: str, ns: str, path: str) -> tuple fails or the row is not there, and the verdict then stands.""" try: rows = await repo.chunks_of_path(org, ns, path, limit=1) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the verdict stands without the head degradations.partial("code_index", "reference_head_unread", e) logger.debug("reference head read skipped: %s", e) return "", False diff --git a/server/code/app/symbol/resolve.py b/server/code/app/symbol/resolve.py index e36a1677bbb..0025dfbdb05 100644 --- a/server/code/app/symbol/resolve.py +++ b/server/code/app/symbol/resolve.py @@ -269,7 +269,7 @@ async def _file_row(repo: CodeRepo, org: str, ns: str, path: str) -> dict[str, A None: a failed read may only lower a verdict (to `not_covered`), never raise it.""" try: rows = await repo.live_files_for_path(org, ns, path) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — a failed read only lowers the verdict degradations.partial("code_index", "file_row_unread", e) logger.debug("file-row read skipped: %s", e) return None diff --git a/server/code/app/symbol/symbol.py b/server/code/app/symbol/symbol.py index 66c92fbd3c5..10dc6d06bf5 100644 --- a/server/code/app/symbol/symbol.py +++ b/server/code/app/symbol/symbol.py @@ -115,7 +115,8 @@ async def _dependency_presence( """When the namespace defines no such symbol and its entry names `depends_on` namespaces, the definition's presence per dependency the caller may read (the shared presence run, one deadline). Loom added those namespaces, so one the caller cannot - read is left out unnamed, as `search_fanout.readable_subset` does. A location, a + read is left out unnamed, as `search_fanout.readable_subset` does; one whose grant + could not be read is noted, unnamed, as a possibly short answer. A location, a symbol_id or an entry without dependencies asks nothing.""" if input.symbol_id or not input.name or _parse_location(input.name): return [], {} @@ -125,8 +126,9 @@ async def _dependency_presence( deps = tuple(d for d in cfg.depends_on if d != ns) if cfg is not None else () if not deps: return [], {} + from server.auth.authz import row_reach from server.code.app import presence as code_presence - from server.code.app import search_fanout as fanout + from server.operations.base import Role def sub_for(dep: str) -> CodeSymbolInput: return input.model_copy( @@ -143,7 +145,10 @@ def sub_for(dep: str) -> CodeSymbolInput: ) try: - readable, _ = await fanout.readable_subset(org, list(deps)) + verdicts = await asyncio.gather(*(row_reach(org, d, Role.VIEWER) for d in deps)) + if None in verdicts: # a grant read failed: a dependency may be missing, unnamed + degradations.partial("identity", "dependency_unverified") + readable = [d for d, ok in zip(deps, verdicts, strict=True) if ok] if not readable: return [], {} with code_span("symbol.dependency", seeds=len(readable)): diff --git a/server/memory/app/search/computed.py b/server/memory/app/search/computed.py index cae2b1d8508..a242287cf62 100644 --- a/server/memory/app/search/computed.py +++ b/server/memory/app/search/computed.py @@ -91,7 +91,7 @@ async def _exp(v: str | None) -> list[str] | None: return out or None except VectorInputTooLargeError: raise - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the term counts unexpanded degradations.partial("memory.search", "aggregate_unexpanded", e) log.warning("derived canonical expand failed (non-fatal): %s", e) return None diff --git a/server/memory/app/search/context.py b/server/memory/app/search/context.py index 4aa13ce1cb8..c9145d3cf75 100644 --- a/server/memory/app/search/context.py +++ b/server/memory/app/search/context.py @@ -104,6 +104,8 @@ class SearchContext: # assemble stage. page_tail: list[_MemorySearchHit] = field(default_factory=list) candidates_total: int = 0 + # The notes the ranking left, parked with `page_tail` for its later pages. + pool_degraded: list[str] = field(default_factory=list) # What the term leg did (`MemorySearchOutput.term_leg`), set when it is joined. term_leg_status: TermLegStatus = "off" # Under the Postgres authority: the hits validation dropped (`pg_validation`). diff --git a/server/memory/app/search/handler.py b/server/memory/app/search/handler.py index 5458e5887b4..8a6a24f240a 100644 --- a/server/memory/app/search/handler.py +++ b/server/memory/app/search/handler.py @@ -70,6 +70,7 @@ ) from server.memory.app.search.vector_legs import _run_vector_legs from server.memory.app.search.verdict import _calibrate_final_hits +from server.observability import degradations async def _run_retrieval_stages( @@ -173,7 +174,13 @@ async def _run_retrieval_stages( async def handle_memory_search(input: MemorySearchInput) -> MemorySearchOutput: if getattr(input, "page", ""): return await _serve_parked_page(input) + # Inside the unit `current()` reads this pass's notes alone, which its parked pages + # keep; a reread re-enters in a unit of its own. + with degradations.unit(): + return await _search_pass(input) + +async def _search_pass(input: MemorySearchInput) -> MemorySearchOutput: input, caller_hyde_explicit, _top_k_ceiling, search_budget = await _resolve_search_input(input) # A reread re-enters on the capped input, where the cap lowers nothing: the ceiling the @@ -329,6 +336,9 @@ async def handle_memory_search(input: MemorySearchInput) -> MemorySearchOutput: run.retrieval_cost_estimate = retrieval_cost_estimate final_hits = await pg_validation.validate(ctx) + # The ranked pool's notes, which its later pages name again; the tags and bodies + # filled below are each page's own. + ctx.pool_degraded = degradations.current() reread_result = await _consistency_reread(ctx, final_hits) if reread_result is not None: diff --git a/server/memory/app/search/output.py b/server/memory/app/search/output.py index 602bbd5da62..200530ad0f4 100644 --- a/server/memory/app/search/output.py +++ b/server/memory/app/search/output.py @@ -87,6 +87,7 @@ async def _serve_parked_page(input: MemorySearchInput) -> MemorySearchOutput: ) if payload is None: return empty + _degradations.restore(payload.get("degraded")) # what the ranking's fallbacks left readable = await _readable_namespaces(input.org, input.namespace, payload) hits, nxt, stale_dropped = await _parked_slice(input, payload, offset, readable) # Hits from a namespace the caller lost are neither served nor counted; the @@ -439,6 +440,7 @@ async def _finish_search_output( namespaces_searched=_output.namespaces_searched, namespaces_skipped=_output.namespaces_skipped, replay=input.as_of is not None, + degraded=ctx.pool_degraded, ) _blob_key = await _pages.store_page( get_client(), diff --git a/server/memory/app/search_pages.py b/server/memory/app/search_pages.py index bc9e3e8d198..f699def75f9 100644 --- a/server/memory/app/search_pages.py +++ b/server/memory/app/search_pages.py @@ -28,6 +28,7 @@ import hashlib import json +from collections.abc import Sequence from datetime import timedelta from typing import TYPE_CHECKING, Any @@ -122,9 +123,10 @@ def encode_page( namespaces_searched: list[str], namespaces_skipped: list[str], replay: bool = False, + degraded: Sequence[str] = (), ) -> str: """`replay`: the search was an `as_of` replay, whose pages the Postgres authority does - not check (`pg_validation`).""" + not check (`pg_validation`). `degraded`: the ranking's notes, which each page names.""" hits = [_parked(h) for h in tail] page: dict[str, Any] = { "v": PAGE_VERSION, @@ -137,6 +139,8 @@ def encode_page( } if replay: page["replay"] = True + if degraded: + page["degraded"] = list(degraded) return json.dumps( page, ensure_ascii=False, diff --git a/tests/unit/test_code_read_degradations.py b/tests/unit/test_code_read_degradations.py index 2d64414f1db..1012a2d56ab 100644 --- a/tests/unit/test_code_read_degradations.py +++ b/tests/unit/test_code_read_degradations.py @@ -163,7 +163,6 @@ async def no_retrieval(*_: Any, **__: Any) -> Any: top_similarity=0.5, score_explanation="", ) - degradations.partial("code_index", "vector_leg_dropped", "DatabaseError") cursor = handler._issue_search_cursor( request, "o", @@ -173,6 +172,7 @@ async def no_retrieval(*_: Any, **__: Any) -> Any: embedding_model=model, indexed_commit="c" * 40, scope=build_scope(), + degraded=["code_index: vector_leg_dropped (DatabaseError)"], ) async def page_two() -> tuple[Any, list[str]]: @@ -185,6 +185,189 @@ async def page_two() -> tuple[Any, list[str]]: assert notes == ["code_index: vector_leg_dropped (DatabaseError)"] +@pytest.mark.asyncio +async def test_a_later_grep_page_names_its_scans_notes(monkeypatch: pytest.MonkeyPatch) -> None: + """The grep pool is what the scan's fallbacks left: page 2, served from it in another + request, names them.""" + from server.code.api.models_grep import CodeGrepInput + from server.code.app import grep, search_cursor + from server.code.domain.search_scope import SearchScope + + stored: dict[str, Any] = {} + + async def pool(org: str, ns: str, key: str, fields: Any) -> dict[str, Any]: + return {"payload": stored[key]} + + async def empty(*_: Any, **__: Any) -> dict[str, Any]: + return {} + + monkeypatch.setattr(search_cursor, "enabled", lambda: True) + monkeypatch.setattr( + search_cursor, "put_pool", lambda org, ns, key, payload, **_: stored.update({key: payload}) + ) + monkeypatch.setattr(grep, "_read_pool_settling", pool) + monkeypatch.setattr(grep, "definitions_for", empty) + monkeypatch.setattr(grep, "index_as_of", empty) + monkeypatch.setattr(grep, "schedule_code_trace", lambda **_: None) + query = CodeGrepInput(pattern="target", include_body=False, limit=1) + hits = [{"path": "a.py", "line": 1}, {"path": "b.py", "line": 2}] + scope = SearchScope() + cursor = grep._issue_grep_cursor( + query, + "org", + "ns", + hits, + served=1, + run_id="pool", + chunks_matched=2, + truncated=False, + match_commits={}, + scope=scope, + degraded=["code_index: pattern_scan_dropped (DatabaseError)"], + ) + degradations.begin() # another request + second, _, _ = await grep._serve_grep_page( + query.model_copy(update={"cursor": cursor}), + "org", + "ns", + None, + "grep", + 0, + scope=scope, # type: ignore[arg-type] + ) + assert second is not None and second.matches == hits[1:] + assert degradations.current() == ["code_index: pattern_scan_dropped (DatabaseError)"] + + +def test_a_later_page_reads_its_own_risk_block_and_names_only_its_own_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The risk block is each page's own read: page 1's failed annotation is no part of + the pool, so page 2, whose annotation answers, names none of it.""" + from server.code.api.models_search import CodeSearchInput + from server.code.app import risk as code_risk + from server.code.app import search, search_cursor + from server.code.app.search import handler + from server.code.app.search.state import CodeSearchResult + from server.code.domain.units import CodeUnit + from server.settings import settings + from tests.unit.test_code_missing_vector_routes import _ModelFilteringRepo + + for name, value in { + "code_intel_enabled": True, + "code_org": "o", + "code_namespace": "n", + "code_trace_log_enabled": False, + "code_risk_annotations": True, + }.items(): + monkeypatch.setattr(settings, name, value) + repo = _ModelFilteringRepo(handler._embedding_model_name()) + stored: dict[str, Any] = {} + pool = [CodeUnit(unit_id="L1", path="src/a.cpp"), CodeUnit(unit_id="L2", path="src/b.cpp")] + + def put_pool(org: str, ns: str, key: str, payload: dict[str, Any], **_: Any) -> None: + stored["payload"] = payload + + async def get_pool(*_: Any) -> dict[str, Any]: + return {"payload": stored["payload"], "indexed_commit": "c" * 40} + + async def as_of(*_: Any) -> dict[str, Any]: + return {"commit": "c" * 40} + + async def thresholds(*_: Any) -> tuple[float, float, float]: + return 0.30, 0.22, 0.62 + + async def ranked(*_: Any, **__: Any) -> CodeSearchResult: + return CodeSearchResult(units=pool[:1], pool=list(pool)) + + async def annotate_failed(*_: Any, **__: Any) -> int: + degradations.partial("code_index", "risk_unannotated", TimeoutError()) + return 0 + + async def annotated(*_: Any, **__: Any) -> int: + return 0 + + monkeypatch.setattr(search_cursor, "enabled", lambda: True) + monkeypatch.setattr(search_cursor, "encode", lambda **k: "cursor") + monkeypatch.setattr(search_cursor, "decode", lambda *a, **k: {"r": "run.x", "o": 1, "t": 0}) + monkeypatch.setattr(search_cursor, "expired", lambda *a, **k: False) + monkeypatch.setattr(search_cursor, "search_scope_digest", lambda *_: "x") + monkeypatch.setattr(search_cursor, "put_pool", put_pool) + monkeypatch.setattr(search_cursor, "get_pool", get_pool) + monkeypatch.setattr(handler, "CodeRepo", lambda: repo) + monkeypatch.setattr(handler, "index_as_of", as_of) + monkeypatch.setattr(handler, "resolve_code_thresholds", thresholds) + monkeypatch.setattr(handler, "_annotate_served", annotate_failed) + monkeypatch.setattr(search, "search", ranked) + monkeypatch.setattr(code_risk, "annotate_units", annotated) + request = CodeSearchInput(query="q", top_k=1, bodies="none") + + async def page(cursor: str) -> list[str]: + degradations.begin() # each page is its own request + await handler.handle_code_search(request.model_copy(update={"cursor": cursor})) + return degradations.current() + + first = asyncio.run(page("")) + assert "code_index: risk_unannotated (TimeoutError)" in first + assert not any("risk_unannotated" in n for n in stored["payload"]["degraded"]) + assert not any("risk_unannotated" in n for n in asyncio.run(page("cursor"))) + + +def test_a_search_without_its_embedder_says_so_and_is_not_memoized( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A lexical-only answer, ranked so because the embedder would not build, is the + fallback's: it is noted and the memo does not replay it once the embedder is back.""" + from server.code.api.models_search import CodeSearchInput + from server.code.app import search, search_memo + from server.code.app.search import handler + from server.code.app.search.state import CodeSearchResult + from server.code.domain.units import CodeUnit + from server.embedding import embedder + from server.settings import settings + from tests.unit.test_code_missing_vector_routes import _ModelFilteringRepo + + for name, value in { + "code_intel_enabled": True, + "code_org": "o", + "code_namespace": "n", + "code_trace_log_enabled": False, + "code_risk_annotations": False, + "code_search_memo_enabled": True, + }.items(): + monkeypatch.setattr(settings, name, value) + repo = _ModelFilteringRepo(handler._embedding_model_name()) + kept: list[str] = [] + + def no_embedder() -> Any: + raise RuntimeError("no provider") + + async def as_of(*_: Any) -> dict[str, Any]: + return {"commit": "c" * 40} + + async def thresholds(*_: Any) -> tuple[float, float, float]: + return 0.30, 0.22, 0.62 + + async def ranked(*_: Any, **k: Any) -> CodeSearchResult: + assert k["embedder"] is None + return CodeSearchResult(units=[CodeUnit(unit_id="L1", path="src/a.cpp")]) + + async def miss(*_: Any) -> None: + return None + + monkeypatch.setattr(embedder, "get_embedder", no_embedder) + monkeypatch.setattr(handler, "CodeRepo", lambda: repo) + monkeypatch.setattr(handler, "index_as_of", as_of) + monkeypatch.setattr(handler, "resolve_code_thresholds", thresholds) + monkeypatch.setattr(search, "search", ranked) + monkeypatch.setattr(search_memo, "get", miss) + monkeypatch.setattr(search_memo, "put", lambda org, ns, key, *_a, **_k: kept.append(key)) + + asyncio.run(handler.handle_code_search(CodeSearchInput(query="q", top_k=1, bodies="none"))) + assert "embedder: query_vector_dropped (RuntimeError)" in degradations.current() + assert kept == [] + + @pytest.mark.asyncio async def test_a_map_without_its_hubs_says_so_and_is_not_kept( monkeypatch: pytest.MonkeyPatch, @@ -215,6 +398,42 @@ async def _boom(*_: Any, **__: Any) -> list[Any]: assert context._MAP_CACHE.get(("o", "n", "", 2000, "head")) is None +@pytest.mark.asyncio +async def test_a_map_attempt_left_behind_by_an_index_advance_names_nothing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The first render's hub read fails, the head moves, and the second render answers + whole: the served map is the second's, so the response names none of the first's.""" + from server.code.app import context, fan_in + + class _Repo: + heads = iter(["h1", "h2", "h2", "h2"]) + + async def get_state(self, *_: Any) -> str: + return next(self.heads) + + async def top_summaries(self, *_: Any, **__: Any) -> list[Any]: + return [] + + async def top_files_by_callers(self, *_: Any, **__: Any) -> list[Any]: + return [] + + calls: list[int] = [] + + async def _first_fails(*_: Any, **__: Any) -> list[Any]: + calls.append(1) + if len(calls) == 1: + raise ConnectionError("replica gone") + return [] + + monkeypatch.setattr(fan_in, "top_under", _first_fails) + monkeypatch.setattr(context, "_MAP_CACHE", context.TtlCache(900.0)) + artifact = await context._render_map(_Repo(), "o", "n", "", 2000) # type: ignore[arg-type] + assert artifact.commit_sha == "h2" and len(calls) == 2 + assert degradations.current() == [] + assert context._MAP_CACHE.get(("o", "n", "", 2000, "h2")) is artifact + + @pytest.mark.asyncio async def test_unread_issue_titles_are_noted() -> None: from server.code.app.blame import _issue_titles diff --git a/tests/unit/test_code_symbol_dependency.py b/tests/unit/test_code_symbol_dependency.py index 718cd8cebd5..a6233a3c919 100644 --- a/tests/unit/test_code_symbol_dependency.py +++ b/tests/unit/test_code_symbol_dependency.py @@ -22,13 +22,22 @@ def _cfgs(deps: tuple[str, ...]) -> list[Any]: ] -def _run(name: str, *, deps=("code-weave",), rows=None, fail=False, symbol_id="", refused=()): +def _run( + name: str, + *, + deps=("code-weave",), + rows=None, + fail=False, + symbol_id="", + refused=(), + unverified=(), +): calls: list[Any] = [] - async def fake_readable(org, namespaces): - return [n for n in namespaces if n not in refused], [ - {"namespace": n, "reason": "not_readable"} for n in namespaces if n in refused - ] + async def fake_reach(org, namespace, role): + if namespace in unverified: + return None + return namespace not in refused async def fake_run(inp, namespaces, sub_for, single, *, row_of, op): calls.append((list(namespaces), op, sub_for(namespaces[0]).namespace)) @@ -59,7 +68,7 @@ def fake_summarize(rs): patch("server.code.domain.index.repos.configured_repos", return_value=_cfgs(deps)), patch("server.code.app.presence.run", new=fake_run), patch("server.code.app.presence.summarize", new=fake_summarize), - patch("server.code.app.search_fanout.readable_subset", new=fake_readable), + patch("server.auth.authz.row_reach", new=fake_reach), ): degradations.begin() out = asyncio.run(h._dependency_presence(inp, "clickhouse", "code-lumen")) @@ -98,3 +107,11 @@ def test_a_dependency_the_caller_cannot_read_is_a_miss_that_names_nothing() -> N out, calls = _run("weave::x", deps=("code-weave", "code-secret"), refused=("code-secret",)) assert calls[0][0] == ["code-weave"] assert not any("code-secret" in n for n in degradations.current()) + + +def test_a_dependency_whose_grant_could_not_be_read_is_noted_unnamed() -> None: + """An unverified refusal may hide a dependency the caller can read: the answer says it + may be short, and names no namespace.""" + out, calls = _run("weave::x", deps=("code-weave", "code-secret"), unverified=("code-secret",)) + assert calls[0][0] == ["code-weave"] + assert degradations.current() == ["identity: dependency_unverified"] diff --git a/tests/unit/test_decision_code_discovery.py b/tests/unit/test_decision_code_discovery.py index b78d895595b..885cee5239f 100644 --- a/tests/unit/test_decision_code_discovery.py +++ b/tests/unit/test_decision_code_discovery.py @@ -428,6 +428,7 @@ async def finish(inp): embedding_model="fake-ngram-3072", memo_key=None, scope=search._scope_of(inp), + pool_noted=[], ) async def retrieve(*args, **kwargs): diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index e5a88d09624..8876415f1e2 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -275,14 +275,14 @@ async def _slow(source: str) -> list[dict[str, Any]]: async def test_only_a_caller_that_reads_the_org_whole_reads_its_request_counts( monkeypatch, ) -> None: - """The rollup keeps no namespace or user: a member's `*` token, a delegated `*` - token, an org admin narrowed to some namespaces or pinned to one user, an org-wide - token that names no org, and no token where one is required read no counts.""" + """The rollup keeps no namespace or user: a member's `*` token, an org admin narrowed + to some namespaces or pinned to one user, an org-wide token that names no org, and no + token where one is required read no counts. A delegated org admin's `*` token reads + them, as the org-wide rollups' rule has it.""" ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 1618, "server_errors": 1618}]) admin = (Role.ORG_ADMIN,) member = await _incidents(auth=_token()) - delegated = await _incidents(auth=_token(creator="ada", parents=("tok-1",))) narrowed = await _incidents(auth=_token(namespaces=("team",), roles=admin)) pinned = await _incidents(auth=_token(roles=admin, read_scope="own_user", read_user_id="ada")) await _incidents(org="*", auth=_token(org="*", roles=admin)) @@ -290,9 +290,11 @@ async def test_only_a_caller_that_reads_the_org_whole_reads_its_request_counts( await _incidents(auth=None) assert ch.statements("sli_minute") == [] - assert member.incidents == delegated.incidents == narrowed.incidents == pinned.incidents == [] + assert member.incidents == narrowed.incidents == pinned.incidents == [] whole = await _incidents() assert [i.subject for i in whole.incidents] == ["code"] + delegated = await _incidents(auth=_token(roles=admin, creator="ada", parents=("tok-1",))) + assert [i.subject for i in delegated.incidents] == ["code"] @pytest.mark.asyncio diff --git a/tests/unit/test_search_pages.py b/tests/unit/test_search_pages.py index db0ce127a4b..dec31b37980 100644 --- a/tests/unit/test_search_pages.py +++ b/tests/unit/test_search_pages.py @@ -327,3 +327,31 @@ async def _down(org: str, *_: object) -> fanout.Fanout: ) out = await h.handle_memory_search(page) assert [r.memory_key for r in out.results] == ["b"] + + +@pytest.mark.asyncio +async def test_a_page_of_a_degraded_search_names_the_rankings_notes(monkeypatch) -> None: + """The parked tail is what the first call's fallbacks left: each page, served in its own + request, names them; a search that noted nothing parks no key.""" + from server.memory.api.models_search import MemorySearchInput + from server.memory.app import search as h + from server.observability import degradations + + assert "degraded" not in json.loads(_encode(1, 2, [_hit("b", 0.8, ns="n")])) + note = "memory.search: lexical_leg_dropped (DatabaseError)" + content = _encode(1, 2, [_hit("b", 0.8, ns="n")], degraded=[note]) + _callers_namespaces(monkeypatch, ["n"]) + patch_handler_name(monkeypatch, "get_client", lambda: _CH(content)) + degradations.begin() # another request + out = await h.handle_memory_search( + MemorySearchInput( + org="o", + namespace="n", + agent="*", + query="q", + top_k=1, + page=sp.make_handle(sp.page_blob_key(content), 0), + ) + ) + assert [r.memory_key for r in out.results] == ["b"] + assert out.degraded == [note] From 573737c07dbb242a7fb9cc0488cd738647df70cd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 07:43:25 +0530 Subject: [PATCH 09/47] Gates whose grant read fails say so, and memory.search names only the served pass's notes loom_search's repository legs, memory.ask's code grounding and code.ask's memory context read the grant with row_reach. When it cannot be read they note identity: repo_gate_unverified, code_grounding_unverified or memory_context_unverified, with no reason or namespace, so the answer and precedent caches do not keep the smaller answer. A memory.search consistency reread runs in degradations.scoped(). When its answer is served, its notes replace the first pass's; a reread that fails or finds nothing is dropped with its notes. No delegated token reads ops.incidents request counts: org_admin is never delegated and a child is capped at admin. The test mints its child through delegation.delegate. The docs and the gate's docstring say that calls to collections the caller cannot read are counted. http-api.md now says a missing degraded key means no fallback was noted, names the caches that keep a fallback with its entries, and covers code.grep and memory.search pages. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 8 +-- docs/reference/http-api.md | 21 +++++-- server/code/app/answers.py | 7 ++- server/code/app/coverage.py | 2 +- server/code/app/repo_scope.py | 10 ++- server/code/app/settings.py | 2 +- server/code/app/symbol/symbol.py | 4 +- server/insights/app/incidents.py | 7 ++- server/memory/app/code_grounding.py | 10 ++- server/memory/app/search/consistency.py | 62 ++++++++++++------- tests/unit/test_code_ask_cache_v2.py | 42 ++++++++++++- tests/unit/test_memory_ask_precedents.py | 21 +++++++ .../unit/test_memory_code_grounding_authz.py | 26 ++++++-- .../unit/test_memory_search_handler_gates.py | 37 +++++++++++ tests/unit/test_ops_incidents.py | 27 ++++++-- tests/unit/test_repo_docs.py | 28 ++++++--- tests/unit/test_request_sli.py | 3 - tests/unit/test_search_read_your_writes.py | 34 ++++++++++ 18 files changed, 280 insertions(+), 71 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index cdf492cda6f..588b1165dad 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -156,10 +156,10 @@ Request counts come from `loom_telemetry.sli_minute`, which trails the calls by minutes and keeps no namespace or user. They are read for the org the call acts in, and only by a caller that reads that org whole, as the org-wide rollups have it: a platform admin, or an org admin of the org whose claim is `*`, reading whole namespaces, with no -restricted namespace of the org hidden from it. A token delegated with those roles and -claims reads them too. A member's token, an admin narrowed to some namespaces or pinned to one user, -and a `*` token that names no org read none. The -other kinds are deployment state, the same for every org: a readiness or +restricted namespace of the org hidden from it. The counts include calls to collections +the caller cannot read: they name no collection. A member's token, an admin narrowed to +some namespaces or pinned to one user, a delegated token (never an org admin) and a `*` +token that names no org read none. The other kinds are deployment state, the same for every org: a readiness or provider incident names the check or provider and an error's kind, as `/v1/health` does, and a worker incident names a worker of any of the deployment's processes with its streak and error kind, where `/v1/health?include=workers` shows only the answering process's diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 9d1fd6c8229..b35d7f75cb5 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -303,7 +303,8 @@ A response served from a fallback or a partial read names it in `degraded`, a li `provider: effect (kind)` entries such as `rerank: input_order_kept (ReadTimeout)` or `code_index: calls_tests_dropped (DatabaseError)` (`server/observability/degradations.py`). The transport adds the request's entries to every op's response, over HTTP and MCP, and -leaves the key out when nothing degraded: an answer without `degraded` was served in full. +leaves the key out when no fallback was noted. A budget or token cut is not a fallback +and is not listed (below): an answer without `degraded` may still be cut to its budget. The HTTP status stays 200. An entry names a Loom error's code and message, or another error's kind only; the full text is in the server log. @@ -319,11 +320,19 @@ error's kind only; the full text is in the server log. - Over MCP the trimmed result keeps `degraded` at the top and drops the copies inside its sections; `loom_search` also ends its text with a `Degraded:` line. An idempotent replay answers the `degraded` its first answer carried, on either transport. -- An answer served from a fallback is not kept for a later call: `code.search` and - `code.ask` do not cache it, `code.map` does not keep its map, and `code.review_brief` - serves the brief unstored (`stored: false`). Each judges the entries its own reads - recorded, so one the request recorded before it does not stop the cache. A later page - of a `code.search` names the entries its first page named. +- An answer served from a fallback is not kept as a whole answer: `code.search` and + `code.ask` do not cache it, `code.map` does not keep its map, `memory.ask` stores no + precedent, and `code.review_brief` serves the brief unstored (`stored: false`). Each + judges the entries its own reads recorded, so one the request recorded before it does + not stop the cache. Some caches keep a fallback with its entries and name them on each + answer served from it: `code.index_status` and `code.repos` keep such a status for + `LOOM_CODE_STATUS_TTL_S`, the constructor-coverage and `overrides` probes keep a + failed read for 30 seconds, the pending-extraction count for + `LOOM_MEMORY_PENDING_DISCLOSURE_TTL_S` and namespace health for + `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`. +- A later page of `code.search`, `code.grep` or `memory.search` names the entries of the + run that ranked its pool. What each page reads for itself (the risk block, context + lines, definitions, tags, bodies) it notes on its own. - Whether Loom is degraded now, rather than one answer, is [`ops.incidents`](./operations/ops.md#opsincidents) ([incidents](../operations/monitoring.md#opsincidents)). diff --git a/server/code/app/answers.py b/server/code/app/answers.py index c3b51aa450b..011ba64de07 100644 --- a/server/code/app/answers.py +++ b/server/code/app/answers.py @@ -546,10 +546,13 @@ async def _inject_memory_context(question: str) -> MemoryContext: # against the code namespace only. No right to read it → no enrichment, never a 403 # on the ask. try: - from server.auth.authz import row_in_scope + from server.auth.authz import row_reach from server.operations.base import Role - if not await row_in_scope(mem_org, mem_ns, Role.VIEWER, hides_answer=False): + verdict = await row_reach(mem_org, mem_ns, Role.VIEWER) + if verdict is None: # the grant read failed: the excerpts are dropped, unnamed + degradations.partial("identity", "memory_context_unverified") + if not verdict: return MemoryContext() except Exception as e: # noqa: BLE001 — fail closed logger.debug("code.ask memory enrichment authorization failed: %s", e) diff --git a/server/code/app/coverage.py b/server/code/app/coverage.py index 550e9afcf16..5ff4afd9fc7 100644 --- a/server/code/app/coverage.py +++ b/server/code/app/coverage.py @@ -168,7 +168,7 @@ async def positive_control(repo: CodeRepo, org: str, ns: str) -> tuple[bool, str return cached[0], probe try: files, _total = await _grep_tests(repo, org, ns, cc.grep_pattern("symbol", probe), limit=3) - except Exception as e: # noqa: BLE001 — a failed control is a failed control + except Exception as e: # noqa: BLE001 — the claim answers without its positive control degradations.partial("code_index", "coverage_control_unread", e) return False, probe _control_cache[(org, ns)] = (bool(files), probe, now) diff --git a/server/code/app/repo_scope.py b/server/code/app/repo_scope.py index fe32455d8c5..f5c7937b534 100644 --- a/server/code/app/repo_scope.py +++ b/server/code/app/repo_scope.py @@ -11,7 +11,7 @@ import logging -from server.auth.authz import row_in_scope +from server.auth.authz import row_reach from server.code.domain.index.repos import ( RegistryUnread, configured_repos, @@ -36,12 +36,16 @@ def trunk_namespace_of(org: str, code_namespace: str) -> str: async def readable_repo_namespace(org: str, code_namespace: str) -> str: """`trunk_namespace_of`, passed through the gate for the current - principal (VIEWER); "" when unbound, refused, or the check fails (closed).""" + principal (VIEWER); "" when unbound, refused, or the check fails (closed). A grant + that could not be read is noted: the repository legs it drops may be readable.""" try: ns = trunk_namespace_of(org, code_namespace) # refuses until the registry is read if not ns: return "" - return ns if await row_in_scope(org, ns, Role.VIEWER, hides_answer=False) else "" + verdict = await row_reach(org, ns, Role.VIEWER) + if verdict is None: + degradations.partial("identity", "repo_gate_unverified") + return ns if verdict else "" except RegistryUnread: return "" # unread: closed, and no gate failure worth a warning per request except Exception as e: # noqa: BLE001 — a gate that cannot check refuses diff --git a/server/code/app/settings.py b/server/code/app/settings.py index d540eee87d3..83231a5eb77 100644 --- a/server/code/app/settings.py +++ b/server/code/app/settings.py @@ -103,7 +103,7 @@ async def _control(repo: CodeRepo, org: str, ns: str) -> tuple[bool, str]: return False, "" try: return (await _declaration(repo, org, ns, probe)) is not None, probe - except Exception as e: # noqa: BLE001 — a failed control is a failed control + except Exception as e: # noqa: BLE001 — the facts answer without their control degradations.partial("code_index", "setting_control_unread", e) logger.info("setting_facts control failed: %s", e) return False, probe diff --git a/server/code/app/symbol/symbol.py b/server/code/app/symbol/symbol.py index 10dc6d06bf5..0d05d248a9e 100644 --- a/server/code/app/symbol/symbol.py +++ b/server/code/app/symbol/symbol.py @@ -115,8 +115,8 @@ async def _dependency_presence( """When the namespace defines no such symbol and its entry names `depends_on` namespaces, the definition's presence per dependency the caller may read (the shared presence run, one deadline). Loom added those namespaces, so one the caller cannot - read is left out unnamed, as `search_fanout.readable_subset` does; one whose grant - could not be read is noted, unnamed, as a possibly short answer. A location, a + read is left out unnamed; one whose grant could not be read is noted, unnamed, as a + possibly short answer. A location, a symbol_id or an entry without dependencies asks nothing.""" if input.symbol_id or not input.name or _parse_location(input.name): return [], {} diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 8aaf22f058e..b7804666893 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -155,9 +155,10 @@ async def _reads_org_calls(org: str) -> bool: """Whether the caller may read `org`'s call counts. The rollup keeps no namespace or user, so only a caller that reads the org whole does (`reads_every_namespace`, the org-wide rollups' rule), reading whole namespaces, with no restricted namespace - hidden from it; with auth off, the install's caller. Fails closed: a member, a - narrowed or pinned token, an unknown restricted set, or no token where one is - required, reads none.""" + hidden from it; with auth off, the install's caller. The counts include calls to + collections it cannot read, which they do not name. Fails closed: a member, a + narrowed or pinned token, a delegated one (never an org admin), an unknown + restricted set, or no token where one is required, reads none.""" from server.auth.context import ( current_auth, reads_every_namespace, diff --git a/server/memory/app/code_grounding.py b/server/memory/app/code_grounding.py index bab4825a78d..17e4ae6157c 100644 --- a/server/memory/app/code_grounding.py +++ b/server/memory/app/code_grounding.py @@ -74,10 +74,14 @@ async def _authorized_code_target(search_input: Any, settings: Any) -> tuple[str if not code_ns: return ("", "") try: - from server.auth.authz import row_in_scope + from server.auth.authz import row_reach from server.operations.base import Role - if not await row_in_scope(code_org, code_ns, Role.VIEWER, hides_answer=False): + verdict = await row_reach(code_org, code_ns, Role.VIEWER) + if verdict is None: # the grant read failed: the grounding is dropped, unnamed + degradations.partial("identity", "code_grounding_unverified") + return ("", "") + if not verdict: _warn_once( "code grounding skipped (the caller may not read the code target): %s", PermissionError(f"{code_org}/{code_ns}"), @@ -236,7 +240,7 @@ async def _symbol(sym: str) -> Any | None: consumer=GROUNDING_CONSUMER, ) ) - except Exception as err: # noqa: BLE001 — additive + except Exception as err: # noqa: BLE001 — the answer is grounded without the symbol degradations.partial("memory.ask", "code_symbol_dropped", err) return None diff --git a/server/memory/app/search/consistency.py b/server/memory/app/search/consistency.py index 29dd119c7ad..5e42c73c5c7 100644 --- a/server/memory/app/search/consistency.py +++ b/server/memory/app/search/consistency.py @@ -17,6 +17,7 @@ from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput, _MemorySearchHit from server.memory.app.recent_writes import written_recently from server.memory.app.search.context import SearchContext +from server.observability import degradations log = logging.getLogger(__package__) @@ -176,22 +177,26 @@ async def _consistency_reread( _newest_hit_age_s(final_hits), ) reread = None - try: - with sequential_reads(): - reread = await asyncio.wait_for( - handle_memory_search(reread_input), timeout=search_budget.remaining_wall_s() - ) - except TimeoutError: - log.warning("memory.search: fresh-hit sequential re-read exceeded the wall budget") - except VectorInputTooLargeError: - raise - except Exception as e: # noqa: BLE001 — an optional re-read; the first pass stands - log.warning("memory.search: fresh-hit sequential re-read failed: %s", e) + with degradations.scoped(): # the re-read's notes reach the request if it is served + try: + with sequential_reads(): + reread = await asyncio.wait_for( + handle_memory_search(reread_input), + timeout=search_budget.remaining_wall_s(), + ) + except TimeoutError: + log.warning("memory.search: fresh-hit sequential re-read exceeded the wall budget") + except VectorInputTooLargeError: + raise + except Exception as e: # noqa: BLE001 — an optional re-read; the first pass stands + log.warning("memory.search: fresh-hit sequential re-read failed: %s", e) + reread_noted = degradations.current() if reread is not None and reread.results: reread.retrieval_work = { **dict(reread.retrieval_work or {}), "read_your_writes_fresh_hit": True, } + _serve_notes_of(reread_noted) return reread if _sequential_retry_wanted( @@ -206,18 +211,20 @@ async def _consistency_reread( len(ctx.namespaces), ) retry_result = None - try: - with sequential_reads(): - retry_result = await asyncio.wait_for( - handle_memory_search(reread_input), - timeout=search_budget.remaining_wall_s(), - ) - except TimeoutError: - log.warning("memory.search: sequential-consistency retry exceeded the wall budget") - except VectorInputTooLargeError: - raise - except Exception as e: # noqa: BLE001 — an optional retry; the first pass stands - log.warning("memory.search: sequential-consistency retry failed: %s", e) + with degradations.scoped(): # as above: the retry's notes, if it is served + try: + with sequential_reads(): + retry_result = await asyncio.wait_for( + handle_memory_search(reread_input), + timeout=search_budget.remaining_wall_s(), + ) + except TimeoutError: + log.warning("memory.search: sequential-consistency retry exceeded the wall budget") + except VectorInputTooLargeError: + raise + except Exception as e: # noqa: BLE001 — an optional retry; the first pass stands + log.warning("memory.search: sequential-consistency retry failed: %s", e) + retry_noted = degradations.current() if retry_result is not None and retry_result.results: log.info( "memory.search: sequential-consistency retry found %d hit(s) the first " @@ -228,5 +235,14 @@ async def _consistency_reread( **dict(retry_result.retrieval_work or {}), "read_your_writes_retry": True, } + _serve_notes_of(retry_noted) return retry_result return None + + +def _serve_notes_of(noted: list[str]) -> None: + """The pass serves its re-read's answer, so it names the re-read's notes in place of + its own. `handle_memory_search` runs each pass in a `degradations.unit()`: this + rebinds only that unit's list, and the caller's notes stand.""" + degradations.begin() + degradations.restore(noted) diff --git a/tests/unit/test_code_ask_cache_v2.py b/tests/unit/test_code_ask_cache_v2.py index 56854ca3b0b..9200fdbc287 100644 --- a/tests/unit/test_code_ask_cache_v2.py +++ b/tests/unit/test_code_ask_cache_v2.py @@ -471,7 +471,7 @@ async def _public(org: str, namespaces: list[str]) -> dict[str, str]: monkeypatch.setattr(settings, "code_ask_memory_namespace", "decisions") monkeypatch.setattr(settings, "code_ask_memory_org", ORG) monkeypatch.setattr(ca, "_inject_memory_context", _REAL_INJECT) - monkeypatch.setattr(authz, "row_in_scope", _allowed) + monkeypatch.setattr(authz, "row_reach", _allowed) monkeypatch.setattr("server.memory.app.search.handle_memory_search", _search) monkeypatch.setattr("server.identity.app.namespace_visibility.visibility_map", _public) repo = env["repo"] @@ -483,6 +483,46 @@ async def _public(org: str, namespaces: list[str]) -> dict[str, str]: assert repo.inserts[-1]["memory_keys"] == stamped +def test_an_answer_without_memory_context_whose_grant_was_unread_is_not_cached( + env: dict[str, Any], monkeypatch: pytest.MonkeyPatch +) -> None: + """The bound memory namespace's grant could not be read: the answer is served without + its excerpts, says so, and is not kept, since the excerpts may be readable.""" + import server.auth.authz as authz + from server.observability import degradations + + async def _unverified(*a: Any, **k: Any) -> None: + return None + + async def _search(inp: Any) -> Any: + raise AssertionError("an unverified namespace is not searched") + + monkeypatch.setattr(settings, "code_ask_memory_namespace", "decisions") + monkeypatch.setattr(settings, "code_ask_memory_org", ORG) + monkeypatch.setattr(ca, "_inject_memory_context", _REAL_INJECT) + monkeypatch.setattr(authz, "row_reach", _unverified) + monkeypatch.setattr("server.memory.app.search.handle_memory_search", _search) + repo = env["repo"] + + async def ask() -> tuple[Any, list[str]]: + degradations.begin() + out = await ca.ask( + repo, + ORG, + NS, + question="why is the guard there?", + embedder=_Embedder(), + llm=_LLM(), + search_kwargs={"top_k": 10, "token_budget": 4000}, + index_head=HEAD, + ) + return out, degradations.current() + + out, notes = asyncio.run(ask()) + assert out.source == "synthesized" and not repo.inserts + assert notes == ["identity: memory_context_unverified"] + + @pytest.mark.parametrize("pending", [True, None]) def test_an_answer_is_not_cached_while_an_erasure_may_have_missed_it( quoted: dict[str, Any], monkeypatch: pytest.MonkeyPatch, pending: Any diff --git a/tests/unit/test_memory_ask_precedents.py b/tests/unit/test_memory_ask_precedents.py index a3106ac2f85..9e563e73ab5 100644 --- a/tests/unit/test_memory_ask_precedents.py +++ b/tests/unit/test_memory_ask_precedents.py @@ -363,6 +363,27 @@ async def degraded_search(search_input: Any): assert out.source == "synthesized" and prec_env.inserts == [] +@pytest.mark.asyncio +async def test_an_answer_whose_code_grant_was_unread_is_no_precedent( + prec_env, monkeypatch: pytest.MonkeyPatch +) -> None: + """The bound code index's grant could not be read, so the answer lacks the grounding + the caller may be allowed: it says so and is not stored.""" + import server.auth.authz as authz + from server.observability import degradations + from server.settings import settings + + async def _unverified(*a: Any, **k: Any) -> None: + return None + + monkeypatch.setattr(settings, "memory_ask_code_namespace", "code-x") + monkeypatch.setattr(authz, "row_reach", _unverified) + degradations.begin() + out = await _ask() + assert out.source == "synthesized" and prec_env.inserts == [] + assert "identity: code_grounding_unverified" in degradations.current() + + @pytest.mark.asyncio async def test_uncited_or_hedged_answers_are_not_stored(prec_env) -> None: prec_env.llm._text = "I have no memory of your favorite color." diff --git a/tests/unit/test_memory_code_grounding_authz.py b/tests/unit/test_memory_code_grounding_authz.py index 8e3ce04618a..28fcf43a6e9 100644 --- a/tests/unit/test_memory_code_grounding_authz.py +++ b/tests/unit/test_memory_code_grounding_authz.py @@ -81,7 +81,7 @@ async def test_unauthorized_principal_makes_every_leg_a_noop(legs, monkeypatch) async def _deny(*a, **k): return False - monkeypatch.setattr(authz, "row_in_scope", _deny) + monkeypatch.setattr(authz, "row_reach", _deny) set_current_auth( AuthInfo( subject="b@x", @@ -97,12 +97,30 @@ async def _deny(*a, **k): assert legs == {"search": 0, "symbol": 0, "prs": 0} +@pytest.mark.asyncio +async def test_an_unverified_grant_makes_every_leg_a_noop_and_says_so(legs, monkeypatch) -> None: + """The grant read failed: the code target may be readable, so the ask that answers + without its grounding names that, and names no namespace.""" + from server.observability import degradations + + async def _unverified(*a, **k): + return None + + monkeypatch.setattr(authz, "row_reach", _unverified) + degradations.begin() + pool = [_mem("see PR #12345 and FooBar")] + out = await g.apply_code_grounding("FooBar?", _input(), pool, _settings()) + assert out == pool + assert legs == {"search": 0, "symbol": 0, "prs": 0} + assert degradations.current() == ["identity: code_grounding_unverified"] + + @pytest.mark.asyncio async def test_authorized_principal_runs_the_legs_once_resolved(legs, monkeypatch) -> None: async def _allow(*a, **k): return True - monkeypatch.setattr(authz, "row_in_scope", _allow) + monkeypatch.setattr(authz, "row_reach", _allow) set_current_auth( AuthInfo( subject="a@x", @@ -122,7 +140,7 @@ async def test_restricted_target_leaves_one_audit_row(legs, monkeypatch) -> None async def _allow(*a, **k): return True - monkeypatch.setattr(authz, "row_in_scope", _allow) + monkeypatch.setattr(authz, "row_reach", _allow) nc._cache[ORG] = (1e12, frozenset({CODE_NS})) rows: list[Any] = [] @@ -156,7 +174,7 @@ async def test_each_leg_authorizes_when_called_alone(legs, monkeypatch) -> None: async def _deny(*a, **k): return False - monkeypatch.setattr(authz, "row_in_scope", _deny) + monkeypatch.setattr(authz, "row_reach", _deny) set_current_auth( AuthInfo( subject="b@x", diff --git a/tests/unit/test_memory_search_handler_gates.py b/tests/unit/test_memory_search_handler_gates.py index ea5b6a46e6e..a0d47ff97be 100644 --- a/tests/unit/test_memory_search_handler_gates.py +++ b/tests/unit/test_memory_search_handler_gates.py @@ -1101,3 +1101,40 @@ async def search(inp: Any) -> Any: assert moved.score_components["code_changed_places"] == -3.0 assert f"rank_score={moved.rank_score:.2f}" in moved.explanation assert "rank_score=0.95" not in moved.explanation + + +async def test_a_parked_page_keeps_the_rankings_notes_not_the_served_blocks( + search_env, monkeypatch +) -> None: + """A note taken before validation is the ranking's and is parked with the tail; a tag + or body fill after it is the served block's, named on this page alone.""" + import json + + from server.memory.app import search_pages + from server.memory.app.search import handler, pg_validation + from server.observability import degradations + + real_validate, real_shape = pg_validation.validate, handler._shape_final_hits + parked: dict[str, Any] = {} + + async def validate(ctx: Any) -> Any: + degradations.partial("memory.search", "lexical_leg_dropped", "DatabaseError") + return await real_validate(ctx) + + async def shape(ctx: Any, hits: Any) -> Any: + degradations.partial("memory.search", "tags_unread", "TimeoutError") + return await real_shape(ctx, hits) + + async def store_page(ch: Any, **kw: Any) -> str: + parked.update(json.loads(kw["content"])) + return "page/abc" + + monkeypatch.setattr(pg_validation, "validate", validate) + monkeypatch.setattr(handler, "_shape_final_hits", shape) + monkeypatch.setattr(search_pages, "store_page", store_page) + search_env.hits = [_svc_hit(k, sim=s) for k, s in (("a", 0.9), ("b", 0.8), ("c", 0.7))] + degradations.begin() + out = await _run(search_env, top_k=1, paging=True) + assert out.next_page and parked["hits"] + assert parked["degraded"] == ["memory.search: lexical_leg_dropped (DatabaseError)"] + assert "memory.search: tags_unread (TimeoutError)" in degradations.current() diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 8876415f1e2..503ba345289 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -276,13 +276,30 @@ async def test_only_a_caller_that_reads_the_org_whole_reads_its_request_counts( monkeypatch, ) -> None: """The rollup keeps no namespace or user: a member's `*` token, an org admin narrowed - to some namespaces or pinned to one user, an org-wide token that names no org, and no - token where one is required read no counts. A delegated org admin's `*` token reads - them, as the org-wide rollups' rule has it.""" + to some namespaces or pinned to one user, a token an org admin delegated (capped at + admin, since `org_admin` is never delegated), an org-wide token that names no org, and + no token where one is required read no counts.""" + import time + + from server.auth.delegation import delegate + from server.auth.jwt import verify_token + ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 1618, "server_errors": 1618}]) admin = (Role.ORG_ADMIN,) + parent = _token(roles=admin, token_id="tok-1", issued_at=int(time.time())) + minted = await delegate( + parent, + org="acme", + requested={"*": None}, + scoped=False, + ttl_seconds=None, + is_service_account=True, + ) + child = verify_token(minted.mint("sa:bot")) + assert child.namespaces == ("*",) and child.roles == (Role.ADMIN,) member = await _incidents(auth=_token()) + delegated = await _incidents(auth=child) narrowed = await _incidents(auth=_token(namespaces=("team",), roles=admin)) pinned = await _incidents(auth=_token(roles=admin, read_scope="own_user", read_user_id="ada")) await _incidents(org="*", auth=_token(org="*", roles=admin)) @@ -290,11 +307,9 @@ async def test_only_a_caller_that_reads_the_org_whole_reads_its_request_counts( await _incidents(auth=None) assert ch.statements("sli_minute") == [] - assert member.incidents == narrowed.incidents == pinned.incidents == [] + assert member.incidents == delegated.incidents == narrowed.incidents == pinned.incidents == [] whole = await _incidents() assert [i.subject for i in whole.incidents] == ["code"] - delegated = await _incidents(auth=_token(roles=admin, creator="ada", parents=("tok-1",))) - assert [i.subject for i in delegated.incidents] == ["code"] @pytest.mark.asyncio diff --git a/tests/unit/test_repo_docs.py b/tests/unit/test_repo_docs.py index d693476b0ca..ae5215181ef 100644 --- a/tests/unit/test_repo_docs.py +++ b/tests/unit/test_repo_docs.py @@ -21,6 +21,7 @@ KnowledgeSearchOutput, _SearchHit, ) +from server.observability import degradations ORG = "acme" @@ -99,10 +100,10 @@ def test_the_docs_namespace_is_the_trunk_branchs_the_page_order() -> None: def _gate(allowed: set[str]): - async def row_in_scope(org, ns, role, *, hides_answer=True): + async def row_reach(org, ns, role): return ns in allowed - return row_in_scope + return row_reach def _search( @@ -138,7 +139,7 @@ async def test_under_a_code_scope_the_repositorys_docs_join_the_knowledge_sectio calls, ), ) - monkeypatch.setattr("server.code.app.repo_scope.row_in_scope", _gate({"code-kj"})) + monkeypatch.setattr("server.code.app.repo_scope.row_reach", _gate({"code-kj"})) tok = set_code_scope(f"{ORG}/code-kj-26-7") try: repo_ns = await repo_scope.repo_namespace_in_scope(ORG) # every branch reads the trunk @@ -168,7 +169,7 @@ async def test_the_knowledge_leg_reads_only_the_namespace_the_gate_resolved( async def never(*a, **k): raise AssertionError("the leg must not run a gate of its own") - monkeypatch.setattr("server.code.app.repo_scope.row_in_scope", never) + monkeypatch.setattr("server.code.app.repo_scope.row_reach", never) # the namespace the gate admitted is read as given out = await rd.knowledge_with_repo_docs(BASE, repo_namespace="code-kj") assert [h.source_uri for h in out.results] == ["doc://secret", "notes://a"] @@ -195,20 +196,29 @@ async def scoped(scope: str | None) -> str: finally: reset_code_scope(tok) - monkeypatch.setattr("server.code.app.repo_scope.row_in_scope", _gate({"code-kj"})) + monkeypatch.setattr("server.code.app.repo_scope.row_reach", _gate({"code-kj"})) assert await scoped(f"{ORG}/code-kj-26-7") == "code-kj" assert await scoped(None) == "" # not a coding checkout assert await scoped("other/code-kj") == "" # another org's repository assert await scoped(f"{ORG}/memory-ns") == "" # not a repository index - monkeypatch.setattr("server.code.app.repo_scope.row_in_scope", _gate(set())) + monkeypatch.setattr("server.code.app.repo_scope.row_reach", _gate(set())) assert await scoped(f"{ORG}/code-kj") == "" # refused: a restricted repository stays its own async def boom(*a, **k): raise RuntimeError("grants read failed") - monkeypatch.setattr("server.code.app.repo_scope.row_in_scope", boom) + monkeypatch.setattr("server.code.app.repo_scope.row_reach", boom) assert await scoped(f"{ORG}/code-kj") == "" # the check fails: closed + async def unverified(*a, **k): + return None + + # the grant read failed: closed, and the dropped legs are noted without the namespace + monkeypatch.setattr("server.code.app.repo_scope.row_reach", unverified) + degradations.begin() + assert await scoped(f"{ORG}/code-kj") == "" + assert degradations.current() == ["identity: repo_gate_unverified"] + @pytest.mark.asyncio async def test_a_slow_repository_search_answers_nothing(monkeypatch) -> None: @@ -284,7 +294,7 @@ async def run(request, plan): monkeypatch.setattr(document_reads, "resolve_list", resolve) monkeypatch.setattr(source_access, "prepare", prepare) monkeypatch.setattr(document_reads, "run_checked_list", run) - monkeypatch.setattr("server.code.app.repo_scope.row_in_scope", _gate({"code-kj"})) + monkeypatch.setattr("server.code.app.repo_scope.row_reach", _gate({"code-kj"})) out = await cc._with_repo_docs(ORG, "code-kj-26-7", "# map", 2500) assert out.startswith("# map\n\n## Repository docs (code-kj)") assert "- On-call runbook — doc://runbook" in out @@ -293,7 +303,7 @@ async def run(request, plan): # a map that already fills the budget gets nothing added, and no read assert await cc._with_repo_docs(ORG, "code-kj", "x" * 4 * 2490, 2500) == "x" * 4 * 2490 # a caller the gate refuses reads no listing, cached or not - monkeypatch.setattr("server.code.app.repo_scope.row_in_scope", _gate(set())) + monkeypatch.setattr("server.code.app.repo_scope.row_reach", _gate(set())) assert await cc._with_repo_docs(ORG, "code-kj", "# map", 2500) == "# map" diff --git a/tests/unit/test_request_sli.py b/tests/unit/test_request_sli.py index 145a60210ed..2e3fa23e383 100644 --- a/tests/unit/test_request_sli.py +++ b/tests/unit/test_request_sli.py @@ -1236,12 +1236,9 @@ def test_only_answers_whole_without_the_namespace_leave_an_unverified_refusal_un never, cond = "never", "conditional" assert unmarked == { # Namespaces Loom adds to the answer on its own. - ("server/code/app/answers.py", "_inject_memory_context", never), ("server/code/app/answers_cache.py", "reuse_allowed", never), ("server/code/app/search_fanout.py", "readable_subset", never), ("server/memory/app/code_link_reads.py", "readable_namespaces", never), - ("server/memory/app/code_grounding.py", "_authorized_code_target", never), - ("server/code/app/repo_scope.py", "readable_repo_namespace", never), # The wording of a refusal another check decided. ("server/memory/app/decision_extract.py", "_readable_names", never), ("server/tracker/app/dupcheck_fanout.py", "readable_tracker_namespaces", never), diff --git a/tests/unit/test_search_read_your_writes.py b/tests/unit/test_search_read_your_writes.py index 344ed1a9681..c5236a4d077 100644 --- a/tests/unit/test_search_read_your_writes.py +++ b/tests/unit/test_search_read_your_writes.py @@ -210,3 +210,37 @@ async def search(inp: object) -> object: monkeypatch.setattr(pkg, "handle_memory_search", search) monkeypatch.setattr("server.memory.store.read_your_writes_enabled", lambda: True) assert asyncio.run(_consistency_reread(_empty_pass_ctx(60_000), [])) is None # type: ignore[arg-type] + + +@pytest.mark.parametrize("served", [True, False]) +def test_a_pass_names_the_notes_of_the_pass_it_serves(monkeypatch, served: bool) -> None: + """An adopted retry's answer is served: its notes replace the first pass's. A retry that + fails is thrown away with its notes, and the first pass's stand.""" + from types import SimpleNamespace + + import server.memory.app.search as pkg + from server.memory.app.search.consistency import _consistency_reread + from server.observability import degradations + + first = "memory.search: lexical_leg_dropped (DatabaseError)" + retried = "memory.search: chunk_leg_dropped (TimeoutError)" + + async def search(inp: object) -> object: + degradations.partial("memory.search", "chunk_leg_dropped", TimeoutError()) + if not served: + raise RuntimeError("replica unavailable") + return SimpleNamespace(results=["hit"], retrieval_work={}) + + async def one_pass() -> tuple[object, list[str]]: + degradations.begin() + degradations.partial("identity", "repo_gate_unverified") # the caller's, before it + with degradations.unit(): # as handle_memory_search runs a pass + degradations.partial("memory.search", "lexical_leg_dropped", "DatabaseError") + out = await _consistency_reread(_empty_pass_ctx(60_000), []) # type: ignore[arg-type] + return out, degradations.current() + + monkeypatch.setattr(pkg, "handle_memory_search", search) + monkeypatch.setattr("server.memory.store.read_your_writes_enabled", lambda: True) + out, notes = asyncio.run(one_pass()) + assert (out is not None) is served + assert notes == ["identity: repo_gate_unverified", retried if served else first] From 22f6d8d36c21b7c46398952b08148ba3745e8302 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 07:55:59 +0530 Subject: [PATCH 10/47] A clone lag over a commit the mirror lacks is unknown, not a failed read code.index_status and code.repos noted git_mirror: lag_unknown whenever git could not count the commits between a watermark and the clone head, so a watermark the clone did not hold yet marked the status degraded and kept it from being published. When the count fails, each sha is checked with rev-parse --verify --quiet: exit 1 (no such commit) gives lag -1 and no note, exit 128 (git cannot read the mirror) keeps the note and the status unpublished. The check is gitrepo.holds_commit, which mirror_commit_facts now uses too. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/index/gitrepo.py | 20 +++++++ server/code/app/index/review_brief_sources.py | 10 +--- server/code/app/index_status.py | 17 +++++- tests/unit/test_gitrepo_option_injection.py | 23 ++++++++ tests/unit/test_ui_read_caches.py | 58 +++++++++++++++++++ 5 files changed, 118 insertions(+), 10 deletions(-) diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index 41beaf5a2d8..f55c6bfd4cf 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -921,6 +921,26 @@ async def commit_count_between(git_dir: str, since_sha: str, until_sha: str) -> return int(out.strip() or "0") +async def holds_commit(git_dir: str, sha: str, *, timeout_s: float | None = None) -> bool: + """Whether the mirror holds commit `sha`. False when git read the mirror and found no + such commit (exit 1), a miss; GitError when git cannot read the mirror (exit 128) or + `sha` is no object id.""" + try: + await _git( + git_dir, + "rev-parse", + "--verify", + "--quiet", + f"{_object_id(sha)}^{{commit}}", + timeout_s=timeout_s, + ) + except GitError as e: + if e.returncode == 1: + return False + raise + return True + + @dataclass(frozen=True) class DiffEntry: status: str # A | M | D | T (a rename or copy arrives as D+A or A) diff --git a/server/code/app/index/review_brief_sources.py b/server/code/app/index/review_brief_sources.py index 817a817baf8..bdbc3b4895d 100644 --- a/server/code/app/index/review_brief_sources.py +++ b/server/code/app/index/review_brief_sources.py @@ -121,14 +121,8 @@ async def mirror_commit_facts( subject names no PR. A mirror git cannot read raises.""" from server.code.app.index import gitrepo - try: - await gitrepo.run( - git_dir, "rev-parse", "--verify", "--quiet", f"{sha}^{{commit}}", timeout_s=timeout_s - ) - except gitrepo.GitError as e: - if e.returncode == 1: # read, and no such commit: a miss, not a failed mirror - return None - raise + if not await gitrepo.holds_commit(git_dir, sha, timeout_s=timeout_s): + return None # read, and no such commit: a miss, not a failed mirror text = await gitrepo.run( git_dir, "log", diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index aae41aae315..c04cd17e85c 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -221,6 +221,18 @@ def reset_repo_status_cache() -> None: ) +async def _commit_missing(gitrepo: Any, git_dir: str, shas: tuple[str, ...]) -> bool: + """Whether the mirror, read, holds no commit for one of `shas`: a lag over history the + clone lacks is unknown, not a failed read. Not missing when git cannot read it.""" + try: + for sha in shas: + if not await gitrepo.holds_commit(git_dir, sha): + return True + except Exception: # noqa: BLE001 — git cannot read the mirror: the count's failure stands + return False + return False + + async def _lag_between(gitrepo: Any, git_dir: str, since: str, until: str) -> int: """`commit_count_between`, remembered: the pair is immutable history.""" key = (git_dir, since, until) @@ -229,8 +241,9 @@ async def _lag_between(gitrepo: Any, git_dir: str, since: str, until: str) -> in return hit try: n = int(await gitrepo.commit_count_between(git_dir, since, until)) - except Exception as e: # noqa: BLE001 — non-ancestor / unknown sha - degradations.partial("git_mirror", "lag_unknown", e) + except Exception as e: # noqa: BLE001 — the lag reads as unknown (-1) + if not await _commit_missing(gitrepo, git_dir, (since, until)): + degradations.partial("git_mirror", "lag_unknown", e) return -1 if len(_lag_cache) >= _LAG_CACHE_MAX: _lag_cache.clear() diff --git a/tests/unit/test_gitrepo_option_injection.py b/tests/unit/test_gitrepo_option_injection.py index 56d61efb22e..5d7f34517c8 100644 --- a/tests/unit/test_gitrepo_option_injection.py +++ b/tests/unit/test_gitrepo_option_injection.py @@ -48,6 +48,7 @@ async def spawn(*args, **kw): lambda: gitrepo.branches_containing("/g", EVIL), lambda: gitrepo.release_containing("/g", EVIL), lambda: gitrepo.grep_paths("/g", EVIL, "x", ()), + lambda: gitrepo.holds_commit("/g", EVIL), ], ) def test_a_non_revision_is_refused_before_git_runs(no_git, call) -> None: @@ -89,3 +90,25 @@ def test_object_ids_still_count_against_a_real_repository(tmp_path: Path) -> Non with pytest.raises(gitrepo.GitError): asyncio.run(gitrepo.commits_between(git_dir, f"--output={probe}", shas[2], 10)) assert not probe.exists() + + +def test_holds_commit_tells_a_missing_commit_from_a_mirror_git_cannot_read(tmp_path: Path) -> None: + """Exit 1 (git read the mirror, no such commit) is a miss; exit 128 (no repository) + raises, as a failed read.""" + repo = tmp_path / "r" + repo.mkdir() + _git(repo, "init", "-q", "-b", "main") + (repo / "f").write_text("x") + _git(repo, "add", "f") + _git(repo, "-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x") + head = _git(repo, "rev-parse", "HEAD") + git_dir = str(repo / ".git") + assert asyncio.run(gitrepo.holds_commit(git_dir, head)) + assert asyncio.run(gitrepo.holds_commit(git_dir, head[:7])) + for absent in ("0123456789abcdef0123456789abcdef01234567", "abc1234"): + assert asyncio.run(gitrepo.holds_commit(git_dir, absent)) is False + not_a_repo = tmp_path / "not-a-repo" + not_a_repo.mkdir() + with pytest.raises(gitrepo.GitError) as caught: + asyncio.run(gitrepo.holds_commit(str(not_a_repo), head)) + assert caught.value.returncode == 128 diff --git a/tests/unit/test_ui_read_caches.py b/tests/unit/test_ui_read_caches.py index 8689390a6dc..7cbd93c90ff 100644 --- a/tests/unit/test_ui_read_caches.py +++ b/tests/unit/test_ui_read_caches.py @@ -183,3 +183,61 @@ async def _publish(cfg: Any, st: Any) -> None: assert [index_status._status_cache[("acme", ns)][2] for ns in names] == [[note], [note]] assert degradations.current() == [note] index_status.reset_repo_status_cache() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mirror", ["lacks_the_watermark", "unreadable"]) +async def test_a_lag_the_clone_cannot_count_is_noted_only_when_git_cannot_read_it( + tmp_path, monkeypatch, mirror: str +) -> None: + """A watermark the clone does not hold is an unknown lag (-1), a miss: no `degraded`, + and the status is published. A mirror git cannot read is a failed read: noted, and + the status is not published.""" + import asyncio + import subprocess + + from server.observability import degradations + + repo = tmp_path / "r" + repo.mkdir() + + def git(*args: str) -> str: + return subprocess.run( + ["git", *args], cwd=repo, check=True, capture_output=True, text=True + ).stdout.strip() + + git("init", "-q", "-b", "main") + (repo / "f").write_text("x") + git("add", "f") + git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x") + head = git("rev-parse", "HEAD") + git_dir = repo / ".git" + if mirror == "unreadable": + git_dir = tmp_path / "not-a-repo" + git_dir.mkdir() + absent = "0123456789abcdef0123456789abcdef01234567" + cfg = SimpleNamespace(org="acme", namespace="code-x", git_dir=str(git_dir), git_branch="main") + published: list[str] = [] + + async def _status(c: Any) -> Any: + _, lags = await index_status._clone_lags(c, {}, {"git_head": -1}, lambda k: absent) + return SimpleNamespace(org=c.org, namespace=c.namespace, lags=lags) + + async def _publish(c: Any, st: Any) -> None: + published.append(c.namespace) + + monkeypatch.setattr(index_status, "published_clone_head", lambda state, branch: head) + monkeypatch.setattr(index_status, "_repo_status", _status) + monkeypatch.setattr(index_status, "_publish_status_snapshot", _publish) + index_status.reset_repo_status_cache() + index_status._lag_cache.clear() + degradations.begin() + st = await index_status._repo_status_cached(cfg) + await asyncio.sleep(0) + assert st.lags == {"git_head": -1} + if mirror == "unreadable": + assert [n.split(" (")[0] for n in degradations.current()] == ["git_mirror: lag_unknown"] + assert published == [] + else: + assert degradations.current() == [] and published == ["code-x"] + index_status.reset_repo_status_cache() From 4ec306c7668a736338d73afe95d2dbd334b8d29a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 09:11:25 +0530 Subject: [PATCH 11/47] Added-namespace gates note an unread grant; ops.incidents says whether it read the calls - readable_subset, readable_namespaces and restricted_namespaces_hidden_from read each verdict with row_reach (or the new authz.restricted_verdict). A namespace whose grant could not be read is still left out, and the answer notes identity: fanout_unverified, code_links_unverified or restricted_unverified, naming no namespace. The request-SLI scan pins direct row_reach and restricted_verdict calls too. - ops.incidents answers requests: read, not_permitted or unread on every answer, so an ok that did not consult the org's calls says so. - memory.search parks the notes taken through the verdict, so a failed term leg is named on later pages too. - code.index_status notes lag_unknown when no clone tip is published and git cannot read the mirror's. - Code lessons note a failed file read, and a lesson path or file read cut within the fixed enrichment bound; a cut by the call's deadline stays unnoted. - code_backport_gaps notes a pass failure (FellBack) for a fix whose read falls back again, so a fix that never gets written builds a streak. - Comments and docs: the table-summary except, the brief builder's scoped(), and the ops.incidents source cache in the degraded section. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 5 + docs/reference/http-api.md | 5 +- docs/reference/operations/ops.md | 1 + sdk/go/wire/models.gen.go | 3 +- sdk/python/loom/ops.py | 1 + sdk/rust/src/wire_models.rs | 12 ++ sdk/rust/tests/registry_contracts.rs | 3 +- sdk/typescript/src/generated/ops.ts | 1 + server/auth/authz.py | 20 +++- server/auth/context.py | 22 ++-- server/code/app/enrich.py | 9 +- server/code/app/index/pass_stream.py | 3 +- server/code/app/index_status.py | 6 +- server/code/app/result_lessons.py | 8 +- server/code/app/search_fanout.py | 12 +- server/code/workers/backport_gaps.py | 9 +- server/insights/api/models_ops.py | 14 ++- server/insights/app/incidents.py | 66 ++++++----- server/memory/app/code_link_reads.py | 12 +- server/memory/app/path_lessons.py | 18 ++- server/memory/app/search/handler.py | 6 +- .../test_branch_fanout_skips_unreadable.py | 4 +- tests/unit/test_code_backport_gaps.py | 47 ++++++++ tests/unit/test_code_blame_range.py | 12 +- tests/unit/test_code_first_build.py | 4 +- tests/unit/test_code_result_lessons.py | 80 +++++++++++++- tests/unit/test_code_search_cursor.py | 16 +++ .../test_code_verify_citations_resolve.py | 4 +- tests/unit/test_degradations.py | 22 ++++ tests/unit/test_memory_code_plane_reads.py | 8 +- .../unit/test_memory_search_handler_gates.py | 29 +++++ tests/unit/test_ops_incidents.py | 102 +++++++++++++---- tests/unit/test_request_sli.py | 103 +++++++++++++++++- tests/unit/test_ui_read_caches.py | 12 +- 34 files changed, 563 insertions(+), 116 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 588b1165dad..e4da51e0317 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -168,6 +168,11 @@ however many clients poll during an outage, and each read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A source that failed is named in the response's `degraded` while its failure is cached, and the other sources still answer. +Every answer says in `requests` whether the org's call counts were read, since `ok` +covers the org's calls only when they were: `read`; `not_permitted` when the call names +no single org or the caller does not read the org whole; `unread` when the counts, the +restricted set or a restricted namespace's grant could not be read. + ### Smoke test After a deploy, write and read one memory end to end: diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index b35d7f75cb5..0ef2b7f174e 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -328,8 +328,9 @@ error's kind only; the full text is in the server log. answer served from it: `code.index_status` and `code.repos` keep such a status for `LOOM_CODE_STATUS_TTL_S`, the constructor-coverage and `overrides` probes keep a failed read for 30 seconds, the pending-extraction count for - `LOOM_MEMORY_PENDING_DISCLOSURE_TTL_S` and namespace health for - `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`. + `LOOM_MEMORY_PENDING_DISCLOSURE_TTL_S`, namespace health for + `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`, and each of `ops.incidents`' ClickHouse + sources for 5 seconds. - A later page of `code.search`, `code.grep` or `memory.search` names the entries of the run that ranked its pool. What each page reads for itself (the risk block, context lines, definitions, tags, bodies) it notes on its own. diff --git a/docs/reference/operations/ops.md b/docs/reference/operations/ops.md index cc7e96b34f6..430bcab4d60 100644 --- a/docs/reference/operations/ops.md +++ b/docs/reference/operations/ops.md @@ -58,6 +58,7 @@ Whether Loom is degraded now, from its checks, providers, workers and calls. | `status` | `Literal['ok', 'degraded']` | `degraded` when an incident is listed, else `ok`. | | `incidents` | `list[OpsIncident]` | Errors first, at most 20. | | `window_minutes` | `int` | Minutes of history a `provider` or `requests` incident reads. | +| `requests` | `Literal['read', 'not_permitted', 'unread']` | Whether the org's call counts were read, so `ok` covers its calls only with `read`: `not_permitted` when the call names no single org or the caller does not read the org whole (a member, a narrowed, pinned or delegated token, a restricted… | ## `ops.projection_failures.list` diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index a5d46647f74..097b3631ed8 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: e9d5400400fc9ed5ffcddfead9a1760771c8dda2049199908fc00227763e24df +// Registry model schema SHA-256: 12f5e2b6c4640dab18ca772e4c4d3c90f50f186fe7e01a6dc738578844d844c0 // Package wire contains the Go requests and responses for Loom operations. package wire @@ -10181,6 +10181,7 @@ type OpsIncidentsOutput struct { Status string `json:"status"` Incidents *[]OpsIncident `json:"incidents,omitempty"` WindowMinutes int64 `json:"window_minutes"` + Requests string `json:"requests"` } // OpsProjectionFailuresListInput is the request to ops.projection_failures.list. diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 2a0da0fdecc..5f3f45e548d 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -18484,6 +18484,7 @@ class OpsIncidentsOutput(TypedDict, total=False): status: Required[Literal["ok", "degraded"]] incidents: NotRequired[list["OpsIncident"]] window_minutes: Required[int] + requests: Required[Literal["read", "not_permitted", "unread"]] class OpsIncident(TypedDict, total=False): diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 6251bb19691..3c8928b3661 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -49769,6 +49769,17 @@ pub struct OpsIncident { pub age_s: Option, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum OpsIncidentsOutputRequests { + #[serde(rename = "read")] + Read, + #[serde(rename = "not_permitted")] + NotPermitted, + #[serde(rename = "unread")] + Unread, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct OpsIncidentsOutput { @@ -49776,6 +49787,7 @@ pub struct OpsIncidentsOutput { #[serde(default = "default_2209")] pub incidents: Vec, pub window_minutes: Integer, + pub requests: OpsIncidentsOutputRequests, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index 804da0163d7..8875213049c 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -6785,7 +6785,8 @@ fn ops_incidents() { let encoded = serde_json::to_value(value).unwrap(); assert!(encoded.is_object()); let value: clickhouse_loom::OpsIncidentsOutput = - serde_json::from_str("{\"status\":\"ok\",\"window_minutes\":1}").unwrap(); + serde_json::from_str("{\"status\":\"ok\",\"window_minutes\":1,\"requests\":\"read\"}") + .unwrap(); let encoded = serde_json::to_value(value).unwrap(); assert!(encoded.is_object()); assert_eq!( diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index f5272f69483..d825335f0ed 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -8925,6 +8925,7 @@ export interface OpsIncidentsOutput { status: "ok" | "degraded"; incidents?: OpsIncident[]; window_minutes: number; + requests: "read" | "not_permitted" | "unread"; } export interface OpsProjectionFailuresListInput { diff --git a/server/auth/authz.py b/server/auth/authz.py index a3c9a4a27f8..beac34dbc78 100644 --- a/server/auth/authz.py +++ b/server/auth/authz.py @@ -754,12 +754,25 @@ async def restricted_allows( """`_check_restricted` as a predicate. A refusal made because a read it needed failed marks the request the server's, as `row_in_scope` does (`hides_answer` there).""" + verdict = await restricted_verdict(auth, required_role, org, namespace, grants=grants) + if verdict is None and hides_answer: # the server's failure + note_answered_unverified() + return bool(verdict) + + +async def restricted_verdict( + auth: AuthorizationClaims, + required_role: Role, + org: str, + namespace: str, + *, + grants: GrantMap | None = None, +) -> bool | None: + """`restricted_allows`' answer, None for a refusal that could not be verified.""" try: await _check_restricted(auth, required_role, org, namespace, grants) except PermissionError as e: - if hides_answer and getattr(e, "unverified", False): # the server's failure - note_answered_unverified() - return False + return None if getattr(e, "unverified", False) else False return True @@ -974,6 +987,7 @@ async def row_reach(org: str, namespace: str, required_role: Role = Role.VIEWER) "may_be_restricted", "names_namespace", "restricted_allows", + "restricted_verdict", "row_in_scope", "row_reach", "scope_flags", diff --git a/server/auth/context.py b/server/auth/context.py index 4623ecd7724..e037e3f8cec 100644 --- a/server/auth/context.py +++ b/server/auth/context.py @@ -235,8 +235,10 @@ async def restricted_namespaces_hidden_from(org: str) -> list[str]: """Restricted namespaces of `org` the current caller may NOT read — the set an org-wide rollup must exclude even for an org admin (collections are left out by `collection_clause`). Empty with auth disabled; `["*"]` when it - cannot be told.""" - from server.auth.authz import restricted_allows + cannot be told. One whose grant could not be read is hidden and noted + (`identity: restricted_unverified`), naming no namespace.""" + from server.auth.authz import restricted_verdict + from server.observability import degradations from server.operations.base import Role auth = current_auth() @@ -251,12 +253,16 @@ async def restricted_namespaces_hidden_from(org: str) -> list[str]: # the request that hid it all is the server's (fail_closed). note_answered_unverified() return ["*"] - # A listing the caller did not scope: a namespace left out does not mark. - return [ - ns - for ns in sorted(names) - if not await restricted_allows(auth, Role.VIEWER, org, ns, hides_answer=False) - ] + # A listing the caller did not scope: a namespace left out does not mark the request + # the server's, and one whose grant could not be read is noted. + hidden = [] + for ns in sorted(names): + verdict = await restricted_verdict(auth, Role.VIEWER, org, ns) + if verdict is None: + degradations.partial("identity", "restricted_unverified") + if not verdict: + hidden.append(ns) + return hidden async def collection_clause(org: str, column: str = "namespace") -> tuple[str, dict[str, Any]]: diff --git a/server/code/app/enrich.py b/server/code/app/enrich.py index 1dc3b9a7ff8..9a12507e964 100644 --- a/server/code/app/enrich.py +++ b/server/code/app/enrich.py @@ -103,19 +103,22 @@ async def share_edit_example_reads() -> AsyncIterator[None]: reads.close() -async def bounded[T](coro: Awaitable[T], fallback: T, seconds: float | None = None) -> T: +async def bounded[T]( + coro: Awaitable[T], fallback: T, seconds: float | None = None, *, cut_noted: bool = False +) -> T: """`coro`'s answer within `seconds` (`code_enrich_timeout_s` when None), else `fallback`. A read that fails is named in `degraded`, and so is one cut by the fixed `code_enrich_timeout_s`: the store answered slowly. One cut by the `seconds` a caller passes is not, since that is what is left of the caller's budget (often nothing) and - the cut is the budget working, like a token cut.""" + the cut is the budget working, like a token cut; `cut_noted` when `seconds` is a share + of the fixed bound, so the cut is noted too.""" try: return await asyncio.wait_for( coro, timeout=settings.code_enrich_timeout_s if seconds is None else seconds ) except TimeoutError as e: logger.debug("code enrich cut by its bound") - if seconds is None: + if seconds is None or cut_noted: degradations.partial("code_index", "enrichment_skipped", e) return fallback except Exception as e: # noqa: BLE001 — enrichment degrades, never fails diff --git a/server/code/app/index/pass_stream.py b/server/code/app/index/pass_stream.py index 6e5b465d460..460ee94d3ed 100644 --- a/server/code/app/index/pass_stream.py +++ b/server/code/app/index/pass_stream.py @@ -386,7 +386,8 @@ def _brief_builder(cfg: Any) -> Any: from server.observability import degradations async def _build(repo: Any, org: str, ns: str, **kw: Any) -> None: - # Each brief's own notes decide whether it is stored (`build_for_merge`). + # A brief's notes stay off the pass's list and off a waiting `code.refresh`'s; + # `build_for_merge`'s own `unit()` decides whether it is stored. with degradations.scoped(): await build_for_merge( repo, org, ns, path_prefixes=tuple(cfg.path_prefixes), call=call_code_op, **kw diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index c04cd17e85c..b71c50171b7 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -275,7 +275,9 @@ async def _clone_lags( ) for (name, _), n in zip(marks, lag_counts, strict=True): lags[name] = n - except Exception as e: # noqa: BLE001 — missing clone must not break status + except Exception as e: # noqa: BLE001 — the lags stay unknown (-1) + if not clone_head: # no published tip, and git could not read the mirror's + degradations.partial("git_mirror", "lag_unknown", e) logger.debug("code status: clone tip unavailable for %s: %s", cfg.namespace, e) return clone_head, lags @@ -807,7 +809,7 @@ async def _table_summary_cached( try: n, stamp = await read(CodeRepo()) rows, at = int(n), summary_stamp(stamp) - except Exception as e: # noqa: BLE001 — status stays whole when the read fails + except Exception as e: # noqa: BLE001 — the status names the failure and is not published degradations.partial("code_index", f"{what.replace(' ', '_')}_summary_unread", e) logger.debug("code status: %s summary unavailable for %s: %s", what, ns, e) return rows, at # not kept: the status entry names the failure, the next one reads diff --git a/server/code/app/result_lessons.py b/server/code/app/result_lessons.py index f0cfbfcfbca..ad5d9b61224 100644 --- a/server/code/app/result_lessons.py +++ b/server/code/app/result_lessons.py @@ -53,6 +53,7 @@ async def _scoped_lesson_paths( symbols: dict[str, set[str]], source: path_lessons.SourceSpans, remaining: float, + cut_noted: bool, ) -> list[str]: limit = settings.code_result_lessons_paths if not trunk or not namespaces or not any(path in symbols for path in paths[limit:]): @@ -66,6 +67,7 @@ async def _scoped_lesson_paths( ), set(), seconds=timeout_s, + cut_noted=cut_noted, ) span_attrs(sp, results=len(linked)) return sorted(paths, key=lambda path: path not in linked)[:limit] @@ -121,6 +123,9 @@ async def scope() -> tuple[str, list[str], str, bool]: narrowed = _bound_s(input, started) bound = settings.code_enrich_timeout_s if narrowed is None else narrowed + # A read cut within the fixed bound is the store's slowness, and noted; one cut by + # the call's own deadline is its budget working. + fixed = narrowed is None if bound <= 0: return path_lessons.Lessons([]) with code_span("enrich.lessons"): @@ -133,7 +138,7 @@ async def scope() -> tuple[str, list[str], str, bool]: top = offered_paths[: settings.code_result_lessons_paths] if on_trunk and source is not None and matched_symbols: top = await _scoped_lesson_paths( - org, nss, trunk, offered_paths, matched_symbols, source, remaining + org, nss, trunk, offered_paths, matched_symbols, source, remaining, fixed ) remaining = bound - (time.monotonic() - read_started) if remaining <= 0: @@ -150,6 +155,7 @@ async def scope() -> tuple[str, list[str], str, bool]: top, token_budget=settings.code_result_lessons_tokens, timeout_s=remaining, + cut_noted=fixed, matched_symbols=matched_symbols if on_trunk else None, source=source, query=query, diff --git a/server/code/app/search_fanout.py b/server/code/app/search_fanout.py index 060e8148bc6..017125e2095 100644 --- a/server/code/app/search_fanout.py +++ b/server/code/app/search_fanout.py @@ -121,13 +121,15 @@ async def readable_subset( """The namespaces the principal may read, and the rest as `{namespace, reason: "not_readable"}`. Only for namespaces LOOM added on its own (a release-branch fan-out, a trunk or sibling namespace); a list the caller named goes through `authorize`, which - fails closed.""" - from server.auth.authz import row_in_scope + fails closed. One whose grant could not be read is skipped too and noted + (`identity: fanout_unverified`), naming no namespace.""" + from server.auth.authz import row_reach + from server.observability import degradations from server.operations.base import Role - verdicts = await asyncio.gather( - *(row_in_scope(org, ns, Role.VIEWER, hides_answer=False) for ns in namespaces) - ) + verdicts = await asyncio.gather(*(row_reach(org, ns, Role.VIEWER) for ns in namespaces)) + if None in verdicts: + degradations.partial("identity", "fanout_unverified") readable = [ns for ns, ok in zip(namespaces, verdicts, strict=True) if ok] skipped = [ {"namespace": ns, "reason": "not_readable"} diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index c20a856815f..aa71c70c681 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -43,6 +43,10 @@ SETTLED = frozenset({"covered", "not_affected"}) +class FellBack(RuntimeError): + """A fix's composed read served a smaller answer (its notes are the message).""" + + @dataclass class BackportGapsResult: namespaces: int = 0 @@ -276,7 +280,9 @@ async def compute_fix( read, its tracker record did not answer, or a read it fell back on left a smaller answer (a night of unknowns must not overwrite verdicts), counted on the result either way. A read that fell back is retried once while the pass is - before `deadline` (on the monotonic clock; None: no bound).""" + before `deadline` (on the monotonic clock; None: no bound); one that falls back again + is a failure of the pass (`note_failure`), so a fix that falls back every night + builds the worker's failure streak.""" try: out, noted = await _read_fix(cfg, pr, runner) if noted and (deadline is None or time.monotonic() < deadline): @@ -289,6 +295,7 @@ async def compute_fix( return [] if noted: logger.info("code_backport_gaps: #%s not written, it fell back: %s", pr, "; ".join(noted)) + note_failure(FellBack("; ".join(noted)), f"code_backport_gaps:#{pr}") if ( noted or bool(getattr(out, "tracker_unavailable", False)) diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 1fc249a97d9..a7acb12e64a 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -169,8 +169,9 @@ class OpsIncidentsInput(BaseModel): It lists failing readiness checks, providers and workers, and the share of the org's calls that failed on the server, which only a caller that reads the org whole (an - org admin over `*`, a platform admin) reads. Identity is optional: the org is the - token's (role check only; no namespace is addressed).""" + org admin over `*`, a platform admin) reads; `requests` says whether they were read. + Identity is optional: the org is the token's (role check only; no namespace is + addressed).""" org: str = "" @@ -195,6 +196,9 @@ class OpsIncident(BaseModel): age_s: float | None = None +RequestsRead = Literal["read", "not_permitted", "unread"] + + class OpsIncidentsOutput(BaseModel): """The deployment's current incidents, as the server that answers sees them. A client polls it, through `loom_op` over MCP, to tell a Loom outage from an empty @@ -206,3 +210,9 @@ class OpsIncidentsOutput(BaseModel): incidents: list[OpsIncident] = Field(default_factory=list) # Minutes of history a `provider` or `requests` incident reads. window_minutes: int + # Whether the org's call counts were read, so `ok` covers its calls only with `read`: + # `not_permitted` when the call names no single org or the caller does not read the + # org whole (a member, a narrowed, pinned or delegated token, a restricted namespace + # hidden from it); `unread` when the counts, the restricted set or a restricted + # namespace's grant could not be read. + requests: RequestsRead diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index b7804666893..45001a1c301 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -23,7 +23,12 @@ from typing import Any from server.core.errors import caller_text -from server.insights.api.models_ops import OpsIncident, OpsIncidentsInput, OpsIncidentsOutput +from server.insights.api.models_ops import ( + OpsIncident, + OpsIncidentsInput, + OpsIncidentsOutput, + RequestsRead, +) from server.insights.store import ops as ops_store from server.observability import degradations, provider_health from server.settings import settings @@ -52,10 +57,11 @@ def _line(text: object) -> str: async def _cached( source: str, org: str, read: Callable[[], Awaitable[list[OpsIncident]]] -) -> list[OpsIncident]: - """`read()`'s incidents, or the ones it gave within `_SOURCE_TTL_S`. Polls that arrive - while it reads wait for that read rather than start their own. A failed read is - cached too, and named in `degraded` on every answer that serves it.""" +) -> tuple[list[OpsIncident], bool]: + """(`read()`'s incidents, or the ones it gave within `_SOURCE_TTL_S`; whether that + read answered). Polls that arrive while it reads wait for that read rather than start + their own. A failed read is cached too, and named in `degraded` on every answer that + serves it.""" key = (source, org) lock = _locks.get(key) if lock is None: @@ -74,7 +80,7 @@ async def _cached( hit = _cache[key] = (time.monotonic(), incidents, failure) if hit[2]: degradations.partial("ops.incidents", f"{source}_unread", hit[2]) - return hit[1] + return hit[1], not hit[2] async def _readiness() -> list[OpsIncident]: @@ -151,14 +157,15 @@ async def _workers() -> list[OpsIncident]: return out -async def _reads_org_calls(org: str) -> bool: - """Whether the caller may read `org`'s call counts. The rollup keeps no namespace or - user, so only a caller that reads the org whole does (`reads_every_namespace`, the +async def _reads_org_calls(org: str) -> RequestsRead: + """`read` when the caller may read `org`'s call counts. The rollup keeps no namespace + or user, so only a caller that reads the org whole does (`reads_every_namespace`, the org-wide rollups' rule), reading whole namespaces, with no restricted namespace hidden from it; with auth off, the install's caller. The counts include calls to collections it cannot read, which they do not name. Fails closed: a member, a - narrowed or pinned token, a delegated one (never an org admin), an unknown - restricted set, or no token where one is required, reads none.""" + narrowed or pinned token, a delegated one (never an org admin), or no token where one + is required, is `not_permitted`; an unknown restricted set, or a restricted + namespace whose grant could not be read, is `unread`.""" from server.auth.context import ( current_auth, reads_every_namespace, @@ -168,13 +175,18 @@ async def _reads_org_calls(org: str) -> bool: auth = current_auth() if auth is None: - return not settings.auth_actually_required() + return "not_permitted" if settings.auth_actually_required() else "read" if not reads_every_namespace(auth, org) or request_narrowed(): - return False - hidden = await restricted_namespaces_hidden_from(org) + return "not_permitted" + with degradations.unit(): # its own note: a grant it could not read + hidden = await restricted_namespaces_hidden_from(org) + unverified = bool(degradations.current()) if hidden == ["*"]: # the restricted set is unread degradations.partial("ops.incidents", "requests_unread", "ClassificationUnavailable") - return not hidden + return "unread" + if unverified: + return "unread" + return "not_permitted" if hidden else "read" async def _requests(org: str, minutes: int) -> list[OpsIncident]: @@ -198,23 +210,22 @@ async def _requests(org: str, minutes: int) -> list[OpsIncident]: return out -async def _no_incidents() -> list[OpsIncident]: - return [] +async def _request_incidents(org: str, minutes: int) -> tuple[list[OpsIncident], RequestsRead]: + """The org's request incidents, and whether its counts were read. No single org to + read (an org-wide token that named none) is `not_permitted`, as is a token that may + not read the whole org's counts.""" + reach: RequestsRead = await _reads_org_calls(org) if org and org != "*" else "not_permitted" + if reach != "read": + return [], reach + calls, answered = await _cached("requests", org, lambda: _requests(org, minutes)) + return calls, "read" if answered else "unread" async def handle_ops_incidents(input: OpsIncidentsInput) -> OpsIncidentsOutput: """The current incidents, errors first.""" minutes = settings.ops_incidents_window_minutes - org = input.org - # No single org to read (an org-wide token that named none), or a token that may not - # read the whole org's counts: no request incidents. - requests = ( - _cached("requests", org, lambda: _requests(org, minutes)) - if org and org != "*" and await _reads_org_calls(org) - else _no_incidents() - ) - ready, workers, calls = await asyncio.gather( - _readiness(), _cached("workers", "", _workers), requests + ready, (workers, _), (calls, requests) = await asyncio.gather( + _readiness(), _cached("workers", "", _workers), _request_incidents(input.org, minutes) ) incidents = [*ready, *_providers(minutes * 60.0), *workers, *calls] incidents.sort(key=lambda i: (i.severity != "error", i.kind, i.subject)) @@ -222,4 +233,5 @@ async def handle_ops_incidents(input: OpsIncidentsInput) -> OpsIncidentsOutput: status="degraded" if incidents else "ok", incidents=incidents[:MAX_INCIDENTS], window_minutes=minutes, + requests=requests, ) diff --git a/server/memory/app/code_link_reads.py b/server/memory/app/code_link_reads.py index 7411cf4b738..afb1b933c7a 100644 --- a/server/memory/app/code_link_reads.py +++ b/server/memory/app/code_link_reads.py @@ -128,14 +128,16 @@ def _tag_namespaces(org: str) -> list[tuple[str, str]]: async def readable_namespaces(org: str, namespaces: set[str]) -> set[str]: - """The namespaces among `namespaces` the caller may read.""" - from server.auth.authz import row_in_scope + """The namespaces among `namespaces` the caller may read. One whose grant could not + be read is left out and noted (`identity: code_links_unverified`), naming no + namespace.""" + from server.auth.authz import row_reach from server.operations.base import Role names = sorted(namespaces) - allowed = await asyncio.gather( - *(row_in_scope(org, ns, Role.VIEWER, hides_answer=False) for ns in names) - ) + allowed = await asyncio.gather(*(row_reach(org, ns, Role.VIEWER) for ns in names)) + if None in allowed: + degradations.partial("identity", "code_links_unverified") return {ns for ns, ok in zip(names, allowed, strict=True) if ok} diff --git a/server/memory/app/path_lessons.py b/server/memory/app/path_lessons.py index 9980e82519c..bd8b240206d 100644 --- a/server/memory/app/path_lessons.py +++ b/server/memory/app/path_lessons.py @@ -32,6 +32,7 @@ from server.memory.domain.lemmatize import snowball_stem_tokens from server.memory.domain.recall import query_tokens from server.memory.store import code_links +from server.observability import degradations logger = logging.getLogger(__name__) @@ -259,6 +260,7 @@ async def lessons_for_paths( *, token_budget: int, timeout_s: float | None = None, + cut_noted: bool = False, query: str = "", matched_symbols: dict[str, set[str]] | None = None, source: SourceSpans | None = None, @@ -280,7 +282,8 @@ async def lessons_for_paths( another path or symbol than the row was written against, when there are any; and `supersedes_key`, the key of the older row it replaces, when the conflict check linked one. `timeout_s` bounds the file reads together; - failed or unfinished reads leave the completed files' rows intact. A nonempty `query` + failed or unfinished reads leave the completed files' rows intact. A failed read is + named in `degraded`, and so is one `timeout_s` cut when `cut_noted`. A nonempty `query` ranks matching excerpts after constraints and pins across the selected paths, preserving path and listing order on ties. Uncapped grep and read answers focus lessons on the returned source. Search focuses a file when a matched definition has a @@ -305,7 +308,9 @@ async def lessons_for_paths( for group in groups ] windows = source if source is not None and source.windows is not None else None - per_read = await _read_paths(reads, timeout_s, include_source_links=windows is not None) + per_read = await _read_paths( + reads, timeout_s, cut_noted=cut_noted, include_source_links=windows is not None + ) # every row a row read here replaces, whichever file or read it came from superseded = {i for hits, _ in per_read for h in hits for i in h.get("supersedes_ids") or []} out: list[dict[str, Any]] = [] @@ -395,9 +400,11 @@ async def _read_paths( reads: Sequence[MemoryForFileInput], timeout_s: float | None, *, + cut_noted: bool = False, include_source_links: bool = False, ) -> list[tuple[list[dict[str, Any]], bool]]: - """Keep completed file reads when another fails or runs past the shared bound.""" + """Keep completed file reads when another fails or runs past the shared bound. A + failed read is noted, and so are unfinished ones when `cut_noted`.""" tasks = [ asyncio.create_task( listing_rows(inp, include_source_links=True) @@ -408,6 +415,11 @@ async def _read_paths( ] try: done, _ = await asyncio.wait(tasks, timeout=timeout_s) + for task in done: + if not task.cancelled() and (e := task.exception()) is not None: + degradations.partial("code_lessons", "file_lessons_dropped", e) + if cut_noted and len(done) < len(tasks): + degradations.partial("code_lessons", "file_lessons_dropped", "TimeoutError") return [ task.result() if task in done and not task.cancelled() and task.exception() is None diff --git a/server/memory/app/search/handler.py b/server/memory/app/search/handler.py index 8a6a24f240a..c0304028472 100644 --- a/server/memory/app/search/handler.py +++ b/server/memory/app/search/handler.py @@ -336,9 +336,6 @@ async def _search_pass(input: MemorySearchInput) -> MemorySearchOutput: run.retrieval_cost_estimate = retrieval_cost_estimate final_hits = await pg_validation.validate(ctx) - # The ranked pool's notes, which its later pages name again; the tags and bodies - # filled below are each page's own. - ctx.pool_degraded = degradations.current() reread_result = await _consistency_reread(ctx, final_hits) if reread_result is not None: @@ -357,6 +354,9 @@ async def _search_pass(input: MemorySearchInput) -> MemorySearchOutput: final_hits, calibration, abstain_verdict = await _verdict( ctx, run, final_hits, evidence_support_count ) + # The ranked pool's notes, the term leg's included, which its later pages name + # again; the tags and bodies filled below are each page's own. + ctx.pool_degraded = degradations.current() final_hits, _unit_bodies, _namespaces_searched = await _shape_final_hits(ctx, final_hits) _output = _build_search_output( diff --git a/tests/unit/test_branch_fanout_skips_unreadable.py b/tests/unit/test_branch_fanout_skips_unreadable.py index 703fa4774ba..210b230ec25 100644 --- a/tests/unit/test_branch_fanout_skips_unreadable.py +++ b/tests/unit/test_branch_fanout_skips_unreadable.py @@ -14,12 +14,12 @@ def _patch_readable(monkeypatch: pytest.MonkeyPatch, readable: set[str]) -> None: - async def row_in_scope(org: str, ns: str, role: object, *, hides_answer=True) -> bool: + async def row_reach(org: str, ns: str, role: object) -> bool: return ns in readable import server.auth.authz as authz - monkeypatch.setattr(authz, "row_in_scope", row_in_scope) + monkeypatch.setattr(authz, "row_reach", row_reach) @pytest.mark.asyncio diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index 820a4e13a0a..93f3937bb38 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -1413,6 +1413,53 @@ async def _runner(req): assert degradations.current() == [] +@pytest.mark.asyncio +async def test_a_fix_that_falls_back_every_night_fails_each_pass() -> None: + """A fix that is never written must not go unseen: each pass in which its read falls + back twice notes a failure, so the worker's streak builds and alerts; a fix whose + second read answers whole is no failure.""" + from types import SimpleNamespace + + from server.observability import degradations + from server.workers import pass_context + + async def _always(req): + degradations.partial("code_index", "backport_ledger_dropped", ConnectionError("x")) + return _out(req.pr_number) + + reads: list[int] = [] + + async def _once(req): + reads.append(req.pr_number) + if len(reads) % 2: + degradations.partial("code_index", "backport_ledger_dropped", ConnectionError("x")) + return _out(req.pr_number) + + async def _pass(runner) -> pass_context.PassContext: + ctx = pass_context.begin("code_backport_gaps") + degradations.begin() + try: + await wk.compute_fix( + SimpleNamespace(org="acme", namespace=NS), + 7, + {}, + runner=runner, + result=wk.BackportGapsResult(), + stamp=NOW, + version=1, + ) + finally: + pass_context.clear() + return ctx + + nights = [await _pass(_always) for _ in range(2)] + assert [(c.count, c.failures[0][:2]) for c in nights] == [ + (1, ("code_backport_gaps:#7", "FellBack")) + ] * 2 + assert "backport_ledger_dropped" in nights[0].failures[0][2] + assert (await _pass(_once)).count == 0 + + async def test_a_fix_that_fell_back_is_read_again_only_within_the_pass_budget() -> None: """A fallback is often a timed-out leg: the second read that answers whole writes the fix's rows; a pass already past its budget does not read it again.""" diff --git a/tests/unit/test_code_blame_range.py b/tests/unit/test_code_blame_range.py index d7816c48626..df6c233ad0d 100644 --- a/tests/unit/test_code_blame_range.py +++ b/tests/unit/test_code_blame_range.py @@ -542,10 +542,10 @@ async def _recorded_state(org: str, ns: str) -> dict[str, dict[str, Any]]: repo.all_state = _recorded_state readable = {"code-clickhouse-26-3"} - async def _only(org: str, ns: str, role: Any, *, hides_answer: bool = True) -> bool: + async def _only(org: str, ns: str, role: Any) -> bool: return ns in readable - monkeypatch.setattr(authz, "row_in_scope", _only) + monkeypatch.setattr(authz, "row_reach", _only) repo.rows[NS] = [ { "pr_number": 100, @@ -705,11 +705,11 @@ async def test_a_window_end_outside_the_indexed_head_does_not_resolve(wired, mon async def _is_ancestor(git_dir: str, ancestor: str, descendant: str, **_kw: Any) -> bool: return ancestor != later or descendant == other_head - async def _only(org: str, ns: str, role: Any, *, hides_answer: bool = True) -> bool: + async def _only(org: str, ns: str, role: Any) -> bool: return ns in readable monkeypatch.setattr(gitrepo, "is_ancestor", _is_ancestor) - monkeypatch.setattr(authz, "row_in_scope", _only) + monkeypatch.setattr(authz, "row_reach", _only) commit_coverage.reset() base = {"stage": "last_touched", "org": ORG, "namespace": NS, "path": PATH} lines = {"start_line": 10, "end_line": 12} @@ -755,11 +755,11 @@ async def test_the_default_window_start_is_a_cut_this_namespaces_head_contains( async def _is_ancestor(git_dir: str, ancestor: str, descendant: str, **_kw: Any) -> bool: return ancestor != BASE or descendant == other_head - async def _all(org: str, ns: str, role: Any, *, hides_answer: bool = True) -> bool: + async def _all(org: str, ns: str, role: Any) -> bool: return True monkeypatch.setattr(gitrepo, "is_ancestor", _is_ancestor) - monkeypatch.setattr(authz, "row_in_scope", _all) + monkeypatch.setattr(authz, "row_reach", _all) commit_coverage.reset() out = await h.handle_code_blame_range( CodeBlameRangeInput( diff --git a/tests/unit/test_code_first_build.py b/tests/unit/test_code_first_build.py index e558e0d5b1a..7555a3d2dbd 100644 --- a/tests/unit/test_code_first_build.py +++ b/tests/unit/test_code_first_build.py @@ -465,10 +465,10 @@ def _readable(monkeypatch: pytest.MonkeyPatch, *namespaces: str) -> None: """The caller may read these namespaces besides the one it addressed.""" from server.auth import authz - async def _in_scope(org, ns, role, *, hides_answer=True): + async def _reach(org, ns, role): return ns in namespaces - monkeypatch.setattr(authz, "row_in_scope", _in_scope) + monkeypatch.setattr(authz, "row_reach", _reach) def _answer(out: Any) -> dict[str, Any]: diff --git a/tests/unit/test_code_result_lessons.py b/tests/unit/test_code_result_lessons.py index 3942047a356..3fb2c7c7366 100644 --- a/tests/unit/test_code_result_lessons.py +++ b/tests/unit/test_code_result_lessons.py @@ -601,7 +601,7 @@ async def test_a_namespace_the_caller_cannot_read_is_never_read( check), only the role check faked.""" from server.auth import authz - async def _in_scope(org: str, ns: str, role: Any, *, hides_answer: bool = True) -> bool: + async def _reach(org: str, ns: str, role: Any) -> bool: return ns in {"mem-home", "code-repo"} calls: list[dict[str, Any]] = [] @@ -612,7 +612,7 @@ async def _read( calls.append({"nss": nss, "trunk": trunk}) return path_lessons.Lessons([]) - monkeypatch.setattr(authz, "row_in_scope", _in_scope) + monkeypatch.setattr(authz, "row_reach", _reach) monkeypatch.setattr("server.auth.context.current_auth", lambda: object()) monkeypatch.setattr("server.code.app.memory_links.trunk_namespace", _trunk) monkeypatch.setattr("server.identity.app.request_scope.request_narrowed", lambda: False) @@ -1091,3 +1091,79 @@ async def test_unlimited_lessons_keep_all_selected_rows(monkeypatch: pytest.Monk ] found = await _lessons(monkeypatch, {"a.py": rows}, ["a.py"], budget=0) assert {row["memory_key"] for row in found} == {str(i) for i in range(8)} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("other_file", ["slow", "failing"]) +@pytest.mark.parametrize("bound", ["fixed", "deadline"]) +async def test_a_file_whose_lessons_are_missing_is_noted_unless_the_deadline_cut_it( + monkeypatch: pytest.MonkeyPatch, other_file: str, bound: str +) -> None: + """A failed file read is noted; a slow one is noted when the fixed bound cut it (the + store answered slowly), not when what was left of the call's deadline did.""" + from server.observability import degradations + + async def _nss(org: str, code_ns: str, extra: list[str]) -> list[str]: + return ["code-repo"] + + async def _rows(inp: Any) -> tuple[list[dict[str, Any]], bool]: + if inp.path == "a.py": + return [_hit("notes/known", state="fresh")], False + if other_file == "failing": + raise RuntimeError("the other file's read failed") + await asyncio.sleep(5) + raise AssertionError("the unfinished read must be cancelled") + + monkeypatch.setattr(code_plane_reads, "lesson_namespaces", _nss) + monkeypatch.setattr("server.code.app.memory_links.trunk_namespace", _trunk) + monkeypatch.setattr("server.identity.app.request_scope.request_narrowed", lambda: False) + monkeypatch.setattr(path_lessons, "listing_rows", _rows) + started = time.monotonic() + if bound == "fixed": + monkeypatch.setattr(settings, "code_enrich_timeout_s", 0.05) + inp = _input(deadline_ms=0) + else: + monkeypatch.setattr(settings, "code_enrich_timeout_s", 5.0) + inp, started = _input(deadline_ms=1000), started - 0.9 # about 0.1 s left + degradations.begin() + + found = await result_lessons.lessons_for(inp, ["a.py", "b.py"], started) + + assert [row["memory_key"] for row in found.rows] == ["notes/known"] + noted = { + "failing": ["code_lessons: file_lessons_dropped (RuntimeError)"], + "slow": ["code_lessons: file_lessons_dropped (TimeoutError)"] if bound == "fixed" else [], + }[other_file] + assert degradations.current() == noted + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cut_noted", [True, False]) +async def test_a_lesson_path_read_cut_is_noted_only_within_the_fixed_bound( + monkeypatch: pytest.MonkeyPatch, cut_noted: bool +) -> None: + """Placing files with a matched lesson first takes a share of the read's bound: a cut + within the fixed bound is the store's slowness and noted, one within the call's + deadline is not. The files keep their order either way.""" + from server.observability import degradations + + async def _slow(*a: Any, **kw: Any) -> set[str]: + await asyncio.sleep(5) + return {"b.py"} + + monkeypatch.setattr(path_lessons, "paths_with_matched_links", _slow) + monkeypatch.setattr(settings, "code_result_lessons_paths", 1) + degradations.begin() + top = await result_lessons._scoped_lesson_paths( + "acme", + ["code-repo"], + "code-repo", + ["a.py", "b.py"], + {"b.py": {"f"}}, + None, # type: ignore[arg-type] + 0.03, + cut_noted, + ) + assert top == ["a.py"] + noted = ["code_index: enrichment_skipped (TimeoutError)"] if cut_noted else [] + assert degradations.current() == noted diff --git a/tests/unit/test_code_search_cursor.py b/tests/unit/test_code_search_cursor.py index 0bcd1806090..548f4ab3567 100644 --- a/tests/unit/test_code_search_cursor.py +++ b/tests/unit/test_code_search_cursor.py @@ -300,6 +300,22 @@ def test_page_two_is_a_point_read_with_zero_embedding_calls( assert nxt["o"] == 5 and nxt["r"] == _fixture_pool_id(inp, "run1") +def test_a_pool_row_without_notes_serves_its_page_whole(monkeypatch: pytest.MonkeyPatch) -> None: + """A pool row a previous build parked has no `degraded` key: its page is served and + names no note.""" + from server.observability import degradations + + inp = _inp(top_k=2) + cursor = _fixture_search_cursor(inp, offset=2) + payload = _payload(6) + assert "degraded" not in payload + _drive(monkeypatch, inp, {"payload": payload, "indexed_commit": "", "created_at": None}) + degradations.begin() + out = asyncio.run(h.handle_code_search(inp.model_copy(update={"cursor": cursor}))) + assert [u.unit_id for u in out.results] == ["c2", "c3"] + assert degradations.current() == [] + + def test_last_page_has_no_cursor(monkeypatch: pytest.MonkeyPatch) -> None: inp = _inp(top_k=5) cursor = _fixture_search_cursor(inp, offset=4) diff --git a/tests/unit/test_code_verify_citations_resolve.py b/tests/unit/test_code_verify_citations_resolve.py index 312ced6ccbb..84021d8128d 100644 --- a/tests/unit/test_code_verify_citations_resolve.py +++ b/tests/unit/test_code_verify_citations_resolve.py @@ -368,11 +368,11 @@ def test_base_namespaces_are_read_only_when_the_caller_may_read_them() -> None: from server.code.app import citations as h from server.core.errors import AuthInsufficientError - async def _only_n(org: str, ns: str, role: Any, *, hides_answer: bool = True) -> bool: + async def _only_n(org: str, ns: str, role: Any) -> bool: return ns == "n" repo = _repo() - with patch.object(authz, "row_in_scope", _only_n): + with patch.object(authz, "row_reach", _only_n): with pytest.raises(AuthInsufficientError): _run(repo, "#101", base_namespace="base") assert not any(c[1] == "base" for c in repo.calls), "refused before any base read" diff --git a/tests/unit/test_degradations.py b/tests/unit/test_degradations.py index 0e39ef3ab43..038e117ca59 100644 --- a/tests/unit/test_degradations.py +++ b/tests/unit/test_degradations.py @@ -78,6 +78,28 @@ def test_a_unit_reads_only_its_own_notes_and_the_request_still_names_them(): assert D.current() == ["rerank: input_order_kept (x)", "code_index: fan_in_dropped (y)"] +@pytest.mark.asyncio +async def test_a_unit_in_gathered_child_tasks_lists_its_notes_in_the_parent(): + """A task runs in a copy of the context that holds the request's list: each child's + unit reads only its own notes, and leaves them in the request's list.""" + D.begin() + D.partial("rerank", "input_order_kept", "x") + + async def child(name: str) -> list[str]: + with D.unit(): + await asyncio.sleep(0) + D.partial("code_index", f"{name}_dropped", "y") + return D.current() + + own = await asyncio.gather(child("a"), child("b")) + assert own == [["code_index: a_dropped (y)"], ["code_index: b_dropped (y)"]] + assert D.current() == [ + "rerank: input_order_kept (x)", + "code_index: a_dropped (y)", + "code_index: b_dropped (y)", + ] + + @pytest.mark.asyncio async def test_requests_are_isolated_by_contextvar(): D.begin() diff --git a/tests/unit/test_memory_code_plane_reads.py b/tests/unit/test_memory_code_plane_reads.py index 6908910497a..a5c77a5d515 100644 --- a/tests/unit/test_memory_code_plane_reads.py +++ b/tests/unit/test_memory_code_plane_reads.py @@ -452,10 +452,10 @@ async def test_the_lesson_scope_is_the_callers_own_the_teams_and_the_readable_ex from server.auth.jwt import AuthInfo from server.operations.base import Role - async def readable(org, ns, role, *, hides_answer=True): + async def readable(org, ns, role): return ns not in ("secret", "code-a") - monkeypatch.setattr(authz, "row_in_scope", readable) + monkeypatch.setattr(authz, "row_reach", readable) monkeypatch.setattr("server.code.app.memory_links.trunk_namespace", lambda org, n: "code-a") set_current_auth( AuthInfo( @@ -485,10 +485,10 @@ async def test_lessons_keep_the_named_order_and_read_nothing_when_none_is_readab hidden = {"secret"} - async def readable(org, ns, role, *, hides_answer=True): + async def readable(org, ns, role): return ns not in hidden - monkeypatch.setattr(authz, "row_in_scope", readable) + monkeypatch.setattr(authz, "row_reach", readable) monkeypatch.setattr(memory_links, "trunk_namespace", lambda org, n: "code-a") nss = await code_plane_reads.lesson_namespaces("o", "code-a-26-8", ["bob", "secret", "alice"]) assert nss == [settings.default_namespace, "bob", "alice", "code-a"] diff --git a/tests/unit/test_memory_search_handler_gates.py b/tests/unit/test_memory_search_handler_gates.py index a0d47ff97be..fdd492dd898 100644 --- a/tests/unit/test_memory_search_handler_gates.py +++ b/tests/unit/test_memory_search_handler_gates.py @@ -1138,3 +1138,32 @@ async def store_page(ch: Any, **kw: Any) -> str: assert out.next_page and parked["hits"] assert parked["degraded"] == ["memory.search: lexical_leg_dropped (DatabaseError)"] assert "memory.search: tags_unread (TimeoutError)" in degradations.current() + + +async def test_a_parked_page_keeps_the_term_legs_note(search_env, monkeypatch) -> None: + """The term leg joins the pool before its tail is parked: when its read fails, the + definitions it would have placed are missing from every page, so the note is parked + with the tail.""" + import asyncio + import json + + from server.memory.app import search_pages + from server.memory.app.search import term_leg + from server.observability import degradations + + parked: dict[str, Any] = {} + + async def failed_read() -> Any: + raise ConnectionError("x") + + async def store_page(ch: Any, **kw: Any) -> str: + parked.update(json.loads(kw["content"])) + return "page/abc" + + monkeypatch.setattr(term_leg, "launch", lambda *a, **k: asyncio.ensure_future(failed_read())) + monkeypatch.setattr(search_pages, "store_page", store_page) + search_env.hits = [_svc_hit(k, sim=s) for k, s in (("a", 0.9), ("b", 0.8), ("c", 0.7))] + degradations.begin() + out = await _run(search_env, top_k=1, paging=True) + assert out.next_page and parked["hits"] + assert parked["degraded"] == ["memory.search: term_definitions_withheld (ConnectionError)"] diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 503ba345289..fe8a8c175bc 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -79,7 +79,7 @@ async def test_a_healthy_deployment_answers_ok_with_no_incident(monkeypatch) -> out = await _incidents() - assert (out.status, out.incidents) == ("ok", []) + assert (out.status, out.incidents, out.requests) == ("ok", [], "read") assert out.window_minutes == settings.ops_incidents_window_minutes assert degradations.current() == [] (sli,) = ch.statements("sli_minute") @@ -216,6 +216,7 @@ def _down(sql, params): out = await _incidents() assert [(i.kind, i.subject) for i in out.incidents] == [("readiness", "migrations")] + assert out.requests == "unread" # `ok` would not have covered the org's calls notes = degradations.current() assert [n.split(" (")[0] for n in notes] == [ "ops.incidents: workers_unread", @@ -277,8 +278,9 @@ async def test_only_a_caller_that_reads_the_org_whole_reads_its_request_counts( ) -> None: """The rollup keeps no namespace or user: a member's `*` token, an org admin narrowed to some namespaces or pinned to one user, a token an org admin delegated (capped at - admin, since `org_admin` is never delegated), an org-wide token that names no org, and - no token where one is required read no counts.""" + admin, since `org_admin` is never delegated, flat or per namespace), an org-wide token + that names no org, and no token where one is required read no counts, and each answer + says so in `requests`.""" import time from server.auth.delegation import delegate @@ -297,19 +299,35 @@ async def test_only_a_caller_that_reads_the_org_whole_reads_its_request_counts( ) child = verify_token(minted.mint("sa:bot")) assert child.namespaces == ("*",) and child.roles == (Role.ADMIN,) - - member = await _incidents(auth=_token()) - delegated = await _incidents(auth=child) - narrowed = await _incidents(auth=_token(namespaces=("team",), roles=admin)) - pinned = await _incidents(auth=_token(roles=admin, read_scope="own_user", read_user_id="ada")) - await _incidents(org="*", auth=_token(org="*", roles=admin)) - await _incidents(org="", auth=_token(org="*", roles=admin)) - await _incidents(auth=None) + # A per-namespace child takes its creator's grant on each namespace it names. + ch.on("loom.namespace_grants", [{"role": "admin"}]).on("loom.namespaces", []) + minted = await delegate( + parent, + org="acme", + requested={"team": None, "ops": None}, + scoped=True, + ttl_seconds=None, + is_service_account=True, + ) + per_namespace = verify_token(minted.mint("sa:bot2")) + assert per_namespace.has_ns_roles() and per_namespace.best_ns_role() == Role.ADMIN + + outs = [ + await _incidents(auth=_token()), # a member + await _incidents(auth=child), + await _incidents(auth=per_namespace), + await _incidents(auth=_token(namespaces=("team",), roles=admin)), + await _incidents(auth=_token(roles=admin, read_scope="own_user", read_user_id="ada")), + await _incidents(org="*", auth=_token(org="*", roles=admin)), + await _incidents(org="", auth=_token(org="*", roles=admin)), + await _incidents(auth=None), + ] assert ch.statements("sli_minute") == [] - assert member.incidents == delegated.incidents == narrowed.incidents == pinned.incidents == [] + assert [(o.incidents, o.requests) for o in outs] == [([], "not_permitted")] * len(outs) + assert degradations.current() == [] whole = await _incidents() - assert [i.subject for i in whole.incidents] == ["code"] + assert [i.subject for i in whole.incidents] == ["code"] and whole.requests == "read" @pytest.mark.asyncio @@ -317,18 +335,31 @@ async def test_an_org_admin_with_a_restricted_namespace_hidden_reads_no_counts( monkeypatch, ) -> None: """The counts would include a restricted namespace the admin holds no grant for; when - the restricted set cannot be read, none are read and the answer says so.""" + the restricted set, or a restricted namespace's grant, cannot be read, none are read + and the answer says so.""" ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 1618, "server_errors": 1618}]) hidden = AsyncMock(return_value=["code-secret"]) monkeypatch.setattr("server.auth.context.restricted_namespaces_hidden_from", hidden) - assert (await _incidents()).incidents == [] + out = await _incidents() + assert (out.incidents, out.requests) == ([], "not_permitted") assert degradations.current() == [] hidden.return_value = ["*"] - assert (await _incidents()).incidents == [] - assert ch.statements("sli_minute") == [] + out = await _incidents() + assert (out.incidents, out.requests) == ([], "unread") assert degradations.current() == ["ops.incidents: requests_unread (ClassificationUnavailable)"] + async def _unverified(org: str) -> list[str]: + degradations.partial("identity", "restricted_unverified") + return ["code-secret"] + + degradations.begin() + monkeypatch.setattr("server.auth.context.restricted_namespaces_hidden_from", _unverified) + out = await _incidents() + assert (out.incidents, out.requests) == ([], "unread") + assert degradations.current() == ["identity: restricted_unverified"] + assert ch.statements("sli_minute") == [] + def test_any_viewer_polls_it_and_it_reads_no_namespace() -> None: op = OPERATIONS_BY_NAME["ops.incidents"] @@ -350,12 +381,16 @@ def transports(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: from server.transport import http as http_mod from server.transport import mcp_tools - tokens = {"acme": _token(), "acme-team": _token(namespaces=("team",))} + tokens = { + "acme": _token(), + "acme-team": _token(namespaces=("team",)), + "acme-admin": ORG_WIDE, + } ran: list[str] = [] async def _handler(inp: OpsIncidentsInput) -> OpsIncidentsOutput: ran.append(inp.org) - return OpsIncidentsOutput(status="ok", window_minutes=15) + return await handle_ops_incidents(inp) def _verify(token: str, *, secret: str | None = None) -> AuthInfo: if token not in tokens: @@ -386,6 +421,7 @@ async def _noop(*_a: Any, **_k: Any) -> None: http_app.include_router(http_mod.build_router()) mcp_app = FastAPI() mcp.attach(mcp_app) + _ch(monkeypatch) return {"http": TestClient(http_app), "mcp": TestClient(mcp_app), "ran": ran} @@ -433,3 +469,31 @@ def test_a_body_without_org_polls_the_tokens_org(transports: dict[str, Any]) -> ) assert r.status_code == 200, r.text assert transports["ran"] == ["acme", "acme"] + + +def test_loom_op_reaches_it_and_every_answer_says_whether_the_counts_were_read( + transports: dict[str, Any], +) -> None: + """Off the default listing, a client reaches it through `loom_op`; a member's answer + says its `ok` does not cover the org's calls, an org admin's that it does.""" + + def _loom_op(who: str) -> dict[str, Any]: + body = { + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "loom_op", + "arguments": {"op": "ops.incidents", "arguments": {"org": "acme"}}, + }, + } + r = transports["mcp"].post("/mcp", json=body, headers={"Authorization": f"Bearer {who}"}) + assert r.status_code == 200, r.text + return dict(r.json()["result"]) + + member, admin = _loom_op("acme"), _loom_op("acme-admin") + assert member["isError"] is False and admin["isError"] is False + assert member["structuredContent"]["requests"] == "not_permitted" + assert admin["structuredContent"]["requests"] == "read" + assert _http(transports, "acme", "acme").json()["requests"] == "not_permitted" + assert transports["ran"] == ["acme", "acme", "acme"] diff --git a/tests/unit/test_request_sli.py b/tests/unit/test_request_sli.py index 2e3fa23e383..c9e2daa8762 100644 --- a/tests/unit/test_request_sli.py +++ b/tests/unit/test_request_sli.py @@ -1197,21 +1197,31 @@ def test_only_answers_whole_without_the_namespace_leave_an_unverified_refusal_un namespace (one Loom adds on its own), the call filters a listing the caller did not scope, or another way in already admits the caller. Marking is the default, so a new call site counts an outage; this pins - the opt-outs by file and function, and whether each is unconditional.""" + the opt-outs by file and function, and whether each is unconditional. A + direct `row_reach` or `restricted_verdict` call outside `authz` marks nothing + unless its function calls `note_answered_unverified`, on some path.""" import ast from server.core.paths import REPO_ROOT + def _name(call: ast.Call) -> str: + return getattr(call.func, "id", getattr(call.func, "attr", "")) + unmarked: set[tuple[str, str, str]] = set() for path in (REPO_ROOT / "server").rglob("*.py"): tree = ast.parse(path.read_text()) + rel = str(path.relative_to(REPO_ROOT)) for fn in ast.walk(tree): if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)): continue - for call in ast.walk(fn): - if not isinstance(call, ast.Call): + calls = [c for c in ast.walk(fn) if isinstance(c, ast.Call)] + marks = any(_name(c) == "note_answered_unverified" for c in calls) + for call in calls: + name = _name(call) + if name in {"row_reach", "restricted_verdict"}: + if rel != "server/auth/authz.py": # where they are defined and wrapped + unmarked.add((rel, fn.name, "conditional" if marks else "never")) continue - name = getattr(call.func, "id", getattr(call.func, "attr", "")) if name not in { "row_in_scope", "_in_scope", @@ -1226,7 +1236,6 @@ def test_only_answers_whole_without_the_namespace_leave_an_unverified_refusal_un for kw in call.keywords: if kw.arg != "hides_answer": continue - rel = str(path.relative_to(REPO_ROOT)) if isinstance(kw.value, ast.Name) and kw.value.id == "hides_answer": continue # a gate passing its caller's choice through if not isinstance(kw.value, ast.Constant): @@ -1237,13 +1246,23 @@ def test_only_answers_whole_without_the_namespace_leave_an_unverified_refusal_un assert unmarked == { # Namespaces Loom adds to the answer on its own. ("server/code/app/answers_cache.py", "reuse_allowed", never), + # ...whose grant, when it cannot be read, is named in `degraded` instead + # (`identity: _unverified`, no namespace). ("server/code/app/search_fanout.py", "readable_subset", never), ("server/memory/app/code_link_reads.py", "readable_namespaces", never), + ("server/code/app/repo_scope.py", "readable_repo_namespace", never), + ("server/code/app/answers.py", "_inject_memory_context", never), + ("server/memory/app/code_grounding.py", "_authorized_code_target", never), + ("server/code/app/symbol/symbol.py", "_dependency_presence", never), + # (a listing the caller did not scope; an unread restricted set marks) + ("server/auth/context.py", "restricted_namespaces_hidden_from", cond), + # An id's holder or an in-use name: an unverified verdict marks. + ("server/memory/app/id_namespace.py", "namespace_for_id", cond), + ("server/identity/app/registration.py", "refused_as_in_use", cond), # The wording of a refusal another check decided. ("server/memory/app/decision_extract.py", "_readable_names", never), ("server/tracker/app/dupcheck_fanout.py", "readable_tracker_namespaces", never), ("server/tracker/app/common.py", "linked_trackers", never), - ("server/auth/context.py", "restricted_namespaces_hidden_from", never), # (the ADMIN check refused the link; this picks 403 or NOT_A_TRACKER_NAMESPACE) ("server/code/app/repo_admin.py", "_tracker_or_refuse", never), # (the inbox is taken either way; this picks whether its owner is named) @@ -1270,6 +1289,78 @@ def test_only_answers_whole_without_the_namespace_leave_an_unverified_refusal_un } +@pytest.mark.parametrize("gate", ["readable_subset", "readable_namespaces", "restricted_hidden"]) +@pytest.mark.parametrize("unread", [True, False]) +def test_a_gate_over_namespaces_loom_adds_notes_a_grant_it_could_not_read( + monkeypatch, gate: str, unread: bool +) -> None: + """A namespace whose grant could not be read is left out like a refused one, and the + answer, smaller for it, says so in `degraded` without naming it; a plain refusal is + no note. Neither marks the request the server's.""" + from server.auth import authz, fail_closed + from server.auth import context as auth_context + from server.auth.jwt import AuthInfo + from server.code.app import search_fanout + from server.core import request_work + from server.memory.app import code_link_reads + from server.observability import degradations + + def _refuse(namespace: str) -> None: + if namespace == "mine": + return + e = PermissionError("refused") + e.unverified = namespace == "unread" # type: ignore[attr-defined] + raise e + + async def _check(auth: Any, *, namespace: str, **_: Any) -> None: + _refuse(namespace) + + async def _restricted(auth: Any, role: Any, org: str, namespace: str, grants: Any) -> None: + _refuse(namespace) + + names = ["mine", "theirs", *(["unread"] if unread else [])] + + class _Directory: + def restricted_code_namespaces(self, org: str) -> set[str]: + return set(names[:2]) + + async def restricted_set(self, org: str) -> list[str]: + return names[2:] + + monkeypatch.setattr(authz, "check_authorized", _check) + monkeypatch.setattr(authz, "_check_restricted", _restricted) + monkeypatch.setattr(auth_context, "directory", lambda: _Directory()) + eve = AuthInfo( + subject="eve", org="o", namespaces=("*",), roles=(Role.VIEWER,), is_service_account=False + ) + + async def _read() -> tuple[Any, list[str], bool]: + request_work.begin() + degradations.begin() + auth_context.set_current_auth(eve) + try: + if gate == "readable_subset": + answer: Any = (await search_fanout.readable_subset("o", names))[0] + elif gate == "readable_namespaces": + answer = sorted(await code_link_reads.readable_namespaces("o", set(names))) + else: + answer = sorted( + set(names) - set(await auth_context.restricted_namespaces_hidden_from("o")) + ) + finally: + auth_context.set_current_auth(None) + return answer, degradations.current(), fail_closed.answered_unverified() + + readable, noted, marked = asyncio.run(_read()) + note = { + "readable_subset": "identity: fanout_unverified", + "readable_namespaces": "identity: code_links_unverified", + "restricted_hidden": "identity: restricted_unverified", + }[gate] + assert readable == ["mine"] + assert noted == ([note] if unread else []) and not marked + + def test_a_task_op_refused_on_its_own_side_without_a_readable_grant_is_the_server_s( monkeypatch, ) -> None: diff --git a/tests/unit/test_ui_read_caches.py b/tests/unit/test_ui_read_caches.py index 7cbd93c90ff..832c2cafcdd 100644 --- a/tests/unit/test_ui_read_caches.py +++ b/tests/unit/test_ui_read_caches.py @@ -186,13 +186,14 @@ async def _publish(cfg: Any, st: Any) -> None: @pytest.mark.asyncio -@pytest.mark.parametrize("mirror", ["lacks_the_watermark", "unreadable"]) +@pytest.mark.parametrize("mirror", ["lacks_the_watermark", "unreadable", "tip_unread"]) async def test_a_lag_the_clone_cannot_count_is_noted_only_when_git_cannot_read_it( tmp_path, monkeypatch, mirror: str ) -> None: """A watermark the clone does not hold is an unknown lag (-1), a miss: no `degraded`, and the status is published. A mirror git cannot read is a failed read: noted, and - the status is not published.""" + the status is not published, whether the clone's tip was published or had to be read + from it.""" import asyncio import subprocess @@ -212,7 +213,7 @@ def git(*args: str) -> str: git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x") head = git("rev-parse", "HEAD") git_dir = repo / ".git" - if mirror == "unreadable": + if mirror != "lacks_the_watermark": git_dir = tmp_path / "not-a-repo" git_dir.mkdir() absent = "0123456789abcdef0123456789abcdef01234567" @@ -226,7 +227,8 @@ async def _status(c: Any) -> Any: async def _publish(c: Any, st: Any) -> None: published.append(c.namespace) - monkeypatch.setattr(index_status, "published_clone_head", lambda state, branch: head) + tip = "" if mirror == "tip_unread" else head # no clone_head row: git reads the tip + monkeypatch.setattr(index_status, "published_clone_head", lambda state, branch: tip) monkeypatch.setattr(index_status, "_repo_status", _status) monkeypatch.setattr(index_status, "_publish_status_snapshot", _publish) index_status.reset_repo_status_cache() @@ -235,7 +237,7 @@ async def _publish(c: Any, st: Any) -> None: st = await index_status._repo_status_cached(cfg) await asyncio.sleep(0) assert st.lags == {"git_head": -1} - if mirror == "unreadable": + if mirror != "lacks_the_watermark": assert [n.split(" (")[0] for n in degradations.current()] == ["git_mirror: lag_unknown"] assert published == [] else: From dd69b2718c56126d32b222bfd557b6f9675139fe Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 10:01:19 +0530 Subject: [PATCH 12/47] ops.incidents' request share leaves out its own polls; an unread registry notes The `read` class counted `ops.incidents` itself, so a client polling it through an outage diluted the failures it asked about and helped a quiet org clear the call floor. The request read now filters on `operation != 'ops.incidents'`. `loom_search`'s repository legs dropped silently when the registry was not read yet; they now note `identity: repo_registry_unread`. `restricted_hidden` returns whether a restricted grant could not be read, so `ops.incidents` no longer infers it from the notes inside a unit. The `deployment_scoped` reference row, the `memory.set_from_messages` `degraded` description and the dashboard's reason for leaving out the op match what the code does. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/operations.md | 2 +- docs/reference/operations/memory.md | 2 +- server/auth/context.py | 20 +++++++++++----- server/code/app/repo_scope.py | 5 ++-- server/insights/app/incidents.py | 10 ++------ server/insights/store/ops.py | 12 +++++++--- server/memory/api/models_bulk.py | 5 ++-- server/operations/dashboard.py | 2 +- tests/analyzer/shapes.txt | 2 +- tests/unit/test_ops_incidents.py | 15 ++++-------- tests/unit/test_ops_incidents_sql.py | 9 +++++-- tests/unit/test_repo_docs.py | 11 +++++++++ tests/unit/test_request_sli.py | 2 +- .../test_set_from_messages_fail_closed.py | 24 +++++++++++++++++++ 14 files changed, 82 insertions(+), 39 deletions(-) diff --git a/docs/reference/operations.md b/docs/reference/operations.md index caa6d7f40a5..eb6f6d7268b 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -25,7 +25,7 @@ carries: | `maturity` | `stable` or `experimental`. It decides the [MCP `all` listing](#mcp-all-listing), and `op_reach_census.py --check` fails a stable op nothing reaches. | | `budget_p99_ms`, `shape_budgets_p99_ms` | The target p99 latency, overall and per request shape. A successful call over budget emits a `budget.violated` event. | | `skip_namespace_authz` | The op acts _on_ a namespace (join, leave, register) rather than in one, or its target is one only the handler can resolve (an id, an erasure scope); the handler enforces its own rules. The role check still runs. | -| `deployment_scoped` | The op reads facts about the deployment (build, registry), not tenant data; a namespace-scoped token passes with its best role. | +| `deployment_scoped` | The op reads facts about the deployment (build, registry, incidents), and at most an org-wide aggregate its handler authorizes; a namespace-scoped token passes with its best role. | | `row_scoped` | The op is addressed by an org-wide id (`memory_id`, `erasure_id`, `pattern_id`). The handler authorizes the row's scope and hides a foreign row ([row-scoped operations](../architecture/security.md#row-scoped-operations)). | [Adding an operation](../development/adding-an-operation.md) walks through declaring one. diff --git a/docs/reference/operations/memory.md b/docs/reference/operations/memory.md index 81d89489151..83e649a8aec 100644 --- a/docs/reference/operations/memory.md +++ b/docs/reference/operations/memory.md @@ -2233,7 +2233,7 @@ Run LLM extraction on `messages` and write the extracted facts. | `pipeline_errors` | `list[str]` | Fail-open pipeline steps that logged-and-skipped (operator hook unreachable, fetch_existing failed, unknown step id, ...). | | `value_updates_linked` | `int` | Older memories this ingest marked superseded by a value update (memory.app.value_updates; 0 when detection is off). | | `stubbed_fields` | `list[str]` | Schema mode only: record_schema fields the extractor could not validate after its retries and wrote as null (never a fabricated value). | -| `degraded` | `list[str]` | Schema mode only: what the response skipped and why, e.g. the memory_records projection for a caller bounded to one user. | +| `degraded` | `list[str]` | What the response left out and why: the request's fallbacks, and in schema mode the projections it skipped. | | `deferred` | `bool` | defer=true: nothing extracted yet; `written` is empty and `queue_id` is the handle memory.extraction_status_mine (and memory.extraction_status) report on. | | `queue_id` | `str` | The queued batch's id for `memory.extraction_status_mine` and `memory.extraction_status`; '' when inline. | | `deferred_by` | `str` | "" (inline) \| "flag" (the caller passed defer=true) \| "allowlist" (the deployment's extraction_defer_agents chose for the caller) | diff --git a/server/auth/context.py b/server/auth/context.py index e037e3f8cec..993f8d38619 100644 --- a/server/auth/context.py +++ b/server/auth/context.py @@ -237,13 +237,19 @@ async def restricted_namespaces_hidden_from(org: str) -> list[str]: left out by `collection_clause`). Empty with auth disabled; `["*"]` when it cannot be told. One whose grant could not be read is hidden and noted (`identity: restricted_unverified`), naming no namespace.""" + return (await restricted_hidden(org))[0] + + +async def restricted_hidden(org: str) -> tuple[list[str], bool]: + """(`restricted_namespaces_hidden_from`'s list, whether a grant among them could not + be read), for a caller that answers differently when it could not tell.""" from server.auth.authz import restricted_verdict from server.observability import degradations from server.operations.base import Role auth = current_auth() if auth is None: - return [] + return [], False try: names = directory().restricted_code_namespaces(org) names |= set(await directory().restricted_set(org)) @@ -252,17 +258,18 @@ async def restricted_namespaces_hidden_from(org: str) -> list[str]: # trust, so the caller must see nothing of the org's namespaces, and # the request that hid it all is the server's (fail_closed). note_answered_unverified() - return ["*"] + return ["*"], False # A listing the caller did not scope: a namespace left out does not mark the request # the server's, and one whose grant could not be read is noted. - hidden = [] + hidden, unverified = [], False for ns in sorted(names): verdict = await restricted_verdict(auth, Role.VIEWER, org, ns) - if verdict is None: - degradations.partial("identity", "restricted_unverified") + unverified |= verdict is None if not verdict: hidden.append(ns) - return hidden + if unverified: + degradations.partial("identity", "restricted_unverified") + return hidden, unverified async def collection_clause(org: str, column: str = "namespace") -> tuple[str, dict[str, Any]]: @@ -387,6 +394,7 @@ async def resolve_org_scope(org: str, *, column: str = "namespace") -> OrgScopeF "reads_every_namespace", "resolve_my_namespaces", "resolve_org_scope", + "restricted_hidden", "restricted_namespaces_hidden_from", "rollup_member_namespaces", "set_current_auth", diff --git a/server/code/app/repo_scope.py b/server/code/app/repo_scope.py index f5c7937b534..45020521389 100644 --- a/server/code/app/repo_scope.py +++ b/server/code/app/repo_scope.py @@ -46,8 +46,9 @@ async def readable_repo_namespace(org: str, code_namespace: str) -> str: if verdict is None: degradations.partial("identity", "repo_gate_unverified") return ns if verdict else "" - except RegistryUnread: - return "" # unread: closed, and no gate failure worth a warning per request + except RegistryUnread as e: # unread: closed, and no warning per request + degradations.partial("identity", "repo_registry_unread", e) + return "" except Exception as e: # noqa: BLE001 — a gate that cannot check refuses degradations.partial("identity", "repo_gate_unchecked", e) # One line per scoped request while the grants read is down. diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 45001a1c301..c4193f1a177 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -166,11 +166,7 @@ async def _reads_org_calls(org: str) -> RequestsRead: narrowed or pinned token, a delegated one (never an org admin), or no token where one is required, is `not_permitted`; an unknown restricted set, or a restricted namespace whose grant could not be read, is `unread`.""" - from server.auth.context import ( - current_auth, - reads_every_namespace, - restricted_namespaces_hidden_from, - ) + from server.auth.context import current_auth, reads_every_namespace, restricted_hidden from server.identity.app.request_scope import request_narrowed auth = current_auth() @@ -178,9 +174,7 @@ async def _reads_org_calls(org: str) -> RequestsRead: return "not_permitted" if settings.auth_actually_required() else "read" if not reads_every_namespace(auth, org) or request_narrowed(): return "not_permitted" - with degradations.unit(): # its own note: a grant it could not read - hidden = await restricted_namespaces_hidden_from(org) - unverified = bool(degradations.current()) + hidden, unverified = await restricted_hidden(org) if hidden == ["*"]: # the restricted set is unread degradations.partial("ops.incidents", "requests_unread", "ClassificationUnavailable") return "unread" diff --git a/server/insights/store/ops.py b/server/insights/store/ops.py index 26e4ef3a80a..5303bd981a0 100644 --- a/server/insights/store/ops.py +++ b/server/insights/store/ops.py @@ -9,6 +9,10 @@ from server.core.repo_base import _CHClient, _default_client from server.observability.store.event_reads import MASKED_EVENTS +# not a setting: the op whose own polls a request share must not count, since a client +# polling it through an outage would dilute the failures it asks about +INCIDENTS_OP = "ops.incidents" + async def active_parts_by_table(*, ch: _CHClient | None = None) -> list[dict[str, Any]]: """The 20 loom tables with the most active parts, with their row counts.""" @@ -107,8 +111,9 @@ async def request_errors_by_class( org: str, minutes: int, *, ch: _CHClient | None = None ) -> list[dict[str, Any]]: """The org's requests and server-side failures per SLO class over the last - `minutes`, from the SLI rollup (`slo_class != ''` leaves out its resume marks). The - rollup trails the ledger by one to two minutes.""" + `minutes`, from the SLI rollup (`slo_class != ''` leaves out its resume marks), not + counting `ops.incidents`' own polls. The rollup trails the ledger by one to two + minutes.""" ch = ch or _default_client() return list( await ch.query_all( @@ -118,10 +123,11 @@ async def request_errors_by_class( WHERE slo_class != '' AND minute >= toStartOfMinute(now() - toIntervalMinute({minutes:UInt32})) AND org = {org:String} + AND operation != {polls:String} GROUP BY slo_class ORDER BY slo_class LIMIT 16 """, - params={"org": org, "minutes": int(minutes)}, + params={"org": org, "minutes": int(minutes), "polls": INCIDENTS_OP}, ) ) diff --git a/server/memory/api/models_bulk.py b/server/memory/api/models_bulk.py index 040a89c305c..b8cb5083b19 100644 --- a/server/memory/api/models_bulk.py +++ b/server/memory/api/models_bulk.py @@ -349,9 +349,8 @@ class MemorySetFromMessagesOutput(BaseModel): # after its retries and wrote as null (never a fabricated value). Empty # when every field validated or on the messages path. stubbed_fields: list[str] = Field(default_factory=list) - # Schema mode only: what the response skipped and why, e.g. the - # memory_records projection for a caller bounded to one user. Empty when - # nothing was skipped. + # What the response left out and why: the request's fallbacks, and in schema + # mode the projections it skipped. degraded: list[str] = Field(default_factory=list) # defer=true: nothing extracted yet; `written` is empty and `queue_id` is # the handle memory.extraction_status_mine (and memory.extraction_status) report on. diff --git a/server/operations/dashboard.py b/server/operations/dashboard.py index 4b72f1c49ef..f4ad7dbffee 100644 --- a/server/operations/dashboard.py +++ b/server/operations/dashboard.py @@ -177,7 +177,7 @@ def _named_once(*groups: dict[str, str]) -> dict[str, str]: "observe.crystallize", "observe.record", "ops.capabilities", - # polled by clients; only it carries the org's request failure share + # polled by clients; the dashboard shows deployment health on its own pages "ops.incidents", ), CLIENT_CALL, diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 70b3c2719b4..d7a32cb4f33 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -647,7 +647,6 @@ 49041bd47683 SELECT count() AS n FROM loom.entity_summaries FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} 492df45ef39b INSERT INTO loom.conversation_embeddings SELECT e.* EXCEPT (embedded, known) REPLACE (if(p.matched = ? AND e.known = ?, p.holder.?, e.agent) AS agent, if(p.matched = ? AND e.known = ?, p.holder.?, e.r 4967ddddb4bf ALTER TABLE loom.learnings_supporters DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync -4994bed5d69d SELECT slo_class, sum(requests) AS requests, sum(server_errors) AS server_errors FROM loom_telemetry.sli_minute WHERE slo_class != ? AND minute >= toStartOfMinute(now() - toIntervalMinute({minutes:UIn 49b4574ab213 SELECT concat(?, c.session_id, ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, c.content AS content_excerpt, toString(ss.session_date) AS created_at, toString(ss.session_date) AS valid_at 49bd450f5650 SELECT tag, count() AS rows FROM (SELECT arrayJoin(tags) AS tag FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND user_id != {id:String}) GROUP 49c788209c09 SELECT count() AS n FROM loom.documents FINAL WHERE org = {org:String} AND user_id = {uid:String} AND (superseded_at IS NULL OR (blob_path != ? AND blob_erased_at IS NULL)) @@ -1348,6 +1347,7 @@ 99b329fe464e SELECT agent, user_id, session_id, version, summary_text, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- NB: alias must NOT be `valid_at` — under the analyzer a -- SELECT alias 99bb0fb8f03c ALTER TABLE loom.session_summaries UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_m 99d86c8fa8ea SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g +99e205d8de95 SELECT slo_class, sum(requests) AS requests, sum(server_errors) AS server_errors FROM loom_telemetry.sli_minute WHERE slo_class != ? AND minute >= toStartOfMinute(now() - toIntervalMinute({minutes:UIn 99ebc0e5d139 SELECT agent, user_id, session_id, version, summary_text, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- NB: alias must NOT be `valid_at` — under the analyzer a -- SELECT alias 99ebe72c9d4f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 9a356be92fff SELECT path, commit_sha, run_at, lines, tests FROM loom.code_coverage_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND tombstoned_at IS NULL diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index fe8a8c175bc..e421ec34ea5 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -52,7 +52,7 @@ def _clean(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr(incidents, "_locks", {}) monkeypatch.setenv("LOOM_INSTANCE_LABEL", "deploy:web:blue") monkeypatch.setattr( - "server.auth.context.restricted_namespaces_hidden_from", AsyncMock(return_value=[]) + "server.auth.context.restricted_hidden", AsyncMock(return_value=([], False)) ) provider_health.reset() degradations.begin() @@ -338,26 +338,21 @@ async def test_an_org_admin_with_a_restricted_namespace_hidden_reads_no_counts( the restricted set, or a restricted namespace's grant, cannot be read, none are read and the answer says so.""" ch = _ch(monkeypatch, sli=[{"slo_class": "code", "requests": 1618, "server_errors": 1618}]) - hidden = AsyncMock(return_value=["code-secret"]) - monkeypatch.setattr("server.auth.context.restricted_namespaces_hidden_from", hidden) + hidden = AsyncMock(return_value=(["code-secret"], False)) + monkeypatch.setattr("server.auth.context.restricted_hidden", hidden) out = await _incidents() assert (out.incidents, out.requests) == ([], "not_permitted") assert degradations.current() == [] - hidden.return_value = ["*"] + hidden.return_value = (["*"], False) out = await _incidents() assert (out.incidents, out.requests) == ([], "unread") assert degradations.current() == ["ops.incidents: requests_unread (ClassificationUnavailable)"] - async def _unverified(org: str) -> list[str]: - degradations.partial("identity", "restricted_unverified") - return ["code-secret"] - degradations.begin() - monkeypatch.setattr("server.auth.context.restricted_namespaces_hidden_from", _unverified) + hidden.return_value = (["code-secret"], True) # its grant could not be read out = await _incidents() assert (out.incidents, out.requests) == ([], "unread") - assert degradations.current() == ["identity: restricted_unverified"] assert ch.statements("sli_minute") == [] diff --git a/tests/unit/test_ops_incidents_sql.py b/tests/unit/test_ops_incidents_sql.py index 28cef07c7ec..2087361ab99 100644 --- a/tests/unit/test_ops_incidents_sql.py +++ b/tests/unit/test_ops_incidents_sql.py @@ -75,6 +75,10 @@ def test_a_deployment_label_has_deploy_as_its_first_segment() -> None: (3, "interactive", "o2", "code.search", 50, 0), # another org's (3, "", "o1", "code.search", 7, 7), # a resume mark of the rollup (40, "batch", "o1", "code.search", 30, 30), # outside the window + (2, "read", "o1", "memory.get", 100, 15), + (2, "read", "o1", "ops.incidents", 180, 0), # a client's polls: not in the share + (2, "read", "o3", "memory.get", 10, 10), + (2, "read", "o3", "ops.incidents", 30, 0), # nor toward the call floor ] @@ -103,6 +107,7 @@ async def read(org: str) -> list[tuple[str, int, int]]: rows = await ops_store.request_errors_by_class(org, 15, ch=ch) # type: ignore[arg-type] return [(r["slo_class"], int(r["requests"]), int(r["server_errors"])) for r in rows] - assert await read("o1") == [("interactive", 1618, 1618)] + assert await read("o1") == [("interactive", 1618, 1618), ("read", 100, 15)] assert await read("o2") == [("interactive", 50, 0)] - assert await read("o3") == [] + assert await read("o3") == [("read", 10, 10)] + assert await read("o4") == [] diff --git a/tests/unit/test_repo_docs.py b/tests/unit/test_repo_docs.py index ae5215181ef..cd53862e637 100644 --- a/tests/unit/test_repo_docs.py +++ b/tests/unit/test_repo_docs.py @@ -219,6 +219,17 @@ async def unverified(*a, **k): assert await scoped(f"{ORG}/code-kj") == "" assert degradations.current() == ["identity: repo_gate_unverified"] + def unread(*a, **k): + raise repos.RegistryUnread("registry not read yet") + + # the registry is not read yet: closed, and the dropped legs are noted too + monkeypatch.setattr("server.code.app.repo_scope.trunk_namespace_of", unread) + degradations.begin() + assert await scoped(f"{ORG}/code-kj") == "" + assert degradations.current() == [ + "identity: repo_registry_unread (BACKEND_UNAVAILABLE: registry not read yet)" + ] + @pytest.mark.asyncio async def test_a_slow_repository_search_answers_nothing(monkeypatch) -> None: diff --git a/tests/unit/test_request_sli.py b/tests/unit/test_request_sli.py index c9e2daa8762..d4f76fc3e48 100644 --- a/tests/unit/test_request_sli.py +++ b/tests/unit/test_request_sli.py @@ -1255,7 +1255,7 @@ def _name(call: ast.Call) -> str: ("server/memory/app/code_grounding.py", "_authorized_code_target", never), ("server/code/app/symbol/symbol.py", "_dependency_presence", never), # (a listing the caller did not scope; an unread restricted set marks) - ("server/auth/context.py", "restricted_namespaces_hidden_from", cond), + ("server/auth/context.py", "restricted_hidden", cond), # An id's holder or an in-use name: an unverified verdict marks. ("server/memory/app/id_namespace.py", "namespace_for_id", cond), ("server/identity/app/registration.py", "refused_as_in_use", cond), diff --git a/tests/unit/test_set_from_messages_fail_closed.py b/tests/unit/test_set_from_messages_fail_closed.py index d39a96479ad..2a1cf4a8f1c 100644 --- a/tests/unit/test_set_from_messages_fail_closed.py +++ b/tests/unit/test_set_from_messages_fail_closed.py @@ -109,6 +109,30 @@ async def _pipeline_with_soft_errors(steps, state): ] +@pytest.mark.asyncio +async def test_a_fallback_of_a_plain_call_is_in_its_degraded( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Off schema mode the response names the request's fallbacks in `degraded` too.""" + import server.memory.app.extract.handler as mx + import server.memory.app.pipeline as pipe + from server.observability import degradations + from server.operations.registry import OPERATIONS_BY_NAME + from server.transport.arg_check import response_body + + _stub_projections(monkeypatch) + + async def _pipeline(steps, state): + degradations.partial("memory.set_from_messages", "existing_unread", "TimeoutError") + return state + + monkeypatch.setattr(pipe, "run_pipeline", _pipeline) + degradations.begin() + out = await mx.handle_memory_set_from_messages(_input()) + body = response_body(OPERATIONS_BY_NAME["memory.set_from_messages"], {}, out) + assert body["degraded"] == ["memory.set_from_messages: existing_unread (TimeoutError)"] + + @pytest.mark.asyncio @pytest.mark.parametrize("projected", [True, False]) async def test_schema_mode_surfaces_stubbed_fields( From d9395b1cf70fad4b750ceadb9ed26fdc0ba25efe Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 11:23:01 +0530 Subject: [PATCH 13/47] Tracker gates note a grant they could not read The binding gate read the grant through `row_in_scope(..., hides_answer=False)`, which turned an unreadable grant into a quiet refusal, and its except only logged. code.history, code.blame_range, code.symbol's history, code.bisect_candidates and memory.ask then answered without the tracker facts and named nothing. The gate now reads `row_reach`: an unverified refusal of a tracker Loom adds notes `identity: tracker_unverified`, one the caller named still marks the request, and a gate that raises notes `identity: tracker_gate_unchecked`. The duplicate check's fan-out, the test signal's churn namespace and a remote's indexed branches note the same way, and memory.ask notes a failed tracker facts read. The monitoring page and the incident settings' comments say `ops.incidents`' own calls are left out of the request share and the call floor. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 25 +++--- docs/reference/configuration.md | 4 +- loom.example.yaml | 9 +- schemas/loom-settings.schema.json | 4 +- server/code/app/repo_admin.py | 8 +- server/code/app/symbol/symbol.py | 4 +- server/memory/app/ask/records.py | 3 +- server/settings/catalog.py | 8 +- server/tracker/app/binding.py | 22 +++-- server/tracker/app/dupcheck_fanout.py | 33 +++++--- server/tracker/app/test_signal.py | 18 +++- tests/unit/test_code_repo_remote_branches.py | 2 +- tests/unit/test_code_repo_self_service.py | 16 +++- tests/unit/test_request_sli.py | 29 ++++--- tests/unit/test_tracker_binding.py | 87 ++++++++++++++++++-- tests/unit/test_tracker_binding_discovery.py | 2 +- tests/unit/test_tracker_binding_op.py | 4 +- tests/unit/test_tracker_dupcheck_fanout.py | 29 ++++++- tests/unit/test_tracker_multi_binding.py | 8 +- tests/unit/test_tracker_test_daily.py | 2 +- tests/unit/test_tracker_test_signal.py | 26 +++++- 21 files changed, 262 insertions(+), 81 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index e4da51e0317..788ce5d0977 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -150,20 +150,21 @@ first, at most 20: | `readiness` | a readiness check of this process fails, except `draining`: a process shutting down still answers what it started, and every deploy drains one | error when required, else warn | | `provider` | a provider's last call failed within `LOOM_OPS_INCIDENTS_WINDOW_MINUTES` (15); a later success clears it | warn | | `worker` | an enabled worker's last 3 or more passes failed in a row, the last within 6 hours, in this deployment's processes (`loom.worker_status` rows unlabelled or whose label's first `:` segment is `deploy`; an isolated or a bench server reads only its own label's) | warn | -| `requests` | at least `LOOM_OPS_INCIDENTS_ERROR_SHARE` (0.1) of one SLO class's calls in the org the call acts in failed on the server over the window, counted once the class has `LOOM_OPS_INCIDENTS_MIN_REQUESTS` (20) | error | +| `requests` | at least `LOOM_OPS_INCIDENTS_ERROR_SHARE` (0.1) of one SLO class's calls, other than `ops.incidents`' own, in the org the call acts in failed on the server over the window, counted once the class has `LOOM_OPS_INCIDENTS_MIN_REQUESTS` (20) | error | Request counts come from `loom_telemetry.sli_minute`, which trails the calls by about two -minutes and keeps no namespace or user. They are read for the org the call acts in, and -only by a caller that reads that org whole, as the org-wide rollups have it: a platform -admin, or an org admin of the org whose claim is `*`, reading whole namespaces, with no -restricted namespace of the org hidden from it. The counts include calls to collections -the caller cannot read: they name no collection. A member's token, an admin narrowed to -some namespaces or pinned to one user, a delegated token (never an org admin) and a `*` -token that names no org read none. The other kinds are deployment state, the same for every org: a readiness or -provider incident names the check or provider and an error's kind, as `/v1/health` does, -and a worker incident names a worker of any of the deployment's processes with its streak -and error kind, where `/v1/health?include=workers` shows only the answering process's -workers. Each ClickHouse source is read at most once every 5 seconds per process, +minutes and keeps no namespace or user. They leave out `ops.incidents`' own calls, so a +client polling it through an outage does not dilute the failures it asks about. They are +read for the org the call acts in, and only by a caller that reads that org whole, as the +org-wide rollups have it: a platform admin, or an org admin of the org whose claim is +`*`, reading whole namespaces, with no restricted namespace of the org hidden from it. The +counts include calls to collections the caller cannot read: they name no collection. A +member's token, an admin narrowed to some namespaces or pinned to one user, a delegated +token (never an org admin) and a `*` token that names no org read none. The other kinds +are deployment state, the same for every org: a readiness or provider incident names the +check or provider and an error's kind, as `/v1/health` does, and a worker incident names +a worker of any of the deployment's processes with its streak and error kind, where +`/v1/health?include=workers` shows only the answering process's workers. Each ClickHouse source is read at most once every 5 seconds per process, however many clients poll during an outage, and each read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A source that failed is named in the response's `degraded` while its failure is cached, and the other sources still answer. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index bb4714415e2..1294f37d840 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1714,8 +1714,8 @@ Telemetry, audit, tracing and the ops surface. | `LOOM_OPS_PROCEDURE_PLANE_RETENTION_WARN` | `float` | `0.5` | | Success retention (fraction) below which the `procedure_plane` check warns. | | `LOOM_OPS_PROCEDURE_PLANE_MIN_PAIRS` | `int` | `20` | | Pairs the `procedure_plane` check measures success retention over before its warning can fire. | | `LOOM_OPS_INCIDENTS_WINDOW_MINUTES` | `int` | `15` | | Minutes of history ops.incidents reads: a provider failure seen within them, and the caller's org's request failures over them. | -| `LOOM_OPS_INCIDENTS_ERROR_SHARE` | `float` | `0.1` | | Share (0-1) of the org's requests of one SLO class that failed on the server's side, over the window, at which ops.incidents lists a `requests` incident. | -| `LOOM_OPS_INCIDENTS_MIN_REQUESTS` | `int` | `20` | | Requests of one SLO class in the window before ops.incidents judges its share. | +| `LOOM_OPS_INCIDENTS_ERROR_SHARE` | `float` | `0.1` | | Share (0-1) of the org's requests of one SLO class, other than ops.incidents' own, that failed on the server's side over the window, at which ops.incidents lists a `requests` incident. | +| `LOOM_OPS_INCIDENTS_MIN_REQUESTS` | `int` | `20` | | Requests of one SLO class in the window, other than ops.incidents' own, before ops.incidents judges its share. | | `LOOM_AUDIT_VERIFIER_ENABLED` | `bool` | `True` | | Periodic re-hash of audit rows; a mismatch writes `audit.tamper_detected`. Per-row detection, not a hash chain (see server/observability/audit.py). | | `LOOM_AUDIT_VERIFIER_INTERVAL_SECONDS` | `int` | `3600` | | Seconds between audit verifier passes (row re-hash and checkpoint sealing). | | `LOOM_AUDIT_CHECKPOINT_WINDOW_SECONDS` | `int` | `3600` | | Length, seconds, of one audit window. Each closed window is sealed as a chained checkpoint once `audit_checkpoint_grace_seconds` old, and the last `audit_checkpoint_verify_windows` are recounted every pass: a short recount is a deletion, which per-row hashes cannot see. | diff --git a/loom.example.yaml b/loom.example.yaml index 9d46ecabd47..6e796157647 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -5049,12 +5049,13 @@ settings: # caller's org's request failures over them. [restart] # ops_incidents_window_minutes: 15 - # Share (0-1) of the org's requests of one SLO class that failed on the server's side, - # over the window, at which ops.incidents lists a `requests` incident. [restart] + # Share (0-1) of the org's requests of one SLO class, other than ops.incidents' own, + # that failed on the server's side over the window, at which ops.incidents lists a + # `requests` incident. [restart] # ops_incidents_error_share: 0.1 - # Requests of one SLO class in the window before ops.incidents judges its share. - # [restart] + # Requests of one SLO class in the window, other than ops.incidents' own, before + # ops.incidents judges its share. [restart] # ops_incidents_min_requests: 20 # Periodic re-hash of audit rows; a mismatch writes `audit.tamper_detected`. Per-row diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 3cab34bdb7c..964d3c01d48 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -6047,13 +6047,13 @@ "exclusiveMinimum": 0, "maximum": 1, "type": "number", - "description": "Share (0-1) of the org's requests of one SLO class that failed on the server's side, over the window, at which ops.incidents lists a `requests` incident." + "description": "Share (0-1) of the org's requests of one SLO class, other than ops.incidents' own, that failed on the server's side over the window, at which ops.incidents lists a `requests` incident." }, "ops_incidents_min_requests": { "default": 20, "minimum": 1, "type": "integer", - "description": "Requests of one SLO class in the window before ops.incidents judges its share." + "description": "Requests of one SLO class in the window, other than ops.incidents' own, before ops.incidents judges its share." }, "ops_incidents_window_minutes": { "default": 15, diff --git a/server/code/app/repo_admin.py b/server/code/app/repo_admin.py index 1301511055f..8d980818f85 100644 --- a/server/code/app/repo_admin.py +++ b/server/code/app/repo_admin.py @@ -45,6 +45,7 @@ ValidationError, caller_text, ) +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -233,13 +234,16 @@ async def _register( async def _indexed_branches(org: str, repo: str, git_remote: str) -> list[dict[str, str]]: """The branches of the repository already indexed in `org` (config + registry). The - namespace is named only where the caller may read it; elsewhere it is ''.""" + namespace is named only where the caller may read it; elsewhere it is ''. One whose + grant could not be read is '' too and noted (`identity: branch_namespace_unverified`).""" want = repo_key(repo, git_remote) out = [] for c in code_repos.configured_repos(): if c.org != org or repo_key(c.repo, c.git_remote) != want: continue - readable = await authz.row_in_scope(org, c.namespace, hides_answer=False) + readable = await authz.row_reach(org, c.namespace) + if readable is None: + degradations.partial("identity", "branch_namespace_unverified") out.append({"branch": c.git_branch, "namespace": c.namespace if readable else ""}) return sorted(out, key=lambda x: x["branch"]) diff --git a/server/code/app/symbol/symbol.py b/server/code/app/symbol/symbol.py index 0d05d248a9e..db52799876b 100644 --- a/server/code/app/symbol/symbol.py +++ b/server/code/app/symbol/symbol.py @@ -116,8 +116,8 @@ async def _dependency_presence( namespaces, the definition's presence per dependency the caller may read (the shared presence run, one deadline). Loom added those namespaces, so one the caller cannot read is left out unnamed; one whose grant could not be read is noted, unnamed, as a - possibly short answer. A location, a - symbol_id or an entry without dependencies asks nothing.""" + possibly short answer. A location, a symbol_id or an entry without dependencies asks + nothing.""" if input.symbol_id or not input.name or _parse_location(input.name): return [], {} from server.code.domain.index.repos import repo_for_namespace diff --git a/server/memory/app/ask/records.py b/server/memory/app/ask/records.py index c84edddc6d7..ba1f77a096b 100644 --- a/server/memory/app/ask/records.py +++ b/server/memory/app/ask/records.py @@ -34,7 +34,8 @@ async def _append_tracker_facts( if line: lines.append(line) keys.append(f"tracker_item:{tracker_ns}:{num}") - except Exception as e: # noqa: BLE001 — additive + except Exception as e: # noqa: BLE001 — additive: the answer stands without the facts + degradations.partial("memory.ask", "tracker_facts_dropped", e) logger.debug("memory.ask qa facts skipped: %s", e) diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 689e3c622ca..445ee196c7d 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -4465,10 +4465,12 @@ class ObservabilitySettings(BaseModel): # Minutes of history ops.incidents reads: a provider failure seen within them, and # the caller's org's request failures over them. ops_incidents_window_minutes: int = Field(default=15, ge=1, le=1440) - # Share (0-1) of the org's requests of one SLO class that failed on the server's - # side, over the window, at which ops.incidents lists a `requests` incident. + # Share (0-1) of the org's requests of one SLO class, other than ops.incidents' + # own, that failed on the server's side over the window, at which ops.incidents + # lists a `requests` incident. ops_incidents_error_share: float = Field(default=0.1, gt=0, le=1) - # Requests of one SLO class in the window before ops.incidents judges its share. + # Requests of one SLO class in the window, other than ops.incidents' own, before + # ops.incidents judges its share. ops_incidents_min_requests: int = Field(default=20, ge=1) # Periodic re-hash of audit rows; a mismatch writes `audit.tamper_detected`. # Per-row detection, not a hash chain (see server/observability/audit.py). diff --git a/server/tracker/app/binding.py b/server/tracker/app/binding.py index 6b9b6a67d62..288eb63ba26 100644 --- a/server/tracker/app/binding.py +++ b/server/tracker/app/binding.py @@ -269,20 +269,28 @@ async def _gated(org: str, code_namespace: str, ns: str, *, hides_answer: bool) """The binding gate for one linked tracker, as the current principal: a STANDARD one by whoever may read the code namespace, a RESTRICTED one (or one the tracker plane does not know) by its own two-factor gate. - Closed on any error.""" + Closed on any error. A refusal that could not be verified marks the request when + `hides_answer`, else is noted (`identity: tracker_unverified`), since the answer + lacks a tracker the caller may read; a gate that raised is noted too. Neither note + names the namespace.""" + from server.observability import degradations + try: - from server.auth.authz import row_in_scope + from server.auth.authz import row_reach + from server.auth.fail_closed import note_answered_unverified from server.operations.base import Role from server.tracker.domain.namespaces import tracker_namespace target = tracker_namespace(org, ns) standard = target is not None and not target.restricted - return bool( - await row_in_scope( - org, code_namespace if standard else ns, Role.VIEWER, hides_answer=hides_answer - ) - ) + verdict = await row_reach(org, code_namespace if standard else ns, Role.VIEWER) + if verdict is None and hides_answer: + note_answered_unverified() + elif verdict is None: + degradations.partial("identity", "tracker_unverified") + return bool(verdict) except Exception as e: # noqa: BLE001 — the binding gate fails closed on any error + degradations.partial("identity", "tracker_gate_unchecked", e) log.debug("qa binding authorization failed (closed): %s", e) return False diff --git a/server/tracker/app/dupcheck_fanout.py b/server/tracker/app/dupcheck_fanout.py index 3f4cecf9ab6..8b2ddd27350 100644 --- a/server/tracker/app/dupcheck_fanout.py +++ b/server/tracker/app/dupcheck_fanout.py @@ -34,8 +34,12 @@ async def _may_read_tracker( read only with a grant on itself; a standard one by whoever may read it or any code namespace bound to it. `hides_answer`: the caller named it (see `row_in_scope`). `operator`: the operator's repositories (`binding.operator_repositories`) when the - caller read them once for many trackers; None: `code_namespaces_linking` reads them.""" - from server.auth.authz import row_in_scope + caller read them once for many trackers; None: `code_namespaces_linking` reads them. + Refused where a grant could not be read and no other way admits: that marks the + request when `hides_answer`, else is noted (`identity: tracker_unverified`), unnamed.""" + from server.auth.authz import row_reach + from server.auth.fail_closed import note_answered_unverified + from server.observability import degradations from server.operations.base import Role from server.tracker.app.binding import code_namespaces_linking from server.tracker.domain.namespaces import tracker_namespace @@ -43,16 +47,21 @@ async def _may_read_tracker( target = tracker_namespace(org, ns) if target is None: return False - if await row_in_scope(org, ns, Role.VIEWER, hides_answer=hides_answer): - return True - if target.restricted: - return False - code = [c for c, kind in code_kinds.items() if kind == "code"] - # The org's links: a maintainer's, else the operator's map for its own repositories. - for code_ns in code_namespaces_linking(org, ns, code, operator=operator): - if await row_in_scope(org, code_ns, Role.VIEWER, hides_answer=hides_answer): - return True - return False + verdict = await row_reach(org, ns, Role.VIEWER) + if not verdict and not target.restricted: + code = [c for c, kind in code_kinds.items() if kind == "code"] + # The org's links: a maintainer's, else the operator's map for its own repositories. + for code_ns in code_namespaces_linking(org, ns, code, operator=operator): + linked = await row_reach(org, code_ns, Role.VIEWER) + if linked: + return True + if linked is None: + verdict = None + if verdict is None and hides_answer: + note_answered_unverified() + elif verdict is None: + degradations.partial("identity", "tracker_unverified") + return bool(verdict) async def readable_tracker_namespaces( diff --git a/server/tracker/app/test_signal.py b/server/tracker/app/test_signal.py index 42e1a75a390..58adcb8d233 100644 --- a/server/tracker/app/test_signal.py +++ b/server/tracker/app/test_signal.py @@ -57,16 +57,26 @@ async def _code_namespace_authorized(org: str, code_namespace: str) -> tuple[str return code_org, "", caller_text(e) if not ns: return code_org, "", "no code namespace configured" + from server.observability import degradations + try: - from server.auth.authz import row_in_scope + from server.auth.authz import row_reach + from server.auth.fail_closed import note_answered_unverified from server.operations.base import Role - # A code namespace the caller named holds part of the answer; the - # deployment's default only enriches it. + # A code namespace the caller named holds part of the answer, so an unverified + # refusal marks the request; the deployment's default only enriches it, so one + # is noted, unnamed. named = bool(code_namespace) - if not await row_in_scope(code_org, ns, Role.VIEWER, hides_answer=named): + verdict = await row_reach(code_org, ns, Role.VIEWER) + if verdict is None and named: + note_answered_unverified() + elif verdict is None: + degradations.partial("identity", "churn_unverified") + if not verdict: return code_org, ns, "unauthorized" except Exception as e: # noqa: BLE001 — closed + degradations.partial("identity", "churn_gate_unchecked", e) return code_org, ns, f"authorization failed: {type(e).__name__}" return code_org, ns, "" diff --git a/tests/unit/test_code_repo_remote_branches.py b/tests/unit/test_code_repo_remote_branches.py index 72443ddcb21..d8a4dd79476 100644 --- a/tests/unit/test_code_repo_remote_branches.py +++ b/tests/unit/test_code_repo_remote_branches.py @@ -150,7 +150,7 @@ async def _readable(org: str, ns: str, *a: Any, **k: Any) -> bool: monkeypatch.setattr(reg, "remote_branches", _remote) monkeypatch.setattr(reg, "refresh_db_repos", _refresh) monkeypatch.setattr(reg, "active_count", _count) - monkeypatch.setattr("server.auth.authz.row_in_scope", _readable) + monkeypatch.setattr("server.auth.authz.row_reach", _readable) monkeypatch.setattr( repos, "configured_repos", diff --git a/tests/unit/test_code_repo_self_service.py b/tests/unit/test_code_repo_self_service.py index 3be768c2a32..97c71b98439 100644 --- a/tests/unit/test_code_repo_self_service.py +++ b/tests/unit/test_code_repo_self_service.py @@ -1371,7 +1371,7 @@ async def _branches(repo: str, token: str, **_: Any) -> dict[str, Any]: async def _in_scope(org: str, ns: str, *a: Any, **k: Any) -> bool: return ns == "code-ch" - monkeypatch.setattr(authz, "row_in_scope", _in_scope) + monkeypatch.setattr(authz, "row_reach", _in_scope) out = await admin.handle_code_repo_remote_branches( NS(org=ORG, repo="https://github.com/clickhouse/ClickHouse.git", access_token="") ) @@ -1381,6 +1381,20 @@ async def _in_scope(org: str, ns: str, *a: Any, **k: Any) -> bool: ] assert "26.3" not in out.suggested + async def _unverified(org: str, ns: str, *a: Any, **k: Any) -> bool | None: + return True if ns == "code-ch" else None + + # a grant that could not be read: the namespace is not named, and the answer says so + from server.observability import degradations + + monkeypatch.setattr(authz, "row_reach", _unverified) + degradations.begin() + out = await admin.handle_code_repo_remote_branches( + NS(org=ORG, repo="https://github.com/clickhouse/ClickHouse.git", access_token="") + ) + assert out.indexed[0] == {"branch": "26.3", "namespace": ""} + assert degradations.current() == ["identity: branch_namespace_unverified"] + @pytest.mark.asyncio async def test_the_entry_not_the_namespace_name_is_what_refuses( diff --git a/tests/unit/test_request_sli.py b/tests/unit/test_request_sli.py index d4f76fc3e48..fd6f4e54db7 100644 --- a/tests/unit/test_request_sli.py +++ b/tests/unit/test_request_sli.py @@ -1254,20 +1254,16 @@ def _name(call: ast.Call) -> str: ("server/code/app/answers.py", "_inject_memory_context", never), ("server/memory/app/code_grounding.py", "_authorized_code_target", never), ("server/code/app/symbol/symbol.py", "_dependency_presence", never), + # (a remote's indexed branches, naming only namespaces the caller reads) + ("server/code/app/repo_admin.py", "_indexed_branches", never), # (a listing the caller did not scope; an unread restricted set marks) ("server/auth/context.py", "restricted_hidden", cond), - # An id's holder or an in-use name: an unverified verdict marks. - ("server/memory/app/id_namespace.py", "namespace_for_id", cond), - ("server/identity/app/registration.py", "refused_as_in_use", cond), - # The wording of a refusal another check decided. - ("server/memory/app/decision_extract.py", "_readable_names", never), + # The linked trackers, noted by the tracker gates (`identity: tracker_unverified`) + # unless the caller named the tracker's item or the namespace, which marks. + ("server/tracker/app/binding.py", "_gated", cond), + ("server/tracker/app/dupcheck_fanout.py", "_may_read_tracker", cond), ("server/tracker/app/dupcheck_fanout.py", "readable_tracker_namespaces", never), ("server/tracker/app/common.py", "linked_trackers", never), - # (the ADMIN check refused the link; this picks 403 or NOT_A_TRACKER_NAMESPACE) - ("server/code/app/repo_admin.py", "_tracker_or_refuse", never), - # (the inbox is taken either way; this picks whether its owner is named) - ("server/tasks/app/inboxes.py", "handle_inbox_register", never), - # A code answer the linked tracker only enriches. ("server/code/app/bisect_scan.py", "_linked_scan", never), ("server/code/app/blame.py", "_tracker_side", never), ("server/code/app/history.py", "_tracker_facts", never), @@ -1275,15 +1271,22 @@ def _name(call: ast.Call) -> str: ("server/memory/app/ask/records.py", "_append_tracker_facts", never), ("server/tracker/app/ask_route.py", "_searched_everywhere", never), ("server/tracker/app/ask_route.py", "qa_route_answer", never), - # ...unless the caller named the tracker's item or the namespace. ("server/code/app/bisect.py", "_handle_bisect", cond), + # (the default code namespace a test's churn reads: `identity: churn_unverified`) ("server/tracker/app/test_signal.py", "_code_namespace_authorized", cond), + # An id's holder or an in-use name: an unverified verdict marks. + ("server/memory/app/id_namespace.py", "namespace_for_id", cond), + ("server/identity/app/registration.py", "refused_as_in_use", cond), + # The wording of a refusal another check decided. + ("server/memory/app/decision_extract.py", "_readable_names", never), + # (the ADMIN check refused the link; this picks 403 or NOT_A_TRACKER_NAMESPACE) + ("server/code/app/repo_admin.py", "_tracker_or_refuse", never), + # (the inbox is taken either way; this picks whether its owner is named) + ("server/tasks/app/inboxes.py", "handle_inbox_register", never), # A task's owner side, which marks only where it alone refused. ("server/tasks/app/common.py", "_owner_check", never), # A listing the caller did not scope. ("server/tasks/app/inboxes.py", "handle_inbox_list", never), - # (a remote's indexed branches, naming only namespaces the caller reads) - ("server/code/app/repo_admin.py", "_indexed_branches", never), # One namespace of a tracker source: marked when the source is refused. ("server/tracker/app/sources.py", "_admits", never), } diff --git a/tests/unit/test_tracker_binding.py b/tests/unit/test_tracker_binding.py index b4890346a87..38bee5e871a 100644 --- a/tests/unit/test_tracker_binding.py +++ b/tests/unit/test_tracker_binding.py @@ -53,7 +53,7 @@ async def _scope(org, ns, role, *, hides_answer=True): seen.append((org, ns, role.name)) return ns == "tracker-clickhouse" - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) assert ( await b.authorized_tracker_namespace("clickhouse", "code-clickhouse-26-4") == "tracker-clickhouse" @@ -71,8 +71,12 @@ async def test_gate_failure_is_closed(bound, monkeypatch) -> None: async def _boom(org, ns, role, *, hides_answer=True): raise RuntimeError("down") - monkeypatch.setattr(authz, "row_in_scope", _boom) + monkeypatch.setattr(authz, "row_reach", _boom) + from server.observability import degradations + + degradations.begin() assert await b.authorized_tracker_namespace("clickhouse", "code-clickhouse") == "" + assert degradations.current() == ["identity: tracker_gate_unchecked (RuntimeError)"] # --- which gate --------------------------------------------------------- @@ -108,7 +112,7 @@ async def _scope(org, ns, role, *, hides_answer=True): seen.append(ns) return ns.startswith("code-") # may read the repository, holds nothing on qa-* - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) assert ( await b.authorized_tracker_namespace("clickhouse", "code-clickhouse-26-4") == "tracker-clickhouse" @@ -126,7 +130,7 @@ async def _scope(org, ns, role, *, hides_answer=True): seen.append(ns) return ns.startswith("code-") - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) assert await b.authorized_tracker_namespace("clickhouse", "code-example-private") == "" assert seen == ["tracker-priv"], ( "restricted: the gate is on the tracker namespace, and the caller has nothing there" @@ -145,6 +149,79 @@ async def _scope(org, ns, role, *, hides_answer=True): seen.append(ns) return False - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) assert await b.authorized_tracker_namespace("clickhouse", "code-clickhouse") == "" assert seen == ["tracker-clickhouse"] + + +async def _unverified(org, ns, role=None): + return None # a refusal whose grant read failed + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "caller", + ["code.history", "code.blame_range", "code.symbol", "code.bisect_candidates", "memory.ask"], +) +async def test_each_caller_names_a_tracker_whose_grant_could_not_be_read( + bound, monkeypatch, caller: str +) -> None: + """A code or memory answer the linked tracker only enriches is served without the + tracker, says so in `degraded` without naming it, and is not the server's failure.""" + from server.auth import fail_closed + from server.core import request_work + from server.observability import degradations + + monkeypatch.setattr(authz, "row_reach", _unverified) + request_work.begin() + degradations.begin() + ns = "code-clickhouse" + if caller == "code.history": + from server.code.app import history + + assert await history._tracker_facts(ORG, ns, [1]) == {} + elif caller == "code.blame_range": + from server.code.app import blame + + assert await blame._tracker_side(ORG, ns, [1]) == ({}, [], "", False) + elif caller == "code.symbol": + from server.code.app import symbol_history + + assert await symbol_history._tracker_side(ORG, ns, [1], []) == ({}, [], [], "", False) + elif caller == "code.bisect_candidates": + from server.code.app import bisect_scan + + rows = await bisect_scan._linked_scan( + ORG, ns, "", None, set(), frames=[], patterns=[], weights={}, limit=5 + ) + assert rows == [] + else: + from server.memory.app.ask import records + + lines: list[str] = [] + await records._append_tracker_facts(lines, [], ORG, ns, [1]) + assert lines == [] + assert degradations.current() == ["identity: tracker_unverified"] + assert not fail_closed.answered_unverified() + + +@pytest.mark.asyncio +async def test_a_tracker_the_caller_asked_for_marks_an_unverified_refusal( + bound, monkeypatch +) -> None: + from server.auth import fail_closed + from server.core import request_work + from server.observability import degradations + + monkeypatch.setattr(authz, "row_reach", _unverified) + request_work.begin() + degradations.begin() + assert await b.authorized_tracker_namespace(ORG, "code-clickhouse") == "" + assert fail_closed.answered_unverified() and degradations.current() == [] + from server.tracker.app import common + + # the trackers a search reads beside the addressed one: noted, not marked + request_work.begin() + assert await common.linked_trackers(ORG, "code-clickhouse") == [] + assert degradations.current() == ["identity: tracker_unverified"] + assert not fail_closed.answered_unverified() diff --git a/tests/unit/test_tracker_binding_discovery.py b/tests/unit/test_tracker_binding_discovery.py index 0f498e0dd21..a642003861a 100644 --- a/tests/unit/test_tracker_binding_discovery.py +++ b/tests/unit/test_tracker_binding_discovery.py @@ -52,7 +52,7 @@ async def readable(org, namespace, role=None, *, hides_answer=True): monkeypatch.setattr(settings, "tracker_code_namespace_bindings_json", "{}") monkeypatch.setattr("server.code.app.reads.code_index", Repository) monkeypatch.setattr("server.core.ch.get_client", lambda: SimpleNamespace(_client=object())) - monkeypatch.setattr("server.auth.authz.row_in_scope", readable) + monkeypatch.setattr("server.auth.authz.row_reach", readable) monkeypatch.setattr("server.identity.app.namespace_kinds.kind_map", kinds) monkeypatch.setattr("server.code.domain.scope.current_code_scope", lambda: None) monkeypatch.setattr("server.identity.app.request_scope.request_scope", lambda: WHOLE_NAMESPACE) diff --git a/tests/unit/test_tracker_binding_op.py b/tests/unit/test_tracker_binding_op.py index 5a411e76257..f3dcab3feb2 100644 --- a/tests/unit/test_tracker_binding_op.py +++ b/tests/unit/test_tracker_binding_op.py @@ -59,7 +59,7 @@ async def _scope(org, ns, role, *, hides_answer=True): seen.append((org, ns, role.name)) return ns in allowed - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) return allowed, seen @@ -127,7 +127,7 @@ async def test_a_failing_gate_is_closed_and_still_names_nothing(monkeypatch) -> async def _boom(org, ns, role, *, hides_answer=True): raise RuntimeError(f"gate down for {ns}") - monkeypatch.setattr(authz, "row_in_scope", _boom) + monkeypatch.setattr(authz, "row_reach", _boom) out = await resolve_binding(ORG, "code-example-private") assert out["kind"] == "none" and not out["authorized"] and out["tracker_namespace"] == "" assert PRIV not in repr(out) diff --git a/tests/unit/test_tracker_dupcheck_fanout.py b/tests/unit/test_tracker_dupcheck_fanout.py index 9c55d6a30fc..2fdcb5d464d 100644 --- a/tests/unit/test_tracker_dupcheck_fanout.py +++ b/tests/unit/test_tracker_dupcheck_fanout.py @@ -48,7 +48,7 @@ def _wire_namespaces( async def _scope(org, n, role=None, *, hides_answer=True): return n in readable or n in code_readable - monkeypatch.setattr("server.auth.authz.row_in_scope", _scope) + monkeypatch.setattr("server.auth.authz.row_reach", _scope) async def _kinds(org): return {"code-clickhouse": "code", "code-example-private": "code", "alice": "memory"} @@ -509,3 +509,30 @@ async def links(out, *args, **kwargs): monkeypatch.setattr(hd, "_with_links", links) await hd.execute_duplicate_check(plan) assert [i.namespace for i in checked.await_args.args[0]] == [PUB] + + +@pytest.mark.asyncio +async def test_a_record_whose_grant_could_not_be_read_is_left_out_and_noted(monkeypatch) -> None: + from server.auth import fail_closed + from server.core import request_work + from server.observability import degradations + + _wire_namespaces(monkeypatch, readable=set(), code_readable={"code-clickhouse"}) + priv: list[bool | None] = [None] + + async def _reach(org, n, role=None): + if n in (PRIV, PUB): + return priv[0] if n == PRIV else None + return n == "code-clickhouse" + + monkeypatch.setattr("server.auth.authz.row_reach", _reach) + request_work.begin() + degradations.begin() + # the public record still opens through its repository; the restricted one is noted + assert await fo.readable_tracker_namespaces(ORG, "", [], 4) == [PUB] + assert degradations.current() == ["identity: tracker_unverified"] + assert not fail_closed.answered_unverified() + priv[0] = False # a plain refusal is no note + degradations.begin() + assert await fo.readable_tracker_namespaces(ORG, "", [], 4) == [PUB] + assert degradations.current() == [] diff --git a/tests/unit/test_tracker_multi_binding.py b/tests/unit/test_tracker_multi_binding.py index a53e7b8fda7..e69224fdf2c 100644 --- a/tests/unit/test_tracker_multi_binding.py +++ b/tests/unit/test_tracker_multi_binding.py @@ -50,7 +50,7 @@ def wired(monkeypatch): async def _scope(org, ns, role=None, *, hides_answer=True): return ns in readable - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) yield readable b.reset_overrides_for_tests({}) @@ -318,7 +318,7 @@ async def _refresh(**_): async def _scope(org, ns, role=None, *, hides_answer=True): return ns in admin_of if role is Role.ADMIN else ns in admin_of | readers - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) try: out = await adm.handle_code_repo_set_source( CodeRepoSetSourceInput(org=ORG, namespace=CODE, tracker_namespaces=[DESK, QA]) @@ -485,7 +485,7 @@ async def _scope(org, ns, role=None, *, hides_answer=True): monkeypatch.setattr( "server.tracker.domain.namespaces.tracker_namespace", lambda org, n: NAMESPACES.get(n) ) - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) monkeypatch.setattr( "server.code.domain.index.repos.repo_for_namespace", lambda org, ns: SimpleNamespace(repo="Acme/widgets"), @@ -540,7 +540,7 @@ async def _scope(org, ns, role=None, *, hides_answer=True): lambda org, ns: SimpleNamespace(repo="Acme/widgets"), ) monkeypatch.setattr(b, "branches_following", lambda org, ns: [f"{CODE}-26-8"]) - monkeypatch.setattr(authz, "row_in_scope", _scope) + monkeypatch.setattr(authz, "row_reach", _scope) out = await adm.handle_code_repo_set_source( CodeRepoSetSourceInput(org=ORG, namespace=CODE, tracker_namespaces=[QA]) ) diff --git a/tests/unit/test_tracker_test_daily.py b/tests/unit/test_tracker_test_daily.py index 68419c6b173..25df154dd77 100644 --- a/tests/unit/test_tracker_test_daily.py +++ b/tests/unit/test_tracker_test_daily.py @@ -894,7 +894,7 @@ class _E: async def _ok(org, ns, role=None, *, hides_answer=True): return True - monkeypatch.setattr(authz, "row_in_scope", _ok) + monkeypatch.setattr(authz, "row_reach", _ok) return repo diff --git a/tests/unit/test_tracker_test_signal.py b/tests/unit/test_tracker_test_signal.py index 0846fd5392e..0e9fac6a32f 100644 --- a/tests/unit/test_tracker_test_signal.py +++ b/tests/unit/test_tracker_test_signal.py @@ -443,7 +443,7 @@ async def _ok(org, ns, role=Role.VIEWER, *, hides_answer=True): import server.auth.authz as authz - monkeypatch.setattr(authz, "row_in_scope", _ok) + monkeypatch.setattr(authz, "row_reach", _ok) return repo @@ -740,3 +740,27 @@ def test_a_failed_baseline_read_leaves_a_storm_only_verdict_undecided() -> None: # no storm counted: the floor K changed nothing calm = {**infra, "storm_hours": 0, "baseline_unavailable": "breaker open"} assert tsig._storm_unread(feat, calm, th, ts.verdict(feat, 0, th)[0]) == "" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("named", [True, False]) +async def test_a_churn_namespace_whose_grant_could_not_be_read( + monkeypatch, wired, named: bool +) -> None: + """Named, the namespace holds part of the answer: the request is the server's. The + deployment's default only enriches it: the leg is unavailable and noted, unnamed.""" + import server.auth.authz as authz + from server.auth import fail_closed + from server.core import request_work + from server.observability import degradations + + async def _unverified(org, ns, role=None): + return None + + monkeypatch.setattr(authz, "row_reach", _unverified) + request_work.begin() + degradations.begin() + out = await tsig._code_namespace_authorized(ORG, "code-clickhouse" if named else "") + assert out == (ORG, "code-clickhouse", "unauthorized") + assert fail_closed.answered_unverified() is named + assert degradations.current() == ([] if named else ["identity: churn_unverified"]) From 8030ffa6060b45ca64f31405ddb9a9f2a65f7245 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 12:26:03 +0530 Subject: [PATCH 14/47] A failed status count is kept briefly and named; an unread record tracker notes A failed symbol-stats or unit-risk count was not cached, so every code.index_status call reran the FINAL counts. It is now kept for PROBE_ERROR_TTL_S with its kind, and every answer served from it names it in `degraded`. memory.ask's record route notes a linked tracker it could not read (`memory.ask: record_tracker_unread`) beside the answer's `Not read` line. The `degraded` comments on memory.search and memory.set, the SDK docstring and two guides say the field names a provider, a store read or a gate. The guide's `deployment_scoped` row matches the reference, and the incident share comment and two paragraphs are rewrapped. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/development/adding-an-operation.md | 2 +- docs/features/memory/writing.md | 18 +++++----- docs/guides/debugging.md | 16 ++++----- docs/operations/monitoring.md | 9 ++--- docs/reference/configuration.md | 2 +- docs/reference/mcp.md | 8 ++--- docs/reference/operations/memory.md | 6 ++-- loom.example.yaml | 6 ++-- schemas/loom-settings.schema.json | 2 +- sdk/python/loom/memory.py | 5 +-- server/code/app/index_status.py | 35 ++++++++++++------- server/memory/api/models_crud.py | 5 +-- server/memory/api/models_search.py | 6 ++-- server/settings/catalog.py | 5 ++- server/tracker/app/ask_route.py | 3 ++ tests/unit/test_status_summaries_published.py | 30 ++++++++++++++++ tests/unit/test_tracker_multi_binding.py | 5 +++ 17 files changed, 107 insertions(+), 56 deletions(-) diff --git a/docs/development/adding-an-operation.md b/docs/development/adding-an-operation.md index 0bd9bc8cf67..3e5c16e662c 100644 --- a/docs/development/adding-an-operation.md +++ b/docs/development/adding-an-operation.md @@ -118,7 +118,7 @@ The declaration lives in the group's ops module, `server//api/ops_ CodeIndexStat return st -_SYMBOL_STATS_CACHE: dict[tuple[str, str], tuple[float, int, str]] = {} -_UNIT_RISK_CACHE: dict[tuple[str, str], tuple[float, int, str]] = {} +# (when read, rows, stamp, the failed read's kind or "") +_SYMBOL_STATS_CACHE: dict[tuple[str, str], tuple[float, int, str, str]] = {} +_UNIT_RISK_CACHE: dict[tuple[str, str], tuple[float, int, str, str]] = {} # "the caller never looked for a published row" — distinct from None, "looked, none # there": only the latter computes AND publishes. _NOT_LOOKED_UP: Any = object() @@ -739,8 +740,8 @@ async def symbol_stats_summary_cached( """`symbol_stats_rows` / `symbol_stats_at` for code.index_status. The table moves once a week, so the answer is held per namespace for ten minutes in the process (the read scans the - namespace's stats rows); the read failing open to (0, "") keeps status - whole.""" + namespace's stats rows). A failed read answers (0, ""), named in `degraded` on + every answer served from it (`_table_summary_cached`).""" if max_age_s is None: max_age_s = settings.code_status_symbol_stats_ttl_s return await _table_summary_cached( @@ -764,7 +765,7 @@ async def unit_risk_summary_cached( ) -> tuple[int, str]: """`unit_risk_rows` / `unit_risk_at` for code.index_status — the weekly unit-risk leg's progress, held ten minutes per namespace - like the stats fields; (0, "") when the read fails.""" + like the stats fields; (0, "") when the read fails, named in `degraded`.""" if max_age_s is None: max_age_s = settings.code_status_symbol_stats_ttl_s return await _table_summary_cached( @@ -780,7 +781,7 @@ async def unit_risk_summary_cached( async def _table_summary_cached( - cache: dict[tuple[str, str], tuple[float, int, str]], + cache: dict[tuple[str, str], tuple[float, int, str, str]], org: str, ns: str, read: Callable[[Any], Awaitable[tuple[int, datetime | None]]], @@ -791,34 +792,44 @@ async def _table_summary_cached( published: Any = _NOT_LOOKED_UP, ) -> tuple[int, str]: """The process memo, else the published state row, else one count — published for everyone - when the caller looked for a row and found none, so the next open anywhere reads the row.""" + when the caller looked for a row and found none, so the next open anywhere reads the row. + A failed count answers (0, "") and is kept `PROBE_ERROR_TTL_S` with its kind, so pollers + do not rerun it on every call, and every answer served from it names it in `degraded`.""" + from server.code.app.symbol.dispatch import PROBE_ERROR_TTL_S from server.code.store.index import parse_published_summary, summary_stamp + from server.core.errors import caller_text + effect = f"{what.replace(' ', '_')}_summary_unread" cache_key = (org, ns) now = time.monotonic() hit = cache.get(cache_key) - if hit is not None and now - hit[0] < max_age_s: + if hit is not None and now - hit[0] < ( + min(max_age_s, PROBE_ERROR_TTL_S) if hit[3] else max_age_s + ): + if hit[3]: + degradations.partial("code_index", effect, hit[3]) return hit[1], hit[2] if len(cache) > 256: cache.clear() row = parse_published_summary(published) if published is not _NOT_LOOKED_UP else None if row is not None: - cache[cache_key] = (now, row[0], row[1]) + cache[cache_key] = (now, row[0], row[1], "") return row rows, at = 0, "" try: n, stamp = await read(CodeRepo()) rows, at = int(n), summary_stamp(stamp) except Exception as e: # noqa: BLE001 — the status names the failure and is not published - degradations.partial("code_index", f"{what.replace(' ', '_')}_summary_unread", e) + degradations.partial("code_index", effect, e) logger.debug("code status: %s summary unavailable for %s: %s", what, ns, e) - return rows, at # not kept: the status entry names the failure, the next one reads + cache[cache_key] = (now, rows, at, caller_text(e)) + return rows, at if key and published is None: try: await CodeRepo().publish_summary(org, ns, key, rows, at) except Exception as e: # noqa: BLE001 — a failed publish keeps the answer logger.debug("code status: %s summary not published for %s: %s", what, ns, e) - cache[cache_key] = (now, rows, at) + cache[cache_key] = (now, rows, at, "") return rows, at diff --git a/server/memory/api/models_crud.py b/server/memory/api/models_crud.py index ce3e6ef8353..8b30d9eb7be 100644 --- a/server/memory/api/models_crud.py +++ b/server/memory/api/models_crud.py @@ -452,8 +452,9 @@ class MemorySetOutput(BaseModel): # ANOTHER key; nothing was written at `memory_key`, so a get/lock/update of # it finds no row. This names the key that holds it ("" when it is this one). merged_into_key: str = "" - # Providers that fell back on this write and what the response did instead - # (`classify: caller_type_kept (ReadTimeout)`). Empty when nothing degraded. + # What this answer fell back on or left out (a provider, a store read or a gate), + # each `source: effect (kind)`, such as `classify: caller_type_kept (ReadTimeout)`; + # left out of the response when empty. degraded: list[str] = [] # Set when the declared memory_type did not fit the value and the row was # stored under another type (currently: 'procedural' on a value that is not diff --git a/server/memory/api/models_search.py b/server/memory/api/models_search.py index d8e00671b21..9eb8f0c504c 100644 --- a/server/memory/api/models_search.py +++ b/server/memory/api/models_search.py @@ -829,9 +829,9 @@ def _say_what_was_compared(self) -> Self: # `page=` named a parked list that is gone. "page_expired", ] = "" - # Providers that fell back on this read and what the response did instead - # (`rerank: input_order_kept (ReadTimeout)`). A degraded answer is not the - # normal answer, and this field is how an agent tells them apart. + # What this answer fell back on or left out (a provider, a store read or a gate), + # each `source: effect (kind)`, such as `rerank: input_order_kept (ReadTimeout)`; + # left out of the response when empty. degraded: list[str] = [] # Named recipe applied (if any) + a terse final scoring posture. recipe: str = "" diff --git a/server/settings/catalog.py b/server/settings/catalog.py index cc90d1c0b42..0a2f333644b 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -4465,9 +4465,8 @@ class ObservabilitySettings(BaseModel): # Minutes of history ops.incidents reads: a provider failure seen within them, and # the caller's org's request failures over them. ops_incidents_window_minutes: int = Field(default=15, ge=1, le=1440) - # Share (0-1) of the org's requests of one SLO class, other than ops.incidents' - # own, that failed on the server's side over the window, at which ops.incidents - # lists a `requests` incident. + # Share (0-1) of one SLO class's requests in the window, other than ops.incidents' + # own, failing on the server, at which ops.incidents lists a `requests` incident. ops_incidents_error_share: float = Field(default=0.1, gt=0, le=1) # Requests of one SLO class in the window, other than ops.incidents' own, before # ops.incidents judges its share. diff --git a/server/tracker/app/ask_route.py b/server/tracker/app/ask_route.py index 1f6a462d42d..50592708014 100644 --- a/server/tracker/app/ask_route.py +++ b/server/tracker/app/ask_route.py @@ -28,6 +28,8 @@ import re from typing import Any +from server.observability import degradations + logger = logging.getLogger("loom.tracker.ask_route") _RELEASE_WORDS = re.compile( @@ -147,6 +149,7 @@ async def _searched_everywhere( else: got, k = await _catalogue(question, org, t, subject) except Exception as e: # noqa: BLE001 — one tracker never blocks the others; named below + degradations.partial("memory.ask", "record_tracker_unread", e) logger.debug("memory.ask qa route on %s skipped: %s", t, e) unread.append(t) continue diff --git a/tests/unit/test_status_summaries_published.py b/tests/unit/test_status_summaries_published.py index c2eb5b67578..b993134d30d 100644 --- a/tests/unit/test_status_summaries_published.py +++ b/tests/unit/test_status_summaries_published.py @@ -168,3 +168,33 @@ def test_the_status_handler_reads_the_state_before_the_summaries() -> None: assert "_state_for_status(" in b assert 'published=state.get("symbol_stats_summary")' in b assert 'published=state.get("unit_risk_summary")' in b + + +@pytest.mark.asyncio +async def test_a_failed_count_is_kept_briefly_and_named_on_each_answer( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Pollers do not rerun a failing count on every call, and no answer served from the + failure reads as whole.""" + from server.code.app.symbol.dispatch import PROBE_ERROR_TTL_S + from server.observability import degradations + + counts = 0 + + async def count(self: Any, org: str, ns: str) -> tuple[int, datetime | None]: + nonlocal counts + counts += 1 + raise TimeoutError("count timed out") + + monkeypatch.setattr(cr.CodeRepo, "symbol_stats_summary", count) + note = ["code_index: symbol_stats_summary_unread (TimeoutError)"] + for _ in range(2): + degradations.begin() + assert await index_status.symbol_stats_summary_cached("o", "n") == (0, "") + assert degradations.current() == note + assert counts == 1 + # past PROBE_ERROR_TTL_S the count runs again, though the ten-minute memo has not run out + at, rows, stamp, kind = index_status._SYMBOL_STATS_CACHE[("o", "n")] + index_status._SYMBOL_STATS_CACHE[("o", "n")] = (at - PROBE_ERROR_TTL_S - 1, rows, stamp, kind) + await index_status.symbol_stats_summary_cached("o", "n") + assert counts == 2 diff --git a/tests/unit/test_tracker_multi_binding.py b/tests/unit/test_tracker_multi_binding.py index e69224fdf2c..82dab12c65a 100644 --- a/tests/unit/test_tracker_multi_binding.py +++ b/tests/unit/test_tracker_multi_binding.py @@ -443,9 +443,14 @@ async def _component(src, org, t, subject): monkeypatch.setattr( "server.tracker.store.source.TrackerSource", lambda org, t: SimpleNamespace() ) + from server.observability import degradations + + degradations.begin() lines, key = await ar._searched_everywhere("component", "merges?", ORG, CODE, QA, "merges") assert lines == [f"{DESK}:", f"{DESK} line", f"Not read (tracker unavailable): {QA}"] assert key == f"key:{DESK}" + # `degraded` says so too, without the namespace the text names + assert degradations.current() == ["memory.ask: record_tracker_unread (RuntimeError)"] @pytest.mark.asyncio From 5036958ade5e2511e4484d6ea857f9f450245783 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 12:35:03 +0530 Subject: [PATCH 15/47] A published summary answers while a failed count is kept A kept failed count was served before the published row was looked at, so a status whose state already held the summary answered zeros and a note for up to PROBE_ERROR_TTL_S. The row in hand now answers first; the kept failure only spares the count. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/index_status.py | 12 ++++++++---- tests/unit/test_status_summaries_published.py | 9 ++++++++- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index ec7e8aa614f..77efab188cc 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -803,18 +803,22 @@ async def _table_summary_cached( cache_key = (org, ns) now = time.monotonic() hit = cache.get(cache_key) - if hit is not None and now - hit[0] < ( + fresh = hit is not None and now - hit[0] < ( min(max_age_s, PROBE_ERROR_TTL_S) if hit[3] else max_age_s - ): - if hit[3]: - degradations.partial("code_index", effect, hit[3]) + ) + if hit is not None and fresh and not hit[3]: return hit[1], hit[2] if len(cache) > 256: cache.clear() + # A published row in hand answers even while a failed count is kept: that entry only + # spares the count. row = parse_published_summary(published) if published is not _NOT_LOOKED_UP else None if row is not None: cache[cache_key] = (now, row[0], row[1], "") return row + if hit is not None and fresh: + degradations.partial("code_index", effect, hit[3]) + return hit[1], hit[2] rows, at = 0, "" try: n, stamp = await read(CodeRepo()) diff --git a/tests/unit/test_status_summaries_published.py b/tests/unit/test_status_summaries_published.py index b993134d30d..fd95a0b5113 100644 --- a/tests/unit/test_status_summaries_published.py +++ b/tests/unit/test_status_summaries_published.py @@ -193,8 +193,15 @@ async def count(self: Any, org: str, ns: str) -> tuple[int, datetime | None]: assert await index_status.symbol_stats_summary_cached("o", "n") == (0, "") assert degradations.current() == note assert counts == 1 + # a published row in hand answers while the failure is kept, with no note + degradations.begin() + got = await index_status.symbol_stats_summary_cached("o", "n", published=_row(4, "x")) + assert got == (4, "x") and degradations.current() == [] and counts == 1 + index_status._SYMBOL_STATS_CACHE.clear() + assert await index_status.symbol_stats_summary_cached("o", "n") == (0, "") + assert counts == 2 # past PROBE_ERROR_TTL_S the count runs again, though the ten-minute memo has not run out at, rows, stamp, kind = index_status._SYMBOL_STATS_CACHE[("o", "n")] index_status._SYMBOL_STATS_CACHE[("o", "n")] = (at - PROBE_ERROR_TTL_S - 1, rows, stamp, kind) await index_status.symbol_stats_summary_cached("o", "n") - assert counts == 2 + assert counts == 3 From a634980f5655d8066642d556149759867486102b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 12:42:59 +0530 Subject: [PATCH 16/47] A kept failed count survives the memo's size eviction The memo was cleared at 256 entries before a kept failure was served, and the failure was not written back, so the next poll reran the count the entry was there to spare. The eviction now runs only before a write. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/index_status.py | 10 +++++----- tests/unit/test_status_summaries_published.py | 8 ++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index 77efab188cc..3ad9c05ac16 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -808,17 +808,17 @@ async def _table_summary_cached( ) if hit is not None and fresh and not hit[3]: return hit[1], hit[2] - if len(cache) > 256: - cache.clear() # A published row in hand answers even while a failed count is kept: that entry only # spares the count. row = parse_published_summary(published) if published is not _NOT_LOOKED_UP else None + if row is None and hit is not None and fresh: + degradations.partial("code_index", effect, hit[3]) + return hit[1], hit[2] + if len(cache) > 256: # evicted only before a write, so a kept failure survives it + cache.clear() if row is not None: cache[cache_key] = (now, row[0], row[1], "") return row - if hit is not None and fresh: - degradations.partial("code_index", effect, hit[3]) - return hit[1], hit[2] rows, at = 0, "" try: n, stamp = await read(CodeRepo()) diff --git a/tests/unit/test_status_summaries_published.py b/tests/unit/test_status_summaries_published.py index fd95a0b5113..061e5cfa0fc 100644 --- a/tests/unit/test_status_summaries_published.py +++ b/tests/unit/test_status_summaries_published.py @@ -205,3 +205,11 @@ async def count(self: Any, org: str, ns: str) -> tuple[int, datetime | None]: index_status._SYMBOL_STATS_CACHE[("o", "n")] = (at - PROBE_ERROR_TTL_S - 1, rows, stamp, kind) await index_status.symbol_stats_summary_cached("o", "n") assert counts == 3 + # a full memo keeps the failure: eviction runs only before a write + for i in range(300): + index_status._SYMBOL_STATS_CACHE[("o", f"other-{i}")] = (at, 1, "", "") + degradations.begin() + assert await index_status.symbol_stats_summary_cached("o", "n") == (0, "") + assert counts == 3 and degradations.current() == note + assert await index_status.symbol_stats_summary_cached("o", "n") == (0, "") + assert counts == 3, "the next poll still finds the failure" From 8fa337f064cb7ede6a3af85b946f41c59a89984c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 14:14:16 +0530 Subject: [PATCH 17/47] Every broad except in the code and memory apps notes or is listed tests/unit/test_degraded_unnoted.py walks server/code/app and server/memory/app outside the index plane. A broad handler passes when it always raises, calls degradations.partial, note or restore, or keeps the failure's text for the answer through caller_text(e). Every other handler is listed in tests/unit/degraded_unnoted.txt with its category, and the test fails on a handler in neither place and on a stale entry. Going through the list added a note wherever the answer got smaller: memory.search's computed count, date difference and support count, its outer stage catches, graph, chunk, boost, spelling and paging legs; memory.ask's decomposition, intent, grounding and row legs; set_from_messages' judge, sweep, backfill and checks; context.pack's sections; code_index: state_unread, which judges a commit against cached heads; and the code search, grep, bisect and citation reads. Seven caches that kept a failed read as a plain value now keep its text and name it on each answer served from them. A failed re-read under scoped() is noted after the block, which drops an unserved re-read's notes. Store fallbacks that fed provider health with nothing to clear them now use partial. The rerank endpoint and Cohere record their successes, and a second test fails on a health-counted note no record_success clears. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/http-api.md | 5 +- server/code/app/bisect.py | 2 + server/code/app/bisect_fix.py | 1 + server/code/app/blame.py | 1 + server/code/app/citations.py | 2 + server/code/app/common.py | 47 ++- server/code/app/context.py | 4 +- server/code/app/first_build.py | 2 + server/code/app/grep_bodies.py | 4 +- server/code/app/grep_source.py | 4 + server/code/app/index_status.py | 13 +- server/code/app/outcome.py | 2 +- server/code/app/path_guards.py | 31 +- server/code/app/presence.py | 2 + server/code/app/repo_admin.py | 3 +- server/code/app/repos.py | 3 +- server/code/app/review_brief.py | 2 + server/code/app/search/handler.py | 37 ++- server/code/app/search/rank.py | 2 + server/code/app/search/rerank.py | 2 + server/code/app/search/symbol.py | 1 + server/code/app/search/window.py | 2 + server/code/app/symbol/impact.py | 4 +- server/code/app/symbol/outline.py | 3 +- server/code/app/symbol_context.py | 1 + server/memory/app/agent_rules.py | 2 + server/memory/app/answer_consistency.py | 3 + server/memory/app/ask/completion.py | 5 +- server/memory/app/ask/handler.py | 5 +- server/memory/app/ask/identifiers.py | 76 +++-- server/memory/app/ask/pool.py | 16 +- server/memory/app/ask/question_shapes.py | 5 +- server/memory/app/ask/retrieval_legs.py | 10 +- server/memory/app/ask_literal_evidence.py | 5 +- server/memory/app/ask_when_evidence.py | 3 +- server/memory/app/bulk_set.py | 2 + server/memory/app/classify.py | 1 + server/memory/app/code_grounding.py | 11 +- server/memory/app/conflicts_ops.py | 2 + server/memory/app/context_pack.py | 14 +- server/memory/app/deep_evidence.py | 1 + server/memory/app/durability_verifier.py | 2 + server/memory/app/embedder_calibration.py | 21 +- server/memory/app/evidence_transfer.py | 7 +- server/memory/app/extract/handler.py | 11 +- server/memory/app/extract/judge.py | 2 + server/memory/app/extract/relations.py | 2 + server/memory/app/extract/sweep.py | 2 + server/memory/app/facts.py | 2 + server/memory/app/handlers.py | 3 +- server/memory/app/loom_search/fanout.py | 8 +- server/memory/app/loom_search/handler.py | 2 + server/memory/app/pipeline.py | 4 + server/memory/app/procedure.py | 4 +- server/memory/app/recall.py | 4 +- server/memory/app/recent_seeds.py | 5 +- server/memory/app/rerank.py | 9 +- server/memory/app/restore.py | 2 + server/memory/app/retrieval/chunks.py | 1 + server/memory/app/retrieval/graph.py | 3 + server/memory/app/retrieval/key_axis.py | 16 +- server/memory/app/retrieval/search.py | 2 + server/memory/app/retrieval/summaries.py | 12 +- server/memory/app/search/anchor_pool.py | 1 + server/memory/app/search/ann_entity_boosts.py | 2 + server/memory/app/search/assemble.py | 10 +- server/memory/app/search/computed.py | 9 +- server/memory/app/search/consistency.py | 70 ++-- server/memory/app/search/digest_descent.py | 3 +- server/memory/app/search/embed.py | 2 + server/memory/app/search/fallbacks.py | 4 +- server/memory/app/search/key_match.py | 3 +- server/memory/app/search/output.py | 6 +- server/memory/app/search/payload.py | 15 +- server/memory/app/search/query_spelling.py | 3 + server/memory/app/search/ranking.py | 2 + server/memory/app/search/scope.py | 3 + server/memory/app/search/telemetry.py | 2 +- server/memory/app/search/term_leg.py | 1 + server/memory/app/search/tiers.py | 3 +- server/memory/app/search/vector_legs.py | 3 +- server/memory/app/search_bm25.py | 2 + server/memory/app/search_pages.py | 3 +- server/memory/app/served_duplicates.py | 3 + server/memory/app/session_brief.py | 14 +- server/memory/app/set_commit.py | 4 +- server/memory/app/stack.py | 4 + server/memory/app/webhooks.py | 4 +- server/memory/app/write.py | 2 + server/memory/app/write_fence.py | 2 +- server/tasks/store/runs.py | 8 +- tests/unit/degraded_unnoted.txt | 313 ++++++++++++++++++ tests/unit/test_code_repos_refresh_cost.py | 49 +++ tests/unit/test_degraded_unnoted.py | 172 ++++++++++ .../unit/test_memory_search_computed_notes.py | 59 ++++ tests/unit/test_memory_webhooks.py | 2 +- tests/unit/test_search_read_your_writes.py | 6 +- 97 files changed, 1040 insertions(+), 214 deletions(-) create mode 100644 tests/unit/degraded_unnoted.txt create mode 100644 tests/unit/test_degraded_unnoted.py create mode 100644 tests/unit/test_memory_search_computed_notes.py diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index e34d99276e9..95331cb882d 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -326,8 +326,9 @@ error's kind only; the full text is in the server log. judges the entries its own reads recorded, so one the request recorded before it does not stop the cache. Some caches keep a fallback with its entries and name them on each answer served from it: `code.index_status` and `code.repos` keep such a status for - `LOOM_CODE_STATUS_TTL_S`, the constructor-coverage and `overrides` probes keep a - failed read for 30 seconds, the pending-extraction count for + `LOOM_CODE_STATUS_TTL_S`, the constructor-coverage and `overrides` probes, and + `code.index_status`' symbol-stats and unit-risk counts, keep a failed read for 30 + seconds, the pending-extraction count for `LOOM_MEMORY_PENDING_DISCLOSURE_TTL_S`, namespace health for `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`, and each of `ops.incidents`' ClickHouse sources for 5 seconds. diff --git a/server/code/app/bisect.py b/server/code/app/bisect.py index 220041c3147..30b3030723c 100644 --- a/server/code/app/bisect.py +++ b/server/code/app/bisect.py @@ -273,6 +273,7 @@ async def _mark_stage( try: records = await repo.pr_records_by_number(org, ns, [c.pr_number for c in pool]) except Exception as e: # noqa: BLE001 — the marks are a ranking prior, not the answer + degradations.partial("code_index", "pr_records_unread", e) logger.info("bisect: ledger records unread (%s)", e) records, stage.status = {}, "ledger_failed" first = bi.mark_bisect_candidates(pool, records=records, frames=frames, diff_kinds={}) @@ -319,6 +320,7 @@ async def _attach_merge_shas(repo: CodeRepo, org: str, ns: str, ranked: list[bi. try: stored: dict[int, Any] = await repo.merge_commits_of(org, ns, numbers) except Exception as e: # noqa: BLE001 — the mirror still answers + degradations.partial("code_index", "merge_ledger_unread", e) logger.info("bisect: ledger merge commits unread (%s)", e) stored = {} cfg, _siblings = cb.repo_siblings(org, ns) diff --git a/server/code/app/bisect_fix.py b/server/code/app/bisect_fix.py index ea2aad57289..e9fbff92b44 100644 --- a/server/code/app/bisect_fix.py +++ b/server/code/app/bisect_fix.py @@ -273,6 +273,7 @@ async def _fix_named_stage( try: rows = await source.items_by_number(org, tracker_ns, missing) except Exception as e: # noqa: BLE001 — fails open to the scan's order + degradations.partial("tracker", "named_cause_unread", e) logger.info("bisect: named cause rows unavailable (%s)", e) lead: list[bi.Candidate] = [] for n in named[:3]: diff --git a/server/code/app/blame.py b/server/code/app/blame.py index 58283ed2501..7bc4aa7f16b 100644 --- a/server/code/app/blame.py +++ b/server/code/app/blame.py @@ -147,6 +147,7 @@ async def _namespace_head(repo: CodeRepo, org: str, ns: str) -> str: try: state = await repo.all_state(org, ns) except Exception as e: # noqa: BLE001 — the mirror's ref is the fallback + degradations.partial("code_index", "branch_head_unread", e) logger.debug("blame_range: state read failed for %s: %s", ns, e) return "" return state_value(state, "git_head") diff --git a/server/code/app/citations.py b/server/code/app/citations.py index b9761828937..bff2ee39fe7 100644 --- a/server/code/app/citations.py +++ b/server/code/app/citations.py @@ -187,6 +187,7 @@ async def _read_names( try: idx.error_codes = await error_code_names(repo, org, ns) except Exception as e: # noqa: BLE001 — the table is optional; its names stay unresolved + degradations.partial("code_index", "error_codes_unread", e) logger.info("verify_citations: ErrorCodes table unread: %s", e) sem = asyncio.Semaphore(NAME_CONCURRENCY) @@ -649,6 +650,7 @@ async def _merge_sha_of( try: facts = await repo.pr_merge_facts(org, ns_i, pr_number=pr_number) except Exception as e: # noqa: BLE001 — a ledger read failure is a miss + degradations.partial("code_index", "merge_ledger_unread", e) logger.info("verify_citations: pr_merge_facts failed for %s: %s", ns_i, e) facts = None sha = sha_text(facts.get("merge_sha")) if facts else "" diff --git a/server/code/app/common.py b/server/code/app/common.py index a657fd5db6b..1b6f3de437a 100644 --- a/server/code/app/common.py +++ b/server/code/app/common.py @@ -18,7 +18,7 @@ ) from server.code.app.ttl_cache import TtlCache from server.core.background import create_deferred_task -from server.core.errors import PreconditionFailedError +from server.core.errors import PreconditionFailedError, caller_text from server.core.relative_paths import without_dot_slashes from server.observability import degradations from server.observability.consumer import current_consumer @@ -197,7 +197,8 @@ def invalidate_index_as_of(org: str, ns: str) -> None: # (org, ns) -> note. Sixty seconds per namespace; the count behind it is # `table_counts`' fingerprint-cached scan, held a minute while the entry is building and # ten otherwise (code_context). -_COVERAGE_NOTE_CACHE: TtlCache[tuple[str, str], str] = TtlCache(60.0, maxsize=256) +# (org, ns) -> (note, failed read's text or "") +_COVERAGE_NOTE_CACHE: TtlCache[tuple[str, str], tuple[str, str]] = TtlCache(60.0, maxsize=256) def coverage_note_text(coverage: float) -> str: @@ -215,8 +216,15 @@ async def embedding_coverage_note(repo: CodeRepo, org: str, ns: str) -> str: namespace's vector leg covers less than the ready threshold of its chunks, "" otherwise. Fail-open to "": a note must never sink a served answer.""" hit = _COVERAGE_NOTE_CACHE.get((org, ns)) - if hit is not None: - return hit + if hit is None: + hit = await _coverage_note(repo, org, ns) + _COVERAGE_NOTE_CACHE.put((org, ns), hit) + if hit[1]: # each answer served from a failed read names it + degradations.partial("code_index", "coverage_note_unread", hit[1]) + return hit[0] + + +async def _coverage_note(repo: CodeRepo, org: str, ns: str) -> tuple[str, str]: note = "" try: from server.code.app.index_status import _counts_max_age_s, coverage_fields @@ -232,8 +240,8 @@ async def embedding_coverage_note(repo: CodeRepo, org: str, ns: str) -> str: note = coverage_note_text(float(coverage_fields(counts)["embedding_coverage"])) except Exception as e: # noqa: BLE001 — the note is advisory logger.debug("code coverage note unavailable for %s/%s: %s", org, ns, e) - _COVERAGE_NOTE_CACHE.put((org, ns), note) - return note + return note, caller_text(e) + return note, "" async def index_as_of(repo: CodeRepo, org: str, ns: str) -> dict[str, Any]: @@ -358,9 +366,9 @@ def mirror_fetch_overdue( return ((now or datetime.now(UTC)) - ts).total_seconds() > limit -# (git_dir, branch, git_head) -> (expires_monotonic, lag). One rev-list per +# (git_dir, branch, git_head) -> (lag, failed read's text or ""). One rev-list per # minute per repo instead of one subprocess per search call. -_LAG_CACHE: TtlCache[tuple[str, str, str], int] = TtlCache(60.0, maxsize=64) +_LAG_CACHE: TtlCache[tuple[str, str, str], tuple[int, str]] = TtlCache(60.0, maxsize=64) def _published_lag(state: Any, cfg: Any, git_head: str) -> int: @@ -377,15 +385,20 @@ async def _lag_commits_cached(cfg: Any, git_head: str) -> int: key = (cfg.git_dir, cfg.git_branch, git_head) hit = _LAG_CACHE.get(key) - if hit is not None: - return hit - try: - tip = await gitrepo.head_sha(cfg.git_dir, cfg.git_branch) - lag = await gitrepo.commit_count_between(cfg.git_dir, git_head, tip) - except Exception: # noqa: BLE001 — clone unreadable here: unknown, not stale - lag = -1 - _LAG_CACHE.put(key, lag) - return lag + if hit is None: + try: + tip = await gitrepo.head_sha(cfg.git_dir, cfg.git_branch) + hit = (await gitrepo.commit_count_between(cfg.git_dir, git_head, tip), "") + except Exception as e: # noqa: BLE001 — clone unreadable here: unknown, not stale + from server.code.app.index_status import _commit_missing + + # A head the clone does not hold yet is unknown, not a failed read. + missing = await _commit_missing(gitrepo, cfg.git_dir, (git_head,)) + hit = (-1, "" if missing else caller_text(e)) + _LAG_CACHE.put(key, hit) + if hit[1]: + degradations.partial("git_mirror", "lag_unknown", hit[1]) + return hit[0] def path_coverage(cfg: RepoConfig | None, path_prefix: str) -> tuple[bool, tuple[str, ...]]: diff --git a/server/code/app/context.py b/server/code/app/context.py index c01857a81c3..924f444148a 100644 --- a/server/code/app/context.py +++ b/server/code/app/context.py @@ -295,8 +295,8 @@ async def _build_map_text( model = "" try: model = get_embedder().model_name - except Exception: # noqa: BLE001 — summaries read with no model - pass + except Exception as exc: # noqa: BLE001 — summaries read with no model + degradations.partial("code_index", "map_summaries_dropped", exc) rows = await repo.top_summaries(org, ns, model, module_prefix=module_prefix, limit=60) callers, cards = await _call_graph_hubs(repo, org, ns, model, module_prefix) lines = ["# Repo map (include-graph and call-graph hubs; per-merge fresh)"] diff --git a/server/code/app/first_build.py b/server/code/app/first_build.py index a0637655294..e3ad5324053 100644 --- a/server/code/app/first_build.py +++ b/server/code/app/first_build.py @@ -45,6 +45,7 @@ from server.code.domain.index.blame_range import sha_text from server.code.store.index import CodeRepo from server.core.errors import ValidationError +from server.observability import degradations logger = logging.getLogger(__name__) @@ -96,6 +97,7 @@ async def _ledger(repo: CodeRepo, org: str, ns: str, sub: Subject) -> None: ) sub.outside = sub.outside or bool(later) except Exception as e: # noqa: BLE001 — the mirror is the other witness + degradations.partial("code_index", "merge_ledger_unread", e) logger.info("first_build: ledger read failed (%s)", e) sub.outside = True # not placed: only the mirror can make it known return diff --git a/server/code/app/grep_bodies.py b/server/code/app/grep_bodies.py index 5df887b18b8..de42398f523 100644 --- a/server/code/app/grep_bodies.py +++ b/server/code/app/grep_bodies.py @@ -12,6 +12,7 @@ from server.code.app.spans import code_span from server.code.domain.deadline import Budget from server.code.domain.units import estimate_tokens +from server.observability import degradations logger = logging.getLogger(__name__) @@ -89,7 +90,8 @@ async def read() -> None: await read() except TimeoutError: incomplete, note = True, "enclosing body lookup timed out" - except Exception: # Matching lines remain useful when a body read fails. + except Exception as exc: # Matching lines remain useful when a body read fails. + degradations.partial("code_index", "enclosing_bodies_unread", exc) logger.warning("code.grep enclosing body lookup failed", exc_info=True) incomplete, note = True, "some enclosing bodies could not be read" definitions = _distinct(rows) diff --git a/server/code/app/grep_source.py b/server/code/app/grep_source.py index ab988188c10..d2ec89943ce 100644 --- a/server/code/app/grep_source.py +++ b/server/code/app/grep_source.py @@ -21,6 +21,7 @@ ) from server.code.domain.symbol_body import complete_source_span, retained_source_lines from server.code.store.index import CodeRepo +from server.observability import degradations logger = logging.getLogger(__name__) @@ -105,6 +106,7 @@ async def verify_complete_contexts( async with asyncio.timeout(None if budget is None else budget.left_ms() / 1000): rows = await repo.symbol_spans_by_ids(org, ns, ids, source_only=True) except Exception as exc: # noqa: BLE001 — keep centered excerpts if the optional lookup fails + degradations.partial("code_index", "declaration_extents_unread", exc) logger.debug("grep declaration extent lookup failed: %s", type(exc).__name__) return frozenset() ends: dict[tuple[str, str, int, str], set[int]] = {} @@ -497,6 +499,7 @@ async def recover_page_context( budget.drop("grep context recovery timed out") span_attrs(span, reason="deadline") except Exception as exc: # noqa: BLE001 — keep the surrounding indexed evidence when recovery fails + degradations.partial("code_index", "context_recovery_dropped", exc) logger.debug("grep context recovery failed: %s", type(exc).__name__) span_attrs(span, reason="source_unavailable") recovered = sum(bool(result.windows) for result in readable) @@ -566,6 +569,7 @@ async def recover_source_chunks( budget.drop("grep source recovery timed out") break except Exception as exc: # noqa: BLE001 — retain disclosed partial grep hits when source recovery fails + degradations.partial("code_index", "source_recovery_dropped", exc) logger.warning("code.grep source recovery failed for %s: %s", path, exc) continue remaining -= chars diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index 3ad9c05ac16..98af73b6ff2 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -406,6 +406,7 @@ def detail(key: str) -> str: last_error=str(err)[:200], ) except Exception as e: # noqa: BLE001 — worker registry is best-effort + degradations.partial("code_index", "workers_unread", e) logger.debug("code status: worker snapshot unavailable: %s", e) coverage = coverage_fields(counts) @@ -722,10 +723,12 @@ def _fresh_heads(st: CodeIndexStatusOutput, state: IndexState) -> None: async def _state_for_status(org: str, ns: str) -> dict[str, Any]: """The namespace's `code_index_state` rows for `code.index_status`; {} - when the read fails (the status stays whole, the summaries count).""" + when the read fails, noted: a commit is then judged against the cached status's + heads, and the summaries count.""" try: return await CodeRepo().all_state(org, ns) except Exception as e: # noqa: BLE001 — status never fails on its state read + degradations.partial("code_index", "state_unread", e) logger.debug("code.index_status: state read failed for %s: %s", ns, e) return {} @@ -814,7 +817,9 @@ async def _table_summary_cached( if row is None and hit is not None and fresh: degradations.partial("code_index", effect, hit[3]) return hit[1], hit[2] - if len(cache) > 256: # evicted only before a write, so a kept failure survives it + # A poll that finds its own kept failure returned above; a write past 256 entries, for + # any namespace, clears the memo, kept failures included. + if len(cache) > 256: cache.clear() if row is not None: cache[cache_key] = (now, row[0], row[1], "") @@ -922,6 +927,7 @@ async def handle_code_recent_commits(input: CodeRecentCommitsInput) -> CodeRecen try: # best-effort decoration from the bare clone meta = await gitrepo.commit_meta_many(cfg.git_dir, [s for s in shas if s]) except Exception as e: # noqa: BLE001 — a missing clone leaves rows undecorated + degradations.partial("git_mirror", "commit_meta_unread", e) logger.debug("code.recent_commits: clone metadata unavailable for %s: %s", ns, e) out: list[CodeRecentCommitRow] = [] for r, sha in zip(rows, shas, strict=True): @@ -1000,8 +1006,9 @@ async def _coverage_cached( try: gap_counts = await repo.coverage_gaps(org, ns) except Exception as e: # noqa: BLE001 — coverage must not fail on the gap queries + degradations.partial("code_index", "coverage_gaps_unread", e) logger.warning("code.coverage: gap queries failed for %s/%s: %s", org, ns, e) - gap_counts = None + return cov, None # served, not kept if len(_coverage_cache) > 256: _coverage_cache.clear() _coverage_cache[key] = (fp, now, cov, gap_counts) diff --git a/server/code/app/outcome.py b/server/code/app/outcome.py index a6ad3389466..151ba96f19f 100644 --- a/server/code/app/outcome.py +++ b/server/code/app/outcome.py @@ -91,7 +91,7 @@ async def handle_code_outcome(input: CodeOutcomeInput) -> CodeOutcomeOutput: # tombstones the entry it was served from. try: await _fold_outcome_signal(org, ns, input) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — one lost vote, never the op logger.debug("code.outcome signal fold failed: %s", e) return CodeOutcomeOutput(recorded=True) diff --git a/server/code/app/path_guards.py b/server/code/app/path_guards.py index 5f0e884b403..ff086b1ed84 100644 --- a/server/code/app/path_guards.py +++ b/server/code/app/path_guards.py @@ -49,7 +49,8 @@ from server.code.app.ttl_cache import TtlCache from server.code.domain.extract.call_guards import callee_tag, guard_names, site_guards_of from server.code.store.index import CodeRepo -from server.core.errors import NotFoundError +from server.core.errors import NotFoundError, caller_text +from server.observability import degradations logger = logging.getLogger(__name__) @@ -59,7 +60,8 @@ # others not yet, so an absent row is "not walked", not "unconditional". CAUSE_INDEXING = "guards_indexing" CAUSE_NO_SITE = "hop_without_site" -_GUARD_STAGE_CACHE: TtlCache[tuple[str, str], bool] = TtlCache(300.0) +# (org, ns) -> (converged, failed read's text or "") +_GUARD_STAGE_CACHE: TtlCache[tuple[str, str], tuple[bool, str]] = TtlCache(300.0) async def _guard_stage_converged(repo: Any, org: str, ns: str) -> bool: @@ -69,18 +71,19 @@ async def _guard_stage_converged(repo: Any, org: str, ns: str) -> bool: namespace per five minutes; an unreadable state falls back to the row probe alone rather than turning a measured verdict into `unknown`.""" hit = _GUARD_STAGE_CACHE.get((org, ns)) - if hit is not None: - return hit - try: - from server.code.domain.extract.extractor_stamp import stage_stamps - - state = await repo.all_state(org, ns) - recorded = str((state.get("extractor_stamp_guard") or {}).get("value") or "") - ok = bool(recorded) and recorded == stage_stamps()["guard"] - except Exception: # noqa: BLE001 — state unreadable: do not invent an abstain - ok = True - _GUARD_STAGE_CACHE.put((org, ns), ok) - return ok + if hit is None: + try: + from server.code.domain.extract.extractor_stamp import stage_stamps + + state = await repo.all_state(org, ns) + recorded = str((state.get("extractor_stamp_guard") or {}).get("value") or "") + hit = (bool(recorded) and recorded == stage_stamps()["guard"], "") + except Exception as e: # noqa: BLE001 — state unreadable: do not invent an abstain + hit = (True, caller_text(e)) + _GUARD_STAGE_CACHE.put((org, ns), hit) + if hit[1]: # judged converged without the state read + degradations.partial("code_index", "guard_stage_unread", hit[1]) + return hit[0] async def _unindexed_verdict( diff --git a/server/code/app/presence.py b/server/code/app/presence.py index 22da3aa6d32..9e59c2fdf67 100644 --- a/server/code/app/presence.py +++ b/server/code/app/presence.py @@ -33,6 +33,7 @@ from server.code.api.models_grep import CodeGrepInput, CodeGrepOutput from server.code.api.models_symbol import CodeSymbolInput, CodeSymbolOutput +from server.observability import degradations from server.settings import settings MAX_NAMESPACES = 8 @@ -197,6 +198,7 @@ async def _one(org: str, ns: str, repo: Any, call: Awaitable[Any]) -> Answered: except asyncio.CancelledError: raise except Exception as e: # noqa: BLE001 — per-namespace, disclosed as unknown + degradations.partial("code_index", "namespace_unanswered", e) err, as_of = e, {} return out, dict(as_of or {}), int((time.monotonic() - t0) * 1000), err diff --git a/server/code/app/repo_admin.py b/server/code/app/repo_admin.py index 8d980818f85..ae4bf3b0139 100644 --- a/server/code/app/repo_admin.py +++ b/server/code/app/repo_admin.py @@ -314,7 +314,8 @@ async def _onboarding_warnings(provider: str) -> list[str]: try: passes = await _worker_passes_from_ledger() - except Exception: # noqa: BLE001 — settings still provide a conservative answer + except Exception as exc: # noqa: BLE001 — settings still provide a conservative answer + degradations.partial("code_index", "worker_ledger_unread", exc) passes = {} warnings: list[str] = [] if not settings.code_ingest_enabled and not (passes.get("code_ingest") or {}).get( diff --git a/server/code/app/repos.py b/server/code/app/repos.py index 434a01dca35..2880b3733fe 100644 --- a/server/code/app/repos.py +++ b/server/code/app/repos.py @@ -307,7 +307,8 @@ async def _listing_gate( **_known_grant_kw(roles, key, grants_read=grants_read), ) return True - except Exception: # noqa: BLE001 — PermissionError / IdentityIncomplete + except Exception as exc: # noqa: BLE001 — PermissionError / IdentityIncomplete + degradations.partial("identity", "listing_gate_unchecked", exc) # A principal of the same org sees every # repository it may ask to join — open (one click) or # approval (a maintainer decides) — as a request-only entry: diff --git a/server/code/app/review_brief.py b/server/code/app/review_brief.py index 79438b85a51..1cd861d3967 100644 --- a/server/code/app/review_brief.py +++ b/server/code/app/review_brief.py @@ -448,7 +448,9 @@ async def _build_open( title = str((item or {}).get("title") or "") author = str((item or {}).get("author") or "") # the author feeds the revert prior except Exception as e: # noqa: BLE001 — the title and author are decoration + degradations.partial("code.review_brief", "pr_item_unread", e) logger.debug("code.review_brief: items row for PR %s skipped: %s", pr_number, e) + store = False # a brief built without its items row is served, not kept try: if img is None: files = await gitrepo.diff_name_only(cfg.git_dir, base, head_sha) diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index 6082f2fac53..ff658257897 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -901,7 +901,11 @@ async def _user_recent_dirs(org: str, user_id: str) -> list[str]: (personalization — tie-break input only), from the namespaces the caller may read and inside the request's read scope.""" from server.auth.context import current_auth, resolve_my_namespaces - from server.core.errors import AuthInsufficientError, IdentityIncompleteError + from server.core.errors import ( + AuthInsufficientError, + IdentityIncompleteError, + caller_text, + ) from server.identity.domain.read_scope import request_read_filters try: @@ -912,26 +916,31 @@ async def _user_recent_dirs(org: str, user_id: str) -> list[str]: except (AuthInsufficientError, IdentityIncompleteError): return [] except Exception as e: # noqa: BLE001 — personalization is best-effort + degradations.partial("code_index", "personalization_dropped", e) logger.debug("code.search: caller namespaces unavailable: %s", e) return [] key = (org, user_id, namespaces, scope) now = time.monotonic() cached = _RECENT_DIR_CACHE.get(key) - if cached is not None and now - cached[0] < 300: - return cached[1] - dirs: list[str] = [] - try: - from server.memory.app.code_plane_reads import user_file_dirs + if cached is None or now - cached[0] >= 300: + dirs: list[str] = [] + failure = "" + try: + from server.memory.app.code_plane_reads import user_file_dirs - dirs = await user_file_dirs(org, user_id, namespaces, scope=scope) - except Exception as e: # noqa: BLE001 — personalization is best-effort - logger.debug("code.search: recent-dirs lookup failed: %s", e) - if len(_RECENT_DIR_CACHE) > 2000: - _RECENT_DIR_CACHE.clear() - _RECENT_DIR_CACHE[key] = (now, dirs[:50]) - return dirs[:50] + dirs = await user_file_dirs(org, user_id, namespaces, scope=scope) + except Exception as e: # noqa: BLE001 — personalization is best-effort + logger.debug("code.search: recent-dirs lookup failed: %s", e) + failure = caller_text(e) + if len(_RECENT_DIR_CACHE) > 2000: + _RECENT_DIR_CACHE.clear() + cached = _RECENT_DIR_CACHE[key] = (now, dirs[:50], failure) + if cached[2]: + degradations.partial("code_index", "personalization_dropped", cached[2]) + return cached[1] +# key -> (read_at, dirs, failed read's text or "") _RECENT_DIR_CACHE: dict[ - tuple[str, str, tuple[str, ...] | None, ReadFilters], tuple[float, list[str]] + tuple[str, str, tuple[str, ...] | None, ReadFilters], tuple[float, list[str], str] ] = {} diff --git a/server/code/app/search/rank.py b/server/code/app/search/rank.py index 97b35d8dcf8..61d956baf8e 100644 --- a/server/code/app/search/rank.py +++ b/server/code/app/search/rank.py @@ -26,6 +26,7 @@ from server.code.domain.units import CodeUnit, unit_from_chunk from server.code.store.index import CodeRepo from server.memory.domain.rerank_names import BUILTIN_PICK +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -134,6 +135,7 @@ async def _rank_units( if signals: ranked = _apply_outcome_boost(ranked, signals) except Exception as e: # noqa: BLE001 — ranking signal is best-effort + degradations.partial("code_index", "outcome_boost_dropped", e) logger.debug("outcome boost skipped: %s", e) # ---- personalization tie-break: before the rerank, whose order says nothing diff --git a/server/code/app/search/rerank.py b/server/code/app/search/rerank.py index 892bf38444f..fac4b86fce7 100644 --- a/server/code/app/search/rerank.py +++ b/server/code/app/search/rerank.py @@ -175,6 +175,7 @@ async def _rerank_units( except customer.HOLDS: raise # a refusal or an unread switch, not a provider fault except Exception as e: # noqa: BLE001 — fail-open keeps fused order + degradations.partial("rerank", "input_order_kept", e) logger.warning("code.search rerank failed (%s); fused order kept", e) return units, False # The service fails open by handing back the SAME candidate list (a provider error, or a reply @@ -244,6 +245,7 @@ def _pick_client(*, issue: bool) -> Any: try: client = get_llm_client_without_fallback(model) except Exception as e: # noqa: BLE001 — a model no client is built for keeps the ranking + degradations.partial("llm", "pick_skipped", e) logger.warning("code.search pick model %r has no client (%s); ranking kept", model, e) return None return None if isinstance(client, FakeLLMClient) else client diff --git a/server/code/app/search/symbol.py b/server/code/app/search/symbol.py index 3c3eba801f2..43dd727cc88 100644 --- a/server/code/app/search/symbol.py +++ b/server/code/app/search/symbol.py @@ -125,6 +125,7 @@ async def fill(unit: CodeUnit) -> None: try: unit.body = await symbol_body(repo, org, ns, unit.model_dump(), model=model) except Exception as error: # noqa: BLE001 — a source read cannot discard a resolved definition + degradations.partial("code_index", "symbol_body_unread", error) logger.warning("code.search symbol source unavailable: %s", error) if not unit.body: unit.elided = True diff --git a/server/code/app/search/window.py b/server/code/app/search/window.py index f43cbff9701..95be0854a6d 100644 --- a/server/code/app/search/window.py +++ b/server/code/app/search/window.py @@ -13,6 +13,7 @@ from server.code.domain.idents import embedded_idents from server.code.domain.units import CodeUnit from server.code.store.index import CodeRepo +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -64,6 +65,7 @@ async def _order_window( ranked, hub_added = code_fan_in.merge_hubs(ranked, hubs) span_attrs(sp, results=hub_added) except Exception as e: # noqa: BLE001 — the pool still sorts + degradations.partial("code_index", "fan_in_hubs_dropped", e) logger.debug("fan-in hub candidates skipped: %s", e) if min_fan_in > 0: ranked = [u for u in ranked if u.fan_in >= min_fan_in] diff --git a/server/code/app/symbol/impact.py b/server/code/app/symbol/impact.py index ec6f8c7781a..f81d140c053 100644 --- a/server/code/app/symbol/impact.py +++ b/server/code/app/symbol/impact.py @@ -63,6 +63,7 @@ from server.code.domain.index.verdicts import paths_seen as _paths_seen from server.code.store.index import CodeRepo from server.core.errors import NotFoundError +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -543,7 +544,8 @@ def _indexed_prefixes(org: str, ns: str) -> tuple[str, ...]: cfg = repo_for_namespace(org, ns) return tuple(cfg.path_prefixes) if cfg else () - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — no prefixes: no path reads as outside the index + degradations.partial("code_index", "path_prefixes_unread", e) logger.debug("repo prefixes lookup skipped: %s", e) return () diff --git a/server/code/app/symbol/outline.py b/server/code/app/symbol/outline.py index 27a08622fe9..2129084a595 100644 --- a/server/code/app/symbol/outline.py +++ b/server/code/app/symbol/outline.py @@ -118,7 +118,8 @@ async def _container_skeleton( repo.class_skeleton_chunk(org, ns, path, qn), repo.outline_for_path(org, ns, path), ) - except Exception: # noqa: BLE001 — additive: the joined body still ships + except Exception as exc: # noqa: BLE001 — additive: the joined body still ships + degradations.partial("code_index", "class_outline_dropped", exc) logger.warning("code.symbol skeleton read failed for %s", qn) return await symbol_body(repo, org, ns, sym), [], "" body = str(skel["content"]) if skel else await symbol_body(repo, org, ns, sym) diff --git a/server/code/app/symbol_context.py b/server/code/app/symbol_context.py index 6dab3862915..93362c2c2b5 100644 --- a/server/code/app/symbol_context.py +++ b/server/code/app/symbol_context.py @@ -181,6 +181,7 @@ async def rank_by_context( near_paths=near, ) except Exception as e: # noqa: BLE001 — falls back to path distance + degradations.partial("code_index", "co_change_unread", e) logger.debug("code.symbol co-change read failed: %s", e) co_change = {} return rank_definitions(rows, near, co_change) diff --git a/server/memory/app/agent_rules.py b/server/memory/app/agent_rules.py index 1c09de7ddc8..ac7783d4c57 100644 --- a/server/memory/app/agent_rules.py +++ b/server/memory/app/agent_rules.py @@ -10,6 +10,7 @@ from collections.abc import Awaitable, Callable from server.memory.domain import assistant_rules +from server.observability import degradations log = logging.getLogger(__name__) @@ -54,5 +55,6 @@ def serves(h: H) -> bool: wider = await widen(wider_k) served = [h for h in wider if serves(h)] except Exception as e: # noqa: BLE001 — the first pass's served hits still answer + degradations.partial("knowledge", "widened_hits_dropped", e) log.warning("knowledge search widened past dropped hits failed: %s", e) return served[:top_k] diff --git a/server/memory/app/answer_consistency.py b/server/memory/app/answer_consistency.py index 221986889a7..b07182dde91 100644 --- a/server/memory/app/answer_consistency.py +++ b/server/memory/app/answer_consistency.py @@ -35,6 +35,7 @@ from typing import Any from server.knowledge.app.source_corpus import LostCorpus +from server.observability import degradations from server.settings.budgets import llm_max_tokens log = logging.getLogger(__name__) @@ -172,6 +173,7 @@ async def check(llm: Any, question: str, answer: str, cited: list[Any]) -> Verdi except LostCorpus: raise except Exception as e: # noqa: BLE001 — a check never blocks an answer + degradations.partial("memory.ask", "consistency_unchecked", e) log.warning("answer consistency check failed (open): %s", e) return Verdict() @@ -312,6 +314,7 @@ async def premise_check( ) v = parse_premise(str(getattr(res, "text", "") or "")) except Exception as e: # noqa: BLE001 — a premise check never blocks an answer + degradations.partial("memory.ask", "premise_unchecked", e) log.warning("premise check failed (open): %s", e) return PremiseVerdict(ran=ran) ran = ran or v.ran diff --git a/server/memory/app/ask/completion.py b/server/memory/app/ask/completion.py index 10f66b0a731..348115312d0 100644 --- a/server/memory/app/ask/completion.py +++ b/server/memory/app/ask/completion.py @@ -116,6 +116,7 @@ async def bridge_rows_by_key(search_input: Any, bridge: str, *, top_k: int = 6) out.append(hit) return out except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.partial("memory.ask", "bridge_rows_dropped", e) logger.warning("memory.ask bridge key read failed (open): %s", e) return [] @@ -415,7 +416,8 @@ def _completion_hits(rows: list[dict[str, Any]], ranked: list[Any], explanation: source="fact", explanation=explanation, ) - except Exception: # noqa: BLE001 — skip a row that won't validate + except Exception as exc: # noqa: BLE001 — skip a row that won't validate + degradations.partial("memory.ask", "completion_row_dropped", exc) continue hit._row_identity = row_identity(r) # the row read, for the pool and the authority out.append(hit) @@ -480,6 +482,7 @@ async def _bridge_content_fallback( cues = question_cues(q) missed = unmatched_prefixes(prefixes, rows, cues, list(_parse_opts(q).values())) except Exception as e: # noqa: BLE001 — the prefix rows stand + degradations.partial("memory.ask", "bridge_content_dropped", e) logger.debug("bridge content fallback failed: %s", e) return [] if not missed: diff --git a/server/memory/app/ask/handler.py b/server/memory/app/ask/handler.py index 7364f470f80..d0600fa614f 100644 --- a/server/memory/app/ask/handler.py +++ b/server/memory/app/ask/handler.py @@ -404,6 +404,7 @@ def _grounding_for(res: MemoryAskResult, retrieval_query: str, input: MemoryAskI window=resolve_time_window(retrieval_query, input.observation_date), ) except Exception as e: # noqa: BLE001 - telemetry, never blocks the answer + degradations.partial("memory.ask", "grounding_unscored", e) log.debug("answer grounding skipped: %s", e) return Grounding() @@ -501,6 +502,7 @@ async def search(top_k: int) -> list[Any]: route_reason=ask_routing.route_reason(synth.documents), ) except Exception as e: # noqa: BLE001 - the memory path is always available + degradations.partial("memory.ask", "synthesize_route_dropped", e) log.debug("memory.ask synthesize route skipped: %s", e) return None @@ -523,7 +525,8 @@ async def _pending_extraction(input: MemoryAskInput) -> int: return await pending_extraction( org=input.org, namespace=input.namespace, agent=input.agent, user_id=uid ) - except Exception: # noqa: BLE001 — an advisory count; 0 on failure + except Exception as exc: # noqa: BLE001 — an advisory count; 0 on failure + degradations.partial("memory", "pending_count_unread", exc) return 0 diff --git a/server/memory/app/ask/identifiers.py b/server/memory/app/ask/identifiers.py index ebde9e042db..8a14a1180a8 100644 --- a/server/memory/app/ask/identifiers.py +++ b/server/memory/app/ask/identifiers.py @@ -136,7 +136,8 @@ async def _mention_window_chunks(search_input: Any, question: str, ranked: list[ from server.embedding import get_embedder qvec = list(await get_embedder().embed(question)) - except Exception: # noqa: BLE001 — length order is the fallback + except Exception as exc: # noqa: BLE001 — length order is the fallback + degradations.partial("memory.ask", "mention_ranking_dropped", exc) qvec = [] rows = await _plain_chunks( memory_repo.find_chunks_by_session_date, @@ -175,7 +176,8 @@ async def _mention_window_chunks(search_input: Any, question: str, ranked: list[ valid_at=str(r.get("valid_at") or "")[:19], ) ) - except Exception: # noqa: BLE001 — skip a row that won't validate + except Exception as exc: # noqa: BLE001 — skip a row that won't validate + degradations.partial("memory.ask", "mention_chunk_dropped", exc) continue return out @@ -278,8 +280,8 @@ def _injectable_identifiers(query_text: str) -> list[str]: if len(t) >= 5 and t.lower() not in seen: seen.add(t.lower()) out.append(t) - except Exception: # noqa: BLE001 — injection is additive; the shapes above still apply - pass + except Exception as exc: # noqa: BLE001 — injection is additive; the shapes above still apply + degradations.partial("memory.ask", "identifiers_dropped", exc) # Symbols, file names and quoted phrases. for t in _technical_identifiers(query_text or ""): if t.lower() not in seen: @@ -351,6 +353,7 @@ async def _chase_identifiers( try: rows = await _inject_identifier_memories(search_input, idents, have + added) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.partial("memory.ask", "identifier_chase_cut", e) logger.debug("identifier chase stopped: %s", e) break walked += 1 @@ -527,6 +530,41 @@ async def _read_latest_word( return rows +def _injected_hits(rows: list[Any], ranked: list[Any]) -> list[Any]: + """The rows `ranked` does not hold yet as hits, deduped by key: a fact at rank 1.0 and a + chunk just under it.""" + have = {getattr(h, "memory_key", "") for h in ranked} + out: list[Any] = [] + for r in rows: + k = str(r.get("memory_key") or "") + if not k or k in have: + continue + have.add(k) + try: + hit = _MemorySearchHit( + memory_key=k, + memory_type=str(r.get("memory_type") or "semantic"), + content_excerpt=str(r.get("content_excerpt") or ""), + distance=0.0 if not k.startswith("chunk:") else 0.05, + similarity=1.0 if not k.startswith("chunk:") else 0.95, + # Injected chunks rank just under the injected facts. + rank_score=1.0 if not k.startswith("chunk:") else 0.95, + source="chunk" if k.startswith("chunk:") else "fact", + # The fact's own clock (valid_at), not the ingest wall-clock: + # the latest-statement verifier compares this against the + # `[user @ ...]` turn stamps in chunks, and created_at is + # always later than every turn. + valid_at=str(r.get("valid_at") or r.get("created_at") or "")[:19], + version=int(r.get("version") or 0), + ) + except Exception as exc: # noqa: BLE001 — skip a row that won't validate + degradations.partial("memory.ask", "identifier_rows_dropped", exc) + continue + hit._row_identity = row_identity(r) # the row read (none for a chunk), for the authority + out.append(hit) + return out + + async def _inject_identifier_memories( search_input: Any, idents: list[str], ranked: list[Any], *, case_insensitive: bool = False ) -> list[Any]: @@ -620,6 +658,7 @@ async def _inject_identifier_memories( user_id=getattr(search_input, "user_id", None), ) except Exception as e: # noqa: BLE001 — chunks are additive too + degradations.partial("memory.ask", "identifier_chunks_dropped", e) logger.debug("identifier chunk injection failed: %s", e) rows = list(rows) + await _read_decisive_chunks( search_input, idents, qvec, case_insensitive, _lim_settings @@ -632,34 +671,7 @@ async def _inject_identifier_memories( logger.debug("identifier injection failed: %s", e) return [] - have = {getattr(h, "memory_key", "") for h in ranked} - out: list[Any] = [] - for r in rows: - k = str(r.get("memory_key") or "") - if not k or k in have: - continue - have.add(k) - try: - hit = _MemorySearchHit( - memory_key=k, - memory_type=str(r.get("memory_type") or "semantic"), - content_excerpt=str(r.get("content_excerpt") or ""), - distance=0.0 if not k.startswith("chunk:") else 0.05, - similarity=1.0 if not k.startswith("chunk:") else 0.95, - # Injected chunks rank just under the injected facts. - rank_score=1.0 if not k.startswith("chunk:") else 0.95, - source="chunk" if k.startswith("chunk:") else "fact", - # The fact's own clock (valid_at), not the ingest wall-clock: - # the latest-statement verifier compares this against the - # `[user @ ...]` turn stamps in chunks, and created_at is - # always later than every turn. - valid_at=str(r.get("valid_at") or r.get("created_at") or "")[:19], - version=int(r.get("version") or 0), - ) - except Exception: # noqa: BLE001 — skip a row that won't validate - continue - hit._row_identity = row_identity(r) # the row read (none for a chunk), for the authority - out.append(hit) + out = _injected_hits(rows, ranked) try: from server.core import request_work as _rw diff --git a/server/memory/app/ask/pool.py b/server/memory/app/ask/pool.py index a55ef1fda2d..173f5405d9b 100644 --- a/server/memory/app/ask/pool.py +++ b/server/memory/app/ask/pool.py @@ -57,6 +57,7 @@ ) from server.memory.app.ask.synthesis import _publish_window_keys from server.memory.domain.search_types import governed_after_computed +from server.observability import degradations logger = logging.getLogger(__name__) @@ -83,7 +84,8 @@ def _full_scan_window( try: intent = _pqi(question, None) - except Exception: # noqa: BLE001 — the grammar abstains, never blocks + except Exception as exc: # noqa: BLE001 — the grammar abstains, never blocks + degradations.partial("memory.ask", "query_intent_unparsed", exc) intent = None if not ( is_count_intent(intent) or _is_set_q(question) or _HOW_MANY_Q_RE.search(question or "") @@ -187,7 +189,8 @@ def _ask_pool_size( from server.memory.domain.query_intent import parse_query_intent as _pqi _early = _pqi(question, getattr(search_input, "observation_date", None) or None) - except Exception: # noqa: BLE001 — the grammar abstains, never blocks + except Exception as exc: # noqa: BLE001 — the grammar abstains, never blocks + degradations.partial("memory.ask", "query_intent_unparsed", exc) _early = None if is_count_intent(_early): window = _count_window @@ -292,7 +295,8 @@ async def _widen_by_question( _sub = await handle_memory_search(_with(search_input, query=_part)) except VectorInputTooLargeError: raise - except Exception: # noqa: BLE001 — additive + except Exception as exc: # noqa: BLE001 — additive + degradations.partial("memory.ask", "compound_part_dropped", exc) continue run.ranked.extend(h for h in _sub.results or [] if pooled.add(h)) # Multi-hop decomposition: a question whose answer needs @@ -350,7 +354,8 @@ async def _widen_by_question( _sub_hits = list(_sub.results or []) except VectorInputTooLargeError: raise - except Exception: # noqa: BLE001 — additive + except Exception as exc: # noqa: BLE001 — additive + degradations.partial("memory.ask", "entity_follow_dropped", exc) continue added = 0 for h in _sub_hits: @@ -471,7 +476,8 @@ async def _complete_options(run: _AskRun) -> None: intent = parse_query_intent( run.query_text, getattr(search_input, "observation_date", None) or None ) - except Exception: # noqa: BLE001 — the grammar abstains, it never blocks + except Exception as exc: # noqa: BLE001 — the grammar abstains, it never blocks + degradations.partial("memory.ask", "query_intent_unparsed", exc) intent = None # Option completion: a multiple-choice question diff --git a/server/memory/app/ask/question_shapes.py b/server/memory/app/ask/question_shapes.py index b259aee4ea8..e76ebe6e50b 100644 --- a/server/memory/app/ask/question_shapes.py +++ b/server/memory/app/ask/question_shapes.py @@ -8,6 +8,8 @@ import re from typing import Any +from server.observability import degradations + # An inference question asks what is likely, not what was said # — "Would Dana go on another roadtrip soon?", "Would Priya be # considered religious?", "What job might Lena pursue?". Most @@ -216,7 +218,8 @@ def _parse_options_safe(question: str) -> dict[str, str]: from server.memory.domain.ask_option_guard import parse_options return parse_options(question or "") - except Exception: # noqa: BLE001 — a parser error is not an abstain reason + except Exception as exc: # noqa: BLE001 — a parser error is not an abstain reason + degradations.partial("memory.ask", "options_unparsed", exc) return {} diff --git a/server/memory/app/ask/retrieval_legs.py b/server/memory/app/ask/retrieval_legs.py index e36cb71545c..088248a6152 100644 --- a/server/memory/app/ask/retrieval_legs.py +++ b/server/memory/app/ask/retrieval_legs.py @@ -13,6 +13,7 @@ looks_multihop, ) from server.memory.domain.search_types import hit_row_key, names_row +from server.observability import degradations from server.settings.budgets import llm_max_tokens logger = logging.getLogger(__name__) @@ -142,6 +143,7 @@ async def _pending_evidence_stage( ranked = list(_pending) + list(ranked) pending_evidence_n = len(_pending) except Exception as e: # noqa: BLE001 — pending evidence never fails an answer + degradations.partial("memory.ask", "pending_evidence_dropped", e) logger.debug("memory.ask pending evidence skipped: %s", e) return ranked, pending_evidence_n @@ -191,6 +193,7 @@ async def decompose_question(llm: Any, question: str, *, max_parts: int = 4) -> text = str(getattr(res, "text", "") or "") return parse_decomposition(text, question, max_parts=max_parts) except Exception as e: # noqa: BLE001 — additive + degradations.partial("memory.ask", "decomposition_dropped", e) logger.warning("memory.ask decompose failed (fail-open): %s", e) return [] @@ -254,6 +257,7 @@ async def decomposed_retrieval( except VectorInputTooLargeError: raise except Exception as e: # noqa: BLE001 — additive + degradations.partial("memory.ask", "decomposed_part_dropped", e) logger.warning("memory.ask decompose: part retrieval failed (fail-open): %s", e) if stats is not None: stats["failed"] = int(stats.get("failed", 0)) + 1 @@ -289,7 +293,8 @@ def _time_cue_first( try: obs = str(observation_date)[:10] if observation_date else None tw = resolve_time_window(question, obs) - except Exception: # noqa: BLE001 — a parser miss leaves the order alone + except Exception as exc: # noqa: BLE001 — a parser miss leaves the order alone + degradations.partial("memory.ask", "time_cue_unparsed", exc) return ranked if tw is None or not tw.bounded or tw.days > _TIME_CUE_MAX_DAYS or tw.kind == "habitual": return ranked @@ -348,7 +353,8 @@ async def _order_window_turns( bounds=bounds, top_k=int(settings_obj.memory_ask_cue_window_turns_top_k or 24), ) - except Exception: # noqa: BLE001 — additive, never blocks the answer + except Exception as exc: # noqa: BLE001 — additive, never blocks the answer + degradations.partial("memory.ask", "dated_turns_dropped", exc) return "", "" if not turns: return "", "" diff --git a/server/memory/app/ask_literal_evidence.py b/server/memory/app/ask_literal_evidence.py index 0e5bd8ccb04..a97002c96b4 100644 --- a/server/memory/app/ask_literal_evidence.py +++ b/server/memory/app/ask_literal_evidence.py @@ -26,6 +26,7 @@ from server.memory.api.models_search import _MemorySearchHit from server.memory.domain.question_literals import question_literals from server.memory.domain.sensitivity import without_high +from server.observability import degradations log = logging.getLogger(__name__) @@ -104,7 +105,8 @@ def turn_hits(rows: list[dict[str, Any]], ranked: list[Any], *, max_hits: int) - explanation="literal completion", ) ) - except Exception: # noqa: BLE001 — skip a row that won't validate + except Exception as exc: # noqa: BLE001 — skip a row that won't validate + degradations.partial("memory.ask", "literal_turns_dropped", exc) continue if len(out) >= max_hits: break @@ -129,6 +131,7 @@ async def literal_complete( org=org, namespace=ns, literal=lit, limit=max_hits * 2 ) except Exception as e: # noqa: BLE001 — additive, never fatal + degradations.partial("memory.ask", "literal_turns_dropped", e) log.warning("literal completion failed for %r (fail-open): %s", lit, e) # A turn that reads as high still counts as a statement, but its text never # becomes a hit or reaches the synthesis prompt. diff --git a/server/memory/app/ask_when_evidence.py b/server/memory/app/ask_when_evidence.py index b648415d952..1b056f05275 100644 --- a/server/memory/app/ask_when_evidence.py +++ b/server/memory/app/ask_when_evidence.py @@ -310,7 +310,8 @@ def cue_window_bounds( try: tw = resolve_time_window(question, str(observation_date)[:10]) _date.fromisoformat(str(observation_date)[:10]) - except Exception: # noqa: BLE001 — a parser miss or a bad date means no window + except Exception as exc: # noqa: BLE001 — a parser miss or a bad date means no window + degradations.partial("memory.ask", "time_cue_unparsed", exc) return None if tw is None or not tw.bounded or tw.kind == "habitual": obs = _date.fromisoformat(str(observation_date)[:10]) diff --git a/server/memory/app/bulk_set.py b/server/memory/app/bulk_set.py index 3007053da07..df428cbd510 100644 --- a/server/memory/app/bulk_set.py +++ b/server/memory/app/bulk_set.py @@ -87,6 +87,7 @@ PeerErased, heads_unchanged, ) +from server.observability import degradations from server.observability.budget_shape import note_budget_shape if TYPE_CHECKING: @@ -1713,6 +1714,7 @@ async def _one(idx: int, vec: list[float], candidate_rows: list[dict[str, Any]] except customer.HOLDS: raise # held, as the batch's own embeds would be: the write answers it except Exception as e: # noqa: BLE001 — the fact writes unchecked + degradations.partial("memory", "conflict_unchecked", e) log.warning("bulk_set: conflict check failed for %r: %s", entry.memory_key, e) jobs = [_one(idx, vec, prefetched.get(j)) for j, ((idx, *_), vec) in enumerate(pairs)] diff --git a/server/memory/app/classify.py b/server/memory/app/classify.py index 3c466eb76a7..a1e8faa2990 100644 --- a/server/memory/app/classify.py +++ b/server/memory/app/classify.py @@ -210,6 +210,7 @@ async def get_namespace_classify_config( params={"org": org, "ns": namespace}, ) except Exception as e: # noqa: BLE001 — a failed config read means no classifier + _degradations.partial("classify", "caller_type_kept", e) log.warning("classify config lookup failed: %s", e) return "", "" if not row: diff --git a/server/memory/app/code_grounding.py b/server/memory/app/code_grounding.py index 17e4ae6157c..69ffd15f398 100644 --- a/server/memory/app/code_grounding.py +++ b/server/memory/app/code_grounding.py @@ -168,6 +168,7 @@ async def _inject_code_context( from server.code.app.symbol import handle_code_symbol from server.memory.api.models_search import _MemorySearchHit except Exception as e: # noqa: BLE001 — code plane absent: skip + degradations.partial("memory.ask", "code_grounding_dropped", e) logger.debug("code-context imports failed: %s", e) return [] @@ -205,7 +206,8 @@ def _render(u: Any, src_tag: str) -> Any | None: valid_at="", source="code_index", ) - except Exception: # noqa: BLE001 — grounding is advisory: the hit serves without it + except Exception as exc: # noqa: BLE001 — grounding is advisory: the hit serves without it + degradations.partial("memory.ask", "code_grounding_dropped", exc) return None # Op-routing: prefer code.symbol (ONE authoritative definition) for the @@ -439,6 +441,7 @@ async def _inject_pr_facts( try: items = await repo.items_by_number(code_org, code_ns, rest) except Exception as e: # noqa: BLE001 — no gh-items rows: PR-plane facts only + degradations.partial("memory.ask", "gh_items_dropped", e) _warn_once("gh-items grounding lookup failed: %s", e) for num, row in items.items(): content = describe_item(num, row, as_of_date) @@ -457,7 +460,8 @@ async def _inject_pr_facts( source="code_index", ) ) - except Exception: # noqa: BLE001 — one malformed item is skipped + except Exception as exc: # noqa: BLE001 — one malformed item is skipped + degradations.partial("memory.ask", "gh_items_dropped", exc) continue for num, row in facts.items(): author = str(row.get("author") or "").strip() @@ -494,7 +498,8 @@ async def _inject_pr_facts( source="code_index", ) ) - except Exception: # noqa: BLE001 — one malformed fact is skipped + except Exception as exc: # noqa: BLE001 — one malformed fact is skipped + degradations.partial("memory.ask", "pr_facts_dropped", exc) continue return hits[:8] diff --git a/server/memory/app/conflicts_ops.py b/server/memory/app/conflicts_ops.py index 855fb5cf76b..91d4a060185 100644 --- a/server/memory/app/conflicts_ops.py +++ b/server/memory/app/conflicts_ops.py @@ -31,6 +31,7 @@ _ConflictRow, ) from server.memory.app import webhooks +from server.observability import degradations from server.operations.read_projection import project_rows from server.settings import settings @@ -364,6 +365,7 @@ async def handle_conflicts_resolve( conflicts_repo, input.org, input.namespace, request_scope(), fresh=True ) except Exception as e: # noqa: BLE001 — the count never fails an applied resolve + degradations.partial("conflicts.resolve", "total_unread", e) log.warning("conflicts.resolve: conflicted count failed for %s: %s", input.memory_id, e) return ConflictsResolveOutput( resolved=True, diff --git a/server/memory/app/context_pack.py b/server/memory/app/context_pack.py index c8259126330..7186deded64 100644 --- a/server/memory/app/context_pack.py +++ b/server/memory/app/context_pack.py @@ -680,6 +680,7 @@ async def _pack_decisions_from_hits( if not narrowed: records = await _decision_records(get_client(), input.org, input.namespace, keys) except Exception as e: # noqa: BLE001 — the excerpt is the fallback + degradations.partial("context.pack", "decision_records_unread", e) log.warning("context.pack: decision records unavailable: %s", e) lines: list[str] = [] citations: list[str] = [] @@ -1188,6 +1189,7 @@ def _put_optional( try: put(staged) except Exception as error: # noqa: BLE001 — a failed optional renderer leaves its prefix intact + degradations.partial("context.pack", f"{name}_dropped", error) log.warning("context.pack: section %s failed: %s", name, error) return st if contributions is not None and staged != st: @@ -1295,12 +1297,14 @@ async def _fallback(self) -> ContextPackOutput: if self._direct is not None: try: direct = await self._direct.ordinary() - except Exception: # noqa: BLE001 — a failed ordinary section is omitted without retry + except Exception as exc: # noqa: BLE001 — a failed ordinary section is omitted without retry + degradations.partial("context.pack", "knowledge_dropped", exc) self._direct = None if self._stack is not None: try: stack = await self._stack.ordinary() - except Exception: # noqa: BLE001 — a failed ordinary section is omitted without retry + except Exception as exc: # noqa: BLE001 — a failed ordinary section is omitted without retry + degradations.partial("context.pack", "memory_stack_dropped", exc) self._stack = None self._output = _render_checked_pack(self._prefix, stack, direct) self._ordinary_ready = True @@ -1328,12 +1332,14 @@ async def current(self) -> ContextPackOutput: if self._direct is not None: try: direct = await self._direct.current() - except Exception: # noqa: BLE001 — a failed optional section cannot expose a partial mixed pack + except Exception as exc: # noqa: BLE001 — a failed optional section cannot expose a partial mixed pack + degradations.partial("context.pack", "knowledge_dropped", exc) self._direct, failed = None, True if self._stack is not None: try: stack = await self._stack.current() - except Exception: # noqa: BLE001 — a failed optional section cannot expose a partial mixed pack + except Exception as exc: # noqa: BLE001 — a failed optional section cannot expose a partial mixed pack + degradations.partial("context.pack", "memory_stack_dropped", exc) self._stack, failed = None, True if failed or not self.fresh(): return await self._fallback() diff --git a/server/memory/app/deep_evidence.py b/server/memory/app/deep_evidence.py index 06fccc3041e..4a636165a2c 100644 --- a/server/memory/app/deep_evidence.py +++ b/server/memory/app/deep_evidence.py @@ -158,6 +158,7 @@ async def select_candidates( except LostCorpus: raise except Exception as e: # noqa: BLE001 — the pass is best-effort + degradations.partial("memory.ask", "deep_selection_dropped", e) log.warning("deep-evidence selector failed (fail-open to top ranked): %s", e) picks = [] if not picks: diff --git a/server/memory/app/durability_verifier.py b/server/memory/app/durability_verifier.py index 2e25ff62afe..1571b40597f 100644 --- a/server/memory/app/durability_verifier.py +++ b/server/memory/app/durability_verifier.py @@ -38,6 +38,7 @@ DURABILITY_VERIFIER_SYSTEM_PROMPT as VERIFIER_SYSTEM_PROMPT, ) from server.memory.domain.prompt_fence import FENCE_NOTE, fence, new_nonce +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -255,6 +256,7 @@ async def _ask( timeout=timeout_s, ) except Exception as exc: # noqa: BLE001 — fail open: keep every fact + degradations.partial("memory.set_from_messages", "durability_unverified", exc) log.warning("durability verifier call failed (%s); keeping all facts", type(exc).__name__) return Verdicts() v = parse_verdicts(getattr(result, "text", "") or "", len(facts), len(stored or [])) diff --git a/server/memory/app/embedder_calibration.py b/server/memory/app/embedder_calibration.py index 044a7fd40d3..d7f65b24e26 100644 --- a/server/memory/app/embedder_calibration.py +++ b/server/memory/app/embedder_calibration.py @@ -32,8 +32,10 @@ from typing import Any, Literal from server.core import readiness +from server.core.errors import caller_text from server.llm import customer from server.memory.store.rows import next_version +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -410,7 +412,8 @@ async def _embed_pair(a: str, b: str, *, query: bool) -> float: # Per-namespace overrides, populated lazily by get_namespace_calibration. _ns_overrides: dict[tuple[str, str], CalibrationResult | None] = {} -_ns_negative_at: dict[tuple[str, str], float] = {} +# (org, namespace) -> (cached None at, the failed read's text or "" for no row) +_ns_negative_at: dict[tuple[str, str], tuple[float, str]] = {} _ns_found_at: dict[tuple[str, str], float] = {} @@ -681,11 +684,12 @@ async def get_namespace_calibration(org: str, namespace: str) -> CalibrationResu < settings.memory_calibration_namespace_ttl_s ): return cached - elif ( - time.monotonic() - _ns_negative_at.get(key, 0.0) - < settings.memory_calibration_namespace_miss_ttl_s - ): - return None + else: + at, failure = _ns_negative_at.get(key, (0.0, "")) + if time.monotonic() - at < settings.memory_calibration_namespace_miss_ttl_s: + if failure: # each read served from a failed lookup names it + degradations.partial("memory", "namespace_calibration_unread", failure) + return None try: from server.core.ch import get_client @@ -711,13 +715,14 @@ async def get_namespace_calibration(org: str, namespace: str) -> CalibrationResu # Table missing or CH down — cache None so we don't hammer CH # on every search. log.debug("ns calibration lookup failed (%s); caching None briefly", e) + degradations.partial("memory", "namespace_calibration_unread", e) _ns_overrides[key] = None - _ns_negative_at[key] = time.monotonic() + _ns_negative_at[key] = (time.monotonic(), caller_text(e)) return None if row is None: _ns_overrides[key] = None - _ns_negative_at[key] = time.monotonic() + _ns_negative_at[key] = (time.monotonic(), "") return None result = CalibrationResult( diff --git a/server/memory/app/evidence_transfer.py b/server/memory/app/evidence_transfer.py index b4a1622ea70..b691639af25 100644 --- a/server/memory/app/evidence_transfer.py +++ b/server/memory/app/evidence_transfer.py @@ -37,6 +37,7 @@ from server.memory.domain.okf_evidence import evidence_is_high, evidence_keys from server.memory.domain.sensitivity import joined_overlaps_high from server.observability import audit as _audit +from server.observability import degradations log = logging.getLogger(__name__) @@ -53,7 +54,8 @@ def _decode_cursor(cursor: str) -> tuple[str, int] | None: pad = "=" * (-len(cursor) % 4) sid, idx = json.loads(base64.urlsafe_b64decode(cursor + pad).decode()) return str(sid), int(idx) - except Exception: # noqa: BLE001 — a bad cursor restarts the page, not the request + except Exception as exc: # noqa: BLE001 — a bad cursor restarts the page, not the request + degradations.partial("memory.export_evidence", "cursor_reset", exc) return None @@ -86,7 +88,8 @@ def _decode_edge_cursor(cursor: str) -> tuple[str, str, str] | None: pad = "=" * (-len(cursor) % 4) a, b, c = json.loads(base64.urlsafe_b64decode(cursor + pad).decode()) return str(a), str(b), str(c) - except Exception: # noqa: BLE001 — a bad cursor restarts the page, not the request + except Exception as exc: # noqa: BLE001 — a bad cursor restarts the page, not the request + degradations.partial("memory.export_evidence", "cursor_reset", exc) return None diff --git a/server/memory/app/extract/handler.py b/server/memory/app/extract/handler.py index 1afd86d1bc5..0ac3adf8bac 100644 --- a/server/memory/app/extract/handler.py +++ b/server/memory/app/extract/handler.py @@ -48,7 +48,6 @@ record_input_projection_failure, ) from server.observability import degradations as _degradations -from server.observability import provider_health from server.observability.otel import traced log = logging.getLogger(__name__) @@ -350,11 +349,10 @@ async def _set_record_from_messages( evidence_ids=evidence_ids, ) if not projected: - # A scope skip, not a provider failure: keep it off /v1/health. - with provider_health.unrecorded(): - _degradations.note( - "records", "projection_skipped", "read scope below the namespace" - ) + # A scope skip, not a provider failure: kept off /v1/health. + _degradations.partial( + "records", "projection_skipped", "read scope below the namespace" + ) except Exception as e: # noqa: BLE001 — a projection; the write stands log.warning("memory_records inline projection failed (non-fatal): %s", e) await record_input_projection_failure( @@ -451,6 +449,7 @@ async def _ontology_warnings(input: MemorySetFromMessagesInput, state: Any) -> l seen_verb_warnings.add(v_lc) ontology_warnings.append(f"relation_verb:{v_lc} not in accepted ontology") except Exception as e: # noqa: BLE001 — warnings are advisory + _degradations.partial("memory.set_from_messages", "ontology_warnings_dropped", e) log.warning("ontology-warning check failed (non-fatal): %s", e) return ontology_warnings diff --git a/server/memory/app/extract/judge.py b/server/memory/app/extract/judge.py index 3307dd97873..efa8b5bb4a9 100644 --- a/server/memory/app/extract/judge.py +++ b/server/memory/app/extract/judge.py @@ -18,6 +18,7 @@ _JUDGE_SYSTEM_PROMPT, with_strict_examples_preamble, ) +from server.observability import degradations from server.observability.genai import staged log = logging.getLogger("server.memory.app.extract") @@ -58,6 +59,7 @@ async def _judge_facts( except customer.HOLDS: raise # a held call is no verdict to keep every fact on: the extract waits except Exception as e: # noqa: BLE001 — a failed judge call means no verdicts, not a failed extract + degradations.partial("memory.set_from_messages", "judge_skipped", e) log.warning("extraction judge call failed (every fact kept): %s", e) return {}, None try: diff --git a/server/memory/app/extract/relations.py b/server/memory/app/extract/relations.py index 505da130812..7e43e2833b0 100644 --- a/server/memory/app/extract/relations.py +++ b/server/memory/app/extract/relations.py @@ -13,6 +13,7 @@ from server.llm.client import LLMResult, get_llm_client from server.llm.json_text import strip_code_fence from server.memory.app.extract.models import ExtractedFact +from server.observability import degradations from server.observability.genai import llm_stage log = logging.getLogger("server.memory.app.extract") @@ -83,6 +84,7 @@ async def _backfill_relations( except customer.HOLDS: raise # a held call is not a provider failure: the extract waits except Exception as e: # noqa: BLE001 — the first pass's facts stand + degradations.partial("memory.set_from_messages", "relations_unbackfilled", e) log.warning("relation backfill call failed (non-fatal): %s", e) return facts, None, 0 try: diff --git a/server/memory/app/extract/sweep.py b/server/memory/app/extract/sweep.py index f364421ac9e..537c37d5f00 100644 --- a/server/memory/app/extract/sweep.py +++ b/server/memory/app/extract/sweep.py @@ -24,6 +24,7 @@ from server.memory.app.extract.parse import _parse_fact_list from server.memory.app.extract.turns import _format_indexed_turns from server.memory.domain.extraction_policy import with_policy +from server.observability import degradations from server.observability.genai import generation_attrs, llm_stage from server.settings import settings @@ -283,6 +284,7 @@ async def _one(g_idxs: list[int], g_sents: dict[int, list[str]]) -> LLMResult | except customer.HOLDS: raise # a held call is not a provider failure: the extract waits except Exception as e: # noqa: BLE001 — the first pass's facts stand + degradations.partial("memory.set_from_messages", "coverage_sweep_dropped", e) log.warning("coverage sweep call failed (non-fatal): %s", e) return None diff --git a/server/memory/app/facts.py b/server/memory/app/facts.py index 5582bc75875..1fa292b8cc3 100644 --- a/server/memory/app/facts.py +++ b/server/memory/app/facts.py @@ -371,6 +371,7 @@ async def walk(self, input: FactsTraverseInput) -> FactsTraverseOutput: # A write in the walk's own millisecond retires it (`>` below). wrote, started = await _after_own_projections(org, ns) except Exception as e: # noqa: BLE001 — a walk never fails on its memo's marks + degradations.partial("facts.traverse", "graph_marks_unread", e) log.warning("facts.traverse: graph marks unread (%s); walking without the memo", e) return await _handle_facts_traverse_uncached(input) key = _traverse_key(input) @@ -779,6 +780,7 @@ async def handle_facts_path(input: FactsPathInput) -> FactsPathOutput: try: await _after_own_projections(input.org, input.namespace) except Exception as e: # noqa: BLE001 — a path never fails on the graph marks + degradations.partial("facts.path", "graph_marks_unread", e) log.warning("facts.path: graph marks unread (%s); walking now", e) ch = get_client() params: dict[str, Any] = { diff --git a/server/memory/app/handlers.py b/server/memory/app/handlers.py index f876254dce7..2b40f1d32b6 100644 --- a/server/memory/app/handlers.py +++ b/server/memory/app/handlers.py @@ -517,6 +517,7 @@ async def _handle_memory_get(input: MemoryGetInput) -> MemoryGetOutput: if int(r["n_30d"]) > 0 ] except Exception as e: # noqa: BLE001 — the served figures are optional detail on memory.get + degradations.partial("memory.get", "served_unread", e) log.warning("served lookup failed (non-fatal): %s", e) from server.memory.app.query import _canonical_keys_for_rows @@ -827,7 +828,7 @@ class _DeleteDeferred(BackendUnavailableError): def _check_deferred(e: Exception) -> _DeleteDeferred: """The 503 of a delete that did not finish: its check record, its tombstone, the check after it, or a retry's run of an owed check failed. A recorded check stays owed.""" - degradations.note("memory.delete_version", "check_deferred", e) + degradations.partial("memory.delete_version", "check_deferred", e) log.warning("memory.delete_version: the delete did not finish: %s", e) return _DeleteDeferred( "the delete did not finish; a retry finishes it, or the background worker once its " diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index 505b7181162..641eee3eb14 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -446,9 +446,11 @@ async def search_sections( know_result = error if isinstance(know_result, Exception): payload["knowledge"] = {"error": _leg_error("knowledge", know_result), "results": []} - payload["profile"] = { - "results": [] if isinstance(profile_rows, Exception) else list(profile_rows) - } + payload["profile"] = ( + {"error": _leg_error("profile", profile_rows), "results": []} + if isinstance(profile_rows, Exception) + else {"results": list(profile_rows)} + ) # Conversations: thread-history search, bundled so "have we discussed X" # lands in the same call. diff --git a/server/memory/app/loom_search/handler.py b/server/memory/app/loom_search/handler.py index 0f25d78b78d..518ae8ba25f 100644 --- a/server/memory/app/loom_search/handler.py +++ b/server/memory/app/loom_search/handler.py @@ -20,6 +20,7 @@ ) from server.memory.app.loom_search.fanout import search_sections from server.memory.app.loom_search.tracker_leg import prepare_tracker_search +from server.observability import degradations log = logging.getLogger(__name__) @@ -38,6 +39,7 @@ async def handle_search(input: SearchInput) -> SearchOutput: try: read, _ = await namespaces_to_search(input.org, input.namespace, namespace_scope) except Exception as e: # noqa: BLE001 — no fan-out namespaces narrows the search, never widens + degradations.partial("loom_search", "namespaces_unresolved", e) log.warning("search namespace resolution failed (non-fatal): %s", e) # Consent is narrowed below over the addressed namespace (plus the code # scope's repository namespace), so no leg reads wider than its consent. diff --git a/server/memory/app/pipeline.py b/server/memory/app/pipeline.py index 1878e3a59f0..d04dd2aef8b 100644 --- a/server/memory/app/pipeline.py +++ b/server/memory/app/pipeline.py @@ -47,6 +47,7 @@ from server.memory.domain.ownership import ownership_of, user_names_in from server.memory.domain.premise_facts import premise_facts_from_messages from server.memory.domain.recall_echoes import key_tokens, recall_echoes +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -424,6 +425,7 @@ async def _fetch_for_forget_requests( identity, [{"role": "user", "content": clause}], limit=limit ) except Exception as e: # noqa: BLE001 — a missed candidate, never a failed write + degradations.partial("memory.set_from_messages", "forget_candidates_unread", e) log.warning("forget request: candidate fetch failed (open): %s", e) continue for r in rows or []: @@ -513,6 +515,7 @@ async def _existing_keys_named(state: WorkflowState, tokens: set[str]) -> set[st ) found |= {str(r.get("memory_key") or "") for r in rows or []} except Exception as e: # noqa: BLE001 — fail open: an unknown key is not an echo + degradations.partial("memory.set_from_messages", "echo_check_skipped", e) log.warning("recall-echo key lookup failed (non-fatal): %s", e) return found @@ -780,6 +783,7 @@ async def _near(text: str, vec: list[float]) -> list[Any]: vectors = await get_embedder().embed_many(wanted) found = dict(zip(wanted, await asyncio.gather(*map(_near, wanted, vectors)), strict=True)) except Exception as e: # noqa: BLE001 — a failed read must not fail the extraction + degradations.partial("memory.set_from_messages", "durable_check_skipped", e) log.warning("verify_durable: stored-memory read failed (non-fatal): %s", e) return [] return [found.get(t, []) for t in texts] diff --git a/server/memory/app/procedure.py b/server/memory/app/procedure.py index 3d19e8ee4bb..cccd34593d4 100644 --- a/server/memory/app/procedure.py +++ b/server/memory/app/procedure.py @@ -213,7 +213,8 @@ async def _procedure_rows( found = await memory_repo.get_many_by_keys( identity, keys, scope=request_scope(), exclude_high_sensitivity=True ) - except Exception: # noqa: BLE001 — an unreadable namespace drops its candidates, not the match + except Exception as exc: # noqa: BLE001 — an unreadable namespace drops its candidates, not the match + degradations.partial("procedure", "rows_unread", exc) continue for row in found: if isinstance(row.value, dict): @@ -565,6 +566,7 @@ async def handle_procedure_locate(input: ProcedureLocateInput) -> ProcedureLocat if len(notes) >= input.max_notes: break except Exception as e: # noqa: BLE001 — notes are evidence, not the answer + degradations.partial("procedure.locate", "failure_notes_unread", e) log.debug("procedure.locate: failure notes unavailable: %s", e) rendered = render_local_context(ctx, name=name) diff --git a/server/memory/app/recall.py b/server/memory/app/recall.py index e2c84b8bd13..d989e883714 100644 --- a/server/memory/app/recall.py +++ b/server/memory/app/recall.py @@ -13,6 +13,7 @@ from server.core.naming import named from server.memory.api.models_temporal import MemoryRecallInput, MemoryRecallOutput, _RecallTurn from server.memory.domain import recall as svc +from server.observability import degradations def _session_read(thread: str, scoped: MemoryRecallInput) -> str | None: @@ -116,7 +117,8 @@ async def handle_memory_recall(input: MemoryRecallInput) -> MemoryRecallOutput: ts = datetime.fromisoformat(str(last.get("observed"))[:19]) next_cursor = encode_cursor(ts, str(last.get("eid") or "")) - except Exception: # noqa: BLE001 — the last page has no cursor + except Exception as exc: # noqa: BLE001 — the last page has no cursor + degradations.partial("memory.recall", "next_cursor_dropped", exc) next_cursor = "" else: next_offset = int(input.offset) + len(page) diff --git a/server/memory/app/recent_seeds.py b/server/memory/app/recent_seeds.py index 3b5dec4be52..c16d5db308d 100644 --- a/server/memory/app/recent_seeds.py +++ b/server/memory/app/recent_seeds.py @@ -14,6 +14,8 @@ from typing import Any +from server.observability import degradations + _SQL = """ SELECT arrayJoin(entities) AS entity, max(created_at) AS last_seen FROM ( @@ -97,7 +99,8 @@ async def recent_seed_entities( if e and e not in out: out.append(e) return out - except Exception: # noqa: BLE001 — a recency seed never fails a search + except Exception as exc: # noqa: BLE001 — a recency seed never fails a search + degradations.partial("memory.search", "recent_seeds_dropped", exc) return [] diff --git a/server/memory/app/rerank.py b/server/memory/app/rerank.py index d3d59d88391..aded93eb1e5 100644 --- a/server/memory/app/rerank.py +++ b/server/memory/app/rerank.py @@ -58,6 +58,7 @@ from server.memory.app.log_once import LogOnce from server.memory.domain.rerank_names import BUILTIN_OPENAI, is_rerank_choice from server.observability import degradations as _degradations +from server.observability import provider_health from server.observability.genai import llm_stage from server.settings import BUILTIN_COHERE, is_builtin_cohere, settings @@ -216,6 +217,7 @@ async def rerank( log.warning("rerank.call returned malformed payload; falling back") _degradations.note("rerank", "input_order_kept", "malformed payload") return candidates + provider_health.record_success("rerank") # The endpoint names a candidate by (namespace, key), and a key can name several (one per # session): each entry takes the key's next candidate in input order. @@ -288,7 +290,9 @@ async def _rerank_with_builtin_cohere( results = payload.get("results") if isinstance(payload, dict) else None if not isinstance(results, list): + _degradations.note("rerank:cohere", "input_order_kept", "malformed payload") return candidates + provider_health.record_success("rerank:cohere") ordered: list[RerankCandidate] = [] seen_idx: set[int] = set() @@ -364,7 +368,7 @@ async def _rerank_with_builtin_openai( raise # a refusal or an unread switch: never "kept the input order" except Exception as e: # noqa: BLE001 — a failed LLM rerank keeps the input order log.warning("builtin:openai rerank failed (%s); fallback", e) - _degradations.note("rerank:openai", "input_order_kept", e) + _degradations.partial("rerank:openai", "input_order_kept", e) # the LLM client counts it return candidates try: @@ -385,7 +389,7 @@ async def _rerank_with_builtin_openai( indices.append(int(item)) except (ValueError, _json.JSONDecodeError) as e: log.warning("builtin:openai rerank parse failed (%s); fallback", e) - _degradations.note("rerank:openai", "input_order_kept", f"parse: {e}") + _degradations.partial("rerank:openai", "input_order_kept", f"parse: {e}") return candidates # Apply the ranking — kept indices first (in LLM order), dropped @@ -426,6 +430,7 @@ async def get_namespace_rerank_config( params={"org": org, "ns": namespace}, ) except Exception as e: # noqa: BLE001 — a failed config read means no reranker + _degradations.partial("memory.search", "rerank_config_unread", e) log.warning("rerank config lookup failed: %s", e) return "", "" if not row: diff --git a/server/memory/app/restore.py b/server/memory/app/restore.py index 4ea0e07b7a9..eba81d9de68 100644 --- a/server/memory/app/restore.py +++ b/server/memory/app/restore.py @@ -35,6 +35,7 @@ version_over, version_time, ) +from server.observability import degradations from server.observability.budget_shape import note_budget_shape if TYPE_CHECKING: @@ -286,6 +287,7 @@ async def _plain_restore_finishes_an_undo( try: return await _an_undos_restore(input, memory_id, version) except Exception as e: # noqa: BLE001 — an unread record is no restore to finish + degradations.partial("memory.restore", "undo_record_unread", e) log.warning( "memory.restore: Undo record read failed for %s: %s", memory_id, error_summary(e) ) diff --git a/server/memory/app/retrieval/chunks.py b/server/memory/app/retrieval/chunks.py index 58bb27abab2..d864e957441 100644 --- a/server/memory/app/retrieval/chunks.py +++ b/server/memory/app/retrieval/chunks.py @@ -634,6 +634,7 @@ async def _chunk_anchor_windows( try: neighbor_rows.extend(await _chunk_query(ch, neighbor_sql, neighbor_params)) except Exception as e: # noqa: BLE001 — neighbour chunks are optional context around the hits + degradations.partial("memory.search", "chunk_windows_dropped", e) log.warning("chunk leg: neighbour window read failed (served without): %s", e) return neighbor_rows diff --git a/server/memory/app/retrieval/graph.py b/server/memory/app/retrieval/graph.py index 0f92498e6d5..39655fe1bc1 100644 --- a/server/memory/app/retrieval/graph.py +++ b/server/memory/app/retrieval/graph.py @@ -13,6 +13,7 @@ from server.memory.app.search_llm import expand_verb_synonyms from server.memory.domain.graph_paths import extend_paths from server.memory.domain.graph_quality import canonical_entity_text +from server.observability import degradations log = logging.getLogger("server.memory.app.retrieval") @@ -231,6 +232,7 @@ async def _one_hop( # Fail-open (additive leg), but LOG it — a silent `return []` here can # hide a real query bug (such as an alias shadowing a column) for an # entire leg. A cold/absent plane is normal; an exception is not. + degradations.partial("memory.search", "graph_expansion_dropped", e) log.warning("fetch_graph_neighbors failed (fail-open): %s", e) return [] @@ -326,5 +328,6 @@ async def fetch_triple_matched_memories( rows = await ch.query_all(sql, params=params) return [str(r["memory_key"]) for r in rows] except Exception as e: # noqa: BLE001 — the triple leg is additive; fail open + degradations.partial("memory.search", "triple_match_dropped", e) log.warning("fetch_triple_matched_memories failed (fail-open): %s", e) return [] diff --git a/server/memory/app/retrieval/key_axis.py b/server/memory/app/retrieval/key_axis.py index 16cde6ec4eb..1a5b3d71405 100644 --- a/server/memory/app/retrieval/key_axis.py +++ b/server/memory/app/retrieval/key_axis.py @@ -8,8 +8,10 @@ import logging from typing import Any +from server.core.errors import caller_text from server.memory.domain.import_keys import IMPORT_KEY_MATCH from server.memory.domain.search_types import SearchQuery +from server.observability import degradations log = logging.getLogger("server.memory.app.retrieval") @@ -21,9 +23,10 @@ def key_axis_from_reuse(reused_share: float, threshold: float) -> bool: return float(reused_share) >= float(threshold) -# (org, namespace) -> (probed_at_monotonic, reused_share; None when the probe failed). -# The share is cached, not the decision, so a changed threshold applies at once. -_KEY_AXIS_AUTO: dict[tuple[str, str], tuple[float, float | None]] = {} +# (org, namespace) -> (probed_at_monotonic, reused_share; None when the probe failed, +# the failed probe's text or ""). The share is cached, not the decision, so a changed +# threshold applies at once. +_KEY_AXIS_AUTO: dict[tuple[str, str], tuple[float, float | None, str]] = {} def _decide(share: float | None, settings_obj: Any) -> bool: @@ -61,6 +64,8 @@ async def key_axis_auto( key = (str(org), str(namespace)) hit = _KEY_AXIS_AUTO.get(key) if hit is not None and now - hit[0] < ttl: + if hit[2]: # each search served from a failed probe names it + degradations.partial("memory.search", "key_axis_dropped", hit[2]) return _decide(hit[1], _s) share = 0.0 try: @@ -83,10 +88,11 @@ async def key_axis_auto( if rows: share = float((rows[0] or {}).get("reused_share") or 0.0) except Exception as e: # noqa: BLE001 — a probe, never a failure; off is the cheaper side + degradations.partial("memory.search", "key_axis_dropped", e) log.warning("memory.search: key-axis auto probe failed for %s/%s: %s", org, namespace, e) - _KEY_AXIS_AUTO[key] = (now, None) + _KEY_AXIS_AUTO[key] = (now, None, caller_text(e)) return False - _KEY_AXIS_AUTO[key] = (now, share) + _KEY_AXIS_AUTO[key] = (now, share, "") return _decide(share, _s) diff --git a/server/memory/app/retrieval/search.py b/server/memory/app/retrieval/search.py index fb8e6876f6d..740161d77b9 100644 --- a/server/memory/app/retrieval/search.py +++ b/server/memory/app/retrieval/search.py @@ -42,6 +42,7 @@ hit_row_key, row_identity, ) +from server.observability import degradations log = logging.getLogger("server.memory.app.retrieval") @@ -94,6 +95,7 @@ async def _fold_reinforcement_into_rows( memory_keys=[str(r.get("memory_key") or "") for r in rows], ) except Exception as e: # noqa: BLE001 — the fold is a boost, never the leg + degradations.partial("memory.search", "reinforcement_unread", e) _reinforcement_read_failures += 1 if _reinforcement_read_failures <= 3 or _reinforcement_read_failures % 100 == 0: log.warning( diff --git a/server/memory/app/retrieval/summaries.py b/server/memory/app/retrieval/summaries.py index c550ca1987b..d12e39e0f83 100644 --- a/server/memory/app/retrieval/summaries.py +++ b/server/memory/app/retrieval/summaries.py @@ -8,6 +8,7 @@ import logging from typing import Any +from server.core.errors import caller_text from server.core.vectors.search_settings import vector_search_settings from server.memory.domain.search_parsing import _iso_date from server.memory.domain.search_types import SearchHit @@ -232,7 +233,8 @@ async def fetch_session_summaries( # not only @handles) without an LLM enrichment call or a # per-query round trip. Keyed by (org, sorted namespaces); values are lowercased # entity strings. Populated only while the read leg is enabled. -_SUMMARY_ENTITY_CACHE: dict[tuple[str, tuple[str, ...]], tuple[float, frozenset[str]]] = {} +# (org, namespaces) -> (read_at, entities, failed read's text or "") +_SUMMARY_ENTITY_CACHE: dict[tuple[str, tuple[str, ...]], tuple[float, frozenset[str], str]] = {} async def summary_entities_present(ch: Any, org: str, namespaces: list[str]) -> frozenset[str]: @@ -248,7 +250,10 @@ async def summary_entities_present(ch: Any, org: str, namespaces: list[str]) -> now = time.monotonic() cached = _SUMMARY_ENTITY_CACHE.get(key) if cached is not None and (now - cached[0]) < settings.memory_summary_entity_ttl_s: + if cached[2]: # each search served from a failed read names it + degradations.partial("memory.search", "summary_entities_unread", cached[2]) return cached[1] + failure = "" try: rows = await ch.query_all( """ @@ -263,9 +268,10 @@ async def summary_entities_present(ch: Any, org: str, namespaces: list[str]) -> ) ents = frozenset(str(r.get("e") or "") for r in rows if r.get("e")) except Exception as e: # noqa: BLE001 — a failed vocabulary read disables the summary gate + degradations.partial("memory.search", "summary_entities_unread", e) log.warning("summary_entities_present failed (fail-open): %s", e) - ents = frozenset() - _SUMMARY_ENTITY_CACHE[key] = (now, ents) + ents, failure = frozenset(), caller_text(e) + _SUMMARY_ENTITY_CACHE[key] = (now, ents, failure) return ents diff --git a/server/memory/app/search/anchor_pool.py b/server/memory/app/search/anchor_pool.py index b38b6a8a76f..4b2366105d3 100644 --- a/server/memory/app/search/anchor_pool.py +++ b/server/memory/app/search/anchor_pool.py @@ -162,4 +162,5 @@ async def _anchor_rows_for_ns(ns: str) -> tuple[str, list[dict[str, Any]]]: hit._row_identity = row_identity(row) ctx.all_hits.append(_stamp_row_owner(hit, row.get("agent"), row.get("scope"))) except Exception as e: # noqa: BLE001 — the anchor pool is an optional recall stage + degradations.partial("memory.search", "anchor_pool_dropped", e) log.warning("anchor-pool stage failed (non-fatal): %s", e) diff --git a/server/memory/app/search/ann_entity_boosts.py b/server/memory/app/search/ann_entity_boosts.py index 731631fe398..452c2f90f60 100644 --- a/server/memory/app/search/ann_entity_boosts.py +++ b/server/memory/app/search/ann_entity_boosts.py @@ -8,6 +8,7 @@ from server.core.ch import get_client from server.core.vectors.private_first import each from server.core.vectors.search_settings import vector_search_settings +from server.observability import degradations from server.observability.otel import traced log = logging.getLogger(__name__) @@ -109,6 +110,7 @@ async def _one_entity(entity: str) -> list[tuple[str, str, float]]: }, ) except Exception as e: # noqa: BLE001 — entity boost is optional; search runs without it + degradations.partial("memory.search", "entity_boost_dropped", e) log.warning("entity_vectors lookup failed for %r: %s", entity, e) return [] return [ diff --git a/server/memory/app/search/assemble.py b/server/memory/app/search/assemble.py index b6ae748bf9f..a8a98d7f1fb 100644 --- a/server/memory/app/search/assemble.py +++ b/server/memory/app/search/assemble.py @@ -22,6 +22,7 @@ from server.memory.app.served_duplicates import hide_pool_duplicates from server.memory.app.served_superseded import annotate_pool_superseded from server.memory.domain.search_types import RowKey, hit_row_key, names_row +from server.observability import degradations log = logging.getLogger(__package__) @@ -164,7 +165,8 @@ def _summary_hit_to_wire(ns: str, h: Any) -> _MemorySearchHit: try: for ns, sh in await summary_task: ctx.all_hits.append(_summary_hit_to_wire(ns, sh)) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the pool answers without the session summaries + degradations.partial("memory.search", "session_summaries_dropped", e) log.warning("session-summary leg failed (non-fatal): %s", e) # Fold the PRE-BUILT entity summaries in as additive dense rows (source="entity_summary"; # calibrated into the pool band by the assembler, never displacing a fact). Default OFF → @@ -173,13 +175,15 @@ def _summary_hit_to_wire(ns: str, h: Any) -> _MemorySearchHit: try: for ns, eh in await entity_summary_task: ctx.all_hits.append(_summary_hit_to_wire(ns, eh)) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the pool answers without the entity summaries + degradations.partial("memory.search", "entity_summaries_dropped", e) log.warning("entity-summary leg failed (non-fatal): %s", e) if observation_task is not None: try: for ns, oh in await observation_task: ctx.all_hits.append(_summary_hit_to_wire(ns, oh)) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the pool answers without the observations + degradations.partial("memory.search", "observations_dropped", e) log.warning("observation leg failed (non-fatal): %s", e) # Digest-anchored expansion: the sessions behind the top-m digests contribute their own # top-k facts as candidates. The assembly so far is charged to `assemble` first, so the diff --git a/server/memory/app/search/computed.py b/server/memory/app/search/computed.py index a242287cf62..47bc700125c 100644 --- a/server/memory/app/search/computed.py +++ b/server/memory/app/search/computed.py @@ -144,7 +144,8 @@ async def _exp(v: str | None) -> list[str] | None: result = agg except VectorInputTooLargeError: raise - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the hits answer without the computed count + degradations.partial("memory.search", "aggregate_dropped", e) log.warning("derived aggregate leg failed (non-fatal): %s", e) cache["v"] = result return result @@ -182,7 +183,8 @@ async def _maybe_temporal_diff(ctx: SearchContext) -> dict[str, Any] | None: to_observation=to_observation, run_id=str(getattr(input, "run_id", "") or ""), ) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the hits answer without the date difference + degradations.partial("memory.search", "temporal_diff_dropped", e) log.warning("temporal diff leg failed (non-fatal): %s", e) cache["v"] = result return result @@ -273,7 +275,8 @@ async def _floor_and_computed_evidence( evidence_support_count = 0 try: evidence_support_count = await _evidence_support_count(input, final_hits) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — calibration reads no support: confidence may drop + degradations.partial("memory.search", "evidence_support_unread", e) log.warning("evidence support lookup failed (non-fatal): %s", e) _clock.mark("evidence_support") return final_hits, derived_aggregate, evidence_support_count diff --git a/server/memory/app/search/consistency.py b/server/memory/app/search/consistency.py index 5e42c73c5c7..8f206ad597d 100644 --- a/server/memory/app/search/consistency.py +++ b/server/memory/app/search/consistency.py @@ -13,7 +13,7 @@ from server.core.ch import sequential_reads, sequential_reads_active from server.core.datetimes import naive_utc_now -from server.core.errors import VectorInputTooLargeError +from server.core.errors import VectorInputTooLargeError, caller_text from server.memory.api.models_search import MemorySearchInput, MemorySearchOutput, _MemorySearchHit from server.memory.app.recent_writes import written_recently from server.memory.app.search.context import SearchContext @@ -51,6 +51,7 @@ async def _written_elsewhere( try: return await namespace_write_marks.written_within(org, namespace, window_s) except Exception as e: # noqa: BLE001 — the after-the-fact re-reads still apply + degradations.partial("memory.search", "read_your_writes_unchecked", e) log.warning("memory.search: write-mark read failed: %s", e) return False @@ -153,7 +154,6 @@ async def _consistency_reread( # the same question minutes later answers correctly). Run the whole search once more with # `select_sequential_consistency = 1` on every statement; adopt the retry when it found # anything. Costs one extra pass only on the path that was about to abstain anyway. - from server.memory.app.search import handle_memory_search from server.memory.store import read_your_writes_enabled _rw_window_s = float(_settings.ch_read_your_writes_window_s) @@ -176,21 +176,9 @@ async def _consistency_reread( "consistency (read-your-writes, cross-process)", _newest_hit_age_s(final_hits), ) - reread = None - with degradations.scoped(): # the re-read's notes reach the request if it is served - try: - with sequential_reads(): - reread = await asyncio.wait_for( - handle_memory_search(reread_input), - timeout=search_budget.remaining_wall_s(), - ) - except TimeoutError: - log.warning("memory.search: fresh-hit sequential re-read exceeded the wall budget") - except VectorInputTooLargeError: - raise - except Exception as e: # noqa: BLE001 — an optional re-read; the first pass stands - log.warning("memory.search: fresh-hit sequential re-read failed: %s", e) - reread_noted = degradations.current() + reread, reread_noted = await _sequential_pass( + reread_input, search_budget, "fresh-hit sequential re-read" + ) if reread is not None and reread.results: reread.retrieval_work = { **dict(reread.retrieval_work or {}), @@ -210,21 +198,9 @@ async def _consistency_reread( "sequential consistency (read-your-writes)", len(ctx.namespaces), ) - retry_result = None - with degradations.scoped(): # as above: the retry's notes, if it is served - try: - with sequential_reads(): - retry_result = await asyncio.wait_for( - handle_memory_search(reread_input), - timeout=search_budget.remaining_wall_s(), - ) - except TimeoutError: - log.warning("memory.search: sequential-consistency retry exceeded the wall budget") - except VectorInputTooLargeError: - raise - except Exception as e: # noqa: BLE001 — an optional retry; the first pass stands - log.warning("memory.search: sequential-consistency retry failed: %s", e) - retry_noted = degradations.current() + retry_result, retry_noted = await _sequential_pass( + reread_input, search_budget, "sequential-consistency retry" + ) if retry_result is not None and retry_result.results: log.info( "memory.search: sequential-consistency retry found %d hit(s) the first " @@ -240,6 +216,36 @@ async def _consistency_reread( return None +async def _sequential_pass( + reread_input: MemorySearchInput, search_budget: Any, what: str +) -> tuple[MemorySearchOutput | None, list[str]]: + """The whole search once more under sequential consistency, within the wall budget: + its answer (None when it failed or ran out of time) and the notes it took inside + `scoped()`, which reach the request only if the caller serves it. A failure is noted + after the scope, so it is named whether or not the re-read is served.""" + from server.memory.app.search import handle_memory_search + + result, failure = None, "" + with degradations.scoped(): + try: + with sequential_reads(): + result = await asyncio.wait_for( + handle_memory_search(reread_input), + timeout=search_budget.remaining_wall_s(), + ) + except TimeoutError: + log.warning("memory.search: %s exceeded the wall budget", what) + except VectorInputTooLargeError: + raise + except Exception as e: # noqa: BLE001 — an optional re-read; the first pass stands + log.warning("memory.search: %s failed: %s", what, e) + failure = caller_text(e) + noted = degradations.current() + if failure: + degradations.partial("memory.search", "read_your_writes_unchecked", failure) + return result, noted + + def _serve_notes_of(noted: list[str]) -> None: """The pass serves its re-read's answer, so it names the re-read's notes in place of its own. `handle_memory_search` runs each pass in a `degradations.unit()`: this diff --git a/server/memory/app/search/digest_descent.py b/server/memory/app/search/digest_descent.py index 4803e36541e..62c0c262d6b 100644 --- a/server/memory/app/search/digest_descent.py +++ b/server/memory/app/search/digest_descent.py @@ -148,5 +148,6 @@ async def _rows_for_target( ctx.all_hits.append(hit) added += 1 ctx.actual_work["digest_descent_added"] = added - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the pool answers without the descent's facts + degradations.partial("memory.search", "digest_descent_dropped", e) log.warning("digest descent stage failed (non-fatal): %s", e) diff --git a/server/memory/app/search/embed.py b/server/memory/app/search/embed.py index 2e9986c8962..69acc03fa5e 100644 --- a/server/memory/app/search/embed.py +++ b/server/memory/app/search/embed.py @@ -11,6 +11,7 @@ from server.memory.app.search.budget import SearchBudget from server.memory.app.search.query_spelling import embed_query from server.memory.domain.search_prompts import _HYDE_PROMPT +from server.observability import degradations from server.observability.genai import llm_stage from server.settings.budgets import llm_max_tokens @@ -131,6 +132,7 @@ async def _embed_search_query( # Re-append the date suffix so dates survive the overwrite. hyde_query = f"{input.query}\n{hyde_text}{date_suffix}" except Exception as e: # noqa: BLE001 — HyDE is optional; the plain query embed still runs + degradations.partial("memory.search", "hyde_dropped", e) log.warning("HyDE generation failed (non-fatal): %s", e) async def embed(text: str) -> list[float]: diff --git a/server/memory/app/search/fallbacks.py b/server/memory/app/search/fallbacks.py index 6ee6dede64a..4fffc64f993 100644 --- a/server/memory/app/search/fallbacks.py +++ b/server/memory/app/search/fallbacks.py @@ -14,6 +14,7 @@ from server.memory.app.search.scoring import drop_rerank_trail from server.memory.app.search.verdict import gate_order from server.memory.domain.search_types import hit_sort_key +from server.observability import degradations log = logging.getLogger(__package__) @@ -107,5 +108,6 @@ async def _maybe_iterative_retry(ctx: SearchContext) -> None: ctx.final_hits = final_hits[: input.top_k] except VectorInputTooLargeError: raise - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the first pass's hits answer without the retry's + degradations.partial("memory.search", "retry_dropped", e) log.warning("iterative retrieve retry failed: %s", e) diff --git a/server/memory/app/search/key_match.py b/server/memory/app/search/key_match.py index 20cc2e602d8..d694b563191 100644 --- a/server/memory/app/search/key_match.py +++ b/server/memory/app/search/key_match.py @@ -392,5 +392,6 @@ async def _rows_for_ns(ns: str) -> tuple[str, list[dict[str, Any]], bool]: ctx.actual_work["key_match_added"] = added if component_only: ctx.actual_work["key_match_component_only"] = True - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — the pool answers without the key matches + degradations.partial("memory.search", "key_match_dropped", e) log.warning("key-match stage failed (non-fatal): %s", e) diff --git a/server/memory/app/search/output.py b/server/memory/app/search/output.py index 200530ad0f4..2f54fbf7805 100644 --- a/server/memory/app/search/output.py +++ b/server/memory/app/search/output.py @@ -61,7 +61,7 @@ async def _serve_parked_page(input: MemorySearchInput) -> MemorySearchOutput: embedder_name = "" try: embedder_name = str(getattr(get_embedder(), "model_name", "") or "") - except Exception: # noqa: BLE001 + except Exception: # noqa: BLE001 — only the model label goes blank pass empty = MemorySearchOutput( results=[], @@ -456,6 +456,7 @@ async def _finish_search_output( _output.next_page = _pages.make_handle(_blob_key, 0) ctx.actual_work["page_tail_rows"] = len(ctx.page_tail) except Exception as e: # noqa: BLE001 — a page handle is a courtesy, never a failure + _degradations.partial("memory.search", "next_page_dropped", e) log.warning("memory.search page handle not stored (fail-open): %s", e) try: from server.memory.app.pending_disclosure import pending_extraction as _pending @@ -466,7 +467,8 @@ async def _finish_search_output( agent=getattr(input, "agent", "*"), user_id=getattr(input, "user_id", None), ) - except Exception: # noqa: BLE001 + except Exception as exc: # noqa: BLE001 — a disclosure count: 0, named in degraded + _degradations.partial("memory", "pending_count_unread", exc) _output.pending_extraction = 0 _schedule_trace_log( input, _output, embedder, search_budget.elapsed_ms(), query_vec=ctx.query_vec diff --git a/server/memory/app/search/payload.py b/server/memory/app/search/payload.py index 2c2e07b1161..f951036278d 100644 --- a/server/memory/app/search/payload.py +++ b/server/memory/app/search/payload.py @@ -43,7 +43,8 @@ def _resolve_relative_words(hits: list[Any]) -> None: new = resolve_relative_phrase(text, anchor) if new != text: h.content_excerpt = new - except Exception: # noqa: BLE001 — a rendering nicety never breaks a search + except Exception as exc: # noqa: BLE001 — a rendering nicety never breaks a search + degradations.partial("memory.search", "relative_dates_unresolved", exc) continue @@ -263,7 +264,7 @@ async def _fill_hit_tags( got = list(stamped) if stamped is not None else by_key.get((ns, str(h.memory_key))) try: h.tags = list(got) if got else [] - except Exception: # noqa: BLE001 + except Exception: # noqa: BLE001 — only a foreign hit type refuses the field continue if got: filled += 1 @@ -382,7 +383,7 @@ def _body_row(h: Any) -> Any: h.body_truncated = True h.next = f'memory.get(memory_key="{h.memory_key}")' elided += 1 - except Exception: # noqa: BLE001 + except Exception: # noqa: BLE001 — only a foreign hit type refuses the field pass continue v = body_row.value @@ -392,7 +393,7 @@ def _body_row(h: Any) -> Any: try: h.content_excerpt = text h.body_truncated = False - except Exception: # noqa: BLE001 + except Exception: # noqa: BLE001 — only a foreign hit type refuses the field continue spent += cost returned += 1 @@ -401,7 +402,7 @@ def _body_row(h: Any) -> Any: try: h.body_truncated = True h.next = f'memory.get(memory_key="{h.memory_key}")' - except Exception: # noqa: BLE001 + except Exception: # noqa: BLE001 — only a foreign hit type refuses the field continue elided += 1 return (returned, elided, tokens) @@ -548,7 +549,7 @@ async def _expand_source_bodies( h.content_excerpt = text h.body_truncated = False h.score_components = {**(getattr(h, "score_components", {}) or {}), "source_body": 1.0} - except Exception: # noqa: BLE001 + except Exception: # noqa: BLE001 — only a foreign hit type refuses the field continue served.add(eid) spent += cost @@ -582,5 +583,5 @@ def _apply_bodies(hits: list[Any], input: Any) -> None: if new != body: try: h.content_excerpt = new - except Exception: # noqa: BLE001 + except Exception: # noqa: BLE001 — only a foreign hit type refuses the field pass diff --git a/server/memory/app/search/query_spelling.py b/server/memory/app/search/query_spelling.py index 222524e3384..bdd2a7ad8ef 100644 --- a/server/memory/app/search/query_spelling.py +++ b/server/memory/app/search/query_spelling.py @@ -20,6 +20,7 @@ from server.memory.domain.query_spelling import apply_spellings, pick_spellings, spelling_candidates from server.memory.domain.search_types import SearchQuery from server.memory.store.query_spellings import spelling_rows +from server.observability import degradations from server.settings import settings log = logging.getLogger(__package__) @@ -100,6 +101,7 @@ async def _lookup( with statement_timeout(settings.memory_search_spelling_lookup_timeout_s): rows = await spelling_rows(get_client(), q, tokens) except Exception as e: # noqa: BLE001 — the spelling is a recall aid; the query embeds as typed + degradations.partial("memory.search", "query_spellings_skipped", e) # Read after the await. A failure recorded since this lookup started # (or a back-off begun) is the same slow moment, so it counts once. failures, retry_at = _failed.get(where, (0, 0.0)) @@ -171,6 +173,7 @@ async def embed_query( try: return await embed(apply_spellings(text, spellings)), spellings except Exception as e: # noqa: BLE001 — the rewrite is a recall aid; the vector as typed serves + degradations.partial("memory.search", "query_spellings_skipped", e) failure = e if as_typed is None and isinstance(failure, EmbedTimeoutError): # The provider hangs: only an embedding-cache hit can still answer diff --git a/server/memory/app/search/ranking.py b/server/memory/app/search/ranking.py index 00901b44277..85389b6d6c2 100644 --- a/server/memory/app/search/ranking.py +++ b/server/memory/app/search/ranking.py @@ -18,6 +18,7 @@ _record_rerank_trail, ) from server.memory.domain.search_types import RANK_SCORE_PRE_RERANK, hit_sort_key +from server.observability import degradations log = logging.getLogger(__package__) @@ -50,6 +51,7 @@ async def _apply_mention_boost(ctx: SearchContext) -> None: str(r["memory_key"]): [str(e) for e in (r["entities"] or []) if e] for r in _rows } except Exception as e: # noqa: BLE001 — a boost, never a failure + degradations.partial("memory.search", "mention_boost_dropped", e) log.warning("memory.search: mention boost entity read failed: %s", e) return ctx.actual_work["mention_boost_filled"] = sum(1 for v in entities_by_key.values() if v) diff --git a/server/memory/app/search/scope.py b/server/memory/app/search/scope.py index 402d3a81fc6..70fd106e42f 100644 --- a/server/memory/app/search/scope.py +++ b/server/memory/app/search/scope.py @@ -21,6 +21,7 @@ from server.memory.api.models_search import SEARCH_ENTITY_FILTER_MAX, MemorySearchInput from server.memory.app.search.query_plan import _enrichment_parser_gate_active from server.memory.domain.graph_quality import names_only +from server.observability import degradations log = logging.getLogger(__package__) @@ -256,6 +257,7 @@ async def _resolve_entity_scope( except VectorInputTooLargeError: raise except Exception as e: # noqa: BLE001 — canonical entity lookup is optional; raw filter kept + degradations.partial("memory.search", "entity_aliases_dropped", e) log.warning("entity canonical lookup failed (non-fatal): %s", e) elif _canonical_task is not None: # Parallel path: the lookup was launched before the embed and @@ -265,5 +267,6 @@ async def _resolve_entity_scope( except VectorInputTooLargeError: raise except Exception as e: # noqa: BLE001 — canonical entity lookup is optional; raw filter kept + degradations.partial("memory.search", "entity_aliases_dropped", e) log.warning("entity canonical lookup failed (non-fatal): %s", e) run.effective_entity_filter = effective_entity_filter diff --git a/server/memory/app/search/telemetry.py b/server/memory/app/search/telemetry.py index c29cbf108c4..6303b316ed9 100644 --- a/server/memory/app/search/telemetry.py +++ b/server/memory/app/search/telemetry.py @@ -244,7 +244,7 @@ async def _bg() -> None: [row], settings={"async_insert": 1, "wait_for_async_insert": 0}, ) - except Exception as e: # noqa: BLE001 + except Exception as e: # noqa: BLE001 — a ledger row, never the answer log.warning("%s write failed (non-fatal): %s", table, e) after_write.schedule(_bg(), name="memory.search.trace_log") diff --git a/server/memory/app/search/term_leg.py b/server/memory/app/search/term_leg.py index 571e84b01c5..2c0dfd708a1 100644 --- a/server/memory/app/search/term_leg.py +++ b/server/memory/app/search/term_leg.py @@ -356,6 +356,7 @@ async def _score( try: vectors = await live_vectors(org, namespace, idents, model=model, sequential=False) except Exception as e: # noqa: BLE001 — a score is not worth failing the search over + degradations.partial("memory.search", "term_scores_unread", e) log.warning("term leg scores not read: %s", error_summary(e)) return for ident, hit in zip(idents, hits, strict=True): diff --git a/server/memory/app/search/tiers.py b/server/memory/app/search/tiers.py index 38e1a553ea7..0173ec6f1c9 100644 --- a/server/memory/app/search/tiers.py +++ b/server/memory/app/search/tiers.py @@ -114,7 +114,8 @@ async def _prepend_tier( created_at=str(getattr(r, "created_at", "") or ""), score_components={tier: 1.0}, ) - except Exception: # noqa: BLE001 — a row the hit model refuses is left out + except Exception as exc: # noqa: BLE001 — a row the hit model refuses is left out + degradations.partial("memory.search", "tier_row_dropped", exc) continue who = [getattr(r, c, None) for c in ("agent", "user_id", "session_id")] if None not in who: diff --git a/server/memory/app/search/vector_legs.py b/server/memory/app/search/vector_legs.py index 0b47a31ad79..e580b45a60a 100644 --- a/server/memory/app/search/vector_legs.py +++ b/server/memory/app/search/vector_legs.py @@ -119,7 +119,7 @@ async def _search_one(ctx: SearchContext, ns: str) -> tuple[str, list[Any]]: # empty leg for this namespace, recorded on `degraded` so the caller # can see the answer was drawn from less than the store holds. log.warning("memory.search vector leg failed open on fresh-part error (ns=%s): %s", ns, e) - _degradations.note("clickhouse", "vector_leg_empty", "fresh-part code 10 after retries") + _degradations.partial("clickhouse", "vector_leg_empty", "fresh-part code 10 after retries") return ns, [] @@ -206,6 +206,7 @@ async def _run_vector_legs( try: ctx.entity_boost_by_key = await entity_boost_task except Exception as e: # noqa: BLE001 — entity boost is optional; search runs without it + _degradations.partial("memory.search", "entity_boost_dropped", e) log.warning("entity_vectors ANN read failed (non-fatal): %s", e) # Cross-namespace ordering is pure score-rank: private-first is already diff --git a/server/memory/app/search_bm25.py b/server/memory/app/search_bm25.py index 1e0d4a49089..2c7e990fadd 100644 --- a/server/memory/app/search_bm25.py +++ b/server/memory/app/search_bm25.py @@ -6,6 +6,7 @@ from server.core import bm25 from server.memory.domain.search_types import _CHClient +from server.observability import degradations from server.settings import settings _BM25_CORPUS_CACHE: dict[tuple[str, str], tuple[float, int, float]] = {} @@ -246,6 +247,7 @@ async def _read(tail: bool) -> tuple[list[dict[str, Any]], list[dict[str, Any]] return None _BM25_CORPUS_CACHE[cache_key] = (_time.time(), n_total, avgdl) except Exception as e: # noqa: BLE001 — a failed BM25 stats read disables BM25 scoring + degradations.partial("memory.search", "bm25_unweighted", e) bm25.record_stats_failure("memory", e) return None diff --git a/server/memory/app/search_pages.py b/server/memory/app/search_pages.py index f699def75f9..52f4589367c 100644 --- a/server/memory/app/search_pages.py +++ b/server/memory/app/search_pages.py @@ -101,7 +101,8 @@ def unparked(row: dict[str, Any]) -> _MemorySearchHit | None: chunk_typed = bool(r.pop("chunk_typed", False)) try: hit = _MemorySearchHit.model_validate(r) - except Exception: # noqa: BLE001 — a row this build cannot read is skipped + except Exception as exc: # noqa: BLE001 — a row this build cannot read is skipped + degradations.partial("memory.search", "parked_row_dropped", exc) return None if identity is not None: hit._row_identity = tuple(identity) diff --git a/server/memory/app/served_duplicates.py b/server/memory/app/served_duplicates.py index 94e86fb6004..e414f8c3f1a 100644 --- a/server/memory/app/served_duplicates.py +++ b/server/memory/app/served_duplicates.py @@ -25,6 +25,7 @@ from server.identity.domain.read_scope import ReadFilters from server.memory.domain.search_types import RowKey, hit_row_key, names_row, record_row_key from server.memory.store.dedup import CanonicalRow, DuplicateStatus +from server.observability import degradations log = logging.getLogger(__name__) @@ -129,6 +130,7 @@ async def hide_pool_duplicates(ctx: Any) -> None: found = await memory_repo.status_by_rows(input.org, rows, scope=scope) truth: _Truth = {record_row_key(r): r for r in found} except Exception as e: # noqa: BLE001 — hiding is a filter, never a failure + degradations.partial("memory.search", "duplicates_unhidden", e) log.warning("memory.search: duplicate status read failed: %s", e) return dups = [h for h in facts if _is_duplicate(truth.get(hit_row_key(h, ns_default)))] @@ -142,6 +144,7 @@ async def hide_pool_duplicates(ctx: Any) -> None: input.org, sorted({_hit_ns(h, ns_default) for h in dups}), ids, scope ) except Exception as e: # noqa: BLE001 — hiding is a filter, never a failure + degradations.partial("memory.search", "canonicals_dropped", e) log.warning("memory.search: canonical read failed: %s", e) ctx.all_hits = _rewrite_pool(ctx.all_hits, dups, truth, canon, ns_default, ctx.actual_work) diff --git a/server/memory/app/session_brief.py b/server/memory/app/session_brief.py index edca536b3e8..c3d1cd0429f 100644 --- a/server/memory/app/session_brief.py +++ b/server/memory/app/session_brief.py @@ -17,7 +17,7 @@ from server.core.ch import get_client from server.core.datetimes import naive_utc_now -from server.core.errors import BackendUnavailableError +from server.core.errors import BackendUnavailableError, caller_text from server.core.naming import named from server.identity.app.request_scope import request_scope from server.identity.domain.read_scope import WHOLE_NAMESPACE, ReadFilters @@ -38,6 +38,7 @@ from server.memory.domain import session_brief_render as sb_render from server.memory.domain.extraction_policy import with_policy from server.memory.store import session_briefs as repo +from server.observability import degradations from server.observability.budget_shape import note_budget_shape from server.observability.genai import staged from server.settings import settings @@ -152,21 +153,22 @@ def fallback() -> sb.BriefSections: except Exception as e: # a failed call costs this window only if operator_policy and isinstance(e, customer.ModelCallsDisabled): raise # a switched-off org stops the save under a policy + degradations.partial("session.brief_save", "window_model_dropped", e) log.warning( "session.brief_save: model call failed (%s); window revised without the model", e, ) return fallback(), 0, 0, 0, False + rejected: object = "unparseable reply" try: parsed = sb.parse_revision(result.text) except Exception as e: # noqa: BLE001 — a rejected reply costs this window only - log.warning( - "session.brief_save: model reply rejected (%s); window revised without the model", e - ) - parsed = None + rejected, parsed = caller_text(e), None if parsed is None: + degradations.partial("session.brief_save", "window_model_dropped", rejected) log.warning( - "session.brief_save: unparseable model output; window revised without the model" + "session.brief_save: model reply rejected (%s); window revised without the model", + rejected, ) return ( fallback(), diff --git a/server/memory/app/set_commit.py b/server/memory/app/set_commit.py index eb0e78fdb15..5141945a9be 100644 --- a/server/memory/app/set_commit.py +++ b/server/memory/app/set_commit.py @@ -62,6 +62,7 @@ heads_unchanged, ) from server.memory.store.rows import identity_key +from server.observability import degradations log = logging.getLogger(__name__) @@ -171,7 +172,8 @@ def set_peers(conflict_result: Any) -> list[Any]: similarity=round(float(getattr(p, "similarity", 0.0) or 0.0), 4), ) ) - except Exception: # noqa: BLE001 — a malformed peer must not fail the write + except Exception as exc: # noqa: BLE001 — a malformed peer must not fail the write + degradations.partial("memory.set", "peers_dropped", exc) continue return out diff --git a/server/memory/app/stack.py b/server/memory/app/stack.py index b780d62599d..d65f9f9010a 100644 --- a/server/memory/app/stack.py +++ b/server/memory/app/stack.py @@ -17,6 +17,7 @@ from server.knowledge.app.source_search_proofs import SearchProofs from server.memory.api.models_lifecycle import MemoryStackInput, MemoryStackOutput, _StackEntry from server.memory.app.stack_knowledge import StackKnowledge +from server.observability import degradations log = logging.getLogger(__name__) @@ -102,6 +103,7 @@ async def _stack_profile(input: MemoryStackInput, fill: _StackFill) -> None: ) fill.section_counts["profile"] = prof_out.section_count except Exception as e: # noqa: BLE001 — a failed profile section must not fail the stack + degradations.partial("memory.stack", "profile_dropped", e) log.warning("memory.stack: profile.render fan-out failed: %s", e) @@ -266,6 +268,7 @@ async def _stack_procedures(input: MemoryStackInput, fill: _StackFill) -> None: ) ) except Exception as e: # noqa: BLE001 — a failed procedure section must not fail the stack + degradations.partial("memory.stack", "procedures_dropped", e) log.warning("memory.stack: procedure.match fan-out failed (non-fatal): %s", e) @@ -355,6 +358,7 @@ async def run_checked_stack(input: MemoryStackInput, plan: ReadPlan) -> CheckedS input.org, input.namespace, input.agent, seed, int(input.knowledge_top_k), plan ) except Exception as e: # noqa: BLE001 — a failed knowledge section must not fail the stack + degradations.partial("memory.stack", "knowledge_dropped", e) log.warning("memory.stack: knowledge fan-out failed (non-fatal): %s", e) return CheckedStack(fill, knowledge, plan.marked) diff --git a/server/memory/app/webhooks.py b/server/memory/app/webhooks.py index df2b1becf21..019931237c8 100644 --- a/server/memory/app/webhooks.py +++ b/server/memory/app/webhooks.py @@ -118,7 +118,7 @@ async def _fresh_hooks() -> Registry: refresh_s=settings.memory_webhook_refresh_seconds, max_stale_s=float("inf") ) if hooks is None: - degradations.note("memory.webhook", "registry_unread") + degradations.partial("memory.webhook", "registry_unread") return {} return hooks @@ -213,7 +213,7 @@ async def announce( ] await store.insert_outbox(rows) except Exception as e: # noqa: BLE001 — the write is in; its announcement must not fail it - degradations.note("memory.webhook", "not_announced", e) + degradations.partial("memory.webhook", "not_announced", e) log.warning("memory webhooks: %d changes not announced: %s", len(changes), e) return bool(rows) diff --git a/server/memory/app/write.py b/server/memory/app/write.py index 437ff326347..9345e70c80f 100644 --- a/server/memory/app/write.py +++ b/server/memory/app/write.py @@ -56,6 +56,7 @@ from server.memory.store.lifecycle import finish_followups from server.memory.store.pg_memory import AdmissionContendedError, HeadMoved from server.memory.store.rows import next_version, version_over +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -241,6 +242,7 @@ async def _set_resolve_type(input: MemorySetInput) -> tuple[MemorySetInput, str, except customer.HOLDS: raise # a refusal or an unread switch, not a classifier fault except Exception as e: # noqa: BLE001 — classify failure keeps the caller-supplied type + degradations.partial("classify", "caller_type_kept", e) log.warning("classify failed (non-fatal); using caller-supplied type: %s", e) resolved_memory_type = input.memory_type diff --git a/server/memory/app/write_fence.py b/server/memory/app/write_fence.py index 26d9e5519e4..28448ee3af3 100644 --- a/server/memory/app/write_fence.py +++ b/server/memory/app/write_fence.py @@ -61,7 +61,7 @@ async def _committed_above( try: return await memory_repo.versions_above(org, namespace, memory_rows, ch=ch) except Exception as e: # noqa: BLE001 — the fence must not fail the write it guards - degradations.note("write_fence", "versions_kept", e) + degradations.partial("write_fence", "versions_kept", e) log.warning("write fence: committed versions unread, rows keep their versions: %s", e) return None diff --git a/server/tasks/store/runs.py b/server/tasks/store/runs.py index 85919457eaf..b95c10cd5d5 100644 --- a/server/tasks/store/runs.py +++ b/server/tasks/store/runs.py @@ -19,7 +19,7 @@ from server.core.ch import sequential_reads from server.core.leases import key_exists from server.identity.domain.read_scope import ReadFilters, scope_and -from server.observability import degradations, provider_health +from server.observability import degradations from server.observability.store.event_reads import MASKED_EVENTS from server.tasks.store.rows import RunLedgerRow @@ -136,8 +136,7 @@ def _keeper_failed(e: BaseException, what: str = "Keeper claim failed") -> None: if what not in _keeper_errors_logged: _keeper_errors_logged.add(what) log.warning("run.begin: %s, checking the run row only: %s", what, e) - with provider_health.unrecorded(): - degradations.note("run_claims", "row_check_only", e) + degradations.partial("run_claims", "row_check_only", e) async def claim_run( @@ -181,8 +180,7 @@ async def _claim_holder(ch: Any, key: str) -> RunClaim | NoClaim: ) except Exception as e: # noqa: BLE001 — unreadable counts as another user's claim log.debug("run.begin: claim %s not readable: %s", key, e) - with provider_health.unrecorded(): - degradations.note("run_claims", "claim_unreadable", e) + degradations.partial("run_claims", "claim_unreadable", e) return RunClaim(won=False, user_id="", session_id="", unreadable=True) if row is None: return NoClaim.RELEASED diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt new file mode 100644 index 00000000000..81b7c3fa395 --- /dev/null +++ b/tests/unit/degraded_unnoted.txt @@ -0,0 +1,313 @@ +# Broad handlers in server/code/app and server/memory/app that name nothing in +# `degraded`, each with why it need not (tests/unit/test_degraded_unnoted.py lists the +# categories). The list only shrinks: a handler that serves a smaller answer notes it. + +server/code/app/answers.py::_memory_context_cacheable::1 cache_fallback +server/code/app/answers_cache.py::_check_stored::1 write +server/code/app/answers_cache.py::_erasure_may_have_passed::1 cache_fallback +server/code/app/answers_cache.py::_exact_cached::1 cache_fallback +server/code/app/answers_cache.py::_pre_synthesis_cache_on::1 settings +server/code/app/answers_cache.py::_remember::1 write +server/code/app/answers_cache.py::_request_cost::1 telemetry +server/code/app/answers_cache.py::_reuse_from_trunk::1 cache_fallback +server/code/app/answers_cache.py::_reuse_from_trunk::2 write +server/code/app/answers_cache.py::_serve_from_cache::1 cache_fallback +server/code/app/answers_cache.py::_tombstone_entry::1 write +server/code/app/answers_cache.py::_trunk_of::1 cache_fallback +server/code/app/answers_cache.py::reuse_allowed::1 cache_fallback +server/code/app/ask.py::handle_code_ask::2 telemetry +server/code/app/ask.py::handle_code_ask::3 telemetry +server/code/app/bisect.py::_time_window::1 logged_only_nonanswer +server/code/app/common.py::_trace_as_of::1 telemetry +server/code/app/common.py::answer_args::1 telemetry +server/code/app/common.py::as_of_columns::1 telemetry +server/code/app/common.py::bounded_args_json::1 telemetry +server/code/app/common.py::record_code_ask_cache::1 telemetry +server/code/app/common.py::record_code_outcome::1 telemetry +server/code/app/common.py::record_code_shunt::1 telemetry +server/code/app/common.py::schedule_code_trace._write::1 telemetry +server/code/app/common.py::schedule_code_trace_validation_failure::1 telemetry +server/code/app/index_status.py::_commit_missing::1 noted_by_caller # _lag_between notes git_mirror: lag_unknown +server/code/app/index_status.py::_publish_status_snapshot::1 write +server/code/app/index_status.py::_refresh_repo_status::1 logged_only_nonanswer +server/code/app/index_status.py::_table_summary_cached::2 write +server/code/app/index_status.py::published_status_snapshot::1 cache_fallback +server/code/app/ingest.py::_settle_links::1 write +server/code/app/ingest.py::handle_code_refresh._one_pass::1 write +server/code/app/outcome.py::handle_code_outcome::1 write +server/code/app/outcome.py::handle_code_outcome::2 write +server/code/app/prose_candidates.py::discover_candidates::1 logged_only_nonanswer +server/code/app/repo_admin.py::_inherit_tracker_links::1 write +server/code/app/repos.py::_code_repo_rows::1 full_answer_fallback +server/code/app/review_brief.py::_payload_for::1 cache_fallback +server/code/app/risk.py::RiskPrefetch._run::1 full_answer_fallback +server/code/app/risk.py::RiskPrefetch.start::1 full_answer_fallback +server/code/app/search/handler.py::_embedding_model_name::1 full_answer_fallback +server/code/app/search_cursor.py::get_pool::1 cache_fallback +server/code/app/search_cursor.py::get_pool::2 cache_fallback +server/code/app/search_cursor.py::put_pool._bg::1 write +server/code/app/search_memo.py::_ranking_fingerprint::1 settings +server/code/app/search_memo.py::enabled::1 settings +server/code/app/search_memo.py::get::1 cache_fallback +server/code/app/search_memo.py::put._bg::1 write +server/code/app/spans.py::code_span::1 telemetry +server/code/app/spans.py::current_otel_ids::1 telemetry +server/code/app/spans.py::set_code_span_attributes::1 telemetry +server/code/app/spans.py::span_attrs::1 telemetry +server/code/app/unit_risk.py::read_rows::1 cache_fallback +server/code/app/watches.py::notify_once::1 logged_only_nonanswer +server/memory/app/apply.py::_mirror::1 write +server/memory/app/apply.py::apply_one::1 write +server/memory/app/ask/cascade.py::_first_answer::1 full_answer_fallback +server/memory/app/ask/handler.py::_record_contradiction._bg::1 write +server/memory/app/ask/handler.py::_schedule_cited_used._bg::1 write +server/memory/app/ask/handler.py::_schedule_deferred_consistency._bg::1 logged_only_nonanswer +server/memory/app/ask/handler.py::_schedule_deferred_consistency._bg::2 telemetry +server/memory/app/ask/handler.py::_synth_accounting::1 telemetry +server/memory/app/ask/identifiers.py::_chase_identifiers::2 full_answer_fallback +server/memory/app/ask/identifiers.py::_inject_identifier_memories::4 telemetry +server/memory/app/ask/rendering.py::_assemble_prompt::1 telemetry +server/memory/app/ask/source_context.py::cancel_and_drain::1 logged_only_nonanswer +server/memory/app/ask/supersession.py::_with_excerpt::1 full_answer_fallback +server/memory/app/ask/supersession.py::_with_excerpt::2 full_answer_fallback +server/memory/app/assistant_learnings.py::file_assistant_rules::1 write +server/memory/app/auto_resolution.py::follow_beside_response::1 write +server/memory/app/auto_resolution.py::follow_pairs::1 write +server/memory/app/auto_resolution.py::owe_retirements::1 write +server/memory/app/auto_resolution.py::record_refusals::1 write +server/memory/app/auto_resolution.py::refuse_outranked::1 write +server/memory/app/auto_resolution.py::unrecorded::1 write +server/memory/app/blacklist.py::add::1 write +server/memory/app/blacklist_guard.py::_write_hits::1 write +server/memory/app/blacklist_sweep.py::sweep_pattern::2 write +server/memory/app/bulk_rows.py::_bulk_contextualize::1 write +server/memory/app/bulk_rows.py::_with_attribute_tags::1 write +server/memory/app/bulk_rows.py::_with_sensitivity_tag::1 write +server/memory/app/bulk_set.py::_audit_bulk_write::1 write +server/memory/app/bulk_set.py::_batched_peers::1 cache_fallback +server/memory/app/bulk_set.py::_bulk_audit::1 write +server/memory/app/bulk_set.py::_bulk_existing_lookup::1 write +server/memory/app/bulk_set.py::_bulk_follow_row_supersessions::1 write +server/memory/app/bulk_set.py::_bulk_identity_dupes::1 write +server/memory/app/bulk_set.py::_bulk_intra_batch_pairs::1 write +server/memory/app/bulk_set.py::_bulk_mark_same_key::1 write +server/memory/app/bulk_set.py::_bulk_post_insert_links::1 write +server/memory/app/bulk_set.py::_bulk_record_write_metrics::1 telemetry +server/memory/app/bulk_set.py::_bulk_resolve_entities::1 write +server/memory/app/bulk_set.py::_bulk_run_projections._projection._run::1 write +server/memory/app/bulk_set.py::_bulk_settle_verdicts::1 write +server/memory/app/bulk_set.py::_bulk_settle_verdicts::2 write +server/memory/app/bulk_set.py::_close_overtaken_edges::1 write +server/memory/app/bulk_set.py::_namespace_policy::1 cache_fallback +server/memory/app/bulk_set.py::_record_evidence::1 write +server/memory/app/bulk_set.py::_type_floor::1 cache_fallback +server/memory/app/capacity.py::_count::1 telemetry +server/memory/app/capacity.py::_rates::1 telemetry +server/memory/app/capacity.py::observe::1 telemetry +server/memory/app/capacity.py::observe::2 telemetry +server/memory/app/chunk_context.py::contextualize_chunks.one::1 write +server/memory/app/chunk_projection.py::_embed_chunks::1 full_answer_fallback +server/memory/app/chunk_projection.py::_embed_chunks::2 write +server/memory/app/chunk_projection.py::write_memory_chunks::1 write +server/memory/app/code_grounding.py::_authorized_code_target::2 write +server/memory/app/code_link_lag.py::refresh::1 logged_only_nonanswer +server/memory/app/code_link_policy.py::_revise::1 logged_only_nonanswer +server/memory/app/code_link_policy.py::apply_policies::2 logged_only_nonanswer +server/memory/app/code_link_recheck.py::recheck_all::1 logged_only_nonanswer +server/memory/app/code_links.py::_link_org::1 logged_only_nonanswer +server/memory/app/code_links.py::sweep_unlinkable::1 logged_only_nonanswer +server/memory/app/code_renames.py::revise::1 logged_only_nonanswer +server/memory/app/conflict_resolver.py::_act_on_verdicts::2 logged_only_nonanswer +server/memory/app/conflict_resolver.py::_after_retire::1 logged_only_nonanswer +server/memory/app/conflicts.py::_policy_before_gate::1 settings +server/memory/app/conflicts.py::_substitution_verdict::1 settings +server/memory/app/conflicts.py::apply_refines::1 write +server/memory/app/conflicts.py::apply_refines::2 write +server/memory/app/conflicts.py::auto_reinforce_peer::1 write +server/memory/app/conflicts.py::prefetch_write_config::1 cache_fallback +server/memory/app/conflicts.py::same_key_mark::1 write +server/memory/app/consolidate.py::_ask_merge::1 write +server/memory/app/consolidate.py::_ask_merge::2 write +server/memory/app/consolidate.py::_record_consolidation_run::1 write +server/memory/app/consolidate.py::_retire_merged::1 write +server/memory/app/consolidate.py::_write_canonical._lineage::1 write +server/memory/app/context_pack.py::_pack_startup_recall._vtext::1 full_answer_fallback +server/memory/app/coverage_sweep_gate.py::_load::1 settings +server/memory/app/curation.py::quotes_a_redacted_key::1 cache_fallback +server/memory/app/decision.py::_write_decision::1 write +server/memory/app/decision.py::handle_decision_outcome::1 write +server/memory/app/decision.py::handle_decision_record::1 write +server/memory/app/decision_extract.py::_may::1 logged_only_nonanswer +server/memory/app/decision_extract.py::_readable_names::1 logged_only_nonanswer +server/memory/app/decision_extract.py::symbol_definitions::1 logged_only_nonanswer +server/memory/app/digest_chain.py::link_digest::1 write +server/memory/app/drops.py::_count::1 telemetry +server/memory/app/drops.py::_flush_and_rearm::1 telemetry +server/memory/app/drops.py::flush_drops::1 telemetry +server/memory/app/drops.py::record_drop::1 telemetry +server/memory/app/edge_links.py::_drop_links_of::1 write +server/memory/app/edge_links.py::drop_undeclared_edges::1 write +server/memory/app/edge_links.py::drop_undeclared_edges_beside.drop::1 write +server/memory/app/edge_links.py::drop_undeclared_edges_beside::1 write +server/memory/app/edge_links.py::project_revised_edges::1 write +server/memory/app/edge_repair.py::end_overtaken_edges::1 write +server/memory/app/edge_repair.py::end_overtaken_edges::2 write +server/memory/app/edge_repair.py::record_edges_closes::1 write +server/memory/app/embedder_calibration.py::_read_shared::1 logged_only_nonanswer +server/memory/app/embedder_calibration.py::_served_model::1 settings +server/memory/app/embedder_calibration.py::calibrate_embedder::1 logged_only_nonanswer +server/memory/app/embedder_calibration.py::calibrate_embedder::2 logged_only_nonanswer +server/memory/app/embedder_calibration.py::publish_calibration::1 write +server/memory/app/embedder_calibration.py::refresh_shared::1 logged_only_nonanswer +server/memory/app/entity_resolution.py::resolve_entities_for_write::1 write +server/memory/app/entity_resolution.py::resolve_entities_for_write::2 write +server/memory/app/expiry.py::_after_expiry::1 write +server/memory/app/expiry.py::_record_mirror_failures::1 write +server/memory/app/expiry.py::emit_sweep_event::1 telemetry +server/memory/app/exposure_ledger.py::record_exposure._bg::1 telemetry +server/memory/app/extract/client.py::extractor_llm_cache_on::1 settings +server/memory/app/extract/handler.py::_account_build::1 telemetry +server/memory/app/extract/handler.py::_account_build::2 telemetry +server/memory/app/extract/handler.py::_project_extraction._project_chunks::1 write +server/memory/app/extract/handler.py::_project_extraction._project_evidence_links::1 write +server/memory/app/extract/handler.py::_project_extraction._project_session_summary::1 write +server/memory/app/extract/handler.py::_set_record_from_messages::1 write +server/memory/app/extract/handler.py::_set_record_from_messages::2 write +server/memory/app/extract/handler.py::_source_evidence_ids::1 write +server/memory/app/fix_records.py::activity_of::1 write +server/memory/app/graph_write_marks.py::_end::1 write +server/memory/app/graph_write_marks.py::_record_write::1 write +server/memory/app/graph_write_marks.py::flush_now::1 write +server/memory/app/graph_write_marks.py::track._begin::1 write +server/memory/app/handlers.py::_restore_newer_chunks::1 write +server/memory/app/handlers.py::_restore_newer_chunks::2 write +server/memory/app/handlers.py::_restore_newer_chunks::3 write +server/memory/app/handlers.py::_retire_derived::1 write +server/memory/app/handlers.py::_retire_derived::2 write +server/memory/app/handlers.py::_retire_derived::3 write +server/memory/app/handlers.py::_retire_derived::4 write +server/memory/app/handlers.py::finish_delete_check::1 write +server/memory/app/handlers.py::handle_memory_touch::1 write +server/memory/app/high_fence.py::_settled_fence::1 write +server/memory/app/high_fence.py::fence_committed::1 write +server/memory/app/high_fence.py::recheck_live_vectors::1 write +server/memory/app/inline_records.py::_write_inline_record_projection::1 write +server/memory/app/inspect.py::_record_exposure::1 telemetry +server/memory/app/intent_marks.py::flush::1 write +server/memory/app/key_supersession.py::supersede_same_key_rows::1 write +server/memory/app/loom_search/fanout.py::_prepare_knowledge::1 noted_by_caller # _leg_error notes the knowledge leg +server/memory/app/loom_search/fanout.py::search_sections::1 noted_by_caller # _leg_error notes the knowledge leg +server/memory/app/move.py::_redirect_source::1 write +server/memory/app/namespace_retrieval_defaults.py::parse::1 settings +server/memory/app/namespace_retrieval_defaults.py::resolve::1 settings +server/memory/app/namespace_types.py::get_type_config::1 settings +server/memory/app/observe.py::_coerce_str::1 full_answer_fallback +server/memory/app/ops.py::_open_conflict_for_edge::1 write +server/memory/app/ops.py::_open_conflict_for_edge::2 write +server/memory/app/ops.py::handle_memory_link::1 write +server/memory/app/ops.py::handle_memory_outcome::1 write +server/memory/app/ops.py::handle_memory_outcome::2 write +server/memory/app/ops.py::handle_memory_outcome_run::1 write +server/memory/app/path_lessons.py::_confirmed_omissions::1 full_answer_fallback +server/memory/app/pending_evidence.py::rank_pending_turns::1 full_answer_fallback +server/memory/app/period_digest.py::_source_memories::1 logged_only_nonanswer +server/memory/app/period_digest.py::_write_period::1 logged_only_nonanswer +server/memory/app/period_digest.py::_write_period::2 logged_only_nonanswer +server/memory/app/period_digest.py::_write_period::3 logged_only_nonanswer +server/memory/app/period_digest.py::_write_period::4 logged_only_nonanswer +server/memory/app/period_digest.py::_write_period::5 logged_only_nonanswer +server/memory/app/period_digest.py::_write_period::6 logged_only_nonanswer +server/memory/app/period_digest.py::_write_period::7 logged_only_nonanswer +server/memory/app/period_digest.py::run_period_digest::1 logged_only_nonanswer +server/memory/app/pg_delivery.py::_last_attempt::1 write +server/memory/app/pg_delivery.py::_publish_audits::1 write +server/memory/app/pg_delivery.py::_publish_namespace::1 write +server/memory/app/pg_delivery.py::_publish_namespace::2 write +server/memory/app/pg_delivery.py::_retire_old_vectors::1 write +server/memory/app/pg_delivery.py::deliver_namespace::1 write +server/memory/app/pipeline.py::_conflict_policy::1 settings +server/memory/app/pipeline.py::_reinforce_restated::1 write +server/memory/app/pipeline.py::_step_fetch_namespace_categories::1 write +server/memory/app/precedents.py::fast_reuse::1 cache_fallback +server/memory/app/precedents.py::reuse::1 cache_fallback +server/memory/app/precedents.py::schedule_store._bg::1 cache_fallback +server/memory/app/procedure.py::handle_procedure_record_run::1 telemetry +server/memory/app/procedure_evolve.py::_record_evolve_metric::1 telemetry +server/memory/app/profile_search.py::_queue_detached::1 write +server/memory/app/profile_search.py::queue_profile_reembed::1 write +server/memory/app/profile_search.py::reembed_after_write::1 write +server/memory/app/profile_search.py::schedule_reembed_after_write::1 write +server/memory/app/projection_errors.py::record_input_projection_failure::1 write +server/memory/app/projections.py::resolve_projection_entity_map::1 write +server/memory/app/promote.py::handle_memory_promote::1 write +server/memory/app/proposals.py::_surface_conflicts::1 write +server/memory/app/proposals.py::policy_for::1 settings +server/memory/app/query.py::_record_read_exposure::1 telemetry +server/memory/app/recall_credit.py::consumer_closed_loop::1 telemetry +server/memory/app/reextract.py::replay.one::1 logged_only_nonanswer +server/memory/app/rerank.py::_host_of::1 telemetry +server/memory/app/restore.py::_insert_restore::1 write +server/memory/app/restore.py::_mirror_landed::1 write +server/memory/app/restore.py::_restore_landed::1 write +server/memory/app/restore.py::handle_memory_restore::1 write +server/memory/app/retrieval/retry.py::_call_retrying_empty_block::1 full_answer_fallback +server/memory/app/run_retention.py::apply::1 write +server/memory/app/search/anchor_pool.py::_stamp_row_owner::1 full_answer_fallback +server/memory/app/search/assemble.py::_assemble_final_hits::4 full_answer_fallback +server/memory/app/search/assemble.py::_assemble_final_hits::5 telemetry +server/memory/app/search/embed.py::_embed_text_and_window::1 telemetry +server/memory/app/search/evidence.py::_apply_min_similarity_floor::1 full_answer_fallback +server/memory/app/search/key_match.py::_run_key_match_pool._rows_for_ns::1 full_answer_fallback +server/memory/app/search/output.py::_serve_parked_page::1 telemetry +server/memory/app/search/payload.py::_apply_bodies::1 full_answer_fallback +server/memory/app/search/payload.py::_expand_source_bodies::2 full_answer_fallback +server/memory/app/search/payload.py::_expand_unit_bodies::1 full_answer_fallback +server/memory/app/search/payload.py::_expand_unit_bodies::2 full_answer_fallback +server/memory/app/search/payload.py::_expand_unit_bodies::3 full_answer_fallback +server/memory/app/search/payload.py::_fill_hit_tags::2 full_answer_fallback +server/memory/app/search/request.py::apply_explain_default::1 full_answer_fallback +server/memory/app/search/scoring.py::asserted_component::1 full_answer_fallback +server/memory/app/search/telemetry.py::_build_query_node_row::1 write +server/memory/app/search/telemetry.py::_build_trace_row::1 telemetry +server/memory/app/search/telemetry.py::_ledger_run_label::1 telemetry +server/memory/app/search/telemetry.py::_schedule_exposure::1 telemetry +server/memory/app/search/telemetry.py::_schedule_recall_credit._bg_usage::1 telemetry +server/memory/app/search/telemetry.py::_schedule_trace_log._bg::1 telemetry +server/memory/app/search/telemetry.py::_staged::1 telemetry +server/memory/app/search/telemetry.py::_start_actual_work::1 telemetry +server/memory/app/search/telemetry.py::_trace_operation::1 telemetry +server/memory/app/search/telemetry.py::search_shape_sha256::1 telemetry +server/memory/app/search/verdict.py::_flag_below_threshold::1 full_answer_fallback +server/memory/app/search_tag_filter.py::stamp_row_tags::1 full_answer_fallback +server/memory/app/sensitivity_sweep.py::_close_mined_facts::1 logged_only_nonanswer +server/memory/app/sensitivity_sweep.py::_close_owed_now::1 logged_only_nonanswer +server/memory/app/sensitivity_sweep.py::apply::1 logged_only_nonanswer +server/memory/app/served_duplicates.py::_substitute::1 full_answer_fallback +server/memory/app/served_reads.py::records_served.wrap.handle::1 telemetry +server/memory/app/served_reads.py::schedule_served._write::1 telemetry +server/memory/app/session_outcomes.py::distil_contrasts::1 logged_only_nonanswer +server/memory/app/session_outcomes.py::label_sessions::1 logged_only_nonanswer +server/memory/app/set_chunks.py::_embed_chunks::1 full_answer_fallback +server/memory/app/set_chunks.py::_embed_chunks::2 write +server/memory/app/set_chunks.py::tombstone_set_chunks_fail_open::1 write +server/memory/app/set_chunks.py::write_set_chunks_fail_open::1 write +server/memory/app/set_commit.py::_project_set_entities_fail_open::1 write +server/memory/app/set_commit.py::count_attribute_tags::1 telemetry +server/memory/app/set_commit.py::count_write::1 telemetry +server/memory/app/standing.py::as_successor::1 write +server/memory/app/standing.py::behind.one::1 write +server/memory/app/trajectory_notes.py::distill_events::1 logged_only_nonanswer +server/memory/app/trajectory_notes.py::distill_events::2 logged_only_nonanswer +server/memory/app/trajectory_notes.py::distill_notes::1 logged_only_nonanswer +server/memory/app/trajectory_notes.py::distill_notes::2 logged_only_nonanswer +server/memory/app/trajectory_notes.py::distill_notes::3 logged_only_nonanswer +server/memory/app/trajectory_notes.py::supersede_session_procedures::1 logged_only_nonanswer +server/memory/app/trajectory_notes.py::supersede_session_procedures::2 logged_only_nonanswer +server/memory/app/triple_projections.py::_close_planned::1 write +server/memory/app/triple_projections.py::_close_planned::2 write +server/memory/app/triple_projections.py::_write_stated_relations::1 write +server/memory/app/triple_projections.py::_write_stated_relations::2 write +server/memory/app/triple_projections.py::reconcile_row_facts::1 write +server/memory/app/value_updates.py::link_value_updates._one::1 write +server/memory/app/value_updates.py::link_value_updates::1 write +server/memory/app/verify.py::_mirror_verified_to_embeddings::1 write diff --git a/tests/unit/test_code_repos_refresh_cost.py b/tests/unit/test_code_repos_refresh_cost.py index 6e0e623ca64..de749ac2281 100644 --- a/tests/unit/test_code_repos_refresh_cost.py +++ b/tests/unit/test_code_repos_refresh_cost.py @@ -175,3 +175,52 @@ async def _none(org: str, ns: str, **_: Any) -> tuple[int, str]: assert computed["n"] == 1, "index_status reads the 30 s status code.repos already holds" assert out1.ops and out1 is not listing_row and out2 is not out1 assert not listing_row.ops, "the per-call fields were set on a copy, not on the cached row" + + +@pytest.mark.asyncio +async def test_a_commit_judged_without_the_state_read_says_so( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With `commit` set the fresh heads come from the state read; when it fails the + commit is judged against the cached status's heads, and the answer names it.""" + import server.code.app.index.commit_coverage as cc + import server.code.app.index.mirrors as mirrors + from server.code.api.models_status import CodeIndexStatusInput + from server.observability import degradations + from server.settings import settings + + monkeypatch.setattr(settings, "code_intel_enabled", True) + monkeypatch.setattr(settings, "code_org", "acme") + monkeypatch.setattr(settings, "code_namespace", "code-z") + monkeypatch.setattr(settings, "code_repo", "acme/code-z") + monkeypatch.setattr(settings, "code_git_dir", "var/code-z.git") + monkeypatch.setattr(settings, "code_git_branch", "main") + monkeypatch.setattr(settings, "code_path_prefixes", "") + monkeypatch.setattr(settings, "code_github_token", "") + + async def _none(org: str, ns: str, **_: Any) -> tuple[int, str]: + return 0, "" + + async def _dir(cfg: Any, **_: Any) -> tuple[str, str]: + return "var/code-z.git", "" + + async def _coverage(*_: Any, **__: Any) -> dict[str, Any]: + return {"commit": "abc1234"} + + monkeypatch.setattr(index_status, "symbol_stats_summary_cached", _none) + monkeypatch.setattr(index_status, "unit_risk_summary_cached", _none) + monkeypatch.setattr(mirrors, "history_dir", _dir) + monkeypatch.setattr(cc, "commit_coverage", _coverage) + await index_status._repo_status_cached(_cfg("code-z")) # the cached status, read whole + + async def _down(self: Any, org: str, ns: str) -> dict[str, Any]: + raise TimeoutError("state read timed out") + + monkeypatch.setattr(_FakeRepo, "all_state", _down) + degradations.begin() + out = await index_status.handle_code_index_status( + CodeIndexStatusInput(org="acme", namespace="code-z", commit="abc1234") + ) + assert out.commit_coverage is not None and out.commit_coverage.commit == "abc1234" + # (the fake repository leaves the cached status its own notes too) + assert "code_index: state_unread (TimeoutError)" in degradations.current() diff --git a/tests/unit/test_degraded_unnoted.py b/tests/unit/test_degraded_unnoted.py new file mode 100644 index 00000000000..1f59ed5bf7f --- /dev/null +++ b/tests/unit/test_degraded_unnoted.py @@ -0,0 +1,172 @@ +"""Every broad `except` in the code and memory apps either names its fallback in +`degraded` or is listed, with why it need not, in `degraded_unnoted.txt`; and every +fallback that feeds provider health names a provider whose success clears it.""" + +from __future__ import annotations + +import ast +from pathlib import Path + +from server.core.paths import REPO_ROOT + +_DIRS = ("server/code/app", "server/memory/app") +# The index plane's own passes, like the workers and stores outside these dirs. +_EXCLUDED = ("server/code/app/index/",) +_ALLOWLIST = Path(__file__).with_name("degraded_unnoted.txt") +_CATEGORIES = { + # a cache, memo or precomputed read that falls back to the live read + "cache_fallback", + # another source or path answers in full + "full_answer_fallback", + # a write or a side effect; the answer read is whole + "write", + # spans, metrics, logs, ledgers + "telemetry", + # a settings lookup that falls back to its default + "settings", + # a cut by a budget the caller or the op sets + "budget", + # a cut by the call's own deadline + "own_deadline", + # no response path: a background pass, startup or cleanup in an app module + "logged_only_nonanswer", + # the caller names the fallback from what the handler returns (the line says where) + "noted_by_caller", +} +_NOTES = {"partial", "note", "restore"} + + +def _broad(h: ast.ExceptHandler) -> bool: + if h.type is None: + return True + names = h.type.elts if isinstance(h.type, ast.Tuple) else [h.type] + return any(isinstance(n, ast.Name) and n.id in {"Exception", "BaseException"} for n in names) + + +def _is_degradations(node: ast.expr) -> bool: + return isinstance(node, ast.Name) and node.id.lstrip("_") == "degradations" + + +def _notes(h: ast.ExceptHandler) -> bool: + """The handler always raises (a `raise` among its own statements, not under an `if`), + names its fallback (`degradations.partial` / `note` / `restore`), or keeps the failure's + text for the answer (`caller_text(e)`: a kept failure noted on each answer served from + it, or a failure field of the response).""" + if any(isinstance(s, ast.Raise) for s in h.body): + return True + for n in ast.walk(ast.Module(body=h.body, type_ignores=[])): + if not isinstance(n, ast.Call): + continue + if isinstance(n.func, ast.Attribute): + if n.func.attr in _NOTES and _is_degradations(n.func.value): + return True + if isinstance(n.func, ast.Name) and n.func.id == "caller_text" and h.name: + if any(isinstance(a, ast.Name) and a.id == h.name for a in n.args): + return True + return False + + +def _unnoted() -> list[str]: + """`path::enclosing.qualname::ordinal` of each broad handler that notes nothing; the + ordinal counts the broad handlers of that function in source order.""" + out: list[str] = [] + for d in _DIRS: + for path in sorted((REPO_ROOT / d).rglob("*.py")): + rel = str(path.relative_to(REPO_ROOT)) + if rel.startswith(_EXCLUDED): + continue + counts: dict[str, int] = {} + + def visit(node: ast.AST, qual: str, rel: str = rel, counts: dict = counts) -> None: + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + visit(child, f"{qual}.{child.name}" if qual else child.name) + continue + if isinstance(child, ast.ExceptHandler) and _broad(child): + q = qual or "" + counts[q] = counts.get(q, 0) + 1 + if not _notes(child): + out.append(f"{rel}::{q}::{counts[q]}") + visit(child, qual) + + visit(ast.parse(path.read_text()), "") + return out + + +def _allowlist() -> dict[str, str]: + entries: dict[str, str] = {} + for raw in _ALLOWLIST.read_text().splitlines(): + line = raw.split("#", 1)[0].strip() + if not line: + continue + key, category = line.split() + assert key not in entries, f"listed twice: {key}" + assert category in _CATEGORIES, f"{key}: unknown category {category!r}" + entries[key] = category + return entries + + +def test_every_broad_handler_notes_its_fallback_or_says_why_it_need_not() -> None: + """A handler that serves a smaller answer calls `degradations.partial`; the rest are + listed by category. The list only shrinks: an entry whose handler now notes, moved or + is gone fails until it is removed.""" + found, listed = _unnoted(), _allowlist() + missing = [k for k in found if k not in listed] + stale = [k for k in listed if k not in set(found)] + assert not missing, ( + "broad handlers that note nothing and are not in degraded_unnoted.txt: note the " + "fallback with degradations.partial, or list it with its category:\n" + "\n".join(missing) + ) + assert not stale, "degraded_unnoted.txt lists handlers that note or are gone:\n" + "\n".join( + stale + ) + + +def _health_notes(tree: ast.AST) -> list[tuple[int, str | None]]: + """(line, provider literal or None) of each `degradations.note` that feeds provider + health (no `health=False`).""" + out: list[tuple[int, str | None]] = [] + for n in ast.walk(tree): + if not (isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute)): + continue + if n.func.attr != "note" or not _is_degradations(n.func.value): + continue + health = next((k.value for k in n.keywords if k.arg == "health"), None) + if isinstance(health, ast.Constant) and health.value is False: + continue + first = n.args[0] if n.args else None + literal = first.value if isinstance(first, ast.Constant) else None + out.append((n.lineno, literal if isinstance(literal, str) else None)) + return out + + +def _cleared_by_success(trees: dict[str, ast.AST]) -> set[str]: + """The provider names a `record_success("")` call clears.""" + names: set[str] = set() + for tree in trees.values(): + for n in ast.walk(tree): + if isinstance(n, ast.Call) and getattr(n.func, "attr", None) == "record_success": + if n.args and isinstance(n.args[0], ast.Constant): + names.add(str(n.args[0].value)) + return names + + +def test_a_fallback_counted_in_provider_health_names_a_provider_a_success_clears() -> None: + """`ops.incidents` and `/v1/health` list a provider whose last call failed until a + later success clears it. A note that feeds that state names a provider that also + records its successes; a store read or a handler's step uses `partial`, or it would + read failing for the whole window after one fallback.""" + trees = { + str(p.relative_to(REPO_ROOT)): ast.parse(p.read_text()) + for p in (REPO_ROOT / "server").rglob("*.py") + } + cleared = _cleared_by_success(trees) + bad = [ + f"{rel}:{line} {provider!r}" + for rel, tree in trees.items() + for line, provider in _health_notes(tree) + if provider not in cleared + ] + assert not bad, "health-counted notes no success clears (use degradations.partial):\n" + ( + "\n".join(bad) + ) diff --git a/tests/unit/test_memory_search_computed_notes.py b/tests/unit/test_memory_search_computed_notes.py new file mode 100644 index 00000000000..465b841cc08 --- /dev/null +++ b/tests/unit/test_memory_search_computed_notes.py @@ -0,0 +1,59 @@ +"""The computed-answer legs of memory.search name a failed read in `degraded`: the hits +answer without the date difference, and calibration without the support count.""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.memory.app.search import computed +from server.observability import degradations + + +class _Embedder: + model_name = "fake" + + async def embed(self, text: str) -> list[float]: + raise RuntimeError("embedder down") + + +@pytest.mark.asyncio +async def test_a_date_difference_whose_operands_did_not_embed_is_named() -> None: + ctx: Any = SimpleNamespace( + temporal_diff_cache={}, + temporal_diff_spec={"operands": ["the move", "the wedding"], "to_observation": False}, + input=SimpleNamespace(org="o", namespace="n", agent="a", user_id="-", run_id=""), + embedder=_Embedder(), + actual_work={"embedding_calls": 0}, + obs_date=None, + ) + degradations.begin() + assert await computed._maybe_temporal_diff(ctx) is None + assert degradations.current() == ["memory.search: temporal_diff_dropped (RuntimeError)"] + + +@pytest.mark.asyncio +async def test_a_support_count_that_failed_is_named(monkeypatch: pytest.MonkeyPatch) -> None: + async def _none(ctx: Any) -> None: + return None + + async def _down(input: Any, hits: Any) -> int: + raise TimeoutError("support read timed out") + + monkeypatch.setattr(computed, "_apply_min_similarity_floor", lambda hits, *a, **k: hits) + monkeypatch.setattr(computed, "_noise_floor", lambda *a: 0.0) + monkeypatch.setattr(computed, "_floor_mode", lambda *a: "") + monkeypatch.setattr(computed, "_maybe_temporal_diff", _none) + monkeypatch.setattr(computed, "_maybe_derived_aggregate", _none) + monkeypatch.setattr(computed, "_evidence_support_count", _down) + ctx: Any = SimpleNamespace( + input=SimpleNamespace(top_k=5, namespace="n"), clock=SimpleNamespace(mark=lambda *_: None) + ) + degradations.begin() + hits, aggregate, support = await computed._floor_and_computed_evidence( + ctx, SimpleNamespace(ns_calibration={}), [] + ) + assert (hits, aggregate, support) == ([], None, 0) + assert degradations.current() == ["memory.search: evidence_support_unread (TimeoutError)"] diff --git a/tests/unit/test_memory_webhooks.py b/tests/unit/test_memory_webhooks.py index 8310b6ba836..0ae6fecd156 100644 --- a/tests/unit/test_memory_webhooks.py +++ b/tests/unit/test_memory_webhooks.py @@ -259,7 +259,7 @@ async def slow_live() -> list[dict[str, Any]]: monkeypatch.setattr(store, "live_webhooks", slow_live) monkeypatch.setattr(settings, "memory_webhook_refresh_seconds", 30.0) - monkeypatch.setattr(app.degradations, "note", lambda p, e, r="": notes.append((p, e))) + monkeypatch.setattr(app.degradations, "partial", lambda p, e, r="": notes.append((p, e))) _unread_registry() ch = RecordingCH().install(monkeypatch) # Two writes at once: the second takes the first's failed read, not a second one. diff --git a/tests/unit/test_search_read_your_writes.py b/tests/unit/test_search_read_your_writes.py index c5236a4d077..6d838421670 100644 --- a/tests/unit/test_search_read_your_writes.py +++ b/tests/unit/test_search_read_your_writes.py @@ -215,7 +215,7 @@ async def search(inp: object) -> object: @pytest.mark.parametrize("served", [True, False]) def test_a_pass_names_the_notes_of_the_pass_it_serves(monkeypatch, served: bool) -> None: """An adopted retry's answer is served: its notes replace the first pass's. A retry that - fails is thrown away with its notes, and the first pass's stand.""" + fails is thrown away with its notes; the first pass's stand, and the failure is named.""" from types import SimpleNamespace import server.memory.app.search as pkg @@ -243,4 +243,6 @@ async def one_pass() -> tuple[object, list[str]]: monkeypatch.setattr("server.memory.store.read_your_writes_enabled", lambda: True) out, notes = asyncio.run(one_pass()) assert (out is not None) is served - assert notes == ["identity: repo_gate_unverified", retried if served else first] + unchecked = "memory.search: read_your_writes_unchecked (RuntimeError)" + expected = [retried] if served else [first, unchecked] + assert notes == ["identity: repo_gate_unverified", *expected] From 247195117907d01b095c7a8af14da4974ed36b86 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 14:40:21 +0530 Subject: [PATCH 18/47] A cached as-of names its failed lag read; a refusal lists without a note index_as_of serves its block from a 30 s cache. A block built while the clone's lag read failed (lag_commits -1) is kept with the failure's text and names git_mirror: lag_unknown on each answer served from it, not only on the first. code.repos' listing gate noted identity: listing_gate_unchecked for every exception, including the PermissionError and IdentityIncompleteError that list a repository request-only to a member who cannot read it. It now notes only a check that could not run, such as a failed SCIM read. code.coverage keeps a failed gap read for the counts' max age again, rather than retrying it on every call, and names it on each page served from it. The sender census's reviewed digest of sdk/python/loom/memory.py is renewed for the docstring change to `degraded`; no sender changed. The code.search pick tests stub the coverage note their fake repository cannot read. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/http-api.md | 6 ++-- server/code/app/common.py | 29 ++++++++------- server/code/app/index_status.py | 12 +++++-- server/code/app/repos.py | 6 +++- tests/unit/session_content_senders.json | 2 +- tests/unit/test_code_ingest_fair_fetch.py | 43 +++++++++++++++++++++-- tests/unit/test_code_page_shapes.py | 13 +++++-- tests/unit/test_code_repos_reads_once.py | 43 +++++++++++++++++++++++ tests/unit/test_code_search_pick.py | 4 +++ 9 files changed, 133 insertions(+), 25 deletions(-) diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 95331cb882d..3e93d044bfa 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -326,9 +326,9 @@ error's kind only; the full text is in the server log. judges the entries its own reads recorded, so one the request recorded before it does not stop the cache. Some caches keep a fallback with its entries and name them on each answer served from it: `code.index_status` and `code.repos` keep such a status for - `LOOM_CODE_STATUS_TTL_S`, the constructor-coverage and `overrides` probes, and - `code.index_status`' symbol-stats and unit-risk counts, keep a failed read for 30 - seconds, the pending-extraction count for + `LOOM_CODE_STATUS_TTL_S`, the constructor-coverage and `overrides` probes, + `code.index_status`' symbol-stats and unit-risk counts, and the `as_of` block's lag + read keep a failed read for 30 seconds, the pending-extraction count for `LOOM_MEMORY_PENDING_DISCLOSURE_TTL_S`, namespace health for `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`, and each of `ops.incidents`' ClickHouse sources for 5 seconds. diff --git a/server/code/app/common.py b/server/code/app/common.py index 1b6f3de437a..857732e815a 100644 --- a/server/code/app/common.py +++ b/server/code/app/common.py @@ -183,11 +183,11 @@ def freshness_status(lag: int, stale: bool) -> str: return "fresh" if lag == 0 else "behind" -# (org, ns) -> as_of block. The block is one point read of code_index_state plus a -# cached rev-list, and a code.search fan-out asks for it once per namespace per call. -# 30 s per namespace per worker; code.refresh and the ingest pass invalidate it when -# git_head moves. -_AS_OF_CACHE: TtlCache[tuple[str, str], dict[str, Any]] = TtlCache(30.0, maxsize=2000) +# (org, ns) -> (as_of block, the failed lag read's text or ""). The block is one point +# read of code_index_state plus a cached rev-list, and a code.search fan-out asks for it +# once per namespace per call. 30 s per namespace per worker; code.refresh and the +# ingest pass invalidate it when git_head moves. +_AS_OF_CACHE: TtlCache[tuple[str, str], tuple[dict[str, Any], str]] = TtlCache(30.0, maxsize=2000) def invalidate_index_as_of(org: str, ns: str) -> None: @@ -256,7 +256,9 @@ async def index_as_of(repo: CodeRepo, org: str, ns: str) -> dict[str, Any]: answer.""" hit = _AS_OF_CACHE.get((org, ns)) if hit is not None: - block = dict(hit) + block = dict(hit[0]) + if hit[1]: # each answer served from a failed lag read names it + degradations.partial("git_mirror", "lag_unknown", hit[1]) if block: set_code_span_attributes(lag_commits=block["lag_commits"], stale=block["stale"]) return block @@ -271,10 +273,13 @@ async def index_as_of(repo: CodeRepo, org: str, ns: str) -> dict[str, Any]: cfg = repo_for_namespace(org, ns) updated = head.get("updated_at") + lag_failure = "" if cfg is None: lag = -1 elif await present_dir(cfg): - lag = await _lag_commits_cached(cfg, commit) + lag, lag_failure = await _lag_commits_cached(cfg, commit) + if lag_failure: + degradations.partial("git_mirror", "lag_unknown", lag_failure) else: lag = _published_lag(state, cfg, commit) fetched = (state.get("clone_head") or {}).get("updated_at") @@ -297,7 +302,7 @@ async def index_as_of(repo: CodeRepo, org: str, ns: str) -> dict[str, Any]: if failing := failing_tiers(state, cfg, ingest_lag=lag): # A failing tier stops moving: what it answers may trail the head, and why. block["failing_tiers"] = failing - _AS_OF_CACHE.put((org, ns), block) + _AS_OF_CACHE.put((org, ns), (block, lag_failure)) return dict(block) except Exception as err: # noqa: BLE001 — unknown freshness, not an error degradations.partial("code_index", "as_of_unread", err) @@ -380,7 +385,9 @@ def _published_lag(state: Any, cfg: Any, git_head: str) -> int: return published_lags(state, {"git_head": git_head}, tip)["git_head"] -async def _lag_commits_cached(cfg: Any, git_head: str) -> int: +async def _lag_commits_cached(cfg: Any, git_head: str) -> tuple[int, str]: + """(lag, the failed read's text or ""); `index_as_of` names a failure on each + answer it serves from one.""" from server.code.app.index import gitrepo key = (cfg.git_dir, cfg.git_branch, git_head) @@ -396,9 +403,7 @@ async def _lag_commits_cached(cfg: Any, git_head: str) -> int: missing = await _commit_missing(gitrepo, cfg.git_dir, (git_head,)) hit = (-1, "" if missing else caller_text(e)) _LAG_CACHE.put(key, hit) - if hit[1]: - degradations.partial("git_mirror", "lag_unknown", hit[1]) - return hit[0] + return hit def path_coverage(cfg: RepoConfig | None, path_prefix: str) -> tuple[bool, tuple[str, ...]]: diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index 98af73b6ff2..93cb902c6c4 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -970,7 +970,8 @@ def share(num: int, den: int) -> float: ) -_CoverageEntry = tuple[str, float, dict[str, Any], dict[str, int] | None] +# (fingerprint, read_at, coverage, gap counts or None, the failed gap read's text or "") +_CoverageEntry = tuple[str, float, dict[str, Any], dict[str, int] | None, str] _coverage_cache: dict[tuple[str, str], _CoverageEntry] = {} @@ -988,6 +989,8 @@ async def _coverage_cached( hit = _coverage_cache.get(key) now = time.monotonic() if hit is not None and hit[0] == fp and now - hit[1] < _counts_max_age_s(state): + if hit[4]: # each page served from a failed gap read names it + degradations.partial("code_index", "coverage_gaps_unread", hit[4]) return hit[2], hit[3] # The pass that moved the rows published their # coverage beside its counts; a row whose fingerprint is ours is the @@ -997,6 +1000,7 @@ async def _coverage_cached( published = parse_shared_coverage(state.get("coverage"), fp) refresh = getattr(repo, "refresh_coverage", None) + failure = "" if published is not None: cov, gap_counts = published elif refresh is not None: @@ -1006,12 +1010,14 @@ async def _coverage_cached( try: gap_counts = await repo.coverage_gaps(org, ns) except Exception as e: # noqa: BLE001 — coverage must not fail on the gap queries + from server.core.errors import caller_text + degradations.partial("code_index", "coverage_gaps_unread", e) logger.warning("code.coverage: gap queries failed for %s/%s: %s", org, ns, e) - return cov, None # served, not kept + gap_counts, failure = None, caller_text(e) if len(_coverage_cache) > 256: _coverage_cache.clear() - _coverage_cache[key] = (fp, now, cov, gap_counts) + _coverage_cache[key] = (fp, now, cov, gap_counts, failure) return cov, gap_counts diff --git a/server/code/app/repos.py b/server/code/app/repos.py index 2880b3733fe..7ba58d0810a 100644 --- a/server/code/app/repos.py +++ b/server/code/app/repos.py @@ -16,6 +16,7 @@ from server.code.domain.index.remote import PUBLIC_HOST, repo_key, stated_repo_key from server.code.domain.index.state import STAGE_KEY, shown_detail from server.code.store.index import CodeRepo +from server.core.errors import IdentityIncompleteError from server.core.grant_sql import LIVE_GRANT from server.observability import degradations from server.operations.read_projection import project_rows @@ -308,7 +309,10 @@ async def _listing_gate( ) return True except Exception as exc: # noqa: BLE001 — PermissionError / IdentityIncomplete - degradations.partial("identity", "listing_gate_unchecked", exc) + if not isinstance(exc, (PermissionError, IdentityIncompleteError)): + # a refusal is the answer; a check that could not run (a failed grant or + # SCIM read) lists the entry request-only without knowing + degradations.partial("identity", "listing_gate_unchecked", exc) # A principal of the same org sees every # repository it may ask to join — open (one click) or # approval (a maintainer decides) — as a request-only entry: diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index e40123b41f3..181d7097bd8 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -422,7 +422,7 @@ "sdk/python/loom/integrations/langgraph.py": "5d68e6ab1645d868477a13b14aa6d734c72f72057464cac9a21aa707add17e7b", "sdk/python/loom/integrations/llamaindex.py": "06eaa071115cad752d27bdc9bf7c4d5b6f5d7d39d9896267fcd459a4e06bf661", "sdk/python/loom/integrations/openai_agents.py": "143fe1df060b96550a33f77fa44416e291c2154552e433f8309275f61c8fca2a", - "sdk/python/loom/memory.py": "0cf1ee9e997a2368f6f2ecbdab50116b6ce0c3469ee875f20fd8b6c295931b82", + "sdk/python/loom/memory.py": "e6e66b95c36a1189c307a8065904cb529fdf25096ac66adb2646c1f2fd145557", "sdk/python/loom/run.py": "1d47d5f4d197f78de347d2cf66b9f59f4292846d214f7116c444035971c6ab42", "sdk/python/loom/session.py": "5f0fd61fcfdbf9d60888b111887fca8f32e24eb51ca9ff04a256901657c3202b", "sdk/typescript/src/integrations/claude-memory.ts": "c846f0011d7cf1ba4b30e99fbfd8adb6b29abff56856d0dbe14fba620007f6bc", diff --git a/tests/unit/test_code_ingest_fair_fetch.py b/tests/unit/test_code_ingest_fair_fetch.py index 79b71fc1635..78aa4798e3a 100644 --- a/tests/unit/test_code_ingest_fair_fetch.py +++ b/tests/unit/test_code_ingest_fair_fetch.py @@ -321,8 +321,8 @@ def _as_of( cfg = SimpleNamespace(git_dir="loom.git", git_branch="main") monkeypatch.setattr("server.code.domain.index.repos.repo_for_namespace", lambda org, ns: cfg) - async def lag(cfg: Any, head: str) -> int: - return 0 # the mirror's own tip: "0 behind" + async def lag(cfg: Any, head: str) -> tuple[int, str]: + return 0, "" # the mirror's own tip: "0 behind" monkeypatch.setattr(cc, "_lag_commits_cached", lag) cc.invalidate_index_as_of("o", "code-loom") @@ -370,6 +370,45 @@ def test_an_index_no_pass_ever_fetched_for_reads_stale_once_its_head_is_old( assert block["stale_reason"] == "mirror_not_fetched" and block["fetched_at"] == "" +def test_a_failed_lag_read_is_named_on_each_answer_the_as_of_cache_serves( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The block keeps lag -1 for 30 s; every answer served from it names the failed + read, not only the one that made it.""" + from server.observability import degradations + + cfg = SimpleNamespace(git_dir="loom.git", git_branch="main") + monkeypatch.setattr("server.code.domain.index.repos.repo_for_namespace", lambda org, ns: cfg) + reads: list[str] = [] + + async def present(cfg: Any) -> bool: + return True + + async def lag(cfg: Any, head: str) -> tuple[int, str]: + reads.append(head) + return -1, "GitError" + + monkeypatch.setattr("server.code.app.index.mirrors.present_dir", present) + monkeypatch.setattr(cc, "_lag_commits_cached", lag) + repo = _AsOfRepo(_ago(minutes=5), _ago(minutes=5)) + + async def twice() -> list[tuple[int, list[str]]]: + served = [] + for _ in range(2): + degradations.begin() + block = await cc.index_as_of(repo, "o", "code-loom") # type: ignore[arg-type] + served.append((block["lag_commits"], degradations.current())) + return served + + cc.invalidate_index_as_of("o", "code-loom") + try: + served = asyncio.run(twice()) + finally: + cc.invalidate_index_as_of("o", "code-loom") + assert len(reads) == 1 # the second answer is the cached block + assert served == [(-1, ["git_mirror: lag_unknown (GitError)"])] * 2 + + def test_mirror_fetch_overdue_reads_naive_clickhouse_utc() -> None: now = datetime(2026, 9, 24, 16, 45, tzinfo=UTC) assert cc.mirror_fetch_overdue(datetime(2026, 9, 24, 13, 17), now) is True diff --git a/tests/unit/test_code_page_shapes.py b/tests/unit/test_code_page_shapes.py index d0416ed0a2f..1944ddd3e5f 100644 --- a/tests/unit/test_code_page_shapes.py +++ b/tests/unit/test_code_page_shapes.py @@ -142,9 +142,16 @@ async def _boom(self: Any, org: str, ns: str) -> dict[str, int]: _FakeRepo.calls["gaps"] += 1 raise RuntimeError("no gap tables") + from server.observability import degradations + monkeypatch.setattr(_FakeRepo, "coverage_gaps", _boom) inp = CodeCoverageInput(org="acme", namespace="code-z") - out1 = await index_status.handle_code_coverage(inp) - out2 = await index_status.handle_code_coverage(inp) - assert out1.gaps is None and out2.gaps is None + outs, noted = [], [] + for _ in range(2): + degradations.begin() + outs.append(await index_status.handle_code_coverage(inp)) + noted.append(degradations.current()) + assert outs[0].gaps is None and outs[1].gaps is None assert _FakeRepo.calls["gaps"] == 1 and _FakeRepo.calls["coverage"] == 1 + # the kept failure is named on each page served from it, not only the first + assert noted == [["code_index: coverage_gaps_unread (RuntimeError)"]] * 2 diff --git a/tests/unit/test_code_repos_reads_once.py b/tests/unit/test_code_repos_reads_once.py index c6340d43fed..15453a61674 100644 --- a/tests/unit/test_code_repos_reads_once.py +++ b/tests/unit/test_code_repos_reads_once.py @@ -17,6 +17,7 @@ from server.auth import authz from server.code.app import index_status, repos +from server.core.errors import BackendUnavailableError, IdentityIncompleteError from server.operations.base import Role @@ -126,3 +127,45 @@ def test_the_listing_hands_the_gate_its_grant() -> None: gate = src[src.index("async def _listing_gate(") :] gate = gate[: gate.index("\ndef ", 1)] assert "**_known_grant_kw(roles, key, grants_read=grants_read)" in gate + + +@pytest.mark.parametrize( + ("refusal", "noted"), + [ + (PermissionError("no access"), False), + (IdentityIncompleteError("scoped token needs org and namespace"), False), + (BackendUnavailableError("cannot read whether SCIM deactivated the subject"), True), + ], +) +def test_the_listing_gate_names_a_check_it_could_not_run_not_a_refusal( + monkeypatch: pytest.MonkeyPatch, refusal: Exception, noted: bool +) -> None: + """A refusal lists the entry request-only and is the answer; a check that could not + run lists it the same way without knowing, and says so.""" + from types import SimpleNamespace + + from server.identity.app import namespace_classification + from server.observability import degradations + + async def check(*a: Any, **k: Any) -> None: + raise refusal + + monkeypatch.setattr(authz, "check_authorized", check) + monkeypatch.setattr(namespace_classification, "is_restricted_cached", lambda o, n: False) + caller = SimpleNamespace(org="o", has_role=lambda role: False) + + async def gate() -> tuple[bool | None, list[str]]: + degradations.begin() + listed = await repos._listing_gate( + caller, + SimpleNamespace(org="o", namespace="n"), + policies={("o", "n"): "approval"}, + roles={}, + grants_read=True, + ) + return listed, degradations.current() + + listed, notes = asyncio.run(gate()) + assert listed is False # request-only either way + unread = "BACKEND_UNAVAILABLE: cannot read whether SCIM deactivated the subject" + assert notes == ([f"identity: listing_gate_unchecked ({unread})"] if noted else []) diff --git a/tests/unit/test_code_search_pick.py b/tests/unit/test_code_search_pick.py index 13a2a4c1101..f8b3377dd62 100644 --- a/tests/unit/test_code_search_pick.py +++ b/tests/unit/test_code_search_pick.py @@ -379,12 +379,16 @@ async def thresholds(org: str, ns: str) -> tuple[float, float, float]: async def cap(org: str, ns: str, **k: Any) -> bool: return over_cap + async def no_coverage_note(repo: Any, org: str, ns: str) -> str: + return "" # `_Repo` has no counts read, whose failure would keep the answer from the memo + monkeypatch.setattr("server.observability.budget.namespace_over_cap", cap) monkeypatch.setattr(memo, "enabled", lambda _input: True) monkeypatch.setattr(memo, "get", no_hit) monkeypatch.setattr(memo, "put", lambda *a, **k: puts.append(a)) monkeypatch.setattr(handler, "CodeRepo", lambda: _Repo()) monkeypatch.setattr(handler, "index_as_of", as_of) + monkeypatch.setattr(handler, "embedding_coverage_note", no_coverage_note) monkeypatch.setattr(handler, "resolve_code_thresholds", thresholds) monkeypatch.setattr(embedding, "get_embedder", lambda: _Embedder()) monkeypatch.setattr( From ede53df3e25b3ee9576aa2c01e572ab45cc5fc6e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 14:50:44 +0530 Subject: [PATCH 19/47] A failed gap read is named whichever path served the coverage The publisher keeps a failed gap read as gaps: null in the shared coverage row, and code.coverage served it, from the row or from the process memo, with no note; only a repository without the publisher noted. A page whose gap counts are None now names code_index: coverage_gaps_unread on every path, with the failure's kind when this process saw it. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/index_status.py | 10 ++++++--- tests/unit/test_coverage_published.py | 31 +++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index 93cb902c6c4..f49a2668a66 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -970,7 +970,8 @@ def share(num: int, den: int) -> float: ) -# (fingerprint, read_at, coverage, gap counts or None, the failed gap read's text or "") +# (fingerprint, read_at, coverage, gap counts or None when their read failed, that +# failure's text when this process saw it or "") _CoverageEntry = tuple[str, float, dict[str, Any], dict[str, int] | None, str] _coverage_cache: dict[tuple[str, str], _CoverageEntry] = {} @@ -989,7 +990,7 @@ async def _coverage_cached( hit = _coverage_cache.get(key) now = time.monotonic() if hit is not None and hit[0] == fp and now - hit[1] < _counts_max_age_s(state): - if hit[4]: # each page served from a failed gap read names it + if hit[3] is None: # each page served from a failed gap read names it degradations.partial("code_index", "coverage_gaps_unread", hit[4]) return hit[2], hit[3] # The pass that moved the rows published their @@ -1012,9 +1013,12 @@ async def _coverage_cached( except Exception as e: # noqa: BLE001 — coverage must not fail on the gap queries from server.core.errors import caller_text - degradations.partial("code_index", "coverage_gaps_unread", e) logger.warning("code.coverage: gap queries failed for %s/%s: %s", org, ns, e) gap_counts, failure = None, caller_text(e) + if gap_counts is None: + # The gap queries failed, here or where the shared row was computed (which + # keeps no kind): the page renders without its gaps row. + degradations.partial("code_index", "coverage_gaps_unread", failure) if len(_coverage_cache) > 256: _coverage_cache.clear() _coverage_cache[key] = (fp, now, cov, gap_counts, failure) diff --git a/tests/unit/test_coverage_published.py b/tests/unit/test_coverage_published.py index 09c1aa728d4..b6c3d8955e1 100644 --- a/tests/unit/test_coverage_published.py +++ b/tests/unit/test_coverage_published.py @@ -128,6 +128,37 @@ def test_parse_shared_coverage_tolerates_garbage() -> None: assert cov == _COV and gaps is None +@pytest.mark.asyncio +async def test_a_failed_gap_read_is_named_on_every_page_whichever_path_served_it() -> None: + """The publisher keeps a failed gap read as `gaps: null` beside the coverage. A page + computed here, one read from the shared row and one from the process memo each + render without the gaps row, and each names it.""" + from server.observability import degradations + + class _NoGaps(_Repo): + async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: + raise TimeoutError + + repo = _NoGaps() + state = _state(("h1", "s1", "p1")) + noted = [] + for _ in range(2): # computed and published, then from the memo + degradations.begin() + _, gaps = await index_status._coverage_cached(repo, "o", "n", state) + assert gaps is None + noted.append(degradations.current()) + ((_, value, detail),) = repo.published + assert json.loads(value)["gaps"] is None + index_status.reset_repo_status_cache() + degradations.begin() # another process: the shared row answers + _, gaps = await index_status._coverage_cached( + repo, "o", "n", dict(state, coverage={"value": value, "detail": detail}) + ) + assert gaps is None and repo.computed == 1 + noted.append(degradations.current()) + assert noted == [["code_index: coverage_gaps_unread"]] * 3 + + @pytest.mark.asyncio async def test_recent_commits_are_remembered_for_a_minute(monkeypatch: pytest.MonkeyPatch) -> None: calls = 0 From 761340c5354f93e71e2bea90a56aa3eb690e7f5c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 16:22:33 +0530 Subject: [PATCH 20/47] A gathered read that failed is noted, and a bulk write without its live rows refuses The scan now covers the exception branches over an asyncio.gather(..., return_exceptions=True) result, and review_brief_build.py. The branches it found note: code.setting_facts' reads, where a failed declaration answers unknown rather than not_a_setting; code.blame_range's enclosing function, review comments and merge ledger; code.symbol_history's issue facts and tracker side, which now answers tracker_unavailable; memory.for_file's other namespaces; loom_search's tracker namespaces; the bisect fusion windows and linked trackers; and each review brief section and read, with a failed index head, so such a brief is not stored. memory.bulk_set and memory.append_batch refuse with a retryable BACKEND_UNAVAILABLE when the batched live-row read fails, and write nothing: the batch used to be written as if no key existed, overwriting read-only keys and unpinning pinned ones. The unknown write outcome goes with it. A failed gap read is no longer published as the shared coverage row, so every process computes the gaps again; this process keeps the failure 30 s. A malformed pending batch is noted. The http-api.md cache list names every cache that keeps a fallback, and the as_of figure is about 90 s. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- deploy/hyperdx_dashboards.md | 27 ++- docs/reference/http-api.md | 26 ++- docs/reference/operations/code.md | 2 +- server/code/api/models_conventions.py | 3 +- server/code/app/bisect_fusion.py | 4 +- server/code/app/bisect_scan.py | 1 + server/code/app/blame.py | 10 +- server/code/app/common.py | 7 +- server/code/app/index/review_brief_build.py | 18 +- server/code/app/index_status.py | 15 +- server/code/app/settings.py | 42 +++-- server/code/app/symbol_history.py | 21 ++- server/code/domain/index/setting_facts.py | 8 +- server/code/store/index/status.py | 24 +-- server/memory/app/bulk_rows.py | 21 +-- server/memory/app/bulk_set.py | 87 +++++----- server/memory/app/for_file.py | 1 + server/memory/app/loom_search/fanout.py | 8 +- server/memory/app/loom_search/tracker_leg.py | 10 +- server/memory/app/pending_evidence.py | 5 +- server/memory/app/set_commit.py | 2 - server/observability/metrics.py | 2 +- tests/unit/degraded_unnoted.txt | 7 +- tests/unit/test_bulk_conflict_verdicts.py | 4 +- tests/unit/test_bulk_identity_dedup.py | 22 ++- tests/unit/test_bulk_rows_carry_labels.py | 2 +- tests/unit/test_code_blame_range.py | 41 +++-- tests/unit/test_code_review_brief_mirror.py | 14 +- tests/unit/test_code_setting_facts.py | 28 +++- tests/unit/test_code_symbol_history.py | 29 ++++ tests/unit/test_coverage_published.py | 65 +++++--- tests/unit/test_definition_write_rules.py | 6 +- tests/unit/test_degraded_unnoted.py | 156 ++++++++++++++---- .../unit/test_loom_search_tracker_general.py | 18 ++ tests/unit/test_memory_append_batch.py | 4 +- tests/unit/test_memory_bulk_parity.py | 17 +- tests/unit/test_memory_for_file.py | 32 ++++ tests/unit/test_pending_evidence.py | 7 +- .../test_review_brief_store_needs_diff.py | 38 +++++ 39 files changed, 600 insertions(+), 234 deletions(-) diff --git a/deploy/hyperdx_dashboards.md b/deploy/hyperdx_dashboards.md index dd1f1fc3597..2afde24b193 100644 --- a/deploy/hyperdx_dashboards.md +++ b/deploy/hyperdx_dashboards.md @@ -435,20 +435,19 @@ and use a time-series tile if you need rate. For a windowed count prefer the Outcome is a five-value enum set in `memory/app/handlers._count_write`: -| Outcome | Means | -| --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `created` | first write to this `memory_key` — genuinely new knowledge | -| `updated` | a new version of a key that already existed | -| `merged` | canonical-form match — caller restated something Loom already knew, **no row inserted** | -| `duplicate` | very-high similarity but canonical mismatch; inserted with `status='duplicate'` | -| `conflicted` | close-but-different peers; inserted and both sides flagged | -| `rejected` | a pinned peer blocked the write (409 PINNED_CONFLICT) | -| `blacklisted` | value matched a blacklist pattern (422 BLACKLISTED) | -| `too_large` | value exceeded `char_limit` (422 CHAR_LIMIT_EXCEEDED) | -| `precondition_failed` | `if_match_sha256` did not match the live row (409) | -| `error` | any other `HTTPException` — a CH outage or a namespace-config bug, deliberately NOT labelled `rejected` so an infrastructure failure is not read as a policy refusal | -| `unchanged` | bulk/extract path only: a byte-identical restatement skipped by the re-ingest gate. Distinct from `merged`, which is a canonical-form conflict merge on the point path | -| `unknown` | bulk/extract path only: the existing-key lookup failed (fail-open), so created-vs-updated is not knowable. Non-zero here means the panel below is under-reporting, not that nothing happened | +| Outcome | Means | +| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `created` | first write to this `memory_key` — genuinely new knowledge | +| `updated` | a new version of a key that already existed | +| `merged` | canonical-form match — caller restated something Loom already knew, **no row inserted** | +| `duplicate` | very-high similarity but canonical mismatch; inserted with `status='duplicate'` | +| `conflicted` | close-but-different peers; inserted and both sides flagged | +| `rejected` | a pinned peer blocked the write (409 PINNED_CONFLICT) | +| `blacklisted` | value matched a blacklist pattern (422 BLACKLISTED) | +| `too_large` | value exceeded `char_limit` (422 CHAR_LIMIT_EXCEEDED) | +| `precondition_failed` | `if_match_sha256` did not match the live row (409) | +| `error` | any other `HTTPException` — a CH outage or a namespace-config bug, deliberately NOT labelled `rejected` so an infrastructure failure is not read as a policy refusal | +| `unchanged` | bulk/extract path only: a byte-identical restatement skipped by the re-ingest gate. Distinct from `merged`, which is a canonical-form conflict merge on the point path | The four refusal outcomes are mapped once at the handler boundary from the `code` in the raised `HTTPException` (`_WRITE_OUTCOME_BY_ERROR_CODE`), not diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 3e93d044bfa..15dd6f8c595 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -324,14 +324,24 @@ error's kind only; the full text is in the server log. `code.ask` do not cache it, `code.map` does not keep its map, `memory.ask` stores no precedent, and `code.review_brief` serves the brief unstored (`stored: false`). Each judges the entries its own reads recorded, so one the request recorded before it does - not stop the cache. Some caches keep a fallback with its entries and name them on each - answer served from it: `code.index_status` and `code.repos` keep such a status for - `LOOM_CODE_STATUS_TTL_S`, the constructor-coverage and `overrides` probes, - `code.index_status`' symbol-stats and unit-risk counts, and the `as_of` block's lag - read keep a failed read for 30 seconds, the pending-extraction count for - `LOOM_MEMORY_PENDING_DISCLOSURE_TTL_S`, namespace health for - `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`, and each of `ops.incidents`' ClickHouse - sources for 5 seconds. + not stop the cache. +- Some caches keep a fallback with its entries and name them on each answer served from + it, for: + - `LOOM_CODE_STATUS_TTL_S`: a `code.index_status` or `code.repos` status; + - 30 seconds: a failed constructor-coverage or `overrides` probe, `code.index_status`' + symbol-stats or unit-risk count, and `code.coverage`'s gap counts, which are not + published to other processes; + - 60 seconds: a failed lag read of the `as_of` block, and a block built from it + 30 seconds more, so about 90 seconds in all; `code.search`'s coverage note; + - 300 seconds: `code.search`'s personalization directories and the `code.path_guards` + guard stage; + - `LOOM_MEMORY_SEARCH_KEY_AXIS_AUTO_TTL_SECONDS`, `LOOM_MEMORY_SUMMARY_ENTITY_TTL_S` + and `LOOM_MEMORY_CALIBRATION_NAMESPACE_MISS_TTL_S`: `memory.search`'s key-axis + probe, summary-entity vocabulary and namespace calibration; + - `LOOM_MEMORY_PENDING_DISCLOSURE_TTL_S` and + `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`: the pending-extraction count and + namespace health; + - 5 seconds: each of `ops.incidents`' ClickHouse sources. - A later page of `code.search`, `code.grep` or `memory.search` names the entries of the run that ranked its pool. What each page reads for itself (the risk block, context lines, definitions, tags, bodies) it notes on its own. diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index d16505ed879..1ec6eee205e 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -1622,7 +1622,7 @@ One ClickHouse setting, the four places that define it: its declaration and tier | --- | --- | --- | | `name` | `str` | The setting asked about, trimmed. | | `verdict` | `str` | known \| not_a_setting \| unknown | -| `causes` | `list[str]` | control_failed \| no_declaration \| invalid_name \| history_unread | +| `causes` | `list[str]` | control_failed \| declaration_unread \| no_declaration \| invalid_name \| history_unread \| randomization_unread \| tests_unread | | `declaration` | `dict[str, Any]` | {file, line, type, default, description, tier, alias} | | `tier` | `str` | The declaration's tier (production \| important \| beta \| experimental \| obsolete); '' without a declaration. | | `history` | `list[dict[str, Any]]` | [{version, old, new, reason, line}], newest release first | diff --git a/server/code/api/models_conventions.py b/server/code/api/models_conventions.py index 278753d061a..0ec21604c2a 100644 --- a/server/code/api/models_conventions.py +++ b/server/code/api/models_conventions.py @@ -32,7 +32,8 @@ class CodeSettingFactsOutput(BaseModel): name: str # known | not_a_setting | unknown verdict: str = "unknown" - # control_failed | no_declaration | invalid_name | history_unread + # control_failed | declaration_unread | no_declaration | invalid_name | history_unread | + # randomization_unread | tests_unread causes: list[str] = Field(default_factory=list) # {file, line, type, default, description, tier, alias} declaration: dict[str, Any] = Field(default_factory=dict) diff --git a/server/code/app/bisect_fusion.py b/server/code/app/bisect_fusion.py index 10df0d08320..8313aeeebf2 100644 --- a/server/code/app/bisect_fusion.py +++ b/server/code/app/bisect_fusion.py @@ -138,8 +138,10 @@ async def rows_of() -> list[dict[str, Any]]: ) if isinstance(vector, customer.HOLDS): raise vector # the org's model calls are held: the request answers that - for leg, failed in (("read", rows), ("embed", vector)): + for leg, failed in (("tracker", rows), ("embedder", vector)): if isinstance(failed, BaseException): + # the window's candidates are not fused in (its status says so too) + degradations.partial(leg, f"{window.replace(' ', '_')}_dropped", failed) logger.info("bisect fusion: %s %s failed: %s", window, leg, failed) return None return rows, vector diff --git a/server/code/app/bisect_scan.py b/server/code/app/bisect_scan.py index a0683406861..261f51f59ec 100644 --- a/server/code/app/bisect_scan.py +++ b/server/code/app/bisect_scan.py @@ -233,6 +233,7 @@ async def _linked_scan( out: list[dict[str, Any]] = [] for t, got in zip(extra, found, strict=True): if isinstance(got, BaseException): + degradations.partial("tracker", "linked_tracker_dropped", got) logger.info("bisect: linked tracker %s failed: %s", t, got) continue for r in got[0]: diff --git a/server/code/app/blame.py b/server/code/app/blame.py index 7bc4aa7f16b..394a7e1c6fc 100644 --- a/server/code/app/blame.py +++ b/server/code/app/blame.py @@ -478,6 +478,7 @@ async def _ledger_leg( ok = True for res in results: if isinstance(res, BaseException): + degradations.partial("code_index", "merge_ledger_unread", res) # beside `failed` logger.info("blame_range: ledger read failed: %s", res) ok = False continue @@ -584,11 +585,14 @@ async def _symbol_and_comments( repo.review_comments_for(org, ns, [path], limit=120, humans_only=True), return_exceptions=True, ) - rows: list[dict[str, Any]] = [] if isinstance(got[0], BaseException) else list(got[0]) - comments: list[dict[str, Any]] = [] if isinstance(got[1], BaseException) else list(got[1]) - for name, res in (("functions", got[0]), ("review comments", got[1])): + halves: list[list[dict[str, Any]]] = [] + for name, res in (("enclosing_function", got[0]), ("review_comments", got[1])): if isinstance(res, BaseException): + degradations.partial("code_index", f"{name}_unread", res) logger.info("blame_range: %s read failed: %s", name, res) + res = [] + halves.append(list(res)) + rows, comments = halves sym = intro.enclosing_symbol(rows, start, end) return (dict(sym) if sym else {}), comments diff --git a/server/code/app/common.py b/server/code/app/common.py index 857732e815a..79bce9b0707 100644 --- a/server/code/app/common.py +++ b/server/code/app/common.py @@ -194,10 +194,9 @@ def invalidate_index_as_of(org: str, ns: str) -> None: _AS_OF_CACHE.pop((org, ns)) -# (org, ns) -> note. Sixty seconds per namespace; the count behind it is -# `table_counts`' fingerprint-cached scan, held a minute while the entry is building and -# ten otherwise (code_context). -# (org, ns) -> (note, failed read's text or "") +# (org, ns) -> (note, failed read's text or ""). Sixty seconds per namespace; the count +# behind it is `table_counts`' fingerprint-cached scan, held a minute while the entry is +# building and ten otherwise (code_context). _COVERAGE_NOTE_CACHE: TtlCache[tuple[str, str], tuple[str, str]] = TtlCache(60.0, maxsize=256) diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index b84efc5ba76..87e86958022 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -74,6 +74,7 @@ async def build_brief( }, ) except Exception as e: # noqa: BLE001 — every section fails open + degradations.partial("code.review_brief", "symbols_failed", e) logger.info("review_brief: code.impact failed for PR %s: %s", inp.pr_number, e) sections["symbols"] = failed_section("code.impact", e) @@ -156,6 +157,7 @@ async def _function_rows(inp: BriefInputs, repo: Any, paths: list[str]) -> list[ try: return list(await repo.functions_for_paths(inp.org, inp.ns, wanted, limit=400)) except Exception as e: # noqa: BLE001 — decoration; the sections degrade + degradations.partial("code_index", "function_rows_unread", e) logger.info("review_brief: functions_for_paths failed for PR %s: %s", inp.pr_number, e) return [] @@ -186,6 +188,7 @@ async def _symbols_section( try: await _decorate_callers(rows, inp, repo, fn_rows or []) except Exception as e: # noqa: BLE001 — counts are decoration + degradations.partial("code_index", "caller_counts_unread", e) logger.info("review_brief: caller counts failed for PR %s: %s", inp.pr_number, e) rows.sort(key=lambda r: (-int(r["callers_hop1"]), r["qualified_name"], r["path"])) verdict = str(impact.get("verdict") or "") or ("touched" if rows else "no_symbols") @@ -224,6 +227,7 @@ async def _decorate_callers( try: stats = await code_fan_in.stats_for(repo, inp.org, inp.ns, wanted) except Exception as e: # noqa: BLE001 — fan-in is decoration on decoration + degradations.partial("code_index", "fan_in_unread", e) logger.info("review_brief: fan-in stats failed for PR %s: %s", inp.pr_number, e) for r in rows: sid = ids.get((r["path"], r["qualified_name"]), "") @@ -276,6 +280,7 @@ async def _tests_section( epistemic = "lower_bound" for (kind, subject), res in zip(subjects, results[: len(subjects)], strict=True): if isinstance(res, BaseException): + degradations.partial("code.review_brief", "coverage_claim_failed", res) causes.append(f"coverage_claim:{type(res).__name__}") continue tests = list(res.get("tests") or []) @@ -292,6 +297,7 @@ async def _tests_section( if home_wanted: res = results[-1] if isinstance(res, BaseException): + degradations.partial("code.review_brief", "test_home_failed", res) causes.append(f"test_home:{type(res).__name__}") else: rows.append( @@ -338,6 +344,7 @@ async def _settings_section( causes: list[str] = [] for (name, source), res in zip(settings, results, strict=True): if isinstance(res, BaseException): + degradations.partial("code.review_brief", "setting_facts_failed", res) causes.append(f"setting_facts:{type(res).__name__}") continue rand = dict(res.get("randomized_in_ci") or {}) @@ -379,6 +386,7 @@ async def _history_section(call: CallOp, inp: BriefInputs, names: list[str]) -> causes: list[str] = [] for name, res in zip(names, results, strict=True): if isinstance(res, BaseException): + degradations.partial("code.review_brief", "symbol_history_failed", res) causes.append(f"symbol_history:{type(res).__name__}") continue s = dict(res.get("summary") or {}) @@ -446,6 +454,7 @@ async def _blame_section( exact = True for (p, s, e), res in zip(ranges, results, strict=True): if isinstance(res, BaseException): + degradations.partial("code.review_brief", "blame_range_failed", res) causes.append(f"blame_range:{type(res).__name__}") exact = False continue @@ -494,6 +503,7 @@ async def _tracker_section( try: status, rows = await reader(inp.org, inp.ns, inp.pr_number, touched) except Exception as e: # noqa: BLE001 — the section reports its failure; the brief still serves + degradations.partial("code.review_brief", "tracker_failed", e) return failed_section("tracker", e) if status != SERVED: return section( @@ -532,6 +542,7 @@ async def _risk_section( try: fit = await risk_fit.stored_fit(repo, inp.org, inp.ns) except Exception as e: # noqa: BLE001 — the section reports its failure; the brief still serves + degradations.partial("code.review_brief", "risk_failed", e) return failed_section("risk_fit", e) if fit is None: return no_fit @@ -658,7 +669,8 @@ async def build_for_merge( head = "" try: head = str(await repo.get_state(org, ns, "git_head") or "") - except Exception: # noqa: BLE001 — an unread head is blank; the brief still serves + except Exception as e: # noqa: BLE001 — served with a blank indexed_commit, not stored + degradations.partial("code_index", "head_unread", e) head = "" inp = BriefInputs( org=org, @@ -706,6 +718,7 @@ async def _ledger_author(repo: Any, org: str, ns: str, pr_number: int) -> str: try: facts = await repo.pr_merge_facts(org, ns, pr_number=int(pr_number), within_head=False) except Exception as e: # noqa: BLE001 — the prior falls back to the base rate + degradations.partial("code_index", "pr_author_unread", e) logger.info("review_brief: ledger facts read failed for PR %s: %s", pr_number, e) facts = None return str((facts or {}).get("author") or "") @@ -762,7 +775,8 @@ async def build_for_open( head = "" try: head = str(await repo.get_state(org, ns, "git_head") or "") - except Exception: # noqa: BLE001 — an unread head is blank; the brief still serves + except Exception as e: # noqa: BLE001 — served with a blank indexed_commit, not stored + degradations.partial("code_index", "head_unread", e) head = "" inp = BriefInputs( org=org, diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index f49a2668a66..9da927f3cdb 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -982,14 +982,19 @@ async def _coverage_cached( """`repo.coverage` + `repo.coverage_gaps`, remembered per (org, ns) while the counts fingerprint of `state` matches and the entry is younger than the counts max age (60 s while an index builds, 10 min steady). The gap counts are None when their queries failed — the - page renders without the gaps row.""" + page renders without the gaps row, nothing is published, and the entry is kept only + `PROBE_ERROR_TTL_S`, so the next read after it computes again.""" + from server.code.app.symbol.dispatch import PROBE_ERROR_TTL_S from server.code.store.index import counts_fingerprint key = (org, ns) fp = counts_fingerprint(state) hit = _coverage_cache.get(key) now = time.monotonic() - if hit is not None and hit[0] == fp and now - hit[1] < _counts_max_age_s(state): + max_age_s = _counts_max_age_s(state) + if hit is not None and hit[3] is None: + max_age_s = min(max_age_s, PROBE_ERROR_TTL_S) + if hit is not None and hit[0] == fp and now - hit[1] < max_age_s: if hit[3] is None: # each page served from a failed gap read names it degradations.partial("code_index", "coverage_gaps_unread", hit[4]) return hit[2], hit[3] @@ -1006,7 +1011,7 @@ async def _coverage_cached( cov, gap_counts = published elif refresh is not None: cov, gap_counts = await refresh(org, ns, fingerprint=fp) - else: # a repository without the publisher (test fakes): compute, keep + else: # a repository without the publisher (test fakes): compute cov = await repo.coverage(org, ns) try: gap_counts = await repo.coverage_gaps(org, ns) @@ -1016,8 +1021,8 @@ async def _coverage_cached( logger.warning("code.coverage: gap queries failed for %s/%s: %s", org, ns, e) gap_counts, failure = None, caller_text(e) if gap_counts is None: - # The gap queries failed, here or where the shared row was computed (which - # keeps no kind): the page renders without its gaps row. + # The gap queries failed here, or in the publisher (which keeps no kind): the page + # renders without its gaps row. degradations.partial("code_index", "coverage_gaps_unread", failure) if len(_coverage_cache) > 256: _coverage_cache.clear() diff --git a/server/code/app/settings.py b/server/code/app/settings.py index 83231a5eb77..d1fdc3fb4af 100644 --- a/server/code/app/settings.py +++ b/server/code/app/settings.py @@ -109,6 +109,12 @@ async def _control(repo: CodeRepo, org: str, ns: str) -> tuple[bool, str]: return False, probe +# The reads `handle_code_setting_facts` gathers, in order, and what each answers when it +# fails. +_READS = ("control", "declaration", "history", "randomization", "tests") +_UNREAD: tuple[Any, ...] = ((False, ""), None, [], [], ([], 0)) + + async def handle_code_setting_facts(input: Any) -> Any: require_code_intel() started = time.monotonic() @@ -127,25 +133,25 @@ async def handle_code_setting_facts(input: Any) -> Any: repo.grep_files(org, ns, name, path_prefix="tests/", limit=1), return_exceptions=True, ) - control_ok, probe = ( - cast(tuple[bool, str], gathered[0]) - if not isinstance(gathered[0], BaseException) - else (False, "") - ) - decl = gathered[1] if not isinstance(gathered[1], BaseException) else None - hist_rows = gathered[2] if not isinstance(gathered[2], BaseException) else [] - rand_rows = gathered[3] if not isinstance(gathered[3], BaseException) else [] - grep_res = gathered[4] if not isinstance(gathered[4], BaseException) else ([], 0) - for g in gathered: + got: list[Any] = [] + unread: list[str] = [] + for read, g, default in zip(_READS, gathered, _UNREAD, strict=True): if isinstance(g, BaseException): - logger.info("setting_facts read failed (open): %s", g) - facts.declaration = cast(sf.Declaration | None, decl) - facts.history = sf.parse_history(cast(list[dict[str, Any]], hist_rows), name) - facts.randomization = sf.parse_randomization(cast(list[dict[str, Any]], rand_rows), name) - facts.tests_total = int(cast(tuple[Any, int], grep_res)[1] or 0) - verdict, causes = sf.verdict_of(facts, control_ok=control_ok) - if isinstance(gathered[2], BaseException): - causes = [*causes, "history_unread"] + degradations.partial("code_index", f"setting_{read}_unread", g) + logger.info("setting_facts: %s read failed (open): %s", read, g) + unread.append(read) + g = default + got.append(g) + control_ok, probe = cast(tuple[bool, str], got[0]) + facts.declaration = cast(sf.Declaration | None, got[1]) + facts.history = sf.parse_history(cast(list[dict[str, Any]], got[2]), name) + facts.randomization = sf.parse_randomization(cast(list[dict[str, Any]], got[3]), name) + facts.tests_total = int(cast(tuple[Any, int], got[4])[1] or 0) + verdict, causes = sf.verdict_of( + facts, control_ok=control_ok, declaration_ok="declaration" not in unread + ) + # the verdict names an unread control or declaration; the other reads only shrink it + causes = [*causes, *(f"{r}_unread" for r in unread if r not in ("control", "declaration"))] trace_run_id = new_trace_run_id() schedule_code_trace( org=org, diff --git a/server/code/app/symbol_history.py b/server/code/app/symbol_history.py index 898cff068e3..2d07b8adbc6 100644 --- a/server/code/app/symbol_history.py +++ b/server/code/app/symbol_history.py @@ -27,6 +27,7 @@ from server.code.domain.index import symbol_history as sh from server.code.store.index import CodeRepo from server.core.errors import ValidationError +from server.observability import degradations from server.tracker.domain import bisect as bi logger = logging.getLogger(__name__) @@ -67,6 +68,7 @@ async def _tracker_side( ) issues = [*incidents, *issues] except TrackerUnavailable as e: + degradations.partial("tracker", "symbol_facts_unread", e) # beside tracker_unavailable logger.info("symbol_history: qa unavailable on %s (%s)", tracker_ns, e) return {}, [], [], tracker_ns, False return facts, edges, issues, tracker_ns, True @@ -139,16 +141,21 @@ async def handle_code_symbol_history(input: Any) -> Any: _tracker_side(org, ns, pr_numbers, frames, path), return_exceptions=True, ) - issue_facts = ( - cast(dict[int, dict[str, Any]], gathered[0]) - if not isinstance(gathered[0], BaseException) - else {} - ) + issue_facts: dict[int, dict[str, Any]] = {} + if isinstance(gathered[0], BaseException): + degradations.partial("code_index", "issue_facts_unread", gathered[0]) + logger.info("symbol_history: linked issues read failed (open): %s", gathered[0]) + else: + issue_facts = cast(dict[int, dict[str, Any]], gathered[0]) if isinstance(gathered[1], BaseException): + degradations.partial("tracker", "symbol_facts_unread", gathered[1]) logger.info("symbol_history: qa side failed (open): %s", gathered[1]) tracker_facts, tracker_edges, open_issues, tracker_ns, qa_ok = {}, [], [], "", False + # a side that raised did not say which namespace it read: unavailable all the same + tracker_unavailable = True else: tracker_facts, tracker_edges, open_issues, tracker_ns, qa_ok = gathered[1] + tracker_unavailable = bool(tracker_ns) and not qa_ok rows = sh.build_rows( prs, issue_facts={k: _issue_view(v) for k, v in issue_facts.items()}, @@ -161,7 +168,7 @@ async def handle_code_symbol_history(input: Any) -> Any: ) summary = sh.summarize(rows, window_prs=_PR_WINDOW, open_issues=len(open_issues), qa_ok=qa_ok) verdict, causes = sh.verdict_of(rows, resolved=True) - if tracker_ns and not qa_ok: + if tracker_unavailable: causes = [*causes, "tracker_unavailable"] span_comments = [ { @@ -213,7 +220,7 @@ async def handle_code_symbol_history(input: Any) -> Any: open_issues_naming=[_open_issue_view(r) for r in open_issues[:5]], summary=summary, tracker_namespace=tracker_ns, - tracker_unavailable=bool(tracker_ns) and not qa_ok, + tracker_unavailable=tracker_unavailable, trace_run_id=trace_run_id, ) diff --git a/server/code/domain/index/setting_facts.py b/server/code/domain/index/setting_facts.py index 7142466052f..6ef427d050b 100644 --- a/server/code/domain/index/setting_facts.py +++ b/server/code/domain/index/setting_facts.py @@ -333,13 +333,17 @@ def _sampler_end(text: str) -> int: return len(text) -def verdict_of(facts: Facts, *, control_ok: bool) -> tuple[str, list[str]]: +def verdict_of( + facts: Facts, *, control_ok: bool, declaration_ok: bool = True +) -> tuple[str, list[str]]: """`known` when the tree declares the setting; `not_a_setting` when the positive control found its own declaration and this name has none; `unknown` when the control failed (the declaration files are not in the - index or the read fell over).""" + index or the read fell over) or this name's declaration read failed.""" if not control_ok: return "unknown", ["control_failed"] + if not declaration_ok: + return "unknown", ["declaration_unread"] if facts.declaration is None: return "not_a_setting", ["no_declaration"] return "known", [] diff --git a/server/code/store/index/status.py b/server/code/store/index/status.py index a3b52c77059..ab1874fbe09 100644 --- a/server/code/store/index/status.py +++ b/server/code/store/index/status.py @@ -43,9 +43,9 @@ def parse_shared_coverage( row: StateEntry | None, fingerprint: str -) -> tuple[dict[str, Any], dict[str, int] | None] | None: - """The published coverage when the row's - fingerprint is the caller's; None otherwise (missing, stale, unparsable).""" +) -> tuple[dict[str, Any], dict[str, int]] | None: + """The published coverage and gap counts when the row's fingerprint is the + caller's; None otherwise (missing, stale, unparsable, or without its gap counts).""" if not row or str(row.get("detail") or "") != fingerprint: return None try: @@ -55,8 +55,9 @@ def parse_shared_coverage( if not isinstance(parsed, dict) or not isinstance(parsed.get("cov"), dict): return None gaps = parsed.get("gaps") - counts = {str(k): int(v) for k, v in gaps.items()} if isinstance(gaps, dict) else None - return parsed["cov"], counts + if not isinstance(gaps, dict): + return None + return parsed["cov"], {str(k): int(v) for k, v in gaps.items()} def _coverage_embedded(raw: str | None) -> int | None: @@ -99,16 +100,19 @@ async def refresh_coverage( counts; a reader with no matching row calls it too, so the first cold open pays once for every process and colour. A cold computation reads about 1.2 GB and takes 4 s on a large repository; the row is a point - read. `must_land`: a failed write raises, for a caller that writes the - counts only once this row has landed.""" + read. A failed gap read publishes nothing, so every process computes + again rather than serving no gaps until the counts move, and the gap + counts answer None. `must_land`: a failed gap read or write raises, for + a caller that writes the counts only once this row has landed.""" if fingerprint is None: fingerprint = counts_fingerprint(await self.all_state(org, ns)) cov = await self.coverage(org, ns) - gaps: dict[str, int] | None try: gaps = await self.coverage_gaps(org, ns) - except Exception: # noqa: BLE001 — the gap queries are additive - gaps = None + except Exception: # the gap queries are additive; nothing is published + if must_land: + raise + return cov, None try: await self.set_state( org, diff --git a/server/memory/app/bulk_rows.py b/server/memory/app/bulk_rows.py index 1c4c53e4eac..f53128b95ac 100644 --- a/server/memory/app/bulk_rows.py +++ b/server/memory/app/bulk_rows.py @@ -166,13 +166,6 @@ class _BulkWriteState: existing_rows: dict[str, Any] = field(default_factory=dict) # Under Postgres, each other key's deleted head: a write goes above it too. deleted_heads: dict[str, Any] = field(default_factory=dict) - # Whether the batched lookup below actually succeeded. It is fail-open - # (log-and-continue), so on a ClickHouse hiccup `existing_ids` is empty and every entry - # would look new, emitting N `created` ticks for a re-ingest of an unchanged corpus: the - # exact false signal the counter exists to remove, during an incident when the panel is - # trusted. MUST be initialised here, before the lookup: initialising it after the lookup - # would clobber the success assignment and classify every batch as `unknown`. - existing_lookup_ok: bool = False # Under the Postgres authority: the scope generations the verdicts are reached at. generations: dict[tuple[str, str], int] = field(default_factory=dict) # Each memory type's (conflict threshold, reach), read once per call. @@ -216,10 +209,9 @@ class _BulkWriteState: retyped: list[str] = field(default_factory=list) skipped_pinned: list[str] = field(default_factory=list) skipped_locked: list[str] = field(default_factory=list) - # Write outcomes for `loom.memory.writes`: created / updated / unknown. + # Write outcomes for `loom.memory.writes`: created / updated. n_created: int = 0 n_updated: int = 0 - n_unknown: int = 0 # The write's clock: a row's expiry is settled against it at build and at replay. now_utc: datetime = field(default_factory=lambda: datetime.now(UTC)) # Keys of a step built without a vector whose labels the replay changed: its row lands @@ -684,10 +676,7 @@ def write_step_results(state: _BulkWriteState, plan: BulkVerdictPlan) -> None: ): # It was built and counted as a write of a key the batch had already seen. res.version, res.memory_id = 0, "" - if state.existing_lookup_ok: - state.n_updated -= 1 - else: - state.n_unknown -= 1 + state.n_updated -= 1 if step.outcome in (StepOutcome.UNCHANGED, StepOutcome.RELABEL): # The same bytes again: a restatement, whether or not it changes a label. _note_restatement(state, str(row["memory_id"])) @@ -909,11 +898,7 @@ async def _bulk_build_rows( # corpus re-extracting the same keys: the same false signal the counter exists to # remove, with the opposite sign. `existing_ids` is the same lookup the pin and # skip-gate checks use. - if not state.existing_lookup_ok: - # Unknown, not "new". Counting these as `created` would fabricate - # learning volume during an incident. - state.n_unknown += 1 - elif entry.memory_key in state.existing_ids or entry.memory_key in state.built: + if entry.memory_key in state.existing_ids or entry.memory_key in state.built: # A key an earlier entry of this batch built is a new version, not a creation. state.n_updated += 1 else: diff --git a/server/memory/app/bulk_set.py b/server/memory/app/bulk_set.py index df428cbd510..c496e6d0652 100644 --- a/server/memory/app/bulk_set.py +++ b/server/memory/app/bulk_set.py @@ -17,7 +17,7 @@ from server.core.ch import get_client, sequential_reads from server.core.datetimes import naive_utc_now from server.core.error_summary import error_summary -from server.core.errors import ValidationError +from server.core.errors import BackendUnavailableError, LoomServerError, ValidationError from server.core.hashing import hash_text from server.core.hashing import sha256_value as _content_sha256 from server.core.vectors import codes_state @@ -121,41 +121,44 @@ def value_updates_enabled(request_value: bool | None = None) -> bool: async def _bulk_existing_lookup(ch: Any, input: MemoryBulkSetInput, state: _BulkWriteState) -> None: """Phase 1: one batched read of the live rows under this session's keys — id, content hash, pin, creation time and the carried columns per key — into `state`. - Fail-open: on an error `state.existing_lookup_ok` stays False.""" + Fails closed: without the live rows a batch would overwrite a read-only key, unpin a + pinned one and announce revisions as new writes, so a failed read refuses the batch + before anything is written, retryable.""" + import server.memory.store as memory_repo + try: - keys = [entry.memory_key for entry in input.entries] - if keys: - import server.memory.store as memory_repo - - # Full rows (a revision carries every column forward), with sequential - # consistency: the answer decides skip, pin and version per entry. Under - # Postgres a deleted head comes in the same read: a write goes above it too. - held = await memory_repo.memory_rows_by_identity_keys( - [ - (input.org, input.namespace, input.agent, input.user_id, input.session_id, k) - for k in keys - ], - ch=ch, - sequential=True, - include_tombstoned=pg.enabled(), - ) - rows = {key[5]: r for key, r in held.items() if r.tombstoned_at is None} - state.existing_rows = rows - state.deleted_heads = { - key[5]: r for key, r in held.items() if r.tombstoned_at is not None - } - state.existing_ids = {k: str(r.memory_id) for k, r in rows.items() if r.memory_id} - state.existing_sha = { - k: hash_text(r.content_sha256) for k, r in rows.items() if r.content_sha256 - } - state.existing_pinned = {k: bool(r.pinned) for k, r in rows.items()} - state.existing_created = {k: r.created_at for k, r in rows.items() if r.created_at} - state.existing_carried = { - k: {c: getattr(r, c, None) for c in _BULK_CARRIED_COLS} for k, r in rows.items() - } - state.existing_lookup_ok = True - except Exception as e: # noqa: BLE001 — writes without prior state - log.warning("bulk_set existing-id lookup failed (non-fatal): %s", error_summary(e)) + # Full rows (a revision carries every column forward), with sequential + # consistency: the answer decides skip, pin and version per entry. Under + # Postgres a deleted head comes in the same read: a write goes above it too. + held = await memory_repo.memory_rows_by_identity_keys( + [ + (input.org, input.namespace, input.agent, input.user_id, input.session_id, k) + for k in (entry.memory_key for entry in input.entries) + ], + ch=ch, + sequential=True, + include_tombstoned=pg.enabled(), + ) + except LoomServerError: + raise # a coded store failure (a timeout, an unavailable backend) as it is + except Exception as e: # refused as a backend failure, nothing written + log.warning("bulk_set: live-row lookup failed: %s", error_summary(e)) + op = "memory.append_batch" if state.strict_append else "memory.bulk_set" + raise BackendUnavailableError( + f"{op} could not read its keys' live rows; nothing was written" + ) from e + rows = {key[5]: r for key, r in held.items() if r.tombstoned_at is None} + state.existing_rows = rows + state.deleted_heads = {key[5]: r for key, r in held.items() if r.tombstoned_at is not None} + state.existing_ids = {k: str(r.memory_id) for k, r in rows.items() if r.memory_id} + state.existing_sha = { + k: hash_text(r.content_sha256) for k, r in rows.items() if r.content_sha256 + } + state.existing_pinned = {k: bool(r.pinned) for k, r in rows.items()} + state.existing_created = {k: r.created_at for k, r in rows.items() if r.created_at} + state.existing_carried = { + k: {c: getattr(r, c, None) for c in _BULK_CARRIED_COLS} for k, r in rows.items() + } async def _bulk_identity_dupes(ch: Any, input: MemoryBulkSetInput) -> dict[str, tuple[str, str]]: @@ -804,9 +807,8 @@ def _owes_retirement(r: dict[str, Any], retire: dict[str, tuple[Any, int]]) -> b def _vectors_to_retire(state: _BulkWriteState) -> dict[str, tuple[Any, int]]: """memory_key -> (identity key, version) of each key whose winning row (the highest version in the batch) lands unembedded and may have a live vector: the - batch embedded an earlier entry of it, the replaced version was embedded, or the - lookup failed and nobody knows. A row the replay left without the vector its level - takes lands unembedded too.""" + batch embedded an earlier entry of it, or the replaced version was embedded. A row the + replay left without the vector its level takes lands unembedded too.""" winners = kept_versions(state.memory_rows) batch_embedded = {str(r.get("memory_key")) for r in state.embedding_rows} # an earlier entry's vector is not the winner's: match the row by its version @@ -820,7 +822,7 @@ def _vectors_to_retire(state: _BulkWriteState) -> dict[str, tuple[Any, int]]: continue prev = state.existing_rows.get(key) prev_embedded = prev is not None and is_embedded(prev.memory_type, prev.sensitivity) - if key in batch_embedded or not state.existing_lookup_ok or prev_embedded: + if key in batch_embedded or prev_embedded: out[key] = (identity_key(r), int(r["version"])) return out @@ -1072,7 +1074,6 @@ def _bulk_record_write_metrics(input: MemoryBulkSetInput, state: _BulkWriteState for outcome, count in ( ("created", state.n_created), ("updated", state.n_updated), - ("unknown", state.n_unknown), ("blacklisted", len(state.skipped_blacklisted)), ("rejected", len(state.skipped_pinned) + len(state.skipped_locked)), # NOT the point path's `merged` (a canonical-form conflict merge). @@ -1335,8 +1336,6 @@ async def handle_memory_append_batch(input: MemoryAppendBatchInput) -> MemoryBul def _require_whole_append(input: MemoryBulkSetInput, state: _BulkWriteState) -> None: if not state.strict_append: return - if not state.existing_lookup_ok: - raise ValidationError("memory.append_batch could not verify fresh keys") if state.existing_rows or state.deleted_heads: raise ValidationError("memory.append_batch keys must not already exist") if ( @@ -1551,9 +1550,7 @@ async def _bulk_follow_ups( async def _bulk_announce(state: _BulkWriteState) -> None: """The written rows, to the namespace's webhooks: a key that was live, or that an earlier entry of this batch wrote, is revised; any other is - written. An unchanged restatement writes no row and sends nothing. When - the live-key lookup failed (`existing_lookup_ok` is False) every key looks - new, so a revision is announced as written.""" + written. An unchanged restatement writes no row and sends nothing.""" seen = set(state.existing_ids) changes: list[tuple[EventType, dict[str, Any]]] = [] for row in state.memory_rows: diff --git a/server/memory/app/for_file.py b/server/memory/app/for_file.py index 889583ce1d8..5ab779a2138 100644 --- a/server/memory/app/for_file.py +++ b/server/memory/app/for_file.py @@ -874,6 +874,7 @@ async def _merged_rows( rows = list(own) for ns, res in zip(extras, got, strict=True): if isinstance(res, BaseException): + degradations.partial("memory.for_file", "other_namespaces_dropped", res) log.debug("memory.for_file: extra namespace %s skipped: %s", ns, res) continue rows.extend(res) diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index 641eee3eb14..bd17891d86a 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -439,13 +439,13 @@ async def search_sections( i for i, (_, m) in models.items() if code_change.moved_for_stale_code(m) ) payload["memory"] = drop_flagged_hits(memory) - if not isinstance(know_result, Exception): + if isinstance(know_result, Exception): + payload["knowledge"] = {"error": _leg_error("knowledge", know_result), "results": []} + else: try: payload["knowledge"] = await _published_knowledge(know_result, plan, agent) except Exception as error: # noqa: BLE001 — a failed knowledge renewal leaves other sections available - know_result = error - if isinstance(know_result, Exception): - payload["knowledge"] = {"error": _leg_error("knowledge", know_result), "results": []} + payload["knowledge"] = {"error": _leg_error("knowledge", error), "results": []} payload["profile"] = ( {"error": _leg_error("profile", profile_rows), "results": []} if isinstance(profile_rows, Exception) diff --git a/server/memory/app/loom_search/tracker_leg.py b/server/memory/app/loom_search/tracker_leg.py index 811148c7a7c..0b9bcf6ffb0 100644 --- a/server/memory/app/loom_search/tracker_leg.py +++ b/server/memory/app/loom_search/tracker_leg.py @@ -223,6 +223,7 @@ async def tracker_leg( out = await execute_duplicate_check(plan.duplicate) if out.tracker_unavailable: + degradations.partial("loom_search", "tracker_dropped", "tracker_unavailable") return None return lean_tracker_section(out, defect_report_shape(query) or {}) except Exception as e: # noqa: BLE001 — fail open: the memory legs answer @@ -258,7 +259,14 @@ async def _similar_section( results: list[dict[str, Any]] = [] served: list[str] = [] for namespace, output in zip(plan.namespaces, outputs, strict=True): - if isinstance(output, BaseException) or output.tracker_unavailable: + if isinstance(output, BaseException): + degradations.partial("loom_search", "tracker_dropped", output) + logger.info( + "loom_search tracker search failed on %s: %s", namespace, type(output).__name__ + ) + continue + if output.tracker_unavailable: + degradations.partial("loom_search", "tracker_dropped", "tracker_unavailable") continue served.append(namespace) for row in output.items: diff --git a/server/memory/app/pending_evidence.py b/server/memory/app/pending_evidence.py index 4026ad8d602..2de2fe1ede9 100644 --- a/server/memory/app/pending_evidence.py +++ b/server/memory/app/pending_evidence.py @@ -61,7 +61,7 @@ def rank_pending_turns( """The pending turns most lexically related to the question. Score is the count of shared content words (then the shared fraction of the question's words); a turn under `min_overlap` shared words is not - evidence. Pure; malformed payloads are skipped.""" + evidence. A malformed payload is skipped and noted.""" q_tokens = _tokens(question) if not q_tokens: return [] @@ -69,7 +69,8 @@ def rank_pending_turns( for b in batches: try: data = json.loads(b.get("payload") or "{}") - except Exception: # noqa: BLE001 — a malformed batch is not evidence + except Exception as e: # noqa: BLE001 — a malformed batch is not evidence + degradations.partial("memory.ask", "pending_batch_dropped", e) continue msgs = data.get("messages") or [] if not isinstance(msgs, list): diff --git a/server/memory/app/set_commit.py b/server/memory/app/set_commit.py index 5141945a9be..970ee3aaa65 100644 --- a/server/memory/app/set_commit.py +++ b/server/memory/app/set_commit.py @@ -96,8 +96,6 @@ def count_write(namespace: str, outcome: str) -> None: refused rejected / blacklisted / too_large / precondition_failed failed error (infrastructure; see handle_memory_set) bulk-only unchanged (byte-identical restatement) - unknown (the existing-key lookup failed, so - created-vs-updated is not knowable) Keep this list in step with `_WRITE_OUTCOME_BY_ERROR_CODE`, the instrument description in `observability/metrics`, and the table in diff --git a/server/observability/metrics.py b/server/observability/metrics.py index 5416406dc22..e8c51f2daa3 100644 --- a/server/observability/metrics.py +++ b/server/observability/metrics.py @@ -223,7 +223,7 @@ def _init_memory_instruments(meter: Any) -> None: description=( "Memory write outcomes (created/updated/merged/duplicate/" "conflicted/rejected/blacklisted/too_large/precondition_failed/" - "error/unchanged/unknown)" + "error/unchanged)" ), unit="1", ) diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 81b7c3fa395..a876ec26bf0 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -27,6 +27,8 @@ server/code/app/common.py::record_code_outcome::1 server/code/app/common.py::record_code_shunt::1 telemetry server/code/app/common.py::schedule_code_trace._write::1 telemetry server/code/app/common.py::schedule_code_trace_validation_failure::1 telemetry +server/code/app/index/review_brief_build.py::build_for_merge::4 write +server/code/app/index/review_brief_build.py::build_for_open::3 write server/code/app/index_status.py::_commit_missing::1 noted_by_caller # _lag_between notes git_mirror: lag_unknown server/code/app/index_status.py::_publish_status_snapshot::1 write server/code/app/index_status.py::_refresh_repo_status::1 logged_only_nonanswer @@ -86,7 +88,6 @@ server/memory/app/bulk_rows.py::_with_sensitivity_tag::1 server/memory/app/bulk_set.py::_audit_bulk_write::1 write server/memory/app/bulk_set.py::_batched_peers::1 cache_fallback server/memory/app/bulk_set.py::_bulk_audit::1 write -server/memory/app/bulk_set.py::_bulk_existing_lookup::1 write server/memory/app/bulk_set.py::_bulk_follow_row_supersessions::1 write server/memory/app/bulk_set.py::_bulk_identity_dupes::1 write server/memory/app/bulk_set.py::_bulk_intra_batch_pairs::1 write @@ -124,6 +125,7 @@ server/memory/app/conflicts.py::_substitution_verdict::1 server/memory/app/conflicts.py::apply_refines::1 write server/memory/app/conflicts.py::apply_refines::2 write server/memory/app/conflicts.py::auto_reinforce_peer::1 write +server/memory/app/conflicts.py::candidate_rows_many::gather::1 cache_fallback server/memory/app/conflicts.py::prefetch_write_config::1 cache_fallback server/memory/app/conflicts.py::same_key_mark::1 write server/memory/app/consolidate.py::_ask_merge::1 write @@ -196,7 +198,6 @@ server/memory/app/inspect.py::_record_exposure::1 server/memory/app/intent_marks.py::flush::1 write server/memory/app/key_supersession.py::supersede_same_key_rows::1 write server/memory/app/loom_search/fanout.py::_prepare_knowledge::1 noted_by_caller # _leg_error notes the knowledge leg -server/memory/app/loom_search/fanout.py::search_sections::1 noted_by_caller # _leg_error notes the knowledge leg server/memory/app/move.py::_redirect_source::1 write server/memory/app/namespace_retrieval_defaults.py::parse::1 settings server/memory/app/namespace_retrieval_defaults.py::resolve::1 settings @@ -209,7 +210,6 @@ server/memory/app/ops.py::handle_memory_outcome::1 server/memory/app/ops.py::handle_memory_outcome::2 write server/memory/app/ops.py::handle_memory_outcome_run::1 write server/memory/app/path_lessons.py::_confirmed_omissions::1 full_answer_fallback -server/memory/app/pending_evidence.py::rank_pending_turns::1 full_answer_fallback server/memory/app/period_digest.py::_source_memories::1 logged_only_nonanswer server/memory/app/period_digest.py::_write_period::1 logged_only_nonanswer server/memory/app/period_digest.py::_write_period::2 logged_only_nonanswer @@ -310,4 +310,5 @@ server/memory/app/triple_projections.py::_write_stated_relations::2 server/memory/app/triple_projections.py::reconcile_row_facts::1 write server/memory/app/value_updates.py::link_value_updates._one::1 write server/memory/app/value_updates.py::link_value_updates::1 write +server/memory/app/value_updates.py::link_value_updates::gather::1 cache_fallback server/memory/app/verify.py::_mirror_verified_to_embeddings::1 write diff --git a/tests/unit/test_bulk_conflict_verdicts.py b/tests/unit/test_bulk_conflict_verdicts.py index 979ccaa00a3..3a89b088d88 100644 --- a/tests/unit/test_bulk_conflict_verdicts.py +++ b/tests/unit/test_bulk_conflict_verdicts.py @@ -29,7 +29,7 @@ def _stored(**keys: tuple[str, str]): """A bulk's state over stored rows `keys` (key -> (memory_id, sha)), no entries yet.""" from server.memory.app.bulk_rows import _BulkWriteState - state = _BulkWriteState(existing_lookup_ok=True) + state = _BulkWriteState() state.existing_ids = {k: mid for k, (mid, _sha) in keys.items()} state.existing_sha = {k: sha for k, (_mid, sha) in keys.items()} return state @@ -274,7 +274,7 @@ def _batch(stored_sha: str, *entries: tuple[str, bool]): from server.memory.api.models_bulk import _BulkSetResult from server.memory.app.bulk_rows import _bulk_skip_gate, _BulkWriteState, _keep_row - state = _BulkWriteState(existing_lookup_ok=True) + state = _BulkWriteState() state.existing_ids, state.existing_sha = {"k": "e1"}, {"k": stored_sha} for sha, pinned in entries: if _bulk_skip_gate(NS(memory_key="k"), sha, state, {}): diff --git a/tests/unit/test_bulk_identity_dedup.py b/tests/unit/test_bulk_identity_dedup.py index 3e0c873cd57..4f2283baca5 100644 --- a/tests/unit/test_bulk_identity_dedup.py +++ b/tests/unit/test_bulk_identity_dedup.py @@ -155,6 +155,26 @@ async def test_lookup_failure_is_fail_open(harness) -> None: assert len(_memory_rows(ch)) == 1 and out.identity_duplicates == {} +@pytest.mark.asyncio +async def test_a_failed_live_row_read_refuses_the_batch_and_writes_nothing( + harness, monkeypatch: pytest.MonkeyPatch +) -> None: + """Without the live rows a read-only key would be overwritten and a pinned one unpinned, + so a failed read refuses the batch with a retryable error before any write.""" + from server.core.errors import BackendUnavailableError + + async def _down(*_: Any, **__: Any) -> Any: + raise RuntimeError("Code: 241. DB::Exception: memory limit") + + ch = _StubCH(keeper=None) + events = harness(ch) + monkeypatch.setattr("server.memory.store.memory_rows_by_identity_keys", _down) + with pytest.raises(BackendUnavailableError, match="nothing was written") as raised: + await mem_extract.handle_memory_bulk_set(_input()) + assert raised.value.status_code == 503 and raised.value.headers() == {"Retry-After": "1"} + assert ch.insert_calls == [] and events == [] + + @pytest.mark.asyncio async def test_session_scope_restores_the_old_gate( harness, monkeypatch: pytest.MonkeyPatch @@ -597,6 +617,6 @@ async def _heads(keys: Any, **kw: Any) -> dict[Any, MemoryRow]: inp.entries.append(_BulkSetEntry(memory_key="gone", memory_type="semantic", value="back")) state = bulk_rows._BulkWriteState() await bulk_set._bulk_existing_lookup(object(), inp, state) - assert asked["include_tombstoned"] is True and state.existing_lookup_ok + assert asked["include_tombstoned"] is True assert set(state.existing_rows) == {"live"} == set(state.existing_ids) assert set(state.deleted_heads) == {"gone"} diff --git a/tests/unit/test_bulk_rows_carry_labels.py b/tests/unit/test_bulk_rows_carry_labels.py index d4501429469..ccff6609383 100644 --- a/tests/unit/test_bulk_rows_carry_labels.py +++ b/tests/unit/test_bulk_rows_carry_labels.py @@ -399,7 +399,7 @@ def test_a_row_landing_without_its_vector_retires_the_keys_old_one(vectorless: b from server.memory.app.bulk_rows import _BulkWriteState from server.memory.app.bulk_set import _vectors_to_retire - state = _BulkWriteState(now_utc=NOW, existing_lookup_ok=True) + state = _BulkWriteState(now_utc=NOW) state.existing_rows["k"] = NS(memory_type="semantic", sensitivity="") state.memory_rows = [ { diff --git a/tests/unit/test_code_blame_range.py b/tests/unit/test_code_blame_range.py index df6c233ad0d..a4d2b1a53bf 100644 --- a/tests/unit/test_code_blame_range.py +++ b/tests/unit/test_code_blame_range.py @@ -17,6 +17,7 @@ from server.code.api.models_history import CodeBlameRangeInput from server.code.app.index.gitrepo import GitError from server.code.domain.index import blame_range as br +from server.observability import degradations from server.operations.base import Role from server.operations.registry import OPERATIONS_BY_NAME from server.tracker.domain.errors import TrackerUnavailable @@ -672,22 +673,42 @@ async def test_unresolved_window_and_ledger_failure_are_named(wired) -> None: assert not [c for c in git.calls if c[0] == "blame"] repo.fail_ledger = True - out = await h.handle_code_blame_range( - CodeBlameRangeInput( - stage="last_touched", - org=ORG, - namespace=NS, - path=PATH, - start_line=10, - end_line=12, - to_version="26.3", + with degradations.unit(): + out = await h.handle_code_blame_range( + CodeBlameRangeInput( + stage="last_touched", + org=ORG, + namespace=NS, + path=PATH, + start_line=10, + end_line=12, + to_version="26.3", + ) ) - ) + assert degradations.current() == ["code_index: merge_ledger_unread (RuntimeError)"] assert out.verdict == "candidates" and out.causes == ["ledger_failed"] assert out.legs["ledger"]["status"] == "failed" and out.epistemic == "exact" assert [c["evidence"] for c in out.candidates] == ["blame", "blame"] +@pytest.mark.asyncio +async def test_a_failed_function_or_comment_read_leaves_its_half_empty_and_named() -> None: + class _Down(_Repo): + async def functions_for_paths(self, org, ns, paths, *, limit=400, **_kw): + raise TimeoutError + + async def review_comments_for(self, org, ns, paths, *, limit=30, humans_only=True): + raise RuntimeError("ch down") + + with degradations.unit(): + got = await h._symbol_and_comments(_Down(), ORG, NS, PATH, 10, 12) # type: ignore[arg-type] + assert degradations.current() == [ + "code_index: enclosing_function_unread (TimeoutError)", + "code_index: review_comments_unread (RuntimeError)", + ] + assert got == ({}, []) + + @pytest.mark.asyncio async def test_a_window_end_outside_the_indexed_head_does_not_resolve(wired, monkeypatch) -> None: """The mirror holds LATER, a commit of the branch past the one the namespace indexes. diff --git a/tests/unit/test_code_review_brief_mirror.py b/tests/unit/test_code_review_brief_mirror.py index 955f4c780ce..37a3b180b70 100644 --- a/tests/unit/test_code_review_brief_mirror.py +++ b/tests/unit/test_code_review_brief_mirror.py @@ -248,10 +248,22 @@ async def review_brief( return self.stored async def pr_merge_facts( - self, org: str, ns: str, *, pr_number: int = 0, merge_sha: str = "" + self, + org: str, + ns: str, + *, + pr_number: int = 0, + merge_sha: str = "", + within_head: bool = True, ) -> dict[str, Any] | None: return None # the PR predates the backfill horizon + # The build's reads answer: a failed one notes and leaves the brief unstored. + async def functions_for_paths( + self, org: str, ns: str, paths: list[str], *, limit: int = 400 + ) -> list[dict[str, Any]]: + return [] + async def insert_rows(self, table: str, rows: list[dict[str, Any]]) -> None: self.inserted.append((table, rows)) diff --git a/tests/unit/test_code_setting_facts.py b/tests/unit/test_code_setting_facts.py index d4690a533da..8bec2fb0ab7 100644 --- a/tests/unit/test_code_setting_facts.py +++ b/tests/unit/test_code_setting_facts.py @@ -13,6 +13,7 @@ from server.code.api.models_conventions import CodeSettingFactsInput from server.code.app.ttl_cache import clear_all from server.code.domain.index import setting_facts as sf +from server.observability import degradations from server.operations.base import Role from server.operations.registry import OPERATIONS_BY_NAME @@ -244,13 +245,34 @@ async def test_unknown_name_is_not_a_setting_only_with_the_control_green(wired) @pytest.mark.asyncio async def test_one_failing_read_is_named_not_fatal(wired) -> None: wired(_Repo(history_fails=True)) - out = await h.handle_code_setting_facts( - CodeSettingFactsInput(org=ORG, namespace=NS, name="use_skip_indexes_if_final") - ) + with degradations.unit(): + out = await h.handle_code_setting_facts( + CodeSettingFactsInput(org=ORG, namespace=NS, name="use_skip_indexes_if_final") + ) + assert degradations.current() == ["code_index: setting_history_unread (RuntimeError)"] assert out.verdict == "known" and out.causes == ["history_unread"] and out.history == [] assert out.randomized_in_ci["randomized"] +class _DeclarationFails(_Repo): + async def grep_chunks(self, org, ns, pattern, **kw): + if "zz_definitely_missing" in pattern: + raise RuntimeError("boom") + return await super().grep_chunks(org, ns, pattern, **kw) + + +@pytest.mark.asyncio +async def test_a_failed_declaration_read_is_not_a_negative(wired) -> None: + """The control is green, but an unread declaration proves nothing: unknown, named.""" + wired(_DeclarationFails()) + with degradations.unit(): + out = await h.handle_code_setting_facts( + CodeSettingFactsInput(org=ORG, namespace=NS, name="zz_definitely_missing") + ) + assert degradations.current() == ["code_index: setting_declaration_unread (RuntimeError)"] + assert out.verdict == "unknown" and out.causes == ["declaration_unread"] and out.control["ok"] + + def test_plain_string_descriptions_and_alias_declarations_are_found() -> None: """Shapes from the 248 CI-randomized settings: three declared with a plain C string instead of R"(...)", one reachable only as the alias of a diff --git a/tests/unit/test_code_symbol_history.py b/tests/unit/test_code_symbol_history.py index c7c4fd057e5..35cfd2d93c2 100644 --- a/tests/unit/test_code_symbol_history.py +++ b/tests/unit/test_code_symbol_history.py @@ -360,3 +360,32 @@ async def test_two_rows_of_one_definition_are_not_ambiguous(wired) -> None: CodeSymbolHistoryInput(org=ORG, namespace=NS, name="loadDataParts") ) assert out.ambiguous is False + + +@pytest.mark.asyncio +async def test_a_tracker_side_or_issue_read_that_raised_is_named( + wired, monkeypatch: pytest.MonkeyPatch +) -> None: + """A side that raised names no namespace, and is unavailable all the same.""" + from server.observability import degradations + + class _Broken(_Source): + async def prs_facts(self, org, ns, numbers, *, names=None): + raise RuntimeError("boom") + + async def _no_items(self, org, ns, numbers): + raise TimeoutError + + wired["src"] = _Broken() + monkeypatch.setattr(_Repo, "items_by_number", _no_items) + with degradations.unit(): + out = await h.handle_code_symbol_history( + CodeSymbolHistoryInput(org=ORG, namespace=NS, name="x") + ) + notes = degradations.current() + assert out.tracker_unavailable and out.causes == ["tracker_unavailable"] + assert out.tracker_namespace == "" and out.prs[0]["linked_issues"] == [{"number": 100}] + assert notes == [ + "code_index: issue_facts_unread (TimeoutError)", + "tracker: symbol_facts_unread (RuntimeError)", + ] diff --git a/tests/unit/test_coverage_published.py b/tests/unit/test_coverage_published.py index b6c3d8955e1..4272da4777d 100644 --- a/tests/unit/test_coverage_published.py +++ b/tests/unit/test_coverage_published.py @@ -122,41 +122,66 @@ def test_parse_shared_coverage_tolerates_garbage() -> None: assert ( cr.parse_shared_coverage({"value": json.dumps({"cov": []}), "detail": "fp"}, "fp") is None ) - cov, gaps = cr.parse_shared_coverage( - {"value": json.dumps({"cov": _COV, "gaps": None}), "detail": "fp"}, "fp" - ) or (None, None) - assert cov == _COV and gaps is None + # a row without its gap counts is no answer: the reader computes them + assert ( + cr.parse_shared_coverage( + {"value": json.dumps({"cov": _COV, "gaps": None}), "detail": "fp"}, "fp" + ) + is None + ) @pytest.mark.asyncio -async def test_a_failed_gap_read_is_named_on_every_page_whichever_path_served_it() -> None: - """The publisher keeps a failed gap read as `gaps: null` beside the coverage. A page - computed here, one read from the shared row and one from the process memo each - render without the gaps row, and each names it.""" +async def test_a_failed_gap_read_publishes_nothing_and_is_computed_again( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A failed gap read is not published, so no process serves it until the counts + move. This process keeps it `PROBE_ERROR_TTL_S`, naming it on each page, then computes + again and publishes once the gaps read.""" + from server.code.app.symbol.dispatch import PROBE_ERROR_TTL_S from server.observability import degradations + from tests.unit.clock_fake import ManualClock + + clock = ManualClock(t=1000.0) + monkeypatch.setattr(index_status.time, "monotonic", clock.monotonic) class _NoGaps(_Repo): + down = True + async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: - raise TimeoutError + if self.down: + raise TimeoutError + return dict(_GAPS) repo = _NoGaps() state = _state(("h1", "s1", "p1")) noted = [] - for _ in range(2): # computed and published, then from the memo + for _ in range(2): # computed, then from the memo degradations.begin() _, gaps = await index_status._coverage_cached(repo, "o", "n", state) assert gaps is None noted.append(degradations.current()) - ((_, value, detail),) = repo.published - assert json.loads(value)["gaps"] is None - index_status.reset_repo_status_cache() - degradations.begin() # another process: the shared row answers - _, gaps = await index_status._coverage_cached( - repo, "o", "n", dict(state, coverage={"value": value, "detail": detail}) - ) - assert gaps is None and repo.computed == 1 - noted.append(degradations.current()) - assert noted == [["code_index: coverage_gaps_unread"]] * 3 + assert noted == [["code_index: coverage_gaps_unread"]] * 2 + assert repo.computed == 1 and repo.published == [] + repo.down = False + clock.advance(PROBE_ERROR_TTL_S) + degradations.begin() + _, gaps = await index_status._coverage_cached(repo, "o", "n", state) + assert gaps == _GAPS and repo.computed == 2 and degradations.current() == [] + ((_, value, _),) = repo.published + assert json.loads(value)["gaps"] == _GAPS + + +@pytest.mark.asyncio +async def test_a_must_land_refresh_raises_on_a_failed_gap_read() -> None: + class _NoGaps(_Repo): + async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: + raise TimeoutError + + repo = _NoGaps() + with pytest.raises(TimeoutError): + await repo.refresh_coverage("o", "n", fingerprint="fp", must_land=True) + assert repo.published == [] @pytest.mark.asyncio diff --git a/tests/unit/test_definition_write_rules.py b/tests/unit/test_definition_write_rules.py index 9373dd4a342..917d4cc06cd 100644 --- a/tests/unit/test_definition_write_rules.py +++ b/tests/unit/test_definition_write_rules.py @@ -184,7 +184,7 @@ def test_a_bulk_definition_never_folds_into_another_row_of_its_bytes() -> None: from server.memory.app.bulk_rows import _bulk_skip_gate, _BulkWriteState def folded(memory_type: str) -> dict[str, str]: - state = _BulkWriteState(existing_lookup_ok=True) + state = _BulkWriteState() entry = SimpleNamespace(memory_key="definition/arr", memory_type=memory_type) dupes = {"sha": ("arr_note", "mid-1")} # the same bytes under another key _bulk_skip_gate(entry, "sha", state, dupes) @@ -220,7 +220,7 @@ async def test_a_bulk_definition_has_no_reach_for_the_gap_check() -> None: from server.memory.app import bulk_set from server.memory.app.bulk_rows import _BulkWriteState - state = _BulkWriteState(existing_lookup_ok=True) + state = _BulkWriteState() state.floors = {"semantic": (0.8, 0.2)} row = {"org": "o", "namespace": "n", "embedding": [0.6, 0.8]} state.embedding_rows = [ @@ -251,7 +251,7 @@ async def verdicts(*a: Any, **kw: Any) -> dict[int, Any]: monkeypatch.setattr(bulk_set, "_apply_verdicts", lambda *a: None) async def run(memory_type: str) -> None: - state = _BulkWriteState(existing_lookup_ok=True) + state = _BulkWriteState() state.memory_rows = [{"memory_type": memory_type, "memory_key": "k", "memory_id": "m"}] state.pending = [(0, "text", "excerpt", "key text")] clock = SimpleNamespace(mark=lambda _stage: None) diff --git a/tests/unit/test_degraded_unnoted.py b/tests/unit/test_degraded_unnoted.py index 1f59ed5bf7f..14e568a1b1e 100644 --- a/tests/unit/test_degraded_unnoted.py +++ b/tests/unit/test_degraded_unnoted.py @@ -10,8 +10,11 @@ from server.core.paths import REPO_ROOT _DIRS = ("server/code/app", "server/memory/app") -# The index plane's own passes, like the workers and stores outside these dirs. +# The index plane's ingest passes, which serve no response, like the workers and stores +# outside these dirs. _EXCLUDED = ("server/code/app/index/",) +# The index-plane modules a request runs: a review brief built on a miss. +_INCLUDED = {"server/code/app/index/review_brief_build.py"} _ALLOWLIST = Path(__file__).with_name("degraded_unnoted.txt") _CATEGORIES = { # a cache, memo or precomputed read that falls back to the live read @@ -24,84 +27,181 @@ "telemetry", # a settings lookup that falls back to its default "settings", - # a cut by a budget the caller or the op sets - "budget", - # a cut by the call's own deadline - "own_deadline", # no response path: a background pass, startup or cleanup in an app module "logged_only_nonanswer", - # the caller names the fallback from what the handler returns (the line says where) + # the caller names the fallback from what the handler returns (the comment says where) "noted_by_caller", } _NOTES = {"partial", "note", "restore"} +_EXCEPTION_TYPES = {"Exception", "BaseException"} def _broad(h: ast.ExceptHandler) -> bool: if h.type is None: return True names = h.type.elts if isinstance(h.type, ast.Tuple) else [h.type] - return any(isinstance(n, ast.Name) and n.id in {"Exception", "BaseException"} for n in names) + return any(isinstance(n, ast.Name) and n.id in _EXCEPTION_TYPES for n in names) def _is_degradations(node: ast.expr) -> bool: return isinstance(node, ast.Name) and node.id.lstrip("_") == "degradations" -def _notes(h: ast.ExceptHandler) -> bool: - """The handler always raises (a `raise` among its own statements, not under an `if`), - names its fallback (`degradations.partial` / `note` / `restore`), or keeps the failure's - text for the answer (`caller_text(e)`: a kept failure noted on each answer served from - it, or a failure field of the response).""" - if any(isinstance(s, ast.Raise) for s in h.body): - return True - for n in ast.walk(ast.Module(body=h.body, type_ignores=[])): +def _calls_note(nodes: list[ast.AST], helpers: set[str], failure: str | None) -> bool: + """A call among `nodes` names the fallback: `degradations.partial` / `note` / `restore`, + a function of the same module that calls one (`helpers`), or `caller_text` of the + failure (`failure`; None for any), which keeps its text for the answer: a kept + failure noted on each answer served from it, or a failure field of the response.""" + for n in nodes: if not isinstance(n, ast.Call): continue - if isinstance(n.func, ast.Attribute): - if n.func.attr in _NOTES and _is_degradations(n.func.value): - return True - if isinstance(n.func, ast.Name) and n.func.id == "caller_text" and h.name: - if any(isinstance(a, ast.Name) and a.id == h.name for a in n.args): + f = n.func + if isinstance(f, ast.Attribute) and f.attr in _NOTES and _is_degradations(f.value): + return True + if isinstance(f, ast.Name) and f.id in helpers: + return True + if isinstance(f, ast.Name) and f.id == "caller_text": + if failure is None or any(isinstance(a, ast.Name) and a.id == failure for a in n.args): return True return False +def _statements(body: list[ast.stmt]) -> list[ast.AST]: + return list(ast.walk(ast.Module(body=body, type_ignores=[]))) + + +def _notes(h: ast.ExceptHandler, helpers: set[str]) -> bool: + """The handler always raises (a `raise` among its own statements, not under an `if`) + or names its fallback (`_calls_note`, with `caller_text` of the caught error).""" + if any(isinstance(s, ast.Raise) for s in h.body): + return True + return _calls_note(_statements(h.body), helpers, h.name or "") + + +def _branch_notes(branch: list[ast.stmt] | ast.expr, helpers: set[str]) -> bool: + """A fallback branch raises (a statement of its own) or names its fallback.""" + if isinstance(branch, list): + if any(isinstance(s, ast.Raise) for s in branch): + return True + return _calls_note(_statements(branch), helpers, None) + return _calls_note(list(ast.walk(branch)), helpers, None) + + +def _noting_helpers(tree: ast.Module) -> set[str]: + """The module's own functions whose body calls `degradations` itself.""" + return { + fn.name + for fn in tree.body + if isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) + and _calls_note(_own_nodes(fn), set(), "") + } + + +def _tests_exception(node: ast.expr) -> bool: + """`isinstance(x, Exception | BaseException)` somewhere in `node`.""" + for n in ast.walk(node): + if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == "isinstance": + if len(n.args) == 2: + kinds = n.args[1].elts if isinstance(n.args[1], ast.Tuple) else [n.args[1]] + if any(isinstance(k, ast.Name) and k.id in _EXCEPTION_TYPES for k in kinds): + return True + return False + + +def _own_nodes(fn: ast.AST) -> list[ast.AST]: + """The nodes of `fn`'s own body, without those of the functions defined in it.""" + out: list[ast.AST] = [] + todo = list(ast.iter_child_nodes(fn)) + while todo: + n = todo.pop() + out.append(n) + if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + todo.extend(ast.iter_child_nodes(n)) + return out + + +def _gather_fallbacks(fn: ast.AST, helpers: set[str]) -> list[bool]: + """In a function that gathers with `return_exceptions=True`, each branch that tests a + result for an exception, in source order: whether the branch taken for an exception + raises or names its fallback. A conditional expression's branch can only name it by a + call in that expression; a comprehension filter that drops exceptions + (`if not isinstance(...)`) never does.""" + own = _own_nodes(fn) + if not any( + isinstance(n, ast.keyword) + and n.arg == "return_exceptions" + and isinstance(n.value, ast.Constant) + and n.value.value is True + for n in own + ): + return [] + sites: list[tuple[int, int, bool]] = [] + for n in own: + if isinstance(n, (ast.If, ast.IfExp)) and _tests_exception(n.test): + negated = isinstance(n.test, ast.UnaryOp) and isinstance(n.test.op, ast.Not) + branch = n.orelse if negated else n.body + sites.append((n.lineno, n.col_offset, _branch_notes(branch, helpers))) + elif isinstance(n, ast.comprehension) and any( + isinstance(i, ast.UnaryOp) and isinstance(i.op, ast.Not) and _tests_exception(i) + for i in n.ifs + ): + sites.append((n.target.lineno, n.target.col_offset, False)) + return [noted for _, _, noted in sorted(sites)] + + def _unnoted() -> list[str]: - """`path::enclosing.qualname::ordinal` of each broad handler that notes nothing; the - ordinal counts the broad handlers of that function in source order.""" + """`path::enclosing.qualname::ordinal` of each broad handler that notes nothing, the + ordinal counting the broad handlers of that function in source order; and + `path::enclosing.qualname::gather::ordinal` of each exception branch over a + `return_exceptions=True` result that notes nothing, counted the same way.""" out: list[str] = [] for d in _DIRS: for path in sorted((REPO_ROOT / d).rglob("*.py")): rel = str(path.relative_to(REPO_ROOT)) - if rel.startswith(_EXCLUDED): + if rel.startswith(_EXCLUDED) and rel not in _INCLUDED: continue counts: dict[str, int] = {} + tree = ast.parse(path.read_text()) + helpers = _noting_helpers(tree) - def visit(node: ast.AST, qual: str, rel: str = rel, counts: dict = counts) -> None: + def visit( + node: ast.AST, + qual: str, + rel: str = rel, + counts: dict = counts, + helpers: set[str] = helpers, + ) -> None: for child in ast.iter_child_nodes(node): if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): - visit(child, f"{qual}.{child.name}" if qual else child.name) + q = f"{qual}.{child.name}" if qual else child.name + for i, noted in enumerate(_gather_fallbacks(child, helpers), 1): + if not noted: + out.append(f"{rel}::{q}::gather::{i}") + visit(child, q) continue if isinstance(child, ast.ExceptHandler) and _broad(child): q = qual or "" counts[q] = counts.get(q, 0) + 1 - if not _notes(child): + if not _notes(child, helpers): out.append(f"{rel}::{q}::{counts[q]}") visit(child, qual) - visit(ast.parse(path.read_text()), "") + visit(tree, "") return out def _allowlist() -> dict[str, str]: entries: dict[str, str] = {} for raw in _ALLOWLIST.read_text().splitlines(): - line = raw.split("#", 1)[0].strip() + line, _, why = raw.partition("#") + line = line.strip() if not line: continue key, category = line.split() assert key not in entries, f"listed twice: {key}" assert category in _CATEGORIES, f"{key}: unknown category {category!r}" + if category == "noted_by_caller": + assert why.strip(), f"{key}: a noted_by_caller entry says where the caller notes" entries[key] = category return entries diff --git a/tests/unit/test_loom_search_tracker_general.py b/tests/unit/test_loom_search_tracker_general.py index 46f21e05e2f..7ffdb22d4d4 100644 --- a/tests/unit/test_loom_search_tracker_general.py +++ b/tests/unit/test_loom_search_tracker_general.py @@ -82,6 +82,24 @@ async def test_empty_tracker_results_add_no_section(trackers: AsyncMock) -> None assert await _run("retention decision", org="o") is None +async def test_a_tracker_whose_search_raised_is_dropped_and_named(trackers: AsyncMock) -> None: + from server.observability import degradations + + served = trackers.side_effect + + async def search(input: Any) -> TrackerSimilarOutput: + if input.namespace == "tracker-one": + raise TimeoutError + return await served(input) + + trackers.side_effect = search + with degradations.unit(): + result = await _run("what did we decide about retention?", org="o", top_k=2) + assert degradations.current() == ["loom_search: tracker_dropped (TimeoutError)"] + assert result is not None and result["namespaces"] == ["tracker-two"] + assert [r["namespace"] for r in result["results"]] == ["tracker-two"] + + async def test_timeout_covers_namespace_discovery( trackers: AsyncMock, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/unit/test_memory_append_batch.py b/tests/unit/test_memory_append_batch.py index b489b7368c8..cf30ad4693b 100644 --- a/tests/unit/test_memory_append_batch.py +++ b/tests/unit/test_memory_append_batch.py @@ -12,7 +12,7 @@ import pytest from server.core import idempotency, pg_lease -from server.core.errors import NotFoundError, ValidationError +from server.core.errors import BackendUnavailableError, NotFoundError, ValidationError from server.memory import store as memory_repo from server.memory.api.models_bulk import MemoryAppendBatchInput from server.memory.app import blacklist_guard, bulk_rows, bulk_set @@ -249,7 +249,7 @@ async def test_existing_live_or_deleted_head_refuses_the_entire_append( async def test_unverifiable_freshness_never_becomes_a_first_write(authority: _Authority) -> None: authority.lookup_error = RuntimeError("head read unavailable") - with pytest.raises(ValidationError, match="verify fresh keys"): + with pytest.raises(BackendUnavailableError, match="could not read its keys' live rows"): await bulk_set.handle_memory_append_batch(_input(("first", "hello"))) assert authority.commit_attempts == 0 diff --git a/tests/unit/test_memory_bulk_parity.py b/tests/unit/test_memory_bulk_parity.py index 659b2c8d209..88970f8e7a3 100644 --- a/tests/unit/test_memory_bulk_parity.py +++ b/tests/unit/test_memory_bulk_parity.py @@ -258,12 +258,12 @@ async def test_bulk_set_revision_carries_the_live_rows_usage_and_resets_its_verd assert (first["recall_count"], first["evidence_count"], first["verified_by"]) == (0, 1, "") -def _vec_state(entries: list[tuple[str, int]], *, lookup_ok: bool = True) -> Any: +def _vec_state(entries: list[tuple[str, int]]) -> Any: """A bulk write state of (sensitivity, version) rows on key `k`, each with an embedding row unless it is high (as the row builder does).""" from server.memory.app.bulk_rows import _BulkWriteState - state = _BulkWriteState(existing_lookup_ok=lookup_ok) + state = _BulkWriteState() ident = {"org": "o", "namespace": "n", "agent": "a", "user_id": "u", "session_id": "s"} for sensitivity, version in entries: row = {**ident, "memory_key": "k", "memory_type": "semantic"} @@ -275,16 +275,15 @@ def _vec_state(entries: list[tuple[str, int]], *, lookup_ok: bool = True) -> Any @pytest.mark.asyncio @pytest.mark.parametrize( - ("entries", "lookup_ok", "retired"), + ("entries", "retired"), [ - ([("", 1), ("high", 2)], True, True), # the high row wins: no vector at all - ([("high", 1), ("", 2)], True, False), # the plain row wins: its vector lands - ([("high", 1)], True, False), # a new key, never embedded: nothing to read - ([("high", 1)], False, True), # the lookup failed: retire by identity anyway + ([("", 1), ("high", 2)], True), # the high row wins: no vector at all + ([("high", 1), ("", 2)], False), # the plain row wins: its vector lands + ([("high", 1)], False), # a new key, never embedded: nothing to read ], ) async def test_bulk_insert_decides_a_keys_vectors_by_the_row_that_wins( - monkeypatch: pytest.MonkeyPatch, entries: Any, lookup_ok: bool, retired: bool + monkeypatch: pytest.MonkeyPatch, entries: Any, retired: bool ) -> None: import server.memory.store as memory_repo @@ -322,7 +321,7 @@ async def _no_chunks(**_k: Any) -> int: from server.memory.app import high_fence monkeypatch.setattr(high_fence, "tombstone_set_chunks", _no_chunks) - await _bulk_set_mod._bulk_insert(object(), _vec_state(entries, lookup_ok=lookup_ok)) + await _bulk_set_mod._bulk_insert(object(), _vec_state(entries)) # a key whose winning row is high is fenced at that row's version, vector or not winner = max(entries, key=lambda e: e[1]) if winner[0] == "high": diff --git a/tests/unit/test_memory_for_file.py b/tests/unit/test_memory_for_file.py index 51dcc23ed5d..df5ca550c7d 100644 --- a/tests/unit/test_memory_for_file.py +++ b/tests/unit/test_memory_for_file.py @@ -1734,3 +1734,35 @@ async def readable(org: str, nss: set[str]) -> set[str]: ) rows, _ = await mff.listing_rows(request) assert "fixed earlier in DB.Reader.loadRows (lines 12-40);" in mff.listing_line(rows[0]) + + +@pytest.mark.asyncio +async def test_a_failed_extra_namespace_read_is_dropped_and_named( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.observability import degradations + + async def extras(_input: Any) -> list[str]: + return ["code-x"] + + async def linked(*_: Any) -> dict[str, Any]: + return {} + + async def rows_for( + _input: Any, ns: str, _path: str, _tags: Any, link: Any, **__: Any + ) -> list[dict[str, Any]]: + await link + if ns == "code-x": + raise TimeoutError + return [_row("style", json.dumps("Two spaces."), namespace=ns)] + + monkeypatch.setattr(mff, "_readable_extras", extras) + monkeypatch.setattr(mff, "_linked", linked) + monkeypatch.setattr(mff, "_rows_for", rows_for) + request = MemoryForFileInput(org="o", namespace="ns", path="src/a.cpp") + with degradations.unit(): + rows, skipped = await mff._merged_rows(request, "src/a.cpp") + assert degradations.current() == [ + "memory.for_file: other_namespaces_dropped (TimeoutError)" + ] + assert [r["memory_key"] for r in rows] == ["style"] and not skipped diff --git a/tests/unit/test_pending_evidence.py b/tests/unit/test_pending_evidence.py index c2cbd89ca96..9d1f614e5f7 100644 --- a/tests/unit/test_pending_evidence.py +++ b/tests/unit/test_pending_evidence.py @@ -9,6 +9,7 @@ import pytest from server.memory.app import pending_evidence as P +from server.observability import degradations def _batch( @@ -52,8 +53,10 @@ def test_rank_picks_the_turns_that_share_words_with_the_question() -> None: t.score >= 1 for t in P.rank_pending_turns("cache", batches) ) assert P.rank_pending_turns("", batches) == [] - # malformed payloads are skipped, not raised - assert P.rank_pending_turns("cache cap", [{"queue_id": "x", "payload": "{not json"}]) == [] + # a malformed payload is skipped, not raised, and named + with degradations.unit(): + assert P.rank_pending_turns("cache cap", [{"queue_id": "x", "payload": "{not json"}]) == [] + assert degradations.current() == ["memory.ask: pending_batch_dropped (JSONDecodeError)"] def test_hits_carry_key_source_session_and_label() -> None: diff --git a/tests/unit/test_review_brief_store_needs_diff.py b/tests/unit/test_review_brief_store_needs_diff.py index 5096c6de7a8..1fe12c550c2 100644 --- a/tests/unit/test_review_brief_store_needs_diff.py +++ b/tests/unit/test_review_brief_store_needs_diff.py @@ -209,3 +209,41 @@ async def pass_() -> list[str]: assert asyncio.run(pass_()) == ["rerank: input_order_kept (x)"] assert [rows[0]["pr_number"] for _, rows in repo.inserted] == [9] + + +def test_a_brief_whose_head_read_failed_names_it_and_is_served_unstored( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Merged and open: stored with a blank `indexed_commit`, it would be served later + without the head it was built at.""" + + class _NoHead(_Repo): + async def get_state(self, org: str, ns: str, key: str) -> str: + raise TimeoutError + + repo = _NoHead() + _noting_build(monkeypatch, noting=set()) + common: dict[str, Any] = {"git_dir": "/x", "title": "t", "changed_paths": ["a.cpp"]} + + async def both() -> tuple[list[dict[str, Any]], list[str]]: + degradations.begin() + merged = await rbb.build_for_merge( + repo, "acme", "code-widgets", pr_number=7, merge_sha="m" * 40, call=_none, **common + ) + opened = await rbb.build_for_open( + repo, + "acme", + "code-widgets", + pr_number=8, + head_sha="h" * 40, + base_sha="b" * 40, + call=_none, + diff="diff --git a/x b/x\n", + **common, + ) + return [merged, opened], degradations.current() + + (merged, opened), notes = asyncio.run(both()) + assert repo.inserted == [] + assert merged["stored"] is False and opened["stored"] is False + assert notes == ["code_index: head_unread (TimeoutError)"] # one note per kind From d5810ae3ec05e3f57c58b3130f7d68a8a7028f2a Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 16:33:17 +0530 Subject: [PATCH 21/47] A published coverage row answers over a kept failed gap read A process that kept a failed gap read served coverage_gaps_unread for PROBE_ERROR_TTL_S even when another process had since published a whole row for the same counts. The kept failure now answers only while no such row is in hand, as the table summaries already do. Part of: https://github.com/ClickHouse/loom/issues/2040 Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/index_status.py | 21 ++++++++++++--------- tests/unit/test_coverage_published.py | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index 9da927f3cdb..ddc26ff5239 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -983,9 +983,10 @@ async def _coverage_cached( fingerprint of `state` matches and the entry is younger than the counts max age (60 s while an index builds, 10 min steady). The gap counts are None when their queries failed — the page renders without the gaps row, nothing is published, and the entry is kept only - `PROBE_ERROR_TTL_S`, so the next read after it computes again.""" + `PROBE_ERROR_TTL_S`, so the next read after it computes again; a row another process + published in that time answers at once.""" from server.code.app.symbol.dispatch import PROBE_ERROR_TTL_S - from server.code.store.index import counts_fingerprint + from server.code.store.index import counts_fingerprint, parse_shared_coverage key = (org, ns) fp = counts_fingerprint(state) @@ -994,17 +995,19 @@ async def _coverage_cached( max_age_s = _counts_max_age_s(state) if hit is not None and hit[3] is None: max_age_s = min(max_age_s, PROBE_ERROR_TTL_S) - if hit is not None and hit[0] == fp and now - hit[1] < max_age_s: - if hit[3] is None: # each page served from a failed gap read names it - degradations.partial("code_index", "coverage_gaps_unread", hit[4]) + fresh = hit is not None and hit[0] == fp and now - hit[1] < max_age_s + if hit is not None and fresh and hit[3] is not None: return hit[2], hit[3] # The pass that moved the rows published their # coverage beside its counts; a row whose fingerprint is ours is the # answer — a point read instead of 1.2 GB of FINAL aggregates. No row (a # namespace nobody computed yet): compute once and publish it ourselves. - from server.code.store.index import parse_shared_coverage - published = parse_shared_coverage(state.get("coverage"), fp) + if hit is not None and fresh and published is None: + # a kept failed gap read answers until a row does, and each page served from it + # names it + degradations.partial("code_index", "coverage_gaps_unread", hit[4]) + return hit[2], hit[3] refresh = getattr(repo, "refresh_coverage", None) failure = "" if published is not None: @@ -1021,8 +1024,8 @@ async def _coverage_cached( logger.warning("code.coverage: gap queries failed for %s/%s: %s", org, ns, e) gap_counts, failure = None, caller_text(e) if gap_counts is None: - # The gap queries failed here, or in the publisher (which keeps no kind): the page - # renders without its gaps row. + # The gap queries failed here, or in `refresh_coverage` (which answers no kind): the + # page renders without its gaps row. degradations.partial("code_index", "coverage_gaps_unread", failure) if len(_coverage_cache) > 256: _coverage_cache.clear() diff --git a/tests/unit/test_coverage_published.py b/tests/unit/test_coverage_published.py index 4272da4777d..cf37d462005 100644 --- a/tests/unit/test_coverage_published.py +++ b/tests/unit/test_coverage_published.py @@ -172,6 +172,27 @@ async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: assert json.loads(value)["gaps"] == _GAPS +@pytest.mark.asyncio +async def test_a_row_another_process_published_answers_over_a_kept_failure() -> None: + from server.observability import degradations + + class _NoGaps(_Repo): + async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: + raise TimeoutError + + repo = _NoGaps() + state = _state(("h1", "s1", "p1")) + _, gaps = await index_status._coverage_cached(repo, "o", "n", state) + assert gaps is None and repo.computed == 1 + row = { + "value": json.dumps({"cov": _COV, "gaps": _GAPS}), + "detail": cr.counts_fingerprint(state), + } + degradations.begin() + _, gaps = await index_status._coverage_cached(repo, "o", "n", dict(state, coverage=row)) + assert gaps == _GAPS and repo.computed == 1 and degradations.current() == [] + + @pytest.mark.asyncio async def test_a_must_land_refresh_raises_on_a_failed_gap_read() -> None: class _NoGaps(_Repo): From 9b6e964a8d0dd8937fe5e08403d3d33ab8aeaf77 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 18:40:15 +0530 Subject: [PATCH 22/47] The index modules a request runs note their fallbacks, and the scan reads them The degraded scan now reads the server/code/app/index/ modules the code and memory apps import, taken from their imports, except the ingest pass, whose notes reach no answer. Of their 63 sites, 31 are listed by category; the rest note: - PR review comments (code.history, code.blame_range), the PR overlay's head placement and name table, a commit's ancestry, commit count and changed paths, a fork lookup on each answer served from its kept failure, the task pack's sections, a failed registry read that keeps the last snapshot, and a history read whose clone failed (git_mirror: clone_failed). - The overlay is cached only when the parse that built it noted nothing; its overlay_note counts the files whose parse or call extraction failed. - A mirror-built review brief whose tracker read failed notes reviewers_unread and is served unstored, since every later read would serve tracker: failed with no note. - The brief's risk section reports a failed fit read (risk_failed). refresh_coverage answers its gap failure, so coverage_gaps_unread keeps the kind; the fakes use the real method and _coverage_cached has no branch for a repository without it. The tracker leg notes a plan whose deadline passed before it starts, pending evidence notes a batch whose messages is not a list, and code.setting_facts lists each gathered read with its default in one place. The bulk lookup's docstring names the codes it refuses with. Tests: one case per review-brief build note, each asserting its note and stored: false; the mirror-built brief; append_batch passing PostgresUnavailableError through; a failed clone and registry read; the fusion window, linked-tracker scan and TrackerUnavailable notes. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- deploy/hyperdx_dashboards.md | 2 +- docs/reference/http-api.md | 6 +- server/code/app/index/commit_coverage.py | 11 +- server/code/app/index/fork_upstream.py | 29 ++-- server/code/app/index/mirrors.py | 2 + server/code/app/index/pr_overlay.py | 75 +++++++---- server/code/app/index/pr_reviews.py | 2 + server/code/app/index/repo_registry.py | 6 +- server/code/app/index/review_brief_build.py | 7 +- server/code/app/index/review_brief_sources.py | 4 +- server/code/app/index/risk_fit.py | 10 +- server/code/app/index/task_pack.py | 4 +- server/code/app/index_status.py | 21 +-- server/code/app/settings.py | 30 ++--- server/code/store/index/status.py | 15 ++- server/memory/app/bulk_set.py | 8 +- server/memory/app/loom_search/tracker_leg.py | 6 +- server/memory/app/pending_evidence.py | 3 +- tests/unit/degraded_unnoted.txt | 29 ++++ tests/unit/test_bisect_fusion.py | 15 +++ tests/unit/test_code_blame_range.py | 3 + .../unit/test_code_ingest_counts_post_step.py | 6 +- tests/unit/test_code_page_shapes.py | 7 + tests/unit/test_code_repos_fork.py | 8 +- tests/unit/test_code_repos_refresh_loop.py | 29 ++++ tests/unit/test_code_review_brief_sections.py | 126 ++++++++++++++++++ tests/unit/test_code_status_ops.py | 7 + tests/unit/test_code_symbol_history.py | 11 +- tests/unit/test_coverage_published.py | 2 +- tests/unit/test_degraded_unnoted.py | 112 ++++++++++------ .../unit/test_loom_search_tracker_general.py | 6 +- tests/unit/test_memory_append_batch.py | 14 ++ tests/unit/test_mirrors.py | 25 ++++ tests/unit/test_pending_evidence.py | 6 + tests/unit/test_tracker_multi_binding.py | 28 ++++ 35 files changed, 529 insertions(+), 146 deletions(-) diff --git a/deploy/hyperdx_dashboards.md b/deploy/hyperdx_dashboards.md index 2afde24b193..b037e7cc24c 100644 --- a/deploy/hyperdx_dashboards.md +++ b/deploy/hyperdx_dashboards.md @@ -433,7 +433,7 @@ and use a time-series tile if you need rate. For a windowed count prefer the `increase` aggregation in a builder tile, which is reset-aware, over hand-rolled `max - min`. -Outcome is a five-value enum set in `memory/app/handlers._count_write`: +Outcome is an eleven-value enum set in `memory/app/set_commit.count_write`: | Outcome | Means | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 15dd6f8c595..e0d06e0fcef 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -321,8 +321,9 @@ error's kind only; the full text is in the server log. sections; `loom_search` also ends its text with a `Degraded:` line. An idempotent replay answers the `degraded` its first answer carried, on either transport. - An answer served from a fallback is not kept as a whole answer: `code.search` and - `code.ask` do not cache it, `code.map` does not keep its map, `memory.ask` stores no - precedent, and `code.review_brief` serves the brief unstored (`stored: false`). Each + `code.ask` do not cache it, `code.map` does not keep its map, the PR overlay that + `code.callers` and `code.impact` read is not kept, `memory.ask` stores no precedent, + and `code.review_brief` serves the brief unstored (`stored: false`). Each judges the entries its own reads recorded, so one the request recorded before it does not stop the cache. - Some caches keep a fallback with its entries and name them on each answer served from @@ -341,6 +342,7 @@ error's kind only; the full text is in the server log. - `LOOM_MEMORY_PENDING_DISCLOSURE_TTL_S` and `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`: the pending-extraction count and namespace health; + - `LOOM_CODE_FORK_UPSTREAM_MISS_TTL_S`: a fork lookup of `code.repos` that failed; - 5 seconds: each of `ops.incidents`' ClickHouse sources. - A later page of `code.search`, `code.grep` or `memory.search` names the entries of the run that ranked its pool. What each page reads for itself (the risk block, context diff --git a/server/code/app/index/commit_coverage.py b/server/code/app/index/commit_coverage.py index 3ad1c72d136..b5027b5a96b 100644 --- a/server/code/app/index/commit_coverage.py +++ b/server/code/app/index/commit_coverage.py @@ -23,6 +23,8 @@ import re from typing import Any +from server.observability import degradations + SHA_RE = re.compile(r"^[0-9a-fA-F]{7,40}$") # (git_dir, commit, watermark) -> bool | None; bounded, positive answers only @@ -51,7 +53,8 @@ async def _commits_since(git_dir: str, commit: str, watermark: str) -> int: return _COUNT_MEMO[key] try: count = int(await gitrepo.commit_count_between(git_dir, commit, watermark)) - except Exception: # noqa: BLE001 — unknown sha: -1, never a guess + except Exception as e: # noqa: BLE001 — unknown sha: -1, never a guess + degradations.partial("git_mirror", "commits_since_unread", e) return -1 if len(_COUNT_MEMO) >= _MEMO_MAX: _COUNT_MEMO.clear() @@ -71,7 +74,8 @@ async def _paths_since(git_dir: str, commit: str, head: str) -> list[str] | None return _PATHS_MEMO[key] try: paths = await gitrepo.diff_name_only(git_dir, commit, head, limit=100_000) - except Exception: # noqa: BLE001 — an unknown sha or a failed diff: None, never a guess + except Exception as e: # noqa: BLE001 — an unknown sha or a failed diff: None, never a guess + degradations.partial("git_mirror", "paths_since_unread", e) return None if len(_PATHS_MEMO) >= _PATHS_MEMO_MAX: _PATHS_MEMO.clear() @@ -99,7 +103,8 @@ async def covered(git_dir: str, commit: str, watermark: str) -> bool | None: return _MEMO[key] try: got = await gitrepo.is_ancestor(git_dir, commit, watermark) - except Exception: # noqa: BLE001 — a timeout or a missing mirror is "unknown" + except Exception as e: # noqa: BLE001 — a timeout or a missing mirror is "unknown" + degradations.partial("git_mirror", "ancestry_unread", e) return None if got is not None: if len(_MEMO) >= _MEMO_MAX: diff --git a/server/code/app/index/fork_upstream.py b/server/code/app/index/fork_upstream.py index ca825c6f77c..4302a5e6fbf 100644 --- a/server/code/app/index/fork_upstream.py +++ b/server/code/app/index/fork_upstream.py @@ -9,9 +9,10 @@ off asks about none. One `GET /repos/{owner}/{name}` per new slug per process per day, for the first few such candidates: answers (fork or not) are cached for a day, a failed or timed-out read for ten minutes, and nothing here ever raises — a -failure is "not indexed". This module only names repositories; which entries the -caller may read is still decided by the handler's per-entry gate, so a fork maps -only to an index the caller can already read. +failure is "not indexed", noted in `degraded` on each answer while it is kept. This +module only names repositories; which entries the caller may read is still decided by +the handler's per-entry gate, so a fork maps only to an index the caller can already +read. """ from __future__ import annotations @@ -22,6 +23,8 @@ from collections.abc import Awaitable, Callable from server.code.app.ttl_cache import TtlCache +from server.core.errors import caller_text +from server.observability import degradations from server.settings import settings logger = logging.getLogger("loom.code.fork_upstream") @@ -36,11 +39,15 @@ # (`../..`, `a/b?x=`) with the server's token. _SLUG = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,38})/(?!\.{1,2}$)[a-z0-9._-]{1,100}$") -# slug -> upstream slugs; a failed read is kept `code_fork_upstream_miss_ttl_s` as "not a -# known fork". +# slug -> upstream slugs _cache: TtlCache[str, tuple[str, ...]] = TtlCache( lambda: settings.code_fork_upstream_cache_ttl_s, maxsize=MAX_CACHE ) +# slug -> why its read failed, kept `code_fork_upstream_miss_ttl_s` as "not a known fork" +# and noted on each answer that serves it +_failed: TtlCache[str, str] = TtlCache( + lambda: settings.code_fork_upstream_miss_ttl_s, maxsize=MAX_CACHE +) def valid_slug(slug: str) -> bool: @@ -52,6 +59,7 @@ def valid_slug(slug: str) -> bool: def reset() -> None: _cache.clear() + _failed.clear() async def _github_upstreams(slug: str) -> list[str]: @@ -68,7 +76,7 @@ async def _ask(slug: str, fetch: Fetch) -> None: _cache.put(slug, ups) except Exception as e: # noqa: BLE001 — a failed read is "not a known fork" logger.debug("fork_upstream: %s: %s", slug, e) - _cache.put(slug, (), ttl_s=settings.code_fork_upstream_miss_ttl_s) + _failed.put(slug, caller_text(e)) async def fork_upstreams( @@ -81,7 +89,7 @@ async def fork_upstreams( if not settings.code_fork_upstream_lookup_enabled: return [] todo = [s for s in dict.fromkeys(slugs[:MAX_CANDIDATES]) if valid_slug(s)] - missing = [s for s in todo if s not in _cache] + missing = [s for s in todo if s not in _cache and s not in _failed] if missing: f = fetch or _github_upstreams tasks = [asyncio.ensure_future(_ask(s, f)) for s in missing] @@ -94,6 +102,9 @@ async def fork_upstreams( for t in tasks: t.cancel() for s in missing: - if s not in _cache: - _cache.put(s, (), ttl_s=settings.code_fork_upstream_miss_ttl_s) + if s not in _cache and s not in _failed: + _failed.put(s, f"no answer within {bound}s") + for s in todo: + if (why := _failed.get(s)) is not None: + degradations.partial("code.repos", "fork_upstream_unread", why) return [(s, u) for s in todo for u in (_cache.get(s) or ())] diff --git a/server/code/app/index/mirrors.py b/server/code/app/index/mirrors.py index f0b7a213285..7517d94a6c4 100644 --- a/server/code/app/index/mirrors.py +++ b/server/code/app/index/mirrors.py @@ -48,6 +48,7 @@ from server.core import readiness from server.core.background import detached_task from server.core.ch import set_query_tag +from server.observability import degradations from server.observability.budgets import request_time_left_s from server.settings import settings @@ -130,6 +131,7 @@ async def history_dir(cfg: Any, *, op: str = "", head: str = "") -> tuple[str, s return cfg.git_dir, "" state, reason = job_state(cfg.git_dir) if state == "failed": + degradations.partial("git_mirror", "clone_failed", reason) return "", f"no_git_mirror: {cfg.label}: clone failed ({reason}); retried each minute" return "", f"no_git_mirror: cloning {cfg.label}" diff --git a/server/code/app/index/pr_overlay.py b/server/code/app/index/pr_overlay.py index 60d1d3c0767..70ce6d34693 100644 --- a/server/code/app/index/pr_overlay.py +++ b/server/code/app/index/pr_overlay.py @@ -38,6 +38,7 @@ from typing import Any, NamedTuple, cast from server.code.app.ttl_cache import TtlCache +from server.observability import degradations from server.settings import settings logger = logging.getLogger("loom.code_index.pr_overlay") @@ -424,6 +425,7 @@ async def load_pr_overlay( ) except Exception as e: # noqa: BLE001 — a head the mirror or the store cannot place is not read logger.warning("pr_overlay: head of PR %s not placed: %s", pr_number, e) + degradations.partial("code_index", "pr_head_unread", e) head, tip, index_head = "", "", "" if not head: ov.reason = HEAD_NOT_IN_MIRROR @@ -470,17 +472,19 @@ async def from_mirror(path: str) -> bytes | None: except gitrepo.BlobTooLarge: return None # not parsed either way - await _parse_post_image( - repo, - org, - ns, - ov, - read=from_mirror, - path_prefixes=path_prefixes, - table_at=_table_at(index_head, generation), - ) - if key and not ov.unreached: # the next request finishes a partial one - _CACHE.put(key, ov) + with degradations.unit(): + await _parse_post_image( + repo, + org, + ns, + ov, + read=from_mirror, + path_prefixes=path_prefixes, + table_at=_table_at(index_head, generation), + ) + # the next request finishes a partial one, or one a failed read left smaller + if key and not ov.unreached and not degradations.current(): + _CACHE.put(key, ov) return ov @@ -534,17 +538,18 @@ async def from_request(path: str) -> bytes | None: text = img.files.get(path) return None if text is None else text.encode() - await _parse_post_image( - repo, - org, - ns, - ov, - read=from_request, - path_prefixes=path_prefixes, - table_at=_table_at(index_head, generation), - ) - if key and not ov.unreached: - _CACHE.put(key, ov) + with degradations.unit(): + await _parse_post_image( + repo, + org, + ns, + ov, + read=from_request, + path_prefixes=path_prefixes, + table_at=_table_at(index_head, generation), + ) + if key and not ov.unreached and not degradations.current(): + _CACHE.put(key, ov) return ov @@ -552,6 +557,7 @@ class _Facts(NamedTuple): symbols: tuple[Any, ...] names: frozenset[str] # the names it defines or calls timed_out: bool # its parse ran past its limits + unread: bool = False # its parse failed, or its calls could not be listed # Per file, so a push that changes one file of a PR re-parses that file alone, for @@ -566,6 +572,7 @@ class _Facts(NamedTuple): class _Edges(NamedTuple): edges: tuple[OverlayEdge, ...] timed_out: bool # parsing the file again ran past its limits + unread: bool = False # its edges could not be extracted # (path, content digest, digest of the name-table rows its names bind to) -> edges. @@ -674,13 +681,15 @@ def _parsed_facts(path: str, source: bytes) -> tuple[Any, _Facts]: pf, err = parse_for_ingest(path, source) timed_out = parse_timed_out(err) if pf is None or not pf.symbols: - return None, _Facts((), frozenset(), timed_out) + return None, _Facts((), frozenset(), timed_out, bool(err) and not timed_out) names = {s.name for s in pf.symbols if s.kind in ("function", "method")} + unread = False try: names |= collect_call_names(pf) except Exception as e: # noqa: BLE001 — a file whose calls cannot be listed binds nothing logger.debug("pr_overlay: call names of %s failed: %s", path, e) - return pf, _Facts(tuple(pf.symbols), frozenset(names), timed_out) + unread = True + return pf, _Facts(tuple(pf.symbols), frozenset(names), timed_out, unread) def _file_edges( @@ -700,7 +709,7 @@ def _file_edges( edges, _misses = extract_edges_and_misses(pf, table, None) except Exception as e: # noqa: BLE001 — per file, never the overlay logger.debug("pr_overlay: edges of %s failed: %s", path, e) - return _Edges((), False) + return _Edges((), False, unread=True) found = tuple( OverlayEdge( edge_kind=ed.edge_kind, @@ -739,6 +748,7 @@ async def _parse_post_image( names: set[str] = set() deadline = time.monotonic() + settings.code_pr_overlay_parse_window_s timed_out = 0 + unread: set[str] = set() # the files whose parse, calls or edges failed for p in paths: source = await read(p) if source is None or len(source) > MAX_FILE_BYTES: @@ -748,14 +758,16 @@ async def _parse_post_image( if got is None: ov.unreached += 1 continue - pf, (symbols, file_names, file_timed_out) = got + pf, (symbols, file_names, file_timed_out, calls_unread) = got timed_out += file_timed_out + if calls_unread: + unread.add(p) if not symbols: continue files[p] = (source, digest, pf, symbols, file_names) names |= file_names if not files: - _note_left_out(ov, timed_out) + _note_left_out(ov, timed_out, len(unread)) return # one name-keyed read serves both questions: which post-image functions # the index already defines (classification) and what the files' call @@ -790,14 +802,18 @@ async def _parse_post_image( ov.unreached += 1 continue timed_out += edges.timed_out + if edges.unread: + unread.add(p) ov.edges.extend(edges.edges) - _note_left_out(ov, timed_out) + _note_left_out(ov, timed_out, len(unread)) -def _note_left_out(ov: PrOverlay, timed_out: int) -> None: +def _note_left_out(ov: PrOverlay, timed_out: int, unread: int) -> None: parts = [] if timed_out: parts.append(f"{timed_out} changed file(s) whose parse ran past its limits") + if unread: + parts.append(f"{unread} changed file(s) whose parse or call extraction failed") if ov.unreached: parts.append( f"{ov.unreached} changed file(s) {NOT_REACHED}: the request's parse time was spent" @@ -834,6 +850,7 @@ async def _name_table( got = await repo.name_candidates(org, ns, chunk) except Exception as e: # noqa: BLE001 — a failed chunk adds nothing; the PR's own names still bind logger.info("pr_overlay: name table read failed for PR %s: %s", pr_number, e) + degradations.partial("code_index", "overlay_names_unread", e) continue for n in chunk: rows = list(got.get(n) or []) diff --git a/server/code/app/index/pr_reviews.py b/server/code/app/index/pr_reviews.py index af8da84efdd..9d6d3f69027 100644 --- a/server/code/app/index/pr_reviews.py +++ b/server/code/app/index/pr_reviews.py @@ -22,6 +22,7 @@ from typing import Any from server.code.domain.pr_reviews import MAX_PRS +from server.observability import degradations logger = logging.getLogger(__name__) @@ -107,6 +108,7 @@ async def reviews_for( ) except Exception as e: # noqa: BLE001 — reviews enrich the rows, never gate them logger.info("pr_reviews: read failed for %s: %s", ns, e) + degradations.partial("code_index", "pr_reviews_unread", e) return None return fold(list(rows), nums, per) diff --git a/server/code/app/index/repo_registry.py b/server/code/app/index/repo_registry.py index ff464fd1177..6753f5589ef 100644 --- a/server/code/app/index/repo_registry.py +++ b/server/code/app/index/repo_registry.py @@ -32,6 +32,7 @@ from server.code.domain.index.repos import reset_for_tests as reset_snapshot_for_tests from server.core import readiness from server.core.secrets_at_rest import seal, unseal +from server.observability import degradations from server.settings import settings logger = logging.getLogger("loom.code_index.repo_registry") @@ -149,7 +150,7 @@ async def refresh_db_repos(*, force: bool = False, ch: Any | None = None) -> lis async def read_registry(ch: Any | None = None) -> bool: """Read loom.code_repos into the snapshot now. False when that read failed - and the last snapshot was kept; True with self-service off.""" + and the last snapshot was kept, noted; True with self-service off.""" global _LOADED_AT if not settings.code_self_service_enabled: return True @@ -164,10 +165,11 @@ async def read_registry(ch: Any | None = None) -> bool: set_registry_repos([row_to_config(r) for r in active], page) _LOADED_AT = time.monotonic() return True - except Exception as e: # noqa: BLE001 — keep the last snapshot + except Exception as e: # noqa: BLE001 — keep the last snapshot, which answers stale logger.warning( "code_repos: refresh failed, keeping %d entries: %s", len(registry_repos()), e ) + degradations.partial("code_index", "registry_unread", e) return False diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 87e86958022..395cd42b975 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -12,6 +12,7 @@ from server.code.app.index.review_brief import ( EMPTY, + FAILED, IMPACT_SEED_FILES, MAX_COVERAGE_SETTINGS, MAX_COVERAGE_SYMBOLS, @@ -695,9 +696,9 @@ async def build_for_merge( if store and changed_paths and not diff: logger.info("review_brief: PR %s served unstored, its diff was not read", pr_number) payload["stored"] = False - elif store and degradations.current(): - # A read it ran fell back: the stored copy would be served later without its - # `degraded`. + elif store and (degradations.current() or (provenance or {}).get("tracker") == FAILED): + # A read it ran, or the caller's tracker read, fell back: the stored copy would + # be served later without its `degraded`. logger.info("review_brief: PR %s served unstored, a read fell back", pr_number) payload["stored"] = False elif store: diff --git a/server/code/app/index/review_brief_sources.py b/server/code/app/index/review_brief_sources.py index bdbc3b4895d..12216b6269b 100644 --- a/server/code/app/index/review_brief_sources.py +++ b/server/code/app/index/review_brief_sources.py @@ -11,6 +11,7 @@ from typing import Any from server.code.app.index.review_brief import FAILED, NOT_BOUND, RESTRICTED, SERVED +from server.observability import degradations from server.settings import settings logger = logging.getLogger(__name__) @@ -174,8 +175,9 @@ async def mirror_provenance(org: str, ns: str, facts: dict[str, Any]) -> dict[st a fact on the record, never a failed brief.""" try: tracker_status, tracker_row = await tracker_pr_facts(org, ns, int(facts["pr_number"])) - except Exception as e: # noqa: BLE001 — the brief stands without the reviewers + except Exception as e: # noqa: BLE001 — the brief stands without the reviewers, unstored logger.info("review_brief: qa facts for PR %s failed: %s", facts.get("pr_number"), e) + degradations.partial("code.review_brief", "reviewers_unread", e) tracker_status, tracker_row = FAILED, {} title_from = "tracker" if tracker_row.get("title") else "mirror" if title_from == "tracker": diff --git a/server/code/app/index/risk_fit.py b/server/code/app/index/risk_fit.py index 74bd655210f..d8b3f0f8c65 100644 --- a/server/code/app/index/risk_fit.py +++ b/server/code/app/index/risk_fit.py @@ -46,13 +46,9 @@ def parse_fit(text: str) -> dict[str, Any] | None: async def stored_fit(repo: Any, org: str, ns: str) -> dict[str, Any] | None: - """The namespace's stored fit, or None (no row, unparsable, or the - state read failed — the brief section fails open to `no_fit`).""" - try: - return parse_fit(str(await repo.get_state(org, ns, STATE_KEY) or "")) - except Exception as e: # noqa: BLE001 — a missing fit is an empty section - logger.info("risk_fit: state read failed for %s/%s: %s", org, ns, e) - return None + """The namespace's stored fit, or None (no row, or unparsable). A failed state read + raises: the brief's risk section reports it failed.""" + return parse_fit(str(await repo.get_state(org, ns, STATE_KEY) or "")) def refit_due(fit: dict[str, Any] | None, *, now: datetime | None = None) -> bool: diff --git a/server/code/app/index/task_pack.py b/server/code/app/index/task_pack.py index 1dd70881582..893a148e3e2 100644 --- a/server/code/app/index/task_pack.py +++ b/server/code/app/index/task_pack.py @@ -29,6 +29,7 @@ from typing import Any from server.code.store.index import CodeRepo +from server.observability import degradations logger = logging.getLogger(__name__) @@ -255,8 +256,9 @@ def render( async def _safe(coro: Any, default: Any) -> Any: try: return await coro - except Exception: # a failed section takes its default; the pack still serves + except Exception as e: logger.info("task pack section failed", exc_info=True) + degradations.partial("code_index", "task_pack_section_dropped", e) return default diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index ddc26ff5239..f1e431231ac 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -1008,25 +1008,18 @@ async def _coverage_cached( # names it degradations.partial("code_index", "coverage_gaps_unread", hit[4]) return hit[2], hit[3] - refresh = getattr(repo, "refresh_coverage", None) failure = "" if published is not None: cov, gap_counts = published - elif refresh is not None: - cov, gap_counts = await refresh(org, ns, fingerprint=fp) - else: # a repository without the publisher (test fakes): compute - cov = await repo.coverage(org, ns) - try: - gap_counts = await repo.coverage_gaps(org, ns) - except Exception as e: # noqa: BLE001 — coverage must not fail on the gap queries + else: + cov, gap_counts, failed = await repo.refresh_coverage(org, ns, fingerprint=fp) + if failed is not None: from server.core.errors import caller_text - logger.warning("code.coverage: gap queries failed for %s/%s: %s", org, ns, e) - gap_counts, failure = None, caller_text(e) - if gap_counts is None: - # The gap queries failed here, or in `refresh_coverage` (which answers no kind): the - # page renders without its gaps row. - degradations.partial("code_index", "coverage_gaps_unread", failure) + logger.warning("code.coverage: gap queries failed for %s/%s: %s", org, ns, failed) + # the page renders without its gaps row + failure = caller_text(failed) + degradations.partial("code_index", "coverage_gaps_unread", failure) if len(_coverage_cache) > 256: _coverage_cache.clear() _coverage_cache[key] = (fp, now, cov, gap_counts, failure) diff --git a/server/code/app/settings.py b/server/code/app/settings.py index d1fdc3fb4af..b1d94511697 100644 --- a/server/code/app/settings.py +++ b/server/code/app/settings.py @@ -15,6 +15,7 @@ import asyncio import logging import time +from collections.abc import Awaitable from typing import Any, cast from server.code.api.models_conventions import CodeSettingFactsOutput @@ -109,12 +110,6 @@ async def _control(repo: CodeRepo, org: str, ns: str) -> tuple[bool, str]: return False, probe -# The reads `handle_code_setting_facts` gathers, in order, and what each answers when it -# fails. -_READS = ("control", "declaration", "history", "randomization", "tests") -_UNREAD: tuple[Any, ...] = ((False, ""), None, [], [], ([], 0)) - - async def handle_code_setting_facts(input: Any) -> Any: require_code_intel() started = time.monotonic() @@ -125,17 +120,22 @@ async def handle_code_setting_facts(input: Any) -> Any: if not sf.valid_name(name): return CodeSettingFactsOutput(name=name, verdict="not_a_setting", causes=["invalid_name"]) with code_span("setting_facts.reads", seeds=1): - gathered = await asyncio.gather( - _control(repo, org, ns), - _declaration(repo, org, ns, name), - history_chunks(repo, org, ns), - repo.chunk_contains(org, ns, sf.RANDOMIZER_FILE, f'"{name}":', limit=4), - repo.grep_files(org, ns, name, path_prefix="tests/", limit=1), - return_exceptions=True, - ) + # each read, and what it answers when it fails + reads: list[tuple[str, Awaitable[Any], Any]] = [ + ("control", _control(repo, org, ns), (False, "")), + ("declaration", _declaration(repo, org, ns, name), None), + ("history", history_chunks(repo, org, ns), []), + ( + "randomization", + repo.chunk_contains(org, ns, sf.RANDOMIZER_FILE, f'"{name}":', limit=4), + [], + ), + ("tests", repo.grep_files(org, ns, name, path_prefix="tests/", limit=1), ([], 0)), + ] + gathered = await asyncio.gather(*(r[1] for r in reads), return_exceptions=True) got: list[Any] = [] unread: list[str] = [] - for read, g, default in zip(_READS, gathered, _UNREAD, strict=True): + for (read, _, default), g in zip(reads, gathered, strict=True): if isinstance(g, BaseException): degradations.partial("code_index", f"setting_{read}_unread", g) logger.info("setting_facts: %s read failed (open): %s", read, g) diff --git a/server/code/store/index/status.py b/server/code/store/index/status.py index ab1874fbe09..87e63426465 100644 --- a/server/code/store/index/status.py +++ b/server/code/store/index/status.py @@ -92,7 +92,7 @@ class StatusMixin(CodeRepoBase): async def refresh_coverage( self, org: str, ns: str, *, fingerprint: str | None = None, must_land: bool = False - ) -> tuple[dict[str, Any], dict[str, int] | None]: + ) -> tuple[dict[str, Any], dict[str, int] | None, Exception | None]: """Compute `coverage` and `coverage_gaps` once and publish them as the shared `coverage` state row (value = JSON, detail = counts fingerprint), the way `refresh_table_counts` publishes @@ -101,18 +101,19 @@ async def refresh_coverage( open pays once for every process and colour. A cold computation reads about 1.2 GB and takes 4 s on a large repository; the row is a point read. A failed gap read publishes nothing, so every process computes - again rather than serving no gaps until the counts move, and the gap - counts answer None. `must_land`: a failed gap read or write raises, for - a caller that writes the counts only once this row has landed.""" + again rather than serving no gaps until the counts move: the gap counts + answer None, with the failure third. `must_land`: a failed gap read or + write raises, for a caller that writes the counts only once this row has + landed.""" if fingerprint is None: fingerprint = counts_fingerprint(await self.all_state(org, ns)) cov = await self.coverage(org, ns) try: gaps = await self.coverage_gaps(org, ns) - except Exception: # the gap queries are additive; nothing is published + except Exception as e: # the gap queries are additive; nothing is published if must_land: raise - return cov, None + return cov, None, e try: await self.set_state( org, @@ -124,7 +125,7 @@ async def refresh_coverage( except Exception: # the answer stands without the row, unless it must land if must_land: raise - return cov, gaps + return cov, gaps, None async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: """Counts of what the index does not know (see CodeCoverageGaps). diff --git a/server/memory/app/bulk_set.py b/server/memory/app/bulk_set.py index c496e6d0652..27183242526 100644 --- a/server/memory/app/bulk_set.py +++ b/server/memory/app/bulk_set.py @@ -123,7 +123,9 @@ async def _bulk_existing_lookup(ch: Any, input: MemoryBulkSetInput, state: _Bulk id, content hash, pin, creation time and the carried columns per key — into `state`. Fails closed: without the live rows a batch would overwrite a read-only key, unpin a pinned one and announce revisions as new writes, so a failed read refuses the batch - before anything is written, retryable.""" + before anything is written, retryably: a coded store error passes as it is (503 + `POSTGRES_UNAVAILABLE` or `OVERLOADED`, 504 `BACKEND_TIMEOUT`), any other failure is + a 503 `BACKEND_UNAVAILABLE`.""" import server.memory.store as memory_repo try: @@ -140,8 +142,8 @@ async def _bulk_existing_lookup(ch: Any, input: MemoryBulkSetInput, state: _Bulk include_tombstoned=pg.enabled(), ) except LoomServerError: - raise # a coded store failure (a timeout, an unavailable backend) as it is - except Exception as e: # refused as a backend failure, nothing written + raise # the store's own code: POSTGRES_UNAVAILABLE, OVERLOADED, BACKEND_TIMEOUT + except Exception as e: # refused as BACKEND_UNAVAILABLE, nothing written log.warning("bulk_set: live-row lookup failed: %s", error_summary(e)) op = "memory.append_batch" if state.strict_append else "memory.bulk_set" raise BackendUnavailableError( diff --git a/server/memory/app/loom_search/tracker_leg.py b/server/memory/app/loom_search/tracker_leg.py index 0b9bcf6ffb0..4fdf4c2c506 100644 --- a/server/memory/app/loom_search/tracker_leg.py +++ b/server/memory/app/loom_search/tracker_leg.py @@ -213,7 +213,11 @@ async def tracker_leg( query: str, *, plan: TrackerSearchPlan | None, top_k: int = TRACKER_LEG_TOP_K ) -> dict[str, Any] | None: """Search the prepared targets within the original discovery-and-read deadline.""" - if plan is None or asyncio.get_running_loop().time() >= plan.deadline: + if plan is None: + return None + if asyncio.get_running_loop().time() >= plan.deadline: + # named as the timeout inside the leg is + degradations.partial("loom_search", "tracker_dropped", TimeoutError()) return None try: async with asyncio.timeout_at(plan.deadline): diff --git a/server/memory/app/pending_evidence.py b/server/memory/app/pending_evidence.py index 2de2fe1ede9..048bdfff5d5 100644 --- a/server/memory/app/pending_evidence.py +++ b/server/memory/app/pending_evidence.py @@ -72,8 +72,9 @@ def rank_pending_turns( except Exception as e: # noqa: BLE001 — a malformed batch is not evidence degradations.partial("memory.ask", "pending_batch_dropped", e) continue - msgs = data.get("messages") or [] + msgs = (data.get("messages") or []) if isinstance(data, dict) else None if not isinstance(msgs, list): + degradations.partial("memory.ask", "pending_batch_dropped", "messages is not a list") continue qid = str(b.get("queue_id") or "") sid = str(b.get("session_id") or data.get("session_id") or "") diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index a876ec26bf0..98151f0ef0f 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -27,8 +27,37 @@ server/code/app/common.py::record_code_outcome::1 server/code/app/common.py::record_code_shunt::1 telemetry server/code/app/common.py::schedule_code_trace._write::1 telemetry server/code/app/common.py::schedule_code_trace_validation_failure::1 telemetry +server/code/app/index/bootstrap.py::_pin_ledger_merges::1 logged_only_nonanswer # the clone job's pin pass +server/code/app/index/bootstrap.py::index_slice._one::1 logged_only_nonanswer +server/code/app/index/bootstrap.py::mirror_job::1 noted_by_caller # mirrors.history_dir notes git_mirror: clone_failed from job_state +server/code/app/index/denylist.py::_show_text::1 logged_only_nonanswer # the denylist the ingest and the code-link pass load +server/code/app/index/history_bound.py::publish::1 write +server/code/app/index/ingest_parse.py::parse_for_ingest::1 noted_by_caller # returns the error: the ingest stores it, memory_links raises ParseFailed, the PR overlay counts it in overlay_note +server/code/app/index/maintainers.py::sync_quietly::1 write +server/code/app/index/maintainers.py::sync_restricted_page_branches::1 logged_only_nonanswer +server/code/app/index/mirrors.py::_fetch_round::1 logged_only_nonanswer +server/code/app/index/mirrors.py::_fetch_round::2 logged_only_nonanswer +server/code/app/index/mirrors.py::_merge_page::1 logged_only_nonanswer +server/code/app/index/mirrors.py::_named_paths::1 logged_only_nonanswer +server/code/app/index/mirrors.py::_run::1 logged_only_nonanswer +server/code/app/index/mirrors.py::_run::2 logged_only_nonanswer +server/code/app/index/packs.py::_co_change_gaps::1 logged_only_nonanswer # the ingest's PR pack +server/code/app/index/packs.py::_envelope_line::1 logged_only_nonanswer # the ingest's PR pack +server/code/app/index/packs.py::_reviews_for::1 logged_only_nonanswer # the ingest's PR pack +server/code/app/index/packs.py::_tracker_lines::1 logged_only_nonanswer # the ingest's PR pack +server/code/app/index/pr_overlay.py::_file_edges::1 noted_by_caller # _parse_post_image counts the file in overlay_note +server/code/app/index/pr_overlay.py::_index_head::1 cache_fallback # the names are read, nothing kept +server/code/app/index/pr_overlay.py::_parsed_facts::1 noted_by_caller # _parse_post_image counts the file in overlay_note +server/code/app/index/pr_overlay.py::_state_generation::1 cache_fallback # the names are read, nothing kept +server/code/app/index/registry.py::ensure_registered::1 write +server/code/app/index/retire.py::refresh_code_views::1 write server/code/app/index/review_brief_build.py::build_for_merge::4 write server/code/app/index/review_brief_build.py::build_for_open::3 write +server/code/app/index/risk_fit.py::refit_namespace::1 write # the weekly refit +server/code/app/index/scip_delta.py::_declaration_line_test::1 logged_only_nonanswer # the SCIP apply's edge filter, a worker pass +server/code/app/index/scip_delta.py::_declaration_line_test::2 logged_only_nonanswer # the SCIP apply's edge filter, a worker pass +server/code/app/index/scip_delta.py::_indexable_prefixes::1 logged_only_nonanswer # the SCIP apply's repo entry, a worker pass +server/code/app/index/scip_delta.py::_path_refusal::1 logged_only_nonanswer # the SCIP apply's repo entry, a worker pass server/code/app/index_status.py::_commit_missing::1 noted_by_caller # _lag_between notes git_mirror: lag_unknown server/code/app/index_status.py::_publish_status_snapshot::1 write server/code/app/index_status.py::_refresh_repo_status::1 logged_only_nonanswer diff --git a/tests/unit/test_bisect_fusion.py b/tests/unit/test_bisect_fusion.py index b2472d48b88..b1f6da293b0 100644 --- a/tests/unit/test_bisect_fusion.py +++ b/tests/unit/test_bisect_fusion.py @@ -197,6 +197,21 @@ async def failed() -> tuple: assert got == pool and summary == {"status": "window_unavailable"} +@pytest.mark.asyncio +@pytest.mark.parametrize("window", ["window", "wide window"]) +async def test_a_window_read_that_raised_is_named_and_fuses_nothing(window: str) -> None: + from server.observability import degradations + + async def down() -> list[dict]: + raise TimeoutError + + with degradations.unit(): + assert await cbf._read_and_embed(window, down, "") is None + assert degradations.current() == [ + f"tracker: {window.replace(' ', '_')}_dropped (TimeoutError)" + ] + + @pytest.mark.asyncio async def test_rerank_is_off_by_default_and_keeps_order_on_failure(monkeypatch) -> None: pool = [_cand(1), _cand(2)] diff --git a/tests/unit/test_code_blame_range.py b/tests/unit/test_code_blame_range.py index a4d2b1a53bf..a74353f8d34 100644 --- a/tests/unit/test_code_blame_range.py +++ b/tests/unit/test_code_blame_range.py @@ -279,6 +279,9 @@ async def functions_for_paths(self, org, ns, paths, *, limit=400, **_kw): async def review_comments_for(self, org, ns, paths, *, limit=30, humans_only=True): return [] + async def review_comments_on_prs(self, org, ns, numbers, paths, **_kw): + return [] + async def items_by_number(self, org, ns, numbers): return {} diff --git a/tests/unit/test_code_ingest_counts_post_step.py b/tests/unit/test_code_ingest_counts_post_step.py index c7e7482b3b3..1e2cf98304f 100644 --- a/tests/unit/test_code_ingest_counts_post_step.py +++ b/tests/unit/test_code_ingest_counts_post_step.py @@ -25,11 +25,13 @@ async def refresh_table_counts(self, org: str, ns: str, **_: Any) -> dict[str, i return {} # The same pass publishes the coverage row - async def refresh_coverage(self, org: str, ns: str, **_: Any) -> tuple[dict[str, Any], None]: + async def refresh_coverage( + self, org: str, ns: str, **_: Any + ) -> tuple[dict[str, Any], None, None]: self.calls.append(("coverage", ns)) if self.fail: raise RuntimeError("ch down") - return {}, None + return {}, None, None def _plan(repo: _Repo, commits: int, **kw: Any) -> ingest_budget.RepoPass: diff --git a/tests/unit/test_code_page_shapes.py b/tests/unit/test_code_page_shapes.py index 1944ddd3e5f..bdcfc4e8b9e 100644 --- a/tests/unit/test_code_page_shapes.py +++ b/tests/unit/test_code_page_shapes.py @@ -13,6 +13,7 @@ from server.code.app import index_status from server.code.app.index import gitrepo +from server.code.store import index as cr _STATE = { "git_head": {"value": "a" * 40, "detail": "", "updated_at": ""}, @@ -51,6 +52,12 @@ async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: "code_files_no_symbols": 0, } + async def set_state(self, org: str, ns: str, key: str, value: str, detail: str = "") -> None: + pass + + # the real method, bound to this fake + refresh_coverage = cr.CodeRepo.refresh_coverage + async def recent_indexed_commits( self, org: str, ns: str, *, limit: int ) -> list[dict[str, Any]]: diff --git a/tests/unit/test_code_repos_fork.py b/tests/unit/test_code_repos_fork.py index 1a97a4cc526..38cb7884018 100644 --- a/tests/unit/test_code_repos_fork.py +++ b/tests/unit/test_code_repos_fork.py @@ -18,6 +18,7 @@ from server.auth.jwt import AuthInfo from server.code.app import index_status from server.code.app import repos as repos_mod +from server.observability import degradations from server.operations.base import Role from server.settings import settings from tests.unit.code_fixtures import repo_config @@ -180,8 +181,11 @@ async def test_non_fork_error_or_timeout_is_not_indexed(plane, github, monkeypat answers, calls = github answers["someone/clickhouse"] = answer monkeypatch.setattr(settings, "code_fork_upstream_budget_s", 0.05) - assert await _repos(repos=[_GH + "someone/ClickHouse"]) == [] - assert await _repos(repos=[_GH + "someone/ClickHouse"]) == [] + for _ in range(2): # the second answer is served from the kept miss, noted again + degradations.begin() + assert await _repos(repos=[_GH + "someone/ClickHouse"]) == [] + noted = [n for n in degradations.current() if "fork_upstream_unread" in n] + assert len(noted) == (0 if answer == [] else 1) assert calls == ["someone/clickhouse"] # the miss is cached too diff --git a/tests/unit/test_code_repos_refresh_loop.py b/tests/unit/test_code_repos_refresh_loop.py index bfc291ccbd1..e9f4a8fe6be 100644 --- a/tests/unit/test_code_repos_refresh_loop.py +++ b/tests/unit/test_code_repos_refresh_loop.py @@ -107,6 +107,35 @@ async def registry_rows(self) -> list[dict[str, Any]]: repo_registry.reset_for_tests() +def test_a_refresh_that_keeps_the_last_snapshot_names_it( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """`code.repos` lists the kept snapshot, which may lack an entry added since.""" + import server.code.store.index as store + from server.observability import degradations + + class _Down(_Repo): + async def registry_rows(self) -> list[dict[str, Any]]: + raise ConnectionError("store unreachable") + + async def notes_of_refresh() -> list[str]: + with degradations.unit(): + await repo_registry.refresh_db_repos(force=True) + return degradations.current() + + monkeypatch.setattr(settings, "code_self_service_enabled", True) + repo_registry.reset_for_tests() + try: + monkeypatch.setattr(store, "CodeRepo", _Repo) + _Repo.rows = [_row("standard")] + assert asyncio.run(notes_of_refresh()) == [] + monkeypatch.setattr(store, "CodeRepo", _Down) + assert asyncio.run(notes_of_refresh()) == ["code_index: registry_unread (ConnectionError)"] + assert [c.namespace for c in registry_repos()] == ["code-widgets"] + finally: + repo_registry.reset_for_tests() + + def test_the_snapshot_keeps_the_namespace_of_a_removed_page_branch( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/tests/unit/test_code_review_brief_sections.py b/tests/unit/test_code_review_brief_sections.py index 1f323dd6aee..5b6f4ccd47c 100644 --- a/tests/unit/test_code_review_brief_sections.py +++ b/tests/unit/test_code_review_brief_sections.py @@ -1111,3 +1111,129 @@ def test_review_brief_builder_imports_no_handler_or_operation() -> None: for m in names if m.startswith(("server.code.app.review_brief", "server.code.api", "server.operations")) ] + + +class _FailingRepo(_Repo): + """`_Repo` whose `failing` read raises; the merge ledger has no row.""" + + def __init__(self, failing: str) -> None: + super().__init__() + self.failing = failing + + def _check(self, read: str) -> None: + if read == self.failing: + raise TimeoutError + + async def functions_for_paths(self, *a: Any, **kw: Any) -> list[dict[str, Any]]: + self._check("functions_for_paths") + return await super().functions_for_paths(*a, **kw) + + async def caller_counts(self, *a: Any) -> dict[str, dict[str, int]]: + self._check("caller_counts") + return await super().caller_counts(*a) + + async def symbol_stats(self, *a: Any) -> dict[str, dict[str, Any]]: + self._check("symbol_stats") + return await super().symbol_stats(*a) + + async def get_state(self, org: str, ns: str, key: str) -> str: + if key != "git_head": + self._check("fit") + return await super().get_state(org, ns, key) + + async def pr_merge_facts(self, *a: Any, **kw: Any) -> dict[str, Any]: + self._check("pr_merge_facts") + return {} + + +def _merge_reads(monkeypatch: pytest.MonkeyPatch, tracker: Any) -> None: + """The mirror's parent and diff, the tracker section's reader, and the stored row as + its payload.""" + from server.code.app.index import gitrepo, packs + + async def run(git_dir: str, *args: str) -> str: + return PARENT if args[0] == "rev-parse" else DIFF + + monkeypatch.setattr(gitrepo, "run", run) + monkeypatch.setattr(packs, "tracker_section_rows", tracker) + monkeypatch.setattr(review_brief_build, "brief_row", lambda org, ns, payload: payload) + + +@pytest.mark.parametrize( + ("failing", "note"), + [ + ("code.impact", "code.review_brief: symbols_failed (RuntimeError)"), + ("functions_for_paths", "code_index: function_rows_unread (TimeoutError)"), + ("caller_counts", "code_index: caller_counts_unread (TimeoutError)"), + ("symbol_stats", "code_index: fan_in_unread (TimeoutError)"), + ("code.coverage_claim", "code.review_brief: coverage_claim_failed (RuntimeError)"), + ("code.test_home", "code.review_brief: test_home_failed (RuntimeError)"), + ("code.setting_facts", "code.review_brief: setting_facts_failed (RuntimeError)"), + ("code.symbol_history", "code.review_brief: symbol_history_failed (RuntimeError)"), + ("code.blame_range", "code.review_brief: blame_range_failed (RuntimeError)"), + ("tracker", "code.review_brief: tracker_failed (TimeoutError)"), + ("fit", "code.review_brief: risk_failed (TimeoutError)"), + ("pr_merge_facts", "code_index: pr_author_unread (TimeoutError)"), + ], +) +@pytest.mark.asyncio +async def test_a_merged_brief_whose_read_failed_names_it_and_is_served_unstored( + monkeypatch: pytest.MonkeyPatch, failing: str, note: str +) -> None: + from server.observability import degradations + + async def tracker(*a: Any) -> tuple[str, list[dict[str, Any]]]: + if failing == "tracker": + raise TimeoutError + return await _tracker_not_bound(*a) + + _merge_reads(monkeypatch, tracker) + repo = _FailingRepo(failing) + with degradations.unit(): + payload = await review_brief_build.build_for_merge( + repo, + ORG, + NS, + git_dir="/x", + pr_number=117354, + title="t", + merge_sha=SHA, + changed_paths=PATHS, + call=_Calls(fail={failing}), + ) + assert degradations.current() == [note] + assert payload["stored"] is False and repo.inserted == [] + + +@pytest.mark.asyncio +async def test_a_mirror_built_brief_whose_tracker_read_failed_names_it_and_is_served_unstored( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Its provenance is read before the build: stored, every later read would serve + `tracker: failed` without the note.""" + from server.observability import degradations + + async def down(*a: Any) -> Any: + raise TimeoutError + + _merge_reads(monkeypatch, _tracker_not_bound) + monkeypatch.setattr(review_brief_sources, "tracker_pr_facts", down) + repo = _FailingRepo("") + with degradations.unit(): + facts: dict[str, Any] = {"pr_number": 117354, "title": "t"} + provenance = await review_brief_sources.mirror_provenance(ORG, NS, facts) + payload = await review_brief_build.build_for_merge( + repo, + ORG, + NS, + git_dir="/x", + pr_number=117354, + title="t", + merge_sha=SHA, + changed_paths=PATHS, + call=_Calls(), + provenance=provenance, + ) + assert degradations.current() == ["code.review_brief: reviewers_unread (TimeoutError)"] + assert payload["provenance"]["tracker"] == rb.FAILED + assert payload["stored"] is False and repo.inserted == [] diff --git a/tests/unit/test_code_status_ops.py b/tests/unit/test_code_status_ops.py index 04672b69785..d2ca18764b0 100644 --- a/tests/unit/test_code_status_ops.py +++ b/tests/unit/test_code_status_ops.py @@ -12,6 +12,7 @@ from server.code.app import ingest as refresh_mod from server.code.app.index import registry as reg_mod from server.code.domain.index.repos import RepoConfig +from server.code.store import index as cr from server.operations.base import Role from server.settings import settings @@ -55,6 +56,12 @@ async def table_counts(self, org: str, ns: str, **_: Any) -> dict[str, int]: async def get_state(self, org: str, ns: str, key: str) -> str: return "a" * 40 if key == "git_head" else "" + async def set_state(self, org: str, ns: str, key: str, value: str, detail: str = "") -> None: + pass + + # the real method, bound to this fake + refresh_coverage = cr.CodeRepo.refresh_coverage + async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: return { "functions_scanned": 122579, diff --git a/tests/unit/test_code_symbol_history.py b/tests/unit/test_code_symbol_history.py index 35cfd2d93c2..37a80a42e39 100644 --- a/tests/unit/test_code_symbol_history.py +++ b/tests/unit/test_code_symbol_history.py @@ -324,14 +324,19 @@ async def test_unbound_unavailable_and_unresolved(wired) -> None: "unknown", "named", } and out.open_issues_naming == [] + from server.observability import degradations + wired["qa"], wired["src"] = QA, _Source(down=True) - out = await h.handle_code_symbol_history( - CodeSymbolHistoryInput(org=ORG, namespace=NS, name="x") - ) + with degradations.unit(): + out = await h.handle_code_symbol_history( + CodeSymbolHistoryInput(org=ORG, namespace=NS, name="x") + ) + assert degradations.current() == ["tracker: symbol_facts_unread (TrackerUnavailable)"] assert ( out.tracker_unavailable and out.causes == ["tracker_unavailable"] and out.summary["prs_total"] == 4 + and out.tracker_namespace == QA ) wired["seeds"] = [] out = await h.handle_code_symbol_history( diff --git a/tests/unit/test_coverage_published.py b/tests/unit/test_coverage_published.py index cf37d462005..e238aacdc80 100644 --- a/tests/unit/test_coverage_published.py +++ b/tests/unit/test_coverage_published.py @@ -161,7 +161,7 @@ async def coverage_gaps(self, org: str, ns: str) -> dict[str, int]: _, gaps = await index_status._coverage_cached(repo, "o", "n", state) assert gaps is None noted.append(degradations.current()) - assert noted == [["code_index: coverage_gaps_unread"]] * 2 + assert noted == [["code_index: coverage_gaps_unread (TimeoutError)"]] * 2 assert repo.computed == 1 and repo.published == [] repo.down = False clock.advance(PROBE_ERROR_TTL_S) diff --git a/tests/unit/test_degraded_unnoted.py b/tests/unit/test_degraded_unnoted.py index 14e568a1b1e..4fa9a10605c 100644 --- a/tests/unit/test_degraded_unnoted.py +++ b/tests/unit/test_degraded_unnoted.py @@ -1,20 +1,27 @@ """Every broad `except` in the code and memory apps either names its fallback in `degraded` or is listed, with why it need not, in `degraded_unnoted.txt`; and every -fallback that feeds provider health names a provider whose success clears it.""" +fallback that feeds provider health names a provider whose success clears it. + +The scan reads each handler and gather branch on its own, so it does not see a result +tested in another function, `asyncio.wait`, an `isinstance` filter that keeps the +successes, an exception test inside a `BoolOp`, or which call of a noting helper runs.""" from __future__ import annotations import ast +import functools from pathlib import Path from server.core.paths import REPO_ROOT _DIRS = ("server/code/app", "server/memory/app") -# The index plane's ingest passes, which serve no response, like the workers and stores -# outside these dirs. -_EXCLUDED = ("server/code/app/index/",) -# The index-plane modules a request runs: a review brief built on a miss. -_INCLUDED = {"server/code/app/index/review_brief_build.py"} +_INDEX = "server/code/app/index/" +_INDEX_PKG = "server.code.app.index" +# The ingest pass that `code.refresh` and the ingest worker run: it writes the index, +# and its notes reach no answer, like the workers and stores outside these dirs. +_INGEST_PASS = {"ingest_pass", "pass_stream", "entry_lock", "erasing"} +# Read on a request through a scanned module: the review brief's build reads the fit. +_ALSO_SCANNED = {"risk_fit"} _ALLOWLIST = Path(__file__).with_name("degraded_unnoted.txt") _CATEGORIES = { # a cache, memo or precomputed read that falls back to the live read @@ -149,44 +156,73 @@ def _gather_fallbacks(fn: ast.AST, helpers: set[str]) -> list[bool]: return [noted for _, _, noted in sorted(sites)] +@functools.cache +def _trees() -> dict[str, ast.Module]: + return { + str(path.relative_to(REPO_ROOT)): ast.parse(path.read_text()) + for d in _DIRS + for path in sorted((REPO_ROOT / d).rglob("*.py")) + } + + +def _index_modules_imported(tree: ast.Module) -> set[str]: + out: set[str] = set() + for n in ast.walk(tree): + if isinstance(n, ast.ImportFrom) and n.module == _INDEX_PKG: + out |= {a.name for a in n.names} + elif isinstance(n, ast.ImportFrom) and (n.module or "").startswith(_INDEX_PKG + "."): + out.add(str(n.module).split(".")[4]) + elif isinstance(n, ast.Import): + out |= {a.name.split(".")[4] for a in n.names if a.name.startswith(_INDEX_PKG + ".")} + return out + + +def _scanned_index_modules() -> set[str]: + """The `server/code/app/index/` modules a request runs: those the code and memory + apps import from outside the package, except the ingest pass.""" + imported = set(_ALSO_SCANNED) + for rel, tree in _trees().items(): + if not rel.startswith(_INDEX): + imported |= _index_modules_imported(tree) + return {f"{_INDEX}{m}.py" for m in imported - _INGEST_PASS} + + def _unnoted() -> list[str]: """`path::enclosing.qualname::ordinal` of each broad handler that notes nothing, the ordinal counting the broad handlers of that function in source order; and `path::enclosing.qualname::gather::ordinal` of each exception branch over a `return_exceptions=True` result that notes nothing, counted the same way.""" out: list[str] = [] - for d in _DIRS: - for path in sorted((REPO_ROOT / d).rglob("*.py")): - rel = str(path.relative_to(REPO_ROOT)) - if rel.startswith(_EXCLUDED) and rel not in _INCLUDED: - continue - counts: dict[str, int] = {} - tree = ast.parse(path.read_text()) - helpers = _noting_helpers(tree) - - def visit( - node: ast.AST, - qual: str, - rel: str = rel, - counts: dict = counts, - helpers: set[str] = helpers, - ) -> None: - for child in ast.iter_child_nodes(node): - if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): - q = f"{qual}.{child.name}" if qual else child.name - for i, noted in enumerate(_gather_fallbacks(child, helpers), 1): - if not noted: - out.append(f"{rel}::{q}::gather::{i}") - visit(child, q) - continue - if isinstance(child, ast.ExceptHandler) and _broad(child): - q = qual or "" - counts[q] = counts.get(q, 0) + 1 - if not _notes(child, helpers): - out.append(f"{rel}::{q}::{counts[q]}") - visit(child, qual) - - visit(tree, "") + scanned_index = _scanned_index_modules() + for rel, tree in _trees().items(): + if rel.startswith(_INDEX) and rel not in scanned_index: + continue + counts: dict[str, int] = {} + helpers = _noting_helpers(tree) + + def visit( + node: ast.AST, + qual: str, + rel: str = rel, + counts: dict = counts, + helpers: set[str] = helpers, + ) -> None: + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + q = f"{qual}.{child.name}" if qual else child.name + for i, noted in enumerate(_gather_fallbacks(child, helpers), 1): + if not noted: + out.append(f"{rel}::{q}::gather::{i}") + visit(child, q) + continue + if isinstance(child, ast.ExceptHandler) and _broad(child): + q = qual or "" + counts[q] = counts.get(q, 0) + 1 + if not _notes(child, helpers): + out.append(f"{rel}::{q}::{counts[q]}") + visit(child, qual) + + visit(tree, "") return out diff --git a/tests/unit/test_loom_search_tracker_general.py b/tests/unit/test_loom_search_tracker_general.py index 7ffdb22d4d4..cf876dbb2d3 100644 --- a/tests/unit/test_loom_search_tracker_general.py +++ b/tests/unit/test_loom_search_tracker_general.py @@ -231,7 +231,11 @@ async def test_preflight_consumes_the_same_execution_budget(trackers: AsyncMock) plan = await leg.prepare_tracker_search("retention", org="o") assert plan is not None expired = replace(plan, deadline=asyncio.get_running_loop().time() - 1) - assert await leg.tracker_leg("retention", plan=expired) is None + from server.observability import degradations + + with degradations.unit(): + assert await leg.tracker_leg("retention", plan=expired) is None + assert degradations.current() == ["loom_search: tracker_dropped (TimeoutError)"] trackers.assert_not_awaited() diff --git a/tests/unit/test_memory_append_batch.py b/tests/unit/test_memory_append_batch.py index cf30ad4693b..ce6d2496fcb 100644 --- a/tests/unit/test_memory_append_batch.py +++ b/tests/unit/test_memory_append_batch.py @@ -13,6 +13,7 @@ from server.core import idempotency, pg_lease from server.core.errors import BackendUnavailableError, NotFoundError, ValidationError +from server.core.pg import PostgresUnavailableError from server.memory import store as memory_repo from server.memory.api.models_bulk import MemoryAppendBatchInput from server.memory.app import blacklist_guard, bulk_rows, bulk_set @@ -256,6 +257,19 @@ async def test_unverifiable_freshness_never_becomes_a_first_write(authority: _Au assert authority.rows == {} +@pytest.mark.asyncio +async def test_a_coded_store_failure_refuses_the_append_with_its_own_code( + authority: _Authority, +) -> None: + authority.lookup_error = PostgresUnavailableError("authority down") + + with pytest.raises(PostgresUnavailableError, match="authority down"): + await bulk_set.handle_memory_append_batch(_input(("first", "hello"))) + + assert authority.commit_attempts == 0 + assert authority.rows == {} + + @pytest.mark.asyncio @pytest.mark.parametrize("tombstoned", [False, True]) async def test_a_head_appearing_at_locked_admission_is_not_overwritten( diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index c0e15b1d687..6c00bbf0682 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -61,6 +61,31 @@ async def _slow(cfg: Any) -> str: assert await mirrors.history_dir(cfg) == (cfg.git_dir, "") +@pytest.mark.asyncio +async def test_a_read_whose_clone_failed_names_it_and_one_still_cloning_does_not( + monkeypatch, tmp_path +) -> None: + from server.observability import degradations + + fail = asyncio.Event() + + async def _failed(cfg: Any) -> str: + await fail.wait() + return "git clone failed (exit 128)" + + monkeypatch.setattr(bootstrap, "clone_and_pin", _failed) + cfg = _Cfg(str(tmp_path / "r.git")) + with degradations.unit(): + assert await mirrors.history_dir(cfg) == ("", "no_git_mirror: cloning o/code-r") + assert degradations.current() == [] + fail.set() + await bootstrap._MIRROR_JOBS[("clone", cfg.git_dir)][0] + with degradations.unit(): + _, gap = await mirrors.history_dir(cfg) + assert gap.startswith("no_git_mirror: o/code-r: clone failed (git clone failed") + assert degradations.current() == ["git_mirror: clone_failed (git clone failed (exit 128))"] + + @pytest.mark.asyncio async def test_without_the_sandbox_a_read_clones_a_self_registered_mirror_only_with_the_git_waiver( monkeypatch, tmp_path diff --git a/tests/unit/test_pending_evidence.py b/tests/unit/test_pending_evidence.py index 9d1f614e5f7..4a8f8939627 100644 --- a/tests/unit/test_pending_evidence.py +++ b/tests/unit/test_pending_evidence.py @@ -57,6 +57,12 @@ def test_rank_picks_the_turns_that_share_words_with_the_question() -> None: with degradations.unit(): assert P.rank_pending_turns("cache cap", [{"queue_id": "x", "payload": "{not json"}]) == [] assert degradations.current() == ["memory.ask: pending_batch_dropped (JSONDecodeError)"] + for payload in ('{"messages": "hi"}', "[1]"): + with degradations.unit(): + assert P.rank_pending_turns("cache cap", [{"queue_id": "x", "payload": payload}]) == [] + assert degradations.current() == [ + "memory.ask: pending_batch_dropped (messages is not a list)" + ] def test_hits_carry_key_source_session_and_label() -> None: diff --git a/tests/unit/test_tracker_multi_binding.py b/tests/unit/test_tracker_multi_binding.py index 82dab12c65a..e5959a437f8 100644 --- a/tests/unit/test_tracker_multi_binding.py +++ b/tests/unit/test_tracker_multi_binding.py @@ -262,6 +262,34 @@ async def _scan(src, org, t, plan, **_): assert got == [{"pr_number": 9, "tracker_namespace": DESK}] +@pytest.mark.asyncio +async def test_bisect_names_a_linked_tracker_whose_scan_failed(wired, monkeypatch) -> None: + from server.code.app import bisect_scan + from server.observability import degradations + + async def _scan(src, org, t, plan, **_): + raise TimeoutError + + monkeypatch.setattr(bisect_scan, "_scan", _scan) + monkeypatch.setattr( + "server.tracker.store.source.TrackerSource", lambda org, t: SimpleNamespace() + ) + with degradations.unit(): + got = await bisect_scan._linked_scan( + ORG, + CODE, + QA, + bisect_scan.ScanPlan(paths=["a.cpp"]), + set(), + frames=[], + patterns=[], + weights={}, + limit=5, + ) + assert degradations.current() == ["tracker: linked_tracker_dropped (TimeoutError)"] + assert got == [] + + @pytest.mark.asyncio async def test_memory_ask_searches_every_tracker_for_a_component_question( wired, monkeypatch From abdd205d0ea47143cdaad83d8afec577ce6e3a6b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 23:13:59 +0530 Subject: [PATCH 23/47] A PR overlay whose re-parse of a kept file raised says so Facts kept from an earlier parse hold no tree, so the overlay's edges parse the file again. A parse that raised there returned no edges with nothing counted, so code.callers and code.impact served fewer overlay edges with no overlay_note, and the overlay was cached whole. It now counts as unread, as in _parsed_facts, and _note_left_out lists the unread files in degraded too (code_index: overlay_files_unread), which keeps the overlay out of its cache. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/index/pr_overlay.py | 5 +++-- tests/unit/degraded_unnoted.txt | 4 ++-- tests/unit/test_pr_post_image.py | 34 +++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/server/code/app/index/pr_overlay.py b/server/code/app/index/pr_overlay.py index 70ce6d34693..d0c59053fb0 100644 --- a/server/code/app/index/pr_overlay.py +++ b/server/code/app/index/pr_overlay.py @@ -703,8 +703,8 @@ def _file_edges( if pf is None: pf, err = parse_for_ingest(path, source) timed_out = parse_timed_out(err) - if pf is None or timed_out: - return _Edges((), timed_out) + if pf is None or err: # a parse that raised binds nothing, as in `_parsed_facts` + return _Edges((), timed_out, unread=bool(err) and not timed_out) try: edges, _misses = extract_edges_and_misses(pf, table, None) except Exception as e: # noqa: BLE001 — per file, never the overlay @@ -814,6 +814,7 @@ def _note_left_out(ov: PrOverlay, timed_out: int, unread: int) -> None: parts.append(f"{timed_out} changed file(s) whose parse ran past its limits") if unread: parts.append(f"{unread} changed file(s) whose parse or call extraction failed") + degradations.partial("code_index", "overlay_files_unread", f"{unread} changed file(s)") if ov.unreached: parts.append( f"{ov.unreached} changed file(s) {NOT_REACHED}: the request's parse time was spent" diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 98151f0ef0f..b6628cfede3 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -45,9 +45,9 @@ server/code/app/index/packs.py::_co_change_gaps::1 server/code/app/index/packs.py::_envelope_line::1 logged_only_nonanswer # the ingest's PR pack server/code/app/index/packs.py::_reviews_for::1 logged_only_nonanswer # the ingest's PR pack server/code/app/index/packs.py::_tracker_lines::1 logged_only_nonanswer # the ingest's PR pack -server/code/app/index/pr_overlay.py::_file_edges::1 noted_by_caller # _parse_post_image counts the file in overlay_note +server/code/app/index/pr_overlay.py::_file_edges::1 noted_by_caller # _note_left_out notes code_index: overlay_files_unread and counts it in overlay_note server/code/app/index/pr_overlay.py::_index_head::1 cache_fallback # the names are read, nothing kept -server/code/app/index/pr_overlay.py::_parsed_facts::1 noted_by_caller # _parse_post_image counts the file in overlay_note +server/code/app/index/pr_overlay.py::_parsed_facts::1 noted_by_caller # _note_left_out notes code_index: overlay_files_unread and counts it in overlay_note server/code/app/index/pr_overlay.py::_state_generation::1 cache_fallback # the names are read, nothing kept server/code/app/index/registry.py::ensure_registered::1 write server/code/app/index/retire.py::refresh_code_views::1 write diff --git a/tests/unit/test_pr_post_image.py b/tests/unit/test_pr_post_image.py index b0fa86384f3..c0347d0c1e5 100644 --- a/tests/unit/test_pr_post_image.py +++ b/tests/unit/test_pr_post_image.py @@ -451,6 +451,40 @@ async def read(path: str) -> bytes: assert ov.note == "1 changed file(s) whose parse ran past its limits" and ov.unreached == 0 +def test_a_kept_files_reparse_that_raised_is_counted_and_noted( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Facts kept from an earlier parse hold no tree, so the edges parse the file again; a + parse that raises there binds no edge, and the overlay says so.""" + from server.code.app.index import ingest_parse + from server.code.domain.extract.treesitter import ParsedFile + from server.observability import degradations + + async def read(path: str) -> bytes: + return POST.encode() + + async def parse() -> tuple[po.PrOverlay, list[str]]: + ov = po.PrOverlay(pr_number=7, changed_paths=[PATH], hunks={PATH: [(1, 20)]}) + with degradations.unit(): + await po._parse_post_image( + _Repo(), "acme", "code-ch", ov, read=read, path_prefixes=(), table_at=None + ) + return ov, degradations.current() + + first, notes = asyncio.run(parse()) + assert first.edges and first.note == "" and notes == [] + po._FILE_EDGES.clear() + + def raised(path: str, source: bytes) -> tuple[ParsedFile, str]: + return ParsedFile(path=path, lang="cpp", source=source), "parse: RuntimeError: boom" + + monkeypatch.setattr(ingest_parse, "parse_for_ingest", raised) + second, notes = asyncio.run(parse()) + assert second.symbols and second.edges == [] + assert second.note == "1 changed file(s) whose parse or call extraction failed" + assert notes == ["code_index: overlay_files_unread (1 changed file(s))"] + + def test_an_open_brief_over_a_partial_overlay_is_served_unstored( monkeypatch: pytest.MonkeyPatch, ) -> None: From 8d641d5d0cf984c520c7448ffe3212fc1a30ffc3 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Thu, 3 Dec 2026 23:20:01 +0530 Subject: [PATCH 24/47] List the calibration worker's key check in the degraded allowlist The merge brings get_namespace_calibration_stored_key, a broad handler only the code_calibration worker reaches: logged_only_nonanswer. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- tests/unit/degraded_unnoted.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index b6628cfede3..ccf4206a676 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -188,6 +188,7 @@ server/memory/app/embedder_calibration.py::_read_shared::1 server/memory/app/embedder_calibration.py::_served_model::1 settings server/memory/app/embedder_calibration.py::calibrate_embedder::1 logged_only_nonanswer server/memory/app/embedder_calibration.py::calibrate_embedder::2 logged_only_nonanswer +server/memory/app/embedder_calibration.py::get_namespace_calibration_stored_key::1 logged_only_nonanswer # the code_calibration worker's key check server/memory/app/embedder_calibration.py::publish_calibration::1 write server/memory/app/embedder_calibration.py::refresh_shared::1 logged_only_nonanswer server/memory/app/entity_resolution.py::resolve_entities_for_write::1 write From ebb5d2e2e429244e09a9b187b177ad01cd539895 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 02:08:48 +0530 Subject: [PATCH 25/47] Scan the knowledge, tracker and LLM fallbacks and the timeout cuts for degraded The degraded scan now reads server/knowledge/app, server/tracker/app and server/llm beside the code and memory apps, and every except TimeoutError that does not raise (listed as path::function::timeout::N). Of server/code/app/index/ it scans the modules the apps import and those they import in turn, stopping at the ingest pass and the per-file ingest only it calls, in place of a hand-kept extra. Two categories join the list: deadline, for a timeout of the caller's own budget, and fail_closed, for a security or privacy check that cannot be read and refuses as it would on a refusal. The sites it found note their fallback: the model fallback's answer (llm: fallback_model_answered), the conversation search's substring fallback, each private mirror leg that is dropped (with no reason, as the document-sources rule allows), the knowledge search's lexical, rerank, span, live and repository-document legs, the duplicate check's legs, links, rerank and fit, the tracker facts, test signal, source views and patch history, the literal definitions and HyDE leg of code.search cut by their fixed bounds, the bisect stages cut by theirs, the term leg and the read-your-writes re-read, and a branch's code state. Review found more: a failed usage-totals read, a failed identity-dedup read, a present mirror whose fetch failed, and an ops.incidents call whose tenancy check refuses, which now answers requests: unread where the op failed. The overlay cache gate has its test, and the reference lists the overlay's per-file caches. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/http-api.md | 3 + server/code/app/bisect_fix.py | 15 ++- server/code/app/index/bootstrap.py | 7 +- server/code/app/index/mirrors.py | 9 +- server/code/app/index/task_pack.py | 2 +- server/code/app/search/definitions.py | 4 +- server/code/app/search_legs.py | 9 ++ server/insights/app/incidents.py | 14 ++- server/knowledge/app/bm25.py | 2 + server/knowledge/app/conversations.py | 5 +- server/knowledge/app/extractors.py | 2 + server/knowledge/app/inspect.py | 6 + server/knowledge/app/knowledge_search.py | 5 +- server/knowledge/app/live_search.py | 3 + server/knowledge/app/repo_docs.py | 5 + server/knowledge/app/source_access.py | 3 + server/knowledge/app/source_corpus.py | 2 + server/knowledge/app/source_documents.py | 5 + server/knowledge/app/source_listing.py | 7 ++ server/knowledge/app/source_passages.py | 2 + server/knowledge/app/source_search.py | 3 + server/knowledge/app/source_search_passes.py | 3 + server/knowledge/app/source_titles.py | 2 + server/knowledge/app/tune.py | 2 + server/llm/fallback.py | 5 +- server/memory/app/bulk_set.py | 4 +- server/memory/app/code_plane_reads.py | 5 +- server/memory/app/search/consistency.py | 3 +- server/memory/app/search/term_leg.py | 6 +- server/memory/store/reads.py | 11 +- server/tracker/app/ask_route.py | 1 + server/tracker/app/binding.py | 2 + server/tracker/app/contract.py | 2 + server/tracker/app/dupcheck.py | 14 ++- server/tracker/app/dupcheck_answer.py | 4 + server/tracker/app/dupcheck_candidates.py | 3 + server/tracker/app/dupcheck_fit.py | 2 + server/tracker/app/dupcheck_links.py | 5 +- server/tracker/app/facts.py | 3 + server/tracker/app/handlers.py | 3 + server/tracker/app/links.py | 2 + server/tracker/app/patch_history.py | 24 ++-- server/tracker/app/registry_sources.py | 5 +- server/tracker/app/similar.py | 5 +- server/tracker/app/sources.py | 3 + server/tracker/app/test_signal.py | 4 + tests/unit/degraded_unnoted.txt | 114 +++++++++++++++++- tests/unit/test_bulk_identity_dedup.py | 2 + tests/unit/test_code_bisect_deadline.py | 54 ++++++++- tests/unit/test_code_search_deadline.py | 41 +++++-- .../unit/test_conversation_search_service.py | 33 +++++ tests/unit/test_degraded_unnoted.py | 85 ++++++++++--- tests/unit/test_llm_fallback.py | 4 + tests/unit/test_memory_repo.py | 25 ++++ tests/unit/test_mirrors.py | 34 ++++++ tests/unit/test_ops_incidents.py | 14 +++ tests/unit/test_pr_post_image.py | 63 ++++++++++ 57 files changed, 629 insertions(+), 76 deletions(-) diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index e0d06e0fcef..a839f5843fa 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -343,6 +343,9 @@ error's kind only; the full text is in the server log. `LOOM_MEMORY_NAMESPACE_HEALTH_FAILURE_TTL_S`: the pending-extraction count and namespace health; - `LOOM_CODE_FORK_UPSTREAM_MISS_TTL_S`: a fork lookup of `code.repos` that failed; + - `LOOM_CODE_PR_OVERLAY_FILE_TTL_S`: the PR overlay's per-file parse and edge results, + including a parse or call extraction that failed, which each overlay built from them + names; - 5 seconds: each of `ops.incidents`' ClickHouse sources. - A later page of `code.search`, `code.grep` or `memory.search` names the entries of the run that ranked its pool. What each page reads for itself (the risk block, context diff --git a/server/code/app/bisect_fix.py b/server/code/app/bisect_fix.py index b053a5e0b95..237816cf9ef 100644 --- a/server/code/app/bisect_fix.py +++ b/server/code/app/bisect_fix.py @@ -149,7 +149,8 @@ async def _dupcheck_fix(task: Any, started: float | None = None) -> dict[str, An """The matched issue's fix, or {} when there is none. The check started at the top of the call; this waits for what is left of its budget (`code_bisect_dupcheck_timeout_s` from `started`). Past it the - bisect answers with the fusion alone and says so (`status: timeout`); any + bisect answers with the fusion alone and says so (`status: timeout`, and in + `degraded`; `status: deadline` when the caller's deadline ran out first); any error answers as it would without the check.""" if task is None: return {} @@ -157,9 +158,10 @@ async def _dupcheck_fix(task: Any, started: float | None = None) -> dict[str, An left = budget - (time.monotonic() - started) if started is not None else budget try: return dict(await asyncio.wait_for(task, timeout=max(0.05, _budget(left)))) - except TimeoutError: + except TimeoutError as e: if _expired("dupcheck"): return {"status": "deadline", "budget_s": budget} + degradations.partial("tracker", "dupcheck_fix_timed_out", e) return {"status": "timeout", "budget_s": budget} except Exception as e: # noqa: BLE001 — fail open degradations.partial("tracker", "dupcheck_fix_skipped", e) @@ -360,8 +362,13 @@ async def one(r: Any) -> tuple[Any, list[dict[str, Any]]]: asyncio.gather(*(one(r) for r in ranges)), timeout=_budget(settings.code_bisect_fix_blame_budget_s), ) - except TimeoutError: - summary["skipped"] = "deadline" if _expired("fix_blame") else "timeout" + except TimeoutError as e: + if _expired("fix_blame"): + summary["skipped"] = "deadline" + return pool, summary + # cut by `code_bisect_fix_blame_budget_s`, a fixed bound: the mirror answered slowly + degradations.partial("git_mirror", "fix_blame_timed_out", e) + summary["skipped"] = "timeout" return pool, summary except Exception as e: # noqa: BLE001 — a lever beside the scan, never the answer degradations.partial("git_mirror", "fix_blame_skipped", e) diff --git a/server/code/app/index/bootstrap.py b/server/code/app/index/bootstrap.py index b389313f2f2..7a61220dd30 100644 --- a/server/code/app/index/bootstrap.py +++ b/server/code/app/index/bootstrap.py @@ -440,9 +440,10 @@ def _current_job(key: tuple[str, str]) -> asyncio.Task[str] | None: return task -def job_state(git_dir: str) -> tuple[str, str]: - """('cloning' | 'failed' | '', reason) of this process's clone of `git_dir`.""" - task, _ = _MIRROR_JOBS.get(("clone", git_dir), (None, 0.0)) +def job_state(git_dir: str, name: str = "clone") -> tuple[str, str]: + """('cloning' | 'failed' | '', reason) of this process's `name` job (the clone, or a + fetch) of `git_dir`; 'cloning' is a job still running.""" + task, _ = _MIRROR_JOBS.get((name, git_dir), (None, 0.0)) if task is not None and not task.done(): return "cloning", "" reason = _job_failure(task) diff --git a/server/code/app/index/mirrors.py b/server/code/app/index/mirrors.py index 607faf6e53b..fc37df247f6 100644 --- a/server/code/app/index/mirrors.py +++ b/server/code/app/index/mirrors.py @@ -118,14 +118,17 @@ async def history_dir(cfg: Any, *, op: str = "", head: str = "") -> tuple[str, s ('', what the read answers instead): `NO_ENTRY_MIRROR` when the namespace has no entry (`cfg` None). A missing mirror's clone starts here; with `op` the read waits for it up to `code_mirror_clone_wait_s` or what is left of the op's budget. A present mirror that - lacks `head` serves as it is and fetches its branch in the background.""" + lacks `head` serves as it is and fetches its branch in the background; while the last + such fetch failed, the read names it (`git_mirror: fetch_failed`).""" if cfg is None: return "", NO_ENTRY_MIRROR if not history_enabled(): return "", NO_GIT_HISTORY if await asyncio.to_thread(_present, cfg): - if head: - await holds(cfg, head) + if head and not await holds(cfg, head): + state, reason = job_state(cfg.git_dir, "fetch") + if state == "failed": + degradations.partial("git_mirror", "fetch_failed", reason) return cfg.git_dir, "" if why := _absent_reason(cfg): return "", f"no_git_mirror: {cfg.label} {why}" diff --git a/server/code/app/index/task_pack.py b/server/code/app/index/task_pack.py index 893a148e3e2..3ed574b262f 100644 --- a/server/code/app/index/task_pack.py +++ b/server/code/app/index/task_pack.py @@ -256,7 +256,7 @@ def render( async def _safe(coro: Any, default: Any) -> Any: try: return await coro - except Exception as e: + except Exception as e: # a failed section takes its default, noted; the pack still serves logger.info("task pack section failed", exc_info=True) degradations.partial("code_index", "task_pack_section_dropped", e) return default diff --git a/server/code/app/search/definitions.py b/server/code/app/search/definitions.py index 53036cf59ce..fc07450b55b 100644 --- a/server/code/app/search/definitions.py +++ b/server/code/app/search/definitions.py @@ -382,10 +382,12 @@ async def _literal_leg( path_prefix=path_prefix, scope=scope, ) - except TimeoutError: + except TimeoutError as e: if not bound.expired(): raise logger.info("code.search literal lookup stopped at its bound of %g s", seconds) + if seconds >= _LITERAL_SECONDS: # the fixed bound cut it, not the request's window + degradations.partial("code_index", "literal_definitions_dropped", e) return [] return literal_definitions(literals, rows) diff --git a/server/code/app/search_legs.py b/server/code/app/search_legs.py index 46fef7de10b..41724d4429e 100644 --- a/server/code/app/search_legs.py +++ b/server/code/app/search_legs.py @@ -35,6 +35,7 @@ from typing import Any from server.core.llm_free import reads_llm_free +from server.observability import degradations from server.settings import settings # The legs whose rows the answer cannot do without; the deadline waits for @@ -141,7 +142,12 @@ def _left(cap_s: float | None = None) -> float | None: if plain: await asyncio.wait(plain, timeout=_left()) pending_model = [t for t in model if not t.done()] + # A model leg cut by `code_search_llm_leg_grace_ms` with the request's budget still + # left is a fixed-bound cut, noted; one cut by what was left is the budget working. + grace_cut = False if pending_model: + rem = _left() + grace_cut = bool(grace) and (rem is None or grace / 1000.0 < rem) await asyncio.wait(pending_model, timeout=_left(grace / 1000.0 if grace else None)) core = [tasks[n] for n in names if n in CORE_LEGS] if core and not any(t.done() for t in core): @@ -157,6 +163,9 @@ def _left(cap_s: float | None = None) -> float | None: for n in dropped: with contextlib.suppress(asyncio.CancelledError, Exception): await tasks[n] + for n in dropped: + if grace_cut and n in LLM_LEGS: + degradations.partial("llm", f"{n}_leg_dropped", "past its grace") if dropped: result.legs_timed_out = dropped result.epistemic = "partial" diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index c4193f1a177..a7a6ca73bb3 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -22,7 +22,7 @@ from datetime import UTC, datetime from typing import Any -from server.core.errors import caller_text +from server.core.errors import LoomServerError, caller_text, error_kind from server.insights.api.models_ops import ( OpsIncident, OpsIncidentsInput, @@ -164,8 +164,10 @@ async def _reads_org_calls(org: str) -> RequestsRead: hidden from it; with auth off, the install's caller. The counts include calls to collections it cannot read, which they do not name. Fails closed: a member, a narrowed or pinned token, a delegated one (never an org admin), or no token where one - is required, is `not_permitted`; an unknown restricted set, or a restricted - namespace whose grant could not be read, is `unread`.""" + is required, is `not_permitted`; an unknown restricted set, a restricted + namespace whose grant could not be read, or an org whose tenancy a platform + administrator's repository read could not check (`tenancy.ensure_held`: a cell that + cannot tell, or another cell's org), is `unread`.""" from server.auth.context import current_auth, reads_every_namespace, restricted_hidden from server.identity.app.request_scope import request_narrowed @@ -174,7 +176,11 @@ async def _reads_org_calls(org: str) -> RequestsRead: return "not_permitted" if settings.auth_actually_required() else "read" if not reads_every_namespace(auth, org) or request_narrowed(): return "not_permitted" - hidden, unverified = await restricted_hidden(org) + try: + hidden, unverified = await restricted_hidden(org) + except LoomServerError as e: + degradations.partial("ops.incidents", "requests_unread", error_kind(e)) + return "unread" if hidden == ["*"]: # the restricted set is unread degradations.partial("ops.incidents", "requests_unread", "ClassificationUnavailable") return "unread" diff --git a/server/knowledge/app/bm25.py b/server/knowledge/app/bm25.py index 00e52cbcc20..8d2c3eb6fa7 100644 --- a/server/knowledge/app/bm25.py +++ b/server/knowledge/app/bm25.py @@ -19,6 +19,7 @@ from server.core import bm25 from server.knowledge.domain.live_chunks import LIVE_CHUNK_SQL +from server.observability import degradations from server.settings import settings @@ -134,6 +135,7 @@ async def lexical_stats( ch, org=org, namespaces=namespaces, tokens=tokens, n_docs=n_docs ) except Exception as e: # noqa: BLE001 — stats are an optimisation of ranking + degradations.partial("knowledge", "lexical_leg_dropped", e) bm25.record_stats_failure("knowledge", e) return 0.0, [] diff --git a/server/knowledge/app/conversations.py b/server/knowledge/app/conversations.py index e1d5d3ab786..7cc00254019 100644 --- a/server/knowledge/app/conversations.py +++ b/server/knowledge/app/conversations.py @@ -75,6 +75,7 @@ reads_high, without_high, ) +from server.observability import degradations from server.observability.budget_shape import note_budget_shape from server.observability.genai import staged from server.observability.otel import traced @@ -905,7 +906,8 @@ async def _search_conversations( Embed the query, rank `loom.conversation_embeddings` by cosine distance with recency tiebreak. Falls back to substring search when - the embedder is unavailable so the endpoint never 5xx's. + the embedder is unavailable so the endpoint never 5xx's, and names it in + `degraded`. """ import asyncio @@ -918,6 +920,7 @@ async def _search_conversations( query_vec = await embedder.embed(input.query[:EMBEDDED_EXCERPT_CHARS]) except Exception as e: # noqa: BLE001 — embed failure falls back to substring search log.warning("conversation embed query failed; falling back to substring: %s", e) + degradations.partial("embedder", "conversation_substring_fallback", e) query_vec = None scope = _conversation_read_scope() diff --git a/server/knowledge/app/extractors.py b/server/knowledge/app/extractors.py index 701019ac5a4..eac808d1c8b 100644 --- a/server/knowledge/app/extractors.py +++ b/server/knowledge/app/extractors.py @@ -34,6 +34,7 @@ parse_artifact, refuse_past_source, ) +from server.observability import degradations from server.settings import settings logger = logging.getLogger("loom.knowledge.extractors") @@ -222,6 +223,7 @@ async def _formats_within(url: str, timeout_s: float) -> frozenset[str] | None: async with asyncio.timeout(timeout_s): return (await capabilities(url)).formats except (ExtractorUnavailable, TimeoutError) as e: + degradations.partial("knowledge", "extractor_formats_unread", e) logger.warning("document extractor %s: %s", _origin(url), str(e) or "timed out") return None diff --git a/server/knowledge/app/inspect.py b/server/knowledge/app/inspect.py index 3dd9cd41bda..d5ea41bebdf 100644 --- a/server/knowledge/app/inspect.py +++ b/server/knowledge/app/inspect.py @@ -76,6 +76,7 @@ from server.knowledge.store import pg_documents from server.memory.app.query import document_decision_tally from server.memory.app.search import pg_validation +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -510,6 +511,9 @@ async def guarded[T](self, section: str, read: Callable[[], Awaitable[T]], defau except BACKEND_NOT_NOW: raise except Exception as exc: # noqa: BLE001 — a read-only report; one section must not sink the rest + degradations.partial( + "knowledge", "inspect_section_skipped", f"{section}: {type(exc).__name__}" + ) log.warning("knowledge.inspect %s skipped: %s", section, exc) self.skipped.append(f"{section}: {type(exc).__name__}") return default @@ -555,6 +559,7 @@ async def unprojected_jobs(self) -> None: except BACKEND_NOT_NOW: raise except Exception as exc: # noqa: BLE001 — a read-only report; the job sections stand as read + degradations.partial("knowledge", "ingestion_jobs_uncompared", exc) log.warning("knowledge.inspect %s skipped: %s", INGESTIONS_PROJECTION, exc) self.jobs_not_compared(type(exc).__name__) return @@ -863,6 +868,7 @@ async def served(self, rows: list[dict[str, Any]]) -> list[dict[str, Any]]: except BACKEND_NOT_NOW: raise except Exception as exc: # noqa: BLE001 — a read-only report; the listing stands as read + degradations.partial("knowledge", "listed_heads_unchecked", exc) log.warning("knowledge.inspect listed.heads skipped: %s", exc) self.skipped.append(f"{LISTED_HEADS}: {type(exc).__name__}") self.documents_whole = False diff --git a/server/knowledge/app/knowledge_search.py b/server/knowledge/app/knowledge_search.py index 6d40df5db0c..03c732e39b0 100644 --- a/server/knowledge/app/knowledge_search.py +++ b/server/knowledge/app/knowledge_search.py @@ -30,6 +30,7 @@ from server.knowledge.app.source_search_proofs import SearchProofs from server.knowledge.domain.chunking import embedding_text from server.memory.app.log_once import LogOnce +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -378,8 +379,9 @@ async def _rerank( candidates=candidates, excerpt_chars=chars, ) - except TimeoutError: + except TimeoutError as e: # The search's own deadline, not the provider's failure: no health record. + degradations.partial("rerank", "input_order_kept", e) log.info("knowledge.search rerank cut at %ss", settings.knowledge_search_rerank_timeout_s) return hits, False # The service hands back its input on a failure, or an order it could not read in @@ -618,6 +620,7 @@ async def _embed_many(texts: list[str]) -> list[list[float]]: except LostCorpus: raise except Exception as e: # noqa: BLE001 — the chunk is still the answer + degradations.partial("knowledge", "spans_unnarrowed", e) log.debug("knowledge.search span narrowing skipped: %s", e) diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index bfb6e75fd6c..0f81f68f090 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -16,6 +16,7 @@ from server.knowledge.app import connected_accounts, live_provider_search, session_admission from server.knowledge.domain.sources import MIRRORED_ACCESS from server.knowledge.store import sources as source_store +from server.observability import degradations from server.settings import settings @@ -130,6 +131,7 @@ async def native( break return LiveResult(tuple(contributions), deadline) if contributions else None except Exception: # noqa: BLE001 — optional private search never exposes account/provider detail + degradations.partial("knowledge", "live_results_dropped") return None @@ -146,4 +148,5 @@ async def publish(result: LiveResult | None) -> LiveResult | None: return None return result except Exception: # noqa: BLE001 — expired or revoked live results leave indexed search intact + degradations.partial("knowledge", "live_results_dropped") return None diff --git a/server/knowledge/app/repo_docs.py b/server/knowledge/app/repo_docs.py index 1339e187d75..fafa24b422f 100644 --- a/server/knowledge/app/repo_docs.py +++ b/server/knowledge/app/repo_docs.py @@ -28,6 +28,7 @@ _SearchHit, ) from server.knowledge.app import source_publication +from server.observability import degradations from server.settings import settings log = logging.getLogger("loom.repo_docs") @@ -114,6 +115,7 @@ async def _renew_extra(self, *, ordinary: bool = False) -> None: else: await extra.current() except Exception: # noqa: BLE001 — an additive renewal failure leaves the base search intact + degradations.partial("knowledge", "repo_docs_dropped") self._lost |= extra.lost self.extra = None log.info("repo docs search did not answer") @@ -209,6 +211,7 @@ async def resolve_repo_search( ) ) except Exception: # noqa: BLE001 — an additive scope failure leaves the base search intact + degradations.partial("knowledge", "repo_docs_dropped") log.info("repo docs search did not answer") return RepoSearchRequest(base, extra, repo_namespace, deadline) @@ -225,6 +228,7 @@ async def search_repo_docs(request: RepoSearchRequest, plan: ReadPlan) -> Checke async with asyncio.timeout_at(request.extra_deadline): return await run_checked_search(request.extra, plan) except Exception: # noqa: BLE001 — a failed additive search cannot expose private details + degradations.partial("knowledge", "repo_docs_dropped") log.info("repo docs search did not answer") return None @@ -353,6 +357,7 @@ async def list_repo_docs( if checked.proofs is not None and not checked.proofs.fresh(): await checked.ordinary() except Exception: # noqa: BLE001 — a failed additive listing cannot expose private details + degradations.partial("knowledge", "repo_docs_unlisted") log.info("repo docs listing did not answer") return RepoListing(ns, []) docs = [ diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index e0a5137900c..e3ca0d450a8 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -24,6 +24,7 @@ from server.knowledge.domain.sources import KnowledgeSource from server.knowledge.store import mirrors as mirrors_repo from server.knowledge.store import source_access as store +from server.observability import degradations from server.operations.base import Role from server.settings import settings @@ -137,6 +138,7 @@ async def check( with sequential_reads(), private_work(): return await self._check(candidates, chunks=chunks) except Exception: # noqa: BLE001 — a failed candidate read must disclose no partial leg + degradations.partial("knowledge", "mirror_leg_dropped") self.failed = True return [] @@ -301,6 +303,7 @@ async def prepare(org: str, namespaces: list[str]) -> ReadPlan: ) ) except Exception: # noqa: BLE001 — unreadable unconditional evidence must fail closed uniformly + degradations.partial("knowledge", "mirror_leg_dropped") plan.marked = plan.unread = True request_work.mark_mirrored(unread=True) return plan diff --git a/server/knowledge/app/source_corpus.py b/server/knowledge/app/source_corpus.py index a80bb175c62..89b4037502c 100644 --- a/server/knowledge/app/source_corpus.py +++ b/server/knowledge/app/source_corpus.py @@ -13,6 +13,7 @@ from server.knowledge.app.source_access import AccessEvidence, Admitted, ReadPlan from server.knowledge.domain.chunk_metadata import read_structure from server.memory.domain.corpus_synthesis import CorpusChunk +from server.observability import degradations from server.observability.genai import current_stage, llm_stage @@ -206,6 +207,7 @@ async def load( try: document = await _mirror(plan, namespace, uri, model) except Exception: # noqa: BLE001 — a conditional mirror failure cannot publish a partial corpus + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True document = _Document([]) by_uri[uri] = document diff --git a/server/knowledge/app/source_documents.py b/server/knowledge/app/source_documents.py index 25dececb3b6..786d49a0cda 100644 --- a/server/knowledge/app/source_documents.py +++ b/server/knowledge/app/source_documents.py @@ -15,6 +15,7 @@ from server.knowledge.store import source_access as evidence from server.knowledge.store import source_documents as store from server.knowledge.store.documents import DocumentRow +from server.observability import degradations @dataclass(frozen=True) @@ -42,6 +43,7 @@ async def _discover(plan: ReadPlan, pairs: list[tuple[str, str]]) -> list[dict[s wanted.remove(key) out.append({"namespace": key[0], "source_uri": key[1]}) except Exception: # noqa: BLE001 — every selected discovery read must fail closed uniformly + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = plan.unread = True request_work.mark_mirrored(unread=True) return out @@ -70,6 +72,7 @@ async def refresh(plan: ReadPlan, document: CheckedDocument) -> CheckedDocument if _same(document.row, plan, item) and plan.current(item): return CheckedDocument(item, document.row) except Exception: # noqa: BLE001 — conditional revalidation cannot authorize an open copy + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return None @@ -118,6 +121,7 @@ async def get(plan: ReadPlan, namespace: str, source_uri: str) -> CheckedDocumen if refreshed is not None: return refreshed except Exception: # noqa: BLE001 — conditional content or permission failure invalidates all copies + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return None @@ -170,5 +174,6 @@ async def chunks(plan: ReadPlan, document: CheckedDocument, *, model: str) -> li and plan.current(proof[_chunk_key(item.admitted.candidate)]) ] except Exception: # noqa: BLE001 — conditional chunk failure invalidates the entire document + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return None diff --git a/server/knowledge/app/source_listing.py b/server/knowledge/app/source_listing.py index 61694166f40..0af43ce46c6 100644 --- a/server/knowledge/app/source_listing.py +++ b/server/knowledge/app/source_listing.py @@ -18,6 +18,7 @@ from server.knowledge.domain.access_list import candidate_keys from server.knowledge.domain.document_access import public_tags from server.knowledge.store import source_documents as store +from server.observability import degradations if TYPE_CHECKING: from server.knowledge.store.documents import DocumentListRow @@ -82,6 +83,7 @@ async def stage(self, item: Admitted | None) -> None: if item is not None and _matches(item, self.input, self.cursor): self.pending.append(item) except Exception: # noqa: BLE001 — invalid admitted metadata is a conditional leg failure + degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True if len(self.pending) == 64: await self.flush() @@ -106,6 +108,7 @@ async def flush(self) -> None: if len(self.heap) > self.input.limit + 1: heapq.heappop(self.heap) except Exception: # noqa: BLE001 — conditional shadow failure invalidates the mirror leg + degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True async def take(self, batch: list[dict[str, Any]]) -> None: @@ -120,6 +123,7 @@ async def take(self, batch: list[dict[str, Any]]) -> None: raise ValueError("unexpected list admission identity") admitted[key] = proof except Exception: # noqa: BLE001 — candidate checks cannot change unconditional discovery + degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True for row in batch: namespace, uri = row["namespace"], row["source_uri"] @@ -149,6 +153,7 @@ async def take(self, batch: list[dict[str, Any]]) -> None: ): self.winner = item except Exception: # noqa: BLE001 — invalid admitted metadata cannot affect unread status + degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True @@ -193,6 +198,7 @@ async def select( await selected.stage(selected.winner) await selected.flush() except Exception: # noqa: BLE001 — fixed metadata discovery failure discloses no partial list + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = plan.unread = True request_work.mark_mirrored(unread=True) return ( @@ -304,5 +310,6 @@ async def collect( except LostCorpus: pass except Exception: # noqa: BLE001 — selected fields, counts and final proofs fail closed together + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return Listing([], ListProofs(plan, input.include_superseded, ())) diff --git a/server/knowledge/app/source_passages.py b/server/knowledge/app/source_passages.py index 56005f50fbb..386f8aa880d 100644 --- a/server/knowledge/app/source_passages.py +++ b/server/knowledge/app/source_passages.py @@ -16,6 +16,7 @@ from server.knowledge.app.source_search_proofs import SearchProofs from server.memory.app.agent_rules import request_rule_agent, served_hits from server.memory.domain.assistant_rules import hits_to_ask +from server.observability import degradations @dataclass @@ -120,6 +121,7 @@ async def current(self) -> list[_SearchHit]: try: wide = (await self._wide.current()).results except Exception: # noqa: BLE001 — discard mixed work if an optional renewal fails + degradations.partial("knowledge", "mirror_leg_dropped") return await self._fallback() if not self.fresh(): return await self._fallback() diff --git a/server/knowledge/app/source_search.py b/server/knowledge/app/source_search.py index d55bb33795f..20a727c6009 100644 --- a/server/knowledge/app/source_search.py +++ b/server/knowledge/app/source_search.py @@ -13,6 +13,7 @@ from server.knowledge.app.source_access import Admitted, ReadPlan from server.knowledge.domain.access_list import candidate_keys from server.knowledge.store import source_candidates as store +from server.observability import degradations @dataclass(frozen=True) @@ -91,6 +92,7 @@ async def take(batch: list[dict[str, Any]]) -> None: if batch and len(out) < limit: await take(batch) except Exception: # noqa: BLE001 — an unconditional discovery failure invalidates every mirror leg + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = plan.unread = True request_work.mark_mirrored(unread=True) return [] if plan.failed or plan.unread else out @@ -163,6 +165,7 @@ async def hydrate( for leg, pool in checked.items() } except Exception: # noqa: BLE001 — conditional hydration must not expose partial mirror results + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return {} diff --git a/server/knowledge/app/source_search_passes.py b/server/knowledge/app/source_search_passes.py index c615c8033fb..e9fbaef2aa4 100644 --- a/server/knowledge/app/source_search_passes.py +++ b/server/knowledge/app/source_search_passes.py @@ -12,6 +12,7 @@ from server.knowledge.app.source_search import Hydrated, _chunk_key, discover, hydrate, recheck from server.knowledge.app.source_search_proofs import SearchProofs from server.knowledge.store.source_candidates import ChunkKey, Leg +from server.observability import degradations @dataclass @@ -96,6 +97,7 @@ async def collect( ) mirrored = await hydrate(self.plan, candidates, model=query.embedding_model) except Exception: # noqa: BLE001 — a failed conditional pass must disclose no partial mirrors + degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True self._passes.append(_Pass(ordinary, mirrored, legs, fallback, top_k, lexical_weight)) @@ -119,6 +121,7 @@ async def finish(self) -> list[list[RankedHit]]: raise ValueError("invalid final search admission") return [selected.ranked(checked) for selected in self._passes] except Exception: # noqa: BLE001 — final candidate failure invalidates every earlier mirror pass + degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True self.proofs = SearchProofs(self.plan, "", ()) return self.ordinary() diff --git a/server/knowledge/app/source_titles.py b/server/knowledge/app/source_titles.py index 121c20512d2..8797b632861 100644 --- a/server/knowledge/app/source_titles.py +++ b/server/knowledge/app/source_titles.py @@ -13,6 +13,7 @@ from server.knowledge.app.source_access import Admitted, ReadPlan from server.knowledge.app.source_list_proofs import ListProofs from server.knowledge.store import source_documents as store +from server.observability import degradations @dataclass(frozen=True) @@ -108,5 +109,6 @@ async def collect( return [] return titles except Exception: # noqa: BLE001 — a conditional title failure discloses no partial leg + degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return [] diff --git a/server/knowledge/app/tune.py b/server/knowledge/app/tune.py index f63578c838f..849279b9a55 100644 --- a/server/knowledge/app/tune.py +++ b/server/knowledge/app/tune.py @@ -62,6 +62,7 @@ from server.knowledge.store import blobs from server.knowledge.store import inspect as inspect_store from server.knowledge.store import tune as store +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -261,6 +262,7 @@ async def _load(org: str, namespace: str, rows: list[dict[str, Any]]) -> tuple[l max_bytes=settings.document_extractor_max_artifact_bytes, ) except Exception as e: # noqa: BLE001 — one unreadable artifact must not sink the sample + degradations.partial("knowledge", "tune_artifacts_unread", e) log.warning("namespace.tune: artifact of %s not read: %s", doc.uri, type(e).__name__) unread += 1 continue diff --git a/server/llm/fallback.py b/server/llm/fallback.py index c2250596d4d..e49d97c1004 100644 --- a/server/llm/fallback.py +++ b/server/llm/fallback.py @@ -21,7 +21,8 @@ so spend is attributed to the model that earned it. The fallback itself is counted in `loom.llm.fallback` and logged once per call, so an operator sees "opus was down for 40 minutes, 312 asks answered by gpt-4o-mini" -rather than an unexplained cost dip. +rather than an unexplained cost dip, and named in the answer's `degraded` +(`llm: fallback_model_answered`), so a caller knows another model answered. """ from __future__ import annotations @@ -34,6 +35,7 @@ from server.llm._retry import is_provider_outage from server.llm.client import LLMClient, LLMResult +from server.observability import degradations log = logging.getLogger(__name__) @@ -106,6 +108,7 @@ async def complete( ) except Exception: # noqa: BLE001 — telemetry must not block the answer pass + degradations.partial("llm", "fallback_model_answered", reason) return await self.secondary.complete( system, user, max_tokens=max_tokens, response_format=response_format, **kw ) diff --git a/server/memory/app/bulk_set.py b/server/memory/app/bulk_set.py index 27183242526..c58e2bae584 100644 --- a/server/memory/app/bulk_set.py +++ b/server/memory/app/bulk_set.py @@ -167,7 +167,7 @@ async def _bulk_identity_dupes(ch: Any, input: MemoryBulkSetInput) -> dict[str, """Phase 2: content hash -> (keeper key, keeper memory_id) of the keys under this identity (any session, any key) whose current version is live and holds an entry's exact bytes; a definition is never a keeper. Empty when the scope is not - `identity` or the read failed.""" + `identity` or the read failed, which is noted (`memory: identity_dedup_unchecked`).""" # Identity-scoped exact dedup. The gate above is session-scoped, so the same fact # re-observed in a later session, or extracted under a key variant, would land as a new # active row (~9% of active rows in real namespaces were exact copies). A key in @@ -255,6 +255,8 @@ async def _bulk_identity_dupes(ch: Any, input: MemoryBulkSetInput) -> dict[str, ) except Exception as e: # noqa: BLE001 — a dedup read never blocks an ingest log.warning("bulk_set identity-dedup lookup failed (non-fatal): %s", error_summary(e)) + # the entries write unchecked, as `conflict_unchecked` does for the conflict check + degradations.partial("memory", "identity_dedup_unchecked", e) return identity_dupes diff --git a/server/memory/app/code_plane_reads.py b/server/memory/app/code_plane_reads.py index f844cb122d7..6dcff6c7d25 100644 --- a/server/memory/app/code_plane_reads.py +++ b/server/memory/app/code_plane_reads.py @@ -19,6 +19,7 @@ from server.memory.store import code_links as links_store from server.memory.store import code_plane_reads as reads from server.memory.store.code_links import LinkRow +from server.observability import degradations from server.settings import settings @@ -310,7 +311,9 @@ async def _definitions_at( files = await _parse_link_source( code.parsed_link_paths(org, code_namespace, head, unique, named=named) ) - except (gitrepo.GitError, code.ParseFailed, TimeoutError): + except (gitrepo.GitError, code.ParseFailed, TimeoutError) as e: + # served as trunk has it: a read or parse that failed, or ran past its fixed bound + degradations.partial("code_lessons", "branch_code_state_unread", e) return None if files is None: return None diff --git a/server/memory/app/search/consistency.py b/server/memory/app/search/consistency.py index 8f206ad597d..134846f4bce 100644 --- a/server/memory/app/search/consistency.py +++ b/server/memory/app/search/consistency.py @@ -233,8 +233,9 @@ async def _sequential_pass( handle_memory_search(reread_input), timeout=search_budget.remaining_wall_s(), ) - except TimeoutError: + except TimeoutError as e: # `memory_search_fallback_max_wall_ms`, a fixed bound log.warning("memory.search: %s exceeded the wall budget", what) + failure = caller_text(e) except VectorInputTooLargeError: raise except Exception as e: # noqa: BLE001 — an optional re-read; the first pass stands diff --git a/server/memory/app/search/term_leg.py b/server/memory/app/search/term_leg.py index 2c0dfd708a1..9ea02cba107 100644 --- a/server/memory/app/search/term_leg.py +++ b/server/memory/app/search/term_leg.py @@ -132,7 +132,8 @@ async def outcome(task: asyncio.Task[TermLeg] | None, wait_s: float) -> TermLeg: return TermLeg("off") try: return await asyncio.wait_for(task, wait_s) - except TimeoutError: + except TimeoutError as e: # `memory_term_leg_wait_ms`, a fixed bound + degradations.partial("memory.search", "term_definitions_withheld", e) return TermLeg("timed_out") except Exception as e: # noqa: BLE001 — a failed read withholds the definitions only degradations.partial("memory.search", "term_definitions_withheld", e) @@ -202,7 +203,8 @@ async def _read( ) -> TermLeg: try: return await _read_bounded(org, namespace, query, excluded, query_vec, model, whole=whole) - except TimeoutError: + except TimeoutError as e: # the leg's work bound (`_Work`), a constant + degradations.partial("memory.search", "term_definitions_withheld", e) return TermLeg("timed_out") diff --git a/server/memory/store/reads.py b/server/memory/store/reads.py index 981477aa3c3..02d59c6a878 100644 --- a/server/memory/store/reads.py +++ b/server/memory/store/reads.py @@ -43,6 +43,7 @@ _is_full_row, read_your_writes_enabled, ) +from server.observability import degradations # The key columns a bulk read locates its heads by before fetching the rows # without FINAL. @@ -1521,7 +1522,9 @@ async def _overlay_usage_totals(row: MemoryRow, ch: _CHClient) -> MemoryRow: """Overlay append-only usage counters when the totals table has data. Hot paths write `memory_usage_events`; the SummingMergeTree totals - become authoritative over the row's own counters once non-zero. + become authoritative over the row's own counters once non-zero. A failed read + keeps the row's own counters and is noted (`memory: usage_totals_unread`): every + caller answers a read (`memory.get`, `memory.get_by_id`, `memory.list`, the bulk get). """ try: totals = await ch.query_one( @@ -1542,7 +1545,8 @@ async def _overlay_usage_totals(row: MemoryRow, ch: _CHClient) -> MemoryRow: "mid": row.memory_id, }, ) - except Exception: # noqa: BLE001 — usage totals are optional; keep the row + except Exception as e: # noqa: BLE001 — usage totals are optional; keep the row + degradations.partial("memory", "usage_totals_unread", e) return row return _with_usage(row, totals) @@ -1575,7 +1579,8 @@ async def overlay_usage_totals_many( "mids": [str(r.memory_id) for r in rows], }, ) - except Exception: # noqa: BLE001 — usage totals are optional; keep the rows + except Exception as e: # noqa: BLE001 — usage totals are optional; keep the rows + degradations.partial("memory", "usage_totals_unread", e) return rows by_id = {str(t["memory_id"]): t for t in totals} return [_with_usage(r, by_id.get(str(r.memory_id))) for r in rows] diff --git a/server/tracker/app/ask_route.py b/server/tracker/app/ask_route.py index 50592708014..756498055ee 100644 --- a/server/tracker/app/ask_route.py +++ b/server/tracker/app/ask_route.py @@ -106,6 +106,7 @@ async def qa_route_answer( shape, question, code_org, code_ns, tracker_ns, subject ) except Exception as e: # noqa: BLE001 — the route never blocks an ask + degradations.partial("memory.ask", "record_route_dropped", e) logger.debug("memory.ask qa route skipped (%s): %s", shape, e) return None if not lines: diff --git a/server/tracker/app/binding.py b/server/tracker/app/binding.py index 288eb63ba26..a4c69fc2f44 100644 --- a/server/tracker/app/binding.py +++ b/server/tracker/app/binding.py @@ -41,6 +41,7 @@ from typing import Any from server.code.domain.index import repos +from server.observability import degradations from server.settings import settings log = logging.getLogger("loom.tracker.binding") @@ -131,6 +132,7 @@ async def refresh_overrides(*, force: bool = False) -> None: _AFTER_WRITE = False return except Exception as e: # noqa: BLE001 — keep the last snapshot + degradations.partial("tracker", "binding_overrides_unread", e) log.warning("qa bindings: override refresh failed, keeping %d: %s", len(_OVERRIDES), e) diff --git a/server/tracker/app/contract.py b/server/tracker/app/contract.py index 15fc52e73f5..f650bfa2176 100644 --- a/server/tracker/app/contract.py +++ b/server/tracker/app/contract.py @@ -11,6 +11,7 @@ import time from typing import Any +from server.observability import degradations from server.tracker.domain.contract import ( ALIASES, OPTIONAL, @@ -69,6 +70,7 @@ async def _q(sql: str, params: dict[str, Any] | None = None) -> list[dict[str, A _q(f"DESCRIBE TABLE {database}.{table}"), timeout=budget_s ) except Exception as e: # noqa: BLE001 — an unknown table is "missing" + degradations.partial("tracker", "contract_table_undescribed", e) log.info("contract[%s] DESCRIBE %s.%s: %s", credential, database, table, e) continue out[table] = {str(r.get("name") or ""): str(r.get("type") or "") for r in desc} diff --git a/server/tracker/app/dupcheck.py b/server/tracker/app/dupcheck.py index 53ace08965f..04e3db67b22 100644 --- a/server/tracker/app/dupcheck.py +++ b/server/tracker/app/dupcheck.py @@ -28,6 +28,7 @@ from server.code.domain.index.repos import registry_unread from server.core.llm_free import reads_llm_free from server.llm import customer +from server.observability import degradations from server.settings import settings from server.tracker.api.models import ( TrackerDuplicateCheckInput, @@ -150,6 +151,7 @@ async def run() -> Any: CodePrCheckInput(org=org, namespace=code_ns, title=title[:500], body=body[:20000]) ) except Exception as e: # noqa: BLE001 — fail open: the issue answer stands alone + degradations.partial("code_index", "related_prs_skipped", e) logger.info("tracker.duplicate_check: related PR search skipped: %s", e) return None @@ -187,6 +189,7 @@ async def _with_links( timeout=settings.tracker_dupcheck_links_budget_s, ) except Exception as e: # noqa: BLE001 — rows keep whatever landed in time + degradations.partial("tracker", "fix_links_cut", e) logger.info("tracker.duplicate_check: fix links cut short: %s", e) related: list[dict[str, Any]] = [] lead = dl.lead_issue(d) @@ -196,7 +199,8 @@ async def _with_links( pc_out = await asyncio.wait_for( asyncio.shield(pr_task), timeout=settings.tracker_dupcheck_pr_wait_s ) - except Exception: # noqa: BLE001 — a slow or failed search adds nothing + except Exception as e: # noqa: BLE001 — a slow or failed search adds nothing + degradations.partial("code_index", "related_prs_cut", e) pc_out = None exclude = {int(lk.get("number") or 0) for r in rows for lk in (r.get("links") or [])} related = dl.related_prs(pc_out, exclude) if pc_out is not None else [] @@ -219,6 +223,7 @@ async def _links_and_releases( try: await dl.release_of_merges(org, code_ns, rows) except Exception as e: # noqa: BLE001 — the tracker's estimate stands + degradations.partial("git_mirror", "fix_releases_unread", e) logger.info("tracker.duplicate_check: release lookup skipped: %s", e) @@ -302,6 +307,7 @@ async def one(ns: str, group: list[dict[str, Any]]) -> None: for res in results: if isinstance(res, BaseException): logger.info("tracker.duplicate_check: fix links skipped: %s", res) + degradations.partial("tracker", "fix_links_unread", res) async def _checked( @@ -341,6 +347,7 @@ async def _checked( logger.info( "tracker.duplicate_check on %s failed inside a fan-out: %s", inp.namespace, o ) + degradations.partial("tracker", "fanout_namespace_unread", o) kept.append(None) else: kept.append(o) @@ -470,6 +477,7 @@ async def hand_over() -> None: try: pool = await _rerank_pool(src, input, run, wall) except Exception as e: # noqa: BLE001 — the rerank is optional + degradations.partial("tracker", "rerank_pool_dropped", e) logger.info("duplicate_check: rerank pool failed (%s)", e) pool = [] title, body = _draft_text(input, run) @@ -525,6 +533,7 @@ async def _rerank_pool( ) ) except Exception as e: # noqa: BLE001 — no text, no rerank + degradations.partial("tracker", "rerank_text_unread", e) logger.info("duplicate_check: rerank text unavailable (%s)", e) return [] by = {int(r["number"]): r for r in rows if int(r.get("number") or 0) > 0} @@ -578,7 +587,8 @@ async def _rerank_call(input: Any, cands: list[dict[str, Any]]) -> Any: dr.rerank(get_llm_client_for_model(model), title, body, cands, body_chars=chars), timeout=timeout, ) - except TimeoutError: + except TimeoutError as e: + degradations.partial("llm", "dupcheck_rerank_skipped", e) return dr.Rerank(pool=len(cands), error="timeout") diff --git a/server/tracker/app/dupcheck_answer.py b/server/tracker/app/dupcheck_answer.py index f1ba1e6353f..52922742263 100644 --- a/server/tracker/app/dupcheck_answer.py +++ b/server/tracker/app/dupcheck_answer.py @@ -12,6 +12,7 @@ from server.core.datetimes import to_naive_utc from server.core.llm_free import reads_llm_free +from server.observability import degradations from server.settings import settings from server.tracker.api.models import ( TrackerDuplicateCheckOutput, @@ -92,6 +93,7 @@ async def with_canonical(src: Any, input: Any, out: Any) -> Any: try: gold = await src.duplicate_gold(input.org, input.namespace, limit=2000) except Exception as e: # noqa: BLE001 — a pointer beside the answer, never the answer + degradations.partial("tracker", "duplicate_map_unread", e) logger.info("duplicate_check: duplicate map unavailable (%s)", e) return out targets_of = {int(g["number"]): [int(t) for t in g.get("targets") or []] for g in gold} @@ -107,6 +109,7 @@ async def with_canonical(src: Any, input: Any, out: Any) -> Any: try: found = await src.items_by_number(input.org, input.namespace, [t for t, _ in wanted]) except Exception as e: # noqa: BLE001 — canonicals are extra rows + degradations.partial("tracker", "canonical_rows_unread", e) logger.info("duplicate_check: canonical rows unavailable (%s)", e) found = {} wall = parse_as_of(input.as_of) @@ -232,6 +235,7 @@ async def judge_uncertain(src: Any, input: Any, run: dict[str, Any], out: Any, f body_chars=chars, ) except Exception as e: # noqa: BLE001 — no text, no judge + degradations.partial("tracker", "judge_text_unread", e) logger.info("dupcheck judge: candidate text unavailable (%s)", e) return out text_by = {int(r["number"]): r for r in rows} diff --git a/server/tracker/app/dupcheck_candidates.py b/server/tracker/app/dupcheck_candidates.py index 1ea6a6578dc..ed2b97d67b3 100644 --- a/server/tracker/app/dupcheck_candidates.py +++ b/server/tracker/app/dupcheck_candidates.py @@ -11,6 +11,7 @@ from datetime import datetime from typing import Any +from server.observability import degradations from server.settings import settings from server.tracker.api.models import ( TrackerSimilarInput, @@ -189,6 +190,7 @@ async def _resolve_error_name(src: Any, input: Any, q: Any, meta: dict[str, Any] try: codes = await src.error_name_codes(input.org, input.namespace) except Exception as e: # noqa: BLE001 — the name only adds evidence + degradations.partial("tracker", "error_names_unread", e) logger.info("duplicate_check: error names unavailable (%s)", e) return for name in names: @@ -223,6 +225,7 @@ async def _fingerprint_leg( limit=FINGERPRINT_MAX, ) except Exception as e: # noqa: BLE001 — the leg is skipped + degradations.partial("tracker", "fingerprint_leg_dropped", e) logger.info("duplicate_check: fingerprint leg skipped (%s)", e) return [] own = int(getattr(q, "number", 0) or 0) diff --git a/server/tracker/app/dupcheck_fit.py b/server/tracker/app/dupcheck_fit.py index b6ce4250511..54dbd0751d5 100644 --- a/server/tracker/app/dupcheck_fit.py +++ b/server/tracker/app/dupcheck_fit.py @@ -24,6 +24,7 @@ from server.code.app.reads import CodeIndexReads from server.llm import customer +from server.observability import degradations from server.settings import settings from server.tracker.api.models import TrackerDuplicateCheckInput from server.tracker.domain import dupcheck as dc @@ -114,6 +115,7 @@ async def stored_fit(repo: Any, org: str, ns: str) -> dict[str, Any] | None: return fit return None except Exception as e: # noqa: BLE001 — a missing fit is an uncalibrated answer + degradations.partial("tracker", "dupcheck_fit_unread", e) logger.info("dupcheck_fit: state read failed for %s/%s: %s", org, ns, e) return None diff --git a/server/tracker/app/dupcheck_links.py b/server/tracker/app/dupcheck_links.py index 839d8219cc2..f34f33d449a 100644 --- a/server/tracker/app/dupcheck_links.py +++ b/server/tracker/app/dupcheck_links.py @@ -18,6 +18,8 @@ from datetime import datetime from typing import Any +from server.observability import degradations + LINKS_PER_ISSUE = 2 BACKPORTS_SHOWN = 4 RELATED_PRS_MAX = 3 @@ -290,7 +292,8 @@ async def release_of_merges( async def one(pr: int, sha: str) -> tuple[int, str | None]: try: return pr, await gitrepo.release_containing(git_dir, sha, timeout_s=timeout_s) - except Exception: # noqa: BLE001 — the tracker's estimate stands + except Exception as e: # noqa: BLE001 — the tracker's estimate stands + degradations.partial("git_mirror", "fix_release_unread", e) return pr, None for pr, rel in await asyncio.gather(*(one(p, sha) for p, sha in shas.items())): diff --git a/server/tracker/app/facts.py b/server/tracker/app/facts.py index f49f865d3b8..5badce498d4 100644 --- a/server/tracker/app/facts.py +++ b/server/tracker/app/facts.py @@ -16,6 +16,8 @@ import logging from typing import Any +from server.observability import degradations + logger = logging.getLogger("loom.tracker.facts") _EDGE_RELS = ("fixes", "backports", "caused_by", "tested_by") @@ -116,6 +118,7 @@ async def tracker_facts_for_numbers( refs = [f"{r.get('repo') or ''}#{n}" for n, r in rows.items()] edges = await source.edges_from(org, tracker_ns, refs, list(_EDGE_RELS)) except Exception as e: # noqa: BLE001 — additive, never a failed request + degradations.partial("tracker", "item_facts_unread", e) logger.debug("qa facts skipped for %s/%s: %s", org, tracker_ns, e) return {} return {n: fact_of(r, edges) for n, r in rows.items()} diff --git a/server/tracker/app/handlers.py b/server/tracker/app/handlers.py index 9dc7ebf7dff..48d6ce9c8b2 100644 --- a/server/tracker/app/handlers.py +++ b/server/tracker/app/handlers.py @@ -14,6 +14,7 @@ from typing import Any from server.core.errors import ValidationError +from server.observability import degradations from server.tracker.api.models import ( TrackerAnswerInput, TrackerAnswerOutput, @@ -98,6 +99,7 @@ async def _attach_fixed_by_files(src: Any, org: str, ns: str, items: list[dict[s try: files = await src.pr_files(org, ns, wanted[:32]) except Exception as e: # noqa: BLE001 — enrichment only + degradations.partial("tracker", "fixed_by_files_unread", e) common._unavailable("tracker.item/files", ns, e) return for it in items: @@ -309,6 +311,7 @@ async def _answer_elsewhere( for ns, a in zip(namespaces, outs, strict=True): if isinstance(a, BaseException): logger.info("tracker.answer on %s failed inside a fan-out: %s", ns, a) + degradations.partial("tracker", "linked_tracker_unread", a) continue served = [s for s in a.sections if s.status == "served" and not s.params.get("numbers")] if not served: diff --git a/server/tracker/app/links.py b/server/tracker/app/links.py index 5c39fc2f640..a30e9314618 100644 --- a/server/tracker/app/links.py +++ b/server/tracker/app/links.py @@ -23,6 +23,7 @@ from datetime import datetime, timedelta from typing import Any +from server.observability import degradations from server.tracker.domain import similar as sim from server.tracker.store.links import LinkCandidate @@ -337,6 +338,7 @@ async def fix_candidate( repo = TrackerLinksRepo() rows = await repo.candidates_for_issue(org, tracker_namespace, int(issue_number), limit=2) except Exception as e: # noqa: BLE001 — a candidate is a bonus, never the answer + degradations.partial("tracker", "fix_candidate_unread", e) logging.getLogger("loom.tracker.links").info("link candidate read failed: %s", e) return None if not rows: diff --git a/server/tracker/app/patch_history.py b/server/tracker/app/patch_history.py index 413e16d6845..56266427421 100644 --- a/server/tracker/app/patch_history.py +++ b/server/tracker/app/patch_history.py @@ -42,6 +42,7 @@ from dataclasses import dataclass, field from typing import Any +from server.observability import degradations from server.settings import settings from server.tracker.domain.patch_presence import ( EXACT, @@ -189,7 +190,8 @@ async def _git_rc(git_dir: str, *args: str, timeout_s: float) -> tuple[int, str] ) try: out, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout_s) - except TimeoutError: + except TimeoutError as e: + degradations.partial("git_mirror", "patch_history_timed_out", e) return -1, "" finally: # a deadline or the caller cancelling (code_backport) must not leave a @@ -397,7 +399,7 @@ async def gated(coro: Any) -> Any: present_added: list[tuple[str, str]] = [] for (p, (a, r)), tip in zip(per_path.items(), tips, strict=True): if isinstance(tip, BaseException): - hp.reason = f"error:{type(tip).__name__}" + hp.reason = _unread(tip) hp.ms = int((time.monotonic() - started) * 1000) return hp if tip is None: @@ -444,16 +446,24 @@ async def gated(coro: Any) -> Any: if probes: results = await asyncio.gather(*coros, return_exceptions=True) for (p, x), res in zip(probes, results, strict=True): - hp.lines.append( - LineHistory(p, x, f"error:{type(res).__name__}") - if isinstance(res, BaseException) - else res - ) + hp.lines.append(_unread_line(p, x, res) if isinstance(res, BaseException) else res) decide_history(hp) if leg == "removed" else decide_origin(hp) hp.ms = int((time.monotonic() - started) * 1000) return hp +def _unread(error: BaseException) -> str: + """A tip read that raised: the branch is left undecided, and named in `degraded`.""" + degradations.partial("git_mirror", "patch_history_unread", error) + return f"error:{type(error).__name__}" + + +def _unread_line(path: str, line: str, error: BaseException) -> LineHistory: + """A line probe that raised: decided without it, and named in `degraded`.""" + degradations.partial("git_mirror", "patch_history_line_unread", error) + return LineHistory(path, line, f"error:{type(error).__name__}") + + def history_leg(hp: HistoryPresence) -> str: """Which history read the tip's counts call for: `removed` (the fix's lines absent, at most half of the pre-image left — restructured, or diff --git a/server/tracker/app/registry_sources.py b/server/tracker/app/registry_sources.py index 82f95c48dee..b0500ea4536 100644 --- a/server/tracker/app/registry_sources.py +++ b/server/tracker/app/registry_sources.py @@ -26,6 +26,7 @@ from server.core import readiness from server.core.datetimes import naive_utc_now_seconds as _now from server.core.secrets_at_rest import seal, unseal +from server.observability import degradations from server.settings import settings from server.tracker.domain import sources from server.tracker.domain.sources import DbSource @@ -57,7 +58,8 @@ def decrypt_password(enc: str) -> str: def _namespaces_of(raw: Any) -> dict[str, dict[str, Any]]: try: data = json.loads(raw) if isinstance(raw, str) else dict(raw or {}) - except Exception: # noqa: BLE001 — an unparseable stored map links no namespace + except Exception as e: # noqa: BLE001 — an unparseable stored map links no namespace + degradations.partial("tracker", "source_namespaces_unparsed", e) return {} out: dict[str, dict[str, Any]] = {} for ns, spec in (data or {}).items(): @@ -125,6 +127,7 @@ async def refresh_db_sources(*, force: bool = False, ch: Any | None = None) -> l sources.set_registered([row_to_source(r) for r in rows if r.get("name") and r.get("host")]) _LOADED_AT = now except Exception as e: # noqa: BLE001 — keep the last snapshot + degradations.partial("tracker", "sources_registry_unread", e) logger.warning( "tracker_sources: refresh failed, keeping %d entries: %s", len(sources.registered()), diff --git a/server/tracker/app/similar.py b/server/tracker/app/similar.py index 9c74357a9db..55251c7e744 100644 --- a/server/tracker/app/similar.py +++ b/server/tracker/app/similar.py @@ -11,6 +11,7 @@ from server.core.errors import ValidationError, caller_text from server.llm import customer +from server.observability import degradations from server.settings import settings from server.tracker.api.models import ( TrackerSimilarInput, @@ -479,9 +480,10 @@ async def fresh_leg() -> Any: budget = max(0.0, share - (time.monotonic() - started)) try: fresh = await asyncio.wait_for(asyncio.shield(catching_up), timeout=budget) - except TimeoutError: + except TimeoutError as e: # past its share of the budget: the table answers now; the embedding # finishes in the background and the next call finds the rows stored + degradations.partial("tracker", "vector_fresh_pending", e) fresh = ei.CatchUp(status="pending") meta["fresh_pending"] = True meta["fresh_items"] = fresh.embedded @@ -553,6 +555,7 @@ async def _vector_catch_up(src: Any, repo: Any, org: str, ns: str, *, kinds: lis body_chars=int(settings.tracker_embed_body_chars), ) except Exception as e: # noqa: BLE001 — the table's answer stands + degradations.partial("tracker", "vector_fresh_dropped", e) logger.info("tracker.similar/vector catch-up on %s failed: %s: %s", ns, type(e).__name__, e) return ei.CatchUp(status="tracker_unavailable") diff --git a/server/tracker/app/sources.py b/server/tracker/app/sources.py index 8be55b482a7..0a1129b7d3e 100644 --- a/server/tracker/app/sources.py +++ b/server/tracker/app/sources.py @@ -23,6 +23,7 @@ from server.core.errors import AuthInsufficientError, ValidationError, caller_text from server.identity.api.models import NamespaceDeleteInput from server.identity.app import namespace as namespace_ops +from server.observability import degradations from server.operations.base import Role from server.settings import settings from server.tracker.api.models import ( @@ -200,6 +201,7 @@ async def _contract_view( ) checked_here = rep is not None except Exception as e: # noqa: BLE001 — the card says "unchecked", not a 500 + degradations.partial("tracker", "contract_unchecked", e) logger.info("tracker.source.list: contract check of %r did not answer: %s", name, e) rep = None if rep is None: @@ -264,6 +266,7 @@ async def _freshness(org: str, namespace: str) -> dict[str, Any]: timeout=settings.tracker_freshness_budget_s, ) except Exception as e: # noqa: BLE001 — freshness is advisory + degradations.partial("tracker", "freshness_unread", e) logger.info("tracker.source.list: freshness of %s/%s did not answer: %s", org, namespace, e) return {} if isinstance(out, dict) and out: diff --git a/server/tracker/app/test_signal.py b/server/tracker/app/test_signal.py index 58adcb8d233..1a596c5c9ef 100644 --- a/server/tracker/app/test_signal.py +++ b/server/tracker/app/test_signal.py @@ -12,6 +12,7 @@ from typing import Any from server.code.app.reads import CodeIndexReads +from server.observability import degradations from server.settings import settings from server.tracker.api.models import ( TrackerTestSignalInput, @@ -113,6 +114,7 @@ async def churn_leg(org: str, code_namespace: str, test_name: str, *, days: int) else [] ) except Exception as e: # noqa: BLE001 — the ledger leg never fails the verdict + degradations.partial("code_index", "churn_ledger_unread", e) logger.info("tracker.test_signal churn leg on %s/%s failed: %s", code_org, ns, e) return { **ts.churn_unavailable(f"ledger read failed: {type(e).__name__}", days=days), @@ -301,6 +303,7 @@ async def smell_leg( per_path = max(1, int(settings.tracker_test_signal_smell_chunks)) rows = await _code_repo().chunks_for_paths(code_org, ns, model, paths, per_path=per_path) except Exception as e: # noqa: BLE001 — the smell leg never fails the verdict + degradations.partial("code_index", "smell_chunks_unread", e) logger.info("tracker.test_signal smell leg on %s/%s failed: %s", code_org, ns, e) return { "available": False, @@ -366,6 +369,7 @@ async def read() -> dict[str, Any] | None: try: return await asyncio.wait_for(read(), timeout=settings.tracker_test_candidates_timeout_s) except Exception as e: # noqa: BLE001 — the candidate read never fails the answer + degradations.partial("tracker", "test_candidates_dropped", e) logger.info("tracker.test_signal candidates on %s failed: %s", namespace, e) return None diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index ccf4206a676..a5c3524f36e 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -1,6 +1,7 @@ -# Broad handlers in server/code/app and server/memory/app that name nothing in -# `degraded`, each with why it need not (tests/unit/test_degraded_unnoted.py lists the -# categories). The list only shrinks: a handler that serves a smaller answer notes it. +# Broad and timeout handlers in the code, memory, knowledge and tracker apps and the LLM +# clients that name nothing in `degraded`, each with why it need not +# (tests/unit/test_degraded_unnoted.py lists the dirs and the categories). The list only +# shrinks: a handler that serves a smaller answer notes it. server/code/app/answers.py::_memory_context_cacheable::1 cache_fallback server/code/app/answers_cache.py::_check_stored::1 write @@ -27,16 +28,32 @@ server/code/app/common.py::record_code_outcome::1 server/code/app/common.py::record_code_shunt::1 telemetry server/code/app/common.py::schedule_code_trace._write::1 telemetry server/code/app/common.py::schedule_code_trace_validation_failure::1 telemetry +server/code/app/grep.py::_cover_batch_chunks::timeout::1 deadline # cut at what the caller's deadline_ms left; partial_reason names the scan +server/code/app/grep.py::_extra_related_source::timeout::1 deadline # cut at what the caller's deadline_ms left; partial_reason names the stage +server/code/app/grep_bodies.py::definitions_for::timeout::1 deadline # cut at what the caller's deadline_ms left; definitions_partial says so +server/code/app/grep_dependencies.py::add_dependencies::timeout::1 deadline # cut at what the caller's deadline_ms left; partial_reason names the lookup +server/code/app/grep_dependencies.py::forwarded_dependency::timeout::1 deadline # cut at what the caller's deadline_ms left; partial_reason names the lookup +server/code/app/grep_source.py::recover_page_context::timeout::1 deadline # cut at what the caller's deadline_ms left; the budget records the cut +server/code/app/grep_source.py::recover_source_chunks::timeout::1 deadline # cut at what the caller's deadline_ms left; the summary and its warning stay server/code/app/index/bootstrap.py::_pin_ledger_merges::1 logged_only_nonanswer # the clone job's pin pass +server/code/app/index/bootstrap.py::clone_mirror::timeout::1 noted_by_caller # mirrors.history_dir notes git_mirror: clone_failed from job_state server/code/app/index/bootstrap.py::index_slice._one::1 logged_only_nonanswer server/code/app/index/bootstrap.py::mirror_job::1 noted_by_caller # mirrors.history_dir notes git_mirror: clone_failed from job_state +server/code/app/index/bootstrap.py::mirror_job::timeout::1 noted_by_caller # history_dir answers the gap no_git_mirror: cloning; a failed clone is noted server/code/app/index/denylist.py::_show_text::1 logged_only_nonanswer # the denylist the ingest and the code-link pass load +server/code/app/index/egress.py::EgressProxy._tunnel::timeout::1 logged_only_nonanswer # a job's egress proxy drops a silent CONNECT; the git job fails, its caller reports it +server/code/app/index/egress.py::EgressProxy._tunnel::timeout::2 logged_only_nonanswer # a job's egress proxy answers 502 to the job; the git job fails, its caller reports it +server/code/app/index/egress.py::EgressProxy.handle::timeout::1 logged_only_nonanswer # a job's egress proxy at its tunnel cap: the git job fails and its caller reports it +server/code/app/index/egress.py::_splice::timeout::1 logged_only_nonanswer # an idle tunnel's close check in a repository job's egress proxy +server/code/app/index/gitrepo.py::run_bounded::timeout::2 logged_only_nonanswer # the reap after stdout ended: the text read is whole; no output or check raises server/code/app/index/history_bound.py::publish::1 write server/code/app/index/ingest_parse.py::parse_for_ingest::1 noted_by_caller # returns the error: the ingest stores it, memory_links raises ParseFailed, the PR overlay counts it in overlay_note +server/code/app/index/ingest_trigger.py::refresh::1 logged_only_nonanswer # the registry refresh timer's untriggered count keeps its last reading server/code/app/index/maintainers.py::sync_quietly::1 write server/code/app/index/maintainers.py::sync_restricted_page_branches::1 logged_only_nonanswer server/code/app/index/mirrors.py::_fetch_round::1 logged_only_nonanswer server/code/app/index/mirrors.py::_fetch_round::2 logged_only_nonanswer +server/code/app/index/mirrors.py::_low_priority_git::timeout::1 logged_only_nonanswer # the host loop's mirror gc or repack, bounded; its exit is logged server/code/app/index/mirrors.py::_merge_page::1 logged_only_nonanswer server/code/app/index/mirrors.py::_named_paths::1 logged_only_nonanswer server/code/app/index/mirrors.py::_run::1 logged_only_nonanswer @@ -54,10 +71,15 @@ server/code/app/index/retire.py::refresh_code_views::1 server/code/app/index/review_brief_build.py::build_for_merge::4 write server/code/app/index/review_brief_build.py::build_for_open::3 write server/code/app/index/risk_fit.py::refit_namespace::1 write # the weekly refit +server/code/app/index/sandbox.py::_kill_group::timeout::1 logged_only_nonanswer # reaping a killed job: its pipes are closed on our side and it is awaited server/code/app/index/scip_delta.py::_declaration_line_test::1 logged_only_nonanswer # the SCIP apply's edge filter, a worker pass server/code/app/index/scip_delta.py::_declaration_line_test::2 logged_only_nonanswer # the SCIP apply's edge filter, a worker pass server/code/app/index/scip_delta.py::_indexable_prefixes::1 logged_only_nonanswer # the SCIP apply's repo entry, a worker pass server/code/app/index/scip_delta.py::_path_refusal::1 logged_only_nonanswer # the SCIP apply's repo entry, a worker pass +server/code/app/index/tier_health.py::forget::1 write # dropping a tier-health record of a tier the entry no longer runs +server/code/app/index/tier_health.py::note_unavailable::1 write # a tier-health record write; the pass it describes is whole +server/code/app/index/tier_health.py::record::1 write # a tier-health record write; the ingest or CLI pass it describes is whole +server/code/app/index/tier_health.py::refresh_failing::1 logged_only_nonanswer # the registry refresh timer's failing-tier snapshot keeps its last reading server/code/app/index_status.py::_commit_missing::1 noted_by_caller # _lag_between notes git_mirror: lag_unknown server/code/app/index_status.py::_publish_status_snapshot::1 write server/code/app/index_status.py::_refresh_repo_status::1 logged_only_nonanswer @@ -68,12 +90,14 @@ server/code/app/ingest.py::handle_code_refresh._one_pass::1 server/code/app/outcome.py::handle_code_outcome::1 write server/code/app/outcome.py::handle_code_outcome::2 write server/code/app/prose_candidates.py::discover_candidates::1 logged_only_nonanswer +server/code/app/prose_candidates.py::discover_candidates::timeout::1 logged_only_nonanswer # the CLI's dry-run decision preview; its status reads deferred server/code/app/repo_admin.py::_inherit_tracker_links::1 write server/code/app/repos.py::_code_repo_rows::1 full_answer_fallback server/code/app/review_brief.py::_payload_for::1 cache_fallback server/code/app/risk.py::RiskPrefetch._run::1 full_answer_fallback server/code/app/risk.py::RiskPrefetch.start::1 full_answer_fallback server/code/app/search/handler.py::_embedding_model_name::1 full_answer_fallback +server/code/app/search/rerank.py::_rerank_stage::timeout::1 deadline # cut at what the search's deadline left; partial_reason names the rerank server/code/app/search_cursor.py::get_pool::1 cache_fallback server/code/app/search_cursor.py::get_pool::2 cache_fallback server/code/app/search_cursor.py::put_pool._bg::1 write @@ -87,6 +111,65 @@ server/code/app/spans.py::set_code_span_attributes::1 server/code/app/spans.py::span_attrs::1 telemetry server/code/app/unit_risk.py::read_rows::1 cache_fallback server/code/app/watches.py::notify_once::1 logged_only_nonanswer +server/knowledge/app/connected_accounts.py::_revoke::timeout::1 write # the provider revoke after local inactivation; the disconnect is already durable +server/knowledge/app/connected_accounts.py::available::1 fail_closed # an unverifiable registration standing is never reported usable +server/knowledge/app/connected_accounts.py::token_for::2 write # cleanup of the refresh reservation inside a handler that re-raises the failure +server/knowledge/app/connected_restore.py::_restore_owner::1 logged_only_nonanswer # the restore CLI's cleanup: local deletion goes on without the remote revoke +server/knowledge/app/connected_restore.py::offline_refusal::1 logged_only_nonanswer # the restore CLI's gate: unverified worker standing refuses the cleanup +server/knowledge/app/conversations.py::_embed_turn::1 write # conversation.append: the turn is stored; its embedding row records the failure +server/knowledge/app/datasets.py::_forget_quietly::1 write # a snapshot the approval no longer serves; an erasure deletes it +server/knowledge/app/gaps.py::_insert::1 telemetry # the background gap-miss insert; the search answered before it ran +server/knowledge/app/gaps.py::_person::1 telemetry # the background gap-miss insert's asker fold; no answer reads it +server/knowledge/app/gaps.py::erasure_since::1 write # an unread ledger counts as an erasure: the draft, source change or miss is refused +server/knowledge/app/gaps.py::record_miss::1 telemetry # a knowledge-gap miss is telemetry; the search answer is whole +server/knowledge/app/ingest_run.py::run::1 logged_only_nonanswer # the ingest worker's job run; the job ends failed with code internal +server/knowledge/app/move.py::_forget_tables::1 write # the moved document's tables left behind; a later delete of the source settles them +server/knowledge/app/move.py::handle_knowledge_move.one::1 write # knowledge.move raises the first failure once every source has answered +server/knowledge/app/pg_delivery.py::publish_due::1 logged_only_nonanswer # the delivery worker's and restore CLI's pass; the delivery is retried +server/knowledge/app/restore.py::_purge_found::1 write # the undo after a failed restore; the row goes back retired and the failure answers +server/knowledge/app/source_access.py::_eligible_sources::1 fail_closed # an unverifiable crawl authority admits no mirror leg, as a refused one +server/knowledge/app/source_access.py::_eligible_sources::2 fail_closed # an unverifiable connection admits no private leg, as a refused one +server/knowledge/app/source_passages.py::CheckedPassages._fallback::1 noted_by_caller # agent_rules.served_hits notes knowledge: widened_hits_dropped if the wide pass is needed +server/knowledge/app/source_passages.py::collect::1 noted_by_caller # agent_rules.served_hits notes knowledge: widened_hits_dropped if the wide pass is needed +server/knowledge/app/source_push.py::_stop_channels::1 write # provider channel cleanup on renewal; expiry and polling recover a failed stop +server/knowledge/app/source_retirements.py::_run_once::1 logged_only_nonanswer # the source-retirement worker's pass; one source's failure is counted +server/knowledge/app/source_sync.py::_extract_one::1 logged_only_nonanswer # the sync worker's mining of one document; recorded as its failed try +server/knowledge/app/source_sync.py::_extract_pending::1 logged_only_nonanswer # the sync worker's extraction leg; one source's failed read is counted +server/knowledge/app/source_sync.py::_extract_pending::2 logged_only_nonanswer # the sync worker's extraction leg; one source's failed write is counted +server/knowledge/app/source_sync.py::_extract_source::2 logged_only_nonanswer # the sync worker's mining of one source; counted in the pass +server/knowledge/app/source_sync.py::_fetch_and_write::1 logged_only_nonanswer # the sync worker's file fetch; the file waits for a later pass +server/knowledge/app/source_sync.py::_fetch_and_write::2 logged_only_nonanswer # the sync worker's file write; the file waits for a later pass +server/knowledge/app/source_sync.py::_retire_removed_sources::1 logged_only_nonanswer # the sync worker's retirement of removed sources; counted in the pass +server/knowledge/app/source_sync.py::_sync_turn::1 logged_only_nonanswer # the sync worker's turn; recorded as the source's failed turn +server/knowledge/app/source_sync.py::_sync_turn::2 logged_only_nonanswer # the sync worker's pass; one source's failure is counted in the pass +server/knowledge/app/source_sync.py::open_listing::timeout::1 logged_only_nonanswer # the sync worker's folder turn; recorded on the turn as credential_invalid +server/knowledge/app/source_sync_crawl.py::turn::timeout::1 logged_only_nonanswer # the sync worker's crawl turn; marked pass-bound and listed again next pass +server/knowledge/app/source_sync_linear.py::_fetch_and_write::1 logged_only_nonanswer # the sync worker's document write; it waits for a later pass +server/knowledge/app/source_sync_linear.py::turn::timeout::1 logged_only_nonanswer # the sync worker's Linear turn; recorded as credential_invalid +server/knowledge/app/source_sync_notion.py::_fetch_and_write::1 logged_only_nonanswer # the sync worker's page fetch; the page waits for a later pass +server/knowledge/app/source_sync_notion.py::_write::1 logged_only_nonanswer # the sync worker's page write; the page waits for a later pass +server/knowledge/app/source_sync_notion.py::turn::timeout::1 logged_only_nonanswer # the sync worker's Notion turn; recorded as credential_invalid +server/knowledge/app/source_sync_recording.py::_fetch_and_write::1 logged_only_nonanswer # the sync worker's transcript fetch; it waits for a later pass +server/knowledge/app/source_sync_recording.py::_fetch_and_write::2 logged_only_nonanswer # the sync worker's transcript write; it waits for a later pass +server/knowledge/app/sources.py::_Caller.owner::1 fail_closed # an unverifiable caller owns nothing, as one that owns nothing +server/knowledge/app/sources.py::_source_access::1 fail_closed # unverifiable crawl selectors stay private, as for a non-operator +server/knowledge/app/sources.py::_source_access::2 fail_closed # unverifiable personal-source details stay private, as for another owner +server/knowledge/app/writes.py::_drop_own_chunks::1 write # cleanup of an erased write's chunks; the write's own error answers +server/knowledge/app/writes.py::_drop_own_chunks::2 write # retiring a failed write's unpublished chunks; the write's own error answers +server/llm/anthropic.py::AnthropicLLMClient.complete::1 telemetry # cost and content capture of the call +server/llm/anthropic.py::_refusal::1 noted_by_caller # None sends the 400 on: AnthropicLLMClient.complete raises it in _raise_for_status +server/llm/bedrock.py::_record::1 telemetry # cost and content capture of the call +server/llm/cache.py::CachedLLMClient._get::1 cache_fallback # a failed cache read calls the provider +server/llm/cache.py::CachedLLMClient._put._bg::1 write # a lost cache write costs one provider call later +server/llm/cache.py::CachedLLMClient._put::1 telemetry # the stage label of the cache row +server/llm/cache.py::CachedLLMClient._put::2 write # a skipped cache write costs one provider call later +server/llm/cache.py::CachedLLMClient.complete::1 telemetry # the saved-cost counter of a hit +server/llm/cache.py::_record::1 telemetry # the response-cache metric +server/llm/cache.py::wrap_scoped::1 cache_fallback # a client the cache cannot wrap calls the provider uncached +server/llm/fallback.py::FallbackLLMClient.complete::2 telemetry # the fallback metric; the answer and its note stand +server/llm/identity.py::_kept_read::1 full_answer_fallback # the kept copy names the same identity; both change only on re-registration +server/llm/openai.py::_report::1 telemetry # cost and content capture of the call +server/llm/openai.py::learn_from_refusal::1 noted_by_caller # False sends the 400 on: OpenAILLMClient._read raises it in _raise_for_status server/memory/app/apply.py::_mirror::1 write server/memory/app/apply.py::apply_one::1 write server/memory/app/ask/cascade.py::_first_answer::1 full_answer_fallback @@ -118,7 +201,6 @@ server/memory/app/bulk_set.py::_audit_bulk_write::1 server/memory/app/bulk_set.py::_batched_peers::1 cache_fallback server/memory/app/bulk_set.py::_bulk_audit::1 write server/memory/app/bulk_set.py::_bulk_follow_row_supersessions::1 write -server/memory/app/bulk_set.py::_bulk_identity_dupes::1 write server/memory/app/bulk_set.py::_bulk_intra_batch_pairs::1 write server/memory/app/bulk_set.py::_bulk_mark_same_key::1 write server/memory/app/bulk_set.py::_bulk_post_insert_links::1 write @@ -149,6 +231,7 @@ server/memory/app/code_links.py::sweep_unlinkable::1 server/memory/app/code_renames.py::revise::1 logged_only_nonanswer server/memory/app/conflict_resolver.py::_act_on_verdicts::2 logged_only_nonanswer server/memory/app/conflict_resolver.py::_after_retire::1 logged_only_nonanswer +server/memory/app/conflict_resolver.py::judge::timeout::1 logged_only_nonanswer # the conflict resolver worker: the first answer stands, the rest stays owed server/memory/app/conflicts.py::_policy_before_gate::1 settings server/memory/app/conflicts.py::_substitution_verdict::1 settings server/memory/app/conflicts.py::apply_refines::1 write @@ -168,6 +251,7 @@ server/memory/app/curation.py::quotes_a_redacted_key::1 server/memory/app/decision.py::_write_decision::1 write server/memory/app/decision.py::handle_decision_outcome::1 write server/memory/app/decision.py::handle_decision_record::1 write +server/memory/app/decision_extract.py::_call::timeout::1 logged_only_nonanswer # the extract run (CLI, source sync): a lost window is a dropped line in its report server/memory/app/decision_extract.py::_may::1 logged_only_nonanswer server/memory/app/decision_extract.py::_readable_names::1 logged_only_nonanswer server/memory/app/decision_extract.py::symbol_definitions::1 logged_only_nonanswer @@ -285,6 +369,7 @@ server/memory/app/run_retention.py::apply::1 server/memory/app/search/anchor_pool.py::_stamp_row_owner::1 full_answer_fallback server/memory/app/search/assemble.py::_assemble_final_hits::4 full_answer_fallback server/memory/app/search/assemble.py::_assemble_final_hits::5 telemetry +server/memory/app/search/embed.py::_bounded_query_embed::timeout::1 full_answer_fallback # a timed-out attempt is retried; the last one raises EMBED_TIMEOUT server/memory/app/search/embed.py::_embed_text_and_window::1 telemetry server/memory/app/search/evidence.py::_apply_min_similarity_floor::1 full_answer_fallback server/memory/app/search/key_match.py::_run_key_match_pool._rows_for_ns::1 full_answer_fallback @@ -342,3 +427,24 @@ server/memory/app/value_updates.py::link_value_updates._one::1 server/memory/app/value_updates.py::link_value_updates::1 write server/memory/app/value_updates.py::link_value_updates::gather::1 cache_fallback server/memory/app/verify.py::_mirror_verified_to_embeddings::1 write +server/memory/app/webhooks.py::handle_webhook_register::timeout::1 write # a host unresolved within the ack bound is refused: ValidationError raised below +server/tracker/app/binding.py::bindings::1 settings # a malformed bindings setting binds nothing, logged once at error +server/tracker/app/contract.py::warm_at_boot::1 logged_only_nonanswer # the boot warm-up; a failed source is checked lazily on its first read +server/tracker/app/dupcheck_candidates.py::_LegRetry.run::timeout::1 deadline # the retry is cut at the op's own deadline; its legs stay unavailable in leg_status +server/tracker/app/dupcheck_fit.py::refit_namespace::1 write # the weekly refit; last week's fit keeps serving +server/tracker/app/dupcheck_legs.py::op_budget_ms::1 settings # a failed budget lookup holds the check to the declared budget +server/tracker/app/embed_index.py::catch_up::1 write # the hits are served; the embed pass writes the rows later +server/tracker/app/onboarding.py::_read_one_row_each::1 noted_by_caller # the failure is the finding: sources._probe_or_refuse refuses VIEWS_NOT_READABLE +server/tracker/app/onboarding.py::_read_one_row_each_mapped::1 noted_by_caller # the failure is the finding: sources._mapped_report_or_refuse refuses VIEWS_NOT_READABLE +server/tracker/app/onboarding.py::probe_credential::3 write # closing the probe's client; the probe's result is whole +server/tracker/app/registry.py::ensure_configured_tracker_namespaces::1 logged_only_nonanswer # the boot registration of the configured tracker namespaces +server/tracker/app/router.py::_record::1 telemetry # the section's QA metric +server/tracker/app/sources.py::_admits::1 noted_by_caller # refuses; sources._authority marks it the server's with note_answered_unverified +server/tracker/app/sources.py::_breaker_view::1 full_answer_fallback # a source with no breaker slot has failed nothing: CLOSED is its state +server/tracker/app/sources.py::_publish::1 write # publishing the view for other processes; this answer is whole +server/tracker/app/sources.py::_published::1 cache_fallback # a failed read of the published view reads the source live +server/tracker/app/sources.py::_published::2 cache_fallback # an unparsable published view reads the source live +server/tracker/app/sources.py::handle_tracker_source_remove::1 write # the source is retired either way; namespaces_retired lists what was +server/tracker/app/test_signal.py::_baseline::1 full_answer_fallback # the live statement reads the window's baseline +server/tracker/app/test_signal.py::_rollup_leg::1 full_answer_fallback # the live read takes the whole window +server/tracker/app/test_signal.py::_storm_leg::1 full_answer_fallback # the live read takes every failing hour diff --git a/tests/unit/test_bulk_identity_dedup.py b/tests/unit/test_bulk_identity_dedup.py index 4f2283baca5..05c2eb600e9 100644 --- a/tests/unit/test_bulk_identity_dedup.py +++ b/tests/unit/test_bulk_identity_dedup.py @@ -18,6 +18,7 @@ from server.memory.app import bulk_set as _bulk_set_mod from server.memory.app import session_summary as _session_summary_mod from server.memory.app.extract import handler as mem_extract +from server.observability import degradations from tests.unit import clickhouse_local from tests.unit.memory_rows import projection_row @@ -153,6 +154,7 @@ async def test_lookup_failure_is_fail_open(harness) -> None: harness(ch) out = await mem_extract.handle_memory_bulk_set(_input()) assert len(_memory_rows(ch)) == 1 and out.identity_duplicates == {} + assert "memory: identity_dedup_unchecked (RuntimeError)" in degradations.current() @pytest.mark.asyncio diff --git a/tests/unit/test_code_bisect_deadline.py b/tests/unit/test_code_bisect_deadline.py index e1862a67e73..d09c75ec4f9 100644 --- a/tests/unit/test_code_bisect_deadline.py +++ b/tests/unit/test_code_bisect_deadline.py @@ -15,6 +15,8 @@ from server.code.app import bisect as cb from server.code.app import bisect_facts, bisect_fix +from server.observability import degradations +from server.settings import settings from server.tracker.domain import bisect as bi @@ -69,9 +71,12 @@ async def merge_commit_of(self, org: str, ns: str, pr: int) -> str: _reset(tokens) +@pytest.mark.parametrize("deadline_s", [0.7, None]) def test_a_slow_fix_blame_stops_at_the_deadline_not_its_own_budget( - monkeypatch: pytest.MonkeyPatch, + monkeypatch: pytest.MonkeyPatch, deadline_s: float | None ) -> None: + """Cut by the caller's deadline the stage says `deadline` and notes nothing; cut by its + own fixed budget (`code_bisect_fix_blame_budget_s`) it says `timeout` and is noted.""" from server.code.app import blame as code_blame from server.code.app.index import gitrepo, mirrors from server.code.domain.index import fix_blame as fb @@ -97,13 +102,52 @@ async def served(cfg: Any, **_k: Any) -> tuple[str, str]: monkeypatch.setattr( fb, "pre_image_ranges", lambda diff: [SimpleNamespace(path="src/a.cpp", start=1, end=2)] ) - tokens = _with_deadline(0.7) + if deadline_s is None: + monkeypatch.setattr(settings, "code_bisect_fix_blame_budget_s", 0.7) + + async def stage() -> tuple[Any, dict[str, Any], list[str]]: + out, summary = await bisect_fix._fix_blame_stage(Repo(), "o", "n", _pool(), 5) # type: ignore[arg-type] + return out, summary, degradations.current() + + tokens = _with_deadline(deadline_s) try: t0 = time.monotonic() - out, summary = asyncio.run(bisect_fix._fix_blame_stage(Repo(), "o", "n", _pool(), 5)) # type: ignore[arg-type] + out, summary, notes = asyncio.run(stage()) assert time.monotonic() - t0 < 1.5, "answered at the deadline, not after 8 s" - assert out == _pool() and summary["skipped"] == "deadline" - assert bisect_facts._CUT.get() == ["fix_blame"] + if deadline_s is None: + assert out == _pool() and summary["skipped"] == "timeout" + assert bisect_facts._CUT.get() == [] + assert notes == ["git_mirror: fix_blame_timed_out (TimeoutError)"] + else: + assert out == _pool() and summary["skipped"] == "deadline" + assert bisect_facts._CUT.get() == ["fix_blame"] + assert notes == [] + finally: + _reset(tokens) + + +@pytest.mark.parametrize("deadline_s", [0.2, None]) +def test_a_duplicate_check_past_its_budget_is_noted_and_one_past_the_deadline_is_not( + monkeypatch: pytest.MonkeyPatch, deadline_s: float | None +) -> None: + monkeypatch.setattr(settings, "code_bisect_dupcheck_timeout_s", 30.0 if deadline_s else 0.2) + + async def run() -> tuple[dict[str, Any], list[str]]: + task = asyncio.ensure_future(asyncio.sleep(30)) + try: + return await bisect_fix._dupcheck_fix(task, time.monotonic()), degradations.current() + finally: + task.cancel() + + tokens = _with_deadline(deadline_s) + try: + out, notes = asyncio.run(run()) + if deadline_s is None: + assert out == {"status": "timeout", "budget_s": 0.2} + assert notes == ["tracker: dupcheck_fix_timed_out (TimeoutError)"] + else: + assert out == {"status": "deadline", "budget_s": 30.0} + assert notes == [] finally: _reset(tokens) diff --git a/tests/unit/test_code_search_deadline.py b/tests/unit/test_code_search_deadline.py index cf888f2afaf..3db6cd31d73 100644 --- a/tests/unit/test_code_search_deadline.py +++ b/tests/unit/test_code_search_deadline.py @@ -30,6 +30,7 @@ from server.code.app.search import rerank as cs_rerank from server.code.app.search.rerank import _rerank_stage from server.code.app.search.voting import _voting_leg_config +from server.observability import degradations from server.settings import settings _UNIT = dict( @@ -156,20 +157,27 @@ def _run( patch("server.llm.client.get_llm_client_for_model", lambda m: _LLM()), ): t0 = time.perf_counter() - res = asyncio.run( - cs.search( - repo, - "o", - "n", - query=kw.pop("query", _QUESTION), - top_k=5, - embedder=_Embedder(), - **kw, - ) - ) + res = asyncio.run(_search(repo, **kw)) return repo, res, time.perf_counter() - t0 +# The `degraded` entries of the last `_run`. +_NOTES: list[str] = [] + + +def _llm_notes() -> list[str]: + # The fake repo reads no fan-in, which adds its own entry. + return [n for n in _NOTES if n.startswith("llm:")] + + +async def _search(repo: _Repo, **kw: Any) -> Any: + res = await cs.search( + repo, "o", "n", query=kw.pop("query", _QUESTION), top_k=5, embedder=_Embedder(), **kw + ) + _NOTES[:] = degradations.current() + return res + + # ---- llm_legs ------------------------------------------------------------------------------- @@ -267,8 +275,15 @@ def test_no_deadline_is_served_as_before() -> None: def test_grace_bounds_hyde_past_the_plain_legs() -> None: - _, res, wall = _run(llm_delay=2.0, grace_ms=100) - assert wall < 1.0 and res.legs_timed_out == ["hyde"] and res.epistemic == "partial" + """The grace is a fixed bound: a HyDE leg it cuts, with no deadline or with time + left, is named in `degraded`; one a deadline cuts first is the budget working.""" + for deadline_ms in (None, 5000): + _, res, wall = _run(llm_delay=2.0, grace_ms=100, deadline_ms=deadline_ms) + assert wall < 1.0 and res.legs_timed_out == ["hyde"] and res.epistemic == "partial" + assert _llm_notes() == ["llm: hyde_leg_dropped (past its grace)"] + with patch.object(cs_gather, "MODEL_LEG_MIN_MS", 0): + _, res, _ = _run(llm_delay=2.0, grace_ms=5000, deadline_ms=400) + assert res.legs_timed_out == ["hyde"] and _llm_notes() == [] def test_the_deadline_waits_for_the_first_content_leg() -> None: diff --git a/tests/unit/test_conversation_search_service.py b/tests/unit/test_conversation_search_service.py index 4aea972772d..62edb7538a8 100644 --- a/tests/unit/test_conversation_search_service.py +++ b/tests/unit/test_conversation_search_service.py @@ -201,6 +201,39 @@ async def fake_search_substring(*a, **k): assert hit.content_excerpt == content[:240] +async def test_a_search_the_embedder_failed_answers_by_substring_and_says_so( + monkeypatch, +) -> None: + """`conversation.search` and `loom_search`'s conversation leg answer by substring + when the query embed raises, and name it in `degraded`.""" + from server.knowledge.api.models_conversations import ConversationSearchInput + from server.knowledge.app import conversations as h + from server.knowledge.store import conversations as conversation_repo + from server.observability import degradations + + class _Down: + model_name = "m" + + async def embed(self, text): + raise RuntimeError("embedder down") + + async def namespaces(*a, **k): + return ["ns"], [] + + async def substring(*a, **k): + return [] + + monkeypatch.setattr(h, "get_embedder", lambda: _Down()) + monkeypatch.setattr(h, "namespaces_to_search", namespaces) + monkeypatch.setattr(conversation_repo, "search_substring", substring) + out = await h._search_conversations( + ConversationSearchInput(org="o", namespace="ns", agent="a", query="deploy"), + saved_only=False, + ) + assert out.hits == [] + assert degradations.current() == ["embedder: conversation_substring_fallback (RuntimeError)"] + + @pytest.mark.asyncio async def test_vector_search_holds_back_a_row_whose_text_reads_as_a_credential() -> None: """An embedding row an earlier build wrote for a credential turn is never a hit, even diff --git a/tests/unit/test_degraded_unnoted.py b/tests/unit/test_degraded_unnoted.py index 4fa9a10605c..f08b4819c0b 100644 --- a/tests/unit/test_degraded_unnoted.py +++ b/tests/unit/test_degraded_unnoted.py @@ -1,10 +1,12 @@ -"""Every broad `except` in the code and memory apps either names its fallback in -`degraded` or is listed, with why it need not, in `degraded_unnoted.txt`; and every +"""Every broad `except`, and every `except TimeoutError` that does not raise, in the +code, memory, knowledge and tracker apps and the LLM clients either names its fallback +in `degraded` or is listed, with why it need not, in `degraded_unnoted.txt`; and every fallback that feeds provider health names a provider whose success clears it. The scan reads each handler and gather branch on its own, so it does not see a result tested in another function, `asyncio.wait`, an `isinstance` filter that keeps the -successes, an exception test inside a `BoolOp`, or which call of a noting helper runs.""" +successes, an exception test inside a `BoolOp`, a handler of a narrower exception than a +timeout, or which call of a noting helper runs.""" from __future__ import annotations @@ -14,14 +16,36 @@ from server.core.paths import REPO_ROOT -_DIRS = ("server/code/app", "server/memory/app") +_DIRS = ( + "server/code/app", + "server/memory/app", + "server/knowledge/app", + "server/tracker/app", + "server/llm", +) _INDEX = "server/code/app/index/" _INDEX_PKG = "server.code.app.index" -# The ingest pass that `code.refresh` and the ingest worker run: it writes the index, +# The ingest pass that `code.refresh` and the ingest worker run, with the per-file +# ingest it alone calls (`bootstrap.index_slice` is the pass's): it writes the index, # and its notes reach no answer, like the workers and stores outside these dirs. -_INGEST_PASS = {"ingest_pass", "pass_stream", "entry_lock", "erasing"} -# Read on a request through a scanned module: the review brief's build reads the fit. -_ALSO_SCANNED = {"risk_fit"} +_INGEST_PASS = { + "ingest_pass", + "pass_stream", + "entry_lock", + "erasing", + "ingest", + "ingest_chunks", + "ingest_edges", + "ingest_reconcile", + "ingest_resolve", + "round_reads", + "pass_fetch", + "compiler_tier", + "dependents", + "describe", + "embed_reuse", + "embed_text", +} _ALLOWLIST = Path(__file__).with_name("degraded_unnoted.txt") _CATEGORIES = { # a cache, memo or precomputed read that falls back to the live read @@ -38,6 +62,10 @@ "logged_only_nonanswer", # the caller names the fallback from what the handler returns (the comment says where) "noted_by_caller", + # a timeout of the request's own deadline or budget: the budget working, not a fallback + "deadline", + # a security or privacy check that cannot be read refuses, as it does when it refuses + "fail_closed", } _NOTES = {"partial", "note", "restore"} _EXCEPTION_TYPES = {"Exception", "BaseException"} @@ -50,6 +78,16 @@ def _broad(h: ast.ExceptHandler) -> bool: return any(isinstance(n, ast.Name) and n.id in _EXCEPTION_TYPES for n in names) +def _timeout(h: ast.ExceptHandler) -> bool: + """`except TimeoutError` or `except asyncio.TimeoutError`, alone or in a tuple.""" + names = h.type.elts if isinstance(h.type, ast.Tuple) else [h.type] + return any( + (isinstance(n, ast.Name) and n.id == "TimeoutError") + or (isinstance(n, ast.Attribute) and n.attr == "TimeoutError") + for n in names + ) + + def _is_degradations(node: ast.expr) -> bool: return isinstance(node, ast.Name) and node.id.lstrip("_") == "degradations" @@ -178,18 +216,30 @@ def _index_modules_imported(tree: ast.Module) -> set[str]: def _scanned_index_modules() -> set[str]: - """The `server/code/app/index/` modules a request runs: those the code and memory - apps import from outside the package, except the ingest pass.""" - imported = set(_ALSO_SCANNED) - for rel, tree in _trees().items(): + """The `server/code/app/index/` modules a request runs: those the scanned apps import + from outside the package, and those these import in turn, except the ingest pass.""" + trees = _trees() + todo: set[str] = set() + for rel, tree in trees.items(): if not rel.startswith(_INDEX): - imported |= _index_modules_imported(tree) - return {f"{_INDEX}{m}.py" for m in imported - _INGEST_PASS} + todo |= _index_modules_imported(tree) + seen: set[str] = set() + while todo: + m = todo.pop() + if m in seen or m in _INGEST_PASS: + continue + seen.add(m) + tree = trees.get(f"{_INDEX}{m}.py") + if tree is not None: + todo |= _index_modules_imported(tree) + return {f"{_INDEX}{m}.py" for m in seen} def _unnoted() -> list[str]: """`path::enclosing.qualname::ordinal` of each broad handler that notes nothing, the - ordinal counting the broad handlers of that function in source order; and + ordinal counting the broad handlers of that function in source order; + `path::enclosing.qualname::timeout::ordinal` of each timeout handler that notes + nothing, counted the same way among that function's timeout handlers; and `path::enclosing.qualname::gather::ordinal` of each exception branch over a `return_exceptions=True` result that notes nothing, counted the same way.""" out: list[str] = [] @@ -220,6 +270,11 @@ def visit( counts[q] = counts.get(q, 0) + 1 if not _notes(child, helpers): out.append(f"{rel}::{q}::{counts[q]}") + elif isinstance(child, ast.ExceptHandler) and child.type and _timeout(child): + q = f"{qual or ''}::timeout" + counts[q] = counts.get(q, 0) + 1 + if not _notes(child, helpers): + out.append(f"{rel}::{q}::{counts[q]}") visit(child, qual) visit(tree, "") diff --git a/tests/unit/test_llm_fallback.py b/tests/unit/test_llm_fallback.py index 4a399f30414..73cfcc43e80 100644 --- a/tests/unit/test_llm_fallback.py +++ b/tests/unit/test_llm_fallback.py @@ -11,6 +11,7 @@ from server.llm.client import LLMResult from server.llm.fallback import FallbackLLMClient, hands_over, is_provider_outage +from server.observability import degradations class _Client: @@ -71,6 +72,7 @@ async def test_primary_answers_when_healthy() -> None: fb = FallbackLLMClient(p, s) res = await fb.complete("sys", "user") assert res.model == "strong" and s.calls == 0 and fb.fallbacks == 0 + assert degradations.current() == [] assert fb.model == "strong" and fb.provider == "fake" @@ -86,6 +88,8 @@ async def test_outage_falls_through_to_secondary_and_is_counted(monkeypatch) -> assert res.model == "cheap" and res.text == "from cheap" assert p.calls == 1 and s.calls == 1 and fb.fallbacks == 1 assert recorded == [{"from_model": "strong", "to_model": "cheap", "reason": "http_503"}] + # The answer names the model that stood in, for `memory.ask` and `code.ask` alike. + assert degradations.current() == ["llm: fallback_model_answered (http_503)"] async def test_configuration_errors_do_not_fall_back() -> None: diff --git a/tests/unit/test_memory_repo.py b/tests/unit/test_memory_repo.py index bf5b4609493..e259da7c60c 100644 --- a/tests/unit/test_memory_repo.py +++ b/tests/unit/test_memory_repo.py @@ -180,6 +180,31 @@ async def test_get_by_key_can_overlay_usage_totals() -> None: assert usage_params["mid"] == "11111111-2222-3333-4444-555555555555" +@pytest.mark.asyncio +async def test_a_usage_totals_read_that_fails_keeps_the_rows_counters_and_says_so() -> None: + from server.memory.store.reads import overlay_usage_totals_many + from server.observability import degradations + + class _Down(StubCH): + async def query_one(self, sql: str, params: dict[str, Any] | None = None): + if "memory_usage_totals" in sql: + raise ConnectionError("totals unread") + return await super().query_one(sql, params) + + async def query_all(self, sql: str, params: dict[str, Any] | None = None): + raise ConnectionError("totals unread") + + ch = _Down() + ch.query_one_returns.append(_sample_row()) + identity = Identity(org="clickhouse", namespace="personal-alice", agent="claude-desktop") + row = await get_by_key( + identity, "deploy_window", ch=ch, include_usage_totals=True, scope=WHOLE_NAMESPACE + ) + assert row is not None and row.recall_count == 0 + assert await overlay_usage_totals_many([row], ch=ch) == [row] + assert degradations.current() == ["memory: usage_totals_unread (ConnectionError)"] + + @pytest.mark.asyncio async def test_list_by_namespace_applies_filters_and_limit() -> None: """list_by_namespace honors memory_type filter, pinned_only filter, diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index 612f44a40b5..5bff67483ac 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -86,6 +86,40 @@ async def _failed(cfg: Any) -> str: assert degradations.current() == ["git_mirror: clone_failed (git clone failed (exit 128))"] +@pytest.mark.asyncio +async def test_a_present_mirror_whose_fetch_failed_serves_and_names_it( + monkeypatch, tmp_path +) -> None: + """A present mirror that lacks the head serves as it is: while the fetch for it + runs that is ordinary lag; once that fetch failed, each read names it.""" + from server.observability import degradations + + fail = asyncio.Event() + + async def _failed(cfg: Any) -> str: + await fail.wait() + return "git fetch failed (exit 128)" + + async def lacks(git_dir: str, *args: str) -> str: + raise gitrepo.GitError("missing", returncode=1) + + monkeypatch.setattr(bootstrap, "fetch_mirror", _failed) + monkeypatch.setattr(bootstrap, "_FOREIGN", {}) + monkeypatch.setattr(bootstrap, "_HAVE", set()) + monkeypatch.setattr(gitrepo, "run", lacks) + cfg = _Cfg(str(tmp_path / "r.git")) + os.makedirs(cfg.git_dir) + head = "a" * 40 + with degradations.unit(): + assert await mirrors.history_dir(cfg, head=head) == (cfg.git_dir, "") + assert degradations.current() == [] + fail.set() + await bootstrap._MIRROR_JOBS[("fetch", cfg.git_dir)][0] + with degradations.unit(): + assert await mirrors.history_dir(cfg, head=head) == (cfg.git_dir, "") + assert degradations.current() == ["git_mirror: fetch_failed (git fetch failed (exit 128))"] + + @pytest.mark.asyncio async def test_without_the_sandbox_a_read_clones_a_self_registered_mirror_only_with_the_git_waiver( monkeypatch, tmp_path diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index e421ec34ea5..5eef00f7216 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -14,6 +14,7 @@ from server.auth.context import set_current_auth from server.auth.jwt import AuthInfo, TokenError from server.core import readiness +from server.core.errors import BackendUnavailableError, WrongCellError from server.insights.api.models_ops import OpsIncidentsInput, OpsIncidentsOutput from server.insights.app import incidents from server.insights.app.incidents import handle_ops_incidents @@ -353,6 +354,19 @@ async def test_an_org_admin_with_a_restricted_namespace_hidden_reads_no_counts( hidden.return_value = (["code-secret"], True) # its grant could not be read out = await _incidents() assert (out.incidents, out.requests) == ([], "unread") + + # A platform administrator's repository read checks the org's tenancy: a cell that + # cannot tell, or another cell's org, reads no counts and the other sources answer. + for refused, kind in ( + (BackendUnavailableError("tenancy unread"), "BACKEND_UNAVAILABLE"), + (WrongCellError("acme", cell="b"), "WRONG_CELL"), + ): + degradations.begin() + hidden.side_effect = refused + out = await _incidents() + assert (out.incidents, out.requests) == ([], "unread") + assert degradations.current() == [f"ops.incidents: requests_unread ({kind})"] + hidden.side_effect = None assert ch.statements("sli_minute") == [] diff --git a/tests/unit/test_pr_post_image.py b/tests/unit/test_pr_post_image.py index c0347d0c1e5..43363dff0d1 100644 --- a/tests/unit/test_pr_post_image.py +++ b/tests/unit/test_pr_post_image.py @@ -485,6 +485,69 @@ def raised(path: str, source: bytes) -> tuple[ParsedFile, str]: assert notes == ["code_index: overlay_files_unread (1 changed file(s))"] +def test_a_noted_overlay_is_not_kept_and_the_next_load_parses_again( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An overlay whose build noted a fallback (a failed name read) is served and not + kept, so the next load parses the PR again; a whole one is kept. A head the store + cannot place is noted and answers as a head the mirror lacks.""" + from server.code.app.index import history_bound + from server.observability import degradations + + head = "a" * 40 + + async def tips(*a: Any) -> tuple[str, str, str]: + return head, "c" * 40, "" + + async def base(*a: Any) -> str: + return "b" * 40 + + async def diff(*a: Any, **kw: Any) -> str: + return DIFF + + async def names(*a: Any) -> list[str]: + return [PATH] + + async def show(*a: Any, **kw: Any) -> bytes: + return POST.encode() + + for name, fake in (("merge_base", base), ("run", diff), ("diff_name_only", names)): + monkeypatch.setattr(gitrepo, name, fake) + monkeypatch.setattr(gitrepo, "show_file", show) + monkeypatch.setattr(history_bound, "pull_tips", tips) + + class _Flaky(_Repo): + reads = 0 + + async def name_candidates(self, org: str, ns: str, names: list[str]) -> Any: + type(self).reads += 1 + if type(self).reads == 1: + raise ConnectionError("names unread") + return await super().name_candidates(org, ns, names) + + async def load() -> tuple[po.PrOverlay, list[str]]: + with degradations.unit(): + ov = await po.load_pr_overlay( + _Flaky(), "acme", "code-ch", git_dir="/g", pr_number=7, branch="master" + ) + return ov, degradations.current() + + first, notes = asyncio.run(load()) + assert first.ok and notes == ["code_index: overlay_names_unread (ConnectionError)"] + second, notes = asyncio.run(load()) + assert second is not first and notes == [] and _Flaky.reads == 2 + third, notes = asyncio.run(load()) + assert third is second and notes == [] and _Flaky.reads == 2 + + async def unplaced(*a: Any) -> Any: + raise RuntimeError("ledger unread") + + monkeypatch.setattr(history_bound, "pull_tips", unplaced) + ov, notes = asyncio.run(load()) + assert ov.reason == po.HEAD_NOT_IN_MIRROR + assert notes == ["code_index: pr_head_unread (RuntimeError)"] + + def test_an_open_brief_over_a_partial_overlay_is_served_unstored( monkeypatch: pytest.MonkeyPatch, ) -> None: From 40b4201821fe463277804172b97c3f78df669d8c Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 03:37:54 +0530 Subject: [PATCH 26/47] Name a mirror read failure only where every reader sees it A private mirror leg notes knowledge: mirror_unread, the marker the document-sources rule defines, only when a read it issues for every request fails: the registrations, bindings and listing starts, the reader's identity, a discovery statement. A read issued only for candidates (lists, members, heads) or for an admitted document drops the mirrored results with no note, since its failure depends on whether a hidden document matched. Those handlers are listed fail_closed. request_work.http_mirror_unread had no reader and is removed. A literal definitions read past its fixed bound is the answer for a literal many functions hold, so it notes nothing and is listed under the new answer category. The duplicate check names each leg still down after its retry, tracker.similar names its dropped legs and linked trackers, and a degraded duplicate check is no longer remembered for code.bisect_candidates to reuse. The fallback model is noted once its answer is in hand. A contract whose table is absent notes nothing. connection.list notes a standing read that failed, mentor.brief its writers and adoption reads, and namespace.list_mine its inherited rows and metadata. A malformed stored namespace map is a settings entry, and a knowledge gap's unread erasure ledger, which refuses, is fail_closed. A table-driven test drives each note the scan added that no other test drove and asserts it, the term leg's two timeouts and the rerank pool among them. The usage-totals test checks each of its two reads on its own: one note listed for both hid the absence of either. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/document-sources.md | 13 +- server/code/app/search/definitions.py | 4 +- server/core/request_work.py | 5 - server/identity/app/namespace_membership.py | 14 +- server/insights/app/mentor_brief.py | 8 +- server/knowledge/app/connected_accounts.py | 11 +- server/knowledge/app/source_access.py | 3 +- server/knowledge/app/source_corpus.py | 2 - server/knowledge/app/source_documents.py | 5 +- server/knowledge/app/source_listing.py | 7 +- server/knowledge/app/source_passages.py | 2 - server/knowledge/app/source_search.py | 3 +- server/knowledge/app/source_search_passes.py | 3 - server/knowledge/app/source_titles.py | 2 - server/llm/fallback.py | 5 +- server/tracker/app/contract.py | 8 +- server/tracker/app/dupcheck.py | 48 +- server/tracker/app/dupcheck_legs.py | 6 +- server/tracker/app/registry_sources.py | 3 +- server/tracker/app/similar.py | 8 +- tests/unit/degraded_unnoted.txt | 23 +- tests/unit/test_code_search_definition_leg.py | 15 +- tests/unit/test_degraded_fallback_notes.py | 739 ++++++++++++++++++ tests/unit/test_degraded_unnoted.py | 6 +- tests/unit/test_dupcheck_links.py | 36 + tests/unit/test_llm_fallback.py | 11 + tests/unit/test_memory_repo.py | 2 + tests/unit/test_source_access_plan.py | 43 +- tests/unit/test_source_documents.py | 5 + tests/unit/test_source_listing.py | 5 + tests/unit/test_source_search_pool.py | 5 + tests/unit/test_tracker_duplicate_check.py | 9 + tests/unit/test_tracker_embed.py | 5 + tests/unit/test_tracker_multi_binding.py | 17 + tests/unit/test_tracker_similar.py | 4 + 35 files changed, 1000 insertions(+), 85 deletions(-) create mode 100644 tests/unit/test_degraded_fallback_notes.py diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 0cb6cfddc20..7ef4f40edcb 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -990,9 +990,10 @@ to someone else), a grant to one view of the file only (`view`), and a permissio or role the sync does not know admit nobody. A missing registry or listing row admits nobody. A leg whose per-request reads (the statements it issues whatever matched, the reader's canonical subject and verified emails among them) fail shows no mirrored -document and marks the answer `degraded: mirror_unread`; a read it issues only for -candidates (the lists, the members rows, the heads) that fails drops every mirrored -result without the marker, so the marker says nothing about what matched. Each leg reads +document and lists `knowledge: mirror_unread` in the answer's `degraded`; a read it +issues only for candidates (the lists, the members rows, the heads) that fails drops +every mirrored result without the marker, so the marker says nothing about what +matched. Each leg reads the registry row and the listing row first and then the members rows and the lists, under `sequential_reads()`, so a lagging replica cannot pair a fresh listing row with an older list. It computes the addresses the reader may see before its `LIMIT`, so a page @@ -1574,9 +1575,9 @@ Each implementing pull request lists its own; these pin the model: - A namespace whose documents are all mirrored ranking by both legs. - The check fails closed: - A leg that cannot read the listing row or the owning source's registry row showing - no mirrored document, marked `degraded: mirror_unread`, and one that cannot read - the lists, the members rows or the heads dropping mirrored results without the - marker. + no mirrored document, its `degraded` naming `knowledge: mirror_unread`, and one + that cannot read the lists, the members rows or the heads dropping mirrored + results without the marker. - The same `degraded` marker for a query that matches a hidden document and one that matches nothing while a mirror read fails. - A failed list, members or heads read with one hidden candidate answering exactly diff --git a/server/code/app/search/definitions.py b/server/code/app/search/definitions.py index fc07450b55b..53036cf59ce 100644 --- a/server/code/app/search/definitions.py +++ b/server/code/app/search/definitions.py @@ -382,12 +382,10 @@ async def _literal_leg( path_prefix=path_prefix, scope=scope, ) - except TimeoutError as e: + except TimeoutError: if not bound.expired(): raise logger.info("code.search literal lookup stopped at its bound of %g s", seconds) - if seconds >= _LITERAL_SECONDS: # the fixed bound cut it, not the request's window - degradations.partial("code_index", "literal_definitions_dropped", e) return [] return literal_definitions(literals, rows) diff --git a/server/core/request_work.py b/server/core/request_work.py index 248f355ae76..aa01b834053 100644 --- a/server/core/request_work.py +++ b/server/core/request_work.py @@ -122,11 +122,6 @@ def http_mirror_marked(scope: Mapping[str, Any] | None = None) -> bool: return isinstance(owner, RequestWork) and owner.mirror_marked -def http_mirror_unread(scope: Mapping[str, Any] | None = None) -> bool: - owner = _http_owner.get() if scope is None else scope.get(_HTTP_OWNER_KEY) - return isinstance(owner, RequestWork) and owner.mirror_unread - - def begin() -> RequestWork: """Bind a fresh bag to the current context and return it.""" bag = RequestWork() diff --git a/server/identity/app/namespace_membership.py b/server/identity/app/namespace_membership.py index 60c4153fc2a..3b1ff5467f2 100644 --- a/server/identity/app/namespace_membership.py +++ b/server/identity/app/namespace_membership.py @@ -28,6 +28,7 @@ ) from server.identity.app import namespace as _registry from server.identity.domain import join_policy as _jp +from server.observability import degradations from server.operations.base import grant_rank @@ -463,8 +464,8 @@ async def _inherited_rows(ch: Any, org: str, caller: str, skip: set[str]) -> lis the gate's rule), so `namespace.list_mine` must list those too, or the doctor and any client asking "what can I read" would see only the token's own rows. Returns the creator's rows for namespaces not in `skip`, minus restricted ones — - inheritance never reads a restricted namespace. Fails open to [] on any error: the list - stays what it was.""" + inheritance never reads a restricted namespace. Fails open to [] on any error, noted: + the list stays what it was.""" from server.auth.service_accounts import inheriting_creator creator = await inheriting_creator(org, caller, ch=ch) @@ -489,6 +490,7 @@ async def _inherited_rows(ch: Any, org: str, caller: str, skip: set[str]) -> lis logging.getLogger(__name__).warning( "namespace.list_mine: restricted set unreadable (%s); no inherited rows", e ) + degradations.partial("namespace.list_mine", "inherited_rows_unread", e) return [] out: list[dict[str, Any]] = [] for r in rows: @@ -501,7 +503,8 @@ async def _inherited_rows(ch: Any, org: str, caller: str, skip: set[str]) -> lis skip.add(ns) out.append(r) return out - except Exception: # noqa: BLE001 — inherited rows are extra; list_mine keeps its own rows + except Exception as e: # noqa: BLE001 — inherited rows are extra; list_mine keeps its own rows + degradations.partial("namespace.list_mine", "inherited_rows_unread", e) return [] @@ -610,7 +613,7 @@ async def handle_namespace_list_mine( async def _namespace_meta(ch: Any, org: str, namespaces: list[str]) -> dict[str, dict[str, str]]: - """kind/visibility/title/description for a handful of namespaces; {} on error + """kind/visibility/title/description for a handful of namespaces; {} on error, noted (fail-open to the private defaults and the name's kind — never sink list_mine).""" try: rows = await ch.query_all( @@ -621,7 +624,8 @@ async def _namespace_meta(ch: Any, org: str, namespaces: list[str]) -> dict[str, """, params={"org": org, "ns": namespaces}, ) - except Exception: # noqa: BLE001 — rows list without metadata + except Exception as e: # noqa: BLE001 — rows list without metadata + degradations.partial("namespace.list_mine", "metadata_defaulted", e) return {} return { str(r["namespace"]): { diff --git a/server/insights/app/mentor_brief.py b/server/insights/app/mentor_brief.py index 7ca3564e650..3809a3b8f0b 100644 --- a/server/insights/app/mentor_brief.py +++ b/server/insights/app/mentor_brief.py @@ -25,6 +25,7 @@ from server.insights.app import mentor as svc from server.insights.app import mentor_rules from server.insights.store import mentor as mentor_store +from server.observability import degradations from server.settings import settings log = logging.getLogger(__name__) @@ -60,7 +61,7 @@ def _caller_agent(inp: MentorBriefInput) -> str: async def _top_writers(org: str, namespace: str, window_seconds: int) -> list[str]: """The namespace's writers in the window, most active first — the agents a brief is about. Anonymous names and the dashboard are left out. One - bounded read; a failure is an empty list.""" + bounded read; a failure is an empty list, noted.""" try: return await mentor_store.top_writers( org, @@ -74,6 +75,7 @@ async def _top_writers(org: str, namespace: str, window_seconds: int) -> list[st ) except Exception as exc: # noqa: BLE001 — the brief omits writers log.warning("mentor top writers read failed: %s", exc) + degradations.partial("mentor.brief", "writers_unread", exc) return [] @@ -128,13 +130,14 @@ async def _adoption(profile: mentor_rules.MentorProfile) -> list[MentorAdoption] before a `duplicates_written` hint and again after it followed it). Only client-named sessions count: the placeholder ids ('-', '*') a client sends when it names none are one bucket, not a session. - Two bounded reads; a failure is an empty list.""" + Two bounded reads; a failure is an empty list, noted.""" ch = get_client() who = (profile.org, profile.namespace, profile.agent, int(profile.window_seconds)) try: shown = await mentor_store.hints_shown(*who, cap=ADOPTION_ROW_CAP, ch=ch) except Exception as exc: # noqa: BLE001 — the brief omits adoption log.warning("mentor adoption read failed: %s", exc) + degradations.partial("mentor.brief", "adoption_unread", exc) return [] if not shown: return [] @@ -143,6 +146,7 @@ async def _adoption(profile: mentor_rules.MentorProfile) -> list[MentorAdoption] later = await mentor_store.last_calls(*who, sessions=sessions, ch=ch) except Exception as exc: # noqa: BLE001 — the brief omits adoption log.warning("mentor adoption follow-up read failed: %s", exc) + degradations.partial("mentor.brief", "adoption_unread", exc) return [] last_call: dict[tuple[str, str], Any] = { (str(r["session_id"]), str(r["operation"])): r["last_ts"] for r in later diff --git a/server/knowledge/app/connected_accounts.py b/server/knowledge/app/connected_accounts.py index 4901d7ff95c..7c444e8b5fa 100644 --- a/server/knowledge/app/connected_accounts.py +++ b/server/knowledge/app/connected_accounts.py @@ -43,7 +43,7 @@ from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource from server.knowledge.store import connected_accounts as store from server.knowledge.store import sources as source_store -from server.observability import audit +from server.observability import audit, degradations from server.operations.base import Role from server.settings import settings @@ -908,7 +908,9 @@ async def validate_indexed(source: KnowledgeSource, auth: AuthInfo | None) -> No async def available(account: ConnectedAccount) -> bool: - """An owner-visible active projection must honor the same authoritative fence.""" + """An owner-visible active projection must honor the same authoritative fence. A + refusal answers False; a read that fails answers False too, noted, since the caller + asks about their own account only.""" if not account.active or not account.credential_enc: return False try: @@ -918,7 +920,10 @@ async def available(account: ConnectedAccount) -> bool: return bool( unseal(CREDENTIAL_PURPOSE, account.credential_enc, warn=False) ) and await _fence_current(account) - except Exception: # noqa: BLE001 — unknown registration standing is never reported usable + except ValidationError: # a refusal: standing lost, or the provider unconfigured + return False + except Exception as e: # noqa: BLE001 — unknown registration standing is never reported usable + degradations.partial("knowledge", "connection_unchecked", e) return False diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index e3ca0d450a8..c720873397b 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -138,7 +138,6 @@ async def check( with sequential_reads(), private_work(): return await self._check(candidates, chunks=chunks) except Exception: # noqa: BLE001 — a failed candidate read must disclose no partial leg - degradations.partial("knowledge", "mirror_leg_dropped") self.failed = True return [] @@ -303,7 +302,7 @@ async def prepare(org: str, namespaces: list[str]) -> ReadPlan: ) ) except Exception: # noqa: BLE001 — unreadable unconditional evidence must fail closed uniformly - degradations.partial("knowledge", "mirror_leg_dropped") + degradations.partial("knowledge", "mirror_unread") plan.marked = plan.unread = True request_work.mark_mirrored(unread=True) return plan diff --git a/server/knowledge/app/source_corpus.py b/server/knowledge/app/source_corpus.py index 89b4037502c..a80bb175c62 100644 --- a/server/knowledge/app/source_corpus.py +++ b/server/knowledge/app/source_corpus.py @@ -13,7 +13,6 @@ from server.knowledge.app.source_access import AccessEvidence, Admitted, ReadPlan from server.knowledge.domain.chunk_metadata import read_structure from server.memory.domain.corpus_synthesis import CorpusChunk -from server.observability import degradations from server.observability.genai import current_stage, llm_stage @@ -207,7 +206,6 @@ async def load( try: document = await _mirror(plan, namespace, uri, model) except Exception: # noqa: BLE001 — a conditional mirror failure cannot publish a partial corpus - degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True document = _Document([]) by_uri[uri] = document diff --git a/server/knowledge/app/source_documents.py b/server/knowledge/app/source_documents.py index 786d49a0cda..3214a68df6e 100644 --- a/server/knowledge/app/source_documents.py +++ b/server/knowledge/app/source_documents.py @@ -43,7 +43,7 @@ async def _discover(plan: ReadPlan, pairs: list[tuple[str, str]]) -> list[dict[s wanted.remove(key) out.append({"namespace": key[0], "source_uri": key[1]}) except Exception: # noqa: BLE001 — every selected discovery read must fail closed uniformly - degradations.partial("knowledge", "mirror_leg_dropped") + degradations.partial("knowledge", "mirror_unread") plan.failed = plan.unread = True request_work.mark_mirrored(unread=True) return out @@ -72,7 +72,6 @@ async def refresh(plan: ReadPlan, document: CheckedDocument) -> CheckedDocument if _same(document.row, plan, item) and plan.current(item): return CheckedDocument(item, document.row) except Exception: # noqa: BLE001 — conditional revalidation cannot authorize an open copy - degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return None @@ -121,7 +120,6 @@ async def get(plan: ReadPlan, namespace: str, source_uri: str) -> CheckedDocumen if refreshed is not None: return refreshed except Exception: # noqa: BLE001 — conditional content or permission failure invalidates all copies - degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return None @@ -174,6 +172,5 @@ async def chunks(plan: ReadPlan, document: CheckedDocument, *, model: str) -> li and plan.current(proof[_chunk_key(item.admitted.candidate)]) ] except Exception: # noqa: BLE001 — conditional chunk failure invalidates the entire document - degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return None diff --git a/server/knowledge/app/source_listing.py b/server/knowledge/app/source_listing.py index 0af43ce46c6..da5ec719cdb 100644 --- a/server/knowledge/app/source_listing.py +++ b/server/knowledge/app/source_listing.py @@ -83,7 +83,6 @@ async def stage(self, item: Admitted | None) -> None: if item is not None and _matches(item, self.input, self.cursor): self.pending.append(item) except Exception: # noqa: BLE001 — invalid admitted metadata is a conditional leg failure - degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True if len(self.pending) == 64: await self.flush() @@ -108,7 +107,6 @@ async def flush(self) -> None: if len(self.heap) > self.input.limit + 1: heapq.heappop(self.heap) except Exception: # noqa: BLE001 — conditional shadow failure invalidates the mirror leg - degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True async def take(self, batch: list[dict[str, Any]]) -> None: @@ -123,7 +121,6 @@ async def take(self, batch: list[dict[str, Any]]) -> None: raise ValueError("unexpected list admission identity") admitted[key] = proof except Exception: # noqa: BLE001 — candidate checks cannot change unconditional discovery - degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True for row in batch: namespace, uri = row["namespace"], row["source_uri"] @@ -153,7 +150,6 @@ async def take(self, batch: list[dict[str, Any]]) -> None: ): self.winner = item except Exception: # noqa: BLE001 — invalid admitted metadata cannot affect unread status - degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True @@ -198,7 +194,7 @@ async def select( await selected.stage(selected.winner) await selected.flush() except Exception: # noqa: BLE001 — fixed metadata discovery failure discloses no partial list - degradations.partial("knowledge", "mirror_leg_dropped") + degradations.partial("knowledge", "mirror_unread") plan.failed = plan.unread = True request_work.mark_mirrored(unread=True) return ( @@ -310,6 +306,5 @@ async def collect( except LostCorpus: pass except Exception: # noqa: BLE001 — selected fields, counts and final proofs fail closed together - degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return Listing([], ListProofs(plan, input.include_superseded, ())) diff --git a/server/knowledge/app/source_passages.py b/server/knowledge/app/source_passages.py index 386f8aa880d..56005f50fbb 100644 --- a/server/knowledge/app/source_passages.py +++ b/server/knowledge/app/source_passages.py @@ -16,7 +16,6 @@ from server.knowledge.app.source_search_proofs import SearchProofs from server.memory.app.agent_rules import request_rule_agent, served_hits from server.memory.domain.assistant_rules import hits_to_ask -from server.observability import degradations @dataclass @@ -121,7 +120,6 @@ async def current(self) -> list[_SearchHit]: try: wide = (await self._wide.current()).results except Exception: # noqa: BLE001 — discard mixed work if an optional renewal fails - degradations.partial("knowledge", "mirror_leg_dropped") return await self._fallback() if not self.fresh(): return await self._fallback() diff --git a/server/knowledge/app/source_search.py b/server/knowledge/app/source_search.py index 20a727c6009..c526a271dc3 100644 --- a/server/knowledge/app/source_search.py +++ b/server/knowledge/app/source_search.py @@ -92,7 +92,7 @@ async def take(batch: list[dict[str, Any]]) -> None: if batch and len(out) < limit: await take(batch) except Exception: # noqa: BLE001 — an unconditional discovery failure invalidates every mirror leg - degradations.partial("knowledge", "mirror_leg_dropped") + degradations.partial("knowledge", "mirror_unread") plan.failed = plan.unread = True request_work.mark_mirrored(unread=True) return [] if plan.failed or plan.unread else out @@ -165,7 +165,6 @@ async def hydrate( for leg, pool in checked.items() } except Exception: # noqa: BLE001 — conditional hydration must not expose partial mirror results - degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return {} diff --git a/server/knowledge/app/source_search_passes.py b/server/knowledge/app/source_search_passes.py index e9fbaef2aa4..c615c8033fb 100644 --- a/server/knowledge/app/source_search_passes.py +++ b/server/knowledge/app/source_search_passes.py @@ -12,7 +12,6 @@ from server.knowledge.app.source_search import Hydrated, _chunk_key, discover, hydrate, recheck from server.knowledge.app.source_search_proofs import SearchProofs from server.knowledge.store.source_candidates import ChunkKey, Leg -from server.observability import degradations @dataclass @@ -97,7 +96,6 @@ async def collect( ) mirrored = await hydrate(self.plan, candidates, model=query.embedding_model) except Exception: # noqa: BLE001 — a failed conditional pass must disclose no partial mirrors - degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True self._passes.append(_Pass(ordinary, mirrored, legs, fallback, top_k, lexical_weight)) @@ -121,7 +119,6 @@ async def finish(self) -> list[list[RankedHit]]: raise ValueError("invalid final search admission") return [selected.ranked(checked) for selected in self._passes] except Exception: # noqa: BLE001 — final candidate failure invalidates every earlier mirror pass - degradations.partial("knowledge", "mirror_leg_dropped") self.plan.failed = True self.proofs = SearchProofs(self.plan, "", ()) return self.ordinary() diff --git a/server/knowledge/app/source_titles.py b/server/knowledge/app/source_titles.py index 8797b632861..121c20512d2 100644 --- a/server/knowledge/app/source_titles.py +++ b/server/knowledge/app/source_titles.py @@ -13,7 +13,6 @@ from server.knowledge.app.source_access import Admitted, ReadPlan from server.knowledge.app.source_list_proofs import ListProofs from server.knowledge.store import source_documents as store -from server.observability import degradations @dataclass(frozen=True) @@ -109,6 +108,5 @@ async def collect( return [] return titles except Exception: # noqa: BLE001 — a conditional title failure discloses no partial leg - degradations.partial("knowledge", "mirror_leg_dropped") plan.failed = True return [] diff --git a/server/llm/fallback.py b/server/llm/fallback.py index e49d97c1004..aeaad774477 100644 --- a/server/llm/fallback.py +++ b/server/llm/fallback.py @@ -108,10 +108,11 @@ async def complete( ) except Exception: # noqa: BLE001 — telemetry must not block the answer pass - degradations.partial("llm", "fallback_model_answered", reason) - return await self.secondary.complete( + result = await self.secondary.complete( system, user, max_tokens=max_tokens, response_format=response_format, **kw ) + degradations.partial("llm", "fallback_model_answered", reason) + return result def _reason(exc: BaseException) -> str: diff --git a/server/tracker/app/contract.py b/server/tracker/app/contract.py index f650bfa2176..6283d75ea49 100644 --- a/server/tracker/app/contract.py +++ b/server/tracker/app/contract.py @@ -11,6 +11,7 @@ import time from typing import Any +from server.core.ch_errors import error_code from server.observability import degradations from server.tracker.domain.contract import ( ALIASES, @@ -27,6 +28,10 @@ log = logging.getLogger("loom.tracker.contract") +# UNKNOWN_TABLE, UNKNOWN_DATABASE: the table is not there, which the contract answers. +_ABSENT_CODES = frozenset({60, 81}) + + def _tables_of_interest() -> list[str]: return sorted(set(REQUIRED) | set(OPTIONAL) | set(ALIASES)) @@ -70,7 +75,8 @@ async def _q(sql: str, params: dict[str, Any] | None = None) -> list[dict[str, A _q(f"DESCRIBE TABLE {database}.{table}"), timeout=budget_s ) except Exception as e: # noqa: BLE001 — an unknown table is "missing" - degradations.partial("tracker", "contract_table_undescribed", e) + if error_code(e) not in _ABSENT_CODES: # a read that failed, not an answer + degradations.partial("tracker", "contract_table_undescribed", e) log.info("contract[%s] DESCRIBE %s.%s: %s", credential, database, table, e) continue out[table] = {str(r.get("name") or ""): str(r.get("type") or "") for r in desc} diff --git a/server/tracker/app/dupcheck.py b/server/tracker/app/dupcheck.py index 04e3db67b22..317b3876400 100644 --- a/server/tracker/app/dupcheck.py +++ b/server/tracker/app/dupcheck.py @@ -115,25 +115,30 @@ async def execute_duplicate_check(plan: DuplicateCheckPlan) -> TrackerDuplicateC title, body = str(input.title or "").strip(), str(input.body or "").strip() wall = parse_as_of(input.as_of) wants_prs = bool(input.related_prs) and not plan.explicit - pr_task = _start_pr_check(input.org, plan.code_namespace, title, body) if wants_prs else None - deadline = dl.start_deadline() - try: - inputs = [input.model_copy(update={"namespace": ns}) for ns in plan.targets] or [input] - out = await _checked(inputs, wall, int(input.top_k)) - return await _with_links( - out, - input.org, - inputs[0].namespace, - pr_task, - wall, - plan.code_namespace, - title, - cache=plan.cache, + # The answer's own notes, the PR search's among them, decide whether `_with_links` + # may remember it. + with degradations.unit(): + pr_task = ( + _start_pr_check(input.org, plan.code_namespace, title, body) if wants_prs else None ) - finally: - dl.end_deadline(deadline) - if pr_task is not None and not pr_task.done(): - pr_task.cancel() + deadline = dl.start_deadline() + try: + inputs = [input.model_copy(update={"namespace": ns}) for ns in plan.targets] or [input] + out = await _checked(inputs, wall, int(input.top_k)) + return await _with_links( + out, + input.org, + inputs[0].namespace, + pr_task, + wall, + plan.code_namespace, + title, + cache=plan.cache, + ) + finally: + dl.end_deadline(deadline) + if pr_task is not None and not pr_task.done(): + pr_task.cancel() def _start_pr_check(org: str, code_ns: str, title: str, body: str) -> Any: @@ -171,7 +176,8 @@ async def _with_links( ) -> TrackerDuplicateCheckOutput: """Every issue row shown carries its linked PRs and the release its fix ships in; on none / related the PRs that may already address the draft ride along; and one sentence - leads the answer. Each read fails open to the answer as it was.""" + leads the answer. Each read fails open to the answer as it was, noted; an answer with a + note is not remembered for `recent_answer`.""" from server.tracker.app import dupcheck_links as dl if out is None or getattr(out, "tracker_unavailable", False): @@ -209,8 +215,8 @@ async def _with_links( final = out.model_copy( update={k: d.get(k) for k in ("items", "closest", "nearest", "related_prs", "answer")}, ) - if wall is None and code_ns and cache: - remember_answer(org, code_ns, title, final) + if wall is None and code_ns and cache and not degradations.current(): + remember_answer(org, code_ns, title, final) # a degraded answer is not replayed return final diff --git a/server/tracker/app/dupcheck_legs.py b/server/tracker/app/dupcheck_legs.py index 7ca1f99e002..d58d9f5aea6 100644 --- a/server/tracker/app/dupcheck_legs.py +++ b/server/tracker/app/dupcheck_legs.py @@ -17,6 +17,8 @@ from dataclasses import dataclass from typing import Any +from server.observability import degradations + # The legs a check reports, in answer order. LEGS: tuple[str, ...] = ("lexical", "frames", "mentions", "vector", "fix_path") @@ -226,7 +228,8 @@ def leg_report( """One row per leg: `status` ok | degraded | skipped, a `reason` code and `message`, `retried`, and the leg's `ms` (both tries when retried); a degraded row's `cause` is its read's failure code (the `reason` too, unless - the retry was skipped: then the reason says why). + the retry was skipped: then the reason says why), and each degraded row is named + in `degraded`: a leg the retry recovered is not. `trace` is what the handler recorded per failed leg: the Failure of its last try, `retried`, and a retry that was skipped with its reason; a leg that failed after the retry step (the fix-path file read) is classified from `errors`.""" @@ -261,6 +264,7 @@ def leg_report( message = f"{message}; {MESSAGES[skip]}"[:_MESSAGE_MAX] reason = skip row.update(status="degraded", reason=reason, message=message) + degradations.partial("tracker", f"{name}_leg_dropped", row["cause"]) elif raw in _SKIP_REASONS: code, message = _SKIP_REASONS[raw] row.update(status="skipped", reason=code, message=message) diff --git a/server/tracker/app/registry_sources.py b/server/tracker/app/registry_sources.py index b0500ea4536..1d6f115d971 100644 --- a/server/tracker/app/registry_sources.py +++ b/server/tracker/app/registry_sources.py @@ -58,8 +58,7 @@ def decrypt_password(enc: str) -> str: def _namespaces_of(raw: Any) -> dict[str, dict[str, Any]]: try: data = json.loads(raw) if isinstance(raw, str) else dict(raw or {}) - except Exception as e: # noqa: BLE001 — an unparseable stored map links no namespace - degradations.partial("tracker", "source_namespaces_unparsed", e) + except Exception: # noqa: BLE001 — an unparseable stored map links no namespace return {} out: dict[str, dict[str, Any]] = {} for ns, spec in (data or {}).items(): diff --git a/server/tracker/app/similar.py b/server/tracker/app/similar.py index 55251c7e744..045beaf9296 100644 --- a/server/tracker/app/similar.py +++ b/server/tracker/app/similar.py @@ -62,7 +62,7 @@ def _merge_similar(namespaces: list[str], outs: list[Any], top_k: int) -> Tracke """One `tracker.similar` answer over several trackers: every item names its `namespace`; ranked by the fused score (reciprocal-rank based, so comparable across trackers); `query` and `legs` are the primary's; a - tracker that failed inside the fan-out is left out and logged, except a + tracker that failed inside the fan-out is left out, logged and noted, except a held model call (`customer.HOLDS`), which is the answer.""" served: list[tuple[str, Any]] = [] for ns, o in zip(namespaces, outs, strict=False): @@ -70,6 +70,7 @@ def _merge_similar(namespaces: list[str], outs: list[Any], top_k: int) -> Tracke raise o # the org's model calls are held: the request answers that if isinstance(o, BaseException): logger.info("tracker.similar on %s failed inside a fan-out: %s", ns, o) + degradations.partial("tracker", "linked_tracker_unread", o) continue served.append((ns, o)) items = [{**it, "namespace": ns} for ns, o in served for it in (o.items or [])] @@ -113,9 +114,10 @@ async def similar_in_namespace(input: TrackerSimilarInput) -> TrackerSimilarOutp ) status: dict[str, str] = {} meta: dict[str, Any] = {} + errors: dict[str, BaseException] = {} record: dict[str, Any] = {"status": "skipped", "relations": {}} ranked, record = await asyncio.gather( - _similar_legs(src, input, q, stats, item, kinds, legs_on, status, meta), + _similar_legs(src, input, q, stats, item, kinds, legs_on, status, meta, errors=errors), _similar_record(src, input, q, item), ) # The vector leg adds its own candidates after the ranked ones and never re-ranks. @@ -131,6 +133,8 @@ async def similar_in_namespace(input: TrackerSimilarInput) -> TrackerSimilarOutp if any(not r.get("title") for r in head): meta.setdefault("timings_ms", {})["hydrate"] = int((time.monotonic() - t0) * 1000) items = [_similar_item(r, record["relations"]) for r in top] + for leg in [k for k, v in status.items() if v == "tracker_unavailable"]: + degradations.partial("tracker", f"{leg}_leg_dropped", errors.get(leg, "")) ran = [v for k, v in status.items() if k != "fields" and v != "skipped"] return TrackerSimilarOutput( items=items, diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index a5c3524f36e..81f9ae38225 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -96,6 +96,7 @@ server/code/app/repos.py::_code_repo_rows::1 server/code/app/review_brief.py::_payload_for::1 cache_fallback server/code/app/risk.py::RiskPrefetch._run::1 full_answer_fallback server/code/app/risk.py::RiskPrefetch.start::1 full_answer_fallback +server/code/app/search/definitions.py::_literal_leg::timeout::1 answer # a literal read past its fixed bound names nothing: the answer, not a fault of the store server/code/app/search/handler.py::_embedding_model_name::1 full_answer_fallback server/code/app/search/rerank.py::_rerank_stage::timeout::1 deadline # cut at what the search's deadline left; partial_reason names the rerank server/code/app/search_cursor.py::get_pool::1 cache_fallback @@ -112,7 +113,6 @@ server/code/app/spans.py::span_attrs::1 server/code/app/unit_risk.py::read_rows::1 cache_fallback server/code/app/watches.py::notify_once::1 logged_only_nonanswer server/knowledge/app/connected_accounts.py::_revoke::timeout::1 write # the provider revoke after local inactivation; the disconnect is already durable -server/knowledge/app/connected_accounts.py::available::1 fail_closed # an unverifiable registration standing is never reported usable server/knowledge/app/connected_accounts.py::token_for::2 write # cleanup of the refresh reservation inside a handler that re-raises the failure server/knowledge/app/connected_restore.py::_restore_owner::1 logged_only_nonanswer # the restore CLI's cleanup: local deletion goes on without the remote revoke server/knowledge/app/connected_restore.py::offline_refusal::1 logged_only_nonanswer # the restore CLI's gate: unverified worker standing refuses the cleanup @@ -120,19 +120,33 @@ server/knowledge/app/conversations.py::_embed_turn::1 server/knowledge/app/datasets.py::_forget_quietly::1 write # a snapshot the approval no longer serves; an erasure deletes it server/knowledge/app/gaps.py::_insert::1 telemetry # the background gap-miss insert; the search answered before it ran server/knowledge/app/gaps.py::_person::1 telemetry # the background gap-miss insert's asker fold; no answer reads it -server/knowledge/app/gaps.py::erasure_since::1 write # an unread ledger counts as an erasure: the draft, source change or miss is refused +server/knowledge/app/gaps.py::erasure_since::1 fail_closed # an unread ledger counts as an erasure: the draft, source change or miss is refused server/knowledge/app/gaps.py::record_miss::1 telemetry # a knowledge-gap miss is telemetry; the search answer is whole server/knowledge/app/ingest_run.py::run::1 logged_only_nonanswer # the ingest worker's job run; the job ends failed with code internal server/knowledge/app/move.py::_forget_tables::1 write # the moved document's tables left behind; a later delete of the source settles them server/knowledge/app/move.py::handle_knowledge_move.one::1 write # knowledge.move raises the first failure once every source has answered server/knowledge/app/pg_delivery.py::publish_due::1 logged_only_nonanswer # the delivery worker's and restore CLI's pass; the delivery is retried server/knowledge/app/restore.py::_purge_found::1 write # the undo after a failed restore; the row goes back retired and the failure answers +server/knowledge/app/source_access.py::ReadPlan.check::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_access.py::_eligible_sources::1 fail_closed # an unverifiable crawl authority admits no mirror leg, as a refused one server/knowledge/app/source_access.py::_eligible_sources::2 fail_closed # an unverifiable connection admits no private leg, as a refused one +server/knowledge/app/source_corpus.py::load::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_documents.py::chunks::1 fail_closed # an admitted document's re-read: unmarked like a candidate read, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_documents.py::get::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_documents.py::refresh::1 fail_closed # an admitted document's re-read: unmarked like a candidate read, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_listing.py::_Selection.flush::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_listing.py::_Selection.stage::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_listing.py::_Selection.take::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_listing.py::_Selection.take::2 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_listing.py::collect::1 fail_closed # an admitted document's re-read: unmarked like a candidate read, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_passages.py::CheckedPassages._fallback::1 noted_by_caller # agent_rules.served_hits notes knowledge: widened_hits_dropped if the wide pass is needed +server/knowledge/app/source_passages.py::CheckedPassages.current::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_passages.py::collect::1 noted_by_caller # agent_rules.served_hits notes knowledge: widened_hits_dropped if the wide pass is needed server/knowledge/app/source_push.py::_stop_channels::1 write # provider channel cleanup on renewal; expiry and polling recover a failed stop server/knowledge/app/source_retirements.py::_run_once::1 logged_only_nonanswer # the source-retirement worker's pass; one source's failure is counted +server/knowledge/app/source_search.py::hydrate::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_search_passes.py::SearchPasses.collect::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_search_passes.py::SearchPasses.finish::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_sync.py::_extract_one::1 logged_only_nonanswer # the sync worker's mining of one document; recorded as its failed try server/knowledge/app/source_sync.py::_extract_pending::1 logged_only_nonanswer # the sync worker's extraction leg; one source's failed read is counted server/knowledge/app/source_sync.py::_extract_pending::2 logged_only_nonanswer # the sync worker's extraction leg; one source's failed write is counted @@ -151,6 +165,7 @@ server/knowledge/app/source_sync_notion.py::_write::1 server/knowledge/app/source_sync_notion.py::turn::timeout::1 logged_only_nonanswer # the sync worker's Notion turn; recorded as credential_invalid server/knowledge/app/source_sync_recording.py::_fetch_and_write::1 logged_only_nonanswer # the sync worker's transcript fetch; it waits for a later pass server/knowledge/app/source_sync_recording.py::_fetch_and_write::2 logged_only_nonanswer # the sync worker's transcript write; it waits for a later pass +server/knowledge/app/source_titles.py::collect::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/sources.py::_Caller.owner::1 fail_closed # an unverifiable caller owns nothing, as one that owns nothing server/knowledge/app/sources.py::_source_access::1 fail_closed # unverifiable crawl selectors stay private, as for a non-operator server/knowledge/app/sources.py::_source_access::2 fail_closed # unverifiable personal-source details stay private, as for another owner @@ -166,6 +181,7 @@ server/llm/cache.py::CachedLLMClient._put::2 server/llm/cache.py::CachedLLMClient.complete::1 telemetry # the saved-cost counter of a hit server/llm/cache.py::_record::1 telemetry # the response-cache metric server/llm/cache.py::wrap_scoped::1 cache_fallback # a client the cache cannot wrap calls the provider uncached +server/llm/fallback.py::FallbackLLMClient.complete::1 noted_by_caller # complete notes fallback_model_answered once the secondary has answered server/llm/fallback.py::FallbackLLMClient.complete::2 telemetry # the fallback metric; the answer and its note stand server/llm/identity.py::_kept_read::1 full_answer_fallback # the kept copy names the same identity; both change only on re-registration server/llm/openai.py::_report::1 telemetry # cost and content capture of the call @@ -430,7 +446,7 @@ server/memory/app/verify.py::_mirror_verified_to_embeddings::1 server/memory/app/webhooks.py::handle_webhook_register::timeout::1 write # a host unresolved within the ack bound is refused: ValidationError raised below server/tracker/app/binding.py::bindings::1 settings # a malformed bindings setting binds nothing, logged once at error server/tracker/app/contract.py::warm_at_boot::1 logged_only_nonanswer # the boot warm-up; a failed source is checked lazily on its first read -server/tracker/app/dupcheck_candidates.py::_LegRetry.run::timeout::1 deadline # the retry is cut at the op's own deadline; its legs stay unavailable in leg_status +server/tracker/app/dupcheck_candidates.py::_LegRetry.run::timeout::1 noted_by_caller # dupcheck_legs.leg_report notes each leg the cut retry leaves unavailable server/tracker/app/dupcheck_fit.py::refit_namespace::1 write # the weekly refit; last week's fit keeps serving server/tracker/app/dupcheck_legs.py::op_budget_ms::1 settings # a failed budget lookup holds the check to the declared budget server/tracker/app/embed_index.py::catch_up::1 write # the hits are served; the embed pass writes the rows later @@ -438,6 +454,7 @@ server/tracker/app/onboarding.py::_read_one_row_each::1 server/tracker/app/onboarding.py::_read_one_row_each_mapped::1 noted_by_caller # the failure is the finding: sources._mapped_report_or_refuse refuses VIEWS_NOT_READABLE server/tracker/app/onboarding.py::probe_credential::3 write # closing the probe's client; the probe's result is whole server/tracker/app/registry.py::ensure_configured_tracker_namespaces::1 logged_only_nonanswer # the boot registration of the configured tracker namespaces +server/tracker/app/registry_sources.py::_namespaces_of::1 settings # a malformed stored namespace map links no namespace; read by the registry refresh, not an answer server/tracker/app/router.py::_record::1 telemetry # the section's QA metric server/tracker/app/sources.py::_admits::1 noted_by_caller # refuses; sources._authority marks it the server's with note_answered_unverified server/tracker/app/sources.py::_breaker_view::1 full_answer_fallback # a source with no breaker slot has failed nothing: CLOSED is its state diff --git a/tests/unit/test_code_search_definition_leg.py b/tests/unit/test_code_search_definition_leg.py index f0ec75cf819..7bc4005652a 100644 --- a/tests/unit/test_code_search_definition_leg.py +++ b/tests/unit/test_code_search_definition_leg.py @@ -1508,9 +1508,11 @@ async def literal_function_chunks(self, *a: Any, **k: Any): def test_a_literal_read_slower_than_the_leg_window_leaves_the_frames_and_the_names( - caplog: pytest.LogCaptureFixture, + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch ) -> None: + from server.code.app.search import definitions from server.code.app.search.definitions import _definition_leg + from server.observability import degradations class _Slow(_Framed): """A literal read that never returns, under the client's own wait.""" @@ -1571,6 +1573,17 @@ async def served(repo: _Slow, leg_ms: int) -> list[str]: assert _literal_seconds(None) == _literal_seconds(5000) == _LITERAL_SECONDS assert _literal_seconds(1) == 0.0005 + # cut by that fixed bound, the read is still an answer: nothing in `degraded`, so a + # search for a widely held literal stays whole and may be memoised + async def noted() -> list[str]: + degradations.begin() + await served(_Slow(), 5000) + return degradations.current() + + monkeypatch.setattr(definitions, "_LITERAL_SECONDS", 0.05) + repo, result, work = _Slow(), _Result(), {} + assert asyncio.run(noted()) == [] + # ---- the leg inside search() -------------------------------------------------------- diff --git a/tests/unit/test_degraded_fallback_notes.py b/tests/unit/test_degraded_fallback_notes.py new file mode 100644 index 00000000000..92e86a00621 --- /dev/null +++ b/tests/unit/test_degraded_fallback_notes.py @@ -0,0 +1,739 @@ +"""Each fallback the degraded scan and its review found, and no other test drives, names +itself in `degraded`: one row per note site, driven by the failure the note describes, so a +note that is removed fails here.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Awaitable, Callable +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.observability import degradations + +Driver = Callable[[pytest.MonkeyPatch], Awaitable[Any]] + + +async def _boom(*_a: Any, **_k: Any) -> Any: + raise RuntimeError("read failed") + + +def _src(*names: str, **attrs: Any) -> SimpleNamespace: + """An object whose `names` methods raise, as a store that is down does.""" + return SimpleNamespace(**{n: _boom for n in names}, **attrs) + + +# ---- knowledge ----------------------------------------------------------------------- + + +async def _lexical_stats(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import bm25 + + mp.setattr(bm25, "corpus_stats", _boom) + return await bm25.lexical_stats( + None, # type: ignore[arg-type] + org="o", + namespaces=["n"], + embedding_model="m", + tokens=["t"], + ) + + +async def _connection(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import connected_accounts as ca + + mp.setattr(ca, "client", lambda _kind: None) + mp.setattr(ca, "_standing", _boom) + account = SimpleNamespace( + active=True, credential_enc=b"x", kind="gdrive", connected_at=None, org="o", subject="s" + ) + return await ca.available(account) # type: ignore[arg-type] + + +async def _extractor_formats(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import extractors + + async def _slow(_url: str) -> Any: + raise TimeoutError + + mp.setattr(extractors, "capabilities", _slow) + return await extractors._formats_within("http://extractor", 1.0) + + +def _inspect() -> Any: + from server.knowledge.api.models_inspect import KnowledgeInspectInput + from server.knowledge.app import inspect + + return inspect._Inspect(KnowledgeInspectInput(org="o", namespace="n")) + + +async def _inspect_section(mp: pytest.MonkeyPatch) -> Any: + return await _inspect().guarded("counts", _boom, 0) + + +async def _inspect_jobs(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import inspect + + mp.setattr(inspect.pg, "enabled", lambda: True) + mp.setattr(inspect.ingest_jobs, "unprojected", _boom) + return await _inspect().unprojected_jobs() + + +async def _inspect_heads(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import inspect + + mp.setattr(inspect.pg, "enabled", lambda: True) + mp.setattr(inspect.documents_repo, "get_many_by_uris", _boom) + return await _inspect().served([{"source_uri": "u", "version": 1}]) + + +async def _rerank(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import knowledge_search as ks + from server.memory.app import rerank + + async def _slow(**_k: Any) -> Any: + await asyncio.sleep(5) + + mp.setattr(rerank, "rerank", _slow) + mp.setattr(ks.settings, "knowledge_search_rerank_timeout_s", 0.01) + hit = SimpleNamespace(_context="", content="text", similarity=0.5) + return await ks._rerank("http://rerank", "q", [hit, hit], 2) # type: ignore[list-item] + + +async def _spans(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import knowledge_search as ks + from server.memory.app import spans + + mp.setattr(spans, "best_spans", _boom) + return await ks._narrow_spans(SimpleNamespace(), [0.1], [SimpleNamespace(content="x")]) # type: ignore[arg-type, list-item] + + +async def _live_search(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import live_search as ls + + mp.setattr(ls, "current_auth", lambda: SimpleNamespace(org="o")) + mp.setattr(ls.settings, "auth_required", True) + mp.setattr(ls.settings, "knowledge_mirrored_sources_enabled", True) + mp.setattr(ls, "protected_for", lambda _auth: True) + mp.setattr(ls, "is_answer_token", lambda _auth: False) + mp.setattr(ls.request_tail, "required_active", lambda: True) + mp.setattr(ls.request_work, "mark_mirrored", lambda **_k: True) + mp.setattr(ls.connected_accounts, "own_subject", _boom) + return await ls.search("o", ["n"], "q", top_k=3) + + +async def _live_publish(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import live_search as ls + + return await ls.publish(SimpleNamespace(check=_boom)) # type: ignore[arg-type] + + +async def _repo_docs_renewal(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import repo_docs + + extra = SimpleNamespace(proofs=None, lost=False, ordinary=_boom, current=_boom) + search = repo_docs.RepoSearch(SimpleNamespace(), SimpleNamespace(), extra) # type: ignore[arg-type] + return await search._renew_extra() + + +async def _repo_docs_scope(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.api.models_knowledge import KnowledgeSearchInput + from server.knowledge.app import knowledge_search, repo_docs + + calls: list[str] = [] + + async def _resolve(inp: Any) -> Any: + calls.append(inp.namespace) + if len(calls) > 1: + raise RuntimeError("scope unreadable") + return SimpleNamespace(namespaces=[inp.namespace]) + + mp.setattr(knowledge_search, "resolve_search", _resolve) + inp = KnowledgeSearchInput(org="o", namespace="n", query="q") + return await repo_docs.resolve_repo_search(inp, repo_namespace="docs") + + +async def _repo_docs_search(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import repo_docs + + past = SimpleNamespace(extra=object(), extra_deadline=-1.0) # its budget already spent + return await repo_docs.search_repo_docs(past, None) # type: ignore[arg-type] + + +async def _repo_docs_listing(mp: pytest.MonkeyPatch) -> Any: + from server.code.app import repo_scope + from server.knowledge.app import document_reads, repo_docs + + async def _docs(_org: str, _ns: str) -> str: + return "docs" + + mp.setattr(repo_scope, "readable_repo_namespace", _docs) + mp.setattr(document_reads, "resolve_list", _boom) + return await repo_docs.list_repo_docs("o", "code") + + +async def _tune_artifacts(mp: pytest.MonkeyPatch) -> Any: + from server.knowledge.app import tune + + mp.setattr(tune.blobs, "locate", _boom) + row = { + "source_uri": "u", + "title": "t", + "description": "", + "artifact_sha256": "a" * 64, + "chars": 0, + "text": "", + "doc_format": "pdf", + } + return await tune._load("o", "n", [row]) + + +# ---- tracker ------------------------------------------------------------------------- + + +def _dupcheck_output(**kw: Any) -> Any: + from server.tracker.api.models import TrackerDuplicateCheckOutput + + return TrackerDuplicateCheckOutput(**kw) + + +async def _record_route(mp: pytest.MonkeyPatch) -> Any: + from server.memory.app import code_grounding + from server.tracker.app import ask_route + + mp.setattr(ask_route, "classify", lambda _q: ("flaky", "test_x")) + mp.setattr( + code_grounding, "_resolve_code_target", lambda *_a: (_ for _ in ()).throw(RuntimeError()) + ) + return await ask_route.qa_route_answer("is test_x flaky", None, None, [], "m") + + +async def _binding_overrides(mp: pytest.MonkeyPatch) -> Any: + from server.code.app import reads + from server.core import ch + from server.tracker.app import binding + + mp.setattr(ch, "get_client", lambda: SimpleNamespace(_client=object())) + mp.setattr(reads, "code_index", lambda: _src("state_values_for_keys")) + return await binding.refresh_overrides(force=True) + + +async def _contract_table(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import contract + + async def _query(sql: str, _params: Any) -> list[dict[str, Any]]: + if "system.columns" in sql: + return [] # the catalogue is hidden: each table is described + raise RuntimeError("Code: 210. DB::NetException: Connection refused (NETWORK_ERROR)") + + return await contract.describe("c", "db", query=_query) + + +async def _related_prs_skipped(mp: pytest.MonkeyPatch) -> Any: + from server.code.app import pr_check + from server.tracker.app import dupcheck + + mp.setattr(pr_check, "handle_code_pr_check", _boom) + return await dupcheck._start_pr_check("o", "code", "title", "body") + + +async def _fix_links_cut(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck + + mp.setattr(dupcheck, "_links_and_releases", _boom) + out = _dupcheck_output(verdict="related", items=[{"number": 1}]) + return await dupcheck._with_links(out, "o", "n", None) + + +async def _related_prs_cut(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck + + failed: asyncio.Future[Any] = asyncio.get_running_loop().create_future() + failed.set_exception(RuntimeError("search failed")) + return await dupcheck._with_links(_dupcheck_output(verdict="none"), "o", "n", failed) + + +async def _fix_releases(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck, dupcheck_links + + async def _none(*_a: Any, **_k: Any) -> None: + return None + + mp.setattr(dupcheck, "_attach_links", _none) + mp.setattr(dupcheck_links, "release_of_merges", _boom) + return await dupcheck._links_and_releases([{"number": 1}], "o", "n", None, "code") + + +async def _fix_links(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck + + src = _src("fix_prs_of_issues", known=True, repos=lambda: ["r"]) + mp.setattr(dupcheck.tsource, "tracker_source", lambda _o, _n: src) + return await dupcheck._attach_links([{"number": 1}], "o", "n") + + +async def _fanout_namespace(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.api.models import TrackerDuplicateCheckInput + from server.tracker.app import dupcheck + + async def _one(inp: Any, _wall: Any, *, pool_ready: Any) -> Any: + if inp.namespace == "b": + raise RuntimeError("tracker b down") + pool_ready.set_result([]) + return _dupcheck_output(verdict="none") + + mp.setattr(dupcheck, "_check_one", _one) + inputs = [ + TrackerDuplicateCheckInput(org="o", namespace=ns, title="t", rerank=False) + for ns in ("a", "b") + ] + return await dupcheck._checked(inputs, None, 5) + + +def _rerank_input() -> SimpleNamespace: + return SimpleNamespace(org="o", namespace="n", rerank=True, title="t", body="b") + + +async def _rerank_text(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck + + mp.setattr(dupcheck.settings, "tracker_dupcheck_rerank_enabled", True) + run = {"q": SimpleNamespace(number=1, error_code=0), "leg_heads": {"lexical": [5]}} + return await dupcheck._rerank_pool(_src("embed_items_by_number"), _rerank_input(), run, None) + + +async def _rerank_call(mp: pytest.MonkeyPatch) -> Any: + from server.llm import client + from server.tracker.app import dup_rerank, dupcheck + + async def _slow(*_a: Any, **_k: Any) -> Any: + await asyncio.sleep(5) + + mp.setattr(dupcheck, "reads_llm_free", lambda: False) + mp.setattr(dupcheck.settings, "tracker_dupcheck_rerank_timeout_s", 0.01) + mp.setattr(dup_rerank, "rerank", _slow) + mp.setattr(client, "get_llm_client_for_model", lambda _m: None) + return await dupcheck._rerank_call(_rerank_input(), [{"number": 1}]) + + +async def _rerank_pool(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck + + async def _judged(_s: Any, _i: Any, _r: Any, o: Any, _f: Any) -> Any: + return o + + async def _canonical(_s: Any, _i: Any, o: Any) -> Any: + return o + + async def _none(*_a: Any, **_k: Any) -> Any: + return None + + out = _dupcheck_output(verdict="none") + mp.setattr(dupcheck.tsource, "tracker_source", lambda *_a: None) + mp.setattr(dupcheck, "candidates", _none) + mp.setattr(dupcheck, "_rerank_pool", _boom) + mp.setattr(dupcheck, "_draft_text", lambda *_a: ("t", "b")) + mp.setattr(dupcheck, "cached_fit", _none) + mp.setattr(dupcheck, "answer", lambda *_a, **_k: out) + mp.setattr(dupcheck, "judge_uncertain", _judged) + mp.setattr(dupcheck, "with_closest", lambda o, *_a: o) + mp.setattr(dupcheck, "with_canonical", _canonical) + ready = asyncio.get_running_loop().create_future() + await dupcheck._check_one(SimpleNamespace(org="o", namespace="n", top_k=5), None, ready) + return await ready + + +async def _duplicate_map(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck_answer + + out = _dupcheck_output(items=[{"number": 1}]) + inp = SimpleNamespace(org="o", namespace="n", as_of="") + return await dupcheck_answer.with_canonical(_src("duplicate_gold"), inp, out) + + +async def _canonical_rows(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck_answer + + async def _gold(*_a: Any, **_k: Any) -> list[dict[str, Any]]: + return [{"number": 1, "targets": [2]}] + + out = _dupcheck_output(items=[{"number": 1}]) + inp = SimpleNamespace(org="o", namespace="n", as_of="") + src = _src("items_by_number", duplicate_gold=_gold) + return await dupcheck_answer.with_canonical(src, inp, out) + + +async def _judge_text(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck_answer + + mp.setattr(dupcheck_answer.settings, "tracker_dupcheck_judge_enabled", True) + mp.setattr(dupcheck_answer, "reads_llm_free", lambda: False) + out = _dupcheck_output(verdict="related", items=[{"number": 3, "kind": "issue"}]) + run = {"unserved": [], "q": SimpleNamespace(text="")} + src = _src("embed_items_by_number") + return await dupcheck_answer.judge_uncertain(src, _rerank_input(), run, out, object()) + + +async def _error_names(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck_candidates + + inp = SimpleNamespace(org="o", namespace="n", title="(SIZES_OF_COLUMNS_DOESNT_MATCH)", body="") + q = SimpleNamespace(error_code=0) + return await dupcheck_candidates._resolve_error_name(_src("error_name_codes"), inp, q, {}) + + +async def _fingerprint(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck_candidates + + mp.setattr(dupcheck_candidates.settings, "tracker_dupcheck_rerank_enabled", True) + q = SimpleNamespace(error_code=241, number=0) + src = _src("fingerprint_issues") + return await dupcheck_candidates._fingerprint_leg(src, _rerank_input(), q, None, {}) + + +async def _stored_fit(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import dupcheck_fit + + return await dupcheck_fit.stored_fit(_src("get_state"), "o", "n") + + +async def _item_facts(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import facts, source + + mp.setattr(source, "tracker_source", lambda _o, _n: _src("items_by_number")) + return await facts.tracker_facts_for_numbers("o", "t", [5]) + + +async def _fixed_by_files(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import handlers + + items = [{"tracker": {"fixed_by": [5]}}] + return await handlers._attach_fixed_by_files(_src("pr_files"), "o", "n", items) + + +async def _linked_answer(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import handlers, router + + mp.setattr(router, "answer", _boom) + return await handlers._answer_elsewhere("q", ["other"], {}) + + +async def _fix_candidate(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import links + + return await links.fix_candidate("o", "t", 5, repo=_src("candidates_for_issue")) + + +async def _patch_history_timeout(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import patch_history + + class _Hung: + returncode: int | None = None + + async def communicate(self) -> tuple[bytes, bytes]: + await asyncio.sleep(5) + return b"", b"" + + def kill(self) -> None: + self.returncode = -9 + + async def wait(self) -> int: + return -9 + + async def _spawn(*_a: Any, **_k: Any) -> _Hung: + return _Hung() + + mp.setattr(patch_history.asyncio, "create_subprocess_exec", _spawn) + return await patch_history._git_rc("/m.git", "log", timeout_s=0.01) + + +async def _patch_history_tip(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import patch_history + + return patch_history._unread(RuntimeError("tip unreadable")) + + +async def _patch_history_line(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import patch_history + + return patch_history._unread_line("a.py", "x = 1", RuntimeError("probe failed")) + + +async def _sources_registry(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import registry_sources + + mp.setattr(registry_sources.settings, "tracker_self_service_enabled", True) + mp.setattr(registry_sources, "_read_rows", _boom) + return await registry_sources.refresh_db_sources(force=True, ch=object()) + + +async def _vector_catch_up(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import embed_index, similar + + mp.setattr(embed_index, "cursor_state", lambda: (_ for _ in ()).throw(RuntimeError())) + return await similar._vector_catch_up(None, None, "o", "n", kinds=["issue"]) + + +async def _contract_unchecked(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import sources + + mp.setattr(sources.contract_reports, "cached", lambda _name: None) + mp.setattr(sources.contract, "enforced", lambda: True) + mp.setattr(sources.contract, "check", _boom) + return await sources._contract_view("qa", "db", True) + + +async def _freshness(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import source, sources + + async def _unpublished(*_a: Any) -> None: + return None + + mp.setattr(sources, "_published", _unpublished) + mp.setattr(source, "tracker_source", lambda _o, _n: _src("item_counts")) + return await sources._freshness("o", "n") + + +async def _authorized(_org: str, _ns: str) -> tuple[str, str, str]: + return "o", "code", "" + + +async def _churn_ledger(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import test_signal + + mp.setattr(test_signal, "_code_namespace_authorized", _authorized) + mp.setattr(test_signal.ts, "home_of", lambda _name: (["test_x"], "")) + mp.setattr(test_signal, "_code_repo", lambda: _src("paths_by_stem")) + return await test_signal.churn_leg("o", "code", "test_x", days=30) + + +async def _smell_chunks(mp: pytest.MonkeyPatch) -> Any: + from server.embedding import embedder + from server.tracker.app import test_signal + + mp.setattr(test_signal, "_code_namespace_authorized", _authorized) + mp.setattr(test_signal, "_home_for_smells", lambda _name, _churn: ["tests/test_x.py"]) + mp.setattr(embedder, "get_embedder", lambda: SimpleNamespace(model_name="m")) + mp.setattr(test_signal, "_code_repo", lambda: _src("chunks_for_paths")) + return await test_signal.smell_leg("o", "code", "test_x", {}) + + +async def _test_candidates(mp: pytest.MonkeyPatch) -> Any: + from server.tracker.app import test_signal + + mp.setattr(test_signal, "_daily_repo", lambda: _src("test_names_like")) + until = datetime(2026, 1, 8, tzinfo=UTC) # only the read's window; no clock is read + return await test_signal._name_candidates("o", "n", "test_x", until - timedelta(days=7), until) + + +# ---- identity, mentor, code lessons -------------------------------------------------- + + +async def _inherited_rows(mp: pytest.MonkeyPatch) -> Any: + from server.auth import aliases, service_accounts + from server.identity.app import namespace_membership + + async def _creator(*_a: Any, **_k: Any) -> str: + return "creator" + + mp.setattr(service_accounts, "inheriting_creator", _creator) + mp.setattr(aliases, "subject_aliases", _boom) + return await namespace_membership._inherited_rows(None, "o", "sa:c", set()) + + +async def _inherited_restricted(mp: pytest.MonkeyPatch) -> Any: + from server.auth import aliases, service_accounts + from server.identity.app import namespace_classification, namespace_membership + + async def _creator(*_a: Any, **_k: Any) -> str: + return "creator" + + async def _spellings(*_a: Any, **_k: Any) -> list[str]: + return ["creator"] + + async def _rows(*_a: Any) -> list[dict[str, Any]]: + return [{"namespace": "team", "status": "active"}] + + mp.setattr(service_accounts, "inheriting_creator", _creator) + mp.setattr(aliases, "subject_aliases", _spellings) + mp.setattr(namespace_membership, "_membership_rows", _rows) + mp.setattr(namespace_classification, "restricted_set", _boom) + return await namespace_membership._inherited_rows(None, "o", "sa:c", set()) + + +async def _namespace_meta(mp: pytest.MonkeyPatch) -> Any: + from server.identity.app import namespace_membership + + return await namespace_membership._namespace_meta(_src("query_all"), "o", ["n"]) + + +async def _writers(mp: pytest.MonkeyPatch) -> Any: + from server.insights.app import mentor_brief + + mp.setattr(mentor_brief, "get_client", lambda: None) + mp.setattr(mentor_brief.mentor_store, "top_writers", _boom) + return await mentor_brief._top_writers("o", "n", 3600) + + +def _profile() -> Any: + return SimpleNamespace(org="o", namespace="n", agent="a", window_seconds=3600, hints=[]) + + +async def _adoption_shown(mp: pytest.MonkeyPatch) -> Any: + from server.insights.app import mentor_brief + + mp.setattr(mentor_brief, "get_client", lambda: None) + mp.setattr(mentor_brief.mentor_store, "hints_shown", _boom) + return await mentor_brief._adoption(_profile()) + + +async def _adoption_followed(mp: pytest.MonkeyPatch) -> Any: + from server.insights.app import mentor_brief + + async def _shown(*_a: Any, **_k: Any) -> list[dict[str, Any]]: + return [{"session_id": "s1", "code": "c", "first_ts": 0}] + + mp.setattr(mentor_brief, "get_client", lambda: None) + mp.setattr(mentor_brief.mentor_store, "hints_shown", _shown) + mp.setattr(mentor_brief.mentor_store, "last_calls", _boom) + return await mentor_brief._adoption(_profile()) + + +async def _term_leg_wait(mp: pytest.MonkeyPatch) -> Any: + from server.memory.app.search import term_leg + + async def _slow() -> Any: + await asyncio.sleep(5) + + return await term_leg.outcome(asyncio.ensure_future(_slow()), 0.01) + + +async def _term_leg_work(mp: pytest.MonkeyPatch) -> Any: + from server.memory.app.search import term_leg + + async def _over(*_a: Any, **_k: Any) -> Any: + raise TimeoutError # what `_Work.charge` raises past its bound + + mp.setattr(term_leg, "_read_bounded", _over) + return await term_leg._read("o", "n", "q", set(), None, "") + + +async def _branch_code_state(mp: pytest.MonkeyPatch) -> Any: + from server.code.app import memory_links + from server.code.app.index import gitrepo + from server.memory.app import code_plane_reads + + async def _unreadable(_read: Any) -> Any: + raise gitrepo.GitError("bad object") + + mp.setattr(memory_links, "parsed_link_path", lambda *_a, **_k: None) + mp.setattr(code_plane_reads, "_parse_link_source", _unreadable) + return await code_plane_reads._definitions_at("o", "code", "abc", ["a.py"], "pkg.f") + + +_CASES: list[tuple[Driver, str]] = [ + (_lexical_stats, "knowledge: lexical_leg_dropped (RuntimeError)"), + (_connection, "knowledge: connection_unchecked (RuntimeError)"), + (_extractor_formats, "knowledge: extractor_formats_unread (TimeoutError)"), + (_inspect_section, "knowledge: inspect_section_skipped (counts: RuntimeError)"), + (_inspect_jobs, "knowledge: ingestion_jobs_uncompared (RuntimeError)"), + (_inspect_heads, "knowledge: listed_heads_unchecked (RuntimeError)"), + (_rerank, "rerank: input_order_kept (TimeoutError)"), + (_spans, "knowledge: spans_unnarrowed (RuntimeError)"), + (_live_search, "knowledge: live_results_dropped"), + (_live_publish, "knowledge: live_results_dropped"), + (_repo_docs_renewal, "knowledge: repo_docs_dropped"), + (_repo_docs_scope, "knowledge: repo_docs_dropped"), + (_repo_docs_search, "knowledge: repo_docs_dropped"), + (_repo_docs_listing, "knowledge: repo_docs_unlisted"), + (_tune_artifacts, "knowledge: tune_artifacts_unread (RuntimeError)"), + (_record_route, "memory.ask: record_route_dropped (RuntimeError)"), + (_binding_overrides, "tracker: binding_overrides_unread (RuntimeError)"), + (_contract_table, "tracker: contract_table_undescribed (RuntimeError)"), + (_related_prs_skipped, "code_index: related_prs_skipped (RuntimeError)"), + (_fix_links_cut, "tracker: fix_links_cut (RuntimeError)"), + (_related_prs_cut, "code_index: related_prs_cut (RuntimeError)"), + (_fix_releases, "git_mirror: fix_releases_unread (RuntimeError)"), + (_fix_links, "tracker: fix_links_unread (RuntimeError)"), + (_fanout_namespace, "tracker: fanout_namespace_unread (RuntimeError)"), + (_rerank_text, "tracker: rerank_text_unread (RuntimeError)"), + (_rerank_call, "llm: dupcheck_rerank_skipped (TimeoutError)"), + (_rerank_pool, "tracker: rerank_pool_dropped (RuntimeError)"), + (_duplicate_map, "tracker: duplicate_map_unread (RuntimeError)"), + (_canonical_rows, "tracker: canonical_rows_unread (RuntimeError)"), + (_judge_text, "tracker: judge_text_unread (RuntimeError)"), + (_error_names, "tracker: error_names_unread (RuntimeError)"), + (_fingerprint, "tracker: fingerprint_leg_dropped (RuntimeError)"), + (_stored_fit, "tracker: dupcheck_fit_unread (RuntimeError)"), + (_item_facts, "tracker: item_facts_unread (RuntimeError)"), + (_fixed_by_files, "tracker: fixed_by_files_unread (RuntimeError)"), + (_linked_answer, "tracker: linked_tracker_unread (RuntimeError)"), + (_fix_candidate, "tracker: fix_candidate_unread (RuntimeError)"), + (_patch_history_timeout, "git_mirror: patch_history_timed_out (TimeoutError)"), + (_patch_history_tip, "git_mirror: patch_history_unread (RuntimeError)"), + (_patch_history_line, "git_mirror: patch_history_line_unread (RuntimeError)"), + (_sources_registry, "tracker: sources_registry_unread (RuntimeError)"), + (_vector_catch_up, "tracker: vector_fresh_dropped (RuntimeError)"), + (_contract_unchecked, "tracker: contract_unchecked (RuntimeError)"), + (_freshness, "tracker: freshness_unread (RuntimeError)"), + (_churn_ledger, "code_index: churn_ledger_unread (RuntimeError)"), + (_smell_chunks, "code_index: smell_chunks_unread (RuntimeError)"), + (_test_candidates, "tracker: test_candidates_dropped (RuntimeError)"), + (_inherited_rows, "namespace.list_mine: inherited_rows_unread (RuntimeError)"), + (_inherited_restricted, "namespace.list_mine: inherited_rows_unread (RuntimeError)"), + (_namespace_meta, "namespace.list_mine: metadata_defaulted (RuntimeError)"), + (_writers, "mentor.brief: writers_unread (RuntimeError)"), + (_adoption_shown, "mentor.brief: adoption_unread (RuntimeError)"), + (_adoption_followed, "mentor.brief: adoption_unread (RuntimeError)"), + (_term_leg_wait, "memory.search: term_definitions_withheld (TimeoutError)"), + (_term_leg_work, "memory.search: term_definitions_withheld (TimeoutError)"), + (_branch_code_state, "code_lessons: branch_code_state_unread (GitError)"), +] + + +@pytest.mark.parametrize( + ("driver", "note"), _CASES, ids=[d.__name__.lstrip("_") for d, _ in _CASES] +) +async def test_each_fallback_names_itself_in_degraded( + monkeypatch: pytest.MonkeyPatch, driver: Driver, note: str +) -> None: + degradations.begin() + await driver(monkeypatch) + assert note in degradations.current() + + +async def test_an_absent_table_is_the_contracts_answer_not_a_fallback() -> None: + """A required table the source lacks is `missing` in the contract: no note.""" + from server.tracker.app import contract + + async def _query(sql: str, _params: Any) -> list[dict[str, Any]]: + if "system.columns" in sql: + return [] + raise RuntimeError("Code: 60. DB::Exception: Table db.t does not exist. (UNKNOWN_TABLE)") + + degradations.begin() + assert await contract.describe("c", "db", query=_query) == {} + assert degradations.current() == [] + + +async def test_a_refused_connection_is_an_answer_not_a_fallback( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A lost standing answers `connected: false` with no note; only a read that failed + is noted.""" + from server.knowledge.app import connected_accounts as ca + + async def _lost(*_a: Any, **_k: Any) -> None: + raise ca.OwnerUnavailable() + + monkeypatch.setattr(ca, "client", lambda _kind: None) + monkeypatch.setattr(ca, "_standing", _lost) + account = SimpleNamespace( + active=True, credential_enc=b"x", kind="gdrive", connected_at=None, org="o", subject="s" + ) + degradations.begin() + assert await ca.available(account) is False # type: ignore[arg-type] + assert degradations.current() == [] diff --git a/tests/unit/test_degraded_unnoted.py b/tests/unit/test_degraded_unnoted.py index f08b4819c0b..50d6ed2411d 100644 --- a/tests/unit/test_degraded_unnoted.py +++ b/tests/unit/test_degraded_unnoted.py @@ -66,6 +66,8 @@ "deadline", # a security or privacy check that cannot be read refuses, as it does when it refuses "fail_closed", + # what the handler returns is the answer itself, not a fallback (the comment says why) + "answer", } _NOTES = {"partial", "note", "restore"} _EXCEPTION_TYPES = {"Exception", "BaseException"} @@ -291,8 +293,8 @@ def _allowlist() -> dict[str, str]: key, category = line.split() assert key not in entries, f"listed twice: {key}" assert category in _CATEGORIES, f"{key}: unknown category {category!r}" - if category == "noted_by_caller": - assert why.strip(), f"{key}: a noted_by_caller entry says where the caller notes" + if category in ("noted_by_caller", "answer"): + assert why.strip(), f"{key}: a {category} entry says where or why in its comment" entries[key] = category return entries diff --git a/tests/unit/test_dupcheck_links.py b/tests/unit/test_dupcheck_links.py index 6c19987434e..f14272b47cc 100644 --- a/tests/unit/test_dupcheck_links.py +++ b/tests/unit/test_dupcheck_links.py @@ -12,6 +12,7 @@ import server.tracker.store.source as src import server.tracker.store.source.qa_intel as qi +from server.observability import degradations from server.tracker.api.models import MAX_FRAME_CHARS from server.tracker.app import dupcheck_links as dl from server.tracker.domain.errors import TrackerUnavailable @@ -323,6 +324,38 @@ async def failing() -> Any: assert (await h._with_links(unavailable, ORG, PUB, None)) is unavailable +@pytest.mark.asyncio +async def test_an_answer_without_its_links_says_so_and_is_not_remembered(monkeypatch) -> None: + """A check `bisect`'s fix stage would reuse through `recent_answer` must be whole: one + whose links read failed names it in `degraded` and is not kept; a whole one is.""" + from server.observability import degradations + from server.tracker.app import dupcheck as h + + async def boom(self, org, ns, issues): + raise TrackerUnavailable("down") + + async def none(self, org, ns, issues): + return {} + + monkeypatch.setattr(src.TrackerSource, "known", property(lambda self: True)) + monkeypatch.setattr(src.TrackerSource, "repos", lambda self: [REPO]) + title = "has over JSON dynamic subcolumns got 4x slower" + out = _output(verdict="duplicate_of", items=[{"number": 5, "state": "closed"}]) + h._RECENT.clear() + try: + monkeypatch.setattr(src.TrackerSource, "fix_prs_of_issues", boom) + degradations.begin() + await h._with_links(out, ORG, PUB, None, None, "code-a", title) + assert degradations.current() == ["tracker: fix_links_unread (TrackerUnavailable)"] + assert not h._RECENT + monkeypatch.setattr(src.TrackerSource, "fix_prs_of_issues", none) + degradations.begin() + await h._with_links(out, ORG, PUB, None, None, "code-a", title) + assert degradations.current() == [] and len(h._RECENT) == 1 + finally: + h._RECENT.clear() + + @pytest.mark.asyncio async def test_the_search_legs_budget_has_no_room_for_the_pr_search(monkeypatch) -> None: from unittest.mock import AsyncMock @@ -499,7 +532,10 @@ async def release(git_dir, sha, *, timeout_s=3.0): unreleased = {"number": 2, "links": [{"number": 3, "state": "merged"}]} broken = {"number": 5, "links": [{"number": 4, "state": "merged"}], "fixed_in": "26.1"} bare = {"number": 6} + degradations.begin() await dl.release_of_merges(ORG, "code-clickhouse", [near_cut, unreleased, broken, bare]) + # the release a failed read left unread is the tracker's estimate, and says so + assert degradations.current() == ["git_mirror: fix_release_unread (GitError)"] assert near_cut["fixed_in"] == "26.7" and near_cut["fixed_in_source"] == "release_tag" assert "fixed_in" not in unreleased and unreleased["fixed_in_source"] == "not_released" assert broken["fixed_in"] == "26.1" and broken["fixed_in_source"] == "tracker" diff --git a/tests/unit/test_llm_fallback.py b/tests/unit/test_llm_fallback.py index 73cfcc43e80..fbf0898eb32 100644 --- a/tests/unit/test_llm_fallback.py +++ b/tests/unit/test_llm_fallback.py @@ -92,6 +92,17 @@ async def test_outage_falls_through_to_secondary_and_is_counted(monkeypatch) -> assert degradations.current() == ["llm: fallback_model_answered (http_503)"] +async def test_a_secondary_that_fails_too_claims_no_answer() -> None: + degradations.begin() + p, s = ( + _Client("strong", raise_exc=_http_error(503)), + _Client("cheap", raise_exc=_http_error(503)), + ) + with pytest.raises(httpx.HTTPStatusError): + await FallbackLLMClient(p, s).complete("sys", "user") + assert s.calls == 1 and degradations.current() == [] + + async def test_configuration_errors_do_not_fall_back() -> None: # 401/403/404 are configuration; 400 hands over (see the block at the end # of this file). diff --git a/tests/unit/test_memory_repo.py b/tests/unit/test_memory_repo.py index e259da7c60c..e2042e76c40 100644 --- a/tests/unit/test_memory_repo.py +++ b/tests/unit/test_memory_repo.py @@ -201,6 +201,8 @@ async def query_all(self, sql: str, params: dict[str, Any] | None = None): identity, "deploy_window", ch=ch, include_usage_totals=True, scope=WHOLE_NAMESPACE ) assert row is not None and row.recall_count == 0 + assert degradations.current() == ["memory: usage_totals_unread (ConnectionError)"] + degradations.begin() # the two reads note alike: each is checked on its own assert await overlay_usage_totals_many([row], ch=ch) == [row] assert degradations.current() == ["memory: usage_totals_unread (ConnectionError)"] diff --git a/tests/unit/test_source_access_plan.py b/tests/unit/test_source_access_plan.py index a85e57e2b4d..e62f791d6e3 100644 --- a/tests/unit/test_source_access_plan.py +++ b/tests/unit/test_source_access_plan.py @@ -14,6 +14,7 @@ from server.knowledge.app import source_access as app from server.knowledge.domain.access_list import AccessList, to_json from server.knowledge.domain.serving import Serving +from server.observability import degradations from server.operations.base import Role SID = "11111111-1111-4111-8111-111111111111" @@ -112,10 +113,46 @@ async def test_checked_document_retains_its_scope_and_metadata(world): @pytest.mark.parametrize("stage", ["sources", "mirrors", "listings", "reader"]) async def test_unconditional_read_failure_has_one_public_marker(world, stage): + """The marker is the request's, read before any candidate: a query that matches a + hidden document and one that matches nothing name it alike.""" world[stage].side_effect = RuntimeError("private row or backend cause") - plan = await app.prepare("acme", ["docs"]) - assert await plan.check([candidate()], chunks=True) == [] - assert plan.marked and plan.unread and world["bag"].mirror_unread + world["doc"]["access_json"] = to_json(AccessList(emails=("other@example.com",))) + answers = [] + for candidates in ([candidate()], []): + degradations.begin() + plan = await app.prepare("acme", ["docs"]) + assert await plan.check(candidates, chunks=True) == [] + assert plan.marked and plan.unread and world["bag"].mirror_unread + answers.append(degradations.current()) + assert answers == [["knowledge: mirror_unread"]] * 2 + + +@pytest.mark.parametrize("stage", ["metadata", "heads", "groups", "owner"]) +async def test_a_failed_candidate_read_names_nothing_a_query_with_no_candidate_would_not( + world, monkeypatch, stage +): + """A list, members, heads or owner read runs only for a candidate, and candidates + include documents the reader may not see: its failure leaves `degraded` as a query + that matched nothing leaves it.""" + if stage == "heads": + monkeypatch.setattr(app.pg, "enabled", lambda: True) + world["doc"]["access_json"] = to_json( + AccessList(groups=("team@example.com",)) + if stage == "groups" + else AccessList(owner="alias@example.com") + if stage == "owner" + else AccessList(emails=("other@example.com",)) + ) + world[stage].side_effect = RuntimeError("private candidate error") + answers = [] + for candidates in ([candidate()], []): + degradations.begin() + plan = await app.prepare("acme", ["docs"]) + assert await plan.check(candidates, chunks=True) == [] + assert not plan.unread + answers.append(degradations.current()) + assert answers == [[], []] + assert world[stage].await_count == 1 # the hidden candidate's read did fail async def test_no_active_mirrored_source_runs_no_leg(world): diff --git a/tests/unit/test_source_documents.py b/tests/unit/test_source_documents.py index c64797906f8..38d1f6e53db 100644 --- a/tests/unit/test_source_documents.py +++ b/tests/unit/test_source_documents.py @@ -9,6 +9,7 @@ import pytest from server.knowledge.app.source_access import Admitted +from server.observability import degradations MIRROR = "acl-" + "1" * 24 @@ -158,9 +159,11 @@ async def broken(_org, pairs): return [] app.evidence.metadata.side_effect = broken + degradations.begin() assert await app.get(plan, "team", "gdrive:file#native") is None assert [len(batch) for batch in calls] == [64, 1] assert plan.failed and plan.unread + assert degradations.current() == ["knowledge: mirror_unread"] assert phases == [] plan.check.assert_not_awaited() app.store.contents.assert_not_awaited() @@ -171,8 +174,10 @@ async def test_conditional_failure_is_atomic_without_unread(world, stage): app, plan, _row, _phases = world target = plan.check if stage == "check" else app.store.contents target.side_effect = RuntimeError("private failure") + degradations.begin() assert await app.get(plan, "team", "gdrive:file#native") is None assert plan.failed and not plan.unread + assert degradations.current() == [] # a candidate's read: no marker async def test_cancellation_propagates(world): diff --git a/tests/unit/test_source_listing.py b/tests/unit/test_source_listing.py index f9cf17cab70..36ae60b0983 100644 --- a/tests/unit/test_source_listing.py +++ b/tests/unit/test_source_listing.py @@ -14,6 +14,7 @@ from server.knowledge.app import source_documents from server.knowledge.app.source_access import Admitted from server.knowledge.domain.serving import Serving +from server.observability import degradations NOW = datetime(2025, 1, 1, tzinfo=UTC) NS = "acl-" + "1" * 24 @@ -335,8 +336,10 @@ async def test_discovery_failure_marks_unread_and_never_reads_selected_fields(wo state.stream_error = RuntimeError("private candidate failure") mark = [] monkeypatch.setattr(request_work, "mark_mirrored", lambda **kwargs: mark.append(kwargs)) + degradations.begin() assert await collect(world) == [] assert plan.failed and plan.unread and mark == [{"unread": True}] + assert degradations.current() == ["knowledge: mirror_unread"] source_documents.store.list_projection.assert_not_awaited() @@ -345,8 +348,10 @@ async def test_conditional_failure_keeps_all_fixed_discovery_but_does_not_mark_u for index in range(130): add(f"gdrive:{index:04d}", 100) state.conditional_error = True + degradations.begin() assert await collect(world) == [] assert state.discovered == 130 and plan.failed and not plan.unread + assert degradations.current() == [] # a candidate's read: no marker source_documents.store.list_projection.assert_not_awaited() diff --git a/tests/unit/test_source_search_pool.py b/tests/unit/test_source_search_pool.py index 1aaa89f8b8d..7aaf69401cb 100644 --- a/tests/unit/test_source_search_pool.py +++ b/tests/unit/test_source_search_pool.py @@ -11,6 +11,7 @@ from server.knowledge.app import source_search as app from server.knowledge.app.search import HybridSearchQuery from server.knowledge.app.source_access import Admitted +from server.observability import degradations MIRROR = "acl-" + "1" * 24 SID = "11111111-1111-4111-8111-111111111111" @@ -151,8 +152,10 @@ async def rows(_leg): yield row(i) install(rows) + degradations.begin() assert await app.collect_leg(plan, q, "semantic", limit=100) == [] assert plan.failed and not plan.unread and closed == ["semantic"] + assert degradations.current() == [] # a candidate's read: no marker async def test_late_discovery_failure_discards_earlier_batches_and_marks_unread(world): @@ -164,8 +167,10 @@ async def rows(_leg): raise RuntimeError("synthetic private backend error") install(rows) + degradations.begin() assert await app.collect_leg(plan, q, "semantic", limit=100) == [] assert plan.failed and plan.unread and closed == ["semantic"] + assert degradations.current() == ["knowledge: mirror_unread"] async def test_selected_discovery_streams_open_even_after_another_candidate_failure(world): diff --git a/tests/unit/test_tracker_duplicate_check.py b/tests/unit/test_tracker_duplicate_check.py index 226febaa2d1..b4d8bd5bac7 100644 --- a/tests/unit/test_tracker_duplicate_check.py +++ b/tests/unit/test_tracker_duplicate_check.py @@ -18,6 +18,7 @@ import server.tracker.store.source as src import server.tracker.store.source.qa_intel as qi from server.core.errors import ValidationError +from server.observability import degradations from server.operations.base import Role from server.operations.registry import OPERATIONS_BY_NAME from server.settings import settings @@ -1478,11 +1479,14 @@ async def test_a_transient_leg_failure_is_retried_once_and_the_leg_answers(monke calls = _flaky_lexical(s, [_timeout()]) _wire(monkeypatch, s) monkeypatch.setattr(settings, "tracker_dupcheck_leg_retry_delay_ms", 0, raising=False) + degradations.begin() out = await hd.handle_tracker_duplicate_check( TrackerDuplicateCheckInput(org=ORG, namespace=NS, **DRAFT) ) assert calls["n"] == 2 assert out.legs["lexical"] == "served" and out.epistemic == "calibrated" + # the leg the retry recovered is whole: nothing names it in `degraded` + assert not [n for n in degradations.current() if "_leg_dropped" in n] lex = _leg(out, "lexical") assert (lex.status, lex.retried, lex.reason) == ("ok", True, "recovered_on_retry") assert lex.namespace == NS and "legs_retry" in out.query["timings_ms"] @@ -1509,6 +1513,7 @@ def net() -> BaseException: calls = _flaky_lexical(s, [net(), net(), net()]) _wire(monkeypatch, s) monkeypatch.setattr(settings, "tracker_dupcheck_leg_retry_delay_ms", 0, raising=False) + degradations.begin() out = await hd.handle_tracker_duplicate_check( TrackerDuplicateCheckInput(org=ORG, namespace=NS, **DRAFT) ) @@ -1523,6 +1528,10 @@ def net() -> BaseException: assert "code 210" in lex.message and "SELECT" not in lex.message assert out.legs["lexical"] == "tracker_unavailable" and out.epistemic == "degraded" assert not out.tracker_unavailable # the record itself was readable + # a `none` or a verdict without the leg names it, with the read's failure code + assert [n for n in degradations.current() if "_leg_dropped" in n] == [ + "tracker: lexical_leg_dropped (ch_transient)" + ] @pytest.mark.asyncio diff --git a/tests/unit/test_tracker_embed.py b/tests/unit/test_tracker_embed.py index 166d890d4f4..083c9f033c4 100644 --- a/tests/unit/test_tracker_embed.py +++ b/tests/unit/test_tracker_embed.py @@ -22,6 +22,7 @@ import server.tracker.store.source as src import server.tracker.store.source.qa_intel as qi from server.erasure.store import census as erasure_census +from server.observability import degradations from server.settings import settings from server.tracker.api.models import TrackerSimilarInput from server.tracker.app import embed_index as ei @@ -1310,21 +1311,25 @@ async def embed_items(self, *a, **k): monkeypatch.setattr(tsrc, "tracker_source", lambda org, ns: s) monkeypatch.setattr(settings, "tracker_similar_catch_up_budget_ms", 0, raising=False) leg["cursors"] = _Cursors({"issue": T0}) + degradations.begin() out = await tsim.handle_tracker_similar( TrackerSimilarInput(org=ORG, namespace=NS, issue_number=119601, legs=["vector"]) ) assert out.legs["vector"] == "served" and [i["number"] for i in out.items] == [116490] assert out.query["fresh_pending"] is True and out.query["fresh_items"] == 0 + assert degradations.current() == ["tracker: vector_fresh_pending (TimeoutError)"] assert len(tsim._BACKGROUND) == 1 await asyncio.gather(*tsim._BACKGROUND) assert not tsim._BACKGROUND and [r["number"] for r in leg["repo"].inserted] == [120001] # with the budget: waited for, the fresh row is in the answer monkeypatch.setattr(settings, "tracker_similar_catch_up_budget_ms", 5000, raising=False) leg["repo"].digests.clear() + degradations.begin() out = await tsim.handle_tracker_similar( TrackerSimilarInput(org=ORG, namespace=NS, issue_number=119601, legs=["vector"]) ) assert out.query["fresh_items"] == 1 and "fresh_pending" not in out.query + assert degradations.current() == [] assert {i["number"] for i in out.items} == {116490, 120001} diff --git a/tests/unit/test_tracker_multi_binding.py b/tests/unit/test_tracker_multi_binding.py index e5959a437f8..c179e25e8e1 100644 --- a/tests/unit/test_tracker_multi_binding.py +++ b/tests/unit/test_tracker_multi_binding.py @@ -185,6 +185,23 @@ async def similar_item(self, org, ns, number): assert out.query == {"number": 101} +@pytest.mark.asyncio +async def test_similar_names_a_linked_tracker_it_could_not_read(wired, monkeypatch) -> None: + from server.observability import degradations + from server.tracker.api.models import TrackerSimilarInput, TrackerSimilarOutput + + async def _one(inp): + if inp.namespace == DESK: + raise RuntimeError("desk down") + return TrackerSimilarOutput(items=[{"number": 7, "score": 0.9}]) + + monkeypatch.setattr(tsim, "_similar_one", _one) + degradations.begin() + out = await tsim.handle_tracker_similar(TrackerSimilarInput(org=ORG, namespace=CODE, text="x")) + assert out.namespaces == [QA] and [it["namespace"] for it in out.items] == [QA] + assert degradations.current() == ["tracker: linked_tracker_unread (RuntimeError)"] + + @pytest.mark.asyncio async def test_similar_on_one_tracker_is_the_single_read(wired, monkeypatch) -> None: from server.tracker.api.models import TrackerSimilarInput, TrackerSimilarOutput diff --git a/tests/unit/test_tracker_similar.py b/tests/unit/test_tracker_similar.py index 1995a898119..72aac7f3e96 100644 --- a/tests/unit/test_tracker_similar.py +++ b/tests/unit/test_tracker_similar.py @@ -16,6 +16,7 @@ import server.tracker.store.source.base as src_base import server.tracker.store.source.qa_intel as qi from server.code.app.symbol import trace as code_trace +from server.observability import degradations from server.operations.base import Role from server.operations.registry import OPERATIONS_BY_NAME from server.settings import settings @@ -704,11 +705,14 @@ async def test_similar_text_query_and_unavailable_source(monkeypatch) -> None: # one leg down: named, the others serve; every leg down: tracker_unavailable s = _Src(item=_item(), down={"frames"}) monkeypatch.setattr(tsrc, "tracker_source", lambda org, ns: s) + degradations.begin() out = await tsim.handle_tracker_similar( TrackerSimilarInput(org=ORG, namespace=NS, issue_number=117352) ) assert out.legs["frames"] == "tracker_unavailable" and out.legs["lexical"] == "served" assert not out.tracker_unavailable and out.items + # the answer without the leg names it in `degraded` too + assert degradations.current() == ["tracker: frames_leg_dropped (TrackerUnavailable)"] s = _Src(item=_item(), down={"lexical", "frames", "mentions"}) monkeypatch.setattr(tsrc, "tracker_source", lambda org, ns: s) out = await tsim.handle_tracker_similar( From 22b51088236cfa979b595230dc0677eb86bc408b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 04:38:27 +0530 Subject: [PATCH 27/47] Drop the notes of an answer replaced before it is served Each knowledge.search render runs in scoped() and keeps its notes only when it is served: a render that loses a mirrored document mid-request takes its rerank or span note with it. The served render's notes are held on the CheckedSearch as one group (degradations.hold), which its ordinary fallback swaps for its own; another holder of the same note keeps its copy. memory.ask's mirrored attempt runs in scoped() too, and only a lost document discards its notes. The duplicate check's preparation runs in its own unit, and a plan whose gates noted anything is not remembered for code.bisect_candidates. A code.search whose literal read reached its bound counts it (retrieval_work.literal_read_cut) and is not memoised; the cut still notes nothing. mentor.brief names each failed evidence read and a failed profile read, not a mentor turned off. Under a plan that reads mirrors, the repository-docs search and listing name no timeout, since their candidate checks run inside the bound. RequestWork.mirror_unread and mark_mirrored(unread=...) had no reader and are removed. The allowlist names a damaged namespace map fail_closed, the fallback model's handler full_answer_fallback, and three admitted re-reads as such. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/code-index-architecture.md | 16 ++-- docs/architecture/document-sources.md | 40 ++++---- docs/reference/http-api.md | 11 ++- server/assistant/app/runtime.py | 2 +- server/code/app/search/definitions.py | 7 +- server/code/app/search/handler.py | 6 +- server/core/request_work.py | 5 +- server/insights/app/mentor_brief.py | 7 +- server/knowledge/app/knowledge_search.py | 26 +++++- server/knowledge/app/repo_docs.py | 19 +++- server/knowledge/app/source_access.py | 2 +- server/knowledge/app/source_documents.py | 2 +- server/knowledge/app/source_listing.py | 2 +- server/knowledge/app/source_search.py | 2 +- server/memory/app/ask/pipeline.py | 23 ++++- server/observability/degradations.py | 93 +++++++++++++++---- server/tracker/app/dupcheck.py | 64 +++++++------ tests/unit/degraded_unnoted.txt | 12 +-- tests/unit/test_code_search_definition_leg.py | 6 +- tests/unit/test_code_search_pick.py | 31 ++++++- tests/unit/test_degradations.py | 24 +++++ tests/unit/test_degraded_fallback_notes.py | 38 +++++++- tests/unit/test_mentor.py | 30 +++++- tests/unit/test_mirror_request_owner.py | 84 +++++++---------- tests/unit/test_source_access.py | 10 +- tests/unit/test_source_access_plan.py | 10 +- tests/unit/test_source_ask_generation.py | 54 +++++++++++ tests/unit/test_source_listing.py | 4 +- tests/unit/test_source_search_result.py | 54 +++++++++++ tests/unit/test_tracker_dupcheck_fanout.py | 65 +++++++++++++ 30 files changed, 568 insertions(+), 181 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 5395a6706c0..fd4f461dffb 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -611,14 +611,14 @@ in `pkg/json/__init__.py`; its stored qualified name remains intact. Constructor names remain explicit, and ambiguous matches stay unlinked unless the memory's file scope selects one definition. -| Op | Path | How | -| -------------------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, the definitions the query names (`definitions.py`: the functions of the innermost two frames inside the repository of a pasted Python traceback, read by file and name and each served as the chunk that holds the frame's source line, then the names the rest of the text spells out as code, each one written with its owner and after them the first other name, three definitions in all; for a name the text only calls without a receiver inside a fenced block marked as Python, outside its comments, its string literals and its lines that lead with a dotted name or a path and a colon (the form of a pasted exception or warning line), a method or a nested definition of a Python file is left out, and a definition in another language is read as for any other name; a traceback whose frames name nothing in the index adds no name of its own; in the places those leave, the functions outside test and vendored paths that hold a literal the text marks as code and no identifier rule reads, a token with a hyphen inside written between backticks or quotes or the name of a long option with underscores, found as a whole token by one read through the n-gram index that the leg waits half a second for, and under a request budget no more than half the leg window, a literal that more than three functions hold or whose read runs longer being dropped; the text is the request's `report` when it sends one, the whole of a report it searches with the opening of), fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `rank.py` applies the priors and then serves the named definitions directly after the first unit, at its score; `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. | -| `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. | -| `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. | -| `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. | -| `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. | -| `code.trace` | `code/app/symbol/trace.py` | Reads the frames of the text: qualified `a::b` names, C/C++ `dir/file.cpp:N` locations, and Python frames in the interpreter, notebook and test-runner forms, which `frames` returns as `path:line in function`. A name resolves through the symbol table and a location to the innermost symbol that holds its line. A Python frame resolves to the definition of its function in the file under the longest tail of its printed path, as written or under `src/` or `lib/`; its line chooses only among several definitions of the name. Over `max_frames` a native backtrace keeps its first frames and a Python traceback its last. | +| Op | Path | How | +| -------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, the definitions the query names (`definitions.py`: the functions of the innermost two frames inside the repository of a pasted Python traceback, read by file and name and each served as the chunk that holds the frame's source line, then the names the rest of the text spells out as code, each one written with its owner and after them the first other name, three definitions in all; for a name the text only calls without a receiver inside a fenced block marked as Python, outside its comments, its string literals and its lines that lead with a dotted name or a path and a colon (the form of a pasted exception or warning line), a method or a nested definition of a Python file is left out, and a definition in another language is read as for any other name; a traceback whose frames name nothing in the index adds no name of its own; in the places those leave, the functions outside test and vendored paths that hold a literal the text marks as code and no identifier rule reads, a token with a hyphen inside written between backticks or quotes or the name of a long option with underscores, found as a whole token by one read through the n-gram index that the leg waits half a second for, and under a request budget no more than half the leg window, a literal that more than three functions hold or whose read runs longer being dropped, the cut counted as `retrieval_work.literal_read_cut` and such a run not memoized; the text is the request's `report` when it sends one, the whole of a report it searches with the opening of), fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `rank.py` applies the priors and then serves the named definitions directly after the first unit, at its score; `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. | +| `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. | +| `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. | +| `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. | +| `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. | +| `code.trace` | `code/app/symbol/trace.py` | Reads the frames of the text: qualified `a::b` names, C/C++ `dir/file.cpp:N` locations, and Python frames in the interpreter, notebook and test-runner forms, which `frames` returns as `path:line in function`. A name resolves through the symbol table and a location to the innermost symbol that holds its line. A Python frame resolves to the definition of its function in the file under the longest tail of its printed path, as written or under `src/` or `lib/`; its line chooses only among several definitions of the name. Over `max_frames` a native backtrace keeps its first frames and a Python traceback its last. | The lexical text-index gate tokenizes the query with `splitByNonAlpha`, matching the index tokenizer. The score counts only whole app lexemes and rejects partial matches diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 7ef4f40edcb..65664e9a7e9 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -928,10 +928,10 @@ inputs alone expose no mirrored document. A request keeps a monotonic mirror mark in its existing work bag, shared with child legs. An unbound direct helper serves no mirrored content. Active registrations, mirror bindings and listing starts are read in sequence before candidate permissions. A failed -unconditional read marks `mirror_unread`; a failed candidate read invalidates the whole -mirror plan without that marker. Checked adapters cover search, get, outline, download -and listing. Other readers, marked-request sinks and session protections remain -prerequisites to enabling mirrored sources. +unconditional read names `knowledge: mirror_unread` in the answer's `degraded`; a failed +candidate read invalidates the whole mirror plan without that marker. Checked adapters +cover search, get, outline, download and listing. Other readers, marked-request sinks +and session protections remain prerequisites to enabling mirrored sources. `documents.access_keys` and its bloom index select coarse candidates under the ClickHouse authority. Owner and group buckets retain candidates needing identity @@ -992,21 +992,23 @@ nobody. A leg whose per-request reads (the statements it issues whatever matched reader's canonical subject and verified emails among them) fail shows no mirrored document and lists `knowledge: mirror_unread` in the answer's `degraded`; a read it issues only for candidates (the lists, the members rows, the heads) that fails drops -every mirrored result without the marker, so the marker says nothing about what -matched. Each leg reads -the registry row and the listing row first and then the members rows and the lists, -under `sequential_reads()`, so a lagging replica cannot pair a fresh listing row with an -older list. It computes the addresses the reader may see before its `LIMIT`, so a page -is never cut short by the check, and caches no admitted set. No score depends on a -document the reader may not see: a mirror's chunks add nothing to any corpus statistic -(the lexical leg's document counts, lengths and term frequencies), and a mirror leg -scores its lexical hits with fixed corpus constants, which depend on no document, so a -namespace fed only by mirrored sources still ranks by both legs. Under the Postgres -authority each leg judges the addresses it is about to answer by their heads, so a -narrowing or a retirement committed and not yet published already applies, and a missing -head drops the address; a leg that cannot read the heads shows no mirrored document. The -implementing pull request measures the leg on a mirror of a million documents under both -storage authorities and puts the figures here. +every mirrored result without the marker, so the marker says nothing about what matched. +For the same reason a repository-docs search or listing that passes +`knowledge_repo_docs_timeout_s` under a plan that reads mirrors is dropped without +`knowledge: repo_docs_dropped` or `repo_docs_unlisted`: its candidate checks run inside +that bound. Each leg reads the registry row and the listing row first and then the +members rows and the lists, under `sequential_reads()`, so a lagging replica cannot pair +a fresh listing row with an older list. It computes the addresses the reader may see +before its `LIMIT`, so a page is never cut short by the check, and caches no admitted +set. No score depends on a document the reader may not see: a mirror's chunks add +nothing to any corpus statistic (the lexical leg's document counts, lengths and term +frequencies), and a mirror leg scores its lexical hits with fixed corpus constants, +which depend on no document, so a namespace fed only by mirrored sources still ranks by +both legs. Under the Postgres authority each leg judges the addresses it is about to +answer by their heads, so a narrowing or a retirement committed and not yet published +already applies, and a missing head drops the address; a leg that cannot read the heads +shows no mirrored document. The implementing pull request measures the leg on a mirror +of a million documents under both storage authorities and puts the figures here. ### Every complete listing reads the lists again diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index a839f5843fa..47d28c7f74c 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -323,9 +323,14 @@ error's kind only; the full text is in the server log. - An answer served from a fallback is not kept as a whole answer: `code.search` and `code.ask` do not cache it, `code.map` does not keep its map, the PR overlay that `code.callers` and `code.impact` read is not kept, `memory.ask` stores no precedent, - and `code.review_brief` serves the brief unstored (`stored: false`). Each - judges the entries its own reads recorded, so one the request recorded before it does - not stop the cache. + `tracker.duplicate_check` keeps no answer for `code.bisect_candidates` to reuse, and + `code.review_brief` serves the brief unstored (`stored: false`). Each judges the + entries its own reads recorded, so one the request recorded before it does not stop + the cache. +- An answer replaced before it is served does not list what it recorded: a document + search that lost access to a mirrored document mid-request and answers from its + ordinary pass, and the `memory.ask` attempt discarded for the same reason, list only + the served answer's entries. - Some caches keep a fallback with its entries and name them on each answer served from it, for: - `LOOM_CODE_STATUS_TTL_S`: a `code.index_status` or `code.repos` status; diff --git a/server/assistant/app/runtime.py b/server/assistant/app/runtime.py index 87b200a8d9b..0db7b5e4e7a 100644 --- a/server/assistant/app/runtime.py +++ b/server/assistant/app/runtime.py @@ -328,7 +328,7 @@ async def _mirror_admission(org: str, namespace: str) -> bool: try: sources = await source_access.has_active_mirrored_sources(org, namespace) except Exception: # noqa: BLE001 — unknown admission must never become an ordinary answer - request_work.mark_mirrored(unread=True) + request_work.mark_mirrored() with private_work(): pass raise BackendUnavailableError( diff --git a/server/code/app/search/definitions.py b/server/code/app/search/definitions.py index 53036cf59ce..d4693aa7fb1 100644 --- a/server/code/app/search/definitions.py +++ b/server/code/app/search/definitions.py @@ -356,6 +356,7 @@ async def _literal_leg( literals: list[str], *, seconds: float, + work: dict[str, int], path_prefix: str, scope: SearchScope | None, ) -> list[dict[str, Any]]: @@ -365,7 +366,9 @@ async def _literal_leg( paths whatever the query asks for: a test that asserts on a message id is not where it is emitted. One read through the n-gram index that no key bounds, so the leg waits `seconds` for it and ClickHouse stops it after as long: the literals of a - read that runs longer name nothing. That is an answer, not a fault of the store.""" + read that runs longer name nothing. That is an answer, not a fault of the store, so it + is not noted; a slow store can cut a rare literal's read too, so the run counts it + (`literal_read_cut`) and is not memoised.""" if not literals: return [] try: @@ -386,6 +389,7 @@ async def _literal_leg( if not bound.expired(): raise logger.info("code.search literal lookup stopped at its bound of %g s", seconds) + work["literal_read_cut"] = 1 return [] return literal_definitions(literals, rows) @@ -480,6 +484,7 @@ async def _definition_leg( model, literals, seconds=_literal_seconds(leg_ms), + work=work, path_prefix=path_prefix, scope=scope, ), diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index ff658257897..13411f5a1ec 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -401,12 +401,14 @@ async def _finish_search( partial=res.partial, partial_reason=res.partial_reason, ) - # a failed history read, a failed leg, a failed pick, a deadline-cut answer and one - # served from a fallback (`degraded`) are transient: never replay + # a failed history read, a failed leg, a failed pick, a literal read its bound cut, a + # deadline-cut answer and one served from a fallback (`degraded`) are transient: never + # replay if ( memo_key is not None and not (res.history or {}).get("failed") and not res.retrieval_work.get("pick_failed") + and not res.retrieval_work.get("literal_read_cut") and not out.partial and not res.epistemic and not degradations.current() diff --git a/server/core/request_work.py b/server/core/request_work.py index aa01b834053..4d876fae1b6 100644 --- a/server/core/request_work.py +++ b/server/core/request_work.py @@ -72,7 +72,6 @@ class RequestWork: # Mutable with the bag: a child leg marks its parent request even when it admits # nothing. Diagnostic suppression must not hide this authorization state. mirror_marked: bool = False - mirror_unread: bool = False mirror_event_registered: bool = False def mark(self, name: str) -> float: @@ -156,17 +155,15 @@ def admitted_scope() -> tuple[str, str] | None: return bag.admitted if bag is not None else None -def mark_mirrored(*, unread: bool = False) -> bool: +def mark_mirrored() -> bool: """Mark a leg; False means no outer request bag exists and it must serve no mirror.""" bag = _current.get() if bag is None: return False bag.mirror_marked = True - bag.mirror_unread |= unread owner = _http_owner.get() if owner is not None: owner.mirror_marked = True - owner.mirror_unread |= unread return True diff --git a/server/insights/app/mentor_brief.py b/server/insights/app/mentor_brief.py index 3809a3b8f0b..e5ec04a006b 100644 --- a/server/insights/app/mentor_brief.py +++ b/server/insights/app/mentor_brief.py @@ -206,7 +206,7 @@ async def _usage_evidence(org: str, namespace: str, agent: str, window_seconds: """The evidence ladder, the oldest ledger row in the window, how long the ledger keeps this namespace's rows, and the reads that failed ("step: reason"). Read at each brief, not from the cached profile; the five reads run at once and stand alone: a failed one - leaves its rungs without a count.""" + leaves its rungs without a count and is noted (`mentor.brief: _unread`).""" if agent in ANONYMOUS_AGENTS: # No agent in particular: the ledger's `-` and `*` rows are everyone's unattributed # calls, not one agent's. @@ -238,6 +238,7 @@ async def read(step: str, coro: Awaitable[Any]) -> tuple[Any, str]: return await coro, "" except Exception as exc: # noqa: BLE001 — a failed read leaves its rungs uncounted log.warning("mentor %s read failed: %s", step, exc) + degradations.partial("mentor.brief", f"{step}_unread", exc) return None, type(exc).__name__ outcomes = await asyncio.gather(*(read(step, coro) for step, coro in reads)) @@ -278,7 +279,9 @@ async def handle_mentor_brief(inp: MentorBriefInput) -> MentorBriefOutput: ) if profile is None: # The mentor is off (TTL 0) or the read failed and is remembered: - # an honest empty brief, not an error. + # an honest empty brief, not an error. Only the failure is a fallback. + if int(settings.mentor_ttl_seconds) > 0: + degradations.partial("mentor.brief", "profile_unread") return MentorBriefOutput( org=inp.org, namespace=inp.namespace, diff --git a/server/knowledge/app/knowledge_search.py b/server/knowledge/app/knowledge_search.py index 03c732e39b0..17d34bd2fb6 100644 --- a/server/knowledge/app/knowledge_search.py +++ b/server/knowledge/app/knowledge_search.py @@ -120,6 +120,8 @@ class CheckedSearch: _ordinary_dropped: int lost: bool = False ordinary_rerank_possible: bool = False + # The served render's notes; the ordinary fallback swaps in its own. + held: degradations.Held | None = None _failed: bool = dataclasses.field(default=False, init=False) _checking: asyncio.Lock = dataclasses.field( default_factory=asyncio.Lock, init=False, repr=False @@ -145,10 +147,16 @@ async def _fallback(self) -> KnowledgeSearchOutput: source_publication.discard(self.proofs) self.proofs, self.lost = None, True try: - self.output = await self._renderer.render(self._ordinary, self._ordinary_dropped) + self.output, noted = await _attempt( + self._renderer.render(self._ordinary, self._ordinary_dropped) + ) except BaseException: self._failed = True raise + if self.held is not None: + self.held.swap(noted) # the discarded render's notes go with it + else: + degradations.restore(noted) return self.output async def ordinary(self) -> KnowledgeSearchOutput: @@ -247,9 +255,9 @@ async def _run_search(request: SearchRequest, plan: ReadPlan) -> CheckedSearch: renderer = _SearchRenderer(input, embedder, query_vec, endpoint, pool, skipped, plan.marked) lost = False try: - output = await renderer.render(results_per_ns, dropped.count, proofs) + output, noted = await _attempt(renderer.render(results_per_ns, dropped.count, proofs)) except LostCorpus: - output = await renderer.render(ordinary, ordinary_dropped) + output, noted = await _attempt(renderer.render(ordinary, ordinary_dropped)) proofs, lost = None, True return CheckedSearch( output, @@ -259,9 +267,21 @@ async def _run_search(request: SearchRequest, plan: ReadPlan) -> CheckedSearch: ordinary_dropped, lost=lost, ordinary_rerank_possible=bool(endpoint) and sum(len(hits) for _, hits in ordinary) > 1, + held=degradations.hold(noted), ) +async def _attempt( + render: Awaitable[KnowledgeSearchOutput], +) -> tuple[KnowledgeSearchOutput, list[str]]: + """A render's answer and the notes it took. A render that raises, one that lost a + mirrored document among them, takes its notes with it: a rerank or span fallback of + an answer not served must not be named.""" + with degradations.scoped(): + output = await render + return output, degradations.current() + + # The fields that narrow a knowledge.search to part of the namespace's documents. _HARD_FILTERS = ( "tags", diff --git a/server/knowledge/app/repo_docs.py b/server/knowledge/app/repo_docs.py index fafa24b422f..8d7d8ecd4a7 100644 --- a/server/knowledge/app/repo_docs.py +++ b/server/knowledge/app/repo_docs.py @@ -216,6 +216,15 @@ async def resolve_repo_search( return RepoSearchRequest(base, extra, repo_namespace, deadline) +def _note_dropped(effect: str, e: BaseException, *, marked: bool) -> None: + """Name a dropped additive leg, except a timeout under a plan that reads mirrors: the + leg's mirror candidate checks run inside its bound, and how long they take depends on + documents the caller may not see, of which `degraded` says nothing + (docs/architecture/document-sources.md). The leg is dropped either way.""" + if not (marked and isinstance(e, TimeoutError)): + degradations.partial("knowledge", effect) + + async def search_repo_docs(request: RepoSearchRequest, plan: ReadPlan) -> CheckedSearch | None: """Run the resolved additive leg within its remaining scope-and-search budget.""" from server.knowledge.app.knowledge_search import run_checked_search @@ -227,8 +236,8 @@ async def search_repo_docs(request: RepoSearchRequest, plan: ReadPlan) -> Checke raise TimeoutError() async with asyncio.timeout_at(request.extra_deadline): return await run_checked_search(request.extra, plan) - except Exception: # noqa: BLE001 — a failed additive search cannot expose private details - degradations.partial("knowledge", "repo_docs_dropped") + except Exception as e: # noqa: BLE001 — a failed additive search cannot expose private details + _note_dropped("repo_docs_dropped", e, marked=plan.marked) log.info("repo docs search did not answer") return None @@ -332,6 +341,7 @@ async def list_repo_docs( ns = await readable_repo_namespace(org, code_namespace) if not ns: return RepoListing("", []) + marked = False try: from server.knowledge.app.document_reads import resolve_list, run_checked_list from server.knowledge.app.source_access import prepare @@ -347,6 +357,7 @@ async def list_repo_docs( ) ) plan = await prepare(org, list(request.namespaces)) + marked = plan.marked if not plan.marked: hit = _LIST_CACHE.get((org, ns, limit)) if hit is not None and hit[0] > time.monotonic(): @@ -356,8 +367,8 @@ async def list_repo_docs( # Check retained deadlines after the timeout context has finished its cleanup. if checked.proofs is not None and not checked.proofs.fresh(): await checked.ordinary() - except Exception: # noqa: BLE001 — a failed additive listing cannot expose private details - degradations.partial("knowledge", "repo_docs_unlisted") + except Exception as e: # noqa: BLE001 — a failed additive listing cannot expose private details + _note_dropped("repo_docs_unlisted", e, marked=marked) log.info("repo docs listing did not answer") return RepoListing(ns, []) docs = [ diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index c720873397b..3de93c496f1 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -304,7 +304,7 @@ async def prepare(org: str, namespaces: list[str]) -> ReadPlan: except Exception: # noqa: BLE001 — unreadable unconditional evidence must fail closed uniformly degradations.partial("knowledge", "mirror_unread") plan.marked = plan.unread = True - request_work.mark_mirrored(unread=True) + request_work.mark_mirrored() return plan diff --git a/server/knowledge/app/source_documents.py b/server/knowledge/app/source_documents.py index 3214a68df6e..f45131bc36a 100644 --- a/server/knowledge/app/source_documents.py +++ b/server/knowledge/app/source_documents.py @@ -45,7 +45,7 @@ async def _discover(plan: ReadPlan, pairs: list[tuple[str, str]]) -> list[dict[s except Exception: # noqa: BLE001 — every selected discovery read must fail closed uniformly degradations.partial("knowledge", "mirror_unread") plan.failed = plan.unread = True - request_work.mark_mirrored(unread=True) + request_work.mark_mirrored() return out diff --git a/server/knowledge/app/source_listing.py b/server/knowledge/app/source_listing.py index da5ec719cdb..555fe724699 100644 --- a/server/knowledge/app/source_listing.py +++ b/server/knowledge/app/source_listing.py @@ -196,7 +196,7 @@ async def select( except Exception: # noqa: BLE001 — fixed metadata discovery failure discloses no partial list degradations.partial("knowledge", "mirror_unread") plan.failed = plan.unread = True - request_work.mark_mirrored(unread=True) + request_work.mark_mirrored() return ( [] if plan.failed or plan.unread diff --git a/server/knowledge/app/source_search.py b/server/knowledge/app/source_search.py index c526a271dc3..e2f5d99976e 100644 --- a/server/knowledge/app/source_search.py +++ b/server/knowledge/app/source_search.py @@ -94,7 +94,7 @@ async def take(batch: list[dict[str, Any]]) -> None: except Exception: # noqa: BLE001 — an unconditional discovery failure invalidates every mirror leg degradations.partial("knowledge", "mirror_unread") plan.failed = plan.unread = True - request_work.mark_mirrored(unread=True) + request_work.mark_mirrored() return [] if plan.failed or plan.unread else out diff --git a/server/memory/app/ask/pipeline.py b/server/memory/app/ask/pipeline.py index 9cf0572abe5..f4fd3ef3f25 100644 --- a/server/memory/app/ask/pipeline.py +++ b/server/memory/app/ask/pipeline.py @@ -65,6 +65,7 @@ ) from server.memory.domain import ask_attribution as _attr from server.memory.domain.search_types import governed_after_computed +from server.observability import degradations def _world_knowledge_allowed(world_knowledge: str | None, settings: Any) -> bool: @@ -368,18 +369,30 @@ async def _answer_with_knowledge( if not marked: return await generate(block, hits, None) if knowledge.mirrored: + # The mirrored attempt's notes are named unless a lost document discards it: then + # the ordinary attempt's are the answer's. + noted: list[str] = [] try: - result = await owned_attempt(generate(block, hits, knowledge)) - if not knowledge.fresh(): - raise LostCorpus() + with degradations.scoped(): + try: + result = await owned_attempt(generate(block, hits, knowledge)) + finally: + noted = degradations.current() + if not knowledge.fresh(): + raise LostCorpus() + except LostCorpus: + block, hits = await knowledge.ordinary() + except BaseException: + degradations.restore(noted) + raise + else: + degradations.restore(noted) from server.knowledge.app import source_publication if knowledge.passages is not None: for proof in knowledge.passages.publication_proofs(): source_publication.retain(proof) return result - except LostCorpus: - block, hits = await knowledge.ordinary() return await owned_attempt(generate(block, hits, None)) diff --git a/server/observability/degradations.py b/server/observability/degradations.py index 8904f3b58fa..64988689201 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -21,7 +21,8 @@ An answer kept for a later call (a memo, a stored brief) is built inside `unit()`, and kept only when the unit's own notes are empty: an earlier note of the request is not -the answer's. +the answer's. An answer a later step may still replace lists its notes through `hold()`, +and the replacement swaps them, so a discarded answer's notes go with it. degraded: ["classify: caller_type_kept (HTTPStatusError)", "rerank: input_order_kept (ReadTimeout)"] @@ -42,11 +43,44 @@ _MAX_NOTES = 8 _MAX_REASON = 160 -_notes: contextvars.ContextVar[list[str] | None] = contextvars.ContextVar( + +class Held: + """The notes of an answer a later step may replace (a checked document search that + falls back to its ordinary render): listed in the request while held, and replaced + whole by `swap`. Another holder of the same note keeps its own copy.""" + + __slots__ = ("entries",) + + def __init__(self, entries: list[str]) -> None: + self.entries = list(entries) + + def swap(self, entries: list[str]) -> None: + self.entries = list(entries) + + +_notes: contextvars.ContextVar[list[str | Held] | None] = contextvars.ContextVar( "loom_degradations", default=None ) +def _flat(lst: list[str | Held] | None) -> list[str]: + """The distinct notes of a list, a held group's in its place, at most `_MAX_NOTES`.""" + out: list[str] = [] + for item in lst or (): + for entry in item.entries if isinstance(item, Held) else (item,): + if entry not in out and len(out) < _MAX_NOTES: + out.append(entry) + return out + + +def _bound() -> list[str | Held]: + lst = _notes.get() + if lst is None: + lst = [] + _notes.set(lst) + return lst + + def begin() -> None: """Bind a fresh, empty note list for this request.""" _notes.set([]) @@ -95,13 +129,11 @@ def note(provider: str, effect: str, reason: object = "", *, health: bool = True text = caller_text(reason) text = text.replace("\n", " ").strip()[:_MAX_REASON] entry = f"{provider}: {effect}" + (f" ({text})" if text else "") - lst = _notes.get() - if lst is None: - # No transport bound a list (a worker, a test): still count it - # for health, and start a list so a later reader sees it. - lst = [] - _notes.set(lst) - if entry not in lst and len(lst) < _MAX_NOTES: + # No transport bound a list (a worker, a test): still count it for health, and + # start a list so a later reader sees it. + lst = _bound() + listed = _flat(lst) + if entry not in listed and len(listed) < _MAX_NOTES: lst.append(entry) if not health: return @@ -125,26 +157,36 @@ def partial(provider: str, effect: str, reason: object = "") -> None: def current() -> list[str]: - """The notes recorded so far in this request (a copy).""" - lst = _notes.get() - return list(lst) if lst else [] + """The notes recorded so far in this request (a copy), each held group's as it is now.""" + return _flat(_notes.get()) def restore(entries: Any) -> None: """List `entries`, the notes of the request whose stored answer this one serves (a later page), as they were. Provider health counted them when they happened. Bounded - like `note`; anything but a list is ignored.""" + like `note`; anything but a list is ignored. A `Held` group (a unit's own list) is + listed as the group, so a later swap still replaces it.""" if not isinstance(entries, list): return - lst = _notes.get() - if lst is None: - lst = [] - _notes.set(lst) - for entry in map(str, entries): - if entry not in lst and len(lst) < _MAX_NOTES: + lst = _bound() + for item in entries: + if isinstance(item, Held): + if not any(item is held for held in lst): + lst.append(item) + continue + entry, listed = str(item), _flat(lst) + if entry not in listed and len(listed) < _MAX_NOTES: lst.append(entry) +def hold(entries: list[str]) -> Held: + """List `entries` in this request as one `Held` group, which the answer's replacement + swaps.""" + held = Held(entries) + _bound().append(held) + return held + + def on_response(body: Any) -> Any: """`body` (a dumped op result) with `degraded`: the op's own notes first (an output that declares the field), then this request's, each once. A response nothing @@ -162,4 +204,15 @@ def on_response(body: Any) -> Any: return {k: v for k, v in body.items() if k != "degraded"} if "degraded" in body else body -__all__ = ["begin", "current", "note", "on_response", "partial", "restore", "scoped", "unit"] +__all__ = [ + "Held", + "begin", + "current", + "hold", + "note", + "on_response", + "partial", + "restore", + "scoped", + "unit", +] diff --git a/server/tracker/app/dupcheck.py b/server/tracker/app/dupcheck.py index 317b3876400..4936173b37e 100644 --- a/server/tracker/app/dupcheck.py +++ b/server/tracker/app/dupcheck.py @@ -70,36 +70,44 @@ async def prepare_duplicate_check(input: TrackerDuplicateCheckInput) -> Duplicat from server.tracker.app.dupcheck_fanout import readable_tracker_namespaces from server.tracker.domain.namespaces import tracker_namespace - input = common._with_default_org(input) - requested = list(input.namespaces or []) # A registry read may discover more bindings; resolve before remembering an answer. - cache = not registry_unread() - explicit = tracker_namespace(input.org, input.namespace) is not None and not requested - linked = [] if explicit else await common.linked_trackers(input.org, input.namespace) - code_ns = "" if explicit or tracker_namespace(input.org, input.namespace) else input.namespace - input = await common._bound_input(input) - if ( - not str(input.title or "").strip() - and not str(input.body or "").strip() - and int(input.issue_number or 0) <= 0 - ): - raise ValidationError("title, body or issue_number is required") - if explicit: - targets = [input.namespace] - else: - bound = input.namespace if tracker_namespace(input.org, input.namespace) is not None else "" - # An unbound repository must not receive clearance from an unrelated tracker. - targets = ( - await readable_tracker_namespaces( - input.org, - bound, - requested, - int(settings.tracker_dupcheck_fanout_namespaces), - linked=linked, - ) - if bound or linked or requested - else [] + registry_read = not registry_unread() + with degradations.unit(): + input = common._with_default_org(input) + requested = list(input.namespaces or []) + explicit = tracker_namespace(input.org, input.namespace) is not None and not requested + linked = [] if explicit else await common.linked_trackers(input.org, input.namespace) + code_ns = ( + "" if explicit or tracker_namespace(input.org, input.namespace) else input.namespace ) + input = await common._bound_input(input) + if ( + not str(input.title or "").strip() + and not str(input.body or "").strip() + and int(input.issue_number or 0) <= 0 + ): + raise ValidationError("title, body or issue_number is required") + if explicit: + targets = [input.namespace] + else: + bound = ( + input.namespace if tracker_namespace(input.org, input.namespace) is not None else "" + ) + # An unbound repository must not receive clearance from an unrelated tracker. + targets = ( + await readable_tracker_namespaces( + input.org, + bound, + requested, + int(settings.tracker_dupcheck_fanout_namespaces), + linked=linked, + ) + if bound or linked or requested + else [] + ) + # A target a gate could not verify, or an unread binding, is noted: the answer + # may lack a tracker, so it is not remembered. + cache = registry_read and not degradations.current() return DuplicateCheckPlan(input, tuple(targets), code_ns, explicit, cache) diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 81f9ae38225..e7cc8b2e6a1 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -96,7 +96,7 @@ server/code/app/repos.py::_code_repo_rows::1 server/code/app/review_brief.py::_payload_for::1 cache_fallback server/code/app/risk.py::RiskPrefetch._run::1 full_answer_fallback server/code/app/risk.py::RiskPrefetch.start::1 full_answer_fallback -server/code/app/search/definitions.py::_literal_leg::timeout::1 answer # a literal read past its fixed bound names nothing: the answer, not a fault of the store +server/code/app/search/definitions.py::_literal_leg::timeout::1 answer # the bound names nothing, as the leg's design says; the run counts it (`literal_read_cut`) and is not memoised server/code/app/search/handler.py::_embedding_model_name::1 full_answer_fallback server/code/app/search/rerank.py::_rerank_stage::timeout::1 deadline # cut at what the search's deadline left; partial_reason names the rerank server/code/app/search_cursor.py::get_pool::1 cache_fallback @@ -140,13 +140,13 @@ server/knowledge/app/source_listing.py::_Selection.take::1 server/knowledge/app/source_listing.py::_Selection.take::2 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_listing.py::collect::1 fail_closed # an admitted document's re-read: unmarked like a candidate read, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_passages.py::CheckedPassages._fallback::1 noted_by_caller # agent_rules.served_hits notes knowledge: widened_hits_dropped if the wide pass is needed -server/knowledge/app/source_passages.py::CheckedPassages.current::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_passages.py::CheckedPassages.current::1 fail_closed # an admitted document's re-read: unmarked like a candidate read, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_passages.py::collect::1 noted_by_caller # agent_rules.served_hits notes knowledge: widened_hits_dropped if the wide pass is needed server/knowledge/app/source_push.py::_stop_channels::1 write # provider channel cleanup on renewal; expiry and polling recover a failed stop server/knowledge/app/source_retirements.py::_run_once::1 logged_only_nonanswer # the source-retirement worker's pass; one source's failure is counted -server/knowledge/app/source_search.py::hydrate::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_search.py::hydrate::1 fail_closed # an admitted document's re-read: unmarked like a candidate read, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_search_passes.py::SearchPasses.collect::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) -server/knowledge/app/source_search_passes.py::SearchPasses.finish::1 fail_closed # a candidate read: its failure drops mirrored results unmarked, so degraded says nothing of what matched (document-sources.md) +server/knowledge/app/source_search_passes.py::SearchPasses.finish::1 fail_closed # an admitted document's re-read: unmarked like a candidate read, so degraded says nothing of what matched (document-sources.md) server/knowledge/app/source_sync.py::_extract_one::1 logged_only_nonanswer # the sync worker's mining of one document; recorded as its failed try server/knowledge/app/source_sync.py::_extract_pending::1 logged_only_nonanswer # the sync worker's extraction leg; one source's failed read is counted server/knowledge/app/source_sync.py::_extract_pending::2 logged_only_nonanswer # the sync worker's extraction leg; one source's failed write is counted @@ -181,7 +181,7 @@ server/llm/cache.py::CachedLLMClient._put::2 server/llm/cache.py::CachedLLMClient.complete::1 telemetry # the saved-cost counter of a hit server/llm/cache.py::_record::1 telemetry # the response-cache metric server/llm/cache.py::wrap_scoped::1 cache_fallback # a client the cache cannot wrap calls the provider uncached -server/llm/fallback.py::FallbackLLMClient.complete::1 noted_by_caller # complete notes fallback_model_answered once the secondary has answered +server/llm/fallback.py::FallbackLLMClient.complete::1 full_answer_fallback # the secondary model answers in full; complete notes fallback_model_answered once it has server/llm/fallback.py::FallbackLLMClient.complete::2 telemetry # the fallback metric; the answer and its note stand server/llm/identity.py::_kept_read::1 full_answer_fallback # the kept copy names the same identity; both change only on re-registration server/llm/openai.py::_report::1 telemetry # cost and content capture of the call @@ -454,7 +454,7 @@ server/tracker/app/onboarding.py::_read_one_row_each::1 server/tracker/app/onboarding.py::_read_one_row_each_mapped::1 noted_by_caller # the failure is the finding: sources._mapped_report_or_refuse refuses VIEWS_NOT_READABLE server/tracker/app/onboarding.py::probe_credential::3 write # closing the probe's client; the probe's result is whole server/tracker/app/registry.py::ensure_configured_tracker_namespaces::1 logged_only_nonanswer # the boot registration of the configured tracker namespaces -server/tracker/app/registry_sources.py::_namespaces_of::1 settings # a malformed stored namespace map links no namespace; read by the registry refresh, not an answer +server/tracker/app/registry_sources.py::_namespaces_of::1 fail_closed # a damaged stored map links no namespace, so each check on the source refuses (test_tracker_source_add) server/tracker/app/router.py::_record::1 telemetry # the section's QA metric server/tracker/app/sources.py::_admits::1 noted_by_caller # refuses; sources._authority marks it the server's with note_answered_unverified server/tracker/app/sources.py::_breaker_view::1 full_answer_fallback # a source with no breaker slot has failed nothing: CLOSED is its state diff --git a/tests/unit/test_code_search_definition_leg.py b/tests/unit/test_code_search_definition_leg.py index 7bc4005652a..57b53b7de9f 100644 --- a/tests/unit/test_code_search_definition_leg.py +++ b/tests/unit/test_code_search_definition_leg.py @@ -1562,6 +1562,7 @@ async def served(repo: _Slow, leg_ms: int) -> list[str]: ] assert result.legs_timed_out == [] and "legs_timed_out" not in work assert (work["frame_definitions"], work["named_definitions"]) == (2, 1) + assert work["literal_read_cut"] == 1 # so the run is not memoised assert repo.seconds == 0.2 and work["leg_phase_ms"] < 400 # the read reaching its bound is an answer: the client's wait did not end, and # nothing is logged as a fault @@ -1573,8 +1574,8 @@ async def served(repo: _Slow, leg_ms: int) -> list[str]: assert _literal_seconds(None) == _literal_seconds(5000) == _LITERAL_SECONDS assert _literal_seconds(1) == 0.0005 - # cut by that fixed bound, the read is still an answer: nothing in `degraded`, so a - # search for a widely held literal stays whole and may be memoised + # cut by that fixed bound, the read is still an answer: nothing in `degraded`; the + # run counts the cut, since a slow store can cut a rare literal's read too async def noted() -> list[str]: degradations.begin() await served(_Slow(), 5000) @@ -1583,6 +1584,7 @@ async def noted() -> list[str]: monkeypatch.setattr(definitions, "_LITERAL_SECONDS", 0.05) repo, result, work = _Slow(), _Result(), {} assert asyncio.run(noted()) == [] + assert work["literal_read_cut"] == 1 # ---- the leg inside search() -------------------------------------------------------- diff --git a/tests/unit/test_code_search_pick.py b/tests/unit/test_code_search_pick.py index f8b3377dd62..772b0e61ce7 100644 --- a/tests/unit/test_code_search_pick.py +++ b/tests/unit/test_code_search_pick.py @@ -340,10 +340,17 @@ def line(body: str, symbol: str = "pkg.mod::Uploader::send") -> str: def _handle( - monkeypatch: Any, model: Any, *, over_cap: bool = False, noted: bool = False, **kw: Any + monkeypatch: Any, + model: Any, + *, + over_cap: bool = False, + noted: bool = False, + literal_cut: bool = False, + **kw: Any, ) -> tuple[dict[str, Any], list[Any]]: """The registered op's reply over `_Repo`, and what it wrote to the memo. `noted`: a - read inside the search falls back and says so in `degraded`.""" + read inside the search falls back and says so in `degraded`. `literal_cut`: the + definition leg's literal read reached its bound, which names nothing.""" import server.operations # noqa: F401 — handlers import wire models lazily from server.code.app import search_memo as memo from server.code.app.search import handler @@ -390,6 +397,14 @@ async def no_coverage_note(repo: Any, org: str, ns: str) -> str: monkeypatch.setattr(handler, "index_as_of", as_of) monkeypatch.setattr(handler, "embedding_coverage_note", no_coverage_note) monkeypatch.setattr(handler, "resolve_code_thresholds", thresholds) + if literal_cut: + from server.code.app.search import gather + + async def cut(*_a: Any, work: dict[str, int], **_k: Any) -> list[dict[str, Any]]: + work["literal_read_cut"] = 1 # what `_literal_leg` counts at its bound + return [] + + monkeypatch.setattr(gather, "_definition_leg", cut) monkeypatch.setattr(embedding, "get_embedder", lambda: _Embedder()) monkeypatch.setattr( "server.llm.client.get_llm_client_without_fallback", lambda name, **k: model @@ -423,6 +438,18 @@ def test_a_search_served_from_a_fallback_is_not_memoized(monkeypatch: pytest.Mon assert noted["results"] == plain["results"] and puts == [] +def test_a_search_whose_literal_read_was_cut_is_not_memoized( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The cut names nothing, but under load it can drop a rare literal's function: the + run says so in its work counters and is not kept for the memo's lifetime.""" + plain, puts = _handle(monkeypatch, _picks(2, 1)) + assert "literal_read_cut" not in plain["retrieval_work"] and len(puts) == 1 + cut, puts = _handle(monkeypatch, _picks(2, 1), literal_cut=True) + assert cut["results"] == plain["results"] and puts == [] + assert cut["retrieval_work"]["literal_read_cut"] == 1 + + def test_a_namespace_over_its_llm_cap_makes_no_pick_call( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/tests/unit/test_degradations.py b/tests/unit/test_degradations.py index 038e117ca59..ff6514c4a57 100644 --- a/tests/unit/test_degradations.py +++ b/tests/unit/test_degradations.py @@ -53,6 +53,30 @@ def test_a_repeated_note_is_listed_once_and_the_cap_counts_distinct_notes(): assert D.current()[-1] == "p: e6" +def test_a_held_group_is_listed_until_its_swap_and_another_holder_keeps_its_copy(): + D.begin() + D.partial("memory", "first") + held = D.hold(["rerank: input_order_kept (TimeoutError)", "knowledge: spans_unnarrowed"]) + other = D.hold(["rerank: input_order_kept (TimeoutError)"]) + with D.unit(): + inner = D.hold(["llm: fallback_model_answered"]) + assert D.current() == ["llm: fallback_model_answered"] + assert D.current() == [ + "memory: first", + "rerank: input_order_kept (TimeoutError)", + "knowledge: spans_unnarrowed", + "llm: fallback_model_answered", + ] + held.swap([]) + inner.swap([]) # still swappable once its unit has ended + assert D.current() == ["memory: first", "rerank: input_order_kept (TimeoutError)"] + other.swap([]) + D.partial("memory", "first") + assert D.current() == ["memory: first"] + held.swap([f"x: {i}" for i in range(10)]) + assert len(D.current()) == D._MAX_NOTES + + def test_notes_feed_provider_health(): D.note("classify", "caller_type_kept", "HTTP 502") st = provider_health.status() diff --git a/tests/unit/test_degraded_fallback_notes.py b/tests/unit/test_degraded_fallback_notes.py index 92e86a00621..1bdda896fb5 100644 --- a/tests/unit/test_degraded_fallback_notes.py +++ b/tests/unit/test_degraded_fallback_notes.py @@ -158,9 +158,10 @@ async def _resolve(inp: Any) -> Any: async def _repo_docs_search(mp: pytest.MonkeyPatch) -> Any: from server.knowledge.app import repo_docs + from server.knowledge.app.source_access import ReadPlan past = SimpleNamespace(extra=object(), extra_deadline=-1.0) # its budget already spent - return await repo_docs.search_repo_docs(past, None) # type: ignore[arg-type] + return await repo_docs.search_repo_docs(past, ReadPlan("o")) # type: ignore[arg-type] async def _repo_docs_listing(mp: pytest.MonkeyPatch) -> Any: @@ -737,3 +738,38 @@ async def _lost(*_a: Any, **_k: Any) -> None: degradations.begin() assert await ca.available(account) is False # type: ignore[arg-type] assert degradations.current() == [] + + +@pytest.mark.parametrize("failure", [TimeoutError(), RuntimeError("store down")]) +async def test_a_mirror_reading_docs_leg_names_no_timeout( + monkeypatch: pytest.MonkeyPatch, failure: BaseException +) -> None: + """Under a plan that reads mirrors, the docs search and listing run their candidate + checks inside the bound, so a timeout names nothing; any other failure is named.""" + from server.code.app import repo_scope + from server.knowledge.app import document_reads, knowledge_search, repo_docs, source_access + from server.knowledge.app.source_access import ReadPlan + + async def _fail(*_a: Any, **_k: Any) -> Any: + raise failure + + async def _docs(_org: str, _ns: str) -> str: + return "docs" + + async def _marked(org: str, _namespaces: list[str]) -> ReadPlan: + return ReadPlan(org, marked=True) + + async def _request(_input: Any) -> Any: + return SimpleNamespace(namespaces=("docs",)) + + monkeypatch.setattr(knowledge_search, "run_checked_search", _fail) + monkeypatch.setattr(repo_scope, "readable_repo_namespace", _docs) + monkeypatch.setattr(document_reads, "resolve_list", _request) + monkeypatch.setattr(source_access, "prepare", _marked) + monkeypatch.setattr(document_reads, "run_checked_list", _fail) + request = SimpleNamespace(extra=object(), extra_deadline=float("inf")) + degradations.begin() + assert await repo_docs.search_repo_docs(request, ReadPlan("o", marked=True)) is None # type: ignore[arg-type] + assert (await repo_docs.list_repo_docs("o", "code")).docs == [] + named = [] if isinstance(failure, TimeoutError) else ["repo_docs_dropped", "repo_docs_unlisted"] + assert degradations.current() == [f"knowledge: {effect}" for effect in named] diff --git a/tests/unit/test_mentor.py b/tests/unit/test_mentor.py index addf80ab8ac..0b7b88b057e 100644 --- a/tests/unit/test_mentor.py +++ b/tests/unit/test_mentor.py @@ -26,7 +26,7 @@ from server.insights.app import mentor as m from server.insights.app import mentor_brief as handler from server.insights.app import mentor_rules -from server.observability import ledger +from server.observability import degradations, ledger from server.settings import settings from server.transport import mcp_call, mcp_op, mcp_outcome, mcp_primer, mcp_tools from server.transport.mcp_op import OP_MENTION @@ -1264,6 +1264,7 @@ def test_a_failed_evidence_read_leaves_its_rungs_uncounted( M_REPORTED: RuntimeError("x"), } ) + degradations.begin() out = _brief(monkeypatch, ch) ladder = {e.rung: e.count for e in out.usage_evidence} assert ladder["attempt"] is None and ladder["returned_hit"] is None @@ -1271,6 +1272,10 @@ def test_a_failed_evidence_read_leaves_its_rungs_uncounted( # The other reads still answer. assert ladder["indexed_write"] == 3 and ladder["task_outcome"] == 0 assert out.skipped == ["calls: RuntimeError", "reported_keys: RuntimeError"] + assert sorted(degradations.current()) == [ + "mentor.brief: calls_unread (RuntimeError)", + "mentor.brief: reported_keys_unread (RuntimeError)", + ] assert out.ledger_from is None and out.ledger_retention_days == 0 @@ -1282,12 +1287,35 @@ def test_mentor_brief_when_the_mentor_is_off_is_an_honest_empty_brief( monkeypatch.setattr(settings, "mentor_ttl_seconds", 0, raising=False) ch = _CH({**_EVIDENCE_ROWS, M_RETENTION: [{"retention_days": 0}]}) monkeypatch.setattr(handler, "get_client", lambda: ch) + degradations.begin() out = asyncio.run( handler.handle_mentor_brief(MentorBriefInput(org="o", namespace="ns", agent="a")) ) assert out.healthy is True and out.hints == [] and out.skipped == ["profile: unavailable"] # The ladder reads no profile, so it still answers. assert {e.rung: e.count for e in out.usage_evidence}["attempt"] == 1 + # A mentor turned off is no fallback. + assert degradations.current() == [] + + +def test_a_profile_whose_read_failed_is_named_in_degraded( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.insights.api.models_mentor import MentorBriefInput + + async def _failed(*_a: Any, **_k: Any) -> Any: + return None # what `mentor_profile` answers for a failed or remembered read + + monkeypatch.setattr(settings, "mentor_ttl_seconds", 60, raising=False) + monkeypatch.setattr(m, "mentor_profile", _failed) + ch = _CH({**_EVIDENCE_ROWS, M_RETENTION: [{"retention_days": 0}]}) + monkeypatch.setattr(handler, "get_client", lambda: ch) + degradations.begin() + out = asyncio.run( + handler.handle_mentor_brief(MentorBriefInput(org="o", namespace="ns", agent="a")) + ) + assert out.skipped == ["profile: unavailable"] + assert degradations.current() == ["mentor.brief: profile_unread"] def test_planes_cover_every_registered_op_prefix() -> None: diff --git a/tests/unit/test_mirror_request_owner.py b/tests/unit/test_mirror_request_owner.py index 0a9c5faca8d..59a12e35acc 100644 --- a/tests/unit/test_mirror_request_owner.py +++ b/tests/unit/test_mirror_request_owner.py @@ -36,9 +36,9 @@ def instrumentor_background_state(): BackgroundTask._otel_original_call = original_hook -def flags(scope): +def owner_marked(scope): owner = scope.get(_OWNER_KEY) - return bool(owner and owner.mirror_marked), bool(owner and owner.mirror_unread) + return bool(owner and owner.mirror_marked) @pytest.fixture @@ -60,18 +60,15 @@ async def observe(request, call_next): try: return await call_next(request) finally: - state.seen.append((request.url.path, flags(request.scope))) + state.seen.append((request.url.path, owner_marked(request.scope))) inner = BaseHTTPMiddleware(endpoint, dispatch=observe) outer = BaseHTTPMiddleware(inner, dispatch=observe) return owner_application(outer) -@pytest.mark.parametrize("unread", [False, True]) @pytest.mark.parametrize("replace_child_bag", [False, True]) -async def test_http_owner_survives_private_child_and_bag_replacement( - world, unread, replace_child_bag -): +async def test_http_owner_survives_private_child_and_bag_replacement(world, replace_child_bag): async def endpoint(scope, receive, send): world.scopes.append(scope) parent = request_work.begin() @@ -81,7 +78,7 @@ async def child(): request_work.begin() with private_work(): assert request_work.current() is None - assert request_work.mark_mirrored(unread=unread) + assert request_work.mark_mirrored() task = asyncio.create_task(child()) try: @@ -91,12 +88,12 @@ async def child(): task.cancel() await asyncio.gather(task, return_exceptions=True) assert parent.mirror_marked is (not replace_child_bag) - assert flags(scope) == (True, unread) + assert owner_marked(scope) # A later logical operation has independent counters and local flags. next_bag = request_work.begin() assert next_bag is not parent and not request_work.mirror_marked() assert next_bag.ch_statements == 0 - assert flags(scope) == (True, unread) + assert owner_marked(scope) await PlainTextResponse("ready")(scope, receive, send) async with httpx.AsyncClient( @@ -104,19 +101,19 @@ async def child(): ) as client: response = await client.get("/marked") assert response.status_code == 200 and response.text == "ready" - assert world.seen == [("/marked", (True, unread)), ("/marked", (True, unread))] - assert flags(world.scopes[0]) == (True, unread) + assert world.seen == [("/marked", True), ("/marked", True)] + assert owner_marked(world.scopes[0]) assert request_work._current.get() is None async def test_sequential_http_requests_keep_owner_and_accounting_separate(world): async def endpoint(scope, receive, send): world.scopes.append(scope) - assert flags(scope) == (False, False) + assert not owner_marked(scope) assert request_work._current.get() is None bag = request_work.begin() if scope["path"] == "/marked": - assert request_work.mark_mirrored(unread=True) + assert request_work.mark_mirrored() bag.ch_statements = 11 else: assert not request_work.mirror_marked() and bag.ch_statements == 0 @@ -129,10 +126,10 @@ async def endpoint(scope, receive, send): assert (await client.get("/ordinary")).status_code == 200 assert world.scopes[0].get(_OWNER_KEY) is not world.scopes[1].get(_OWNER_KEY) assert world.seen == [ - ("/marked", (True, True)), - ("/marked", (True, True)), - ("/ordinary", (False, False)), - ("/ordinary", (False, False)), + ("/marked", True), + ("/marked", True), + ("/ordinary", False), + ("/ordinary", False), ] assert request_work._current.get() is None @@ -148,10 +145,10 @@ async def endpoint(scope, receive, send): assert request_work.mark_mirrored() marked.set() await asyncio.wait_for(ordinary.wait(), timeout=5) - assert flags(scope) == (True, False) + assert owner_marked(scope) else: await asyncio.wait_for(marked.wait(), timeout=5) - assert not request_work.mirror_marked() and flags(scope) == (False, False) + assert not request_work.mirror_marked() and not owner_marked(scope) ordinary.set() await PlainTextResponse("ready")(scope, receive, send) @@ -170,10 +167,10 @@ async def endpoint(scope, receive, send): by_path = {scope["path"]: scope for scope in world.scopes} assert by_path["/marked"].get(_OWNER_KEY) is not by_path["/ordinary"].get(_OWNER_KEY) assert sorted(world.seen) == [ - ("/marked", (True, False)), - ("/marked", (True, False)), - ("/ordinary", (False, False)), - ("/ordinary", (False, False)), + ("/marked", True), + ("/marked", True), + ("/ordinary", False), + ("/ordinary", False), ] assert request_work._current.get() is None @@ -192,7 +189,7 @@ async def endpoint(scope, receive, send): world.scopes.append(scope) assert request_work._current.get() is None request_work.begin() - assert request_work.mark_mirrored(unread=False) + assert request_work.mark_mirrored() raise failure async with httpx.AsyncClient( @@ -207,39 +204,20 @@ async def endpoint(scope, receive, send): assert caught.value.__context__ is failure assert caught.value.__suppress_context__ assert str(caught.value) == "Private request failed" - assert flags(world.scopes[0]) == (True, False) + assert owner_marked(world.scopes[0]) assert request_work._current.get() is prior and not prior.mirror_marked request_work.begin() - assert request_work.mark_mirrored(unread=True) - assert flags(world.scopes[0]) == (True, False) + assert request_work.mark_mirrored() + assert owner_marked(world.scopes[0]) def test_worker_bag_without_http_owner_remains_fresh(world): first = request_work.begin() - assert request_work.mark_mirrored(unread=True) + assert request_work.mark_mirrored() second = request_work.begin() - assert first is not second and first.mirror_marked and first.mirror_unread - assert not request_work.mirror_marked() and not second.mirror_unread - - -async def test_http_owner_unread_is_monotonic_across_distinct_logical_bags(world): - async def endpoint(scope, receive, send): - world.scopes.append(scope) - request_work.begin() - assert request_work.mark_mirrored(unread=True) - assert flags(scope) == (True, True) - next_bag = request_work.begin() - assert request_work.mark_mirrored(unread=False) - assert next_bag.mirror_marked and not next_bag.mirror_unread - assert flags(scope) == (True, True) - await PlainTextResponse("ready")(scope, receive, send) - - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=application(world, endpoint)), base_url="http://test" - ) as client: - assert (await client.get("/marked")).status_code == 200 - assert world.seen == [("/marked", (True, True)), ("/marked", (True, True))] + assert first is not second and first.mirror_marked and not second.mirror_marked + assert not request_work.mirror_marked() async def test_outside_request_mark_cannot_mutate_a_completed_http_owner(world): @@ -253,10 +231,10 @@ async def endpoint(scope, receive, send): ) as client: assert (await client.get("/ordinary")).status_code == 200 completed = world.scopes[0] - assert flags(completed) == (False, False) + assert not owner_marked(completed) request_work.begin() - assert request_work.mark_mirrored(unread=True) - assert flags(completed) == (False, False) + assert request_work.mark_mirrored() + assert not owner_marked(completed) async def test_owner_survives_installed_instrumentor_finalizers(world): diff --git a/tests/unit/test_source_access.py b/tests/unit/test_source_access.py index 29194acdfb3..00bf846d009 100644 --- a/tests/unit/test_source_access.py +++ b/tests/unit/test_source_access.py @@ -162,11 +162,11 @@ async def test_child_leg_mark_is_monotonic_and_visible_after_private_scope(): async def child(): with private_work(): - request_work.mark_mirrored(unread=True) + request_work.mark_mirrored() request_work.mark_mirrored() await asyncio.gather(child(), child()) - assert request_work.mirror_marked() and bag.mirror_unread + assert request_work.mirror_marked() and bag.mirror_marked @pytest.mark.asyncio @@ -174,10 +174,10 @@ async def test_next_request_has_no_preceding_mirror_mark(): from server.core import request_work first = request_work.begin() - request_work.mark_mirrored(unread=True) + request_work.mark_mirrored() second = request_work.begin() - assert first.mirror_marked and first.mirror_unread - assert not request_work.mirror_marked() and not second.mirror_unread + assert first.mirror_marked and not second.mirror_marked + assert not request_work.mirror_marked() def test_candidate_keys_are_coarse_and_keep_unknown_readers_to_anyone(): diff --git a/tests/unit/test_source_access_plan.py b/tests/unit/test_source_access_plan.py index e62f791d6e3..f85e54bb25d 100644 --- a/tests/unit/test_source_access_plan.py +++ b/tests/unit/test_source_access_plan.py @@ -122,7 +122,7 @@ async def test_unconditional_read_failure_has_one_public_marker(world, stage): degradations.begin() plan = await app.prepare("acme", ["docs"]) assert await plan.check(candidates, chunks=True) == [] - assert plan.marked and plan.unread and world["bag"].mirror_unread + assert plan.marked and plan.unread and world["bag"].mirror_marked answers.append(degradations.current()) assert answers == [["knowledge: mirror_unread"]] * 2 @@ -203,7 +203,7 @@ async def test_candidate_failure_discards_prior_results_without_read_marker( world["doc"]["access_json"] = to_json(AccessList(owner="alias@example.com")) world[stage].side_effect = RuntimeError("private candidate error") assert await plan.check([candidate()], chunks=True) == [] - assert plan.failed and not plan.unread and not world["bag"].mirror_unread + assert plan.failed and not plan.unread assert await plan.check([candidate()], chunks=True) == [] @@ -427,7 +427,7 @@ async def chunks(_org, _model, _keys, *, embedded_only=True): assert await source_search.hydrate(plan, {"semantic": [retained]}, model="fake") == { "semantic": [] } - assert not plan.failed and not plan.unread and not world["bag"].mirror_unread + assert not plan.failed and not plan.unread @pytest.mark.parametrize( @@ -447,7 +447,7 @@ async def test_each_batch_refreshes_current_source_and_reader_evidence(world, ch else: world["reader"].return_value = ReaderIdentity("lee", frozenset(), frozenset()) assert await plan.check([candidate()], chunks=True) == [] - assert not plan.failed and not plan.unread and not world["bag"].mirror_unread + assert not plan.failed and not plan.unread @pytest.mark.parametrize("stage", ["sources", "mirrors", "listings", "reader"]) @@ -456,7 +456,7 @@ async def test_scope_refresh_failures_are_conditional_without_unread(world, stag assert await plan.check([candidate()], chunks=True) world[stage].side_effect = RuntimeError("private refresh failure") assert await plan.check([candidate()], chunks=True) == [] - assert plan.failed and not plan.unread and not world["bag"].mirror_unread + assert plan.failed and not plan.unread async def test_refresh_never_adds_new_source_legs_or_rebinds_initial_sources(world): diff --git a/tests/unit/test_source_ask_generation.py b/tests/unit/test_source_ask_generation.py index 4bf635fdc92..08012690c7c 100644 --- a/tests/unit/test_source_ask_generation.py +++ b/tests/unit/test_source_ask_generation.py @@ -370,3 +370,57 @@ async def test_repeated_request_cancellation_joins_the_provider_cleanup(world): if not task.done(): task.cancel() await asyncio.gather(*owned, return_exceptions=True) + + +class _Knowledge: + """Admitted mirrored passages whose document is lost while `lose` says so.""" + + mirrored = True + passages = None + + def __init__(self, lose): + self.lose, self.lost = lose, False + + async def current(self): + return "private block", 1 + + async def ordinary(self): + return "ordinary block", 1 + + def fresh(self): + return not self.lost + + +@pytest.mark.parametrize("lose", [True, False]) +async def test_a_discarded_mirrored_attempt_takes_its_notes_with_it(lose): + """The mirrored attempt noted a fallback: served, its note stands; discarded for a + lost document, the ordinary attempt is served and names only its own.""" + from server.observability import degradations + + knowledge = _Knowledge(lose) + + async def generate(block, _hits, checked): + if checked is not None: + degradations.partial("llm", "fallback_model_answered", "http_503") + knowledge.lost = knowledge.lose + return block + + degradations.begin() + degradations.partial("memory.search", "earlier_note") + got = await pipeline._answer_with_knowledge(generate, knowledge, marked=True) + assert got == ("ordinary block" if lose else "private block") + attempt = [] if lose else ["llm: fallback_model_answered (http_503)"] + assert degradations.current() == ["memory.search: earlier_note", *attempt] + + +async def test_a_mirrored_attempt_that_fails_keeps_its_notes(): + from server.observability import degradations + + async def generate(_block, _hits, _checked): + degradations.partial("llm", "fallback_model_answered", "http_503") + raise RuntimeError("synthesis failed") + + degradations.begin() + with pytest.raises(RuntimeError): + await pipeline._answer_with_knowledge(generate, _Knowledge(False), marked=True) + assert degradations.current() == ["llm: fallback_model_answered (http_503)"] diff --git a/tests/unit/test_source_listing.py b/tests/unit/test_source_listing.py index 36ae60b0983..0a40100f537 100644 --- a/tests/unit/test_source_listing.py +++ b/tests/unit/test_source_listing.py @@ -335,10 +335,10 @@ async def test_discovery_failure_marks_unread_and_never_reads_selected_fields(wo add("gdrive:a", 100) state.stream_error = RuntimeError("private candidate failure") mark = [] - monkeypatch.setattr(request_work, "mark_mirrored", lambda **kwargs: mark.append(kwargs)) + monkeypatch.setattr(request_work, "mark_mirrored", lambda: mark.append(True)) degradations.begin() assert await collect(world) == [] - assert plan.failed and plan.unread and mark == [{"unread": True}] + assert plan.failed and plan.unread and mark == [True] assert degradations.current() == ["knowledge: mirror_unread"] source_documents.store.list_projection.assert_not_awaited() diff --git a/tests/unit/test_source_search_result.py b/tests/unit/test_source_search_result.py index c15d00de430..1fb3740e42b 100644 --- a/tests/unit/test_source_search_result.py +++ b/tests/unit/test_source_search_result.py @@ -124,3 +124,57 @@ async def best_spans(_query, _chunks, batch): with pytest.raises(LostCorpus): await app._narrow_spans(embedder, [1.0], [hit], proofs=proofs) assert not hit.span and state["calls"] == (0 if lost == "before" else 1) + + +def _rerank_fails_then(monkeypatch, *checks): + """A marked search over two mirrored hits whose rerank times out, its proof checks + answering `checks` in turn; the ordinary pass holds one hit, so it is not reranked.""" + from server.knowledge.api.models_knowledge import KnowledgeSearchInput + from server.knowledge.app import source_access, source_search_passes + from server.observability import degradations + + async def rerank(_endpoint, _query, hits, _top): + degradations.partial("rerank", "input_order_kept", TimeoutError()) + return hits, False + + proofs = SimpleNamespace(mirrored=True, check=AsyncMock(side_effect=list(checks))) + mirrored = [("team", [ChunkHit("team", f"gdrive:{n}", 0, n, [], 0.1, score=0.9) for n in "ab"])] + ordinary = [("team", [ChunkHit("team", "ordinary:one", 0, "Ordinary", [], 0.1, score=0.9)])] + embedder = SimpleNamespace(model_name="fake", embed=AsyncMock(return_value=[1.0])) + monkeypatch.setattr( + source_search_passes, "SearchPasses", lambda _plan: SimpleNamespace(proofs=proofs) + ) + monkeypatch.setattr(app, "get_embedder", lambda: embedder) + monkeypatch.setattr(app, "_rerank_endpoint", lambda _input: "rerank") + monkeypatch.setattr(app, "_namespaces_search", lambda *_a, **_k: None) + monkeypatch.setattr(app, "_search_marked", AsyncMock(return_value=(mirrored, ordinary, 0))) + monkeypatch.setattr(app, "_rerank", rerank) + monkeypatch.setattr(app, "_missed", lambda *_a, **_k: False) + degradations.begin() + request = app.SearchRequest( + KnowledgeSearchInput(org="acme", namespace="team", query="q"), ("team",), () + ) + return app.run_checked_search(request, source_access.ReadPlan("acme", marked=True)) + + +async def test_a_render_that_lost_a_document_takes_its_rerank_note_with_it(monkeypatch): + """The rerank timed out, then the proof check lost a mirrored document: the ordinary + render is served, and names no rerank it never ran.""" + from server.observability import degradations + + result = await _rerank_fails_then(monkeypatch, None, LostCorpus()) + assert result.lost + assert [h.source_uri for h in result.output.results] == ["ordinary:one"] + assert degradations.current() == [] + + +async def test_a_later_fallback_replaces_the_served_renders_notes(monkeypatch): + """A render served with its rerank note, then renewed after the document was lost: + the ordinary fallback's notes replace it.""" + from server.observability import degradations + + result = await _rerank_fails_then(monkeypatch, None, None, None, LostCorpus()) + assert degradations.current() == ["rerank: input_order_kept (TimeoutError)"] + output = await result.current() + assert [h.source_uri for h in output.results] == ["ordinary:one"] + assert degradations.current() == [] diff --git a/tests/unit/test_tracker_dupcheck_fanout.py b/tests/unit/test_tracker_dupcheck_fanout.py index 2fdcb5d464d..f9649a371c9 100644 --- a/tests/unit/test_tracker_dupcheck_fanout.py +++ b/tests/unit/test_tracker_dupcheck_fanout.py @@ -473,6 +473,71 @@ async def _one(input, wall, **_kw): assert remembered == ["code-example-private"] +def _remembering(monkeypatch) -> list[str]: + """A check bound to the private record whose namespaces answer at once; the list fills + with each namespace `remember_answer` keeps.""" + from server.code.domain.index import repos + + async def _bind(input): + return input.model_copy(update={"namespace": PRIV}) + + async def _one(input, wall, **_kw): + return _out("none", []) + + remembered: list[str] = [] + monkeypatch.setattr(tcommon, "_bound_input", _bind) + monkeypatch.setattr(tcommon, "_with_default_org", lambda i: i) + monkeypatch.setattr(hd, "_check_one", _one) + monkeypatch.setattr(hd, "remember_answer", lambda org, ns, text, out: remembered.append(ns)) + monkeypatch.setattr(settings, "code_self_service_enabled", True) + monkeypatch.setattr(repos, "_registry_loaded", True) + return remembered + + +@pytest.mark.asyncio +async def test_a_note_the_request_held_before_the_check_does_not_stop_its_memo( + monkeypatch, +) -> None: + from server.observability import degradations + + _wire_namespaces(monkeypatch, readable={PRIV, PUB}) + remembered = _remembering(monkeypatch) + degradations.begin() + degradations.partial("memory", "earlier_step_dropped") + await hd.handle_tracker_duplicate_check( + TrackerDuplicateCheckInput( + org=ORG, namespace="code-example-private", title="x", related_prs=False + ) + ) + assert remembered == ["code-example-private"] + assert degradations.current() == ["memory: earlier_step_dropped"] + + +@pytest.mark.asyncio +async def test_a_target_the_gate_could_not_verify_keeps_the_answer_out_of_the_memo( + monkeypatch, +) -> None: + """The public record's grant, and its repository's, could not be read: the check + answers without it, says so, and is not kept for `code.bisect_candidates`.""" + from server.observability import degradations + + _wire_namespaces(monkeypatch, readable={PRIV}) + + async def _unverified(org, n, role=None, *, hides_answer=True): + return True if n == PRIV else None + + monkeypatch.setattr("server.auth.authz.row_reach", _unverified) + remembered = _remembering(monkeypatch) + degradations.begin() + await hd.handle_tracker_duplicate_check( + TrackerDuplicateCheckInput( + org=ORG, namespace="code-example-private", title="x", related_prs=False + ) + ) + assert "identity: tracker_unverified" in degradations.current() + assert remembered == [] + + @pytest.mark.asyncio async def test_prepared_duplicate_targets_do_not_discover_new_bindings(monkeypatch) -> None: from unittest.mock import AsyncMock From 8290d448188aaae9aab0e8066ed5daba279e2011 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 05:33:11 +0530 Subject: [PATCH 28/47] Keep a note a held group repeats; cache nothing a cut read built A plain note is deduplicated and capped against the request's own notes only. A held group that lists the same note, or fills the cap, no longer keeps it out, so the group's later swap cannot take it away; unit() exits through restore(), so this held for every unit. A literal read cut at its bound still names nothing, and now marks its unit unkeepable (degradations.unkeepable, read by keepable()). The code.search memo, code.ask's answer cache and memory.ask's precedent store keep nothing built on it, and a decision's code discovery defers on retrieval_work.literal_read_cut. A search pass dropped for good takes its held notes back (discard): an ordinary render that fails, a repository-docs leg dropped at its renewal or by its deadline, the wide pass the ordinary passages do not select, and the wider pass loom_search's ordinary section does not serve. CheckedSearch.held always holds a group. A repository-docs renewal past its deadline under a plan that reads mirrors names no timeout, as the search and listing do. A tracker source whose stored namespace map does not parse logs a warning naming the org and source. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/code-index-architecture.md | 16 ++--- docs/architecture/document-sources.md | 2 +- docs/reference/http-api.md | 9 ++- server/code/app/answers_cache.py | 5 +- server/code/app/prose_candidates.py | 7 ++- server/code/app/search/definitions.py | 3 +- server/code/app/search/handler.py | 3 +- server/knowledge/app/knowledge_search.py | 12 ++-- server/knowledge/app/repo_docs.py | 11 +++- server/knowledge/app/source_passages.py | 4 +- server/memory/app/ask/cascade.py | 3 +- server/memory/app/loom_search/fanout.py | 8 ++- server/observability/degradations.py | 61 ++++++++++++++----- server/tracker/app/registry_sources.py | 15 ++++- tests/unit/degraded_unnoted.txt | 2 +- tests/unit/test_code_answer_completeness.py | 48 +++++++++++++++ tests/unit/test_code_search_pick.py | 21 ++++++- tests/unit/test_decision_code_discovery.py | 5 +- tests/unit/test_degradations.py | 42 +++++++++++++ tests/unit/test_degraded_fallback_notes.py | 8 ++- tests/unit/test_memory_ask_precedents.py | 39 ++++++++++++ tests/unit/test_source_fanout_renewal.py | 18 ++++++ tests/unit/test_source_repo_search.py | 17 ++++-- tests/unit/test_source_search_result.py | 62 ++++++++++++++++++++ tests/unit/test_tracker_source_add.py | 12 +++- 25 files changed, 376 insertions(+), 57 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index fd4f461dffb..f6a322f1342 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -611,14 +611,14 @@ in `pkg/json/__init__.py`; its stored qualified name remains intact. Constructor names remain explicit, and ambiguous matches stay unlinked unless the memory's file scope selects one definition. -| Op | Path | How | -| -------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, the definitions the query names (`definitions.py`: the functions of the innermost two frames inside the repository of a pasted Python traceback, read by file and name and each served as the chunk that holds the frame's source line, then the names the rest of the text spells out as code, each one written with its owner and after them the first other name, three definitions in all; for a name the text only calls without a receiver inside a fenced block marked as Python, outside its comments, its string literals and its lines that lead with a dotted name or a path and a colon (the form of a pasted exception or warning line), a method or a nested definition of a Python file is left out, and a definition in another language is read as for any other name; a traceback whose frames name nothing in the index adds no name of its own; in the places those leave, the functions outside test and vendored paths that hold a literal the text marks as code and no identifier rule reads, a token with a hyphen inside written between backticks or quotes or the name of a long option with underscores, found as a whole token by one read through the n-gram index that the leg waits half a second for, and under a request budget no more than half the leg window, a literal that more than three functions hold or whose read runs longer being dropped, the cut counted as `retrieval_work.literal_read_cut` and such a run not memoized; the text is the request's `report` when it sends one, the whole of a report it searches with the opening of), fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `rank.py` applies the priors and then serves the named definitions directly after the first unit, at its score; `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. | -| `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. | -| `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. | -| `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. | -| `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. | -| `code.trace` | `code/app/symbol/trace.py` | Reads the frames of the text: qualified `a::b` names, C/C++ `dir/file.cpp:N` locations, and Python frames in the interpreter, notebook and test-runner forms, which `frames` returns as `path:line in function`. A name resolves through the symbol table and a location to the innermost symbol that holds its line. A Python frame resolves to the definition of its function in the file under the longest tail of its printed path, as written or under `src/` or `lib/`; its line chooses only among several definitions of the name. Over `max_frames` a native backtrace keeps its first frames and a Python traceback its last. | +| Op | Path | How | +| -------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, the definitions the query names (`definitions.py`: the functions of the innermost two frames inside the repository of a pasted Python traceback, read by file and name and each served as the chunk that holds the frame's source line, then the names the rest of the text spells out as code, each one written with its owner and after them the first other name, three definitions in all; for a name the text only calls without a receiver inside a fenced block marked as Python, outside its comments, its string literals and its lines that lead with a dotted name or a path and a colon (the form of a pasted exception or warning line), a method or a nested definition of a Python file is left out, and a definition in another language is read as for any other name; a traceback whose frames name nothing in the index adds no name of its own; in the places those leave, the functions outside test and vendored paths that hold a literal the text marks as code and no identifier rule reads, a token with a hyphen inside written between backticks or quotes or the name of a long option with underscores, found as a whole token by one read through the n-gram index that the leg waits half a second for, and under a request budget no more than half the leg window, a literal that more than three functions hold or whose read runs longer being dropped, the cut counted as `retrieval_work.literal_read_cut` and kept out of every cache (the `code.search` memo, a `code.ask` answer, a `memory.ask` precedent); the text is the request's `report` when it sends one, the whole of a report it searches with the opening of), fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `rank.py` applies the priors and then serves the named definitions directly after the first unit, at its score; `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. | +| `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. | +| `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. | +| `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. | +| `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. | +| `code.trace` | `code/app/symbol/trace.py` | Reads the frames of the text: qualified `a::b` names, C/C++ `dir/file.cpp:N` locations, and Python frames in the interpreter, notebook and test-runner forms, which `frames` returns as `path:line in function`. A name resolves through the symbol table and a location to the innermost symbol that holds its line. A Python frame resolves to the definition of its function in the file under the longest tail of its printed path, as written or under `src/` or `lib/`; its line chooses only among several definitions of the name. Over `max_frames` a native backtrace keeps its first frames and a Python traceback its last. | The lexical text-index gate tokenizes the query with `splitByNonAlpha`, matching the index tokenizer. The score counts only whole app lexemes and rejects partial matches diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 65664e9a7e9..17e83bd3cce 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -993,7 +993,7 @@ reader's canonical subject and verified emails among them) fail shows no mirrore document and lists `knowledge: mirror_unread` in the answer's `degraded`; a read it issues only for candidates (the lists, the members rows, the heads) that fails drops every mirrored result without the marker, so the marker says nothing about what matched. -For the same reason a repository-docs search or listing that passes +For the same reason a repository-docs search, its renewal or a listing that passes `knowledge_repo_docs_timeout_s` under a plan that reads mirrors is dropped without `knowledge: repo_docs_dropped` or `repo_docs_unlisted`: its candidate checks run inside that bound. Each leg reads the registry row and the listing row first and then the diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 47d28c7f74c..5427d3c8390 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -327,10 +327,17 @@ error's kind only; the full text is in the server log. `code.review_brief` serves the brief unstored (`stored: false`). Each judges the entries its own reads recorded, so one the request recorded before it does not stop the cache. +- A `code.search` literal read cut at its bound lists nothing, since a literal that many + functions hold names no definition, and counts `retrieval_work.literal_read_cut`. A slow + store can cut a rare literal's read too, so `code.search` and `code.ask` do not cache an + answer built on it, `memory.ask` stores no precedent from it, and a decision's code + discovery is deferred. - An answer replaced before it is served does not list what it recorded: a document search that lost access to a mirrored document mid-request and answers from its ordinary pass, and the `memory.ask` attempt discarded for the same reason, list only - the served answer's entries. + the served answer's entries. So does a search pass the answer leaves out: a wider pass + it did not need, a repository-docs leg dropped past its deadline, or an ordinary render + that failed, whose failure the caller names. - Some caches keep a fallback with its entries and name them on each answer served from it, for: - `LOOM_CODE_STATUS_TTL_S`: a `code.index_status` or `code.repos` status; diff --git a/server/code/app/answers_cache.py b/server/code/app/answers_cache.py index ed7fa25f290..a331651667e 100644 --- a/server/code/app/answers_cache.py +++ b/server/code/app/answers_cache.py @@ -331,8 +331,9 @@ def _exact_cached(llm: Any, org: str, ns: str) -> Any: async def _remember(ctx: _AskCtx, res: AskResult, llm: Any) -> None: """Store a memoizable answer, or a negative entry for an abstain. A partial answer, - or one served from a fallback (a note of the unit `ask` builds it in), is not stored.""" - if res.partial or degradations.current(): + one served from a fallback (a note of the unit `ask` builds it in) and one whose read + was cut short (`degradations.unkeepable`) are not stored.""" + if res.partial or not degradations.keepable(): return try: if res.abstain: diff --git a/server/code/app/prose_candidates.py b/server/code/app/prose_candidates.py index 92ffca536a6..950416e65de 100644 --- a/server/code/app/prose_candidates.py +++ b/server/code/app/prose_candidates.py @@ -105,7 +105,12 @@ async def _discover(org: str, result: CodeDiscovery) -> None: confident_similarity=confident, deadline_ms=1500, ) - if out.partial or out.epistemic == "partial" or out.legs_timed_out: + if ( + out.partial + or out.epistemic == "partial" + or out.legs_timed_out + or out.retrieval_work.get("literal_read_cut") + ): result.status, result.note = "deferred", "retrieval or index freshness is incomplete" return units = [ diff --git a/server/code/app/search/definitions.py b/server/code/app/search/definitions.py index d4693aa7fb1..f0e32ce4933 100644 --- a/server/code/app/search/definitions.py +++ b/server/code/app/search/definitions.py @@ -368,7 +368,7 @@ async def _literal_leg( waits `seconds` for it and ClickHouse stops it after as long: the literals of a read that runs longer name nothing. That is an answer, not a fault of the store, so it is not noted; a slow store can cut a rare literal's read too, so the run counts it - (`literal_read_cut`) and is not memoised.""" + (`literal_read_cut`) and no cache keeps what it built (`degradations.unkeepable`).""" if not literals: return [] try: @@ -390,6 +390,7 @@ async def _literal_leg( raise logger.info("code.search literal lookup stopped at its bound of %g s", seconds) work["literal_read_cut"] = 1 + degradations.unkeepable() return [] return literal_definitions(literals, rows) diff --git a/server/code/app/search/handler.py b/server/code/app/search/handler.py index 13411f5a1ec..9dd014c4ac5 100644 --- a/server/code/app/search/handler.py +++ b/server/code/app/search/handler.py @@ -408,10 +408,9 @@ async def _finish_search( memo_key is not None and not (res.history or {}).get("failed") and not res.retrieval_work.get("pick_failed") - and not res.retrieval_work.get("literal_read_cut") and not out.partial and not res.epistemic - and not degradations.current() + and degradations.keepable() ): from server.code.app import search_memo as memo diff --git a/server/knowledge/app/knowledge_search.py b/server/knowledge/app/knowledge_search.py index 17d34bd2fb6..56d7c78339e 100644 --- a/server/knowledge/app/knowledge_search.py +++ b/server/knowledge/app/knowledge_search.py @@ -121,7 +121,7 @@ class CheckedSearch: lost: bool = False ordinary_rerank_possible: bool = False # The served render's notes; the ordinary fallback swaps in its own. - held: degradations.Held | None = None + held: degradations.Held = dataclasses.field(default_factory=lambda: degradations.hold([])) _failed: bool = dataclasses.field(default=False, init=False) _checking: asyncio.Lock = dataclasses.field( default_factory=asyncio.Lock, init=False, repr=False @@ -152,13 +152,15 @@ async def _fallback(self) -> KnowledgeSearchOutput: ) except BaseException: self._failed = True + self.discard() # nothing of it is served; the caller names the failure raise - if self.held is not None: - self.held.swap(noted) # the discarded render's notes go with it - else: - degradations.restore(noted) + self.held.swap(noted) # the discarded render's notes go with it return self.output + def discard(self) -> None: + """Take the served render's notes back: the caller serves nothing of this search.""" + self.held.swap([]) + async def ordinary(self) -> KnowledgeSearchOutput: async with self._checking: with private_work() if self.marked else nullcontext(): diff --git a/server/knowledge/app/repo_docs.py b/server/knowledge/app/repo_docs.py index 8d7d8ecd4a7..3ebd4dba921 100644 --- a/server/knowledge/app/repo_docs.py +++ b/server/knowledge/app/repo_docs.py @@ -114,9 +114,10 @@ async def _renew_extra(self, *, ordinary: bool = False) -> None: await extra.ordinary() else: await extra.current() - except Exception: # noqa: BLE001 — an additive renewal failure leaves the base search intact - degradations.partial("knowledge", "repo_docs_dropped") + except Exception as e: # noqa: BLE001 — an additive renewal failure leaves the base search intact + _note_dropped("repo_docs_dropped", e, marked=self.base.marked) self._lost |= extra.lost + extra.discard() self.extra = None log.info("repo docs search did not answer") @@ -127,8 +128,14 @@ def _drop_expired_extra(self) -> None: and asyncio.get_running_loop().time() >= self.request.extra_deadline ): self._lost |= self.extra.lost + self.extra.discard() self.extra = None + def discard(self) -> None: + """Take both legs' notes back: the caller serves nothing of this search.""" + for child in self.children: + child.discard() + async def _ordinary(self) -> KnowledgeSearchOutput: self._lost = True await gather_or_cancel(self.base.ordinary(), self._renew_extra(ordinary=True)) diff --git a/server/knowledge/app/source_passages.py b/server/knowledge/app/source_passages.py index 56005f50fbb..25507482a10 100644 --- a/server/knowledge/app/source_passages.py +++ b/server/knowledge/app/source_passages.py @@ -93,8 +93,10 @@ async def _fallback(self) -> list[_SearchHit]: try: wide = (await self._wide.ordinary()).results except Exception: # noqa: BLE001 — the first complete ordinary pass still answers - self._wide = None + self._wide = None # its failed render took its notes back self.hits = await self._select(first, wide) + if self._wide is not None and not self._used_wide: + self._wide.discard() # the ordinary answer is final and serves the first alone self._ordinary_ready = True except BaseException: self._failed = True diff --git a/server/memory/app/ask/cascade.py b/server/memory/app/ask/cascade.py index edeb7b5f648..ca8123149d5 100644 --- a/server/memory/app/ask/cascade.py +++ b/server/memory/app/ask/cascade.py @@ -610,12 +610,13 @@ async def _deferred_judge() -> Any: if codes_only(): return verdict, note, premise_text, None # An answer a fallback served is no precedent: its reuse would drop the `degraded`. + # Nor is one a cut read built (a code grounding search's literal read). _precedent_eligible = bool( precedent_key and marked_cited and not ans.deep_fired and not _policy.cheap_answer_failed(ans.answer, ans.cited) - and not degradations.current() + and degradations.keepable() ) _prec_synth_model = _LAST_SYNTH_MODEL.get() or str(getattr(ans.client, "model", "") or "") _prec_cited, _prec_answer = list(ans.cited), ans.answer diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index bd17891d86a..ab5c7bfb850 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -241,20 +241,26 @@ async def _ordinary_knowledge( agent: str, ) -> dict[str, Any]: await first.ordinary() + served_wider = False async def expanded(k: int) -> KnowledgeSearchOutput: + nonlocal served_wider if wider is not None: # A wider fallback is additive; served_hits keeps the first on failure. await wider.ordinary() + served_wider = True return wider.output request = first.request.wider(k) # The saved authorized scopes run without any new mirror discovery. ordinary = await repo_docs.run_repo_search(request, ReadPlan(request.base.input.org)) return await ordinary.current() - return await _filtered_knowledge( + section = await _filtered_knowledge( first.output, expanded, agent, int(first.request.base.input.top_k) ) + if wider is not None and not served_wider: + wider.discard() # unused or failed: its renders' notes go with it + return section async def _knowledge_section( diff --git a/server/observability/degradations.py b/server/observability/degradations.py index 64988689201..c1c25a3fb47 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -20,8 +20,9 @@ - a provider failed, and its own client already recorded the failure. An answer kept for a later call (a memo, a stored brief) is built inside `unit()`, and -kept only when the unit's own notes are empty: an earlier note of the request is not -the answer's. An answer a later step may still replace lists its notes through `hold()`, +kept only when the unit's own notes are empty and nothing in it called `unkeepable()` +(`keepable`): an earlier note of the request is not the answer's. An answer a later step +may still replace lists its notes through `hold()`, and the replacement swaps them, so a discarded answer's notes go with it. degraded: ["classify: caller_type_kept (HTTPStatusError)", @@ -58,22 +59,33 @@ def swap(self, entries: list[str]) -> None: self.entries = list(entries) -_notes: contextvars.ContextVar[list[str | Held] | None] = contextvars.ContextVar( +class _Unkept: + """In a note list: what the unit built is the answer for this call, but a later one + may read more, so no cache keeps it. `degraded` does not list it.""" + + __slots__ = () + + +_UNKEPT = _Unkept() + +_notes: contextvars.ContextVar[list[str | Held | _Unkept] | None] = contextvars.ContextVar( "loom_degradations", default=None ) -def _flat(lst: list[str | Held] | None) -> list[str]: +def _flat(lst: list[str | Held | _Unkept] | None) -> list[str]: """The distinct notes of a list, a held group's in its place, at most `_MAX_NOTES`.""" out: list[str] = [] for item in lst or (): + if isinstance(item, _Unkept): + continue for entry in item.entries if isinstance(item, Held) else (item,): if entry not in out and len(out) < _MAX_NOTES: out.append(entry) return out -def _bound() -> list[str | Held]: +def _bound() -> list[str | Held | _Unkept]: lst = _notes.get() if lst is None: lst = [] @@ -81,6 +93,14 @@ def _bound() -> list[str | Held]: return lst +def _add(lst: list[str | Held | _Unkept], entry: str) -> None: + """List a note once, at most `_MAX_NOTES` of them, counting only the request's own + notes: a held group a later swap may empty does not stand in for one.""" + own = [item for item in lst if isinstance(item, str)] + if entry not in own and len(own) < _MAX_NOTES: + lst.append(entry) + + def begin() -> None: """Bind a fresh, empty note list for this request.""" _notes.set([]) @@ -131,10 +151,7 @@ def note(provider: str, effect: str, reason: object = "", *, health: bool = True entry = f"{provider}: {effect}" + (f" ({text})" if text else "") # No transport bound a list (a worker, a test): still count it for health, and # start a list so a later reader sees it. - lst = _bound() - listed = _flat(lst) - if entry not in listed and len(listed) < _MAX_NOTES: - lst.append(entry) + _add(_bound(), entry) if not health: return try: @@ -165,18 +182,32 @@ def restore(entries: Any) -> None: """List `entries`, the notes of the request whose stored answer this one serves (a later page), as they were. Provider health counted them when they happened. Bounded like `note`; anything but a list is ignored. A `Held` group (a unit's own list) is - listed as the group, so a later swap still replaces it.""" + listed as the group, so a later swap still replaces it, and an `unkeepable` mark + carries to the caller's unit.""" if not isinstance(entries, list): return lst = _bound() for item in entries: - if isinstance(item, Held): + if isinstance(item, Held | _Unkept): if not any(item is held for held in lst): lst.append(item) continue - entry, listed = str(item), _flat(lst) - if entry not in listed and len(listed) < _MAX_NOTES: - lst.append(entry) + _add(lst, str(item)) + + +def unkeepable() -> None: + """Keep what this unit builds out of every cache without naming anything: a read its + own bound cut is the answer for this call, but a later one may read more.""" + lst = _bound() + if _UNKEPT not in lst: + lst.append(_UNKEPT) + + +def keepable() -> bool: + """Whether a cache may keep what this unit built: it noted nothing and called no + `unkeepable()`.""" + lst = _notes.get() or [] + return not _flat(lst) and _UNKEPT not in lst def hold(entries: list[str]) -> Held: @@ -209,10 +240,12 @@ def on_response(body: Any) -> Any: "begin", "current", "hold", + "keepable", "note", "on_response", "partial", "restore", "scoped", "unit", + "unkeepable", ] diff --git a/server/tracker/app/registry_sources.py b/server/tracker/app/registry_sources.py index 1d6f115d971..9aa450ec4ce 100644 --- a/server/tracker/app/registry_sources.py +++ b/server/tracker/app/registry_sources.py @@ -55,10 +55,17 @@ def decrypt_password(enc: str) -> str: _LOADED_AT = 0.0 -def _namespaces_of(raw: Any) -> dict[str, dict[str, Any]]: +def _namespaces_of(raw: Any, *, org: str, name: str) -> dict[str, dict[str, Any]]: try: data = json.loads(raw) if isinstance(raw, str) else dict(raw or {}) - except Exception: # noqa: BLE001 — an unparseable stored map links no namespace + except Exception as e: # noqa: BLE001 — an unparseable stored map links no namespace + # The kind only: the stored text names the source's namespaces. + logger.warning( + "tracker source %s/%s: stored namespace map did not parse (%s); it links no namespace", + org, + name, + type(e).__name__, + ) return {} out: dict[str, dict[str, Any]] = {} for ns, spec in (data or {}).items(): @@ -96,7 +103,9 @@ def row_to_source(r: dict[str, Any]) -> DbSource: database=str(r.get("database") or ""), user=str(r.get("user") or ""), password=decrypt_password(str(r.get("password_enc") or "")), - namespaces=_namespaces_of(r.get("namespaces_json")), + namespaces=_namespaces_of( + r.get("namespaces_json"), org=str(r.get("org") or ""), name=str(r.get("name") or "") + ), created_by=str(r.get("created_by") or ""), mapping_json=str(r.get("mapping_json") or ""), created_at=r.get("created_at") if isinstance(r.get("created_at"), datetime) else None, diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index e7cc8b2e6a1..b5fa18ce7f5 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -96,7 +96,7 @@ server/code/app/repos.py::_code_repo_rows::1 server/code/app/review_brief.py::_payload_for::1 cache_fallback server/code/app/risk.py::RiskPrefetch._run::1 full_answer_fallback server/code/app/risk.py::RiskPrefetch.start::1 full_answer_fallback -server/code/app/search/definitions.py::_literal_leg::timeout::1 answer # the bound names nothing, as the leg's design says; the run counts it (`literal_read_cut`) and is not memoised +server/code/app/search/definitions.py::_literal_leg::timeout::1 answer # the bound names nothing, as the leg's design says; the run counts it (`literal_read_cut`) and no cache keeps what it built (`degradations.unkeepable`) server/code/app/search/handler.py::_embedding_model_name::1 full_answer_fallback server/code/app/search/rerank.py::_rerank_stage::timeout::1 deadline # cut at what the search's deadline left; partial_reason names the rerank server/code/app/search_cursor.py::get_pool::1 cache_fallback diff --git a/tests/unit/test_code_answer_completeness.py b/tests/unit/test_code_answer_completeness.py index d1aed0caff8..3378f87f6f0 100644 --- a/tests/unit/test_code_answer_completeness.py +++ b/tests/unit/test_code_answer_completeness.py @@ -214,6 +214,54 @@ async def not_gone(*args: Any, **kwargs: Any) -> bool: assert stored == [{"kind": "negative", "abstain_reason": "no_evidence"}] +@pytest.mark.asyncio +async def test_an_answer_built_on_a_cut_literal_read_is_not_stored( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The cut names nothing, but under load it can drop a rare literal's function: a + later ask may read it, so neither the answer nor an abstain is kept.""" + import asyncio + + from server.code.app import answers_cache + from server.code.app.search import definitions + from server.observability import degradations + from server.settings import settings + + class _Slow: + async def literal_function_chunks(self, *a: Any, **k: Any) -> list[Any]: + await asyncio.sleep(60) + return [] + + stored: list[Any] = [] + + async def store(ctx: Any, row: Any) -> None: + stored.append(row) + + async def not_gone(*args: Any, **kwargs: Any) -> bool: + return False + + monkeypatch.setattr(answers_cache, "_store_then_check", store) + monkeypatch.setattr(answers_cache, "_answer_may_be_gone", not_gone) + monkeypatch.setattr(answers_cache, "_entry_row", lambda ctx, **kw: kw) + monkeypatch.setattr(settings, "code_ask_negative_cache_ttl_s", 600) + result = answers_entry.AskResult(source="abstained", abstain=True, abstain_reason="no_evidence") + ctx = SimpleNamespace(index_head="h" * 40) + + degradations.begin() + with degradations.unit(): # as `ask` builds its answer + work: dict[str, int] = {} + literal = ["quota-exceeded"] + cut = await definitions._literal_leg( + _Slow(), "o", "n", "m", literal, seconds=0.001, work=work, path_prefix="", scope=None + ) + assert cut == [] and work == {"literal_read_cut": 1} + await answers_cache._remember(ctx, result, None) + assert stored == [] and degradations.current() == [] + with degradations.unit(): + await answers_cache._remember(ctx, result, None) + assert stored == [{"kind": "negative", "abstain_reason": "no_evidence"}] + + def test_ranking_changes_invalidate_cached_answers(monkeypatch: pytest.MonkeyPatch) -> None: from server.settings import settings diff --git a/tests/unit/test_code_search_pick.py b/tests/unit/test_code_search_pick.py index 772b0e61ce7..581ac775188 100644 --- a/tests/unit/test_code_search_pick.py +++ b/tests/unit/test_code_search_pick.py @@ -398,11 +398,26 @@ async def no_coverage_note(repo: Any, org: str, ns: str) -> str: monkeypatch.setattr(handler, "embedding_coverage_note", no_coverage_note) monkeypatch.setattr(handler, "resolve_code_thresholds", thresholds) if literal_cut: - from server.code.app.search import gather + from server.code.app.search import definitions, gather + + class _Slow: + async def literal_function_chunks(self, *_a: Any, **_k: Any) -> list[Any]: + await asyncio.sleep(60) + return [] async def cut(*_a: Any, work: dict[str, int], **_k: Any) -> list[dict[str, Any]]: - work["literal_read_cut"] = 1 # what `_literal_leg` counts at its bound - return [] + # the literal read, past its bound + return await definitions._literal_leg( + _Slow(), # type: ignore[arg-type] + "o", + "n", + "m", + ["quota-exceeded"], + seconds=0.001, + work=work, + path_prefix="", + scope=None, + ) monkeypatch.setattr(gather, "_definition_leg", cut) monkeypatch.setattr(embedding, "get_embedder", lambda: _Embedder()) diff --git a/tests/unit/test_decision_code_discovery.py b/tests/unit/test_decision_code_discovery.py index 885cee5239f..1d2c277edd8 100644 --- a/tests/unit/test_decision_code_discovery.py +++ b/tests/unit/test_decision_code_discovery.py @@ -196,12 +196,15 @@ async def test_candidates_outside_current_code_evidence_are_rejected(monkeypatch @pytest.mark.parametrize( - "change", ["partial", "failed_leg", "unknown", "stale", "branch", "commit", "tier"] + "change", + ["partial", "failed_leg", "literal_cut", "unknown", "stale", "branch", "commit", "tier"], ) @pytest.mark.asyncio async def test_incomplete_retrieval_is_deferred_not_empty_success(monkeypatch, index, change): if change == "partial": index.result.retrieval_work["vector_leg_failed"] = 1 + elif change == "literal_cut": # names nothing, but a later pass may read the literal + index.result.retrieval_work["literal_read_cut"] = 1 elif change == "failed_leg": index.result.epistemic = "partial" elif change == "tier": diff --git a/tests/unit/test_degradations.py b/tests/unit/test_degradations.py index ff6514c4a57..1e49cf15784 100644 --- a/tests/unit/test_degradations.py +++ b/tests/unit/test_degradations.py @@ -77,6 +77,48 @@ def test_a_held_group_is_listed_until_its_swap_and_another_holder_keeps_its_copy assert len(D.current()) == D._MAX_NOTES +def test_a_note_a_held_group_also_lists_stays_after_the_swap(): + rerank = "rerank: input_order_kept (TimeoutError)" + D.begin() + held = D.hold([rerank]) + D.partial("rerank", "input_order_kept", TimeoutError()) + assert D.current() == [rerank] + held.swap([]) + assert D.current() == [rerank] + # A unit's notes reach the caller through restore, which counts the same way. + D.begin() + held = D.hold([rerank]) + with D.unit(): + D.partial("rerank", "input_order_kept", TimeoutError()) + held.swap([]) + assert D.current() == [rerank] + + +def test_an_unkeepable_unit_names_nothing_and_keeps_its_callers_answer_out(): + D.begin() + with D.unit(): + assert D.keepable() + with D.unit(): + with D.unit(): # a code.search run inside the ask that builds on it + D.unkeepable() + assert not D.keepable() + assert not D.keepable() and D.current() == [] + with D.unit(): + assert D.keepable() # an earlier unit's mark is not this one's + assert not D.keepable() and D.on_response({}) == {} + + +def test_a_held_group_at_the_cap_keeps_no_note_out(): + D.begin() + full = [f"x: {i}" for i in range(D._MAX_NOTES)] + held = D.hold(full) + D.partial("x", "0") # listed by the group too + D.partial("memory", "first") # past the cap while the group is held + assert D.current() == full + held.swap([]) + assert D.current() == ["x: 0", "memory: first"] + + def test_notes_feed_provider_health(): D.note("classify", "caller_type_kept", "HTTP 502") st = provider_health.status() diff --git a/tests/unit/test_degraded_fallback_notes.py b/tests/unit/test_degraded_fallback_notes.py index 1bdda896fb5..ee07b929526 100644 --- a/tests/unit/test_degraded_fallback_notes.py +++ b/tests/unit/test_degraded_fallback_notes.py @@ -134,8 +134,12 @@ async def _live_publish(mp: pytest.MonkeyPatch) -> Any: async def _repo_docs_renewal(mp: pytest.MonkeyPatch) -> Any: from server.knowledge.app import repo_docs - extra = SimpleNamespace(proofs=None, lost=False, ordinary=_boom, current=_boom) - search = repo_docs.RepoSearch(SimpleNamespace(), SimpleNamespace(), extra) # type: ignore[arg-type] + extra = SimpleNamespace( + proofs=None, lost=False, ordinary=_boom, current=_boom, discard=lambda: None + ) + # under a plan that reads mirrors too: only a timeout goes unnamed there + base = SimpleNamespace(marked=True) + search = repo_docs.RepoSearch(SimpleNamespace(), base, extra) # type: ignore[arg-type] return await search._renew_extra() diff --git a/tests/unit/test_memory_ask_precedents.py b/tests/unit/test_memory_ask_precedents.py index 9e563e73ab5..321ce8bb730 100644 --- a/tests/unit/test_memory_ask_precedents.py +++ b/tests/unit/test_memory_ask_precedents.py @@ -363,6 +363,45 @@ async def degraded_search(search_input: Any): assert out.source == "synthesized" and prec_env.inserts == [] +@pytest.mark.asyncio +async def test_an_answer_whose_code_search_cut_its_literal_read_is_no_precedent( + prec_env, monkeypatch: pytest.MonkeyPatch +) -> None: + """The cut names nothing, but a later ask's grounding may read the definition it + dropped, so the answer is not kept for reuse.""" + import server.memory.app.code_grounding as grounding + from server.code.app.search import definitions + from server.observability import degradations + + class _Slow: + async def literal_function_chunks(self, *a: Any, **k: Any) -> list[Any]: + await asyncio.sleep(60) + return [] + + async def grounded(query: str, search_input: Any, pool: list[Any], settings: Any): + with degradations.unit(): # the code.search run the grounding calls + work: dict[str, int] = {} + literal = ["quota-exceeded"] + await definitions._literal_leg( + _Slow(), + "o", + "n", + "m", + literal, + seconds=0.001, + work=work, + path_prefix="", + scope=None, + ) + return pool + + monkeypatch.setattr(grounding, "apply_code_grounding", grounded) + degradations.begin() + out = await _ask() + assert out.source == "synthesized" and prec_env.inserts == [] + assert degradations.current() == [] + + @pytest.mark.asyncio async def test_an_answer_whose_code_grant_was_unread_is_no_precedent( prec_env, monkeypatch: pytest.MonkeyPatch diff --git a/tests/unit/test_source_fanout_renewal.py b/tests/unit/test_source_fanout_renewal.py index 3327f9b3236..fba306b6dff 100644 --- a/tests/unit/test_source_fanout_renewal.py +++ b/tests/unit/test_source_fanout_renewal.py @@ -241,3 +241,21 @@ async def run(request, plan): wider.base.proofs.check.assert_not_awaited() wider_renderer.render.assert_not_awaited() first_renderer.render.assert_not_awaited() + + +@pytest.mark.parametrize("wider_case", ["unused", "failed"]) +async def test_a_wider_pass_the_ordinary_section_does_not_serve_takes_its_notes_with_it( + wider_case, +): + from server.observability import degradations + + degradations.begin() + first, _ = result("first", ordinary_full=wider_case == "unused") + wider, wider_renderer = result("wider", fail_render=wider_case == "failed") + wider.base.held = degradations.hold(["rerank: input_order_kept (TimeoutError)"]) + with private_work(): + know = await fanout._ordinary_knowledge(first, wider, "reader") + served = ["ordinary-a", "ordinary-b"] if wider_case == "unused" else ["ordinary-a"] + assert [h["source_uri"] for h in know["results"]] == served + assert wider_renderer.render.await_count == (wider_case == "failed") + assert "rerank: input_order_kept (TimeoutError)" not in degradations.current() diff --git a/tests/unit/test_source_repo_search.py b/tests/unit/test_source_repo_search.py index 51999084f9b..b3da7431c71 100644 --- a/tests/unit/test_source_repo_search.py +++ b/tests/unit/test_source_repo_search.py @@ -18,6 +18,7 @@ from server.knowledge.app import knowledge_search as search from server.knowledge.app import repo_docs, source_access from server.knowledge.app.source_corpus import LostCorpus +from server.observability import degradations from tests.unit.clock_fake import ManualClock @@ -386,14 +387,19 @@ async def wait_forever(): async def expire_before_renewal(request, plan): result = await original(request, plan) children["repo"].proofs.check = wait_forever + children["repo"].held = degradations.hold(["knowledge: spans_unnarrowed"]) clock.advance(request.extra_deadline - clock.monotonic()) return result monkeypatch.setattr(repo_docs, "run_repo_search", expire_before_renewal) monkeypatch.setattr(repo_docs.settings, "knowledge_repo_docs_timeout_s", 0.005) - out = await asyncio.wait_for( - repo_docs.knowledge_with_repo_docs(INPUT, repo_namespace="repo"), timeout=0.1 - ) + with degradations.scoped(): + out = await asyncio.wait_for( + repo_docs.knowledge_with_repo_docs(INPUT, repo_namespace="repo"), timeout=0.1 + ) + # The renewal's checks of mirror candidates ran inside the bound: no timeout named, + # and the dropped leg's render notes go with it. + assert degradations.current() == [] assert [h.source_uri for h in out.results] == ["private:home"] assert entered == [] and cleaned == [] assert not children["home"].lost and "check:home" in events @@ -485,7 +491,10 @@ async def check(): await asyncio.sleep(0.01) children["home"].proofs.check = check - out = await result.current() + with degradations.scoped(): + children["repo"].held = degradations.hold(["knowledge: spans_unnarrowed"]) + out = await result.current() + assert degradations.current() == [] # the expired leg's notes went with it assert [h.source_uri for h in out.results] == ["private:home"] assert result.extra is None and not children["home"].lost assert "ordinary:home" not in events diff --git a/tests/unit/test_source_search_result.py b/tests/unit/test_source_search_result.py index 1fb3740e42b..7ff2bb9f15c 100644 --- a/tests/unit/test_source_search_result.py +++ b/tests/unit/test_source_search_result.py @@ -178,3 +178,65 @@ async def test_a_later_fallback_replaces_the_served_renders_notes(monkeypatch): output = await result.current() assert [h.source_uri for h in output.results] == ["ordinary:one"] assert degradations.current() == [] + + +async def test_a_fallback_whose_render_fails_names_nothing_of_the_discarded_render(monkeypatch): + """The ordinary render raised: nothing of the search is served, so the mixed render's + rerank note goes; the caller names the failure.""" + from server.observability import degradations + + result = await _rerank_fails_then(monkeypatch, None, None, None, LostCorpus()) + + async def fails(*_a): + raise RuntimeError("ordinary render failed") + + result._renderer = SimpleNamespace(marked=True, render=fails) + with pytest.raises(RuntimeError): + await result.current() + assert degradations.current() == [] + with pytest.raises(LostCorpus): # failed for good + await result.ordinary() + + +@pytest.mark.parametrize("fail", [False, True], ids=["unused", "failed"]) +async def test_a_wide_pass_the_ordinary_passages_drop_takes_its_notes_with_it(fail): + from server.knowledge.api.models_knowledge import _SearchHit + from server.knowledge.app.source_passages import CheckedPassages + from server.observability import degradations + + def hit(uri): + return _SearchHit( + source_uri=uri, + content=uri, + chunk_idx=0, + tags=[], + distance=0.2, + similarity=0.8, + score=0.8, + ) + + def checked(uris, effect, *, fail_render=False, held=()): + out = KnowledgeSearchOutput(results=[hit(u) for u in uris], embedding_model="m") + + async def render(*_a): + if fail_render: + raise RuntimeError("render failed") + degradations.partial("knowledge", effect) + return out + + proof = SimpleNamespace(mirrored=True, check=AsyncMock(), fresh=lambda: False) + renderer = SimpleNamespace(marked=True, render=render) + return app.CheckedSearch(out, proof, renderer, [], 0, held=degradations.hold(list(held))) + + degradations.begin() + first = checked(["a", "b"], "spans_unnarrowed") + wide = checked( + ["a", "b", "c"], + "wide_spans_unnarrowed", + fail_render=fail, + held=["rerank: input_order_kept (TimeoutError)"], + ) + passages = CheckedPassages(first, wide, "reader", 2, None, []) + assert [h.source_uri for h in await passages.ordinary()] == ["a", "b"] + # the first pass's ordinary render is served with its note; the wide pass is not + assert degradations.current() == ["knowledge: spans_unnarrowed"] diff --git a/tests/unit/test_tracker_source_add.py b/tests/unit/test_tracker_source_add.py index 570d1fec34b..85bbea9dc24 100644 --- a/tests/unit/test_tracker_source_add.py +++ b/tests/unit/test_tracker_source_add.py @@ -1223,7 +1223,9 @@ async def _admits(auth: Any, org: str, namespace: str, *, flagged: bool) -> bool @pytest.mark.parametrize("op", ["rotate", "set_mapping", "remove", "inspect"]) @pytest.mark.asyncio -async def test_a_source_whose_namespaces_did_not_parse_is_refused(_cfg, monkeypatch, op) -> None: +async def test_a_source_whose_namespaces_did_not_parse_is_refused( + _cfg, monkeypatch, op, caplog +) -> None: """A damaged `namespaces_json` reads as no namespace; "every namespace" of none admits nobody, so each op refuses rather than reading `all([])` as admin.""" from server.auth import fail_closed @@ -1252,10 +1254,14 @@ async def test_a_source_whose_namespaces_did_not_parse_is_refused(_cfg, monkeypa TrackerSourceInspectInput(org=ORG, name="clickstack") ), } - with pytest.raises(AuthInsufficientError): - await calls[op]() + with caplog.at_level("WARNING", logger="loom.tracker.registry_sources"): + with pytest.raises(AuthInsufficientError): + await calls[op]() found = rs.find(ORG, "clickstack") assert found is not None and found.namespaces == {} # still registered, no namespace + # the operator is told which source, and not what the stored map held + assert f"tracker source {ORG}/clickstack: stored namespace map did not parse" in caplog.text + assert "not json" not in caplog.text assert fail_closed.answered_unverified() is False # the caller's refusal, not the server's From 9d5be55154c4e908ed505fead906291cad8f414e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 06:57:33 +0530 Subject: [PATCH 29/47] degraded: note a refused pick, take back dropped passes' notes, one keep gate - A pick the gateway refuses or defers for the caller (403, 429) keeps the ranking and now notes `llm: pick_skipped`, through `partial`, since provider health does not count the refusal. The scan reads refusal handlers too (`::refused::`); the pick's narrow handler was outside it. - A pass dropped for good takes its notes back: the marked eager wide pass the passages leave out (a search lists its served render's notes again whenever it is read, so a later fallback that serves it names them), a context.pack knowledge or memory-stack section dropped for a failed read (`CheckedPassages.discard()`, and the stack's build notes held as one group), both searches of a failed loom_search knowledge section, and a repository-docs leg that answered before its base search failed. - `scoped()` yields its own list, and memory.ask's mirrored attempt restores that list, so an `unkeepable` mark set in it reaches the caller's unit; restoring `current()` dropped it. - A failed definition lookup counts `definition_leg_failed`, which `failure_reason` reads, so the search is partial and a decision's code discovery defers. - Every keep gate reads `keepable()`, in place of `not current()`. - The docs put the additive leg's render notes out of scope with timing. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/code-index-architecture.md | 16 ++-- docs/architecture/document-sources.md | 8 +- docs/reference/http-api.md | 8 +- server/code/app/context.py | 10 +-- server/code/app/index/pr_overlay.py | 4 +- server/code/app/index/review_brief_build.py | 4 +- server/code/app/index_status.py | 4 +- server/code/app/search/definitions.py | 11 ++- server/code/app/search/rerank.py | 2 + server/code/app/search/state.py | 4 +- server/knowledge/app/knowledge_search.py | 17 ++++- server/knowledge/app/repo_docs.py | 19 ++++- server/knowledge/app/source_passages.py | 10 ++- server/memory/app/ask/pipeline.py | 10 +-- server/memory/app/context_pack.py | 4 + server/memory/app/facts.py | 2 +- server/memory/app/loom_search/fanout.py | 75 ++++++++++--------- server/memory/app/stack.py | 54 ++++++++----- server/observability/degradations.py | 14 ++-- server/tracker/app/dupcheck.py | 4 +- tests/unit/test_code_search_definition_leg.py | 9 ++- tests/unit/test_code_search_pick.py | 6 +- tests/unit/test_decision_code_discovery.py | 32 ++++++++ tests/unit/test_degraded_unnoted.py | 39 ++++++---- tests/unit/test_source_ask_generation.py | 16 ++++ tests/unit/test_source_checked_pack.py | 56 ++++++++++++++ tests/unit/test_source_fanout_renewal.py | 20 ++++- tests/unit/test_source_repo_search.py | 28 +++++++ tests/unit/test_source_search_result.py | 73 ++++++++++++++++++ 29 files changed, 430 insertions(+), 129 deletions(-) diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index f4530bfc6c0..c9a6e532070 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -611,14 +611,14 @@ in `pkg/json/__init__.py`; its stored qualified name remains intact. Constructor names remain explicit, and ambiguous matches stay unlinked unless the memory's file scope selects one definition. -| Op | Path | How | -| -------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, the definitions the query names (`definitions.py`: the functions of the innermost two frames inside the repository of a pasted Python traceback, read by file and name and each served as the chunk that holds the frame's source line, then the names the rest of the text spells out as code, each one written with its owner and after them the first other name, three definitions in all; for a name the text only calls without a receiver inside a fenced block marked as Python, outside its comments, its string literals and its lines that lead with a dotted name or a path and a colon (the form of a pasted exception or warning line), a method or a nested definition of a Python file is left out, and a definition in another language is read as for any other name; a traceback whose frames name nothing in the index adds no name of its own; in the places those leave, the functions outside test and vendored paths that hold a literal the text marks as code and no identifier rule reads, a token with a hyphen inside written between backticks or quotes or the name of a long option with underscores, found as a whole token by one read through the n-gram index that the leg waits half a second for, and under a request budget no more than half the leg window, a literal that more than three functions hold or whose read runs longer being dropped, the cut counted as `retrieval_work.literal_read_cut` and kept out of every cache (the `code.search` memo, a `code.ask` answer, a `memory.ask` precedent); the text is the request's `report` when it sends one, the whole of a report it searches with the opening of), fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `rank.py` applies the priors and then serves the named definitions directly after the first unit, at its score; `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. | -| `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. | -| `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. | -| `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. | -| `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. | -| `code.trace` | `code/app/symbol/trace.py` | Reads the frames of the text: qualified `a::b` names, C/C++ `dir/file.cpp:N` locations, and Python frames in the interpreter, notebook and test-runner forms, which `frames` returns as `path:line in function`. A name resolves through the symbol table and a location to the innermost symbol that holds its line. A Python frame resolves to the definition of its function in the file under the longest tail of its printed path, as written or under `src/` or `lib/`; its line chooses only among several definitions of the name. Over `max_frames` a native backtrace keeps its first frames and a Python traceback its last. | +| Op | Path | How | +| -------------------------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `code.search` | `code/app/search/pipeline.py` | Routes first (pattern, path, history question), then runs legs under the deadline (`gather.py`): lexical (idf-weighted token count), vector (a scan with no vector index, or twin shortlist), PR history, the definitions the query names (`definitions.py`: the functions of the innermost two frames inside the repository of a pasted Python traceback, read by file and name and each served as the chunk that holds the frame's source line, then the names the rest of the text spells out as code, each one written with its owner and after them the first other name, three definitions in all; for a name the text only calls without a receiver inside a fenced block marked as Python, outside its comments, its string literals and its lines that lead with a dotted name or a path and a colon (the form of a pasted exception or warning line), a method or a nested definition of a Python file is left out, and a definition in another language is read as for any other name; a traceback whose frames name nothing in the index adds no name of its own; in the places those leave, the functions outside test and vendored paths that hold a literal the text marks as code and no identifier rule reads, a token with a hyphen inside written between backticks or quotes or the name of a long option with underscores, found as a whole token by one read through the n-gram index that the leg waits half a second for, and under a request budget no more than half the leg window, a literal that more than three functions hold or whose read runs longer being dropped, the cut counted as `retrieval_work.literal_read_cut` and kept out of every cache (the `code.search` memo, a `code.ask` answer, a `memory.ask` precedent); a frame, name or literal lookup that fails counted as `retrieval_work.definition_leg_failed`, which makes the answer partial (`partial_reason: retrieval unavailable: definition`); the text is the request's `report` when it sends one, the whole of a report it searches with the opening of), fuzzy symbol vote. `fusion.py` fuses by reciprocal rank (k = 60); `rank.py` applies the priors and then serves the named definitions directly after the first unit, at its score; `serve.py` pages into the token budget or abstains. A repeat within the memo window is one read of `code_search_memo`. | +| `code.grep` | `code/store/index/grep.py` | The 3-gram index narrows granules; `position()` or `match()` decides; each hit joins its enclosing unit. `mode=presence` spans up to eight branch namespaces. | +| `code.symbol` | `code/app/symbol/` | A qualified name is a key-prefix read of `code_symbols`; a short name goes through `code_symbol_names`; several definitions rank by `near_paths` or the PR under review. | +| `code.callers`, `code.impact` | `code/store/index/edges.py` | Callers are the `to_symbol_id` range of `code_edges`, compiler rows preferred, with the unresolved count. `code.impact` maps diff hunks to seed symbols and walks outward; an empty walk answers `no_indexed_paths`, `no_seeds_in_hunks` or `no_static_callers`. | +| `code.outline`, `code.enclosing` | — | Per-path reads of `code_symbols` and `code_chunks` spans. | +| `code.trace` | `code/app/symbol/trace.py` | Reads the frames of the text: qualified `a::b` names, C/C++ `dir/file.cpp:N` locations, and Python frames in the interpreter, notebook and test-runner forms, which `frames` returns as `path:line in function`. A name resolves through the symbol table and a location to the innermost symbol that holds its line. A Python frame resolves to the definition of its function in the file under the longest tail of its printed path, as written or under `src/` or `lib/`; its line chooses only among several definitions of the name. Over `max_frames` a native backtrace keeps its first frames and a Python traceback its last. | The lexical text-index gate tokenizes the query with `splitByNonAlpha`, matching the index tokenizer. The score counts only whole app lexemes and rejects partial matches diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 17e83bd3cce..1095e148b2f 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -1103,9 +1103,11 @@ against a live Workspace. `LOOM_KNOWLEDGE_SOURCE_PROBE_TIMEOUT_S` can be raised | A stolen connected credential changes the store | Only read scopes are accepted; the credential is sealed and never returned. | the connect callback; `server/core/secrets_at_rest.py` | Out of scope: response timing, and when a pass reaches the namespace sources, which the -mirrored sources' turns before them delay; a resource limit (memory, rows read) that a -mirror's size can trip on a per-request statement, which like timing depends on how much -the mirror holds; how fast the shared pass gets to a connected owner's own source, which +mirrored sources' turns before them delay; under a plan that reads mirrors, whether +`degraded` lists the repository-docs leg's own render notes, which follows whether the +leg answered within its bound and so, like timing, can depend on documents the caller may +not see; a resource limit (memory, rows read) that a mirror's size can trip on a +per-request statement, which like timing depends on how much the mirror holds; how fast the shared pass gets to a connected owner's own source, which its fresh or stale code and per-item status reflect; that a namespace erasure is still retrying, which a namespace admin sees whatever its cause; a worker an orchestrating agent starts outside a flagged session's process tree; a person who hands their own diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 5427d3c8390..06b8f70ad2d 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -335,9 +335,11 @@ error's kind only; the full text is in the server log. - An answer replaced before it is served does not list what it recorded: a document search that lost access to a mirrored document mid-request and answers from its ordinary pass, and the `memory.ask` attempt discarded for the same reason, list only - the served answer's entries. So does a search pass the answer leaves out: a wider pass - it did not need, a repository-docs leg dropped past its deadline, or an ordinary render - that failed, whose failure the caller names. + the served answer's entries. So does a search pass or section the answer leaves out: a + wider pass it did not need, a repository-docs leg dropped past its deadline or with the + base search that failed, an ordinary render that failed, and a `context.pack` knowledge + or memory-stack section or a `loom_search` knowledge section dropped for a failed read, + whose failure the caller names. - Some caches keep a fallback with its entries and name them on each answer served from it, for: - `LOOM_CODE_STATUS_TTL_S`: a `code.index_status` or `code.repos` status; diff --git a/server/code/app/context.py b/server/code/app/context.py index 924f444148a..7b8a18a078c 100644 --- a/server/code/app/context.py +++ b/server/code/app/context.py @@ -269,17 +269,17 @@ async def _render_map( if cached is not None: return cached # Each attempt's notes are its own: only the served attempt's reach the response. - with degradations.scoped(): + with degradations.scoped() as noted: text = await _build_map_text(repo, org, ns, module_prefix, token_budget) - noted = degradations.current() + kept = degradations.keepable() # Detect a completed index advance, not a snapshot of its progressive writes. if await repo.get_state(org, ns, "git_head") != head: continue artifact = _MapArtifact(text=text, commit_sha=head) - if noted: # a map a read left smaller is served, not kept - degradations.restore(noted) - else: + if kept: _MAP_CACHE.put(key, artifact) + else: # a map a read left smaller is served, not kept + degradations.restore(noted) return artifact raise OverloadedError("Repository index changed while rendering the map; retry shortly.") diff --git a/server/code/app/index/pr_overlay.py b/server/code/app/index/pr_overlay.py index d0c59053fb0..94b1f9cd197 100644 --- a/server/code/app/index/pr_overlay.py +++ b/server/code/app/index/pr_overlay.py @@ -483,7 +483,7 @@ async def from_mirror(path: str) -> bytes | None: table_at=_table_at(index_head, generation), ) # the next request finishes a partial one, or one a failed read left smaller - if key and not ov.unreached and not degradations.current(): + if key and not ov.unreached and degradations.keepable(): _CACHE.put(key, ov) return ov @@ -548,7 +548,7 @@ async def from_request(path: str) -> bytes | None: path_prefixes=path_prefixes, table_at=_table_at(index_head, generation), ) - if key and not ov.unreached and not degradations.current(): + if key and not ov.unreached and degradations.keepable(): _CACHE.put(key, ov) return ov diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 395cd42b975..ca91dd4e9b6 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -696,7 +696,7 @@ async def build_for_merge( if store and changed_paths and not diff: logger.info("review_brief: PR %s served unstored, its diff was not read", pr_number) payload["stored"] = False - elif store and (degradations.current() or (provenance or {}).get("tracker") == FAILED): + elif store and (not degradations.keepable() or (provenance or {}).get("tracker") == FAILED): # A read it ran, or the caller's tracker read, fell back: the stored copy would # be served later without its `degraded`. logger.info("review_brief: PR %s served unstored, a read fell back", pr_number) @@ -803,7 +803,7 @@ async def build_for_open( "review_brief: open PR %s served unstored, its overlay is partial", pr_number ) payload["stored"] = False - elif store and degradations.current(): + elif store and not degradations.keepable(): logger.info("review_brief: open PR %s served unstored, a read fell back", pr_number) payload["stored"] = False elif store: diff --git a/server/code/app/index_status.py b/server/code/app/index_status.py index d149a8f3e02..6efb4d3861d 100644 --- a/server/code/app/index_status.py +++ b/server/code/app/index_status.py @@ -180,9 +180,9 @@ async def _compute_repo_status( # a caller without a prefetched state (code.index_status, tests' fakes) # keeps the one-argument call st = await (_repo_status(cfg, state=state) if state is not None else _repo_status(cfg)) - noted = degradations.current() + noted, kept = degradations.current(), degradations.keepable() _status_cache[key] = (time.monotonic(), st, noted) - if not noted: # another process's listing would serve the row without them + if kept: # another process's listing would serve the row without its notes create_deferred_task(_publish_status_snapshot(cfg, st)) return st diff --git a/server/code/app/search/definitions.py b/server/code/app/search/definitions.py index f0e32ce4933..8bdf8f16fa0 100644 --- a/server/code/app/search/definitions.py +++ b/server/code/app/search/definitions.py @@ -403,12 +403,16 @@ def _literal_seconds(leg_ms: int | None) -> float: return min(_LITERAL_SECONDS, leg_ms * _LITERAL_WINDOW_SHARE / 1000.0) -async def _or_nothing(lookup: str, read: Awaitable[list[dict[str, Any]]]) -> list[dict[str, Any]]: +async def _or_nothing( + lookup: str, read: Awaitable[list[dict[str, Any]]], work: dict[str, int] +) -> list[dict[str, Any]]: """The rows of one of the leg's lookups, none when it fails: each adds to an - answer and none gates another.""" + answer and none gates another. A failure counts `definition_leg_failed`, which + makes the answer partial, as a failed content leg does.""" try: return await read except Exception as e: # noqa: BLE001 — the definitions add to an answer, never gate it + work["definition_leg_failed"] = 1 degradations.partial("code_index", "definition_leg_dropped", e) logger.warning("code.search definition leg failed (%s lookup): %s", lookup, e) return [] @@ -461,6 +465,7 @@ async def _definition_leg( path_prefix=path_prefix, scope=scope, ), + work, ), _or_nothing( "name", @@ -475,6 +480,7 @@ async def _definition_leg( path_prefix=path_prefix, scope=scope, ), + work, ), _or_nothing( "literal", @@ -489,6 +495,7 @@ async def _definition_leg( path_prefix=path_prefix, scope=scope, ), + work, ), ) rows: list[dict[str, Any]] = [] diff --git a/server/code/app/search/rerank.py b/server/code/app/search/rerank.py index 858bdc64151..94f04f7f086 100644 --- a/server/code/app/search/rerank.py +++ b/server/code/app/search/rerank.py @@ -321,6 +321,8 @@ async def _pick_units( except ModelCallRefused as e: # The gateway's answer for the caller at the pick's model, which it logged and no # one retries: it refused no other call of the search, so the search goes on. + # `partial`: provider health does not count a refusal for the caller. + degradations.partial("llm", "pick_skipped", e) logger.warning("code.search pick refused (%s); ranking kept", e) return units, 0, "" except customer.HOLDS: diff --git a/server/code/app/search/state.py b/server/code/app/search/state.py index 9d7e9366bd4..2fec2810028 100644 --- a/server/code/app/search/state.py +++ b/server/code/app/search/state.py @@ -63,7 +63,9 @@ class CodeSearchResult: @property def failure_reason(self) -> str: unavailable = [ - name for name in ("lexical", "vector") if self.retrieval_work.get(f"{name}_leg_failed") + name + for name in ("lexical", "vector", "definition") + if self.retrieval_work.get(f"{name}_leg_failed") ] return "retrieval unavailable: " + ", ".join(unavailable) if unavailable else "" diff --git a/server/knowledge/app/knowledge_search.py b/server/knowledge/app/knowledge_search.py index 56d7c78339e..97fcda8ad9d 100644 --- a/server/knowledge/app/knowledge_search.py +++ b/server/knowledge/app/knowledge_search.py @@ -122,11 +122,15 @@ class CheckedSearch: ordinary_rerank_possible: bool = False # The served render's notes; the ordinary fallback swaps in its own. held: degradations.Held = dataclasses.field(default_factory=lambda: degradations.hold([])) + _noted: list[str] = dataclasses.field(init=False) _failed: bool = dataclasses.field(default=False, init=False) _checking: asyncio.Lock = dataclasses.field( default_factory=asyncio.Lock, init=False, repr=False ) + def __post_init__(self) -> None: + self._noted = list(self.held.entries) + @property def marked(self) -> bool: return self._renderer.marked @@ -147,18 +151,23 @@ async def _fallback(self) -> KnowledgeSearchOutput: source_publication.discard(self.proofs) self.proofs, self.lost = None, True try: - self.output, noted = await _attempt( + self.output, self._noted = await _attempt( self._renderer.render(self._ordinary, self._ordinary_dropped) ) except BaseException: self._failed = True self.discard() # nothing of it is served; the caller names the failure raise - self.held.swap(noted) # the discarded render's notes go with it + return self._served() + + def _served(self) -> KnowledgeSearchOutput: + # the served render's notes, in place of a discarded render's + self.held.swap(self._noted) return self.output def discard(self) -> None: - """Take the served render's notes back: the caller serves nothing of this search.""" + """Take the served render's notes back: the caller serves nothing of this search + until it reads it again.""" self.held.swap([]) async def ordinary(self) -> KnowledgeSearchOutput: @@ -177,7 +186,7 @@ async def current(self) -> KnowledgeSearchOutput: await self.proofs.check() except LostCorpus: return await self._fallback() - return self.output + return self._served() @dataclasses.dataclass(frozen=True) diff --git a/server/knowledge/app/repo_docs.py b/server/knowledge/app/repo_docs.py index 3ebd4dba921..5cfe6afeaf8 100644 --- a/server/knowledge/app/repo_docs.py +++ b/server/knowledge/app/repo_docs.py @@ -254,10 +254,23 @@ async def run_repo_search(request: RepoSearchRequest, plan: ReadPlan) -> RepoSea if any(child.input.org != plan.org for child in (request.base, request.extra) if child): raise ValueError("document read scope changed") + finished: list[CheckedSearch] = [] + + async def extra_leg() -> CheckedSearch | None: + leg = await search_repo_docs(request, plan) + if leg is not None: + finished.append(leg) + return leg + with private_work() if plan.marked else nullcontext(): - base, extra = await gather_or_cancel( - run_checked_search(request.base, plan), search_repo_docs(request, plan) - ) + try: + base, extra = await gather_or_cancel( + run_checked_search(request.base, plan), extra_leg() + ) + except BaseException: + for leg in finished: + leg.discard() # nothing of this search is served; the caller names the failure + raise assert base is not None return RepoSearch(request, base, extra) diff --git a/server/knowledge/app/source_passages.py b/server/knowledge/app/source_passages.py index 25507482a10..b5a251b1042 100644 --- a/server/knowledge/app/source_passages.py +++ b/server/knowledge/app/source_passages.py @@ -78,8 +78,16 @@ async def saved(_width: int) -> list[_SearchHit]: first, saved, lambda hit: hit.tags, self._agent, self._top_k, keep=self._keep ) self._used_wide = used_wide + if self._wide is not None and not used_wide: + self._wide.discard() # the answer leaves it out; a later selection may read it again return result + def discard(self) -> None: + """Take both passes' notes back: the caller serves nothing of these passages.""" + for child in (self._first, self._wide): + if child is not None: + child.discard() + async def _fallback(self) -> list[_SearchHit]: if self._failed: raise LostCorpus() @@ -95,8 +103,6 @@ async def _fallback(self) -> list[_SearchHit]: except Exception: # noqa: BLE001 — the first complete ordinary pass still answers self._wide = None # its failed render took its notes back self.hits = await self._select(first, wide) - if self._wide is not None and not self._used_wide: - self._wide.discard() # the ordinary answer is final and serves the first alone self._ordinary_ready = True except BaseException: self._failed = True diff --git a/server/memory/app/ask/pipeline.py b/server/memory/app/ask/pipeline.py index f4fd3ef3f25..f0f5ea14aa6 100644 --- a/server/memory/app/ask/pipeline.py +++ b/server/memory/app/ask/pipeline.py @@ -371,13 +371,9 @@ async def _answer_with_knowledge( if knowledge.mirrored: # The mirrored attempt's notes are named unless a lost document discards it: then # the ordinary attempt's are the answer's. - noted: list[str] = [] try: - with degradations.scoped(): - try: - result = await owned_attempt(generate(block, hits, knowledge)) - finally: - noted = degradations.current() + with degradations.scoped() as noted: + result = await owned_attempt(generate(block, hits, knowledge)) if not knowledge.fresh(): raise LostCorpus() except LostCorpus: @@ -386,7 +382,7 @@ async def _answer_with_knowledge( degradations.restore(noted) raise else: - degradations.restore(noted) + degradations.restore(noted) # with its held groups and `unkeepable` mark from server.knowledge.app import source_publication if knowledge.passages is not None: diff --git a/server/memory/app/context_pack.py b/server/memory/app/context_pack.py index 7186deded64..ad030f125ab 100644 --- a/server/memory/app/context_pack.py +++ b/server/memory/app/context_pack.py @@ -1299,12 +1299,14 @@ async def _fallback(self) -> ContextPackOutput: direct = await self._direct.ordinary() except Exception as exc: # noqa: BLE001 — a failed ordinary section is omitted without retry degradations.partial("context.pack", "knowledge_dropped", exc) + self._direct.discard() self._direct = None if self._stack is not None: try: stack = await self._stack.ordinary() except Exception as exc: # noqa: BLE001 — a failed ordinary section is omitted without retry degradations.partial("context.pack", "memory_stack_dropped", exc) + self._stack.discard() self._stack = None self._output = _render_checked_pack(self._prefix, stack, direct) self._ordinary_ready = True @@ -1334,12 +1336,14 @@ async def current(self) -> ContextPackOutput: direct = await self._direct.current() except Exception as exc: # noqa: BLE001 — a failed optional section cannot expose a partial mixed pack degradations.partial("context.pack", "knowledge_dropped", exc) + self._direct.discard() self._direct, failed = None, True if self._stack is not None: try: stack = await self._stack.current() except Exception as exc: # noqa: BLE001 — a failed optional section cannot expose a partial mixed pack degradations.partial("context.pack", "memory_stack_dropped", exc) + self._stack.discard() self._stack, failed = None, True if failed or not self.fresh(): return await self._fallback() diff --git a/server/memory/app/facts.py b/server/memory/app/facts.py index 1fa292b8cc3..de9315909a1 100644 --- a/server/memory/app/facts.py +++ b/server/memory/app/facts.py @@ -386,7 +386,7 @@ async def walk(self, input: FactsTraverseInput) -> FactsTraverseOutput: out = await _handle_facts_traverse_uncached(input) else: out = await _handle_facts_traverse_uncached(input) - whole = not degradations.current() # a walk a read left smaller is not kept + whole = degradations.keepable() # a walk a read left smaller is not kept if settling or not whole: return out if len(self.cache) > 512: diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index ab5c7bfb850..b826e2a66cc 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -279,41 +279,48 @@ async def expanded(k: int) -> KnowledgeSearchOutput: raise return wider.output - if not plan.marked: - return await _filtered_knowledge(first.output, expanded, agent, top_k) - set_query_tag("knowledge.mirror.fanout") - await first.current() - if not first.fresh(): - return await _ordinary_knowledge(first, None, agent) - initial = await _filtered_knowledge(first.output, expanded, agent, top_k) - if wider is None and widening_error is None: - if first.fresh(): - for proof in first.publication_proofs: - source_publication.retain(proof) - return initial - return await _ordinary_knowledge(first, None, agent) - await first.current() - if not first.fresh(): - return await _ordinary_knowledge(first, wider, agent) - used_wider = False - - async def cached(_k: int) -> KnowledgeSearchOutput: - nonlocal used_wider - used_wider = True - if widening_error is not None: - raise widening_error - assert wider is not None - # Renew only when the renewed first pass still needs the wider result. - await wider.current() - return wider.output + try: + if not plan.marked: + return await _filtered_knowledge(first.output, expanded, agent, top_k) + set_query_tag("knowledge.mirror.fanout") + await first.current() + if not first.fresh(): + return await _ordinary_knowledge(first, None, agent) + initial = await _filtered_knowledge(first.output, expanded, agent, top_k) + if wider is None and widening_error is None: + if first.fresh(): + for proof in first.publication_proofs: + source_publication.retain(proof) + return initial + return await _ordinary_knowledge(first, None, agent) + await first.current() + if not first.fresh(): + return await _ordinary_knowledge(first, wider, agent) + used_wider = False + + async def cached(_k: int) -> KnowledgeSearchOutput: + nonlocal used_wider + used_wider = True + if widening_error is not None: + raise widening_error + assert wider is not None + # Renew only when the renewed first pass still needs the wider result. + await wider.current() + return wider.output - final = await _filtered_knowledge(first.output, cached, agent, top_k) - if not first.fresh() or (used_wider and wider is not None and not wider.fresh()): - return await _ordinary_knowledge(first, wider, agent) - for result in (first, wider) if used_wider and wider is not None else (first,): - for proof in result.publication_proofs: - source_publication.retain(proof) - return final + final = await _filtered_knowledge(first.output, cached, agent, top_k) + if not first.fresh() or (used_wider and wider is not None and not wider.fresh()): + return await _ordinary_knowledge(first, wider, agent) + for result in (first, wider) if used_wider and wider is not None else (first,): + for proof in result.publication_proofs: + source_publication.retain(proof) + return final + except BaseException: + # the section is an error, which the caller names: nothing of either search is served + for search in (first, wider): + if search is not None: + search.discard() + raise async def _published_knowledge( diff --git a/server/memory/app/stack.py b/server/memory/app/stack.py index d65f9f9010a..8a53cda1254 100644 --- a/server/memory/app/stack.py +++ b/server/memory/app/stack.py @@ -304,6 +304,8 @@ class CheckedStack: _prefix: _StackFill _knowledge: StackKnowledge | None marked: bool + # the build's notes, which a caller that drops the stack takes back + held: degradations.Held = field(default_factory=lambda: degradations.hold([])) _knowledge_used: bool = field(default=False, init=False) @property @@ -335,32 +337,44 @@ async def current(self) -> MemoryStackOutput: await self._knowledge.current() return self.output + def discard(self) -> None: + """Take the build's notes back: the caller serves nothing of this stack.""" + self.held.swap([]) + async def run_checked_stack(input: MemoryStackInput, plan: ReadPlan) -> CheckedStack: if input.org != plan.org: raise ValueError("document read scope changed") input = input.model_copy(deep=True) with private_work() if plan.marked else nullcontext(): - ch = get_client() - fill = _StackFill(budget=input.token_budget) - await _stack_profile(input, fill) - await _stack_pinned(ch, input, fill) - most_recent_excerpt = await _stack_recent(ch, input, fill) - seed = (input.seed_query or "").strip() or most_recent_excerpt - if input.seed_query and input.procedure_limit > 0: - await _stack_procedures(input, fill) - knowledge = None - if input.include_knowledge and input.knowledge_top_k > 0 and seed: - from server.memory.app import stack_knowledge - - try: - knowledge = await stack_knowledge.collect( - input.org, input.namespace, input.agent, seed, int(input.knowledge_top_k), plan - ) - except Exception as e: # noqa: BLE001 — a failed knowledge section must not fail the stack - degradations.partial("memory.stack", "knowledge_dropped", e) - log.warning("memory.stack: knowledge fan-out failed (non-fatal): %s", e) - return CheckedStack(fill, knowledge, plan.marked) + # a build that raises serves nothing, and takes its notes with it + with degradations.scoped(): + ch = get_client() + fill = _StackFill(budget=input.token_budget) + await _stack_profile(input, fill) + await _stack_pinned(ch, input, fill) + most_recent_excerpt = await _stack_recent(ch, input, fill) + seed = (input.seed_query or "").strip() or most_recent_excerpt + if input.seed_query and input.procedure_limit > 0: + await _stack_procedures(input, fill) + knowledge = None + if input.include_knowledge and input.knowledge_top_k > 0 and seed: + from server.memory.app import stack_knowledge + + try: + knowledge = await stack_knowledge.collect( + input.org, + input.namespace, + input.agent, + seed, + int(input.knowledge_top_k), + plan, + ) + except Exception as e: # noqa: BLE001 — a failed knowledge section must not fail the stack + degradations.partial("memory.stack", "knowledge_dropped", e) + log.warning("memory.stack: knowledge fan-out failed (non-fatal): %s", e) + noted = degradations.current() + return CheckedStack(fill, knowledge, plan.marked, degradations.hold(noted)) async def handle_memory_stack(input: MemoryStackInput) -> MemoryStackOutput: diff --git a/server/observability/degradations.py b/server/observability/degradations.py index c1c25a3fb47..885211d2f77 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -22,8 +22,8 @@ An answer kept for a later call (a memo, a stored brief) is built inside `unit()`, and kept only when the unit's own notes are empty and nothing in it called `unkeepable()` (`keepable`): an earlier note of the request is not the answer's. An answer a later step -may still replace lists its notes through `hold()`, -and the replacement swaps them, so a discarded answer's notes go with it. +may still replace lists its notes through `hold()`, and the replacement swaps them, so a +discarded answer's notes go with it. degraded: ["classify: caller_type_kept (HTTPStatusError)", "rerank: input_order_kept (ReadTimeout)"] @@ -107,13 +107,15 @@ def begin() -> None: @contextmanager -def scoped() -> Iterator[None]: +def scoped() -> Iterator[list[str | Held | _Unkept]]: """A fresh note list inside the block, and the caller's back after it: a unit of a worker's pass (one review brief) reads only its own notes, and a request that runs - the pass inline keeps its own.""" - token = _notes.set([]) + the pass inline keeps its own. It yields the block's own list, which `restore` lists + in the caller's with its held groups and `unkeepable` mark.""" + own: list[str | Held | _Unkept] = [] + token = _notes.set(own) try: - yield + yield own finally: _notes.reset(token) diff --git a/server/tracker/app/dupcheck.py b/server/tracker/app/dupcheck.py index 4936173b37e..e2dd0d70972 100644 --- a/server/tracker/app/dupcheck.py +++ b/server/tracker/app/dupcheck.py @@ -107,7 +107,7 @@ async def prepare_duplicate_check(input: TrackerDuplicateCheckInput) -> Duplicat ) # A target a gate could not verify, or an unread binding, is noted: the answer # may lack a tracker, so it is not remembered. - cache = registry_read and not degradations.current() + cache = registry_read and degradations.keepable() return DuplicateCheckPlan(input, tuple(targets), code_ns, explicit, cache) @@ -223,7 +223,7 @@ async def _with_links( final = out.model_copy( update={k: d.get(k) for k in ("items", "closest", "nearest", "related_prs", "answer")}, ) - if wall is None and code_ns and cache and not degradations.current(): + if wall is None and code_ns and cache and degradations.keepable(): remember_answer(org, code_ns, title, final) # a degraded answer is not replayed return final diff --git a/tests/unit/test_code_search_definition_leg.py b/tests/unit/test_code_search_definition_leg.py index 57b53b7de9f..de3f5bb449e 100644 --- a/tests/unit/test_code_search_definition_leg.py +++ b/tests/unit/test_code_search_definition_leg.py @@ -1079,12 +1079,13 @@ def test_frames_and_the_spelled_name_share_the_places_after_the_first_unit() -> def test_one_lookup_failing_leaves_the_other_served() -> None: + # and counts the failure, which makes the answer partial assert _framed_leg(_Framed(fail="name")) == ( ["pkg.query::Query::_merge", "pkg.query::Query::combine"], - {"frame_definitions": 2}, + {"frame_definitions": 2, "definition_leg_failed": 1}, ) served, work = _framed_leg(_Framed(fail="frame")) - assert work == {"named_definitions": 3} + assert work == {"named_definitions": 3, "definition_leg_failed": 1} assert sorted(served) == [ "pkg.query::Query::combine", "pkg.query::RawQuery::combine", @@ -1499,11 +1500,11 @@ async def literal_function_chunks(self, *a: Any, **k: Any): # each lookup adds to the answer and neither gates the other assert _framed_leg(_NoNames(emits, *named), report) == ( # type: ignore[arg-type] ["pkg.base::Checker::visit_lambda", "pkg.lint::report"], - {"literal_definitions": 2}, + {"literal_definitions": 2, "definition_leg_failed": 1}, ) assert _framed_leg(_NoLiterals(emits, *named), report) == ( # type: ignore[arg-type] ["pkg.a::Query::combine", "pkg.b::Raw::combine"], - {"named_definitions": 2}, + {"named_definitions": 2, "definition_leg_failed": 1}, ) diff --git a/tests/unit/test_code_search_pick.py b/tests/unit/test_code_search_pick.py index 5fd2df3fecd..f16a4532bd3 100644 --- a/tests/unit/test_code_search_pick.py +++ b/tests/unit/test_code_search_pick.py @@ -21,7 +21,7 @@ from server.code.app import search as cs from server.code.app.search import rerank as cs_rerank from server.code.domain.units import CodeUnit -from server.core.errors import ModelCallDeferred, ModelCallRefused +from server.core.errors import ModelCallDeferred, ModelCallRefused, caller_text from server.llm import customer from server.llm.client import LLMResult from server.llm.fake import FakeLLMClient @@ -491,12 +491,16 @@ async def complete(self, system: str, user: str, **kw: Any) -> LLMResult: def test_a_pick_the_gateway_refuses_for_the_caller_keeps_the_ranking_and_says_so( monkeypatch: pytest.MonkeyPatch, answer: Exception ) -> None: + from server.observability import degradations + plain, _ = _handle(monkeypatch, _picks(2, 1)) model = _Held(answer) + degradations.begin() held, puts = _handle(monkeypatch, model, rerank="builtin:pick") # the gateway was asked once, and its answer is not the search's assert len(model.calls) == 1 assert held["results"] == plain["results"] and "pick_confidence" not in held + assert degradations.current() == [f"llm: pick_skipped ({caller_text(answer)})"] # a caller that asked for the pick reads that none was made, and the gateway may # take the caller back: the answer is not kept for the memo's lifetime assert held["retrieval_work"]["pick_failed"] == 1 and puts == [] diff --git a/tests/unit/test_decision_code_discovery.py b/tests/unit/test_decision_code_discovery.py index 1d2c277edd8..635235a865d 100644 --- a/tests/unit/test_decision_code_discovery.py +++ b/tests/unit/test_decision_code_discovery.py @@ -222,6 +222,38 @@ async def test_incomplete_retrieval_is_deferred_not_empty_success(monkeypatch, i assert discovery.status == "deferred" and discovery.candidates == [] +@pytest.mark.parametrize("lookup", ["frame", "name", "literal"]) +@pytest.mark.asyncio +async def test_a_failed_definition_lookup_defers_discovery(monkeypatch, index, lookup): + """The search answered without that lookup's definitions: a later pass may read the + code it missed.""" + from server.code.app.search import definitions + + async def answers(*_a, **_k): + return [] + + async def fails(*_a, **_k): + raise RuntimeError("read failed") + + for leg in ("frame", "name", "literal"): + monkeypatch.setattr(definitions, f"_{leg}_leg", fails if leg == lookup else answers) + await definitions._definition_leg( + None, # type: ignore[arg-type] + "o", + "ns", + "m", + query="`retry_delay()` waits", + run=True, + work=index.result.retrieval_work, + path_prefix="", + scope=None, + ) + assert index.result.partial_reason == "retrieval unavailable: definition" + report, _ = await preview(monkeypatch) + discovery = report.records[0].code_discovery + assert discovery.status == "deferred" and discovery.candidates == [] + + @pytest.mark.asyncio async def test_a_moving_code_head_discards_the_grounded_candidates(monkeypatch, index): async def moving_chunks(self, org, namespace, model, keys): diff --git a/tests/unit/test_degraded_unnoted.py b/tests/unit/test_degraded_unnoted.py index 50d6ed2411d..a0820515b79 100644 --- a/tests/unit/test_degraded_unnoted.py +++ b/tests/unit/test_degraded_unnoted.py @@ -1,12 +1,13 @@ -"""Every broad `except`, and every `except TimeoutError` that does not raise, in the -code, memory, knowledge and tracker apps and the LLM clients either names its fallback -in `degraded` or is listed, with why it need not, in `degraded_unnoted.txt`; and every -fallback that feeds provider health names a provider whose success clears it. +"""Every broad `except`, and every `except TimeoutError` or gateway refusal +(`ModelCallRefused`) that does not raise, in the code, memory, knowledge and tracker +apps and the LLM clients either names its fallback in `degraded` or is listed, with why +it need not, in `degraded_unnoted.txt`; and every fallback that feeds provider health +names a provider whose success clears it. The scan reads each handler and gather branch on its own, so it does not see a result tested in another function, `asyncio.wait`, an `isinstance` filter that keeps the -successes, an exception test inside a `BoolOp`, a handler of a narrower exception than a -timeout, or which call of a noting helper runs.""" +successes, an exception test inside a `BoolOp`, a handler of another narrow exception, or +which call of a noting helper runs.""" from __future__ import annotations @@ -80,14 +81,19 @@ def _broad(h: ast.ExceptHandler) -> bool: return any(isinstance(n, ast.Name) and n.id in _EXCEPTION_TYPES for n in names) -def _timeout(h: ast.ExceptHandler) -> bool: - """`except TimeoutError` or `except asyncio.TimeoutError`, alone or in a tuple.""" +def _narrow(h: ast.ExceptHandler) -> str | None: + """`timeout` for `except TimeoutError` or `asyncio.TimeoutError`, `refused` for a + gateway's refusal for the caller (`ModelCallRefused`, or its `ModelCallDeferred`), + alone or in a tuple; None for any other handler.""" names = h.type.elts if isinstance(h.type, ast.Tuple) else [h.type] - return any( - (isinstance(n, ast.Name) and n.id == "TimeoutError") - or (isinstance(n, ast.Attribute) and n.attr == "TimeoutError") + kinds = { + n.id if isinstance(n, ast.Name) else n.attr for n in names - ) + if isinstance(n, ast.Name | ast.Attribute) + } + if "TimeoutError" in kinds: + return "timeout" + return "refused" if kinds & {"ModelCallRefused", "ModelCallDeferred"} else None def _is_degradations(node: ast.expr) -> bool: @@ -241,7 +247,8 @@ def _unnoted() -> list[str]: """`path::enclosing.qualname::ordinal` of each broad handler that notes nothing, the ordinal counting the broad handlers of that function in source order; `path::enclosing.qualname::timeout::ordinal` of each timeout handler that notes - nothing, counted the same way among that function's timeout handlers; and + nothing, counted the same way among that function's timeout handlers (`refused` for + a gateway refusal's); and `path::enclosing.qualname::gather::ordinal` of each exception branch over a `return_exceptions=True` result that notes nothing, counted the same way.""" out: list[str] = [] @@ -272,8 +279,10 @@ def visit( counts[q] = counts.get(q, 0) + 1 if not _notes(child, helpers): out.append(f"{rel}::{q}::{counts[q]}") - elif isinstance(child, ast.ExceptHandler) and child.type and _timeout(child): - q = f"{qual or ''}::timeout" + elif ( + isinstance(child, ast.ExceptHandler) and child.type and (kind := _narrow(child)) + ): + q = f"{qual or ''}::{kind}" counts[q] = counts.get(q, 0) + 1 if not _notes(child, helpers): out.append(f"{rel}::{q}::{counts[q]}") diff --git a/tests/unit/test_source_ask_generation.py b/tests/unit/test_source_ask_generation.py index 08012690c7c..ef4f6dd394c 100644 --- a/tests/unit/test_source_ask_generation.py +++ b/tests/unit/test_source_ask_generation.py @@ -413,6 +413,22 @@ async def generate(block, _hits, checked): assert degradations.current() == ["memory.search: earlier_note", *attempt] +async def test_a_served_mirrored_attempt_keeps_the_answer_out_of_the_callers_caches(): + """The attempt's code grounding cut a literal read, which names nothing: the mark + reaches the unit `memory.ask` builds its answer in, so no precedent keeps it.""" + from server.observability import degradations + + async def generate(block, _hits, _checked): + degradations.unkeepable() + return block + + degradations.begin() + with degradations.unit(): + got = await pipeline._answer_with_knowledge(generate, _Knowledge(False), marked=True) + assert got == "private block" and degradations.current() == [] + assert not degradations.keepable() + + async def test_a_mirrored_attempt_that_fails_keeps_its_notes(): from server.observability import degradations diff --git a/tests/unit/test_source_checked_pack.py b/tests/unit/test_source_checked_pack.py index 5b11af35da1..364defa4dd0 100644 --- a/tests/unit/test_source_checked_pack.py +++ b/tests/unit/test_source_checked_pack.py @@ -333,3 +333,59 @@ async def send(message): with pytest.raises(request_tail.RequiredTailError): await request_tail.RequestTailMiddleware(app)({"type": "http"}, None, send) assert sent == [] and world.state.renders == [] + + +@pytest.mark.parametrize("read", ["current", "ordinary"]) +@pytest.mark.parametrize("pool", ["direct", "stack"]) +async def test_a_pool_the_pack_drops_takes_its_notes_with_it(pool, read): + from server.observability import degradations + + degradations.begin() + input = ContextPackInput( + org="acme", + namespace="docs", + agent="reader", + query="question", + include_knowledge=True, + only_sections=["profile", "knowledge", "memory_stack"], + ) + prefix = context_pack._PackState(input, dict(_DEFAULT_SECTION_TOKENS[input.mode])) + held = degradations.hold([f"{pool}: built_smaller"]) + + async def fails(): + raise RuntimeError("read failed") + + child = SimpleNamespace( + lost=False, fresh=lambda: True, current=fails, ordinary=fails, discard=lambda: held.swap([]) + ) + checked = context_pack.CheckedPack( + prefix, child if pool == "stack" else None, child if pool == "direct" else None, True + ) + await getattr(checked, read)() + # the section is omitted: only its drop is named + effect = "knowledge_dropped" if pool == "direct" else "memory_stack_dropped" + assert degradations.current() == [f"context.pack: {effect} (RuntimeError)"] + + +async def test_a_stack_holds_its_build_notes_for_a_caller_that_drops_it(monkeypatch): + from server.memory.api.models_lifecycle import MemoryStackInput + from server.observability import degradations + + async def profile(input, fill): + degradations.partial("memory.stack", "profile_dropped", "x") + + async def nothing(*_a): + return "" + + monkeypatch.setattr(stack, "get_client", lambda: None) + monkeypatch.setattr(stack, "_stack_profile", profile) + monkeypatch.setattr(stack, "_stack_pinned", nothing) + monkeypatch.setattr(stack, "_stack_recent", nothing) + degradations.begin() + checked = await stack.run_checked_stack( + MemoryStackInput(org="acme", namespace="docs", agent="reader"), + source_access.ReadPlan("acme"), + ) + assert degradations.current() == ["memory.stack: profile_dropped (x)"] + checked.discard() + assert degradations.current() == [] diff --git a/tests/unit/test_source_fanout_renewal.py b/tests/unit/test_source_fanout_renewal.py index fba306b6dff..7b46ddd101c 100644 --- a/tests/unit/test_source_fanout_renewal.py +++ b/tests/unit/test_source_fanout_renewal.py @@ -23,6 +23,7 @@ from server.memory.api.models_search import MemorySearchOutput from server.memory.app.loom_search import fanout from server.memory.domain.assistant_rules import hits_to_ask +from server.observability import degradations def hit(uri, *, other=False): @@ -38,7 +39,9 @@ def hit(uri, *, other=False): ) -def result(name, *, lost=False, fail_render=False, needs_widen=False, ordinary_full=False): +def result( + name, *, lost=False, fail_render=False, needs_widen=False, ordinary_full=False, noted=() +): inp = KnowledgeSearchInput(org="acme", namespace="home", query="cache", top_k=2) request = repo_docs.RepoSearchRequest( SearchRequest(inp, ("home",), ()), None, "", asyncio.get_running_loop().time() + 100 @@ -70,7 +73,7 @@ async def render(*_args): fresh=lambda: not lost, ) renderer = SimpleNamespace(marked=True, render=AsyncMock(side_effect=render)) - checked = CheckedSearch(mixed, proof, renderer, [], 7) + checked = CheckedSearch(mixed, proof, renderer, [], 7, held=degradations.hold(list(noted))) return repo_docs.RepoSearch(request, checked, None), renderer @@ -259,3 +262,16 @@ async def test_a_wider_pass_the_ordinary_section_does_not_serve_takes_its_notes_ assert [h["source_uri"] for h in know["results"]] == served assert wider_renderer.render.await_count == (wider_case == "failed") assert "rerank: input_order_kept (TimeoutError)" not in degradations.current() + + +async def test_a_knowledge_section_that_fails_takes_both_searches_notes_with_it(monkeypatch): + """The wider search answered, then the first pass's renewal raised: the section is an + error, so neither search's render notes are named.""" + degradations.begin() + first, _ = result("first", needs_widen=True, noted=["knowledge: first_noted"]) + wider, _ = result("wider", noted=["knowledge: wider_noted"]) + first.base.proofs.check.side_effect = [None, RuntimeError("renewal failed")] + monkeypatch.setattr(repo_docs, "run_repo_search", AsyncMock(return_value=wider)) + with private_work(), pytest.raises(RuntimeError, match="renewal failed"): + await fanout._published_knowledge(first, ReadPlan("acme", marked=True), "reader") + assert degradations.current() == [] diff --git a/tests/unit/test_source_repo_search.py b/tests/unit/test_source_repo_search.py index b3da7431c71..16c17955e40 100644 --- a/tests/unit/test_source_repo_search.py +++ b/tests/unit/test_source_repo_search.py @@ -517,3 +517,31 @@ async def test_completed_ordinary_extra_survives_base_work_after_its_deadline( home = "ordinary:home" if force_ordinary or prior_loss else "private:home" assert [h.source_uri for h in out.results] == [home, "ordinary:repo"] assert result.extra is children["repo"] + + +async def test_a_failed_base_takes_the_finished_extra_legs_notes_with_it(monkeypatch): + """The additive leg answered, then the base search raised: nothing of the search is + served, so the leg's render notes are not named.""" + done = asyncio.Event() + + async def run(request, plan): + if request.input.namespace == "home": + await done.wait() + raise RuntimeError("base failed") + done.set() + out = KnowledgeSearchOutput(results=[hit("repo:a", 0.9, "repo")], embedding_model="fake") + renderer = SimpleNamespace(marked=True, render=None) + held = degradations.hold(["knowledge: repo_noted"]) + return search.CheckedSearch(out, None, renderer, [], 0, held=held) + + monkeypatch.setattr(search, "run_checked_search", run) + degradations.begin() + request = repo_docs.RepoSearchRequest( + search.SearchRequest(INPUT, ("home",), ()), + search.SearchRequest(INPUT.model_copy(update={"namespace": "repo"}), ("repo",), ()), + "repo", + asyncio.get_running_loop().time() + 100, + ) + with pytest.raises(RuntimeError, match="base failed"): + await repo_docs.run_repo_search(request, source_access.ReadPlan("acme", marked=True)) + assert degradations.current() == [] diff --git a/tests/unit/test_source_search_result.py b/tests/unit/test_source_search_result.py index 7ff2bb9f15c..404ead801e9 100644 --- a/tests/unit/test_source_search_result.py +++ b/tests/unit/test_source_search_result.py @@ -240,3 +240,76 @@ async def render(*_a): assert [h.source_uri for h in await passages.ordinary()] == ["a", "b"] # the first pass's ordinary render is served with its note; the wide pass is not assert degradations.current() == ["knowledge: spans_unnarrowed"] + + +def _passes(monkeypatch, ordinary_first): + """A marked passages read over a first pass of two hits that serve the reader, its + ordinary render `ordinary_first`, and an eager wide pass of three; each pass's render + notes `knowledge: pass_`, and the first's ordinary render its own.""" + from server.knowledge.api.models_knowledge import KnowledgeSearchInput, _SearchHit + from server.knowledge.app import source_access, source_passages + from server.observability import degradations + + def hit(uri): + other = uri == "other" + tags = ["source-kind:assistant_turn", "agent:other-bot"] if other else [] + return _SearchHit( + source_uri=uri, content=uri, chunk_idx=0, tags=tags, distance=0.2, similarity=0.8 + ) + + async def run(request, plan): + k = request.input.top_k + out = KnowledgeSearchOutput(results=[hit(u) for u in "abc"[:k]], embedding_model="m") + + async def render(*_a): + degradations.partial("knowledge", "first_ordinary") + return KnowledgeSearchOutput( + results=[hit(u) for u in ordinary_first], embedding_model="m" + ) + + # the first pass read mirrors; the wide pass did not, so its fallback renders nothing + proof = SimpleNamespace(mirrored=True, check=AsyncMock(), fresh=lambda: True) + return app.CheckedSearch( + out, + proof if k == 2 else None, + SimpleNamespace(marked=True, render=render), + [], + 0, + held=degradations.hold([f"knowledge: pass_{k}"]), + ) + + monkeypatch.setattr(app, "run_checked_search", run) + degradations.begin() + request = app.SearchRequest( + KnowledgeSearchInput(org="acme", namespace="team", query="q", top_k=2), ("team",), () + ) + return source_passages.collect(request, source_access.ReadPlan("acme", marked=True), "reader") + + +async def test_a_marked_wide_pass_the_passages_leave_out_takes_its_notes_with_it(monkeypatch): + from server.observability import degradations + + passages = await _passes(monkeypatch, "ab") + assert [h.source_uri for h in passages.hits] == ["a", "b"] + assert degradations.current() == ["knowledge: pass_2"] + + +async def test_a_wide_pass_a_later_fallback_serves_names_its_notes_again(monkeypatch): + """Left out at first, then served by the ordinary answer, whose first pass drops a + hit that serves another bot: the wide pass's render is the answer's again.""" + from server.observability import degradations + + passages = await _passes(monkeypatch, ["other", "a"]) + assert degradations.current() == ["knowledge: pass_2"] + assert [h.source_uri for h in await passages.ordinary()] == ["a", "b"] + assert degradations.current() == ["knowledge: first_ordinary", "knowledge: pass_8"] + + +async def test_discarded_passages_take_both_passes_notes_with_them(monkeypatch): + from server.observability import degradations + + passages = await _passes(monkeypatch, ["other", "a"]) + await passages.ordinary() + assert degradations.current() == ["knowledge: first_ordinary", "knowledge: pass_8"] + passages.discard() + assert degradations.current() == [] From b0fbe7f74245b44d9064b09c0f9059e08a1c0e5e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 08:19:07 +0530 Subject: [PATCH 30/47] degradations: hold a scoped list as it stands The memory stack's build and a knowledge search's render held `current()`, which flattens the scoped list: an `unkeepable` mark set in the step never reached the caller's unit, and a group held inside it was listed as a copy a later swap could not change. A held group now carries notes, inner groups and the mark, `_flat` and `keepable()` read through it, and both steps hold their `scoped()` list. Dropping the step takes all of it back. code.setting_facts gets a test that fails its test-count read: the note is listed, the count is 0 and the causes are unchanged. A merged review brief served unstored logs its failed reads, whether a read fell back and whether the tracker read failed, as the open brief does. The allowlist header names the four kinds of site the scan lists. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/index/review_brief_build.py | 9 +++- server/knowledge/app/knowledge_search.py | 15 +++--- server/memory/app/stack.py | 4 +- server/observability/degradations.py | 52 ++++++++++++++------- tests/unit/degraded_unnoted.txt | 10 ++-- tests/unit/test_code_setting_facts.py | 19 +++++++- tests/unit/test_degradations.py | 17 +++++++ tests/unit/test_source_checked_pack.py | 33 +++++++++++++ tests/unit/test_source_search_result.py | 17 +++++++ 9 files changed, 143 insertions(+), 33 deletions(-) diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index 4caf7127ab7..bb09edd9b9a 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -1236,7 +1236,14 @@ async def build_for_merge( ): # A stored brief is served as it is: a read that raised would never be retried, # and the stored copy would be served later without its `degraded` - logger.info("review_brief: PR %s served unstored, reads failed: %s", pr_number, failed) + logger.info( + "review_brief: PR %s served unstored (failed reads %s, a read fell back %s," + " tracker failed %s)", + pr_number, + failed, + not degradations.keepable(), + (provenance or {}).get("tracker") == FAILED, + ) payload["stored"] = False elif store: try: diff --git a/server/knowledge/app/knowledge_search.py b/server/knowledge/app/knowledge_search.py index 97fcda8ad9d..37498f67d85 100644 --- a/server/knowledge/app/knowledge_search.py +++ b/server/knowledge/app/knowledge_search.py @@ -122,7 +122,7 @@ class CheckedSearch: ordinary_rerank_possible: bool = False # The served render's notes; the ordinary fallback swaps in its own. held: degradations.Held = dataclasses.field(default_factory=lambda: degradations.hold([])) - _noted: list[str] = dataclasses.field(init=False) + _noted: list[degradations.Entry] = dataclasses.field(init=False) _failed: bool = dataclasses.field(default=False, init=False) _checking: asyncio.Lock = dataclasses.field( default_factory=asyncio.Lock, init=False, repr=False @@ -284,13 +284,14 @@ async def _run_search(request: SearchRequest, plan: ReadPlan) -> CheckedSearch: async def _attempt( render: Awaitable[KnowledgeSearchOutput], -) -> tuple[KnowledgeSearchOutput, list[str]]: - """A render's answer and the notes it took. A render that raises, one that lost a - mirrored document among them, takes its notes with it: a rerank or span fallback of - an answer not served must not be named.""" - with degradations.scoped(): +) -> tuple[KnowledgeSearchOutput, list[degradations.Entry]]: + """A render's answer and the notes it took, as its scoped list stands (with its held + groups and `unkeepable` mark). A render that raises, one that lost a mirrored + document among them, takes its notes with it: a rerank or span fallback of an answer + not served must not be named.""" + with degradations.scoped() as noted: output = await render - return output, degradations.current() + return output, noted # The fields that narrow a knowledge.search to part of the namespace's documents. diff --git a/server/memory/app/stack.py b/server/memory/app/stack.py index 8a53cda1254..bc5860a6e24 100644 --- a/server/memory/app/stack.py +++ b/server/memory/app/stack.py @@ -348,7 +348,7 @@ async def run_checked_stack(input: MemoryStackInput, plan: ReadPlan) -> CheckedS input = input.model_copy(deep=True) with private_work() if plan.marked else nullcontext(): # a build that raises serves nothing, and takes its notes with it - with degradations.scoped(): + with degradations.scoped() as noted: ch = get_client() fill = _StackFill(budget=input.token_budget) await _stack_profile(input, fill) @@ -373,7 +373,7 @@ async def run_checked_stack(input: MemoryStackInput, plan: ReadPlan) -> CheckedS except Exception as e: # noqa: BLE001 — a failed knowledge section must not fail the stack degradations.partial("memory.stack", "knowledge_dropped", e) log.warning("memory.stack: knowledge fan-out failed (non-fatal): %s", e) - noted = degradations.current() + # held as it stands, with its groups and `unkeepable` mark return CheckedStack(fill, knowledge, plan.marked, degradations.hold(noted)) diff --git a/server/observability/degradations.py b/server/observability/degradations.py index 885211d2f77..d96ce6e1269 100644 --- a/server/observability/degradations.py +++ b/server/observability/degradations.py @@ -48,14 +48,16 @@ class Held: """The notes of an answer a later step may replace (a checked document search that falls back to its ordinary render): listed in the request while held, and replaced - whole by `swap`. Another holder of the same note keeps its own copy.""" + whole by `swap`. Another holder of the same note keeps its own copy. A scoped list + held as it stands keeps its groups, which a later swap still changes, and its + `unkeepable` mark, which the swap takes back with its notes.""" __slots__ = ("entries",) - def __init__(self, entries: list[str]) -> None: + def __init__(self, entries: list[Entry]) -> None: self.entries = list(entries) - def swap(self, entries: list[str]) -> None: + def swap(self, entries: list[Entry]) -> None: self.entries = list(entries) @@ -68,24 +70,37 @@ class _Unkept: _UNKEPT = _Unkept() -_notes: contextvars.ContextVar[list[str | Held | _Unkept] | None] = contextvars.ContextVar( +# What a note list holds: a note, a held group, or the `unkeepable` mark +Entry = str | Held | _Unkept + +_notes: contextvars.ContextVar[list[Entry] | None] = contextvars.ContextVar( "loom_degradations", default=None ) -def _flat(lst: list[str | Held | _Unkept] | None) -> list[str]: +def _flat(lst: list[Entry] | None) -> list[str]: """The distinct notes of a list, a held group's in its place, at most `_MAX_NOTES`.""" out: list[str] = [] - for item in lst or (): - if isinstance(item, _Unkept): - continue - for entry in item.entries if isinstance(item, Held) else (item,): - if entry not in out and len(out) < _MAX_NOTES: - out.append(entry) + + def walk(items: list[Entry]) -> None: + for item in items: + if isinstance(item, Held): + walk(item.entries) + elif isinstance(item, str) and item not in out and len(out) < _MAX_NOTES: + out.append(item) + + walk(lst or []) return out -def _bound() -> list[str | Held | _Unkept]: +def _marked(lst: list[Entry]) -> bool: + """Whether a list, or a group it holds, carries the `unkeepable` mark.""" + return any( + item is _UNKEPT or (isinstance(item, Held) and _marked(item.entries)) for item in lst + ) + + +def _bound() -> list[Entry]: lst = _notes.get() if lst is None: lst = [] @@ -93,7 +108,7 @@ def _bound() -> list[str | Held | _Unkept]: return lst -def _add(lst: list[str | Held | _Unkept], entry: str) -> None: +def _add(lst: list[Entry], entry: str) -> None: """List a note once, at most `_MAX_NOTES` of them, counting only the request's own notes: a held group a later swap may empty does not stand in for one.""" own = [item for item in lst if isinstance(item, str)] @@ -107,12 +122,12 @@ def begin() -> None: @contextmanager -def scoped() -> Iterator[list[str | Held | _Unkept]]: +def scoped() -> Iterator[list[Entry]]: """A fresh note list inside the block, and the caller's back after it: a unit of a worker's pass (one review brief) reads only its own notes, and a request that runs the pass inline keeps its own. It yields the block's own list, which `restore` lists in the caller's with its held groups and `unkeepable` mark.""" - own: list[str | Held | _Unkept] = [] + own: list[Entry] = [] token = _notes.set(own) try: yield own @@ -209,12 +224,12 @@ def keepable() -> bool: """Whether a cache may keep what this unit built: it noted nothing and called no `unkeepable()`.""" lst = _notes.get() or [] - return not _flat(lst) and _UNKEPT not in lst + return not _flat(lst) and not _marked(lst) -def hold(entries: list[str]) -> Held: +def hold(entries: list[Entry]) -> Held: """List `entries` in this request as one `Held` group, which the answer's replacement - swaps.""" + swaps: notes, or a `scoped()` list as it stands.""" held = Held(entries) _bound().append(held) return held @@ -238,6 +253,7 @@ def on_response(body: Any) -> Any: __all__ = [ + "Entry", "Held", "begin", "current", diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index bd64c67c837..045d9522396 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -1,7 +1,9 @@ -# Broad and timeout handlers in the code, memory, knowledge and tracker apps and the LLM -# clients that name nothing in `degraded`, each with why it need not -# (tests/unit/test_degraded_unnoted.py lists the dirs and the categories). The list only -# shrinks: a handler that serves a smaller answer notes it. +# The sites tests/unit/test_degraded_unnoted.py scans in the code, memory, knowledge and +# tracker apps and the LLM clients that name nothing in `degraded`, each with why it need +# not: broad handlers (`path::function::ordinal`), timeout handlers +# (`path::function::timeout::ordinal`), refusal handlers (`path::function::refused::ordinal`) +# and gather branches (`path::function::gather::ordinal`). The test lists the dirs and +# the categories. The list only shrinks: a site that serves a smaller answer notes it. server/code/app/answers.py::_memory_context_cacheable::1 cache_fallback server/code/app/answers_cache.py::_check_stored::1 write diff --git a/tests/unit/test_code_setting_facts.py b/tests/unit/test_code_setting_facts.py index 3dc0baf1a51..91e1a2e65ea 100644 --- a/tests/unit/test_code_setting_facts.py +++ b/tests/unit/test_code_setting_facts.py @@ -134,7 +134,7 @@ def test_verdict_needs_the_control_before_a_negative() -> None: class _Repo: def __init__(self, *, history_fails: bool = False, fails: frozenset[str] = frozenset()) -> None: self.history_fails = history_fails - # `declaration` (the subject's), `control` (the control's), `randomizer` + # `declaration` (the subject's), `control` (the control's), `randomizer`, `tests` self.fails = fails self.calls: list[tuple[str, Any]] = [] @@ -192,6 +192,8 @@ async def grep_files( scope=None, ): self.calls.append(("grep_files", pattern)) + if "tests" in self.fails: + raise TimeoutError("files down") return [], 21 if "use_skip" in pattern else 0 @@ -294,6 +296,21 @@ async def test_a_failed_declaration_or_randomizer_read_is_named(wired) -> None: assert not out.randomized_in_ci["randomized"] +@pytest.mark.asyncio +async def test_a_failed_test_count_is_named_in_degraded_only(wired) -> None: + """An unread test count is no count of zero: `degraded` names the read, and `causes` + and the verdict, which it does not decide, are as with the count read.""" + wired(_Repo(fails=frozenset({"tests"}))) + with degradations.unit(): + out = await h.handle_code_setting_facts( + CodeSettingFactsInput(org=ORG, namespace=NS, name="use_skip_indexes_if_final") + ) + assert degradations.current() == [ + f"code_index: setting_tests_unread ({caller_text(TimeoutError('files down'))})" + ] + assert (out.verdict, out.causes, out.tests_total) == ("known", [], 0) + + @pytest.mark.asyncio async def test_a_control_read_that_raised_is_unread_not_failed(wired) -> None: """A control whose read raised says nothing of the index, where one that found no diff --git a/tests/unit/test_degradations.py b/tests/unit/test_degradations.py index 1e49cf15784..2dfe0086389 100644 --- a/tests/unit/test_degradations.py +++ b/tests/unit/test_degradations.py @@ -108,6 +108,23 @@ def test_an_unkeepable_unit_names_nothing_and_keeps_its_callers_answer_out(): assert not D.keepable() and D.on_response({}) == {} +def test_a_scoped_list_held_as_it_stands_keeps_its_groups_and_mark(): + """A step that holds its scoped list (the memory stack, a knowledge render) keeps a + group set inside it, which a later swap still changes, and its `unkeepable` mark; + swapping the step's own group empty takes all of them back.""" + D.begin() + with D.unit(): + with D.scoped() as noted: + inner = D.hold([]) + D.unkeepable() + step = D.hold(noted) + assert D.current() == [] and not D.keepable() # the mark alone + inner.swap(["knowledge: ordinary (y)"]) + assert D.current() == ["knowledge: ordinary (y)"] + step.swap([]) + assert D.current() == [] and D.keepable() + + def test_a_held_group_at_the_cap_keeps_no_note_out(): D.begin() full = [f"x: {i}" for i in range(D._MAX_NOTES)] diff --git a/tests/unit/test_source_checked_pack.py b/tests/unit/test_source_checked_pack.py index 364defa4dd0..0ef24e1ffea 100644 --- a/tests/unit/test_source_checked_pack.py +++ b/tests/unit/test_source_checked_pack.py @@ -389,3 +389,36 @@ async def nothing(*_a): assert degradations.current() == ["memory.stack: profile_dropped (x)"] checked.discard() assert degradations.current() == [] + + +async def test_a_stack_holds_a_mark_and_a_group_its_build_set(monkeypatch): + """The build's scoped list is held as it stands: an `unkeepable` mark set inside the + stack keeps the caller's unit out of its caches, a group held inside it is still the + one a later swap changes, and dropping the stack takes both back.""" + from server.memory.api.models_lifecycle import MemoryStackInput + from server.observability import degradations + + inner: list[degradations.Held] = [] + + async def profile(input, fill): + inner.append(degradations.hold([])) + degradations.unkeepable() + + async def nothing(*_a): + return "" + + monkeypatch.setattr(stack, "get_client", lambda: None) + monkeypatch.setattr(stack, "_stack_profile", profile) + monkeypatch.setattr(stack, "_stack_pinned", nothing) + monkeypatch.setattr(stack, "_stack_recent", nothing) + degradations.begin() + with degradations.unit(): + checked = await stack.run_checked_stack( + MemoryStackInput(org="acme", namespace="docs", agent="reader"), + source_access.ReadPlan("acme"), + ) + assert degradations.current() == [] and not degradations.keepable() # the mark alone + inner[0].swap(["knowledge: ordinary (y)"]) + assert degradations.current() == ["knowledge: ordinary (y)"] + checked.discard() + assert degradations.current() == [] and degradations.keepable() diff --git a/tests/unit/test_source_search_result.py b/tests/unit/test_source_search_result.py index 404ead801e9..85ae066a45b 100644 --- a/tests/unit/test_source_search_result.py +++ b/tests/unit/test_source_search_result.py @@ -180,6 +180,23 @@ async def test_a_later_fallback_replaces_the_served_renders_notes(monkeypatch): assert degradations.current() == [] +async def test_a_served_render_carries_its_unkeepable_mark_to_the_callers_unit(monkeypatch): + """A render's scoped list is held as it stands: a mark set in it keeps the caller's + unit out of its caches, though it names nothing.""" + from server.observability import degradations + + async def marks(_endpoint, _query, hits, _top): + degradations.unkeepable() + return hits, True + + pending = _rerank_fails_then(monkeypatch, None, None, None, None) + monkeypatch.setattr(app, "_rerank", marks) + with degradations.unit(): + result = await pending + assert not result.lost + assert degradations.current() == [] and not degradations.keepable() + + async def test_a_fallback_whose_render_fails_names_nothing_of_the_discarded_render(monkeypatch): """The ordinary render raised: nothing of the search is served, so the mixed render's rerank note goes; the caller names the failure.""" From 1bca74768e8a8387a07628bc7b042aebf933ad96 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 08:37:40 +0530 Subject: [PATCH 31/47] memory.search: restore the re-read's scoped list as it stands The sequential re-read returned `current()` from its `scoped()` block, so the pass that serves it restored flat text: a mark set in the re-read never reached the pass's unit. It now returns the scoped list, as the memory stack and the knowledge render hold theirs. The review brief builders bind whether a read fell back, and whether the tracker read failed, once for the store gate and its log line. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/index/review_brief_build.py | 15 ++++++------ server/memory/app/search/consistency.py | 12 +++++----- tests/unit/test_search_read_your_writes.py | 26 +++++++++++++++++++++ 3 files changed, 40 insertions(+), 13 deletions(-) diff --git a/server/code/app/index/review_brief_build.py b/server/code/app/index/review_brief_build.py index bb09edd9b9a..7f774b64df2 100644 --- a/server/code/app/index/review_brief_build.py +++ b/server/code/app/index/review_brief_build.py @@ -1228,12 +1228,12 @@ async def build_for_merge( # blame and diff sections: serve it, but leave the store to a process that # reads the diff, or every later read would serve the degraded copy. failed = failed_reads(payload.get("sections") or {}) + fell_back = not degradations.keepable() + tracker_failed = (provenance or {}).get("tracker") == FAILED if store and changed_paths and not diff: logger.info("review_brief: PR %s served unstored, its diff was not read", pr_number) payload["stored"] = False - elif store and ( - failed or not degradations.keepable() or (provenance or {}).get("tracker") == FAILED - ): + elif store and (failed or fell_back or tracker_failed): # A stored brief is served as it is: a read that raised would never be retried, # and the stored copy would be served later without its `degraded` logger.info( @@ -1241,8 +1241,8 @@ async def build_for_merge( " tracker failed %s)", pr_number, failed, - not degradations.keepable(), - (provenance or {}).get("tracker") == FAILED, + fell_back, + tracker_failed, ) payload["stored"] = False elif store: @@ -1397,7 +1397,8 @@ async def build_for_open( # an overlay that was off, left a changed file unreached or parsed another head; a # parse that failed or ran past its limits does so again, so its brief is stored overlay_partial = note_may_change(str(payload.get("overlay_note") or "")) - if store and (failed or diff_unread or overlay_partial or not degradations.keepable()): + fell_back = not degradations.keepable() + if store and (failed or diff_unread or overlay_partial or fell_back): logger.info( "review_brief: open PR %s served unstored (diff unread %s, overlay off or" " partial %s, failed reads %s, a read fell back %s)", @@ -1405,7 +1406,7 @@ async def build_for_open( diff_unread, overlay_partial, failed, - not degradations.keepable(), + fell_back, ) payload["stored"] = False elif store: diff --git a/server/memory/app/search/consistency.py b/server/memory/app/search/consistency.py index 134846f4bce..3685b9896fd 100644 --- a/server/memory/app/search/consistency.py +++ b/server/memory/app/search/consistency.py @@ -218,15 +218,16 @@ async def _consistency_reread( async def _sequential_pass( reread_input: MemorySearchInput, search_budget: Any, what: str -) -> tuple[MemorySearchOutput | None, list[str]]: +) -> tuple[MemorySearchOutput | None, list[degradations.Entry]]: """The whole search once more under sequential consistency, within the wall budget: - its answer (None when it failed or ran out of time) and the notes it took inside - `scoped()`, which reach the request only if the caller serves it. A failure is noted + its answer (None when it failed or ran out of time) and its `scoped()` list as it + stands (with its held groups and `unkeepable` mark), which reaches the request only + if the caller serves it. A failure is noted after the scope, so it is named whether or not the re-read is served.""" from server.memory.app.search import handle_memory_search result, failure = None, "" - with degradations.scoped(): + with degradations.scoped() as noted: try: with sequential_reads(): result = await asyncio.wait_for( @@ -241,13 +242,12 @@ async def _sequential_pass( except Exception as e: # noqa: BLE001 — an optional re-read; the first pass stands log.warning("memory.search: %s failed: %s", what, e) failure = caller_text(e) - noted = degradations.current() if failure: degradations.partial("memory.search", "read_your_writes_unchecked", failure) return result, noted -def _serve_notes_of(noted: list[str]) -> None: +def _serve_notes_of(noted: list[degradations.Entry]) -> None: """The pass serves its re-read's answer, so it names the re-read's notes in place of its own. `handle_memory_search` runs each pass in a `degradations.unit()`: this rebinds only that unit's list, and the caller's notes stand.""" diff --git a/tests/unit/test_search_read_your_writes.py b/tests/unit/test_search_read_your_writes.py index 6d838421670..fe4a6a68c24 100644 --- a/tests/unit/test_search_read_your_writes.py +++ b/tests/unit/test_search_read_your_writes.py @@ -246,3 +246,29 @@ async def one_pass() -> tuple[object, list[str]]: unchecked = "memory.search: read_your_writes_unchecked (RuntimeError)" expected = [retried] if served else [first, unchecked] assert notes == ["identity: repo_gate_unverified", *expected] + + +def test_a_served_retry_carries_its_mark_to_the_pass(monkeypatch) -> None: + """The retry's scoped list is restored as it stands: an `unkeepable` mark set in the + re-read the pass serves keeps the pass's unit out of its caches, though it names + nothing.""" + from types import SimpleNamespace + + import server.memory.app.search as pkg + from server.memory.app.search.consistency import _consistency_reread + from server.observability import degradations + + async def search(inp: object) -> object: + degradations.unkeepable() + return SimpleNamespace(results=["hit"], retrieval_work={}) + + async def one_pass() -> tuple[object, bool, list[str]]: + degradations.begin() + with degradations.unit(): # as handle_memory_search runs a pass + out = await _consistency_reread(_empty_pass_ctx(60_000), []) # type: ignore[arg-type] + return out, degradations.keepable(), degradations.current() + + monkeypatch.setattr(pkg, "handle_memory_search", search) + monkeypatch.setattr("server.memory.store.read_your_writes_enabled", lambda: True) + out, keepable, notes = asyncio.run(one_pass()) + assert out is not None and not keepable and notes == [] From 038ccbbfb0a264e2358020825131f1105ddeb170 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 08:50:40 +0530 Subject: [PATCH 32/47] search: rewrap the sequential re-read docstring The docstring of _sequential_pass broke a sentence across a short line; it is reflowed, with no change to the text. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/memory/app/search/consistency.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/memory/app/search/consistency.py b/server/memory/app/search/consistency.py index 3685b9896fd..5bfe260d95c 100644 --- a/server/memory/app/search/consistency.py +++ b/server/memory/app/search/consistency.py @@ -222,8 +222,8 @@ async def _sequential_pass( """The whole search once more under sequential consistency, within the wall budget: its answer (None when it failed or ran out of time) and its `scoped()` list as it stands (with its held groups and `unkeepable` mark), which reaches the request only - if the caller serves it. A failure is noted - after the scope, so it is named whether or not the re-read is served.""" + if the caller serves it. A failure is noted after the scope, so it is named whether + or not the re-read is served.""" from server.memory.app.search import handle_memory_search result, failure = None, "" From 6172a497644f75dd826e8736a1befaae5b16d222 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 08:59:01 +0530 Subject: [PATCH 33/47] consistency: say why a failed re-read's note stays A failed re-read answers None and is never served; its note is taken after the scope, so it stays when the caller drops that re-read's list. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/memory/app/search/consistency.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/memory/app/search/consistency.py b/server/memory/app/search/consistency.py index 5bfe260d95c..aaa1549d08a 100644 --- a/server/memory/app/search/consistency.py +++ b/server/memory/app/search/consistency.py @@ -222,8 +222,8 @@ async def _sequential_pass( """The whole search once more under sequential consistency, within the wall budget: its answer (None when it failed or ran out of time) and its `scoped()` list as it stands (with its held groups and `unkeepable` mark), which reaches the request only - if the caller serves it. A failure is noted after the scope, so it is named whether - or not the re-read is served.""" + if the caller serves it. A failure is noted after the scope, so it stays when the + caller drops the failed re-read's list.""" from server.memory.app.search import handle_memory_search result, failure = None, "" From 2b9764494ae603fdc908da6f926a5d24da7df3cc Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 09:13:08 +0530 Subject: [PATCH 34/47] degraded: drop an unused wider pass's notes and an empty scope's profile note Under a marked plan, loom.search's knowledge section builds the wider search while it ranks the first pass. When the renewed first pass fills the page alone, the section served no wider result but kept its render notes; it now discards the wider search before it returns. mentor.brief named profile_unread whenever the profile was None with the TTL on, but mentor_profile also answers None without a read for an empty org or namespace. The note now needs both. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/insights/app/mentor_brief.py | 7 +++-- server/memory/app/loom_search/fanout.py | 2 ++ tests/unit/test_mentor.py | 18 ++++++++++++ tests/unit/test_source_fanout_renewal.py | 36 ++++++++++++++++++++++++ 4 files changed, 60 insertions(+), 3 deletions(-) diff --git a/server/insights/app/mentor_brief.py b/server/insights/app/mentor_brief.py index e5ec04a006b..acbfd1917d6 100644 --- a/server/insights/app/mentor_brief.py +++ b/server/insights/app/mentor_brief.py @@ -278,9 +278,10 @@ async def handle_mentor_brief(inp: MentorBriefInput) -> MentorBriefOutput: inp.org, inp.namespace, agent, profile.window_seconds if profile else window ) if profile is None: - # The mentor is off (TTL 0) or the read failed and is remembered: - # an honest empty brief, not an error. Only the failure is a fallback. - if int(settings.mentor_ttl_seconds) > 0: + # The mentor is off (TTL 0), the scope is empty (nothing is read), or the + # read failed and is remembered: an honest empty brief, not an error. Only + # the failure is a fallback. + if int(settings.mentor_ttl_seconds) > 0 and inp.org and inp.namespace: degradations.partial("mentor.brief", "profile_unread") return MentorBriefOutput( org=inp.org, diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index 50d760504ec..d4988774115 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -317,6 +317,8 @@ async def cached(_k: int) -> KnowledgeSearchOutput: for result in (first, wider) if used_wider and wider is not None else (first,): for proof in result.publication_proofs: source_publication.retain(proof) + if wider is not None and not used_wider: + wider.discard() # built for the first ranking, unused by the renewed one return final except BaseException: # the section is an error, which the caller names: nothing of either search is served diff --git a/tests/unit/test_mentor.py b/tests/unit/test_mentor.py index 0b7b88b057e..763cd06077c 100644 --- a/tests/unit/test_mentor.py +++ b/tests/unit/test_mentor.py @@ -1298,6 +1298,24 @@ def test_mentor_brief_when_the_mentor_is_off_is_an_honest_empty_brief( assert degradations.current() == [] +@pytest.mark.parametrize(("org", "namespace"), [("o", ""), ("", "ns")]) +def test_a_brief_for_an_empty_scope_names_no_failed_profile_read( + monkeypatch: pytest.MonkeyPatch, org: str, namespace: str +) -> None: + """`mentor_profile` reads nothing for an empty org or namespace: no fallback.""" + from server.insights.api.models_mentor import MentorBriefInput + + monkeypatch.setattr(settings, "mentor_ttl_seconds", 60, raising=False) + ch = _CH({**_EVIDENCE_ROWS, M_RETENTION: [{"retention_days": 0}]}) + monkeypatch.setattr(handler, "get_client", lambda: ch) + degradations.begin() + out = asyncio.run( + handler.handle_mentor_brief(MentorBriefInput(org=org, namespace=namespace, agent="a")) + ) + assert out.skipped == ["profile: unavailable"] + assert degradations.current() == [] + + def test_a_profile_whose_read_failed_is_named_in_degraded( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/tests/unit/test_source_fanout_renewal.py b/tests/unit/test_source_fanout_renewal.py index f340478c19e..7640a4ed5e2 100644 --- a/tests/unit/test_source_fanout_renewal.py +++ b/tests/unit/test_source_fanout_renewal.py @@ -247,6 +247,42 @@ async def run(request, plan): first_renderer.render.assert_not_awaited() +async def test_a_wider_pass_the_renewed_first_pass_does_not_use_takes_its_notes_with_it( + monkeypatch, +): + """The first ranking built the wider search; the renewed first pass, its expired extra + dropped, fills the page alone, so only the first pass's notes are named.""" + from dataclasses import replace + + degradations.begin() + first, _ = result("first", noted=["knowledge: first_noted"]) + first.base.output.results = [hit("private-a"), hit("private-b")] + extra, _ = result("extra") + other = hit("extra-other", other=True) + other.namespace, other.score = "repo", 0.99 + extra.base.output.results = [other] + first.extra = extra.base + extra_request = SearchRequest( + first.request.base.input.model_copy( + update={"namespace": "repo", "namespace_scope": "this", "rerank": "none"} + ), + ("repo",), + (), + ) + first.request = replace(first.request, extra=extra_request, repo_namespace="repo") + wider, _ = result("wider", noted=["knowledge: wider_noted"]) + + async def run(request, plan): + first.request = replace(first.request, extra_deadline=asyncio.get_running_loop().time() - 1) + return wider + + monkeypatch.setattr(repo_docs, "run_repo_search", run) + with private_work(): + know = await fanout._knowledge_section(first, ReadPlan("acme", marked=True), "reader") + assert [h["source_uri"] for h in know["results"]] == ["private-a", "private-b"] + assert degradations.current() == ["knowledge: first_noted"] + + @pytest.mark.parametrize("wider_case", ["unused", "failed"]) async def test_a_wider_pass_the_ordinary_section_does_not_serve_takes_its_notes_with_it( wider_case, From b33be4ffd15df7484ac1a324f03cccaa3bc7d2c5 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 09:52:19 +0530 Subject: [PATCH 35/47] degraded: name only what the served answer fell back on loom.search, marked plan: the first ranking's eager widening that failed wrote knowledge: widened_hits_dropped, although that ranking is never served once its widening failed. Its expander now records the error and answers with the first pass; cached raises it again only for a renewed ranking that still needs the wider result, and an ordinary section names its own widening. Repository search: the notes a pass's legs make while they run (a lexical leg dropped, the extra leg's repo_docs_dropped) went straight into the request's list, so a pass left out kept them. run_repo_search now runs its legs in scoped() and holds that list on the RepoSearch; discard() empties it, and a served pass lists it through the group. A search that fails holds nothing, which replaces the finished-leg loop. code.backport_gap: its symbol, patch and history stages run under fixed walls (settings, as the op takes no caller deadline), so a stage cut by its wall is a slow read; a cut and a read that raised are now noted (code_index: symbol_presence_*, patch_presence_*, git_mirror: branch_history_*, with the exception's type). mentor: profile_read_applies(org, namespace) is the one no-read rule for mentor_profile, warm_profile, the hint and mentor.brief. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/backport.py | 17 +++-- server/insights/app/mentor.py | 22 +++--- server/insights/app/mentor_brief.py | 2 +- server/knowledge/app/repo_docs.py | 25 +++---- server/memory/app/loom_search/fanout.py | 18 +++-- tests/unit/degraded_unnoted.txt | 1 + tests/unit/test_code_backport_gap_exact.py | 7 ++ tests/unit/test_code_backport_gaps.py | 37 ++++++++++ tests/unit/test_source_fanout_renewal.py | 79 +++++++++++++++++++--- tests/unit/test_source_repo_search.py | 35 ++++++++++ 10 files changed, 196 insertions(+), 47 deletions(-) diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 737bafb49dc..376f284f1bc 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -274,11 +274,14 @@ async def one(ns: str) -> tuple[dict[str, list[str]], dict[str, Any]]: result: dict[str, dict[str, tuple[str, str]]] = {s: {} for s in symbols} for ns, t in tasks.items(): if t in pending or t.cancelled(): + # the stage's wall is a fixed setting, not a caller's deadline: a slow read + degradations.partial("code_index", "symbol_presence_timed_out") for s in symbols: result[s][ns] = ("unknown", "deadline") continue err = t.exception() if err is not None: + degradations.partial("code_index", "symbol_presence_unread", type(err).__name__) logger.debug("backport_gap: presence read failed on %s: %s", ns, err) for s in symbols: result[s][ns] = ("unknown", f"error:{type(err).__name__}") @@ -385,10 +388,13 @@ async def one(ns: str) -> pp.PatchPresence: out: dict[str, pp.PatchPresence] = {} for ns, t in tasks.items(): if t in pending or t.cancelled(): + degradations.partial("code_index", "patch_presence_timed_out") # a fixed wall out[ns] = pp.PatchPresence(reason="deadline") elif t.exception() is not None: - logger.debug("backport_gap: patch read failed on %s: %s", ns, t.exception()) - out[ns] = pp.PatchPresence(reason=f"error:{type(t.exception()).__name__}") + err = t.exception() + degradations.partial("code_index", "patch_presence_unread", type(err).__name__) + logger.debug("backport_gap: patch read failed on %s: %s", ns, err) + out[ns] = pp.PatchPresence(reason=f"error:{type(err).__name__}") else: out[ns] = t.result() return groups, out @@ -592,10 +598,13 @@ async def _history_stage( out: dict[str, ph.HistoryPresence] = {} for ns, t in tasks.items(): if t in pending or t.cancelled(): + degradations.partial("git_mirror", "branch_history_timed_out") # a fixed wall out[ns] = ph.HistoryPresence(reason="deadline") elif t.exception() is not None: - logger.debug("backport_gap: history read failed on %s: %s", ns, t.exception()) - out[ns] = ph.HistoryPresence(reason=f"error:{type(t.exception()).__name__}") + err = t.exception() + degradations.partial("git_mirror", "branch_history_unread", type(err).__name__) + logger.debug("backport_gap: history read failed on %s: %s", ns, err) + out[ns] = ph.HistoryPresence(reason=f"error:{type(err).__name__}") else: out[ns] = t.result() return out diff --git a/server/insights/app/mentor.py b/server/insights/app/mentor.py index e5f6c656cb2..10045c19324 100644 --- a/server/insights/app/mentor.py +++ b/server/insights/app/mentor.py @@ -164,6 +164,12 @@ def _ttl() -> int: return int(settings.mentor_ttl_seconds) +def profile_read_applies(org: str, namespace: str) -> bool: + """Whether a profile is read for this scope: the mentor is on (TTL above 0) and the + org and namespace are set. Nothing reads a profile otherwise.""" + return _ttl() > 0 and bool(org) and bool(namespace) + + def _session(session_key: str, *, clock: Callable[[], float]) -> dict[str, Any]: now = clock() st = _sessions.get(session_key) @@ -371,12 +377,12 @@ async def mentor_profile( window_seconds: int = WINDOW_SECONDS_DEFAULT, clock: Callable[[], float] = time.monotonic, ) -> MentorProfile | None: - """The cached profile for this agent and window; None when the TTL is 0 - (the mentor is off), when the read failed, or while a failure is still + """The cached profile for this agent and window; None when no profile is read + (`profile_read_applies`), when the read failed, or while a failure is still remembered. Never raises.""" - ttl = _ttl() - if ttl <= 0 or not org or not namespace: + if not profile_read_applies(org, namespace): return None + ttl = _ttl() agent = str(agent or "-") identity = (str(org), str(namespace), agent) now = clock() @@ -404,9 +410,7 @@ def warm_profile(org: str, namespace: str, agent: str) -> None: call or pack reads the result. Never blocks the caller.""" key = (str(org), str(namespace), str(agent or "-")) if ( - _ttl() <= 0 - or not org - or not namespace + not profile_read_applies(org, namespace) or (*key, WINDOW_SECONDS_DEFAULT) in _cache or key in _inflight ): @@ -515,9 +519,7 @@ def call_hint( try: if not public_diagnostics(): return None - if _ttl() <= 0: - return None - if not org or not namespace: + if not profile_read_applies(org, namespace): return None if agent in _SILENT_CALLERS or str(arguments.get("consumer") or "") in _SILENT_CALLERS: return None diff --git a/server/insights/app/mentor_brief.py b/server/insights/app/mentor_brief.py index acbfd1917d6..5c518bca0b6 100644 --- a/server/insights/app/mentor_brief.py +++ b/server/insights/app/mentor_brief.py @@ -281,7 +281,7 @@ async def handle_mentor_brief(inp: MentorBriefInput) -> MentorBriefOutput: # The mentor is off (TTL 0), the scope is empty (nothing is read), or the # read failed and is remembered: an honest empty brief, not an error. Only # the failure is a fallback. - if int(settings.mentor_ttl_seconds) > 0 and inp.org and inp.namespace: + if svc.profile_read_applies(inp.org, inp.namespace): degradations.partial("mentor.brief", "profile_unread") return MentorBriefOutput( org=inp.org, diff --git a/server/knowledge/app/repo_docs.py b/server/knowledge/app/repo_docs.py index 5cfe6afeaf8..dc0d80a70b1 100644 --- a/server/knowledge/app/repo_docs.py +++ b/server/knowledge/app/repo_docs.py @@ -74,6 +74,8 @@ class RepoSearch: request: RepoSearchRequest base: CheckedSearch extra: CheckedSearch | None + # The notes its legs made while they ran, their renders' groups among them + held: degradations.Held = dataclasses.field(default_factory=lambda: degradations.Held([])) _lost: bool = dataclasses.field(default=False, init=False) _base_used: bool = dataclasses.field(default=False, init=False) @@ -132,7 +134,9 @@ def _drop_expired_extra(self) -> None: self.extra = None def discard(self) -> None: - """Take both legs' notes back: the caller serves nothing of this search.""" + """Take its legs' notes back, its renders' with them: the caller serves nothing + of this search.""" + self.held.swap([]) for child in self.children: child.discard() @@ -254,25 +258,14 @@ async def run_repo_search(request: RepoSearchRequest, plan: ReadPlan) -> RepoSea if any(child.input.org != plan.org for child in (request.base, request.extra) if child): raise ValueError("document read scope changed") - finished: list[CheckedSearch] = [] - - async def extra_leg() -> CheckedSearch | None: - leg = await search_repo_docs(request, plan) - if leg is not None: - finished.append(leg) - return leg - with private_work() if plan.marked else nullcontext(): - try: + # A search that fails lists nothing its legs noted: the caller names the failure. + with degradations.scoped() as legs: base, extra = await gather_or_cancel( - run_checked_search(request.base, plan), extra_leg() + run_checked_search(request.base, plan), search_repo_docs(request, plan) ) - except BaseException: - for leg in finished: - leg.discard() # nothing of this search is served; the caller names the failure - raise assert base is not None - return RepoSearch(request, base, extra) + return RepoSearch(request, base, extra, degradations.hold(legs)) def merge_hits(base: list[_SearchHit], extra: list[_SearchHit], top_k: int) -> list[_SearchHit]: diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index d4988774115..b584ffccd8a 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -274,13 +274,19 @@ async def _knowledge_section( top_k = int(first.request.base.input.top_k) async def expanded(k: int) -> KnowledgeSearchOutput: - nonlocal wider, widening_error + nonlocal wider + wider = await repo_docs.run_repo_search(first.request.wider(k), plan) + return wider.output + + async def eager(k: int) -> KnowledgeSearchOutput: + nonlocal widening_error try: - wider = await repo_docs.run_repo_search(first.request.wider(k), plan) - except Exception as error: + return await expanded(k) + except Exception as error: # noqa: BLE001 — the ranking that is served names it + # A first ranking whose widening failed is never served: `cached` raises the + # error again for the renewed ranking if it still needs the wider result. widening_error = error - raise - return wider.output + return first.output try: if not plan.marked: @@ -289,7 +295,7 @@ async def expanded(k: int) -> KnowledgeSearchOutput: await first.current() if not first.fresh(): return await _ordinary_knowledge(first, None, agent) - initial = await _filtered_knowledge(first.output, expanded, agent, top_k) + initial = await _filtered_knowledge(first.output, eager, agent, top_k) if wider is None and widening_error is None: if first.fresh(): for proof in first.publication_proofs: diff --git a/tests/unit/degraded_unnoted.txt b/tests/unit/degraded_unnoted.txt index 045d9522396..bc3865b80b2 100644 --- a/tests/unit/degraded_unnoted.txt +++ b/tests/unit/degraded_unnoted.txt @@ -331,6 +331,7 @@ server/memory/app/inline_records.py::_write_inline_record_projection::1 server/memory/app/inspect.py::_record_exposure::1 telemetry server/memory/app/intent_marks.py::flush::1 write server/memory/app/key_supersession.py::supersede_same_key_rows::1 write +server/memory/app/loom_search/fanout.py::_knowledge_section.eager::1 noted_by_caller # a first ranking never served; cached raises it for the one served server/memory/app/loom_search/fanout.py::_prepare_knowledge::1 noted_by_caller # _leg_error notes the knowledge leg server/memory/app/move.py::_redirect_source::1 write server/memory/app/namespace_retrieval_defaults.py::parse::1 settings diff --git a/tests/unit/test_code_backport_gap_exact.py b/tests/unit/test_code_backport_gap_exact.py index 6d4347bb639..2f3d57ad252 100644 --- a/tests/unit/test_code_backport_gap_exact.py +++ b/tests/unit/test_code_backport_gap_exact.py @@ -17,6 +17,7 @@ import server.code.app.backport as h import server.tracker.app.binding as binding from server.code.api.models_history import CodeBackportGapInput +from server.observability import degradations from server.settings import settings from server.tracker.domain import backport as bp from server.tracker.domain import patch_presence as pp @@ -635,6 +636,7 @@ async def chunks_for_patch(self, org, ns, paths, symbols, needles, *, limit=400) monkeypatch.setattr(settings, "code_backport_patch_budget_ms", 50) repo = _Broken(CHUNKS, slow="code-clickhouse-26-8") wired(_Source(sections=[DIFF_SRC]), repo) + degradations.begin() out = await h.handle_code_backport_gap( CodeBackportGapInput( org=ORG, @@ -649,6 +651,11 @@ async def chunks_for_patch(self, org, ns, paths, symbols, needles, *, limit=400) assert by["26.8"]["presence"]["patch"]["reason"] == "deadline" assert by["26.2"]["presence"]["patch"]["reason"] == "error:RuntimeError" assert (by["26.6"]["verdict"], by["26.6"]["epistemic"]) == ("gap", "exact") + # the stage's wall is a fixed setting, so a cut is a slow read and is named + assert { + "code_index: patch_presence_unread (RuntimeError)", + "code_index: patch_presence_timed_out", + } <= set(degradations.current()) @pytest.mark.asyncio diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index 2e9a1404be3..959785d4aa4 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -26,6 +26,7 @@ from server.code.api.models_history import CodeBackportGapInput, CodeBackportGapsInput from server.code.store import backport_gaps as gr from server.core.errors import AuthInsufficientError +from server.observability import degradations from server.operations.base import Role from server.operations.registry import OPERATIONS_BY_NAME from server.settings import settings @@ -799,6 +800,7 @@ async def _hang(git_dir, branch, groups, *, timeout_s=2.0, gate=None, **kw): monkeypatch.setattr(ph, "branch_history", _hang) monkeypatch.setattr(settings, "code_backport_history_budget_ms", 50) + degradations.begin() out = await h.handle_code_backport_gap( CodeBackportGapInput( org=ORG, namespace=NS, pr_number=115670, history=True, branches=["26.6", "26.5"] @@ -808,6 +810,41 @@ async def _hang(git_dir, branch, groups, *, timeout_s=2.0, gate=None, **kw): assert by["26.6"]["presence"]["history"]["reason"] == "error:RuntimeError" assert by["26.5"]["presence"]["history"]["reason"] == "deadline" assert all(b["basis"] == "symbol" and b["epistemic"] == "lower_bound" for b in out.branches) + # the stage's wall is a fixed setting, so a cut is a slow read and is named + assert { + "git_mirror: branch_history_unread (RuntimeError)", + "git_mirror: branch_history_timed_out", + } <= set(degradations.current()) + + +@pytest.mark.asyncio +async def test_a_symbol_presence_read_cut_or_failed_is_named(monkeypatch) -> None: + import server.code.app.search_fanout as fanout + + class _Repo: + async def symbol_names_present(self, org, ns, names): + if ns == "failed": + raise RuntimeError("boom") + await asyncio.sleep(5) + return {} + + async def _authorize(org, namespaces, *, op="code.search"): + return None + + async def _as_of(repo, org, ns): + return {"commit": "head"} + + monkeypatch.setattr(fanout, "authorize", _authorize) + monkeypatch.setattr(h, "index_as_of", _as_of) + degradations.begin() + out = await h._symbol_presence("o", _Repo(), ["failed", "slow"], ["f"], 50) + assert out == { + "f": {"failed": ("unknown", "error:RuntimeError"), "slow": ("unknown", "deadline")} + } + assert degradations.current() == [ + "code_index: symbol_presence_unread (RuntimeError)", + "code_index: symbol_presence_timed_out", + ] def test_branch_refs_come_from_the_configuration(monkeypatch) -> None: diff --git a/tests/unit/test_source_fanout_renewal.py b/tests/unit/test_source_fanout_renewal.py index 7640a4ed5e2..0281b253972 100644 --- a/tests/unit/test_source_fanout_renewal.py +++ b/tests/unit/test_source_fanout_renewal.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +from dataclasses import replace from types import SimpleNamespace from unittest.mock import AsyncMock @@ -247,15 +248,10 @@ async def run(request, plan): first_renderer.render.assert_not_awaited() -async def test_a_wider_pass_the_renewed_first_pass_does_not_use_takes_its_notes_with_it( - monkeypatch, -): - """The first ranking built the wider search; the renewed first pass, its expired extra - dropped, fills the page alone, so only the first pass's notes are named.""" - from dataclasses import replace - - degradations.begin() - first, _ = result("first", noted=["knowledge: first_noted"]) +def _first_whose_extra_needs_widening(noted=()): + """A first pass that fills its page alone once its repository-docs extra leg, whose + one hit is another bot's, is dropped; `expire` drops it at the next renewal.""" + first, _ = result("first", noted=list(noted)) first.base.output.results = [hit("private-a"), hit("private-b")] extra, _ = result("extra") other = hit("extra-other", other=True) @@ -270,10 +266,24 @@ async def test_a_wider_pass_the_renewed_first_pass_does_not_use_takes_its_notes_ (), ) first.request = replace(first.request, extra=extra_request, repo_namespace="repo") + + def expire(): + first.request = replace(first.request, extra_deadline=asyncio.get_running_loop().time() - 1) + + return first, expire + + +async def test_a_wider_pass_the_renewed_first_pass_does_not_use_takes_its_notes_with_it( + monkeypatch, +): + """The first ranking built the wider search; the renewed first pass, its expired extra + dropped, fills the page alone, so only the first pass's notes are named.""" + degradations.begin() + first, expire = _first_whose_extra_needs_widening(noted=["knowledge: first_noted"]) wider, _ = result("wider", noted=["knowledge: wider_noted"]) async def run(request, plan): - first.request = replace(first.request, extra_deadline=asyncio.get_running_loop().time() - 1) + expire() return wider monkeypatch.setattr(repo_docs, "run_repo_search", run) @@ -283,6 +293,55 @@ async def run(request, plan): assert degradations.current() == ["knowledge: first_noted"] +def _widened_dropped(): + return [n for n in degradations.current() if n.startswith("knowledge: widened_hits_dropped")] + + +async def test_a_failed_eager_widening_the_renewed_first_pass_does_not_need_names_nothing( + monkeypatch, +): + degradations.begin() + first, expire = _first_whose_extra_needs_widening() + + async def run(request, plan): + expire() + raise RuntimeError("wider failed") + + monkeypatch.setattr(repo_docs, "run_repo_search", run) + with private_work(): + know = await fanout._knowledge_section(first, ReadPlan("acme", marked=True), "reader") + assert [h["source_uri"] for h in know["results"]] == ["private-a", "private-b"] + assert _widened_dropped() == [] + + +async def test_a_failed_eager_widening_the_ordinary_section_replaces_names_nothing(monkeypatch): + """The first pass is lost at its renewal: the ordinary section widens again, and that + search answers.""" + degradations.begin() + first, _ = result("first", needs_widen=True) + first.base.proofs.check.side_effect = [None, LostCorpus()] + ordinary_wider, _ = result("ordinary-wider") + run = AsyncMock(side_effect=[RuntimeError("wider failed"), ordinary_wider]) + monkeypatch.setattr(repo_docs, "run_repo_search", run) + with private_work(): + know = await fanout._knowledge_section(first, ReadPlan("acme", marked=True), "reader") + assert [h["source_uri"] for h in know["results"]] == ["private-ordinary-wider"] + assert run.await_count == 2 + assert _widened_dropped() == [] + + +async def test_a_failed_eager_widening_the_renewed_first_pass_needs_is_named(monkeypatch): + degradations.begin() + first, _ = result("first", needs_widen=True) + monkeypatch.setattr( + repo_docs, "run_repo_search", AsyncMock(side_effect=RuntimeError("wider failed")) + ) + with private_work(): + know = await fanout._knowledge_section(first, ReadPlan("acme", marked=True), "reader") + assert [h["source_uri"] for h in know["results"]] == ["private-a"] + assert len(_widened_dropped()) == 1 + + @pytest.mark.parametrize("wider_case", ["unused", "failed"]) async def test_a_wider_pass_the_ordinary_section_does_not_serve_takes_its_notes_with_it( wider_case, diff --git a/tests/unit/test_source_repo_search.py b/tests/unit/test_source_repo_search.py index 16c17955e40..52be2c2baa2 100644 --- a/tests/unit/test_source_repo_search.py +++ b/tests/unit/test_source_repo_search.py @@ -545,3 +545,38 @@ async def run(request, plan): with pytest.raises(RuntimeError, match="base failed"): await repo_docs.run_repo_search(request, source_access.ReadPlan("acme", marked=True)) assert degradations.current() == [] + + +async def _lexical_noting_search(monkeypatch): + """A repository search whose base leg noted its lexical leg dropped while it ran, then + rendered with a rerank note of its own.""" + + async def run(request, plan): + degradations.partial("knowledge", "lexical_leg_dropped", "TimeoutError") + out = KnowledgeSearchOutput(results=[hit("home:a", 0.9, "home")], embedding_model="fake") + held = degradations.hold(["rerank: input_order_kept (TimeoutError)"]) + renderer = SimpleNamespace(marked=False, render=None) + return search.CheckedSearch(out, None, renderer, [], 0, held=held) + + monkeypatch.setattr(search, "run_checked_search", run) + request = repo_docs.RepoSearchRequest( + search.SearchRequest(INPUT, ("home",), ()), None, "", asyncio.get_running_loop().time() + ) + return await repo_docs.run_repo_search(request, source_access.ReadPlan("acme")) + + +async def test_a_pass_left_out_takes_its_legs_notes_with_it(monkeypatch): + degradations.begin() + wider = await _lexical_noting_search(monkeypatch) + wider.discard() + assert degradations.current() == [] + + +async def test_a_served_pass_lists_its_legs_notes_once(monkeypatch): + degradations.begin() + degradations.partial("knowledge", "lexical_leg_dropped", "TimeoutError") + await _lexical_noting_search(monkeypatch) + assert degradations.current() == [ + "knowledge: lexical_leg_dropped (TimeoutError)", + "rerank: input_order_kept (TimeoutError)", + ] From 5240eda429d6fe5db1047e612f3997de7e66b982 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 10:34:57 +0530 Subject: [PATCH 36/47] backport: write a fix whose one branch's stage fell back A stage cut or read that failed on one branch made the nightly worker read the whole fix as fallen back: no branch got a row, FellBack was noted, and the streak built. Each such outcome is the branch's own, which its row carries (a presence reason of deadline or error:*), so the worker's fallback check now leaves out backport.BRANCH_STAGE_NOTES: the six stage notes and the history leg's patch_history_timed_out. A fix-wide note (the fix ledger, the tracker, file presence) still keeps the fix unwritten. code.backport_gap keeps listing every note. The stage notes take the error itself as their reason, so a Loom error reads as its code, and branch_presence_unread is file_presence_unread. docs/reference/http-api.md now promises what holds: degraded never leaves out a fallback the served answer used, Loom takes back the notes of the work it drops at the sites it names, and it names three cases where a note of replaced work stays. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/http-api.md | 19 ++++++--- server/code/app/backport.py | 23 ++++++++-- server/code/workers/backport_gaps.py | 8 ++-- tests/unit/test_code_backport_gaps.py | 60 +++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 12 deletions(-) diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 06b8f70ad2d..0fc3468d2e8 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -332,14 +332,23 @@ error's kind only; the full text is in the server log. store can cut a rare literal's read too, so `code.search` and `code.ask` do not cache an answer built on it, `memory.ask` stores no precedent from it, and a decision's code discovery is deferred. -- An answer replaced before it is served does not list what it recorded: a document +- `degraded` never leaves out a fallback the served answer used. It can also name one + from work the served answer replaced, which costs that answer a cache entry and hides + nothing. Loom takes back the entries of the work it drops in these places: a document search that lost access to a mirrored document mid-request and answers from its ordinary pass, and the `memory.ask` attempt discarded for the same reason, list only the served answer's entries. So does a search pass or section the answer leaves out: a - wider pass it did not need, a repository-docs leg dropped past its deadline or with the - base search that failed, an ordinary render that failed, and a `context.pack` knowledge - or memory-stack section or a `loom_search` knowledge section dropped for a failed read, - whose failure the caller names. + wider pass it did not need, with what its legs recorded, a repository-docs leg dropped + past its deadline or with the base search that failed, an ordinary render that failed, + the passages `context.pack` leaves out, and a `context.pack` knowledge or memory-stack + section or a `loom_search` knowledge section dropped for a failed read, whose failure + the caller names. Elsewhere an entry of replaced work stays, for example: + - `knowledge: widened_hits_dropped` from `loom_search`'s renewed knowledge ranking + when the ordinary section is served in its place; + - what a repository-docs leg's own legs recorded, when the leg is dropped at its + renewal, and that renewal's `knowledge: repo_docs_dropped` when the search it + belongs to is left out; + - the first pass's render entries when the wider pass is served. - Some caches keep a fallback with its entries and name them on each answer served from it, for: - `LOOM_CODE_STATUS_TTL_S`: a `code.index_status` or `code.repos` status; diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 8bc277e836f..80a15c4c6ea 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -75,6 +75,21 @@ _HISTORY_GIT_PROCS = 4 +# A branch's own stage outcome, which its row carries (a presence reason of `deadline` or +# `error:*`, not settled): the nightly worker writes such a read as it is. +BRANCH_STAGE_NOTES = frozenset( + { + "code_index: symbol_presence_timed_out", + "code_index: symbol_presence_unread", + "code_index: patch_presence_timed_out", + "code_index: patch_presence_unread", + "git_mirror: branch_history_timed_out", + "git_mirror: branch_history_unread", + "git_mirror: patch_history_timed_out", # one git command of a branch's history read + } +) + + async def _settle(tasks: Any, wall_ms: int) -> set[asyncio.Future[Any]]: """Wait for per-namespace `tasks` up to the wall, cancel (and reap) the ones still running, and return them. A cancel of the caller cancels every task too: @@ -271,7 +286,7 @@ async def one(ns: str) -> tuple[dict[str, list[str]], dict[str, Any]]: continue err = t.exception() if err is not None: - degradations.partial("code_index", "symbol_presence_unread", type(err).__name__) + degradations.partial("code_index", "symbol_presence_unread", err) logger.debug("backport_gap: presence read failed on %s: %s", ns, err) for s in symbols: result[s][ns] = ("unknown", f"error:{type(err).__name__}") @@ -300,7 +315,7 @@ async def _file_presence( index_as_of(repo, org, ns), ) except Exception as e: # noqa: BLE001 — one branch's read, disclosed as unknown - degradations.partial("code_index", "branch_presence_unread", e) + degradations.partial("code_index", "file_presence_unread", e) logger.debug("backport_gap: file presence failed on %s: %s", ns, e) return [], [], False return ( @@ -382,7 +397,7 @@ async def one(ns: str) -> pp.PatchPresence: out[ns] = pp.PatchPresence(reason="deadline") elif t.exception() is not None: err = t.exception() - degradations.partial("code_index", "patch_presence_unread", type(err).__name__) + degradations.partial("code_index", "patch_presence_unread", err) logger.debug("backport_gap: patch read failed on %s: %s", ns, err) out[ns] = pp.PatchPresence(reason=f"error:{type(err).__name__}") else: @@ -590,7 +605,7 @@ async def _history_stage( out[ns] = ph.HistoryPresence(reason="deadline") elif t.exception() is not None: err = t.exception() - degradations.partial("git_mirror", "branch_history_unread", type(err).__name__) + degradations.partial("git_mirror", "branch_history_unread", err) logger.debug("backport_gap: history read failed on %s: %s", ns, err) out[ns] = ph.HistoryPresence(reason=f"error:{type(err).__name__}") else: diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index aa71c70c681..a0b5f0be395 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -247,8 +247,9 @@ async def collect_fixes( async def _read_fix(cfg: Any, pr: int, runner: Any) -> tuple[Any, list[str]]: - """The fix's composed read, and the notes it made apart from the pass's.""" - from server.code.app.backport import BackportGapRequest + """The fix's composed read, and the notes it made apart from the pass's, except a + branch's own stage outcome, which that branch's row carries.""" + from server.code.app.backport import BRANCH_STAGE_NOTES, BackportGapRequest with degradations.scoped(): out = await runner( @@ -262,7 +263,8 @@ async def _read_fix(cfg: Any, pr: int, runner: Any) -> tuple[Any, list[str]]: trace=False, ) ) - return out, degradations.current() + noted = degradations.current() + return out, [n for n in noted if n.split(" (", 1)[0] not in BRANCH_STAGE_NOTES] async def compute_fix( diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index 959785d4aa4..9577793488a 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -817,6 +817,66 @@ async def _hang(git_dir, branch, groups, *, timeout_s=2.0, gate=None, **kw): } <= set(degradations.current()) +@pytest.mark.asyncio +async def test_a_stage_cut_on_one_branch_still_writes_every_branch_row(wired, monkeypatch) -> None: + """The nightly pass, through the composed read: one branch's history stage runs past + its wall. That branch's row carries the cut as its floor, so the fix is written whole + and the pass notes no failure.""" + from types import SimpleNamespace + + import server.code.domain.index.repos as repos + from server.workers import pass_context + + three = { + "code-clickhouse-26-4": "26.4", + "code-clickhouse-26-5": "26.5", + "code-clickhouse-26-6": "26.6", + } + monkeypatch.setattr( + repos, + "configured_repos", + lambda: [_Cfg(NS, "master"), *(_Cfg(n, v) for n, v in three.items())], + ) + answered = ph.branch_history + + async def _one_slow(git_dir, branch, groups, **kw): + if branch == "26.5": + await asyncio.sleep(5) + return await answered(git_dir, branch, groups, **kw) + + monkeypatch.setattr(ph, "branch_history", _one_slow) + monkeypatch.setattr(settings, "code_backport_history_budget_ms", 50) + ctx = pass_context.begin("code_backport_gaps") + degradations.begin() + result = wk.BackportGapsResult() + try: + rows = await wk.compute_fix( + SimpleNamespace(org=ORG, namespace=NS), + 115670, + {}, + runner=h.run_backport_gap, + result=result, + stamp=NOW, + version=1, + ) + finally: + pass_context.clear() + by = {r["branch"]: r for r in rows} + assert sorted(by) == ["26.4", "26.5", "26.6"] + assert (by["26.6"]["verdict"], by["26.6"]["epistemic"], by["26.6"]["basis"]) == ( + "gap", + "exact", + "history", + ) + assert (by["26.5"]["basis"], by["26.5"]["epistemic"], by["26.5"]["settled"]) == ( + "symbol", + "lower_bound", + 0, + ) + assert result.fixes_computed == 1 and result.fixes_unavailable == 0 + assert ctx.count == 0 + + @pytest.mark.asyncio async def test_a_symbol_presence_read_cut_or_failed_is_named(monkeypatch) -> None: import server.code.app.search_fanout as fanout From 73b3f68425c65ed0b86d7f7d22f5ef6652bd1e73 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 11:00:19 +0530 Subject: [PATCH 37/47] backport: every per-branch note leaves the fix written Two more per-branch history notes made the nightly worker leave the whole fix unwritten: git_mirror: patch_history_unread (a branch's tip read raised) and patch_history_line_unread (a line probe raised). Each leaves that branch's history reason error: and its row at the symbol floor. git_mirror: lag_unknown is one branch's lag, which no row stores. BRANCH_STAGE_NOTES holds all three now. file_presence_unread stays out: that branch's row would read no_index, not error:*. A worker test drives every member of the set through compute_fix and the composed read (the real stage where cheap, else a branch read that makes the note) and checks that every branch's row is written; another checks that a failed file presence read still leaves the fix unwritten with FellBack. The worker's docstrings name the exception. docs/reference/http-api.md: Loom never takes back an entry of a fallback the served answer used. The places it lists take back their renders' entries; only loom_search's repository search takes back its legs' entries too, when the whole search is dropped, and those leg entries are among the examples that stay. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/http-api.md | 29 +++-- server/code/app/backport.py | 8 +- server/code/workers/backport_gaps.py | 7 +- tests/unit/test_code_backport_gaps.py | 173 ++++++++++++++++++++++---- 4 files changed, 181 insertions(+), 36 deletions(-) diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 0fc3468d2e8..d10766e9ccc 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -332,17 +332,24 @@ error's kind only; the full text is in the server log. store can cut a rare literal's read too, so `code.search` and `code.ask` do not cache an answer built on it, `memory.ask` stores no precedent from it, and a decision's code discovery is deferred. -- `degraded` never leaves out a fallback the served answer used. It can also name one - from work the served answer replaced, which costs that answer a cache entry and hides - nothing. Loom takes back the entries of the work it drops in these places: a document - search that lost access to a mirrored document mid-request and answers from its - ordinary pass, and the `memory.ask` attempt discarded for the same reason, list only - the served answer's entries. So does a search pass or section the answer leaves out: a - wider pass it did not need, with what its legs recorded, a repository-docs leg dropped - past its deadline or with the base search that failed, an ordinary render that failed, - the passages `context.pack` leaves out, and a `context.pack` knowledge or memory-stack - section or a `loom_search` knowledge section dropped for a failed read, whose failure - the caller names. Elsewhere an entry of replaced work stays, for example: +- Loom never takes back an entry of a fallback the served answer used. `degraded` can + also name one from work the served answer replaced, which costs that answer a cache + entry and hides nothing. Loom takes back entries of the work it drops here: + - a document search that lost access to a mirrored document mid-request and answers + from its ordinary pass lists only the served render's entries, and the `memory.ask` + attempt discarded for the same reason takes back all of its own; + - a search pass or section the answer leaves out takes back its renders' entries: a + wider pass it did not need, a repository-docs leg dropped past its deadline, an + ordinary render that failed, and a `context.pack` knowledge section dropped for a + failed read, whose failure the caller names; + - a `context.pack` memory-stack section dropped for a failed read takes back all of + its build's entries; + - `loom_search`'s repository search also takes back what its legs recorded, as one + group, when the whole search is dropped: a wider pass the section did not need, a + search whose base search failed, and the knowledge section dropped for a failed read. +- Elsewhere an entry of replaced work stays, for example: + - what a dropped pass's legs recorded before it rendered, such as + `knowledge: lexical_leg_dropped`, unless the whole repository search is dropped; - `knowledge: widened_hits_dropped` from `loom_search`'s renewed knowledge ranking when the ordinary section is served in its place; - what a repository-docs leg's own legs recorded, when the leg is dropped at its diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 80a15c4c6ea..dba9e8550b6 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -75,8 +75,9 @@ _HISTORY_GIT_PROCS = 4 -# A branch's own stage outcome, which its row carries (a presence reason of `deadline` or -# `error:*`, not settled): the nightly worker writes such a read as it is. +# A branch's own read outcome: its row carries it (a presence reason of `deadline` or +# `error:*`, not settled) or stores nothing of it (the lag), so the nightly worker writes +# such a read as it is. Not `file_presence_unread`: that row would read `no_index`. BRANCH_STAGE_NOTES = frozenset( { "code_index: symbol_presence_timed_out", @@ -86,6 +87,9 @@ "git_mirror: branch_history_timed_out", "git_mirror: branch_history_unread", "git_mirror: patch_history_timed_out", # one git command of a branch's history read + "git_mirror: patch_history_unread", # a branch's tip read raised: `error:*` + "git_mirror: patch_history_line_unread", # a line probe raised: decided without it + "git_mirror: lag_unknown", # a branch's lag, which no row stores } ) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index a0b5f0be395..4ae6322c286 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -12,7 +12,9 @@ is skipped until its window closes. The leg stops cleanly at `budget_s` and says where; a QA miss on one fix, or a read its answer fell back on, writes nothing for it (a night of `unknown` rows would overwrite a day of -verdicts) and the next fix runs. +verdicts) and the next fix runs. One branch's own stage outcome +(`backport.BRANCH_STAGE_NOTES`) is no such read: its row carries it, a `deadline` or +`error:*` floor, and replaces that branch's previous verdict. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ @@ -281,7 +283,8 @@ async def compute_fix( """One fix's composed read → its table rows; [] when the fix could not be read, its tracker record did not answer, or a read it fell back on left a smaller answer (a night of unknowns must not overwrite verdicts), counted on - the result either way. A read that fell back is retried once while the pass is + the result either way. One branch's own stage outcome does not count: its row + carries it and replaces that branch's previous verdict. A read that fell back is retried once while the pass is before `deadline` (on the monotonic clock; None: no bound); one that falls back again is a failure of the pass (`note_failure`), so a fix that falls back every night builds the worker's failure streak.""" diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index 9577793488a..deaeb37d244 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -817,35 +817,128 @@ async def _hang(git_dir, branch, groups, *, timeout_s=2.0, gate=None, **kw): } <= set(degradations.current()) -@pytest.mark.asyncio -async def test_a_stage_cut_on_one_branch_still_writes_every_branch_row(wired, monkeypatch) -> None: - """The nightly pass, through the composed read: one branch's history stage runs past - its wall. That branch's row carries the cut as its floor, so the fix is written whole - and the pass notes no failure.""" +_CUT_NS, _CUT = "code-clickhouse-26-5", "26.5" + + +async def _slow(*_a: Any, **_k: Any) -> Any: + await asyncio.sleep(5) + + +async def _raises(*_a: Any, **_k: Any) -> Any: + raise RuntimeError("boom") + + +def _on_cut_branch(monkeypatch, repo, name, then) -> None: + """`repo.` answers as before on every branch but the cut one, where `then` runs.""" + original = getattr(repo, name) + + async def read(org, ns, *a, **k): + return await (then() if ns == _CUT_NS else original(org, ns, *a, **k)) + + monkeypatch.setattr(repo, name, read) + + +def _history_on_cut_branch(monkeypatch, then) -> None: + answered = ph.branch_history + + async def read(git_dir, branch, groups, **kw): + fn = then if branch == _CUT else answered + return await fn(git_dir, branch, groups, **kw) + + monkeypatch.setattr(ph, "branch_history", read) + + +async def _git_timed_out(*_a: Any, **_k: Any) -> Any: + # what `_git_rc` notes for a git command past its bound; the leg reads it as `deadline` + degradations.partial("git_mirror", "patch_history_timed_out", TimeoutError()) + return ph.HistoryPresence(reason="deadline") + + +async def _tip_unread(*_a: Any, **_k: Any) -> Any: + hp = ph.HistoryPresence() + hp.reason = ph._unread(OSError("tip")) + return hp + + +def _line_unread(monkeypatch, wired) -> None: + answered = ph.branch_history + + async def read(git_dir, branch, groups, **kw): + hp = await answered(git_dir, branch, groups, **kw) + hp.lines.append(ph._unread_line(SRC, "return x;", OSError("line"))) + return hp + + _history_on_cut_branch(monkeypatch, read) + + +def _lag_unknown(monkeypatch, wired) -> None: + as_of = h.index_as_of + + async def read(repo, org, ns): + if ns == _CUT_NS: + degradations.partial("git_mirror", "lag_unknown", "git rev-list failed") + return await as_of(repo, org, ns) + + monkeypatch.setattr(h, "index_as_of", read) + + +def _budget(monkeypatch, name) -> None: + monkeypatch.setattr(settings, name, 50) + + +# How one branch's read produces each per-branch note, through the real stage where cheap. +_BRANCH_STAGE_CASES = { + "code_index: symbol_presence_timed_out": lambda mp, w: ( + _budget(mp, "code_backport_presence_budget_ms"), + _on_cut_branch(mp, w["repo"], "symbol_names_present", _slow), + ), + "code_index: symbol_presence_unread": lambda mp, w: _on_cut_branch( + mp, w["repo"], "symbol_names_present", _raises + ), + "code_index: patch_presence_timed_out": lambda mp, w: ( + _budget(mp, "code_backport_patch_budget_ms"), + _on_cut_branch(mp, w["repo"], "chunks_for_patch", _slow), + ), + "code_index: patch_presence_unread": lambda mp, w: _on_cut_branch( + mp, w["repo"], "chunks_for_patch", _raises + ), + "git_mirror: branch_history_timed_out": lambda mp, w: ( + _budget(mp, "code_backport_history_budget_ms"), + _history_on_cut_branch(mp, _slow), + ), + "git_mirror: branch_history_unread": lambda mp, w: _history_on_cut_branch(mp, _raises), + "git_mirror: patch_history_timed_out": lambda mp, w: _history_on_cut_branch(mp, _git_timed_out), + "git_mirror: patch_history_unread": lambda mp, w: _history_on_cut_branch(mp, _tip_unread), + "git_mirror: patch_history_line_unread": _line_unread, + "git_mirror: lag_unknown": _lag_unknown, +} + + +def test_every_per_branch_stage_note_has_a_worker_case() -> None: + assert set(_BRANCH_STAGE_CASES) == h.BRANCH_STAGE_NOTES + + +async def _worker_pass(monkeypatch) -> tuple[list[Any], Any, Any, list[str]]: + """One nightly `compute_fix` over three branches through the composed read: its rows, + result, pass context, and the notes the read made.""" from types import SimpleNamespace import server.code.domain.index.repos as repos from server.workers import pass_context - three = { - "code-clickhouse-26-4": "26.4", - "code-clickhouse-26-5": "26.5", - "code-clickhouse-26-6": "26.6", - } + three = {"code-clickhouse-26-4": "26.4", _CUT_NS: _CUT, "code-clickhouse-26-6": "26.6"} monkeypatch.setattr( repos, "configured_repos", lambda: [_Cfg(NS, "master"), *(_Cfg(n, v) for n, v in three.items())], ) - answered = ph.branch_history + seen: list[str] = [] - async def _one_slow(git_dir, branch, groups, **kw): - if branch == "26.5": - await asyncio.sleep(5) - return await answered(git_dir, branch, groups, **kw) + async def runner(req): + out = await h.run_backport_gap(req) + seen.extend(degradations.current()) + return out - monkeypatch.setattr(ph, "branch_history", _one_slow) - monkeypatch.setattr(settings, "code_backport_history_budget_ms", 50) ctx = pass_context.begin("code_backport_gaps") degradations.begin() result = wk.BackportGapsResult() @@ -854,15 +947,36 @@ async def _one_slow(git_dir, branch, groups, **kw): SimpleNamespace(org=ORG, namespace=NS), 115670, {}, - runner=h.run_backport_gap, + runner=runner, result=result, stamp=NOW, version=1, ) finally: pass_context.clear() + return rows, result, ctx, seen + + +@pytest.mark.asyncio +@pytest.mark.parametrize("note", sorted(_BRANCH_STAGE_CASES)) +async def test_one_branchs_stage_note_still_writes_every_branch_row( + wired, monkeypatch, note +) -> None: + """One branch's read makes a per-branch note: that branch's row carries the outcome (or + stores nothing of it), so the fix is written whole and the pass notes no failure.""" + _BRANCH_STAGE_CASES[note](monkeypatch, wired) + rows, result, ctx, seen = await _worker_pass(monkeypatch) + assert note in {n.split(" (", 1)[0] for n in seen} + assert sorted(r["branch"] for r in rows) == ["26.4", "26.5", "26.6"] + assert result.fixes_computed == 1 and result.fixes_unavailable == 0 + assert ctx.count == 0 + + +@pytest.mark.asyncio +async def test_a_branch_history_cut_writes_that_branch_at_its_floor(wired, monkeypatch) -> None: + _BRANCH_STAGE_CASES["git_mirror: branch_history_timed_out"](monkeypatch, wired) + rows, _, _, _ = await _worker_pass(monkeypatch) by = {r["branch"]: r for r in rows} - assert sorted(by) == ["26.4", "26.5", "26.6"] assert (by["26.6"]["verdict"], by["26.6"]["epistemic"], by["26.6"]["basis"]) == ( "gap", "exact", @@ -873,8 +987,25 @@ async def _one_slow(git_dir, branch, groups, **kw): "lower_bound", 0, ) - assert result.fixes_computed == 1 and result.fixes_unavailable == 0 - assert ctx.count == 0 + + +@pytest.mark.asyncio +async def test_a_branch_file_presence_read_that_failed_leaves_the_fix_unwritten( + wired, monkeypatch +) -> None: + """A fix with files and no symbols reads each branch's file presence. One that fails + would read as `no_index`, not `error:*`, so the fix keeps last night's rows.""" + + class _FilesOnly(_Source): + async def pr_change(self, org, ns, n): + return {**(await super().pr_change(org, ns, n)), "hunk_contexts": []} + + wired["src"] = _FilesOnly() + _on_cut_branch(monkeypatch, wired["repo"], "live_paths_present", _raises) + rows, result, ctx, seen = await _worker_pass(monkeypatch) + assert "code_index: file_presence_unread (RuntimeError)" in seen + assert rows == [] and result.fixes_unavailable == 1 + assert [f[:2] for f in ctx.failures] == [("code_backport_gaps:#115670", "FellBack")] @pytest.mark.asyncio From 67cfa197ba01ad524363f254c2b9e2444fa6ac09 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 11:04:24 +0530 Subject: [PATCH 38/47] backport: wrap compute_fix's docstring at the line limit Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/workers/backport_gaps.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index 4ae6322c286..70247b522e8 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -284,10 +284,10 @@ async def compute_fix( read, its tracker record did not answer, or a read it fell back on left a smaller answer (a night of unknowns must not overwrite verdicts), counted on the result either way. One branch's own stage outcome does not count: its row - carries it and replaces that branch's previous verdict. A read that fell back is retried once while the pass is - before `deadline` (on the monotonic clock; None: no bound); one that falls back again - is a failure of the pass (`note_failure`), so a fix that falls back every night - builds the worker's failure streak.""" + carries it and replaces that branch's previous verdict. A read that fell back is + retried once while the pass is before `deadline` (on the monotonic clock; None: no + bound); one that falls back again is a failure of the pass (`note_failure`), so a + fix that falls back every night builds the worker's failure streak.""" try: out, noted = await _read_fix(cfg, pr, runner) if noted and (deadline is None or time.monotonic() < deadline): From f8f1c1a00193360ca72fe873946e4c06997c2a91 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 11:36:43 +0530 Subject: [PATCH 39/47] backport: name a mirror git cannot read and a refused line probe A mirror git cannot read (`rev-parse` exits 128, as for an empty directory or none at all) answered `no_branch_ref` with no note, and a `git log -S` probe git refused answered `error:git` with no note. Only the ref's miss (exit 1) is `no_branch_ref` now; any other exit raises `MirrorReadError`, so the history stage names `branch_history_unread`. A probe exit other than 0 raises too, so the leg names `patch_history_line_unread`. `BRANCH_STAGE_NOTES` is `BRANCH_NOTES`, since an unknown lag is no stage outcome. Its comment and the worker's docstrings say what each member's row stores: a symbol-presence cut or failure stores `unknown` with `deadline` or `error:*`, a patch or history one the symbol floor, unsettled, and an unknown lag changes no row. They name the per-branch notes left out of the set: `file_presence_unread`, `backport_ledger_dropped` and `as_of_unread`. A line probe that raised leaves the branch undecided unless another probe names the pick. `docs/reference/http-api.md` says a document search that lost a mirrored document takes back the lost render's entries, and the comment on the wider pass's `discard()` says its legs' notes go too. Tests: a missing ref is still `no_branch_ref`; an empty or absent mirror raises; an empty mirror through the nightly worker names `branch_history_unread` and writes every branch's row; a refused probe on either leg is named; a branch whose ledger read failed leaves the fix unwritten with `FellBack`; and an unknown lag writes the rows written without it. Each fails without its change. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/reference/http-api.md | 2 +- server/code/app/backport.py | 15 ++- server/code/workers/backport_gaps.py | 17 ++-- server/memory/app/loom_search/fanout.py | 2 +- server/tracker/app/patch_history.py | 27 ++++-- tests/unit/test_code_backport_gaps.py | 118 ++++++++++++++++++++---- 6 files changed, 136 insertions(+), 45 deletions(-) diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index d10766e9ccc..3bbaebda035 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -336,7 +336,7 @@ error's kind only; the full text is in the server log. also name one from work the served answer replaced, which costs that answer a cache entry and hides nothing. Loom takes back entries of the work it drops here: - a document search that lost access to a mirrored document mid-request and answers - from its ordinary pass lists only the served render's entries, and the `memory.ask` + from its ordinary pass takes back the lost render's entries, and the `memory.ask` attempt discarded for the same reason takes back all of its own; - a search pass or section the answer leaves out takes back its renders' entries: a wider pass it did not need, a repository-docs leg dropped past its deadline, an diff --git a/server/code/app/backport.py b/server/code/app/backport.py index dba9e8550b6..61351c8cb63 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -75,10 +75,13 @@ _HISTORY_GIT_PROCS = 4 -# A branch's own read outcome: its row carries it (a presence reason of `deadline` or -# `error:*`, not settled) or stores nothing of it (the lag), so the nightly worker writes -# such a read as it is. Not `file_presence_unread`: that row would read `no_index`. -BRANCH_STAGE_NOTES = frozenset( +# A note about one branch's read whose row claims no more than the read: a symbol-presence +# cut or failure stores `unknown` with `deadline` or `error:*`, a patch or history one the +# symbol floor (unsettled, no reason), and no row stores the lag. So the nightly worker +# writes such a read as it is. Left out, so the fix keeps its previous rows: +# `file_presence_unread` (the row would read `no_index`), `backport_ledger_dropped` (`gap` +# where the ledger holds the backport) and `as_of_unread` (`unknown` or `no_index`). +BRANCH_NOTES = frozenset( { "code_index: symbol_presence_timed_out", "code_index: symbol_presence_unread", @@ -88,7 +91,9 @@ "git_mirror: branch_history_unread", "git_mirror: patch_history_timed_out", # one git command of a branch's history read "git_mirror: patch_history_unread", # a branch's tip read raised: `error:*` - "git_mirror: patch_history_line_unread", # a line probe raised: decided without it + # a line probe raised: the branch stays undecided (`error:*`) unless another probe + # names the pick + "git_mirror: patch_history_line_unread", "git_mirror: lag_unknown", # a branch's lag, which no row stores } ) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index 70247b522e8..9d6555a04cd 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -12,9 +12,10 @@ is skipped until its window closes. The leg stops cleanly at `budget_s` and says where; a QA miss on one fix, or a read its answer fell back on, writes nothing for it (a night of `unknown` rows would overwrite a day of -verdicts) and the next fix runs. One branch's own stage outcome -(`backport.BRANCH_STAGE_NOTES`) is no such read: its row carries it, a `deadline` or -`error:*` floor, and replaces that branch's previous verdict. +verdicts) and the next fix runs. A note about one branch's read +(`backport.BRANCH_NOTES`) is no such read: that branch's row claims no more than the +read (`unknown` with `deadline` or `error:*` for symbol presence, the symbol floor for +a patch or history read, unchanged for an unknown lag) and replaces its previous verdict. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ @@ -250,8 +251,8 @@ async def collect_fixes( async def _read_fix(cfg: Any, pr: int, runner: Any) -> tuple[Any, list[str]]: """The fix's composed read, and the notes it made apart from the pass's, except a - branch's own stage outcome, which that branch's row carries.""" - from server.code.app.backport import BRANCH_STAGE_NOTES, BackportGapRequest + note about one branch's read (`BRANCH_NOTES`), whose row claims no more than it.""" + from server.code.app.backport import BRANCH_NOTES, BackportGapRequest with degradations.scoped(): out = await runner( @@ -266,7 +267,7 @@ async def _read_fix(cfg: Any, pr: int, runner: Any) -> tuple[Any, list[str]]: ) ) noted = degradations.current() - return out, [n for n in noted if n.split(" (", 1)[0] not in BRANCH_STAGE_NOTES] + return out, [n for n in noted if n.split(" (", 1)[0] not in BRANCH_NOTES] async def compute_fix( @@ -283,8 +284,8 @@ async def compute_fix( """One fix's composed read → its table rows; [] when the fix could not be read, its tracker record did not answer, or a read it fell back on left a smaller answer (a night of unknowns must not overwrite verdicts), counted on - the result either way. One branch's own stage outcome does not count: its row - carries it and replaces that branch's previous verdict. A read that fell back is + the result either way. A note about one branch's read (`BRANCH_NOTES`) does not + count: that branch's row is written as the read left it. A read that fell back is retried once while the pass is before `deadline` (on the monotonic clock; None: no bound); one that falls back again is a failure of the pass (`note_failure`), so a fix that falls back every night builds the worker's failure streak.""" diff --git a/server/memory/app/loom_search/fanout.py b/server/memory/app/loom_search/fanout.py index b584ffccd8a..fc78dcc896e 100644 --- a/server/memory/app/loom_search/fanout.py +++ b/server/memory/app/loom_search/fanout.py @@ -262,7 +262,7 @@ async def expanded(k: int) -> KnowledgeSearchOutput: first.output, expanded, agent, int(first.request.base.input.top_k) ) if wider is not None and not served_wider: - wider.discard() # unused or failed: its renders' notes go with it + wider.discard() # unused or failed: its legs' notes go with it, its renders' too return section diff --git a/server/tracker/app/patch_history.py b/server/tracker/app/patch_history.py index 56266427421..bff10d0697e 100644 --- a/server/tracker/app/patch_history.py +++ b/server/tracker/app/patch_history.py @@ -287,14 +287,15 @@ async def line_history( ) -> LineHistory: """One removed line the tip lacks: never in the branch's first-parent history for that path (`never`), or there once and removed since - (`removed`, with the commit that changed its count).""" + (`removed`, with the commit that changed its count). A refused `git log` + raises `MirrorReadError`.""" if timeout_s is None: timeout_s = settings.tracker_patch_line_timeout_s rc, sha, _, _ = await _last_count_change(git_dir, branch, path, norm, timeout_s=timeout_s) if rc == -1: return LineHistory(path, norm, "deadline") - if rc != 0: - return LineHistory(path, norm, "error:git") + if rc != 0: # `log -S` finding nothing exits 0 + raise MirrorReadError(f"git log exited {rc} for {path}") return LineHistory(path, norm, REMOVED if sha else NEVER, commit=sha[:12]) @@ -321,7 +322,8 @@ async def line_origin( ) -> LineHistory: """One added line the tip HAS: the commit that brought it, and whether that commit names the fix (`picked`) or not (`added`: the line may be - generic, or the pick was squashed into something unnamed).""" + generic, or the pick was squashed into something unnamed). A refused + `git log` raises `MirrorReadError`.""" if timeout_s is None: timeout_s = settings.tracker_patch_line_timeout_s rc, sha, subject, body = await _last_count_change( @@ -333,22 +335,26 @@ async def line_origin( ) if rc == -1: return LineHistory(path, norm, "deadline") - if rc != 0 or not sha: - return LineHistory(path, norm, "error:git" if rc != 0 else NEVER) + if rc != 0: + raise MirrorReadError(f"git log exited {rc} for {path}") + if not sha: + return LineHistory(path, norm, NEVER) state = PICKED if names_fix(subject, body, pr_number=pr_number, merge_sha=merge_sha) else ADDED return LineHistory(path, norm, state, commit=sha[:12], subject=subject.strip()) async def _unreadable_ref(git_dir: str, branch: str, *, timeout_s: float) -> str: """Why `branch` has no tip to read ("no_branch_ref", "deadline"), or "" when it - does. A path read against a ref the mirror lacks, or a mirror that is not - there, fails like any other read, so only a resolved tip may read as - `path_absent`.""" + does. A path read against a ref the mirror lacks fails like any other read, + so only a resolved tip may read as `path_absent`. Only the ref's miss (exit + 1) is `no_branch_ref`; a mirror git cannot read raises `MirrorReadError`.""" if not branch or not git_dir: return "no_branch_ref" rc, _ = await _git_rc( git_dir, "rev-parse", "--verify", "-q", f"{branch}^{{commit}}", timeout_s=timeout_s ) + if rc not in (0, -1, 1): + raise MirrorReadError(f"git rev-parse exited {rc} for {branch}") return "" if rc == 0 else "deadline" if rc == -1 else "no_branch_ref" @@ -459,7 +465,8 @@ def _unread(error: BaseException) -> str: def _unread_line(path: str, line: str, error: BaseException) -> LineHistory: - """A line probe that raised: decided without it, and named in `degraded`.""" + """A line probe that raised: the branch stays undecided (`error:*`) unless + another probe names the pick, and the probe is named in `degraded`.""" degradations.partial("git_mirror", "patch_history_line_unread", error) return LineHistory(path, line, f"error:{type(error).__name__}") diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index deaeb37d244..e9b3b5a4cd7 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -553,14 +553,50 @@ async def test_branch_history_decides_from_the_tip_then_the_history(mirror) -> N @pytest.mark.asyncio -async def test_a_ref_or_mirror_that_is_not_there_is_never_path_absent(mirror) -> None: - """A branch the mirror has not fetched, or no mirror at all, reads nothing: no - verdict, never `not_affected` for paths nobody looked at.""" +async def test_a_ref_or_mirror_that_is_not_there_is_never_path_absent(mirror, tmp_path) -> None: + """A branch the mirror has not fetched reads nothing: no verdict, never + `not_affected` for paths nobody looked at. A mirror git cannot read (none there, + or an empty directory) is a failed read, not a missing ref.""" git_dir, branch = mirror groups = _mirror_groups([" return x;", "int keep_me(int x)"], ["a b c d"]) - for gd, br in [(git_dir, "no-such-branch"), ("/nonexistent/mirror.git", branch)]: - hp = await ph.branch_history(gd, br, groups) - assert (hp.verdict, hp.reason, hp.paths_absent) == ("", "no_branch_ref", 0), (gd, br) + hp = await ph.branch_history(git_dir, "no-such-branch", groups) + assert (hp.verdict, hp.reason, hp.paths_absent) == ("", "no_branch_ref", 0) + (tmp_path / "empty").mkdir() + for gd in ("/nonexistent/mirror.git", str(tmp_path / "empty")): + with pytest.raises(ph.MirrorReadError): + await ph.branch_history(gd, branch, groups) + + +@pytest.mark.asyncio +async def test_a_refused_line_probe_is_named(mirror, monkeypatch) -> None: + """`git log -S` exits 0 when no commit matches; any other exit is git refusing the + read, which the leg names and does not decide on.""" + git_dir, branch = mirror + real = ph._git_rc + + async def _log_refused(gd, *args, timeout_s): + if args and args[0] == "log": + return 128, "" + return await real(gd, *args, timeout_s=timeout_s) + + monkeypatch.setattr(ph, "_git_rc", _log_refused) + with pytest.raises(ph.MirrorReadError): + await ph.line_history(git_dir, branch, "a.cpp", "return x;") + with pytest.raises(ph.MirrorReadError): + await ph.line_origin(git_dir, branch, "a.cpp", "return x;", pr_number=99, merge_sha="") + degradations.begin() + removed_leg = _mirror_groups( + [" auto never_a = 1;", " auto never_b = 2;"], + [" auto also_absent = 3;", " auto and_this = 4;"], + ) + added_leg = _mirror_groups( + [" auto never_a = 1;"], [" int picked_line = 7;", " return x;"] + ) + for groups in (removed_leg, added_leg): + hp = await ph.branch_history(git_dir, branch, groups, pr_number=99) + assert hp.verdict == "" and hp.reason == "error:MirrorReadError" + assert hp.lines and {x.state for x in hp.lines} == {"error:MirrorReadError"} + assert degradations.current() == ["git_mirror: patch_history_line_unread (MirrorReadError)"] @pytest.mark.asyncio @@ -818,6 +854,7 @@ async def _hang(git_dir, branch, groups, *, timeout_s=2.0, gate=None, **kw): _CUT_NS, _CUT = "code-clickhouse-26-5", "26.5" +_BRANCH_HISTORY = ph.branch_history # the real read, which `wired` replaces async def _slow(*_a: Any, **_k: Any) -> Any: @@ -875,9 +912,10 @@ def _lag_unknown(monkeypatch, wired) -> None: as_of = h.index_as_of async def read(repo, org, ns): - if ns == _CUT_NS: - degradations.partial("git_mirror", "lag_unknown", "git rev-list failed") - return await as_of(repo, org, ns) + if ns != _CUT_NS: + return await as_of(repo, org, ns) + degradations.partial("git_mirror", "lag_unknown", "git rev-list failed") + return {**(await as_of(repo, org, ns)), "lag_commits": -1, "status": "unknown"} monkeypatch.setattr(h, "index_as_of", read) @@ -887,7 +925,7 @@ def _budget(monkeypatch, name) -> None: # How one branch's read produces each per-branch note, through the real stage where cheap. -_BRANCH_STAGE_CASES = { +_BRANCH_CASES = { "code_index: symbol_presence_timed_out": lambda mp, w: ( _budget(mp, "code_backport_presence_budget_ms"), _on_cut_branch(mp, w["repo"], "symbol_names_present", _slow), @@ -914,8 +952,8 @@ def _budget(monkeypatch, name) -> None: } -def test_every_per_branch_stage_note_has_a_worker_case() -> None: - assert set(_BRANCH_STAGE_CASES) == h.BRANCH_STAGE_NOTES +def test_every_per_branch_note_has_a_worker_case() -> None: + assert set(_BRANCH_CASES) == h.BRANCH_NOTES async def _worker_pass(monkeypatch) -> tuple[list[Any], Any, Any, list[str]]: @@ -958,13 +996,11 @@ async def runner(req): @pytest.mark.asyncio -@pytest.mark.parametrize("note", sorted(_BRANCH_STAGE_CASES)) -async def test_one_branchs_stage_note_still_writes_every_branch_row( - wired, monkeypatch, note -) -> None: - """One branch's read makes a per-branch note: that branch's row carries the outcome (or - stores nothing of it), so the fix is written whole and the pass notes no failure.""" - _BRANCH_STAGE_CASES[note](monkeypatch, wired) +@pytest.mark.parametrize("note", sorted(_BRANCH_CASES)) +async def test_one_branchs_note_still_writes_every_branch_row(wired, monkeypatch, note) -> None: + """One branch's read makes a per-branch note: that branch's row claims no more than the + read, so the fix is written whole and the pass notes no failure.""" + _BRANCH_CASES[note](monkeypatch, wired) rows, result, ctx, seen = await _worker_pass(monkeypatch) assert note in {n.split(" (", 1)[0] for n in seen} assert sorted(r["branch"] for r in rows) == ["26.4", "26.5", "26.6"] @@ -974,7 +1010,7 @@ async def test_one_branchs_stage_note_still_writes_every_branch_row( @pytest.mark.asyncio async def test_a_branch_history_cut_writes_that_branch_at_its_floor(wired, monkeypatch) -> None: - _BRANCH_STAGE_CASES["git_mirror: branch_history_timed_out"](monkeypatch, wired) + _BRANCH_CASES["git_mirror: branch_history_timed_out"](monkeypatch, wired) rows, _, _, _ = await _worker_pass(monkeypatch) by = {r["branch"]: r for r in rows} assert (by["26.6"]["verdict"], by["26.6"]["epistemic"], by["26.6"]["basis"]) == ( @@ -1008,6 +1044,48 @@ async def pr_change(self, org, ns, n): assert [f[:2] for f in ctx.failures] == [("code_backport_gaps:#115670", "FellBack")] +@pytest.mark.asyncio +async def test_a_branch_ledger_read_that_failed_leaves_the_fix_unwritten( + wired, monkeypatch +) -> None: + """Without the ledger's backport PRs a branch could read `gap` where it holds the + backport, so the fix keeps last night's rows.""" + _on_cut_branch(monkeypatch, wired["repo"], "backport_prs_titled", _raises) + rows, result, ctx, seen = await _worker_pass(monkeypatch) + assert "code_index: backport_ledger_dropped (RuntimeError)" in seen + assert rows == [] and result.fixes_unavailable == 1 + assert [f[:2] for f in ctx.failures] == [("code_backport_gaps:#115670", "FellBack")] + + +@pytest.mark.asyncio +async def test_a_mirror_git_cannot_read_is_named_and_every_row_written( + wired, monkeypatch, tmp_path +) -> None: + """An empty directory as the mirror: `rev-parse` exits 128, not the ref's miss (1), + so the branch's history read is named, and the fix is still written whole.""" + + async def read(git_dir, branch, groups, **kw): + return await _BRANCH_HISTORY(str(tmp_path), branch, groups, **kw) + + _history_on_cut_branch(monkeypatch, read) + rows, result, ctx, seen = await _worker_pass(monkeypatch) + assert "git_mirror: branch_history_unread (MirrorReadError)" in seen + assert sorted(r["branch"] for r in rows) == ["26.4", "26.5", "26.6"] + assert result.fixes_unavailable == 0 and ctx.count == 0 + + +@pytest.mark.asyncio +async def test_a_branch_whose_lag_is_unknown_writes_the_rows_it_would_without( + wired, monkeypatch +) -> None: + """No row stores a branch's lag, so an unknown one changes no row.""" + without, _, _, _ = await _worker_pass(monkeypatch) + _lag_unknown(monkeypatch, wired) + rows, _, _, seen = await _worker_pass(monkeypatch) + assert "git_mirror: lag_unknown (git rev-list failed)" in seen + assert rows == without # 26.5's row as well + + @pytest.mark.asyncio async def test_a_symbol_presence_read_cut_or_failed_is_named(monkeypatch) -> None: import server.code.app.search_fanout as fanout From 83fec11d19c95f8bb43233be51f194853cc9f999 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 11:54:48 +0530 Subject: [PATCH 40/47] backport: an empty mirror path is no mirror, not a missing ref `_unreadable_ref` answered `no_branch_ref` for an empty `git_dir`, which means there is no mirror at all. Only an empty branch name answers `no_branch_ref` now; an empty `git_dir` raises `MirrorReadError`, as a mirror git cannot read does, so the history stage names `branch_history_unread`. The empty-mirror test covers an empty path and fails without the change. The comments on `BRANCH_NOTES` and the worker's docstring say a patch or history read leaves the row that presence and the record gave (a files-only fix floors on file presence, and a branch the record decided keeps that verdict), that an unknown lag changes no row, that `as_of_unread` reads `unknown(no_index)` where the row would read `not_affected`, and that a line probe that raised leaves the branch at `error:*`, or `deadline` when another probe timed out. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/backport.py | 13 +++++++------ server/code/workers/backport_gaps.py | 5 +++-- server/tracker/app/patch_history.py | 14 +++++++++----- tests/unit/test_code_backport_gaps.py | 2 +- 4 files changed, 20 insertions(+), 14 deletions(-) diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 61351c8cb63..1970ff32207 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -76,11 +76,12 @@ # A note about one branch's read whose row claims no more than the read: a symbol-presence -# cut or failure stores `unknown` with `deadline` or `error:*`, a patch or history one the -# symbol floor (unsettled, no reason), and no row stores the lag. So the nightly worker -# writes such a read as it is. Left out, so the fix keeps its previous rows: +# cut or failure stores `unknown` with `deadline` or `error:*`, a patch or history one +# leaves the row that presence and the record gave, and no row stores the lag. So the +# nightly worker writes such a read as it is. Left out, so the fix keeps its previous rows: # `file_presence_unread` (the row would read `no_index`), `backport_ledger_dropped` (`gap` -# where the ledger holds the backport) and `as_of_unread` (`unknown` or `no_index`). +# where the ledger holds the backport) and `as_of_unread` (`unknown(no_index)` where it +# would read `not_affected`). BRANCH_NOTES = frozenset( { "code_index: symbol_presence_timed_out", @@ -91,8 +92,8 @@ "git_mirror: branch_history_unread", "git_mirror: patch_history_timed_out", # one git command of a branch's history read "git_mirror: patch_history_unread", # a branch's tip read raised: `error:*` - # a line probe raised: the branch stays undecided (`error:*`) unless another probe - # names the pick + # a line probe raised: the branch stays undecided (`error:*`, or `deadline` when + # another probe timed out) unless another probe names the pick "git_mirror: patch_history_line_unread", "git_mirror: lag_unknown", # a branch's lag, which no row stores } diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index 9d6555a04cd..b414d464f86 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -14,8 +14,9 @@ writes nothing for it (a night of `unknown` rows would overwrite a day of verdicts) and the next fix runs. A note about one branch's read (`backport.BRANCH_NOTES`) is no such read: that branch's row claims no more than the -read (`unknown` with `deadline` or `error:*` for symbol presence, the symbol floor for -a patch or history read, unchanged for an unknown lag) and replaces its previous verdict. +read (`unknown` with `deadline` or `error:*` for symbol presence; a patch or history +read leaves the row that presence and the record gave; an unknown lag changes no row) +and replaces its previous verdict. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ diff --git a/server/tracker/app/patch_history.py b/server/tracker/app/patch_history.py index bff10d0697e..5b5640876de 100644 --- a/server/tracker/app/patch_history.py +++ b/server/tracker/app/patch_history.py @@ -346,10 +346,13 @@ async def line_origin( async def _unreadable_ref(git_dir: str, branch: str, *, timeout_s: float) -> str: """Why `branch` has no tip to read ("no_branch_ref", "deadline"), or "" when it does. A path read against a ref the mirror lacks fails like any other read, - so only a resolved tip may read as `path_absent`. Only the ref's miss (exit - 1) is `no_branch_ref`; a mirror git cannot read raises `MirrorReadError`.""" - if not branch or not git_dir: + so only a resolved tip may read as `path_absent`. Only a missing ref (no branch + name, or exit 1) is `no_branch_ref`; no mirror, or one git cannot read, raises + `MirrorReadError`.""" + if not branch: return "no_branch_ref" + if not git_dir: + raise MirrorReadError(f"no mirror to read {branch}") rc, _ = await _git_rc( git_dir, "rev-parse", "--verify", "-q", f"{branch}^{{commit}}", timeout_s=timeout_s ) @@ -465,8 +468,9 @@ def _unread(error: BaseException) -> str: def _unread_line(path: str, line: str, error: BaseException) -> LineHistory: - """A line probe that raised: the branch stays undecided (`error:*`) unless - another probe names the pick, and the probe is named in `degraded`.""" + """A line probe that raised: the branch stays undecided (`error:*`, or + `deadline` when another probe timed out) unless another probe names the pick, + and the probe is named in `degraded`.""" degradations.partial("git_mirror", "patch_history_line_unread", error) return LineHistory(path, line, f"error:{type(error).__name__}") diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index e9b3b5a4cd7..ddc5fab1006 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -562,7 +562,7 @@ async def test_a_ref_or_mirror_that_is_not_there_is_never_path_absent(mirror, tm hp = await ph.branch_history(git_dir, "no-such-branch", groups) assert (hp.verdict, hp.reason, hp.paths_absent) == ("", "no_branch_ref", 0) (tmp_path / "empty").mkdir() - for gd in ("/nonexistent/mirror.git", str(tmp_path / "empty")): + for gd in ("", "/nonexistent/mirror.git", str(tmp_path / "empty")): with pytest.raises(ph.MirrorReadError): await ph.branch_history(gd, branch, groups) From 43148325bba90f543af96b1634a588d915eb5555 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 12:08:38 +0530 Subject: [PATCH 41/47] backport: say what a branch note's row claims without listing each case The comment on BRANCH_NOTES and the worker's docstring listed what each note's row stores, which missed a branch the record decides and a probe that names the pick. Such a row claims only what the reads that answered show; that is the rule the worker relies on. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/backport.py | 18 +++++++----------- server/code/workers/backport_gaps.py | 6 ++---- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 1970ff32207..42fbd5ebfb2 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -75,13 +75,11 @@ _HISTORY_GIT_PROCS = 4 -# A note about one branch's read whose row claims no more than the read: a symbol-presence -# cut or failure stores `unknown` with `deadline` or `error:*`, a patch or history one -# leaves the row that presence and the record gave, and no row stores the lag. So the -# nightly worker writes such a read as it is. Left out, so the fix keeps its previous rows: -# `file_presence_unread` (the row would read `no_index`), `backport_ledger_dropped` (`gap` -# where the ledger holds the backport) and `as_of_unread` (`unknown(no_index)` where it -# would read `not_affected`). +# A note about one branch's read whose row claims only what the reads that answered show, +# so the nightly worker writes the fix with it. Left out, so the fix keeps its previous +# rows: `file_presence_unread`, `backport_ledger_dropped` and `as_of_unread`, each of +# which would leave a row that states what the failed read did not show (`no_index`, or +# `gap` where the ledger holds the backport). BRANCH_NOTES = frozenset( { "code_index: symbol_presence_timed_out", @@ -91,10 +89,8 @@ "git_mirror: branch_history_timed_out", "git_mirror: branch_history_unread", "git_mirror: patch_history_timed_out", # one git command of a branch's history read - "git_mirror: patch_history_unread", # a branch's tip read raised: `error:*` - # a line probe raised: the branch stays undecided (`error:*`, or `deadline` when - # another probe timed out) unless another probe names the pick - "git_mirror: patch_history_line_unread", + "git_mirror: patch_history_unread", # a branch's tip read raised + "git_mirror: patch_history_line_unread", # a line probe of a branch raised "git_mirror: lag_unknown", # a branch's lag, which no row stores } ) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index b414d464f86..b345325004b 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -13,10 +13,8 @@ and says where; a QA miss on one fix, or a read its answer fell back on, writes nothing for it (a night of `unknown` rows would overwrite a day of verdicts) and the next fix runs. A note about one branch's read -(`backport.BRANCH_NOTES`) is no such read: that branch's row claims no more than the -read (`unknown` with `deadline` or `error:*` for symbol presence; a patch or history -read leaves the row that presence and the record gave; an unknown lag changes no row) -and replaces its previous verdict. +(`backport.BRANCH_NOTES`) is no such read: that branch's row claims only what the reads +that answered show, and replaces its previous verdict. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ From de8801ee93807a9af4ab3d8bf35bd756b5a07823 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 12:19:38 +0530 Subject: [PATCH 42/47] backport: test the left-out watermark note, and say less where a rule is restated A failed index watermark read (`as_of_unread`) keeps the fix unwritten, now with a worker case beside the file-presence and ledger ones. `_read_fix` and the per-branch test no longer restate the rule the module docstring holds, and the left-out notes can leave such a row: on a branch the record decides, none changes it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/app/backport.py | 2 +- server/code/workers/backport_gaps.py | 2 +- tests/unit/test_code_backport_gaps.py | 25 +++++++++++++++++++++++-- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/server/code/app/backport.py b/server/code/app/backport.py index 42fbd5ebfb2..335a7523e12 100644 --- a/server/code/app/backport.py +++ b/server/code/app/backport.py @@ -78,7 +78,7 @@ # A note about one branch's read whose row claims only what the reads that answered show, # so the nightly worker writes the fix with it. Left out, so the fix keeps its previous # rows: `file_presence_unread`, `backport_ledger_dropped` and `as_of_unread`, each of -# which would leave a row that states what the failed read did not show (`no_index`, or +# which can leave a row that states what the failed read did not show (`no_index`, or # `gap` where the ledger holds the backport). BRANCH_NOTES = frozenset( { diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index b345325004b..8e44fc68a3a 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -250,7 +250,7 @@ async def collect_fixes( async def _read_fix(cfg: Any, pr: int, runner: Any) -> tuple[Any, list[str]]: """The fix's composed read, and the notes it made apart from the pass's, except a - note about one branch's read (`BRANCH_NOTES`), whose row claims no more than it.""" + note about one branch's read (`BRANCH_NOTES`).""" from server.code.app.backport import BRANCH_NOTES, BackportGapRequest with degradations.scoped(): diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index ddc5fab1006..8aae0417087 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -998,8 +998,8 @@ async def runner(req): @pytest.mark.asyncio @pytest.mark.parametrize("note", sorted(_BRANCH_CASES)) async def test_one_branchs_note_still_writes_every_branch_row(wired, monkeypatch, note) -> None: - """One branch's read makes a per-branch note: that branch's row claims no more than the - read, so the fix is written whole and the pass notes no failure.""" + """One branch's read makes a per-branch note: that branch's row claims only what the + reads that answered show, so the fix is written whole and the pass notes no failure.""" _BRANCH_CASES[note](monkeypatch, wired) rows, result, ctx, seen = await _worker_pass(monkeypatch) assert note in {n.split(" (", 1)[0] for n in seen} @@ -1057,6 +1057,27 @@ async def test_a_branch_ledger_read_that_failed_leaves_the_fix_unwritten( assert [f[:2] for f in ctx.failures] == [("code_backport_gaps:#115670", "FellBack")] +@pytest.mark.asyncio +async def test_a_branch_index_watermark_read_that_failed_leaves_the_fix_unwritten( + wired, monkeypatch +) -> None: + """Without the index watermark a branch can read `unknown(no_index)` where it would read + `not_affected`, so the fix keeps last night's rows.""" + as_of = h.index_as_of + + async def read(repo, org, ns): + if ns != _CUT_NS: + return await as_of(repo, org, ns) + degradations.partial("code_index", "as_of_unread", RuntimeError("boom")) + return {} + + monkeypatch.setattr(h, "index_as_of", read) + rows, result, ctx, seen = await _worker_pass(monkeypatch) + assert "code_index: as_of_unread (RuntimeError)" in seen + assert rows == [] and result.fixes_unavailable == 1 + assert [f[:2] for f in ctx.failures] == [("code_backport_gaps:#115670", "FellBack")] + + @pytest.mark.asyncio async def test_a_mirror_git_cannot_read_is_named_and_every_row_written( wired, monkeypatch, tmp_path From b32b093c24f53f84dd9eb2139d587af9635bcdad Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 12:28:56 +0530 Subject: [PATCH 43/47] backport_gaps: name the notes BRANCH_NOTES lists, not any branch note Three notes about one branch's read stay out of BRANCH_NOTES and keep the fix unwritten; the worker's docstrings now say "a note BRANCH_NOTES lists" where they said any note about one branch's read. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/workers/backport_gaps.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index 8e44fc68a3a..6830bc96c28 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -12,9 +12,9 @@ is skipped until its window closes. The leg stops cleanly at `budget_s` and says where; a QA miss on one fix, or a read its answer fell back on, writes nothing for it (a night of `unknown` rows would overwrite a day of -verdicts) and the next fix runs. A note about one branch's read -(`backport.BRANCH_NOTES`) is no such read: that branch's row claims only what the reads -that answered show, and replaces its previous verdict. +verdicts) and the next fix runs. A note `backport.BRANCH_NOTES` lists is no such read: +that branch's row claims only what the reads that answered show, and replaces its +previous verdict. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ @@ -249,8 +249,8 @@ async def collect_fixes( async def _read_fix(cfg: Any, pr: int, runner: Any) -> tuple[Any, list[str]]: - """The fix's composed read, and the notes it made apart from the pass's, except a - note about one branch's read (`BRANCH_NOTES`).""" + """The fix's composed read, and the notes it made apart from the pass's, except one + `BRANCH_NOTES` lists.""" from server.code.app.backport import BRANCH_NOTES, BackportGapRequest with degradations.scoped(): @@ -283,8 +283,8 @@ async def compute_fix( """One fix's composed read → its table rows; [] when the fix could not be read, its tracker record did not answer, or a read it fell back on left a smaller answer (a night of unknowns must not overwrite verdicts), counted on - the result either way. A note about one branch's read (`BRANCH_NOTES`) does not - count: that branch's row is written as the read left it. A read that fell back is + the result either way. A note `BRANCH_NOTES` lists does not count: that + branch's row is written as the read left it. A read that fell back is retried once while the pass is before `deadline` (on the monotonic clock; None: no bound); one that falls back again is a failure of the pass (`note_failure`), so a fix that falls back every night builds the worker's failure streak.""" From 183de2c4913d8f69f0fd18cb2d2e848391c3cf18 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 12:39:25 +0530 Subject: [PATCH 44/47] backport_gaps: say whose row a BRANCH_NOTES note leaves Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/workers/backport_gaps.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index 6830bc96c28..cc9af669017 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -13,8 +13,8 @@ and says where; a QA miss on one fix, or a read its answer fell back on, writes nothing for it (a night of `unknown` rows would overwrite a day of verdicts) and the next fix runs. A note `backport.BRANCH_NOTES` lists is no such read: -that branch's row claims only what the reads that answered show, and replaces its -previous verdict. +the row of the branch whose read made it claims only what the reads that answered +show, and replaces its previous verdict. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ @@ -249,7 +249,7 @@ async def collect_fixes( async def _read_fix(cfg: Any, pr: int, runner: Any) -> tuple[Any, list[str]]: - """The fix's composed read, and the notes it made apart from the pass's, except one + """The fix's composed read, and the notes it made apart from the pass's, except those `BRANCH_NOTES` lists.""" from server.code.app.backport import BRANCH_NOTES, BackportGapRequest @@ -283,8 +283,8 @@ async def compute_fix( """One fix's composed read → its table rows; [] when the fix could not be read, its tracker record did not answer, or a read it fell back on left a smaller answer (a night of unknowns must not overwrite verdicts), counted on - the result either way. A note `BRANCH_NOTES` lists does not count: that - branch's row is written as the read left it. A read that fell back is + the result either way. A note `BRANCH_NOTES` lists does not count: the + fix's rows are written as the read left them. A read that fell back is retried once while the pass is before `deadline` (on the monotonic clock; None: no bound); one that falls back again is a failure of the pass (`note_failure`), so a fix that falls back every night builds the worker's failure streak.""" From 8add8882ba7ece2c41b812e4f93b0a2b6d107c57 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 12:49:37 +0530 Subject: [PATCH 45/47] backport_gaps: shorten the BRANCH_NOTES docstrings Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/workers/backport_gaps.py | 7 +++---- tests/unit/test_code_backport_gaps.py | 5 +++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index cc9af669017..246448a7fab 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -12,9 +12,8 @@ is skipped until its window closes. The leg stops cleanly at `budget_s` and says where; a QA miss on one fix, or a read its answer fell back on, writes nothing for it (a night of `unknown` rows would overwrite a day of -verdicts) and the next fix runs. A note `backport.BRANCH_NOTES` lists is no such read: -the row of the branch whose read made it claims only what the reads that answered -show, and replaces its previous verdict. +verdicts) and the next fix runs. A read that made only notes `backport.BRANCH_NOTES` +lists does not count. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ @@ -286,7 +285,7 @@ async def compute_fix( the result either way. A note `BRANCH_NOTES` lists does not count: the fix's rows are written as the read left them. A read that fell back is retried once while the pass is before `deadline` (on the monotonic clock; None: no - bound); one that falls back again is a failure of the pass (`note_failure`), so a + bound); one that still falls back is a failure of the pass (`note_failure`), so a fix that falls back every night builds the worker's failure streak.""" try: out, noted = await _read_fix(cfg, pr, runner) diff --git a/tests/unit/test_code_backport_gaps.py b/tests/unit/test_code_backport_gaps.py index 8aae0417087..19a361d42bb 100644 --- a/tests/unit/test_code_backport_gaps.py +++ b/tests/unit/test_code_backport_gaps.py @@ -998,8 +998,9 @@ async def runner(req): @pytest.mark.asyncio @pytest.mark.parametrize("note", sorted(_BRANCH_CASES)) async def test_one_branchs_note_still_writes_every_branch_row(wired, monkeypatch, note) -> None: - """One branch's read makes a per-branch note: that branch's row claims only what the - reads that answered show, so the fix is written whole and the pass notes no failure.""" + """One branch's read makes a note `BRANCH_NOTES` lists: that branch's row claims only + what the reads that answered show, so the fix is written whole and the pass notes no + failure.""" _BRANCH_CASES[note](monkeypatch, wired) rows, result, ctx, seen = await _worker_pass(monkeypatch) assert note in {n.split(" (", 1)[0] for n in seen} From dc50cd3d158a402969bf0b5a868e3738c3b47153 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 13:09:29 +0530 Subject: [PATCH 46/47] backport_gaps: rewrap the module docstring Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/workers/backport_gaps.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index 246448a7fab..a1182e6692f 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -12,8 +12,8 @@ is skipped until its window closes. The leg stops cleanly at `budget_s` and says where; a QA miss on one fix, or a read its answer fell back on, writes nothing for it (a night of `unknown` rows would overwrite a day of -verdicts) and the next fix runs. A read that made only notes `backport.BRANCH_NOTES` -lists does not count. +verdicts) and the next fix runs. A read that made only notes +`backport.BRANCH_NOTES` lists does not count. Rows are inserted in batches, never one fix at a time. Restricted trunks are skipped: the table would hold the private record's titles. """ From fd58ac1165b49daa231476248a1fcb62278cb9c0 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 13:15:35 +0530 Subject: [PATCH 47/47] backport_gaps: state the per-trunk pass bound Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/code/workers/backport_gaps.py | 27 ++++++++++++++------------- server/workers/registry.py | 3 +-- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index a1182e6692f..d9887d35320 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -5,17 +5,17 @@ row per release branch into loom.code_backport_gaps, so `code.backport_gaps` answers "which fixes does 26.6 still owe" from loom's own table. -Paced under the QA budgets: one fix per `pace_s` (three tracker reads each, all +Paced under the QA budgets: one fix per `pace_s` (its tracker reads all go through the source layer — predicate, budget, breaker, cache), at most -`prs_per_pass` fixes a night, never computed first and then the stalest, -and a fix whose every branch row is settled (covered / not_affected exact) -is skipped until its window closes. The leg stops cleanly at `budget_s` -and says where; a QA miss on one fix, or a read its answer fell back on, -writes nothing for it (a night of `unknown` rows would overwrite a day of -verdicts) and the next fix runs. A read that made only notes -`backport.BRANCH_NOTES` lists does not count. -Rows are inserted in batches, never one fix at a time. Restricted trunks -are skipped: the table would hold the private record's titles. +`prs_per_pass` fixes a trunk per pass, never computed first and then the +stalest, and a fix whose every branch row is settled (covered / not_affected +exact) is skipped until its window closes. The leg stops cleanly at +`budget_s` and says where; a QA miss on one fix, or a read its answer fell +back on, writes nothing for it (a night of `unknown` rows would overwrite a +day of verdicts) and the next fix runs. A read that made only notes +`backport.BRANCH_NOTES` lists does not count. Rows are inserted in batches, +never one fix at a time. Restricted trunks are skipped: the table would hold +the private record's titles. """ from __future__ import annotations @@ -284,9 +284,10 @@ async def compute_fix( smaller answer (a night of unknowns must not overwrite verdicts), counted on the result either way. A note `BRANCH_NOTES` lists does not count: the fix's rows are written as the read left them. A read that fell back is - retried once while the pass is before `deadline` (on the monotonic clock; None: no - bound); one that still falls back is a failure of the pass (`note_failure`), so a - fix that falls back every night builds the worker's failure streak.""" + retried once while the pass is before `deadline` (on the monotonic clock; + None: no bound); one that still falls back is a failure of the pass + (`note_failure`), so a fix that falls back every night builds the worker's + failure streak.""" try: out, noted = await _read_fix(cfg, pr, runner) if noted and (deadline is None or time.monotonic() < deadline): diff --git a/server/workers/registry.py b/server/workers/registry.py index 3a356f4621e..b82a24b057b 100644 --- a/server/workers/registry.py +++ b/server/workers/registry.py @@ -587,8 +587,7 @@ def _spec_for(row: _Worker) -> WorkerSpec: "code_backport_gaps_interval_seconds", # The report reads the PR ledger: no ledger, no pass. also_requires="code_pr_history_enabled", - # ≤ 300 composed reads a night, paced one per second, budgeted inside - # the pass: the setting is the ceiling, not the plan + # Paced and budgeted inside the pass: the setting is the ceiling, not the plan max_pass_setting="code_backport_gaps_max_pass_seconds", ), _Worker(