Skip to content

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

Wait for the module on every write, not just nine of them

Shanu42f1244ecf08
diff --git a/src/openhuman/modules/memory_part_01.rs b/src/openhuman/modules/memory_part_01.rs
index 8013442394..1734300313 100644
--- a/src/openhuman/modules/memory_part_01.rs
+++ b/src/openhuman/modules/memory_part_01.rs
@@ -229,24 +229,66 @@ pub(crate) fn policy() -> Option<&'static Arc<Config>> {
/// "timed out".
const MODULE_LOADING_GRACE: Duration = Duration::from_secs(8);
-/// Operations that keep waiting while the module loads.
+/// The operations a caller may stop waiting for. **Everything else waits.**
///
-/// A write that gives up is lost work: the message a chat turn autosaves, a
-/// sync an operator kicked off, the shutdown that releases queue locks. Those
-/// wait for the outcome however long a cold download takes, exactly as every
-/// call did before the wait was bounded. Reads are the other case — a page or
-/// a turn that is better served by "memory is loading" now than by the result
-/// in three minutes — and every operation not named here is treated as one.
-const UNBOUNDED_OPERATIONS: &[&str] = &[
- "store",
- "import_records",
- "ingest_coding_sessions",
- "run_source_sync",
- "run_connection_sync",
- "bootstrap_connection",
- "forget",
- "override_scheduler_gate",
- "shutdown",
+/// A write that gives up is lost work: the message a chat turn autosaves, the
+/// turn the archivist records after the fact, a sync an operator kicked off,
+/// the shutdown that releases queue locks. None of those has a retry above it,
+/// so a `Unavailable` answer during a cold load does not delay the write — it
+/// discards it. Reads are the other case: a page or a turn is better served by
+/// "memory is loading" now than by the right answer three minutes from now.
+///
+/// # Why this names the reads and not the writes
+///
+/// It was the other way round first, and that was a bug. Listing the *writes*
+/// makes every unlisted member a read, so the default for anything the list
+/// forgets — or anything a future contract adds — is to drop the call. The
+/// first version of this list named nine operations out of seventy and
+/// silently classified `ingest_document`, `ingest_chat`, `insert_turn`,
+/// `set_goals`, `append` and two dozen other mutations as reads.
+///
+/// Naming the reads inverts the failure: a member nobody classified waits for
+/// the module, which costs a slow first call on a cold launch and loses
+/// nothing. Add a read here only when it genuinely cannot mutate — when in
+/// doubt, leave it out and it waits.
+const BOUNDED_READ_OPERATIONS: &[&str] = &[
+ "answer",
+ "chunk_detail",
+ "chunk_score",
+ "count_chunks",
+ "cover_window",
+ "degraded_state",
+ "diagnose",
+ "doctor",
+ "embed_text",
+ "embedder_slug",
+ "export_page",
+ "flavour_profile",
+ "get",
+ "get_chunk",
+ "get_facet",
+ "get_person",
+ "goals",
+ "health",
+ "list",
+ "list_active_facets",
+ "list_all_facets",
+ "list_chunks",
+ "list_namespaces",
+ "list_people",
+ "namespaces",
+ "queue_stats",
+ "recall",
+ "score_person",
+ "session_turns",
+ "snapshots",
+ "storage_kinds",
+ "store_stats",
+ "sync_audit_log",
+ "sync_statuses",
+ "tool_rules",
+ "top_entities",
+ "workflow_identity_matches",
];
/// Install the host-side callbacks the module reaches for while it loads.
@@ -345,11 +387,13 @@ impl ModuleMemoryProvider {
}
/// How long `operation` may wait for the module: `None` waits it out.
+ ///
+ /// Unrecognised operations wait — see [`BOUNDED_READ_OPERATIONS`].
fn loading_grace(&self, operation: &str) -> Option<Duration> {
- if UNBOUNDED_OPERATIONS.contains(&operation) {
- None
- } else {
+ if BOUNDED_READ_OPERATIONS.contains(&operation) {
Some(self.loading_grace)
+ } else {
+ None
}
}
@@ -519,163 +563,6 @@ fn from_bus(error: &tinybus::Error) -> MemoryError {
wire::from_wire(error.wire_name(), &error.to_string())
}
-#[async_trait]
-impl MemoryProvider for ModuleMemoryProvider {
- fn driver_id(&self) -> &str {
- &self.driver_id
- }
-
- /// The families the **pinned artifact** serves — not the whole contract.
- ///
- /// # This couples to the registry pin, and the coupling IS enforced
- ///
- /// `Capabilities::all()` grows whenever a family is added to the contract,
- /// but the *artifact* only grows when a release is cut and
- /// [`registry`](super::registry) is re-pinned to it. Returning `all()`
- /// between those two moments over-claimed: the host said it could do
- /// something the loaded binary could not, and [`Self::verify`] noticed and
- /// logged it without narrowing the advertised set. The failure mode was a
- /// call that reached the module and came back `UnknownMethod` (#5598)
- /// rather than a family that cleanly reported itself absent.
- ///
- /// [`ARTIFACT_CAPABILITIES`] is now the source of truth, and
- /// `the_capability_list_matches_the_pinned_release` fails if it is widened
- /// without moving [`ARTIFACT_CAPABILITIES_PIN`] and the registry pin
- /// together.
- ///
- /// The kernel filters its RPC surface and agent-tool assembly from this set,
- /// and the guard builds one family decorator per `provides()`, so an
- /// over-claim here is precisely what turns an absent family into a live
- /// method that answers `UnknownMethod`.
- fn capabilities(&self) -> Capabilities {
- artifact_capabilities()
- }
-
- async fn health(&self) -> MemoryHealth {
- // An unreachable module is a *health* answer, not an error: that is the
- // question this method exists to answer, and returning `Down` is how
- // status output shows an unsupported platform or a refused artifact.
- //
- // A module that is still loading is *not* down. `Down` is the signal
- // that tells the kernel to give up on this driver and rebind the
- // fallback, and a cold launch on a slow link must not trip it; the
- // driver is serving, just not yet. Configuration stays authoritative:
- // a host whose modules are switched off is down whatever the
- // process-wide table says about a load someone else started.
- let modules_enabled = self
- .config
- .as_ref()
- .or_else(|| policy())
- .is_some_and(|config| config.modules.enabled);
- if modules_enabled && matches!(ops::state_of(MODULE_ID), super::types::ModuleState::Loading)
- {
- return MemoryHealth::degraded("the memory module is loading");
- }
- match self.proxy("health").await {
- Ok(proxy) => proxy
- .call::<MemoryHealth>("Health", ())
- .await
- .unwrap_or_else(|error| MemoryHealth::down(error.to_string())),
- Err(MemoryError::Unavailable(reason)) => MemoryHealth::degraded(reason),
- Err(error) => MemoryHealth::down(error.to_string()),
- }
- }
-
- async fn shutdown(&self) -> Result<(), MemoryError> {
- // Deliberately does not load the module in order to shut it down: a
- // shutdown on a driver that was never used should be a no-op, not a
- // download. tinybus never unloads a library anyway, so this releases
- // backend resources only.
- if self.verified.get().is_none() {
- return Ok(());
- }
- let proxy = self.proxy("shutdown").await?;
- proxy
- .call::<()>(methods::SHUTDOWN, ())
- .await
- .map_err(|error| from_bus(&error))
- }
-
- fn as_ingest(&self) -> Option<&dyn MemoryIngest> {
- Some(self)
- }
- fn as_documents(&self) -> Option<&dyn MemoryDocuments> {
- Some(self)
- }
- fn as_tree(&self) -> Option<&dyn MemoryTree> {
- Some(self)
- }
- fn as_entities(&self) -> Option<&dyn MemoryEntities> {
- Some(self)
- }
- fn as_graph(&self) -> Option<&dyn MemoryGraph> {
- Some(self)
- }
- fn as_diff(&self) -> Option<&dyn MemoryDiff> {
- Some(self)
- }
- fn as_goals(&self) -> Option<&dyn MemoryGoals> {
- Some(self)
- }
- fn as_tool_memory(&self) -> Option<&dyn MemoryToolMemory> {
- Some(self)
- }
- fn as_sources(&self) -> Option<&dyn MemorySourceSink> {
- Some(self)
- }
- fn as_maintenance(&self) -> Option<&dyn MemoryMaintenance> {
- Some(self)
- }
- // The four families below are gated on the pinned artifact rather than
- // returning `Some(self)` unconditionally. `provides()` derives from these
- // accessors, the guard builds its decorators from `provides()`, and every
- // caller already writes a clean "driver does not support the X family"
- // error on `None` — so gating here converts a deep `UnknownMethod` into an
- // early, accurate refusal at every call site at once (#5598).
- fn as_people(&self) -> Option<&dyn MemoryPeople> {
- artifact_serves(Capability::People).then_some(self as &dyn MemoryPeople)
- }
- fn as_chunks(&self) -> Option<&dyn MemoryChunks> {
- artifact_serves(Capability::Chunks).then_some(self as &dyn MemoryChunks)
- }
- fn as_retrieval(&self) -> Option<&dyn MemoryRetrieval> {
- artifact_serves(Capability::Retrieval).then_some(self as &dyn MemoryRetrieval)
- }
- fn as_profile(&self) -> Option<&dyn MemoryProfile> {
- artifact_serves(Capability::Profile).then_some(self as &dyn MemoryProfile)
- }
-
- fn as_source_sync(&self) -> Option<&dyn MemorySourceSync> {
- artifact_serves(Capability::SourceSync).then_some(self as &dyn MemorySourceSync)
- }
-
- fn as_coding_sessions(&self) -> Option<&dyn MemoryCodingSessions> {
- artifact_serves(Capability::CodingSessions).then_some(self as &dyn MemoryCodingSessions)
- }
- fn as_episodic(&self) -> Option<&dyn MemoryEpisodic> {
- artifact_serves(Capability::Episodic).then_some(self as &dyn MemoryEpisodic)
- }
- fn as_scoring(&self) -> Option<&dyn MemoryScoring> {
- artifact_serves(Capability::Scoring).then_some(self as &dyn MemoryScoring)
- }
- fn as_document_ingest(&self) -> Option<&dyn MemoryDocumentIngest> {
- artifact_serves(Capability::DocumentIngest).then_some(self as &dyn MemoryDocumentIngest)
- }
- fn as_conversation_ingest(&self) -> Option<&dyn MemoryConversationIngest> {
- artifact_serves(Capability::ConversationIngest)
- .then_some(self as &dyn MemoryConversationIngest)
- }
- fn as_learning_ingest(&self) -> Option<&dyn MemoryLearningIngest> {
- artifact_serves(Capability::LearningIngest).then_some(self as &dyn MemoryLearningIngest)
- }
- fn as_event_ingest(&self) -> Option<&dyn MemoryEventIngest> {
- artifact_serves(Capability::EventIngest).then_some(self as &dyn MemoryEventIngest)
- }
- fn as_answer(&self) -> Option<&dyn MemoryAnswer> {
- artifact_serves(Capability::Answer).then_some(self as &dyn MemoryAnswer)
- }
-}
-
macro_rules! module_call {
($self:expr, $operation:literal, $method:expr, $args:expr) => {
diff --git a/src/openhuman/modules/memory_part_04.rs b/src/openhuman/modules/memory_part_04.rs
index 6320947388..fa587a2d7a 100644
--- a/src/openhuman/modules/memory_part_04.rs
+++ b/src/openhuman/modules/memory_part_04.rs
@@ -1,3 +1,160 @@
+#[async_trait]
+impl MemoryProvider for ModuleMemoryProvider {
+ fn driver_id(&self) -> &str {
+ &self.driver_id
+ }
+
+ /// The families the **pinned artifact** serves — not the whole contract.
+ ///
+ /// # This couples to the registry pin, and the coupling IS enforced
+ ///
+ /// `Capabilities::all()` grows whenever a family is added to the contract,
+ /// but the *artifact* only grows when a release is cut and
+ /// [`registry`](super::registry) is re-pinned to it. Returning `all()`
+ /// between those two moments over-claimed: the host said it could do
+ /// something the loaded binary could not, and [`Self::verify`] noticed and
+ /// logged it without narrowing the advertised set. The failure mode was a
+ /// call that reached the module and came back `UnknownMethod` (#5598)
+ /// rather than a family that cleanly reported itself absent.
+ ///
+ /// [`ARTIFACT_CAPABILITIES`] is now the source of truth, and
+ /// `the_capability_list_matches_the_pinned_release` fails if it is widened
+ /// without moving [`ARTIFACT_CAPABILITIES_PIN`] and the registry pin
+ /// together.
+ ///
+ /// The kernel filters its RPC surface and agent-tool assembly from this set,
+ /// and the guard builds one family decorator per `provides()`, so an
+ /// over-claim here is precisely what turns an absent family into a live
+ /// method that answers `UnknownMethod`.
+ fn capabilities(&self) -> Capabilities {
+ artifact_capabilities()
+ }
+
+ async fn health(&self) -> MemoryHealth {
+ // An unreachable module is a *health* answer, not an error: that is the
+ // question this method exists to answer, and returning `Down` is how
+ // status output shows an unsupported platform or a refused artifact.
+ //
+ // A module that is still loading is *not* down. `Down` is the signal
+ // that tells the kernel to give up on this driver and rebind the
+ // fallback, and a cold launch on a slow link must not trip it; the
+ // driver is serving, just not yet. Configuration stays authoritative:
+ // a host whose modules are switched off is down whatever the
+ // process-wide table says about a load someone else started.
+ let modules_enabled = self
+ .config
+ .as_ref()
+ .or_else(|| policy())
+ .is_some_and(|config| config.modules.enabled);
+ if modules_enabled && matches!(ops::state_of(MODULE_ID), super::types::ModuleState::Loading)
+ {
+ return MemoryHealth::degraded("the memory module is loading");
+ }
+ match self.proxy("health").await {
+ Ok(proxy) => proxy
+ .call::<MemoryHealth>("Health", ())
+ .await
+ .unwrap_or_else(|error| MemoryHealth::down(error.to_string())),
+ Err(MemoryError::Unavailable(reason)) => MemoryHealth::degraded(reason),
+ Err(error) => MemoryHealth::down(error.to_string()),
+ }
+ }
+
+ async fn shutdown(&self) -> Result<(), MemoryError> {
+ // Deliberately does not load the module in order to shut it down: a
+ // shutdown on a driver that was never used should be a no-op, not a
+ // download. tinybus never unloads a library anyway, so this releases
+ // backend resources only.
+ if self.verified.get().is_none() {
+ return Ok(());
+ }
+ let proxy = self.proxy("shutdown").await?;
+ proxy
+ .call::<()>(methods::SHUTDOWN, ())
+ .await
+ .map_err(|error| from_bus(&error))
+ }
+
+ fn as_ingest(&self) -> Option<&dyn MemoryIngest> {
+ Some(self)
+ }
+ fn as_documents(&self) -> Option<&dyn MemoryDocuments> {
+ Some(self)
+ }
+ fn as_tree(&self) -> Option<&dyn MemoryTree> {
+ Some(self)
+ }
+ fn as_entities(&self) -> Option<&dyn MemoryEntities> {
+ Some(self)
+ }
+ fn as_graph(&self) -> Option<&dyn MemoryGraph> {
+ Some(self)
+ }
+ fn as_diff(&self) -> Option<&dyn MemoryDiff> {
+ Some(self)
+ }
+ fn as_goals(&self) -> Option<&dyn MemoryGoals> {
+ Some(self)
+ }
+ fn as_tool_memory(&self) -> Option<&dyn MemoryToolMemory> {
+ Some(self)
+ }
+ fn as_sources(&self) -> Option<&dyn MemorySourceSink> {
+ Some(self)
+ }
+ fn as_maintenance(&self) -> Option<&dyn MemoryMaintenance> {
+ Some(self)
+ }
+ // The four families below are gated on the pinned artifact rather than
+ // returning `Some(self)` unconditionally. `provides()` derives from these
+ // accessors, the guard builds its decorators from `provides()`, and every
+ // caller already writes a clean "driver does not support the X family"
+ // error on `None` — so gating here converts a deep `UnknownMethod` into an
+ // early, accurate refusal at every call site at once (#5598).
+ fn as_people(&self) -> Option<&dyn MemoryPeople> {
+ artifact_serves(Capability::People).then_some(self as &dyn MemoryPeople)
+ }
+ fn as_chunks(&self) -> Option<&dyn MemoryChunks> {
+ artifact_serves(Capability::Chunks).then_some(self as &dyn MemoryChunks)
+ }
+ fn as_retrieval(&self) -> Option<&dyn MemoryRetrieval> {
+ artifact_serves(Capability::Retrieval).then_some(self as &dyn MemoryRetrieval)
+ }
+ fn as_profile(&self) -> Option<&dyn MemoryProfile> {
+ artifact_serves(Capability::Profile).then_some(self as &dyn MemoryProfile)
+ }
+
+ fn as_source_sync(&self) -> Option<&dyn MemorySourceSync> {
+ artifact_serves(Capability::SourceSync).then_some(self as &dyn MemorySourceSync)
+ }
+
+ fn as_coding_sessions(&self) -> Option<&dyn MemoryCodingSessions> {
+ artifact_serves(Capability::CodingSessions).then_some(self as &dyn MemoryCodingSessions)
+ }
+ fn as_episodic(&self) -> Option<&dyn MemoryEpisodic> {
+ artifact_serves(Capability::Episodic).then_some(self as &dyn MemoryEpisodic)
+ }
+ fn as_scoring(&self) -> Option<&dyn MemoryScoring> {
+ artifact_serves(Capability::Scoring).then_some(self as &dyn MemoryScoring)
+ }
+ fn as_document_ingest(&self) -> Option<&dyn MemoryDocumentIngest> {
+ artifact_serves(Capability::DocumentIngest).then_some(self as &dyn MemoryDocumentIngest)
+ }
+ fn as_conversation_ingest(&self) -> Option<&dyn MemoryConversationIngest> {
+ artifact_serves(Capability::ConversationIngest)
+ .then_some(self as &dyn MemoryConversationIngest)
+ }
+ fn as_learning_ingest(&self) -> Option<&dyn MemoryLearningIngest> {
+ artifact_serves(Capability::LearningIngest).then_some(self as &dyn MemoryLearningIngest)
+ }
+ fn as_event_ingest(&self) -> Option<&dyn MemoryEventIngest> {
+ artifact_serves(Capability::EventIngest).then_some(self as &dyn MemoryEventIngest)
+ }
+ fn as_answer(&self) -> Option<&dyn MemoryAnswer> {
+ artifact_serves(Capability::Answer).then_some(self as &dyn MemoryAnswer)
+ }
+}
+
#[async_trait]
impl MemoryCore for ModuleMemoryProvider {
async fn store(
diff --git a/src/openhuman/modules/memory_tests.rs b/src/openhuman/modules/memory_tests.rs
index e3d3ddc8cc..719bfbdf65 100644
--- a/src/openhuman/modules/memory_tests.rs
+++ b/src/openhuman/modules/memory_tests.rs
@@ -248,8 +248,22 @@ async fn a_read_against_a_loading_module_reports_unavailable_within_its_grace()
let provider = ModuleMemoryProvider::new(Arc::new(Config::default()))
.with_loading_grace(std::time::Duration::from_millis(30));
- // Loading is degraded, never down: `Down` is what rebinds the fallback.
+ // Observe first, assert last. An assertion that fired here would leave
+ // MODULE_ID parked in `Loading` for every test that runs after this one in
+ // the same process, turning one failure into a cascade of unrelated ones.
let health = provider.health().await;
+ let started = std::time::Instant::now();
+ let outcome = MemoryCore::get(&provider, "ns", "key").await;
+ let elapsed = started.elapsed();
+
+ table.complete(
+ MODULE_ID,
+ Resolution::Failed("planted by a test".to_string()),
+ sender,
+ );
+ table.reset_for_test(MODULE_ID);
+
+ // Loading is degraded, never down: `Down` is what rebinds the fallback.
assert!(
matches!(
health,
@@ -257,43 +271,84 @@ async fn a_read_against_a_loading_module_reports_unavailable_within_its_grace()
),
"a loading module must report Degraded, got {health:?}"
);
-
// A read gives up after its grace with the retryable class, and does so
// promptly rather than at some caller's deadline.
- let started = std::time::Instant::now();
- let outcome = MemoryCore::get(&provider, "ns", "key").await;
assert!(
matches!(outcome, Err(MemoryError::Unavailable(_))),
"expected Unavailable while loading, got {outcome:?}"
);
- assert!(started.elapsed() < std::time::Duration::from_secs(5));
-
- table.complete(
- MODULE_ID,
- Resolution::Failed("planted by a test".to_string()),
- sender,
- );
- table.reset_for_test(MODULE_ID);
+ assert!(elapsed < std::time::Duration::from_secs(5));
}
#[test]
fn writes_wait_for_the_module_and_reads_do_not() {
let provider = provider();
- for write in ["store", "import_records", "run_source_sync", "shutdown"] {
+ // Every family that mutates, one representative each. A bounded wait here
+ // does not delay the call, it discards it: none of these has a retry above
+ // it, so the archivist's turn, the autosaved message or the operator's
+ // sync would be lost rather than late.
+ for write in [
+ "store",
+ "forget",
+ "import_records",
+ "ingest_document",
+ "ingest_chat",
+ "ingest_email",
+ "ingest_coding_sessions",
+ "typed_ingest_event",
+ "insert_turn",
+ "insert_event",
+ "open_segment",
+ "set_goals",
+ "append",
+ "put_document",
+ "put_relation",
+ "put_tool_rule",
+ "upsert_facet",
+ "delete_facet",
+ "forget_source",
+ "purge_all",
+ "compact",
+ "consolidate",
+ "reembed",
+ "retry_failed",
+ "flush_pending",
+ "cascade",
+ "seal",
+ "summarise",
+ "run_source_sync",
+ "run_connection_sync",
+ "bootstrap_connection",
+ "override_scheduler_gate",
+ "shutdown",
+ ] {
assert_eq!(
provider.loading_grace(write),
None,
- "{write} must wait it out"
+ "{write} mutates, so it must wait the module out"
);
}
- for read in ["get", "recall", "list", "health", "namespaces"] {
+ for read in [
+ "get",
+ "recall",
+ "list",
+ "health",
+ "namespaces",
+ "export_page",
+ ] {
assert!(
provider.loading_grace(read).is_some(),
"{read} must be bounded"
);
}
+ // The default for anything nobody classified is to wait, so a member added
+ // upstream tomorrow cannot start silently dropping writes.
+ assert_eq!(
+ provider.loading_grace("a_member_from_a_future_contract"),
+ None,
+ "an unrecognised operation must wait rather than be treated as a read"
+ );
}
-
#[test]
fn the_capability_list_matches_the_pinned_release() {
// ARTIFACT_CAPABILITIES describes what ONE specific release of the module
diff --git a/src/openhuman/modules/memory_tests_part_01_tests.rs b/src/openhuman/modules/memory_tests_part_01_tests.rs
index f3273ce32c..18e1f4c801 100644
--- a/src/openhuman/modules/memory_tests_part_01_tests.rs
+++ b/src/openhuman/modules/memory_tests_part_01_tests.rs
@@ -131,3 +131,91 @@ fn scoring_is_advertised_and_has_a_host_accessor() {
"Scoring is advertised, so the accessor must be wired"
);
}
+
+/// Every operation label in the client is classified, and no mutation reached
+/// the read list.
+///
+/// The first version of this classification named the *writes* and let
+/// everything else be a read, which silently bounded two dozen mutations
+/// (#6006 review). Reading the sources keeps the check honest as members are
+/// added: a new `put_*` or `ingest_*` that lands in `BOUNDED_READ_OPERATIONS`
+/// fails here rather than in the field, where the symptom is a lost write on a
+/// cold launch and nothing in the log.
+#[test]
+fn no_mutating_operation_label_is_classified_as_a_read() {
+ // Written the way the call sites are: `self.proxy("x")` directly, or the
+ // operation literal handed to one of the two dispatch macros.
+ let call_site = regex::Regex::new(
+ r#"(?:proxy\(|module_call!\(self, |module_call_slow!\(self, )"([a-z_]+)""#,
+ )
+ .expect("a valid pattern");
+
+ let mut labels: Vec<String> = Vec::new();
+ for part in 1..=4 {
+ let path = format!(
+ "{}/src/openhuman/modules/memory_part_0{part}.rs",
+ env!("CARGO_MANIFEST_DIR")
+ );
+ let source = std::fs::read_to_string(&path).unwrap_or_else(|_| panic!("read {path}"));
+ for captured in call_site.captures_iter(&source) {
+ labels.push(captured[1].to_string());
+ }
+ }
+ labels.sort();
+ labels.dedup();
+ assert!(
+ labels.len() > 60,
+ "the scan found only {} labels; the call-site pattern has drifted from the code",
+ labels.len()
+ );
+
+ // A label carrying one of these is a mutation by name. The read list must
+ // not contain one, whatever a future edit believes.
+ const MUTATING: &[&str] = &[
+ "store",
+ "forget",
+ "purge",
+ "delete",
+ "put_",
+ "set_",
+ "insert_",
+ "ingest",
+ "append",
+ "upsert",
+ "import",
+ "reembed",
+ "compact",
+ "consolidate",
+ "cascade",
+ "seal",
+ "flush",
+ "retry_",
+ "run_",
+ "bootstrap_",
+ "override_",
+ "shutdown",
+ "summaris",
+ "open_segment",
+ ];
+ let provider = provider();
+ for label in &labels {
+ // `store_stats` reads; `store` writes. Match the whole word for the
+ // labels that are a prefix of a legitimate read.
+ let mutates = MUTATING.iter().any(|marker| {
+ if marker.ends_with('_') {
+ label.starts_with(marker)
+ } else {
+ label == marker
+ || label.starts_with(&format!("{marker}_"))
+ || label.contains(marker)
+ }
+ }) && label != "store_stats";
+ if mutates {
+ assert_eq!(
+ provider.loading_grace(label),
+ None,
+ "{label} names a mutation but is classified as a bounded read"
+ );
+ }
+ }
+}
diff --git a/src/openhuman/modules/ops.rs b/src/openhuman/modules/ops.rs
index cada62adff..5c1d1719ef 100644
--- a/src/openhuman/modules/ops.rs
+++ b/src/openhuman/modules/ops.rs
@@ -298,7 +298,11 @@ fn load_cached(
let mut last_error = String::new();
for asset in assets {
- let cache_dir = artifact_dir(install_root, record, asset.host_key);
+ let Some(cache_dir) = artifact_dir(install_root, record, asset.host_key) else {
+ last_error =
+ "the module's cache path could not be built from its registry entry".to_string();
+ continue;
+ };
let release = tinybus::module::CachedRelease {
release_url: record.release_url,
asset_name: asset.archive,
@@ -338,12 +342,51 @@ fn load_cached(
))
}
-/// Where one artifact of one module version is cached.
-fn artifact_dir(install_root: &Path, record: &ModuleRecord, host_key: &str) -> PathBuf {
- install_root
- .join(record.id)
- .join(record.version)
- .join(host_key)
+/// Whether `component` is safe to use as one directory name.
+///
+/// The three values that build a cache path — a module id, its version, and a
+/// host key — are compiled-in `const` data today, so nothing reaches this with
+/// a separator in it. It is checked anyway because of what sits at the end of
+/// the path: [`prune_stale_versions`] calls `remove_dir_all` on what these
+/// build. A registry edit or a future value that carried `..` or a separator
+/// would turn a cache tidy-up into deleting somewhere else entirely, and a
+/// rule that has to hold for a delete is worth stating rather than inferring
+/// from where the data happens to come from today.
+fn is_safe_path_component(component: &str) -> bool {
+ !component.is_empty()
+ && component != "."
+ && component != ".."
+ && !component.contains('/')
+ && !component.contains('\\')
+ && !component.contains('\0')
+ // A leading dot would collide with the `.staging-*` directories a
+ // concurrent download is filling.
+ && !component.starts_with('.')
+}
+
+/// Where one artifact of one module version is cached, when all three
+/// components are usable as directory names.
+///
+/// `None` rather than a sanitised path: a registry entry that cannot name a
+/// directory is a build-time mistake, and quietly rewriting it would hide the
+/// mistake behind a cache that silently never hits.
+fn artifact_dir(install_root: &Path, record: &ModuleRecord, host_key: &str) -> Option<PathBuf> {
+ for component in [record.id, record.version, host_key] {
+ if !is_safe_path_component(component) {
+ log::error!(
+ "[modules] '{}' has a component that cannot name a directory; refusing to build a \
+ cache path from it",
+ record.id
+ );
+ return None;
+ }
+ }
+ Some(
+ install_root
+ .join(record.id)
+ .join(record.version)
+ .join(host_key),
+ )
}
/// Remove cached versions of `record` other than the pinned one.
@@ -353,6 +396,16 @@ fn artifact_dir(install_root: &Path, record: &ModuleRecord, host_key: &str) -> P
/// are left alone — a concurrent process may be filling one — and every
/// removal is logged, because a cache that empties itself is worth noticing.
fn prune_stale_versions(install_root: &Path, record: &ModuleRecord) {
+ // Both sides of the comparison below have to be real directory names, or
+ // "everything that is not the pinned version" is not a set this function
+ // should be handing to `remove_dir_all`.
+ if !is_safe_path_component(record.id) || !is_safe_path_component(record.version) {
+ log::error!(
+ "[modules] refusing to prune '{}': its id or version cannot name a directory",
+ record.id
+ );
+ return;
+ }
let module_root = install_root.join(record.id);
let Ok(entries) = std::fs::read_dir(&module_root) else {
return;
@@ -361,7 +414,10 @@ fn prune_stale_versions(install_root: &Path, record: &ModuleRecord) {
let path = entry.path();
let name = entry.file_name();
let name = name.to_string_lossy();
- if !path.is_dir() || name == record.version || name.starts_with('.') {
+ // `read_dir` never yields `.` or `..`, and the leading-dot skip covers
+ // the staging directories; the guard is here so the delete depends on
+ // this function's own check rather than on that being remembered.
+ if !path.is_dir() || name == record.version || !is_safe_path_component(&name) {
continue;
}
match std::fs::remove_dir_all(&path) {
diff --git a/src/openhuman/modules/ops_tests.rs b/src/openhuman/modules/ops_tests.rs
index a52b05c338..75533c08a5 100644
--- a/src/openhuman/modules/ops_tests.rs
+++ b/src/openhuman/modules/ops_tests.rs
@@ -187,6 +187,14 @@ async fn a_bounded_wait_with_nothing_cached_and_downloads_off_fails_rather_than_
let mut config = offline_config();
config.modules.install_dir = Some(install.path().display().to_string());
+ // The resolution table is process-wide, and the module-backed document
+ // tests populate this same slot when they are run with `--ignored`. A slot
+ // left behind by one of those would be answered from cache before this
+ // config is ever consulted, so clear it first and again at the end rather
+ // than depending on which tests ran before this one.
+ let table = crate::openhuman::modules::resolution::table();
+ table.reset_for_test("tinydocs");
+
// Nothing to download from, nothing cached: the resolution settles at once,
// so a bounded caller gets the terminal reason, never `StillLoading`.
let outcome = ops::ensure_loaded_within(
@@ -195,6 +203,14 @@ async fn a_bounded_wait_with_nothing_cached_and_downloads_off_fails_rather_than_
Some(std::time::Duration::from_secs(30)),
)
.await;
+ // The outcome is remembered as a failure, and reported as one.
+ let state = ops::state_of("tinydocs");
+ let status = list(&config)
+ .into_iter()
+ .find(|status| status.id == "tinydocs")
+ .expect("tinydocs is a registry entry");
+ table.reset_for_test("tinydocs");
+
match outcome {
Err(ops::LoadError::Failed(reason)) => assert!(
reason.contains("downloads are disabled")
@@ -203,13 +219,7 @@ async fn a_bounded_wait_with_nothing_cached_and_downloads_off_fails_rather_than_
),
other => panic!("expected a terminal failure, got {other:?}"),
}
-
- // The outcome is remembered as a failure, and reported as one.
- assert_eq!(ops::state_of("tinydocs"), ModuleState::Failed);
- let status = list(&config)
- .into_iter()
- .find(|status| status.id == "tinydocs")
- .expect("tinydocs is a registry entry");
+ assert_eq!(state, ModuleState::Failed);
assert_eq!(status.state, ModuleState::Failed);
assert!(status.detail.is_some());
}
@@ -218,14 +228,56 @@ async fn a_bounded_wait_with_nothing_cached_and_downloads_off_fails_rather_than_
fn each_artifact_of_a_version_has_its_own_cache_directory() {
let record = registry::find("tinydocs").expect("tinydocs is a registry entry");
let root = std::path::Path::new("/cache/modules");
- let dir = ops::artifact_dir(root, record, "macos-26-arm64");
+ let dir = ops::artifact_dir(root, record, "macos-26-arm64").expect("a usable cache path");
assert_eq!(
dir,
root.join("tinydocs")
.join(record.version)
.join("macos-26-arm64")
);
- assert_ne!(dir, ops::artifact_dir(root, record, "macos-15-arm64"));
+ assert_ne!(Some(dir), ops::artifact_dir(root, record, "macos-15-arm64"));
+}
+
+#[test]
+fn a_component_that_cannot_name_a_directory_yields_no_cache_path() {
+ // The delete in `prune_stale_versions` is built from these components, so
+ // a value that escapes its directory must produce no path at all rather
+ // than one that resolves somewhere else.
+ for bad in ["..", ".", "", "a/b", "a\\b", ".hidden", "a\0b"] {
+ assert!(
+ !ops::is_safe_path_component(bad),
+ "{bad:?} must be refused as a directory name"
+ );
+ }
+ for good in [
+ "tinydocs",
+ "0.1.15",
+ "macos-26-arm64",
+ "ubuntu-22.04-x86_64",
+ ] {
+ assert!(ops::is_safe_path_component(good), "{good:?} is a real name");
+ }
+
+ let record = registry::find("tinydocs").expect("tinydocs is a registry entry");
+ let root = std::path::Path::new("/cache/modules");
+ assert_eq!(ops::artifact_dir(root, record, ".."), None);
+ assert_eq!(ops::artifact_dir(root, record, "a/b"), None);
+ // Every shipped registry entry names a directory on every host it claims.
+ for entry in registry::ALL {
+ assert!(
+ ops::is_safe_path_component(entry.id) && ops::is_safe_path_component(entry.version),
+ "registry entry '{}' cannot name a cache directory",
+ entry.id
+ );
+ for asset in entry.assets {
+ assert!(
+ ops::is_safe_path_component(asset.host_key),
+ "'{}' host key '{}' cannot name a cache directory",
+ entry.id,
+ asset.host_key
+ );
+ }
+ }
}
#[test]