Skip to content

feat[go]: implement /api/v1/datasets/<dataset_id> PUT - #16122

Merged
JinHai-CN merged 8 commits into
infiniflow:mainfrom
Haruko386:moon
Jun 18, 2026
Merged

JinHai-CN merged 8 commits into
infiniflow:mainfrom
Haruko386:moon

Conversation

@Haruko386

Copy link
Copy Markdown
Member

What problem does this PR solve?

As pic shows

image

Type of change

  • New Feature (non-breaking change which adds functionality)

@Haruko386 Haruko386 added the ci Continue Integration label Jun 17, 2026
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 17, 2026
@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

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: 54917f2d-a8b0-4d5e-ab39-f5bf8137d823

📥 Commits

Reviewing files that changed from the base of the PR and between ee801a3 and fd179b5.

📒 Files selected for processing (1)
  • internal/router/router.go
💤 Files with no reviewable changes (1)
  • internal/router/router.go

📝 Walkthrough

Walkthrough

Adds a PUT /api/v1/datasets/:dataset_id REST endpoint backed by DatasetService.UpdateDataset, which validates ownership, normalizes fields and parser config, updates pagerank via the document engine, persists changes, and transactionally syncs connector links via ConnectorDAO.LinkDatasetConnectors. Also makes provider manager initialization thread-safe and adds a full test suite.

Changes

Dataset Update API with Connector Linking

Layer / File(s) Summary
Request types and normalization helpers
internal/service/dataset.go, internal/dao/connector.go
Defines UpdateDatasetRequest, DatasetConnectorRequest, and DatasetConnectorLink structs. Adds helpers datasetUpdateParserID, datasetUpdateEmbeddingID, normalizeDatasetUpdateExt, normalizeDatasetUpdateParserConfig, and datasetBoolValue for field resolution and type coercion.
Thread-safe provider manager initialization
internal/dao/database.go
Adds sync and os imports, a package-level mutex, and rewrites GetModelProviderManager() to use double-checked locking. Adds findModelConfigDir() to search candidate relative paths; failures invoke log.Fatal.
UpdateDataset service and embedding availability
internal/service/dataset.go
Implements DatasetService.UpdateDataset: validates tenant ownership, normalizes ext/parser_config, resolves parser/embedding IDs, conditionally updates pagerank, detects no-op requests, persists dataset changes, links connectors via DAO, and returns updated dataset. Refactors verifyEmbeddingAvailability to use GetModelConfigFromProviderInstance.
ConnectorDAO transactional connector linking
internal/dao/connector.go
Implements ConnectorDAO.LinkDatasetConnectors: diffs connector2kb mappings, updates auto_parse for existing links, inserts missing links with generated UUIDs, schedules sync/prune tasks, deletes removed links, and cancels active/scheduled SyncLogs.
HTTP handler, routes, and router test
internal/handler/datasets.go, internal/router/router.go, internal/router/router_test.go
Adds DatasetsHandler.UpdateDataset with authentication, input validation, JSON binding, and service dispatch. Registers PUT /api/v1/datasets/:dataset_id and PUT /api/v1/messages/:memory_message routes. Adds a test verifying route registration and auth protection.
Comprehensive UpdateDataset test suite
internal/service/dataset_update_test.go
Adds 9 test cases covering field updates, missing dataset, non-owner access, name validation, duplicate names, no-op requests, connector linking with AutoParse persistence, provider+instance embedding resolution, and empty connector ID rejection. Includes DB setup and entity insertion helpers.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • Hz-186

Poem

🐇 A dataset hops into the PUT lane,
Its fields get trimmed, its connectors chained.
The provider sleeps safe behind a lock,
No race condition can pick that lock!
Transactions wrap each link and prune —
This rabbit ships a clean lagoon. 🌊

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is incomplete. While it correctly identifies the change type as a new feature, it lacks substantive explanation of the problem being solved beyond referencing an attached image. Expand the 'What problem does this PR solve?' section with a clear narrative explanation of the functionality being added, rather than relying solely on an image reference.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main feature being implemented: a PUT endpoint for the /api/v1/datasets/<dataset_id> API route.
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.

@Haruko386
Haruko386 marked this pull request as draft June 17, 2026 05:10
@Haruko386
Haruko386 marked this pull request as ready for review June 17, 2026 05:11

