MemOS icon indicating copy to clipboard operation
MemOS copied to clipboard

fix: guard against episode storm stalling foreground sessions

Open 0xDe1ty opened this issue 6 months ago • 1 comments

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

  1. No episode turn limit — episodes grow unbounded; the full L1→L2→L3→skill chain hits all at once when the topic finally ends
  2. Synchronous classify in before_prompt_build — relation.classify() is an LLM call that blocks foreground prompt construction with no timeout
  3. 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 with Promise.race against 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 semaphore
  • core/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 JSDoc
  • core/config/defaults.ts — defaults: maxTurns=30, classifyTimeout=5s, bgConcurrency=2
  • core/pipeline/types.ts — SessionRoutingConfig extended
  • core/pipeline/deps.ts — config extraction + semaphore wiring
  • core/pipeline/orchestrator.ts — turn-limit guard + classify timeout wrapper

Testing

  • tsc --noEmit passes (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)

0xDe1ty avatar May 31 '26 14:05 0xDe1ty

Linked to #1755 — detailed root-cause analysis is in the issue comments.

0xDe1ty avatar May 31 '26 14:05 0xDe1ty

Automated Test Results: PASSED

Cloud test-engine rerun against dev-v2.0.22 completed successfully.

  • Run: tr-412e6861-c10 on cloud test-engine 10010
  • memos_local_plugin/unit: 8 passed, 0 failed, 0 skipped

Manual code review is still required before merge.

Memtensor-AI avatar Jul 02 '26 12:07 Memtensor-AI

🤖 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:

  1. Extending the Semaphore interface with a destroy(reason?: Error) method that rejects all queued waiters, then calling it from close() before delegating to inner.close().
  2. Tracking an #closed flag inside RateLimitedLlmClient and having each method throw a descriptive error if #closed is 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.

Memtensor-AI avatar Jul 23 '26 10:07 Memtensor-AI

✅ Automated Test Results: PASSED

All tests passed (10/10 executed). memos_local_plugin/unit: 10/10. Duration: 6s

Branch: fix/episode-storm-guard

Memtensor-AI avatar Jul 23 '26 10:07 Memtensor-AI