Skip to content

fix(mascot): stop phrase-regen from swap-spiraling memory-pressured boxes#256

Open
yalexx wants to merge 1 commit into
mainfrom
fix/mascot-phrase-regen-safety
Open

fix(mascot): stop phrase-regen from swap-spiraling memory-pressured boxes#256
yalexx wants to merge 1 commit into
mainfrom
fix/mascot-phrase-regen-safety

Conversation

@yalexx

@yalexx yalexx commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

Field incident

Customer box (Jul 6): maybeRegenerateInBackground() picked llama3.2:3b, inference timed out at 60s — and because a failed generation never writes the cache, the stale cache retried the full 2GB model load on every mascot fetch (~every 90s), driving the box to 92% RAM + 100% swap until everything else fell over.

Fixes

  • 12h failure backoff (persisted in KV) — timeouts, bad output, and low-memory skips all block background retries; the explicit Settings "regenerate" button bypasses the backoff but not the memory guard
  • Tiny models only (≤2B) — removed 3B+ from PREFERRED_MODELS and removed the "first installed model" fallback (could select a user-pulled 7B+)
  • RAM headroom guard — generation skipped below 3GB MemAvailable (fails open on non-Linux dev machines)
  • keep_alive: 0 — Ollama unloads the model immediately after the call instead of holding ~2.6GB for the default 5min

Testing

  • tsc --noEmit clean
  • mascot unit + route tests: 19/19 pass

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Reduced repeated mascot phrase generation attempts after failures, helping avoid unnecessary retries and improving stability.
    • Prevented regeneration when system memory is too low, reducing the chance of slowdowns or failures.
    • Improved phrase generation reliability by using smaller, more suitable model options and releasing resources immediately after use.

…oxes

Field incident (customer box, Jul 6): the background mascot phrase regen
picked llama3.2:3b, timed out at 60s, and because a failed generation
never updates the cache, the still-stale cache retried the full model
load on every mascot fetch — 2.6GB RAM + 145% CPU every ~90s until the
box hit 92% RAM + 100% swap.

- 12h failure backoff persisted in KV: a timeout/bad-output/low-memory
  attempt blocks background retries; explicit Settings regen bypasses it
- tiny models only (<=2B): drop 3B+ from the preferred list and stop
  falling back to 'first installed model' (could be a user-pulled 7B+)
- RAM headroom guard: skip generation below 3GB MemAvailable
- keep_alive: 0 so Ollama unloads the model right after the call instead
  of holding gigabytes for the default 5 minutes

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@yalexx
yalexx requested a review from a team as a code owner July 8, 2026 09:12
@coderabbitai

coderabbitai Bot commented Jul 8, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The mascot phrase generation logic in src/lib/mascot-phrases-server.ts adds persistent failure backoff tracking via KV storage, a RAM headroom check before running Ollama models, restricts model selection to small (≤2B) models, and unloads models immediately after use via keep_alive: 0.

Changes

Generation Gating and Model Safety

Layer / File(s) Summary
Constants, model restriction, and helpers
src/lib/mascot-phrases-server.ts
Adds KV_LAST_FAILURE_KEY, backoff interval, RAM headroom threshold; restricts PREFERRED_MODELS to small models; updates pickOllamaModel to avoid arbitrary fallback; adds helpers for RAM detection and failure timestamp read/record/clear.
Ollama request unload behavior
src/lib/mascot-phrases-server.ts
Sets keep_alive: 0 in the /api/generate request payload to unload the model immediately after generation.
Background and forced regeneration gating
src/lib/mascot-phrases-server.ts
maybeRegenerateInBackground and forceRegenerate now skip or block regeneration based on failure backoff and RAM headroom, recording/clearing failure timestamps depending on generation outcome.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant RegenerateFn as maybeRegenerateInBackground/forceRegenerate
  participant MemCheck as hasMemoryHeadroom
  participant KV
  participant Ollama

  Caller->>RegenerateFn: trigger regeneration
  RegenerateFn->>KV: read last failure timestamp
  RegenerateFn->>MemCheck: check available RAM
  MemCheck-->>RegenerateFn: headroom result
  alt backoff not elapsed or low memory
    RegenerateFn->>KV: record failure timestamp
    RegenerateFn-->>Caller: skip generation
  else proceed
    RegenerateFn->>Ollama: generate phrases (keep_alive 0)
    alt success
      Ollama-->>RegenerateFn: phrases
      RegenerateFn->>KV: clear failure timestamp
    else failure
      Ollama-->>RegenerateFn: error
      RegenerateFn->>KV: record failure timestamp
    end
  end