@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

🤖 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 `@internal/dao/connector.go`:
- Around line 136-144: The connector existence check using tx.Where("id = ?",
connector.ID).First(&fullConnector) is performed after creating the Connector2Kb
row, which means invalid connector IDs result in a generic database error after
transaction rollback. Move this validation block to execute before the Create()
call that inserts the Connector2Kb row. This ensures the connector is validated
early and returns a specific error for invalid IDs, aligning with the validation
pattern used elsewhere in the codebase.

In `@internal/handler/datasets.go`:
- Around line 174-210: In the UpdateDataset method, the error handling at the
jsonError call has a nil pointer dereference risk. When the condition `err !=
nil || code != common.CodeSuccess` is true, the code unconditionally calls
`err.Error()`, but err could be nil if only the code check failed. Fix this by
checking if err is not nil before calling err.Error(), and provide a default
error message when err is nil (for example, derive a message from the error code
or use a generic error message). Alternatively, work with the service layer to
ensure UpdateDataset always returns an error when the code is not CodeSuccess.
🪄 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: 49bd9ebb-bd60-484e-bcb2-7f734d2ebb4e

📥 Commits

Reviewing files that changed from the base of the PR and between 2290bb0 and 45eca73.

📒 Files selected for processing (4)
  • internal/dao/connector.go
  • internal/handler/datasets.go
  • internal/router/router.go
  • internal/service/dataset.go

