Repository navigation
Conversation
📝 WalkthroughWalkthroughAdds 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. ChangesDataset owner filtering
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
Possibly related PRs
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
web/src/services/knowledge-service.ts (1)
270-271: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse the standard registered service path.
Route this endpoint through
registerNextServerand@/utils/next-request, matching neighboring service endpoints. The directrequest.getbypasses 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 viaregisterNextServer, 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 winDefine a same-file query-key factory.
Replace the inline array with a
{Domain}Keysfactory whose return value usesas const, and reuse it for future invalidations.As per coding guidelines,
web/src/**/*.{ts,tsx}: Never write raw React QueryqueryKeyarrays 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 winAdd 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
📒 Files selected for processing (12)
api/apps/restful_apis/dataset_api.pyapi/apps/services/dataset_api_service.pyapi/db/services/knowledgebase_service.pyinternal/dao/kb.gointernal/entity/dataset.gointernal/handler/dataset.gointernal/service/dataset/crud.goweb/src/hooks/use-knowledge-request.tsweb/src/interfaces/database/dataset.tsweb/src/pages/datasets/use-select-owners.tsweb/src/services/knowledge-service.tsweb/src/utils/api.ts
| 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") |
There was a problem hiding this comment.
🗄️ 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
| queryFn: async () => { | ||
| const { data } = await datasetFilter(); | ||
| if (data.code === 0) { | ||
| return data.data; | ||
| } | ||
| }, | ||
| }); |
There was a problem hiding this comment.
🩺 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$' .
fiRepository: 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 200Repository: 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
left a comment
There was a problem hiding this comment.
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:
IDatasetFilterandDatasetOwnerFilterare well-defined. - Proper React Query pattern:
useQuerywith a named query key, sensible defaulting when data is unavailable. - Defensive nil checks in Go: The Go service guards against nil
joinedTenantentries.
⚠️ 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/GetOwnerFilterdatabase queries - The new
list_dataset_filters/ListDatasetFiltersservice methods - The new
?type=filterAPI route handler - The new
useGetDatasetFilterhook
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, theJOINtoUserusesUser.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, theJOINwill exclude that owner entirely from results. For team-owned KBs where the original owner was deleted, this could hide datasets from the filter. Consider usingLEFT JOINand falling back to a default label (tenant ID) ifnicknameis NULL. (Same concern applies to the GoGetOwnerFilter.)
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.
|
Tested, worked on both Python and Go version. |
No description provided.