Skip to content

Add task API - #14393

Merged
wangq8 merged 3 commits into
infiniflow:mainfrom
wangq8:qi/task-api
Apr 27, 2026
Merged

wangq8 merged 3 commits into
infiniflow:mainfrom
wangq8:qi/task-api

Conversation

@wangq8

@wangq8 wangq8 commented Apr 27, 2026 •

Copy link
Copy Markdown
Collaborator

What problem does this PR solve?

Add task API

Type of change

  • Refactor

@wangq8 wangq8 added the ci Continue Integration label Apr 27, 2026
@coderabbitai

coderabbitai Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9419f3c7-e865-4909-a3f4-3096c99b49d7

📥 Commits

Reviewing files that changed from the base of the PR and between b7520b1 and 918be72.

📒 Files selected for processing (1)
  • api/apps/restful_apis/task_api.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/apps/restful_apis/task_api.py

📝 Walkthrough

Walkthrough

Removes the canvas-specific cancel handler and introduces task cancellation endpoints: POST /api/v1/tasks/<task_id>/cancel and PATCH /api/v1/tasks/<task_id>. New flow sets a Redis cancellation flag, validates and updates task state, and attempts to sync document run state.

Changes

Cohort / File(s) Summary
Removed canvas endpoint
api/apps/canvas_app.py
Deletes legacy PUT /cancel/<task_id> route and its cancel(task_id) handler.
Task cancellation API
api/apps/restful_apis/task_api.py
Adds POST /tasks/<task_id>/cancel and PATCH /tasks/<task_id> endpoints with shared _cancel_task logic: validate existence and progress, set "<task_id>-cancel" in Redis, return connection errors for Redis failures, set task progress = -1 and append a timestamped message (conditional WHERE progress in [0,1)), and attempt to set associated document run state to CANCEL and progress = 0 (errors logged).
Frontend service methods
web/src/services/agent-service.ts
Changes cancelDataflow and cancelCanvas HTTP verb from PUT to POST.
Frontend API helpers
web/src/utils/api.ts
Repoints cancelCanvas and cancelDataflow URLs from ${webAPI}/canvas/cancel/:id to ${restAPIv1}/tasks/:id/cancel.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client (UI)
    participant API as Task API
    participant Redis as Redis
    participant DB as Database
    participant Doc as Document Service

    Client->>API: POST /api/v1/tasks/{id}/cancel
    API->>DB: GET task by id
    alt task not found
        DB-->>API: Not found
        API-->>Client: 404 (RetCode.NOT_FOUND)
    else task found & valid
        API->>Redis: SET "{id}-cancel" = "x"
        alt Redis error
            Redis-->>API: error
            API-->>Client: 502 (RetCode.CONNECTION_ERROR)
        else Redis OK
            API->>DB: UPDATE task (WHERE progress>=0 and <1) -> progress=-1, append timestamped message
            DB-->>API: OK / errors logged
            alt task has real doc_id
                API->>Doc: UPDATE run state -> CANCEL, set doc progress=0
                Doc-->>API: OK / errors logged
            end
            API-->>Client: 200 { data: true }
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰
I hopped from canvas to REST today,
Poked Redis gently — "please, stop, okay?"
DB scribbled notes, docs blinked to red,
Tasks take a break, then curl in bed.
The rabbit grinned and bounced away.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request description is largely incomplete, only restating the title without providing meaningful context, background, or explanation of what problem is being solved. Expand the description with details about why the task API was added, what problems it solves, and how it improves the codebase (e.g., consolidation of endpoints, better organization).
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Add task API' is vague and generic, lacking specificity about which task API was added or what the primary change entails beyond the broad term 'Add'. Use a more specific title that describes the concrete change, such as 'Migrate task cancellation from canvas_app to restful task API' or 'Refactor task cancellation endpoints to task API'.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@wangq8
wangq8 marked this pull request as ready for review April 27, 2026 06:19
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐖api The modified files are located under directory 'api/apps/sdk' labels Apr 27, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (2)
web/src/utils/api.ts (1)

199-218: Two keys mapping to the same URL builder.

cancelCanvas (L199) and cancelDataflow (L218) now produce identical URLs. That's intentional given the unified backend route, but consider keeping a single helper (e.g. cancelTask) and aliasing — or at minimum colocating the two definitions with a comment — so a future refactor doesn't drift them apart.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@web/src/utils/api.ts` around lines 199 - 218, The file defines two helpers
cancelCanvas and cancelDataflow that build the same URL; replace them with a
single canonical helper (e.g., cancelTask: (taskId: string) =>
`${restAPIv1}/tasks/${taskId}/cancel`) and then re-export or alias cancelCanvas
and cancelDataflow to that helper (or keep the original names pointing to the
same function) so callers can remain unchanged; update references to the unique
symbols cancelCanvas and cancelDataflow to use the new cancelTask helper and add
a short colocated comment explaining the intentional aliasing to prevent future
drift.
api/apps/restful_apis/task_api.py (1)

61-87: Mixed f-string + %s formatting in logging.exception calls.

logging.exception(f"Failed ... {task_id}: %s", str(e)) interpolates task_id eagerly via the f-string, then leaves a stray %s for the logger to fill with str(e) — and logging.exception already appends the traceback, so passing str(e) separately is redundant. Pick one style consistently:

-        logging.exception(f"Failed to set cancel flag for task {task_id}: %s", str(e))
+        logging.exception("Failed to set cancel flag for task %s", task_id)
...
-        logging.exception(f"Failed to update task {task_id} progress after cancellation, %s", str(e))
+        logging.exception("Failed to update task %s progress after cancellation", task_id)
...
-        logging.exception(f"Failed to update document run status for task {task_id}: %s", str(e))
+        logging.exception("Failed to update document run status for task %s", task_id)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/task_api.py` around lines 61 - 87, The
logging.exception calls mix f-strings and %-style placeholders (e.g.
logging.exception(f"...{task_id}: %s", str(e))) which is incorrect; replace
these with a single consistent message form—either use an f-string that includes
the exception (e.g. f"Failed to update task {task_id} progress after
cancellation: {e}") and call logging.exception(...) with just that string, or
pass a static format string with exc_info=True (or let logging.exception add the
traceback) but do not combine f-strings and "%s". Update the three occurrences
of logging.exception in this snippet (the one after the cancel flag, the
TaskService.model.update except block, and the DocumentService except block) to
use a single consistent style.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/task_api.py`:
- Around line 58-75: The current cancellation path can clobber a just-completed
task because it unconditionally writes progress=-1; change this to call the
existing TaskService.update_progress (or replicate its guarded WHERE +
DB.lock("update_progress") behavior) instead of directly updating
TaskService.model: use TaskService.update_progress(task_id, progress=-1,
progress_msg_append=cancel_msg) or if you must update here, perform the same
conditional WHERE that prevents transitions out of terminal states and acquire
the same DB.lock("update_progress") around the update so the write is serialized
and will not overwrite a finished task; keep REDIS_CONN.set for the cancel flag
but do not perform the unconditional TaskService.model.update.
- Around line 62-65: The return uses an unnecessary f-string; update the call to
get_json_result in task_api.py (the return using RetCode.CONNECTION_ERROR) to
remove the leading f on the message (i.e., use a plain string) and, if available
in the current scope (e.g., variable task_id), include the task identifier in
the message like "Failed to stop task {task_id}" so the message is informative;
ensure you reference get_json_result and RetCode.CONNECTION_ERROR when making
the change.
- Around line 33-89: Add INFO-level logs for the cancellation flow in
cancel_task: log an entry when cancellation is initiated (include task_id,
timestamp and user identity if available from the request context or current
user helper) before calling REDIS_CONN.set, and log a success message after the
cancel flag and DB updates complete (include task_id, doc_id if present, and
timestamp). Place the entry log at the start of cancel_task and the success log
right before returning get_json_result(data=True); reference the REDIS_CONN.set
call, TaskService.model.update usage, and the DocumentService.update_by_id call
so the log reflects both Redis and DB outcomes.
- Around line 92-105: The patch_task route currently calls the decorated
cancel_task handler directly which re-invokes decorators; extract the
cancellation logic into a plain async helper (e.g. _do_cancel_task(task_id))
that contains the core cancellation flow, update the decorated cancel_task(...)
endpoint to call and return await _do_cancel_task(task_id), and change
patch_task to call and return await _do_cancel_task(task_id) instead of invoking
cancel_task; keep decorators (like `@login_required`) only on the HTTP handlers
and ensure the helper is a simple async function without route/auth decorators.

---

Nitpick comments:
In `@api/apps/restful_apis/task_api.py`:
- Around line 61-87: The logging.exception calls mix f-strings and %-style
placeholders (e.g. logging.exception(f"...{task_id}: %s", str(e))) which is
incorrect; replace these with a single consistent message form—either use an
f-string that includes the exception (e.g. f"Failed to update task {task_id}
progress after cancellation: {e}") and call logging.exception(...) with just
that string, or pass a static format string with exc_info=True (or let
logging.exception add the traceback) but do not combine f-strings and "%s".
Update the three occurrences of logging.exception in this snippet (the one after
the cancel flag, the TaskService.model.update except block, and the
DocumentService except block) to use a single consistent style.

In `@web/src/utils/api.ts`:
- Around line 199-218: The file defines two helpers cancelCanvas and
cancelDataflow that build the same URL; replace them with a single canonical
helper (e.g., cancelTask: (taskId: string) =>
`${restAPIv1}/tasks/${taskId}/cancel`) and then re-export or alias cancelCanvas
and cancelDataflow to that helper (or keep the original names pointing to the
same function) so callers can remain unchanged; update references to the unique
symbols cancelCanvas and cancelDataflow to use the new cancelTask helper and add
a short colocated comment explaining the intentional aliasing to prevent future
drift.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 192fabd7-71d7-4818-8059-0361c639013b

📥 Commits

Reviewing files that changed from the base of the PR and between 0b46ab0 and fe525cb.

📒 Files selected for processing (4)
  • api/apps/canvas_app.py
  • api/apps/restful_apis/task_api.py
  • web/src/services/agent-service.ts
  • web/src/utils/api.ts
💤 Files with no reviewable changes (1)
  • api/apps/canvas_app.py

Comment on lines +33 to +89
async def cancel_task(task_id):
"""Cancel a running task.

Sets a Redis cancel flag, updates the task progress to -1 (cancelled),
and marks the associated document's run status as CANCEL if applicable.
"""
exists, task = TaskService.get_by_id(task_id)
if not exists:
return get_data_error_result(
code=RetCode.NOT_FOUND,
message=f"Task '{task_id}' not found.",
)

# A task is stoppable if it hasn't completed (progress < 1) and isn't already
# in a failed/cancelled state (progress >= 0). progress == -1 means the task
# previously failed or was cancelled.
if task.progress < 0:
return get_data_error_result(
message="Task is already in a cancelled or failed state.",
)
if task.progress >= 1:
return get_data_error_result(
message="Task has already completed and cannot be stopped.",
)

try:
REDIS_CONN.set(f"{task_id}-cancel", "x")
except Exception as e:
logging.exception(f"Failed to set cancel flag for task {task_id}: %s", str(e))
return get_json_result(
code=RetCode.CONNECTION_ERROR,
message=f"Failed to stop task",
)

# Append a cancellation message so the user can see it in progress_msg.
try:
cancel_msg = f"\n{datetime.now().strftime('%H:%M:%S')} Task stopped by user."
TaskService.model.update(
progress_msg=TaskService.model.progress_msg + cancel_msg,
progress=-1,
).where(TaskService.model.id == task_id).execute()
except Exception as e:
logging.exception(f"Failed to update task {task_id} progress after cancellation, %s", str(e))

# If the task belongs to a document, also mark the document's run status as
# cancelled so that the UI reflects the state correctly.
try:
from api.db.services.document_service import DocumentService
doc_id = task.doc_id
if doc_id and doc_id not in (CANVAS_DEBUG_DOC_ID, GRAPH_RAPTOR_FAKE_DOC_ID):
_, doc = DocumentService.get_by_id(doc_id)
if doc and str(doc.run) in (TaskStatus.RUNNING.value, TaskStatus.SCHEDULE.value):
DocumentService.update_by_id(doc_id, {"run": TaskStatus.CANCEL.value, "progress": 0})
except Exception as e:
logging.exception(f"Failed to update document run status for task {task_id}: %s", str(e))

return get_json_result(data=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Add an INFO log for the successful cancellation path.

Only the failure branches log. Cancellation is a security/audit-relevant state transition (task progress → -1, document run → CANCEL); please add an INFO log on entry and on success so operators can trace which user cancelled which task and when.

 async def cancel_task(task_id):
@@
     exists, task = TaskService.get_by_id(task_id)
+    logging.info("Cancel task requested: task_id=%s", task_id)
     if not exists:
@@
-    return get_json_result(data=True)
+    logging.info("Cancel task succeeded: task_id=%s doc_id=%s", task_id, task.doc_id)
+    return get_json_result(data=True)

As per coding guidelines: "Add logging for new flows".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/task_api.py` around lines 33 - 89, Add INFO-level logs
for the cancellation flow in cancel_task: log an entry when cancellation is
initiated (include task_id, timestamp and user identity if available from the
request context or current user helper) before calling REDIS_CONN.set, and log a
success message after the cancel flag and DB updates complete (include task_id,
doc_id if present, and timestamp). Place the entry log at the start of
cancel_task and the success log right before returning
get_json_result(data=True); reference the REDIS_CONN.set call,
TaskService.model.update usage, and the DocumentService.update_by_id call so the
log reflects both Redis and DB outcomes.

Comment thread api/apps/restful_apis/task_api.py Resolved
Comment thread api/apps/restful_apis/task_api.py Resolved
Comment thread api/apps/restful_apis/task_api.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@api/apps/restful_apis/task_api.py`:
- Around line 79-114: The logging calls use mixed styles (f-strings and %s
placeholders) and pass exception objects redundantly; change the three
logging.exception calls that reference task_id and exceptions to use
lazy-formatting with %s/%r placeholders and omit passing the exception as a
formatting arg so the logger records the traceback itself — e.g., replace
logging.exception(f"Failed to set cancel flag for task {task_id}: %s", str(e))
and logging.exception("Failed to update task %s progress after cancellation:
%s", task_id, e) and logging.exception(f"Failed to update document run status
for task {task_id}: %s", str(e)) with logging.exception("Failed to set cancel
flag for task %s", task_id), logging.exception("Failed to update task %s
progress after cancellation", task_id), and logging.exception("Failed to update
document run status for task %s", task_id) respectively (locations: the
REDIS_CONN.set try/except, the TaskService.model.update except, and the
DocumentService except).
- Around line 79-86: The Redis cancel marker is being set without expiry in
REDIS_CONN.set(f"{task_id}-cancel", "x"); change it to set a bounded TTL (e.g.,
24 hours = 86400 seconds) by passing the exp parameter so the cancel key expires
after a safe window; update the same pattern where used (referenced call sites:
REDIS_CONN.set in task_api.py, agent/canvas.py around has_canceled usage,
task_service.py method that marks cancellations, and dataset_api_service.py) and
keep the existing exception handling and return behavior intact.
- Around line 55-65: After fetching the task in _cancel_task (using
TaskService.get_by_id), import current_user from api.apps and immediately verify
the caller owns the task via the parent document by calling
DocumentService.accessible(task.doc_id, current_user.id) and return a NOT_FOUND
or FORBIDDEN get_data_error_result if access is denied; only proceed with
setting the Redis flag and updating progress/doc run status after that check.
Also fix the two logging.exception calls (the one around the Redis/cancel block
and the one updating the document) to use lazy formatting consistently
(logging.exception("message %s: %s", var, e)) instead of mixing f-strings with
positional arguments.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9fabcfa5-af36-4676-874b-c5b4c60e5531

📥 Commits

Reviewing files that changed from the base of the PR and between fe525cb and b7520b1.

📒 Files selected for processing (1)
  • api/apps/restful_apis/task_api.py

Comment on lines +55 to +65
async def _cancel_task(task_id):
"""
Sets a Redis cancel flag, updates the task progress to -1 (cancelled),
and marks the associated document's run status as CANCEL if applicable.
"""
exists, task = TaskService.get_by_id(task_id)
if not exists:
return get_data_error_result(
code=RetCode.NOT_FOUND,
message=f"Task '{task_id}' not found.",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm the codebase's typical pattern for tenant/ownership checks on similar
# document/task mutating endpoints, so we can mirror it here.
echo "=== current_user usage in restful_apis ==="
rg -nP --type=py -C2 '\bcurrent_user\b' api/apps/restful_apis/ | head -120

echo
echo "=== Examples of tenant/owner enforcement around DocumentService ==="
rg -nP --type=py -C3 '(accessible|tenant|current_user)\b.*(doc|kb|task)' api/apps/ | head -120

echo
echo "=== How was the old PUT /cancel/<task_id> on canvas_app.py scoped? ==="
git log --all --oneline -- api/apps/canvas_app.py | head -10
git show HEAD~1:api/apps/canvas_app.py 2>/dev/null | rg -nP -C3 'cancel|stop' | head -80

Repository: infiniflow/ragflow

Length of output: 16241


🏁 Script executed:

#!/bin/bash

# Read the full _cancel_task function and surrounding context
echo "=== Full task_api.py content (lines 1-130) ==="
head -130 api/apps/restful_apis/task_api.py | cat -n

echo ""
echo "=== Check if file is longer than 130 lines ==="
wc -l api/apps/restful_apis/task_api.py

Repository: infiniflow/ragflow

Length of output: 5465


🏁 Script executed:

#!/bin/bash

# Check TaskService.get_by_id to understand what it returns
echo "=== TaskService.get_by_id implementation ==="
rg -n "def get_by_id" api/ --type=py -A 15 | grep -A 15 "class TaskService\|def get_by_id"

echo ""
echo "=== Task model and tenant relationship ==="
rg -n "class Task|tenant" api/db/ --type=py | head -40

Repository: infiniflow/ragflow

Length of output: 6598


🏁 Script executed:

#!/bin/bash

# Check DocumentService.accessible pattern for comparison
echo "=== DocumentService.accessible implementation ==="
rg -n "def accessible" api/ --type=py -B 2 -A 8 | grep -A 8 "DocumentService"

echo ""
echo "=== Check if tasks are scoped by tenant ==="
rg -n "task.*tenant|Task.*tenant" api/db/ --type=py | head -20

Repository: infiniflow/ragflow

Length of output: 227


🏁 Script executed:

#!/bin/bash

# Verify Redis CONN usage and TTL patterns elsewhere
echo "=== Redis CONN.set patterns in codebase ==="
rg -n "REDIS_CONN\.set" api/ --type=py -B 1 -A 1 | head -60

echo ""
echo "=== Check for EX/PX (TTL) usage in Redis sets ==="
rg -n "REDIS_CONN\.set.*EX|REDIS_CONN\.set.*PX|ex=|px=" api/ --type=py

Repository: infiniflow/ragflow

Length of output: 34911


🏁 Script executed:

#!/bin/bash

# Check ruff config and current formatting compliance
echo "=== Check ruff/pyproject.toml ==="
if [ -f pyproject.toml ]; then
  rg -n "ruff|tool.ruff" pyproject.toml -A 10
fi

echo ""
echo "=== Lines 82 and 114 of task_api.py (logging format check) ==="
sed -n '75,90p; 107,120p' api/apps/restful_apis/task_api.py | cat -n

Repository: infiniflow/ragflow

Length of output: 1938


🏁 Script executed:

#!/bin/bash

# Check if Task model has tenant_id and how it's used in queries
echo "=== Task model definition ==="
rg -n "class Task" api/db/db_models.py -A 30 | head -50

echo ""
echo "=== TaskService methods - how tasks are retrieved ==="
rg -n "def.*task\|class TaskService" api/db/services/task_service.py -A 5 | head -60

echo ""
echo "=== Check if current_user is imported in task_api.py ==="
head -30 api/apps/restful_apis/task_api.py | grep -i "current_user\|login_required"

Repository: infiniflow/ragflow

Length of output: 2121


🏁 Script executed:

#!/bin/bash

# Verify DocumentService.accessible implementation to understand the pattern we need
echo "=== DocumentService.accessible method ==="
rg -n "def accessible" api/db/services/ --type=py -B 2 -A 10

echo ""
echo "=== Example task ownership check pattern ==="
rg -n "task.*current_user\|current_user.*task" api/ --type=py -B 2 -A 2 | head -40

Repository: infiniflow/ragflow

Length of output: 6414


🏁 Script executed:

#!/bin/bash

# Check if there's an accessible method for Task or if we need to verify via doc_id
echo "=== TaskService implementation ==="
grep -n "class TaskService" api/db/services/task_service.py -A 30 | head -40

echo ""
echo "=== Check how tasks are accessed - via doc_id ownership ==="
rg -n "task\." api/apps/restful_apis/ --type=py -B 1 -A 1 | grep -A 2 "doc_id"

Repository: infiniflow/ragflow

Length of output: 2355


🏁 Script executed:

#!/bin/bash

# Verify the TTL issue more broadly - check if any cancel keys have TTL
echo "=== All REDIS_CONN.set for cancel flags ==="
rg -n "cancel.*REDIS_CONN\.set|REDIS_CONN\.set.*cancel" api/ --type=py -B 1 -A 2

echo ""
echo "=== Check redis wrapper for set method signature ==="
rg -n "def set" rag/utils/redis_conn.py -A 5

Repository: infiniflow/ragflow

Length of output: 1610


Add authorization check before cancelling task — current_user cannot be verified as task owner.

_cancel_task accepts any logged-in user and cancels a task by ID without verifying that current_user owns the task or its parent document. This is a horizontal privilege escalation vulnerability: a user from one tenant can cancel running ingestion tasks from another tenant by calling POST /api/v1/tasks/<task_id>/cancel.

The function retrieves the task (line 60) and later updates its associated document (line 112) without ever validating ownership. You must add a check similar to the pattern used elsewhere in the codebase (e.g., DocumentService.accessible(doc_id, current_user.id) in document_app.py):

  1. Import current_user from api.apps
  2. After fetching the task, verify ownership via the associated document: DocumentService.accessible(task.doc_id, current_user.id) before proceeding with any mutations

Additionally, fix the logging anti-pattern on lines 82 and 114: replace logging.exception(f"message {var}: %s", str(e)) with logging.exception("message %s: %s", var, e) to use consistent lazy formatting instead of mixing f-strings with positional arguments.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/task_api.py` around lines 55 - 65, After fetching the
task in _cancel_task (using TaskService.get_by_id), import current_user from
api.apps and immediately verify the caller owns the task via the parent document
by calling DocumentService.accessible(task.doc_id, current_user.id) and return a
NOT_FOUND or FORBIDDEN get_data_error_result if access is denied; only proceed
with setting the Redis flag and updating progress/doc run status after that
check. Also fix the two logging.exception calls (the one around the Redis/cancel
block and the one updating the document) to use lazy formatting consistently
(logging.exception("message %s: %s", var, e)) instead of mixing f-strings with
positional arguments.

Comment thread api/apps/restful_apis/task_api.py Resolved
Comment on lines +79 to +86
try:
REDIS_CONN.set(f"{task_id}-cancel", "x")
except Exception as e:
logging.exception(f"Failed to set cancel flag for task {task_id}: %s", str(e))
return get_json_result(
code=RetCode.CONNECTION_ERROR,
message="Failed to stop task",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the REDIS_CONN.set wrapper to determine the correct TTL parameter name
# and any existing cancel-key conventions.
fd -t f redis_conn.py
rg -nP --type=py -C3 'def\s+set\s*\(' rag/utils/redis_conn.py
echo
echo "=== Existing cancel-key writes elsewhere ==="
rg -nP --type=py -C2 '\-cancel'

Repository: infiniflow/ragflow

Length of output: 4307


Set a TTL on the Redis cancel marker to avoid unbounded key growth.

REDIS_CONN.set(f"{task_id}-cancel", "x") has no expiry, so every cancellation permanently adds a key to Redis. The has_canceled check only needs the flag readable while the executor is processing; a bounded TTL (e.g., 24 hours — anything longer than worst-case task runtime) prevents unbounded accumulation and avoids stale flags affecting task ID reuse.

The REDIS_CONN.set method accepts exp (in seconds). This issue also affects agent/canvas.py:278, api/db/services/task_service.py:512, and api/apps/services/dataset_api_service.py:817.

🛡️ Suggested change
-        REDIS_CONN.set(f"{task_id}-cancel", "x")
+        # TTL must comfortably exceed worst-case task runtime
+        REDIS_CONN.set(f"{task_id}-cancel", "x", exp=24 * 3600)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@api/apps/restful_apis/task_api.py` around lines 79 - 86, The Redis cancel
marker is being set without expiry in REDIS_CONN.set(f"{task_id}-cancel", "x");
change it to set a bounded TTL (e.g., 24 hours = 86400 seconds) by passing the
exp parameter so the cancel key expires after a safe window; update the same
pattern where used (referenced call sites: REDIS_CONN.set in task_api.py,
agent/canvas.py around has_canceled usage, task_service.py method that marks
cancellations, and dataset_api_service.py) and keep the existing exception
handling and return behavior intact.

@codecov

codecov Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.30%. Comparing base (6a23dfe) to head (918be72).
⚠️ Report is 14 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14393   +/-   ##
=======================================
  Coverage   95.30%   95.30%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          670      670           
  Misses         16       16           
  Partials       17       17           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@wangq8
wangq8 merged commit 488c3ef into infiniflow:main Apr 27, 2026
1 of 2 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 28, 2026
1 task done
@coderabbitai coderabbitai Bot mentioned this pull request May 14, 2026
11 of 20 tasks
yuzhichang added a commit to RazmikGevorgyan/ragflow that referenced this pull request Jun 30, 2026
…as SSE and state serialization

Conflict resolution notes:
- agent/canvas.py, agent/component/base.py: auto-merged cleanly
- api/apps/canvas_app.py: deleted in main by PR infiniflow#14393 (Add task API);
  PR 14210's _canvas_json_default helper and its two usages have been
  ported to api/apps/restful_apis/agent_api.py (lines 75-86 helper, 303
  and 1517 apply it to the canvas session/agent chat SSE yields).

Closes infiniflow#14229
yuzhichang added a commit to RazmikGevorgyan/ragflow that referenced this pull request Jun 30, 2026
…as SSE and state serialization

Conflict resolution notes:
- agent/canvas.py, agent/component/base.py: auto-merged cleanly
- api/apps/canvas_app.py: deleted in main by PR infiniflow#14393 (Add task API);
  PR 14210's _canvas_json_default helper and its two usages have been
  ported to api/apps/restful_apis/agent_api.py (helper at L75, applied
  to the canvas session SSE yield at L326 and the agent chat completion
  SSE yield at L1588).

Closes infiniflow#14229
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐖api The modified files are located under directory 'api/apps/sdk' ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant