OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: Permanent AGFSNotADirectoryError misclassified as "Transient API error" causes infinite retry and deadlocks the whole semantic ingest queue

Open leo8103lee opened this issue 2 months ago • 7 comments

Issue Origin

Observed or reproduced in a real environment

Bug Description

When add_resource writes a small document (below the ~1024-token split threshold), the resource is stored as a single file. The semantic processor afterwards calls ls() on that same path as if it were a directory, which raises AGFSNotADirectoryError.

This structural error is then classified as a transient error and re-enqueued:

openviking.pyagfs.exceptions.AGFSNotADirectoryError: not a directory: //resources////.md openviking.storage.queuefs.semantic_processor - WARNING - Transient API error processing semantic message, re-enqueueing

Because the condition is deterministic, the task can never succeed. There is no retry ceiling and no dead-letter queue, so the message is retried forever while holding an AddResource concurrency slot. With vlm.max_concurrent=4, four such documents saturate the entire ingest pipeline.

Observed impact

In our deployment the queue was fully deadlocked for 15+ hours:

  • 4 AddResource tasks stuck in processing (8.6h–15.6h each)
  • 85 tasks stuck in pending, none progressing
  • Every new add_resource call returned HTTP 409
  • /ready kept reporting status: ready — nothing in the health surface exposed the stall

Retry counts from a single container's logs (paths anonymised):

Target Retries logged
<pkg-a>/<ver>/<subdir>/doc-1.md 1622
<pkg-a>/<ver>/<subdir>/doc-2.md 1066
<pkg-a>/<ver>/<subdir>/doc-3.md 38
<pkg-a>/<ver>/<subdir>/doc-4.md 38
... 8 more paths 12–32 each

The two write paths behave differently

The same single-file resource shape is fine when written through content/write:

Write path isDir AGFSNotADirectoryError occurrences
POST /api/v1/content/write False 0
add_resource False 1000+

One more suspicious symptom: some failing paths contain a duplicated segment, e.g. .../<doc>.md/<doc>.md, which suggests the file name is being appended as a directory component somewhere in the add_resource path resolution.

Note: the data itself is written correctly

The resource content is fully and correctly persisted — we byte-compared the stored content against the uploaded temp file and they are identical. Only the semantic post-processing (L0/L1 abstract generation) fails. So the damage is not data loss, it is pipeline starvation.

Steps to Reproduce

  1. Start openviking-server with vlm.max_concurrent: 4 (any local/OpenAI-compatible VLM).
  2. Use add_resource to upload a Markdown file smaller than the split threshold (~1024 tokens; ours were 1.5–5.4 KB) targeting a path under an existing resource tree, e.g. viking://resources/<pkg>/<version>/<subdir>/<doc>.md
  3. Verify the resource is created as a file: GET /api/v1/fs/stat?uri=... returns isDir: false.
  4. Watch the server logs — AGFSNotADirectoryError is raised and logged as Transient API error ... re-enqueueing, repeating indefinitely.
  5. Repeat with 4 such documents to occupy every AddResource slot.
  6. Every subsequent add_resource now returns 409, and GET /api/v1/tasks shows tasks piling up in pending while processing entries never age out.

Expected Behavior

  1. AGFSNotADirectoryError is a deterministic structural error and should be classified as permanent, not transient — it must fail the task instead of re-enqueueing.
  2. The queue should enforce a max_retries ceiling with backoff, and route exhausted messages to a dead-letter queue. (The embedding path already has a circuit breaker — failure_threshold=5, reset_timeout=60, max_reset_timeout=600 — the semantic ingest queue has no equivalent protection.)
  3. A failed or stuck task must release its concurrency slot so one malformed input cannot starve the entire pipeline.
  4. add_resource should handle the single-file resource shape consistently with content/write, or the semantic processor should detect isDir == false and generate the abstract without attempting ls() on a file path.
  5. /ready (or a queue-health endpoint) should surface a stalled ingest queue rather than reporting healthy while nothing progresses.

Actual Behavior

The task is retried indefinitely (1600+ times observed), never completes, never releases its slot. Four such tasks deadlock the entire ingest queue while /ready still reports status: ready. Recovery required manually calling POST /api/v1/tasks/{task_id}/cancel on each stuck task.

queuefs.recover_stale_sec: 0 did not help — the tasks remained in processing across multiple container restarts.

Minimal Reproducible Example

#!/usr/bin/env bash
# Reproduces the deadlock on OpenViking v0.4.19
# Precondition: server running with vlm.max_concurrent=4 (the default in our setup)

BASE="http://127.0.0.1:1933"
KEY="<user-api-key>"
TARGET="viking://resources/demo/v1/subdir"

