Skip to content

Go: implement memory messages APIs - #15276

Closed
tmimmanuel wants to merge 1 commit into
infiniflow:mainfrom
tmimmanuel:go/tenant-users-list-api
Closed

tmimmanuel wants to merge 1 commit into
infiniflow:mainfrom
tmimmanuel:go/tenant-users-list-api

Conversation

@tmimmanuel

@tmimmanuel tmimmanuel commented May 27, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Implements the Go API slice for memory messages from #15240:

  • POST /api/v1/messages
  • GET /api/v1/messages

The 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

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

Tests

go test -vet=off ./internal/service -run '^$'
go test -vet=off ./internal/handler ./internal/router ./internal/engine/elasticsearch ./internal/engine/infinity
git diff --check

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 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
📝 Walkthrough

Walkthrough

Adds 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).

Changes

Memory messaging feature

Layer / File(s) Summary
Router and HTTP handler endpoints
internal/router/router.go, internal/handler/memory.go
Routes /api/v1/messages for POST (add) and GET (retrieve). Handlers authenticate users, parse requests, validate inputs, and delegate to service with error handling.
Service structure and dependency injection
internal/service/memory.go
Extends MemoryService with docEngine and modelProvider fields initialized in the constructor to enable document persistence and embedding capabilities.
Message add and get operations
internal/service/message.go (lines 17–187)
Defines request/response types and implements AddMessage (validates, resolves accessible memories, saves with error aggregation) and GetMessages (searches by memory/agent/session, maps results, sorts, truncates to limit).
Message embedding and document indexing
internal/service/message.go (lines 189–249)
Implements saveRawMessage: embeds combined user/agent content, generates message ID with Redis fallback, constructs indexed document payload with scalar metadata and vector field, selects tenant-scoped index name with Infinity-specific handling.
Memory access control and helper functions
internal/service/message.go (lines 251–345)
Implements accessibleMemories for access control via team-permission tenant expansion. Provides utilities for parsing memory IDs, normalizing strings with deduplication, deriving index names, and generating message IDs.
Type conversion utilities for message responses
internal/service/message.go (lines 347–481)
Provides helpers to convert loosely-typed document rows to strongly-typed MessageItem fields: string handling, numeric parsing, boolean coercion, and vector embedding extraction.
Infinity engine document storage for memory messages
internal/engine/infinity/document.go
Routes memory_ table names to new InsertMemoryMessage method; implements insert/update logic with row deletion, document validation, and error handling.
Elasticsearch engine support for memory indices
internal/engine/elasticsearch/chunk.go
Detects memory_ indices and applies memory-specific field mapping (convertMessageSelectFields), filter conversion (convertMessageFilter), and result normalization (normalizeMessageRows). Wraps keyword-only queries with explicit bool filters.
Infinity engine support for memory indices
internal/engine/infinity/chunk.go
Detects memory_ index tables and applies memory-specific field selection, filter conversion, and result normalization instead of standard document field mapping. Provides same helper functions as Elasticsearch for field and filter handling.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

💞 feature

Suggested reviewers

  • Hz-186

Poem

🐰 I hopped through code with nimble paws today,
I stitched the memories so they would stay,
Vectors tucked in rows so neat,
Routes and services drum a steady beat,
A rabbit cheers — messages saved away!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: implement memory messages APIs' clearly and concisely describes the main change—implementing the memory messages API endpoints for the Go backend.
Description check ✅ Passed The description follows the template structure, clearly explains the problem being solved, correctly identifies it as a New Feature, includes relevant issue reference (#15240), and provides test commands.
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.

@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.

🧹 Nitpick comments (1)
internal/service/tenant_test.go (1)

10-24: 🏗️ Heavy lift

Add an owner-success test for the new endpoint contract.

This test validates only the rejection path. Please add a companion case for tenantID == userID that asserts success code and returned user payload mapping (including delta_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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f0632c and 0367d83.

📒 Files selected for processing (5)
  • internal/dao/user_tenant.go
  • internal/handler/tenant.go
  • internal/router/router.go
  • internal/service/tenant.go
  • internal/service/tenant_test.go

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

As far as I know, this PR overlaps with #15295 , I suggest you submit another feature or close it

JinHai-CN pushed a commit that referenced this pull request May 28, 2026
## 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
@tmimmanuel
tmimmanuel force-pushed the go/tenant-users-list-api branch from 0367d83 to 02b7832 Compare May 29, 2026 15:18
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 29, 2026
@tmimmanuel tmimmanuel changed the title Go: implement tenant users list API Go: implement memory messages APIs May 29, 2026

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

🧹 Nitpick comments (4)
internal/service/message.go (2)

258-270: 💤 Low value

UserTenantService 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 win

Consider adding an upper bound for limit to prevent excessive resource usage.

The limit parameter 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: Align convertMessageField mapping with saveRawMessage; tighten OrderBy field conversion for memory indices

In internal/engine/elasticsearch/chunk.go, convertMessageField maps:

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: saveRawMessage persists 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 for memory_*, convertMessageSelectFields/convertMessageFilter use convertMessageField, and normalizeMessageRows backfills logical fields from storage fields—so filtering/selecting these values won’t silently break due to field-name mismatch.

One gap: ES OrderBy does not use convertMessageField (it uses parseOrderByExpr with field.Field directly). GetMessages currently orders by valid_at_flt, which exists in the stored doc, but any future use of valid_at/other logical names in OrderBy would 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 win

Guard rank/availability column injection against memory_ indices

internal/service/message.go’s GetMessages builds a SearchRequest using Filter + SelectFields and does not set match expressions in this path, so the chunk.go logic that appends pagerank_fea/tag_feas (and the available_int=1 default 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.json defines status_int, while conf/infinity_mapping.json defines available_int/pagerank_fea/tag_feas, so matching/retrieval on memory could request/filter non-existent columns. Add an isMemoryIndex exclusion 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0367d83 and 02b7832.

📒 Files selected for processing (8)
  • internal/engine/elasticsearch/chunk.go
  • internal/engine/infinity/chunk.go
  • internal/engine/infinity/document.go
  • internal/handler/auth.go
  • internal/handler/memory.go
  • internal/router/router.go
  • internal/service/memory.go
  • internal/service/message.go

Comment thread internal/engine/elasticsearch/chunk.go Resolved
Comment thread internal/handler/memory.go Resolved
Comment thread internal/handler/memory.go Resolved
Comment thread internal/service/message.go Resolved
@tmimmanuel
tmimmanuel requested a review from Haruko386 May 29, 2026 15:36

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @tmimmanuel just do a small change plz

Comment thread internal/handler/memory.go Resolved
@Haruko386 Haruko386 added the ci Continue Integration label Jun 2, 2026
@codecov

codecov Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (cd18cfa) to head (b0b7e7e).
⚠️ Report is 44 commits behind head on main.

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.
📢 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.

Comment thread .github/workflows/tests.yml Resolved
@tmimmanuel

Copy link
Copy Markdown
Contributor Author

@Haruko386
Fixed CI, please check.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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:

  1. 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_id attribution semantics as Python:
    • normal authenticated users must not be able to spoof user_id;
    • API-token callers may provide an external user_id.
  • 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>".
  1. GET /api/v1/messages
  • Match the Python response fields exactly:
    • message_id
    • message_type
    • source_id
    • memory_id
    • user_id
    • agent_id
    • session_id
    • valid_at
    • invalid_at
    • forget_at
    • status
    • content
  • Do not return extra fields such as id or content_embed.
  • Preserve source_id: 0 for raw messages instead of converting it to null.
  • Confirm that empty agent_id and session_id filters behave the same as Python’s MessageService.get_recent_messages.
  • Keep support for repeated memory_id query params and comma-separated memory_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;
  • GET response field shape;
  • raw message source_id value.

@Haruko386 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

you should summit PR code in another PR

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Okay, I will

@tmimmanuel
tmimmanuel force-pushed the go/tenant-users-list-api branch from 73113df to f2c38f8 Compare June 4, 2026 03:44
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 4, 2026
@JinHai-CN JinHai-CN closed this Sep 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants