Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(hooks): harden ingest rate limiter

AkitaOnRails1160cc58c2b8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88d6a75f..42b58917 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
the unused LLM retry-exhaustion error variant was removed ([#171]).
### Fixed
+- `/hook/batch` now skips per-source rate-limited items and continues accepting
+ later unrelated sources, returns non-contiguous acknowledgements for new spool
+ drains, bounds limiter key bytes, keys by actor+session with deterministic
+ missing-session fallbacks, and avoids spending source tokens on globally
+ saturated events. `AI_MEMORY_HOOK_RATE_PER_SEC` and
+ `AI_MEMORY_HOOK_RATE_BURST` are now parsed through typed server config
+ instead of the hooks crate reading env directly ([#170]).
- MCP tool calls over the stdio transport now fall back to an anonymous
synthetic request context when HTTP request parts are absent, while preserving
real streamable-HTTP auth/session parts when present ([#168]).
diff --git a/README.md b/README.md
index 7b95f1dd..f483d553 100644
--- a/README.md
+++ b/README.md
@@ -375,6 +375,11 @@ Bearer auth protects `/mcp`, `/hook`, `/handoff`, `/admin/*`, and
as the password. Non-loopback binds should also set
`AI_MEMORY_ALLOWED_HOSTS` to guard against DNS rebinding.
+Busy shared hook servers can also set `AI_MEMORY_HOOK_RATE_PER_SEC` (tokens per
+second per actor/session source) and optionally `AI_MEMORY_HOOK_RATE_BURST` to
+bound one runaway session without blocking unrelated hook sources. Unset or `0`
+rate leaves the limiter disabled.
+
For shared servers where each developer should authenticate their own hook
writes, native Claude Code hooks can use a stored OIDC device token instead of
embedding a shared static token:
diff --git a/crates/ai-memory-cli/src/commands/hook_capture.rs b/crates/ai-memory-cli/src/commands/hook_capture.rs
index 8b4fce5f..44ccdcd9 100644
--- a/crates/ai-memory-cli/src/commands/hook_capture.rs
+++ b/crates/ai-memory-cli/src/commands/hook_capture.rs
@@ -198,17 +198,28 @@ pub async fn post_hook(
/// Outcome of one `POST /hook/batch` request — many spooled events delivered in
/// a single round-trip, so a draining client amortizes TLS + network RTT + the
/// edge auth hop over the whole batch instead of paying it per event.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BatchOutcome {
/// Server committed the leading `usize` items (contiguous prefix, oldest
/// first). Equals the request length on full success; a smaller value means
/// the server stopped on that item (fail-fast) — the caller deletes the
/// prefix and charges the next item a retry.
Accepted(usize),
+ /// Server committed these item indexes, which may be non-contiguous when it
+ /// skipped per-source rate-limited events and continued with later sources.
+ /// If `failed_index` is present, that item failed processing and should be
+ /// charged instead of assuming the first unaccepted item failed.
+ AcceptedIndices {
+ indices: Vec<usize>,
+ failed_index: Option<usize>,
+ },
/// `429` — ingest saturated after committing this many leading items. The
/// caller deletes that prefix and retries the rest later WITHOUT bumping
/// attempts (saturation isn't a failure).
Saturated(usize),
+ /// `429` with a non-contiguous committed set. New servers can include this
+ /// when a global saturation happens after earlier skipped items.
+ SaturatedIndices(Vec<usize>),
/// `404`/`405` — the server has no `/hook/batch` (a pre-upgrade build). The
/// caller falls back to per-event `POST /hook` for the rest of the drain.
Unsupported,
@@ -244,22 +255,35 @@ pub async fn post_batch(
if status.is_success() {
match resp.json::<serde_json::Value>().await {
Ok(v) => {
- let accepted = v
- .get("accepted")
- .and_then(serde_json::Value::as_u64)
- .unwrap_or(0) as usize;
- BatchOutcome::Accepted(accepted)
+ if let Some(indices) = accepted_indices(&v) {
+ BatchOutcome::AcceptedIndices {
+ indices,
+ failed_index: failed_index(&v),
+ }
+ } else {
+ let accepted = v
+ .get("accepted")
+ .and_then(serde_json::Value::as_u64)
+ .unwrap_or(0) as usize;
+ BatchOutcome::Accepted(accepted)
+ }
}
Err(_) => BatchOutcome::Failed,
}
} else if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
- let accepted = resp
- .json::<serde_json::Value>()
- .await
- .ok()
- .and_then(|v| v.get("accepted").and_then(serde_json::Value::as_u64))
- .unwrap_or(0) as usize;
- BatchOutcome::Saturated(accepted)
+ let body = resp.json::<serde_json::Value>().await.ok();
+ if let Some(indices) = body.as_ref().and_then(accepted_indices) {
+ BatchOutcome::SaturatedIndices(indices)
+ } else {
+ let accepted = body
+ .and_then(|v| {
+ v.get("accepted")
+ .and_then(serde_json::Value::as_u64)
+ .map(|n| n as usize)
+ })
+ .unwrap_or(0);
+ BatchOutcome::Saturated(accepted)
+ }
} else if status == reqwest::StatusCode::NOT_FOUND
|| status == reqwest::StatusCode::METHOD_NOT_ALLOWED
{
@@ -272,6 +296,19 @@ pub async fn post_batch(
}
}
+fn failed_index(v: &serde_json::Value) -> Option<usize> {
+ v.get("failed_index")?.as_u64().map(|n| n as usize)
+}
+
+fn accepted_indices(v: &serde_json::Value) -> Option<Vec<usize>> {
+ let arr = v.get("accepted_indices")?.as_array()?;
+ let mut indices = Vec::with_capacity(arr.len());
+ for item in arr {
+ indices.push(item.as_u64()? as usize);
+ }
+ Some(indices)
+}
+
/// GET the handoff text with a caller-chosen budget. Returns None on any error
/// or an empty body. This is the one synchronous read on the agent's critical
/// path (session-start injects it as context), so the budget is larger than a
diff --git a/crates/ai-memory-cli/src/commands/hook_spool.rs b/crates/ai-memory-cli/src/commands/hook_spool.rs
index 9e857ed3..598ef8c5 100644
--- a/crates/ai-memory-cli/src/commands/hook_spool.rs
+++ b/crates/ai-memory-cli/src/commands/hook_spool.rs
@@ -484,6 +484,20 @@ pub async fn drain(
break;
}
}
+ BatchOutcome::AcceptedIndices {
+ indices,
+ failed_index,
+ } => {
+ let sent = delete_accepted_indices(&chunk, &indices);
+ result.sent += sent;
+ if let Some(failed_index) = failed_index.and_then(|i| chunk.get(i).map(|_| i)) {
+ bump_or_drop(&chunk[failed_index].0, &chunk[failed_index].1, &mut result);
+ result.remaining += chunk.len().saturating_sub(sent).saturating_sub(1)
+ + files.len().saturating_sub(idx);
+ break;
+ }
+ result.remaining += chunk.len().saturating_sub(sent);
+ }
BatchOutcome::Saturated(k) => {
// Server ingest filled after committing a leading prefix.
// Delete only that prefix; leave the saturated item and all
@@ -498,6 +512,13 @@ pub async fn drain(
chunk.len().saturating_sub(k) + files.len().saturating_sub(idx);
break;
}
+ BatchOutcome::SaturatedIndices(indices) => {
+ let sent = delete_accepted_indices(&chunk, &indices);
+ result.sent += sent;
+ result.remaining +=
+ chunk.len().saturating_sub(sent) + files.len().saturating_sub(idx);
+ break;
+ }
BatchOutcome::Unsupported => {
// Pre-upgrade server with no /hook/batch: fall back to the
// per-event path for the current chunk and the rest of the
@@ -575,6 +596,17 @@ pub async fn drain(
result
}
+fn delete_accepted_indices(chunk: &[(PathBuf, SpoolEntry)], indices: &[usize]) -> usize {
+ let mut sent = 0usize;
+ for idx in indices.iter().copied() {
+ if let Some((path, _)) = chunk.get(idx) {
+ let _ = std::fs::remove_file(path);
+ sent += 1;
+ }
+ }
+ sent
+}
+
fn batch_request_timeout(
per_event_timeout: Duration,
remaining_budget: Duration,
@@ -1177,6 +1209,111 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn non_contiguous_batch_ack_deletes_only_accepted_indices() {
+ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ while let Ok((mut s, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = vec![0_u8; 65536];
+ let _ = s.read(&mut buf).await;
+ let body = r#"{"accepted":0,"accepted_indices":[1]}"#;
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = s.write_all(resp.as_bytes()).await;
+ });
+ }
+ });
+
+ let tmp = tempfile::tempdir().unwrap();
+ let spool = spool_dir(tmp.path());
+ for i in 0..2 {
+ write_spool_entry(
+ &spool,
+ &format!("evt-{i}.json"),
+ format!("http://{addr}/hook?event=e{i}"),
+ );
+ }
+
+ let r = drain(
+ &spool,
+ tmp.path(),
+ Duration::from_secs(5),
+ Duration::from_secs(2),
+ )
+ .await;
+
+ assert_eq!(r.sent, 1);
+ assert_eq!(r.dropped, 0);
+ assert_eq!(r.remaining, 1);
+ let mut files = list_entries(&spool).unwrap();
+ files.sort();
+ assert_eq!(files.len(), 1);
+ assert!(files[0].ends_with("evt-0.json"));
+ assert_eq!(sorted_attempts(&spool), vec![0]);
+ }
+
+ #[tokio::test]
+ async fn non_contiguous_batch_ack_charges_reported_failed_index() {
+ use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};
+
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ while let Ok((mut s, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = vec![0_u8; 65536];
+ let _ = s.read(&mut buf).await;
+ let body = r#"{"accepted":0,"accepted_indices":[],"failed_index":1}"#;
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = s.write_all(resp.as_bytes()).await;
+ });
+ }
+ });
+
+ let tmp = tempfile::tempdir().unwrap();
+ let spool = spool_dir(tmp.path());
+ for i in 0..3 {
+ write_spool_entry(
+ &spool,
+ &format!("evt-{i}.json"),
+ format!("http://{addr}/hook?event=e{i}"),
+ );
+ }
+
+ let r = drain(
+ &spool,
+ tmp.path(),
+ Duration::from_secs(5),
+ Duration::from_secs(2),
+ )
+ .await;
+
+ assert_eq!(r.sent, 0);
+ assert_eq!(r.dropped, 0);
+ assert_eq!(r.remaining, 3);
+ let mut files = list_entries(&spool).unwrap();
+ files.sort();
+ assert_eq!(files.len(), 3);
+ let attempts: Vec<u32> = files
+ .iter()
+ .map(|path| {
+ serde_json::from_slice::<SpoolEntry>(&std::fs::read(path).unwrap())
+ .unwrap()
+ .attempts
+ })
+ .collect();
+ assert_eq!(attempts, vec![0, 1, 0]);
+ }
+
/// A mock hook server: answers `200 {"accepted":N}` to `POST /hook/batch`
/// (N = array length in the body) and `202 queued` to a per-event
/// `POST /hook`. Counts every request so a test can assert batching. Reads
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 4aa02161..b95337b9 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -290,7 +290,14 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
ai_memory_hooks::SubagentSessionSet::default(),
)),
ingest_rate: std::sync::Arc::new(tokio::sync::Mutex::new(
- ai_memory_hooks::IngestRateLimiter::from_env(),
+ ai_memory_hooks::IngestRateLimiter::new(
+ config.hook_rate_per_sec.max(0.0),
+ if config.hook_rate_burst > 0.0 {
+ config.hook_rate_burst
+ } else {
+ config.hook_rate_per_sec.max(1.0)
+ },
+ ),
)),
home_dir: config.home_dir.clone(),
});
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 85de56ee..d6776a37 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -133,6 +133,10 @@ pub struct Config {
/// and `per_actor` are for shared installs. See [`AutoScopeSettings`]
/// and [`ai_memory_core::ActiveProjectMode`].
pub auto_scope: AutoScopeSettings,
+ /// Env-backed alias for hook ingest tokens per second per source.
+ pub hook_rate_per_sec: f64,
+ /// Env-backed alias for hook ingest burst tokens per source.
+ pub hook_rate_burst: f64,
/// `Host`-header allowlist for the HTTP server. Requests whose
/// `Host` header doesn't match this list are rejected before they
/// reach MCP, hook, admin, or web routes (DNS-rebinding defence).
@@ -367,6 +371,8 @@ impl Default for Config {
sanitize: ai_memory_core::SanitizeConfig::default(),
auth: AuthSettings::default(),
auto_scope: AutoScopeSettings::default(),
+ hook_rate_per_sec: 0.0,
+ hook_rate_burst: 0.0,
allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()],
cors_allow_origins: Vec::new(),
admission_webhooks: Vec::new(),
@@ -1023,6 +1029,8 @@ mod tests {
r#"
bind = "0.0.0.0:9999"
log_level = "debug"
+ hook_rate_per_sec = 7.5
+ hook_rate_burst = 12.0
[maintenance]
enabled = false
@@ -1073,6 +1081,8 @@ mod tests {
let cfg = Config::load(Some(&cfg_path), Some(tmp.path().to_path_buf())).unwrap();
assert_eq!(cfg.bind, "0.0.0.0:9999");
assert_eq!(cfg.log_level, "debug");
+ assert_eq!(cfg.hook_rate_per_sec, 7.5);
+ assert_eq!(cfg.hook_rate_burst, 12.0);
assert!(!cfg.maintenance.enabled);
assert_eq!(cfg.maintenance.lint_interval_secs, 3600);
assert!(cfg.auto_improve.scheduler.enabled);
diff --git a/crates/ai-memory-cli/templates/config.default.toml b/crates/ai-memory-cli/templates/config.default.toml
index 73070cd3..ba73018d 100644
--- a/crates/ai-memory-cli/templates/config.default.toml
+++ b/crates/ai-memory-cli/templates/config.default.toml
@@ -18,6 +18,13 @@ allowed_hosts = ["localhost", "127.0.0.1", "::1"]
# Default tracing filter (overridable by RUST_LOG).
log_level = "info"
+# Optional server-side hook ingest limiter for shared/remote installs. The rate
+# is tokens per second per actor/session source; 0 or unset disables it. Burst
+# defaults to the rate (minimum one token when enabled). Env equivalents:
+# `AI_MEMORY_HOOK_RATE_PER_SEC` and `AI_MEMORY_HOOK_RATE_BURST`.
+# hook_rate_per_sec = 0.0
+# hook_rate_burst = 0.0
+
# M8 retention-sweep parameters.
#
# Formula:
diff --git a/crates/ai-memory-hooks/src/lib.rs b/crates/ai-memory-hooks/src/lib.rs
index a8932677..747ee997 100644
--- a/crates/ai-memory-hooks/src/lib.rs
+++ b/crates/ai-memory-hooks/src/lib.rs
@@ -17,6 +17,9 @@
//!
//! Privacy strip is a *typed* boundary: there is no way to write an
//! observation without first passing through `Sanitized::new`.
+//!
+//! This crate does not read process environment directly; server configuration
+//! is resolved once by `ai-memory-cli` and threaded in as typed state.
pub mod log;
pub mod payload;
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index 03bba928..4c039e51 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -232,10 +232,8 @@ struct TokenBucket {
last_refill: std::time::Instant,
}
-/// Per-source (session) admission rate limiter that runs BEFORE the global
-/// ingest semaphore, so one runaway source can't exhaust the shared ingest
-/// capacity for everyone — the 2026-06-29 subagent-flood/OOM shape. A bounded
-/// LRU of token buckets; disabled (pass-through) when `refill_per_sec <= 0`.
+/// Per-source admission rate limiter. A bounded LRU of token buckets; disabled
+/// (pass-through) when `refill_per_sec <= 0`.
pub struct IngestRateLimiter {
buckets: HashMap<String, TokenBucket>,
order: VecDeque<String>,
@@ -264,24 +262,6 @@ impl IngestRateLimiter {
}
}
- /// Build from env: `AI_MEMORY_HOOK_RATE_PER_SEC` (tokens/sec per source; 0
- /// or unset = disabled, no behaviour change) and `AI_MEMORY_HOOK_RATE_BURST`
- /// (default = per_sec, min 1).
- #[must_use]
- pub fn from_env() -> Self {
- let per_sec = std::env::var("AI_MEMORY_HOOK_RATE_PER_SEC")
- .ok()
- .and_then(|v| v.trim().parse::<f64>().ok())
- .filter(|v| *v > 0.0)
- .unwrap_or(0.0);
- let burst = std::env::var("AI_MEMORY_HOOK_RATE_BURST")
- .ok()
- .and_then(|v| v.trim().parse::<f64>().ok())
- .filter(|v| *v > 0.0)
- .unwrap_or_else(|| per_sec.max(1.0));
- Self::new(per_sec, burst)
- }
-
/// Try to admit one event for `key` at `now`. `true` when disabled or a
/// token was available; `false` when the key is over its burst. O(1)
/// amortized; evicts the oldest-inserted key over the cap (a re-inserted
@@ -290,15 +270,16 @@ impl IngestRateLimiter {
if self.refill_per_sec <= 0.0 {
return true;
}
- if !self.buckets.contains_key(key) {
+ let key = bounded_rate_key(key);
+ if !self.buckets.contains_key(&key) {
self.buckets.insert(
- key.to_string(),
+ key.clone(),
TokenBucket {
tokens: self.burst,
last_refill: now,
},
);
- self.order.push_back(key.to_string());
+ self.order.push_back(key.clone());
while self.buckets.len() > self.max_keys {
if let Some(oldest) = self.order.pop_front() {
self.buckets.remove(&oldest);
@@ -307,7 +288,9 @@ impl IngestRateLimiter {
}
}
}
- let bucket = self.buckets.get_mut(key).expect("present after insert");
+ let Some(bucket) = self.buckets.get_mut(&key) else {
+ return true;
+ };
let elapsed = now
.saturating_duration_since(bucket.last_refill)
.as_secs_f64();
@@ -326,6 +309,54 @@ impl IngestRateLimiter {
fn len(&self) -> usize {
self.buckets.len()
}
+
+ #[cfg(test)]
+ fn max_stored_key_len(&self) -> usize {
+ self.buckets.keys().map(String::len).max().unwrap_or(0)
+ }
+}
+
+const INGEST_RATE_MAX_KEY_BYTES: usize = 128;
+
+fn bounded_rate_key(raw: &str) -> String {
+ if raw.len() <= INGEST_RATE_MAX_KEY_BYTES {
+ return raw.to_string();
+ }
+ format!("h:{:016x}", fnv1a64(raw.as_bytes()))
+}
+
+fn log_rate_key(raw: &str) -> String {
+ bounded_rate_key(raw)
+ .chars()
+ .map(|c| if c.is_control() { '_' } else { c })
+ .collect()
+}
+
+fn fnv1a64(bytes: &[u8]) -> u64 {
+ let mut hash = 0xcbf29ce484222325u64;
+ for b in bytes {
+ hash ^= u64::from(*b);
+ hash = hash.wrapping_mul(0x100000001b3);
+ }
+ hash
+}
+
+fn ingest_rate_key(env: &HookEnvelope, actor_user: Option<&str>) -> String {
+ let user = actor_user.unwrap_or("");
+ if let Some(session_id) = env.session_id.as_deref().filter(|s| !s.is_empty()) {
+ return format!("u:{user}\ns:{session_id}");
+ }
+ let fallback = serde_json::to_string(&env.raw).unwrap_or_default();
+ format!(
+ "u:{user}\nmissing:{}:{}:{}:{}:{}:{}:{:016x}",
+ env.agent.as_str(),
+ format_args!("{:?}", env.event),
+ env.cwd.as_deref().unwrap_or(""),
+ env.workspace_override.as_deref().unwrap_or(""),
+ env.project_override.as_deref().unwrap_or(""),
+ env.project_strategy.as_str(),
+ fnv1a64(fallback.as_bytes())
+ )
}
/// Shared state passed to the hook handler.
@@ -364,10 +395,9 @@ pub struct HookState {
/// In-flight hook processing limiter. Requests acquire one permit before
/// spawning work and return 429 immediately when saturated.
pub ingest_semaphore: Arc<tokio::sync::Semaphore>,
- /// Per-source (session) ingest rate limiter, checked BEFORE the global
- /// `ingest_semaphore` so one runaway source can't exhaust shared capacity
- /// and 429 everyone. Disabled (pass-through) unless
- /// `AI_MEMORY_HOOK_RATE_PER_SEC` is set.
+ /// Per-source ingest rate limiter. The global `ingest_semaphore` is acquired
+ /// first for stored events so globally rejected events do not spend source
+ /// tokens. Disabled (pass-through) unless configured by the CLI.
pub ingest_rate: Arc<tokio::sync::Mutex<IngestRateLimiter>>,
/// Opt-in (`AI_MEMORY_CONSOLIDATE_ON_SESSION_END`): when true and a
/// `consolidator` is present, SessionEnd also runs LLM consolidation on
@@ -425,23 +455,20 @@ async fn handle_hook(
if should_drop_subagent(&state, &env, &actor_key).await {
return (StatusCode::ACCEPTED, "subagent capture dropped");
}
- // Per-source rate limit BEFORE the global semaphore, so one runaway
- // session can't drain shared ingest capacity and 429 everyone. Keyed by
- // session id (the flooding-agent shape); disabled unless configured.
- let rate_key = env.session_id.clone().unwrap_or_default();
+ let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {
+ warn!("hook ingest saturated; dropping event with 429");
+ return (StatusCode::TOO_MANY_REQUESTS, "hook queue full");
+ };
+ let rate_key = ingest_rate_key(&env, actor_user.as_deref());
if !state
.ingest_rate
.lock()
.await
.try_take(&rate_key, std::time::Instant::now())
{
- warn!(source = %rate_key, "hook ingest rate limit exceeded for source; dropping event with 429");
+ warn!(source = %log_rate_key(&rate_key), "hook ingest rate limit exceeded for source; dropping event with 429");
return (StatusCode::TOO_MANY_REQUESTS, "hook source rate limited");
}
- let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {
- warn!("hook ingest saturated; dropping event with 429");
- return (StatusCode::TOO_MANY_REQUESTS, "hook queue full");
- };
tokio::spawn(async move {
let _permit = permit;
process_envelope(state, env, actor_user).await;
@@ -463,13 +490,72 @@ pub struct HookBatchItem {
pub body: serde_json::Value,
}
-/// Response to `POST /hook/batch`: the length of the contiguous leading prefix
-/// of items that committed (equals the request length on full success).
+/// Response to `POST /hook/batch`: legacy clients read the contiguous leading
+/// prefix in `accepted`; newer clients prefer `accepted_indices` when present to
+/// retain only non-contiguous items skipped by per-source rate limiting.
#[derive(Debug, Serialize)]
pub struct HookBatchAck {
- /// Items committed, oldest-first. The client deletes exactly this many
- /// spool entries and re-sends the rest next pass.
+ /// Contiguous leading prefix committed, oldest-first. Kept for old spool
+ /// drains and as a safe lower bound when `accepted_indices` is absent.
pub accepted: usize,
+ /// Non-contiguous item indexes committed by a server new enough to keep
+ /// scanning past per-source rate-limited items. Omitted when it is exactly
+ /// the legacy accepted prefix so older clients keep working.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub accepted_indices: Option<Vec<usize>>,
+ /// Item index that failed processing after earlier rate-limited skips. New
+ /// spool drains charge this item, not the first unaccepted one.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub failed_index: Option<usize>,
+}
+
+impl HookBatchAck {
+ fn prefix(accepted: usize) -> Self {
+ Self {
+ accepted,
+ accepted_indices: None,
+ failed_index: None,
+ }
+ }
+
+ fn indexed(indices: Vec<usize>) -> Self {
+ Self::indexed_with_empty(indices, false, None)
+ }
+
+ fn indexed_full_scan(indices: Vec<usize>) -> Self {
+ Self::indexed_with_empty(indices, true, None)
+ }
+
+ fn indexed_failed(indices: Vec<usize>, failed_index: usize) -> Self {
+ Self::indexed_with_empty(indices, true, Some(failed_index))
+ }
+
+ fn indexed_with_empty(
+ indices: Vec<usize>,
+ include_empty_indices: bool,
+ failed_index: Option<usize>,
+ ) -> Self {
+ let legacy_prefix = indices
+ .iter()
+ .copied()
+ .enumerate()
+ .take_while(|(pos, idx)| *pos == *idx)
+ .count();
+ let contiguous = indices
+ .iter()
+ .copied()
+ .enumerate()
+ .all(|(pos, idx)| pos == idx);
+ Self {
+ accepted: legacy_prefix,
+ accepted_indices: if contiguous && !(include_empty_indices && indices.is_empty()) {
+ None
+ } else {
+ Some(indices)
+ },
+ failed_index,
+ }
+ }
}
/// Batch sibling of [`handle_hook`]. Accepts many spooled events in ONE request
@@ -478,12 +564,12 @@ pub struct HookBatchAck {
/// dominant cost when a backlog drains to a remote, gated server, and the reason
/// a sequential per-event drain falls behind under parallel load.
///
-/// Unlike `handle_hook` (which spawns and answers `202` immediately), the batch
-/// is processed INLINE and FAIL-FAST: items run in order and the first error
-/// stops the batch, returning `accepted = <committed prefix>`. Inline + fail-fast
-/// keeps every item's side effects (a SessionEnd writes a session page + a
-/// handoff) inside the response window, so a partially-applied batch never
-/// commits beyond what `accepted` reports — the client deletes only that prefix.
+/// Unlike `handle_hook` (which spawns and answers `202` immediately), stored
+/// batch items are processed INLINE so every item's side effects (a SessionEnd
+/// writes a session page + a handoff) stay inside the response window. Real
+/// processing errors still fail-fast. Per-source rate-limit misses are different:
+/// the item is skipped and later unrelated sources continue, with
+/// `accepted_indices` telling new spool drains exactly which entries committed.
async fn handle_hook_batch(
State(state): State<Arc<HookState>>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
@@ -495,18 +581,15 @@ async fn handle_hook_batch(
max = MAX_HOOK_BATCH_ITEMS,
"hook batch too large; rejecting before processing"
);
- return (
- StatusCode::PAYLOAD_TOO_LARGE,
- Json(HookBatchAck { accepted: 0 }),
- );
+ return (StatusCode::PAYLOAD_TOO_LARGE, Json(HookBatchAck::prefix(0)));
}
// All items in a batch share the drain's single identity, so the actor is
// captured once from the batch request (mirrors `handle_hook`).
let actor_user = actor_ext
.map(|axum::Extension(ctx)| ctx.user)
.unwrap_or_default();
- let mut accepted = 0usize;
- for item in items {
+ let mut accepted_indices = Vec::new();
+ for (idx, item) in items.into_iter().enumerate() {
let query = parse_hook_query(&item.url);
let env = HookEnvelope::from_query_and_body(query, item.body);
let actor_key = ActorKey {
@@ -517,46 +600,44 @@ async fn handle_hook_batch(
// as committed so the client clears it from its spool, but do not store
// it. Keeps the contiguous-prefix ack contract intact.
if should_drop_subagent(&state, &env, &actor_key).await {
- accepted += 1;
+ accepted_indices.push(idx);
continue;
}
- // Per-source rate limit (see `handle_hook`): when this source is over
- // its burst, stop the batch at the committed prefix so the client
- // retries the rest as tokens refill — smoothing a flood rather than
- // OOMing on it (the 2026-06-29 flood came through /hook/batch).
- let rate_key = env.session_id.clone().unwrap_or_default();
+ let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {
+ warn!(
+ accepted = accepted_indices.len(),
+ "hook batch ingest saturated; rejecting with 429"
+ );
+ return (
+ StatusCode::TOO_MANY_REQUESTS,
+ Json(HookBatchAck::indexed(accepted_indices)),
+ );
+ };
+ let rate_key = ingest_rate_key(&env, actor_user.as_deref());
if !state
.ingest_rate
.lock()
.await
.try_take(&rate_key, std::time::Instant::now())
{
- warn!(accepted, source = %rate_key, "hook batch source rate limited; stopping at committed prefix");
- return (
- StatusCode::TOO_MANY_REQUESTS,
- Json(HookBatchAck { accepted }),
- );
+ drop(permit);
+ warn!(accepted = accepted_indices.len(), source = %log_rate_key(&rate_key), "hook batch source rate limited; skipping item and continuing");
+ continue;
}
- // Mirror single `/hook`: subagent drops consume no ingest capacity, and
- // only events we will actually process acquire a permit. The batch loop
- // is sequential, so one permit held across this item preserves the
- // server-wide in-flight bound without making all-droppable batches 429
- // under saturation.
- let Ok(permit) = state.ingest_semaphore.clone().try_acquire_owned() else {
- warn!(accepted, "hook batch ingest saturated; rejecting with 429");
- return (
- StatusCode::TOO_MANY_REQUESTS,
- Json(HookBatchAck { accepted }),
- );
- };
let _permit = permit;
if let Err(e) = process(&state, env, actor_user.clone()).await {
- warn!(error = %e, accepted, "hook batch item failed; stopping (fail-fast)");
- break;
+ warn!(error = %e, accepted = accepted_indices.len(), "hook batch item failed; stopping (fail-fast)");
+ return (
+ StatusCode::OK,
+ Json(HookBatchAck::indexed_failed(accepted_indices, idx)),
+ );
}
- accepted += 1;
+ accepted_indices.push(idx);
}
- (StatusCode::OK, Json(HookBatchAck { accepted }))
+ (
+ StatusCode::OK,
+ Json(HookBatchAck::indexed_full_scan(accepted_indices)),
+ )
}
/// Decide whether to accept-but-drop this event under `drop_subagent_captures`,
@@ -1950,6 +2031,58 @@ mod tests {
);
}
+ #[test]
+ fn ingest_rate_limiter_bounds_key_bytes() {
+ let mut rl = IngestRateLimiter::new(1.0, 1.0);
+ let huge = "s".repeat(1024 * 1024);
+ assert!(rl.try_take(&huge, std::time::Instant::now()));
+ assert!(
+ rl.max_stored_key_len() <= INGEST_RATE_MAX_KEY_BYTES,
+ "stored limiter keys must be byte-bounded"
+ );
+ }
+
+ #[test]
+ fn ingest_rate_key_uses_actor_and_missing_session_fallback() {
+ let query = HookQuery {
+ event: "session-start".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ };
+ let one = HookEnvelope::from_query_and_body(query.clone(), serde_json::json!({"cwd":"/a"}));
+ let two = HookEnvelope::from_query_and_body(query.clone(), serde_json::json!({"cwd":"/b"}));
+ assert_ne!(ingest_rate_key(&one, None), ingest_rate_key(&two, None));
+
+ let scoped_a = HookEnvelope::from_query_and_body(
+ HookQuery {
+ workspace: Some("team-a".into()),
+ project_strategy: Some("basename".into()),
+ ..query.clone()
+ },
+ serde_json::json!({"cwd":"/same"}),
+ );
+ let scoped_b = HookEnvelope::from_query_and_body(
+ HookQuery {
+ workspace: Some("team-b".into()),
+ project_strategy: Some("repo-root".into()),
+ ..query.clone()
+ },
+ serde_json::json!({"cwd":"/same"}),
+ );
+ assert_ne!(
+ ingest_rate_key(&scoped_a, None),
+ ingest_rate_key(&scoped_b, None)
+ );
+
+ let with_session =
+ HookEnvelope::from_query_and_body(query, serde_json::json!({"session_id":"same"}));
+ assert_ne!(
+ ingest_rate_key(&with_session, Some("alice")),
+ ingest_rate_key(&with_session, Some("bob")),
+ "different actors sharing a session id get separate limiter buckets"
+ );
+ }
+
#[tokio::test]
async fn handle_hook_rate_limits_a_flooding_source_but_not_others() {
let tmp = TempDir::new().unwrap();
@@ -2010,6 +2143,37 @@ mod tests {
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
}
+ #[tokio::test]
+ async fn handle_hook_does_not_debit_source_token_when_globally_saturated() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_state(&tmp).await;
+ state.ingest_rate = Arc::new(tokio::sync::Mutex::new(IngestRateLimiter::new(0.001, 1.0)));
+ state.ingest_semaphore = Arc::new(tokio::sync::Semaphore::new(0));
+ let state = Arc::new(state);
+
+ let query = HookQuery {
+ event: "session-start".into(),
+ agent: Some("claude-code".into()),
+ ..Default::default()
+ };
+ let body = serde_json::json!({ "session_id": "global-first" });
+ let first = handle_hook(
+ State(state.clone()),
+ Query(query.clone()),
+ None,
+ Json(body.clone()),
+ )
+ .await
+ .into_response();
+ assert_eq!(first.status(), StatusCode::TOO_MANY_REQUESTS);
+
+ state.ingest_semaphore.add_permits(1);
+ let second = handle_hook(State(state), Query(query), None, Json(body))
+ .await
+ .into_response();
+ assert_eq!(second.status(), StatusCode::ACCEPTED);
+ }
+
#[tokio::test]
async fn handle_hook_batch_acks_processed_count() {
let tmp = TempDir::new().unwrap();
@@ -2388,6 +2552,73 @@ mod tests {
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
}
+ #[tokio::test]
+ async fn handle_hook_batch_skips_rate_limited_first_item_and_accepts_later_source() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_state(&tmp).await;
+ let mut limiter = IngestRateLimiter::new(0.001, 1.0);
+ assert!(limiter.try_take("u:\ns:flooder", std::time::Instant::now()));
+ state.ingest_rate = Arc::new(tokio::sync::Mutex::new(limiter));
+
+ let response = handle_hook_batch(
+ State(Arc::new(state)),
+ None,
+ Json(vec![
+ HookBatchItem {
+ url: "http://h/hook?event=session-start&agent=claude-code".into(),
+ body: serde_json::json!({ "session_id": "flooder" }),
+ },
+ HookBatchItem {
+ url: "http://h/hook?event=session-start&agent=claude-code".into(),
+ body: serde_json::json!({ "session_id": "other" }),
+ },
+ ]),
+ )
+ .await
+ .into_response();
+ assert_eq!(response.status(), StatusCode::OK);
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(ack["accepted"], 0);
+ assert_eq!(ack["accepted_indices"], serde_json::json!([1]));
+ }
+
+ #[tokio::test]
+ async fn handle_hook_batch_reports_failed_index_after_rate_limited_skip() {
+ let tmp = TempDir::new().unwrap();
+ let mut state = make_state(&tmp).await;
+ let mut limiter = IngestRateLimiter::new(0.001, 1.0);
+ assert!(limiter.try_take("u:\ns:flooder", std::time::Instant::now()));
+ state.ingest_rate = Arc::new(tokio::sync::Mutex::new(limiter));
+
+ let response = handle_hook_batch(
+ State(Arc::new(state)),
+ None,
+ Json(vec![
+ HookBatchItem {
+ url: "http://h/hook?event=session-start&agent=claude-code".into(),
+ body: serde_json::json!({ "session_id": "flooder" }),
+ },
+ HookBatchItem {
+ url: "http://h/hook?event=user-prompt-submit&agent=claude-code".into(),
+ body: serde_json::json!({ "prompt": "missing session fails" }),
+ },
+ ]),
+ )
+ .await
+ .into_response();
+ assert_eq!(response.status(), StatusCode::OK);
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let ack: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(ack["accepted"], 0);
+ assert_eq!(ack["accepted_indices"], serde_json::json!([]));
+ assert_eq!(ack["failed_index"], 1);
+ }
+
#[tokio::test]
async fn handle_hook_batch_drops_subagent_events_before_capacity_check() {
let tmp = TempDir::new().unwrap();
diff --git a/docs/install.md b/docs/install.md
index 2c4a6b53..ab6ffc2c 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -392,6 +392,15 @@ Timing values must be positive whole minutes. Missing, empty, non-numeric, or
zero values fall back to the built-in defaults; values above 60 are clamped. The
incremental threshold is a positive event count; invalid values fall back to 32.
+Server-side hook ingest also has an optional per-source limiter for shared or
+remote installs that need protection from one runaway agent session. Set
+`AI_MEMORY_HOOK_RATE_PER_SEC` on the server to the token refill rate per
+actor/session source; `0` or unset disables the limiter. Set
+`AI_MEMORY_HOOK_RATE_BURST` to override the burst size (defaults to the refill
+rate, minimum one token when enabled). The limiter is bounded in both key count
+and key bytes, and `/hook/batch` drains can skip over-budget sources while still
+accepting later unrelated sources.
+
### Native service operations
```bash
@@ -757,6 +766,7 @@ The `serve` subcommand also accepts:
| `--web-slug /web` | `AI_MEMORY_WEB_SLUG` | Where the web UI mounts within the base-path. Default `/web`; set to `/` to mount the UI at the base-path root. |
| `--web-ui-dir <path>` | `AI_MEMORY_WEB_UI_DIR` | Serve a custom SPA from `<path>` instead of the built-in browser. ai-memory injects `<base href>` and `<meta name="ai-memory-base-path">` so the SPA can build relative URLs and API calls under the configured prefix. |
| `--cors-allow-origin <origin>` | `AI_MEMORY_CORS_ALLOW_ORIGINS` (CSV) | Allow listed origins to call `/api/v1`. Layer is scoped only to that route — `/mcp`, `/hook`, `/admin`, and `/web` remain origin-locked. |
+| _(config only)_ | `AI_MEMORY_HOOK_RATE_PER_SEC`, `AI_MEMORY_HOOK_RATE_BURST` | Optional per-actor/session hook ingest token bucket. Unset/`0` rate disables it; burst defaults to the rate (minimum one token when enabled). |
On macOS, see [`docs/macos.md`](macos.md); use the archive matching your
architecture: `aarch64` for Apple Silicon, `x86_64` for Intel. On Windows, see