From 5c6eae098eefe485f78f0c1a898f26c4551e41ab Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 14:10:47 +0530 Subject: [PATCH 01/41] A failing knowledge source no longer marks Loom degraded for every org; ops.incidents lists the caller org's failing sources knowledge_source_sync noted a pass failure for every source whose turn failed, so one org's revoked credential built the worker's streak and, after three passes, made ops.incidents answer degraded to every org. A source's failure is already in its own sync state. The pass now tallies the turns that ran and noted failures, mirrored ones included, and notes one SourcesFailed ("7 of 9 sources failed") only when most of them failed: an outage, or a deployment's only source. The store and model legs still note as before. ops.incidents gains `sources`: the caller org's failing sources that every reader of their namespace sees (a count and up to 5, latest failure first), read under the same org-whole gate as `requests`, from one bounded statement in the knowledge store, cached per org. It never changes `status`. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/document-sources.md | 4 +- docs/features/knowledge.md | 10 + docs/operations/monitoring.md | 12 + docs/reference/operations/ops.md | 3 +- sdk/go/client.gen.go | 6 + sdk/go/wire/models.gen.go | 33 +- sdk/python/loom/ops.py | 15 + sdk/rust/src/wire_models.rs | 1549 +++++++++-------- sdk/rust/tests/registry_contracts.rs | 8 + sdk/typescript/src/generated/ops.ts | 13 + server/insights/api/models_ops.py | 44 +- server/insights/app/incidents.py | 101 +- server/knowledge/app/source_sync.py | 30 +- server/knowledge/app/sources.py | 9 + server/knowledge/store/sources.py | 59 + tests/analyzer/cases/workers.py | 5 +- tests/analyzer/shapes.txt | 1 + tests/unit/test_knowledge_source_sync.py | 3 +- .../test_knowledge_source_sync_diagnostics.py | 11 +- .../test_knowledge_source_sync_failures.py | 183 ++ tests/unit/test_ops_incidents.py | 110 +- tests/unit/test_ops_incidents_sql.py | 100 +- 22 files changed, 1483 insertions(+), 826 deletions(-) create mode 100644 tests/unit/test_knowledge_source_sync_failures.py diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 3acaedc49c9..66d1038ed41 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -636,7 +636,9 @@ the public fallback. No reranking provider receives the provisional pools. service's logs and traces) carries codes only (exceptions 3 and 4 apart). Worker pass summaries exclude mirrored turns' completed-source counts, document figures and cut flags. A failed mirrored turn contributes only `SYNC_FAILED`, for - every cause; returned turn details remain private. Mirrored per-file failures emit + every cause, and counts in the pass's tally of failed turns like any other source; + returned turn details remain private. `ops.incidents`' `sources` counts no mirrored + source, since its state is its mirror's. Mirrored per-file failures emit no log record, since the number of records would disclose a document figure. A sync turn enters its private diagnostic scope before taking its source lease or listing files; retirement enters it before reading its queue. That scope suppresses diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 0780517e282..1bac7258b43 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -676,6 +676,16 @@ A source's `sync` in `list` and `inspect` shows what its last turn did: | `unextracted` | Documents it gave up on: three failed tries, or too large for a pass. | | `extract_error` | Why an extraction failed in the last mining turn (`not_run`, `refused`, `out_of_time`, `too_large_for_pass`, `failed:`), or why documents wait (`over_cap`, `switched_off`, `switch_unread`, `no_model`, `held`, `held:`, `pass_bound`). | +A failed turn belongs to its source: its `status` and `error` here, and for an org admin +the org's failing sources in [`ops.incidents`](../operations/monitoring.md#opsincidents)' +`sources`. The worker's pass counts as failed toward its failure streak only when most of +the sources whose turn ran in it failed (`knowledge_source_sync: 7 of 9 sources failed`), +mirrored ones included: an outage of what every source relies on, or a deployment's only +source. One org's refused credential therefore never makes the worker, or `ops.incidents`, +degraded for the other orgs. A turn another copy holds counts neither way. A failure in +the mining leg (a store read or write, a model call) or in retiring a removed source's +documents still counts the pass as failed. + ### A recording source A `recording` source reads transcripts, never audio or video, and nothing in Loom diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 1dca93dd08e..0f156d32311 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -175,6 +175,18 @@ covers the org's calls only when they were: `read`; `not_permitted` when the cal 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. +`sources` lists the org's own [document sources](../features/knowledge.md#syncing-a-source) +whose last sync turn failed: `failing`, how many, and `sample`, at most 5 of them +(`{namespace, name, status}`), the latest failure first, with `status` `failed`, +`rate_limited` or `credential_invalid`. It counts only the sources every reader of their +namespace sees, never a mirrored or a person's connected one, whose state is its mirror's. +It is read under the same rule as the request counts, and `sources.read` answers in the +same words. A failing document source is never an incident and never makes `status` +`degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own +health. The `knowledge_source_sync` worker becomes a `worker` incident only after 3 +passes in a row in which most of the sources failed or a leg every source relies on (the +store, the model) failed. + ### Smoke test After a deploy, write and read one memory end to end: diff --git a/docs/reference/operations/ops.md b/docs/reference/operations/ops.md index 430bcab4d60..0891f8a9836 100644 --- a/docs/reference/operations/ops.md +++ b/docs/reference/operations/ops.md @@ -55,10 +55,11 @@ Whether Loom is degraded now, from its checks, providers, workers and calls. | Output field | Type | Meaning | | --- | --- | --- | -| `status` | `Literal['ok', 'degraded']` | `degraded` when an incident is listed, else `ok`. | +| `status` | `Literal['ok', 'degraded']` | `degraded` when an incident is listed, else `ok`; failing `sources` never count. | | `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… | +| `sources` | `OpsIncidentSources` | The org's document sources whose last sync failed, for its admin to fix; a server of an earlier build leaves it out. | ## `ops.projection_failures.list` diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index 5c06b531847..4a4c80e0eec 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -2399,6 +2399,9 @@ type OpsCapabilitiesInput = wire.OpsCapabilitiesInput // OpsCapabilitiesOutput is the response from ops.capabilities. type OpsCapabilitiesOutput = wire.OpsCapabilitiesOutput +// OpsFailingSource is a model used by Loom operations. +type OpsFailingSource = wire.OpsFailingSource + // OpsHealthCheck is a model used by Loom operations. type OpsHealthCheck = wire.OpsHealthCheck @@ -2411,6 +2414,9 @@ type OpsHealthOutput = wire.OpsHealthOutput // OpsIncident is a model used by Loom operations. type OpsIncident = wire.OpsIncident +// OpsIncidentSources is a model used by Loom operations. +type OpsIncidentSources = wire.OpsIncidentSources + // OpsIncidentsInput is the request to ops.incidents. type OpsIncidentsInput = wire.OpsIncidentsInput diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 1308ad7b614..5d35b24b9b4 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: b0b38eb91033fef8ee46a02e146d5c3d3ae7b8032ea90c9c74c0b9397649c8b9 +// Registry model schema SHA-256: 06bbf5342050633f15e6594b14317730f00f6968e3cb69eb9cd2c8f0d58e156a // Package wire contains the Go requests and responses for Loom operations. package wire @@ -10173,6 +10173,13 @@ type OpsCapabilitiesOutput struct { ConsumerField *string `json:"consumer_field,omitempty"` } +// OpsFailingSource is a model used by Loom operations. +type OpsFailingSource struct { + Namespace string `json:"namespace"` + Name string `json:"name"` + Status string `json:"status"` +} + // OpsHealthCheck is a model used by Loom operations. type OpsHealthCheck struct { Name string `json:"name"` @@ -10208,6 +10215,13 @@ type OpsIncident struct { AgeS Optional[float64] `json:"age_s,omitempty"` } +// OpsIncidentSources is a model used by Loom operations. +type OpsIncidentSources struct { + Failing *int64 `json:"failing,omitempty"` + Sample *[]OpsFailingSource `json:"sample,omitempty"` + Read *string `json:"read,omitempty"` +} + // OpsIncidentsInput is the request to ops.incidents. type OpsIncidentsInput struct { Org *string `json:"org,omitempty"` @@ -10215,14 +10229,15 @@ type OpsIncidentsInput struct { // 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"` - Requests string `json:"requests"` + IgnoredArgs *[]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"` + Requests string `json:"requests"` + Sources *OpsIncidentSources `json:"sources,omitempty"` } // OpsProjectionFailuresListInput is the request to ops.projection_failures.list. diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 7421b49b328..ff90d94d59f 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -18571,6 +18571,7 @@ class OpsIncidentsOutput(TypedDict, total=False): incidents: NotRequired[list["OpsIncident"]] window_minutes: Required[int] requests: Required[Literal["read", "not_permitted", "unread"]] + sources: NotRequired["OpsIncidentSources"] class OpsIncident(TypedDict, total=False): @@ -18581,6 +18582,20 @@ class OpsIncident(TypedDict, total=False): age_s: NotRequired[Optional[float]] +class OpsIncidentSources(TypedDict, total=False): + "The org's own document sources whose last sync turn failed." + + failing: NotRequired[int] + sample: NotRequired[list["OpsFailingSource"]] + read: NotRequired[Literal["read", "not_permitted", "unread"]] + + +class OpsFailingSource(TypedDict, total=False): + namespace: Required[str] + name: Required[str] + status: Required[str] + + class OpsProjectionFailuresListInput(TypedDict, total=False): org: Required[str] namespace: NotRequired[Optional[str]] diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index b108200cb61..4ae4455bb2e 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -50006,6 +50006,36 @@ pub enum OpsIncidentsOutputRequests { Unread, } +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct OpsFailingSource { + pub namespace: String, + pub name: String, + pub status: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum OpsIncidentSourcesRead { + #[serde(rename = "read")] + Read, + #[serde(rename = "not_permitted")] + NotPermitted, + #[serde(rename = "unread")] + Unread, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct OpsIncidentSources { + #[serde(default = "default_2215")] + pub failing: Integer, + #[serde(default = "default_2216")] + pub sample: Vec, + #[serde(default = "default_2217")] + pub read: OpsIncidentSourcesRead, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct OpsIncidentsOutput { @@ -50014,6 +50044,8 @@ pub struct OpsIncidentsOutput { pub incidents: Vec, pub window_minutes: Integer, pub requests: OpsIncidentsOutputRequests, + #[serde(default = "default_2218")] + pub sources: OpsIncidentSources, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -50054,26 +50086,26 @@ pub struct ProjectionFailureRow { pub failure_id: String, pub org: String, pub namespace: String, - #[serde(default = "default_2215")] + #[serde(default = "default_2219")] pub agent: String, pub projection: String, - #[serde(default = "default_2216")] + #[serde(default = "default_2220")] pub source_operation: String, - #[serde(default = "default_2217")] + #[serde(default = "default_2221")] pub source_resource_id: String, - #[serde(default = "default_2218")] + #[serde(default = "default_2222")] pub memory_keys: Vec, - #[serde(default = "default_2219")] + #[serde(default = "default_2223")] pub error_type: String, - #[serde(default = "default_2220")] + #[serde(default = "default_2224")] pub error_message: String, - #[serde(default = "default_2221")] + #[serde(default = "default_2225")] pub payload: std::collections::HashMap, - #[serde(default = "default_2222")] + #[serde(default = "default_2226")] pub status: String, - #[serde(default = "default_2223")] + #[serde(default = "default_2227")] pub created_at: Option, - #[serde(default = "default_2224")] + #[serde(default = "default_2228")] pub resolved_at: Option, } @@ -50227,22 +50259,22 @@ pub struct ProjectionFailureRetryRow { pub projection: String, pub retried: bool, pub resolved: bool, - #[serde(default = "default_2225")] + #[serde(default = "default_2229")] pub abandoned: bool, - #[serde(default = "default_2226")] + #[serde(default = "default_2230")] pub reason: String, - #[serde(default = "default_2227")] + #[serde(default = "default_2231")] pub error: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProjectionFailureRetryOutput { - #[serde(default = "default_2228")] + #[serde(default = "default_2232")] pub results: Vec, pub retried: Integer, pub resolved: Integer, - #[serde(default = "default_2229")] + #[serde(default = "default_2233")] pub abandoned: Integer, } @@ -50324,15 +50356,15 @@ impl ProjectionFailureRetryInput { pub struct OrgModelCallsOutput { pub org: String, pub enabled: bool, - #[serde(default = "default_2230")] + #[serde(default = "default_2234")] pub reason: String, - #[serde(default = "default_2231")] + #[serde(default = "default_2235")] pub updated_by: String, - #[serde(default = "default_2232")] + #[serde(default = "default_2236")] pub updated_at: Option, - #[serde(default = "default_2233")] + #[serde(default = "default_2237")] pub locked: bool, - #[serde(default = "default_2234")] + #[serde(default = "default_2238")] pub locked_by: String, } @@ -50671,7 +50703,7 @@ impl PolicyDecisionsInput { #[non_exhaustive] pub struct PolicyDeleteOutput { pub removed: bool, - #[serde(default = "default_2235")] + #[serde(default = "default_2239")] pub widening: bool, } @@ -50737,12 +50769,12 @@ pub struct PolicyRuleOut { pub condition: std::collections::HashMap, pub description: String, pub enabled: bool, - #[serde(default = "default_2236")] + #[serde(default = "default_2240")] pub mode: String, pub created_by: String, - #[serde(default = "default_2237")] + #[serde(default = "default_2241")] pub created_at: Option, - #[serde(default = "default_2238")] + #[serde(default = "default_2242")] pub updated_at: Option, } @@ -50814,9 +50846,9 @@ impl PolicyListInput { pub struct PolicySetOutput { pub rule: PolicyRuleOut, pub leaf_count: Integer, - #[serde(default = "default_2239")] + #[serde(default = "default_2243")] pub widening: bool, - #[serde(default = "default_2240")] + #[serde(default = "default_2244")] pub change: Vec, } @@ -51086,37 +51118,37 @@ pub struct ProcedureEvolveOutput { pub revision: Integer, pub changed: bool, pub template: bool, - #[serde(default = "default_2241")] + #[serde(default = "default_2245")] pub folded_runs: Integer, - #[serde(default = "default_2242")] + #[serde(default = "default_2246")] pub gate: ProcedureEvolveOutputGate, - #[serde(default = "default_2243")] + #[serde(default = "default_2247")] pub gate_mode: String, - #[serde(default = "default_2244")] + #[serde(default = "default_2248")] pub gate_llr: f64, - #[serde(default = "default_2245")] + #[serde(default = "default_2249")] pub gate_before: std::collections::HashMap, - #[serde(default = "default_2246")] + #[serde(default = "default_2250")] pub gate_after: std::collections::HashMap, - #[serde(default = "default_2247")] + #[serde(default = "default_2251")] pub gate_cost_before: std::collections::HashMap, - #[serde(default = "default_2248")] + #[serde(default = "default_2252")] pub gate_cost_after: std::collections::HashMap, - #[serde(default = "default_2249")] + #[serde(default = "default_2253")] pub gate_reason: String, - #[serde(default = "default_2250")] + #[serde(default = "default_2254")] pub dead_end_steps: Vec, - #[serde(default = "default_2251")] + #[serde(default = "default_2255")] pub fail_prone_steps: Vec, - #[serde(default = "default_2252")] + #[serde(default = "default_2256")] pub fail_prone_transitions: Vec, - #[serde(default = "default_2253")] + #[serde(default = "default_2257")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2254")] + #[serde(default = "default_2258")] pub strikes: Integer, - #[serde(default = "default_2255")] + #[serde(default = "default_2259")] pub quarantined: bool, - #[serde(default = "default_2256")] + #[serde(default = "default_2260")] pub retention: std::collections::HashMap, } @@ -51339,9 +51371,9 @@ pub struct ProcedureForkOutput { pub memory_key: String, pub version: Integer, pub name: String, - #[serde(default = "default_2257")] + #[serde(default = "default_2261")] pub steps: Vec, - #[serde(default = "default_2258")] + #[serde(default = "default_2262")] pub forked_from: std::collections::HashMap, } @@ -51601,32 +51633,32 @@ pub enum ProcedureLocateOutputStatus { #[non_exhaustive] pub struct ProcedureLocateOutput { pub memory_key: String, - #[serde(default = "default_2259")] + #[serde(default = "default_2263")] pub name: String, - #[serde(default = "default_2260")] + #[serde(default = "default_2264")] pub status: ProcedureLocateOutputStatus, pub matched: bool, - #[serde(default = "default_2261")] + #[serde(default = "default_2265")] pub active: Option>, - #[serde(default = "default_2262")] + #[serde(default = "default_2266")] pub hops: Vec>>, - #[serde(default = "default_2263")] + #[serde(default = "default_2267")] pub entry_nodes: Vec, - #[serde(default = "default_2264")] + #[serde(default = "default_2268")] pub dominant_next: Vec, - #[serde(default = "default_2265")] + #[serde(default = "default_2269")] pub revisits: std::collections::HashMap, - #[serde(default = "default_2266")] + #[serde(default = "default_2270")] pub looping: bool, - #[serde(default = "default_2267")] + #[serde(default = "default_2271")] pub exits: Vec, - #[serde(default = "default_2268")] + #[serde(default = "default_2272")] pub failure_notes: Vec>, - #[serde(default = "default_2269")] + #[serde(default = "default_2273")] pub rendered: String, - #[serde(default = "default_2270")] + #[serde(default = "default_2274")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2271")] + #[serde(default = "default_2275")] pub for_agent: std::collections::HashMap, } @@ -51781,43 +51813,43 @@ pub struct ProcedureMatch { pub name: String, pub situation: String, pub steps: Vec, - #[serde(default = "default_2272")] + #[serde(default = "default_2276")] pub tags: Vec, - #[serde(default = "default_2273")] + #[serde(default = "default_2277")] pub metadata: std::collections::HashMap, pub similarity: f64, pub memory_key: String, pub namespace: String, - #[serde(default = "default_2274")] + #[serde(default = "default_2278")] pub graph: Option>, - #[serde(default = "default_2275")] + #[serde(default = "default_2279")] pub template: bool, - #[serde(default = "default_2276")] + #[serde(default = "default_2280")] pub run_stats: std::collections::HashMap, - #[serde(default = "default_2277")] + #[serde(default = "default_2281")] pub status: ProcedureMatchStatus, - #[serde(default = "default_2278")] + #[serde(default = "default_2282")] pub quarantined: Option>, - #[serde(default = "default_2279")] + #[serde(default = "default_2283")] pub fail_prone_steps: Vec, - #[serde(default = "default_2280")] + #[serde(default = "default_2284")] pub revision: Integer, - #[serde(default = "default_2281")] + #[serde(default = "default_2285")] pub rejected_revisions: Vec>, - #[serde(default = "default_2282")] + #[serde(default = "default_2286")] pub tool_overlap: f64, - #[serde(default = "default_2283")] + #[serde(default = "default_2287")] pub score: f64, - #[serde(default = "default_2284")] + #[serde(default = "default_2288")] pub utility: f64, - #[serde(default = "default_2285")] + #[serde(default = "default_2289")] pub goal_similarity: Option, - #[serde(default = "default_2286")] + #[serde(default = "default_2290")] pub for_agent: std::collections::HashMap, - #[serde(default = "default_2287")] + #[serde(default = "default_2291")] pub run_stats_by_agent: std::collections::HashMap>, - #[serde(default = "default_2288")] + #[serde(default = "default_2292")] pub actor: String, } @@ -51825,11 +51857,11 @@ pub struct ProcedureMatch { #[non_exhaustive] pub struct ProcedureMatchOutput { pub matches: Vec, - #[serde(default = "default_2289")] + #[serde(default = "default_2293")] pub matched: Integer, - #[serde(default = "default_2290")] + #[serde(default = "default_2294")] pub procedure_key: String, - #[serde(default = "default_2291")] + #[serde(default = "default_2295")] pub score: f64, } @@ -52221,9 +52253,9 @@ pub struct ProcedureReviseOutput { pub revision: Integer, pub prior_revision: Integer, pub digest: String, - #[serde(default = "default_2292")] + #[serde(default = "default_2296")] pub steps: Vec, - #[serde(default = "default_2293")] + #[serde(default = "default_2297")] pub outcome: ProcedureReviseOutputOutcome, } @@ -52335,14 +52367,14 @@ pub struct ProfileActivityEntry { pub agent: String, pub last_activated_at: String, pub event_count: Integer, - #[serde(default = "default_2294")] + #[serde(default = "default_2298")] pub operations: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProfileActivityOutput { - #[serde(default = "default_2295")] + #[serde(default = "default_2299")] pub entries: Vec, } @@ -52450,17 +52482,17 @@ impl ProfileActivityInput { #[non_exhaustive] pub struct ProfileMutationOutput { pub version: Integer, - #[serde(default = "default_2296")] + #[serde(default = "default_2300")] pub memory_id: String, - #[serde(default = "default_2297")] + #[serde(default = "default_2301")] pub content_sha256: String, - #[serde(default = "default_2298")] + #[serde(default = "default_2302")] pub namespace: String, - #[serde(default = "default_2299")] + #[serde(default = "default_2303")] pub label: String, - #[serde(default = "default_2300")] + #[serde(default = "default_2304")] pub char_limit: Option, - #[serde(default = "default_2301")] + #[serde(default = "default_2305")] pub value_length: Integer, } @@ -52569,7 +52601,7 @@ pub struct ProfileRenderOutput { pub rendered: String, pub section_count: Integer, pub total_chars: Integer, - #[serde(default = "default_2302")] + #[serde(default = "default_2306")] pub labels: Vec, } @@ -52954,17 +52986,17 @@ pub enum ProfileStructuredOutputStatus { #[non_exhaustive] pub struct ProfileStructuredOutput { pub status: ProfileStructuredOutputStatus, - #[serde(default = "default_2303")] + #[serde(default = "default_2307")] pub profile: std::collections::HashMap, - #[serde(default = "default_2304")] + #[serde(default = "default_2308")] pub built_at: Option, - #[serde(default = "default_2305")] + #[serde(default = "default_2309")] pub memory_id: String, - #[serde(default = "default_2306")] + #[serde(default = "default_2310")] pub version: Integer, - #[serde(default = "default_2307")] + #[serde(default = "default_2311")] pub version_text: String, - #[serde(default = "default_2308")] + #[serde(default = "default_2312")] pub schema_sha256: String, } @@ -53081,13 +53113,13 @@ impl ProfileStructuredInput { #[non_exhaustive] pub struct ProfileSchemaOutput { pub found: bool, - #[serde(default = "default_2309")] + #[serde(default = "default_2313")] pub json_schema: std::collections::HashMap, - #[serde(default = "default_2310")] + #[serde(default = "default_2314")] pub schema_sha256: String, - #[serde(default = "default_2311")] + #[serde(default = "default_2315")] pub updated_by: String, - #[serde(default = "default_2312")] + #[serde(default = "default_2316")] pub updated_at: Option, } @@ -53240,10 +53272,10 @@ pub enum RunBeginOutputStatus { #[non_exhaustive] pub struct RunBeginOutput { pub run_id: String, - #[serde(default = "default_2313")] + #[serde(default = "default_2317")] pub status: RunBeginOutputStatus, pub started_at: String, - #[serde(default = "default_2314")] + #[serde(default = "default_2318")] pub next: String, } @@ -53451,31 +53483,31 @@ pub struct RunCompleteOutput { pub run_id: String, pub status: RunCompleteOutputStatus, pub duration_ms: Integer, - #[serde(default = "default_2315")] + #[serde(default = "default_2319")] pub used_applied: Integer, - #[serde(default = "default_2316")] + #[serde(default = "default_2320")] pub undelivered: Integer, - #[serde(default = "default_2317")] + #[serde(default = "default_2321")] pub evidence_applied: Integer, - #[serde(default = "default_2318")] + #[serde(default = "default_2322")] pub harm_applied: Integer, - #[serde(default = "default_2319")] + #[serde(default = "default_2323")] pub memories_written: Vec, - #[serde(default = "default_2320")] + #[serde(default = "default_2324")] pub recalled: Integer, - #[serde(default = "default_2321")] + #[serde(default = "default_2325")] pub observations: Integer, - #[serde(default = "default_2322")] + #[serde(default = "default_2326")] pub procedure_runs_recorded: Integer, - #[serde(default = "default_2323")] + #[serde(default = "default_2327")] pub reflection_key: String, - #[serde(default = "default_2324")] + #[serde(default = "default_2328")] pub retain: String, - #[serde(default = "default_2325")] + #[serde(default = "default_2329")] pub retained: Integer, - #[serde(default = "default_2326")] + #[serde(default = "default_2330")] pub demoted: Integer, - #[serde(default = "default_2327")] + #[serde(default = "default_2331")] pub expiring: Integer, } @@ -54016,25 +54048,25 @@ pub enum RunGetOutputOverBudgetItem { #[non_exhaustive] pub struct RunGetOutput { pub found: bool, - #[serde(default = "default_2328")] + #[serde(default = "default_2332")] pub run: Option, - #[serde(default = "default_2329")] + #[serde(default = "default_2333")] pub recalled: Integer, - #[serde(default = "default_2330")] + #[serde(default = "default_2334")] pub recalled_keys: Vec, - #[serde(default = "default_2331")] + #[serde(default = "default_2335")] pub memories_written: Vec, - #[serde(default = "default_2332")] + #[serde(default = "default_2336")] pub observations: Integer, - #[serde(default = "default_2333")] + #[serde(default = "default_2337")] pub turns: Integer, - #[serde(default = "default_2334")] + #[serde(default = "default_2338")] pub unpriced_turns: Integer, - #[serde(default = "default_2335")] + #[serde(default = "default_2339")] pub cost_usd: f64, - #[serde(default = "default_2336")] + #[serde(default = "default_2340")] pub elapsed_seconds: Integer, - #[serde(default = "default_2337")] + #[serde(default = "default_2341")] pub over_budget: Vec, } @@ -54101,17 +54133,17 @@ pub struct RunGradeProposal { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct RunGradeOutput { - #[serde(default = "default_2338")] + #[serde(default = "default_2342")] pub graded: Integer, - #[serde(default = "default_2339")] + #[serde(default = "default_2343")] pub run_ids: Vec, - #[serde(default = "default_2340")] + #[serde(default = "default_2344")] pub skipped_active: Integer, - #[serde(default = "default_2341")] + #[serde(default = "default_2345")] pub unchanged: Integer, - #[serde(default = "default_2342")] + #[serde(default = "default_2346")] pub memories_counted: Integer, - #[serde(default = "default_2343")] + #[serde(default = "default_2347")] pub proposals_decided: Vec, } @@ -54226,7 +54258,7 @@ impl RunGradeInput { #[non_exhaustive] pub struct RunListOutput { pub runs: Vec, - #[serde(default = "default_2344")] + #[serde(default = "default_2348")] pub total: Option, } @@ -54450,19 +54482,19 @@ impl RunListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct RunRetractCreditOutput { - #[serde(default = "default_2345")] + #[serde(default = "default_2349")] pub run_id: String, - #[serde(default = "default_2346")] + #[serde(default = "default_2350")] pub used_retracted: Integer, - #[serde(default = "default_2347")] + #[serde(default = "default_2351")] pub evidence_retracted: Integer, - #[serde(default = "default_2348")] + #[serde(default = "default_2352")] pub harm_retracted: Integer, - #[serde(default = "default_2349")] + #[serde(default = "default_2353")] pub events_written: Integer, - #[serde(default = "default_2350")] + #[serde(default = "default_2354")] pub more: bool, - #[serde(default = "default_2351")] + #[serde(default = "default_2355")] pub dry_run: bool, } @@ -54619,39 +54651,39 @@ pub struct LiveSearchHit { pub title: String, pub url: String, pub provider: LiveSearchHitProvider, - #[serde(default = "default_2354")] + #[serde(default = "default_2358")] pub content: String, - #[serde(default = "default_2355")] + #[serde(default = "default_2359")] pub live: LiveSearchHitLive, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct LiveSearchResults { - #[serde(default = "default_2353")] + #[serde(default = "default_2357")] pub live: LiveSearchResultsLive, - #[serde(default = "default_2356")] + #[serde(default = "default_2360")] pub results: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SearchOutput { - #[serde(default = "default_2352")] + #[serde(default = "default_2356")] pub tracker: Option>, - #[serde(default = "default_2357")] + #[serde(default = "default_2361")] pub live: Option, - #[serde(default = "default_2358")] + #[serde(default = "default_2362")] pub memory: std::collections::HashMap, - #[serde(default = "default_2359")] + #[serde(default = "default_2363")] pub knowledge: std::collections::HashMap, - #[serde(default = "default_2360")] + #[serde(default = "default_2364")] pub profile: std::collections::HashMap, - #[serde(default = "default_2361")] + #[serde(default = "default_2365")] pub conversations: std::collections::HashMap, - #[serde(default = "default_2362")] + #[serde(default = "default_2366")] pub withheld: Option>, - #[serde(default = "default_2363")] + #[serde(default = "default_2367")] pub namespaces_skipped: Vec, } @@ -54855,7 +54887,7 @@ impl SearchInput { pub struct SessionBriefDeleteOutput { pub deleted: bool, pub brief_key: String, - #[serde(default = "default_2364")] + #[serde(default = "default_2368")] pub revision: Integer, } @@ -54948,67 +54980,67 @@ impl SessionBriefDeleteInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDecision { - #[serde(default = "default_2373")] + #[serde(default = "default_2377")] pub what: String, - #[serde(default = "default_2374")] + #[serde(default = "default_2378")] pub why: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDeadEnd { - #[serde(default = "default_2376")] + #[serde(default = "default_2380")] pub tried: String, - #[serde(default = "default_2377")] + #[serde(default = "default_2381")] pub why_not: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDone { - #[serde(default = "default_2379")] + #[serde(default = "default_2383")] pub what: String, - #[serde(rename = "ref", default = "default_2380")] + #[serde(rename = "ref", default = "default_2384")] pub r#ref: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefFile { - #[serde(default = "default_2384")] + #[serde(default = "default_2388")] pub path: String, - #[serde(default = "default_2385")] + #[serde(default = "default_2389")] pub role: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefSections { - #[serde(default = "default_2370")] + #[serde(default = "default_2374")] pub goal: String, - #[serde(default = "default_2371")] + #[serde(default = "default_2375")] pub status: String, - #[serde(default = "default_2372")] + #[serde(default = "default_2376")] pub verification: String, - #[serde(default = "default_2375")] + #[serde(default = "default_2379")] pub decisions: Vec, - #[serde(default = "default_2378")] + #[serde(default = "default_2382")] pub dead_ends: Vec, - #[serde(default = "default_2381")] + #[serde(default = "default_2385")] pub done: Vec, - #[serde(default = "default_2382")] + #[serde(default = "default_2386")] pub open_questions: Vec, - #[serde(default = "default_2383")] + #[serde(default = "default_2387")] pub next_steps: Vec, - #[serde(default = "default_2386")] + #[serde(default = "default_2390")] pub files: Vec, - #[serde(default = "default_2387")] + #[serde(default = "default_2391")] pub constraints: Vec, - #[serde(default = "default_2388")] + #[serde(default = "default_2392")] pub pointers: Vec, - #[serde(default = "default_2389")] + #[serde(default = "default_2393")] pub client_summary: String, - #[serde(default = "default_2390")] + #[serde(default = "default_2394")] pub client_summary_at: String, } @@ -55016,45 +55048,45 @@ pub struct BriefSections { #[non_exhaustive] pub struct SessionBriefGetOutput { pub found: bool, - #[serde(default = "default_2365")] + #[serde(default = "default_2369")] pub brief_key: String, - #[serde(default = "default_2366")] + #[serde(default = "default_2370")] pub revision: Integer, - #[serde(default = "default_2367")] + #[serde(default = "default_2371")] pub snapshot_id: String, - #[serde(default = "default_2368")] + #[serde(default = "default_2372")] pub snapshot_key: String, - #[serde(default = "default_2369")] + #[serde(default = "default_2373")] pub rendered: String, - #[serde(default = "default_2391")] + #[serde(default = "default_2395")] pub sections: Option, - #[serde(default = "default_2392")] + #[serde(default = "default_2396")] pub project: String, - #[serde(default = "default_2393")] + #[serde(default = "default_2397")] pub branch: String, - #[serde(default = "default_2394")] + #[serde(default = "default_2398")] pub head_sha: String, - #[serde(default = "default_2395")] + #[serde(default = "default_2399")] pub author: String, - #[serde(default = "default_2396")] + #[serde(default = "default_2400")] pub trigger: String, - #[serde(default = "default_2397")] + #[serde(default = "default_2401")] pub actor: String, - #[serde(default = "default_2398")] + #[serde(default = "default_2402")] pub source_sessions: Vec, - #[serde(default = "default_2399")] + #[serde(default = "default_2403")] pub updated_at: Option, - #[serde(default = "default_2400")] + #[serde(default = "default_2404")] pub age_seconds: Integer, - #[serde(default = "default_2401")] + #[serde(default = "default_2405")] pub revisions: Integer, - #[serde(default = "default_2402")] + #[serde(default = "default_2406")] pub events_total: Integer, - #[serde(default = "default_2403")] + #[serde(default = "default_2407")] pub source_chars: Integer, - #[serde(default = "default_2404")] + #[serde(default = "default_2408")] pub brief_chars: Integer, - #[serde(default = "default_2405")] + #[serde(default = "default_2409")] pub deleted: bool, } @@ -55229,34 +55261,34 @@ impl SessionBriefGetInput { pub struct SessionBriefSummary { pub brief_key: String, pub revision: Integer, - #[serde(default = "default_2406")] + #[serde(default = "default_2410")] pub project: String, - #[serde(default = "default_2407")] + #[serde(default = "default_2411")] pub branch: String, - #[serde(default = "default_2408")] + #[serde(default = "default_2412")] pub agent: String, - #[serde(default = "default_2409")] + #[serde(default = "default_2413")] pub goal: String, - #[serde(default = "default_2410")] + #[serde(default = "default_2414")] pub status: String, - #[serde(default = "default_2411")] + #[serde(default = "default_2415")] pub author: String, - #[serde(default = "default_2412")] + #[serde(default = "default_2416")] pub actor: String, - #[serde(default = "default_2413")] + #[serde(default = "default_2417")] pub updated_at: Option, - #[serde(default = "default_2414")] + #[serde(default = "default_2418")] pub age_seconds: Integer, - #[serde(default = "default_2415")] + #[serde(default = "default_2419")] pub brief_chars: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefListOutput { - #[serde(default = "default_2416")] + #[serde(default = "default_2420")] pub briefs: Vec, - #[serde(default = "default_2417")] + #[serde(default = "default_2421")] pub rendered: String, } @@ -55396,25 +55428,25 @@ impl SessionBriefListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefStats { - #[serde(default = "default_2421")] + #[serde(default = "default_2425")] pub events_in: Integer, - #[serde(default = "default_2422")] + #[serde(default = "default_2426")] pub windows: Integer, - #[serde(default = "default_2423")] + #[serde(default = "default_2427")] pub events_total: Integer, - #[serde(default = "default_2424")] + #[serde(default = "default_2428")] pub source_chars: Integer, - #[serde(default = "default_2425")] + #[serde(default = "default_2429")] pub brief_chars: Integer, - #[serde(default = "default_2426")] + #[serde(default = "default_2430")] pub compression_ratio: f64, - #[serde(default = "default_2427")] + #[serde(default = "default_2431")] pub dropped_ungrounded: Integer, - #[serde(default = "default_2428")] + #[serde(default = "default_2432")] pub tokens_in: Integer, - #[serde(default = "default_2429")] + #[serde(default = "default_2433")] pub tokens_out: Integer, - #[serde(default = "default_2430")] + #[serde(default = "default_2434")] pub llm_model: String, } @@ -55424,13 +55456,13 @@ pub struct SessionBriefSaveOutput { pub brief_key: String, pub revision: Integer, pub changed: bool, - #[serde(default = "default_2418")] + #[serde(default = "default_2422")] pub author: String, - #[serde(default = "default_2419")] + #[serde(default = "default_2423")] pub reason: String, - #[serde(default = "default_2420")] + #[serde(default = "default_2424")] pub rendered: String, - #[serde(default = "default_2431")] + #[serde(default = "default_2435")] pub stats: SessionBriefStats, } @@ -56175,39 +56207,39 @@ pub struct TaskPayload { pub priority: Integer, pub disclosure: TaskPayloadDisclosure, pub status: TaskPayloadStatus, - #[serde(default = "default_2432")] + #[serde(default = "default_2436")] pub reason: String, - #[serde(default = "default_2433")] + #[serde(default = "default_2437")] pub blocked_on: String, - #[serde(default = "default_2434")] + #[serde(default = "default_2438")] pub not_before: Option, - #[serde(default = "default_2435")] + #[serde(default = "default_2439")] pub resume_at: Option, - #[serde(default = "default_2436")] + #[serde(default = "default_2440")] pub deadline: Option, - #[serde(default = "default_2437")] + #[serde(default = "default_2441")] pub defer_count: Integer, pub title: String, - #[serde(default = "default_2438")] + #[serde(default = "default_2442")] pub brief: std::collections::HashMap, pub from_agent: String, - #[serde(default = "default_2439")] + #[serde(default = "default_2443")] pub from_subject: String, - #[serde(default = "default_2440")] + #[serde(default = "default_2444")] pub origin: String, - #[serde(default = "default_2441")] + #[serde(default = "default_2445")] pub parent_task_id: Option, - #[serde(default = "default_2442")] + #[serde(default = "default_2446")] pub owner: String, - #[serde(default = "default_2443")] + #[serde(default = "default_2447")] pub attempt: Integer, - #[serde(default = "default_2444")] + #[serde(default = "default_2448")] pub fence: Integer, - #[serde(default = "default_2445")] + #[serde(default = "default_2449")] pub lease_until: Option, - #[serde(default = "default_2446")] + #[serde(default = "default_2450")] pub outcome: std::collections::HashMap, - #[serde(default = "default_2447")] + #[serde(default = "default_2451")] pub last_actor: String, pub created_at: String, pub updated_at: String, @@ -56218,7 +56250,7 @@ pub struct TaskPayload { #[non_exhaustive] pub struct TaskOutput { pub task: TaskPayload, - #[serde(default = "default_2448")] + #[serde(default = "default_2452")] pub seq: Integer, } @@ -56619,10 +56651,10 @@ impl TaskCompleteInput { pub struct InboxCount { pub inbox: String, pub status: String, - #[serde(default = "default_2449")] + #[serde(default = "default_2453")] pub blocked_on: String, pub n: Integer, - #[serde(default = "default_2450")] + #[serde(default = "default_2454")] pub oldest: Option, } @@ -56709,7 +56741,7 @@ pub struct TaskCreateOutput { pub task: TaskPayload, pub created: bool, pub seq: Integer, - #[serde(default = "default_2451")] + #[serde(default = "default_2455")] pub next: String, } @@ -57048,7 +57080,7 @@ impl TaskFailInput { #[non_exhaustive] pub struct TaskGetOutput { pub found: bool, - #[serde(default = "default_2452")] + #[serde(default = "default_2456")] pub task: Option, } @@ -57182,23 +57214,23 @@ pub struct TaskEventPayload { pub task_id: String, pub inbox: String, pub event: String, - #[serde(default = "default_2453")] + #[serde(default = "default_2457")] pub from_status: String, - #[serde(default = "default_2454")] + #[serde(default = "default_2458")] pub to_status: String, - #[serde(default = "default_2455")] + #[serde(default = "default_2459")] pub actor: String, - #[serde(default = "default_2456")] + #[serde(default = "default_2460")] pub agent: String, - #[serde(default = "default_2457")] + #[serde(default = "default_2461")] pub fence: Integer, - #[serde(default = "default_2458")] + #[serde(default = "default_2462")] pub version: Integer, - #[serde(default = "default_2459")] + #[serde(default = "default_2463")] pub reason: String, - #[serde(default = "default_2460")] + #[serde(default = "default_2464")] pub patch: std::collections::HashMap, - #[serde(default = "default_2461")] + #[serde(default = "default_2465")] pub note: String, pub ts: String, } @@ -57538,7 +57570,7 @@ pub struct TaskPullOutput { pub tasks: Vec, pub waited_ms: Integer, pub backend: String, - #[serde(default = "default_2462")] + #[serde(default = "default_2466")] pub note: String, } @@ -57934,7 +57966,7 @@ impl TaskUnblockInput { pub struct TaskUpdateOutput { pub task: TaskPayload, pub seq: Integer, - #[serde(default = "default_2463")] + #[serde(default = "default_2467")] pub conflict: bool, } @@ -58297,19 +58329,19 @@ impl TaskReasonInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerAnswerOutput { - #[serde(default = "default_2464")] + #[serde(default = "default_2468")] pub intent: String, - #[serde(default = "default_2465")] + #[serde(default = "default_2469")] pub anchors: std::collections::HashMap, - #[serde(default = "default_2466")] + #[serde(default = "default_2470")] pub sections: Vec>, - #[serde(default = "default_2467")] + #[serde(default = "default_2471")] pub searched: Vec, - #[serde(default = "default_2468")] + #[serde(default = "default_2472")] pub lines: Vec, - #[serde(default = "default_2469")] + #[serde(default = "default_2473")] pub restricted: bool, - #[serde(default = "default_2470")] + #[serde(default = "default_2474")] pub verdict: String, } @@ -58405,17 +58437,17 @@ impl TrackerAnswerInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerBindingOutput { - #[serde(default = "default_2471")] + #[serde(default = "default_2475")] pub tracker_namespace: String, - #[serde(default = "default_2472")] + #[serde(default = "default_2476")] pub tracker_namespaces: Vec, - #[serde(default = "default_2473")] + #[serde(default = "default_2477")] pub restricted: bool, - #[serde(default = "default_2474")] + #[serde(default = "default_2478")] pub kind: String, - #[serde(default = "default_2475")] + #[serde(default = "default_2479")] pub authorized: bool, - #[serde(default = "default_2476")] + #[serde(default = "default_2480")] pub templates: Vec, } @@ -58468,13 +58500,13 @@ impl TrackerBindingInput { #[non_exhaustive] pub struct TrackerComponentOutput { pub component: String, - #[serde(default = "default_2477")] + #[serde(default = "default_2481")] pub risk: std::collections::HashMap, - #[serde(default = "default_2478")] + #[serde(default = "default_2482")] pub open_issues: Vec>, - #[serde(default = "default_2479")] + #[serde(default = "default_2483")] pub known: bool, - #[serde(default = "default_2480")] + #[serde(default = "default_2484")] pub tracker_unavailable: bool, } @@ -58535,9 +58567,9 @@ impl TrackerComponentInput { #[non_exhaustive] pub struct TrackerContractOutput { pub database: String, - #[serde(default = "default_2481")] + #[serde(default = "default_2485")] pub tables: Vec>, - #[serde(default = "default_2482")] + #[serde(default = "default_2486")] pub templates: std::collections::HashMap, } @@ -58590,66 +58622,66 @@ impl TrackerContractInput { #[non_exhaustive] pub struct TrackerLegStatus { pub name: String, - #[serde(default = "default_2493")] + #[serde(default = "default_2497")] pub status: String, - #[serde(default = "default_2494")] + #[serde(default = "default_2498")] pub reason: String, - #[serde(default = "default_2495")] + #[serde(default = "default_2499")] pub message: String, - #[serde(default = "default_2496")] + #[serde(default = "default_2500")] pub retried: bool, - #[serde(default = "default_2497")] + #[serde(default = "default_2501")] pub ms: Integer, - #[serde(default = "default_2498")] + #[serde(default = "default_2502")] pub cause: String, - #[serde(default = "default_2499")] + #[serde(default = "default_2503")] pub namespace: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerDuplicateCheckOutput { - #[serde(default = "default_2483")] + #[serde(default = "default_2487")] pub verdict: String, - #[serde(default = "default_2484")] + #[serde(default = "default_2488")] pub items: Vec>, - #[serde(default = "default_2485")] + #[serde(default = "default_2489")] pub undecided: bool, - #[serde(default = "default_2486")] + #[serde(default = "default_2490")] pub epistemic: String, - #[serde(default = "default_2487")] + #[serde(default = "default_2491")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2488")] + #[serde(default = "default_2492")] pub judge: std::collections::HashMap, - #[serde(default = "default_2489")] + #[serde(default = "default_2493")] pub fit_at: String, - #[serde(default = "default_2490")] + #[serde(default = "default_2494")] pub fit: std::collections::HashMap, - #[serde(default = "default_2491")] + #[serde(default = "default_2495")] pub query: std::collections::HashMap, - #[serde(default = "default_2492")] + #[serde(default = "default_2496")] pub legs: std::collections::HashMap, - #[serde(default = "default_2500")] + #[serde(default = "default_2504")] pub leg_status: Vec, - #[serde(default = "default_2501")] + #[serde(default = "default_2505")] pub tracker_unavailable: bool, - #[serde(default = "default_2502")] + #[serde(default = "default_2506")] pub namespaces: Vec, - #[serde(default = "default_2503")] + #[serde(default = "default_2507")] pub by_namespace: std::collections::HashMap>, - #[serde(default = "default_2504")] + #[serde(default = "default_2508")] pub closest: Vec>, - #[serde(default = "default_2505")] + #[serde(default = "default_2509")] pub needs: Vec>, - #[serde(default = "default_2506")] + #[serde(default = "default_2510")] pub closest_note: String, - #[serde(default = "default_2507")] + #[serde(default = "default_2511")] pub nearest: Vec>, - #[serde(default = "default_2508")] + #[serde(default = "default_2512")] pub rerank: std::collections::HashMap, - #[serde(default = "default_2509")] + #[serde(default = "default_2513")] pub answer: String, - #[serde(default = "default_2510")] + #[serde(default = "default_2514")] pub related_prs: Vec>, } @@ -58856,17 +58888,17 @@ impl TrackerDuplicateCheckInput { #[non_exhaustive] pub struct TrackerFlakyOutput { pub test_name: String, - #[serde(default = "default_2511")] + #[serde(default = "default_2515")] pub known_flaky: bool, - #[serde(default = "default_2512")] + #[serde(default = "default_2516")] pub open_issues: Integer, - #[serde(default = "default_2513")] + #[serde(default = "default_2517")] pub issues: Vec>, - #[serde(default = "default_2514")] + #[serde(default = "default_2518")] pub verdict: String, - #[serde(default = "default_2515")] + #[serde(default = "default_2519")] pub tracker_unavailable: bool, - #[serde(default = "default_2516")] + #[serde(default = "default_2520")] pub signal: Option>, } @@ -58949,9 +58981,9 @@ impl TrackerFlakyInput { #[non_exhaustive] pub struct TrackerItemOutput { pub items: Vec>, - #[serde(default = "default_2517")] + #[serde(default = "default_2521")] pub unknown: Vec, - #[serde(default = "default_2518")] + #[serde(default = "default_2522")] pub tracker_unavailable: bool, } @@ -59000,19 +59032,19 @@ impl TrackerItemInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerLinksOutput { - #[serde(default = "default_2519")] + #[serde(default = "default_2523")] pub subject: std::collections::HashMap, - #[serde(default = "default_2520")] + #[serde(default = "default_2524")] pub verdict: String, - #[serde(default = "default_2521")] + #[serde(default = "default_2525")] pub items: Vec>, - #[serde(default = "default_2522")] + #[serde(default = "default_2526")] pub epistemic: String, - #[serde(default = "default_2523")] + #[serde(default = "default_2527")] pub record: std::collections::HashMap, - #[serde(default = "default_2524")] + #[serde(default = "default_2528")] pub computed_at: String, - #[serde(default = "default_2525")] + #[serde(default = "default_2529")] pub tracker_unavailable: bool, } @@ -59110,11 +59142,11 @@ impl TrackerLinksInput { pub struct TrackerReleaseOutput { pub version: String, pub blockers: Vec>, - #[serde(default = "default_2526")] + #[serde(default = "default_2530")] pub active_blockers: Integer, - #[serde(default = "default_2527")] + #[serde(default = "default_2531")] pub health: std::collections::HashMap, - #[serde(default = "default_2528")] + #[serde(default = "default_2532")] pub tracker_unavailable: bool, } @@ -59163,17 +59195,17 @@ impl TrackerReleaseInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSimilarOutput { - #[serde(default = "default_2529")] + #[serde(default = "default_2533")] pub items: Vec>, - #[serde(default = "default_2530")] + #[serde(default = "default_2534")] pub query: std::collections::HashMap, - #[serde(default = "default_2531")] + #[serde(default = "default_2535")] pub legs: std::collections::HashMap, - #[serde(default = "default_2532")] + #[serde(default = "default_2536")] pub epistemic: String, - #[serde(default = "default_2533")] + #[serde(default = "default_2537")] pub tracker_unavailable: bool, - #[serde(default = "default_2534")] + #[serde(default = "default_2538")] pub namespaces: Vec, } @@ -59294,19 +59326,19 @@ pub struct TrackerSourceAddOutput { pub name: String, pub host: String, pub database: String, - #[serde(default = "default_2535")] + #[serde(default = "default_2539")] pub namespaces: Vec>, - #[serde(default = "default_2536")] + #[serde(default = "default_2540")] pub contract: std::collections::HashMap, - #[serde(default = "default_2537")] + #[serde(default = "default_2541")] pub roles: Vec, - #[serde(default = "default_2538")] + #[serde(default = "default_2542")] pub my_role: String, - #[serde(default = "default_2539")] + #[serde(default = "default_2543")] pub dry_run: bool, - #[serde(default = "default_2540")] + #[serde(default = "default_2544")] pub written: bool, - #[serde(default = "default_2541")] + #[serde(default = "default_2545")] pub view_templates: std::collections::HashMap, } @@ -59469,13 +59501,13 @@ impl TrackerSourceAddInput { #[non_exhaustive] pub struct TrackerSourceCheckOutput { pub name: String, - #[serde(default = "default_2542")] + #[serde(default = "default_2546")] pub database: String, - #[serde(default = "default_2543")] + #[serde(default = "default_2547")] pub reachable: bool, - #[serde(default = "default_2544")] + #[serde(default = "default_2548")] pub contract: std::collections::HashMap, - #[serde(default = "default_2545")] + #[serde(default = "default_2549")] pub view_templates: std::collections::HashMap, } @@ -59515,11 +59547,11 @@ impl TrackerSourceCheckInput { pub struct TrackerSourceInspectOutput { pub host: String, pub database: String, - #[serde(default = "default_2546")] + #[serde(default = "default_2550")] pub tables: Vec>, - #[serde(default = "default_2547")] + #[serde(default = "default_2551")] pub roles: Vec, - #[serde(default = "default_2548")] + #[serde(default = "default_2552")] pub proposal: std::collections::HashMap, } @@ -59648,9 +59680,9 @@ impl TrackerSourceInspectInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSourceListOutput { - #[serde(default = "default_2549")] + #[serde(default = "default_2553")] pub sources: Vec>, - #[serde(default = "default_2550")] + #[serde(default = "default_2554")] pub self_service: bool, } @@ -59703,9 +59735,9 @@ impl TrackerSourceListInput { #[non_exhaustive] pub struct TrackerSourceRemoveOutput { pub name: String, - #[serde(default = "default_2551")] + #[serde(default = "default_2555")] pub deactivated: bool, - #[serde(default = "default_2552")] + #[serde(default = "default_2556")] pub namespaces_retired: Vec, } @@ -59746,9 +59778,9 @@ impl TrackerSourceRemoveInput { #[non_exhaustive] pub struct TrackerSourceRotateOutput { pub name: String, - #[serde(default = "default_2553")] + #[serde(default = "default_2557")] pub contract: std::collections::HashMap, - #[serde(default = "default_2554")] + #[serde(default = "default_2558")] pub rotated_at: String, } @@ -59795,11 +59827,11 @@ impl TrackerSourceRotateInput { #[non_exhaustive] pub struct TrackerSourceSetMappingOutput { pub name: String, - #[serde(default = "default_2555")] + #[serde(default = "default_2559")] pub contract: std::collections::HashMap, - #[serde(default = "default_2556")] + #[serde(default = "default_2560")] pub dry_run: bool, - #[serde(default = "default_2557")] + #[serde(default = "default_2561")] pub written: bool, } @@ -59866,45 +59898,45 @@ impl TrackerSourceSetMappingInput { #[non_exhaustive] pub struct TrackerTestSignalOutput { pub test_name: String, - #[serde(default = "default_2558")] + #[serde(default = "default_2562")] pub verdict: String, - #[serde(default = "default_2559")] + #[serde(default = "default_2563")] pub why: Vec, - #[serde(default = "default_2560")] + #[serde(default = "default_2564")] pub lower_bound: f64, - #[serde(default = "default_2561")] + #[serde(default = "default_2565")] pub window_days: Integer, - #[serde(default = "default_2562")] + #[serde(default = "default_2566")] pub since: String, - #[serde(default = "default_2563")] + #[serde(default = "default_2567")] pub features: std::collections::HashMap, - #[serde(default = "default_2564")] + #[serde(default = "default_2568")] pub infra: std::collections::HashMap, - #[serde(default = "default_2565")] + #[serde(default = "default_2569")] pub churn: std::collections::HashMap, - #[serde(default = "default_2566")] + #[serde(default = "default_2570")] pub thresholds: std::collections::HashMap, - #[serde(default = "default_2567")] + #[serde(default = "default_2571")] pub source: String, - #[serde(default = "default_2568")] + #[serde(default = "default_2572")] pub timings_ms: std::collections::HashMap, - #[serde(default = "default_2569")] + #[serde(default = "default_2573")] pub tracker_unavailable: bool, - #[serde(default = "default_2570")] + #[serde(default = "default_2574")] pub rollup: std::collections::HashMap, - #[serde(default = "default_2571")] + #[serde(default = "default_2575")] pub streak: std::collections::HashMap, - #[serde(default = "default_2572")] + #[serde(default = "default_2576")] pub smells: std::collections::HashMap, - #[serde(default = "default_2573")] + #[serde(default = "default_2577")] pub prior: std::collections::HashMap, - #[serde(default = "default_2574")] + #[serde(default = "default_2578")] pub unavailable_reason: String, - #[serde(default = "default_2575")] + #[serde(default = "default_2579")] pub candidates: Vec>, - #[serde(default = "default_2576")] + #[serde(default = "default_2580")] pub candidate_matches: Integer, - #[serde(default = "default_2577")] + #[serde(default = "default_2581")] pub resolved_from: String, } @@ -60008,9 +60040,9 @@ impl TrackerTestSignalInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct UiVitalsOutput { - #[serde(default = "default_2578")] + #[serde(default = "default_2582")] pub recorded: bool, - #[serde(default = "default_2579")] + #[serde(default = "default_2583")] pub route: String, } @@ -60194,7 +60226,7 @@ pub struct WebhookDelivery { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookDeliveriesOutput { - #[serde(default = "default_2580")] + #[serde(default = "default_2584")] pub deliveries: Vec, } @@ -60316,14 +60348,14 @@ pub struct WebhookInfo { pub secret_ref: String, pub events: Vec, pub created_at: String, - #[serde(default = "default_2581")] + #[serde(default = "default_2585")] pub secret_present: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookListOutput { - #[serde(default = "default_2582")] + #[serde(default = "default_2586")] pub webhooks: Vec, } @@ -60505,7 +60537,7 @@ pub struct WorkingMemoryMutationOutput { pub version: Integer, pub char_limit: Integer, pub value_length: Integer, - #[serde(default = "default_2583")] + #[serde(default = "default_2587")] pub fill_ratio: f64, } @@ -60729,15 +60761,15 @@ impl WorkingMemoryDeleteInput { pub struct WorkingMemoryGetOutput { pub found: bool, pub block_key: String, - #[serde(default = "default_2584")] + #[serde(default = "default_2588")] pub content: String, - #[serde(default = "default_2585")] + #[serde(default = "default_2589")] pub char_limit: Integer, - #[serde(default = "default_2586")] + #[serde(default = "default_2590")] pub version: Integer, - #[serde(default = "default_2587")] + #[serde(default = "default_2591")] pub updated_at: Option, - #[serde(default = "default_2588")] + #[serde(default = "default_2592")] pub fill_ratio: f64, } @@ -60848,7 +60880,7 @@ pub struct WorkingMemoryBlock { pub content: String, pub char_limit: Integer, pub version: Integer, - #[serde(default = "default_2589")] + #[serde(default = "default_2593")] pub updated_at: Option, } @@ -60856,7 +60888,7 @@ pub struct WorkingMemoryBlock { #[non_exhaustive] pub struct WorkingMemoryRenderOutput { pub rendered: String, - #[serde(default = "default_2590")] + #[serde(default = "default_2594")] pub blocks: Vec, pub block_count: Integer, pub total_chars: Integer, @@ -67884,1131 +67916,1144 @@ fn default_2213() -> Option { fn default_2214() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2215() -> String { +fn default_2215() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_2216() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2217() -> OpsIncidentSourcesRead { + serde_json::from_str("\"unread\"").expect("schema default") +} +fn default_2218() -> OpsIncidentSources { + serde_json::from_str("{\"failing\":0,\"sample\":[],\"read\":\"unread\"}") + .expect("schema default") +} +fn default_2219() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2216() -> String { +fn default_2220() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2217() -> String { +fn default_2221() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2218() -> Vec { +fn default_2222() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2219() -> String { +fn default_2223() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2220() -> String { +fn default_2224() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2221() -> std::collections::HashMap { +fn default_2225() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2222() -> String { +fn default_2226() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2223() -> Option { +fn default_2227() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2224() -> Option { +fn default_2228() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2225() -> bool { +fn default_2229() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2226() -> String { +fn default_2230() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2227() -> String { +fn default_2231() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2228() -> Vec { +fn default_2232() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2229() -> Integer { +fn default_2233() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2230() -> String { +fn default_2234() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2231() -> String { +fn default_2235() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2232() -> Option { +fn default_2236() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2233() -> bool { +fn default_2237() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2234() -> String { +fn default_2238() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2235() -> bool { +fn default_2239() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2236() -> String { +fn default_2240() -> String { serde_json::from_str("\"inherit\"").expect("schema default") } -fn default_2237() -> Option { +fn default_2241() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2238() -> Option { +fn default_2242() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2239() -> bool { +fn default_2243() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2240() -> Vec { +fn default_2244() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2241() -> Integer { +fn default_2245() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2242() -> ProcedureEvolveOutputGate { +fn default_2246() -> ProcedureEvolveOutputGate { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2243() -> String { +fn default_2247() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2244() -> f64 { +fn default_2248() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2245() -> std::collections::HashMap { +fn default_2249() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2246() -> std::collections::HashMap { +fn default_2250() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2247() -> std::collections::HashMap { +fn default_2251() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2248() -> std::collections::HashMap { +fn default_2252() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2249() -> String { +fn default_2253() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2250() -> Vec { +fn default_2254() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2251() -> Vec { +fn default_2255() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2252() -> Vec { +fn default_2256() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2253() -> std::collections::HashMap { +fn default_2257() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2254() -> Integer { +fn default_2258() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2255() -> bool { +fn default_2259() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2256() -> std::collections::HashMap { +fn default_2260() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2257() -> Vec { +fn default_2261() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2258() -> std::collections::HashMap { +fn default_2262() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2259() -> String { +fn default_2263() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2260() -> ProcedureLocateOutputStatus { +fn default_2264() -> ProcedureLocateOutputStatus { serde_json::from_str("\"authored\"").expect("schema default") } -fn default_2261() -> Option> { +fn default_2265() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2262() -> Vec>> { +fn default_2266() -> Vec>> { serde_json::from_str("[]").expect("schema default") } -fn default_2263() -> Vec { +fn default_2267() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2264() -> Vec { +fn default_2268() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2265() -> std::collections::HashMap { +fn default_2269() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2266() -> bool { +fn default_2270() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2267() -> Vec { +fn default_2271() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2268() -> Vec> { +fn default_2272() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2269() -> String { +fn default_2273() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2270() -> std::collections::HashMap { +fn default_2274() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2271() -> std::collections::HashMap { +fn default_2275() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2272() -> Vec { +fn default_2276() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2273() -> std::collections::HashMap { +fn default_2277() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2274() -> Option> { +fn default_2278() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2275() -> bool { +fn default_2279() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2276() -> std::collections::HashMap { +fn default_2280() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2277() -> ProcedureMatchStatus { +fn default_2281() -> ProcedureMatchStatus { serde_json::from_str("\"authored\"").expect("schema default") } -fn default_2278() -> Option> { +fn default_2282() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2279() -> Vec { +fn default_2283() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2280() -> Integer { +fn default_2284() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_2281() -> Vec> { +fn default_2285() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2282() -> f64 { +fn default_2286() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2283() -> f64 { +fn default_2287() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2284() -> f64 { +fn default_2288() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2285() -> Option { +fn default_2289() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2286() -> std::collections::HashMap { +fn default_2290() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2287() -> std::collections::HashMap> { +fn default_2291() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2288() -> String { +fn default_2292() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2289() -> Integer { +fn default_2293() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2290() -> String { +fn default_2294() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2291() -> f64 { +fn default_2295() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2292() -> Vec { +fn default_2296() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2293() -> ProcedureReviseOutputOutcome { +fn default_2297() -> ProcedureReviseOutputOutcome { serde_json::from_str("\"opened\"").expect("schema default") } -fn default_2294() -> Vec { +fn default_2298() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2295() -> Vec { +fn default_2299() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2296() -> String { +fn default_2300() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2297() -> String { +fn default_2301() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2298() -> String { +fn default_2302() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2299() -> String { +fn default_2303() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2300() -> Option { +fn default_2304() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2301() -> Integer { +fn default_2305() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2302() -> Vec { +fn default_2306() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2303() -> std::collections::HashMap { +fn default_2307() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2304() -> Option { +fn default_2308() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2305() -> String { +fn default_2309() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2306() -> Integer { +fn default_2310() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2307() -> String { +fn default_2311() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2308() -> String { +fn default_2312() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2309() -> std::collections::HashMap { +fn default_2313() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2310() -> String { +fn default_2314() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2311() -> String { +fn default_2315() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2312() -> Option { +fn default_2316() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2313() -> RunBeginOutputStatus { +fn default_2317() -> RunBeginOutputStatus { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2314() -> String { +fn default_2318() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2315() -> Integer { +fn default_2319() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2316() -> Integer { +fn default_2320() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2317() -> Integer { +fn default_2321() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2318() -> Integer { +fn default_2322() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2319() -> Vec { +fn default_2323() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2320() -> Integer { +fn default_2324() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_2321() -> Integer { +fn default_2325() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2322() -> Integer { +fn default_2326() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2323() -> String { +fn default_2327() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2324() -> String { +fn default_2328() -> String { serde_json::from_str("\"keep\"").expect("schema default") } -fn default_2325() -> Integer { +fn default_2329() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2326() -> Integer { +fn default_2330() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2327() -> Integer { +fn default_2331() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2328() -> Option { +fn default_2332() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2329() -> Integer { +fn default_2333() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_2330() -> Vec { +fn default_2334() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2331() -> Vec { +fn default_2335() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2332() -> Integer { +fn default_2336() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2333() -> Integer { +fn default_2337() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2334() -> Integer { +fn default_2338() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2335() -> f64 { +fn default_2339() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2336() -> Integer { +fn default_2340() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2337() -> Vec { +fn default_2341() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2338() -> Integer { +fn default_2342() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2339() -> Vec { +fn default_2343() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2340() -> Integer { +fn default_2344() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2341() -> Integer { +fn default_2345() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2342() -> Integer { +fn default_2346() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2343() -> Vec { +fn default_2347() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2344() -> Option { +fn default_2348() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2345() -> String { +fn default_2349() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2346() -> Integer { +fn default_2350() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2347() -> Integer { +fn default_2351() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2348() -> Integer { +fn default_2352() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2349() -> Integer { +fn default_2353() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2350() -> bool { +fn default_2354() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2351() -> bool { +fn default_2355() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2352() -> Option> { +fn default_2356() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2353() -> LiveSearchResultsLive { +fn default_2357() -> LiveSearchResultsLive { serde_json::from_str("true").expect("schema default") } -fn default_2354() -> String { +fn default_2358() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2355() -> LiveSearchHitLive { +fn default_2359() -> LiveSearchHitLive { serde_json::from_str("true").expect("schema default") } -fn default_2356() -> Vec { +fn default_2360() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2357() -> Option { +fn default_2361() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2358() -> std::collections::HashMap { +fn default_2362() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2359() -> std::collections::HashMap { +fn default_2363() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2360() -> std::collections::HashMap { +fn default_2364() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2361() -> std::collections::HashMap { +fn default_2365() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2362() -> Option> { +fn default_2366() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2363() -> Vec { +fn default_2367() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2364() -> Integer { +fn default_2368() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2365() -> String { +fn default_2369() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2366() -> Integer { +fn default_2370() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2367() -> String { +fn default_2371() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2368() -> String { +fn default_2372() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2369() -> String { +fn default_2373() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2370() -> String { +fn default_2374() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2371() -> String { +fn default_2375() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2372() -> String { +fn default_2376() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2373() -> String { +fn default_2377() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2374() -> String { +fn default_2378() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2375() -> Vec { +fn default_2379() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2376() -> String { +fn default_2380() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2377() -> String { +fn default_2381() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2378() -> Vec { +fn default_2382() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2379() -> String { +fn default_2383() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2380() -> String { +fn default_2384() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2381() -> Vec { +fn default_2385() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2382() -> Vec { +fn default_2386() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2383() -> Vec { +fn default_2387() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2384() -> String { +fn default_2388() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2385() -> String { +fn default_2389() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2386() -> Vec { +fn default_2390() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2387() -> Vec { +fn default_2391() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2388() -> Vec { +fn default_2392() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2389() -> String { +fn default_2393() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2390() -> String { +fn default_2394() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2391() -> Option { +fn default_2395() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2392() -> String { +fn default_2396() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2393() -> String { +fn default_2397() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2394() -> String { +fn default_2398() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2395() -> String { +fn default_2399() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2396() -> String { +fn default_2400() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2397() -> String { +fn default_2401() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2398() -> Vec { +fn default_2402() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2399() -> Option { +fn default_2403() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2400() -> Integer { +fn default_2404() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2401() -> Integer { +fn default_2405() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2402() -> Integer { +fn default_2406() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2403() -> Integer { +fn default_2407() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2404() -> Integer { +fn default_2408() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2405() -> bool { +fn default_2409() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2406() -> String { +fn default_2410() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2407() -> String { +fn default_2411() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2408() -> String { +fn default_2412() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2409() -> String { +fn default_2413() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2410() -> String { +fn default_2414() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2411() -> String { +fn default_2415() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2412() -> String { +fn default_2416() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2413() -> Option { +fn default_2417() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2414() -> Integer { +fn default_2418() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2415() -> Integer { +fn default_2419() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2416() -> Vec { +fn default_2420() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2417() -> String { +fn default_2421() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2418() -> String { +fn default_2422() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2419() -> String { +fn default_2423() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2420() -> String { +fn default_2424() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2421() -> Integer { +fn default_2425() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2422() -> Integer { +fn default_2426() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2423() -> Integer { +fn default_2427() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2424() -> Integer { +fn default_2428() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2425() -> Integer { +fn default_2429() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2426() -> f64 { +fn default_2430() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2427() -> Integer { +fn default_2431() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2428() -> Integer { +fn default_2432() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2429() -> Integer { +fn default_2433() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2430() -> String { +fn default_2434() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2431() -> SessionBriefStats { +fn default_2435() -> 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_2432() -> String { +fn default_2436() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2433() -> String { +fn default_2437() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2434() -> Option { +fn default_2438() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2435() -> Option { +fn default_2439() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2436() -> Option { +fn default_2440() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2437() -> Integer { +fn default_2441() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2438() -> std::collections::HashMap { +fn default_2442() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2439() -> String { +fn default_2443() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2440() -> String { +fn default_2444() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2441() -> Option { +fn default_2445() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2442() -> String { +fn default_2446() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2443() -> Integer { +fn default_2447() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2444() -> Integer { +fn default_2448() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2445() -> Option { +fn default_2449() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2446() -> std::collections::HashMap { +fn default_2450() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2447() -> String { +fn default_2451() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2448() -> Integer { +fn default_2452() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2449() -> String { +fn default_2453() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2450() -> Option { +fn default_2454() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2451() -> String { +fn default_2455() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2452() -> Option { +fn default_2456() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2453() -> String { +fn default_2457() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2454() -> String { +fn default_2458() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2455() -> String { +fn default_2459() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2456() -> String { +fn default_2460() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2457() -> Integer { +fn default_2461() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2458() -> Integer { +fn default_2462() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2459() -> String { +fn default_2463() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2460() -> std::collections::HashMap { +fn default_2464() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2461() -> String { +fn default_2465() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2462() -> String { +fn default_2466() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2463() -> bool { +fn default_2467() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2464() -> String { +fn default_2468() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2465() -> std::collections::HashMap { +fn default_2469() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2466() -> Vec> { +fn default_2470() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2467() -> Vec { +fn default_2471() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2468() -> Vec { +fn default_2472() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2469() -> bool { +fn default_2473() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2470() -> String { +fn default_2474() -> String { serde_json::from_str("\"unknown\"").expect("schema default") } -fn default_2471() -> String { +fn default_2475() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2472() -> Vec { +fn default_2476() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2473() -> bool { +fn default_2477() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2474() -> String { +fn default_2478() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2475() -> bool { +fn default_2479() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2476() -> Vec { +fn default_2480() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2477() -> std::collections::HashMap { +fn default_2481() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2478() -> Vec> { +fn default_2482() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2479() -> bool { +fn default_2483() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2480() -> bool { +fn default_2484() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2481() -> Vec> { +fn default_2485() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2482() -> std::collections::HashMap { +fn default_2486() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2483() -> String { +fn default_2487() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2484() -> Vec> { +fn default_2488() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2485() -> bool { +fn default_2489() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2486() -> String { +fn default_2490() -> String { serde_json::from_str("\"calibrated\"").expect("schema default") } -fn default_2487() -> std::collections::HashMap { +fn default_2491() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2488() -> std::collections::HashMap { +fn default_2492() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2489() -> String { +fn default_2493() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2490() -> std::collections::HashMap { +fn default_2494() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2491() -> std::collections::HashMap { +fn default_2495() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2492() -> std::collections::HashMap { +fn default_2496() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2493() -> String { +fn default_2497() -> String { serde_json::from_str("\"ok\"").expect("schema default") } -fn default_2494() -> String { +fn default_2498() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2495() -> String { +fn default_2499() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2496() -> bool { +fn default_2500() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2497() -> Integer { +fn default_2501() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2498() -> String { +fn default_2502() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2499() -> String { +fn default_2503() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2500() -> Vec { +fn default_2504() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2501() -> bool { +fn default_2505() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2502() -> Vec { +fn default_2506() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2503() -> std::collections::HashMap> { +fn default_2507() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2504() -> Vec> { +fn default_2508() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2505() -> Vec> { +fn default_2509() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2506() -> String { +fn default_2510() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2507() -> Vec> { +fn default_2511() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2508() -> std::collections::HashMap { +fn default_2512() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2509() -> String { +fn default_2513() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2510() -> Vec> { +fn default_2514() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2511() -> bool { +fn default_2515() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2512() -> Integer { +fn default_2516() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2513() -> Vec> { +fn default_2517() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2514() -> String { +fn default_2518() -> String { serde_json::from_str("\"no_flaky_signal\"").expect("schema default") } -fn default_2515() -> bool { +fn default_2519() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2516() -> Option> { +fn default_2520() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2517() -> Vec { +fn default_2521() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2518() -> bool { +fn default_2522() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2519() -> std::collections::HashMap { +fn default_2523() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2520() -> String { +fn default_2524() -> String { serde_json::from_str("\"not_computed\"").expect("schema default") } -fn default_2521() -> Vec> { +fn default_2525() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2522() -> String { +fn default_2526() -> String { serde_json::from_str("\"candidate\"").expect("schema default") } -fn default_2523() -> std::collections::HashMap { +fn default_2527() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2524() -> String { +fn default_2528() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2525() -> bool { +fn default_2529() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2526() -> Integer { +fn default_2530() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2527() -> std::collections::HashMap { +fn default_2531() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2528() -> bool { +fn default_2532() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2529() -> Vec> { +fn default_2533() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2530() -> std::collections::HashMap { +fn default_2534() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2531() -> std::collections::HashMap { +fn default_2535() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2532() -> String { +fn default_2536() -> String { serde_json::from_str("\"lower_bound\"").expect("schema default") } -fn default_2533() -> bool { +fn default_2537() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2534() -> Vec { +fn default_2538() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2535() -> Vec> { +fn default_2539() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2536() -> std::collections::HashMap { +fn default_2540() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2537() -> Vec { +fn default_2541() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2538() -> String { +fn default_2542() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2539() -> bool { +fn default_2543() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2540() -> bool { +fn default_2544() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2541() -> std::collections::HashMap { +fn default_2545() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2542() -> String { +fn default_2546() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2543() -> bool { +fn default_2547() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2544() -> std::collections::HashMap { +fn default_2548() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2545() -> std::collections::HashMap { +fn default_2549() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2546() -> Vec> { +fn default_2550() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2547() -> Vec { +fn default_2551() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2548() -> std::collections::HashMap { +fn default_2552() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2549() -> Vec> { +fn default_2553() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2550() -> bool { +fn default_2554() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2551() -> bool { +fn default_2555() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2552() -> Vec { +fn default_2556() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2553() -> std::collections::HashMap { +fn default_2557() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2554() -> String { +fn default_2558() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2555() -> std::collections::HashMap { +fn default_2559() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2556() -> bool { +fn default_2560() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2557() -> bool { +fn default_2561() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2558() -> String { +fn default_2562() -> String { serde_json::from_str("\"no_signal\"").expect("schema default") } -fn default_2559() -> Vec { +fn default_2563() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2560() -> f64 { +fn default_2564() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2561() -> Integer { +fn default_2565() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2562() -> String { +fn default_2566() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2563() -> std::collections::HashMap { +fn default_2567() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2564() -> std::collections::HashMap { +fn default_2568() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2565() -> std::collections::HashMap { +fn default_2569() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2566() -> std::collections::HashMap { +fn default_2570() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2567() -> String { +fn default_2571() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2568() -> std::collections::HashMap { +fn default_2572() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2569() -> bool { +fn default_2573() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2570() -> std::collections::HashMap { +fn default_2574() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2571() -> std::collections::HashMap { +fn default_2575() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2572() -> std::collections::HashMap { +fn default_2576() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2573() -> std::collections::HashMap { +fn default_2577() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2574() -> String { +fn default_2578() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2575() -> Vec> { +fn default_2579() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2576() -> Integer { +fn default_2580() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2577() -> String { +fn default_2581() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2578() -> bool { +fn default_2582() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2579() -> String { +fn default_2583() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2580() -> Vec { +fn default_2584() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2581() -> bool { +fn default_2585() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2582() -> Vec { +fn default_2586() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2583() -> f64 { +fn default_2587() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2584() -> String { +fn default_2588() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2585() -> Integer { +fn default_2589() -> Integer { serde_json::from_str("4096").expect("schema default") } -fn default_2586() -> Integer { +fn default_2590() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2587() -> Option { +fn default_2591() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2588() -> f64 { +fn default_2592() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2589() -> Option { +fn default_2593() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2590() -> Vec { +fn default_2594() -> 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 4e5e0df26c4..fe9b3048bec 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -6809,6 +6809,14 @@ fn ops_incidents() { serde_json::from_str::("[]").unwrap(), "ops.incidents:incidents" ); + assert_eq!( + encoded["sources"], + serde_json::from_str::( + "{\"failing\":0,\"sample\":[],\"read\":\"unread\"}" + ) + .unwrap(), + "ops.incidents:sources" + ); } #[test] fn ops_projection_failures_list() { diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index bd0022dd4ab..162e338b630 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -8969,11 +8969,24 @@ export interface OpsIncident { age_s?: number | null; } +export interface OpsIncidentSources { + failing?: number; + sample?: OpsFailingSource[]; + read?: "read" | "not_permitted" | "unread"; +} + +export interface OpsFailingSource { + namespace: string; + name: string; + status: string; +} + export interface OpsIncidentsOutput { status: "ok" | "degraded"; incidents?: OpsIncident[]; window_minutes: number; requests: "read" | "not_permitted" | "unread"; + sources?: OpsIncidentSources; } export interface OpsProjectionFailuresListInput { diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index a7acb12e64a..2d54f16188d 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -168,10 +168,11 @@ 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, which only a caller that reads the org whole (an - 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).""" + calls that failed on the server; beside them, the org's document sources whose last + sync failed. Only a caller that reads the org whole (an org admin over `*`, a platform + admin) reads the calls and the sources; `requests` and `sources.read` say whether + they were read. Identity is optional: the org is the token's (role check only; no + namespace is addressed).""" org: str = "" @@ -196,7 +197,33 @@ class OpsIncident(BaseModel): age_s: float | None = None -RequestsRead = Literal["read", "not_permitted", "unread"] +OrgRead = Literal["read", "not_permitted", "unread"] + + +class OpsFailingSource(BaseModel): + # The namespace the source's documents live in. + namespace: str + # The source's name, as `knowledge.source.list` lists it. + name: str + # How its last sync turn ended: `failed`, `rate_limited` or `credential_invalid`. + status: str + + +class OpsIncidentSources(BaseModel): + """The org's own document sources whose last sync turn failed. + + Those every reader of their namespace sees, never a mirrored one. A source's failure + is its own (its `sync.status` in `knowledge.source.list`), so it never makes `status` + `degraded`: a revoked credential is its org's to fix, not a Loom outage.""" + + # Sources whose last turn failed; 0 unless `read` is `read`. + failing: int = 0 + # At most 5 of them, the latest failure first. + sample: list[OpsFailingSource] = Field(default_factory=list) + # Whether they were read, as for `requests`: `read`; `not_permitted` when the call + # names no single org or the caller does not read the org whole; `unread` when they, + # the restricted set or a restricted namespace's grant could not be read. + read: OrgRead = "unread" class OpsIncidentsOutput(BaseModel): @@ -204,7 +231,7 @@ class OpsIncidentsOutput(BaseModel): 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`. + # `degraded` when an incident is listed, else `ok`; failing `sources` never count. status: Literal["ok", "degraded"] # Errors first, at most 20. incidents: list[OpsIncident] = Field(default_factory=list) @@ -215,4 +242,7 @@ class OpsIncidentsOutput(BaseModel): # 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 + requests: OrgRead + # The org's document sources whose last sync failed, for its admin to fix; a server + # of an earlier build leaves it out. + sources: OpsIncidentSources = Field(default_factory=OpsIncidentSources) diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index a7a6ca73bb3..890ff7e3b48 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -4,11 +4,14 @@ incident. The answer comes from what the server already keeps: its readiness checks, 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 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 +(`loom_telemetry.sli_minute`). Beside the incidents it names the org's document sources +whose last sync failed (their sync states), which are the org's to fix and never make +the answer `degraded`. Nothing names another org: a provider or worker incident carries +an error's kind, never its text, and the request counts and the sources 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; a source names its namespace). Each ClickHouse source is read at +most once per `_SOURCE_TTL_S` per process (per org for the org's), 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. @@ -24,10 +27,12 @@ from server.core.errors import LoomServerError, caller_text, error_kind from server.insights.api.models_ops import ( + OpsFailingSource, OpsIncident, OpsIncidentsInput, + OpsIncidentSources, OpsIncidentsOutput, - RequestsRead, + OrgRead, ) from server.insights.store import ops as ops_store from server.observability import degradations, provider_health @@ -35,6 +40,8 @@ # not a setting: the bound the output model documents MAX_INCIDENTS = 20 +# not a setting: the bound the output model documents +MAX_SOURCE_SAMPLE = 5 # 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 @@ -45,9 +52,9 @@ # not a setting: a memory bound, not a behaviour _CACHE_MAX = 1024 -# (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]] = {} +# (source, org) -> (read at, what it read, the read's failure or ""), and the lock its +# polls share while one reads +_cache: dict[tuple[str, str], tuple[float, Any, str]] = {} _locks: dict[tuple[str, str], asyncio.Lock] = {} @@ -55,13 +62,13 @@ def _line(text: object) -> str: return " ".join(str(text).split())[:200] -async def _cached( - source: str, org: str, read: Callable[[], Awaitable[list[OpsIncident]]] -) -> 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.""" +async def _cached[T]( + source: str, org: str, read: Callable[[], Awaitable[T]], unread: T +) -> tuple[T, bool]: + """(`read()`'s answer, or the one it gave within `_SOURCE_TTL_S`, or `unread` when it + failed; 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,10 +81,10 @@ async def _cached( 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(), "" + answer, 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) + answer, failure = unread, caller_text(e) + hit = _cache[key] = (time.monotonic(), answer, failure) if hit[2]: degradations.partial("ops.incidents", f"{source}_unread", hit[2]) return hit[1], not hit[2] @@ -157,12 +164,13 @@ async def _workers() -> list[OpsIncident]: return out -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 +async def _reads_org_whole(org: str) -> OrgRead: + """`read` when the caller may read `org`'s call counts and failing sources. The rollup + keeps no namespace or user, and the sources span every namespace, 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), or no token where one 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 @@ -210,22 +218,42 @@ async def _requests(org: str, minutes: int) -> list[OpsIncident]: return out -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" +async def _sources(org: str) -> OpsIncidentSources: + """The org's failing document sources: how many, and the latest few.""" + from server.knowledge.app.sources import failing_sources + + failing, sample = await failing_sources(org, sample=MAX_SOURCE_SAMPLE) + return OpsIncidentSources( + failing=failing, + sample=[OpsFailingSource(**row) for row in sample], + read="read", + ) + + +async def _org_reads( + org: str, minutes: int +) -> tuple[list[OpsIncident], OrgRead, OpsIncidentSources]: + """The org's request incidents, whether its counts were read, and its failing + sources. 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.""" + reach: OrgRead = await _reads_org_whole(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" + return [], reach, OpsIncidentSources(read=reach) + (calls, answered), (sources, _) = await asyncio.gather( + _cached("requests", org, lambda: _requests(org, minutes), list[OpsIncident]()), + _cached("sources", org, lambda: _sources(org), OpsIncidentSources(read="unread")), + ) + return calls, "read" if answered else "unread", sources async def handle_ops_incidents(input: OpsIncidentsInput) -> OpsIncidentsOutput: - """The current incidents, errors first.""" + """The current incidents, errors first, and the org's failing sources, which are no + incident: a source's refused credential is its org's to fix.""" minutes = settings.ops_incidents_window_minutes - ready, (workers, _), (calls, requests) = await asyncio.gather( - _readiness(), _cached("workers", "", _workers), _request_incidents(input.org, minutes) + ready, (workers, _), (calls, requests, sources) = await asyncio.gather( + _readiness(), + _cached("workers", "", _workers, list[OpsIncident]()), + _org_reads(input.org, minutes), ) incidents = [*ready, *_providers(minutes * 60.0), *workers, *calls] incidents.sort(key=lambda i: (i.severity != "error", i.kind, i.subject)) @@ -234,4 +262,5 @@ async def handle_ops_incidents(input: OpsIncidentsInput) -> OpsIncidentsOutput: incidents=incidents[:MAX_INCIDENTS], window_minutes=minutes, requests=requests, + sources=sources, ) diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 4c0ed98514b..89b8523997d 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -190,6 +190,11 @@ class SourceGone(Exception): """The source was removed or replaced during its turn: the turn stops.""" +class SourcesFailed(RuntimeError): + """Most of the sources whose turn ran in a pass failed: the pass's one failure note. + A single source's failure is its own, in its sync state, never the worker's.""" + + # Why a turn stopped short: they lead its error text, and the dashboard reads a note that # starts with one as "Incomplete" (frontend/src/lib/knowledgeSources.ts, CUT_SHORT). class TurnMark(StrEnum): @@ -301,6 +306,11 @@ class PassResult: # Sources whose turn ended with a status other than ok or failed outright, plus one # for each document's failed extraction try. failed: int = 0 + # Sources whose turn ran to an end, mirrored ones included, and those of them that + # failed: the pass notes a failure when most failed (`_note_failed_turns`). Not in the + # pass summary (`workers.source_sync.outcome`). + turns: int = 0 + failed_turns: int = 0 # The pass bound stopped the pass before every source, or every file of one, was # handled. cut: bool = False @@ -389,12 +399,24 @@ async def run_sync( # holds the others back; a requested source goes first anyway. pass_context.set_cursor(_cursor_of(src)) break + _note_failed_turns(result) await _extract_pending(order, run, result) if not order and not mirrored and not result.retired: pass_context.mark_idle() return result +def _note_failed_turns(result: PassResult) -> None: + """One failure for the pass when most of the sources whose turn ran failed: an outage + of what every source relies on, or a deployment's only source. A minority's failures + are their own, in their sync states (`knowledge.source.list`, `ops.incidents`' + `sources`): one org's refused credential is no failure of the worker every org shares.""" + if result.failed_turns * 2 > result.turns: + pass_context.note_failure( + SourcesFailed(f"{result.failed_turns} of {result.turns} sources failed"), WORKER + ) + + async def _sync_mirrored( mirrored: list[KnowledgeSource], states: dict[str, dict[str, str]], @@ -496,16 +518,19 @@ async def _sync_turn( log.info("knowledge_source_sync: %s is being synced by another copy", _cursor_of(src)) return None except Exception as e: # noqa: BLE001 — one source's failure must not stop the others + result.turns += 1 + result.failed_turns += 1 if mirror_synced(src): _mirror_failure(src, result) return None result.errors.append(f"{_cursor_of(src)}: {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: %s failed: %s", _cursor_of(src), e) - pass_context.note_failure(e, _cursor_of(src)) return None + result.turns += 1 if mirror_synced(src): if turn.status != "ok": + result.failed_turns += 1 _mirror_failure(src, result) return turn result.synced += 1 @@ -520,15 +545,14 @@ async def _sync_turn( and src.config.get("provider") == "meet" ): result.failed += 1 + result.failed_turns += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) - pass_context.note_failure(RuntimeError(turn.error or turn.status), _cursor_of(src)) return turn def _mirror_failure(src: KnowledgeSource, result: PassResult) -> None: """Report the same code for every cause without exporting turn details.""" result.errors.append(f"{_cursor_of(src)}: SYNC_FAILED") - pass_context.note_failure(RuntimeError("SYNC_FAILED"), _cursor_of(src)) def _turn_of(src: KnowledgeSource) -> Callable[..., Awaitable[TurnResult]]: diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index 9bf9516c647..c7bd1657448 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -523,6 +523,14 @@ async def handle_knowledge_source_list( ) +async def failing_sources(org: str, *, sample: int) -> tuple[int, list[dict[str, str]]]: + """How many of the org's sources that every reader of their namespace sees ended their + last sync turn failing, and `sample` of them ({namespace, name, status}), the latest + failure first. A mirrored source's state is its mirror's, so none is counted. The + caller decides who may read them: they span every namespace of the org.""" + return await store.failing_sources(org, sample=sample) + + async def handle_knowledge_source_inspect( input: KnowledgeSourceInspectInput, ) -> KnowledgeSourceInspectOutput: @@ -1432,6 +1440,7 @@ def source_rotate_audit_subject(input: KnowledgeSourceRotateInput, response: Any __all__ = [ "credential_of", "deactivate_namespace_sources", + "failing_sources", "retire_sources_of", "request_full_sync", "sources_lease", diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 83ccd85bbda..19d9cf7a1e7 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -29,6 +29,7 @@ from server.core.ch import own_write_reads, sequential_reads from server.core.datetimes import naive_utc_now_seconds +from server.core.naming import not_reserved_sql from server.core.repo_base import _CHClient, _default_client from server.knowledge.domain.live_chunks import has_live_chunks_sql from server.knowledge.domain.restore import RestoreRefused @@ -36,6 +37,7 @@ from server.knowledge.domain.source_crawl import Options from server.knowledge.domain.sources import ( NAMESPACE_ACCESS, + STATE_KEY_PREFIX, SYNC_WORKER_ACTOR, KnowledgeSource, WorkerSourceHistory, @@ -511,6 +513,63 @@ async def read_states( } +# The org's sources shown to every reader of their namespace (`domain.served`) whose last +# turn failed, newest failure first, each row with how many there are. The state of a +# removed source stays, so the registry's active row is joined in; a mirror's own state +# rows and a mirrored or worker source's are left out. `provider_removed` ends only a meet +# recording source's turn, which the sync does not count as failed. +_FAILING_SOURCES_SQL = f""" +SELECT + namespace, + substring(state_key, {{start:UInt64}}) AS source_name, + JSONExtractString(detail, 'status') AS status, + count() OVER () AS failing +FROM {STATE_TABLE} FINAL +WHERE org = {{org:String}} + AND startsWith(state_key, {{prefix:String}}) + AND {not_reserved_sql()} + AND status NOT IN ('', 'ok', 'provider_removed') + AND (namespace, state_key) IN ( + SELECT namespace, concat({{prefix:String}}, name) + FROM {TABLE} FINAL + WHERE org = {{org:String}} AND active + AND access = '{NAMESPACE_ACCESS}' AND credential_mode = 'shared' + AND NOT {WORKER_HISTORY} + ) + AND namespace NOT IN ( + SELECT namespace FROM loom.namespaces FINAL + WHERE org = {{org:String}} AND active = false + ) +ORDER BY JSONExtractString(detail, 'last_synced_at') DESC, namespace, source_name +LIMIT {{limit:UInt64}} +""" + + +async def failing_sources( + org: str, *, sample: int, ch: _CHClient | None = None +) -> tuple[int, list[dict[str, str]]]: + """How many of the org's sources shown to their namespace's readers ended their last + turn failing, and `sample` of them ({namespace, name, status}), the latest first.""" + rows = await (ch or _default_client()).query_all( + _FAILING_SOURCES_SQL, + params={ + "org": org, + "prefix": STATE_KEY_PREFIX, + "start": len(STATE_KEY_PREFIX) + 1, + "limit": sample, + }, + ) + failing = int(rows[0]["failing"]) if rows else 0 + return failing, [ + { + "namespace": str(r["namespace"]), + "name": str(r["source_name"]), + "status": str(r["status"]), + } + for r in rows + ] + + async def write_state( org: str, namespace: str, diff --git a/tests/analyzer/cases/workers.py b/tests/analyzer/cases/workers.py index da8bd121b3e..a2778075a1a 100644 --- a/tests/analyzer/cases/workers.py +++ b/tests/analyzer/cases/workers.py @@ -128,11 +128,14 @@ 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. + # ops.incidents: the deployment's failing workers, the org's request failures and its + # failing document sources. from server.insights.store import ops as ops_store + from server.knowledge.store import sources as source_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) + await source_store.failing_sources(ORG, sample=5, 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 7fadee6c8c9..93400c0f12d 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -519,6 +519,7 @@ 3ab1c4309c45 SELECT * FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND tombstoned_at IS NULL 3abfd3b81984 SELECT org, namespace, agent, user_id, session_id, memory_key, memory_type, scope, content_excerpt, embedding_model, created_at, embed_attempts, run_id, entities, tags, files, concepts, valid_at, vali 3ac3f004eaa2 ALTER TABLE loom.agent_run_claims DELETE WHERE org = {org:String} AND user_id = {uid:String} +3ae2547752e3 SELECT namespace, substring(state_key, {start:UInt64}) AS source_name, JSONExtractString(detail, ?) AS status, count() OVER () AS failing FROM loom.code_index_state FINAL WHERE org = {org:String} AND 3aee32f6c95a WITH docs AS ( SELECT thread_id, msg_id, any(role) AS msg_role, argMax(content, ts) AS body, max(ts) AS saved_at, arrayFilter(t -> length(t) >= ?, splitByNonAlpha(lowerUTF8(body))) AS words FROM loom. 3b05a28d96f2 SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: 3b1ae278b7f6 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index 7a3c3faac0c..bdf7bbcd644 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -3437,7 +3437,8 @@ async def _turn(source: Any, state: Any, run: Any) -> source_sync.TurnResult: run = source_sync.Pass(source_sync._budget(), left=5) turn = asyncio.run(source_sync._sync_turn(src, world.states[src.name], run, result)) assert turn is not None and turn.status == status and not turn.complete - assert result.failed == len(result.errors) == len(failures) == expected_failures + assert result.failed == len(result.errors) == result.failed_turns == expected_failures + assert result.turns == 1 and failures == [] # the pass notes its tally, not the turn assert (result.changed, result.removed, result.unconverted, result.skipped) == (0, 0, 0, 0) assert world.states[src.name]["state_value"] == "old-stamp" detail = _detail(world, src.name) diff --git a/tests/unit/test_knowledge_source_sync_diagnostics.py b/tests/unit/test_knowledge_source_sync_diagnostics.py index a05d19409bd..51d678dce79 100644 --- a/tests/unit/test_knowledge_source_sync_diagnostics.py +++ b/tests/unit/test_knowledge_source_sync_diagnostics.py @@ -64,7 +64,8 @@ async def run(*args: Any, answer: Any = turn) -> Any: assert boundary["states"][-1] is turn answers.append(outcome(result)) if mirrored: - assert result == sync.PassResult(sources=1, private_work=True) + # The pass's tally of turns is all a mirrored turn adds: no document figure. + assert result == sync.PassResult(sources=1, private_work=True, turns=1) else: assert result.changed == count and result.cut assert (answers[0] == answers[1]) is mirrored @@ -101,7 +102,9 @@ async def state(*args: Any, exc: Exception = error) -> None: assert "private-file" not in caplog.text assert result.errors == ["acme/code-acme-app/decks: SYNC_FAILED"] assert result.failed == 0 - assert boundary["failures"] == [("RuntimeError", "SYNC_FAILED")] + # Counted toward the pass's tally, never noted on its own. + assert (result.turns, result.failed_turns) == (1, 1) + assert boundary["failures"] == [] answers.append((dataclasses.asdict(result), caplog.messages[:])) assert answers[0] == answers[1] @@ -118,7 +121,9 @@ async def run(*args: Any) -> Any: assert result.synced == result.failed == 1 assert result.errors == ["acme/code-acme-app/decks: failed ValueError"] assert "namespace diagnostic" in caplog.text - assert boundary["failures"] == [("RuntimeError", "ValueError")] + # The source's failure is its own; the pass notes the tally once (run_sync). + assert (result.turns, result.failed_turns) == (1, 1) + assert boundary["failures"] == [] @pytest.mark.parametrize("mirrored", [False, True]) diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py new file mode 100644 index 00000000000..db8e93c2e74 --- /dev/null +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -0,0 +1,183 @@ +"""What a pass of the source sync tells the worker supervisor about its sources' failures. + +A source whose turn failed has its failure in its own sync state (`status`, `error`), +which its namespace's readers see; the pass notes no failure for it. The pass notes one +failure, naming how many, only when most of the sources it ran failed: an outage, or a +deployment with a single source. A leg every source relies on (the store) notes as +before.""" + +from __future__ import annotations + +import asyncio +import contextlib +from typing import Any + +import pytest + +from server.knowledge.app import source_sync +from server.knowledge.domain.sources import KnowledgeSource +from server.workers import pass_context +from tests.unit.test_knowledge_source_sync import NS, ORG, _detail, _source, _World +from tests.unit.test_knowledge_source_sync import world as world # the fixture +from tests.unit.test_knowledge_source_sync_mirror import _mirrored + + +def _sources(world: _World, *names: str) -> None: + world.sources = [_source(name) for name in names] + + +def _turns(monkeypatch: pytest.MonkeyPatch, failing: set[str], *, how: str = "status") -> None: + """Each source's turn: those in `failing` end `credential_invalid` (`status`), or their + state write raises (`raises`); the others end ok.""" + + async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: + out = source_sync.TurnResult() + if src.name in failing and how == "status": + out.fail("credential_invalid", "the stored credential no longer opens; rotate it") + return out + + monkeypatch.setattr(source_sync, "_turn_of", lambda src: turn) + if how != "raises": + return + write_state = source_sync._write_state + + async def state(src: KnowledgeSource, read: Any, turn: Any) -> None: + if src.name in failing: + raise ConnectionError("state store down") + await write_state(src, read, turn) + + monkeypatch.setattr(source_sync, "_write_state", state) + + +async def _supervised() -> tuple[source_sync.PassResult, pass_context.PassContext]: + """One pass under a pass context, as the supervisor binds it.""" + ctx = pass_context.begin(source_sync.WORKER) + try: + return await source_sync.run_sync(), ctx + finally: + pass_context.clear() + + +@pytest.mark.parametrize("how", ["status", "raises"]) +def test_one_failing_source_of_three_notes_no_pass_failure( + world: _World, monkeypatch: pytest.MonkeyPatch, how: str +) -> None: + _sources(world, "a", "b", "c") + _turns(monkeypatch, {"b"}, how=how) + + result, ctx = asyncio.run(_supervised()) + + assert (ctx.count, ctx.failures) == (0, []) + assert result.failed == 1 and len(result.errors) == 1 + assert result.errors[0].startswith(f"{ORG}/{NS}/b: ") + if how == "status": + # The failure is the source's own, in the sync state its readers see. + assert _detail(world, "b")["status"] == "credential_invalid" + assert _detail(world, "a")["status"] == "ok" + + +@pytest.mark.parametrize("how", ["status", "raises"]) +def test_two_failing_sources_of_three_note_one_pass_failure( + world: _World, monkeypatch: pytest.MonkeyPatch, how: str +) -> None: + _sources(world, "a", "b", "c") + _turns(monkeypatch, {"a", "c"}, how=how) + + result, ctx = asyncio.run(_supervised()) + + assert ctx.count == 1 + assert ctx.failures == [(source_sync.WORKER, "SourcesFailed", "2 of 3 sources failed")] + assert result.failed == 2 and len(result.errors) == 2 + + +def test_the_only_source_failing_notes_one_pass_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """A deployment with one source still builds the worker's streak.""" + _sources(world, "a") + _turns(monkeypatch, {"a"}) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == [(source_sync.WORKER, "SourcesFailed", "1 of 1 sources failed")] + + +def test_half_the_sources_failing_is_not_most_of_them( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + _sources(world, "a", "b") + _turns(monkeypatch, {"a"}) + + result, ctx = asyncio.run(_supervised()) + + assert ctx.count == 0 and result.failed == 1 + + +def test_a_source_another_copy_holds_is_not_counted( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Only the sources whose turn ran count: one another copy syncs is neither.""" + from server.core import leases + + _sources(world, "a", "b", "c") + _turns(monkeypatch, {"a"}) + held = leases.cluster_lease + + @contextlib.asynccontextmanager + async def busy(name: str, **kw: Any) -> Any: + if not name.endswith("/a"): + raise leases.LeaseBusy(name) + async with held(name, **kw) as lease: + yield lease + + monkeypatch.setattr(leases, "cluster_lease", busy) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == [(source_sync.WORKER, "SourcesFailed", "1 of 1 sources failed")] + + +def test_mirrored_failures_count_toward_the_pass_with_their_one_code( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + world.sources = [_mirrored(name="m1"), _mirrored(name="m2"), _source("plain")] + _turns(monkeypatch, {"m1", "m2"}) + + result, ctx = asyncio.run(_supervised()) + + assert result.private_work and ctx.private_work + assert result.errors == [f"{ORG}/{NS}/m1: SYNC_FAILED", f"{ORG}/{NS}/m2: SYNC_FAILED"] + assert result.failed == 0 # a mirrored turn contributes its code, never a figure + assert ctx.failures == [(source_sync.WORKER, "SourcesFailed", "2 of 3 sources failed")] + + +def test_one_mirrored_failure_of_three_notes_no_pass_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + world.sources = [_mirrored(name="m1"), _source("a"), _source("b")] + _turns(monkeypatch, {"m1"}) + + result, ctx = asyncio.run(_supervised()) + + assert result.errors == [f"{ORG}/{NS}/m1: SYNC_FAILED"] + assert ctx.count == 0 + + +def test_a_failed_store_read_every_source_shares_still_notes( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """The extraction leg's read of each source's documents is the store's: every + source's failed read is noted, as before, though every turn was ok.""" + _sources(world, "a", "b", "c") + _turns(monkeypatch, set()) + + async def down(*args: Any, **kw: Any) -> Any: + raise ConnectionError("store down") + + monkeypatch.setattr(source_sync.store, "source_revisions", down) + + result, ctx = asyncio.run(_supervised()) + + assert ctx.count == 3 + assert [what for what, _, _ in ctx.failures] == [f"{ORG}/{NS}/{n}" for n in "abc"] + assert result.errors == [f"{ORG}/{NS}/{n}: extraction ConnectionError" for n in "abc"] diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 5eef00f7216..7a0f05f9157 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -61,8 +61,13 @@ def _clean(monkeypatch: pytest.MonkeyPatch): provider_health.reset() -def _ch(monkeypatch: pytest.MonkeyPatch, *, workers=(), sli=()) -> RecordingCH: - ch = RecordingCH().on("loom.worker_status", list(workers)).on("sli_minute", list(sli)) +def _ch(monkeypatch: pytest.MonkeyPatch, *, workers=(), sli=(), sources=()) -> RecordingCH: + ch = ( + RecordingCH() + .on("loom.worker_status", list(workers)) + .on("sli_minute", list(sli)) + .on("loom.code_index_state", list(sources)) + ) return ch.install(monkeypatch) @@ -212,16 +217,19 @@ 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) + down = RecordingCH().on("loom.worker_status", _down).on("sli_minute", _down) + down.on("loom.code_index_state", _down).install(monkeypatch) 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 + assert (out.sources.read, out.sources.failing, out.sources.sample) == ("unread", 0, []) notes = degradations.current() assert [n.split(" (")[0] for n in notes] == [ "ops.incidents: workers_unread", "ops.incidents: requests_unread", + "ops.incidents: sources_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 @@ -234,7 +242,8 @@ async def test_polls_within_the_ttl_share_one_read_and_a_cached_failure_is_still def _down(sql, params): raise server_error("Connection refused", code=210) - ch = RecordingCH().on("loom.worker_status", _down).on("sli_minute", []).install(monkeypatch) + ch = RecordingCH().on("loom.worker_status", _down).on("sli_minute", []) + ch.on("loom.code_index_state", []).install(monkeypatch) await _incidents() degradations.begin() # the next poll is another request @@ -251,17 +260,19 @@ async def test_polls_that_arrive_while_a_read_is_in_flight_wait_for_it(monkeypat """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.knowledge.store import sources as sources_store from server.workers import status_store calls: list[str] = [] - async def _slow(source: str) -> list[dict[str, Any]]: + async def _slow(source: str) -> Any: calls.append(source) await asyncio.sleep(0.05) - return [] + return (0, []) if source == "sources" else [] monkeypatch.setattr(status_store, "failing_streaks", lambda *a, **k: _slow("workers")) monkeypatch.setattr(ops_store, "request_errors_by_class", lambda *a, **k: _slow("requests")) + monkeypatch.setattr(sources_store, "failing_sources", lambda *a, **k: _slow("sources")) set_current_auth(ORG_WIDE) try: polls = [handle_ops_incidents(OpsIncidentsInput(org="acme")) for _ in range(8)] @@ -269,7 +280,7 @@ async def _slow(source: str) -> list[dict[str, Any]]: finally: set_current_auth(None) - assert sorted(calls) == ["requests", "workers"] + assert sorted(calls) == ["requests", "sources", "workers"] assert [o.status for o in outs] == ["ok"] * 8 @@ -324,11 +335,13 @@ 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 ch.statements("sli_minute") == ch.statements("loom.code_index_state") == [] assert [(o.incidents, o.requests) for o in outs] == [([], "not_permitted")] * len(outs) + assert [o.sources.read for o in outs] == ["not_permitted"] * len(outs) assert degradations.current() == [] whole = await _incidents() assert [i.subject for i in whole.incidents] == ["code"] and whole.requests == "read" + assert whole.sources.read == "read" @pytest.mark.asyncio @@ -367,7 +380,86 @@ async def test_an_org_admin_with_a_restricted_namespace_hidden_reads_no_counts( assert (out.incidents, out.requests) == ([], "unread") assert degradations.current() == [f"ops.incidents: requests_unread ({kind})"] hidden.side_effect = None - assert ch.statements("sli_minute") == [] + assert ch.statements("sli_minute") == ch.statements("loom.code_index_state") == [] + + +# What the sources statement answers: the sample, each row with the total. +_FAILING = [ + {"namespace": "team", "source_name": "decks", "status": "credential_invalid", "failing": 7}, + {"namespace": "ops", "source_name": "runbooks", "status": "rate_limited", "failing": 7}, +] + + +@pytest.mark.asyncio +async def test_the_callers_org_failing_sources_are_listed_and_never_degrade_status( + monkeypatch, +) -> None: + """A tenant's revoked credential is the tenant's to fix: `sources` names the org's + failing sources and `status` stays Loom's own health.""" + ch = _ch(monkeypatch, sources=_FAILING) + + out = await _incidents() + + assert (out.status, out.incidents) == ("ok", []) + assert out.sources.read == "read" and out.sources.failing == 7 + assert [(s.namespace, s.name, s.status) for s in out.sources.sample] == [ + ("team", "decks", "credential_invalid"), + ("ops", "runbooks", "rate_limited"), + ] + (read,) = ch.statements("loom.code_index_state") + assert read.params["org"] == "acme" # the caller's org, never another + assert read.params["limit"] == incidents.MAX_SOURCE_SAMPLE == 5 + assert degradations.current() == [] + + +@pytest.mark.asyncio +async def test_no_failing_source_reads_zero(monkeypatch) -> None: + _ch(monkeypatch) + + out = await _incidents() + + assert (out.sources.read, out.sources.failing, out.sources.sample) == ("read", 0, []) + + +@pytest.mark.asyncio +async def test_each_org_reads_its_own_sources_once_per_ttl(monkeypatch) -> None: + ch = _ch(monkeypatch, sources=_FAILING) + + await _incidents() + await _incidents() + other = await _incidents(org="other", auth=_token(org="other", roles=(Role.ORG_ADMIN,))) + + assert [s.params["org"] for s in ch.statements("loom.code_index_state")] == ["acme", "other"] + assert other.sources.failing == 7 # the route answers every org alike here + + +@pytest.mark.asyncio +async def test_a_member_reads_no_sources(monkeypatch) -> None: + """A member's `*` token could hold no grant on a restricted namespace whose source + fails: only a caller that reads the org whole reads them, as for `requests`.""" + ch = _ch(monkeypatch, sources=_FAILING) + + out = await _incidents(auth=_token()) + + assert (out.sources.read, out.sources.failing, out.sources.sample) == ("not_permitted", 0, []) + assert ch.statements("loom.code_index_state") == [] + + +@pytest.mark.asyncio +async def test_an_unread_sources_read_answers_unread_and_is_named_in_degraded( + monkeypatch, +) -> None: + def _down(sql, params): + raise server_error("Connection refused", code=210) + + ch = RecordingCH().on("loom.worker_status", []).on("sli_minute", []) + ch.on("loom.code_index_state", _down).install(monkeypatch) + + out = await _incidents() + + assert (out.status, out.requests) == ("ok", "read") + assert (out.sources.read, out.sources.failing, out.sources.sample) == ("unread", 0, []) + assert [n.split(" (")[0] for n in degradations.current()] == ["ops.incidents: sources_unread"] def test_any_viewer_polls_it_and_it_reads_no_namespace() -> None: diff --git a/tests/unit/test_ops_incidents_sql.py b/tests/unit/test_ops_incidents_sql.py index 2087361ab99..480c5c0c1d1 100644 --- a/tests/unit/test_ops_incidents_sql.py +++ b/tests/unit/test_ops_incidents_sql.py @@ -1,9 +1,11 @@ -"""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.""" +"""The statements ops.incidents reads, on clickhouse-local over the production tables: +the failure streaks of this deployment's enabled workers, the org's calls per SLO class +that failed on the server, and the org's document sources whose last turn failed.""" from __future__ import annotations +from typing import Any + import pytest from server.insights.store import ops as ops_store @@ -111,3 +113,95 @@ async def read(org: str) -> list[tuple[str, int, int]]: assert await read("o2") == [("interactive", 50, 0)] assert await read("o3") == [("read", 10, 10)] assert await read("o4") == [] + + +_MIRROR = "acl-" + "a" * 24 + +# (org, namespace, source, access, credential mode, source kind, active, version) +_REGISTRY = [ + ("o1", "team", "decks", "namespace", "shared", "gdrive", 1, 1), + ("o1", "ops", "runbooks", "namespace", "shared", "notion", 1, 1), + ("o1", "team", "notes", "namespace", "shared", "gdrive", 1, 1), + ("o1", "team", "fixed", "namespace", "shared", "gdrive", 1, 1), + ("o1", "team", "broke", "namespace", "shared", "gdrive", 1, 1), + ("o1", "team", "drive", "mirrored", "shared", "gdrive", 1, 1), # a mirrored source + ("o1", "team", "mine", "mirrored", "connected", "notion", 1, 1), # a person's own + ("o1", "team", "gone", "namespace", "shared", "gdrive", 1, 1), + ("o1", "team", "gone", "namespace", "shared", "gdrive", 0, 2), # removed since + ("o1", "team", "agent", "namespace", "shared", "mcp", 1, 1), # a worker source + ("o1", "team", "meet", "namespace", "shared", "recording", 1, 1), + ("o1", "team", "fresh", "namespace", "shared", "gdrive", 1, 1), + ("o1", "paused", "old", "namespace", "shared", "gdrive", 1, 1), # an inactive namespace + ("o2", "team", "decks", "namespace", "shared", "gdrive", 1, 1), # another org's +] + +# (org, namespace, state key, status, last turn, version) +_STATES = [ + ("o1", "team", "knowledge_source:decks", "credential_invalid", "2026-03-02T00:00:00+00:00", 1), + ("o1", "ops", "knowledge_source:runbooks", "rate_limited", "2026-03-03T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:notes", "ok", "2026-03-04T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:fixed", "failed", "2026-03-01T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:fixed", "ok", "2026-03-05T00:00:00+00:00", 2), # recovered + ("o1", "team", "knowledge_source:broke", "ok", "2026-02-01T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:broke", "failed", "2026-03-01T00:00:00+00:00", 2), + ("o1", "team", "knowledge_source:drive", "failed", "2026-03-09T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:mine", "credential_invalid", "2026-03-09T00:00:00+00:00", 1), + ("o1", _MIRROR, "knowledge_source:drive-id", "failed", "2026-03-09T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:gone", "failed", "2026-03-09T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:agent", "failed", "2026-03-09T00:00:00+00:00", 1), + # A meet recording source, whose turn the sync does not count as failed. + ("o1", "team", "knowledge_source:meet", "provider_removed", "2026-03-09T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:fresh", "", "", 1), # asked for, never run + ("o1", "paused", "knowledge_source:old", "failed", "2026-03-09T00:00:00+00:00", 1), + ("o1", "team", "code_cursor:main", "failed", "2026-03-09T00:00:00+00:00", 1), # no source's + ("o2", "team", "knowledge_source:decks", "failed", "2026-03-09T00:00:00+00:00", 1), +] + + +def _source_rows() -> list[str]: + registry = ", ".join( + f"('{o}', '{ns}', '{name}', '{access}', '{mode}', '{kind}', {active}, {v})" + for o, ns, name, access, mode, kind, active, v in _REGISTRY + ) + states = ", ".join( + f"('{o}', '{ns}', '{key}', '" + + (f'{{"status": "{status}", "last_synced_at": "{at}"}}' if status else "{}") + + f"', {v})" + for o, ns, key, status, at, v in _STATES + ) + return [ + ddl("knowledge_sources"), + ddl("code_index_state"), + ddl("namespaces"), + "INSERT INTO loom.knowledge_sources (org, namespace, name, source_id, access, " + "credential_mode, source_kind, active, version) " + "SELECT o, ns, n, generateUUIDv4(), a, m, k, act, v FROM values(" + "'o String, ns String, n String, a String, m String, k String, act Bool, v UInt64', " + f"{registry})", + f"INSERT INTO loom.code_index_state (org, namespace, state_key, detail, version) " + f"VALUES {states}", + "INSERT INTO loom.namespaces (org, namespace, owner_email, active) VALUES " + "('o1', 'team', '', true), ('o1', 'paused', '', false)", + ] + + +async def test_the_sources_read_counts_and_samples_the_orgs_own_failing_sources() -> None: + from server.knowledge.store import sources + + ch: Any = LocalCH(*_source_rows()) + + failing, sample = await sources.failing_sources("o1", sample=5, ch=ch) + + assert failing == 3 + assert sample == [ + {"namespace": "ops", "name": "runbooks", "status": "rate_limited"}, + {"namespace": "team", "name": "decks", "status": "credential_invalid"}, + {"namespace": "team", "name": "broke", "status": "failed"}, + ] + failing, sample = await sources.failing_sources("o1", sample=2, ch=ch) + assert failing == 3 and [s["name"] for s in sample] == ["runbooks", "decks"] + assert await sources.failing_sources("o2", sample=5, ch=ch) == ( + 1, + [{"namespace": "team", "name": "decks", "status": "failed"}], + ) + assert await sources.failing_sources("o3", sample=5, ch=ch) == (0, []) From 099c35119103d1c05cb5965e1cd8f33ab7510c3e Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 14:43:27 +0530 Subject: [PATCH 02/41] Each source sync leg notes a failure only when most orgs' sources fail The pass counted failed sources across orgs, so one org that holds most of a deployment's sources still built the worker's streak with its own revoked credential. The mining and retirement legs still noted each source's failure, so one document that failed to mine, retried for 3 passes, did the same. Each leg (sync turns, mining, retirement) now tallies the sources it handled per org and notes one SourcesFailed ("sync failed for most sources in 3 of 4 orgs") only when most of the orgs it ran for had most of their sources fail. ops.incidents names sources_unread beside requests_unread when the restricted set cannot be read. The sources statement filters on the status expression, not its alias (test_sql_alias_shadow). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/document-sources.md | 6 +- docs/features/knowledge.md | 15 +-- docs/operations/monitoring.md | 12 +-- server/insights/app/incidents.py | 28 +++--- server/knowledge/app/source_sync.py | 84 ++++++++++------ server/knowledge/store/sources.py | 2 +- tests/analyzer/shapes.txt | 2 +- tests/unit/test_knowledge_source_sync.py | 7 +- .../test_knowledge_source_sync_diagnostics.py | 8 +- .../test_knowledge_source_sync_failures.py | 98 ++++++++++++++++--- tests/unit/test_ops_incidents.py | 18 ++-- 11 files changed, 194 insertions(+), 86 deletions(-) diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 66d1038ed41..0b166cdae25 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -636,9 +636,9 @@ the public fallback. No reranking provider receives the provisional pools. service's logs and traces) carries codes only (exceptions 3 and 4 apart). Worker pass summaries exclude mirrored turns' completed-source counts, document figures and cut flags. A failed mirrored turn contributes only `SYNC_FAILED`, for - every cause, and counts in the pass's tally of failed turns like any other source; - returned turn details remain private. `ops.incidents`' `sources` counts no mirrored - source, since its state is its mirror's. Mirrored per-file failures emit + every cause, and counts in the pass's per-org tally of failed turns like any other + source; returned turn details remain private. `ops.incidents`' `sources` counts no + mirrored source, since its state is its mirror's. Mirrored per-file failures emit no log record, since the number of records would disclose a document figure. A sync turn enters its private diagnostic scope before taking its source lease or listing files; retirement enters it before reading its queue. That scope suppresses diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 1bac7258b43..6049a22be51 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -678,13 +678,14 @@ A source's `sync` in `list` and `inspect` shows what its last turn did: A failed turn belongs to its source: its `status` and `error` here, and for an org admin the org's failing sources in [`ops.incidents`](../operations/monitoring.md#opsincidents)' -`sources`. The worker's pass counts as failed toward its failure streak only when most of -the sources whose turn ran in it failed (`knowledge_source_sync: 7 of 9 sources failed`), -mirrored ones included: an outage of what every source relies on, or a deployment's only -source. One org's refused credential therefore never makes the worker, or `ops.incidents`, -degraded for the other orgs. A turn another copy holds counts neither way. A failure in -the mining leg (a store read or write, a model call) or in retiring a removed source's -documents still counts the pass as failed. +`sources`. Each leg of the worker's pass (the sync turns, mirrored ones included, the +mining and the retirement of removed sources) counts the pass as failed toward the +worker's failure streak only when most of the orgs it ran for had most of their sources +fail (`knowledge_source_sync: sync failed for most sources in 3 of 4 orgs`): an outage of +what every source relies on, such as the store or the model, or a deployment with one +org. One org's failing sources, however many of the deployment's sources are its own, +therefore make neither the worker nor `ops.incidents` degraded for the other orgs. A +source another copy holds counts neither way. ### A recording source diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 0f156d32311..9fe6149ae4c 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -165,10 +165,9 @@ are deployment state, the same for every org: a readiness or provider incident n 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. +read runs at most once every 5 seconds per process, however many clients poll during an +outage, and is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A read that failed is named in the +response's `degraded` while its failure is cached, and the other reads 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 @@ -184,8 +183,9 @@ It is read under the same rule as the request counts, and `sources.read` answers same words. A failing document source is never an incident and never makes `status` `degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own health. The `knowledge_source_sync` worker becomes a `worker` incident only after 3 -passes in a row in which most of the sources failed or a leg every source relies on (the -store, the model) failed. +passes in a row in which one of its legs (the sync turns, the mining, the retirement of +removed sources) failed for most of the sources of most orgs: an outage of what every +source relies on, such as the store or the model, or a deployment with one org. ### Smoke test diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 890ff7e3b48..c2cc6935672 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -9,12 +9,12 @@ the answer `degraded`. Nothing names another org: a provider or worker incident carries an error's kind, never its text, and the request counts and the sources 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; a source names its namespace). Each ClickHouse source is read at -most once per `_SOURCE_TTL_S` per process (per org for the org's), 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. +no namespace or user; a source names its namespace). Each ClickHouse read runs at most +once per `_SOURCE_TTL_S` per process (per org for the org's), so clients polling during +an outage do not add load. A read that does not answer 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 @@ -48,7 +48,8 @@ _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. +# Each org polling holds two entries (its request counts, its sources); past this the +# cache starts over. # not a setting: a memory bound, not a behaviour _CACHE_MAX = 1024 @@ -187,16 +188,21 @@ async def _reads_org_whole(org: str) -> OrgRead: try: hidden, unverified = await restricted_hidden(org) except LoomServerError as e: - degradations.partial("ops.incidents", "requests_unread", error_kind(e)) - return "unread" + return _org_unread(error_kind(e)) if hidden == ["*"]: # the restricted set is unread - degradations.partial("ops.incidents", "requests_unread", "ClassificationUnavailable") - return "unread" + return _org_unread("ClassificationUnavailable") if unverified: return "unread" return "not_permitted" if hidden else "read" +def _org_unread(kind: str) -> OrgRead: + """Neither org read is served: both are named in `degraded`.""" + for read in ("requests", "sources"): + degradations.partial("ops.incidents", f"{read}_unread", kind) + return "unread" + + async def _requests(org: str, minutes: int) -> list[OpsIncident]: """An SLO class of the org's calls whose server-side failures reach the share.""" rows = await ops_store.request_errors_by_class(org, minutes) diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 89b8523997d..be7e8123a14 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -90,6 +90,7 @@ import functools import logging import time +from collections import Counter from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta @@ -191,8 +192,31 @@ class SourceGone(Exception): class SourcesFailed(RuntimeError): - """Most of the sources whose turn ran in a pass failed: the pass's one failure note. - A single source's failure is its own, in its sync state, never the worker's.""" + """A leg of the pass failed for most sources of most orgs: its one failure note. A + source's failure is its own, in its sync state, never the worker's.""" + + +@dataclass +class SourceTally: + """Per org, the sources one leg of a pass handled and those it failed.""" + + ran: Counter[str] = field(default_factory=Counter) + failed: Counter[str] = field(default_factory=Counter) + + def add(self, src: KnowledgeSource, *, failed: bool) -> None: + self.ran[src.org] += 1 + self.failed[src.org] += failed + + def note(self, leg: str) -> None: + """One failure for the pass when most of the orgs the leg ran for had most of their + sources fail: an outage of what every source relies on (the store, the model), or + a deployment with one org. One org's failures, however many of the sources are + its own, are in their sync states (`knowledge.source.list`, `ops.incidents`' + `sources`), and no failure of the worker every org shares.""" + orgs = sum(self.failed[org] * 2 > n for org, n in self.ran.items()) + if orgs * 2 > len(self.ran): + msg = f"{leg} failed for most sources in {orgs} of {len(self.ran)} orgs" + pass_context.note_failure(SourcesFailed(msg), WORKER) # Why a turn stopped short: they lead its error text, and the dashboard reads a note that @@ -306,11 +330,12 @@ class PassResult: # Sources whose turn ended with a status other than ok or failed outright, plus one # for each document's failed extraction try. failed: int = 0 - # Sources whose turn ran to an end, mirrored ones included, and those of them that - # failed: the pass notes a failure when most failed (`_note_failed_turns`). Not in the - # pass summary (`workers.source_sync.outcome`). - turns: int = 0 - failed_turns: int = 0 + # Per leg, the sources it handled and failed: sync turns that ran to an end (mirrored + # ones included), mining and retirement. Each notes at most one failure for the pass + # (`SourceTally.note`). Not in the pass summary (`workers.source_sync.outcome`). + turns: SourceTally = field(default_factory=SourceTally) + mining: SourceTally = field(default_factory=SourceTally) + retiring: SourceTally = field(default_factory=SourceTally) # The pass bound stopped the pass before every source, or every file of one, was # handled. cut: bool = False @@ -361,6 +386,7 @@ async def run_sync( # An admin's delete request goes first, before the backlog of changed files and # before anything that reads the code registry. await _retire_removed_sources(run, result, org=org, namespace=namespace, only=only) + result.retiring.note("retirement") if found: # The repository tags come from the registry: refresh it once per pass, and # stop the pass (RegistryUnread) while it has never been read. @@ -399,24 +425,14 @@ async def run_sync( # holds the others back; a requested source goes first anyway. pass_context.set_cursor(_cursor_of(src)) break - _note_failed_turns(result) + result.turns.note("sync") await _extract_pending(order, run, result) + result.mining.note("mining") if not order and not mirrored and not result.retired: pass_context.mark_idle() return result -def _note_failed_turns(result: PassResult) -> None: - """One failure for the pass when most of the sources whose turn ran failed: an outage - of what every source relies on, or a deployment's only source. A minority's failures - are their own, in their sync states (`knowledge.source.list`, `ops.incidents`' - `sources`): one org's refused credential is no failure of the worker every org shares.""" - if result.failed_turns * 2 > result.turns: - pass_context.note_failure( - SourcesFailed(f"{result.failed_turns} of {result.turns} sources failed"), WORKER - ) - - async def _sync_mirrored( mirrored: list[KnowledgeSource], states: dict[str, dict[str, str]], @@ -518,8 +534,7 @@ async def _sync_turn( log.info("knowledge_source_sync: %s is being synced by another copy", _cursor_of(src)) return None except Exception as e: # noqa: BLE001 — one source's failure must not stop the others - result.turns += 1 - result.failed_turns += 1 + result.turns.add(src, failed=True) if mirror_synced(src): _mirror_failure(src, result) return None @@ -527,10 +542,9 @@ async def _sync_turn( result.failed += 1 log.warning("knowledge_source_sync: %s failed: %s", _cursor_of(src), e) return None - result.turns += 1 if mirror_synced(src): + result.turns.add(src, failed=turn.status != "ok") if turn.status != "ok": - result.failed_turns += 1 _mirror_failure(src, result) return turn result.synced += 1 @@ -539,13 +553,14 @@ async def _sync_turn( result.unconverted += turn.unconverted result.skipped += turn.skipped result.cut |= turn.cut - if turn.status != "ok" and not ( + failed = turn.status != "ok" and not ( turn.status == "provider_removed" and src.kind == "recording" and src.config.get("provider") == "meet" - ): + ) + result.turns.add(src, failed=failed) + if failed: result.failed += 1 - result.failed_turns += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) return turn @@ -1546,7 +1561,9 @@ async def _retire_removed_sources( result.errors.append(f"{_cursor_of(src)}: {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: retiring %s failed: %s", _cursor_of(src), e) - pass_context.note_failure(e, _cursor_of(src)) + result.retiring.add(src, failed=True) + continue + result.retiring.add(src, failed=False) async def _retire_all(src: KnowledgeSource, run: Pass, result: PassResult) -> None: @@ -1667,12 +1684,14 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass except Exception as e: # noqa: BLE001 — one source's failed read must not stop the others result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 - pass_context.note_failure(e, _cursor_of(src)) + result.mining.add(src, failed=True) continue todo = _unmined(docs, detail) # A source with nothing to mine and no stale count to clear needs no write. if todo or detail.get("pending_extract"): queues.append((src, docs, todo)) + else: + result.mining.add(src, failed=False) if not queues: return stop = "" @@ -1700,7 +1719,9 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) - pass_context.note_failure(e, _cursor_of(src)) + result.mining.add(src, failed=True) + continue + result.mining.add(src, failed=False) continue stop = await _extract_source(src, docs, run, result) @@ -1761,6 +1782,7 @@ async def _extract_source( leg (`_Mined.stop`), else ''. A pass stopped or cancelled records nothing: the documents it did not settle are unmined still.""" mined = _Mined(waits={}) + raised = False try: async with _source_turn(src) as lease: with sequential_reads(): @@ -1791,14 +1813,14 @@ def may_write() -> bool: result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: mining %s failed: %s", _cursor_of(src), e) - pass_context.note_failure(e, _cursor_of(src)) + raised = True + result.mining.add(src, failed=raised or mined.failures > 0) result.extracted += mined.extracted result.flagged_pinned += mined.flagged result.unextracted += mined.unextracted result.failed += mined.failures if mined.failures: result.errors.append(f"{_cursor_of(src)}: extraction {mined.error}") - pass_context.note_failure(RuntimeError(mined.error), _cursor_of(src)) if mined.deferred: result.extract_deferred += 1 if mined.deferred.startswith("held:"): diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 19d9cf7a1e7..8d5965c019d 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -528,7 +528,7 @@ async def read_states( WHERE org = {{org:String}} AND startsWith(state_key, {{prefix:String}}) AND {not_reserved_sql()} - AND status NOT IN ('', 'ok', 'provider_removed') + AND JSONExtractString(detail, 'status') NOT IN ('', 'ok', 'provider_removed') AND (namespace, state_key) IN ( SELECT namespace, concat({{prefix:String}}, name) FROM {TABLE} FINAL diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 93400c0f12d..81337382c6e 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -519,7 +519,6 @@ 3ab1c4309c45 SELECT * FROM loom.code_files FINAL WHERE org = {org:String} AND namespace = {ns:String} AND path IN {paths:Array(String)} AND tombstoned_at IS NULL 3abfd3b81984 SELECT org, namespace, agent, user_id, session_id, memory_key, memory_type, scope, content_excerpt, embedding_model, created_at, embed_attempts, run_id, entities, tags, files, concepts, valid_at, vali 3ac3f004eaa2 ALTER TABLE loom.agent_run_claims DELETE WHERE org = {org:String} AND user_id = {uid:String} -3ae2547752e3 SELECT namespace, substring(state_key, {start:UInt64}) AS source_name, JSONExtractString(detail, ?) AS status, count() OVER () AS failing FROM loom.code_index_state FINAL WHERE org = {org:String} AND 3aee32f6c95a WITH docs AS ( SELECT thread_id, msg_id, any(role) AS msg_role, argMax(content, ts) AS body, max(ts) AS saved_at, arrayFilter(t -> length(t) >= ?, splitByNonAlpha(lowerUTF8(body))) AS words FROM loom. 3b05a28d96f2 SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: 3b1ae278b7f6 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { @@ -1936,6 +1935,7 @@ d0c38ecb1040 SELECT chunk_id, path, scope, kind, start_line, end_line, content, d0c98dde6333 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user d10a174bff69 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 d11e82174d2d SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user +d132548714c3 SELECT namespace, substring(state_key, {start:UInt64}) AS source_name, JSONExtractString(detail, ?) AS status, count() OVER () AS failing FROM loom.code_index_state FINAL WHERE org = {org:String} AND d143302e86ef SELECT memory_id, org, namespace, agent, user_id, session_id, memory_key, memory_type, if(length(toString(value_json)) > ?, toString(value_json), value) AS value, -- The stored bytes, for version rows d19be6e39b44 SELECT org, namespace, agent, user_id, session_id, scope, embedding_model, memory_key, created_at, version FROM loom.memory_embeddings FINAL PREWHERE (org, namespace, agent, user_id, session_id, memor d19d31a3306d SELECT count() AS n FROM loom.memory_reinforcement WHERE org = {org:String} AND user_id = {uid:String} AND ? diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index bdf7bbcd644..3caa8eb0ae3 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -2822,7 +2822,8 @@ async def _then(*a: Any, **kw: Any) -> None: monkeypatch.setattr(pass_context, "note_failure", lambda e, what="": failures.append(what)) result = asyncio.run(source_sync.run_sync()) assert result.errors == [f"{ORG}/{NS}/decks: extraction ConnectionError"] - assert result.failed == 1 and failures == [f"{ORG}/{NS}/decks"] + # One source of two: its own failure, in the leg's tally, and no failure of the pass. + assert result.failed == 1 and failures == [] # The leg goes on: the other source's document is mined. assert [uri for uri, _, _ in world.mined] == [DOC2] @@ -3437,8 +3438,8 @@ async def _turn(source: Any, state: Any, run: Any) -> source_sync.TurnResult: run = source_sync.Pass(source_sync._budget(), left=5) turn = asyncio.run(source_sync._sync_turn(src, world.states[src.name], run, result)) assert turn is not None and turn.status == status and not turn.complete - assert result.failed == len(result.errors) == result.failed_turns == expected_failures - assert result.turns == 1 and failures == [] # the pass notes its tally, not the turn + assert result.failed == len(result.errors) == result.turns.failed[ORG] == expected_failures + assert result.turns.ran == {ORG: 1} and failures == [] # the pass notes its tally, not the turn assert (result.changed, result.removed, result.unconverted, result.skipped) == (0, 0, 0, 0) assert world.states[src.name]["state_value"] == "old-stamp" detail = _detail(world, src.name) diff --git a/tests/unit/test_knowledge_source_sync_diagnostics.py b/tests/unit/test_knowledge_source_sync_diagnostics.py index 51d678dce79..8e8f7efe1c0 100644 --- a/tests/unit/test_knowledge_source_sync_diagnostics.py +++ b/tests/unit/test_knowledge_source_sync_diagnostics.py @@ -6,6 +6,7 @@ import contextlib import dataclasses import logging +from collections import Counter from typing import Any import pytest @@ -65,7 +66,8 @@ async def run(*args: Any, answer: Any = turn) -> Any: answers.append(outcome(result)) if mirrored: # The pass's tally of turns is all a mirrored turn adds: no document figure. - assert result == sync.PassResult(sources=1, private_work=True, turns=1) + turns = sync.SourceTally(ran=Counter(acme=1), failed=Counter(acme=0)) + assert result == sync.PassResult(sources=1, private_work=True, turns=turns) else: assert result.changed == count and result.cut assert (answers[0] == answers[1]) is mirrored @@ -103,7 +105,7 @@ async def state(*args: Any, exc: Exception = error) -> None: assert result.errors == ["acme/code-acme-app/decks: SYNC_FAILED"] assert result.failed == 0 # Counted toward the pass's tally, never noted on its own. - assert (result.turns, result.failed_turns) == (1, 1) + assert (result.turns.ran, result.turns.failed) == ({"acme": 1}, {"acme": 1}) assert boundary["failures"] == [] answers.append((dataclasses.asdict(result), caplog.messages[:])) assert answers[0] == answers[1] @@ -122,7 +124,7 @@ async def run(*args: Any) -> Any: assert result.errors == ["acme/code-acme-app/decks: failed ValueError"] assert "namespace diagnostic" in caplog.text # The source's failure is its own; the pass notes the tally once (run_sync). - assert (result.turns, result.failed_turns) == (1, 1) + assert (result.turns.ran, result.turns.failed) == ({"acme": 1}, {"acme": 1}) assert boundary["failures"] == [] diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index db8e93c2e74..07e68f03937 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -1,15 +1,17 @@ """What a pass of the source sync tells the worker supervisor about its sources' failures. A source whose turn failed has its failure in its own sync state (`status`, `error`), -which its namespace's readers see; the pass notes no failure for it. The pass notes one -failure, naming how many, only when most of the sources it ran failed: an outage, or a -deployment with a single source. A leg every source relies on (the store) notes as -before.""" +which its namespace's readers see; the pass notes no failure for it. Each leg of the +pass (the sync turns, the mining, the retirement of removed sources) notes one failure +only when most of the orgs it ran for had most of their sources fail: an outage of what +every source relies on, or a deployment with a single org. One org's failures, however +many of the sources are its own, are no failure of the worker every org shares.""" from __future__ import annotations import asyncio import contextlib +import dataclasses from typing import Any import pytest @@ -26,6 +28,10 @@ def _sources(world: _World, *names: str) -> None: world.sources = [_source(name) for name in names] +def _noted(leg: str, orgs: str = "1 of 1") -> list[tuple[str, str, str]]: + return [(source_sync.WORKER, "SourcesFailed", f"{leg} failed for most sources in {orgs} orgs")] + + def _turns(monkeypatch: pytest.MonkeyPatch, failing: set[str], *, how: str = "status") -> None: """Each source's turn: those in `failing` end `credential_invalid` (`status`), or their state write raises (`raises`); the others end ok.""" @@ -85,8 +91,7 @@ def test_two_failing_sources_of_three_note_one_pass_failure( result, ctx = asyncio.run(_supervised()) - assert ctx.count == 1 - assert ctx.failures == [(source_sync.WORKER, "SourcesFailed", "2 of 3 sources failed")] + assert (ctx.count, ctx.failures) == (1, _noted("sync")) assert result.failed == 2 and len(result.errors) == 2 @@ -99,7 +104,26 @@ def test_the_only_source_failing_notes_one_pass_failure( _, ctx = asyncio.run(_supervised()) - assert ctx.failures == [(source_sync.WORKER, "SourcesFailed", "1 of 1 sources failed")] + assert ctx.failures == _noted("sync") + + +@pytest.mark.parametrize("other_fails", [False, True], ids=["other-ok", "other-fails"]) +def test_one_orgs_failing_sources_are_not_the_others_failure( + world: _World, monkeypatch: pytest.MonkeyPatch, other_fails: bool +) -> None: + """Most of the pass's sources are one org's, and all of them fail: the other org's + source syncs, so the worker has not failed. Both orgs failing is the worker's.""" + world.sources = [ + _source("a"), + _source("b"), + dataclasses.replace(_source("c"), org="other"), + ] + _turns(monkeypatch, {"a", "b", "c"} if other_fails else {"a", "b"}) + + result, ctx = asyncio.run(_supervised()) + + assert result.failed == (3 if other_fails else 2) + assert ctx.failures == (_noted("sync", "2 of 2") if other_fails else []) def test_half_the_sources_failing_is_not_most_of_them( @@ -134,7 +158,7 @@ async def busy(name: str, **kw: Any) -> Any: _, ctx = asyncio.run(_supervised()) - assert ctx.failures == [(source_sync.WORKER, "SourcesFailed", "1 of 1 sources failed")] + assert ctx.failures == _noted("sync") def test_mirrored_failures_count_toward_the_pass_with_their_one_code( @@ -148,7 +172,7 @@ def test_mirrored_failures_count_toward_the_pass_with_their_one_code( assert result.private_work and ctx.private_work assert result.errors == [f"{ORG}/{NS}/m1: SYNC_FAILED", f"{ORG}/{NS}/m2: SYNC_FAILED"] assert result.failed == 0 # a mirrored turn contributes its code, never a figure - assert ctx.failures == [(source_sync.WORKER, "SourcesFailed", "2 of 3 sources failed")] + assert ctx.failures == _noted("sync") def test_one_mirrored_failure_of_three_notes_no_pass_failure( @@ -163,11 +187,11 @@ def test_one_mirrored_failure_of_three_notes_no_pass_failure( assert ctx.count == 0 -def test_a_failed_store_read_every_source_shares_still_notes( +def test_a_failed_store_read_every_source_shares_notes_once( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - """The extraction leg's read of each source's documents is the store's: every - source's failed read is noted, as before, though every turn was ok.""" + """The mining leg's read of each source's documents is the store's: when it fails + for every source, the leg notes one failure, though every turn was ok.""" _sources(world, "a", "b", "c") _turns(monkeypatch, set()) @@ -178,6 +202,52 @@ async def down(*args: Any, **kw: Any) -> Any: result, ctx = asyncio.run(_supervised()) - assert ctx.count == 3 - assert [what for what, _, _ in ctx.failures] == [f"{ORG}/{NS}/{n}" for n in "abc"] + assert (ctx.count, ctx.failures) == (1, _noted("mining")) assert result.errors == [f"{ORG}/{NS}/{n}: extraction ConnectionError" for n in "abc"] + + +@pytest.mark.parametrize("failing", ["b", "abc"]) +def test_a_documents_failed_mining_is_its_sources_unless_most_fail( + world: _World, monkeypatch: pytest.MonkeyPatch, failing: str +) -> None: + """One document that fails to mine is retried for `_WAIT_PASSES` passes, as many as + the worker's streak needs: it is its source's failure, in its sync state. Every + source's mining failing (the model) is the worker's.""" + from server.memory.app.decision_extract import ExtractReport + + _sources(world, "a", "b", "c") + _turns(monkeypatch, set()) + + async def revisions(org: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + return [{"source_uri": f"https://docs.example.com/{tag}", "source_revision": "r1"}] + + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + world.mine_answer = lambda uri: ( + ExtractReport(uri, False, error="no chunks") if uri[-1] in failing else None + ) + + result, ctx = asyncio.run(_supervised()) + + assert len(world.mined) == 3 and result.failed == len(failing) + assert _detail(world, "b")["extract_error"] == "not_run" + assert ctx.failures == (_noted("mining") if failing == "abc" else []) + + +@pytest.mark.parametrize("failing", ["b", "abc"]) +def test_a_removed_sources_failed_retirement_is_its_own_unless_most_fail( + world: _World, monkeypatch: pytest.MonkeyPatch, failing: str +) -> None: + world.sources = [ + dataclasses.replace(_source(name), active=False, pending_delete=True) for name in "abc" + ] + + async def retire(src: KnowledgeSource, run: Any, result: Any) -> None: + if src.name in failing: + raise ConnectionError("store down") + + monkeypatch.setattr(source_sync, "_retire_all", retire) + + result, ctx = asyncio.run(_supervised()) + + assert result.failed == len(failing) + assert ctx.failures == (_noted("retirement") if failing == "abc" else []) diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 7a0f05f9157..f9db37525ff 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -356,17 +356,20 @@ async def test_an_org_admin_with_a_restricted_namespace_hidden_reads_no_counts( monkeypatch.setattr("server.auth.context.restricted_hidden", hidden) out = await _incidents() - assert (out.incidents, out.requests) == ([], "not_permitted") + assert (out.incidents, out.requests, out.sources.read) == ([], "not_permitted", "not_permitted") assert degradations.current() == [] hidden.return_value = (["*"], False) out = await _incidents() - assert (out.incidents, out.requests) == ([], "unread") - assert degradations.current() == ["ops.incidents: requests_unread (ClassificationUnavailable)"] + assert (out.incidents, out.requests, out.sources.read) == ([], "unread", "unread") + assert degradations.current() == [ + "ops.incidents: requests_unread (ClassificationUnavailable)", + "ops.incidents: sources_unread (ClassificationUnavailable)", + ] degradations.begin() hidden.return_value = (["code-secret"], True) # its grant could not be read out = await _incidents() - assert (out.incidents, out.requests) == ([], "unread") + assert (out.incidents, out.requests, out.sources.read) == ([], "unread", "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. @@ -377,8 +380,11 @@ async def test_an_org_admin_with_a_restricted_namespace_hidden_reads_no_counts( degradations.begin() hidden.side_effect = refused out = await _incidents() - assert (out.incidents, out.requests) == ([], "unread") - assert degradations.current() == [f"ops.incidents: requests_unread ({kind})"] + assert (out.incidents, out.requests, out.sources.read) == ([], "unread", "unread") + assert degradations.current() == [ + f"ops.incidents: requests_unread ({kind})", + f"ops.incidents: sources_unread ({kind})", + ] hidden.side_effect = None assert ch.statements("sli_minute") == ch.statements("loom.code_index_state") == [] From 375376c51d46b440248a611711bd2865ea70ae7b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 15:08:59 +0530 Subject: [PATCH 03/41] A source sync leg counts its failing orgs against every org the pass serves A leg divided its failing orgs by the orgs it handled, so a leg that reached one org read as a deployment with one org: one org's removed source whose retirement kept failing, or a pass bound that ended the turns inside one org's failing sources, still built the worker's streak. SourceTally.note now counts against the orgs of every active source the pass read, with those the leg ran for; an org the leg had nothing to do for has not failed. The tally keeps its failures' kinds (an exception's class, a turn's status, SYNC_FAILED for a mirrored source), and the note names the most common one: "sync failed for most sources in 3 of 4 orgs (most often credential_invalid)". The ops.incidents wire text says a failing source never makes status degraded by itself, and the read_scope reason names both org reads. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 14 ++-- docs/reference/operations/ops.md | 2 +- sdk/go/wire/models.gen.go | 2 +- server/identity/domain/read_scope.py | 3 +- server/insights/api/models_ops.py | 6 +- server/insights/app/incidents.py | 12 ++-- server/knowledge/app/source_sync.py | 70 +++++++++++-------- .../test_knowledge_source_sync_failures.py | 69 +++++++++++++++--- 8 files changed, 122 insertions(+), 56 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 6049a22be51..94eb93ae815 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -680,12 +680,14 @@ A failed turn belongs to its source: its `status` and `error` here, and for an o the org's failing sources in [`ops.incidents`](../operations/monitoring.md#opsincidents)' `sources`. Each leg of the worker's pass (the sync turns, mirrored ones included, the mining and the retirement of removed sources) counts the pass as failed toward the -worker's failure streak only when most of the orgs it ran for had most of their sources -fail (`knowledge_source_sync: sync failed for most sources in 3 of 4 orgs`): an outage of -what every source relies on, such as the store or the model, or a deployment with one -org. One org's failing sources, however many of the deployment's sources are its own, -therefore make neither the worker nor `ops.incidents` degraded for the other orgs. A -source another copy holds counts neither way. +worker's failure streak only when most of the orgs the pass serves had most of their +sources in that leg fail (`knowledge_source_sync: sync failed for most sources in 3 of 4 +orgs (most often credential_invalid)`); an org the leg had nothing to do for, or that +the pass bound left for the next pass, has not failed. That is an outage of what every +source relies on, such as the store or the model, or a deployment with one org. One +org's failing sources, however many of the deployment's sources are its own, therefore +make neither the worker nor `ops.incidents` degraded for the other orgs. A source +another copy holds counts neither way. ### A recording source diff --git a/docs/reference/operations/ops.md b/docs/reference/operations/ops.md index 0891f8a9836..69d79fe21b7 100644 --- a/docs/reference/operations/ops.md +++ b/docs/reference/operations/ops.md @@ -55,7 +55,7 @@ Whether Loom is degraded now, from its checks, providers, workers and calls. | Output field | Type | Meaning | | --- | --- | --- | -| `status` | `Literal['ok', 'degraded']` | `degraded` when an incident is listed, else `ok`; failing `sources` never count. | +| `status` | `Literal['ok', 'degraded']` | `degraded` when an incident is listed, else `ok`; failing `sources` are no incident. | | `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… | diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 5d35b24b9b4..19fca537098 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: 06bbf5342050633f15e6594b14317730f00f6968e3cb69eb9cd2c8f0d58e156a +// Registry model schema SHA-256: db0af3622b9805754647bd3a221683f04296a59aaac6a56638d34725e1892f24 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/identity/domain/read_scope.py b/server/identity/domain/read_scope.py index b70eaac647b..73d62683627 100644 --- a/server/identity/domain/read_scope.py +++ b/server/identity/domain/read_scope.py @@ -410,7 +410,8 @@ def pin_read_filters[M: BaseModel](input: M, auth: Any) -> tuple[M, bool]: "ops.capabilities": "the deployment's capabilities", "ops.health": "deployment health", "ops.incidents": ( - "the deployment's incidents; a narrowed token reads no request counts, no memory" + "the deployment's incidents; a narrowed token reads no request counts or failing" + " sources, no memory" ), "mentor.guide": "the deployment's static agent guide, no memory", "help.search": "the deployment's shipped documentation, no memory", diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 2d54f16188d..ed9a2f43263 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -214,7 +214,9 @@ class OpsIncidentSources(BaseModel): Those every reader of their namespace sees, never a mirrored one. A source's failure is its own (its `sync.status` in `knowledge.source.list`), so it never makes `status` - `degraded`: a revoked credential is its org's to fix, not a Loom outage.""" + `degraded` by itself: a revoked credential is its org's to fix, not a Loom outage. + The sync worker becomes an incident only when most orgs' sources fail for 3 passes in + a row (an outage, or a deployment with one org).""" # Sources whose last turn failed; 0 unless `read` is `read`. failing: int = 0 @@ -231,7 +233,7 @@ class OpsIncidentsOutput(BaseModel): 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`; failing `sources` never count. + # `degraded` when an incident is listed, else `ok`; failing `sources` are no incident. status: Literal["ok", "degraded"] # Errors first, at most 20. incidents: list[OpsIncident] = Field(default_factory=list) diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index c2cc6935672..99d6cad73c3 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -171,12 +171,12 @@ async def _reads_org_whole(org: str) -> OrgRead: 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), or no token where one - 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`.""" + 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, 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`, and both reads are named in `degraded` (`_org_unread`).""" from server.auth.context import current_auth, reads_every_namespace, restricted_hidden from server.identity.app.request_scope import request_narrowed diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index be7e8123a14..10229ca03a6 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -198,25 +198,36 @@ class SourcesFailed(RuntimeError): @dataclass class SourceTally: - """Per org, the sources one leg of a pass handled and those it failed.""" + """Per org, the sources one leg of a pass handled and those it failed, and the kinds + of their failures.""" ran: Counter[str] = field(default_factory=Counter) failed: Counter[str] = field(default_factory=Counter) + kinds: Counter[str] = field(default_factory=Counter) - def add(self, src: KnowledgeSource, *, failed: bool) -> None: + def add(self, src: KnowledgeSource, failure: str = "") -> None: + """Count a source the leg handled; `failure` is the kind of its failure (an + exception's class, a turn's status, `SYNC_FAILED` for a mirrored source), never + its text.""" self.ran[src.org] += 1 - self.failed[src.org] += failed - - def note(self, leg: str) -> None: - """One failure for the pass when most of the orgs the leg ran for had most of their - sources fail: an outage of what every source relies on (the store, the model), or - a deployment with one org. One org's failures, however many of the sources are - its own, are in their sync states (`knowledge.source.list`, `ops.incidents`' - `sources`), and no failure of the worker every org shares.""" - orgs = sum(self.failed[org] * 2 > n for org, n in self.ran.items()) - if orgs * 2 > len(self.ran): - msg = f"{leg} failed for most sources in {orgs} of {len(self.ran)} orgs" - pass_context.note_failure(SourcesFailed(msg), WORKER) + if failure: + self.failed[src.org] += 1 + self.kinds[failure] += 1 + + def note(self, leg: str, orgs: set[str]) -> None: + """One failure for the pass when most of the orgs it serves (`orgs`, with those + the leg ran for) had most of their sources in the leg fail; an org the leg had + nothing to do for has not failed. That is an outage of what every source relies + on (the store, the model), or a deployment with one org. One org's failures, + however many of the sources are its own, are in their sync states + (`knowledge.source.list`, `ops.incidents`' `sources`), and no failure of the + worker every org shares.""" + served = orgs | set(self.ran) + failing = sum(self.failed[org] * 2 > n for org, n in self.ran.items()) + if failing * 2 > len(served): + kind = self.kinds.most_common(1)[0][0] + msg = f"{leg} failed for most sources in {failing} of {len(served)} orgs" + pass_context.note_failure(SourcesFailed(f"{msg} (most often {kind})"), WORKER) # Why a turn stopped short: they lead its error text, and the dashboard reads a note that @@ -385,8 +396,9 @@ async def run_sync( found = [s for s in found if s.name == only] # An admin's delete request goes first, before the backlog of changed files and # before anything that reads the code registry. + orgs = {s.org for s in found} await _retire_removed_sources(run, result, org=org, namespace=namespace, only=only) - result.retiring.note("retirement") + result.retiring.note("retirement", orgs) if found: # The repository tags come from the registry: refresh it once per pass, and # stop the pass (RegistryUnread) while it has never been read. @@ -425,9 +437,9 @@ async def run_sync( # holds the others back; a requested source goes first anyway. pass_context.set_cursor(_cursor_of(src)) break - result.turns.note("sync") + result.turns.note("sync", orgs) await _extract_pending(order, run, result) - result.mining.note("mining") + result.mining.note("mining", orgs) if not order and not mirrored and not result.retired: pass_context.mark_idle() return result @@ -534,7 +546,7 @@ async def _sync_turn( log.info("knowledge_source_sync: %s is being synced by another copy", _cursor_of(src)) return None except Exception as e: # noqa: BLE001 — one source's failure must not stop the others - result.turns.add(src, failed=True) + result.turns.add(src, "SYNC_FAILED" if mirror_synced(src) else type(e).__name__) if mirror_synced(src): _mirror_failure(src, result) return None @@ -543,7 +555,7 @@ async def _sync_turn( log.warning("knowledge_source_sync: %s failed: %s", _cursor_of(src), e) return None if mirror_synced(src): - result.turns.add(src, failed=turn.status != "ok") + result.turns.add(src, "" if turn.status == "ok" else "SYNC_FAILED") if turn.status != "ok": _mirror_failure(src, result) return turn @@ -558,7 +570,7 @@ async def _sync_turn( and src.kind == "recording" and src.config.get("provider") == "meet" ) - result.turns.add(src, failed=failed) + result.turns.add(src, turn.status if failed else "") if failed: result.failed += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) @@ -1561,9 +1573,9 @@ async def _retire_removed_sources( result.errors.append(f"{_cursor_of(src)}: {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: retiring %s failed: %s", _cursor_of(src), e) - result.retiring.add(src, failed=True) + result.retiring.add(src, type(e).__name__) continue - result.retiring.add(src, failed=False) + result.retiring.add(src) async def _retire_all(src: KnowledgeSource, run: Pass, result: PassResult) -> None: @@ -1684,14 +1696,14 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass except Exception as e: # noqa: BLE001 — one source's failed read must not stop the others result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 - result.mining.add(src, failed=True) + result.mining.add(src, type(e).__name__) continue todo = _unmined(docs, detail) # A source with nothing to mine and no stale count to clear needs no write. if todo or detail.get("pending_extract"): queues.append((src, docs, todo)) else: - result.mining.add(src, failed=False) + result.mining.add(src) if not queues: return stop = "" @@ -1719,9 +1731,9 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) - result.mining.add(src, failed=True) + result.mining.add(src, type(e).__name__) continue - result.mining.add(src, failed=False) + result.mining.add(src) continue stop = await _extract_source(src, docs, run, result) @@ -1782,7 +1794,7 @@ async def _extract_source( leg (`_Mined.stop`), else ''. A pass stopped or cancelled records nothing: the documents it did not settle are unmined still.""" mined = _Mined(waits={}) - raised = False + raised = "" try: async with _source_turn(src) as lease: with sequential_reads(): @@ -1813,8 +1825,8 @@ def may_write() -> bool: result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: mining %s failed: %s", _cursor_of(src), e) - raised = True - result.mining.add(src, failed=raised or mined.failures > 0) + raised = type(e).__name__ + result.mining.add(src, raised or ((mined.error or "failed") if mined.failures else "")) result.extracted += mined.extracted result.flagged_pinned += mined.flagged result.unextracted += mined.unextracted diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 07e68f03937..20b05bd9e54 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -28,8 +28,12 @@ def _sources(world: _World, *names: str) -> None: world.sources = [_source(name) for name in names] -def _noted(leg: str, orgs: str = "1 of 1") -> list[tuple[str, str, str]]: - return [(source_sync.WORKER, "SourcesFailed", f"{leg} failed for most sources in {orgs} orgs")] +def _noted(leg: str, kind: str, orgs: str = "1 of 1") -> list[tuple[str, str, str]]: + msg = f"{leg} failed for most sources in {orgs} orgs (most often {kind})" + return [(source_sync.WORKER, "SourcesFailed", msg)] + + +_KIND = {"status": "credential_invalid", "raises": "ConnectionError"} def _turns(monkeypatch: pytest.MonkeyPatch, failing: set[str], *, how: str = "status") -> None: @@ -91,7 +95,7 @@ def test_two_failing_sources_of_three_note_one_pass_failure( result, ctx = asyncio.run(_supervised()) - assert (ctx.count, ctx.failures) == (1, _noted("sync")) + assert (ctx.count, ctx.failures) == (1, _noted("sync", _KIND[how])) assert result.failed == 2 and len(result.errors) == 2 @@ -104,7 +108,7 @@ def test_the_only_source_failing_notes_one_pass_failure( _, ctx = asyncio.run(_supervised()) - assert ctx.failures == _noted("sync") + assert ctx.failures == _noted("sync", "credential_invalid") @pytest.mark.parametrize("other_fails", [False, True], ids=["other-ok", "other-fails"]) @@ -123,7 +127,30 @@ def test_one_orgs_failing_sources_are_not_the_others_failure( result, ctx = asyncio.run(_supervised()) assert result.failed == (3 if other_fails else 2) - assert ctx.failures == (_noted("sync", "2 of 2") if other_fails else []) + assert ctx.failures == (_noted("sync", "credential_invalid", "2 of 2") if other_fails else []) + + +def test_a_pass_cut_inside_one_orgs_failing_sources_is_not_the_others_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """The pass bound ends the turns after one org's failing sources: the org whose + source the pass did not reach has not failed.""" + world.sources = [_source("a"), _source("b"), dataclasses.replace(_source("c"), org="other")] + _turns(monkeypatch, {"a", "b"}) + ran: list[str] = [] + sync_one = source_sync._sync_one + + async def counted(src: KnowledgeSource, *args: Any) -> Any: + ran.append(src.name) + return await sync_one(src, *args) + + monkeypatch.setattr(source_sync, "_sync_one", counted) + monkeypatch.setattr(source_sync.Pass, "spent", lambda self: len(ran) >= 2) + + result, ctx = asyncio.run(_supervised()) + + assert ran == ["a", "b"] and result.cut and result.failed == 2 + assert ctx.failures == [] def test_half_the_sources_failing_is_not_most_of_them( @@ -158,7 +185,7 @@ async def busy(name: str, **kw: Any) -> Any: _, ctx = asyncio.run(_supervised()) - assert ctx.failures == _noted("sync") + assert ctx.failures == _noted("sync", "credential_invalid") def test_mirrored_failures_count_toward_the_pass_with_their_one_code( @@ -172,7 +199,7 @@ def test_mirrored_failures_count_toward_the_pass_with_their_one_code( assert result.private_work and ctx.private_work assert result.errors == [f"{ORG}/{NS}/m1: SYNC_FAILED", f"{ORG}/{NS}/m2: SYNC_FAILED"] assert result.failed == 0 # a mirrored turn contributes its code, never a figure - assert ctx.failures == _noted("sync") + assert ctx.failures == _noted("sync", "SYNC_FAILED") def test_one_mirrored_failure_of_three_notes_no_pass_failure( @@ -202,7 +229,7 @@ async def down(*args: Any, **kw: Any) -> Any: result, ctx = asyncio.run(_supervised()) - assert (ctx.count, ctx.failures) == (1, _noted("mining")) + assert (ctx.count, ctx.failures) == (1, _noted("mining", "ConnectionError")) assert result.errors == [f"{ORG}/{NS}/{n}: extraction ConnectionError" for n in "abc"] @@ -230,7 +257,7 @@ async def revisions(org: str, ns: str, tag: str, **kw: Any) -> list[dict[str, st assert len(world.mined) == 3 and result.failed == len(failing) assert _detail(world, "b")["extract_error"] == "not_run" - assert ctx.failures == (_noted("mining") if failing == "abc" else []) + assert ctx.failures == (_noted("mining", "not_run") if failing == "abc" else []) @pytest.mark.parametrize("failing", ["b", "abc"]) @@ -250,4 +277,26 @@ async def retire(src: KnowledgeSource, run: Any, result: Any) -> None: result, ctx = asyncio.run(_supervised()) assert result.failed == len(failing) - assert ctx.failures == (_noted("retirement") if failing == "abc" else []) + assert ctx.failures == (_noted("retirement", "ConnectionError") if failing == "abc" else []) + + +def test_one_orgs_failed_retirement_is_not_the_others_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Only one org has a removed source, and its retirement fails every pass: the other + org, which the leg has nothing to do for, has not failed.""" + world.sources = [ + dataclasses.replace(_source("gone"), active=False, pending_delete=True), + dataclasses.replace(_source("c"), org="other"), + ] + _turns(monkeypatch, set()) + + async def retire(src: KnowledgeSource, run: Any, result: Any) -> None: + raise ConnectionError("store down") + + monkeypatch.setattr(source_sync, "_retire_all", retire) + + result, ctx = asyncio.run(_supervised()) + + assert result.errors[:1] == [f"{ORG}/{NS}/gone: ConnectionError"] + assert ctx.failures == [] From e529d1c81ff611eff5e1203895917fb4b12b45fb Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 15:25:56 +0530 Subject: [PATCH 04/41] A source sync leg counts against the orgs whose sources the pass syncs The denominator held the org of every active registry row, so orgs whose only rows the pass never syncs (a worker's row, a source in an inactive namespace) diluted an outage of every org it does sync until no leg noted it. It is now the orgs of the usable sources, and the retirement note follows that read. tests/integration/test_ops_incidents.py reads ops.incidents over the transport against the real store: the caller org's two failing sources, latest first, and none of another org's. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/insights/app/incidents.py | 3 +- server/knowledge/app/source_sync.py | 5 +- tests/integration/test_ops_incidents.py | 48 +++++++++++++++++++ .../test_knowledge_source_sync_diagnostics.py | 2 +- .../test_knowledge_source_sync_failures.py | 19 +++++++- 5 files changed, 71 insertions(+), 6 deletions(-) create mode 100644 tests/integration/test_ops_incidents.py diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 99d6cad73c3..7f40e2662dd 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -176,7 +176,8 @@ async def _reads_org_whole(org: str) -> OrgRead: 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`, and both reads are named in `degraded` (`_org_unread`).""" + `unread`. An unknown restricted set and a refused tenancy check name both reads in + `degraded` (`_org_unread`); an unread grant is named there by `restricted_hidden`.""" from server.auth.context import current_auth, reads_every_namespace, restricted_hidden from server.identity.app.request_scope import request_narrowed diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 10229ca03a6..50037e65a23 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -396,15 +396,16 @@ async def run_sync( found = [s for s in found if s.name == only] # An admin's delete request goes first, before the backlog of changed files and # before anything that reads the code registry. - orgs = {s.org for s in found} await _retire_removed_sources(run, result, org=org, namespace=namespace, only=only) - result.retiring.note("retirement", orgs) if found: # The repository tags come from the registry: refresh it once per pass, and # stop the pass (RegistryUnread) while it has never been read. await repo_registry.refresh_db_repos() require_registry_read() usable = await _usable(found) + # The orgs the pass serves: each leg's failure note counts against them. + orgs = {s.org for s in usable} + result.retiring.note("retirement", orgs) if full: for src in usable: await source_ops.request_full_sync(src) diff --git a/tests/integration/test_ops_incidents.py b/tests/integration/test_ops_incidents.py new file mode 100644 index 00000000000..480b941a44a --- /dev/null +++ b/tests/integration/test_ops_incidents.py @@ -0,0 +1,48 @@ +"""ops.incidents over the transport against the real store: the caller org's failing +document sources, read from their sync states, and nothing of another org's.""" + +from __future__ import annotations + +import json +from typing import Any + +import httpx + +from tests.integration._resources import unique_org +from tests.integration._sources import seed_source + +NS = "team-incidents" + + +def _sync_state(ch: Any, org: str, name: str, status: str, synced_at: str) -> None: + detail = json.dumps({"status": status, "last_synced_at": synced_at}, sort_keys=True) + ch.insert( + "loom.code_index_state", + [[org, NS, f"knowledge_source:{name}", detail]], + column_names=["org", "namespace", "state_key", "detail"], + ) + + +def test_the_answer_lists_the_callers_failing_sources_only( + control_plane_url: str, ch_client: Any +) -> None: + org, other = unique_org("incidents"), unique_org("incidents") + for each in (org, other): + for name in ("decks", "notes", "wiki"): + seed_source(ch_client, each, NS, name) + _sync_state(ch_client, org, "decks", "credential_invalid", "2026-01-02T00:00:00+00:00") + _sync_state(ch_client, org, "wiki", "rate_limited", "2026-01-03T00:00:00+00:00") + _sync_state(ch_client, org, "notes", "ok", "2026-01-04T00:00:00+00:00") + _sync_state(ch_client, other, "notes", "failed", "2026-01-05T00:00:00+00:00") + + resp = httpx.post(f"{control_plane_url}/v1/ops.incidents", json={"org": org}, timeout=30.0) + + assert resp.status_code == 200, resp.text + assert resp.json()["sources"] == { + "failing": 2, + "sample": [ + {"namespace": NS, "name": "wiki", "status": "rate_limited"}, + {"namespace": NS, "name": "decks", "status": "credential_invalid"}, + ], + "read": "read", + } diff --git a/tests/unit/test_knowledge_source_sync_diagnostics.py b/tests/unit/test_knowledge_source_sync_diagnostics.py index 8e8f7efe1c0..38d8c2d6b39 100644 --- a/tests/unit/test_knowledge_source_sync_diagnostics.py +++ b/tests/unit/test_knowledge_source_sync_diagnostics.py @@ -66,7 +66,7 @@ async def run(*args: Any, answer: Any = turn) -> Any: answers.append(outcome(result)) if mirrored: # The pass's tally of turns is all a mirrored turn adds: no document figure. - turns = sync.SourceTally(ran=Counter(acme=1), failed=Counter(acme=0)) + turns = sync.SourceTally(ran=Counter(acme=1)) assert result == sync.PassResult(sources=1, private_work=True, turns=turns) else: assert result.changed == count and result.cut diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 20b05bd9e54..23649cee3c1 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -3,8 +3,8 @@ A source whose turn failed has its failure in its own sync state (`status`, `error`), which its namespace's readers see; the pass notes no failure for it. Each leg of the pass (the sync turns, the mining, the retirement of removed sources) notes one failure -only when most of the orgs it ran for had most of their sources fail: an outage of what -every source relies on, or a deployment with a single org. One org's failures, however +only when most of the orgs the pass serves had most of their sources fail: an outage of +what every source relies on, or a deployment with a single org. One org's failures, however many of the sources are its own, are no failure of the worker every org shares.""" from __future__ import annotations @@ -130,6 +130,21 @@ def test_one_orgs_failing_sources_are_not_the_others_failure( assert ctx.failures == (_noted("sync", "credential_invalid", "2 of 2") if other_fails else []) +def test_an_org_the_pass_does_not_sync_does_not_dilute_an_outage( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """The other org's only source is in an inactive namespace: the pass syncs nothing of + it, so every org the pass serves failing is still the worker's failure.""" + world.sources = [_source("a"), _source("b"), dataclasses.replace(_source("c"), org="other")] + world.inactive = {("other", NS)} + _turns(monkeypatch, {"a", "b", "c"}) + + result, ctx = asyncio.run(_supervised()) + + assert result.failed == 2 + assert ctx.failures == _noted("sync", "credential_invalid") + + def test_a_pass_cut_inside_one_orgs_failing_sources_is_not_the_others_failure( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: From e079a3555153f7dccd6c191def088ef198211037 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 15:49:04 +0530 Subject: [PATCH 05/41] ops.incidents sources leave out the collections the caller cannot read The gate lets an org admin over * read the org whole once no restricted namespace is hidden from it, but collections are not in the restricted set: an org admin reaches one only through a grant. The sources read named a collection's failing source to an org admin with no grant on it, and its per-org cache served that answer to every caller. The read now applies collection_clause(org), fails closed when the grants cannot be read, and is cached per org and caller. A source's mining counts as failed only when it raised or most of its documents failed: one document that fails to mine is that document's, in the source's extract_error, even for a deployment's only source. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 4 +- sdk/go/wire/models.gen.go | 2 +- server/insights/api/models_ops.py | 18 +++++---- server/insights/app/incidents.py | 25 ++++++++++--- server/knowledge/app/source_sync.py | 16 ++++---- server/knowledge/app/sources.py | 6 ++- server/knowledge/store/sources.py | 19 +++++++--- .../test_knowledge_source_sync_failures.py | 29 +++++++++++++++ tests/unit/test_ops_incidents.py | 37 ++++++++++++++++++- tests/unit/test_ops_incidents_sql.py | 36 +++++++++++++++++- 10 files changed, 160 insertions(+), 32 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 9fe6149ae4c..8598c865b96 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -180,7 +180,9 @@ whose last sync turn failed: `failing`, how many, and `sample`, at most 5 of the `rate_limited` or `credential_invalid`. It counts only the sources every reader of their namespace sees, never a mirrored or a person's connected one, whose state is its mirror's. It is read under the same rule as the request counts, and `sources.read` answers in the -same words. A failing document source is never an incident and never makes `status` +same words. It leaves out the collections the caller holds no grant for, since an org +admin reaches a collection only through a grant (a platform admin reads every one). A +failing document source is never an incident and never by itself makes `status` `degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own health. The `knowledge_source_sync` worker becomes a `worker` incident only after 3 passes in a row in which one of its legs (the sync turns, the mining, the retirement of diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 19fca537098..91bbd283135 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: db0af3622b9805754647bd3a221683f04296a59aaac6a56638d34725e1892f24 +// Registry model schema SHA-256: 29e1ee0038b87c589e4dbc62b19e64df79ed7eee52cce3e17a8474dbce8586ff // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index ed9a2f43263..2fc74e8b4f3 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -170,9 +170,10 @@ class OpsIncidentsInput(BaseModel): It lists failing readiness checks, providers and workers, and the share of the org's calls that failed on the server; beside them, the org's document sources whose last sync failed. Only a caller that reads the org whole (an org admin over `*`, a platform - admin) reads the calls and the sources; `requests` and `sources.read` say whether - they were read. Identity is optional: the org is the token's (role check only; no - namespace is addressed).""" + admin) reads the calls and the sources, and the sources leave out the collections it + holds no grant for; `requests` and `sources.read` say whether they were read. + Identity is optional: the org is the token's (role check only; no namespace is + addressed).""" org: str = "" @@ -212,11 +213,12 @@ class OpsFailingSource(BaseModel): class OpsIncidentSources(BaseModel): """The org's own document sources whose last sync turn failed. - Those every reader of their namespace sees, never a mirrored one. A source's failure - is its own (its `sync.status` in `knowledge.source.list`), so it never makes `status` - `degraded` by itself: a revoked credential is its org's to fix, not a Loom outage. - The sync worker becomes an incident only when most orgs' sources fail for 3 passes in - a row (an outage, or a deployment with one org).""" + Those every reader of their namespace sees, never a mirrored one, in the namespaces + and the collections the caller reads. A source's failure is its own (its + `sync.status` in `knowledge.source.list`), so it never makes `status` `degraded` by + itself: a revoked credential is its org's to fix, not a Loom outage. The sync worker + becomes an incident only when most orgs' sources fail for 3 passes in a row (an + outage, or a deployment with one org).""" # Sources whose last turn failed; 0 unless `read` is `read`. failing: int = 0 diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 7f40e2662dd..3d8f8abaf96 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -48,8 +48,8 @@ _WORKER_WINDOW_HOURS = 6 # not a setting: polls within it share one read of each ClickHouse source _SOURCE_TTL_S = 5.0 -# Each org polling holds two entries (its request counts, its sources); past this the -# cache starts over. +# Each org polling holds an entry for its request counts and one for each caller's +# sources; past this the cache starts over. # not a setting: a memory bound, not a behaviour _CACHE_MAX = 1024 @@ -226,10 +226,16 @@ async def _requests(org: str, minutes: int) -> list[OpsIncident]: async def _sources(org: str) -> OpsIncidentSources: - """The org's failing document sources: how many, and the latest few.""" + """The org's failing document sources the caller may read: how many, and the latest + few. A collection shows only to whom its grants reach, org admins included; a + platform admin reads every one.""" + from server.auth.context import collection_clause from server.knowledge.app.sources import failing_sources - failing, sample = await failing_sources(org, sample=MAX_SOURCE_SAMPLE) + scope, params = await collection_clause(org) + failing, sample = await failing_sources( + org, sample=MAX_SOURCE_SAMPLE, scope=scope, scope_params=params + ) return OpsIncidentSources( failing=failing, sample=[OpsFailingSource(**row) for row in sample], @@ -237,6 +243,15 @@ async def _sources(org: str) -> OpsIncidentSources: ) +def _caller(org: str) -> str: + """The cache key of the org's sources for the current caller: the collections it + reads are its own, so no caller is served another's read.""" + from server.auth.context import current_auth + + auth = current_auth() + return f"{org}\n{auth.subject}" if auth is not None else org + + async def _org_reads( org: str, minutes: int ) -> tuple[list[OpsIncident], OrgRead, OpsIncidentSources]: @@ -248,7 +263,7 @@ async def _org_reads( return [], reach, OpsIncidentSources(read=reach) (calls, answered), (sources, _) = await asyncio.gather( _cached("requests", org, lambda: _requests(org, minutes), list[OpsIncident]()), - _cached("sources", org, lambda: _sources(org), OpsIncidentSources(read="unread")), + _cached("sources", _caller(org), lambda: _sources(org), OpsIncidentSources(read="unread")), ) return calls, "read" if answered else "unread", sources diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 50037e65a23..d297df1ea78 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -219,14 +219,14 @@ def note(self, leg: str, orgs: set[str]) -> None: the leg ran for) had most of their sources in the leg fail; an org the leg had nothing to do for has not failed. That is an outage of what every source relies on (the store, the model), or a deployment with one org. One org's failures, - however many of the sources are its own, are in their sync states - (`knowledge.source.list`, `ops.incidents`' `sources`), and no failure of the - worker every org shares.""" - served = orgs | set(self.ran) + however many of the sources are its own, are its own (a source's sync state, and + for a state write that failed the server's log), and no failure of the worker + every org shares.""" + serving = orgs | set(self.ran) failing = sum(self.failed[org] * 2 > n for org, n in self.ran.items()) - if failing * 2 > len(served): + if failing * 2 > len(serving): kind = self.kinds.most_common(1)[0][0] - msg = f"{leg} failed for most sources in {failing} of {len(served)} orgs" + msg = f"{leg} failed for most sources in {failing} of {len(serving)} orgs" pass_context.note_failure(SourcesFailed(f"{msg} (most often {kind})"), WORKER) @@ -1827,7 +1827,9 @@ def may_write() -> bool: result.failed += 1 log.warning("knowledge_source_sync: mining %s failed: %s", _cursor_of(src), e) raised = type(e).__name__ - result.mining.add(src, raised or ((mined.error or "failed") if mined.failures else "")) + # One document that fails is its own, in the source's `extract_error`; most of the + # source's documents failing is the source's mining failing. + result.mining.add(src, raised or (mined.error if mined.failures * 2 > len(docs) else "")) result.extracted += mined.extracted result.flagged_pinned += mined.flagged result.unextracted += mined.unextracted diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index c7bd1657448..315c0a049e4 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -523,12 +523,14 @@ async def handle_knowledge_source_list( ) -async def failing_sources(org: str, *, sample: int) -> tuple[int, list[dict[str, str]]]: +async def failing_sources( + org: str, *, sample: int, scope: str = "", scope_params: dict[str, Any] | None = None +) -> tuple[int, list[dict[str, str]]]: """How many of the org's sources that every reader of their namespace sees ended their last sync turn failing, and `sample` of them ({namespace, name, status}), the latest failure first. A mirrored source's state is its mirror's, so none is counted. The caller decides who may read them: they span every namespace of the org.""" - return await store.failing_sources(org, sample=sample) + return await store.failing_sources(org, sample=sample, scope=scope, scope_params=scope_params) async def handle_knowledge_source_inspect( diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 8d5965c019d..cfe08571eb2 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -518,7 +518,8 @@ async def read_states( # removed source stays, so the registry's active row is joined in; a mirror's own state # rows and a mirrored or worker source's are left out. `provider_removed` ends only a meet # recording source's turn, which the sync does not count as failed. -_FAILING_SOURCES_SQL = f""" +def _failing_sources_sql(scope: str) -> str: + return f""" SELECT namespace, substring(state_key, {{start:UInt64}}) AS source_name, @@ -527,7 +528,7 @@ async def read_states( FROM {STATE_TABLE} FINAL WHERE org = {{org:String}} AND startsWith(state_key, {{prefix:String}}) - AND {not_reserved_sql()} + AND {not_reserved_sql()}{scope} AND JSONExtractString(detail, 'status') NOT IN ('', 'ok', 'provider_removed') AND (namespace, state_key) IN ( SELECT namespace, concat({{prefix:String}}, name) @@ -546,13 +547,21 @@ async def read_states( async def failing_sources( - org: str, *, sample: int, ch: _CHClient | None = None + org: str, + *, + sample: int, + scope: str = "", + scope_params: dict[str, Any] | None = None, + ch: _CHClient | None = None, ) -> tuple[int, list[dict[str, str]]]: """How many of the org's sources shown to their namespace's readers ended their last - turn failing, and `sample` of them ({namespace, name, status}), the latest first.""" + turn failing, and `sample` of them ({namespace, name, status}), the latest first. + `scope` is a WHERE fragment on `namespace` with its `scope_params`: the collections + the caller cannot read (`collection_clause`).""" rows = await (ch or _default_client()).query_all( - _FAILING_SOURCES_SQL, + _failing_sources_sql(scope), params={ + **(scope_params or {}), "org": org, "prefix": STATE_KEY_PREFIX, "start": len(STATE_KEY_PREFIX) + 1, diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 23649cee3c1..de12d959dc1 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -275,6 +275,35 @@ async def revisions(org: str, ns: str, tag: str, **kw: Any) -> list[dict[str, st assert ctx.failures == (_noted("mining", "not_run") if failing == "abc" else []) +@pytest.mark.parametrize("failing", ["1", "123"]) +def test_one_failing_document_does_not_fail_its_source( + world: _World, monkeypatch: pytest.MonkeyPatch, failing: str +) -> None: + """A deployment with one source of three documents: one document that fails to mine + is that document's, in its source's `extract_error`; most of them failing is the + source's mining failing.""" + from server.memory.app.decision_extract import ExtractReport + + _sources(world, "a") + _turns(monkeypatch, set()) + + async def revisions(org: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + return [ + {"source_uri": f"https://docs.example.com/{tag}/{i}", "source_revision": "r1"} + for i in "123" + ] + + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + world.mine_answer = lambda uri: ( + ExtractReport(uri, False, error="no chunks") if uri[-1] in failing else None + ) + + result, ctx = asyncio.run(_supervised()) + + assert len(world.mined) == 3 and result.failed == len(failing) + assert ctx.failures == (_noted("mining", "not_run") if failing == "123" else []) + + @pytest.mark.parametrize("failing", ["b", "abc"]) def test_a_removed_sources_failed_retirement_is_its_own_unless_most_fail( world: _World, monkeypatch: pytest.MonkeyPatch, failing: str diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index f9db37525ff..9ad6b56dcb9 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -29,10 +29,11 @@ def _token( org: str = "acme", namespaces: tuple[str, ...] = ("*",), roles: tuple[Role, ...] = (Role.VIEWER,), + subject: str = "viewer", **kw: Any, ) -> AuthInfo: return AuthInfo( - subject="viewer", + subject=subject, org=org, namespaces=namespaces, roles=roles, @@ -55,6 +56,7 @@ def _clean(monkeypatch: pytest.MonkeyPatch): monkeypatch.setattr( "server.auth.context.restricted_hidden", AsyncMock(return_value=([], False)) ) + monkeypatch.setattr("server.auth.sharing.readable", AsyncMock(return_value=[])) provider_health.reset() degradations.begin() yield @@ -439,6 +441,39 @@ async def test_each_org_reads_its_own_sources_once_per_ttl(monkeypatch) -> None: assert other.sources.failing == 7 # the route answers every org alike here +@pytest.mark.asyncio +async def test_a_collection_the_caller_holds_no_grant_for_is_left_out(monkeypatch) -> None: + """An org admin reaches a collection only through a grant, so the sources of the + others are neither counted nor named; a platform admin reads every collection. Each + caller's answer is its own: it is never served from another caller's read.""" + monkeypatch.setattr("server.auth.sharing.readable", AsyncMock(return_value=["col-board"])) + ch = _ch(monkeypatch, sources=_FAILING) + + await _incidents() + await _incidents(auth=_token(roles=(Role.PLATFORM_ADMIN,), subject="root")) + await _incidents(auth=_token(roles=(Role.ORG_ADMIN,), subject="other-admin")) + + admin, platform, other = ch.statements("loom.code_index_state") + assert (admin.params["col_prefix"], admin.params["col_readable"]) == ("col-", ["col-board"]) + assert "startsWith(namespace, {col_prefix:String})" in admin.sql + assert "col_prefix" not in platform.params and "col_prefix" not in platform.sql + assert other.params["col_readable"] == ["col-board"] + + +@pytest.mark.asyncio +async def test_an_unread_collection_reach_answers_unread(monkeypatch) -> None: + monkeypatch.setattr( + "server.auth.sharing.readable", AsyncMock(side_effect=RuntimeError("grants down")) + ) + ch = _ch(monkeypatch, sources=_FAILING) + + out = await _incidents() + + assert (out.sources.read, out.sources.failing, out.sources.sample) == ("unread", 0, []) + assert ch.statements("loom.code_index_state") == [] + assert [n.split(" (")[0] for n in degradations.current()] == ["ops.incidents: sources_unread"] + + @pytest.mark.asyncio async def test_a_member_reads_no_sources(monkeypatch) -> None: """A member's `*` token could hold no grant on a restricted namespace whose source diff --git a/tests/unit/test_ops_incidents_sql.py b/tests/unit/test_ops_incidents_sql.py index 480c5c0c1d1..ff64e531a59 100644 --- a/tests/unit/test_ops_incidents_sql.py +++ b/tests/unit/test_ops_incidents_sql.py @@ -133,6 +133,7 @@ async def read(org: str) -> list[tuple[str, int, int]]: ("o1", "team", "fresh", "namespace", "shared", "gdrive", 1, 1), ("o1", "paused", "old", "namespace", "shared", "gdrive", 1, 1), # an inactive namespace ("o2", "team", "decks", "namespace", "shared", "gdrive", 1, 1), # another org's + ("o1", "col-board", "minutes", "namespace", "shared", "gdrive", 1, 1), # a collection's ] # (org, namespace, state key, status, last turn, version) @@ -155,6 +156,7 @@ async def read(org: str) -> list[tuple[str, int, int]]: ("o1", "paused", "knowledge_source:old", "failed", "2026-03-09T00:00:00+00:00", 1), ("o1", "team", "code_cursor:main", "failed", "2026-03-09T00:00:00+00:00", 1), # no source's ("o2", "team", "knowledge_source:decks", "failed", "2026-03-09T00:00:00+00:00", 1), + ("o1", "col-board", "knowledge_source:minutes", "failed", "2026-03-08T00:00:00+00:00", 1), ] @@ -190,18 +192,48 @@ async def test_the_sources_read_counts_and_samples_the_orgs_own_failing_sources( ch: Any = LocalCH(*_source_rows()) + # No collection clause: a platform admin, or auth off, reads every collection. failing, sample = await sources.failing_sources("o1", sample=5, ch=ch) - assert failing == 3 + assert failing == 4 assert sample == [ + {"namespace": "col-board", "name": "minutes", "status": "failed"}, {"namespace": "ops", "name": "runbooks", "status": "rate_limited"}, {"namespace": "team", "name": "decks", "status": "credential_invalid"}, {"namespace": "team", "name": "broke", "status": "failed"}, ] failing, sample = await sources.failing_sources("o1", sample=2, ch=ch) - assert failing == 3 and [s["name"] for s in sample] == ["runbooks", "decks"] + assert failing == 4 and [s["name"] for s in sample] == ["minutes", "runbooks"] assert await sources.failing_sources("o2", sample=5, ch=ch) == ( 1, [{"namespace": "team", "name": "decks", "status": "failed"}], ) assert await sources.failing_sources("o3", sample=5, ch=ch) == (0, []) + + +@pytest.mark.parametrize("readable", [[], ["col-board"]], ids=["no-grant", "granted"]) +async def test_the_sources_read_leaves_out_the_collections_the_caller_cannot_read( + monkeypatch: pytest.MonkeyPatch, readable: list[str] +) -> None: + """The fragment `collection_clause` gives an org admin, run on the statement.""" + from types import SimpleNamespace + from unittest.mock import AsyncMock + + from server.auth import context + from server.knowledge.store import sources + + admin = SimpleNamespace(has_role=lambda role: False) + monkeypatch.setattr(context, "current_auth", lambda: admin) + monkeypatch.setattr("server.auth.sharing.readable", AsyncMock(return_value=readable)) + where, params = await context.collection_clause("o1") + ch: Any = LocalCH(*_source_rows()) + + failing, sample = await sources.failing_sources( + "o1", sample=5, scope=where, scope_params=params, ch=ch + ) + + names = [s["name"] for s in sample] + if readable: + assert (failing, names) == (4, ["minutes", "runbooks", "decks", "broke"]) + else: + assert (failing, names) == (3, ["runbooks", "decks", "broke"]) From b29f113107b538aa80378626119ca9c31002e2f7 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 16:11:55 +0530 Subject: [PATCH 06/41] A refused credential never counts toward the source sync worker's failure A deployment where most orgs held a lapsed credential (dormant accounts) made every pass note SourcesFailed, and ops.incidents answer degraded to the active orgs. A namespace source's credential_invalid turn now counts as handled in the tally; it stays in result.failed, the errors and the source's sync state. A mirrored turn still counts as failed for every cause alike, so the private status row tells no cause. ops.incidents resolves the caller's collection reach before its cache and keys the cache on it, so a subject reading as a platform admin and as an org admin, or two callers of different reach, are never served each other's read. sharing.readable answers an unread tree or grant as no shared collection; the read checks fail_closed.unreadable and answers unread instead of a narrower count. The docs name what the rules do not catch: a model outage while a pass mines few changed documents, and any leg's failure on a deployment with an active mirrored source, whose passes leave the streak as it was. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 20 ++++-- docs/operations/monitoring.md | 5 +- server/insights/app/incidents.py | 66 ++++++++++++------- server/knowledge/app/source_sync.py | 20 ++++-- tests/unit/test_knowledge_source_sync.py | 4 +- .../test_knowledge_source_sync_failures.py | 43 +++++++++--- tests/unit/test_ops_incidents.py | 27 ++++++-- 7 files changed, 131 insertions(+), 54 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 94eb93ae815..4f1ca730471 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -682,12 +682,20 @@ the org's failing sources in [`ops.incidents`](../operations/monitoring.md#opsin mining and the retirement of removed sources) counts the pass as failed toward the worker's failure streak only when most of the orgs the pass serves had most of their sources in that leg fail (`knowledge_source_sync: sync failed for most sources in 3 of 4 -orgs (most often credential_invalid)`); an org the leg had nothing to do for, or that -the pass bound left for the next pass, has not failed. That is an outage of what every -source relies on, such as the store or the model, or a deployment with one org. One -org's failing sources, however many of the deployment's sources are its own, therefore -make neither the worker nor `ops.incidents` degraded for the other orgs. A source -another copy holds counts neither way. +orgs (most often failed)`); an org the leg had nothing to do for, or that the pass bound +left for the next pass, has not failed. That is an outage of what every source relies +on, such as the store or a source's provider, or a deployment with one org. One org's +failing sources, however many of the deployment's sources are its own, therefore make +neither the worker nor `ops.incidents` degraded for the other orgs. A source another +copy holds counts neither way, and a refused credential (`credential_invalid`) of a +namespace's source never counts: it is its org's to rotate, however many orgs hold one. + +The mining leg counts a source as failed when most of its documents failed, so one +document that fails to mine is that document's, in `extract_error`. A model outage while +a pass mines only a few changed documents is therefore not counted toward the streak; +each source's `extract_error` shows it. A pass that runs any mirrored turn is private, +and the worker's streak stays as it was: on a deployment with an active mirrored source, +no leg's failure reaches the streak, and the pass's status row reads `SYNC_FAILED`. ### A recording source diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 8598c865b96..d6c0fcc08c7 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -187,7 +187,10 @@ failing document source is never an incident and never by itself makes `status` health. The `knowledge_source_sync` worker becomes a `worker` incident only after 3 passes in a row in which one of its legs (the sync turns, the mining, the retirement of removed sources) failed for most of the sources of most orgs: an outage of what every -source relies on, such as the store or the model, or a deployment with one org. +source relies on, such as the store or a source's provider, or a deployment with one org. +A refused credential never counts toward it, and neither does a pass that runs a +mirrored source's turn, which leaves the streak as it was (see +[document sources](../features/knowledge.md#syncing-a-source)). ### Smoke test diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 3d8f8abaf96..bd0eb336b5b 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -42,19 +42,20 @@ MAX_INCIDENTS = 20 # not a setting: the bound the output model documents MAX_SOURCE_SAMPLE = 5 +_UNREAD_SOURCES = OpsIncidentSources(read="unread") # 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 -# Each org polling holds an entry for its request counts and one for each caller's -# sources; past this the cache starts over. +# Each org polling holds an entry for its request counts and one for each collection +# reach its callers have; past this the cache starts over. # not a setting: a memory bound, not a behaviour _CACHE_MAX = 1024 -# (source, org) -> (read at, what it read, the read's failure or ""), and the lock its -# polls share while one reads +# (source, key) -> (read at, what it read, the read's failure or ""), and the lock its +# polls share while one reads; the key is the org, and for the sources the caller's reach _cache: dict[tuple[str, str], tuple[float, Any, str]] = {} _locks: dict[tuple[str, str], asyncio.Lock] = {} @@ -64,28 +65,28 @@ def _line(text: object) -> str: async def _cached[T]( - source: str, org: str, read: Callable[[], Awaitable[T]], unread: T + source: str, key: str, read: Callable[[], Awaitable[T]], unread: T ) -> tuple[T, bool]: """(`read()`'s answer, or the one it gave within `_SOURCE_TTL_S`, or `unread` when it failed; 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) + entry = (source, key) + lock = _locks.get(entry) if lock is None: if len(_locks) >= _CACHE_MAX: _locks.clear() _cache.clear() - lock = _locks[key] = asyncio.Lock() + lock = _locks[entry] = asyncio.Lock() async with lock: - hit = _cache.get(key) + hit = _cache.get(entry) if hit is None or time.monotonic() - hit[0] >= _SOURCE_TTL_S: try: async with asyncio.timeout(settings.readiness_check_timeout_s): answer, failure = await read(), "" except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer answer, failure = unread, caller_text(e) - hit = _cache[key] = (time.monotonic(), answer, failure) + hit = _cache[entry] = (time.monotonic(), answer, failure) if hit[2]: degradations.partial("ops.incidents", f"{source}_unread", hit[2]) return hit[1], not hit[2] @@ -225,14 +226,11 @@ async def _requests(org: str, minutes: int) -> list[OpsIncident]: return out -async def _sources(org: str) -> OpsIncidentSources: - """The org's failing document sources the caller may read: how many, and the latest - few. A collection shows only to whom its grants reach, org admins included; a - platform admin reads every one.""" - from server.auth.context import collection_clause +async def _sources(org: str, scope: str, params: dict[str, Any]) -> OpsIncidentSources: + """The org's failing document sources in the namespaces and collections `scope` + admits: how many, and the latest few.""" from server.knowledge.app.sources import failing_sources - scope, params = await collection_clause(org) failing, sample = await failing_sources( org, sample=MAX_SOURCE_SAMPLE, scope=scope, scope_params=params ) @@ -243,13 +241,33 @@ async def _sources(org: str) -> OpsIncidentSources: ) -def _caller(org: str) -> str: - """The cache key of the org's sources for the current caller: the collections it - reads are its own, so no caller is served another's read.""" - from server.auth.context import current_auth +def _sources_unread(kind: str) -> OpsIncidentSources: + degradations.partial("ops.incidents", "sources_unread", kind) + return OpsIncidentSources(read="unread") - auth = current_auth() - return f"{org}\n{auth.subject}" if auth is not None else org + +async def _sources_read(org: str) -> OpsIncidentSources: + """The org's failing sources the caller may read. A collection shows only to whom its + grants reach, org admins included; a platform admin reads every one. The reach is + resolved first and keys the cache, so callers that read the same collections share + a read and none is served a wider one. A reach that could not be read is `unread`: + `sharing.readable` answers an unread tree or grant as no shared collection, which + would be a narrower count passed off as the whole.""" + from server.auth import fail_closed + from server.auth.context import collection_clause + + fail_closed.reset() + try: + scope, params = await collection_clause(org) + except Exception as e: # noqa: BLE001 — an unread reach leaves the sources unread; the rest answers + return _sources_unread(error_kind(e)) + if fail_closed.unreadable(): + return _sources_unread("CollectionsUnread") + reach = ",".join(params.get("col_readable", ["*"])) + sources, _ = await _cached( + "sources", f"{org}\n{reach}", lambda: _sources(org, scope, params), _UNREAD_SOURCES + ) + return sources async def _org_reads( @@ -261,9 +279,9 @@ async def _org_reads( reach: OrgRead = await _reads_org_whole(org) if org and org != "*" else "not_permitted" if reach != "read": return [], reach, OpsIncidentSources(read=reach) - (calls, answered), (sources, _) = await asyncio.gather( + (calls, answered), sources = await asyncio.gather( _cached("requests", org, lambda: _requests(org, minutes), list[OpsIncident]()), - _cached("sources", _caller(org), lambda: _sources(org), OpsIncidentSources(read="unread")), + _sources_read(org), ) return calls, "read" if answered else "unread", sources diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index d297df1ea78..f6cfc8aa157 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -196,6 +196,11 @@ class SourcesFailed(RuntimeError): source's failure is its own, in its sync state, never the worker's.""" +# A namespace source's turn status that is never the worker's failure: `ok`, and a +# refused credential, which only its org can rotate, however many orgs hold one. +_OWN_FAILURES = frozenset({"ok", "credential_invalid"}) + + @dataclass class SourceTally: """Per org, the sources one leg of a pass handled and those it failed, and the kinds @@ -218,10 +223,10 @@ def note(self, leg: str, orgs: set[str]) -> None: """One failure for the pass when most of the orgs it serves (`orgs`, with those the leg ran for) had most of their sources in the leg fail; an org the leg had nothing to do for has not failed. That is an outage of what every source relies - on (the store, the model), or a deployment with one org. One org's failures, - however many of the sources are its own, are its own (a source's sync state, and - for a state write that failed the server's log), and no failure of the worker - every org shares.""" + on (the store, a source's provider), or a deployment with one org. One org's + failures, however many of the sources are its own, are its own (a source's sync + state, and for a state write that failed the server's log), and no failure of + the worker every org shares.""" serving = orgs | set(self.ran) failing = sum(self.failed[org] * 2 > n for org, n in self.ran.items()) if failing * 2 > len(serving): @@ -556,6 +561,7 @@ async def _sync_turn( log.warning("knowledge_source_sync: %s failed: %s", _cursor_of(src), e) return None if mirror_synced(src): + # Every cause alike: a mirror's turn leaves no more than its one code. result.turns.add(src, "" if turn.status == "ok" else "SYNC_FAILED") if turn.status != "ok": _mirror_failure(src, result) @@ -571,7 +577,7 @@ async def _sync_turn( and src.kind == "recording" and src.config.get("provider") == "meet" ) - result.turns.add(src, turn.status if failed else "") + result.turns.add(src, turn.status if failed and turn.status not in _OWN_FAILURES else "") if failed: result.failed += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) @@ -1828,7 +1834,9 @@ def may_write() -> bool: log.warning("knowledge_source_sync: mining %s failed: %s", _cursor_of(src), e) raised = type(e).__name__ # One document that fails is its own, in the source's `extract_error`; most of the - # source's documents failing is the source's mining failing. + # source's documents failing is the source's mining failing. A model outage while a + # pass mines only a few changed documents is therefore not noted here: each source's + # `extract_error` shows it. result.mining.add(src, raised or (mined.error if mined.failures * 2 > len(docs) else "")) result.extracted += mined.extracted result.flagged_pinned += mined.flagged diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index 3caa8eb0ae3..98147d0961a 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -3438,7 +3438,9 @@ async def _turn(source: Any, state: Any, run: Any) -> source_sync.TurnResult: run = source_sync.Pass(source_sync._budget(), left=5) turn = asyncio.run(source_sync._sync_turn(src, world.states[src.name], run, result)) assert turn is not None and turn.status == status and not turn.complete - assert result.failed == len(result.errors) == result.turns.failed[ORG] == expected_failures + assert result.failed == len(result.errors) == expected_failures + # A refused credential is its org's to rotate: never toward the worker's failure. + assert result.turns.failed[ORG] == (0 if status == "credential_invalid" else expected_failures) assert result.turns.ran == {ORG: 1} and failures == [] # the pass notes its tally, not the turn assert (result.changed, result.removed, result.unconverted, result.skipped) == (0, 0, 0, 0) assert world.states[src.name]["state_value"] == "old-stamp" diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index de12d959dc1..1150ffaf318 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -33,17 +33,17 @@ def _noted(leg: str, kind: str, orgs: str = "1 of 1") -> list[tuple[str, str, st return [(source_sync.WORKER, "SourcesFailed", msg)] -_KIND = {"status": "credential_invalid", "raises": "ConnectionError"} +_KIND = {"status": "failed", "raises": "ConnectionError"} def _turns(monkeypatch: pytest.MonkeyPatch, failing: set[str], *, how: str = "status") -> None: - """Each source's turn: those in `failing` end `credential_invalid` (`status`), or their - state write raises (`raises`); the others end ok.""" + """Each source's turn: those in `failing` end `failed` (`status`), or their state write + raises (`raises`); the others end ok.""" async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: out = source_sync.TurnResult() if src.name in failing and how == "status": - out.fail("credential_invalid", "the stored credential no longer opens; rotate it") + out.fail("failed", "ConnectionError") return out monkeypatch.setattr(source_sync, "_turn_of", lambda src: turn) @@ -82,7 +82,7 @@ def test_one_failing_source_of_three_notes_no_pass_failure( assert result.errors[0].startswith(f"{ORG}/{NS}/b: ") if how == "status": # The failure is the source's own, in the sync state its readers see. - assert _detail(world, "b")["status"] == "credential_invalid" + assert _detail(world, "b")["status"] == "failed" assert _detail(world, "a")["status"] == "ok" @@ -108,7 +108,7 @@ def test_the_only_source_failing_notes_one_pass_failure( _, ctx = asyncio.run(_supervised()) - assert ctx.failures == _noted("sync", "credential_invalid") + assert ctx.failures == _noted("sync", "failed") @pytest.mark.parametrize("other_fails", [False, True], ids=["other-ok", "other-fails"]) @@ -127,7 +127,7 @@ def test_one_orgs_failing_sources_are_not_the_others_failure( result, ctx = asyncio.run(_supervised()) assert result.failed == (3 if other_fails else 2) - assert ctx.failures == (_noted("sync", "credential_invalid", "2 of 2") if other_fails else []) + assert ctx.failures == (_noted("sync", "failed", "2 of 2") if other_fails else []) def test_an_org_the_pass_does_not_sync_does_not_dilute_an_outage( @@ -142,7 +142,32 @@ def test_an_org_the_pass_does_not_sync_does_not_dilute_an_outage( result, ctx = asyncio.run(_supervised()) assert result.failed == 2 - assert ctx.failures == _noted("sync", "credential_invalid") + assert ctx.failures == _noted("sync", "failed") + + +def test_refused_credentials_in_most_orgs_are_no_failure_of_the_worker( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """A refused credential is its org's to rotate, however many orgs hold one (dormant + accounts whose credentials lapsed): it never counts toward the worker's failure.""" + world.sources = [ + _source("a"), + dataclasses.replace(_source("b"), org="o2"), + dataclasses.replace(_source("c"), org="o3"), + ] + + async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: + out = source_sync.TurnResult() + if src.name in "ab": + out.fail("credential_invalid", "the stored credential no longer opens; rotate it") + return out + + monkeypatch.setattr(source_sync, "_turn_of", lambda src: turn) + + result, ctx = asyncio.run(_supervised()) + + assert result.failed == 2 and _detail(world, "a")["status"] == "credential_invalid" + assert ctx.failures == [] def test_a_pass_cut_inside_one_orgs_failing_sources_is_not_the_others_failure( @@ -200,7 +225,7 @@ async def busy(name: str, **kw: Any) -> Any: _, ctx = asyncio.run(_supervised()) - assert ctx.failures == _noted("sync", "credential_invalid") + assert ctx.failures == _noted("sync", "failed") def test_mirrored_failures_count_toward_the_pass_with_their_one_code( diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 9ad6b56dcb9..c57661afd08 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -11,6 +11,7 @@ import pytest +from server.auth import sharing from server.auth.context import set_current_auth from server.auth.jwt import AuthInfo, TokenError from server.core import readiness @@ -42,6 +43,9 @@ def _token( ) +# The collections a caller reads, before the fixture stands in for it. +_READABLE = sharing.readable + # reads the org whole, as the org-wide rollups' rule has it (`reads_every_namespace`) ORG_WIDE = _token(roles=(Role.ORG_ADMIN,)) @@ -450,21 +454,30 @@ async def test_a_collection_the_caller_holds_no_grant_for_is_left_out(monkeypatc ch = _ch(monkeypatch, sources=_FAILING) await _incidents() - await _incidents(auth=_token(roles=(Role.PLATFORM_ADMIN,), subject="root")) + # The same subject as a platform admin reaches every collection: its own read. + await _incidents(auth=_token(roles=(Role.PLATFORM_ADMIN,))) + # Another org admin with the same reach shares the first read. await _incidents(auth=_token(roles=(Role.ORG_ADMIN,), subject="other-admin")) - admin, platform, other = ch.statements("loom.code_index_state") + admin, platform = ch.statements("loom.code_index_state") assert (admin.params["col_prefix"], admin.params["col_readable"]) == ("col-", ["col-board"]) assert "startsWith(namespace, {col_prefix:String})" in admin.sql assert "col_prefix" not in platform.params and "col_prefix" not in platform.sql - assert other.params["col_readable"] == ["col-board"] @pytest.mark.asyncio -async def test_an_unread_collection_reach_answers_unread(monkeypatch) -> None: - monkeypatch.setattr( - "server.auth.sharing.readable", AsyncMock(side_effect=RuntimeError("grants down")) - ) +@pytest.mark.parametrize( + "down", + [RuntimeError("tree unread"), BackendUnavailableError("tree unread")], + ids=["unread", "backend"], +) +async def test_an_unread_collection_reach_answers_unread(monkeypatch, down) -> None: + """The collection tree or a grant cannot be read: `sharing.readable` answers no shared + collection, or the outage, and the sources are unread rather than a narrower count.""" + from server.auth import sharing + + monkeypatch.setattr(sharing, "readable", _READABLE) + monkeypatch.setattr(sharing, "tree", AsyncMock(side_effect=down)) ch = _ch(monkeypatch, sources=_FAILING) out = await _incidents() From b0a7285d4927d1cebc18b793d5b24eec5eaea733 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 16:37:05 +0530 Subject: [PATCH 07/41] Mining counts the documents a pass tried, not a source's documents The mining leg judged a source by all of its live documents, so a source of more documents than a pass tries never counted as failed, even when every document tried failed. Mining now tallies the documents tried per org, counts only the orgs it mined for, and needs at least two tries before an org counts as failing. A source that raised, or whose read or write failed, counts as one failed try at least. The read field's comment of ops.incidents sources names its other unread causes: unread collection grants and a refused tenancy check. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/document-sources.md | 8 +-- docs/features/knowledge.md | 16 +++-- docs/operations/monitoring.md | 5 +- server/insights/api/models_ops.py | 3 +- server/knowledge/app/source_sync.py | 70 +++++++++--------- .../test_knowledge_source_sync_failures.py | 71 ++++++++++++++++++- 6 files changed, 122 insertions(+), 51 deletions(-) diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 0b166cdae25..0b11cc3087c 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -635,10 +635,10 @@ the public fallback. No reranking provider receives the provisional pools. source's status, a worker's pass notes, logs, spans and metrics, the extractor service's logs and traces) carries codes only (exceptions 3 and 4 apart). Worker pass summaries exclude mirrored turns' completed-source counts, document - figures and cut flags. A failed mirrored turn contributes only `SYNC_FAILED`, for - every cause, and counts in the pass's per-org tally of failed turns like any other - source; returned turn details remain private. `ops.incidents`' `sources` counts no - mirrored source, since its state is its mirror's. Mirrored per-file failures emit + figures and cut flags. A failed mirrored turn contributes only `SYNC_FAILED` and + counts as failed in the pass's per-org tally of turns, for every cause, a refused + credential included; returned turn details remain private. `ops.incidents`' + `sources` counts no mirrored source, since its state is its mirror's. Mirrored per-file failures emit no log record, since the number of records would disclose a document figure. A sync turn enters its private diagnostic scope before taking its source lease or listing files; retirement enters it before reading its queue. That scope suppresses diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 4f1ca730471..218b291d79a 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -684,18 +684,20 @@ worker's failure streak only when most of the orgs the pass serves had most of t sources in that leg fail (`knowledge_source_sync: sync failed for most sources in 3 of 4 orgs (most often failed)`); an org the leg had nothing to do for, or that the pass bound left for the next pass, has not failed. That is an outage of what every source relies -on, such as the store or a source's provider, or a deployment with one org. One org's +on, such as the store, a source's provider or the model, or a deployment with one org. One org's failing sources, however many of the deployment's sources are its own, therefore make neither the worker nor `ops.incidents` degraded for the other orgs. A source another copy holds counts neither way, and a refused credential (`credential_invalid`) of a namespace's source never counts: it is its org's to rotate, however many orgs hold one. -The mining leg counts a source as failed when most of its documents failed, so one -document that fails to mine is that document's, in `extract_error`. A model outage while -a pass mines only a few changed documents is therefore not counted toward the streak; -each source's `extract_error` shows it. A pass that runs any mirrored turn is private, -and the worker's streak stays as it was: on a deployment with an active mirrored source, -no leg's failure reaches the streak, and the pass's status row reads `SYNC_FAILED`. +The mining leg counts instead the documents the pass tried, and only the orgs it mined +for: an org has failed when most of the documents tried for it failed, from at least +two. One +document that fails to mine, the only one a pass tries included, is that document's, in +its source's `extract_error`. A pass that runs any mirrored turn is private, and the +worker's streak stays as it was: while auth is on, on a deployment with an active +mirrored source, no leg's failure reaches the streak, and the pass's status row reads +`SYNC_FAILED`. ### A recording source diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index d6c0fcc08c7..9e94fdf10bb 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -186,8 +186,9 @@ failing document source is never an incident and never by itself makes `status` `degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own health. The `knowledge_source_sync` worker becomes a `worker` incident only after 3 passes in a row in which one of its legs (the sync turns, the mining, the retirement of -removed sources) failed for most of the sources of most orgs: an outage of what every -source relies on, such as the store or a source's provider, or a deployment with one org. +removed sources) failed for most of the sources, or of the documents mined, of most +orgs: an outage of what every source relies on, such as the store, a source's provider +or the model, or a deployment with one org. A refused credential never counts toward it, and neither does a pass that runs a mirrored source's turn, which leaves the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 2fc74e8b4f3..024d44e949d 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -226,7 +226,8 @@ class OpsIncidentSources(BaseModel): sample: list[OpsFailingSource] = Field(default_factory=list) # Whether they were read, as for `requests`: `read`; `not_permitted` when the call # names no single org or the caller does not read the org whole; `unread` when they, - # the restricted set or a restricted namespace's grant could not be read. + # the restricted set, a restricted namespace's grant or the caller's collection + # grants could not be read, or a platform admin's tenancy check refused. read: OrgRead = "unread" diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index f6cfc8aa157..d32b18d1930 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -196,42 +196,41 @@ class SourcesFailed(RuntimeError): source's failure is its own, in its sync state, never the worker's.""" -# A namespace source's turn status that is never the worker's failure: `ok`, and a -# refused credential, which only its org can rotate, however many orgs hold one. -_OWN_FAILURES = frozenset({"ok", "credential_invalid"}) - - @dataclass class SourceTally: - """Per org, the sources one leg of a pass handled and those it failed, and the kinds - of their failures.""" + """Per org, what one leg of a pass handled and what of it failed (sources for the + sync and retirement legs, documents tried for mining), and the kinds of the + failures.""" ran: Counter[str] = field(default_factory=Counter) failed: Counter[str] = field(default_factory=Counter) kinds: Counter[str] = field(default_factory=Counter) - def add(self, src: KnowledgeSource, failure: str = "") -> None: - """Count a source the leg handled; `failure` is the kind of its failure (an + def add( + self, src: KnowledgeSource, failure: str = "", *, ran: int = 1, failed: int = 0 + ) -> None: + """Count `ran` units of a source the leg handled, `failed` of them failing (all, + when `failure` names a kind and `failed` is 0). `failure` is the kind (an exception's class, a turn's status, `SYNC_FAILED` for a mirrored source), never its text.""" - self.ran[src.org] += 1 + self.ran[src.org] += ran if failure: - self.failed[src.org] += 1 + self.failed[src.org] += failed or ran self.kinds[failure] += 1 - def note(self, leg: str, orgs: set[str]) -> None: + def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = 1) -> None: """One failure for the pass when most of the orgs it serves (`orgs`, with those - the leg ran for) had most of their sources in the leg fail; an org the leg had - nothing to do for has not failed. That is an outage of what every source relies - on (the store, a source's provider), or a deployment with one org. One org's - failures, however many of the sources are its own, are its own (a source's sync - state, and for a state write that failed the server's log), and no failure of - the worker every org shares.""" + the leg ran for) had most of their units in the leg fail, from at least `least` + units; an org the leg had nothing to do for has not failed. That is an outage of + what every source relies on (the store, a source's provider, the model), or a + deployment with one org. One org's failures, however many of the sources are its + own, are its own (a source's sync state, and for a state write that failed the + server's log), and no failure of the worker every org shares.""" serving = orgs | set(self.ran) - failing = sum(self.failed[org] * 2 > n for org, n in self.ran.items()) + failing = sum(n >= least and self.failed[org] * 2 > n for org, n in self.ran.items()) if failing * 2 > len(serving): kind = self.kinds.most_common(1)[0][0] - msg = f"{leg} failed for most sources in {failing} of {len(serving)} orgs" + msg = f"{leg} failed for most {unit} in {failing} of {len(serving)} orgs" pass_context.note_failure(SourcesFailed(f"{msg} (most often {kind})"), WORKER) @@ -445,7 +444,9 @@ async def run_sync( break result.turns.note("sync", orgs) await _extract_pending(order, run, result) - result.mining.note("mining", orgs) + # Mining follows changes: an org with nothing to mine tells nothing of the model, so + # only the orgs it mined for count, from two documents tried. + result.mining.note("mining", set(), unit="documents", least=2) if not order and not mirrored and not result.retired: pass_context.mark_idle() return result @@ -577,7 +578,10 @@ async def _sync_turn( and src.kind == "recording" and src.config.get("provider") == "meet" ) - result.turns.add(src, turn.status if failed and turn.status not in _OWN_FAILURES else "") + # A refused credential is never the worker's failure: only its org can rotate it, + # however many orgs hold one. + own = turn.status == "credential_invalid" + result.turns.add(src, turn.status if failed and not own else "") if failed: result.failed += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) @@ -1666,7 +1670,7 @@ class _Mined: # Documents settled at a revision: mined, or given up on. settled: dict[str, str] = field(default_factory=dict) # A document's extraction was tried and came back (mined or failed), not held. - tried: bool = False + tries: int = 0 extracted: int = 0 flagged: int = 0 unextracted: int = 0 @@ -1709,8 +1713,6 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass # A source with nothing to mine and no stale count to clear needs no write. if todo or detail.get("pending_extract"): queues.append((src, docs, todo)) - else: - result.mining.add(src) if not queues: return stop = "" @@ -1739,8 +1741,6 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) result.mining.add(src, type(e).__name__) - continue - result.mining.add(src) continue stop = await _extract_source(src, docs, run, result) @@ -1833,11 +1833,11 @@ def may_write() -> bool: result.failed += 1 log.warning("knowledge_source_sync: mining %s failed: %s", _cursor_of(src), e) raised = type(e).__name__ - # One document that fails is its own, in the source's `extract_error`; most of the - # source's documents failing is the source's mining failing. A model outage while a - # pass mines only a few changed documents is therefore not noted here: each source's - # `extract_error` shows it. - result.mining.add(src, raised or (mined.error if mined.failures * 2 > len(docs) else "")) + # The documents it tried, and those that failed; a raise fails the source's whole try. + if raised: + result.mining.add(src, raised, ran=max(mined.tries, 1)) + elif mined.tries: + result.mining.add(src, mined.error, ran=mined.tries, failed=mined.failures) result.extracted += mined.extracted result.flagged_pinned += mined.flagged result.unextracted += mined.unextracted @@ -1897,7 +1897,7 @@ async def _extract_one( report = await asyncio.create_task(_mine(src, uri, _read_deadline(run), may_write)) except Exception as e: # noqa: BLE001 — one document's failure must not stop the others log.warning("knowledge_source_sync: mining %s failed: %s", uri, e) - mined.tried = True + mined.tries += 1 _extract_failed(mined, uri, revision, f"failed:{type(e).__name__}") return True if report.held is not None or report.write_stopped: @@ -1913,7 +1913,7 @@ async def _extract_one( elif report.held is not None: mined.deferred = mined.stop = f"held:{report.held.code}" return False - mined.tried = True + mined.tries += 1 if report.out_of_time and read_s >= _full_read_s(): # It had all the read time a pass gives and did not finish: no pass will do. _give_up_mining(mined, uri, revision, "too_large_for_pass") @@ -2024,7 +2024,7 @@ async def _write_mined( known = {u: r for u, r in {**_mined_of(detail), **mined.settled}.items() if u in live} detail["mined"] = known detail["extract_waits"] = {u: w for u, w in mined.waits.items() if u in live} - if mined.tried: + if mined.tries: detail.update( last_extracted_at=_now_iso(), extracted=mined.extracted, diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 1150ffaf318..88d7edf5237 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -29,7 +29,8 @@ def _sources(world: _World, *names: str) -> None: def _noted(leg: str, kind: str, orgs: str = "1 of 1") -> list[tuple[str, str, str]]: - msg = f"{leg} failed for most sources in {orgs} orgs (most often {kind})" + unit = "documents" if leg == "mining" else "sources" + msg = f"{leg} failed for most {unit} in {orgs} orgs (most often {kind})" return [(source_sync.WORKER, "SourcesFailed", msg)] @@ -158,7 +159,7 @@ def test_refused_credentials_in_most_orgs_are_no_failure_of_the_worker( async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: out = source_sync.TurnResult() - if src.name in "ab": + if src.name in {"a", "b"}: out.fail("credential_invalid", "the stored credential no longer opens; rotate it") return out @@ -329,6 +330,72 @@ async def revisions(org: str, ns: str, tag: str, **kw: Any) -> list[dict[str, st assert ctx.failures == (_noted("mining", "not_run") if failing == "123" else []) +def _documents(monkeypatch: pytest.MonkeyPatch, count: int, org: str = ORG) -> None: + """Each source of `org` holds `count` unmined documents; another org's none.""" + + async def revisions(at: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + if at != org: + return [] + return [ + {"source_uri": f"https://docs.example.com/{tag}/{i}", "source_revision": "r1"} + for i in range(count) + ] + + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + + +def test_a_model_outage_on_a_large_source_is_the_workers_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """A source of more documents than a pass mines: every document it tried failing is + its mining failing, however many it has left.""" + from server.memory.app.decision_extract import ExtractReport + + _sources(world, "a") + _turns(monkeypatch, set()) + _documents(monkeypatch, 100) + world.mine_answer = lambda uri: ExtractReport(uri, False, error="model down") + + _, ctx = asyncio.run(_supervised()) + + assert 1 < len(world.mined) < 100 + assert ctx.failures == _noted("mining", "not_run") + + +def test_an_org_with_nothing_to_mine_does_not_dilute_a_model_outage( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.memory.app.decision_extract import ExtractReport + + world.sources = [_source("a"), dataclasses.replace(_source("c"), org="other")] + _turns(monkeypatch, set()) + _documents(monkeypatch, 3) + world.mine_answer = lambda uri: ExtractReport(uri, False, error="model down") + + _, ctx = asyncio.run(_supervised()) + + assert len(world.mined) == 3 + assert ctx.failures == _noted("mining", "not_run") + + +def test_the_only_document_mined_in_a_pass_failing_is_not_the_workers_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """One changed document of a deployment's only source fails to mine: one try tells + nothing of the model, so it stays the document's own.""" + from server.memory.app.decision_extract import ExtractReport + + _sources(world, "a") + _turns(monkeypatch, set()) + _documents(monkeypatch, 1) + world.mine_answer = lambda uri: ExtractReport(uri, False, error="no chunks") + + result, ctx = asyncio.run(_supervised()) + + assert len(world.mined) == 1 and result.failed == 1 + assert ctx.failures == [] + + @pytest.mark.parametrize("failing", ["b", "abc"]) def test_a_removed_sources_failed_retirement_is_its_own_unless_most_fail( world: _World, monkeypatch: pytest.MonkeyPatch, failing: str From 8be0c265308f27dd0c09b09ec76481b572e66cfe Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 16:43:38 +0530 Subject: [PATCH 08/41] Mining counts against every org the pass serves, as the other legs do Counting the mining leg only against the orgs that mined let one org with changed documents be the majority whenever it alone mined, so its failing documents built the worker's streak for every org. An org with nothing to mine now counts as not failed, as in the sync and retirement legs; the cost, a model outage while fewer than half the orgs mine, is in the docs. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 18 ++++++++++-------- server/knowledge/app/source_sync.py | 5 ++--- .../test_knowledge_source_sync_failures.py | 12 +++++++----- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 218b291d79a..ec01c4396d2 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -690,14 +690,16 @@ neither the worker nor `ops.incidents` degraded for the other orgs. A source ano copy holds counts neither way, and a refused credential (`credential_invalid`) of a namespace's source never counts: it is its org's to rotate, however many orgs hold one. -The mining leg counts instead the documents the pass tried, and only the orgs it mined -for: an org has failed when most of the documents tried for it failed, from at least -two. One -document that fails to mine, the only one a pass tries included, is that document's, in -its source's `extract_error`. A pass that runs any mirrored turn is private, and the -worker's streak stays as it was: while auth is on, on a deployment with an active -mirrored source, no leg's failure reaches the streak, and the pass's status row reads -`SYNC_FAILED`. +The mining leg counts the documents the pass tried instead of sources: an org has failed +when most of the documents tried for it failed, from at least two. One document that +fails to mine, the only one a pass tries included, is that document's, in its source's +`extract_error`. Since an org with nothing to mine has not failed, a model outage while +fewer than half the orgs have changed documents is not counted toward the streak; each +source's `extract_error` shows it, and so does the `provider` incident of +[`ops.incidents`](../operations/monitoring.md#opsincidents) on the process that made the +calls. A pass that runs any mirrored turn is private, and the worker's streak stays as it +was: while auth is on, on a deployment with an active mirrored source, no leg's failure +reaches the streak, and the pass's status row reads `SYNC_FAILED`. ### A recording source diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index d32b18d1930..11705e441fd 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -444,9 +444,8 @@ async def run_sync( break result.turns.note("sync", orgs) await _extract_pending(order, run, result) - # Mining follows changes: an org with nothing to mine tells nothing of the model, so - # only the orgs it mined for count, from two documents tried. - result.mining.note("mining", set(), unit="documents", least=2) + # One document tried tells nothing of the model: an org counts from two. + result.mining.note("mining", orgs, unit="documents", least=2) if not order and not mirrored and not result.retired: pass_context.mark_idle() return result diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 88d7edf5237..70bacca5bbc 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -362,20 +362,22 @@ def test_a_model_outage_on_a_large_source_is_the_workers_failure( assert ctx.failures == _noted("mining", "not_run") -def test_an_org_with_nothing_to_mine_does_not_dilute_a_model_outage( +def test_one_orgs_failing_documents_are_not_the_others_failure( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: + """The only org with documents to mine has all of them fail: an org with nothing to + mine has not failed, so one org never makes the worker fail for the other.""" from server.memory.app.decision_extract import ExtractReport world.sources = [_source("a"), dataclasses.replace(_source("c"), org="other")] _turns(monkeypatch, set()) _documents(monkeypatch, 3) - world.mine_answer = lambda uri: ExtractReport(uri, False, error="model down") + world.mine_answer = lambda uri: ExtractReport(uri, False, error="no chunks") - _, ctx = asyncio.run(_supervised()) + result, ctx = asyncio.run(_supervised()) - assert len(world.mined) == 3 - assert ctx.failures == _noted("mining", "not_run") + assert len(world.mined) == 3 and result.failed == 3 + assert ctx.failures == [] def test_the_only_document_mined_in_a_pass_failing_is_not_the_workers_failure( From 03452ef50c476bce535191aafeb3ddc1c33cb7ef Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 17:18:59 +0530 Subject: [PATCH 09/41] A source sync note names the kind of the orgs that failed The note's "most often" kind was counted over every org, so a healthy org's few failures could name the outage of the others; it is now the most common kind among the orgs that failed. A mining read, write or raise fails a source whole, and its org counts however few documents it has, so a store failure on orgs of one source each is noted. ops.incidents cuts the caller's collection reach at the readiness bound and answers the sources unread past it. The integration test calls with an org admin token, and under auth checks that a member reads none and that an org admin's ungranted collection is left out; CI runs it in the auth-on gates. The docs name a pass that fails outright as a worker failure too, and quote the status row's partial_error as it is. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- .github/workflows/ci.yml | 1 + docs/features/knowledge.md | 15 ++--- docs/operations/monitoring.md | 26 ++++---- sdk/go/wire/models.gen.go | 2 +- server/insights/api/models_ops.py | 4 +- server/insights/app/incidents.py | 17 ++--- server/knowledge/app/source_sync.py | 63 +++++++++++++------ tests/integration/test_ops_incidents.py | 54 +++++++++++++--- .../test_knowledge_source_sync_failures.py | 35 +++++++++++ tests/unit/test_ops_incidents.py | 22 +++++++ 10 files changed, 183 insertions(+), 56 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cf25ce1961d..4a500c95375 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1038,6 +1038,7 @@ jobs: tests/integration/test_projection_failures_restricted.py tests/integration/test_mirror_checked_search_http.py tests/integration/test_mirror_checked_list_http.py + tests/integration/test_ops_incidents.py # The statement corpus: every builder's shapes through # EXPLAIN QUERY TREE on the migrated service, and shapes.txt in step # with the builders. ~10 s; a rejection here is a statement that would diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index ec01c4396d2..f78fc3931a0 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -681,18 +681,19 @@ the org's failing sources in [`ops.incidents`](../operations/monitoring.md#opsin `sources`. Each leg of the worker's pass (the sync turns, mirrored ones included, the mining and the retirement of removed sources) counts the pass as failed toward the worker's failure streak only when most of the orgs the pass serves had most of their -sources in that leg fail (`knowledge_source_sync: sync failed for most sources in 3 of 4 -orgs (most often failed)`); an org the leg had nothing to do for, or that the pass bound -left for the next pass, has not failed. That is an outage of what every source relies -on, such as the store, a source's provider or the model, or a deployment with one org. One org's -failing sources, however many of the deployment's sources are its own, therefore make +sources in that leg fail; the pass's status row then carries, as its `partial_error`, +`sync failed for most sources in 3 of 4 orgs (most often failed)`. An org the leg had +nothing to do for, or that the pass bound left for the next pass, has not failed. That +is an outage of what every source relies on, such as the store, a source's provider or +the model, or a deployment with one org. One org's failing sources, however many of the deployment's sources are its own, therefore make neither the worker nor `ops.incidents` degraded for the other orgs. A source another copy holds counts neither way, and a refused credential (`credential_invalid`) of a namespace's source never counts: it is its org's to rotate, however many orgs hold one. The mining leg counts the documents the pass tried instead of sources: an org has failed -when most of the documents tried for it failed, from at least two. One document that -fails to mine, the only one a pass tries included, is that document's, in its source's +when most of the documents tried for it failed, from at least two, or from one source +whose documents could not be read, whose record could not be written or whose mining +raised. One document that fails to mine, the only one a pass tries included, is that document's, in its source's `extract_error`. Since an org with nothing to mine has not failed, a model outage while fewer than half the orgs have changed documents is not counted toward the streak; each source's `extract_error` shows it, and so does the `provider` incident of diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 9e94fdf10bb..81baece33fe 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -164,10 +164,13 @@ token (never an org admin) and a `*` token that names no org read none. The othe 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 -read runs at most once every 5 seconds per process, however many clients poll during an -outage, and is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A read that failed is named in the -response's `degraded` while its failure is cached, and the other reads still answer. +`/v1/health?include=workers` shows only the answering process's workers. Each of its +ClickHouse reads (the worker streaks, the request counts, the failing sources) runs at +most once every 5 seconds per process, however many clients poll during an outage, and is +cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A read that failed is named in the response's +`degraded` while its failure is cached, and the other reads still answer. The caller's +collection reach, which the failing sources need, comes from the grant cache every call +uses and is cut at the same bound. 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 @@ -184,13 +187,14 @@ same words. It leaves out the collections the caller holds no grant for, since a admin reaches a collection only through a grant (a platform admin reads every one). A failing document source is never an incident and never by itself makes `status` `degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own -health. The `knowledge_source_sync` worker becomes a `worker` incident only after 3 -passes in a row in which one of its legs (the sync turns, the mining, the retirement of -removed sources) failed for most of the sources, or of the documents mined, of most -orgs: an outage of what every source relies on, such as the store, a source's provider -or the model, or a deployment with one org. -A refused credential never counts toward it, and neither does a pass that runs a -mirrored source's turn, which leaves the streak as it was (see +health. The `knowledge_source_sync` worker becomes a `worker` incident after 3 failed +passes in a row, like any worker. A pass that runs fails when it fails outright (its +source list or registry unread, or past its deadline), or when one of its legs (the sync +turns, the mining, the retirement of removed sources) failed for most of the sources, or +of the documents mined, of most orgs: an outage of what every source relies on, such as +the store, a source's provider or the model, or a deployment with one org. A refused +credential never counts toward it, and neither does a pass that runs a mirrored source's +turn, which leaves the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). ### Smoke test diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index b9f98cdab47..75bb2d6d478 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: 5e6901763c808a1413363f5702b5d53add3639b7be898aa18ccb4af88bda883c +// Registry model schema SHA-256: 264dd83aa6e5667d5ffcd22fc4f799960525efe4391c667ce17e96a70285c3ed // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 024d44e949d..eea0bbcd945 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -217,8 +217,8 @@ class OpsIncidentSources(BaseModel): and the collections the caller reads. A source's failure is its own (its `sync.status` in `knowledge.source.list`), so it never makes `status` `degraded` by itself: a revoked credential is its org's to fix, not a Loom outage. The sync worker - becomes an incident only when most orgs' sources fail for 3 passes in a row (an - outage, or a deployment with one org).""" + becomes an incident after 3 failed passes in a row: a pass that fails outright, or + one in which most orgs' sources fail (an outage, or a deployment with one org).""" # Sources whose last turn failed; 0 unless `read` is `read`. failing: int = 0 diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index bd0eb336b5b..747a8d5354f 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -9,12 +9,14 @@ the answer `degraded`. Nothing names another org: a provider or worker incident carries an error's kind, never its text, and the request counts and the sources 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; a source names its namespace). Each ClickHouse read runs at most -once per `_SOURCE_TTL_S` per process (per org for the org's), so clients polling during -an outage do not add load. A read that does not answer 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. +no namespace or user; a source names its namespace). Each of its ClickHouse reads (the +worker streaks, the org's request counts and failing sources) runs at most once per +`_SOURCE_TTL_S` per process (per org, and for the sources per collection reach), so +clients polling during an outage do not add load. A read that does not answer 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. The caller's collection reach, which the sources +need, comes from the grant cache every call uses and is cut at the same bound. """ from __future__ import annotations @@ -258,7 +260,8 @@ async def _sources_read(org: str) -> OpsIncidentSources: fail_closed.reset() try: - scope, params = await collection_clause(org) + async with asyncio.timeout(settings.readiness_check_timeout_s): + scope, params = await collection_clause(org) except Exception as e: # noqa: BLE001 — an unread reach leaves the sources unread; the rest answers return _sources_unread(error_kind(e)) if fail_closed.unreadable(): diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 11705e441fd..fc7ec2fea90 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -90,7 +90,7 @@ import functools import logging import time -from collections import Counter +from collections import Counter, defaultdict from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta @@ -192,8 +192,14 @@ class SourceGone(Exception): class SourcesFailed(RuntimeError): - """A leg of the pass failed for most sources of most orgs: its one failure note. A - source's failure is its own, in its sync state, never the worker's.""" + """A leg of the pass failed for most of what it handled (sources, or for the mining + documents tried) in most orgs: its one failure note. A source's failure is its own, + in its sync state, never the worker's.""" + + +# An org's mining counts as failing from two documents tried: one tells nothing of the +# model. +_LEAST_TRIES = 2 @dataclass @@ -204,33 +210,50 @@ class SourceTally: ran: Counter[str] = field(default_factory=Counter) failed: Counter[str] = field(default_factory=Counter) - kinds: Counter[str] = field(default_factory=Counter) + kinds: defaultdict[str, Counter[str]] = field(default_factory=lambda: defaultdict(Counter)) + # Orgs with a source that failed whole: they count however few units they have. + whole: set[str] = field(default_factory=set) def add( - self, src: KnowledgeSource, failure: str = "", *, ran: int = 1, failed: int = 0 + self, + src: KnowledgeSource, + failure: str = "", + *, + ran: int = 1, + failed: int = 0, + whole: bool = False, ) -> None: """Count `ran` units of a source the leg handled, `failed` of them failing (all, when `failure` names a kind and `failed` is 0). `failure` is the kind (an exception's class, a turn's status, `SYNC_FAILED` for a mirrored source), never - its text.""" + its text; `whole` when the source failed whole (its mining's read, write or + raise), not unit by unit.""" self.ran[src.org] += ran + if whole: + self.whole.add(src.org) if failure: self.failed[src.org] += failed or ran - self.kinds[failure] += 1 + self.kinds[src.org][failure] += 1 def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = 1) -> None: """One failure for the pass when most of the orgs it serves (`orgs`, with those the leg ran for) had most of their units in the leg fail, from at least `least` - units; an org the leg had nothing to do for has not failed. That is an outage of + units or a source that failed whole; an org the leg had nothing to do for has not + failed. That is an outage of what every source relies on (the store, a source's provider, the model), or a deployment with one org. One org's failures, however many of the sources are its own, are its own (a source's sync state, and for a state write that failed the server's log), and no failure of the worker every org shares.""" serving = orgs | set(self.ran) - failing = sum(n >= least and self.failed[org] * 2 > n for org, n in self.ran.items()) - if failing * 2 > len(serving): - kind = self.kinds.most_common(1)[0][0] - msg = f"{leg} failed for most {unit} in {failing} of {len(serving)} orgs" + failing = [ + o + for o, n in self.ran.items() + if (n >= least or o in self.whole) and self.failed[o] * 2 > n + ] + if len(failing) * 2 > len(serving): + # The kind most common in the orgs that failed, not in those that did not. + kind = sum((self.kinds[o] for o in failing), Counter[str]()).most_common(1)[0][0] + msg = f"{leg} failed for most {unit} in {len(failing)} of {len(serving)} orgs" pass_context.note_failure(SourcesFailed(f"{msg} (most often {kind})"), WORKER) @@ -345,9 +368,10 @@ class PassResult: # Sources whose turn ended with a status other than ok or failed outright, plus one # for each document's failed extraction try. failed: int = 0 - # Per leg, the sources it handled and failed: sync turns that ran to an end (mirrored - # ones included), mining and retirement. Each notes at most one failure for the pass - # (`SourceTally.note`). Not in the pass summary (`workers.source_sync.outcome`). + # Per leg, what it handled and failed: sync turns that ran to an end (mirrored ones + # included), the documents mining tried, and retirement. Each notes at most one + # failure for the pass (`SourceTally.note`). Not in the pass summary + # (`workers.source_sync.outcome`). turns: SourceTally = field(default_factory=SourceTally) mining: SourceTally = field(default_factory=SourceTally) retiring: SourceTally = field(default_factory=SourceTally) @@ -444,8 +468,7 @@ async def run_sync( break result.turns.note("sync", orgs) await _extract_pending(order, run, result) - # One document tried tells nothing of the model: an org counts from two. - result.mining.note("mining", orgs, unit="documents", least=2) + result.mining.note("mining", orgs, unit="documents", least=_LEAST_TRIES) if not order and not mirrored and not result.retired: pass_context.mark_idle() return result @@ -1706,7 +1729,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass except Exception as e: # noqa: BLE001 — one source's failed read must not stop the others result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 - result.mining.add(src, type(e).__name__) + result.mining.add(src, type(e).__name__, whole=True) continue todo = _unmined(docs, detail) # A source with nothing to mine and no stale count to clear needs no write. @@ -1739,7 +1762,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) - result.mining.add(src, type(e).__name__) + result.mining.add(src, type(e).__name__, whole=True) continue stop = await _extract_source(src, docs, run, result) @@ -1834,7 +1857,7 @@ def may_write() -> bool: raised = type(e).__name__ # The documents it tried, and those that failed; a raise fails the source's whole try. if raised: - result.mining.add(src, raised, ran=max(mined.tries, 1)) + result.mining.add(src, raised, ran=max(mined.tries, 1), whole=True) elif mined.tries: result.mining.add(src, mined.error, ran=mined.tries, failed=mined.failures) result.extracted += mined.extracted diff --git a/tests/integration/test_ops_incidents.py b/tests/integration/test_ops_incidents.py index 480b941a44a..1018220d5d6 100644 --- a/tests/integration/test_ops_incidents.py +++ b/tests/integration/test_ops_incidents.py @@ -1,5 +1,6 @@ """ops.incidents over the transport against the real store: the caller org's failing -document sources, read from their sync states, and nothing of another org's.""" +document sources, read from their sync states, and nothing of another org's; under auth, +nothing for a member and no collection the caller holds no grant for.""" from __future__ import annotations @@ -7,24 +8,37 @@ from typing import Any import httpx +import pytest from tests.integration._resources import unique_org from tests.integration._sources import seed_source NS = "team-incidents" +BOARD = "col-board" -def _sync_state(ch: Any, org: str, name: str, status: str, synced_at: str) -> None: +def _sync_state(ch: Any, org: str, name: str, status: str, synced_at: str, ns: str = NS) -> None: detail = json.dumps({"status": status, "last_synced_at": synced_at}, sort_keys=True) ch.insert( "loom.code_index_state", - [[org, NS, f"knowledge_source:{name}", detail]], + [[org, ns, f"knowledge_source:{name}", detail]], column_names=["org", "namespace", "state_key", "detail"], ) +def _sources(url: str, org: str, token: str) -> dict[str, Any]: + resp = httpx.post( + f"{url}/v1/ops.incidents", + json={"org": org}, + headers={"Authorization": f"Bearer {token}"}, + timeout=30.0, + ) + assert resp.status_code == 200, resp.text + return resp.json()["sources"] + + def test_the_answer_lists_the_callers_failing_sources_only( - control_plane_url: str, ch_client: Any + control_plane_url: str, ch_client: Any, mint_test_token: Any ) -> None: org, other = unique_org("incidents"), unique_org("incidents") for each in (org, other): @@ -34,11 +48,9 @@ def test_the_answer_lists_the_callers_failing_sources_only( _sync_state(ch_client, org, "wiki", "rate_limited", "2026-01-03T00:00:00+00:00") _sync_state(ch_client, org, "notes", "ok", "2026-01-04T00:00:00+00:00") _sync_state(ch_client, other, "notes", "failed", "2026-01-05T00:00:00+00:00") + admin = mint_test_token(org=org, roles=["org_admin"], subject="incidents-admin") - resp = httpx.post(f"{control_plane_url}/v1/ops.incidents", json={"org": org}, timeout=30.0) - - assert resp.status_code == 200, resp.text - assert resp.json()["sources"] == { + assert _sources(control_plane_url, org, admin) == { "failing": 2, "sample": [ {"namespace": NS, "name": "wiki", "status": "rate_limited"}, @@ -46,3 +58,29 @@ def test_the_answer_lists_the_callers_failing_sources_only( ], "read": "read", } + + +def test_a_member_reads_none_and_an_ungranted_collection_is_left_out( + control_plane_url: str, ch_client: Any, mint_test_token: Any +) -> None: + if httpx.post(f"{control_plane_url}/v1/ops.incidents", json={}, timeout=30).status_code != 401: + pytest.skip("needs a server that enforces auth (LOOM_AUTH_REQUIRED=true)") + org = unique_org("incidents") + seed_source(ch_client, org, NS, "wiki") + seed_source(ch_client, org, BOARD, "minutes") + _sync_state(ch_client, org, "wiki", "failed", "2026-01-02T00:00:00+00:00") + _sync_state(ch_client, org, "minutes", "failed", "2026-01-03T00:00:00+00:00", ns=BOARD) + admin = mint_test_token(org=org, roles=["org_admin"], subject="incidents-admin") + member = mint_test_token(org=org, roles=["viewer"], subject="incidents-member") + + # An org admin reaches a collection only through a grant, and holds none on the board. + assert _sources(control_plane_url, org, admin) == { + "failing": 1, + "sample": [{"namespace": NS, "name": "wiki", "status": "failed"}], + "read": "read", + } + assert _sources(control_plane_url, org, member) == { + "failing": 0, + "sample": [], + "read": "not_permitted", + } diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 70bacca5bbc..a99d2030454 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -330,6 +330,24 @@ async def revisions(org: str, ns: str, tag: str, **kw: Any) -> list[dict[str, st assert ctx.failures == (_noted("mining", "not_run") if failing == "123" else []) +def test_a_store_read_failing_for_each_orgs_only_source_notes_once( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read that fails fails the source's mining whole, so it counts however few + documents an org has: two orgs of one source each are an outage of the store.""" + world.sources = [_source("a"), dataclasses.replace(_source("c"), org="other")] + _turns(monkeypatch, set()) + + async def down(*args: Any, **kw: Any) -> Any: + raise ConnectionError("store down") + + monkeypatch.setattr(source_sync.store, "source_revisions", down) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == _noted("mining", "ConnectionError", "2 of 2") + + def _documents(monkeypatch: pytest.MonkeyPatch, count: int, org: str = ORG) -> None: """Each source of `org` holds `count` unmined documents; another org's none.""" @@ -438,3 +456,20 @@ async def retire(src: KnowledgeSource, run: Any, result: Any) -> None: assert result.errors[:1] == [f"{ORG}/{NS}/gone: ConnectionError"] assert ctx.failures == [] + + +def test_a_note_names_the_kind_most_common_among_the_orgs_that_failed() -> None: + """One org's few rate-limited sources, not most of its own, name no outage of the + two orgs whose only source failed.""" + tally = source_sync.SourceTally() + for i in range(7): + tally.add(_source(f"a{i}"), "rate_limited" if i < 3 else "") + for org in ("b", "c"): + tally.add(dataclasses.replace(_source("x"), org=org), "failed") + ctx = pass_context.begin(source_sync.WORKER) + try: + tally.note("sync", set()) + finally: + pass_context.clear() + + assert ctx.failures == _noted("sync", "failed", "2 of 3") diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index c57661afd08..46b5b25aa9b 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -487,6 +487,28 @@ async def test_an_unread_collection_reach_answers_unread(monkeypatch, down) -> N assert [n.split(" (")[0] for n in degradations.current()] == ["ops.incidents: sources_unread"] +@pytest.mark.asyncio +async def test_a_collection_reach_slower_than_a_readiness_check_answers_unread( + monkeypatch, +) -> None: + """The reach is read before the sources, through the grant cache: it is cut at the + same bound as the reads, so a slow grant store never holds the answer.""" + + async def slow(auth: Any, org: str) -> list[str]: + await asyncio.sleep(5) + return [] + + monkeypatch.setattr(sharing, "readable", slow) + monkeypatch.setattr(settings, "readiness_check_timeout_s", 0.05) + ch = _ch(monkeypatch, sources=_FAILING) + + out = await _incidents() + + assert (out.sources.read, out.sources.failing, out.sources.sample) == ("unread", 0, []) + assert ch.statements("loom.code_index_state") == [] + assert [n.split(" (")[0] for n in degradations.current()] == ["ops.incidents: sources_unread"] + + @pytest.mark.asyncio async def test_a_member_reads_no_sources(monkeypatch) -> None: """A member's `*` token could hold no grant on a restricted namespace whose source From 31699142d960bf3070b9e5bf555945d788205dd1 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 17:45:49 +0530 Subject: [PATCH 10/41] A source sync note is the leg's, and the sources read takes its scope SourcesFailed is noted under the leg's name (sync, mining, retirement), as other workers name a leg, so the status row's partial_leg says which leg failed. SourceTally.add takes the failed count literally, all of the units only when none is given. failing_sources requires its collection scope, so no caller reads every collection by leaving it out; the analyzer corpus runs the statement under an org admin's collection clause too. The docs and the wire text say what the rule does when one org holds every synced source: its failures still build the streak, as on a deployment with one org. monitoring.md names how the reads are cached, the failing sources per org and collection reach. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/document-sources.md | 5 ++- docs/features/knowledge.md | 23 +++++++----- docs/operations/monitoring.md | 13 ++++--- docs/reference/operations/ops.md | 2 +- sdk/go/wire/models.gen.go | 2 +- server/insights/api/models_ops.py | 7 ++-- server/knowledge/app/source_sync.py | 37 ++++++++++--------- server/knowledge/app/sources.py | 2 +- server/knowledge/store/sources.py | 7 ++-- tests/analyzer/cases/workers.py | 12 +++++- tests/analyzer/shapes.txt | 1 + .../test_knowledge_source_sync_failures.py | 7 ++-- tests/unit/test_ops_incidents_sql.py | 15 ++++++-- 13 files changed, 81 insertions(+), 52 deletions(-) diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 0b11cc3087c..5c85027c4e8 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -638,8 +638,9 @@ the public fallback. No reranking provider receives the provisional pools. figures and cut flags. A failed mirrored turn contributes only `SYNC_FAILED` and counts as failed in the pass's per-org tally of turns, for every cause, a refused credential included; returned turn details remain private. `ops.incidents`' - `sources` counts no mirrored source, since its state is its mirror's. Mirrored per-file failures emit - no log record, since the number of records would disclose a document figure. + `sources` counts no mirrored source, since its state is its mirror's. Mirrored + per-file failures emit no log record, since the number of records would disclose a + document figure. A sync turn enters its private diagnostic scope before taking its source lease or listing files; retirement enters it before reading its queue. That scope suppresses client and provider instrumentation, database diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index f78fc3931a0..7f98367c373 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -681,20 +681,23 @@ the org's failing sources in [`ops.incidents`](../operations/monitoring.md#opsin `sources`. Each leg of the worker's pass (the sync turns, mirrored ones included, the mining and the retirement of removed sources) counts the pass as failed toward the worker's failure streak only when most of the orgs the pass serves had most of their -sources in that leg fail; the pass's status row then carries, as its `partial_error`, -`sync failed for most sources in 3 of 4 orgs (most often failed)`. An org the leg had -nothing to do for, or that the pass bound left for the next pass, has not failed. That -is an outage of what every source relies on, such as the store, a source's provider or -the model, or a deployment with one org. One org's failing sources, however many of the deployment's sources are its own, therefore make -neither the worker nor `ops.incidents` degraded for the other orgs. A source another -copy holds counts neither way, and a refused credential (`credential_invalid`) of a -namespace's source never counts: it is its org's to rotate, however many orgs hold one. +sources in that leg fail. The pass's status row then names the leg (`partial_leg`, such +as `sync`) and carries `failed for most sources in 3 of 4 orgs (most often failed)` as +its `partial_error`. The orgs the pass serves are those with a source it syncs, and an +org the leg had nothing to do for, or that the pass bound left for the next pass, has +not failed. Most orgs failing is an outage of what every source relies on, such as the +store, a source's provider or the model, or a deployment where one org holds every +source the pass syncs. Otherwise one org's failing sources, however many of the +deployment's sources are its own, make neither the worker nor `ops.incidents` degraded +for the other orgs. A source another copy holds counts neither way, and a refused +credential (`credential_invalid`) of a namespace's source never counts: it is its org's +to rotate, however many orgs hold one. The mining leg counts the documents the pass tried instead of sources: an org has failed when most of the documents tried for it failed, from at least two, or from one source whose documents could not be read, whose record could not be written or whose mining -raised. One document that fails to mine, the only one a pass tries included, is that document's, in its source's -`extract_error`. Since an org with nothing to mine has not failed, a model outage while +raised. One document that fails to mine, the only one a pass tries included, is that +document's, in its source's `extract_error`. Since an org with nothing to mine has not failed, a model outage while fewer than half the orgs have changed documents is not counted toward the streak; each source's `extract_error` shows it, and so does the `provider` incident of [`ops.incidents`](../operations/monitoring.md#opsincidents) on the process that made the diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 81baece33fe..547a5b4042f 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -165,9 +165,11 @@ are deployment state, the same for every org: a readiness or provider incident n 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 of its -ClickHouse reads (the worker streaks, the request counts, the failing sources) runs at -most once every 5 seconds per process, however many clients poll during an outage, and is -cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A read that failed is named in the response's +ClickHouse reads runs at most once every 5 seconds per process (the worker streaks), per +org (the request counts) or per org and collection reach (the failing sources), however +many clients poll during an outage, and is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A +person's reach holds their own personal collection, so each person who polls as an admin +has a read of the failing sources of their own. A read that failed is named in the response's `degraded` while its failure is cached, and the other reads still answer. The caller's collection reach, which the failing sources need, comes from the grant cache every call uses and is cut at the same bound. @@ -191,8 +193,9 @@ health. The `knowledge_source_sync` worker becomes a `worker` incident after 3 f passes in a row, like any worker. A pass that runs fails when it fails outright (its source list or registry unread, or past its deadline), or when one of its legs (the sync turns, the mining, the retirement of removed sources) failed for most of the sources, or -of the documents mined, of most orgs: an outage of what every source relies on, such as -the store, a source's provider or the model, or a deployment with one org. A refused +of the documents mined, of most orgs with a source it syncs: an outage of what every +source relies on, such as the store, a source's provider or the model, or a deployment +where one org holds every source the pass syncs. A refused credential never counts toward it, and neither does a pass that runs a mirrored source's turn, which leaves the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). diff --git a/docs/reference/operations/ops.md b/docs/reference/operations/ops.md index 69d79fe21b7..76a985b8305 100644 --- a/docs/reference/operations/ops.md +++ b/docs/reference/operations/ops.md @@ -59,7 +59,7 @@ Whether Loom is degraded now, from its checks, providers, workers and calls. | `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… | -| `sources` | `OpsIncidentSources` | The org's document sources whose last sync failed, for its admin to fix; a server of an earlier build leaves it out. | +| `sources` | `OpsIncidentSources` | The org's document sources whose last sync failed, for its admin to fix; by default none, unread (`{failing: 0, sample: [], read: "unread"}`). | ## `ops.projection_failures.list` diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 75bb2d6d478..1e1dcf70ce2 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: 264dd83aa6e5667d5ffcd22fc4f799960525efe4391c667ce17e96a70285c3ed +// Registry model schema SHA-256: 820e302862ac140a92d39298e54546132827f3470de5ea8edab4d4cf84d7bf6a // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index eea0bbcd945..6caf5f6d284 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -218,7 +218,8 @@ class OpsIncidentSources(BaseModel): `sync.status` in `knowledge.source.list`), so it never makes `status` `degraded` by itself: a revoked credential is its org's to fix, not a Loom outage. The sync worker becomes an incident after 3 failed passes in a row: a pass that fails outright, or - one in which most orgs' sources fail (an outage, or a deployment with one org).""" + one in which most orgs' sources fail (an outage, or a deployment where one org holds + every synced source).""" # Sources whose last turn failed; 0 unless `read` is `read`. failing: int = 0 @@ -248,6 +249,6 @@ class OpsIncidentsOutput(BaseModel): # hidden from it); `unread` when the counts, the restricted set or a restricted # namespace's grant could not be read. requests: OrgRead - # The org's document sources whose last sync failed, for its admin to fix; a server - # of an earlier build leaves it out. + # The org's document sources whose last sync failed, for its admin to fix; by + # default none, unread (`{failing: 0, sample: [], read: "unread"}`). sources: OpsIncidentSources = Field(default_factory=OpsIncidentSources) diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index fc7ec2fea90..a315d4b68e4 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -220,30 +220,31 @@ def add( failure: str = "", *, ran: int = 1, - failed: int = 0, + failed: int | None = None, whole: bool = False, ) -> None: - """Count `ran` units of a source the leg handled, `failed` of them failing (all, - when `failure` names a kind and `failed` is 0). `failure` is the kind (an - exception's class, a turn's status, `SYNC_FAILED` for a mirrored source), never - its text; `whole` when the source failed whole (its mining's read, write or - raise), not unit by unit.""" + """Count `ran` units of a source the leg handled and, when `failure` names the + kind of a failure, `failed` of them failing (all of them when not given). The + kind is an exception's class, a turn's status or `SYNC_FAILED` for a mirrored + source, never its text; `whole` when the source failed whole (its mining's read, + write or raise), not unit by unit.""" self.ran[src.org] += ran if whole: self.whole.add(src.org) if failure: - self.failed[src.org] += failed or ran + self.failed[src.org] += ran if failed is None else failed self.kinds[src.org][failure] += 1 def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = 1) -> None: - """One failure for the pass when most of the orgs it serves (`orgs`, with those - the leg ran for) had most of their units in the leg fail, from at least `least` - units or a source that failed whole; an org the leg had nothing to do for has not - failed. That is an outage of - what every source relies on (the store, a source's provider, the model), or a - deployment with one org. One org's failures, however many of the sources are its - own, are its own (a source's sync state, and for a state write that failed the - server's log), and no failure of the worker every org shares.""" + """One failure for the pass, under the leg's name, when most of the orgs it + serves (`orgs`, with those the leg ran for) had most of their units in the leg + fail, from at least `least` units or a source that failed whole. An org the leg + had nothing to do for has not failed. Most orgs failing is an outage of what + every source relies on (the store, a source's provider, the model), or a + deployment where one org holds every source the pass syncs. Otherwise one org's + failures, however many of the sources are its own, are its own (a source's sync + state, and for a state write that failed the server's log), and no failure of + the worker every org shares.""" serving = orgs | set(self.ran) failing = [ o @@ -253,8 +254,8 @@ def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = if len(failing) * 2 > len(serving): # The kind most common in the orgs that failed, not in those that did not. kind = sum((self.kinds[o] for o in failing), Counter[str]()).most_common(1)[0][0] - msg = f"{leg} failed for most {unit} in {len(failing)} of {len(serving)} orgs" - pass_context.note_failure(SourcesFailed(f"{msg} (most often {kind})"), WORKER) + msg = f"failed for most {unit} in {len(failing)} of {len(serving)} orgs" + pass_context.note_failure(SourcesFailed(f"{msg} (most often {kind})"), leg) # Why a turn stopped short: they lead its error text, and the dashboard reads a note that @@ -1691,7 +1692,7 @@ class _Mined: waits: dict[str, list[Any]] # Documents settled at a revision: mined, or given up on. settled: dict[str, str] = field(default_factory=dict) - # A document's extraction was tried and came back (mined or failed), not held. + # Documents whose extraction was tried and came back (mined or failed), not held. tries: int = 0 extracted: int = 0 flagged: int = 0 diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index 315c0a049e4..c96f6aba982 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -524,7 +524,7 @@ async def handle_knowledge_source_list( async def failing_sources( - org: str, *, sample: int, scope: str = "", scope_params: dict[str, Any] | None = None + org: str, *, sample: int, scope: str, scope_params: dict[str, Any] ) -> tuple[int, list[dict[str, str]]]: """How many of the org's sources that every reader of their namespace sees ended their last sync turn failing, and `sample` of them ({namespace, name, status}), the latest diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index cfe08571eb2..6ba8dbd01d7 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -550,14 +550,15 @@ async def failing_sources( org: str, *, sample: int, - scope: str = "", - scope_params: dict[str, Any] | None = None, + scope: str, + scope_params: dict[str, Any], ch: _CHClient | None = None, ) -> tuple[int, list[dict[str, str]]]: """How many of the org's sources shown to their namespace's readers ended their last turn failing, and `sample` of them ({namespace, name, status}), the latest first. `scope` is a WHERE fragment on `namespace` with its `scope_params`: the collections - the caller cannot read (`collection_clause`).""" + the caller cannot read (`collection_clause`), `""` only for a caller that reads + every one.""" rows = await (ch or _default_client()).query_all( _failing_sources_sql(scope), params={ diff --git a/tests/analyzer/cases/workers.py b/tests/analyzer/cases/workers.py index a2778075a1a..70381bdc50d 100644 --- a/tests/analyzer/cases/workers.py +++ b/tests/analyzer/cases/workers.py @@ -135,7 +135,17 @@ async def _worker_passes(ch: RecordingCH, c: dict[str, Any]) -> None: 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) - await source_store.failing_sources(ORG, sample=5, ch=ch) + # A platform admin's read of every collection, and an org admin's, which leaves out + # the collections it cannot read (`collection_clause`). + await source_store.failing_sources(ORG, sample=5, scope="", scope_params={}, ch=ch) + await source_store.failing_sources( + ORG, + sample=5, + scope=" AND (NOT startsWith(namespace, {col_prefix:String})" + " OR namespace IN {col_readable:Array(String)})", + scope_params={"col_prefix": "col-", "col_readable": ["col-board"]}, + 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 c60bd4f810d..7ade719a863 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -708,6 +708,7 @@ 50baf1256eb9 SELECT count() AS n FROM loom.memory_code_links FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL 51005813e7c3 SELECT unit_id, path, churn, amp, tested, callees, computed_at FROM loom.code_unit_risk FINAL WHERE org = {org:String} AND namespace = {ns:String} AND unit_id IN {ids:Array(String)} 511151c6fd23 ALTER TABLE loom.memory UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND has(tags, ?) AND hasAny(tags, {src:Array(String)}) AND hasAny(arrayMap(t -> (names +515e1c1ee3a5 SELECT namespace, substring(state_key, {start:UInt64}) AS source_name, JSONExtractString(detail, ?) AS status, count() OVER () AS failing FROM loom.code_index_state FINAL WHERE org = {org:String} AND 5163c1fd8d3c SELECT count() AS n FROM loom.memory_record_versions WHERE org = {org:String} AND namespace = {ns:String} 516db52eddcc SELECT count() AS n FROM loom.session_brief_revisions WHERE org = {org:String} AND namespace = {ns:String} AND ? 51af520b7286 SELECT DISTINCT tier, qualified_name, symbol_id FROM loom.code_symbol_names WHERE org = {org:String} AND namespace = {ns:String} AND name IN {names:Array(String)} AND (qualified_name = {full:String} O diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index a99d2030454..fa4e16385a9 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -30,8 +30,8 @@ def _sources(world: _World, *names: str) -> None: def _noted(leg: str, kind: str, orgs: str = "1 of 1") -> list[tuple[str, str, str]]: unit = "documents" if leg == "mining" else "sources" - msg = f"{leg} failed for most {unit} in {orgs} orgs (most often {kind})" - return [(source_sync.WORKER, "SourcesFailed", msg)] + msg = f"failed for most {unit} in {orgs} orgs (most often {kind})" + return [(leg, "SourcesFailed", msg)] _KIND = {"status": "failed", "raises": "ConnectionError"} @@ -103,7 +103,8 @@ def test_two_failing_sources_of_three_note_one_pass_failure( def test_the_only_source_failing_notes_one_pass_failure( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - """A deployment with one source still builds the worker's streak.""" + """A deployment with one source still builds the worker's streak, however many orgs + it has besides: an org with no source the pass syncs is not one it serves.""" _sources(world, "a") _turns(monkeypatch, {"a"}) diff --git a/tests/unit/test_ops_incidents_sql.py b/tests/unit/test_ops_incidents_sql.py index ff64e531a59..bbbb124cd77 100644 --- a/tests/unit/test_ops_incidents_sql.py +++ b/tests/unit/test_ops_incidents_sql.py @@ -193,7 +193,9 @@ async def test_the_sources_read_counts_and_samples_the_orgs_own_failing_sources( ch: Any = LocalCH(*_source_rows()) # No collection clause: a platform admin, or auth off, reads every collection. - failing, sample = await sources.failing_sources("o1", sample=5, ch=ch) + failing, sample = await sources.failing_sources( + "o1", sample=5, scope="", scope_params={}, ch=ch + ) assert failing == 4 assert sample == [ @@ -202,13 +204,18 @@ async def test_the_sources_read_counts_and_samples_the_orgs_own_failing_sources( {"namespace": "team", "name": "decks", "status": "credential_invalid"}, {"namespace": "team", "name": "broke", "status": "failed"}, ] - failing, sample = await sources.failing_sources("o1", sample=2, ch=ch) + failing, sample = await sources.failing_sources( + "o1", sample=2, scope="", scope_params={}, ch=ch + ) assert failing == 4 and [s["name"] for s in sample] == ["minutes", "runbooks"] - assert await sources.failing_sources("o2", sample=5, ch=ch) == ( + assert await sources.failing_sources("o2", sample=5, scope="", scope_params={}, ch=ch) == ( 1, [{"namespace": "team", "name": "decks", "status": "failed"}], ) - assert await sources.failing_sources("o3", sample=5, ch=ch) == (0, []) + assert await sources.failing_sources("o3", sample=5, scope="", scope_params={}, ch=ch) == ( + 0, + [], + ) @pytest.mark.parametrize("readable", [[], ["col-board"]], ids=["no-grant", "granted"]) From a4828fcf4d55aaad600400e99c976c54cb640708 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 18:07:45 +0530 Subject: [PATCH 11/41] A failed record write of each org's only source is tested to note once The mining raise path counts a source as failed whole; a test now pins it with two orgs whose only source tried one document and whose record write failed. The docs name the worker status row's error_class and error the note leaves, not the pass event's fields, and drop mirrored turns from the legs that move the streak, since their pass is private. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 45 ++++++++++--------- server/knowledge/app/source_sync.py | 12 ++--- server/knowledge/store/sources.py | 2 +- .../test_knowledge_source_sync_failures.py | 28 ++++++++++++ 4 files changed, 55 insertions(+), 32 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 7f98367c373..ef9f80acef9 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -677,33 +677,34 @@ A source's `sync` in `list` and `inspect` shows what its last turn did: | `extract_error` | Why an extraction failed in the last mining turn (`not_run`, `refused`, `out_of_time`, `too_large_for_pass`, `failed:`), or why documents wait (`over_cap`, `switched_off`, `switch_unread`, `no_model`, `held`, `held:`, `pass_bound`). | A failed turn belongs to its source: its `status` and `error` here, and for an org admin -the org's failing sources in [`ops.incidents`](../operations/monitoring.md#opsincidents)' -`sources`. Each leg of the worker's pass (the sync turns, mirrored ones included, the -mining and the retirement of removed sources) counts the pass as failed toward the -worker's failure streak only when most of the orgs the pass serves had most of their -sources in that leg fail. The pass's status row then names the leg (`partial_leg`, such -as `sync`) and carries `failed for most sources in 3 of 4 orgs (most often failed)` as -its `partial_error`. The orgs the pass serves are those with a source it syncs, and an -org the leg had nothing to do for, or that the pass bound left for the next pass, has -not failed. Most orgs failing is an outage of what every source relies on, such as the -store, a source's provider or the model, or a deployment where one org holds every -source the pass syncs. Otherwise one org's failing sources, however many of the -deployment's sources are its own, make neither the worker nor `ops.incidents` degraded -for the other orgs. A source another copy holds counts neither way, and a refused -credential (`credential_invalid`) of a namespace's source never counts: it is its org's -to rotate, however many orgs hold one. +the org's failing sources in +[`ops.incidents`](../operations/monitoring.md#opsincidents)' `sources`. Each leg of the +worker's pass (the sync turns, the mining and the retirement of removed sources) counts +the pass as failed toward the worker's failure streak only when most of the orgs the +pass serves had most of their sources in that leg fail. The worker's status row then +reads `SourcesFailed`, with the error `sync: failed for most sources in 3 of 4 orgs +(most often failed)`, which names the leg. The orgs the pass serves are those with a +source it syncs, and an org the leg had nothing to do for, or that the pass bound left +for the next pass, has not failed. Most orgs failing is an outage of what every source +relies on, such as the store, a source's provider or the model, or a deployment where +one org holds every source the pass syncs. Otherwise one org's failing sources, however +many of the deployment's sources are its own, make neither the worker nor +`ops.incidents` degraded for the other orgs. A source another copy holds counts neither +way, and a refused credential (`credential_invalid`) of a namespace's source never +counts: it is its org's to rotate, however many orgs hold one. The mining leg counts the documents the pass tried instead of sources: an org has failed when most of the documents tried for it failed, from at least two, or from one source whose documents could not be read, whose record could not be written or whose mining raised. One document that fails to mine, the only one a pass tries included, is that -document's, in its source's `extract_error`. Since an org with nothing to mine has not failed, a model outage while -fewer than half the orgs have changed documents is not counted toward the streak; each -source's `extract_error` shows it, and so does the `provider` incident of -[`ops.incidents`](../operations/monitoring.md#opsincidents) on the process that made the -calls. A pass that runs any mirrored turn is private, and the worker's streak stays as it -was: while auth is on, on a deployment with an active mirrored source, no leg's failure -reaches the streak, and the pass's status row reads `SYNC_FAILED`. +document's, in its source's `extract_error`. Since an org with nothing to mine has not +failed, a model outage while fewer than half the orgs have changed documents is not +counted toward the streak; each source's `extract_error` shows it, and so does the +`provider` incident of [`ops.incidents`](../operations/monitoring.md#opsincidents) on +the process that made the calls. A pass that runs any mirrored turn is private, and the +worker's streak stays as it was: while auth is on, on a deployment with an active +mirrored source, no leg's failure reaches the streak, and the pass's status row reads +`SYNC_FAILED`. ### A recording source diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index a315d4b68e4..119d7ede62c 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -238,13 +238,7 @@ def add( def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = 1) -> None: """One failure for the pass, under the leg's name, when most of the orgs it serves (`orgs`, with those the leg ran for) had most of their units in the leg - fail, from at least `least` units or a source that failed whole. An org the leg - had nothing to do for has not failed. Most orgs failing is an outage of what - every source relies on (the store, a source's provider, the model), or a - deployment where one org holds every source the pass syncs. Otherwise one org's - failures, however many of the sources are its own, are its own (a source's sync - state, and for a state write that failed the server's log), and no failure of - the worker every org shares.""" + fail, from at least `least` units or a source that failed whole.""" serving = orgs | set(self.ran) failing = [ o @@ -603,8 +597,8 @@ async def _sync_turn( ) # A refused credential is never the worker's failure: only its org can rotate it, # however many orgs hold one. - own = turn.status == "credential_invalid" - result.turns.add(src, turn.status if failed and not own else "") + refused = turn.status == "credential_invalid" + result.turns.add(src, turn.status if failed and not refused else "") if failed: result.failed += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 6ba8dbd01d7..87e5b69f71b 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -562,7 +562,7 @@ async def failing_sources( rows = await (ch or _default_client()).query_all( _failing_sources_sql(scope), params={ - **(scope_params or {}), + **scope_params, "org": org, "prefix": STATE_KEY_PREFIX, "start": len(STATE_KEY_PREFIX) + 1, diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index fa4e16385a9..f2f54386279 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -349,6 +349,34 @@ async def down(*args: Any, **kw: Any) -> Any: assert ctx.failures == _noted("mining", "ConnectionError", "2 of 2") +def test_a_failed_record_write_of_each_orgs_only_source_notes_once( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Each org's only source mines its one document, and the write of what it mined + fails: a source whose mining raised failed whole, so its org counts though it tried + a single document.""" + world.sources = [_source("a"), dataclasses.replace(_source("c"), org="other")] + _turns(monkeypatch, set()) + + async def revisions(at: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + return [{"source_uri": f"https://docs.example.com/{tag}/0", "source_revision": "r1"}] + + async def one_try(src: Any, todo: Any, run: Any, result: Any, mined: Any, *a: Any) -> None: + mined.tries += 1 + + async def write(src: Any, mined: Any, *a: Any, **kw: Any) -> None: + if mined is not None: + raise ConnectionError("record store down") + + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + monkeypatch.setattr(source_sync, "_extract_all", one_try) + monkeypatch.setattr(source_sync, "_write_mined", write) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == _noted("mining", "ConnectionError", "2 of 2") + + def _documents(monkeypatch: pytest.MonkeyPatch, count: int, org: str = ORG) -> None: """Each source of `org` holds `count` unmined documents; another org's none.""" From 78e8d5965a6b36946630e61d22be494238c545c7 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 18:28:20 +0530 Subject: [PATCH 12/41] Mining's two-try floor is on the pass, not on each org With the floor on each org, orgs that each mined one changed document never counted, so a model outage on a quiet deployment never built the streak. The leg is now judged once the pass tried two documents in all; the only document a pass tries failing stays that document's. A source that failed whole no longer needs its own exemption. SourceTally.add names its failure argument kind. ops.incidents builds its unread sources answer one way. The docs drop the provider incident as a signal of a mining outage: the worker's model calls run in the worker child process by default, whose provider health no request reads. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 15 +++--- server/insights/app/incidents.py | 5 +- server/knowledge/app/source_sync.py | 48 +++++++------------ .../test_knowledge_source_sync_failures.py | 30 ++++++++++++ 4 files changed, 55 insertions(+), 43 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index ef9f80acef9..b70f71e2169 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -694,14 +694,13 @@ way, and a refused credential (`credential_invalid`) of a namespace's source nev counts: it is its org's to rotate, however many orgs hold one. The mining leg counts the documents the pass tried instead of sources: an org has failed -when most of the documents tried for it failed, from at least two, or from one source -whose documents could not be read, whose record could not be written or whose mining -raised. One document that fails to mine, the only one a pass tries included, is that -document's, in its source's `extract_error`. Since an org with nothing to mine has not -failed, a model outage while fewer than half the orgs have changed documents is not -counted toward the streak; each source's `extract_error` shows it, and so does the -`provider` incident of [`ops.incidents`](../operations/monitoring.md#opsincidents) on -the process that made the calls. A pass that runs any mirrored turn is private, and the +when most of the documents tried for it failed, and a source whose documents could not +be read, whose record could not be written or whose mining raised counts as failed +tries. The leg is judged only from two documents tried in the pass, so the only document +a pass tries failing to mine is that document's, in its source's `extract_error`. Since +an org with nothing to mine has not failed, a model outage while fewer than half the +orgs have changed documents is not counted toward the streak; each source's +`extract_error` shows it. A pass that runs any mirrored turn is private, and the worker's streak stays as it was: while auth is on, on a deployment with an active mirrored source, no leg's failure reaches the streak, and the pass's status row reads `SYNC_FAILED`. diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 747a8d5354f..a4fa887f571 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -44,7 +44,6 @@ MAX_INCIDENTS = 20 # not a setting: the bound the output model documents MAX_SOURCE_SAMPLE = 5 -_UNREAD_SOURCES = OpsIncidentSources(read="unread") # 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 @@ -245,7 +244,7 @@ async def _sources(org: str, scope: str, params: dict[str, Any]) -> OpsIncidentS def _sources_unread(kind: str) -> OpsIncidentSources: degradations.partial("ops.incidents", "sources_unread", kind) - return OpsIncidentSources(read="unread") + return OpsIncidentSources() async def _sources_read(org: str) -> OpsIncidentSources: @@ -268,7 +267,7 @@ async def _sources_read(org: str) -> OpsIncidentSources: return _sources_unread("CollectionsUnread") reach = ",".join(params.get("col_readable", ["*"])) sources, _ = await _cached( - "sources", f"{org}\n{reach}", lambda: _sources(org, scope, params), _UNREAD_SOURCES + "sources", f"{org}\n{reach}", lambda: _sources(org, scope, params), OpsIncidentSources() ) return sources diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 119d7ede62c..1cd6ff35b03 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -197,8 +197,7 @@ class SourcesFailed(RuntimeError): in its sync state, never the worker's.""" -# An org's mining counts as failing from two documents tried: one tells nothing of the -# model. +# A pass's mining is judged from two documents tried: one tells nothing of the model. _LEAST_TRIES = 2 @@ -211,41 +210,26 @@ class SourceTally: ran: Counter[str] = field(default_factory=Counter) failed: Counter[str] = field(default_factory=Counter) kinds: defaultdict[str, Counter[str]] = field(default_factory=lambda: defaultdict(Counter)) - # Orgs with a source that failed whole: they count however few units they have. - whole: set[str] = field(default_factory=set) def add( - self, - src: KnowledgeSource, - failure: str = "", - *, - ran: int = 1, - failed: int | None = None, - whole: bool = False, + self, src: KnowledgeSource, kind: str = "", *, ran: int = 1, failed: int | None = None ) -> None: - """Count `ran` units of a source the leg handled and, when `failure` names the - kind of a failure, `failed` of them failing (all of them when not given). The - kind is an exception's class, a turn's status or `SYNC_FAILED` for a mirrored - source, never its text; `whole` when the source failed whole (its mining's read, - write or raise), not unit by unit.""" + """Count `ran` units of a source the leg handled and, when `kind` names the kind + of a failure, `failed` of them failing (all of them when not given). The kind is + an exception's class, a turn's status or `SYNC_FAILED` for a mirrored source, + never its text.""" self.ran[src.org] += ran - if whole: - self.whole.add(src.org) - if failure: + if kind: self.failed[src.org] += ran if failed is None else failed - self.kinds[src.org][failure] += 1 + self.kinds[src.org][kind] += 1 def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = 1) -> None: - """One failure for the pass, under the leg's name, when most of the orgs it - serves (`orgs`, with those the leg ran for) had most of their units in the leg - fail, from at least `least` units or a source that failed whole.""" + """One failure for the pass, under the leg's name, when the leg handled at least + `least` units and most of the orgs it serves (`orgs`, with those the leg ran for) + had most of their units fail.""" serving = orgs | set(self.ran) - failing = [ - o - for o, n in self.ran.items() - if (n >= least or o in self.whole) and self.failed[o] * 2 > n - ] - if len(failing) * 2 > len(serving): + failing = [o for o, n in self.ran.items() if self.failed[o] * 2 > n] + if sum(self.ran.values()) >= least and len(failing) * 2 > len(serving): # The kind most common in the orgs that failed, not in those that did not. kind = sum((self.kinds[o] for o in failing), Counter[str]()).most_common(1)[0][0] msg = f"failed for most {unit} in {len(failing)} of {len(serving)} orgs" @@ -1724,7 +1708,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass except Exception as e: # noqa: BLE001 — one source's failed read must not stop the others result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 - result.mining.add(src, type(e).__name__, whole=True) + result.mining.add(src, type(e).__name__) continue todo = _unmined(docs, detail) # A source with nothing to mine and no stale count to clear needs no write. @@ -1757,7 +1741,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) - result.mining.add(src, type(e).__name__, whole=True) + result.mining.add(src, type(e).__name__) continue stop = await _extract_source(src, docs, run, result) @@ -1852,7 +1836,7 @@ def may_write() -> bool: raised = type(e).__name__ # The documents it tried, and those that failed; a raise fails the source's whole try. if raised: - result.mining.add(src, raised, ran=max(mined.tries, 1), whole=True) + result.mining.add(src, raised, ran=max(mined.tries, 1)) elif mined.tries: result.mining.add(src, mined.error, ran=mined.tries, failed=mined.failures) result.extracted += mined.extracted diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index f2f54386279..b7a2b76dd33 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -427,6 +427,36 @@ def test_one_orgs_failing_documents_are_not_the_others_failure( assert ctx.failures == [] +def test_a_model_outage_on_one_document_of_each_org_is_the_workers_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Every org mines one changed document and each fails: three tries in the pass, most + of every org's failing, is an outage however few each org tried.""" + from server.memory.app import decision_extract + from server.memory.app.decision_extract import ExtractReport + + world.sources = [ + _source("a"), + dataclasses.replace(_source("b"), org="o2"), + dataclasses.replace(_source("c"), org="o3"), + ] + _turns(monkeypatch, set()) + + async def revisions(at: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + return [{"source_uri": f"https://docs.example.com/{tag}/0", "source_revision": "r1"}] + + async def down(org: str, ns: str, uri: str, **kw: Any) -> ExtractReport: + return ExtractReport(uri, False, error="model down") + + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + monkeypatch.setattr(decision_extract, "extract_document", down) + + result, ctx = asyncio.run(_supervised()) + + assert result.failed == 3 + assert ctx.failures == _noted("mining", "not_run", "3 of 3") + + def test_the_only_document_mined_in_a_pass_failing_is_not_the_workers_failure( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: From 2e1f8cb1f41dbd7d172edabdc26c140926a6feae Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 18:51:31 +0530 Subject: [PATCH 13/41] A failed mining read of a deployment's only source still notes once The two-try floor is for documents: a source whose mining read, write or run fails has failed whole, and the leg is judged however few units it handled, so a store read that fails for a deployment's only source every pass builds the streak as it did. The docs name the denominator in full (the orgs with a synced source and those the leg ran for) and the cost of never counting a refused credential: a refusal every org's credentials share is not counted either. _LEAST_TRIES says why it is not a setting. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 36 +++++++++-------- docs/operations/monitoring.md | 39 ++++++++++--------- server/knowledge/app/source_sync.py | 32 ++++++++++----- .../test_knowledge_source_sync_failures.py | 18 +++++++++ 4 files changed, 80 insertions(+), 45 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index b70f71e2169..6bd85449766 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -684,26 +684,30 @@ the pass as failed toward the worker's failure streak only when most of the orgs pass serves had most of their sources in that leg fail. The worker's status row then reads `SourcesFailed`, with the error `sync: failed for most sources in 3 of 4 orgs (most often failed)`, which names the leg. The orgs the pass serves are those with a -source it syncs, and an org the leg had nothing to do for, or that the pass bound left -for the next pass, has not failed. Most orgs failing is an outage of what every source -relies on, such as the store, a source's provider or the model, or a deployment where -one org holds every source the pass syncs. Otherwise one org's failing sources, however -many of the deployment's sources are its own, make neither the worker nor -`ops.incidents` degraded for the other orgs. A source another copy holds counts neither -way, and a refused credential (`credential_invalid`) of a namespace's source never -counts: it is its org's to rotate, however many orgs hold one. +source it syncs and those the leg ran for (such as an org whose removed source it +retires), and an org the leg had nothing to do for, or that the pass bound left for the +next pass, has not failed. Most orgs failing is an outage of what every source relies +on, such as the store, a source's provider or the model, or a deployment where one org +holds every source the pass syncs. Otherwise one org's failing sources, however many of +the deployment's sources are its own, make neither the worker nor `ops.incidents` +degraded for the other orgs. A source another copy holds counts neither way, and a +refused credential (`credential_invalid`) of a namespace's source never counts: it is +its org's to rotate, however many orgs hold one. So a refusal every org's credentials +share is not counted either, such as a provider refusing every token exchange of a host +whose clock is off, or stored credentials that no longer open after the server's secret +changed without its previous one; each org's failing sources show it. The mining leg counts the documents the pass tried instead of sources: an org has failed when most of the documents tried for it failed, and a source whose documents could not be read, whose record could not be written or whose mining raised counts as failed -tries. The leg is judged only from two documents tried in the pass, so the only document -a pass tries failing to mine is that document's, in its source's `extract_error`. Since -an org with nothing to mine has not failed, a model outage while fewer than half the -orgs have changed documents is not counted toward the streak; each source's -`extract_error` shows it. A pass that runs any mirrored turn is private, and the -worker's streak stays as it was: while auth is on, on a deployment with an active -mirrored source, no leg's failure reaches the streak, and the pass's status row reads -`SYNC_FAILED`. +tries. The leg is judged only from two documents tried in the pass, or from one source +that failed whole, so the only document a pass tries failing to mine is that document's, +in its source's `extract_error`. Since an org with nothing to mine has not failed, a +model outage while fewer than half the orgs have changed documents is not counted toward +the streak; each source's `extract_error` shows it. A pass that runs any mirrored turn +is private, and the worker's streak stays as it was: while auth is on, on a deployment +with an active mirrored source, no leg's failure reaches the streak, and the pass's +status row reads `SYNC_FAILED`. ### A recording source diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 547a5b4042f..276c25715af 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -179,25 +179,26 @@ covers the org's calls only when they were: `read`; `not_permitted` when the cal 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. -`sources` lists the org's own [document sources](../features/knowledge.md#syncing-a-source) -whose last sync turn failed: `failing`, how many, and `sample`, at most 5 of them -(`{namespace, name, status}`), the latest failure first, with `status` `failed`, -`rate_limited` or `credential_invalid`. It counts only the sources every reader of their -namespace sees, never a mirrored or a person's connected one, whose state is its mirror's. -It is read under the same rule as the request counts, and `sources.read` answers in the -same words. It leaves out the collections the caller holds no grant for, since an org -admin reaches a collection only through a grant (a platform admin reads every one). A -failing document source is never an incident and never by itself makes `status` -`degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own -health. The `knowledge_source_sync` worker becomes a `worker` incident after 3 failed -passes in a row, like any worker. A pass that runs fails when it fails outright (its -source list or registry unread, or past its deadline), or when one of its legs (the sync -turns, the mining, the retirement of removed sources) failed for most of the sources, or -of the documents mined, of most orgs with a source it syncs: an outage of what every -source relies on, such as the store, a source's provider or the model, or a deployment -where one org holds every source the pass syncs. A refused -credential never counts toward it, and neither does a pass that runs a mirrored source's -turn, which leaves the streak as it was (see +`sources` lists the org's own +[document sources](../features/knowledge.md#syncing-a-source) whose last sync turn +failed: `failing`, how many, and `sample`, at most 5 of them (`{namespace, name, +status}`), the latest failure first, with `status` `failed`, `rate_limited` or +`credential_invalid`. It counts only the sources every reader of their namespace sees, +never a mirrored or a person's connected one, whose state is its mirror's. It is read +under the same rule as the request counts, and `sources.read` answers in the same words. +It leaves out the collections the caller holds no grant for, since an org admin reaches +a collection only through a grant (a platform admin reads every one). A failing document +source is never an incident and never by itself makes `status` `degraded`: a revoked +credential is its org's to rotate, and `status` stays Loom's own health. The +`knowledge_source_sync` worker becomes a `worker` incident after 3 failed passes in a +row, like any worker. A pass that runs fails when it fails outright (its source list or +registry unread, or past its deadline), or when one of its legs (the sync turns, the +mining, the retirement of removed sources) failed for most of the sources, or of the +documents mined, of most orgs with a source it syncs or that the leg ran for: an outage +of what every source relies on, such as the store, a source's provider or the model, or +a deployment where one org holds every source the pass syncs. A refused credential never +counts toward it, and neither does a pass that runs a mirrored source's turn, which +leaves the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). ### Smoke test diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 1cd6ff35b03..2be1cf4c373 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -193,11 +193,12 @@ class SourceGone(Exception): class SourcesFailed(RuntimeError): """A leg of the pass failed for most of what it handled (sources, or for the mining - documents tried) in most orgs: its one failure note. A source's failure is its own, - in its sync state, never the worker's.""" + documents tried) in most orgs: its one failure note. A source's failure is in its + sync state, and one org's failures are its own unless most orgs' fail.""" -# A pass's mining is judged from two documents tried: one tells nothing of the model. +# not a setting: one document tried tells nothing of the model, so a pass's mining is +# judged from two (or from a source that failed whole) _LEAST_TRIES = 2 @@ -210,26 +211,37 @@ class SourceTally: ran: Counter[str] = field(default_factory=Counter) failed: Counter[str] = field(default_factory=Counter) kinds: defaultdict[str, Counter[str]] = field(default_factory=lambda: defaultdict(Counter)) + # A source failed whole (its mining's read, write or raise): the leg is judged however + # few units it handled. + whole: bool = False def add( - self, src: KnowledgeSource, kind: str = "", *, ran: int = 1, failed: int | None = None + self, + src: KnowledgeSource, + kind: str = "", + *, + ran: int = 1, + failed: int | None = None, + whole: bool = False, ) -> None: """Count `ran` units of a source the leg handled and, when `kind` names the kind of a failure, `failed` of them failing (all of them when not given). The kind is an exception's class, a turn's status or `SYNC_FAILED` for a mirrored source, never its text.""" self.ran[src.org] += ran + self.whole |= whole if kind: self.failed[src.org] += ran if failed is None else failed self.kinds[src.org][kind] += 1 def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = 1) -> None: """One failure for the pass, under the leg's name, when the leg handled at least - `least` units and most of the orgs it serves (`orgs`, with those the leg ran for) - had most of their units fail.""" + `least` units (or a source failed whole) and most of the orgs it serves (`orgs`, + with those the leg ran for) had most of their units fail.""" serving = orgs | set(self.ran) failing = [o for o, n in self.ran.items() if self.failed[o] * 2 > n] - if sum(self.ran.values()) >= least and len(failing) * 2 > len(serving): + judged = self.whole or sum(self.ran.values()) >= least + if judged and len(failing) * 2 > len(serving): # The kind most common in the orgs that failed, not in those that did not. kind = sum((self.kinds[o] for o in failing), Counter[str]()).most_common(1)[0][0] msg = f"failed for most {unit} in {len(failing)} of {len(serving)} orgs" @@ -1708,7 +1720,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass except Exception as e: # noqa: BLE001 — one source's failed read must not stop the others result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 - result.mining.add(src, type(e).__name__) + result.mining.add(src, type(e).__name__, whole=True) continue todo = _unmined(docs, detail) # A source with nothing to mine and no stale count to clear needs no write. @@ -1741,7 +1753,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) - result.mining.add(src, type(e).__name__) + result.mining.add(src, type(e).__name__, whole=True) continue stop = await _extract_source(src, docs, run, result) @@ -1836,7 +1848,7 @@ def may_write() -> bool: raised = type(e).__name__ # The documents it tried, and those that failed; a raise fails the source's whole try. if raised: - result.mining.add(src, raised, ran=max(mined.tries, 1)) + result.mining.add(src, raised, ran=max(mined.tries, 1), whole=True) elif mined.tries: result.mining.add(src, mined.error, ran=mined.tries, failed=mined.failures) result.extracted += mined.extracted diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index b7a2b76dd33..4515fac9dff 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -349,6 +349,24 @@ async def down(*args: Any, **kw: Any) -> Any: assert ctx.failures == _noted("mining", "ConnectionError", "2 of 2") +def test_a_failed_store_read_of_a_deployments_only_source_notes_once( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """The two-try floor is for documents: a read of the only source's documents failing + every pass is the store's, and the worker's failure, however few sources there are.""" + _sources(world, "a") + _turns(monkeypatch, set()) + + async def down(*args: Any, **kw: Any) -> Any: + raise ConnectionError("store down") + + monkeypatch.setattr(source_sync.store, "source_revisions", down) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == _noted("mining", "ConnectionError") + + def test_a_failed_record_write_of_each_orgs_only_source_notes_once( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: From 3617e6e4817f9231590859166e021d7d62a7c2bd Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 19:20:50 +0530 Subject: [PATCH 14/41] ops.incidents keys the sources cache on the clause it runs The sources cache key is built from the readable collections only when a collection clause applies, so a renamed parameter raises instead of sharing the platform admin's entry. The docs say the worker streak catches an outage of what most orgs' sources rely on, a provider most of them use included, and that one fewer than half the orgs use is not counted. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 22 ++++++++++++---------- docs/operations/monitoring.md | 8 ++++---- server/insights/app/incidents.py | 3 ++- 3 files changed, 18 insertions(+), 15 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 6bd85449766..ca79a747bf7 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -686,16 +686,18 @@ reads `SourcesFailed`, with the error `sync: failed for most sources in 3 of 4 o (most often failed)`, which names the leg. The orgs the pass serves are those with a source it syncs and those the leg ran for (such as an org whose removed source it retires), and an org the leg had nothing to do for, or that the pass bound left for the -next pass, has not failed. Most orgs failing is an outage of what every source relies -on, such as the store, a source's provider or the model, or a deployment where one org -holds every source the pass syncs. Otherwise one org's failing sources, however many of -the deployment's sources are its own, make neither the worker nor `ops.incidents` -degraded for the other orgs. A source another copy holds counts neither way, and a -refused credential (`credential_invalid`) of a namespace's source never counts: it is -its org's to rotate, however many orgs hold one. So a refusal every org's credentials -share is not counted either, such as a provider refusing every token exchange of a host -whose clock is off, or stored credentials that no longer open after the server's secret -changed without its previous one; each org's failing sources show it. +next pass, has not failed. Most orgs failing is an outage of what most orgs' sources +rely on, such as the store, a provider most of them use or the model, or a deployment +where one org holds every source the pass syncs. An outage of a provider fewer than half +the orgs use is therefore not counted; each of those orgs' failing sources shows it. +Otherwise one org's failing sources, however many of the deployment's sources are its +own, make neither the worker nor `ops.incidents` degraded for the other orgs. A source +another copy holds counts neither way, and a refused credential (`credential_invalid`) +of a namespace's source never counts: it is its org's to rotate, however many orgs hold +one. So a refusal every org's credentials share is not counted either, such as a +provider refusing every token exchange of a host whose clock is off, or stored +credentials that no longer open after the server's secret changed without its previous +one; each org's failing sources show it. The mining leg counts the documents the pass tried instead of sources: an org has failed when most of the documents tried for it failed, and a source whose documents could not diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 276c25715af..78c641b633c 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -195,10 +195,10 @@ row, like any worker. A pass that runs fails when it fails outright (its source registry unread, or past its deadline), or when one of its legs (the sync turns, the mining, the retirement of removed sources) failed for most of the sources, or of the documents mined, of most orgs with a source it syncs or that the leg ran for: an outage -of what every source relies on, such as the store, a source's provider or the model, or -a deployment where one org holds every source the pass syncs. A refused credential never -counts toward it, and neither does a pass that runs a mirrored source's turn, which -leaves the streak as it was (see +of what most orgs' sources rely on, such as the store, a provider most of them use or +the model, or a deployment where one org holds every source the pass syncs. A refused +credential never counts toward it, and neither does a pass that runs a mirrored source's +turn, which leaves the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). ### Smoke test diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index a4fa887f571..32bff44b725 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -265,7 +265,8 @@ async def _sources_read(org: str) -> OpsIncidentSources: return _sources_unread(error_kind(e)) if fail_closed.unreadable(): return _sources_unread("CollectionsUnread") - reach = ",".join(params.get("col_readable", ["*"])) + # The readable collections the statement runs with; no clause reads every one. + reach = ",".join(params["col_readable"]) if scope else "*" sources, _ = await _cached( "sources", f"{org}\n{reach}", lambda: _sources(org, scope, params), OpsIncidentSources() ) From 767c981b6b1985284e62726fb75c60c29cd55683 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 19:44:49 +0530 Subject: [PATCH 15/41] Dormant orgs whose credentials are refused do not hide an outage A refused credential's turn counted as handled, so an org whose every source's credential was refused counted as an org that did not fail and diluted the active orgs' failures: three dormant orgs beside two failing active ones noted nothing. Such a turn is now left out of the tally, and an org with no other turn is not one the leg counts. ops.incidents calls each cached read a read, not a source, now that one of them reads document sources, and its cache comment names the sources key as the org and the collection reach. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 6 +++-- docs/operations/monitoring.md | 5 ++-- server/insights/app/incidents.py | 13 +++++----- server/knowledge/app/source_sync.py | 13 +++++++--- tests/unit/test_knowledge_source_sync.py | 9 ++++--- .../test_knowledge_source_sync_failures.py | 26 +++++++++++++++++++ 6 files changed, 55 insertions(+), 17 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index ca79a747bf7..af8d3187718 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -694,8 +694,10 @@ Otherwise one org's failing sources, however many of the deployment's sources ar own, make neither the worker nor `ops.incidents` degraded for the other orgs. A source another copy holds counts neither way, and a refused credential (`credential_invalid`) of a namespace's source never counts: it is its org's to rotate, however many orgs hold -one. So a refusal every org's credentials share is not counted either, such as a -provider refusing every token exchange of a host whose clock is off, or stored +one. Such a turn is left out of the tally, and an org whose every turn was refused is +not one the pass counts, so dormant orgs whose credentials lapsed never hide an outage +of the active ones. So a refusal every org's credentials share is not counted either, +such as a provider refusing every token exchange of a host whose clock is off, or stored credentials that no longer open after the server's secret changed without its previous one; each org's failing sources show it. diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 78c641b633c..cad93bd5a3b 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -197,8 +197,9 @@ mining, the retirement of removed sources) failed for most of the sources, or of documents mined, of most orgs with a source it syncs or that the leg ran for: an outage of what most orgs' sources rely on, such as the store, a provider most of them use or the model, or a deployment where one org holds every source the pass syncs. A refused -credential never counts toward it, and neither does a pass that runs a mirrored source's -turn, which leaves the streak as it was (see +credential never counts toward it, for or against (an org whose every source's +credential was refused is not one the pass counts), and neither does a pass that runs a +mirrored source's turn, which leaves the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). ### Smoke test diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 32bff44b725..c707a0f8681 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -48,15 +48,16 @@ # 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 +# not a setting: polls within it share each ClickHouse read _SOURCE_TTL_S = 5.0 # Each org polling holds an entry for its request counts and one for each collection # reach its callers have; past this the cache starts over. # not a setting: a memory bound, not a behaviour _CACHE_MAX = 1024 -# (source, key) -> (read at, what it read, the read's failure or ""), and the lock its -# polls share while one reads; the key is the org, and for the sources the caller's reach +# (read, key) -> (read at, what it read, the read's failure or ""), and the lock its +# polls share while one reads; the key is the org, for the sources the org and the +# caller's collection reach _cache: dict[tuple[str, str], tuple[float, Any, str]] = {} _locks: dict[tuple[str, str], asyncio.Lock] = {} @@ -66,13 +67,13 @@ def _line(text: object) -> str: async def _cached[T]( - source: str, key: str, read: Callable[[], Awaitable[T]], unread: T + name: str, key: str, read: Callable[[], Awaitable[T]], unread: T ) -> tuple[T, bool]: """(`read()`'s answer, or the one it gave within `_SOURCE_TTL_S`, or `unread` when it failed; 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.""" - entry = (source, key) + entry = (name, key) lock = _locks.get(entry) if lock is None: if len(_locks) >= _CACHE_MAX: @@ -89,7 +90,7 @@ async def _cached[T]( answer, failure = unread, caller_text(e) hit = _cache[entry] = (time.monotonic(), answer, failure) if hit[2]: - degradations.partial("ops.incidents", f"{source}_unread", hit[2]) + degradations.partial("ops.incidents", f"{name}_unread", hit[2]) return hit[1], not hit[2] diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 2be1cf4c373..31cd884d593 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -214,6 +214,9 @@ class SourceTally: # A source failed whole (its mining's read, write or raise): the leg is judged however # few units it handled. whole: bool = False + # Orgs with a turn whose credential was refused, which is left out of the tally: it + # tells nothing of the worker, and an org with no other turn is not one it serves. + refused: set[str] = field(default_factory=set) def add( self, @@ -238,7 +241,7 @@ def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = """One failure for the pass, under the leg's name, when the leg handled at least `least` units (or a source failed whole) and most of the orgs it serves (`orgs`, with those the leg ran for) had most of their units fail.""" - serving = orgs | set(self.ran) + serving = (orgs | set(self.ran)) - (self.refused - set(self.ran)) failing = [o for o, n in self.ran.items() if self.failed[o] * 2 > n] judged = self.whole or sum(self.ran.values()) >= least if judged and len(failing) * 2 > len(serving): @@ -592,9 +595,11 @@ async def _sync_turn( and src.config.get("provider") == "meet" ) # A refused credential is never the worker's failure: only its org can rotate it, - # however many orgs hold one. - refused = turn.status == "credential_invalid" - result.turns.add(src, turn.status if failed and not refused else "") + # however many orgs hold one (dormant accounts), so it is left out of the tally. + if failed and turn.status == "credential_invalid": + result.turns.refused.add(src.org) + else: + result.turns.add(src, turn.status if failed else "") if failed: result.failed += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index 98147d0961a..ffebb71e282 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -3439,9 +3439,12 @@ async def _turn(source: Any, state: Any, run: Any) -> source_sync.TurnResult: turn = asyncio.run(source_sync._sync_turn(src, world.states[src.name], run, result)) assert turn is not None and turn.status == status and not turn.complete assert result.failed == len(result.errors) == expected_failures - # A refused credential is its org's to rotate: never toward the worker's failure. - assert result.turns.failed[ORG] == (0 if status == "credential_invalid" else expected_failures) - assert result.turns.ran == {ORG: 1} and failures == [] # the pass notes its tally, not the turn + # A refused credential is its org's to rotate: it is left out of the tally. + if status == "credential_invalid": + assert (result.turns.ran, result.turns.refused) == ({}, {ORG}) + else: + assert (result.turns.ran, result.turns.failed[ORG]) == ({ORG: 1}, expected_failures) + assert failures == [] # the pass notes its tally, not the turn assert (result.changed, result.removed, result.unconverted, result.skipped) == (0, 0, 0, 0) assert world.states[src.name]["state_value"] == "old-stamp" detail = _detail(world, src.name) diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 4515fac9dff..dc0b7dfc43f 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -172,6 +172,32 @@ async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnRe assert ctx.failures == [] +def test_dormant_orgs_whose_credentials_are_refused_do_not_hide_an_outage( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Three orgs hold only refused credentials and the two active orgs' sources fail: + an org whose every turn was refused tells nothing of the worker, so it is not one + the pass counts, and the outage of the active orgs is noted.""" + world.sources = [ + dataclasses.replace(_source(name), org=org) + for name, org in (("d1", "o1"), ("d2", "o2"), ("d3", "o3"), ("a", ORG), ("b", "o5")) + ] + + async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: + out = source_sync.TurnResult() + if src.name.startswith("d"): + out.fail("credential_invalid", "the provider refused the credential") + else: + out.fail("failed", "ConnectionError") + return out + + monkeypatch.setattr(source_sync, "_turn_of", lambda src: turn) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == _noted("sync", "failed", "2 of 2") + + def test_a_pass_cut_inside_one_orgs_failing_sources_is_not_the_others_failure( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: From 87a4334caeb931f8e8cf7f7ddbb022abdff0437f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 20:22:32 +0530 Subject: [PATCH 16/41] No leg of a source sync pass counts an org whose every turn was refused Mining and retirement were judged against every org with a usable source, dormant ones included, so three orgs whose only credential is refused beside two active orgs whose documents all fail to mine read 2 of 5 and noted nothing. run_sync now drops those orgs once the turns are done, and judges retirement there too. ops.incidents names its read cache's TTL for what it bounds (every read). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 4 +-- server/insights/app/incidents.py | 10 +++--- server/knowledge/app/source_sync.py | 8 +++-- .../test_knowledge_source_sync_failures.py | 36 +++++++++++++++++++ tests/unit/test_ops_incidents.py | 6 ++-- 5 files changed, 51 insertions(+), 13 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index cad93bd5a3b..fa752f0d9d7 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -168,8 +168,8 @@ a worker of any of the deployment's processes with its streak and error kind, wh ClickHouse reads runs at most once every 5 seconds per process (the worker streaks), per org (the request counts) or per org and collection reach (the failing sources), however many clients poll during an outage, and is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A -person's reach holds their own personal collection, so each person who polls as an admin -has a read of the failing sources of their own. A read that failed is named in the response's +person's reach holds their own personal collection, so each person who polls as an org +admin has a read of the failing sources of their own. A read that failed is named in the response's `degraded` while its failure is cached, and the other reads still answer. The caller's collection reach, which the failing sources need, comes from the grant cache every call uses and is cut at the same bound. diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index c707a0f8681..62935de5af9 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -11,7 +11,7 @@ org the call acts in, read only by a token over every namespace of it (the rollup keeps no namespace or user; a source names its namespace). Each of its ClickHouse reads (the worker streaks, the org's request counts and failing sources) runs at most once per -`_SOURCE_TTL_S` per process (per org, and for the sources per collection reach), so +`_READ_TTL_S` per process (per org, and for the sources per collection reach), so clients polling during an outage do not add load. A read that does not answer 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 @@ -49,7 +49,7 @@ # not a setting: what "current" means for a worker, documented with the op _WORKER_WINDOW_HOURS = 6 # not a setting: polls within it share each ClickHouse read -_SOURCE_TTL_S = 5.0 +_READ_TTL_S = 5.0 # Each org polling holds an entry for its request counts and one for each collection # reach its callers have; past this the cache starts over. # not a setting: a memory bound, not a behaviour @@ -69,7 +69,7 @@ def _line(text: object) -> str: async def _cached[T]( name: str, key: str, read: Callable[[], Awaitable[T]], unread: T ) -> tuple[T, bool]: - """(`read()`'s answer, or the one it gave within `_SOURCE_TTL_S`, or `unread` when it + """(`read()`'s answer, or the one it gave within `_READ_TTL_S`, or `unread` when it failed; 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.""" @@ -82,11 +82,11 @@ async def _cached[T]( lock = _locks[entry] = asyncio.Lock() async with lock: hit = _cache.get(entry) - if hit is None or time.monotonic() - hit[0] >= _SOURCE_TTL_S: + if hit is None or time.monotonic() - hit[0] >= _READ_TTL_S: try: async with asyncio.timeout(settings.readiness_check_timeout_s): answer, failure = await read(), "" - except Exception as e: # noqa: BLE001 — an unread source is noted; the others answer + except Exception as e: # noqa: BLE001 — a failed read is noted; the others answer answer, failure = unread, caller_text(e) hit = _cache[entry] = (time.monotonic(), answer, failure) if hit[2]: diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 31cd884d593..6a9203acd20 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -215,7 +215,7 @@ class SourceTally: # few units it handled. whole: bool = False # Orgs with a turn whose credential was refused, which is left out of the tally: it - # tells nothing of the worker, and an org with no other turn is not one it serves. + # tells nothing of the worker (`run_sync` serves no org whose every turn was refused). refused: set[str] = field(default_factory=set) def add( @@ -241,7 +241,7 @@ def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = """One failure for the pass, under the leg's name, when the leg handled at least `least` units (or a source failed whole) and most of the orgs it serves (`orgs`, with those the leg ran for) had most of their units fail.""" - serving = (orgs | set(self.ran)) - (self.refused - set(self.ran)) + serving = orgs | set(self.ran) failing = [o for o, n in self.ran.items() if self.failed[o] * 2 > n] judged = self.whole or sum(self.ran.values()) >= least if judged and len(failing) * 2 > len(serving): @@ -427,7 +427,6 @@ async def run_sync( usable = await _usable(found) # The orgs the pass serves: each leg's failure note counts against them. orgs = {s.org for s in usable} - result.retiring.note("retirement", orgs) if full: for src in usable: await source_ops.request_full_sync(src) @@ -460,6 +459,9 @@ async def run_sync( # holds the others back; a requested source goes first anyway. pass_context.set_cursor(_cursor_of(src)) break + # An org whose every turn was refused tells nothing of the worker, so no leg counts it. + orgs -= result.turns.refused - set(result.turns.ran) + result.retiring.note("retirement", orgs) result.turns.note("sync", orgs) await _extract_pending(order, run, result) result.mining.note("mining", orgs, unit="documents", least=_LEAST_TRIES) diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index dc0b7dfc43f..c301aace499 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -198,6 +198,42 @@ async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnRe assert ctx.failures == _noted("sync", "failed", "2 of 2") +def test_dormant_orgs_do_not_hide_a_model_outage_of_the_active_ones( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """No leg counts an org whose every turn was refused: the active orgs' changed + documents all failing to mine is noted against the active orgs alone.""" + from server.memory.app import decision_extract + from server.memory.app.decision_extract import ExtractReport + + world.sources = [ + dataclasses.replace(_source(name), org=org) + for name, org in (("d1", "o1"), ("d2", "o2"), ("d3", "o3"), ("a", ORG), ("b", "o5")) + ] + + async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: + out = source_sync.TurnResult() + if src.name.startswith("d"): + out.fail("credential_invalid", "the provider refused the credential") + return out + + async def revisions(at: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + if tag.startswith("source:d"): + return [] + return [{"source_uri": f"https://docs.example.com/{tag}/0", "source_revision": "r1"}] + + async def down(org: str, ns: str, uri: str, **kw: Any) -> ExtractReport: + return ExtractReport(uri, False, error="model down") + + monkeypatch.setattr(source_sync, "_turn_of", lambda src: turn) + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + monkeypatch.setattr(decision_extract, "extract_document", down) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == _noted("mining", "not_run", "2 of 2") + + def test_a_pass_cut_inside_one_orgs_failing_sources_is_not_the_others_failure( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 46b5b25aa9b..8ef162b896c 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -1,5 +1,5 @@ """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.""" +and the org's request failures; a failed read is named in `degraded`, never a 500.""" from __future__ import annotations @@ -218,7 +218,7 @@ async def test_a_provider_failure_older_than_the_window_is_not_current(monkeypat @pytest.mark.asyncio -async def test_an_unread_source_is_named_in_degraded_and_the_others_answer(monkeypatch) -> None: +async def test_a_failed_read_is_named_in_degraded_and_the_others_answer(monkeypatch) -> None: def _down(sql, params): raise server_error("Connection refused", code=210) @@ -263,7 +263,7 @@ def _down(sql, params): @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 + """A stalled store: concurrent polls share each read in flight, so they do not multiply the reads while ClickHouse is slow.""" from server.insights.store import ops as ops_store from server.knowledge.store import sources as sources_store From 9cd2049fae517472e80dd7772f4ad08f43fcfd56 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 20:45:51 +0530 Subject: [PATCH 17/41] A source sync failure note names the kind of the most failed units The tally counted a kind once per source while it counted failures per document, so a mining note could name two sources' failed writes over one source's 40 failed documents. A kind now weighs its failed units; the sync and retirement legs add one unit per source and are unchanged. The orgs whose credential was refused move from the turns tally to PassResult, the one place that reads them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 10 +++++----- server/knowledge/app/source_sync.py | 17 +++++++++-------- tests/unit/test_knowledge_source_sync.py | 2 +- .../unit/test_knowledge_source_sync_failures.py | 16 ++++++++++++++++ 4 files changed, 31 insertions(+), 14 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index fa752f0d9d7..f369fedd952 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -169,8 +169,8 @@ ClickHouse reads runs at most once every 5 seconds per process (the worker strea org (the request counts) or per org and collection reach (the failing sources), however many clients poll during an outage, and is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A person's reach holds their own personal collection, so each person who polls as an org -admin has a read of the failing sources of their own. A read that failed is named in the response's -`degraded` while its failure is cached, and the other reads still answer. The caller's +admin has a read of the failing sources of their own. A read that failed is named in the +response's `degraded` while its failure is cached, and the other reads still answer. The caller's collection reach, which the failing sources need, comes from the grant cache every call uses and is cut at the same bound. @@ -197,9 +197,9 @@ mining, the retirement of removed sources) failed for most of the sources, or of documents mined, of most orgs with a source it syncs or that the leg ran for: an outage of what most orgs' sources rely on, such as the store, a provider most of them use or the model, or a deployment where one org holds every source the pass syncs. A refused -credential never counts toward it, for or against (an org whose every source's -credential was refused is not one the pass counts), and neither does a pass that runs a -mirrored source's turn, which leaves the streak as it was (see +credential never counts toward it, for or against (an org whose every turn was refused +is not one the pass counts), and neither does a pass that runs a mirrored source's turn, +which leaves the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). ### Smoke test diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 6a9203acd20..a263e9b57c0 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -206,7 +206,7 @@ class SourcesFailed(RuntimeError): class SourceTally: """Per org, what one leg of a pass handled and what of it failed (sources for the sync and retirement legs, documents tried for mining), and the kinds of the - failures.""" + failures, each weighed by its failed units.""" ran: Counter[str] = field(default_factory=Counter) failed: Counter[str] = field(default_factory=Counter) @@ -214,9 +214,6 @@ class SourceTally: # A source failed whole (its mining's read, write or raise): the leg is judged however # few units it handled. whole: bool = False - # Orgs with a turn whose credential was refused, which is left out of the tally: it - # tells nothing of the worker (`run_sync` serves no org whose every turn was refused). - refused: set[str] = field(default_factory=set) def add( self, @@ -234,8 +231,9 @@ def add( self.ran[src.org] += ran self.whole |= whole if kind: - self.failed[src.org] += ran if failed is None else failed - self.kinds[src.org][kind] += 1 + n = ran if failed is None else failed + self.failed[src.org] += n + self.kinds[src.org][kind] += n def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = 1) -> None: """One failure for the pass, under the leg's name, when the leg handled at least @@ -369,6 +367,9 @@ class PassResult: turns: SourceTally = field(default_factory=SourceTally) mining: SourceTally = field(default_factory=SourceTally) retiring: SourceTally = field(default_factory=SourceTally) + # Orgs with a turn whose credential was refused, a turn left out of the tally: it + # tells nothing of the worker, so no leg counts an org whose every turn was refused. + refused_orgs: set[str] = field(default_factory=set) # The pass bound stopped the pass before every source, or every file of one, was # handled. cut: bool = False @@ -460,7 +461,7 @@ async def run_sync( pass_context.set_cursor(_cursor_of(src)) break # An org whose every turn was refused tells nothing of the worker, so no leg counts it. - orgs -= result.turns.refused - set(result.turns.ran) + orgs -= result.refused_orgs - set(result.turns.ran) result.retiring.note("retirement", orgs) result.turns.note("sync", orgs) await _extract_pending(order, run, result) @@ -599,7 +600,7 @@ async def _sync_turn( # A refused credential is never the worker's failure: only its org can rotate it, # however many orgs hold one (dormant accounts), so it is left out of the tally. if failed and turn.status == "credential_invalid": - result.turns.refused.add(src.org) + result.refused_orgs.add(src.org) else: result.turns.add(src, turn.status if failed else "") if failed: diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index ffebb71e282..ad656d2d8ac 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -3441,7 +3441,7 @@ async def _turn(source: Any, state: Any, run: Any) -> source_sync.TurnResult: assert result.failed == len(result.errors) == expected_failures # A refused credential is its org's to rotate: it is left out of the tally. if status == "credential_invalid": - assert (result.turns.ran, result.turns.refused) == ({}, {ORG}) + assert (result.turns.ran, result.refused_orgs) == ({}, {ORG}) else: assert (result.turns.ran, result.turns.failed[ORG]) == ({ORG: 1}, expected_failures) assert failures == [] # the pass notes its tally, not the turn diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index c301aace499..554c621385e 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -612,3 +612,19 @@ def test_a_note_names_the_kind_most_common_among_the_orgs_that_failed() -> None: pass_context.clear() assert ctx.failures == _noted("sync", "failed", "2 of 3") + + +def test_a_mining_note_names_the_kind_of_most_failed_documents() -> None: + """A kind weighs the documents that failed of it, not the sources: 40 documents of + one source failing outweigh two sources whose record write raised.""" + tally = source_sync.SourceTally() + tally.add(_source("big"), "not_run", ran=40) + for name in ("s1", "s2"): + tally.add(_source(name), "ConnectionError", whole=True) + ctx = pass_context.begin(source_sync.WORKER) + try: + tally.note("mining", set(), unit="documents", least=2) + finally: + pass_context.clear() + + assert ctx.failures == _noted("mining", "not_run") From ad538c81057b31106ea11a78139a237d7a574b74 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 21:13:15 +0530 Subject: [PATCH 18/41] An org whose every turn was refused counts only in a leg that ran for it The docs and comments said no leg counts such an org, but mining still counts one whose stored documents it mines, which is right: mining needs no credential. The text now says so, and a test pins both cases. A mirrored source is left out of ops.incidents' sources without the wrong reason that its state is its mirror's, and the HTTP reference names the incidents cache by its reads. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/architecture/document-sources.md | 5 ++--- docs/features/knowledge.md | 6 +++--- docs/operations/monitoring.md | 12 ++++++------ docs/reference/http-api.md | 3 ++- server/knowledge/app/source_sync.py | 6 ++++-- server/knowledge/app/sources.py | 4 ++-- tests/unit/test_knowledge_source_sync_failures.py | 12 +++++++----- 7 files changed, 26 insertions(+), 22 deletions(-) diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 5c85027c4e8..00b069d1631 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -638,9 +638,8 @@ the public fallback. No reranking provider receives the provisional pools. figures and cut flags. A failed mirrored turn contributes only `SYNC_FAILED` and counts as failed in the pass's per-org tally of turns, for every cause, a refused credential included; returned turn details remain private. `ops.incidents`' - `sources` counts no mirrored source, since its state is its mirror's. Mirrored - per-file failures emit no log record, since the number of records would disclose a - document figure. + `sources` counts no mirrored source. Mirrored per-file failures emit no log record, + since the number of records would disclose a document figure. A sync turn enters its private diagnostic scope before taking its source lease or listing files; retirement enters it before reading its queue. That scope suppresses client and provider instrumentation, database diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index af8d3187718..54eb98f5b40 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -694,9 +694,9 @@ Otherwise one org's failing sources, however many of the deployment's sources ar own, make neither the worker nor `ops.incidents` degraded for the other orgs. A source another copy holds counts neither way, and a refused credential (`credential_invalid`) of a namespace's source never counts: it is its org's to rotate, however many orgs hold -one. Such a turn is left out of the tally, and an org whose every turn was refused is -not one the pass counts, so dormant orgs whose credentials lapsed never hide an outage -of the active ones. So a refusal every org's credentials share is not counted either, +one. Such a turn is left out of the tally, and an org whose every turn was refused +counts only in a leg that ran for it, such as mining the documents it stored before, so +dormant orgs whose credentials lapsed never hide an outage of the active ones. So a refusal every org's credentials share is not counted either, such as a provider refusing every token exchange of a host whose clock is off, or stored credentials that no longer open after the server's secret changed without its previous one; each org's failing sources show it. diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index f369fedd952..0d83d507a02 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -184,10 +184,10 @@ restricted set or a restricted namespace's grant could not be read. failed: `failing`, how many, and `sample`, at most 5 of them (`{namespace, name, status}`), the latest failure first, with `status` `failed`, `rate_limited` or `credential_invalid`. It counts only the sources every reader of their namespace sees, -never a mirrored or a person's connected one, whose state is its mirror's. It is read -under the same rule as the request counts, and `sources.read` answers in the same words. -It leaves out the collections the caller holds no grant for, since an org admin reaches -a collection only through a grant (a platform admin reads every one). A failing document +never a mirrored or a person's connected one. It is read under the same rule as the +request counts, and `sources.read` answers in the same words. It leaves out the +collections the caller holds no grant for, since an org admin reaches a collection only +through a grant (a platform admin reads every one). A failing document source is never an incident and never by itself makes `status` `degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own health. The `knowledge_source_sync` worker becomes a `worker` incident after 3 failed passes in a @@ -198,8 +198,8 @@ documents mined, of most orgs with a source it syncs or that the leg ran for: an of what most orgs' sources rely on, such as the store, a provider most of them use or the model, or a deployment where one org holds every source the pass syncs. A refused credential never counts toward it, for or against (an org whose every turn was refused -is not one the pass counts), and neither does a pass that runs a mirrored source's turn, -which leaves the streak as it was (see +counts only in a leg that ran for it), and neither does a pass that runs a mirrored +source's turn, which leaves the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). ### Smoke test diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index 3bbaebda035..fd68dd45999 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -376,7 +376,8 @@ error's kind only; the full text is in the server log. - `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. + - 5 seconds: each of `ops.incidents`' ClickHouse reads (the worker streaks, the + org's request counts, and its failing sources per collection reach). - 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/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index a263e9b57c0..86d3c759e90 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -368,7 +368,8 @@ class PassResult: mining: SourceTally = field(default_factory=SourceTally) retiring: SourceTally = field(default_factory=SourceTally) # Orgs with a turn whose credential was refused, a turn left out of the tally: it - # tells nothing of the worker, so no leg counts an org whose every turn was refused. + # tells nothing of the worker, so an org whose every turn was refused counts only in + # a leg that ran for it (mining the documents it stored before, say). refused_orgs: set[str] = field(default_factory=set) # The pass bound stopped the pass before every source, or every file of one, was # handled. @@ -460,7 +461,8 @@ async def run_sync( # holds the others back; a requested source goes first anyway. pass_context.set_cursor(_cursor_of(src)) break - # An org whose every turn was refused tells nothing of the worker, so no leg counts it. + # An org whose every turn was refused tells nothing of the worker: it counts only in a + # leg that ran for it (`SourceTally.note`). orgs -= result.refused_orgs - set(result.turns.ran) result.retiring.note("retirement", orgs) result.turns.note("sync", orgs) diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index c96f6aba982..94b2d59ea66 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -528,8 +528,8 @@ async def failing_sources( ) -> tuple[int, list[dict[str, str]]]: """How many of the org's sources that every reader of their namespace sees ended their last sync turn failing, and `sample` of them ({namespace, name, status}), the latest - failure first. A mirrored source's state is its mirror's, so none is counted. The - caller decides who may read them: they span every namespace of the org.""" + failure first. A mirrored source is not counted. The caller decides who may read + them: they span every namespace of the org.""" return await store.failing_sources(org, sample=sample, scope=scope, scope_params=scope_params) diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 554c621385e..7fbf0faa324 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -198,11 +198,13 @@ async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnRe assert ctx.failures == _noted("sync", "failed", "2 of 2") +@pytest.mark.parametrize(("dormant_docs", "orgs"), [(False, "2 of 2"), (True, "5 of 5")]) def test_dormant_orgs_do_not_hide_a_model_outage_of_the_active_ones( - world: _World, monkeypatch: pytest.MonkeyPatch + world: _World, monkeypatch: pytest.MonkeyPatch, dormant_docs: bool, orgs: str ) -> None: - """No leg counts an org whose every turn was refused: the active orgs' changed - documents all failing to mine is noted against the active orgs alone.""" + """An org whose every turn was refused counts only in a leg that ran for it: the + active orgs' changed documents all failing to mine is noted against them alone, and + the dormant orgs' stored documents still to mine count those orgs too.""" from server.memory.app import decision_extract from server.memory.app.decision_extract import ExtractReport @@ -218,7 +220,7 @@ async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnRe return out async def revisions(at: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: - if tag.startswith("source:d"): + if tag.startswith("source:d") and not dormant_docs: return [] return [{"source_uri": f"https://docs.example.com/{tag}/0", "source_revision": "r1"}] @@ -231,7 +233,7 @@ async def down(org: str, ns: str, uri: str, **kw: Any) -> ExtractReport: _, ctx = asyncio.run(_supervised()) - assert ctx.failures == _noted("mining", "not_run", "2 of 2") + assert ctx.failures == _noted("mining", "not_run", orgs) def test_a_pass_cut_inside_one_orgs_failing_sources_is_not_the_others_failure( From 487839be8454671bd6a975341e6223e6496c519b Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 21:43:36 +0530 Subject: [PATCH 19/41] deployment_scoped names ops.incidents' failing sources among its org reads The comment said a deployment-scoped op reads no namespace's data, with the request counts as its one org-wide read; the failing sources name namespaces and sources too. The knowledge and monitoring paragraphs on source failures are rewrapped. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 9 +++++---- docs/operations/monitoring.md | 34 +++++++++++++++++----------------- server/operations/base.py | 7 ++++--- 3 files changed, 26 insertions(+), 24 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 3893b32c752..e6adbf7c500 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -699,10 +699,11 @@ another copy holds counts neither way, and a refused credential (`credential_inv of a namespace's source never counts: it is its org's to rotate, however many orgs hold one. Such a turn is left out of the tally, and an org whose every turn was refused counts only in a leg that ran for it, such as mining the documents it stored before, so -dormant orgs whose credentials lapsed never hide an outage of the active ones. So a refusal every org's credentials share is not counted either, -such as a provider refusing every token exchange of a host whose clock is off, or stored -credentials that no longer open after the server's secret changed without its previous -one; each org's failing sources show it. +dormant orgs whose credentials lapsed never hide an outage of the active ones. A refusal +every org's credentials share is not counted either, such as a provider refusing every +token exchange of a host whose clock is off, or stored credentials that no longer open +after the server's secret changed without its previous one; each org's failing sources +show it. The mining leg counts the documents the pass tried instead of sources: an org has failed when most of the documents tried for it failed, and a source whose documents could not diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 0d83d507a02..05b1cc43629 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -169,10 +169,10 @@ ClickHouse reads runs at most once every 5 seconds per process (the worker strea org (the request counts) or per org and collection reach (the failing sources), however many clients poll during an outage, and is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A person's reach holds their own personal collection, so each person who polls as an org -admin has a read of the failing sources of their own. A read that failed is named in the -response's `degraded` while its failure is cached, and the other reads still answer. The caller's -collection reach, which the failing sources need, comes from the grant cache every call -uses and is cut at the same bound. +admin has a read of the failing sources of their own. A read that failed is named in +the response's `degraded` while its failure is cached, and the other reads still answer. +The caller's collection reach, which the failing sources need, comes from the grant +cache every call uses and is cut at the same bound. 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 @@ -187,19 +187,19 @@ status}`), the latest failure first, with `status` `failed`, `rate_limited` or never a mirrored or a person's connected one. It is read under the same rule as the request counts, and `sources.read` answers in the same words. It leaves out the collections the caller holds no grant for, since an org admin reaches a collection only -through a grant (a platform admin reads every one). A failing document -source is never an incident and never by itself makes `status` `degraded`: a revoked -credential is its org's to rotate, and `status` stays Loom's own health. The -`knowledge_source_sync` worker becomes a `worker` incident after 3 failed passes in a -row, like any worker. A pass that runs fails when it fails outright (its source list or -registry unread, or past its deadline), or when one of its legs (the sync turns, the -mining, the retirement of removed sources) failed for most of the sources, or of the -documents mined, of most orgs with a source it syncs or that the leg ran for: an outage -of what most orgs' sources rely on, such as the store, a provider most of them use or -the model, or a deployment where one org holds every source the pass syncs. A refused -credential never counts toward it, for or against (an org whose every turn was refused -counts only in a leg that ran for it), and neither does a pass that runs a mirrored -source's turn, which leaves the streak as it was (see +through a grant (a platform admin reads every one). A failing document source is never +an incident and never by itself makes `status` `degraded`: a revoked credential is its +org's to rotate, and `status` stays Loom's own health. The `knowledge_source_sync` +worker becomes a `worker` incident after 3 failed passes in a row, like any worker. A +pass that runs fails when it fails outright (its source list or registry unread, or past +its deadline), or when one of its legs (the sync turns, the mining, the retirement of +removed sources) failed for most of the sources, or of the documents mined, of most orgs +with a source it syncs or that the leg ran for: an outage of what most orgs' sources +rely on, such as the store, a provider most of them use or the model, or a deployment +where one org holds every source the pass syncs. A refused credential never counts +toward it, for or against (an org whose every turn was refused counts only in a leg that +ran for it), and neither does a pass that runs a mirrored source's turn, which leaves +the streak as it was (see [document sources](../features/knowledge.md#syncing-a-source)). ### Smoke test diff --git a/server/operations/base.py b/server/operations/base.py index b41bc378bde..f6f46b4ef7e 100644 --- a/server/operations/base.py +++ b/server/operations/base.py @@ -107,9 +107,10 @@ class Operation: # 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, 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 + # incidents) and no namespace's memory; an org-wide read it also answers + # (ops.incidents' request counts, and its failing sources, which name namespaces and + # sources) is authorized by its handler. 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 From 75541d754f1b93f9321c2735547ec3912c069bb1 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 22:17:15 +0530 Subject: [PATCH 20/41] A credential the deployment's secret no longer opens counts as the worker's failure Every credential_invalid turn was left out of the tally, so dropping the previous root secret before the reseal failed every org's sources and noted nothing. Only a credential the provider refuses is its org's to rotate; one the deployment cannot open now counts. Mining counts each failed document under its own reason, not its source's first, so the note names the reason of most failed documents. ops.incidents caches a sources answer for a minute: a source's state changes once a pass and each read parses every state's detail, its documents' map included. A failed read is still tried again after 5 seconds. The failure-counting rules are one list in the knowledge page, which the monitoring page links to. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 70 +++++++++---------- docs/operations/monitoring.md | 28 ++++---- docs/reference/http-api.md | 4 +- server/insights/app/incidents.py | 36 +++++++--- server/knowledge/app/source_sync.py | 32 +++++---- server/knowledge/app/sources.py | 12 +++- .../test_knowledge_source_sync_failures.py | 59 ++++++++++++++++ tests/unit/test_ops_incidents.py | 29 ++++++++ 8 files changed, 190 insertions(+), 80 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index e6adbf7c500..125c850ac04 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -679,43 +679,43 @@ A source's `sync` in `list` and `inspect` shows what its last turn did: | `unextracted` | Documents it gave up on: three failed tries, or too large for a pass. | | `extract_error` | Why an extraction failed in the last mining turn (`not_run`, `refused`, `out_of_time`, `too_large_for_pass`, `failed:`), or why documents wait (`over_cap`, `switched_off`, `switch_unread`, `no_model`, `held`, `held:`, `pass_bound`). | +### Source failures and the worker's health + A failed turn belongs to its source: its `status` and `error` here, and for an org admin the org's failing sources in -[`ops.incidents`](../operations/monitoring.md#opsincidents)' `sources`. Each leg of the -worker's pass (the sync turns, the mining and the retirement of removed sources) counts -the pass as failed toward the worker's failure streak only when most of the orgs the -pass serves had most of their sources in that leg fail. The worker's status row then -reads `SourcesFailed`, with the error `sync: failed for most sources in 3 of 4 orgs -(most often failed)`, which names the leg. The orgs the pass serves are those with a -source it syncs and those the leg ran for (such as an org whose removed source it -retires), and an org the leg had nothing to do for, or that the pass bound left for the -next pass, has not failed. Most orgs failing is an outage of what most orgs' sources -rely on, such as the store, a provider most of them use or the model, or a deployment -where one org holds every source the pass syncs. An outage of a provider fewer than half -the orgs use is therefore not counted; each of those orgs' failing sources shows it. -Otherwise one org's failing sources, however many of the deployment's sources are its -own, make neither the worker nor `ops.incidents` degraded for the other orgs. A source -another copy holds counts neither way, and a refused credential (`credential_invalid`) -of a namespace's source never counts: it is its org's to rotate, however many orgs hold -one. Such a turn is left out of the tally, and an org whose every turn was refused -counts only in a leg that ran for it, such as mining the documents it stored before, so -dormant orgs whose credentials lapsed never hide an outage of the active ones. A refusal -every org's credentials share is not counted either, such as a provider refusing every -token exchange of a host whose clock is off, or stored credentials that no longer open -after the server's secret changed without its previous one; each org's failing sources -show it. - -The mining leg counts the documents the pass tried instead of sources: an org has failed -when most of the documents tried for it failed, and a source whose documents could not -be read, whose record could not be written or whose mining raised counts as failed -tries. The leg is judged only from two documents tried in the pass, or from one source -that failed whole, so the only document a pass tries failing to mine is that document's, -in its source's `extract_error`. Since an org with nothing to mine has not failed, a -model outage while fewer than half the orgs have changed documents is not counted toward -the streak; each source's `extract_error` shows it. A pass that runs any mirrored turn -is private, and the worker's streak stays as it was: while auth is on, on a deployment -with an active mirrored source, no leg's failure reaches the streak, and the pass's -status row reads `SYNC_FAILED`. +[`ops.incidents`](../operations/monitoring.md#opsincidents)' `sources`. It counts toward +the worker's failure streak only as part of an outage of most orgs: + +- A leg of a pass (the sync turns, the mining, the retirement of removed sources) fails + the pass when most of the orgs it serves had most of their units fail: sources, or + for the mining the documents it tried. The worker's status row then reads + `SourcesFailed`, with an error that names the leg, such as + `sync: failed for most sources in 3 of 4 orgs (most often failed)`. +- A leg serves the orgs with a source the pass syncs and those it ran for, such as an + org whose removed source it retires. An org it had nothing to do for, or that the pass + bound left for the next pass, has not failed. +- So what most orgs' sources rely on counts: the store, a provider most of them use, the + model, or the deployment's secret, when it no longer opens the stored credentials. So + does every failure where one org holds every source the pass syncs. One org's failing + sources, however many they are, never degrade the worker or `ops.incidents` for the + other orgs, and neither does an outage of a provider fewer than half the orgs use. +- A source another copy holds counts neither way. +- A credential the provider refuses (`credential_invalid`) on a namespace's source is + its org's to rotate, so the turn is left out. An org whose every turn was refused + counts only in a leg that ran for it, such as mining the documents it stored before, + so dormant orgs never hide an outage of the active ones. A refusal every org's + credentials share, such as a provider refusing every token exchange of a host whose + clock is off, is not counted either. +- The mining leg is judged from two documents tried in the pass, or from one source that + failed whole: its documents unread, its record unwritten, or its mining raised. The + only document a pass tries failing to mine is that document's, and a model outage + while fewer than half the orgs have changed documents is not counted. +- A pass that runs any mirrored turn is private, and the worker's streak stays as it + was: while auth is on, on a deployment with an active mirrored source, no leg's failure + reaches the streak, and the pass's status row reads `SYNC_FAILED`. + +Each failing source, counted or not, shows in its `status` and `extract_error` and in +its org's `ops.incidents` `sources`. ### A recording source diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 05b1cc43629..bbc5ed6687f 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -165,12 +165,14 @@ are deployment state, the same for every org: a readiness or provider incident n 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 of its -ClickHouse reads runs at most once every 5 seconds per process (the worker streaks), per -org (the request counts) or per org and collection reach (the failing sources), however -many clients poll during an outage, and is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A -person's reach holds their own personal collection, so each person who polls as an org -admin has a read of the failing sources of their own. A read that failed is named in -the response's `degraded` while its failure is cached, and the other reads still answer. +ClickHouse reads runs at most once every 5 seconds per process (the worker streaks) or +per org (the request counts), and the failing sources once a minute per org and +collection reach, since a source's sync state changes once a pass and each read parses +every one of the org's. That holds however many clients poll during an outage, and each +read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A person's reach holds their own +personal collection, so each person who polls as an org admin has a read of the failing +sources of their own. A read that failed is named in the response's `degraded` while its +failure is cached (5 seconds), and the other reads still answer. The caller's collection reach, which the failing sources need, comes from the grant cache every call uses and is cut at the same bound. @@ -191,16 +193,10 @@ through a grant (a platform admin reads every one). A failing document source is an incident and never by itself makes `status` `degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own health. The `knowledge_source_sync` worker becomes a `worker` incident after 3 failed passes in a row, like any worker. A -pass that runs fails when it fails outright (its source list or registry unread, or past -its deadline), or when one of its legs (the sync turns, the mining, the retirement of -removed sources) failed for most of the sources, or of the documents mined, of most orgs -with a source it syncs or that the leg ran for: an outage of what most orgs' sources -rely on, such as the store, a provider most of them use or the model, or a deployment -where one org holds every source the pass syncs. A refused credential never counts -toward it, for or against (an org whose every turn was refused counts only in a leg that -ran for it), and neither does a pass that runs a mirrored source's turn, which leaves -the streak as it was (see -[document sources](../features/knowledge.md#syncing-a-source)). +pass fails when it fails outright (its source list or registry unread, or past its +deadline), or when most orgs' sources fail, as +[source failures and the worker's health](../features/knowledge.md#source-failures-and-the-workers-health) +describes. ### Smoke test diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index fd68dd45999..fbdccc10d34 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -376,8 +376,8 @@ error's kind only; the full text is in the server log. - `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 reads (the worker streaks, the - org's request counts, and its failing sources per collection reach). + - 5 seconds: `ops.incidents`' worker streaks and the org's request counts, and any + of its reads that failed; 60 seconds: its failing sources per collection reach. - 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/server/insights/app/incidents.py b/server/insights/app/incidents.py index 62935de5af9..8d44d133d84 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -10,11 +10,12 @@ an error's kind, never its text, and the request counts and the sources 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; a source names its namespace). Each of its ClickHouse reads (the -worker streaks, the org's request counts and failing sources) runs at most once per -`_READ_TTL_S` per process (per org, and for the sources per collection reach), so -clients polling during an outage do not add load. A read that does not answer 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 +worker streaks, the org's request counts) runs at most once per `_READ_TTL_S` per +process (per org), and the failing sources once per `_SOURCES_TTL_S` (per org and +collection reach), so clients polling during an outage do not add load. A read that +does not answer within a readiness check's bound (`readiness_check_timeout_s`) is named +in the answer's `degraded`, as long as that failure is cached (`_READ_TTL_S`); the +others still answer, so the op answers during a ClickHouse outage too. The caller's collection reach, which the sources need, comes from the grant cache every call uses and is cut at the same bound. """ @@ -48,8 +49,12 @@ # or runs less often than this). # not a setting: what "current" means for a worker, documented with the op _WORKER_WINDOW_HOURS = 6 +# A failed read is tried again after it. # not a setting: polls within it share each ClickHouse read _READ_TTL_S = 5.0 +# Each read parses every one of the org's sync states, their documents' maps included. +# not a setting: a source's sync state changes once a pass (15 minutes by default) +_SOURCES_TTL_S = 60.0 # Each org polling holds an entry for its request counts and one for each collection # reach its callers have; past this the cache starts over. # not a setting: a memory bound, not a behaviour @@ -67,11 +72,16 @@ def _line(text: object) -> str: async def _cached[T]( - name: str, key: str, read: Callable[[], Awaitable[T]], unread: T + name: str, + key: str, + read: Callable[[], Awaitable[T]], + unread: T, + *, + ttl: float = _READ_TTL_S, ) -> tuple[T, bool]: - """(`read()`'s answer, or the one it gave within `_READ_TTL_S`, or `unread` when it - failed; 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 + """(`read()`'s answer, or the one it gave within `ttl`, or `unread` when it failed; + whether that read answered). Polls that arrive while it reads wait for that read + rather than start their own. A failed read is cached for `_READ_TTL_S`, and named in `degraded` on every answer that serves it.""" entry = (name, key) lock = _locks.get(entry) @@ -82,7 +92,7 @@ async def _cached[T]( lock = _locks[entry] = asyncio.Lock() async with lock: hit = _cache.get(entry) - if hit is None or time.monotonic() - hit[0] >= _READ_TTL_S: + if hit is None or time.monotonic() - hit[0] >= (_READ_TTL_S if hit[2] else ttl): try: async with asyncio.timeout(settings.readiness_check_timeout_s): answer, failure = await read(), "" @@ -269,7 +279,11 @@ async def _sources_read(org: str) -> OpsIncidentSources: # The readable collections the statement runs with; no clause reads every one. reach = ",".join(params["col_readable"]) if scope else "*" sources, _ = await _cached( - "sources", f"{org}\n{reach}", lambda: _sources(org, scope, params), OpsIncidentSources() + "sources", + f"{org}\n{reach}", + lambda: _sources(org, scope, params), + OpsIncidentSources(), + ttl=_SOURCES_TTL_S, ) return sources diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 86d3c759e90..82fed15628f 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -367,9 +367,10 @@ class PassResult: turns: SourceTally = field(default_factory=SourceTally) mining: SourceTally = field(default_factory=SourceTally) retiring: SourceTally = field(default_factory=SourceTally) - # Orgs with a turn whose credential was refused, a turn left out of the tally: it - # tells nothing of the worker, so an org whose every turn was refused counts only in - # a leg that ran for it (mining the documents it stored before, say). + # Orgs with a turn whose credential the provider refused, a turn left out of the + # tally: only its org can rotate it, however many orgs hold one (dormant accounts), so + # it tells nothing of the worker. An org whose every turn was refused counts only in a + # leg that ran for it (mining the documents it stored before, say). refused_orgs: set[str] = field(default_factory=set) # The pass bound stopped the pass before every source, or every file of one, was # handled. @@ -461,9 +462,7 @@ async def run_sync( # holds the others back; a requested source goes first anyway. pass_context.set_cursor(_cursor_of(src)) break - # An org whose every turn was refused tells nothing of the worker: it counts only in a - # leg that ran for it (`SourceTally.note`). - orgs -= result.refused_orgs - set(result.turns.ran) + orgs -= result.refused_orgs - set(result.turns.ran) # see `PassResult.refused_orgs` result.retiring.note("retirement", orgs) result.turns.note("sync", orgs) await _extract_pending(order, run, result) @@ -599,9 +598,9 @@ async def _sync_turn( and src.kind == "recording" and src.config.get("provider") == "meet" ) - # A refused credential is never the worker's failure: only its org can rotate it, - # however many orgs hold one (dormant accounts), so it is left out of the tally. - if failed and turn.status == "credential_invalid": + # A refused credential is left out of the tally (`PassResult.refused_orgs`); one the + # deployment's secret no longer opens is the deployment's, and counts. + if failed and turn.status == "credential_invalid" and source_ops.credential_opens(src): result.refused_orgs.add(src.org) else: result.turns.add(src, turn.status if failed else "") @@ -1697,7 +1696,8 @@ class _Mined: extracted: int = 0 flagged: int = 0 unextracted: int = 0 - failures: int = 0 + # Each failed document's reason (a code, never a text), and the first one. + reasons: Counter[str] = field(default_factory=Counter) error: str = "" # Why the turn left documents for a later pass (`over_cap`, `held:`, # `pass_bound`). @@ -1709,6 +1709,10 @@ class _Mined: # ends with nothing recorded, and the leg goes on to the next source. lease_lost: bool = False + @property + def failures(self) -> int: + return sum(self.reasons.values()) + async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: PassResult) -> None: """The extraction leg: mine each source's unmined documents while the pass has @@ -1860,7 +1864,9 @@ def may_write() -> bool: if raised: result.mining.add(src, raised, ran=max(mined.tries, 1), whole=True) elif mined.tries: - result.mining.add(src, mined.error, ran=mined.tries, failed=mined.failures) + result.mining.add(src, ran=mined.tries) + for reason, n in mined.reasons.items(): + result.mining.add(src, reason, ran=0, failed=n) result.extracted += mined.extracted result.flagged_pinned += mined.flagged result.unextracted += mined.unextracted @@ -2000,7 +2006,7 @@ def _give_up_mining(mined: _Mined, uri: str, revision: str, reason: str) -> None mined.waits.pop(uri, None) mined.settled[uri] = revision mined.unextracted += 1 - mined.failures += 1 + mined.reasons[reason] += 1 mined.error = mined.error or reason @@ -2012,7 +2018,7 @@ def _extract_failed(mined: _Mined, uri: str, revision: str, reason: str) -> None _give_up_mining(mined, uri, revision, reason) return mined.waits[uri] = [revision, tries, reason] - mined.failures += 1 + mined.reasons[reason] += 1 mined.error = mined.error or reason diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index 999c174d743..ede74ecf7a9 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -107,13 +107,19 @@ def _now_iso() -> str: return datetime.now(UTC).replace(microsecond=0).isoformat() -def credential_of(src: KnowledgeSource) -> str: +def credential_of(src: KnowledgeSource, *, warn: bool = True) -> str: """The source's credential, '' when it no longer opens.""" if src.credential_mode != "shared": return "" # A connected source never falls back to an ingestion credential. if src.secret_enc: - return unseal(_SECRET_PURPOSE, src.secret_enc) - return unseal(_CREDENTIAL_PURPOSE, src.credential_enc) + return unseal(_SECRET_PURPOSE, src.secret_enc, warn=warn) + return unseal(_CREDENTIAL_PURPOSE, src.credential_enc, warn=warn) + + +def credential_opens(src: KnowledgeSource) -> bool: + """Whether the deployment's secrets open the source's stored credential. A connected + source's credential is its person's, so it is taken as open.""" + return src.credential_mode != "shared" or bool(credential_of(src, warn=False)) async def credential_for(src: KnowledgeSource, *, deadline: float) -> Credential: diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 7fbf0faa324..7fc26539993 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -198,6 +198,65 @@ async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnRe assert ctx.failures == _noted("sync", "failed", "2 of 2") +def test_credentials_the_deployment_no_longer_opens_are_the_workers_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """A stored credential the deployment's secret does not open (a secret rotated + without its previous one) is the deployment's failure, not its org's: every org's + only source ending `credential_invalid` so notes one.""" + world.sources = [ + dataclasses.replace(_source(name), org=org, credential_enc="sealed-elsewhere") + for name, org in (("a", ORG), ("b", "o2")) + ] + + async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: + out = source_sync.TurnResult() + out.fail("credential_invalid", "the stored credential no longer opens; rotate it") + return out + + monkeypatch.setattr(source_sync, "_turn_of", lambda src: turn) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == _noted("sync", "credential_invalid", "2 of 2") + + +def test_a_mining_note_names_the_reason_of_most_failed_documents( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Each failed document counts under its own reason, not its source's first: one + `refused` and four `not_run` documents note `not_run`.""" + from server.memory.app import decision_extract + from server.memory.app.decision_extract import ExtractReport + + world.sources = [ + dataclasses.replace(_source(name), org=org) for name, org in (("a", ORG), ("b", "o2")) + ] + docs = {"source:a": 3, "source:b": 2} + + async def ok(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: + return source_sync.TurnResult() + + async def revisions(at: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + return [ + {"source_uri": f"https://docs.example.com/{tag}/{i}", "source_revision": "r1"} + for i in range(docs.get(tag, 0)) + ] + + async def down(org: str, ns: str, uri: str, **kw: Any) -> ExtractReport: + if uri.endswith("source:a/0"): + return ExtractReport(uri, False, refused=["k: refused: busy"]) + return ExtractReport(uri, False, error="model down") + + monkeypatch.setattr(source_sync, "_turn_of", lambda src: ok) + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + monkeypatch.setattr(decision_extract, "extract_document", down) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == _noted("mining", "not_run", "2 of 2") + + @pytest.mark.parametrize(("dormant_docs", "orgs"), [(False, "2 of 2"), (True, "5 of 5")]) def test_dormant_orgs_do_not_hide_a_model_outage_of_the_active_ones( world: _World, monkeypatch: pytest.MonkeyPatch, dormant_docs: bool, orgs: str diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 8ef162b896c..2ad85c4ebde 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -445,6 +445,35 @@ async def test_each_org_reads_its_own_sources_once_per_ttl(monkeypatch) -> None: assert other.sources.failing == 7 # the route answers every org alike here +@pytest.mark.asyncio +async def test_a_sources_read_serves_a_minute_and_a_failed_one_is_retried_soon( + monkeypatch, +) -> None: + """A source's sync state changes once a pass, and each read parses every one of the + org's states: an answer serves a minute, a failed read only until the next poll + window.""" + from types import SimpleNamespace + + now = [1000.0] + monkeypatch.setattr(incidents, "time", SimpleNamespace(monotonic=lambda: now[0])) + reads: list[float] = [] + + def _sources(sql, params): + reads.append(now[0]) + if len(reads) == 1: + raise server_error("Connection refused", code=210) + return _FAILING + + ch = RecordingCH().on("loom.worker_status", []).on("sli_minute", []) + ch.on("loom.code_index_state", _sources).install(monkeypatch) + + for step in (0, 6, 50, 11): + now[0] += step + await _incidents() + + assert reads == [1000.0, 1006.0, 1067.0] + + @pytest.mark.asyncio async def test_a_collection_the_caller_holds_no_grant_for_is_left_out(monkeypatch) -> None: """An org admin reaches a collection only through a grant, so the sources of the From c5a64ad2dd36d22e674f000aa8e70752d71d27b5 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 22:45:21 +0530 Subject: [PATCH 21/41] ops.incidents stops each ClickHouse read at the bound it waits for A read was cut at the readiness bound on the client only, so the server ran it on for up to the read class's 30 seconds, and a poll after its cached failure could start another beside it. Every read now carries the bound as its statement timeout. The source sync tally takes `handled` and `fail` in place of one `add` keyed on argument shape, and the credential check calls credential_of directly: its only caller sees shared sources alone. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/insights/app/incidents.py | 24 +++++---- server/knowledge/app/source_sync.py | 54 +++++++++---------- server/knowledge/app/sources.py | 6 --- .../test_knowledge_source_sync_failures.py | 8 +-- tests/unit/test_ops_incidents.py | 28 ++++++++++ 5 files changed, 72 insertions(+), 48 deletions(-) diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 8d44d133d84..e28eb26ce84 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -12,12 +12,12 @@ no namespace or user; a source names its namespace). Each of its ClickHouse reads (the worker streaks, the org's request counts) runs at most once per `_READ_TTL_S` per process (per org), and the failing sources once per `_SOURCES_TTL_S` (per org and -collection reach), so clients polling during an outage do not add load. A read that -does not answer within a readiness check's bound (`readiness_check_timeout_s`) is named -in the answer's `degraded`, as long as that failure is cached (`_READ_TTL_S`); the -others still answer, so the op -answers during a ClickHouse outage too. The caller's collection reach, which the sources -need, comes from the grant cache every call uses and is cut at the same bound. +collection reach), so clients polling during an outage do not add load. Each read is +cut at a readiness check's bound (`readiness_check_timeout_s`) on both sides, and one +that does not answer within it is named in the answer's `degraded` as long as that +failure is cached (`_READ_TTL_S`); the others still answer, so the op answers during a +ClickHouse outage too. The caller's collection reach, which the sources need, comes +from the grant cache every call uses and is cut at the same bound. """ from __future__ import annotations @@ -28,6 +28,7 @@ from datetime import UTC, datetime from typing import Any +from server.core.ch import statement_timeout from server.core.errors import LoomServerError, caller_text, error_kind from server.insights.api.models_ops import ( OpsFailingSource, @@ -81,8 +82,9 @@ async def _cached[T]( ) -> tuple[T, bool]: """(`read()`'s answer, or the one it gave within `ttl`, or `unread` when it failed; whether that read answered). Polls that arrive while it reads wait for that read - rather than start their own. A failed read is cached for `_READ_TTL_S`, and named in - `degraded` on every answer that serves it.""" + rather than start their own. The server stops the read at the bound the client + waits, so a poll after a slow read's failure never runs beside it. A failed read is + cached for `_READ_TTL_S`, and named in `degraded` on every answer that serves it.""" entry = (name, key) lock = _locks.get(entry) if lock is None: @@ -94,8 +96,10 @@ async def _cached[T]( hit = _cache.get(entry) if hit is None or time.monotonic() - hit[0] >= (_READ_TTL_S if hit[2] else ttl): try: - async with asyncio.timeout(settings.readiness_check_timeout_s): - answer, failure = await read(), "" + bound = settings.readiness_check_timeout_s + async with asyncio.timeout(bound): + with statement_timeout(bound): + answer, failure = await read(), "" except Exception as e: # noqa: BLE001 — a failed read is noted; the others answer answer, failure = unread, caller_text(e) hit = _cache[entry] = (time.monotonic(), answer, failure) diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 82fed15628f..d1ddfbce273 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -215,25 +215,23 @@ class SourceTally: # few units it handled. whole: bool = False - def add( - self, - src: KnowledgeSource, - kind: str = "", - *, - ran: int = 1, - failed: int | None = None, - whole: bool = False, + def handled( + self, src: KnowledgeSource, n: int = 1, *, failed: str = "", whole: bool = False ) -> None: - """Count `ran` units of a source the leg handled and, when `kind` names the kind - of a failure, `failed` of them failing (all of them when not given). The kind is - an exception's class, a turn's status or `SYNC_FAILED` for a mirrored source, - never its text.""" - self.ran[src.org] += ran + """`n` units of a source the leg handled, every one of them failing when `failed` + names the kind (`fail`).""" + self.ran[src.org] += n self.whole |= whole - if kind: - n = ran if failed is None else failed - self.failed[src.org] += n - self.kinds[src.org][kind] += n + if failed: + self.fail(src, failed, n) + + def fail(self, src: KnowledgeSource, kind: str, n: int = 1) -> None: + """`n` of a source's handled units failing as `kind`: an exception's class, a + turn's status, `SYNC_FAILED` for a mirrored source, or a mining reason + (`not_run`, `refused`, `out_of_time`, `too_large_for_pass`, `failed:`); + a code, never a text.""" + self.failed[src.org] += n + self.kinds[src.org][kind] += n def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = 1) -> None: """One failure for the pass, under the leg's name, when the leg handled at least @@ -573,7 +571,7 @@ async def _sync_turn( log.info("knowledge_source_sync: %s is being synced by another copy", _cursor_of(src)) return None except Exception as e: # noqa: BLE001 — one source's failure must not stop the others - result.turns.add(src, "SYNC_FAILED" if mirror_synced(src) else type(e).__name__) + result.turns.handled(src, failed="SYNC_FAILED" if mirror_synced(src) else type(e).__name__) if mirror_synced(src): _mirror_failure(src, result) return None @@ -583,7 +581,7 @@ async def _sync_turn( return None if mirror_synced(src): # Every cause alike: a mirror's turn leaves no more than its one code. - result.turns.add(src, "" if turn.status == "ok" else "SYNC_FAILED") + result.turns.handled(src, failed="" if turn.status == "ok" else "SYNC_FAILED") if turn.status != "ok": _mirror_failure(src, result) return turn @@ -600,10 +598,10 @@ async def _sync_turn( ) # A refused credential is left out of the tally (`PassResult.refused_orgs`); one the # deployment's secret no longer opens is the deployment's, and counts. - if failed and turn.status == "credential_invalid" and source_ops.credential_opens(src): + if failed and turn.status == "credential_invalid" and source_ops.credential_of(src, warn=False): result.refused_orgs.add(src.org) else: - result.turns.add(src, turn.status if failed else "") + result.turns.handled(src, failed=turn.status if failed else "") if failed: result.failed += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) @@ -1606,9 +1604,9 @@ async def _retire_removed_sources( result.errors.append(f"{_cursor_of(src)}: {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: retiring %s failed: %s", _cursor_of(src), e) - result.retiring.add(src, type(e).__name__) + result.retiring.handled(src, failed=type(e).__name__) continue - result.retiring.add(src) + result.retiring.handled(src) async def _retire_all(src: KnowledgeSource, run: Pass, result: PassResult) -> None: @@ -1734,7 +1732,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass except Exception as e: # noqa: BLE001 — one source's failed read must not stop the others result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 - result.mining.add(src, type(e).__name__, whole=True) + result.mining.handled(src, failed=type(e).__name__, whole=True) continue todo = _unmined(docs, detail) # A source with nothing to mine and no stale count to clear needs no write. @@ -1767,7 +1765,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) - result.mining.add(src, type(e).__name__, whole=True) + result.mining.handled(src, failed=type(e).__name__, whole=True) continue stop = await _extract_source(src, docs, run, result) @@ -1862,11 +1860,11 @@ def may_write() -> bool: raised = type(e).__name__ # The documents it tried, and those that failed; a raise fails the source's whole try. if raised: - result.mining.add(src, raised, ran=max(mined.tries, 1), whole=True) + result.mining.handled(src, max(mined.tries, 1), failed=raised, whole=True) elif mined.tries: - result.mining.add(src, ran=mined.tries) + result.mining.handled(src, mined.tries) for reason, n in mined.reasons.items(): - result.mining.add(src, reason, ran=0, failed=n) + result.mining.fail(src, reason, n) result.extracted += mined.extracted result.flagged_pinned += mined.flagged result.unextracted += mined.unextracted diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index ede74ecf7a9..d83fb0d79bb 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -116,12 +116,6 @@ def credential_of(src: KnowledgeSource, *, warn: bool = True) -> str: return unseal(_CREDENTIAL_PURPOSE, src.credential_enc, warn=warn) -def credential_opens(src: KnowledgeSource) -> bool: - """Whether the deployment's secrets open the source's stored credential. A connected - source's credential is its person's, so it is taken as open.""" - return src.credential_mode != "shared" or bool(credential_of(src, warn=False)) - - async def credential_for(src: KnowledgeSource, *, deadline: float) -> Credential: """A connected row selects only its exact owner and generation, never shared auth.""" if src.credential_mode == "connected": diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 7fc26539993..5ffa7f07029 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -663,9 +663,9 @@ def test_a_note_names_the_kind_most_common_among_the_orgs_that_failed() -> None: two orgs whose only source failed.""" tally = source_sync.SourceTally() for i in range(7): - tally.add(_source(f"a{i}"), "rate_limited" if i < 3 else "") + tally.handled(_source(f"a{i}"), failed="rate_limited" if i < 3 else "") for org in ("b", "c"): - tally.add(dataclasses.replace(_source("x"), org=org), "failed") + tally.handled(dataclasses.replace(_source("x"), org=org), failed="failed") ctx = pass_context.begin(source_sync.WORKER) try: tally.note("sync", set()) @@ -679,9 +679,9 @@ def test_a_mining_note_names_the_kind_of_most_failed_documents() -> None: """A kind weighs the documents that failed of it, not the sources: 40 documents of one source failing outweigh two sources whose record write raised.""" tally = source_sync.SourceTally() - tally.add(_source("big"), "not_run", ran=40) + tally.handled(_source("big"), 40, failed="not_run") for name in ("s1", "s2"): - tally.add(_source(name), "ConnectionError", whole=True) + tally.handled(_source(name), failed="ConnectionError", whole=True) ctx = pass_context.begin(source_sync.WORKER) try: tally.note("mining", set(), unit="documents", least=2) diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 2ad85c4ebde..fe7d9241be0 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -445,6 +445,34 @@ async def test_each_org_reads_its_own_sources_once_per_ttl(monkeypatch) -> None: assert other.sources.failing == 7 # the route answers every org alike here +@pytest.mark.asyncio +async def test_each_read_carries_the_readiness_bound_to_clickhouse(monkeypatch) -> None: + """A read past the bound stops on the server too, so a poll after its cached + failure never runs beside the statement the last one left.""" + from server.core.ch import statement_timeout_var + + seen: dict[str, float] = {} + + def _at(name: str, rows: list[dict[str, Any]]): + def answer(sql, params): + seen[name] = statement_timeout_var.get() + return rows + + return answer + + ch = ( + RecordingCH() + .on("loom.worker_status", _at("workers", [])) + .on("sli_minute", _at("requests", [])) + ) + ch.on("loom.code_index_state", _at("sources", _FAILING)).install(monkeypatch) + + await _incidents() + + bound = settings.readiness_check_timeout_s + assert seen == {"workers": bound, "requests": bound, "sources": bound} + + @pytest.mark.asyncio async def test_a_sources_read_serves_a_minute_and_a_failed_one_is_retried_soon( monkeypatch, From 10bee68068924e6a5177654a688ab0c02edc50c1 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 23:18:11 +0530 Subject: [PATCH 22/41] ops.incidents keeps a failed read as long as an answer A failed sources read was tried again after 5 seconds while an answer was kept a minute, so a read slower than the bound ran every 5 seconds per process and reach. A failed read is now kept for its read's TTL; a cached failure names its read in degraded and never changes status. The knowledge page names the dormant-orgs case beside the one-org case, and says what ops.incidents' sources lists (the last sync turn) and what it does not (mining failures). A test covers a failed record write of documents left waiting. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 13 +++++---- docs/operations/monitoring.md | 2 +- docs/reference/http-api.md | 5 ++-- server/insights/app/incidents.py | 8 +++--- .../test_knowledge_source_sync_failures.py | 28 +++++++++++++++++++ tests/unit/test_ops_incidents.py | 8 +++--- 6 files changed, 48 insertions(+), 16 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 125c850ac04..dd478741530 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -696,9 +696,11 @@ the worker's failure streak only as part of an outage of most orgs: bound left for the next pass, has not failed. - So what most orgs' sources rely on counts: the store, a provider most of them use, the model, or the deployment's secret, when it no longer opens the stored credentials. So - does every failure where one org holds every source the pass syncs. One org's failing - sources, however many they are, never degrade the worker or `ops.incidents` for the - other orgs, and neither does an outage of a provider fewer than half the orgs use. + does every failure where one org is the only one the pass serves: it holds every + source the pass syncs, or every other org's turns were refused. Otherwise one org's + failing sources, however many they are, never degrade the worker or `ops.incidents` + for the other orgs, and neither does an outage of a provider fewer than half the orgs + use. - A source another copy holds counts neither way. - A credential the provider refuses (`credential_invalid`) on a namespace's source is its org's to rotate, so the turn is left out. An org whose every turn was refused @@ -714,8 +716,9 @@ the worker's failure streak only as part of an outage of most orgs: was: while auth is on, on a deployment with an active mirrored source, no leg's failure reaches the streak, and the pass's status row reads `SYNC_FAILED`. -Each failing source, counted or not, shows in its `status` and `extract_error` and in -its org's `ops.incidents` `sources`. +Counted or not, a source whose last sync turn failed shows in its `status` and in its +org's `ops.incidents` `sources`, and a document that failed to mine shows in its +source's `extract_error`. ### A recording source diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index bbc5ed6687f..ff0b78850e8 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -172,7 +172,7 @@ every one of the org's. That holds however many clients poll during an outage, a read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A person's reach holds their own personal collection, so each person who polls as an org admin has a read of the failing sources of their own. A read that failed is named in the response's `degraded` while its -failure is cached (5 seconds), and the other reads still answer. +failure is cached, as long as an answer would be, and the other reads still answer. The caller's collection reach, which the failing sources need, comes from the grant cache every call uses and is cut at the same bound. diff --git a/docs/reference/http-api.md b/docs/reference/http-api.md index fbdccc10d34..9bc61772c89 100644 --- a/docs/reference/http-api.md +++ b/docs/reference/http-api.md @@ -376,8 +376,9 @@ error's kind only; the full text is in the server log. - `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: `ops.incidents`' worker streaks and the org's request counts, and any - of its reads that failed; 60 seconds: its failing sources per collection reach. + - 5 seconds: `ops.incidents`' worker streaks and the org's request counts; 60 + seconds: its failing sources per collection reach. A read that failed is cached as + long. - 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/server/insights/app/incidents.py b/server/insights/app/incidents.py index e28eb26ce84..087d4e66a12 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -15,7 +15,7 @@ collection reach), so clients polling during an outage do not add load. Each read is cut at a readiness check's bound (`readiness_check_timeout_s`) on both sides, and one that does not answer within it is named in the answer's `degraded` as long as that -failure is cached (`_READ_TTL_S`); the others still answer, so the op answers during a +failure is cached; the others still answer, so the op answers during a ClickHouse outage too. The caller's collection reach, which the sources need, comes from the grant cache every call uses and is cut at the same bound. """ @@ -50,7 +50,6 @@ # or runs less often than this). # not a setting: what "current" means for a worker, documented with the op _WORKER_WINDOW_HOURS = 6 -# A failed read is tried again after it. # not a setting: polls within it share each ClickHouse read _READ_TTL_S = 5.0 # Each read parses every one of the org's sync states, their documents' maps included. @@ -84,7 +83,8 @@ async def _cached[T]( whether that read answered). Polls that arrive while it reads wait for that read rather than start their own. The server stops the read at the bound the client waits, so a poll after a slow read's failure never runs beside it. A failed read is - cached for `_READ_TTL_S`, and named in `degraded` on every answer that serves it.""" + cached as long, so a read slower than the bound is not started again sooner, and it + is named in `degraded` on every answer that serves it.""" entry = (name, key) lock = _locks.get(entry) if lock is None: @@ -94,7 +94,7 @@ async def _cached[T]( lock = _locks[entry] = asyncio.Lock() async with lock: hit = _cache.get(entry) - if hit is None or time.monotonic() - hit[0] >= (_READ_TTL_S if hit[2] else ttl): + if hit is None or time.monotonic() - hit[0] >= ttl: try: bound = settings.readiness_check_timeout_s async with asyncio.timeout(bound): diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 5ffa7f07029..b183b9ca80f 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -518,6 +518,34 @@ async def write(src: Any, mined: Any, *a: Any, **kw: Any) -> None: assert ctx.failures == _noted("mining", "ConnectionError", "2 of 2") +def test_a_failed_record_write_of_documents_left_waiting_notes_once( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """Documents left for later (mining switched off for the org) still record why they + wait; that write failing for each org's only source (a store outage) fails the + source whole.""" + world.sources = [_source("a"), dataclasses.replace(_source("c"), org="other")] + _turns(monkeypatch, set()) + + async def revisions(at: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + return [{"source_uri": f"https://docs.example.com/{tag}/0", "source_revision": "r1"}] + + async def off() -> frozenset[str]: + return frozenset({ORG, "other"}) + + async def write(src: Any, mined: Any, *a: Any, **kw: Any) -> None: + if mined is None: + raise ConnectionError("record store down") + + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + monkeypatch.setattr(source_sync.customer, "switched_off_orgs", off) + monkeypatch.setattr(source_sync, "_write_mined", write) + + _, ctx = asyncio.run(_supervised()) + + assert ctx.failures == _noted("mining", "ConnectionError", "2 of 2") + + def _documents(monkeypatch: pytest.MonkeyPatch, count: int, org: str = ORG) -> None: """Each source of `org` holds `count` unmined documents; another org's none.""" diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index fe7d9241be0..cba42504873 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -474,12 +474,12 @@ def answer(sql, params): @pytest.mark.asyncio -async def test_a_sources_read_serves_a_minute_and_a_failed_one_is_retried_soon( +async def test_a_sources_read_serves_a_minute_whether_it_answered_or_failed( monkeypatch, ) -> None: """A source's sync state changes once a pass, and each read parses every one of the - org's states: an answer serves a minute, a failed read only until the next poll - window.""" + org's states: a read serves a minute, a failed one too, so a read slower than the + bound is not started again every few seconds.""" from types import SimpleNamespace now = [1000.0] @@ -499,7 +499,7 @@ def _sources(sql, params): now[0] += step await _incidents() - assert reads == [1000.0, 1006.0, 1067.0] + assert reads == [1000.0, 1067.0] @pytest.mark.asyncio From 1cdeade5857bffb7487d7135253440233a9e8fef Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Fri, 4 Dec 2026 23:43:32 +0530 Subject: [PATCH 23/41] SourceTally.handled names a failure's kind `kind` `failed` was already the tally's counter and the turn's bool, so the keyword that holds a failure's kind is `kind`, as in `fail`. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/knowledge/app/source_sync.py | 24 +++++++++---------- .../test_knowledge_source_sync_failures.py | 8 +++---- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index d1ddfbce273..8859f0db79c 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -216,14 +216,14 @@ class SourceTally: whole: bool = False def handled( - self, src: KnowledgeSource, n: int = 1, *, failed: str = "", whole: bool = False + self, src: KnowledgeSource, n: int = 1, *, kind: str = "", whole: bool = False ) -> None: - """`n` units of a source the leg handled, every one of them failing when `failed` - names the kind (`fail`).""" + """`n` units of a source the leg handled, every one of them failing when `kind` + names a failure's kind (`fail`).""" self.ran[src.org] += n self.whole |= whole - if failed: - self.fail(src, failed, n) + if kind: + self.fail(src, kind, n) def fail(self, src: KnowledgeSource, kind: str, n: int = 1) -> None: """`n` of a source's handled units failing as `kind`: an exception's class, a @@ -571,7 +571,7 @@ async def _sync_turn( log.info("knowledge_source_sync: %s is being synced by another copy", _cursor_of(src)) return None except Exception as e: # noqa: BLE001 — one source's failure must not stop the others - result.turns.handled(src, failed="SYNC_FAILED" if mirror_synced(src) else type(e).__name__) + result.turns.handled(src, kind="SYNC_FAILED" if mirror_synced(src) else type(e).__name__) if mirror_synced(src): _mirror_failure(src, result) return None @@ -581,7 +581,7 @@ async def _sync_turn( return None if mirror_synced(src): # Every cause alike: a mirror's turn leaves no more than its one code. - result.turns.handled(src, failed="" if turn.status == "ok" else "SYNC_FAILED") + result.turns.handled(src, kind="" if turn.status == "ok" else "SYNC_FAILED") if turn.status != "ok": _mirror_failure(src, result) return turn @@ -601,7 +601,7 @@ async def _sync_turn( if failed and turn.status == "credential_invalid" and source_ops.credential_of(src, warn=False): result.refused_orgs.add(src.org) else: - result.turns.handled(src, failed=turn.status if failed else "") + result.turns.handled(src, kind=turn.status if failed else "") if failed: result.failed += 1 result.errors.append(f"{_cursor_of(src)}: {turn.status} {turn.error}".strip()) @@ -1604,7 +1604,7 @@ async def _retire_removed_sources( result.errors.append(f"{_cursor_of(src)}: {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: retiring %s failed: %s", _cursor_of(src), e) - result.retiring.handled(src, failed=type(e).__name__) + result.retiring.handled(src, kind=type(e).__name__) continue result.retiring.handled(src) @@ -1732,7 +1732,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass except Exception as e: # noqa: BLE001 — one source's failed read must not stop the others result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 - result.mining.handled(src, failed=type(e).__name__, whole=True) + result.mining.handled(src, kind=type(e).__name__, whole=True) continue todo = _unmined(docs, detail) # A source with nothing to mine and no stale count to clear needs no write. @@ -1765,7 +1765,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) - result.mining.handled(src, failed=type(e).__name__, whole=True) + result.mining.handled(src, kind=type(e).__name__, whole=True) continue stop = await _extract_source(src, docs, run, result) @@ -1860,7 +1860,7 @@ def may_write() -> bool: raised = type(e).__name__ # The documents it tried, and those that failed; a raise fails the source's whole try. if raised: - result.mining.handled(src, max(mined.tries, 1), failed=raised, whole=True) + result.mining.handled(src, max(mined.tries, 1), kind=raised, whole=True) elif mined.tries: result.mining.handled(src, mined.tries) for reason, n in mined.reasons.items(): diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index b183b9ca80f..dd478437ae4 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -691,9 +691,9 @@ def test_a_note_names_the_kind_most_common_among_the_orgs_that_failed() -> None: two orgs whose only source failed.""" tally = source_sync.SourceTally() for i in range(7): - tally.handled(_source(f"a{i}"), failed="rate_limited" if i < 3 else "") + tally.handled(_source(f"a{i}"), kind="rate_limited" if i < 3 else "") for org in ("b", "c"): - tally.handled(dataclasses.replace(_source("x"), org=org), failed="failed") + tally.handled(dataclasses.replace(_source("x"), org=org), kind="failed") ctx = pass_context.begin(source_sync.WORKER) try: tally.note("sync", set()) @@ -707,9 +707,9 @@ def test_a_mining_note_names_the_kind_of_most_failed_documents() -> None: """A kind weighs the documents that failed of it, not the sources: 40 documents of one source failing outweigh two sources whose record write raised.""" tally = source_sync.SourceTally() - tally.handled(_source("big"), 40, failed="not_run") + tally.handled(_source("big"), 40, kind="not_run") for name in ("s1", "s2"): - tally.handled(_source(name), failed="ConnectionError", whole=True) + tally.handled(_source(name), kind="ConnectionError", whole=True) ctx = pass_context.begin(source_sync.WORKER) try: tally.note("mining", set(), unit="documents", least=2) From b81b76b570e89db8c37f9e162032ea531ba12d6f Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 00:18:18 +0530 Subject: [PATCH 24/41] ops.incidents' sources TTL test uses the shared ManualClock The test built its own clock; the tests rule sends time through tests/unit/clock_fake.py. It still patches the module's time, so asyncio.timeout keeps the loop's clock. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- tests/unit/test_ops_incidents.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index cba42504873..24759d86d01 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -24,6 +24,7 @@ from server.operations.registry import OPERATIONS_BY_NAME from server.settings import settings from tests.unit.ch_fake import RecordingCH, server_error +from tests.unit.clock_fake import ManualClock def _token( @@ -480,14 +481,12 @@ async def test_a_sources_read_serves_a_minute_whether_it_answered_or_failed( """A source's sync state changes once a pass, and each read parses every one of the org's states: a read serves a minute, a failed one too, so a read slower than the bound is not started again every few seconds.""" - from types import SimpleNamespace - - now = [1000.0] - monkeypatch.setattr(incidents, "time", SimpleNamespace(monotonic=lambda: now[0])) + clock = ManualClock(t=1000.0) + monkeypatch.setattr(incidents, "time", clock) # not time.monotonic: asyncio.timeout reads that reads: list[float] = [] def _sources(sql, params): - reads.append(now[0]) + reads.append(clock.t) if len(reads) == 1: raise server_error("Connection refused", code=210) return _FAILING @@ -496,7 +495,7 @@ def _sources(sql, params): ch.on("loom.code_index_state", _sources).install(monkeypatch) for step in (0, 6, 50, 11): - now[0] += step + clock.advance(step) await _incidents() assert reads == [1000.0, 1067.0] From 9ce782c367877a7762ecaca5bf39a495c59747a7 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 00:44:29 +0530 Subject: [PATCH 25/41] ops.incidents keys its sources read without the caller's own collection sharing.readable adds each end user's personal collection to the reach, so every org admin had a read of the failing sources of their own. A personal collection holds no source (PERSONAL_NAMESPACE), so it is left out: admins with the same grants share one read, and the answer is the same. The TTL test now also checks that an answered read serves a minute, and the monitoring page says each cache is per process. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 18 +++++++++--------- server/insights/app/incidents.py | 7 ++++++- tests/unit/test_ops_incidents.py | 25 +++++++++++++++++++++++-- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index ff0b78850e8..37d421ff6f8 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -164,15 +164,15 @@ token (never an org admin) and a `*` token that names no org read none. The othe 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 of its -ClickHouse reads runs at most once every 5 seconds per process (the worker streaks) or -per org (the request counts), and the failing sources once a minute per org and -collection reach, since a source's sync state changes once a pass and each read parses -every one of the org's. That holds however many clients poll during an outage, and each -read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. A person's reach holds their own -personal collection, so each person who polls as an org admin has a read of the failing -sources of their own. A read that failed is named in the response's `degraded` while its -failure is cached, as long as an answer would be, and the other reads still answer. +`/v1/health?include=workers` shows only the answering process's workers. In each +process, each of its ClickHouse reads runs at most once every 5 seconds (the worker +streaks, and the request counts per org), and the failing sources once a minute per org +and collection reach, since a source's sync state changes once a pass and each read +parses every one of the org's. A person's own collection holds no source and is left out +of the reach, so org admins with the same grants share a read. That holds however many +clients poll during an outage, and each read is cut at `LOOM_READINESS_CHECK_TIMEOUT_S`. +A read that failed is named in the response's `degraded` while its failure is cached, as +long as an answer would be, and the other reads still answer. The caller's collection reach, which the failing sources need, comes from the grant cache every call uses and is cut at the same bound. diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 087d4e66a12..f14404f8775 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -269,7 +269,7 @@ async def _sources_read(org: str) -> OpsIncidentSources: a read and none is served a wider one. A reach that could not be read is `unread`: `sharing.readable` answers an unread tree or grant as no shared collection, which would be a narrower count passed off as the whole.""" - from server.auth import fail_closed + from server.auth import fail_closed, sharing from server.auth.context import collection_clause fail_closed.reset() @@ -280,6 +280,11 @@ async def _sources_read(org: str) -> OpsIncidentSources: return _sources_unread(error_kind(e)) if fail_closed.unreadable(): return _sources_unread("CollectionsUnread") + if scope: + # A person's own collection holds no source: left out, so callers with the same + # grants share a read. + shared = [ns for ns in params["col_readable"] if not sharing.is_personal(ns)] + params = {**params, "col_readable": shared} # The readable collections the statement runs with; no clause reads every one. reach = ",".join(params["col_readable"]) if scope else "*" sources, _ = await _cached( diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 24759d86d01..8f0a8ee16e4 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -16,6 +16,7 @@ from server.auth.jwt import AuthInfo, TokenError from server.core import readiness from server.core.errors import BackendUnavailableError, WrongCellError +from server.core.principals import personal_name from server.insights.api.models_ops import OpsIncidentsInput, OpsIncidentsOutput from server.insights.app import incidents from server.insights.app.incidents import handle_ops_incidents @@ -494,11 +495,11 @@ def _sources(sql, params): ch = RecordingCH().on("loom.worker_status", []).on("sli_minute", []) ch.on("loom.code_index_state", _sources).install(monkeypatch) - for step in (0, 6, 50, 11): + for step in (0, 6, 50, 11, 6, 53, 1): clock.advance(step) await _incidents() - assert reads == [1000.0, 1067.0] + assert reads == [1000.0, 1067.0, 1127.0] @pytest.mark.asyncio @@ -521,6 +522,26 @@ async def test_a_collection_the_caller_holds_no_grant_for_is_left_out(monkeypatc assert "col_prefix" not in platform.params and "col_prefix" not in platform.sql +@pytest.mark.asyncio +async def test_org_admins_with_the_same_grants_share_a_read_whatever_their_own_collection( + monkeypatch, +) -> None: + """A person's own collection holds no source (`_source_refusal`), so it neither keys + the read nor joins the statement: each admin reaching it does not add a read.""" + + async def readable(auth, org): + return sorted(["col-board", personal_name(org, auth.subject)]) + + monkeypatch.setattr("server.auth.sharing.readable", readable) + ch = _ch(monkeypatch, sources=_FAILING) + + await _incidents() + await _incidents(auth=_token(roles=(Role.ORG_ADMIN,), subject="other-admin")) + + (read,) = ch.statements("loom.code_index_state") + assert read.params["col_readable"] == ["col-board"] + + @pytest.mark.asyncio @pytest.mark.parametrize( "down", From 9dbeb47b0fa8792807545556ce03d353fc7c2d90 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:15:31 +0530 Subject: [PATCH 26/41] ops.incidents' docstring keys the worker streaks per process, not per org The worker streaks are cached under one key for every org; the module docstring and the cache comment said each read is per org. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- server/insights/app/incidents.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index f14404f8775..5addd5de359 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -9,9 +9,9 @@ the answer `degraded`. Nothing names another org: a provider or worker incident carries an error's kind, never its text, and the request counts and the sources 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; a source names its namespace). Each of its ClickHouse reads (the -worker streaks, the org's request counts) runs at most once per `_READ_TTL_S` per -process (per org), and the failing sources once per `_SOURCES_TTL_S` (per org and +no namespace or user; a source names its namespace). In each process, each of its +ClickHouse reads runs at most once per `_READ_TTL_S` (the worker streaks, and per org the +request counts), and the failing sources once per `_SOURCES_TTL_S` (per org and collection reach), so clients polling during an outage do not add load. Each read is cut at a readiness check's bound (`readiness_check_timeout_s`) on both sides, and one that does not answer within it is named in the answer's `degraded` as long as that @@ -61,8 +61,8 @@ _CACHE_MAX = 1024 # (read, key) -> (read at, what it read, the read's failure or ""), and the lock its -# polls share while one reads; the key is the org, for the sources the org and the -# caller's collection reach +# polls share while one reads; the key is the org (`""` for the worker streaks), for the +# sources the org and the caller's collection reach _cache: dict[tuple[str, str], tuple[float, Any, str]] = {} _locks: dict[tuple[str, str], asyncio.Lock] = {} From a914509bde70707ccb8794d269abc441965e3465 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:36:59 +0530 Subject: [PATCH 27/41] SourceTally names its flag failed_whole; the refusal test reads as one `whole` read as the tally being complete; it says a source's mining failed whole, so the leg is judged however few units it handled. The provider-refusal test gave its turn the text of a credential that no longer opens, the next test's case. The knowledge page says a private pass reads SYNC_FAILED only when a leg failed. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 2 +- server/knowledge/app/source_sync.py | 14 +++++++------- tests/unit/test_knowledge_source_sync_failures.py | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index dd478741530..61f5462a7eb 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -714,7 +714,7 @@ the worker's failure streak only as part of an outage of most orgs: while fewer than half the orgs have changed documents is not counted. - A pass that runs any mirrored turn is private, and the worker's streak stays as it was: while auth is on, on a deployment with an active mirrored source, no leg's failure - reaches the streak, and the pass's status row reads `SYNC_FAILED`. + reaches the streak, and a pass with a failed leg reads `SYNC_FAILED` in its status row. Counted or not, a source whose last sync turn failed shows in its `status` and in its org's `ops.incidents` `sources`, and a document that failed to mine shows in its diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 8859f0db79c..6b608e6f2d2 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -213,15 +213,15 @@ class SourceTally: kinds: defaultdict[str, Counter[str]] = field(default_factory=lambda: defaultdict(Counter)) # A source failed whole (its mining's read, write or raise): the leg is judged however # few units it handled. - whole: bool = False + failed_whole: bool = False def handled( - self, src: KnowledgeSource, n: int = 1, *, kind: str = "", whole: bool = False + self, src: KnowledgeSource, n: int = 1, *, kind: str = "", failed_whole: bool = False ) -> None: """`n` units of a source the leg handled, every one of them failing when `kind` names a failure's kind (`fail`).""" self.ran[src.org] += n - self.whole |= whole + self.failed_whole |= failed_whole if kind: self.fail(src, kind, n) @@ -239,7 +239,7 @@ def note(self, leg: str, orgs: set[str], *, unit: str = "sources", least: int = with those the leg ran for) had most of their units fail.""" serving = orgs | set(self.ran) failing = [o for o, n in self.ran.items() if self.failed[o] * 2 > n] - judged = self.whole or sum(self.ran.values()) >= least + judged = self.failed_whole or sum(self.ran.values()) >= least if judged and len(failing) * 2 > len(serving): # The kind most common in the orgs that failed, not in those that did not. kind = sum((self.kinds[o] for o in failing), Counter[str]()).most_common(1)[0][0] @@ -1732,7 +1732,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass except Exception as e: # noqa: BLE001 — one source's failed read must not stop the others result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 - result.mining.handled(src, kind=type(e).__name__, whole=True) + result.mining.handled(src, kind=type(e).__name__, failed_whole=True) continue todo = _unmined(docs, detail) # A source with nothing to mine and no stale count to clear needs no write. @@ -1765,7 +1765,7 @@ async def _extract_pending(order: list[KnowledgeSource], run: Pass, result: Pass result.errors.append(f"{_cursor_of(src)}: extraction {type(e).__name__}") result.failed += 1 log.warning("knowledge_source_sync: recording %s failed: %s", _cursor_of(src), e) - result.mining.handled(src, kind=type(e).__name__, whole=True) + result.mining.handled(src, kind=type(e).__name__, failed_whole=True) continue stop = await _extract_source(src, docs, run, result) @@ -1860,7 +1860,7 @@ def may_write() -> bool: raised = type(e).__name__ # The documents it tried, and those that failed; a raise fails the source's whole try. if raised: - result.mining.handled(src, max(mined.tries, 1), kind=raised, whole=True) + result.mining.handled(src, max(mined.tries, 1), kind=raised, failed_whole=True) elif mined.tries: result.mining.handled(src, mined.tries) for reason, n in mined.reasons.items(): diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index dd478437ae4..ea2df4bcfa0 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -161,7 +161,7 @@ def test_refused_credentials_in_most_orgs_are_no_failure_of_the_worker( async def turn(src: KnowledgeSource, state: Any, run: Any) -> source_sync.TurnResult: out = source_sync.TurnResult() if src.name in {"a", "b"}: - out.fail("credential_invalid", "the stored credential no longer opens; rotate it") + out.fail("credential_invalid", "the provider refused the credential") return out monkeypatch.setattr(source_sync, "_turn_of", lambda src: turn) @@ -709,7 +709,7 @@ def test_a_mining_note_names_the_kind_of_most_failed_documents() -> None: tally = source_sync.SourceTally() tally.handled(_source("big"), 40, kind="not_run") for name in ("s1", "s2"): - tally.handled(_source(name), kind="ConnectionError", whole=True) + tally.handled(_source(name), kind="ConnectionError", failed_whole=True) ctx = pass_context.begin(source_sync.WORKER) try: tally.note("mining", set(), unit="documents", least=2) From 91e2666baadf95bd923250726b9683450b45f088 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 01:58:49 +0530 Subject: [PATCH 28/41] ops.incidents docs name an unread reach as a cause of unread sources The monitoring page said sources.read answers as requests does; it is also unread when the caller's collection grants are not read within the readiness bound. The reach test's docstring said no caller is served another's read, while its third caller shares the first one's. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 8 +++++--- tests/unit/test_ops_incidents.py | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 37d421ff6f8..2ace3dfacb1 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -187,9 +187,11 @@ failed: `failing`, how many, and `sample`, at most 5 of them (`{namespace, name, status}`), the latest failure first, with `status` `failed`, `rate_limited` or `credential_invalid`. It counts only the sources every reader of their namespace sees, never a mirrored or a person's connected one. It is read under the same rule as the -request counts, and `sources.read` answers in the same words. It leaves out the -collections the caller holds no grant for, since an org admin reaches a collection only -through a grant (a platform admin reads every one). A failing document source is never +request counts, and `sources.read` answers in the same words; it is also `unread` when +the caller's collection grants could not be read within +`LOOM_READINESS_CHECK_TIMEOUT_S`. It leaves out the collections the caller holds no +grant for, since an org admin reaches a collection only through a grant (a platform +admin reads every one). A failing document source is never an incident and never by itself makes `status` `degraded`: a revoked credential is its org's to rotate, and `status` stays Loom's own health. The `knowledge_source_sync` worker becomes a `worker` incident after 3 failed passes in a row, like any worker. A diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index 8f0a8ee16e4..cd391d6b195 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -505,8 +505,8 @@ def _sources(sql, params): @pytest.mark.asyncio async def test_a_collection_the_caller_holds_no_grant_for_is_left_out(monkeypatch) -> None: """An org admin reaches a collection only through a grant, so the sources of the - others are neither counted nor named; a platform admin reads every collection. Each - caller's answer is its own: it is never served from another caller's read.""" + others are neither counted nor named; a platform admin reads every collection. A + caller is never served the read of a wider reach: one with the same reach shares it.""" monkeypatch.setattr("server.auth.sharing.readable", AsyncMock(return_value=["col-board"])) ch = _ch(monkeypatch, sources=_FAILING) From 65431a04143054a979c0962eb52405c840622723 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:21:05 +0530 Subject: [PATCH 29/41] The knowledge page says where a failed retirement of a source shows A failed retirement writes no sync state, so the page names the server's log, the pass's failed count and SOURCE_DELETE_PENDING. A single org's failures note the pass only when most of its sources, or of the documents it tried, fail; the page said every failure did. The test module's docstring names mining's units too. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 9 ++++++--- tests/unit/test_knowledge_source_sync_failures.py | 7 ++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 61f5462a7eb..8b9d5618200 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -696,8 +696,9 @@ the worker's failure streak only as part of an outage of most orgs: bound left for the next pass, has not failed. - So what most orgs' sources rely on counts: the store, a provider most of them use, the model, or the deployment's secret, when it no longer opens the stored credentials. So - does every failure where one org is the only one the pass serves: it holds every - source the pass syncs, or every other org's turns were refused. Otherwise one org's + does a failure of most of an org's sources, or of the documents it tried, where that + org is the only one the pass serves: it holds every source the pass syncs, or every + other org's turns were refused. Otherwise one org's failing sources, however many they are, never degrade the worker or `ops.incidents` for the other orgs, and neither does an outage of a provider fewer than half the orgs use. @@ -718,7 +719,9 @@ the worker's failure streak only as part of an outage of most orgs: Counted or not, a source whose last sync turn failed shows in its `status` and in its org's `ops.incidents` `sources`, and a document that failed to mine shows in its -source's `extract_error`. +source's `extract_error`. A removed source whose documents could not be retired shows +in the server's log and in the pass's `failed` count, and `add` with its name answers +`SOURCE_DELETE_PENDING` until its documents are retired; the next pass tries again. ### A recording source diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index ea2df4bcfa0..07e282dfc2e 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -3,9 +3,10 @@ A source whose turn failed has its failure in its own sync state (`status`, `error`), which its namespace's readers see; the pass notes no failure for it. Each leg of the pass (the sync turns, the mining, the retirement of removed sources) notes one failure -only when most of the orgs the pass serves had most of their sources fail: an outage of -what every source relies on, or a deployment with a single org. One org's failures, however -many of the sources are its own, are no failure of the worker every org shares.""" +only when most of the orgs the pass serves had most of their units (sources, or the +documents mining tried) fail: an outage of what every source relies on, or a deployment +with a single org. One org's failures, however many of the sources are its own, are no +failure of the worker every org shares.""" from __future__ import annotations From 0f0ea2958df8dfdd6b54ad4581c90e4f15fa0ed3 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 02:43:31 +0530 Subject: [PATCH 30/41] A failed retirement is judged against the orgs it retired for Nothing a tenant does fails a retirement: it deletes Loom's own copies with no credential. Judged against every org the pass serves, the failure only this leg catches, a bug in retiring one org's documents, could never be noted, since a store outage broad enough to reach most orgs already fails the sync leg. The leg now serves only the orgs whose removed sources it retired. SourceTally.fail takes its count before its kind, as handled does. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 21 ++++++++------ docs/operations/monitoring.md | 2 +- server/knowledge/app/source_sync.py | 15 ++++++---- .../test_knowledge_source_sync_failures.py | 28 +++++++++++-------- 4 files changed, 39 insertions(+), 27 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 8b9d5618200..20ba3f03e4c 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -691,17 +691,20 @@ the worker's failure streak only as part of an outage of most orgs: for the mining the documents it tried. The worker's status row then reads `SourcesFailed`, with an error that names the leg, such as `sync: failed for most sources in 3 of 4 orgs (most often failed)`. -- A leg serves the orgs with a source the pass syncs and those it ran for, such as an - org whose removed source it retires. An org it had nothing to do for, or that the pass - bound left for the next pass, has not failed. +- The sync turns and the mining serve the orgs with a source the pass syncs and those + they ran for. An org a leg had nothing to do for, or that the pass bound left for the + next pass, has not failed. +- The retirement serves only the orgs whose removed sources it retired: nothing a + tenant does fails a retirement, which deletes Loom's own copies with no credential, so + one org's failing retirement fails the pass unless most of the orgs it retired for + succeeded. - So what most orgs' sources rely on counts: the store, a provider most of them use, the model, or the deployment's secret, when it no longer opens the stored credentials. So does a failure of most of an org's sources, or of the documents it tried, where that org is the only one the pass serves: it holds every source the pass syncs, or every - other org's turns were refused. Otherwise one org's - failing sources, however many they are, never degrade the worker or `ops.incidents` - for the other orgs, and neither does an outage of a provider fewer than half the orgs - use. + other org's turns were refused. Otherwise one org's failing sources, however many + they are, never degrade the worker or `ops.incidents` for the other orgs, and neither + does an outage of a provider fewer than half the orgs use. - A source another copy holds counts neither way. - A credential the provider refuses (`credential_invalid`) on a namespace's source is its org's to rotate, so the turn is left out. An org whose every turn was refused @@ -720,8 +723,8 @@ the worker's failure streak only as part of an outage of most orgs: Counted or not, a source whose last sync turn failed shows in its `status` and in its org's `ops.incidents` `sources`, and a document that failed to mine shows in its source's `extract_error`. A removed source whose documents could not be retired shows -in the server's log and in the pass's `failed` count, and `add` with its name answers -`SOURCE_DELETE_PENDING` until its documents are retired; the next pass tries again. +in the server's log, and `add` with its name answers `SOURCE_DELETE_PENDING` until its +documents are retired; the next pass tries again. ### A recording source diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 2ace3dfacb1..3a514b06f2b 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -196,7 +196,7 @@ an incident and never by itself makes `status` `degraded`: a revoked credential org's to rotate, and `status` stays Loom's own health. The `knowledge_source_sync` worker becomes a `worker` incident after 3 failed passes in a row, like any worker. A pass fails when it fails outright (its source list or registry unread, or past its -deadline), or when most orgs' sources fail, as +deadline), or when a leg of it fails for most of the orgs it serves, as [source failures and the worker's health](../features/knowledge.md#source-failures-and-the-workers-health) describes. diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 6b608e6f2d2..e19bb5b09b2 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -193,8 +193,9 @@ class SourceGone(Exception): class SourcesFailed(RuntimeError): """A leg of the pass failed for most of what it handled (sources, or for the mining - documents tried) in most orgs: its one failure note. A source's failure is in its - sync state, and one org's failures are its own unless most orgs' fail.""" + documents tried) in most of the orgs it serves: its one failure note. A source's + failure is in its sync state, and one org's failures are its own unless most orgs' + fail; a retirement, which no tenant fails, serves only the orgs it retired for.""" # not a setting: one document tried tells nothing of the model, so a pass's mining is @@ -223,9 +224,9 @@ def handled( self.ran[src.org] += n self.failed_whole |= failed_whole if kind: - self.fail(src, kind, n) + self.fail(src, n, kind=kind) - def fail(self, src: KnowledgeSource, kind: str, n: int = 1) -> None: + def fail(self, src: KnowledgeSource, n: int = 1, *, kind: str) -> None: """`n` of a source's handled units failing as `kind`: an exception's class, a turn's status, `SYNC_FAILED` for a mirrored source, or a mining reason (`not_run`, `refused`, `out_of_time`, `too_large_for_pass`, `failed:`); @@ -461,7 +462,9 @@ async def run_sync( pass_context.set_cursor(_cursor_of(src)) break orgs -= result.refused_orgs - set(result.turns.ran) # see `PassResult.refused_orgs` - result.retiring.note("retirement", orgs) + # Nothing a tenant does fails a retirement (it deletes Loom's own copies, with no + # credential), so it is judged against the orgs it retired for alone. + result.retiring.note("retirement", set()) result.turns.note("sync", orgs) await _extract_pending(order, run, result) result.mining.note("mining", orgs, unit="documents", least=_LEAST_TRIES) @@ -1864,7 +1867,7 @@ def may_write() -> bool: elif mined.tries: result.mining.handled(src, mined.tries) for reason, n in mined.reasons.items(): - result.mining.fail(src, reason, n) + result.mining.fail(src, n, kind=reason) result.extracted += mined.extracted result.flagged_pinned += mined.flagged result.unextracted += mined.unextracted diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 07e282dfc2e..12d3898446a 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -3,10 +3,11 @@ A source whose turn failed has its failure in its own sync state (`status`, `error`), which its namespace's readers see; the pass notes no failure for it. Each leg of the pass (the sync turns, the mining, the retirement of removed sources) notes one failure -only when most of the orgs the pass serves had most of their units (sources, or the -documents mining tried) fail: an outage of what every source relies on, or a deployment -with a single org. One org's failures, however many of the sources are its own, are no -failure of the worker every org shares.""" +only when most of the orgs it serves had most of their units (sources, or the documents +mining tried) fail: an outage of what every source relies on, or a deployment with a +single org. One org's failures, however many of the sources are its own, are no failure +of the worker every org shares. A retirement, which no tenant fails, serves only the +orgs it retired for.""" from __future__ import annotations @@ -665,26 +666,31 @@ async def retire(src: KnowledgeSource, run: Any, result: Any) -> None: assert ctx.failures == (_noted("retirement", "ConnectionError") if failing == "abc" else []) -def test_one_orgs_failed_retirement_is_not_the_others_failure( - world: _World, monkeypatch: pytest.MonkeyPatch +@pytest.mark.parametrize("other_retires", [False, True], ids=["alone", "beside_another"]) +def test_a_failed_retirement_is_judged_against_the_orgs_it_ran_for( + world: _World, monkeypatch: pytest.MonkeyPatch, other_retires: bool ) -> None: - """Only one org has a removed source, and its retirement fails every pass: the other - org, which the leg has nothing to do for, has not failed.""" + """Nothing a tenant does fails a retirement: it deletes Loom's own copies, with no + credential. An org with no removed source does not dilute it, so one org's retirement + failing is the worker's failure, unless most of the orgs it retired for succeeded.""" world.sources = [ dataclasses.replace(_source("gone"), active=False, pending_delete=True), - dataclasses.replace(_source("c"), org="other"), + dataclasses.replace( + _source("c"), org="other", active=not other_retires, pending_delete=other_retires + ), ] _turns(monkeypatch, set()) async def retire(src: KnowledgeSource, run: Any, result: Any) -> None: - raise ConnectionError("store down") + if src.org == ORG: + raise ConnectionError("store down") monkeypatch.setattr(source_sync, "_retire_all", retire) result, ctx = asyncio.run(_supervised()) assert result.errors[:1] == [f"{ORG}/{NS}/gone: ConnectionError"] - assert ctx.failures == [] + assert ctx.failures == ([] if other_retires else _noted("retirement", "ConnectionError")) def test_a_note_names_the_kind_most_common_among_the_orgs_that_failed() -> None: From 99f6d158f8a6a1a1ae6ef09045e771866f377010 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:03:16 +0530 Subject: [PATCH 31/41] Docs state the retirement rule as SourceTally.note applies it A failing retirement fails the pass when it fails for most of the orgs it retired for; half is not most. The knowledge page and the OpsIncidentSources docstring name it beside the other ways one org's failures fail the pass, and the orgs comment in run_sync names the legs judged against them. The Go models' schema hash follows the docstring. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 11 ++++++----- sdk/go/wire/models.gen.go | 2 +- server/insights/api/models_ops.py | 7 ++++--- server/knowledge/app/source_sync.py | 2 +- tests/unit/test_knowledge_source_sync_failures.py | 2 +- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 20ba3f03e4c..dd2f70407cb 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -696,15 +696,16 @@ the worker's failure streak only as part of an outage of most orgs: next pass, has not failed. - The retirement serves only the orgs whose removed sources it retired: nothing a tenant does fails a retirement, which deletes Loom's own copies with no credential, so - one org's failing retirement fails the pass unless most of the orgs it retired for - succeeded. + one org's failing retirement fails the pass when it fails for most of the orgs it + retired for, as when that org is the only one retiring. - So what most orgs' sources rely on counts: the store, a provider most of them use, the model, or the deployment's secret, when it no longer opens the stored credentials. So does a failure of most of an org's sources, or of the documents it tried, where that org is the only one the pass serves: it holds every source the pass syncs, or every - other org's turns were refused. Otherwise one org's failing sources, however many - they are, never degrade the worker or `ops.incidents` for the other orgs, and neither - does an outage of a provider fewer than half the orgs use. + other org's turns were refused, and so does the failing retirement above. Otherwise + one org's failing sources, however many they are, never degrade the worker or + `ops.incidents` for the other orgs, and neither does an outage of a provider fewer + than half the orgs use. - A source another copy holds counts neither way. - A credential the provider refuses (`credential_invalid`) on a namespace's source is its org's to rotate, so the turn is left out. An org whose every turn was refused diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index c3380f431b9..68ed5d7ebeb 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: 4ba72f35bcad77b3e7a44373de355ae66a3b5ca37d711cb7e051a77719f4cb3a +// Registry model schema SHA-256: b95a199ff15fbbfecd34c288d695dfaeb59022ff11df10386f1ebec5ed84f694 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 6caf5f6d284..f73f9d33aa7 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -217,9 +217,10 @@ class OpsIncidentSources(BaseModel): and the collections the caller reads. A source's failure is its own (its `sync.status` in `knowledge.source.list`), so it never makes `status` `degraded` by itself: a revoked credential is its org's to fix, not a Loom outage. The sync worker - becomes an incident after 3 failed passes in a row: a pass that fails outright, or - one in which most orgs' sources fail (an outage, or a deployment where one org holds - every synced source).""" + becomes an incident after 3 failed passes in a row: a pass that fails outright, one + in which most orgs' sources fail (an outage, or a deployment where one org holds + every synced source), or one whose retirement of removed sources fails for most of + the orgs it retired for.""" # Sources whose last turn failed; 0 unless `read` is `read`. failing: int = 0 diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index e19bb5b09b2..832984b0f94 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -427,7 +427,7 @@ async def run_sync( await repo_registry.refresh_db_repos() require_registry_read() usable = await _usable(found) - # The orgs the pass serves: each leg's failure note counts against them. + # The orgs the pass serves: the sync and mining notes count against them. orgs = {s.org for s in usable} if full: for src in usable: diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 12d3898446a..8317c68dc41 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -672,7 +672,7 @@ def test_a_failed_retirement_is_judged_against_the_orgs_it_ran_for( ) -> None: """Nothing a tenant does fails a retirement: it deletes Loom's own copies, with no credential. An org with no removed source does not dilute it, so one org's retirement - failing is the worker's failure, unless most of the orgs it retired for succeeded.""" + failing is the worker's failure when it fails for most of the orgs it retired for.""" world.sources = [ dataclasses.replace(_source("gone"), active=False, pending_delete=True), dataclasses.replace( From dee323d1b07eb0b7233957ac4564d8630c631c01 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:24:37 +0530 Subject: [PATCH 32/41] OpsIncidentSources names the mining leg among a pass's failures A pass whose tried documents fail to mine in most orgs fails it too. The knowledge page sets the failing retirement apart from the two ways one org becomes the only org the pass serves. The Go models' schema hash follows the docstring. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 4 ++-- sdk/go/wire/models.gen.go | 2 +- server/insights/api/models_ops.py | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index dd2f70407cb..51238340984 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -702,8 +702,8 @@ the worker's failure streak only as part of an outage of most orgs: model, or the deployment's secret, when it no longer opens the stored credentials. So does a failure of most of an org's sources, or of the documents it tried, where that org is the only one the pass serves: it holds every source the pass syncs, or every - other org's turns were refused, and so does the failing retirement above. Otherwise - one org's failing sources, however many they are, never degrade the worker or + other org's turns were refused. So does the failing retirement above. Otherwise one + org's failing sources, however many they are, never degrade the worker or `ops.incidents` for the other orgs, and neither does an outage of a provider fewer than half the orgs use. - A source another copy holds counts neither way. diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 68ed5d7ebeb..afdd2b0bad1 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: b95a199ff15fbbfecd34c288d695dfaeb59022ff11df10386f1ebec5ed84f694 +// Registry model schema SHA-256: 0d3e6d96beac3208e535f0b5d41adef69a663f824d53b375d5b81cd8c17149c4 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index f73f9d33aa7..9285bad1a1e 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -219,8 +219,8 @@ class OpsIncidentSources(BaseModel): itself: a revoked credential is its org's to fix, not a Loom outage. The sync worker becomes an incident after 3 failed passes in a row: a pass that fails outright, one in which most orgs' sources fail (an outage, or a deployment where one org holds - every synced source), or one whose retirement of removed sources fails for most of - the orgs it retired for.""" + every synced source), one in which most orgs' tried documents fail to mine, or one + whose retirement of removed sources fails for most of the orgs it retired for.""" # Sources whose last turn failed; 0 unless `read` is `read`. failing: int = 0 From 367e4fe12125c628f557b243b3579e6f1f432424 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 03:46:45 +0530 Subject: [PATCH 33/41] ops.incidents' description leaves the platform admin out of the grant rule A platform admin reads every collection; only an org admin's sources leave out the collections it holds no grant for. _org_reads names its read verdict `whole`, so `reach` means the collection reach alone, and the SourcesFailed docstring reads as one clause. The Go models' schema hash follows the description. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- sdk/go/wire/models.gen.go | 2 +- server/insights/api/models_ops.py | 5 +++-- server/insights/app/incidents.py | 6 +++--- server/knowledge/app/source_sync.py | 4 ++-- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index afdd2b0bad1..4b616c46965 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: 0d3e6d96beac3208e535f0b5d41adef69a663f824d53b375d5b81cd8c17149c4 +// Registry model schema SHA-256: e439009fd392c29f100901e7a4b65bdd52b4e9657218bdf42408ec9a8750db47 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 9285bad1a1e..487cdea2718 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -170,8 +170,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; beside them, the org's document sources whose last sync failed. Only a caller that reads the org whole (an org admin over `*`, a platform - admin) reads the calls and the sources, and the sources leave out the collections it - holds no grant for; `requests` and `sources.read` say whether they were read. + admin) reads the calls and the sources, and for an org admin the sources leave out the + collections it holds no grant for; `requests` and `sources.read` say whether they were + read. Identity is optional: the org is the token's (role check only; no namespace is addressed).""" diff --git a/server/insights/app/incidents.py b/server/insights/app/incidents.py index 5addd5de359..0043bff4c2b 100644 --- a/server/insights/app/incidents.py +++ b/server/insights/app/incidents.py @@ -303,9 +303,9 @@ async def _org_reads( """The org's request incidents, whether its counts were read, and its failing sources. 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.""" - reach: OrgRead = await _reads_org_whole(org) if org and org != "*" else "not_permitted" - if reach != "read": - return [], reach, OpsIncidentSources(read=reach) + whole: OrgRead = await _reads_org_whole(org) if org and org != "*" else "not_permitted" + if whole != "read": + return [], whole, OpsIncidentSources(read=whole) (calls, answered), sources = await asyncio.gather( _cached("requests", org, lambda: _requests(org, minutes), list[OpsIncident]()), _sources_read(org), diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 832984b0f94..23c857867dc 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -192,8 +192,8 @@ class SourceGone(Exception): class SourcesFailed(RuntimeError): - """A leg of the pass failed for most of what it handled (sources, or for the mining - documents tried) in most of the orgs it serves: its one failure note. A source's + """A leg of the pass failed for most of what it handled (sources, or, for the mining, + the documents tried) in most of the orgs it serves: its one failure note. A source's failure is in its sync state, and one org's failures are its own unless most orgs' fail; a retirement, which no tenant fails, serves only the orgs it retired for.""" From 130e7c691d2db0726ab765620dabdb6f67bbdc64 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:09:55 +0530 Subject: [PATCH 34/41] The analyzer's sources scope is pinned to collection_clause The corpus case copied the org admin fragment by hand; it is a named constant now, and a unit test asserts collection_clause builds it. OpsIncidentSources says a pass that runs a mirrored turn leaves the streak as it was, and the knowledge page says a lost folder ends its turn failed and counts like a provider's error. The Go models' schema hash follows the docstring. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 3 +++ sdk/go/wire/models.gen.go | 2 +- server/insights/api/models_ops.py | 3 ++- tests/analyzer/cases/workers.py | 15 +++++++++------ tests/unit/test_ops_incidents.py | 15 +++++++++++++++ 5 files changed, 30 insertions(+), 8 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 51238340984..47bdcaeb824 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -713,6 +713,9 @@ the worker's failure streak only as part of an outage of most orgs: so dormant orgs never hide an outage of the active ones. A refusal every org's credentials share, such as a provider refusing every token exchange of a host whose clock is off, is not counted either. +- A folder or shared drive the account no longer sees ends its turn `failed`, which + counts like a provider's error: on a deployment where most orgs' sources lost their + folders, the sync leg fails every pass until they are fixed or removed. - The mining leg is judged from two documents tried in the pass, or from one source that failed whole: its documents unread, its record unwritten, or its mining raised. The only document a pass tries failing to mine is that document's, and a model outage diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 4b616c46965..80b5bba77e9 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: e439009fd392c29f100901e7a4b65bdd52b4e9657218bdf42408ec9a8750db47 +// Registry model schema SHA-256: 5bffc07dadfc8f26430933b4098df552c2b9621ca0e33d4fc9a2d4c18cf4c01f // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index 487cdea2718..fa8049cd54a 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -221,7 +221,8 @@ class OpsIncidentSources(BaseModel): becomes an incident after 3 failed passes in a row: a pass that fails outright, one in which most orgs' sources fail (an outage, or a deployment where one org holds every synced source), one in which most orgs' tried documents fail to mine, or one - whose retirement of removed sources fails for most of the orgs it retired for.""" + whose retirement of removed sources fails for most of the orgs it retired for. While + auth is on, a pass that runs a mirrored source's turn leaves the streak as it was.""" # Sources whose last turn failed; 0 unless `read` is `read`. failing: int = 0 diff --git a/tests/analyzer/cases/workers.py b/tests/analyzer/cases/workers.py index 70381bdc50d..59cd602c80e 100644 --- a/tests/analyzer/cases/workers.py +++ b/tests/analyzer/cases/workers.py @@ -10,6 +10,14 @@ from tests.analyzer.cases._common import NS, ORG, rows_by_substring from tests.analyzer.corpus import Case, RecordingCH +# The fragment `collection_clause` gives an org admin with one grant (pinned to the builder +# in tests/unit/test_ops_incidents.py). +SOURCES_SCOPE = ( + " AND (NOT startsWith(namespace, {col_prefix:String})" + " OR namespace IN {col_readable:Array(String)})" +) +SOURCES_SCOPE_PARAMS = {"col_prefix": "col-", "col_readable": ["col-board"]} + async def _pure_builders(ch: RecordingCH, c: dict[str, Any]) -> None: from server.identity.app.traffic_class_registry import REGISTRY_CLASS_SQL @@ -139,12 +147,7 @@ async def _worker_passes(ch: RecordingCH, c: dict[str, Any]) -> None: # the collections it cannot read (`collection_clause`). await source_store.failing_sources(ORG, sample=5, scope="", scope_params={}, ch=ch) await source_store.failing_sources( - ORG, - sample=5, - scope=" AND (NOT startsWith(namespace, {col_prefix:String})" - " OR namespace IN {col_readable:Array(String)})", - scope_params={"col_prefix": "col-", "col_readable": ["col-board"]}, - ch=ch, + ORG, sample=5, scope=SOURCES_SCOPE, scope_params=SOURCES_SCOPE_PARAMS, ch=ch ) # The cost-cap verdict for a pass's namespaces in one statement. from server.observability import budget diff --git a/tests/unit/test_ops_incidents.py b/tests/unit/test_ops_incidents.py index cd391d6b195..14c1a1cd3b0 100644 --- a/tests/unit/test_ops_incidents.py +++ b/tests/unit/test_ops_incidents.py @@ -522,6 +522,21 @@ async def test_a_collection_the_caller_holds_no_grant_for_is_left_out(monkeypatc assert "col_prefix" not in platform.params and "col_prefix" not in platform.sql +@pytest.mark.asyncio +async def test_the_analyzer_corpus_runs_the_sources_scope_the_builder_makes(monkeypatch) -> None: + """The analyzer corpus EXPLAINs the sources statement with a copied org admin scope; + it must be the fragment `collection_clause` builds.""" + from server.auth.context import collection_clause + from tests.analyzer.cases.workers import SOURCES_SCOPE, SOURCES_SCOPE_PARAMS + + monkeypatch.setattr("server.auth.sharing.readable", AsyncMock(return_value=["col-board"])) + set_current_auth(ORG_WIDE) + try: + assert await collection_clause("acme") == (SOURCES_SCOPE, SOURCES_SCOPE_PARAMS) + finally: + set_current_auth(None) + + @pytest.mark.asyncio async def test_org_admins_with_the_same_grants_share_a_read_whatever_their_own_collection( monkeypatch, From f80dd9d08dfc25697eea8a70dbd1384a9b0524a9 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 04:33:22 +0530 Subject: [PATCH 35/41] A lost folder's failed turn is pinned as counted in the sync tally The tally reads only a turn's status, so a folder the account no longer sees counts as a provider's error does; most orgs' folders lost in one pass are more likely Loom's own failure than every org unsharing at once. The knowledge page gives that reason. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 5 +++-- tests/unit/test_knowledge_source_sync.py | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 47bdcaeb824..0b1a96d851c 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -714,8 +714,9 @@ the worker's failure streak only as part of an outage of most orgs: credentials share, such as a provider refusing every token exchange of a host whose clock is off, is not counted either. - A folder or shared drive the account no longer sees ends its turn `failed`, which - counts like a provider's error: on a deployment where most orgs' sources lost their - folders, the sync leg fails every pass until they are fixed or removed. + counts like a provider's error, since most orgs' folders lost at once are more likely + Loom's own, such as item ids stored wrong: on a deployment where most orgs' sources + lost their folders, the sync leg fails every pass until they are fixed or removed. - The mining leg is judged from two documents tried in the pass, or from one source that failed whole: its documents unread, its record unwritten, or its mining raised. The only document a pass tries failing to mine is that document's, and a model outage diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index ad656d2d8ac..5489e3c4b3d 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -1196,6 +1196,20 @@ def test_a_full_listing_of_a_folder_the_account_lost_retires_nothing(world: _Wor assert _detail(world)["status"] == "failed" +def test_a_lost_folder_counts_in_the_sync_tally(world: _World) -> None: + """A folder the account no longer sees ends its turn `failed`, which the tally counts as + it does a provider's error: it is not a refused credential (`PassResult.refused_orgs`).""" + world.files = [] + world.lost_folders = {FOLDER} + result = asyncio.run(source_sync.run_sync(full=True)) + assert _detail(world)["status"] == "failed" + assert (result.turns.ran, result.turns.failed, result.refused_orgs) == ( + {ORG: 1}, + {ORG: 1}, + set(), + ) + + def test_a_write_cut_before_its_chunks_is_done_again( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: From 7d152db4f298c629bd52aa49c537d77f41b4f853 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:01:29 +0530 Subject: [PATCH 36/41] The lost-folder rule states the trade the tally makes A lost folder fails every turn of its source until it is shared again or the source is removed, so losses that build up one by one count as one at once would. The doc now gives the reason the code has (a wrong stored id gets the same answer) and that cost. The new test drops a line that repeated the fixture's default. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 9 +++++---- tests/unit/test_knowledge_source_sync.py | 1 - 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 0b1a96d851c..39092c78c41 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -713,10 +713,11 @@ the worker's failure streak only as part of an outage of most orgs: so dormant orgs never hide an outage of the active ones. A refusal every org's credentials share, such as a provider refusing every token exchange of a host whose clock is off, is not counted either. -- A folder or shared drive the account no longer sees ends its turn `failed`, which - counts like a provider's error, since most orgs' folders lost at once are more likely - Loom's own, such as item ids stored wrong: on a deployment where most orgs' sources - lost their folders, the sync leg fails every pass until they are fixed or removed. +- A folder or shared drive the account no longer sees ends its turn `failed`, as a + provider's error does, and counts: Loom asking for an item by a wrong id gets the same + answer. The cost: a lost folder fails every turn of its source until it is shared + again or the source is removed, so on a deployment where most orgs lost most of their + sources' folders, at once or one by one, the sync leg fails every pass. - The mining leg is judged from two documents tried in the pass, or from one source that failed whole: its documents unread, its record unwritten, or its mining raised. The only document a pass tries failing to mine is that document's, and a model outage diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index 5489e3c4b3d..d68df817954 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -1199,7 +1199,6 @@ def test_a_full_listing_of_a_folder_the_account_lost_retires_nothing(world: _Wor def test_a_lost_folder_counts_in_the_sync_tally(world: _World) -> None: """A folder the account no longer sees ends its turn `failed`, which the tally counts as it does a provider's error: it is not a refused credential (`PassResult.refused_orgs`).""" - world.files = [] world.lost_folders = {FOLDER} result = asyncio.run(source_sync.run_sync(full=True)) assert _detail(world)["status"] == "failed" From 54bb47cbcc5a64b8e75d483999f7528b28e74588 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:32:55 +0530 Subject: [PATCH 37/41] The mining rule names the orgs the document bound leaves waiting An org whose documents the pass's document bound left waiting counts as not failed, as one with nothing to mine does, so a model outage is noted only while a pass's tries reach most orgs; past twice as many orgs as the bound it never is. The doc states that, and a test pins it: leaving those orgs out would let one org's failing backlog build the streak alone. The lost-folder test moves beside the other note tests and asserts the sync leg's note, the lost-folder threshold is stated per source, and the mining tally's comment gives `error` its own line. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 14 ++++-- server/knowledge/app/source_sync.py | 3 +- tests/unit/test_knowledge_source_sync.py | 13 ----- .../test_knowledge_source_sync_failures.py | 50 +++++++++++++++++-- 4 files changed, 59 insertions(+), 21 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 39092c78c41..77c08be4a55 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -716,12 +716,18 @@ the worker's failure streak only as part of an outage of most orgs: - A folder or shared drive the account no longer sees ends its turn `failed`, as a provider's error does, and counts: Loom asking for an item by a wrong id gets the same answer. The cost: a lost folder fails every turn of its source until it is shared - again or the source is removed, so on a deployment where most orgs lost most of their - sources' folders, at once or one by one, the sync leg fails every pass. + again or the source is removed, so on a deployment where, in most orgs, most sources + each lost a folder or shared drive, at once or one by one, the sync leg fails every + pass. - The mining leg is judged from two documents tried in the pass, or from one source that failed whole: its documents unread, its record unwritten, or its mining raised. The - only document a pass tries failing to mine is that document's, and a model outage - while fewer than half the orgs have changed documents is not counted. + only document a pass tries failing to mine is that document's. An org with nothing to + mine has not failed, nor has one whose documents the pass's document bound + (`LOOM_KNOWLEDGE_SOURCE_SYNC_DOCUMENTS_PER_PASS`, which the sync's fetches spend + first) left waiting. So a model outage is not counted while the pass tries documents + for fewer than half the orgs: while fewer than half have changed documents, while one + org's backlog takes the bound, and always on a deployment of at least twice as many + orgs as the bound. - A pass that runs any mirrored turn is private, and the worker's streak stays as it was: while auth is on, on a deployment with an active mirrored source, no leg's failure reaches the streak, and a pass with a failed leg reads `SYNC_FAILED` in its status row. diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 23c857867dc..d8301d7e773 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -1697,8 +1697,9 @@ class _Mined: extracted: int = 0 flagged: int = 0 unextracted: int = 0 - # Each failed document's reason (a code, never a text), and the first one. + # Each failed document's reason (a code, never a text). reasons: Counter[str] = field(default_factory=Counter) + # The first failed document's reason. error: str = "" # Why the turn left documents for a later pass (`over_cap`, `held:`, # `pass_bound`). diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index d68df817954..ad656d2d8ac 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -1196,19 +1196,6 @@ def test_a_full_listing_of_a_folder_the_account_lost_retires_nothing(world: _Wor assert _detail(world)["status"] == "failed" -def test_a_lost_folder_counts_in_the_sync_tally(world: _World) -> None: - """A folder the account no longer sees ends its turn `failed`, which the tally counts as - it does a provider's error: it is not a refused credential (`PassResult.refused_orgs`).""" - world.lost_folders = {FOLDER} - result = asyncio.run(source_sync.run_sync(full=True)) - assert _detail(world)["status"] == "failed" - assert (result.turns.ran, result.turns.failed, result.refused_orgs) == ( - {ORG: 1}, - {ORG: 1}, - set(), - ) - - def test_a_write_cut_before_its_chunks_is_done_again( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index 8317c68dc41..f8c2e1ff573 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -21,7 +21,7 @@ from server.knowledge.app import source_sync from server.knowledge.domain.sources import KnowledgeSource from server.workers import pass_context -from tests.unit.test_knowledge_source_sync import NS, ORG, _detail, _source, _World +from tests.unit.test_knowledge_source_sync import FOLDER, NS, ORG, _detail, _source, _World from tests.unit.test_knowledge_source_sync import world as world # the fixture from tests.unit.test_knowledge_source_sync_mirror import _mirrored @@ -62,11 +62,13 @@ async def state(src: KnowledgeSource, read: Any, turn: Any) -> None: monkeypatch.setattr(source_sync, "_write_state", state) -async def _supervised() -> tuple[source_sync.PassResult, pass_context.PassContext]: +async def _supervised( + *, full: bool = False +) -> tuple[source_sync.PassResult, pass_context.PassContext]: """One pass under a pass context, as the supervisor binds it.""" ctx = pass_context.begin(source_sync.WORKER) try: - return await source_sync.run_sync(), ctx + return await source_sync.run_sync(full=full), ctx finally: pass_context.clear() @@ -331,6 +333,17 @@ def test_half_the_sources_failing_is_not_most_of_them( assert ctx.count == 0 and result.failed == 1 +def test_a_lost_folder_counts_toward_the_sync_leg(world: _World) -> None: + """A folder the account no longer sees ends its source's turn `failed`, which counts as + a provider's error does: it is not a refused credential (`PassResult.refused_orgs`).""" + world.lost_folders = {FOLDER} + + result, ctx = asyncio.run(_supervised(full=True)) + + assert _detail(world)["status"] == "failed" and result.refused_orgs == set() + assert ctx.failures == _noted("sync", "failed") + + def test_a_source_another_copy_holds_is_not_counted( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -646,6 +659,37 @@ def test_the_only_document_mined_in_a_pass_failing_is_not_the_workers_failure( assert ctx.failures == [] +def test_orgs_the_document_bound_left_waiting_have_not_failed( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """One org's backlog takes every try of the pass while the model is down: the orgs the + bound left waiting have not failed, so one org's failing backlog never fails the + worker, and the outage is not noted (each source's `extract_error` shows it).""" + from server.memory.app.decision_extract import ExtractReport + + world.sources = [ + _source("a"), + dataclasses.replace(_source("b"), org="o2"), + dataclasses.replace(_source("c"), org="o3"), + ] + _turns(monkeypatch, set()) + + async def revisions(at: str, ns: str, tag: str, **kw: Any) -> list[dict[str, str]]: + return [ + {"source_uri": f"https://docs.example.com/{at}/{i}", "source_revision": "r1"} + for i in range(100 if at == ORG else 5) + ] + + monkeypatch.setattr(source_sync.store, "source_revisions", revisions) + world.mine_answer = lambda uri: ExtractReport(uri, False, error="model down") + + result, ctx = asyncio.run(_supervised()) + + assert world.mined and all(f"/{ORG}/" in uri for uri, _, _ in world.mined) + assert result.extract_deferred == 3 # the rest of a's backlog, and b's and c's documents + assert ctx.failures == [] + + @pytest.mark.parametrize("failing", ["b", "abc"]) def test_a_removed_sources_failed_retirement_is_its_own_unless_most_fail( world: _World, monkeypatch: pytest.MonkeyPatch, failing: str From 78cabc676038af0bbc313b1e7f3484085d4298f9 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 05:51:51 +0530 Subject: [PATCH 38/41] The mining rule counts the orgs the pass serves, at no more than half The leg notes only when more than half of the orgs the pass serves fail, so an outage at exactly half is not noted either, and the count is of the orgs the pass serves, not the deployment's. The retirement spends the document bound before the sync's fetches do. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/features/knowledge.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/features/knowledge.md b/docs/features/knowledge.md index 77c08be4a55..da94dec4e2c 100644 --- a/docs/features/knowledge.md +++ b/docs/features/knowledge.md @@ -723,11 +723,11 @@ the worker's failure streak only as part of an outage of most orgs: failed whole: its documents unread, its record unwritten, or its mining raised. The only document a pass tries failing to mine is that document's. An org with nothing to mine has not failed, nor has one whose documents the pass's document bound - (`LOOM_KNOWLEDGE_SOURCE_SYNC_DOCUMENTS_PER_PASS`, which the sync's fetches spend - first) left waiting. So a model outage is not counted while the pass tries documents - for fewer than half the orgs: while fewer than half have changed documents, while one - org's backlog takes the bound, and always on a deployment of at least twice as many - orgs as the bound. + (`LOOM_KNOWLEDGE_SOURCE_SYNC_DOCUMENTS_PER_PASS`, which the retirement and the sync's + fetches spend first) left waiting. So a model outage is not counted while the pass + tries documents for no more than half the orgs it serves: while no more than half + have changed documents, while one org's backlog takes the bound and leaves the others + waiting, and always when the pass serves at least twice as many orgs as the bound. - A pass that runs any mirrored turn is private, and the worker's streak stays as it was: while auth is on, on a deployment with an active mirrored source, no leg's failure reaches the streak, and a pass with a failed leg reads `SYNC_FAILED` in its status row. From 23b6f4ef2ec453eeb1e817842ecdc7dedb5bcc03 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 06:22:55 +0530 Subject: [PATCH 39/41] The sources read's credential and mirror filters each have a row of their own The fixture's only connected source was also mirrored, and the mirror's state row had no registry row, so removing `credential_mode = 'shared'` or `not_reserved_sql()` from the statement failed no test. A namespace source on a connected credential and a source row in a mirror's namespace now leave the count at 4 only while both filters stand. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- tests/unit/test_ops_incidents_sql.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/unit/test_ops_incidents_sql.py b/tests/unit/test_ops_incidents_sql.py index bbbb124cd77..94f9edad406 100644 --- a/tests/unit/test_ops_incidents_sql.py +++ b/tests/unit/test_ops_incidents_sql.py @@ -126,6 +126,8 @@ async def read(org: str) -> list[tuple[str, int, int]]: ("o1", "team", "broke", "namespace", "shared", "gdrive", 1, 1), ("o1", "team", "drive", "mirrored", "shared", "gdrive", 1, 1), # a mirrored source ("o1", "team", "mine", "mirrored", "connected", "notion", 1, 1), # a person's own + ("o1", "team", "linked", "namespace", "connected", "gdrive", 1, 1), # a connected one + ("o1", _MIRROR, "drive-id", "namespace", "shared", "gdrive", 1, 1), # in a mirror ("o1", "team", "gone", "namespace", "shared", "gdrive", 1, 1), ("o1", "team", "gone", "namespace", "shared", "gdrive", 0, 2), # removed since ("o1", "team", "agent", "namespace", "shared", "mcp", 1, 1), # a worker source @@ -147,6 +149,7 @@ async def read(org: str) -> list[tuple[str, int, int]]: ("o1", "team", "knowledge_source:broke", "failed", "2026-03-01T00:00:00+00:00", 2), ("o1", "team", "knowledge_source:drive", "failed", "2026-03-09T00:00:00+00:00", 1), ("o1", "team", "knowledge_source:mine", "credential_invalid", "2026-03-09T00:00:00+00:00", 1), + ("o1", "team", "knowledge_source:linked", "failed", "2026-03-09T00:00:00+00:00", 1), ("o1", _MIRROR, "knowledge_source:drive-id", "failed", "2026-03-09T00:00:00+00:00", 1), ("o1", "team", "knowledge_source:gone", "failed", "2026-03-09T00:00:00+00:00", 1), ("o1", "team", "knowledge_source:agent", "failed", "2026-03-09T00:00:00+00:00", 1), From f02d225e82cbd86c9399d89e428957ad342c2862 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 07:03:19 +0530 Subject: [PATCH 40/41] A worker copy's failed turn is pinned under the one mirrored code An owner's worker copy whose state write raises is tallied under `SYNC_FAILED`, never its exception's class, and its pass is private. OpsIncidentSources keeps what its fields mean and names the Knowledge page section for when the sync worker is listed, in place of a copy of the rule. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- sdk/go/wire/models.gen.go | 2 +- server/insights/api/models_ops.py | 9 +++------ .../test_knowledge_source_sync_failures.py | 20 +++++++++++++++++++ 3 files changed, 24 insertions(+), 7 deletions(-) diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 92c2bfe50cc..3954e28c0f9 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: 62f5ea5edf01c3a30ee6d51f0228e65ca20257f156daf4cb2eb3d41f75160645 +// Registry model schema SHA-256: 2aee48df40dcba9caf5949d49643fcda7d1f881af0245d093cdc813f8bf86133 // Package wire contains the Go requests and responses for Loom operations. package wire diff --git a/server/insights/api/models_ops.py b/server/insights/api/models_ops.py index fa8049cd54a..1ed18d4d0b0 100644 --- a/server/insights/api/models_ops.py +++ b/server/insights/api/models_ops.py @@ -217,12 +217,9 @@ class OpsIncidentSources(BaseModel): Those every reader of their namespace sees, never a mirrored one, in the namespaces and the collections the caller reads. A source's failure is its own (its `sync.status` in `knowledge.source.list`), so it never makes `status` `degraded` by - itself: a revoked credential is its org's to fix, not a Loom outage. The sync worker - becomes an incident after 3 failed passes in a row: a pass that fails outright, one - in which most orgs' sources fail (an outage, or a deployment where one org holds - every synced source), one in which most orgs' tried documents fail to mine, or one - whose retirement of removed sources fails for most of the orgs it retired for. While - auth is on, a pass that runs a mirrored source's turn leaves the streak as it was.""" + itself: a revoked credential is its org's to fix, not a Loom outage. The Knowledge + page, under "Source failures and the worker's health", says when the sync worker + itself is listed.""" # Sources whose last turn failed; 0 unless `read` is `read`. failing: int = 0 diff --git a/tests/unit/test_knowledge_source_sync_failures.py b/tests/unit/test_knowledge_source_sync_failures.py index f8c2e1ff573..ee580f29b97 100644 --- a/tests/unit/test_knowledge_source_sync_failures.py +++ b/tests/unit/test_knowledge_source_sync_failures.py @@ -394,6 +394,26 @@ def test_one_mirrored_failure_of_three_notes_no_pass_failure( assert ctx.count == 0 +def test_a_worker_copys_failure_counts_with_the_one_mirrored_code( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """An owner's worker copy is written into the mirror like a mirrored source: a turn + whose state write raises is tallied under `SYNC_FAILED`, never its exception's class.""" + from server.settings import settings + from tests.unit.test_worker_source_copies import _source as _worker_source + + monkeypatch.setattr(settings, "knowledge_source_worker_copies_enabled", True) + src = _worker_source() + world.sources = [src] + _turns(monkeypatch, {src.name}, how="raises") + + result, ctx = asyncio.run(_supervised()) + + assert result.private_work and ctx.private_work + assert result.errors == [f"{src.org}/{src.namespace}/{src.name}: SYNC_FAILED"] + assert ctx.failures == _noted("sync", "SYNC_FAILED") + + def test_a_failed_store_read_every_source_shares_notes_once( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: From d4228943043443bc6baccc790d7a5e6e51a535e4 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Sat, 5 Dec 2026 07:35:25 +0530 Subject: [PATCH 41/41] The monitoring page says the sources can hold an answer for two bounds The caller's collection reach is resolved before the sources' statement starts, each under LOOM_READINESS_CHECK_TIMEOUT_S, so while both are slow an ops.incidents answer can wait for two bounds. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Lareb Zafar --- docs/operations/monitoring.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index 3a514b06f2b..90ad946ee6a 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -174,7 +174,8 @@ clients poll during an outage, and each read is cut at `LOOM_READINESS_CHECK_TIM A read that failed is named in the response's `degraded` while its failure is cached, as long as an answer would be, and the other reads still answer. The caller's collection reach, which the failing sources need, comes from the grant -cache every call uses and is cut at the same bound. +cache every call uses and is cut at the same bound. It is resolved before the sources' +statement starts, so while both are slow an answer can wait for two bounds. 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