Loading
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: preventing mascot phrase regeneration from overloading memory-pressured boxes.
Description check ✅ Passed It covers the summary and testing well, but it omits the template's Type of change and Checklist sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/mascot-phrase-regen-safety

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed: dependency version conflict. Check your lock file or package.json.


Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 8, 2026

Copy link
Copy Markdown

CI Summary

✅ Tests

  • Result: passed
  • View run
  • Coverage: statements 69.37%, branches 59.35%, functions 64.59%, lines 71.35%

✅ E2E

✅ E2E Install

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/lib/mascot-phrases-server.ts (1)

345-356: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Clear the failure backoff only after the cache write succeeds.

Line 345 and Line 395 clear the persisted backoff before writeCache() succeeds. If that write throws, the cache stays stale while the backoff is cleared, so future mascot fetches can retry generation repeatedly.

As per path instructions: src/lib/** are TypeScript server-side libraries and should be reviewed for proper error handling and type safety.

Proposed fix
-      clearFailure();
-
       const now = Date.now();
       const existingPhrases = cached?.phrases ?? INSPIRATION_PHRASES;
       const merged = mergeBatch(existingPhrases, fresh, mode);
 
-      writeCache({
-        phrases: merged,
-        language: ctx.language,
-        lastFullRegen: mode === "full" ? now : (cached?.lastFullRegen ?? now),
-        lastTopUp: now,
-      });
+      try {
+        writeCache({
+          phrases: merged,
+          language: ctx.language,
+          lastFullRegen: mode === "full" ? now : (cached?.lastFullRegen ?? now),
+          lastTopUp: now,
+        });
+        clearFailure();
+      } catch (err) {
+        recordFailure();
+        throw err;
+      }
-      clearFailure();
       const now = Date.now();
-      writeCache({
-        phrases: fresh,
-        language: ctx.language,
-        lastFullRegen: now,
-        lastTopUp: now,
-      });
+      try {
+        writeCache({
+          phrases: fresh,
+          language: ctx.language,
+          lastFullRegen: now,
+          lastTopUp: now,
+        });
+        clearFailure();
+      } catch (err) {
+        recordFailure();
+        throw err;
+      }
       return fresh;

Also applies to: 395-402

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/mascot-phrases-server.ts` around lines 345 - 356, The failure backoff
is being cleared too early in the mascot phrase generation flow, before the
cache persistence succeeds. Update the relevant logic in the mascot phrases
server code around the `clearFailure()` and `writeCache()` calls so the backoff
is only cleared after `writeCache()` completes successfully, and apply the same
sequencing in the other affected block referenced by the review. Keep the
existing symbols like `clearFailure`, `writeCache`, `mergeBatch`, and the regen
path in `src/lib/mascot-phrases-server.ts` so the persisted state and backoff
stay consistent if cache writes throw.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/lib/mascot-phrases-server.ts`:
- Around line 345-356: The failure backoff is being cleared too early in the
mascot phrase generation flow, before the cache persistence succeeds. Update the
relevant logic in the mascot phrases server code around the `clearFailure()` and
`writeCache()` calls so the backoff is only cleared after `writeCache()`
completes successfully, and apply the same sequencing in the other affected
block referenced by the review. Keep the existing symbols like `clearFailure`,
`writeCache`, `mergeBatch`, and the regen path in
`src/lib/mascot-phrases-server.ts` so the persisted state and backoff stay
consistent if cache writes throw.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 014132e5-0de3-4890-a8c9-9ca3f19f2954

📥 Commits

Reviewing files that changed from the base of the PR and between 111446c and 4598284.

📒 Files selected for processing (1)
  • src/lib/mascot-phrases-server.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant