Repository navigation
Go: implement memory messages APIs - #15276
tmimmanuel wants to merge 1 commit into
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds message add/get HTTP endpoints, implements MemoryService message APIs (validation, access control, embedding, indexing), and adds storage-layer support for memory_ indices in both Elasticsearch and Infinity (field/filter mapping and row normalization). ChangesMemory messaging feature
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/service/tenant_test.go (1)
10-24: 🏗️ Heavy liftAdd an owner-success test for the new endpoint contract.
This test validates only the rejection path. Please add a companion case for
tenantID == userIDthat asserts success code and returned user payload mapping (includingdelta_seconds) to reduce regression risk on the primary path.🤖 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/tenant_test.go` around lines 10 - 24, Add a companion positive test to TestTenantServiceListTenantUsersRejectsNonOwner that calls (&TenantService{}).ListTenantUsers with tenantID equal to userID (e.g., "tenant-1", "tenant-1"), then assert err == nil, users != nil, and code equals the success code (common.CodeOK); also validate the returned users payload contains the expected user entry and that the entry includes a delta_seconds field with a sensible numeric value. Locate and update the test function TestTenantServiceListTenantUsersRejectsNonOwner and/or add a new TestTenantServiceListTenantUsersOwnerSuccess to perform these assertions against ListTenantUsers.
🤖 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.
Nitpick comments:
In `@internal/service/tenant_test.go`:
- Around line 10-24: Add a companion positive test to
TestTenantServiceListTenantUsersRejectsNonOwner that calls
(&TenantService{}).ListTenantUsers with tenantID equal to userID (e.g.,
"tenant-1", "tenant-1"), then assert err == nil, users != nil, and code equals
the success code (common.CodeOK); also validate the returned users payload
contains the expected user entry and that the entry includes a delta_seconds
field with a sensible numeric value. Locate and update the test function
TestTenantServiceListTenantUsersRejectsNonOwner and/or add a new
TestTenantServiceListTenantUsersOwnerSuccess to perform these assertions against
ListTenantUsers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 2604a9ee-e9a0-4431-9e15-02bd86a16fa5
📒 Files selected for processing (5)
internal/dao/user_tenant.gointernal/handler/tenant.gointernal/router/router.gointernal/service/tenant.gointernal/service/tenant_test.go
## Summary - Add Go REST support for `GET /api/v1/system/healthz`. - Return Python-compatible `ok`/`nok` dependency fields for DB, Redis, document engine, and storage. - Return HTTP 200 only when all checks pass; otherwise return HTTP 500 with `_meta` failure details. - Add focused service coverage for the unhealthy dependency response when Go dependencies are not initialized. ## Scope This is a small, isolated slice of #15240. It avoids current open connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs (#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260, #15261, #15262), and the memory-message PR (#15256). Refs #15240
0367d83 to
02b7832
Compare
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
internal/service/message.go (2)
258-270: 💤 Low valueUserTenantService instantiated inside loop can be moved outside.
NewUserTenantService()is created inside the memory iteration loop. Although the code breaks after the first match, the service could be instantiated once before the loop for cleaner code and to avoid repeated allocations if the loop logic changes.Proposed refactor
func (s *MemoryService) accessibleMemories(userID string, memoryIDs []string) ([]*entity.Memory, error) { memories, err := s.memoryDAO.GetByIDs(memoryIDs) if err != nil { return nil, err } if len(memories) == 0 { return []*entity.Memory{}, nil } joinedTenantIDs := map[string]struct{}{userID: {}} + userTenantService := NewUserTenantService() for _, memory := range memories { if memory.TenantID != userID && strings.EqualFold(memory.Permissions, string(TenantPermissionTeam)) { - userTenantService := NewUserTenantService() userTenants, err := userTenantService.GetUserTenantRelationByUserID(userID)🤖 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/message.go` around lines 258 - 270, Move the NewUserTenantService() instantiation out of the memories loop: create a single userTenantService := NewUserTenantService() before the for _, memory := range memories loop and then use that service inside the loop when calling GetUserTenantRelationByUserID(userID); this avoids allocating the service repeatedly (and preserves the existing break behavior) and keeps the logic in the function that contains the loop (the code that calls NewUserTenantService and GetUserTenantRelationByUserID).
118-120: ⚡ Quick winConsider adding an upper bound for
limitto prevent excessive resource usage.The
limitparameter defaults to 10 if <= 0, but there's no upper bound validation. A caller could request an extremely large limit (e.g.,limit=1000000), potentially causing memory pressure or slow queries.Proposed fix to cap limit
if limit <= 0 { limit = 10 } + const maxLimit = 1000 + if limit > maxLimit { + limit = maxLimit + }🤖 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/message.go` around lines 118 - 120, Add an upper bound check for the limit variable to avoid excessive resource usage: define a reasonable constant (e.g., MaxLimit = 100 or configurable) and after the existing defaulting logic (the block that currently sets limit = 10 when limit <= 0) clamp limit with if limit > MaxLimit { limit = MaxLimit }. Reference the existing limit variable in this file (internal/service/message.go) and add the MaxLimit constant near related defaults so callers cannot request unbounded sizes.internal/engine/elasticsearch/chunk.go (1)
1160-1171: AlignconvertMessageFieldmapping withsaveRawMessage; tightenOrderByfield conversion for memory indicesIn
internal/engine/elasticsearch/chunk.go,convertMessageFieldmaps:func convertMessageField(field string) string { switch field { case "message_type": return "message_type_kwd" case "status": return "status_int" case "content": return "content_ltks" default: return field } }This matches the write path in
internal/service/message.go:saveRawMessagepersists both the logical fields (message_type,status,content,valid_at) and the corresponding storage fields (message_type_kwd,status_int,content_ltks,valid_at_flt). On ES reads formemory_*,convertMessageSelectFields/convertMessageFilteruseconvertMessageField, andnormalizeMessageRowsbackfills logical fields from storage fields—so filtering/selecting these values won’t silently break due to field-name mismatch.One gap: ES
OrderBydoes not useconvertMessageField(it usesparseOrderByExprwithfield.Fielddirectly).GetMessagescurrently orders byvalid_at_flt, which exists in the stored doc, but any future use ofvalid_at/other logical names inOrderBywould bypass the logical→storage conversion and lead to incorrect sorting.🤖 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/engine/elasticsearch/chunk.go` around lines 1160 - 1171, convertMessageField is missing the mapping for valid_at and OrderBy paths bypass convertMessageField, so add "valid_at" -> "valid_at_flt" to convertMessageField and ensure parseOrderByExpr (or the code in GetMessages that constructs ES sort clauses) calls convertMessageField for the order-by field when targeting memory_* indices; update parseOrderByExpr/OrderBy construction to translate logical names to storage names (use convertMessageField) so ordering uses the persisted storage fields (e.g., valid_at_flt) consistently with saveRawMessage, convertMessageSelectFields, convertMessageFilter, and normalizeMessageRows.internal/engine/infinity/chunk.go (1)
706-714: ⚡ Quick winGuard rank/availability column injection against
memory_indices
internal/service/message.go’sGetMessagesbuilds aSearchRequestusingFilter+SelectFieldsand does not set match expressions in this path, so thechunk.gologic that appendspagerank_fea/tag_feas(and theavailable_int=1default filter) won’t trigger for the current filter-only flow.The underlying correctness risk remains if any code path issues text/vector matches against
memory_indices:conf/message_infinity_mapping.jsondefinesstatus_int, whileconf/infinity_mapping.jsondefinesavailable_int/pagerank_fea/tag_feas, so matching/retrieval on memory could request/filter non-existent columns. Add anisMemoryIndexexclusion for both the match-driven column append and the default filter branch.🛠️ Suggested guard
- if !isSkillIndex { + if !isSkillIndex && !isMemoryIndex { if !slices.Contains(outputColumns, common.PAGERANK_FLD) { outputColumns = append(outputColumns, common.PAGERANK_FLD) } if !slices.Contains(outputColumns, common.TAG_FLD) { outputColumns = append(outputColumns, common.TAG_FLD) } }🤖 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/engine/infinity/chunk.go` around lines 706 - 714, The code currently appends pagerank/tag columns when !isSkillIndex; update the logic to also skip these injections for memory indices by checking an isMemoryIndex flag (i.e., only append common.PAGERANK_FLD and common.TAG_FLD to outputColumns when !isSkillIndex && !isMemoryIndex), and likewise add the same !isMemoryIndex guard to the branch that adds the default available_int=1 filter so neither match-driven column appends nor the default availability filter are applied for memory_ indices; locate the relevant blocks in chunk.go that reference isSkillIndex, outputColumns, common.PAGERANK_FLD, common.TAG_FLD and the default available_int filter and add the isMemoryIndex exclusion.
🤖 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/engine/elasticsearch/chunk.go`:
- Around line 1190-1195: normalizeMessageRows is trying to set
row["content_embed"] by scanning for q_*_vec keys but those fields are never
requested because SelectFields (used to build the ES _source) only includes
"content_embed"; fix by ensuring the ES query requests the stored vector fields
or by mapping content_embed to those stored columns in
convertMessageSelectFields: either modify the code that builds SelectFields to
include any q_%d_vec fields when "content_embed" is present, or update
convertMessageSelectFields to translate "content_embed" into the actual
q_<dim>_vec field names so normalizeMessageRows will see the q_*_vec entries and
populate content_embed. Ensure the change references normalizeMessageRows,
convertMessageSelectFields, SelectFields, content_embed and q_*_vec so the ES
_source contains the stored vector fields used to populate content_embed.
In `@internal/handler/memory.go`:
- Around line 698-702: The GetMessages handler currently returns "message": true
in its success response which is inconsistent with other handlers (e.g., earlier
responses that use "message": "success"); update the success JSON in the
GetMessages response (the c.JSON call that returns common.CodeSuccess and
messages) to set "message": "success" to match the rest of the file and ensure
consistent API responses.
- Around line 556-560: The code currently assigns effectiveUserID = req.UserID
when auth_via_api_token is marked trusted, then passes it into
memoryService.AddMessage/saveRawMessage without verifying the target user exists
or that the token may impersonate them; update the AddMessage flow to derive
effectiveUserID from the authenticated principal by default and only accept
req.UserID overrides after: (1) verifying the API token has explicit
impersonation rights, (2) checking the requested user exists and is allowed to
be impersonated, and (3) ensuring the target is authorized for the currentMemory
access checks (accessibleMemories/currentUserID) before calling
memoryService.AddMessage/saveRawMessage.
In `@internal/service/message.go`:
- Around line 334-341: nextMemoryMessageID currently falls back to
time.Now().UnixNano(), which can collide under concurrency; change the fallback
to use a package-level atomic counter to guarantee uniqueness: add an int64
counter (e.g., memoryMsgCounter) and on Redis miss call
atomic.AddInt64(&memoryMsgCounter, 1) and combine that monotonic counter with
the current timestamp to produce the returned int64 (or alternatively return an
error when Redis is unavailable if uniqueness must be enforced strictly); update
nextMemoryMessageID to use redisClient.GenerateAutoIncrementID when available,
otherwise use the atomic counter + timestamp composition so docID (derived from
memoryID + messageID) remains unique across goroutines.
---
Nitpick comments:
In `@internal/engine/elasticsearch/chunk.go`:
- Around line 1160-1171: convertMessageField is missing the mapping for valid_at
and OrderBy paths bypass convertMessageField, so add "valid_at" ->
"valid_at_flt" to convertMessageField and ensure parseOrderByExpr (or the code
in GetMessages that constructs ES sort clauses) calls convertMessageField for
the order-by field when targeting memory_* indices; update
parseOrderByExpr/OrderBy construction to translate logical names to storage
names (use convertMessageField) so ordering uses the persisted storage fields
(e.g., valid_at_flt) consistently with saveRawMessage,
convertMessageSelectFields, convertMessageFilter, and normalizeMessageRows.
In `@internal/engine/infinity/chunk.go`:
- Around line 706-714: The code currently appends pagerank/tag columns when
!isSkillIndex; update the logic to also skip these injections for memory indices
by checking an isMemoryIndex flag (i.e., only append common.PAGERANK_FLD and
common.TAG_FLD to outputColumns when !isSkillIndex && !isMemoryIndex), and
likewise add the same !isMemoryIndex guard to the branch that adds the default
available_int=1 filter so neither match-driven column appends nor the default
availability filter are applied for memory_ indices; locate the relevant blocks
in chunk.go that reference isSkillIndex, outputColumns, common.PAGERANK_FLD,
common.TAG_FLD and the default available_int filter and add the isMemoryIndex
exclusion.
In `@internal/service/message.go`:
- Around line 258-270: Move the NewUserTenantService() instantiation out of the
memories loop: create a single userTenantService := NewUserTenantService()
before the for _, memory := range memories loop and then use that service inside
the loop when calling GetUserTenantRelationByUserID(userID); this avoids
allocating the service repeatedly (and preserves the existing break behavior)
and keeps the logic in the function that contains the loop (the code that calls
NewUserTenantService and GetUserTenantRelationByUserID).
- Around line 118-120: Add an upper bound check for the limit variable to avoid
excessive resource usage: define a reasonable constant (e.g., MaxLimit = 100 or
configurable) and after the existing defaulting logic (the block that currently
sets limit = 10 when limit <= 0) clamp limit with if limit > MaxLimit { limit =
MaxLimit }. Reference the existing limit variable in this file
(internal/service/message.go) and add the MaxLimit constant near related
defaults so callers cannot request unbounded sizes.
🪄 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: 576e5756-f145-4071-8dfc-e8566eb89476
📒 Files selected for processing (8)
internal/engine/elasticsearch/chunk.gointernal/engine/infinity/chunk.gointernal/engine/infinity/document.gointernal/handler/auth.gointernal/handler/memory.gointernal/router/router.gointernal/service/memory.gointernal/service/message.go
Haruko386
left a comment
There was a problem hiding this comment.
Hi @tmimmanuel just do a small change plz
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15276 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
@Haruko386 |
Haruko386
left a comment
There was a problem hiding this comment.
Hi @tmimmanuel
Please align the Go implementation of POST /api/v1/messages and GET /api/v1/messages with the Python API behavior.
The current Go implementation is only partially aligned. The route shape is correct, but the behavior and response contract differ from the Python version.
Required changes:
POST /api/v1/messages
- Match the Python success message: return
"All add to task."instead of"Message saved successfully.". - Preserve Python’s behavior of saving the raw message first, creating a memory task, and enqueueing the extraction task for async processing.
- Do not only write the raw message synchronously to the document engine.
- Support the same
user_idattribution semantics as Python:- normal authenticated users must not be able to spoof
user_id; - API-token callers may provide an external
user_id.
- normal authenticated users must not be able to spoof
- Match Python failure semantics for inaccessible or missing memories:
- if no accessible memory exists, return
"Memory not found."; - if some memory writes fail, return
"Some messages failed to add. Detail:<detail>".
- if no accessible memory exists, return
GET /api/v1/messages
- Match the Python response fields exactly:
message_idmessage_typesource_idmemory_iduser_idagent_idsession_idvalid_atinvalid_atforget_atstatuscontent
- Do not return extra fields such as
idorcontent_embed. - Preserve
source_id: 0for raw messages instead of converting it tonull. - Confirm that empty
agent_idandsession_idfilters behave the same as Python’sMessageService.get_recent_messages. - Keep support for repeated
memory_idquery params and comma-separatedmemory_id.
Please add request/response tests comparing these two endpoints against the Python contract, especially:
- missing auth;
- missing
memory_id; - comma-separated
memory_id; - inaccessible memory;
- successful
POST; GETresponse field shape;- raw message
source_idvalue.
There was a problem hiding this comment.
you should summit PR code in another PR
73113df to
f2c38f8
Compare
What problem does this PR solve?
Implements the Go API slice for memory messages from #15240:
POST /api/v1/messagesGET /api/v1/messagesThe PR wires the routes, replaces the previous placeholder handlers, stores raw memory messages with embeddings, lists recent messages from accessible memories, and adds message-index field handling for Elasticsearch and Infinity-backed searches.
Type of change
Tests