Skip to content

fix(service): allow updating memory_type when memory is empty - #16668

Merged
wangq8 merged 2 commits into
infiniflow:mainfrom
euvre:fix-memory-type-empty-memory
Jul 8, 2026
Merged

wangq8 merged 2 commits into
infiniflow:mainfrom
euvre:fix-memory-type-empty-memory

Conversation

@euvre

@euvre euvre commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR fixes a 500 error when users add memory types to a newly created memory.
Previously, the update check relied on a database-level message count, which incorrectly blocked updates to memory_type, embd_id, and tenant_embd_id even when the memory had no indexed messages.

The fix replaces the DAO count with a doc-engine search scoped to the memory index, so the restriction is only enforced when the memory actually contains messages.

Fixes the 500 error when updating memory_type on an empty memory.

Changes

  • Update MemoryService.UpdateMemory to query the doc engine for existing messages instead of using the DAO message count.
  • Add unit tests covering both empty and non-empty memory cases.

Checklist

  • The PR follows the project contribution guidelines.
  • Added tests for the fix.
  • Local gofmt passes.

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jul 6, 2026
@euvre euvre added the ci Continue Integration label Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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: 64f5d43d-1a5b-4aab-a062-53019d93ff71

📥 Commits

Reviewing files that changed from the base of the PR and between 7d828c5 and f04cee5.

📒 Files selected for processing (3)
  • build.sh
  • internal/service/memory.go
  • web/.env.development
💤 Files with no reviewable changes (2)
  • web/.env.development
  • internal/service/memory.go

📝 Walkthrough

Walkthrough

Changes the memory update restriction logic in UpdateMemory to determine field-update eligibility based on existing message count (via listMemoryMessages) rather than MemorySize, fixes a malformed --api CLI flag in build.sh, and switches the dev environment API_PROXY_SCHEME from python to go.

Changes

Memory Update Guard

Layer / File(s) Summary
Message-count-based update guard
internal/service/memory.go
UpdateMemory now calls listMemoryMessages to check total_count when tenant_embd_id, embd_id, or memory_type are in the update payload, rejecting the update if messages exist or if the lookup fails, replacing the prior MemorySize-based check.

Build Script and Dev Environment Fixes

Layer / File(s) Summary
Server startup flag correction
build.sh
Fixes the ragflow_server foreground invocation flag from -- api to --api.
Dev API proxy scheme update
web/.env.development
Changes API_PROXY_SCHEME from 'python' to 'go'.

Estimated code review effort: 2 (Simple) | ~10 minutes

Poem

Three small burrows, three small fixes,
Flags untangled, schemes and switches,
Messages checked before we change,
No more MemorySize, logic rearranged,
Hop, hop, ship it — nothing looks strange! 🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main fix: allowing memory_type updates when a memory is empty.
Description check ✅ Passed The PR description includes the required Summary plus enough context, change details, and testing notes.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

@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

🧹 Nitpick comments (3)
internal/service/memory.go (2)

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

No timeout on the doc-engine search call.

context.Background() is used for s.docEngine.Search, an external I/O call, with no deadline. If the engine hangs or is slow, this call has no bound and can tie up the request. Consider using context.WithTimeout around this call.

🛡️ Proposed fix
-		ctx := context.Background()
+		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+		defer cancel()

Also applies to: 690-690

🤖 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/service/memory.go` at line 675, The doc-engine search path in
memory.go uses context.Background() for s.docEngine.Search, which leaves the
external I/O call without a deadline. Update the search flow to use
context.WithTimeout (and defer cancel) around the Search call, and apply the
same change to the related call site near the other flagged location so both
docEngine.Search invocations are bounded.

675-679: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Redundant re-fetch of the same memory record.

currentMemory was already fetched at line 562 (s.memoryDAO.GetByID(memoryID)) earlier in this function and is still in scope. Re-fetching it here via GetByIDWithContext shadows the outer variable, adds an extra DB round trip, and introduces a (harmless but unnecessary) TOCTOU window. Reuse the outer currentMemory instead.

🤖 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/service/memory.go` around lines 675 - 679, The memory lookup in this
block redundantly re-fetches the same record and shadows the existing
currentMemory from earlier in the function. Remove the GetByIDWithContext call
here and reuse the already-in-scope currentMemory from the prior
GetByID(memoryID) fetch in memory service logic, keeping the existing not-found
handling based on that object instead of adding another database round trip.
internal/service/memory_update_test.go (1)

45-109: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Solid coverage of empty vs. non-empty memory cases.

Both tests correctly exercise the new hasMessages gating path. One optional improvement: the stub Search ignores the incoming req, so the tests don't verify that IndexNames/Filter are correctly scoped to the target memory — only that the boolean gate itself works. Not blocking given the existing coverage goal.

🤖 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/service/memory_update_test.go` around lines 45 - 109, The
update-memory tests cover the empty vs non-empty gating, but the
`memoryUpdateDocEngine.Search` stub currently ignores the incoming request, so
it does not verify that `UpdateMemory` builds the search query with the correct
`IndexNames` and `Filter` for the target memory. Update the stub in these tests
to inspect the `SearchRequest` passed from `MemoryService.UpdateMemory` and
assert the request is scoped to the requested memory ID, while keeping the
existing boolean gate assertions intact.
🤖 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/service/memory.go`:
- Around line 673-695: Gate the `s.docEngine.Search` logic in `UpdateMemory`/the
memory update flow behind a check that `updateDict` actually includes one of the
restricted fields (`tenant_embd_id`, `embd_id`, or `memory_type`). Right now the
block always runs whenever `s.docEngine != nil`, so add a precondition before
the `GetByIDWithContext` and search call, and only compute `hasMessages` when a
restricted field is being changed. Keep the existing `docEngine` path intact,
but avoid the extra DAO fetch and external search for unrelated updates like
`name`, `avatar`, or `description`.

---

Nitpick comments:
In `@internal/service/memory_update_test.go`:
- Around line 45-109: The update-memory tests cover the empty vs non-empty
gating, but the `memoryUpdateDocEngine.Search` stub currently ignores the
incoming request, so it does not verify that `UpdateMemory` builds the search
query with the correct `IndexNames` and `Filter` for the target memory. Update
the stub in these tests to inspect the `SearchRequest` passed from
`MemoryService.UpdateMemory` and assert the request is scoped to the requested
memory ID, while keeping the existing boolean gate assertions intact.

In `@internal/service/memory.go`:
- Line 675: The doc-engine search path in memory.go uses context.Background()
for s.docEngine.Search, which leaves the external I/O call without a deadline.
Update the search flow to use context.WithTimeout (and defer cancel) around the
Search call, and apply the same change to the related call site near the other
flagged location so both docEngine.Search invocations are bounded.
- Around line 675-679: The memory lookup in this block redundantly re-fetches
the same record and shadows the existing currentMemory from earlier in the
function. Remove the GetByIDWithContext call here and reuse the already-in-scope
currentMemory from the prior GetByID(memoryID) fetch in memory service logic,
keeping the existing not-found handling based on that object instead of adding
another database round trip.
🪄 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: 8f524441-c46a-49ad-97e1-e4b1669b66cf

📥 Commits

Reviewing files that changed from the base of the PR and between 57625c9 and 7d828c5.

📒 Files selected for processing (3)
  • internal/service/document.go
  • internal/service/memory.go
  • internal/service/memory_update_test.go

Comment thread internal/service/memory.go Resolved
Signed-off-by: noob <[email protected]>
@euvre
euvre force-pushed the fix-memory-type-empty-memory branch from 7d828c5 to 973530f Compare July 7, 2026 12:22
@dosubot dosubot Bot added size:S This PR changes 10-29 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jul 7, 2026

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Review: #16668

Author: @euvre
Title: fix(service): allow updating memory_type when memory is empty


Core Fix (memory.go)

The change is sound. Replacing currentMemory.MemorySize (DAO-level count) with an actual doc-engine search via listMemoryMessages is the right approach — the DAO counter can be stale or out of sync with the actual indexed messages, causing false 500 errors.

Key observations:

  • The search uses page size 1 with page 1, so it only fetches the total count without loading full results — minimal overhead for an edge-case guard.
  • The type assertion messages["total_count"].(int64) matches listMemoryMessages's return type — correct.
  • Error propagation is properly handled: if the check fails, the update is rejected with a clear error message.

Concerns

1. Missing tests
The PR description says: "Add unit tests covering both empty and non-empty memory cases."
However, no test files appear in the diff (gh pr diff shows only build.sh, memory.go, and .env.development). No *_test.go was changed or created in this PR. If tests were intended but not committed, please add them.

2. Unrelated changes bundled in the same PR
Two changes are included that have nothing to do with the memory fix:

  • build.sh: -- api to --api (space removal). A formatting fix but unrelated.
  • web/.env.development: API_PROXY_SCHEME changed from 'python' to 'go'. This is a local dev config change and should not be in a PR fixing memory type updates.

These should be split into separate PRs to keep history clean and make reviews focused.

Nitpick

The notAllowedUpdate slice is still built unconditionally in the loop before the empty-check. Consider moving the doc-engine check into the loop guard for clarity and to avoid making the doc-engine call when none of the restricted fields are being updated:

for _, f := range []string{"tenant_embd_id", "embd_id", "memory_type"} {
    if _, ok := updateDict[f]; ok {
        messages, err := s.listMemoryMessages(...)
        if err != nil { return nil, err }
        if total, ok := messages["total_count"].(int64); ok && total > 0 {
            return nil, fmt.Errorf("can't update %v when memory isn't empty", f)
        }
    }
}

Verdict

Approve with minor concerns — the core fix is correct and solves the reported 500 error. Recommend addressing the two items above before merging:

  1. Include or add the unit tests
  2. Split unrelated changes (build.sh, .env.development) into separate PRs

@wangq8
wangq8 merged commit 699a25c into infiniflow:main Jul 8, 2026
3 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:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants