Writing an EnricherPlugin for Brain
Brain's plugin system has one constraint that surprises most people when they first read about it: all plugins are compiled into the binary. There is no dynamic loading, no plugin marketplace, no WASM sandbox, no FFI bridge. If you want to extend Brain's behavior, you implement a Rust trait, register it in PluginRegistry at startup, and ship a new binary.
This is deliberate. Every running Brain instance is fully auditable — you can inspect the binary, check its dependency tree, and know with certainty what code is executing in your memory pipeline. There's no runtime surprise from a dynamically loaded plugin that wasn't reviewed, no version drift between plugin and host, no sandbox escape surface. The tradeoff is that adding a plugin requires a compile step. For a system that handles memory — which is to say, stores and returns information about your users — we decided that audibility was worth the deployment friction.
The two plugin types
Brain defines two extension traits, each with a different role:
EnricherPlugin — runs inside the write pipeline, after entity resolution and before deduplication. Receives a mutable slice of candidate memories for the current turn batch. Can add tags, adjust confidence, filter candidates, or attach external metadata. This is the one that ships today.
ConnectorPlugin — pulls external data into the write pipeline on a schedule. The trait is defined and the interface is stable; the built-in implementations (Google Drive, GitHub, Notion, Slack) are not yet shipped. The trait exists so you can implement it for your internal systems now.
Where in the pipeline enrichers run
pre_filter → extract → resolve_refs → [ENRICHERS HERE] → dedupe → conflict → persistThe position is specific and intentional. After resolve_refs, every candidate memory has a stable EntityId for its subject — not a pronoun, not an alias, not "my manager," but the canonical ent_priya_XYZ that persists across sessions. You know exactly who each memory is about.
Before dedupe, the candidate set hasn't been collapsed yet. Near-duplicate candidates are still separate items. This means you can:
- Add tags that affect how deduplication scores candidates against existing memories
- Boost or reduce confidence on candidates based on external signals, changing which ones survive the conflict-detection phase
- Filter candidates outright if your domain rules say they shouldn't be stored
If enrichers ran before entity resolution, you'd receive unresolved subjects. If they ran after dedup, you'd see fewer candidates (the interesting borderline cases would already be merged or dropped). The position gives you the richest input at the moment when enrichment is most useful.
The trait hierarchy
Every plugin implements RecallPlugin as a base — the name predates the
Recall → Brain rename and is still what the trait is called in
brain-plugins:
pub trait RecallPlugin {
fn plugin_id(&self) -> &'static str;
fn plugin_name(&self) -> &'static str;
fn initialize(&self, config: &serde_json::Value) -> PluginResult<()>;
fn shutdown(&self) -> PluginResult<()> { Ok(()) } // default: no-op
}That is the whole base trait. There is no post-persist hook — no
on_write, and no WriteOutcome type — so a plugin participates in the write
path at exactly one point, and the two specialisations are where the work
happens:
pub trait EnricherPlugin: RecallPlugin {
fn enrich(&self, input: EnricherInput<'_>) -> PluginResult<EnricherOutput>;
}
pub trait ConnectorPlugin: RecallPlugin { /* external fetch */ }EnricherPlugin extends it:
pub trait EnricherPlugin: RecallPlugin {
fn enrich(&self, input: EnricherInput<'_>) -> PluginResult<EnricherOutput>;
}
pub struct EnricherInput<'a> {
pub space_id: SpaceId,
/// Candidates from the upstream extractor tiers. Push to add, `retain` to
/// drop, mutate fields to enrich.
pub items: &'a mut Vec<ExtractedItem>,
/// The text the items were extracted from, for context.
pub source_text: &'a str,
/// One clock reading for the whole batch — use this, not the system clock.
pub now_unix_nanos: u64,
}enrich receives one EnricherInput, not a pair of arguments, and returns
counters rather than (). The items come through by mutable reference, so you
iterate and modify in place; all mutations are visible to the next enricher in
the chain, which runs in registration order.
PluginResult<T> uses boxed errors, not anyhow — this is intentional. Plugins are third-party code; using anyhow would force a specific error handling strategy on plugin authors. Boxed errors are more flexible and work with any error type that implements std::error::Error.
A complete working example: domain ontology tagger
Suppose your users are software engineers, and your codebase has a well-defined ontology: certain entity IDs are products, certain ones are teams, certain ones are external vendors. You want this classification added to memory candidates before they're stored, both for retrieval filtering and for downstream analytics.
Here's a complete implementation:
use std::collections::HashMap;
use std::sync::Arc;
use brain_plugins::{EnricherInput, EnricherOutput, EnricherPlugin, PluginResult, RecallPlugin};
use brain_extractors::framework::item::ExtractedItem;
pub struct OntologyEnricher {
/// Keyed on the entity qname the extractor emits, e.g. `"brain:Person"`.
entity_classes: Arc<HashMap<String, EntityClass>>,
}
#[derive(Clone, Copy)]
pub enum EntityClass {
Product,
InternalTeam,
ExternalVendor,
Person,
}
impl EntityClass {
/// A predicate PREFIX, not a tag. `ExtractedItem` has no tag field, so an
/// enrichment that retrieval needs to see has to land on a real one —
/// here, the namespace of the predicate, which `listStatements` filters
/// on exactly.
fn predicate_namespace(&self) -> &'static str {
match self {
EntityClass::Product => "product",
EntityClass::InternalTeam => "team",
EntityClass::ExternalVendor => "vendor",
EntityClass::Person => "person",
}
}
fn confidence_boost(&self) -> f32 {
match self {
EntityClass::Product => 0.05, // products are stable, boost confidence
EntityClass::Person => 0.0, // no adjustment
_ => 0.02,
}
}
}
impl RecallPlugin for OntologyEnricher {
fn plugin_id(&self) -> &'static str { "domain-ontology" }
fn plugin_name(&self) -> &'static str { "Domain Ontology Enricher" }
fn initialize(&self, _config: &serde_json::Value) -> PluginResult<()> {
// config["ontology_path"] → load the entity class map from file or DB.
// This example assumes entity_classes is populated at construction.
Ok(())
}
}
impl EnricherPlugin for OntologyEnricher {
fn enrich(&self, input: EnricherInput<'_>) -> PluginResult<EnricherOutput> {
let mut items_mutated = 0;
// `input.items` is `&mut Vec<ExtractedItem>` — push to add, `retain`
// to drop, mutate fields in place to enrich. `input` also carries
// `space_id` for per-space policy, `source_text` for context, and
// `now_unix_nanos` so every enricher in the batch sees one timestamp.
for item in input.items.iter_mut() {
let ExtractedItem::StatementMention(m) = item else { continue };
let Some(subject) = m.subject_text.as_deref() else { continue };
let Some(class) = self.entity_classes.get(subject) else { continue };
// Namespace the predicate so the read path can filter on it.
if !m.predicate_qname.contains(':') {
m.predicate_qname =
format!("{}:{}", class.predicate_namespace(), m.predicate_qname);
}
// Clamp — confidence is an f32 the downstream stages trust.
m.confidence = (m.confidence + class.confidence_boost()).clamp(0.0, 1.0);
items_mutated += 1;
}
Ok(EnricherOutput { items_added: 0, items_mutated, items_dropped: 0 })
}
}The counters in EnricherOutput are the plugin's whole report back to the
host — items_added, items_mutated, items_dropped. Return them honestly;
the registry surfaces one outcome per enricher and they are what tells an
operator a plugin is running and doing something.
Register it at startup:
let mut registry = PluginRegistry::new();
let ontology = Arc::new(OntologyEnricher {
entity_classes: Arc::new(load_ontology_from_config(&config)?),
});
// Takes the config value too — this is what `initialize` receives.
registry.register_enricher(ontology, &config.plugins.ontology)?;Enable in configuration:
plugins:
enrichers:
- id: domain-ontology
config:
ontology_path: /etc/brain/ontology.jsonAfter this enricher runs, every candidate about a product entity carries a confidence 0.05 higher than the extractor assigned.
It cannot add a tag, and nothing can retrieve by one. ExtractedItem is an
enum over entity, statement and relation variants, and none of them has a tag
or label field. (A connector is different — ConnectorItem carries
tags: Vec<String> applied verbatim to the memory it ingests. But no filter in
the retrieval surface reads them: not RecallBuilder, not listStatements,
not memoryList. They are write-side metadata with no read-side predicate.)
What an enricher can change is what is actually there:
confidence, predicate_qname, event_at_unix_nanos, retract, and the
membership of the batch itself. There is no tag filter in the retrieval surface
either, so a design that routes on labels has nowhere to put them.
What you do instead is make the enrichment land on a field retrieval can see.
Rewriting predicate_qname into a namespaced predicate is the usual move,
because listStatements filters on predicate exactly:
// The enricher rewrote the predicate to `product:decided`, so this is an
// exact filter rather than a label lookup.
const { statements } = await brain.listStatements({
predicate: "product:decided",
onlyCurrent: true,
limit: 100,
});Raising confidence works the same way — listStatements({ minConfidence }) and
RecallBuilder.confidence(threshold) both read it, so a confidence bump is an
enrichment the read path honours without any new vocabulary.
The fail-open contract
If enrich() returns an Err, the write pipeline does not abort. The error is logged at warn level, the candidate vector is unchanged (or partially changed if the enricher modified it before failing), and the pipeline continues to deduplication.
This is the fail-open contract: a failing enricher does not block memory writes.
The implication is that enrichers must not have side effects that require rollback. Don't make external writes inside enrich() and expect them to be reversed if the enricher fails later. Don't assume that if enrich() returns Ok(()), the memory will definitely be stored — downstream stages (dedup, conflict, persist) can still fail. The enricher is a best-effort decoration pass, not a transactional participant.
If an enricher fails consistently, the warn logs will accumulate. There's no built-in circuit breaker for enrichers — the assumption is that enricher failure is rare and represents a bug, not an expected operational state. Monitor plugin errors in your log aggregation.
Running I/O inside an enricher
All plugin methods are synchronous. If your enricher needs to make HTTP calls (for example, looking up entity metadata from an external API), you need to block the current thread inside enrich(). In Tokio, that means using tokio::task::block_in_place:
fn enrich(&self, input: EnricherInput<'_>) -> PluginResult<EnricherOutput> {
let subjects: Vec<&str> = input
.items
.iter()
.filter_map(|item| match item {
ExtractedItem::StatementMention(m) => m.subject_text.as_deref(),
_ => None,
})
.collect();
// Block the current thread to make an async HTTP call.
let classifications = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(self.external_api.classify_entities(&subjects))
})?;
let mut items_mutated = 0;
for (item, class) in input.items.iter_mut().zip(classifications) {
if let ExtractedItem::StatementMention(m) = item {
m.predicate_qname = format!("{}:{}", class.namespace, m.predicate_qname);
items_mutated += 1;
}
}
Ok(EnricherOutput { items_added: 0, items_mutated, items_dropped: 0 })
}The trait's own documentation is blunt about this: enrichers are sync and
must not block on tokio tasks, spawn threads, or perform synchronous IO
beyond a few microseconds. block_in_place inside the write path violates
that, and the paragraph below is the reason it is shown at all — so you can
recognise the shape and then not ship it.
This works but adds latency to every write pipeline execution. For high-throughput namespaces, consider caching external lookups in the enricher's state. The enricher is Arc<dyn EnricherPlugin> — it's shared across write pipeline threads, so internal state must be Send + Sync. Arc<Mutex<HashMap<...>>> or DashMap are good choices for a thread-safe cache.
For heavy I/O that would genuinely slow down the write path, the work does not belong in a plugin at all. There is no post-persist hook to defer it to, and the engine's own background workers — auto-edge, temporal-edge, causal-edge, statement embedding — are not extension points. Do it in your own service, triggered from your own write path once encode has returned the memoryId, and write the result back as a statement.
ConnectorPlugin: external data ingestion
The ConnectorPlugin trait defines how external data sources feed into the write pipeline:
pub trait ConnectorPlugin: RecallPlugin {
fn fetch(&self, req: ConnectorRequest) -> PluginResult<ConnectorResponse>;
}
pub struct ConnectorRequest {
/// Free-text filter applied upstream; empty means everything.
pub query: String,
/// Watermark from the prior successful fetch. `None` on the first call —
/// pick a sensible default, e.g. the past 24 hours.
pub since_unix_nanos: Option<u64>,
/// Hard cap. Return more and the host truncates the excess itself.
pub max_items: u32,
}
pub struct ConnectorItem {
/// Upstream-stable id, used by the host to deduplicate across fetches.
pub external_id: String,
pub text: String,
pub created_at_unix_nanos: u64,
pub source_url: Option<String>,
/// Applied verbatim to the encoded memory.
pub tags: Vec<String>,
}
pub struct ConnectorResponse {
pub items: Vec<ConnectorItem>,
/// New watermark, persisted verbatim by the scheduler.
pub next_since_unix_nanos: u64,
}Three parts of that contract are load-bearing. external_id is how the host
deduplicates across fetches, so it must be stable upstream — a changing id
re-ingests the same document. next_since_unix_nanos must be
monotonically non-decreasing, because the scheduler persists it as its
watermark and a value that goes backward re-reads history forever. And
max_items is enforced by the host, not trusted from the plugin:
fetch_from_connector truncates the excess fail-open, so an over-eager
connector cannot flood the encode pipeline.
Errors propagate to the scheduler, which logs them and retries on the next tick. A connector that fails repeatedly may be paused — unlike an enricher, whose failure is simply skipped for that batch.
The scheduler calls each connector on its own cadence and sends the items through the standard write pipeline.
Built-in implementations for Google Drive, GitHub, Notion, and Slack are on the roadmap. If you need any of these today, implementing ConnectorPlugin for your internal data source is straightforward — the fetch() method is simple: return a list of items with content and optional metadata.
Example: a Notion connector for your company wiki:
pub struct NotionConnector {
client: Arc<NotionApiClient>,
page_ids: Vec<String>,
}
impl ConnectorPlugin for NotionConnector {
fn fetch(&self, req: ConnectorRequest) -> PluginResult<ConnectorResponse> {
let pages = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(
self.client
.fetch_pages_modified_since(&self.page_ids, req.since_unix_nanos),
)
})?;
let pages: Vec<_> = pages.into_iter().take(req.max_items as usize).collect();
let mut newest = req.since_unix_nanos.unwrap_or(0);
let items = pages
.into_iter()
.map(|p| {
newest = newest.max(p.last_edited_unix_nanos);
ConnectorItem {
// Stable across edits — this is what dedup keys on.
external_id: p.id.clone(),
// The title belongs in the text; there is no title field.
text: format!("{}\n\n{}", p.title, p.plain_text),
created_at_unix_nanos: p.last_edited_unix_nanos,
source_url: Some(format!("https://notion.so/{}", p.id)),
tags: vec!["source:notion".to_string()],
}
})
.collect();
// Never below the watermark we were handed.
Ok(ConnectorResponse { items, next_since_unix_nanos: newest })
}
}Note what is not there: no title and no content field. The text is one
string, so a title that matters goes into it — which is also what makes it
searchable by the lexical lane. From the pipeline's perspective a Notion page
is just more text to extract from.
When not to use a plugin
Plugins solve a specific problem: extending Brain's behavior from inside the write pipeline with domain-specific logic. They're the wrong tool for several related problems:
Document ingestion (PDFs, HTML, Word) — extract text upstream using Docling, LlamaParse, or similar tools, then pass the extracted plain text to remember(). Brain's write pipeline expects conversational turn text, not raw document formats. Trying to handle document parsing inside a plugin puts the wrong complexity in the wrong place.
Custom memory kinds — a memory's kind is Episodic, Semantic or
Consolidated, and that enum is fixed in the data model. Plugins cannot add
one. What is extensible is the typed schema above it: statement kinds are
fact, preference, event, attribute, relation and directive, and the
predicates and entity types within them come from a schema document you upload
(uploadSchema, validateSchema, listSchemas). So a domain type belongs in
your schema namespace, not in a plugin — and not in tags, which no retrieval
filter reads.
Backpressure-sensitive I/O — if your enricher calls an external API that can be slow or unavailable, and you need proper backpressure handling (rate limiting, circuit breaking, retry with exponential backoff), the synchronous plugin interface is awkward. Consider fetching external data in a separate service and caching the results in the enricher's in-process state, refreshed on a schedule.
Complex read-time logic — there is no on_read plugin hook today. Read-time plugins (for re-ranking, post-processing, or formatting) are deferred until enricher use cases are validated. If you need read-time customisation, ask the recall for its trace
(includeTrace: true, or queryTrace for a structured query) to see what each
lane scored, and adjust retrieval configuration rather than trying to hook into
the path.
What's coming
The roadmap includes:
- Built-in
ConnectorPluginimplementations (Google Drive, GitHub, Notion, Slack) - An
on_readplugin hook for read-time post-processing - A plugin configuration validator that catches mismatches between plugin requirements and runtime config at startup, rather than at first call
The compile-time constraint is not going away. If you need a use case that genuinely requires dynamic plugin loading — for example, multiple teams shipping plugins independently without coordinating binary builds — the right answer is to run separate Brain instances with different build configurations, not to add dynamic loading to a single instance.
Plugin feature flags: the pdf-extract and scraper crates for document preprocessing are behind Cargo feature flags (off by default) to avoid pulling heavy dependencies into every binary. Enable them in your Cargo.toml only if your enricher needs them.
Chaining multiple enrichers
Multiple enrichers can be registered and run sequentially. Each enricher in the chain sees the mutations of all previous enrichers, so composition is natural: a predicate namespacer runs first, and a confidence adjuster runs second with the namespaced predicate already in place. The two concerns stay separate in code while cooperating at runtime.
What the second one reads is the predicate, not a tag — there is no tag
field for enricher A to have written, so the hand-off has to go through a real
field on ExtractedItem.
let mut registry = PluginRegistry::new();
// Order matters: the ontology enricher runs first and namespaces predicates.
registry.register_enricher(
Arc::new(OntologyEnricher { entity_classes: Arc::new(load_ontology()?) }),
&serde_json::Value::Null,
)?;
// The confidence adjuster runs second and keys off that namespace.
registry.register_enricher(
Arc::new(ConfidenceAdjuster {
rules: vec![
// Products are stable — raise confidence.
AdjustmentRule { namespace: "product", delta: 0.08 },
// Vendors change faster — lower it.
AdjustmentRule { namespace: "vendor", delta: -0.05 },
],
}),
&serde_json::Value::Null,
)?;impl EnricherPlugin for ConfidenceAdjuster {
fn enrich(&self, input: EnricherInput<'_>) -> PluginResult<EnricherOutput> {
let mut items_mutated = 0;
for item in input.items.iter_mut() {
let ExtractedItem::StatementMention(m) = item else { continue };
for rule in &self.rules {
if m.predicate_qname.starts_with(&format!("{}:", rule.namespace)) {
// Clamp on every write. `confidence` is the real field and
// downstream stages trust its range; there is no separate
// `confidence_adjustment` to accumulate into.
m.confidence = (m.confidence + rule.delta).clamp(0.0, 1.0);
items_mutated += 1;
}
}
}
Ok(EnricherOutput { items_added: 0, items_mutated, items_dropped: 0 })
}
}Clamping inside each enricher matters once several of them adjust
independently. Confidence is a plain f32 on the mention, not a delta the
pipeline reconciles later, so two enrichers each adding 0.08 to a 0.9 would
otherwise produce 1.06 and the invariant would break at whichever later stage
happens to notice — not at the enricher that caused it.
Registration order is the execution order. There is no dependency declaration system — if enricher B depends on enricher A's output, register A first. The absence of a formal dependency graph is intentional: enricher chains that require complex ordering are a signal that the logic belongs somewhere else (a single enricher with richer internal state, or a pre-processing step outside the plugin system). Document inter-enricher dependencies explicitly as a comment in the registration block, not in the enricher implementation itself, so the dependency is visible at the call site.
One subtlety: if an enricher returns an Err, the chain continues from the next enricher, not the beginning. The failed enricher's partial mutations (any modifications it made before the error) remain on the candidate vector. If your enricher makes partial modifications and then encounters an error, prefer reverting your changes before returning the error rather than leaving the vector in an inconsistent state. Reversions are straightforward when each enricher processes candidates independently; they're harder when an enricher's logic reads the modifications it's already made.
Testing enrichers
Enricher unit tests need no running Brain and no database. enrich takes an
EnricherInput you can build in test code, and the counters it returns are
what you assert on alongside the mutations:
#[cfg(test)]
mod tests {
use super::*;
use brain_core::SpaceId;
use brain_extractors::framework::item::{ExtractedItem, StatementMention};
fn statement(subject: &str, predicate: &str) -> ExtractedItem {
ExtractedItem::StatementMention(StatementMention {
subject_text: Some(subject.to_string()),
predicate_qname: predicate.to_string(),
confidence: 0.80,
..Default::default()
})
}
fn input<'a>(items: &'a mut Vec<ExtractedItem>) -> EnricherInput<'a> {
EnricherInput {
space_id: SpaceId::default(),
items,
source_text: "test content",
now_unix_nanos: 1_700_000_000_000_000_000,
}
}
#[test]
fn namespaces_the_predicate_of_a_known_subject() {
let mut entity_classes = HashMap::new();
entity_classes.insert("brain:Api".to_string(), EntityClass::Product);
let enricher = OntologyEnricher { entity_classes: Arc::new(entity_classes) };
let mut items = vec![
statement("brain:Api", "decided"),
statement("brain:Unknown", "decided"),
];
let out = enricher.enrich(input(&mut items)).unwrap();
// The known subject got the namespace and the confidence boost.
let ExtractedItem::StatementMention(ref m) = items[0] else { panic!() };
assert_eq!(m.predicate_qname, "product:decided");
assert!((m.confidence - 0.85).abs() < f32::EPSILON);
// The unknown one was left exactly as it arrived.
let ExtractedItem::StatementMention(ref m) = items[1] else { panic!() };
assert_eq!(m.predicate_qname, "decided");
assert!((m.confidence - 0.80).abs() < f32::EPSILON);
// And the counters report it honestly — this is what the host reads.
assert_eq!(out.items_mutated, 1);
assert_eq!(out.items_added, 0);
assert_eq!(out.items_dropped, 0);
}
#[test]
fn an_empty_batch_is_ok() {
let enricher = OntologyEnricher { entity_classes: Arc::new(HashMap::new()) };
let mut items = vec![];
let out = enricher.enrich(input(&mut items)).unwrap();
assert_eq!(out, EnricherOutput::zero());
}
}Four cases every enricher should have: the happy path; a non-matching item,
which must come back untouched; an empty batch, which must return
EnricherOutput::zero() without panicking; and the counters themselves.
That last one is easy to skip and it is the one the host actually consumes — an
enricher that mutates correctly while returning zero() looks idle to every
operator watching it.
The empty-batch case is more common in production than it sounds: upstream tiers legitimately produce no items for a turn that carried nothing durable.
Most enrichers ignore space_id and can be tested with a default. If yours
reads it for per-space policy or per-space vocabularies, vary it across
parameterised tests — a space-dependent enricher is the harder kind to reason
about in production, so the dependency is worth making visible in the test
names.
There is no in-process integration harness. brain_core::testing::TestNamespace
does not exist — no testing module ships in any crate, and nothing spins up an
ephemeral shard for you from Rust. An integration test runs the real thing: the
published image, with the enricher compiled into your build of the server.
# The engine needs io_uring, which the default seccomp profile blocks.
docker run --rm -d --name brain-it \
--security-opt seccomp=unconfined --ulimit memlock=-1 \
-p 9090:9090 -p 9091:9091 \
ghcr.io/arc-labs-ai/brain-db:0.4.0Then drive it from whichever SDK your test suite is written in and assert on
what came out of the pipeline — listStatements({ predicate: "product:decided" })
is the assertion that proves the enricher ran end to end, because the namespaced
predicate only exists if it did. Remember the enrichment is not synchronous with
the acknowledgement: wait for derivation (EncodeBuilder.wait(WaitMode.Derived)
on the wire tier) before asserting, or you will race the extractor.
Monitoring enricher performance
Enrichers add latency to the synchronous write pipeline, and the trait is explicit about the budget: they are sync, and must not block on tokio tasks, spawn threads, or perform synchronous IO beyond a few microseconds. Use plugin-side caches and pre-built indexes for anything non-trivial. The LLM extraction call dominates at 200–800ms; a well-written enricher should be nearly invisible beside it.
There is no trace API to read per-enricher spans from — no getTrace, and
nothing that returns a span list. What the pipeline gets back is the counter
struct each enricher returns:
// EnricherOutput — the whole reporting surface.
pub struct EnricherOutput {
pub items_added: u32,
pub items_mutated: u32,
pub items_dropped: u32,
}The registry collects one EnricherOutcome per registered enricher from
run_enrichers, so the host knows which plugin ran, what it changed, and
whether it failed. For timing, instrument inside enrich() and emit to your
own metrics — the counters say what happened, not how long it took.
If an enricher consistently takes more than 5ms on production-scale candidate batches, profile the enrich() method. The most common performance issue is an O(N×M) algorithm where N is the number of candidates per turn and M is the size of the enricher's lookup table. The domain ontology example above does a HashMap::get() per candidate — O(1) per lookup, O(N) total. An implementation that instead does a linear scan over the entity_classes map for each candidate is O(N×M), which becomes noticeable when M is in the thousands. The fix is always to restructure the lookup as a HashMap keyed on entity ID.
The second most common performance issue is unnecessary allocation. If your
enricher builds a new String for every item even when most items match no
rule, you are allocating on the hot path. Test the cheap predicate first — a
starts_with or a map lookup — and only then format.
A steady stream of errors from an enricher's external dependency means that dependency is flaky. The fail-open contract means those errors do not block writes — the registry catches them and skips the failing plugin for that batch — but it also means the affected items are stored without the enrichment. That is a silent quality loss that accumulates, and it is exactly the failure shape the counters exist to surface.
A local in-process cache absorbs transient failures:
pub struct CachingOntologyEnricher {
entity_classes: Arc<HashMap<String, EntityClass>>,
cache: Arc<DashMap<String, EntityClass>>,
}
impl EnricherPlugin for CachingOntologyEnricher {
fn enrich(&self, input: EnricherInput<'_>) -> PluginResult<EnricherOutput> {
let mut items_mutated = 0;
for item in input.items.iter_mut() {
let ExtractedItem::StatementMention(m) = item else { continue };
let Some(subject) = m.subject_text.as_deref() else { continue };
// Cache first, then the static config. No network call in here —
// the trait forbids IO beyond a few microseconds.
let class = self
.cache
.get(subject)
.map(|e| *e.value())
.or_else(|| self.entity_classes.get(subject).copied());
if let Some(c) = class {
m.predicate_qname =
format!("{}:{}", c.predicate_namespace(), m.predicate_qname);
items_mutated += 1;
}
}
Ok(EnricherOutput { items_added: 0, items_mutated, items_dropped: 0 })
}
}Prefer a DashMap over a Mutex<HashMap> for the access pattern enrichers
see: the Arc<dyn EnricherPlugin> is shared, so several write-pipeline threads
may be inside enrich at once, and DashMap is sharded rather than serialised.
Populate it from outside the enricher — a background refresh task in your own
code — because enrich itself has no budget to fetch anything.
There are no plugin metrics. No brain_plugin_errors_total, and nothing
labelled by plugin_id anywhere in the 74 series — so you cannot alert on a
plugin's error rate from Brain's /metrics. What exists is the
EnricherOutcome the registry returns per enricher per batch, which says which
plugin ran, what it changed and whether it failed. Emit your own counter from
inside enrich if you want an error rate, and keep the thresholds in your own
monitoring: at 10,000 memories a day, a 1% failure rate is 100 memories a day
stored without their enrichment, which is small in absolute terms and
compounding as the space grows.
Deferring expensive enrichment
An enricher is sync and runs inside the write path, so anything that touches the network or takes real time cannot go in one. The question is where it goes instead, and the answer is outside Brain: there is no post-persist hook to hand the work to.
The pattern is to let the write complete, then enrich from your own service:
// 1. The write returns as soon as the memory is durable.
const { memoryId } = await brain.encode({ text: turn, session: conversationId });
// 2. Your own queue. Brain has no hook that would run this for you.
await queue.publish({ memoryId, text: turn });
// 3. In the worker, when the slow classifier eventually answers, write the
// result back as a claim on the typed graph — the enrichment becomes a
// statement, which `listStatements` can filter on exactly.
const label = await slowClassifier.classify(text);
await brain.createStatement({
kind: "attribute",
subject: subjectEntityId,
predicate: `classifier:${label.name}`,
object: { value: label.value },
confidence: label.confidence,
evidence: [memoryId], // ties the claim back to its source memory
});This is better than the hook would have been, for a reason worth stating: the
enrichment lands as a statement with evidence, so it carries its own
provenance — which extractor produced it (extractorId), when
(extractedAtUnixNanos), and which memory it rests on. A tag written into a
record after the fact carries none of that.
The visibility window is real and does not go away. From the moment encode
returns, the memory is in the index and recallable; your statement does not
exist yet. There is no union query to paper over it — no created_after, no
tags_absent, no operator: "OR" in the retrieval surface — so handle it
where it actually is:
- Read the memory and the statement separately:
recallfinds the memory, andlistStatements({ predicate })finds the enrichment. A memory with no statement yet is simply a memory with no statement yet, which your caller can reason about. - Or don't call until the statement exists, if the enrichment is load-bearing
for the answer.
encodereturning is not a promise that derivation finished — on the wire tier,EncodeBuilder.wait(WaitMode.Derived)is the knob that waits for the engine's own derivation before acknowledging.
Cap your own concurrency in your own worker, as you would for any queue. There is no plugin executor to saturate, because there is no plugin running here.