Skip to content

fix(quota): arbitrate the reserved file-slot release instead of leaking it - #700

Open
Ahmath-Gadji wants to merge 1 commit into
fix/660-durable-job-statefrom
fix/664-arbitrate-quota-release
Open

fix(quota): arbitrate the reserved file-slot release instead of leaking it#700
Ahmath-Gadji wants to merge 1 commit into
fix/660-durable-job-statefrom
fix/664-arbitrate-quota-release

Conversation

@Ahmath-Gadji

@Ahmath-Gadji Ahmath-Gadji commented Jul 20, 2026

Copy link
Copy Markdown
Collaborator

Closes the cancel-before-start quota-slot leak that #677 documents as a known gap.

Stacked on #677 (base = fix/660-durable-job-state). It builds directly on the reserve/release machinery introduced there, so it cannot land first. Review #677 before this. Once #677 merges, this retargets to develop cleanly.

The leak

After dispatch the worker owns the uploader's reserved file slot and hands it back in IndexerWorker.process_file's finally. When ray.cancel retires a task before that body runs, the finally never executes and nothing else gives the slot back. The CANCELLED row written by cancel_task is terminal, so the loss is indistinguishable from a clean cancel — the uploader's quota is permanently one narrower, silently.

cancel_task could not simply release. A task cancelled mid-flight does run its finally, so releasing in both places would drive file_count below reality and hand the user free quota. The two cases were distinguishable only by how far the worker happened to get — which is exactly the kind of thing the caller cannot observe.

The fix

TaskStateManager is a single-threaded Ray actor that already arbitrates precisely this shape of race (set_cancelled_if_active, set_failed_if_not_cancelled). A one-shot claim_quota_release compare-and-set is the idiomatic primitive here:

  • process_file's finally asks before releasing.
  • cancel_task asks after claiming the cancellation.
  • The indexer_pool setup-failure release asks too — a cancellation during setup reaches both it and cancel_task.

Exactly one caller is told to release; the outcome no longer depends on worker progress. The dispatcher records quota_reserved on the task at admission so the actor knows whether a slot is outstanding at all (put_file reuses an existing row and reserves nothing).

This also closes the dispatch-partial-success double-release that #677 accepts as a deliberate trade-off: the worker and the request teardown can no longer both consume the same reservation.

Failure behaviour

Biased the same way the rest of the reserve/release design is — an unreachable arbiter releases anyway. An undercount is recoverable and self-heals under the #676 recount; a leak is permanent and silent. _release_cancelled_slot is best-effort throughout, because a cancellation the user already asked for and already saw must not fail on quota bookkeeping.

The one case that stays open is genuinely un-arbitrable and belongs to #676: outright process death between reserve and dispatch, and an unreachable Postgres inside the release itself.

Why now rather than in #676

#685 shipped a cancel-all UI that fires one cancelTask per selected task (Promise.allSettled(activeTaskIds.map(...))). The leak was previously one slot per manual cancel; it is now N slots from a single click, which moves it out of "acceptable known gap" territory.

Verification

  • ruff check / ruff format --check clean; scripts/check_layer_imports.pylayer import guard: OK.
  • Unit: 1839 passed, 0 failed (1831 on the fix: atomic file-quota reserve + durable indexation job state #677 base, +8 here).
  • Integration against real Postgres: 119 passed, 1 failed — unchanged from the base; the failure is the pre-existing test_create_is_idempotent_per_name, fixed separately in test(repos): assert create_partition rejects duplicates, as it does #691.
  • New tests cover both directions of the race and the degraded paths: the claim is grantable exactly once; a task that reserved nothing has nothing to claim; an unknown task claims rather than leaks; the cancel releases when the worker never started; the cancel declines when the worker already owns it; a failing release does not fail the cancellation; and an unreachable state actor still releases.

Summary by CodeRabbit

  • Bug Fixes
    • Improved reserved file-slot handling for indexing tasks canceled before execution by using single-ownership arbitration for quota release.
    • Prevented duplicate quota releases while ensuring the correct path returns reserved slots when a worker loses or fails during release.
    • Added best-effort safeguards so release failures during cancellation don’t block task completion.
  • Tests
    • Expanded unit coverage for quota-release claiming, cancellation scenarios, and quota state arbitration edge cases.
  • Documentation
    • Clarified quota reservation/release ownership behavior after dispatch and handling of unreachable arbitration.

@coderabbitai

coderabbitai Bot commented Jul 20, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8b7b7618-abd2-43a3-8249-cc82e042083e

📥 Commits

Reviewing files that changed from the base of the PR and between a42fbb1 and 690f0ae.

📒 Files selected for processing (10)
  • CLAUDE.md
  • openrag/di/container.py
  • openrag/services/workers/dispatcher.py
  • openrag/services/workers/indexer_actor.py
  • openrag/services/workers/indexer_pool.py
  • openrag/services/workers/task_state.py
  • tests/unit/services/workers/test_dispatcher.py
  • tests/unit/services/workers/test_indexer_pool.py
  • tests/unit/services/workers/test_indexer_worker_quota_release.py
  • tests/unit/services/workers/test_task_state.py
🚧 Files skipped from review as they are similar to previous changes (7)
  • openrag/services/workers/indexer_actor.py
  • tests/unit/services/workers/test_task_state.py
  • openrag/di/container.py
  • openrag/services/workers/task_state.py
  • openrag/services/workers/indexer_pool.py
  • CLAUDE.md
  • openrag/services/workers/dispatcher.py

📝 Walkthrough

Walkthrough

The change adds persistent quota reservation and release-claim state, coordinates worker and cancellation cleanup through one-shot arbitration, wires user_repo into the indexing dispatcher, and adds coverage for release ownership and failure paths.

Changes

Quota release arbitration

Layer / File(s) Summary
Task state claim contract
openrag/services/workers/task_state.py, tests/unit/services/workers/test_task_state.py
Task records persist quota reservation and claim status; claim_quota_release provides single-claim semantics with tests for reserved, unreserved, and unknown tasks.
Worker release arbitration
openrag/services/workers/indexer_actor.py, openrag/services/workers/indexer_pool.py, tests/unit/services/workers/test_indexer_worker_quota_release.py, tests/unit/services/workers/test_indexer_pool.py
Worker cleanup and setup-error paths claim release ownership before returning quota, while claim failures fall back to release and arbitration outcomes are tested.
Cancellation release wiring
openrag/services/workers/dispatcher.py, openrag/di/container.py, tests/unit/services/workers/test_dispatcher.py
Dispatcher cancellation claims reserved slots and releases them through user_repo; queued task metadata records reservation state and cancellation cases are covered.
Release ownership documentation
CLAUDE.md
The File Quota System section documents post-dispatch release arbitration and double-release prevention.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant IndexerWorker
  participant TaskStateManager
  participant WorkerDispatcher
  participant UserRepository

  IndexerWorker->>TaskStateManager: claim_quota_release(task_id)
  TaskStateManager-->>IndexerWorker: claim result
  WorkerDispatcher->>TaskStateManager: claim_quota_release(task_id) after cancellation
  TaskStateManager-->>WorkerDispatcher: claim result
  WorkerDispatcher->>UserRepository: release_file_slot(user_id) when claimed
Loading

Possibly related PRs

  • linagora/openrag#685: Both changes update the worker cancellation path and shared task-state cancellation flow.

Suggested labels: fix

Suggested reviewers: enjoybacon7

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 45.16% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: one-shot arbitration for reserved file-slot release to prevent leaks.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/664-arbitrate-quota-release
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch fix/664-arbitrate-quota-release

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
openrag/services/workers/dispatcher.py (1)

368-445: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Cancellation path leaks the slot instead of releasing it when the arbiter is unreachable.

_release_cancelled_slot wraps the claim_quota_release RPC in a bare try/except that only logs on failure — it never falls back to releasing. This contradicts both the stated PR intent ("favor recoverable undercounts over permanent leaks") and the parallel worker-side helper claim_quota_release in indexer_actor.py, which explicitly treats an unreachable/erroring actor as "release anyway." As written, if the state actor is unreachable exactly during a cancel-before-start (the scenario #664 targets), the slot leaks silently until manual reconciliation — the opposite of the documented tradeoff. This path also lacks test coverage for the RPC-failure case (existing tests only cover release_file_slot raising, and claim_quota_release returning False).

🛡️ Proposed fix: fall back to releasing on arbitration failure
     async def _release_cancelled_slot(self, task_id: str) -> None:
         if self._user_repo is None:
             return
         try:
             details = await self._call(
                 self._tsm.get_details.remote(task_id),
                 task_description=f"get_details({task_id})",
             )
             user_id = (details or {}).get("user_id")
             if user_id is None:
                 return
-            claimed = await self._call(
-                self._tsm.claim_quota_release.remote(task_id),
-                task_description=f"claim_quota_release({task_id})",
-            )
+            try:
+                claimed = await self._call(
+                    self._tsm.claim_quota_release.remote(task_id),
+                    task_description=f"claim_quota_release({task_id})",
+                )
+            except Exception:  # noqa: BLE001 - prefer a recoverable undercount to a leak
+                claimed = True
             if not claimed:
                 return
             await self._user_repo.release_file_slot(user_id)
         except Exception as exc:  # noqa: BLE001 - the cancellation itself already succeeded
             ...

Want me to add a regression test (claim_quota_release.remote raising during cancel_task) alongside this fix, or open a follow-up issue?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openrag/services/workers/dispatcher.py` around lines 368 - 445, Update
_release_cancelled_slot so failures reaching get_details or claim_quota_release,
including RPC exceptions, fall back to releasing the user’s file slot rather
than returning without release; preserve the existing no-op when the user
repository or user_id is unavailable, and keep claim_quota_release returning
false as the non-owner path. Add regression coverage through cancel_task for a
claim_quota_release RPC failure, verifying release_file_slot is still attempted.

Source: Coding guidelines

🧹 Nitpick comments (1)
openrag/services/workers/indexer_actor.py (1)

348-367: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider a timeout on the arbitration RPC.

claim_quota_release awaits tsm.claim_quota_release.remote(task_id) directly with no timeout. This call runs unconditionally in IndexerWorker.process_file's finally (line 170) and in IndexerWorkerActor.process_file's setup-failure handler (indexer_pool.py, line 244) — both cleanup paths. If the TaskStateManager actor is merely slow (not "unreachable" in the sense that raises), this await can hang indefinitely, blocking the worker's cleanup and tying up its concurrency slot. dispatcher.py already wraps equivalent actor calls with call_ray_actor_with_timeout; this helper doesn't.

♻️ Proposed fix: wrap the RPC with a timeout
 async def claim_quota_release(tsm: Any, task_id: str) -> bool:
     try:
-        return bool(await tsm.claim_quota_release.remote(task_id))
+        from services.workers.ray_utils import call_ray_actor_with_timeout
+
+        return bool(
+            await call_ray_actor_with_timeout(
+                future=tsm.claim_quota_release.remote(task_id),
+                timeout=DEFAULT_TIMEOUT,
+                task_description=f"claim_quota_release({task_id})",
+            )
+        )
     except Exception:  # noqa: BLE001 - cleanup must never mask the indexing error

Please confirm whether call_ray_actor_with_timeout is safe to import here without introducing a circular import between indexer_actor.py and ray_utils.py.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openrag/services/workers/indexer_actor.py` around lines 348 - 367, Update
claim_quota_release to wrap the tsm.claim_quota_release.remote(task_id)
arbitration call with call_ray_actor_with_timeout, using the existing
timeout/error-handling conventions from dispatcher.py. Verify the import from
ray_utils.py does not create a circular dependency; if it does, use an
equivalent local timeout mechanism. Preserve the current fallback that logs and
returns True for timeout or other arbitration failures.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@openrag/services/workers/dispatcher.py`:
- Around line 368-445: Update _release_cancelled_slot so failures reaching
get_details or claim_quota_release, including RPC exceptions, fall back to
releasing the user’s file slot rather than returning without release; preserve
the existing no-op when the user repository or user_id is unavailable, and keep
claim_quota_release returning false as the non-owner path. Add regression
coverage through cancel_task for a claim_quota_release RPC failure, verifying
release_file_slot is still attempted.

---

Nitpick comments:
In `@openrag/services/workers/indexer_actor.py`:
- Around line 348-367: Update claim_quota_release to wrap the
tsm.claim_quota_release.remote(task_id) arbitration call with
call_ray_actor_with_timeout, using the existing timeout/error-handling
conventions from dispatcher.py. Verify the import from ray_utils.py does not
create a circular dependency; if it does, use an equivalent local timeout
mechanism. Preserve the current fallback that logs and returns True for timeout
or other arbitration failures.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 40ae186d-7268-4877-a2a6-7b234593d82d

📥 Commits

Reviewing files that changed from the base of the PR and between 0b26864 and a42fbb1.

📒 Files selected for processing (9)
  • CLAUDE.md
  • openrag/di/container.py
  • openrag/services/workers/dispatcher.py
  • openrag/services/workers/indexer_actor.py
  • openrag/services/workers/indexer_pool.py
  • openrag/services/workers/task_state.py
  • tests/unit/services/workers/test_dispatcher.py
  • tests/unit/services/workers/test_indexer_worker_quota_release.py
  • tests/unit/services/workers/test_task_state.py

@hedhoud hedhoud left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The arbitration direction makes sense, but two correctness blockers and one degraded-path leak remain. I’ve left the details inline.

user_id = (details or {}).get("user_id")
if user_id is None:
return
claimed = await self._call(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This claim does not distinguish a task that never started from one that has already created its catalog row. If cancellation lands after add_file_to_partition succeeds but before COMPLETED is reported, the dispatcher can win this claim and decrement file_count even though the file remains stored. Could the worker take ownership when processing starts, or otherwise mark the reservation consumed atomically, so only a true cancel-before-start releases here? This also needs a regression test for that timing window.

user_id=user.get("id") if user else None,
# Tells the actor a slot is outstanding for this task, so
# ``claim_quota_release`` can arbitrate who gives it back.
quota_reserved=quota_reserved,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TaskStateManager is detached and reused under the same actor name. During a rolling upgrade, the existing actor will not accept the new quota_reserved argument and also will not expose claim_quota_release, so new indexing requests can fail until Ray is manually restarted. Could we version the actor name or add an explicit compatibility/recreation guard before changing this contract?

if not claimed:
return
await self._user_repo.release_file_slot(user_id)
except Exception as exc: # noqa: BLE001 - the cancellation itself already succeeded

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If get_details succeeds but this arbitration RPC raises or times out, the outer handler only logs and leaves the slot reserved. That reintroduces the permanent leak this PR is meant to close and differs from the worker-side fallback. Could we release with the already-resolved user_id when the claim cannot be made, and cover that path with a regression test?

@Ahmath-Gadji
Ahmath-Gadji force-pushed the fix/660-durable-job-state branch from a0286dd to 4402d7e Compare July 20, 2026 13:16
Cancelling a task that had not started yet leaked its reserved file slot
outright. After dispatch the worker owns the slot and only releases it in
`IndexerWorker.process_file`'s `finally`; when `ray.cancel` retires the task
before that body runs, the `finally` never executes and nothing else gives the
slot back. The CANCELLED row is terminal, so the loss is indistinguishable from
a clean cancel, and the uploader's quota is permanently one narrower.

`cancel_task` could not simply release, because a task cancelled *mid-flight*
does run its `finally` — releasing in both places would drive `file_count`
below reality and hand out free quota. The two outcomes were only
distinguishable by how far the worker happened to get.

`TaskStateManager` settles it. It is a single-threaded Ray actor and already
arbitrates this way (`set_cancelled_if_active`, `set_failed_if_not_cancelled`),
so a one-shot `claim_quota_release` compare-and-set is the idiomatic primitive
here: the worker and the canceller both ask, exactly one is told to release.
The dispatcher records `quota_reserved` on the task at admission so the actor
knows whether a slot is outstanding at all — `put_file` reuses an existing row
and reserves nothing.

The setup-failure release in `indexer_pool` goes through the same claim: a
cancellation *during* setup reaches both it and `cancel_task`.

This also closes the dispatch-partial-success double-release noted in the PR
description — the worker and the request teardown can no longer both consume
the same reservation.

Failure handling stays biased the way the rest of the branch is: an unreachable
arbiter releases anyway. An undercount is recoverable and self-heals under the
is best-effort throughout, because a cancellation the user already asked for
and already saw must not fail on bookkeeping.

Worth doing now rather than deferring to #676: #685 shipped a cancel-all UI
that fires one cancel per selected task, so the leak had become reachable at
scale from a single click.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fix Fix issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants