OpenViking icon indicating copy to clipboard operation
OpenViking copied to clipboard

[Bug]: cancelled add_resource task keeps materializing; stuck task holds PathLock indefinitely, making the resource undeletable

Open FudanSE-Nick opened this issue 2 months ago • 4 comments

Issue Origin

Observed or reproduced in a real environment

Bug Description

Issue Origin: Observed or reproduced in a real environment (a private production deployment, 2026-09-17), then confirmed by code reading against main.

Two related defects in the add_resource task lifecycle (observed with a git repository import of ~540 files):

  1. A queued or running add_resource task holds its PathLock lease for its entire lifetime, and there is no recovery for stuck tasks — so forget on the resource fails with ResourceBusyError: Resource is being processed indefinitely, with no way to break the lock (the Web UI has no delete entry either).
  2. Cancellation is cooperative, but the ingestion/materialization path has zero cancellation checkpoints — a cancelled task keeps writing the resource tree. If the user deletes the subtree while the cancelled task is still draining, the task re-materializes the deleted tree.

Steps to Reproduce

Bug 1 (stuck task holds PathLock forever):

  1. add_resource a git repo (enqueue creates the task and a PathLock handoff).
  2. Let the task get stuck in running (worker restart / queue hiccup / slow clone). GET /api/v1/tasks shows the task in running indefinitely.
  3. forget the resource -> ResourceBusyError: Resource is being processed: <uri>.
  4. No UI entry exists to delete a resource. Only escape hatch is REST POST /api/v1/tasks/{id}/cancel — which leads to Bug 2.

Bug 2 (cancelled task re-materializes the deleted tree):

  1. Start a large git add_resource import (task A, target URI U).
  2. While A is running, cancel it via REST: task status flips to cancelled.
  3. Delete the subtree at U (forget succeeds once the lock is released).
  4. After a while, list shows the full tree at U again — task A's materialization continued past cancellation and re-created everything.

Observed exactly this: task 39eb4dab (cancelled) re-created the subtree viking://resources/<namespace>/<repo>/... after we had deleted it.

Expected Behavior

  • A queued/running add_resource task must not hold the resource PathLock in a way that permanently blocks forget: either adopted handoff leases require a live processor heartbeat (orphaned leases become pre-emptible), or an admin/operator path exists to force-release the lock and delete the resource.
  • Cancellation should actually stop materialization: cooperative checkpoints in the ingestion loop (per file / per batch in materialize_source, plus stage boundaries in execute_add_resource_job), stop writing on cancellation, clean up partial writes, and settle the task as cancelled without materializing the remainder.

Actual Behavior

  • forget fails with ResourceBusyError: Resource is being processed as long as a queued/stuck task holds the continuously-refreshed handoff lease; no admin path or UI entry can break it.
  • After REST cancel (status shows cancelled), the running task keeps writing: the deleted resource tree is fully re-materialized.

Minimal Reproducible Example

Code path (current `main`):

- `openviking/storage/viking_fs/_ops.py:297-305` — `rm`/`forget` must acquire the pathlock (`pathlock_acquire_tree` / `pathlock_acquire_exact`); `LockAcquisitionError` -> `ResourceBusyError("Resource is being processed")`.
- `openviking/storage/queuefs/add_resource_processor.py:185` — the queue consumer adopts the enqueue-time lock handoff.
- `crates/ragfs/src/lock/manager.rs:248` — parked/handoff leases keep refreshing in the lease registry, so the lock never expires while the task message lives (the 30s default `lock_expire_secs` does not apply to a continuously refreshed lease).
- `openviking/service/task_tracker.py:308-312` — `_is_expired` only evicts terminal tasks (`COMPLETED` / `CANCELLED` / `FAILED`); `RUNNING` / `PENDING` are never recovered: no watchdog, no orphaned-lease cleanup, and `restore_tasks` re-reserves them after restart.
- `openviking/service/task_tracker.py:660+` — `cancel()` only flips the status (`CANCELLING` -> persist -> `CANCELLED`), documented as cooperative.
- The only mid-flight `is_cancellation_requested` checkpoints in the codebase are for skill processing (`openviking/service/resource_service.py:2543`) and external tasks (`openviking/service/external_task_service.py:343`).
- The add_resource pipeline checks task status once at the start of `_process` (`openviking/storage/queuefs/add_resource_processor.py:157-176`, covering only "cancelled while queued"), then runs `execute_add_resource_job` -> SOURCE phase -> `materialize_source` (`openviking/resource/staged_source.py:111`) which contains no cancellation checks (grep `cancel` -> 0 hits).
- Semantic/embedding phases only release *queued* locks on cancel (`openviking/storage/queuefs/semantic_processor.py:785-799`).

Error Logs

ResourceBusyError: Resource is being processed: viking://resources/<namespace>/<repo>

(intermediate task `39eb4dab-8de6-4bdd-9a82-9a8244b8bf6a`: status `running` for hours; after REST cancel returned `cancelled`, the deleted subtree `viking://resources/<namespace>/<repo>` reappeared with full content)

OpenViking Version

A private production deployment; source confirmed against volcengine/OpenViking main (2026-09)

Python Version

n/a (deployment-managed)

Operating System

Linux

Model Backend

No response

Additional Context

Happy to send PRs once the design is confirmed. Proposed directions, both small and independent per the contribution guidelines:

  1. Bug 1: lease heartbeat requirement for adopted handoff leases + pre-emption of orphaned leases; and/or a force-release admin API. (~50-100 LOC)
  2. Bug 2: cancellation checkpoints in materialize_source / stage boundaries with partial-write cleanup. (~50-100 LOC)

FudanSE-Nick avatar Sep 22 '26 07:09 FudanSE-Nick

Thanks for the report. I tried to reproduce this on current main(@172c10507).

Confirmed:

  • While a Git add_resource(wait=false) task is running, deleting the target returns 409 Resource is being processed.
  • This matches the PathLock behavior described in the issue.

I then retried with trusted auth and a non-ROOT user, so POST /api/v1/tasks/{id}/cancel could be called.

I tested cancel at:

  • pending/queued
  • running/fetching
  • running/target_resolve

In my local runs, cancel returned 200, the task became cancelled, delete succeeded after the lock was released, and repeated ls viking://resources/ did not show the deleted tree being recreated.

So I can reproduce the busy-lock behavior, but not the “cancelled task re-materializes the deleted tree” behavior yet.

Could you share what stage task 39eb4dab-8de6-4bdd-9a82-9a8244b8bf6a was in when it was cancelled?

Especially, was it cancelled during:

  • fetching
  • target_resolve
  • another SOURCE-stage value
  • or processing_queue

This matters because the issue seems to point at the SOURCE path (execute_add_resource_job / materialize_source). If the task was already in processing_queue, the write-back may be coming from a different path.

Logs around AddResourceStarted, AddResourceCancelled, ContentTreeCommit, and PathLock events would also help.

sponge225 avatar Sep 22 '26 09:09 sponge225

Taking this one, scoped to Bug 2 (cancelled task keeps materializing).

Root cause: the add_resource pipeline checks cancellation only once at the start of _process (openviking/storage/queuefs/add_resource_processor.py:157-176, covering only "cancelled while queued"); the ingestion/materialization loop (materialize_source, execute_add_resource_job) has zero checkpoints, so after REST cancel the task keeps writing and can re-create a deleted subtree.

Plan: add cooperative is_cancellation_requested checkpoints per file/batch in the materialization loop and at stage boundaries in execute_add_resource_job, stop writing on cancellation, and settle the task as cancelled without materializing the remainder — exactly the boundary proposed in the issue. Bug 1 (orphaned PathLock lease recovery) is a lease-registry design change (Rust lock/manager.rs) and overlaps my #6143 recovery work, so I'm leaving that part to maintainers unless told otherwise.

Tests will be added red-first for mid-materialization cancellation. (Assisted by AI coding agent.)

akushonkamen avatar Oct 16 '26 07:10 akushonkamen

Fix committed locally on branch fix/5283-add-resource-cancellation (commit ca40660, to be opened as a PR by our submission pipeline).

What it does, scoped to Bug 2 exactly as proposed in the issue:

  • TaskTracker.is_cancelled() — new cooperative checkpoint (openviking/service/task_tracker.py:414): answers from the process-local cache when possible, otherwise refreshes the record from the durable store once. Workers run on separate threads/processes from the cancel API, so cache-only checks can never observe a cross-process cancel.
  • AddResourceProcessor._set_stage() aborts at every stage boundary (fetching/parsing → target_resolve → processing_queue) before the next stage writes more of the tree (add_resource_processor.py:225).
  • materialize_source() takes an abort hook checked every 32 entries, and execute_add_resource_job aborts before materialization (staged_source.py:118, resource_service.py:777). Aborts raise asyncio.CancelledError, which reuses the existing cancellation unwinding: lock release, staged-source cleanup, cancelled watch record, and the middleware settling ProcessResult.cancelled.

Regression tests are red before / green after (tests/service/test_add_resource_cancellation.py, 4 tests: cross-tracker store observation, mid-materialization stop with ingestion never started, stage-boundary settle with lock release + watch record). Related subset matches the pre-change baseline exactly — no new failures. Bug 1 (orphaned PathLock lease) remains open for maintainers as noted in my claim.

akushonkamen avatar Oct 16 '26 08:10 akushonkamen

PR opened: #6170 (scoped to Bug 2 as claimed; Bug 1 left to maintainers). Regression tests red-first → green; related-subset failures identical to the pristine-base baseline.

akushonkamen avatar Oct 16 '26 08:10 akushonkamen