OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug] AddResource tasks hang forever in `processing`: `wait_for_descendants` loops on orphan in-memory TaskWorkIndex._work with no timeout (present in 0.4.15 and 0.4.16)

Open livechenjt-prog opened this issue 3 months ago • 3 comments

Summary

AddResource tasks that have already written data to disk sometimes stay stuck in processing forever. The worker appears blocked in TaskWorkIndex.has_work inside wait_for_descendants, which loops asyncio.sleep(0.05) with no timeout whenever an orphan work entry remains in the in-memory _work dict. This leaves the task permanently processing, the queue worker occupied, and subsequent pending AddResource tasks pile up unconsumed.

Environment

  • OpenViking: 0.4.15 (also present in 0.4.16, see below)
  • Symptom seen with both file and URL AddResource imports

Repro / observation

  1. Submit an add-resource (or a batch).
  2. The data is written to disk successfully (resource file present, correct size).
  3. But the queue shows the task stuck in processing with Processed never incrementing; ov observer queue shows AddResource | <N pending> | <k processing> | 0 processed.
  4. Restarting the server does not clear it (tasks are re-queued to processing again).

We have ~21 such zombie tasks accumulating per day on an otherwise healthy instance.

Root cause (from source)

openviking/service/task_tracker.py (wait_for_descendants):

async def wait_for_descendants(self, task_id, current_work_id):
    while self._work_index.has_work(task_id, exclude_work_id=current_work_id):
        await asyncio.sleep(0.05)

openviking/service/task_work_index.py:

self._work: dict[str, set[tuple[str,str]]] = {}   # in-memory only, no TTL
...
def has_work(self, task_id, exclude_work_id=None):
    return bool(self._work.get(task_id) or self._active.get(task_id))

_work is an in-memory structure with no timeout / TTL / reaper. register() adds a (queue_name, work_id) entry; _remove_work() is only called on the ACK/finalization path. If that finalization callback is not reached (worker cancel/timeout/exception/restart window), the entry remains forever in _work[task_id], and wait_for_descendants spins forever.

Because the loop has no timeout and _work is never pruned, the task never completes and never ACKs. Restarting the server reloads the same pending/processing tasks (from the durable queue) and immediately re-hangs.

Also present in 0.4.16

We compared the two tags: in 0.4.16, has_work gained an exclude_work_id parameter (which fixes the different case where the current task counts its own work), but self._work remains in-memory with no TTL and no reaper, and the no-timeout loop is unchanged. So the orphan-work hang (the case where finalization never ran) is not addressed by the 0.4.16 change.

Suggested fix

  1. Give TaskWorkIndex._work entries a TTL / lease expiry (e.g. a per-entry registered_at + a max_work_age_secs, with a background reaper), OR
  2. Make wait_for_descendants respect await asyncio.wait_for(..., timeout=...) and treat a timeout as "descendants settled/warn" instead of hanging forever, OR
  3. (at minimum) Add a max-wait cap to the loop so a worker cannot block indefinitely.

Workaround on our side

We run a watchdog that periodically clears these orphan zombie tasks (resources are already on disk, so nothing is lost). We would prefer first-class fix upstream.

livechenjt-prog avatar Aug 26 '26 05:08 livechenjt-prog

Thanks for the report. I think the observation that the resource is already written to disk is important, but it does not necessarily mean the AddResource task is fully finished.

In the current queue lifecycle, AddResource does more than persist the source resource. After the main resource write succeeds, the AddResource worker still waits for descendant queue work under the same task, such as Semantic / Embedding work used to generate sidecars and update retrieval indexes.

So this state is possible:

resource files: already persisted
task.result: success
task.status: still running
AddResource queue message: not ACKed yet
descendant Semantic/Embedding work: still processing or requeued

That means the leftover task is probably not caused by the resource write itself. The more likely source is a descendant queue message that never reaches a terminal/ACKed state, while the parent AddResource waits indefinitely in wait_for_descendants().

I would avoid treating this as only a stale in-memory TaskWorkIndex entry. If it survives restart, we should first check whether the corresponding Semantic/Embedding queue message is still present in QueueFS and being restored/retried. That would indicate a durable child-work lifecycle issue rather than a pure memory orphan.

Could you share a stable reproduction if you have one? The most useful evidence would be:

  • the stuck task_id
  • queue name of the remaining child work, e.g. Semantic or Embedding
  • child work_id / message_id
  • child message payload URI/context type
  • the exception or retry logs for that child work

A root fix should probably make descendant work reach a terminal state or propagate failure back to the parent AddResource task. A timeout/TTL may help as a guardrail, but it would not address the source if the real issue is a poison descendant message being retried forever.

sponge225 avatar Aug 26 '26 07:08 sponge225

Thanks for the detailed analysis — I agree that "resource on disk ≠ AddResource finished" is the right lens, and that a descendant queue message (Semantic/Embedding) never reaching a terminal ACK is the more likely root than a mere in-memory orphan. That matches what we observed.

What we see on our side (current state, after our mitigations)