Comment thread internal/dao/connector.go
Comment on lines +136 to +144
var fullConnector entity.Connector
if err := tx.Where("id = ?", connector.ID).First(&fullConnector).Error; err != nil {
return err
}
if connectorConfigBool(fullConnector.Config, "sync_deleted_files") {
if err := scheduleConnectorTask(tx, connector.ID, kbID, connectorTaskTypePrune, false); err != nil {
return err
}
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check how connector validation is handled elsewhere in the codebase
echo "=== Checking connector validation patterns ==="
rg -n -C5 'connector.*not.*found|invalid.*connector' --type go -i

echo "=== Check if there's a GetByID that returns nil for not found ==="
ast-grep --pattern 'func ($_ *ConnectorDAO) GetByID($_) ($_, $_)'

Repository: infiniflow/ragflow

Length of output: 6456


🏁 Script executed:

#!/bin/bash
# Get the full LinkDatasetConnectors method to understand context
echo "=== Full LinkDatasetConnectors method ==="
sed -n '93,164p' internal/dao/connector.go | cat -n

# Check method signature and what calls it
echo ""
echo "=== Search for LinkDatasetConnectors calls ==="
rg -n 'LinkDatasetConnectors' --type go -B2 -A2

Repository: infiniflow/ragflow

Length of output: 3712


🏁 Script executed:

#!/bin/bash
# Check where DatasetConnectorLink comes from and if there's pre-validation
echo "=== Check DatasetConnectorLink definition and usage ==="
rg -n 'type DatasetConnectorLink' --type go -A5

echo ""
echo "=== Check how connectorLinks is built in dataset service ==="
sed -n '1200,1260p' internal/service/dataset.go | cat -n

echo ""
echo "=== Check if connector IDs are validated before LinkDatasetConnectors ==="
rg -n 'accessible|GetByID|ValidateConnector' internal/service/dataset.go | head -20

Repository: infiniflow/ragflow

Length of output: 3875


🏁 Script executed:

#!/bin/bash
# Check the full context around LinkDatasetConnectors call in service
echo "=== Full context of LinkDatasetConnectors call in dataset service ==="
sed -n '1240,1260p' internal/service/dataset.go | cat -n

echo ""
echo "=== Check how errors from DAO are handled in dataset service ==="
rg -n 'LinkDatasetConnectors' internal/service/dataset.go -B3 -A3

echo ""
echo "=== Check what gorm.ErrRecordNotFound looks like when returned ==="
rg -n 'gorm.ErrRecordNotFound|RecordNotFound' --type go | head -20

Repository: infiniflow/ragflow

Length of output: 3074


🏁 Script executed:

#!/bin/bash
# Check if there's any pattern of pre-validating connector existence in connector service
echo "=== Check how other methods validate connector existence upfront ==="
rg -n 'GetByID.*connectorID|connectorDAO.GetByID' internal/service/dataset.go -B2 -A2

echo ""
echo "=== Check if connector existence validation happens elsewhere in dataset service ==="
sed -n '1240,1260p' internal/service/dataset.go -C10

echo ""
echo "=== See if connector validation before linking is done elsewhere ==="
rg -n 'for.*connector.*connectorDAO\|for.*connector.*GetByID' internal/service/ --type go -A5 | head -40

Repository: infiniflow/ragflow

Length of output: 2128


🏁 Script executed:

#!/bin/bash
# Let's check the broader pattern - do other dataset operations validate IDs first?
echo "=== Check if there's a pattern of pre-validating foreign key IDs ==="
rg -n 'GetByID.*for.*range\|for.*:=.*range.*{.*GetByID' internal/service/ --type go -A3 | head -50

echo ""
echo "=== Check error handling pattern in connector service for missing connectors ==="
sed -n '285,330p' internal/service/connector.go | cat -n

Repository: infiniflow/ragflow

Length of output: 2124


🏁 Script executed:

#!/bin/bash
# Check if there are any comments or TODOs about validation in LinkDatasetConnectors
echo "=== Check the full LinkDatasetConnectors and surrounding code ==="
sed -n '88,170p' internal/dao/connector.go | cat -n

echo ""
echo "=== Check if transaction failure cascades as expected ==="
rg -n 'DB.Transaction' internal/dao/connector.go -B2 -A15 | head -80

Repository: infiniflow/ragflow

Length of output: 5686


🏁 Script executed:

#!/bin/bash
# Check if Connector2Kb has a foreign key constraint defined
echo "=== Check entity.Connector2Kb definition for constraints ==="
fd -name "*.go" --type f | xargs grep -l "Connector2Kb" | xargs grep -n "type Connector2Kb" -A20

echo ""
echo "=== Verify the order: is connector validation AFTER create? ==="
sed -n '120,150p' internal/dao/connector.go | cat -n

Repository: infiniflow/ragflow

Length of output: 1479


🏁 Script executed:

#!/bin/bash
# Search for entity definitions
echo "=== Find entity files ==="
fd 'entity' -type d

echo ""
echo "=== Check for Connector2Kb definition ==="
find . -name "*.go" -type f | xargs grep -l "type Connector2Kb" | head -5

echo ""
echo "=== Look at the entity definition more carefully ==="
find . -name "*.go" -type f -exec grep -l "Connector2Kb" {} \; | head -10

Repository: infiniflow/ragflow

Length of output: 491


🏁 Script executed:

#!/bin/bash
# Look at the Connector2Kb entity definition
echo "=== Connector2Kb entity definition ==="
cat internal/entity/connector.go | grep -A30 "type Connector2Kb"

echo ""
echo "=== Check if there are database migration or constraint definitions ==="
find . -name "*.go" -type f | xargs grep -l "foreign.*key\|FOREIGN.*KEY" | head -5

Repository: infiniflow/ragflow

Length of output: 2235


🏁 Script executed:

#!/bin/bash
# Check if database creates foreign key constraints
echo "=== Search for database migration or initialization code ==="
find . -name "*.go" -type f | xargs grep -l "CreateTable\|AutoMigrate" | head -5

echo ""
echo "=== Check database initialization ==="
grep -r "AutoMigrate\|CreateTable" --include="*.go" internal/dao/database.go 2>/dev/null | head -20

Repository: infiniflow/ragflow

Length of output: 492


🏁 Script executed:

#!/bin/bash
# Understand the issue better - check if connector validation happens at API level
echo "=== Check the API handler for dataset connector update ==="
rg -n 'LinkDatasetConnectors|connectors.*provided' internal/handler/dataset.go -B5 -A5

echo ""
echo "=== Check if the review's suggestion about explicit validation is followed elsewhere ==="
rg -n 'for.*:=.*range.*{' internal/service/dataset.go | grep -A1 "1243"

echo ""
echo "=== Full context around where connectorLinks are built ==="
sed -n '1241,1256p' internal/service/dataset.go | cat -n

Repository: infiniflow/ragflow

Length of output: 1154


🏁 Script executed:

#!/bin/bash
# Let me verify the actual problem: does the code create the row BEFORE validating the connector exists?
echo "=== Exact sequence in LinkDatasetConnectors for new connectors ==="
sed -n '131,152p' internal/dao/connector.go | cat -n

echo ""
echo "=== Check if there's a database-level foreign key constraint ==="
rg -n 'FOREIGN\|CONSTRAINT\|foreign' internal/dao/database.go

echo ""
echo "=== Check test cases to see what happens with invalid connector IDs ==="
rg -n 'LinkDatasetConnectors' internal/ -l

Repository: infiniflow/ragflow

Length of output: 1200


🏁 Script executed:

#!/bin/bash
# Final verification: check if the transaction properly rolls back on error
echo "=== Verify the full problematic sequence once more ==="
sed -n '120,155p' internal/dao/connector.go | cat -n

echo ""
echo "=== Check if DB.Transaction auto-rollback is standard GORM behavior ==="
rg -n 'DB.Transaction' internal/dao/ -A1 | head -30

echo ""
echo "=== Confirm: is validation REALLY after creation? ==="
sed -n '125,150p' internal/dao/connector.go

Repository: infiniflow/ragflow

Length of output: 3222


Validate connector existence before creating the link.

The code creates the Connector2Kb row (line 131) before checking if the connector exists (line 145). If an invalid connector ID is provided, the First() call fails with gorm.ErrRecordNotFound, the transaction rolls back, and the caller receives a generic "Database operation failed" error.

Move the connector validation before the Create() call. This matches the validation pattern used elsewhere in the codebase (e.g., connector.go service methods) and provides an opportunity to return a more specific error rather than a generic database error.

🤖 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 `@internal/dao/connector.go` around lines 136 - 144, The connector existence
check using tx.Where("id = ?", connector.ID).First(&fullConnector) is performed
after creating the Connector2Kb row, which means invalid connector IDs result in
a generic database error after transaction rollback. Move this validation block
to execute before the Create() call that inserts the Connector2Kb row. This
ensures the connector is validated early and returns a specific error for
invalid IDs, aligning with the validation pattern used elsewhere in the
codebase.

Comment thread internal/handler/datasets.go Resolved
@codecov

codecov Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (69dbc44) to head (fd179b5).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16122   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 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.

@Haruko386
Haruko386 marked this pull request as draft June 17, 2026 07:15
@Haruko386
Haruko386 marked this pull request as ready for review June 17, 2026 07:19
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label Jun 17, 2026
}
}
return updates
}

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.

Please add unit tests

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

Caution

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

⚠️ Outside diff range comments (1)
.github/workflows/release.yml (1)

93-101: ⚠️ Potential issue | 🟠 Major

Add a preflight check to verify package versions match the release tag before publishing.

Both sdk/python/pyproject.toml and admin/client/pyproject.toml define static versions (currently 0.26.0). When a tag like v0.27.0 is pushed, the workflow publishes packages without validating that these static versions match the tag. This creates a mismatch risk: a developer who forgets to update pyproject.toml before tagging will publish packages with the wrong version to PyPI.

Add a validation step after checkout that extracts the expected version from the tag and verifies it matches both pyproject.toml files before the build-and-publish steps run. This prevents accidental version mismatches.

🤖 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 @.github/workflows/release.yml around lines 93 - 101, Add a new validation
step in the workflow that runs before the "Build and push ragflow-sdk" and
"Build and push ragflow-cli" steps. This step should extract the version number
from the git tag (removing the 'v' prefix from github.ref), then read the
version fields from both sdk/python/pyproject.toml and
admin/client/pyproject.toml files to verify they match the extracted tag
version. If either file's version does not match the tag version, the workflow
should fail with a clear error message. The validation should only run when the
condition if: startsWith(github.ref, 'refs/tags/v') is true, ensuring the check
occurs before any publishing happens to PyPI using the PYPI_API_TOKEN secret.
🧹 Nitpick comments (2)
.github/workflows/release.yml (2)

93-101: 🏗️ Heavy lift

Prefer PyPI trusted publishing over a long-lived API token.

Both publish steps still use ${{ secrets.PYPI_API_TOKEN }}. Since this workflow is being touched, consider switching the SDK and CLI publishes to PyPI trusted publishing/OIDC to reduce secret exposure.

🤖 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 @.github/workflows/release.yml around lines 93 - 101, Replace the long-lived
API token approach in both the "Build and push ragflow-sdk" and "Build and push
ragflow-cli" publish steps with PyPI trusted publishing. Remove the `--token ${{
secrets.PYPI_API_TOKEN }}` parameters from both uv publish commands. Add
permissions configuration to the GitHub Actions workflow to enable OIDC token
generation (specifically add permissions for id-token: write). Ensure each PyPI
package (ragflow-sdk and ragflow-cli) is configured in PyPI settings to trust
the GitHub repository as a trusted publisher via OIDC, which will allow the uv
publish command to authenticate without passing explicit tokens.

Source: Linters/SAST tools


77-77: Consider pinning the action to a specific commit SHA for defense-in-depth security.

softprops/action-gh-release@v2 uses a mutable tag. While pinning third-party actions to full commit SHAs is a security best practice, no blanket policy requirement for this currently exists in the repository (other workflows also use unpinned actions like actions/checkout@v6). If hash-pinning is to be enforced uniformly, it should be applied across all workflows.

🤖 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 @.github/workflows/release.yml at line 77, The softprops/action-gh-release
action reference on line 77 uses a mutable tag version (v2) instead of a pinned
commit SHA, which poses a security risk. Replace the `@v2` tag with a full
commit SHA (for example, `@v1.8.0` or the full SHA hash) to pin the action to a
specific immutable commit. This ensures that the workflow always uses the exact
same version of the action and prevents potential supply chain attacks from tag
mutations.

Source: Linters/SAST tools

🤖 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 `@internal/dao/database.go`:
- Around line 195-216: Remove the unsynchronized fast-path check for
modelProviderManager at the beginning of the function (the check that returns
modelProviderManager before acquiring modelProviderManagerMu). This initial read
without holding the mutex creates a data race condition. Instead, acquire the
mutex lock immediately at the start of the function, then proceed with the
existing double-checked locking pattern inside the critical section. The
synchronized checks within the locked section will safely handle all
initialization logic.

---

Outside diff comments:
In @.github/workflows/release.yml:
- Around line 93-101: Add a new validation step in the workflow that runs before
the "Build and push ragflow-sdk" and "Build and push ragflow-cli" steps. This
step should extract the version number from the git tag (removing the 'v' prefix
from github.ref), then read the version fields from both
sdk/python/pyproject.toml and admin/client/pyproject.toml files to verify they
match the extracted tag version. If either file's version does not match the tag
version, the workflow should fail with a clear error message. The validation
should only run when the condition if: startsWith(github.ref, 'refs/tags/v') is
true, ensuring the check occurs before any publishing happens to PyPI using the
PYPI_API_TOKEN secret.

---

Nitpick comments:
In @.github/workflows/release.yml:
- Around line 93-101: Replace the long-lived API token approach in both the
"Build and push ragflow-sdk" and "Build and push ragflow-cli" publish steps with
PyPI trusted publishing. Remove the `--token ${{ secrets.PYPI_API_TOKEN }}`
parameters from both uv publish commands. Add permissions configuration to the
GitHub Actions workflow to enable OIDC token generation (specifically add
permissions for id-token: write). Ensure each PyPI package (ragflow-sdk and
ragflow-cli) is configured in PyPI settings to trust the GitHub repository as a
trusted publisher via OIDC, which will allow the uv publish command to
authenticate without passing explicit tokens.
- Line 77: The softprops/action-gh-release action reference on line 77 uses a
mutable tag version (v2) instead of a pinned commit SHA, which poses a security
risk. Replace the `@v2` tag with a full commit SHA (for example, `@v1.8.0` or
the full SHA hash) to pin the action to a specific immutable commit. This
ensures that the workflow always uses the exact same version of the action and
prevents potential supply chain attacks from tag mutations.
🪄 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: cc020c0c-59e2-4ead-a7a7-98e5a727207b

📥 Commits

Reviewing files that changed from the base of the PR and between 5b094dc and ee801a3.

📒 Files selected for processing (4)
  • .github/workflows/release.yml
  • internal/dao/database.go
  • internal/service/dataset.go
  • internal/service/dataset_update_test.go

Comment thread internal/dao/database.go
Comment on lines +195 to 216
if modelProviderManager != nil {
return modelProviderManager
}

modelProviderManagerMu.Lock()
defer modelProviderManagerMu.Unlock()
if modelProviderManager != nil {
return modelProviderManager
}
if existing := models.GetProviderManager(); existing != nil {
modelProviderManager = existing
return modelProviderManager
}
modelConfigDir, err := findModelConfigDir()
if err != nil {
log.Fatal("Failed to locate model providers:", err)
}
if err := models.InitProviderManager(modelConfigDir); err != nil {
log.Fatal("Failed to load model providers:", err)
}
modelProviderManager = models.GetProviderManager()
return modelProviderManager

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
set -euo pipefail

echo "Inspect all accesses to modelProviderManager:"
rg -n -C3 --type go 'modelProviderManager\s*!=\s*nil|modelProviderManager\s*=|modelProviderManagerMu\.(Lock|Unlock)' internal/dao/database.go

echo
echo "Expected verification result:"
echo "- A read at Line 195 before Lock()"
echo "- Writes in multiple places (e.g., InitDB and GetModelProviderManager), confirming mixed synchronized/unsynchronized access."

Repository: infiniflow/ragflow

Length of output: 1296


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== All accesses to modelProviderManager in codebase ==="
rg -n 'modelProviderManager' internal/dao/database.go

echo
echo "=== Check if modelProviderManager is declared and initialized globally ==="
rg -n -B5 -A5 'var.*modelProviderManager' internal/dao/database.go

Repository: infiniflow/ragflow

Length of output: 1075


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Check entire InitDB function for mutex protection ==="
rg -n -A50 'func InitDB' internal/dao/database.go | head -80

Repository: infiniflow/ragflow

Length of output: 1440


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Get lines around line 182 to see full InitDB function ==="
sed -n '160,190p' internal/dao/database.go

Repository: infiniflow/ragflow

Length of output: 866


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== Verify no other unprotected accesses to modelProviderManager ==="
rg -n 'modelProviderManager' internal/dao/database.go | grep -v 'modelProviderManagerMu'

echo
echo "=== Summary of all accesses ==="
echo "Unprotected writes:"
rg -n 'modelProviderManager\s*=' internal/dao/database.go

echo
echo "Unprotected reads:"
rg -n 'modelProviderManager\s*!=' internal/dao/database.go

Repository: infiniflow/ragflow

Length of output: 843


Remove unsynchronized fast-path check for modelProviderManager to prevent data race.

Line 195 reads modelProviderManager without holding the mutex while other code paths write it (lines 205, 215 under lock, and line 182 in InitDB() without lock). This creates a data race when GetModelProviderManager() is called concurrently with initialization or subsequent calls.

The suggested fix eliminates the unsafe fast-path read by acquiring the mutex immediately.

🔧 Suggested fix
 func GetModelProviderManager() *models.ProviderManager {
-	if modelProviderManager != nil {
-		return modelProviderManager
-	}
-
 	modelProviderManagerMu.Lock()
 	defer modelProviderManagerMu.Unlock()
 	if modelProviderManager != nil {
 		return modelProviderManager
 	}
 	if existing := models.GetProviderManager(); existing != nil {
 		modelProviderManager = existing
 		return modelProviderManager
 	}
 	modelConfigDir, err := findModelConfigDir()
 	if err != nil {
 		log.Fatal("Failed to locate model providers:", err)
 	}
 	if err := models.InitProviderManager(modelConfigDir); err != nil {
 		log.Fatal("Failed to load model providers:", err)
 	}
 	modelProviderManager = models.GetProviderManager()
 	return modelProviderManager
 }
🤖 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 `@internal/dao/database.go` around lines 195 - 216, Remove the unsynchronized
fast-path check for modelProviderManager at the beginning of the function (the
check that returns modelProviderManager before acquiring
modelProviderManagerMu). This initial read without holding the mutex creates a
data race condition. Instead, acquire the mutex lock immediately at the start of
the function, then proceed with the existing double-checked locking pattern
inside the critical section. The synchronized checks within the locked section
will safely handle all initialization logic.

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

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants