OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

Large memory patch misses can stall OpenViking server

Open ehz0ah opened this issue 6 months ago • 1 comments

Summary

OpenViking session commit processing can stall the server under a heavy accumulated-memory update workload. In one Hermes Agent E2E import run, OpenViking completed 187 session commits, then subsequent commit requests timed out while the OpenViking process remained alive and CPU-bound. /health also stopped responding within a 3s timeout.

The workload was a stress case, not a typical small single-user session. The failure mode is still product-relevant: long-lived users or tenants can accumulate large memory documents and repeatedly update the same profile/entity/event files. Expensive memory update work should be bounded or isolated so it cannot starve HTTP request handling.

Ingestion path

This was not a direct OpenViking-only import. The data was ingested through Hermes Agent using the OpenViking memory provider.

Run shape:

  • 272 flattened conversation sessions expected.
  • Import parallelism was 4 workers.
  • Each imported session triggered an OpenViking session commit.
  • All commits targeted the same long-lived memory namespace.

Observed behavior

The persisted OpenViking state reached a stable partial point:

187 archive .done files
187 memory_diff.json files
0 .failed.json archive markers

After that, commit requests began timing out:

Failed to trigger OpenViking commit: HTTPConnectionPool(host='127.0.0.1', port=1933): Read timed out. (read timeout=10)
Import failed for 85 session(s) after retries

The OpenViking process stayed alive but was pinned near one CPU core. A health check timed out:

curl: (28) Operation timed out after 3006 milliseconds with 0 bytes received

Several memory files had grown large by the time of failure:

109548 bytes  memories/events/2026/05/09/.overview.md
69561 bytes   memories/events/2026/05/10/.overview.md
39988 bytes   memories/profile.md
36281 bytes   memories/entities/person/john.md

OpenViking logs showed repeated patch application failures on memory entity files before and during the degradation:

Patch application failed, skipping update
Failed to apply operation: op_type=ResolvedOperation, uris=['viking://user/default/memories/entities/person/john.md']
PatchParseError: Patch application failed: search content not found in original

Similar failures appeared for tim.md, john.md, and james.md. The exception output also included full original memory content and the patch payload, which made individual log entries very large.

Manual process snapshot captured during the degraded state:

PID    STAT  %CPU  COMMAND
18325  Rs+   98.5  openviking-server --host 127.0.0.1 --port 1933

The same run also produced stale lock cleanup warnings:

[SUBTREE] Removing stale lock: /local/default/agent/hermes/memories/.path.ovlock
[SUBTREE] Removing stale lock: /local/default/user/default/memories/.path.ovlock

Those lock warnings may be downstream symptoms rather than the primary cause, but they are part of the observed failure state and may be useful when investigating lock recovery, stuck phase-2 work, or server starvation.

Expected behavior

  • Patch misses should fail quickly and with bounded CPU cost.
  • Session commit work should apply backpressure, fail the job, or remain queued when the workload exceeds safe limits.
  • /health, task status, and new commit requests should remain responsive enough to diagnose the system.
  • Large memory files should not allow one memory update path to monopolize the server process.

Actual behavior

  • Commit requests repeatedly timed out.
  • /health timed out.
  • The process stayed alive and CPU-bound.
  • Missing sessions did not produce archive failed markers; progress stopped after the 187 completed archives.
  • Stale memory lock cleanup warnings appeared during the same degraded run.

Suspected mechanism

The strongest candidate is unbounded fuzzy patch matching after generated memory patches miss the current file content.

Relevant paths:

  • openviking/session/memory/merge_op/patch_handler.py
    • apply_str_patch() first tries direct substring replacement.
    • If the search block is missing, it falls back to line-based fuzzy search.
    • fuzzy_search() calls get_similarity() / levenshtein_distance() repeatedly.
  • openviking/session/memory/memory_updater.py
    • _apply_upsert() applies merge operations and only records the failure after patch application returns or raises.
  • openviking/session/session.py
    • Commit phase 2 runs via asyncio.create_task() inside the same server process.

This means CPU-heavy Python work in commit phase 2 can still starve HTTP handling even though the work is launched as a background task.

This is not a proven sole root cause. The evidence supports investigating the fuzzy patch fallback path first, but other work in the commit phase-2 path, including overview generation, vectorization enqueueing, and lock handling, should also be checked.

Reproduction

A full reproduction may not be deterministic because it depends on model output, patch shape, memory file growth, and timing. A realistic stress reproduction is:

  1. Start OpenViking server.
  2. Send many conversation sessions through Hermes Agent configured with the OpenViking memory provider.
  3. After each Hermes Agent session write is visible in OpenViking, trigger the corresponding OpenViking session commit.
  4. Run with enough parallelism for multiple commit phase-2 tasks to overlap.
  5. Continue until memory files such as profile/entity/event overview files become large.
  6. Observe whether patch failures appear and whether /health and later commit requests remain responsive.

A narrower regression test should target the suspected hot path directly:

  1. Create a large markdown memory document.
  2. Apply a StrPatch whose search block is absent.
  3. Assert that apply_str_patch() fails within a bounded time.
  4. Assert that the error/log path does not include the full original document or full patch payload.

Severity and impact

Severity: availability issue under heavy accumulated-memory update load.

The exact workload is a benchmark/stress scenario. The underlying pattern is not benchmark-specific: a long-running memory system can accumulate large documents, generate stale or non-matching patch operations, and repeatedly update the same memory files. Under those conditions, the server should degrade predictably rather than becoming unresponsive.

Possible remediation options

Short-term hardening:

  • Add bounds to fuzzy patch matching: max file size, search size, candidate count, and/or elapsed time.
  • Skip fuzzy fallback on large files unless a narrow line/window anchor is available.
  • Make patch miss failures cheap and structured.
  • Truncate patch failure logs; emit URI, file size, search size, block count, elapsed time, and reason instead of full document content.
  • Add telemetry around patch application latency and fallback usage.
  • Include lock state/age and phase-2 task identifiers in diagnostics when stale memory locks are cleaned up.

Longer-term fix:

  • Move commit phase-2 memory extraction/update work out of the HTTP server process, or into a worker model that cannot starve request handling.
  • Keep commit phase 1 in the request path: archive the session, enqueue durable work, return a task id.
  • Run extraction, patch application, overview generation, and vectorization enqueueing in bounded workers with concurrency limits, timeouts, and retries.
  • Make patching version-aware, for example with a base revision/content hash, so stale patches can fail cleanly or trigger a re-read/regenerate path.
  • Consider storing structured memory records as the source of truth and rendering large markdown overviews as derived artifacts, instead of repeatedly patching monolithic markdown files.

I'm not sure how to approach and would appreciate some opinions on this issue. Thanks.

ehz0ah avatar May 11 '26 13:05 ehz0ah

Additional occurrence from a separate Hermes Agent LoCoMo E2E import run. This looks like the same failure class, with a more direct stack trace pointing at the suspected fuzzy patch path.

Run shape:

  • Hermes Agent -> OpenViking memory provider ingestion path
  • 272 flattened sessions expected
  • Import parallelism: 1
  • QA/judge were not reached
  • OpenViking and Hermes were running locally; secrets/endpoints omitted

Observed state before stopping the stuck process:

98 import_success.csv rows excluding header
98 archive .done files
98 memory_diff.json files
0 .failed.json markers while the process was hung
last successful session: locomo-e2e-conv-42-session_28
first stuck/failing session: locomo-e2e-conv-42-session_29
OpenViking /health timed out
OpenViking process was alive and pinned near one CPU core
subsequent commit requests timed out with read timeout=10

After sending SIGTERM/shutdown, OpenViking emitted the stack trace for the stuck task and wrote a failed marker for locomo-e2e-conv-42-session_29:

.failed.json:
{"stage":"memory_extraction","error":"cancelled: ","failed_at":"2026-06-16T23:18:59.704Z"}

Relevant stack frames emitted during shutdown:

openviking/session/compressor_v2.py:380 extract_long_term_memories
openviking/session/memory/extract_loop.py:254 run
openviking/session/memory/extract_loop.py:779 _validate_patch_operations
openviking/session/memory/merge_op/patch_handler.py:1010 apply_str_patch
openviking/session/memory/merge_op/patch_handler.py:155 fuzzy_search
openviking/session/memory/merge_op/patch_handler.py:104 get_similarity
openviking/session/memory/merge_op/patch_handler.py:55/68 levenshtein_distance

This supports the suspected mechanism in the issue description: a generated patch missed the exact target content, then validation entered the fuzzy fallback path and spent CPU in pure-Python Levenshtein matching. Because that work ran inside the server process, health checks and commit APIs stopped responding.

In this occurrence, the task did eventually get marked failed only when the server was terminated. During the hung state, the archive did not have a .failed.json, and clients only saw commit/read timeouts.

This also happened with import parallelism set to 1, so parallel commit pressure is not required to trigger it. Parallelism likely increases probability, but a single long-lived accumulated-memory namespace can hit the same CPU-bound fallback.

Useful follow-up regression target remains: exercise apply_str_patch() on a large markdown memory document with an absent or stale multi-line search block and assert bounded runtime / bounded fallback scope / no server event-loop starvation.

ehz0ah avatar Jun 17 '26 05:06 ehz0ah