Right now the queue is clean — no stuck descendants:

AddResource: 0 pending, 0 processing, 9 processed, 0 error
Embedding:   0 pending, 0 processing, 49 processed, 17 error
Semantic:    0 pending, 0 processing, 23 processed, 0 error

queue_messages for Embedding and Semantic is empty of pending/processing rows (nothing being restored/retried).

One concrete trigger we measured: image embedding -> SiliconFlow HTTP 400 (code 20015)

We ran into a very specific, reproducible case that behaves exactly like your "poison descendant being retried/re-enqueued forever": resources containing images (e.g. .jpg sidecars) are sent to our dense embedding backend (SiliconFlow BAAI/bge-large-zh-v1.5), which rejects image inputs with HTTP 400 code 20015 (message: The parameter is invalid). The Embedding queue then fails that child message, and the parent AddResource never gets its descendant ACK -> the parent spins in wait_for_descendants() forever.

Repro (direct, no queue needed): sending an OpenAI-style {type: image_url} input to SiliconFlow /v1/embeddings returns exactly:

{"code":20015,"message":"The parameter is invalid. Please check again.","data":null}

while a plain-text input to the same endpoint returns 200 with a 1024-dim vector.

So for us the "poison descendant" is a multi-modal (image) embedding message whose embedder cannot handle images. The parent AddResource correctly waits, but its descendant is doomed to fail forever. This is a strong candidate for "a descendant never reaching a terminal ACKed state."

What we ship as a guardrail (not claiming it fixes the source)

  1. 30s max-wait cap in wait_for_descendants() so a worker cannot block indefinitely on a doomed descendant. (We accept this is a guardrail, matching your "timeout/TTL helps but isn't the root fix".)
  2. A watchdog that clears AddResource tasks whose resource is already on disk AND whose descendants are stuck — effectively an external ACK.

Request / what would help us

  • Should resource collection creation skip embedding for image-only or multimodal resources when the dense embedder does not advertise image support? (i.e. drop/disable the child Embedding message for image content instead of failing forever).
  • Alternatively, is there a recommended way to make the parent AddResource propagate a descendant failure back so it ACKs (or terminal-fails) the parent rather than hanging?

Happy to capture the stuck task_id + child work_id + exception logs the next time we hit a live repro if that would be more useful than the direct API repro.

livechenjt-prog avatar Aug 26 '26 07:08 livechenjt-prog

Thanks, this is a useful lead. A repeatedly failing Embedding child task would explain why the AddResource parent stays in wait_for_descendants().

I checked the embedding path in v0.4.15, v0.4.16, and current main. They already have the same input guard:

  • EmbeddingMsgConverter may create a multimodal message with image_url parts.
  • TextEmbeddingHandler calls embed_compat().
  • embed_compat() calls embedder.prepare_embedding_input().
  • For text-only embedders, supports_multimodal is False, so image parts should be dropped before calling the provider.

So the direct SiliconFlow repro is useful, but it does not yet prove that OpenViking sent raw image_url to SiliconFlow. We still need to distinguish:

  1. The Embedding worker did not go through the normal input-preparation path.
  2. OpenViking treated the configured embedder as image-capable.
  3. The resource was image-only, so dropping image parts left an empty text input.
  4. The live failure payload was different from the direct API test.

For the next live stuck case, the most useful evidence is the actual stuck Embedding queue row and its matching error log. Please run this before clearing the stuck task:

python3 - <<'PY' <workspace>/_system/queue/queue.db
import json
import sqlite3
import sys

db = sys.argv[1]
conn = sqlite3.connect(db)

rows = conn.execute("""
select id, message_id, status, data
from queue_messages
where queue_name='Embedding'
  and status in ('pending','processing')
order by id
""").fetchall()

print("row_count=", len(rows))

for row_id, message_id, status, raw in rows:
    envelope = json.loads(raw)
    payload = envelope.get("data")

    if isinstance(payload, list):
        payload = bytes(payload).decode("utf-8")
    if isinstance(payload, str):
        payload = json.loads(payload)

    context = payload.get("context_data") or {}

    print(json.dumps({
        "row_id": row_id,
        "message_id": message_id,
        "status": status,
        "task_id": payload.get("task_id"),
        "work_id": payload.get("_task_work_id"),
        "message": payload.get("message"),
        "context_data": {
            "uri": context.get("uri"),
            "level": context.get("level"),
        },
    }, ensure_ascii=False, indent=2))
PY

What we need from that output is:

  • whether task_id matches the stuck AddResource task
  • the child message_id / work_id
  • context_data.uri and context_data.level
  • the actual EmbeddingMsg.message

Please also include the OpenViking log lines for the same message_id or context_data.uri, especially the full embedding exception.

This should tell us whether the stuck descendant is caused by raw image_url, image-only content becoming empty text after downgrade, or a different invalid embedding payload. The fix should then target that source, plus make descendant embedding failures reach a terminal state so AddResource cannot wait forever.

sponge225 avatar Aug 26 '26 08:08 sponge225