fix: guard against episode storm stalling foreground sessions
Problem
Large merged episodes trigger a cascade of expensive post-processing (capture → reward → L2 induction → L3 abstraction → skill crystallization) that can stall OpenClaw and Hermes Agent foreground sessions. This is especially common in long development workflows where relation.classify consistently returns revision/follow_up, allowing a single episode to accumulate dozens or hundreds of turns.
Fixes #1755
Root Causes
- No episode turn limit — episodes grow unbounded; the full L1→L2→L3→skill chain hits all at once when the topic finally ends
- Synchronous classify in
before_prompt_build—relation.classify()is an LLM call that blocks foreground prompt construction with no timeout - Unlimited background LLM concurrency — capture/reward/L2/L3/skill subscribers fire unlimited parallel LLM calls, starving the event loop
Changes
Fix 1: Episode turn hard limit (maxTurnsPerEpisode)
- New config:
algorithm.session.maxTurnsPerEpisode(default 30, range 5–200) - When an open episode reaches this turn count, the next turn forces a topic boundary regardless of relation classification
- Also applies when reopening recovered episodes
Fix 2: Relation classify timeout (classifyTimeoutMs)
- New config:
algorithm.session.classifyTimeoutMs(default 5000ms, range 1000–30000) relation.classify()calls are wrapped withPromise.raceagainst the timeout- On timeout, defaults to
new_task(safe conservative boundary) - Prevents foreground prompt construction from blocking indefinitely
Fix 3: Background LLM concurrency semaphore (bgLlmConcurrency)
- New config:
algorithm.session.bgLlmConcurrency(default 2, range 1–8) - Shared semaphore gates all LLM calls from capture, reward, L2, L3, skill, and feedback subscribers
- Prevents event-loop starvation from concurrent background processing
- Capture's existing
llmConcurrency(per-step α scoring) is unaffected — the semaphore only applies to the shared LLM client used by post-capture processing
New Files
core/util/semaphore.ts— lightweight async semaphorecore/util/rate-limited-llm.ts— transparent LLM client wrapper that acquires a semaphore permit per call
Files Modified
core/config/schema.ts— 3 new config fields with JSDoccore/config/defaults.ts— defaults: maxTurns=30, classifyTimeout=5s, bgConcurrency=2core/pipeline/types.ts— SessionRoutingConfig extendedcore/pipeline/deps.ts— config extraction + semaphore wiringcore/pipeline/orchestrator.ts— turn-limit guard + classify timeout wrapper
Testing
tsc --noEmitpasses (no type errors)- All new config values have sensible defaults that preserve existing behavior for users who don't change them (the turn limit is the only behavior change: episodes that would have grown past 30 turns now get split)
Linked to #1755 — detailed root-cause analysis is in the issue comments.
Automated Test Results: PASSED
Cloud test-engine rerun against dev-v2.0.22 completed successfully.
- Run:
tr-412e6861-c10on cloud test-engine10010 - memos_local_plugin/unit: 8 passed, 0 failed, 0 skipped
Manual code review is still required before merge.
🤖 Open Code Review
Target: PR #1844
Task: f3d1c55808ede3e3
Base: dev-v2.0.25
Head: fix/episode-storm-guard
🔍 OpenCodeReview found 7 issue(s) in this PR.
⚠️ 1 warning(s) occurred during review.
1. apps/memos-local-plugin/core/pipeline/orchestrator.ts (L798-L809)
Silent data loss when turn limit is reached on a closed episode.
When shouldReopen is true but the closed episode has hit maxTurnsPerEpisode, the code only logs and falls through. At that point decision.relation is "follow_up" or "revision" (never "new_task", since shouldReopen is only set for those two), so the subsequent if (decision.relation === "new_task") guard evaluates to false too. Execution then falls through to startEpisode at line ~854, which creates a new episode — but without lastEpisodeBySession being cleared first and without the new_task metadata, silently leaving the relationship tracking state inconsistent.
The intended behavior when the turn limit is reached should be to start a fresh episode explicitly (similar to the new_task path), and the log event should be emitted before the new episode is started, not instead of it. Consider:
if (shouldReopen) {
const prevSnap = session.sessionManager.getEpisode(prev.episodeId);
const turnLimitReached = prevSnap && prevSnap.turns.length >= algorithm.session.maxTurnsPerEpisode;
if (!turnLimitReached) {
// reopen path ...
return { episode: snap, sessionId, relation: decision.relation };
}
log.info("episode.turn_limit_reached", { ... });
// Fall through to start a new episode below, after clearing state.
openEpisodeBySession.delete(sessionId);
lastEpisodeBySession.delete(sessionId);
}
// new episode creation follows...
2. apps/memos-local-plugin/core/pipeline/orchestrator.ts (L96-L107)
Blanket .catch() suppresses all classifyFn() errors, not just timeouts.
The .catch() is chained on Promise.race(), so it catches every rejection — including real LLM errors (network failures, auth errors, rate-limit rejections) thrown by classifyFn(). All of these are silently returned as { relation: 'new_task', confidence: 0, reason: 'classify_timeout' }, making real failures invisible to callers and incorrectly labelling them as a timeout in logs and monitoring.
Distinguish real timeouts from genuine errors:
const timeoutError = new Error("classify_timeout");
return Promise.race([
classifyFn(),
new Promise<RelationDecision>((_, reject) => {
handle = setTimeout(() => reject(timeoutError), timeoutMs);
}),
]).catch((err) => {
if (err !== timeoutError) {
// Re-throw genuine classify errors so callers can handle them properly
throw err;
}
log.warn("relation.classify_timeout", { timeoutMs });
return { relation: "new_task" as const, confidence: 0, reason: "classify_timeout", signals: ["classify_timeout"] };
});
3. apps/memos-local-plugin/core/pipeline/orchestrator.ts (L91-L96)
setTimeout handle is never cancelled, leaking timers when classifyFn() resolves first.
When classifyFn() resolves before the deadline, the pending setTimeout continues to run until it fires and calls reject() on an already-settled promise. At high classification throughput (amplified by the semaphore-controlled LLM concurrency), this creates a pool of live timer handles that grow proportionally to timeoutMs × request_rate.
Store and cancel the handle when the race is won:
let handle: ReturnType<typeof setTimeout>;
return Promise.race([
classifyFn().finally(() => clearTimeout(handle)),
new Promise<RelationDecision>((_, reject) => {
handle = setTimeout(() => reject(new Error("classify_timeout")), timeoutMs);
}),
]).catch(...);
4. apps/memos-local-plugin/core/config/schema.ts (L417)
The hard upper bound of 8 for bgLlmConcurrency is baked into the schema. Users or operators who have high-throughput deployments with many background subscribers (capture, reward, L2, L3, skill-evolution, feedback — already 6 distinct consumers sharing this one semaphore) cannot raise the ceiling above 8 without a schema change. Consider whether a higher ceiling (e.g., 32 or even unlimited with 0 meaning "no cap") is more appropriate, especially since the concurrency budget is already safely capped at runtime by the semaphore. A low schema max may become a latency bottleneck under load.
💡 Suggested Change
Before:
bgLlmConcurrency: NumberInRange(2, 1, 8),
After:
bgLlmConcurrency: NumberInRange(2, 1, 32),
5. apps/memos-local-plugin/core/util/rate-limited-llm.ts (L65-L75)
The semaphore is acquired before iteration starts and held for the entire lifetime of the stream, including consumer-side processing time between yield points. If the inner stream stalls (e.g., network hang, slow consumer) or the consumer abandons early via break/exception, the slot remains occupied until the generator is fully GC'd and finalized.
Since LlmCallOptions already supports signal?: AbortSignal and timeoutMs, consider creating an internal AbortController with a deadline and merging it with the caller's signal before delegating to the inner stream. This ensures a stalled stream cannot hold the semaphore indefinitely and starve all other background callers.
Suggested approach:
async *stream(
messages: LlmMessage[] | string,
opts?: LlmCallOptions,
): AsyncIterable<LlmStreamChunk> {
const release = await this.semaphore.acquire();
try {
yield* this.inner.stream(messages, opts);
} finally {
release();
}
}
Consider adding a timeout guard, e.g. using opts?.timeoutMs or a default, so that a stuck stream releases the permit after a bounded duration.
6. apps/memos-local-plugin/core/util/rate-limited-llm.ts (L85-L87)
The close() method tears down the inner client immediately without draining or cancelling callers currently queued on the semaphore. Because the Semaphore interface exposes only acquire() with no drain()/destroy() method, any pending acquire() promises will eventually resolve and then attempt to call this.inner.complete/completeJson/stream on an already-closed client, causing use-after-close errors or unhandled promise rejections.
Consider one of:
- Extending the
Semaphoreinterface with adestroy(reason?: Error)method that rejects all queued waiters, then calling it fromclose()before delegating toinner.close(). - Tracking an
#closedflag insideRateLimitedLlmClientand having each method throw a descriptive error if#closedis true when the semaphore permit is finally acquired.
7. apps/memos-local-plugin/core/util/semaphore.ts (L25-L29)
Double-release corrupts the semaphore's count. If a caller invokes the release function more than once (accidentally or otherwise), current is decremented again and the guard Math.max(0, …) only prevents it from going negative on the second call — but on any subsequent call the count is already 0, so it stays at 0. From that point on the semaphore allows one extra concurrent slot beyond limit permanently.
Consider guarding against this with a one-shot flag:
function release() {
let released = false;
return function releaseOnce() {
if (released) return;
released = true;
current = Math.max(0, current - 1);
const next = waiters.shift();
if (next) next();
};
}
Then change return release; to return release(); and resolve(release) to resolve(release()) so each acquire call gets its own single-use release function.
Generated by cloud-assistant via Open Code Review.
✅ Automated Test Results: PASSED
All tests passed (10/10 executed). memos_local_plugin/unit: 10/10. Duration: 6s
Branch: fix/episode-storm-guard