Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(memory): host-own the memory-tree degradation taxonomy\n\n`FailureCode`, `FailureClass`, `PipelineFailure` and `DegradedState` were\n`tinycortex::memory::health`'s, reached through one `pub use` in\n`memory/tree/health/mod.rs`. That single re-export was the entire remaining\nproduction `tinycortex` surface of the memory tree: deleting the dependency\nfrom `Cargo.toml` produced one unresolved-module error, in that file, with a\ncascade of unresolved imports of exactly those four names behind it.\n\n#5560 sheds `tinycortex` as well as `tinymemory-core`, so re-pointing the\nshim at either engine was never the fix — only a way to drop off the\n`tinymemory_core::` ratchet while a crate stayed linked, which\n`host_impls.rs` already warns about by name.\n\nNo contract door was needed. Round 1 shipped `MemoryMaintenance::{diagnose,\ndegraded_state}` and the host already calls both; the values arrive over the\nbus as `Diagnosis` / `DegradedCapabilities`, whose `code` and `class` are\nopen-vocabulary strings carrying these exact snake_case spellings. What was\nmissing was ownership of the vocabulary the answer is parsed into, not a\ncall.\n\nThe four types are defined in a new `health/taxonomy.rs`, field for field\nand spelling for spelling — including `PipelineFailure::detail`'s\n`skip_serializing_if` and `DegradedState::storage`'s `#[serde(default)]`\n*without* one, so `storage` keeps being emitted rather than omitted.\n\n`classify_embed_error{,_str}` deliberately did not come with them. They rode\nthe same `pub use` and have no host caller: they read the wording of the\nembed providers' own error strings, which run inside whichever engine ran\nthe embed stage. The driver hands this host a code, not a message, so a copy\nhere would be a second table free to disagree with the one that labels the\njobs.\n\n`taxonomy_tests` pins the wire against JSON captured from a running build\nbefore the move, not transcribed from the engine's source: every one of the\neleven codes, its serde spelling, its derived class and its remediation key,\nplus both class spellings, both object shapes, the two deserialisation\ntolerances, the character-wise detail cap and the `Display` rendering.\n`every_variant_is_in_the_table` makes a new variant a compile error rather\nthan a silently unpinned row — `report_tests` only ever names four codes,\nand a typo in any of the other seven would ship as a status panel that\nquietly stops explaining itself.\n\n

Shanu453ff38d78ad
diff --git a/src/openhuman/memory/tree/health/mod.rs b/src/openhuman/memory/tree/health/mod.rs
index 6a706257df..342a7dbf07 100644
--- a/src/openhuman/memory/tree/health/mod.rs
+++ b/src/openhuman/memory/tree/health/mod.rs
@@ -1,27 +1,31 @@
-//! Host layer over [`tinymemory_core::tree::health`].
+//! The memory-tree pipeline's failure taxonomy and the surfaces built on it.
//!
-//! The health model and its classifier are core; what stays here is the
-//! `user_error` wire payload, which rides a web channel.
+//! Two halves, both host-owned as of #5560: the [`taxonomy`] itself
+//! (`FailureCode`, `FailureClass`, `PipelineFailure`, `DegradedState`), and the
+//! [`user_error`] wire payload that rides a web channel. [`report`] is the
+//! third — the doctor report and the degradation snapshot, read from the bound
+//! driver.
//!
//! # Do not repoint this at `memory::api::health` — it is a different thing (#5560)
//!
//! The name collides and the types do not. `tinymemory_api::health` is
//! `MemoryHealth`, driver *liveness*, one enum. This module is pipeline
//! *failure classification* — `FailureCode`, `FailureClass`, `PipelineFailure`,
-//! `DegradedState` — and `tinycortex::memory::health`'s own docs call the
-//! confusion out by name. A swap would compile at neither end.
+//! `DegradedState` — and the engine's own docs call the confusion out by name.
+//! A swap would compile at neither end.
//!
-//! What this file re-exported used to split cleanly in two; only one half is
-//! left, and the other is documented so nobody re-derives where it went:
+//! # Where each half went, so nobody re-derives it
//!
-//! - **The taxonomy** (`FailureCode`, `FailureClass`, `PipelineFailure`,
-//! `DegradedState`, `classify_embed_error{,_str}`) is `tinycortex`'s; the
-//! engine crate only re-exported it. It follows the
-//! `memory::sync::sync_status` precedent and is named on `tinycortex`
-//! directly below — same items, so no call site changed and none has to when
-//! the engine crate leaves the build. `rpc_part_02.rs` / `rpc_part_03.rs`
-//! and [`report`] still take these from here, so this half is production
-//! surface and stays.
+//! This file used to be two re-exports of somebody else's items. Both are gone:
+//!
+//! - **The taxonomy came home.** It was `tinycortex::memory::health`'s, reached
+//! through a `pub use` here (the engine crate only re-exported it in turn).
+//! That one `pub use` was the **entire** remaining production `tinycortex`
+//! surface of the memory tree, and #5560 sheds `tinycortex` as well as
+//! `tinymemory-core` — so re-pointing it at either engine was never the
+//! answer, only a way to drop off the `tinymemory_core::` ratchet while a
+//! crate stayed linked. The four types are defined in [`taxonomy`] now, wire
+//! for wire, with `taxonomy_tests` pinning every spelling.
//! - **The engine half is gone.** The process-global degradation flags
//! (`mark_*` / `clear_*` / `current_degraded_state`), the engine's `doctor`
//! report and its `test_guard` rode a `pub use tinymemory_core::tree::
@@ -34,27 +38,22 @@
//! `tinymemory_core::tree::health::test_guard` directly now (the
//! `[dev-dependencies]` entry serves them) and the glob is deleted.
//!
-//! Worth knowing before trusting a reading of `current_degraded_state()`: the
-//! flags are process statics, and the loaded module links its **own** copy of
-//! `tinymemory-core`. A degradation the module observes never reaches the
-//! statics this host reads. That is pre-existing and is not #5560's to fix, but
-//! it is the reason moving the flags host-side is a design question rather than
-//! a file move.
+//! # Read this before trusting a degradation reading
+//!
+//! `current_degraded_state` means
+//! [`report::current_degraded_state`](report::current_degraded_state), which
+//! asks the **bound driver**. The engine free function of the same name that
+//! this module used to re-export read three *process statics*, and the loaded
+//! module links its own copy of `tinymemory-core` — so a degradation the module
+//! observed never reached the statics this host was reading, and the host-side
+//! read answered all-clear forever. That is why the snapshot is a contract call
+//! now and why a "just read the flags" shortcut must not come back.
+
+/// The four taxonomy types — `FailureCode`, `FailureClass`, `PipelineFailure`,
+/// `DegradedState` — defined host-side rather than borrowed from an engine.
+mod taxonomy;
-// The taxonomy half, named at the engine that **stays**. `tinycortex` is a
-// direct dependency of this crate and is where these are defined
-// (`tinycortex::memory::health`); `tinymemory_core::tree::health` re-exported
-// them out of its own `engine::backend::health`, which is the same
-// `pub use tinycortex::memory::health`. So this changes no item and no wire
-// byte — an explicit `use` shadows the glob below with the identical item, the
-// way `tree_runtime` already does for the contract's node model — and it
-// records which half of this shim survives `tinymemory-core` leaving the build.
-// Same precedent as `memory::people`, `memory::tool_memory` and
-// `memory::sync::sync_status`.
-pub use tinycortex::memory::health::{
- classify_embed_error, classify_embed_error_str, DegradedState, FailureClass, FailureCode,
- PipelineFailure,
-};
+pub use taxonomy::{DegradedState, FailureClass, FailureCode, PipelineFailure};
/// The doctor report and the degradation snapshot, read from the bound driver
/// rather than from this process's copy of the engine.
diff --git a/src/openhuman/memory/tree/health/report.rs b/src/openhuman/memory/tree/health/report.rs
index 081c459715..d181984bed 100644
--- a/src/openhuman/memory/tree/health/report.rs
+++ b/src/openhuman/memory/tree/health/report.rs
@@ -27,11 +27,14 @@
//! against the JSON this RPC has always emitted.
//!
//! The failure taxonomy is **not** redefined here. [`PipelineFailure`],
-//! [`FailureCode`] and [`FailureClass`] stay `tinycortex`'s — the same items
-//! [`super`] already re-exports, and the same ones
+//! [`FailureCode`] and [`FailureClass`] come from
+//! [`super::taxonomy`](super) — the same items
//! `pipeline_status.first_blocking_cause` is built from out of a
//! `QueueFailure`. Two copies of that vocabulary is exactly how the two halves
-//! of one response start disagreeing about a code.
+//! of one response start disagreeing about a code. (Those types were the
+//! engine's until #5560 and are this host's now; the sentence above was true
+//! before the move for the same reason it is true after it — there is one
+//! definition, wherever it lives.)
use serde::{Deserialize, Serialize};
diff --git a/src/openhuman/memory/tree/health/taxonomy.rs b/src/openhuman/memory/tree/health/taxonomy.rs
new file mode 100644
index 0000000000..d64411b826
--- /dev/null
+++ b/src/openhuman/memory/tree/health/taxonomy.rs
@@ -0,0 +1,308 @@
+//! The pipeline failure + degradation taxonomy, owned by this host (#5560).
+//!
+//! `FailureCode`, `FailureClass`, `PipelineFailure` and `DegradedState` are the
+//! vocabulary the memory-tree status surfaces speak: which distinguishable
+//! thing went wrong, whether retrying can fix it, the i18n key that tells the
+//! user what to do, and "the pipeline ran but recall/structure is reduced".
+//!
+//! # Why they are defined here rather than re-exported
+//!
+//! They were `tinycortex::memory::health`'s, reached through a `pub use` in
+//! [`super`]. That re-export was the **entire** remaining production
+//! `tinycortex` surface of the memory tree — deleting the dependency from
+//! `Cargo.toml` produced one unresolved-module error, in `health/mod.rs`, and a
+//! cascade of unresolved imports of these four names behind it. #5560 sheds
+//! that crate, so a type this host serialises into its own RPC responses has to
+//! be this host's.
+//!
+//! No contract door was needed for the move. The *values* already arrive over
+//! the bus: `MemoryMaintenance::{degraded_state, diagnose}` answer with
+//! `DegradedCapabilities` and `Diagnosis`, whose `code` and `class` are
+//! open-vocabulary strings carrying exactly the snake_case spellings below.
+//! [`report`](super::report) parses them into these types. What was missing was
+//! never a call — it was ownership of the vocabulary the answer is parsed into.
+//!
+//! # The wire is the constraint, and it is pinned
+//!
+//! These are field-for-field and spelling-for-spelling what the engine's types
+//! serialised to, including `PipelineFailure::detail`'s
+//! `skip_serializing_if` and `DegradedState::storage`'s `#[serde(default)]`
+//! **without** one. `taxonomy_tests` pins every variant's wire string, its
+//! derived class and its remediation key against the JSON these RPCs have
+//! always emitted; a rename, a casing change or a re-ordered `class()` arm
+//! fails there rather than in a user's status panel.
+//!
+//! # What deliberately did not come with them
+//!
+//! `classify_embed_error{,_str}` — the parser that turns an embed-stage error
+//! *string* into a [`PipelineFailure`]. It rode the same `pub use` and has no
+//! host caller: it reads the wording of `OpenAiEmbedding::embed`,
+//! `OpenHumanCloudEmbedding::embed` and `tinyinference::embeddings::ollama`,
+//! all of which run inside whichever engine ran the embed stage. Classifying
+//! there is the point — the driver hands this host a code, not a message — so
+//! the classifier stays with the stage and a copy here would be a second table
+//! free to disagree with the one that actually labels the jobs.
+
+use serde::{Deserialize, Serialize};
+
+/// Whether a failure should be retried (`Transient`) or fail fast
+/// (`Unrecoverable`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FailureClass {
+ /// Retry with backoff up to `max_attempts` (network 5xx, timeouts,
+ /// truncated streams).
+ Transient,
+ /// Stop immediately — retrying the same input cannot succeed (budget
+ /// exhausted, bad/missing key, missing local model, dim mismatch).
+ Unrecoverable,
+}
+
+impl FailureClass {
+ /// Stable wire string — the same one the driver sends in
+ /// [`DiagnosisFailure::class`](crate::openhuman::memory::api::provider::diagnosis::DiagnosisFailure)
+ /// and the one `mem_tree_jobs.failure_class` persists.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Transient => "transient",
+ Self::Unrecoverable => "unrecoverable",
+ }
+ }
+}
+
+/// A distinguishable pipeline failure cause. Each variant carries a fixed
+/// [`FailureClass`] and i18n remediation key.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FailureCode {
+ /// Managed embeddings route returned an out-of-budget error (4xx).
+ BudgetExhausted,
+ /// No auth/session available for the embeddings provider.
+ AuthMissing,
+ /// Auth present but rejected (expired/invalid key or JWT).
+ AuthInvalid,
+ /// No embeddings provider is configured at all.
+ EmbeddingsUnconfigured,
+ /// Provider returned vectors of an unexpected dimensionality.
+ EmbeddingDimMismatch,
+ /// A required local model (Ollama) is not available.
+ LocalModelUnavailable,
+ /// The extraction model timed out / exhausted retries.
+ ExtractionTimeout,
+ /// No summarization provider could be resolved for "Build Summary Trees"
+ /// — neither local AI nor a configured cloud chat provider. Distinct from
+ /// [`LocalModelUnavailable`](Self::LocalModelUnavailable), which implies the
+ /// local path was selected; this covers the cloud-only setup whose provider
+ /// failed to resolve, so the remediation names both paths.
+ SummarizerUnavailable,
+ /// The embedding provider refused an empty/whitespace input at the
+ /// pre-flight guard (#13021). Unrecoverable per-row: the offending row
+ /// will never become embeddable, so the worker must tombstone it instead
+ /// of retrying.
+ EmptyInputRefused,
+ /// The host filesystem cannot service the memory_tree path — `create_dir`
+ /// / DB open returned a persistent OS-level I/O error (EIO `5`, ENOSPC
+ /// `28`, EROFS `30`), e.g. a failing/disconnected SD card or a volume the
+ /// kernel remounted read-only. Unrecoverable from inside the app: only the
+ /// user can reseat/replace/free the storage. Distinct from the embeddings
+ /// provider faults above and from the SQLite-level `SQLITE_FULL` /
+ /// `SQLITE_CORRUPT` handled in the queue worker — this is the
+ /// directory/DB-init layer below them.
+ StorageUnavailable,
+ /// Catch-all transient failure (network 5xx, timeout, truncated JSON).
+ Transient,
+}
+
+impl FailureCode {
+ /// Stable wire string.
+ ///
+ /// Kept as an explicit table rather than derived from the serde attribute,
+ /// because the two are read in different places — the string form is what
+ /// a log line and `mem_tree_jobs.failure_reason` carry, the serde form is
+ /// what the RPC body carries — and `taxonomy_tests` asserts they agree.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::BudgetExhausted => "budget_exhausted",
+ Self::AuthMissing => "auth_missing",
+ Self::AuthInvalid => "auth_invalid",
+ Self::EmbeddingsUnconfigured => "embeddings_unconfigured",
+ Self::EmbeddingDimMismatch => "embedding_dim_mismatch",
+ Self::LocalModelUnavailable => "local_model_unavailable",
+ Self::ExtractionTimeout => "extraction_timeout",
+ Self::SummarizerUnavailable => "summarizer_unavailable",
+ Self::EmptyInputRefused => "empty_input_refused",
+ Self::StorageUnavailable => "storage_unavailable",
+ Self::Transient => "transient",
+ }
+ }
+
+ /// Parses the stable wire string produced by [`Self::as_str`].
+ ///
+ /// Deliberately an inherent method returning `Option`, not a
+ /// [`std::str::FromStr`] impl — the trait must return `Result`, and both
+ /// callers ([`report::pipeline_failure`](super::report) and
+ /// `rpc::blocking_cause`) treat "a code this build has never heard of" as
+ /// *no cause to render*, not as an error to surface. An `Option` says that;
+ /// a `Result` would invite someone to propagate it.
+ #[allow(clippy::should_implement_trait)]
+ pub fn from_str(s: &str) -> Option<Self> {
+ Some(match s {
+ "budget_exhausted" => Self::BudgetExhausted,
+ "auth_missing" => Self::AuthMissing,
+ "auth_invalid" => Self::AuthInvalid,
+ "embeddings_unconfigured" => Self::EmbeddingsUnconfigured,
+ "embedding_dim_mismatch" => Self::EmbeddingDimMismatch,
+ "local_model_unavailable" => Self::LocalModelUnavailable,
+ "extraction_timeout" => Self::ExtractionTimeout,
+ "summarizer_unavailable" => Self::SummarizerUnavailable,
+ "empty_input_refused" => Self::EmptyInputRefused,
+ "storage_unavailable" => Self::StorageUnavailable,
+ "transient" => Self::Transient,
+ _ => return None,
+ })
+ }
+
+ /// Retry policy for this cause.
+ ///
+ /// [`LocalModelUnavailable`](Self::LocalModelUnavailable) is deliberately
+ /// **transient** even though the user has to act: the condition (Ollama
+ /// daemon stopped, model not pulled) clears from outside the app, and only
+ /// transient rows are picked up by the driver's `requeue_transient_failed`
+ /// — the automatic self-healing requeue. Classifying it unrecoverable would
+ /// park every affected job until someone clicks "Retry failed" by hand, so
+ /// a user who simply restarts Ollama would never see ingestion resume.
+ pub fn class(self) -> FailureClass {
+ match self {
+ Self::Transient | Self::ExtractionTimeout | Self::LocalModelUnavailable => {
+ FailureClass::Transient
+ }
+ _ => FailureClass::Unrecoverable,
+ }
+ }
+
+ /// i18n key for the user-facing remediation. Embeddings causes lead
+ /// with the local-Ollama path (the steered primary fix per spec FR-015).
+ ///
+ /// These strings are a **frontend contract** — the locale files key on them
+ /// — so they are as much wire as the codes themselves.
+ pub fn remediation_key(self) -> &'static str {
+ match self {
+ Self::BudgetExhausted => "memory.health.remediation.budget_exhausted",
+ Self::AuthMissing => "memory.health.remediation.auth_missing",
+ Self::AuthInvalid => "memory.health.remediation.auth_invalid",
+ Self::EmbeddingsUnconfigured => "memory.health.remediation.embeddings_unconfigured",
+ Self::EmbeddingDimMismatch => "memory.health.remediation.embedding_dim_mismatch",
+ Self::LocalModelUnavailable => "memory.health.remediation.local_model_unavailable",
+ Self::ExtractionTimeout => "memory.health.remediation.extraction_timeout",
+ Self::SummarizerUnavailable => "memory.health.remediation.summarizer_unavailable",
+ Self::EmptyInputRefused => "memory.health.remediation.empty_input_refused",
+ Self::StorageUnavailable => "memory.health.remediation.storage_unavailable",
+ Self::Transient => "memory.health.remediation.transient",
+ }
+ }
+}
+
+/// A typed pipeline failure: a [`FailureCode`] plus the derived class +
+/// remediation key (carried on the wire so the frontend stays presentational)
+/// and an optional human-readable detail for logs/diagnosis.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PipelineFailure {
+ pub code: FailureCode,
+ pub class: FailureClass,
+ /// i18n key — the frontend resolves this to localized remediation text.
+ pub remediation_key: String,
+ /// Optional non-localized detail for logs/diagnosis (never a secret).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub detail: Option<String>,
+}
+
+impl PipelineFailure {
+ /// Build a failure from a code, deriving class + remediation key.
+ pub fn new(code: FailureCode) -> Self {
+ Self {
+ code,
+ class: code.class(),
+ remediation_key: code.remediation_key().to_string(),
+ detail: None,
+ }
+ }
+
+ /// Attach a non-localized detail string (bounded by [`truncate_detail`];
+ /// never log secrets).
+ pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
+ let detail = detail.into();
+ self.detail = Some(truncate_detail(&detail));
+ self
+ }
+
+ /// True when this failure should fail fast (no retry budget).
+ pub fn is_unrecoverable(&self) -> bool {
+ self.class == FailureClass::Unrecoverable
+ }
+}
+
+impl std::fmt::Display for PipelineFailure {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{} ({})", self.code.as_str(), self.class.as_str())?;
+ if let Some(detail) = &self.detail {
+ write!(f, ": {detail}")?;
+ }
+ Ok(())
+ }
+}
+
+impl std::error::Error for PipelineFailure {}
+
+/// Cap a detail string so a full provider response body can never balloon a
+/// log line or a wire payload. Never contains a secret (it is an error body),
+/// but keep it short anyway.
+///
+/// Counts **characters, not bytes**, so a multi-byte detail is never sliced
+/// mid-codepoint. The cap is applied host-side as well as driver-side: the
+/// driver already bounds `DiagnosisFailure::detail` with the same rule, so
+/// [`report`](super::report) carries that value through rather than
+/// re-truncating, and this only bites for details this host attaches itself
+/// (the `unavailable` diagnostic's reason).
+fn truncate_detail(s: &str) -> String {
+ const MAX: usize = 200;
+ if s.chars().count() <= MAX {
+ return s.to_string();
+ }
+ let truncated: String = s.chars().take(MAX).collect();
+ format!("{truncated}…")
+}
+
+/// "The pipeline ran, but output quality is reduced." Surfaced so degraded
+/// results are never presented as success.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct DegradedState {
+ /// True when embeddings were skipped (no usable provider) so semantic
+ /// recall falls back to recency-only.
+ pub semantic_recall: bool,
+ /// True when extraction yielded empty across the board so the wiki has
+ /// no entity/topic structure.
+ pub structure: bool,
+ /// True when the memory_tree's own storage path is unusable — the host
+ /// filesystem returned a persistent I/O error on dir-create / DB open
+ /// (EIO/ENOSPC/EROFS). This is the most severe degradation: the pipeline
+ /// can't even open its DB, so nothing else runs. `#[serde(default)]` keeps
+ /// the wire format backward-compatible (older clients omit it → `false`)
+ /// and there is deliberately **no** `skip_serializing_if`, so the field is
+ /// always emitted — which is what this RPC has always sent.
+ #[serde(default)]
+ pub storage: bool,
+ /// The cause of the most significant degradation, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub cause: Option<PipelineFailure>,
+}
+
+impl DegradedState {
+ /// True when any degradation is present.
+ pub fn is_degraded(&self) -> bool {
+ self.semantic_recall || self.structure || self.storage
+ }
+}
+
+#[cfg(test)]
+#[path = "taxonomy_tests.rs"]
+mod tests;
diff --git a/src/openhuman/memory/tree/health/taxonomy_tests.rs b/src/openhuman/memory/tree/health/taxonomy_tests.rs
new file mode 100644
index 0000000000..57005bf0b4
--- /dev/null
+++ b/src/openhuman/memory/tree/health/taxonomy_tests.rs
@@ -0,0 +1,401 @@
+//! Wire pins for the surrounding module.
+//!
+//! These assert **bytes**, not behaviour. The four taxonomy types were
+//! `tinycortex::memory::health`'s until #5560 and are this host's now; every
+//! literal below is what the engine's copy serialised to before the move,
+//! captured from a running build rather than transcribed from its source, so
+//! the comparison is against what the RPC actually emitted.
+//!
+//! # Why the table is exhaustive rather than a spot check
+//!
+//! `report_tests` already pins the two response envelopes, but it only ever
+//! names four codes. A hand-written enum has eleven spellings, eleven
+//! remediation keys and a class table, and a typo in any of the other seven
+//! would ship: the frontend resolves an unknown `remediation_key` to nothing,
+//! and a mis-spelled `code` makes
+//! [`FailureCode::from_str`](super::FailureCode::from_str) drop a live cause on
+//! the floor — a status panel that silently stops explaining itself, which is
+//! the failure mode #5560 must not introduce while claiming to change nothing.
+//!
+//! [`CODES`] is therefore the whole vocabulary, and
+//! [`every_variant_is_in_the_table`] is what stops it rotting: a new variant is
+//! a compile error in its `match`, not a silently unpinned row.
+
+use super::*;
+
+/// `(variant, wire string, class, remediation key)` for every [`FailureCode`].
+///
+/// Order matches the enum's declaration order, which is also the serde
+/// discriminant order — not that anything depends on it, since every
+/// representation here is by name.
+const CODES: &[(FailureCode, &str, FailureClass, &str)] = &[
+ (
+ FailureCode::BudgetExhausted,
+ "budget_exhausted",
+ FailureClass::Unrecoverable,
+ "memory.health.remediation.budget_exhausted",
+ ),
+ (
+ FailureCode::AuthMissing,
+ "auth_missing",
+ FailureClass::Unrecoverable,
+ "memory.health.remediation.auth_missing",
+ ),
+ (
+ FailureCode::AuthInvalid,
+ "auth_invalid",
+ FailureClass::Unrecoverable,
+ "memory.health.remediation.auth_invalid",
+ ),
+ (
+ FailureCode::EmbeddingsUnconfigured,
+ "embeddings_unconfigured",
+ FailureClass::Unrecoverable,
+ "memory.health.remediation.embeddings_unconfigured",
+ ),
+ (
+ FailureCode::EmbeddingDimMismatch,
+ "embedding_dim_mismatch",
+ FailureClass::Unrecoverable,
+ "memory.health.remediation.embedding_dim_mismatch",
+ ),
+ (
+ FailureCode::LocalModelUnavailable,
+ "local_model_unavailable",
+ FailureClass::Transient,
+ "memory.health.remediation.local_model_unavailable",
+ ),
+ (
+ FailureCode::ExtractionTimeout,
+ "extraction_timeout",
+ FailureClass::Transient,
+ "memory.health.remediation.extraction_timeout",
+ ),
+ (
+ FailureCode::SummarizerUnavailable,
+ "summarizer_unavailable",
+ FailureClass::Unrecoverable,
+ "memory.health.remediation.summarizer_unavailable",
+ ),
+ (
+ FailureCode::EmptyInputRefused,
+ "empty_input_refused",
+ FailureClass::Unrecoverable,
+ "memory.health.remediation.empty_input_refused",
+ ),
+ (
+ FailureCode::StorageUnavailable,
+ "storage_unavailable",
+ FailureClass::Unrecoverable,
+ "memory.health.remediation.storage_unavailable",
+ ),
+ (
+ FailureCode::Transient,
+ "transient",
+ FailureClass::Transient,
+ "memory.health.remediation.transient",
+ ),
+];
+
+/// A variant added to [`FailureCode`] must be added to [`CODES`] too, or its
+/// spelling, class and remediation key go unpinned.
+///
+/// The `match` is what enforces it: adding a variant fails to compile here
+/// first, and the length assertion then fails until the table catches up.
+/// Without this, every other test in this file would keep passing over a
+/// vocabulary it no longer covers.
+#[test]
+fn every_variant_is_in_the_table() {
+ fn position(code: FailureCode) -> usize {
+ match code {
+ FailureCode::BudgetExhausted => 0,
+ FailureCode::AuthMissing => 1,
+ FailureCode::AuthInvalid => 2,
+ FailureCode::EmbeddingsUnconfigured => 3,
+ FailureCode::EmbeddingDimMismatch => 4,
+ FailureCode::LocalModelUnavailable => 5,
+ FailureCode::ExtractionTimeout => 6,
+ FailureCode::SummarizerUnavailable => 7,
+ FailureCode::EmptyInputRefused => 8,
+ FailureCode::StorageUnavailable => 9,
+ FailureCode::Transient => 10,
+ }
+ }
+
+ assert_eq!(CODES.len(), 11, "the table must cover every variant");
+ for (index, (code, ..)) in CODES.iter().enumerate() {
+ assert_eq!(position(*code), index, "table out of order at {index}");
+ }
+}
+
+/// The whole vocabulary, one row at a time: the wire string, the serde
+/// spelling, the derived class, the remediation key, and the round trip back.
+///
+/// `as_str` and the serde representation are asserted to agree — they are two
+/// independent tables (an explicit `match` and `#[serde(rename_all)]`), read by
+/// different consumers, and nothing but this makes them the same words.
+#[test]
+fn every_code_serialises_and_parses_to_its_pinned_spelling() {
+ for (code, wire, class, remediation_key) in CODES {
+ assert_eq!(code.as_str(), *wire, "as_str for {code:?}");
+ assert_eq!(
+ serde_json::to_value(code).unwrap(),
+ serde_json::json!(wire),
+ "serde spelling for {code:?}"
+ );
+ assert_eq!(
+ serde_json::from_value::<FailureCode>(serde_json::json!(wire)).unwrap(),
+ *code,
+ "serde round trip for {code:?}"
+ );
+ assert_eq!(
+ FailureCode::from_str(wire),
+ Some(*code),
+ "from_str for {code:?}"
+ );
+ assert_eq!(code.class(), *class, "class for {code:?}");
+ assert_eq!(
+ code.remediation_key(),
+ *remediation_key,
+ "remediation key for {code:?}"
+ );
+ }
+}
+
+/// The remediation keys are a frontend contract, so the *shape* is pinned too:
+/// every key is `memory.health.remediation.<the code's own wire string>`.
+///
+/// Asserted as a relation rather than as eleven more literals, because that is
+/// the property a locale file relies on — a key that drifts away from its code
+/// resolves to nothing and the panel renders a blank remediation.
+#[test]
+fn every_remediation_key_is_derived_from_its_code() {
+ for (code, wire, _, remediation_key) in CODES {
+ assert_eq!(
+ *remediation_key,
+ format!("memory.health.remediation.{wire}"),
+ "remediation key shape for {code:?}"
+ );
+ }
+}
+
+/// A code this build has no variant for is `None`, not a nearest guess.
+#[test]
+fn an_unknown_code_does_not_parse() {
+ assert_eq!(FailureCode::from_str("a_cause_this_build_never_heard_of"), None);
+ assert_eq!(FailureCode::from_str(""), None);
+ // Casing is not normalised: the wire is snake_case and only snake_case.
+ assert_eq!(FailureCode::from_str("Auth_Missing"), None);
+ assert_eq!(FailureCode::from_str("AuthMissing"), None);
+}
+
+/// Both `FailureClass` spellings, in both directions.
+#[test]
+fn failure_class_serialises_to_its_pinned_spelling() {
+ for (class, wire) in [
+ (FailureClass::Transient, "transient"),
+ (FailureClass::Unrecoverable, "unrecoverable"),
+ ] {
+ assert_eq!(class.as_str(), wire);
+ assert_eq!(
+ serde_json::to_value(class).unwrap(),
+ serde_json::json!(wire)
+ );
+ assert_eq!(
+ serde_json::from_value::<FailureClass>(serde_json::json!(wire)).unwrap(),
+ class
+ );
+ }
+}
+
+/// `PipelineFailure`'s object shape: three fields always, `detail` only when
+/// present. Field names are asserted as an exact object, so a rename cannot
+/// pass by adding a field the assertion does not mention.
+#[test]
+fn pipeline_failure_object_shape_is_unchanged() {
+ let bare = PipelineFailure::new(FailureCode::EmbeddingsUnconfigured);
+ assert_eq!(
+ serde_json::to_value(&bare).unwrap(),
+ serde_json::json!({
+ "code": "embeddings_unconfigured",
+ "class": "unrecoverable",
+ "remediation_key": "memory.health.remediation.embeddings_unconfigured",
+ }),
+ "detail is omitted when None, never emitted as null"
+ );
+
+ let detailed = PipelineFailure::new(FailureCode::Transient).with_detail("boom");
+ assert_eq!(
+ serde_json::to_value(&detailed).unwrap(),
+ serde_json::json!({
+ "code": "transient",
+ "class": "transient",
+ "remediation_key": "memory.health.remediation.transient",
+ "detail": "boom",
+ })
+ );
+}
+
+/// The deserialisation tolerance the wire has always had: `detail` may be
+/// absent. Older payloads (and the driver's own, when it attaches none) omit
+/// it, so `#[serde(default)]` is load-bearing rather than decoration.
+#[test]
+fn pipeline_failure_deserialises_without_a_detail() {
+ let parsed: PipelineFailure = serde_json::from_str(
+ r#"{"code":"auth_missing","class":"unrecoverable","remediation_key":"k"}"#,
+ )
+ .expect("detail is optional");
+ assert_eq!(parsed.code, FailureCode::AuthMissing);
+ assert_eq!(parsed.class, FailureClass::Unrecoverable);
+ assert_eq!(parsed.remediation_key, "k");
+ assert_eq!(parsed.detail, None);
+}
+
+/// `new` derives the class and the remediation key from the code, and
+/// `is_unrecoverable` reads the class rather than re-deriving from the code —
+/// which is what lets `report`/`rpc` override a class the driver stated
+/// without the two disagreeing.
+#[test]
+fn new_derives_class_and_key_and_is_unrecoverable_reads_the_class() {
+ for (code, _, class, remediation_key) in CODES {
+ let failure = PipelineFailure::new(*code);
+ assert_eq!(failure.class, *class);
+ assert_eq!(failure.remediation_key, *remediation_key);
+ assert_eq!(failure.detail, None);
+ assert_eq!(
+ failure.is_unrecoverable(),
+ *class == FailureClass::Unrecoverable
+ );
+ }
+
+ let mut overridden = PipelineFailure::new(FailureCode::BudgetExhausted);
+ assert!(overridden.is_unrecoverable());
+ overridden.class = FailureClass::Transient;
+ assert!(!overridden.is_unrecoverable());
+}
+
+/// `with_detail` caps at 200 **characters** and marks the cut with `…`.
+///
+/// Characters, not bytes: a byte slice would panic on a multi-byte boundary,
+/// and the detail can carry a provider's non-ASCII error body.
+#[test]
+fn with_detail_truncates_by_characters_and_marks_the_cut() {
+ let short = PipelineFailure::new(FailureCode::Transient).with_detail("x");
+ assert_eq!(short.detail.as_deref(), Some("x"));
+
+ let exact = PipelineFailure::new(FailureCode::Transient).with_detail("a".repeat(200));
+ assert_eq!(exact.detail.as_deref().unwrap().chars().count(), 200);
+ assert!(!exact.detail.as_deref().unwrap().ends_with('…'));
+
+ let long = PipelineFailure::new(FailureCode::Transient).with_detail("a".repeat(250));
+ let detail = long.detail.as_deref().unwrap();
+ assert_eq!(detail.chars().count(), 201, "200 kept plus the ellipsis");
+ assert!(detail.ends_with('…'));
+
+ // Multi-byte input must not be sliced mid-codepoint.
+ let wide = PipelineFailure::new(FailureCode::Transient).with_detail("é".repeat(250));
+ let detail = wide.detail.as_deref().unwrap();
+ assert_eq!(detail.chars().count(), 201);
+ assert!(detail.starts_with('é'));
+}
+
+/// The `Display` rendering that reaches logs: `code (class)`, with the detail
+/// appended only when there is one.
+#[test]
+fn pipeline_failure_display_is_unchanged() {
+ assert_eq!(
+ PipelineFailure::new(FailureCode::AuthMissing).to_string(),
+ "auth_missing (unrecoverable)"
+ );
+ assert_eq!(
+ PipelineFailure::new(FailureCode::AuthMissing)
+ .with_detail("boom")
+ .to_string(),
+ "auth_missing (unrecoverable): boom"
+ );
+}
+
+/// `DegradedState`'s object shape: the three flags always present (`storage`
+/// has `#[serde(default)]` and deliberately **no** `skip_serializing_if`),
+/// `cause` only when known.
+#[test]
+fn degraded_state_object_shape_is_unchanged() {
+ assert_eq!(
+ serde_json::to_value(DegradedState::default()).unwrap(),
+ serde_json::json!({
+ "semantic_recall": false,
+ "structure": false,
+ "storage": false,
+ }),
+ "all three flags are emitted; cause is omitted when None"
+ );
+
+ assert_eq!(
+ serde_json::to_value(DegradedState {
+ semantic_recall: true,
+ structure: true,
+ storage: true,
+ cause: Some(PipelineFailure::new(FailureCode::AuthInvalid).with_detail("d")),
+ })
+ .unwrap(),
+ serde_json::json!({
+ "semantic_recall": true,
+ "structure": true,
+ "storage": true,
+ "cause": {
+ "code": "auth_invalid",
+ "class": "unrecoverable",
+ "remediation_key": "memory.health.remediation.auth_invalid",
+ "detail": "d",
+ },
+ })
+ );
+}
+
+/// An older client's payload — no `storage`, no `cause` — still deserialises,
+/// with `storage` defaulting to `false`. That backward compatibility is the
+/// whole reason `storage` carries `#[serde(default)]`.
+#[test]
+fn degraded_state_deserialises_a_payload_without_storage_or_cause() {
+ let parsed: DegradedState =
+ serde_json::from_str(r#"{"semantic_recall":true,"structure":false}"#)
+ .expect("storage and cause are both optional");
+ assert_eq!(
+ parsed,
+ DegradedState {
+ semantic_recall: true,
+ structure: false,
+ storage: false,
+ cause: None,
+ }
+ );
+}
+
+/// `is_degraded` is the OR of the three flags and ignores `cause` — a cause
+/// with no flag set is a report about something already cleared, not a
+/// degradation.
+#[test]
+fn is_degraded_is_the_or_of_the_three_flags() {
+ assert!(!DegradedState::default().is_degraded());
+ for state in [
+ DegradedState {
+ semantic_recall: true,
+ ..Default::default()
+ },
+ DegradedState {
+ structure: true,
+ ..Default::default()
+ },
+ DegradedState {
+ storage: true,
+ ..Default::default()
+ },
+ ] {
+ assert!(state.is_degraded());
+ }
+ assert!(!DegradedState {
+ cause: Some(PipelineFailure::new(FailureCode::Transient)),
+ ..Default::default()
+ }
+ .is_degraded());
+}