refactor(memory): enhance item listing and model deletion logic

- Updated the item listing query to ensure deterministic paging by including the item ID in the order clause.
- Added a new test to verify that models used by memory extraction cannot be deleted, ensuring proper error handling.
- Refactored the model deletion logic to check both embedding and extraction models against tenant memory configurations.
- Introduced a new method to handle tombstone records during memory clearing, ensuring that live memories retain their tombstone status when cleared.
main
wizardchen 2026-08-13 15:31:42 +08:00 committed by lyingbug
parent ffcb10f953
commit 5b0b34195e
6 changed files with 158 additions and 23 deletions

View File

@ -293,7 +293,11 @@ func (r *memoryRepository) ListItems(
limit = 50
}
var items []*types.MemoryItem
err := query.Order("valid_from DESC").Limit(limit).Offset(offset).Find(&items).Error
// id breaks ties so paging stays deterministic. A distillation run writes
// several items at once, and ordering those by valid_from alone lets the
// database return them in a different order per page, which both repeats
// and skips rows across an offset walk.
err := query.Order("valid_from DESC, id DESC").Limit(limit).Offset(offset).Find(&items).Error
if err != nil {
return nil, 0, err
}

View File

@ -794,20 +794,7 @@ func (s *Service) Clear(ctx context.Context) (int64, error) {
}
// Clearing is a rejection of everything currently stored, so it leaves the
// same tombstones an individual delete would.
items, _, err := s.repo.ListItems(ctx, scope, "", types.MaxMemoryTombstones, 0)
if err != nil {
return 0, err
}
for _, item := range items {
if item == nil {
continue
}
if err := s.repo.AddTombstone(
ctx, scope, item.Topic, types.MemoryFingerprint(item.Content), item.SourceMessageID,
); err != nil {
logger.Warnf(ctx, "memory: record tombstone during clear failed: %v", err)
}
}
s.tombstoneEverything(ctx, scope)
removed, err := s.repo.DeleteAll(ctx, scope)
if err != nil {
return 0, err
@ -822,6 +809,48 @@ func (s *Service) Clear(ctx context.Context) (int64, error) {
return removed, nil
}
// tombstoneEverything records a rejection for each memory a clear removes.
//
// A subject keeps at most MaxMemoryTombstones rejections, and the store can
// hold far more rows than that: max_items caps active memories only, so
// superseded and archived rows pile up without limit. Reading one flat page
// therefore spent the whole budget on whatever happened to be newest, and a
// live memory could be left with no tombstone and free to be re-derived.
//
// Walking status by status spends the budget where it changes behaviour: what
// the user was still being served, then what was waiting on their decision,
// then the rest. The total is capped so this call cannot trim away its own
// earlier, more important rows.
func (s *Service) tombstoneEverything(ctx context.Context, scope interfaces.MemoryScope) {
budget := types.MaxMemoryTombstones
for _, status := range []string{
types.MemoryStatusActive,
types.MemoryStatusPending,
types.MemoryStatusArchived,
types.MemoryStatusSuperseded,
} {
if budget <= 0 {
return
}
items, _, err := s.repo.ListItems(ctx, scope, status, budget, 0)
if err != nil {
logger.Warnf(ctx, "memory: list %s items during clear failed: %v", status, err)
continue
}
for _, item := range items {
if item == nil {
continue
}
if err := s.repo.AddTombstone(
ctx, scope, item.Topic, types.MemoryFingerprint(item.Content), item.SourceMessageID,
); err != nil {
logger.Warnf(ctx, "memory: record tombstone during clear failed: %v", err)
}
budget--
}
}
}
// GetSettings returns the merged view the settings UI renders.
func (s *Service) GetSettings(ctx context.Context) (*types.MemorySettings, error) {
scope, err := ResolveScope(ctx)

View File

@ -5,6 +5,7 @@ import (
"fmt"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/types"
@ -433,6 +434,44 @@ func TestClearForgetsEverything(t *testing.T) {
require.Empty(t, topics)
}
// TestClearTombstonesLiveMemoriesFirst pins which memories get the bounded
// rejection budget. max_items caps active memories only, so superseded and
// archived rows accumulate without limit and a long-lived store easily holds
// more rows than MaxMemoryTombstones. Spending the budget on whatever happened
// to be newest left the memory the user was actually being served with no
// tombstone, free to be written straight back.
func TestClearTombstonesLiveMemoriesFirst(t *testing.T) {
svc, db, tenantRepo := newMemoryHarness(t)
ctx := enabledCtx(t, tenantRepo, 1, "alice")
// The one memory still in use, deliberately the oldest row in the store.
require.NoError(t, db.Create(&types.MemoryItem{
ID: "live-1", TenantID: 1, SubjectID: "web_user:alice",
Kind: types.MemoryKindFact, Topic: "数据库", Content: "生产库是 PostgreSQL",
NormalizedKey: "数据库|生产库是 postgresql", Status: types.MemoryStatusActive,
ValidFrom: time.Now().Add(-24 * time.Hour),
}).Error)
// Enough newer dead rows to exhaust the budget on their own.
for i := 0; i < types.MaxMemoryTombstones+10; i++ {
require.NoError(t, db.Create(&types.MemoryItem{
ID: fmt.Sprintf("dead-%d", i), TenantID: 1, SubjectID: "web_user:alice",
Kind: types.MemoryKindFact, Content: fmt.Sprintf("旧的说法 %d", i),
NormalizedKey: fmt.Sprintf("旧|%d", i), Status: types.MemoryStatusSuperseded,
ValidFrom: time.Now(),
}).Error)
}
_, err := svc.Clear(ctx)
require.NoError(t, err)
_, err = svc.Remember(ctx, types.MemoryItem{
Kind: types.MemoryKindFact, Topic: "数据库", Content: "生产库是 PostgreSQL",
})
require.ErrorIs(t, err, ErrPreviouslyForgotten,
"the memory that was in use must keep its tombstone, not be crowded out by dead rows")
}
func TestGetSettingsReportsMergedState(t *testing.T) {
svc, _, tenantRepo := newMemoryHarness(t)
ctx := enabledCtx(t, tenantRepo, 1, "alice")

View File

@ -403,8 +403,13 @@ func (s *modelService) DeleteModel(ctx context.Context, id string) error {
})
return err
}
// Both models memory pins have to be checked. Deleting the extraction
// model leaves the workspace pointing at a model that no longer exists,
// and distillation only warns when it cannot resolve one, so auto
// extraction would stop with nothing surfaced to the admin who did it.
if tenant != nil && tenant.MemoryConfig != nil &&
strings.TrimSpace(tenant.MemoryConfig.EmbeddingModelID) == id {
(strings.TrimSpace(tenant.MemoryConfig.EmbeddingModelID) == id ||
strings.TrimSpace(tenant.MemoryConfig.ExtractModelID) == id) {
logger.Warnf(ctx, "Model %s is used by long-term memory", id)
return apperrors.NewBadRequestError(formatModelInUseMessage(0, 0, true))
}

View File

@ -230,6 +230,36 @@ func TestDeleteModel_RejectsWhenUsedByMemory(t *testing.T) {
assert.Contains(t, appErr.Message, "long-term memory")
}
// The extraction model is pinned by the workspace exactly like the embedding
// one. Deleting it leaves memory_config pointing at a model that is gone, and
// distillation only warns when it cannot resolve one, so auto extraction would
// stop silently instead of the delete being refused.
func TestDeleteModel_RejectsWhenUsedByMemoryExtraction(t *testing.T) {
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(1))
modelID := "memory-extract"
svc := NewModelService(
&stubModelRepoForDelete{model: &types.Model{ID: modelID, TenantID: 1}},
&stubKBRepoForModelDelete{},
&stubAgentRepoForModelDelete{},
nil, nil,
&stubTenantServiceForModelDelete{
tenant: &types.Tenant{
ID: 1,
MemoryConfig: &types.MemoryConfig{
Enabled: true, ExtractModelID: modelID, EmbeddingModelID: "some-other-model",
},
},
},
)
err := svc.DeleteModel(ctx, modelID)
require.Error(t, err)
appErr, ok := apperrors.IsAppError(err)
require.True(t, ok)
assert.Contains(t, appErr.Message, "long-term memory")
}
func TestFormatModelInUseMessage(t *testing.T) {
t.Parallel()
assert.Equal(t,

View File

@ -118,6 +118,14 @@ func (h *MemoryHandler) ListItems(c *gin.Context) {
})
}
const (
// memoryExportPageSize is how many rows one export page reads.
memoryExportPageSize = 500
// memoryExportMaxItems bounds a single export so one enormous store cannot
// turn a download into an unbounded read.
memoryExportMaxItems = 20000
)
func memoryListPaging(c *gin.Context) (limit, offset int) {
limit, _ = strconv.Atoi(c.DefaultQuery("limit", "50"))
if limit <= 0 || limit > 200 {
@ -383,18 +391,38 @@ func (h *MemoryHandler) Clear(c *gin.Context) {
// @Router /memory/export [get]
func (h *MemoryHandler) Export(c *gin.Context) {
ctx := c.Request.Context()
// Export is a snapshot, not a page: the cap matches the largest capacity a
// workspace can configure, so a full space is always exportable in one call.
items, total, err := h.memoryService.ListItems(ctx, "", 2000, 0)
if err != nil {
h.fail(c, err, "Failed to export memories")
return
// Export is a snapshot, not a page, so it walks every status to the end.
//
// A single fixed page used to serve this on the grounds that it matched the
// largest capacity a workspace can configure. It does not: max_items caps
// active memories only, while superseded and archived rows accumulate
// without limit, so a long-lived store holds far more than its capacity and
// the export quietly returned a prefix of it.
var items []*types.MemoryItem
var total int64
for {
page, pageTotal, err := h.memoryService.ListItems(ctx, "", memoryExportPageSize, len(items))
if err != nil {
h.fail(c, err, "Failed to export memories")
return
}
total = pageTotal
items = append(items, page...)
if len(page) < memoryExportPageSize || int64(len(items)) >= total {
break
}
if len(items) >= memoryExportMaxItems {
break
}
}
c.Header("Content-Disposition", `attachment; filename="weknora-memories.json"`)
c.JSON(http.StatusOK, gin.H{
"success": true,
"total": total,
"data": items,
// Say so rather than letting a partial file look complete. Only the
// safety ceiling can trigger this, so it stays false in practice.
"truncated": int64(len(items)) < total,
"data": items,
})
}