OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: Session Phase-2 worker crashes on torn live-messages read; commit task stuck pending forever, client reports misleading "Phase 2 timed out"

Open hhspiny opened this issue 1 month ago • 2 comments

Issue Origin

Observed or reproduced in a real environment

Bug Description

A POST /api/v1/sessions/{id}/commit (compact-driven, keep_recent_count=0) completes Phase 1 normally (archive written, HTTP 200), but the SessionCommit queue worker crashes ~1.5s after dequeue with:

[QueueManager] Concurrent worker error for SessionCommit: Unterminated string starting at: line 1 column 59183 (char 59182)

i.e. a bare json.decoder.JSONDecodeError from Session.load() (session.py:492-496), which reads the live messages.jsonl with no pathlock, concurrently with Phase 1's locked drain-rewrite of the same file (keep_recent_count=0 truncates it to 0 bytes). The worker gets a torn (truncated mid-string) read. Evidence it was torn rather than genuinely corrupt: Phase 1 archived 12 clean, fully-parseable lines (172,516 bytes, each line verified with json.loads) from that same live file seconds later.

The crash is then swallowed by three compounding defects:

  1. SessionCommitProcessor.on_dequeue wraps only _parse_message in try/except; _process (load + everything downstream) is unguarded — so no .failed.json marker is written and tracker.fail is never called. The queue message stays processing and the task stays pending indefinitely (observed still pending 40+ min later; only one pending task system-wide).
  2. Polling clients cannot distinguish a dead task from a slow one, so after ~232s the client reports "compact commit Phase 2 timed out" — masking a 1.5s crash as a 4-minute timeout. The user-facing symptom is "compaction failed" with no hint of the true cause.
  3. Phase 2 reads mutable live state at all, when the immutable messages.jsonl it was just handed is complete — it never needed the live file. (Related: _read_live_messages_strict was already hardened for this exact error signature — see the issue #3984 comment about records being cut producing "Unterminated string" — but load() never got the same treatment, and neither takes the lock.)

Steps to Reproduce

Difficult to reproduce on demand (requires winning a ~ms race), but the setup that triggers it:

  1. A session with a large live messages.jsonl (ours: 12 messages, ~172KB, one 83KB single-line record — large tool outputs widen the race window).
  2. Issue a compact-driven commit with keep_recent_count=0 (or any commit whose Phase 1 drains/truncates the live file), so Phase 1 rewrites messages.jsonl while the Phase-2 worker's session.load() reads it without holding the pathlock.
  3. Observe: worker Concurrent worker error … Unterminated string, task stuck pending, client eventually reports Phase 2 timeout although no extraction ever started (memories_extracted: 0, zero LLM token usage, no .done, no "Starting post-commit extraction" log line).

Expected Behavior

  • The Phase-2 worker either reads under the same pathlock as the Phase-1 writer, or reads the immutable archive file instead of the live file.
  • If the live read still fails, the failure is recorded: .failed.json marker written, task marked failed with the true error, queue message settled (not stuck processing).
  • Polling clients can distinguish dead tasks from slow ones (or the task fails fast), so the reported error is the JSON crash, not a misleading timeout minutes later.

Actual Behavior

  • Worker crashes on torn read; task pending forever; queue row processing forever.
  • Client polls a dead task for ~232s, reports "Phase 2 timed out"; host reports "compaction failed"; host transcript is never rewritten.
  • A retry cannot self-heal (same race window) and the stuck task/row must be cleared manually (via POST /tasks/{id}/cancel plus a hand-written .failed.json — which is what we did).

Minimal Reproducible Example

# Race between writer (holds pathlock) and reader (no lock) on the same file.
# Writer equivalent: Phase-1 drain with keep_recent_count=0.
# Reader equivalent: Session.load(), session/session.py:492-496.
import json, threading

RECORD = '{"id": "m1", "content": "' + "x" * 90000 + '"}'  # large single-line record
PATH = "/tmp/race_messages.jsonl"
open(PATH, "w").write(RECORD + "\n")

def writer():
    # Phase 1 drain: truncate live file (no coordination with reader)
    open(PATH, "w").write("")

def reader(results):
    # Session.load() pattern: unlocked read + bare json.loads per line
    try:
        content = open(PATH).read()
        msgs = [json.loads(line) for line in content.strip().split("\n") if line.strip()]
        results.append(("ok", len(msgs)))
    except Exception as exc:  # load() only swallows storage-not-found; JSON errors propagate
        results.append(("crash", f"{type(exc).__name__}: {exc}"))

results, threads = [], []
for _ in range(200):
    open(PATH, "w").write(RECORD + "\n")
    t1, t2 = threading.Thread(target=writer), threading.Thread(target=reader, args=(results,))
    t1.start(); t2.start(); threads += [t1, t2]
for t in threads:
    t.join()
crashes = [r for r in results if r[0] == "crash"]
print(f"{len(crashes)}/{len(results)} torn reads -> {crashes[0][1] if crashes else 'none'}")

Error Logs

# Phase 1: fine — 12 messages archived, HTTP 200 in 1.8s
2026-10-04 10:18:22,779 - openviking.session.session - INFO - [request_id=720d632b-...] Archived: 12 messages → viking://user/claw/sessions/fcbdf3b0-.../history/archive_002/
2026-10-04 10:18:22,793 - uvicorn.access - INFO - [request_id=720d632b-...] ... "POST /api/v1/sessions/fcbdf3b0-.../commit HTTP/1.1" 200
# Phase 2 worker: crash 1.5s after dequeue, no extraction ever starts
2026-10-04 10:18:22,754 - openviking.storage.queuefs.queue_manager - ERROR - [QueueManager] Concurrent worker error for SessionCommit: Unterminated string starting at: line 1 column 59183 (char 59182)
# Client side: polls dead task, then gives up (~232s later)
2026-10-04T10:22:13.491-07:00 [plugins] openviking: compact commit Phase 2 timed out for session=fcbdf3b0-..., task_id=52301749-...
# Task state afterwards (still, 40+ min later): status=pending, never updated; queue row stuck processing
{"task_id": "52301749-...", "task_type": "session_commit", "status": "pending",
 "created_at": 1791134301.23, "updated_at": 1791134301.23, "processing_seconds": null,
 "result": null, "error": null}

OpenViking Version

0.4.23

Python Version

3.12

Operating System

Linux

Model Backend

Other

Additional Context

  • The archived payload was verified fully parseable line-by-line afterwards — the corruption existed only in the worker's read, supporting the torn-read conclusion over on-disk corruption. Exact byte-level proof would require the worker's read buffer (gone); confidence: crash site certain (only unguarded large-input json.loads in the pre-extraction path — every other parse in that path is guarded or tiny), torn-read mechanism strong inference (identical source read clean seconds later + lock asymmetry + sub-second timing).
  • Possibly related separate observation (same window, may share a root cause in payload handling): session.add_message rejected a capture payload with JSONDecodeError: Unterminated string ... char 2024 (surfaced as INVALID_ARGUMENT), and that session shows only 12 captured messages out of ~800 host-side turns — malformed tool-output payloads may also be breaking capture ingest. Happy to file separately if you prefer.
  • Suggested fix directions (not yet implemented on our side): (a) worker reads the immutable archive file instead of live state, or takes the same exact pathlock; (b) try/except around the Phase-2 prologue writing .failed.json + tracker.fail; (c) client dead-task detection (no task heartbeat/progress within N seconds → fail fast with the worker's error); (d) stale-processing queue delivery recovery.

hhspiny avatar Oct 04 '26 18:10 hhspiny

Root cause: SessionCommitProcessor.on_dequeue only guards _parse_message, so a json.JSONDecodeError from Session.load() escapes the handler — the queue layer leaves the delivery unacked, tracker.fail is never reached, and the task stays pending forever (each restart replays it into the same crash).

Plan: wrap the _process call and mirror the existing session-missing branch in the same function — idempotent tracker.create + tracker.fail so every worker exception leaves an immediate terminal failed state and a settled delivery. The torn-read root cause and client timeout semantics are left as separate follow-ups. Working on a fix now.

akushonkamen avatar Oct 08 '26 15:10 akushonkamen

Opened #5772 — worker exceptions now leave a terminal task state and a settled delivery.

akushonkamen avatar Oct 08 '26 15:10 akushonkamen