# 1) Create a document SMALL ENOUGH to stay below the ~1024-token split
#    threshold, so it is stored as a single file rather than a directory.
printf '# doc-1\n\nshort content, well under 1024 tokens.\n' > /tmp/doc-1.md

# 2) Upload it to the temp store
FID=$(curl -sS -X POST "$BASE/api/v1/resources/temp_upload" \
        -H "X-API-Key: $KEY" \
        -F "file=@/tmp/doc-1.md" \
      | python3 -c 'import json,sys; print(json.load(sys.stdin)["result"]["temp_file_id"])')

# 3) Ingest it into an existing resource tree
curl -sS -X POST "$BASE/api/v1/resources" \
     -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
     -d "{\"temp_file_id\":\"$FID\",\"to\":\"$TARGET\",\"create_parent\":true}"

# 4) The resource IS created correctly as a file:
curl -sS "$BASE/api/v1/fs/stat?uri=$TARGET/doc-1.md" -H "X-API-Key: $KEY"
#    -> "isDir": false   and the content matches the upload byte for byte

# 5) But the server log now repeats forever:
#    AGFSNotADirectoryError: not a directory: /<account>/resources/demo/v1/subdir/doc-1.md
#    semantic_processor - WARNING - Transient API error ... re-enqueueing

# 6) Repeat steps 1-3 with doc-2 .. doc-4 to occupy all four AddResource slots.
#    From here on every add_resource returns HTTP 409, and
#    GET /api/v1/tasks shows tasks accumulating in "pending" forever
#    while the four "processing" entries never age out.
#
#    Only recovery: POST /api/v1/tasks/{task_id}/cancel for each stuck task.

Error Logs

openviking.storage.queuefs.semantic_processor - WARNING - Transient API error processing semantic message, re-enqueueing

