Repository navigation
fix(service): allow updating memory_type when memory is empty - #16668
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
💤 Files with no reviewable changes (2)
📝 WalkthroughWalkthroughChanges the memory update restriction logic in ChangesMemory Update Guard
Build Script and Dev Environment Fixes
Estimated code review effort: 2 (Simple) | ~10 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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: 1
🧹 Nitpick comments (3)
internal/service/memory.go (2)
675-675: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winNo timeout on the doc-engine search call.
context.Background()is used fors.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 usingcontext.WithTimeoutaround 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 winRedundant re-fetch of the same memory record.
currentMemorywas already fetched at line 562 (s.memoryDAO.GetByID(memoryID)) earlier in this function and is still in scope. Re-fetching it here viaGetByIDWithContextshadows the outer variable, adds an extra DB round trip, and introduces a (harmless but unnecessary) TOCTOU window. Reuse the outercurrentMemoryinstead.🤖 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 valueSolid coverage of empty vs. non-empty memory cases.
Both tests correctly exercise the new
hasMessagesgating path. One optional improvement: the stubSearchignores the incomingreq, so the tests don't verify thatIndexNames/Filterare 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
📒 Files selected for processing (3)
internal/service/document.gointernal/service/memory.gointernal/service/memory_update_test.go
Signed-off-by: noob <[email protected]>
7d828c5 to
973530f
Compare
wangq8
left a comment
There was a problem hiding this comment.
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)matcheslistMemoryMessages'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:
-- apito--api(space removal). A formatting fix but unrelated. - web/.env.development:
API_PROXY_SCHEMEchanged 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:
- Include or add the unit tests
- Split unrelated changes (build.sh, .env.development) into separate PRs
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
Checklist