OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

logging.StreamHandler multi-thread deadlock causes session.commit() phase 2 to hang permanently

Open njuboy11 opened this issue 5 months ago • 1 comments

Bug Description

When OpenViking runs with log.output='stdout' (default) and is managed by systemd (which redirects stdout to a file), Python's logging.StreamHandler can deadlock during concurrent log writes. This causes session.commit() phase 2 to hang permanently—the .done file is never written.

Root Cause

logging.StreamHandler.emit() holds a thread lock across stream I/O:

def emit(self, record):
    self.acquire()  # ← lock held
    self.flush()    # ← blocks on systemd-piped file I/O
    self.release()

When two async coroutines in phase 2 concurrently call logger.info() / logger.warning() (e.g., memory extraction results, WM update):

  1. Thread-A: logger.warning(large_payload) → handler.acquire() → stream.flush() blocks on file I/O
  2. Thread-B: logger.info(...) → handler.acquire() → blocks forever waiting for Thread-A
  3. All subsequent logger.*() calls from ANY thread block forever
  4. Phase 2's _write_done_file() needs logger.info() → deadlock → .done never written

Symptoms

  • Phase 1 completes (messages.jsonl written)
  • Phase 2 writes some artifacts (overview.md, memory_diff.json) then stops
  • .done file NEVER appears
  • /var/log/openviking/server.log goes completely silent
  • /health returns 200 (process alive), but all new commits return FAILED_PRECONDITION: unresolved failed archive
  • Process shows 30+ threads but zero CPU on worker threads

Reproduction

  1. log.output='stdout' (OV default)
  2. Run under systemd or any process manager that redirects stdout to a file
  3. Have a session with large messages (triggers multi-memory extraction)
  4. POST /api/v1/sessions/{sid}/commit
  5. After phase 1, server.log goes silent; .done never appears

The deadlock is probabilistic—larger log payloads (many memories, long summaries) increase probability.

Affected Code

openviking_cli/utils/logger.py: _create_log_handler() stdout/stderr branch

if log_output == "stdout":
    return logging.StreamHandler(sys.stdout)  # ← deadlock here
elif log_output == "stderr":
    return logging.StreamHandler(sys.stderr)  # ← deadlock here

Proposed Fix

Replace StreamHandler with QueueHandler + QueueListener (stdlib logging.handlers, available since Python 3.2):

  • QueueHandler.emit() → queue.put(record) — no lock, no I/O, returns immediately
  • QueueListener has a dedicated single thread that is the only consumer touching the real stream
  • One consumer → zero lock contention → deadlock impossible

Changes: ~25 lines net addition to _create_log_handler() + _build_standard_handler(); 4 blocks touched.

Verification

Tested on OpenViking 0.4.4 (356 Qdrant points, 30 sessions, Python 3.12):

  • Before fix: archive_004 deadlocked at 12:47:53 (all files except .done written, log silent thereafter)
  • After fix: archive_012 completed fully in ~2min — 6/6 files, 8 long_term + 5 execution memories, .done with complete message_id boundaries, server.log continuous output

Full evidence chain with reproduction steps and thread dump available.

Note

The file handler branch (TimedRotatingFileHandler / FileHandler) also inherits StreamHandler's locking pattern and could theoretically deadlock under heavy concurrent writes. This PR focuses on the stdout/stderr path (the default and most common trigger case).

njuboy11 avatar Jun 21 '26 05:06 njuboy11

Thanks for reporting this and for providing the detailed reproduction evidence.

We agree that blocking stdout/stderr logging can stall application code when stdout is redirected by systemd/journald. In the current implementation, the stdout/stderr path uses Python StreamHandler, so a blocked stream write/flush can hold the logging handler lock and block later logger.* calls. That matches the failure mode you observed where session commit phase 2 can stop before the final completion marker is written.

After reviewing #2753, we are not going to merge queue-based logging at this stage. QueueHandler + QueueListener is a valid approach, but it changes the global logging lifecycle and needs careful handling of stream separation, formatter/filter reconfiguration after config load, shutdown behavior, queue backpressure, and regression tests. The current patch also has concrete issues, such as a single global listener causing stdout/stderr stream mixing and reconfiguration not reliably updating the real listener handler.

For now, the recommended mitigation for systemd deployments is to configure log.output="file" rather than stdout, so OpenViking writes directly to its log file instead of relying on stdout/journald. We can revisit queue-backed logging if this becomes a recurring production issue, but it should be handled as a complete logging design change rather than a narrow patch.

Thanks again for raising this and for validating the behavior in a real deployment.

qin-ctx avatar Jun 23 '26 06:06 qin-ctx