Traceback (most recent call last):
  File "openviking/storage/viking_fs/_ops.py", line 1949, in _ls_original
  File "openviking/storage/viking_fs/_ops.py", line 2004, in _ls_browsable_items
  File "openviking/storage/viking_fs/_access.py", line 935, in _list_read_path_items
  File "openviking/storage/viking_fs/_ops.py", line 2188, in _ls_entries
    entries = await self._async_agfs.ls(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "openviking/pyagfs/async_client.py", line 126, in ls
    return await self.run("ls", path, **kwargs, ctx=_fs_ctx_or_default(path, fs_ctx))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "openviking/pyagfs/async_client.py", line 96, in run
    return await asyncio.to_thread(getattr(self._client, method_name), *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.13/asyncio/threads.py", line 26, in to_thread
    return await loop.run_in_executor(None, func_call)
  File "/usr/local/lib/python3.13/concurrent/futures/thread.py", line 59, in run
    result = self.fn(*self.args, **self.kwargs)
openviking.pyagfs.exceptions.AGFSNotADirectoryError: not a directory: /<account>/resources/<pkg>/<version>/<subdir>/<doc>.md

--- the same trace repeats continuously; occurrence counts per target from one container's logs ---
1622  <pkg-a>/<ver>/<subdir>/doc-1.md
1066  <pkg-a>/<ver>/<subdir>/doc-2.md
  38  <pkg-a>/<ver>/<subdir>/doc-3.md
  38  <pkg-a>/<ver>/<subdir>/doc-4.md
  ... 8 further paths at 12-32 each

--- note: one failing path contains a duplicated segment, suggesting a path-join issue ---
      <pkg-b>/<ver>/<doc>.md/<doc>.md

OpenViking Version

0.4.19

Python Version

3.13.15

Operating System

macOS

Model Backend

OpenAI

Additional Context

Environment

  • OpenViking: v0.4.19 (official image ghcr.io/volcengine/openviking:latest + a llama-cpp-python layer for local embedding)
  • Host: macOS 26.6.2, Apple M4, arm64, Docker via OrbStack 2.2.3
  • embedding: local bge-small-zh-v1.5 (dim 512), max_concurrent: 4
  • vlm: OpenAI-compatible, self-hosted, max_concurrent: 4, timeout: 300
  • rerank: OpenAI-compatible (llama.cpp bge-reranker-v2-m3)
  • storage: agfs.backend: local, vectordb.backend: local, queuefs.backend: sqlite, recover_stale_sec: 0

leo8103lee avatar Sep 11 '26 01:09 leo8103lee

Thanks for the report. I tested this on the official v0.4.19 tag, which matches the current ghcr.io/volcengine/openviking:latest image revision (f3afef116), using the reported config shape.

I could not reproduce the infinite retry/deadlock.

Results:

  • The MRE as written uses to=viking://resources/demo/v1/subdir.
  • The first upload creates .../subdir/doc-1.md as isDir:false and completes successfully.
  • Repeating the same request 4 times does not occupy 4 slots; the later requests return 409 CONFLICT due to the same tree lock.
  • Four concurrent uploads to four different target dirs all completed with Semantic.requeue_count=0.
  • Logs contained no AGFSNotADirectoryError or Transient API error ... re-enqueueing.

I also tested to=.../doc.md. Since to is treated as a directory by default, it creates .../doc.md/doc.md, which explains the duplicated segment symptom. That case also completed successfully.

So the posted MRE does not reproduce the reported deadlock on official v0.4.19/latest. If the production logs are accurate, I would first verify the exact running image/layer and whether stale semantic queue messages from an older build are involved.

sponge225 avatar Sep 11 '26 03:09 sponge225

Reproduced. Three preconditions, all required:

  1. the target path already exists as a file
  2. the queue is idle when the request is submitted
  3. you look at the server log ~90s later — add_resource returns 200
step 1   to=DIR                -> 200, creates doc.md  (isDir=false)
         wait for queue idle
step 2   to=DIR/doc.md         -> 200 ok      <-- client sees success
         ~90s later, server log:

AGFSNotADirectoryError: not a directory: /ACCT/resources/DIR/doc.md
semantic_processor - WARNING - Transient API error ... re-enqueueing
semantic_processor - WARNING - Circuit breaker is open, re-enqueueing semantic message

Your test passed to=.../doc.md while doc.md did not exist, so it correctly created doc.md/doc.md. Once that leaf exists as a file, handing the same path back as to makes the async semantic stage call ls() on a file.

Why my earlier attempts missed it: with any work in flight, the per-parent tree lock answers 409 before the request reaches the semantic stage. The queue has to be idle.

Repro script: https://gist.github.com/leo8103lee/ff63fb53065f819599aa71cbf25ba6dc

export OV_URL=http://127.0.0.1:1933
export OV_KEY=YOUR_USER_API_KEY
python3 repro_agfs_notadirectory.py

Stdlib only. It waits for an idle queue before step 2 — that wait is what makes it reproducible.

Two observations from the repro run:

  • add_resource returns 200. The failure is entirely async. A client batch-uploading gets no signal that anything went wrong.

  • The circuit breaker fires but does not terminate. The log alternates between Transient API error ... re-enqueueing and Circuit breaker is open, re-enqueueing semantic message. It throttles the retry rate; it never drops the message. One test document I created 40 minutes earlier accumulated 94 errors and held an AddResource slot the whole time — it stopped only when I called /tasks/{id}/cancel manually. Same mechanism behind the 1622 retries in the original report.

So: the deterministic error is real and reproducible. The part worth fixing is that a permanent failure is classified as transient and re-enqueued indefinitely, and that the breaker's open state still re-enqueues instead of dead-lettering.

Also confirming the corrections from my previous comment — the 409s are the per-parent tree lock (by design), and the duplicated path segment is expected to-as-directory behaviour, not a defect.

leo8103lee avatar Sep 11 '26 05:09 leo8103lee

Follow-up from production. I found what keeps a subtree stuck permanently, and it sits one step upstream of the retry loop in the original report.

The blocking mechanism

openviking/service/resource_service.py (v0.4.19), lines 899 and 1310:

resource_lock = await self._viking_fs._async_agfs.pathlock_acquire_tree(
    dst_path,
    timeout_secs=0.0,
)

timeout_secs=0.0 means a single non-blocking attempt. If any .path.ovlock file exists anywhere in the target subtree, add_resource returns 409 immediately and never retries.

The lease expiry in the token is not consulted. In my case three lock files under resources/AgoraRtcKit/4.6.2/symbols/ had expiry timestamps 61 minutes in the past, with mtimes that had not been refreshed since, and they still blocked every add_resource into that parent.

Why it is hard to find

  1. fs/stat reports isLocked for the path itself only, not for descendants. Every ancestor of the lock reported isLocked: false while the tree lock kept failing.

  2. The error text points the wrong way:

    LockAcquisitionError: lock acquire timed out after 25ms
    

    That reads like contention or slow storage. With timeout_secs=0.0 there is no wait — 25ms is just how long the single attempt took. Nothing in the message names the lock that caused the conflict.

How it produces the original bug

  1. Stale lock in the subtree blocks add_resource into the parent.
  2. The leaf is left as a bare file: no directory wrapper, no .abstract.md.
  3. The queued semantic message retries against that path and calls ls() on a file.
  4. AGFSNotADirectoryError, classified transient, re-enqueued forever.

So the infinite retry is the visible end of the chain, but the entry point is a stale lock file plus a non-blocking acquire that treats an expired lease as held.

Numbers from my instance

36 documents in one directory sat file-shaped with no L0 abstract. Over 12 hours the log carried roughly 1000 AGFSNotADirectoryError and about 430 Circuit breaker is open per hour, continuously.

Recovery: delete the stale .path.ovlock files, then re-ingest each document with to set to the resource's own full path rather than the parent directory. Scoping the tree lock to a single node avoids stale locks on sibling nodes. All 36 rebuilt correctly, zero content lost, and both error counts have been 0 since.

Suggestions

  • Treat an expired lease as free. Reclaim or ignore it instead of failing the acquire.
  • Make the acquire timeout configurable rather than a hardcoded 0.0.
  • Name the conflicting lock path in LockAcquisitionError, and say the wait was zero rather than reporting elapsed time as a timeout.
  • Let fs/stat optionally report descendant locks, so this is diagnosable without shell access to the data volume.

Separately, this does not change the point from my previous comment: a permanent AGFSNotADirectoryError is still classified as transient, and the circuit breaker re-enqueues instead of dead-lettering. Fixing the lock handling removes one common way of entering the loop, not the loop itself.

leo8103lee avatar Sep 11 '26 07:09 leo8103lee

The stale-lock entry point I described above is out of scope for #4934 and #4936, so I split it into #4938 to keep it tracked once this issue closes.

Short version: those two PRs fix what happens when a semantic message hits a file target. #4938 is about a target that is a perfectly normal directory, blocked before enqueue by an expired .path.ovlock on a sibling or descendant node. After both PRs land it stops being an infinite retry loop and becomes a silent permanent 409 instead.

Both PRs look right to me for the part they cover, and the circuit-breaker carve-out in #4934 addresses something I had not considered — classifying the error as permanent without it would open the shared API breaker on every malformed file.

leo8103lee avatar Sep 11 '26 08:09 leo8103lee

I'd classify AGFSNotADirectoryError as permanent and release the AddResource slot in a finally block; otherwise one deterministic file/directory mismatch can starve the whole queue. A regression test for a sub-threshold file should verify it isn't retried.

Alex668866 avatar Sep 15 '26 12:09 Alex668866

@Alex668866 The starvation you describe is real — I measured it: one test document held an AddResource slot for ~40 minutes while accumulating 94 errors, and only stopped when I called /tasks/{id}/cancel by hand. But the finally you are asking for is already there, and it cannot fire in this failure mode.

openviking/storage/queuefs/add_resource_processor.py, the exception path already marks the task failed and the finally already releases the lock:

except Exception as exc:
    await self._record_watch_execution(msg, "failed", str(exc) or type(exc).__name__)
    await tracker.fail(msg.task_id, str(exc), ...)
    terminal = True
    self.report_error(str(exc), data)
    return None
finally:
    request_wait_tracker.cleanup(telemetry_id)
    unregister_telemetry(telemetry_id)
    with suppress(Exception):
        if resource_lock is not None:
            await self._viking_fs._async_agfs.pathlock_release(resource_lock)

The reason neither runs is one line earlier in the same try, at add_resource_processor.py:267:

await tracker.wait_for_descendants(msg.task_id, metadata.work_id)

AddResource waits for its descendant work, and the semantic message is a descendant. openviking/service/task_tracker.py:975, unchanged on current main:

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

No timeout, no cancellation check, no iteration bound. So:

semantic message re-enqueues forever
  -> has_work() never goes false
  -> the while loop never exits
  -> the coroutine never leaves the try block
  -> finally never executes, tracker.fail is never reached

A finally only runs on the way out, and this task never gets out. That is why the slot is held rather than released, and why the task sits in running instead of reaching a terminal state.

So the fix has to be at one of two places, not in the exception handling:

  1. Terminate the semantic message — which is what #4934 does, by classifying AGFSNotADirectoryError as permanent while carving it out of CircuitBreaker.record_failure so one malformed file does not open the shared API breaker. Once the descendant reaches a terminal state, has_work() clears and everything downstream unwinds normally.

  2. Bound wait_for_descendants — an unbounded busy-wait means any descendant that fails to terminate pins its parent task forever, not just this error. A deadline, or a cancellation check, would contain the blast radius of the next bug of this shape. The 50ms poll also spins at 20Hz for the entire duration, which in my case was 40 minutes.

On your regression test: agreed, and I would assert two things rather than one. That a sub-threshold file target is not retried, and that the parent AddResource task reaches a terminal state. Testing only the first leaves wait_for_descendants unbounded, so the next descendant that hangs for an unrelated reason reproduces the same symptom with a different cause.

Environment for the measurements above: v0.4.19, Python 3.13, linux/arm64 container on macOS.

leo8103lee avatar Sep 15 '26 13:09 leo8103lee

You're right—the slot is released only after the unbounded descendant wait returns, so finally can't help when that wait never ends. Making AGFSNotADirectoryError permanent should fix this case; a bounded wait and a test for parent termination would cover the wider deadlock risk.

Alex668866 avatar Sep 15 '26 14:09 Alex668866