Skip to content

Fix get datasets owner retrieve the whole dataset - #17370

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-get-datasets-owner-retrieve-the-whole-dataset
Jul 27, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
wangq8:bugfix/fix-get-datasets-owner-retrieve-the-whole-dataset

Conversation

@wangq8

@wangq8 wangq8 commented Jul 24, 2026

Copy link
Copy Markdown
Collaborator

No description provided.

@wangq8 wangq8 added the ci Continue Integration label Jul 24, 2026
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 24, 2026
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds an owner-filter mode to dataset listing endpoints, aggregates visible dataset owners with counts, exposes the result through backend services, and updates the frontend to fetch and use the owner filter data.

Changes

Dataset owner filtering

Layer / File(s) Summary
Owner filter aggregation
internal/entity/dataset.go, internal/dao/kb.go, api/db/services/knowledgebase_service.py, internal/service/dataset/crud.go, api/apps/services/dataset_api_service.py
Adds the owner filter response shape, tenant-scoped owner aggregation, and total count calculation.
Dataset filter endpoint
internal/handler/dataset.go, api/apps/restful_apis/dataset_api.py
Routes type=filter requests to filter-specific services and returns filter results or standardized errors while preserving normal listing behavior.
Frontend owner filter integration
web/src/interfaces/database/dataset.ts, web/src/utils/api.ts, web/src/services/knowledge-service.ts, web/src/hooks/use-knowledge-request.ts, web/src/pages/datasets/use-select-owners.ts
Adds the filter type, API request, React Query hook, fallback shape, and owner-selection data source.

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

Sequence Diagram(s)

sequenceDiagram
  participant DatasetPage
  participant useGetDatasetFilter
  participant DatasetFilterEndpoint
  participant DatasetService
  participant KnowledgebaseDAO
  DatasetPage->>useGetDatasetFilter: Request owner filters
  useGetDatasetFilter->>DatasetFilterEndpoint: GET /datasets?type=filter
  DatasetFilterEndpoint->>DatasetService: ListDatasetFilters(user.ID)
  DatasetService->>KnowledgebaseDAO: GetOwnerFilter(tenantIDs, userID)
  KnowledgebaseDAO-->>DatasetService: Owner counts
  DatasetService-->>DatasetFilterEndpoint: filter.owner and total
  DatasetFilterEndpoint-->>useGetDatasetFilter: Filter response
  useGetDatasetFilter-->>DatasetPage: filter.owner
Loading

Possibly related PRs

Suggested labels: 🌈 python

Suggested reviewers: euvre, jinhai-cn, xugangqiang

Poem

I’m a rabbit with filters to share,
Owner counts hopping through the air.
Backend gathers, frontend knows,
Each tidy label neatly grows.
“Type filter!” I cheer and run—
Dataset choices for everyone!

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is missing entirely, so the required Summary section and background context are absent. Add a ### Summary section with a brief problem statement, what changed, and any relevant background context for reviewers.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is related to the PR’s main change, but it is awkward and not very clear about the new dataset owner filter flow.
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.

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.

@wangq8
wangq8 requested review from dcc123456 and euvre July 24, 2026 12:32

@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: 2

🧹 Nitpick comments (3)
web/src/services/knowledge-service.ts (1)

270-271: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the standard registered service path.

Route this endpoint through registerNextServer and @/utils/next-request, matching neighboring service endpoints. The direct request.get bypasses the repository’s required service-layer convention and may skip shared proxy or request handling.

As per coding guidelines, web/src/services/**/*.{ts,tsx}: Register HTTP endpoints via registerNextServer, routing requests through @/utils/next-request.

🤖 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 `@web/src/services/knowledge-service.ts` around lines 270 - 271, Update
datasetFilter to use the standard registered service path: register the endpoint
through registerNextServer and route its request via `@/utils/next-request`
instead of calling request.get directly. Match the surrounding service endpoint
pattern while preserving the existing api.datasetFilter target and return
behavior.

Source: Coding guidelines

web/src/hooks/use-knowledge-request.ts (1)

216-217: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Define a same-file query-key factory.

Replace the inline array with a {Domain}Keys factory whose return value uses as const, and reuse it for future invalidations.

As per coding guidelines, web/src/**/*.{ts,tsx}: Never write raw React Query queryKey arrays inline.

Suggested pattern
+const KnowledgeKeys = {
+  datasetFilter: () => [KnowledgeApiAction.FetchDatasetFilter] as const,
+};
+
 queryKey:
-  [KnowledgeApiAction.FetchDatasetFilter],
+  KnowledgeKeys.datasetFilter(),
🤖 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 `@web/src/hooks/use-knowledge-request.ts` around lines 216 - 217, Replace the
inline queryKey array in useQuery with a same-file KnowledgeKeys factory whose
returned key is declared as const. Use this factory wherever the dataset-filter
query key is referenced, including future invalidation paths, and do not leave
raw React Query query-key arrays inline.

Source: Coding guidelines

api/apps/services/dataset_api_service.py (1)

461-465: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add structured logging for the new filter flow.

Log a concise event at this service boundary, such as the user and owner-count result, without dataset contents. This will make empty aggregates and regressions diagnosable.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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 `@api/apps/services/dataset_api_service.py` around lines 461 - 465, Add
structured logging to list_dataset_filters after retrieving the owners,
recording the requesting tenant/user identifier and the resulting owner count or
aggregate total without logging dataset contents; use the service’s existing
logging convention and preserve the current response.

Source: Coding guidelines

🤖 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.

Inline comments:
In `@api/apps/restful_apis/dataset_api.py`:
- Around line 366-378: Update the endpoint docstring for the type=filter branch
to document the type query parameter and its response object containing filter
and total fields, replacing the stale array-only schema. Keep the implementation
in the filter branch unchanged and remove any outdated response documentation.

In `@web/src/hooks/use-knowledge-request.ts`:
- Around line 218-224: Update the queryFn in useGetDatasetFilter to throw the
backend response error when data.code is nonzero, while preserving the current
return of data.data for successful responses. Ensure the hook exposes the query
failure instead of returning undefined and producing an empty owner filter.

---

Nitpick comments:
In `@api/apps/services/dataset_api_service.py`:
- Around line 461-465: Add structured logging to list_dataset_filters after
retrieving the owners, recording the requesting tenant/user identifier and the
resulting owner count or aggregate total without logging dataset contents; use
the service’s existing logging convention and preserve the current response.

In `@web/src/hooks/use-knowledge-request.ts`:
- Around line 216-217: Replace the inline queryKey array in useQuery with a
same-file KnowledgeKeys factory whose returned key is declared as const. Use
this factory wherever the dataset-filter query key is referenced, including
future invalidation paths, and do not leave raw React Query query-key arrays
inline.

In `@web/src/services/knowledge-service.ts`:
- Around line 270-271: Update datasetFilter to use the standard registered
service path: register the endpoint through registerNextServer and route its
request via `@/utils/next-request` instead of calling request.get directly. Match
the surrounding service endpoint pattern while preserving the existing
api.datasetFilter target and return behavior.
🪄 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 Plus

Run ID: ae0fa986-9786-4e47-af35-4b41191905de

📥 Commits

Reviewing files that changed from the base of the PR and between bcf1570 and 0979633.

📒 Files selected for processing (12)
  • api/apps/restful_apis/dataset_api.py
  • api/apps/services/dataset_api_service.py
  • api/db/services/knowledgebase_service.py
  • internal/dao/kb.go
  • internal/entity/dataset.go
  • internal/handler/dataset.go
  • internal/service/dataset/crud.go
  • web/src/hooks/use-knowledge-request.ts
  • web/src/interfaces/database/dataset.ts
  • web/src/pages/datasets/use-select-owners.ts
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts

Comment on lines +366 to +378
if request.args.get("type") == "filter":
try:
success, result = dataset_api_service.list_dataset_filters(tenant_id)
if success:
return get_result(data=result)
else:
return get_error_data_result(message=result)
except OperationalError as e:
logging.exception(e)
return get_error_data_result(message="Database operation failed")
except Exception as e:
logging.exception(e)
return get_error_data_result(message="Internal server error")

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Update the endpoint documentation for type=filter.

This branch returns {filter, total}, while the docstring still describes only an array response and does not document the new query parameter. Update the OpenAPI parameters and response schema.

As per coding guidelines, **/*: Remove stale documentation.

🤖 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 `@api/apps/restful_apis/dataset_api.py` around lines 366 - 378, Update the
endpoint docstring for the type=filter branch to document the type query
parameter and its response object containing filter and total fields, replacing
the stale array-only schema. Keep the implementation in the filter branch
unchanged and remove any outdated response documentation.

Source: Coding guidelines

Comment on lines +218 to +224
queryFn: async () => {
const { data } = await datasetFilter();
if (data.code === 0) {
return data.data;
}
},
});

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate and inspect the relevant hook with line numbers.
if [ -f web/src/hooks/use-knowledge-request.ts ]; then
  echo "FOUND web/src/hooks/use-knowledge-request.ts"
  wc -l web/src/hooks/use-knowledge-request.ts
  sed -n '160,260p' web/src/hooks/use-knowledge-request.ts | cat -n -v
  echo "--- search datasetFilter/code handling ---"
  rg -n "datasetFilter|queryFn: async|useQuery|owner list|ownerList|knowledge" web/src/hooks/use-knowledge-request.ts web/src || true
else
  echo "MISSING web/src/hooks/use-knowledge-request.ts"
  fd -a 'use-knowledge-request\.ts$' .
fi

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- knowledge-service request wrappers ---"
sed -n '1,120p' web/src/services/knowledge-service.ts | cat -n -v

echo "--- request utilities / API handling ---"
rg -n "function request|const request|throw|code !== 0|error|message\\.error|message\\.warning|message\\.success" web/src/utils web/src/pages -g '*.ts' -g '*.tsx' | head -n 200

echo "--- relevant hook return consumers (focused repo search) ---"
rg -n "useGetDatasetFilter|filter:\{ owner|filter\\.owner|\\.owner" web/src -g '*.ts' -g '*.tsx' | head -n 200

Repository: infiniflow/ragflow

Length of output: 24229


Propagate dataset filter failures instead of swallowing them as an empty owner set.

queryFn returns undefined when data.code !== 0, and useGetDatasetFilter() then returns filter: { owner: [] }. Throw the backend response error from the query function so the hook exposes the failure; callers depending on filter.owner can decide how to render the error instead of silently operating on an empty filter.

🤖 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 `@web/src/hooks/use-knowledge-request.ts` around lines 218 - 224, Update the
queryFn in useGetDatasetFilter to throw the backend response error when
data.code is nonzero, while preserving the current return of data.data for
successful responses. Ensure the hook exposes the query failure instead of
returning undefined and producing an empty owner filter.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

PR Review: #17370 — Fix get datasets owner retrieve the whole dataset

Author: @wangq8 | +137 / −4 across 12 files

Summary

This PR replaces the old approach of fetching all datasets to build the owner filter on the frontend with a lightweight dedicated endpoint (GET /datasets?type=filter) that returns aggregated owner data (id, label, count) directly from the backend. Both Python and Go backends are updated consistently, and the frontend swaps useFetchAllKnowledgeList + buildOwnersFilter for useGetDatasetFilter.


✅ What's good

  • Clear performance win: No longer pulling the full dataset list just to extract unique owners.
  • Consistent dual-backend implementation: Python (Peewee) and Go (GORM) queries match — same visibility rules, same GROUP BY tenant_id, nickname.
  • Clean types: IDatasetFilter and DatasetOwnerFilter are well-defined.
  • Proper React Query pattern: useQuery with a named query key, sensible defaulting when data is unavailable.
  • Defensive nil checks in Go: The Go service guards against nil joinedTenant entries.

⚠️ Issues to address

1. Query cache not invalidated on dataset mutation

When a user creates or deletes a knowledge base, the existing code calls queryClient.invalidateQueries({ queryKey: [KnowledgeApiAction.FetchKnowledgeListByPage] }) in several mutation hooks (useCreateKnowledge, useDeleteKnowledge, etc.). However, none of these invalidate the new KnowledgeApiAction.FetchDatasetFilter query.

This means after CRUD operations:

  • The dataset list refreshes ✅
  • The owner filter does not refresh ❌ (stale counts, missing new owners)

Fix: In every mutation that invalidates FetchKnowledgeListByPage, also invalidate FetchDatasetFilter:

queryClient.invalidateQueries({
  queryKey: [KnowledgeApiAction.FetchDatasetFilter],
});

Or, if the invalidation is already broad (e.g., no specific key), verify it covers the new key.


2. REST API design: ?type=filter is not RESTful

Using a query parameter to overload the /datasets endpoint with a different response shape is an anti-pattern. A cleaner approach would be a dedicated sub-resource:

GET /api/v1/datasets/filters

or

GET /api/v1/datasets/owners

This separates the concern of "list datasets" from "get filter options" and makes the API more discoverable. However, since this follows existing patterns in the codebase, this is a suggestion rather than a blocker.


3. total field is returned but unused

Both the Python and Go backends compute and return a total field (sum of all owner counts) in the filter response, but the frontend useGetDatasetFilter hook only extracts data.filter and ignores total. This is dead data on the wire — consider either removing it or using it (e.g., to show "X datasets total").


4. Missing test coverage

No tests were added for:

  • The new get_owner_filter / GetOwnerFilter database queries
  • The new list_dataset_filters / ListDatasetFilters service methods
  • The new ?type=filter API route handler
  • The new useGetDatasetFilter hook

Given that this is replacing a potentially expensive operation, adding basic integration/unit tests would improve confidence.


5. Frontend useQuery has no staleTime configuration

useQuery({
  queryKey: [KnowledgeApiAction.FetchDatasetFilter],
  queryFn: async () => { ... },
});

Owner/team membership changes infrequently. Adding a reasonable staleTime (e.g., 5–10 minutes) would reduce unnecessary refetches on window focus / component remounts without meaningful risk of staleness.

useQuery({
  queryKey: [KnowledgeApiAction.FetchDatasetFilter],
  queryFn: async () => { ... },
  staleTime: 5 * 60 * 1000, // 5 minutes
});

🔍 Nitpick

  • In api/db/services/knowledgebase_service.py:get_owner_filter, the JOIN to User uses User.nickname — if a user changes their nickname, the filter label will update on the next query, which is fine. But if a user is deleted, the JOIN will exclude that owner entirely from results. For team-owned KBs where the original owner was deleted, this could hide datasets from the filter. Consider using LEFT JOIN and falling back to a default label (tenant ID) if nickname is NULL. (Same concern applies to the Go GetOwnerFilter.)

Verdict

Request changes — the cache invalidation bug (#1) will cause a visible UX issue. The other items are suggestions and nitpicks. Overall a solid improvement, just needs a small fix on the frontend invalidation side.

@wangq8

wangq8 commented Jul 27, 2026

Copy link
Copy Markdown
Collaborator Author

Tested, worked on both Python and Go version.

@wangq8
wangq8 merged commit 53afc32 into infiniflow:main Jul 27, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. 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.

2 participants